SimrusDenuvo commited on
Commit
19236d7
·
verified ·
1 Parent(s): 52af11a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -90
app.py CHANGED
@@ -1,139 +1,104 @@
1
  import gradio as gr
2
  import time
3
  from transformers import pipeline
4
- from datasets import load_dataset
5
-
6
- # Группированные обращения по категориям
7
- categories = {
8
- "доступ": [
9
- "Клиент: Я не могу войти в личный кабинет\nОтвет: Пожалуйста, проверьте правильность логина и пароля. Если проблема сохраняется — воспользуйтесь восстановлением доступа или обратитесь в поддержку.",
10
- "Клиент: У меня заблокирован вход в интернет-банк\nОтвет: Обратитесь в поддержку для подтверждения личности и восстановления доступа."
11
- ],
12
- "переводы": [
13
- "Клиент: Как перевести деньги на другую карту?\nОтвет: Перевод возможен через мобильное приложение или в отделении. Убедитесь, что карта получателя активна.",
14
- "Клиент: Почему не проходит перевод?\nОтвет: Проверьте лимиты по карте и правильность реквизитов. Если всё верно, свяжитесь с поддержкой."
15
- ],
16
- "смс": [
17
- "Клиент: Мне пришло смс, которого я не ожидал\nОтвет: Это может быть техническое уведомление. Уточните дату и текст сообщения, чтобы мы проверили.",
18
- "Клиент: Получаю подозрительные смс от банка\nОтвет: Не переходите по ссылкам. Немедленно смените пароль и сообщите в службу безопасности."
19
- ]
20
- }
21
-
22
- # Инструкция CoT (расширенная)
23
- cot_instruction = (
24
- "Ты — банковский ассистент. Клиент задал вопрос. Сначала разложи его по смысловым блокам: что именно он хочет, какие данные нужны, возможные причины. "
25
- "После анализа предложи чёткий, полезный и вежливый ответ. Если информации недостаточно — запроси уточнение."
26
- )
27
-
28
- # Инструкция обычная
29
- simple_instruction = (
30
- "Ты — банковский помощник. Отвечай официально, коротко и понятно, без рассуждений."
31
- )
32
-
33
- # Классификация темы обращения
34
-
35
- def classify_topic(user_input):
36
- if any(x in user_input.lower() for x in ["войти", "кабинет", "доступ", "логин", "пароль"]):
37
- return "доступ"
38
- elif any(x in user_input.lower() for x in ["перевод", "перевести", "деньги", "карта"]):
39
- return "переводы"
40
- elif any(x in user_input.lower() for x in ["смс", "сообщение", "уведомление"]):
41
- return "смс"
42
- return "доступ" # fallback
43
 
44
- # Сбор примеров по теме
45
-
46
- def get_few_shot_examples(user_input):
47
- topic = classify_topic(user_input)
48
- return categories.get(topic, categories["доступ"])
49
-
50
- # Модели
51
  models = {
52
- "ruDialoGPT-small": pipeline("text-generation", model="t-bank-ai/ruDialoGPT-small", tokenizer="t-bank-ai/ruDialoGPT-small", device=-1),
53
- "ruDialoGPT-medium": pipeline("text-generation", model="t-bank-ai/ruDialoGPT-medium", tokenizer="t-bank-ai/ruDialoGPT-medium", device=-1),
54
- "ruGPT3-small": pipeline("text-generation", model="ai-forever/rugpt3small_based_on_gpt2", tokenizer="ai-forever/rugpt3small_based_on_gpt2", device=-1),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  }
56
 
57
- # Формирование промптов
58
-
59
- def build_cot_prompt(user_input):
60
- examples = "\n\n".join(get_few_shot_examples(user_input))
61
- return f"{cot_instruction}\n\n{examples}\n\nКлиент: {user_input}\nРассуждение и ответ:"
62
-
63
  def build_simple_prompt(user_input):
64
- examples = "\n\n".join(get_few_shot_examples(user_input))
65
- return f"{simple_instruction}\n\n{examples}\n\nКлиент: {user_input}\nОтвет:"
66
-
67
- # Фильтрация финального ответа
68
 
69
- def extract_final_answer(generated_text):
70
- for line in generated_text.split('\n'):
71
- if "Ответ:" in line:
72
- return line.split("Ответ:")[-1].strip()
73
- return generated_text.strip().split('\n')[-1]
 
 
 
 
 
74
 
75
- # Генерация
 
 
 
76
 
77
- def generate_dual_answers(user_input):
78
  results = {}
79
- prompt_cot = build_cot_prompt(user_input)
80
- prompt_simple = build_simple_prompt(user_input)
81
 
82
  for name, pipe in models.items():
83
- # CoT
84
  start_cot = time.time()
85
- out_cot = pipe(prompt_cot, max_new_tokens=100, do_sample=True, top_p=0.95, temperature=0.9)[0]["generated_text"]
86
  end_cot = round(time.time() - start_cot, 2)
87
- answer_cot = extract_final_answer(out_cot)
88
 
89
- # Simple
90
  start_simple = time.time()
91
- out_simple = pipe(prompt_simple, max_new_tokens=100, do_sample=True, top_p=0.95, temperature=0.9)[0]["generated_text"]
92
  end_simple = round(time.time() - start_simple, 2)
93
- answer_simple = extract_final_answer(out_simple)
94
 
95
  results[name] = {
96
- "cot_answer": answer_cot,
97
  "cot_time": end_cot,
98
- "simple_answer": answer_simple,
99
  "simple_time": end_simple
100
  }
101
 
102
  return (
103
- results["ruDialoGPT-small"]["cot_answer"], f"{results['ruDialoGPT-small']['cot_time']} сек",
104
- results["ruDialoGPT-small"]["simple_answer"], f"{results['ruDialoGPT-small']['simple_time']} сек",
105
- results["ruDialoGPT-medium"]["cot_answer"], f"{results['ruDialoGPT-medium']['cot_time']} сек",
106
- results["ruDialoGPT-medium"]["simple_answer"], f"{results['ruDialoGPT-medium']['simple_time']} сек",
107
- results["ruGPT3-small"]["cot_answer"], f"{results['ruGPT3-small']['cot_time']} сек",
108
- results["ruGPT3-small"]["simple_answer"], f"{results['ruGPT3-small']['simple_time']} сек",
109
  )
110
 
111
- # Интерфейс Gradio
112
- with gr.Blocks() as demo:
113
- gr.Markdown("## 🏦 Банковский помощник: CoT vs. Обычный ответ (магистерская работа)")
114
 
115
- inp = gr.Textbox(label="Вопрос клиента", placeholder="Например: Почему не проходит перевод?", lines=2)
116
  btn = gr.Button("Сгенерировать")
117
 
118
- gr.Markdown("### ruDialoGPT-small")
119
  cot1 = gr.Textbox(label="CoT ответ")
120
  cot1_time = gr.Textbox(label="Время CoT")
121
  simple1 = gr.Textbox(label="Обычный ответ")
122
  simple1_time = gr.Textbox(label="Время обычного")
123
 
124
- gr.Markdown("### ruDialoGPT-medium")
125
  cot2 = gr.Textbox(label="CoT ответ")
126
  cot2_time = gr.Textbox(label="Время CoT")
127
  simple2 = gr.Textbox(label="Обычный ответ")
128
  simple2_time = gr.Textbox(label="Время обычного")
129
 
130
- gr.Markdown("### ruGPT3-small")
131
  cot3 = gr.Textbox(label="CoT ответ")
132
  cot3_time = gr.Textbox(label="Время CoT")
133
  simple3 = gr.Textbox(label="Обычный ответ")
134
  simple3_time = gr.Textbox(label="Время обычного")
135
 
136
- btn.click(generate_dual_answers, inputs=[inp], outputs=[
137
  cot1, cot1_time, simple1, simple1_time,
138
  cot2, cot2_time, simple2, simple2_time,
139
  cot3, cot3_time, simple3, simple3_time
@@ -141,3 +106,4 @@ with gr.Blocks() as demo:
141
 
142
  demo.launch()
143
 
 
 
1
  import gradio as gr
2
  import time
3
  from transformers import pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ # Инициализация моделей
 
 
 
 
 
 
6
  models = {
7
+ "ruGPT3-Medium": pipeline(
8
+ "text-generation",
9
+ model="ai-forever/rugpt3medium_based_on_gpt2",
10
+ tokenizer="ai-forever/rugpt3medium_based_on_gpt2",
11
+ device=-1
12
+ ),
13
+ "ruGPT3-Small": pipeline(
14
+ "text-generation",
15
+ model="ai-forever/rugpt3small_based_on_gpt2",
16
+ tokenizer="ai-forever/rugpt3small_based_on_gpt2",
17
+ device=-1
18
+ ),
19
+ "SambaLingo": pipeline(
20
+ "text-generation",
21
+ model="sambanovasystems/SambaLingo-Russian-Chat",
22
+ tokenizer="sambanovasystems/SambaLingo-Russian-Chat",
23
+ device=-1
24
+ )
25
  }
26
 
27
+ # Построение обычного промпта
 
 
 
 
 
28
  def build_simple_prompt(user_input):
29
+ return f"Клиент: {user_input}\nКатегория обращения:"
 
 
 
30
 
31
+ # Построение CoT-промпта
32
+ def build_cot_prompt(user_input):
33
+ return (
34
+ f"Клиент: {user_input}\n"
35
+ "Проанализируй обращение клиента пошагово:\n"
36
+ "1. Определи суть проблемы.\n"
37
+ "2. Выяви возможные причины.\n"
38
+ "3. Предложи возможные решения.\n"
39
+ "На основе анализа, укажи категорию обращения:"
40
+ )
41
 
42
+ # Генерация результатов
43
+ def generate_classification(user_input):
44
+ prompt_simple = build_simple_prompt(user_input)
45
+ prompt_cot = build_cot_prompt(user_input)
46
 
 
47
  results = {}
 
 
48
 
49
  for name, pipe in models.items():
50
+ # CoT ответ
51
  start_cot = time.time()
52
+ cot_output = pipe(prompt_cot, max_new_tokens=100, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
53
  end_cot = round(time.time() - start_cot, 2)
 
54
 
55
+ # Обычный ответ
56
  start_simple = time.time()
57
+ simple_output = pipe(prompt_simple, max_new_tokens=60, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
58
  end_simple = round(time.time() - start_simple, 2)
 
59
 
60
  results[name] = {
61
+ "cot_answer": cot_output.strip(),
62
  "cot_time": end_cot,
63
+ "simple_answer": simple_output.strip(),
64
  "simple_time": end_simple
65
  }
66
 
67
  return (
68
+ results["ruGPT3-Medium"]["cot_answer"], f"{results['ruGPT3-Medium"]["cot_time"]} сек",
69
+ results["ruGPT3-Medium"]["simple_answer"], f"{results["ruGPT3-Medium"]["simple_time"]} сек",
70
+ results["ruGPT3-Small"]["cot_answer"], f"{results["ruGPT3-Small"]["cot_time"]} сек",
71
+ results["ruGPT3-Small"]["simple_answer"], f"{results["ruGPT3-Small"]["simple_time"]} сек",
72
+ results["SambaLingo"]["cot_answer"], f"{results["SambaLingo"]["cot_time"]} сек",
73
+ results["SambaLingo"]["simple_answer"], f"{results["SambaLingo"]["simple_time"]} сек"
74
  )
75
 
76
+ # Gradio UI
77
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
78
+ gr.Markdown("🏦 **Банковский помощник: CoT vs. Обычный ответ (магистерская работа)**")
79
 
80
+ inp = gr.Textbox(label="Вопрос клиента", placeholder="Например: Я не могу перевести деньги на другую карту", lines=2)
81
  btn = gr.Button("Сгенерировать")
82
 
83
+ gr.Markdown("### ruGPT3-Medium")
84
  cot1 = gr.Textbox(label="CoT ответ")
85
  cot1_time = gr.Textbox(label="Время CoT")
86
  simple1 = gr.Textbox(label="Обычный ответ")
87
  simple1_time = gr.Textbox(label="Время обычного")
88
 
89
+ gr.Markdown("### ruGPT3-Small")
90
  cot2 = gr.Textbox(label="CoT ответ")
91
  cot2_time = gr.Textbox(label="Время CoT")
92
  simple2 = gr.Textbox(label="Обычный ответ")
93
  simple2_time = gr.Textbox(label="Время обычного")
94
 
95
+ gr.Markdown("### SambaLingo-Russian-Chat")
96
  cot3 = gr.Textbox(label="CoT ответ")
97
  cot3_time = gr.Textbox(label="Время CoT")
98
  simple3 = gr.Textbox(label="Обычный ответ")
99
  simple3_time = gr.Textbox(label="Время обычного")
100
 
101
+ btn.click(generate_classification, inputs=[inp], outputs=[
102
  cot1, cot1_time, simple1, simple1_time,
103
  cot2, cot2_time, simple2, simple2_time,
104
  cot3, cot3_time, simple3, simple3_time
 
106
 
107
  demo.launch()
108
 
109
+