SimrusDenuvo commited on
Commit
f5f461a
·
verified ·
1 Parent(s): 4fb6307

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -43
app.py CHANGED
@@ -3,74 +3,114 @@ import time
3
  from transformers import pipeline
4
  from datasets import load_dataset
5
 
6
- # Загрузка датасета с отзывами банков
7
  dataset = load_dataset("Romjiik/Russian_bank_reviews", split="train")
8
 
9
- # Отбираем 2 примера для few-shot в CoT
10
  few_shot_examples = []
11
  for row in dataset.select(range(2)):
12
  review = row["review"]
13
- rating = row["rating"]
14
- ex = f"Клиент: {review}\nОценка: {rating}\nОтвет: Пожалуйста, разъясните ситуацию в деталях. Мы поможем."
15
  few_shot_examples.append(ex)
16
 
17
- # Системная инструкция
18
- system_instruction = (
19
- "Ты — вежливый и точный банковский помощник. "
20
- "Ты читаешь обращения клиентов и даешь корректные, подробные, официальные ответы. "
21
- "Если данных недостаточно — просишь уточнение. Используй рассуждение шаг за шагом."
22
  )
23
 
24
- # Загружаем три модели
 
 
 
 
 
25
  models = {
26
  "ruDialoGPT-small": pipeline("text-generation", model="t-bank-ai/ruDialoGPT-small", tokenizer="t-bank-ai/ruDialoGPT-small", device=-1),
27
  "ruDialoGPT-medium": pipeline("text-generation", model="t-bank-ai/ruDialoGPT-medium", tokenizer="t-bank-ai/ruDialoGPT-medium", device=-1),
28
  "ruGPT3-small": pipeline("text-generation", model="ai-forever/rugpt3small_based_on_gpt2", tokenizer="ai-forever/rugpt3small_based_on_gpt2", device=-1),
29
  }
30
 
31
- # Построение CoT-промпта
32
- def build_prompt(user_input):
 
 
 
 
 
 
 
 
33
  examples = "\n\n".join(few_shot_examples)
34
  return (
35
- f"{system_instruction}\n\n"
36
- f"{examples}\n\n"
37
- f"Клиент: {user_input}\n"
38
- f"Опиши шаг за шагом размышления, затем сформулируй окончательный ответ клиенту:"
39
  )
40
 
41
- # Генерация ответов
42
- def generate_answers(prompt):
43
  results = {}
 
 
 
44
  for name, pipe in models.items():
45
- start = time.time()
46
- out = pipe(prompt, max_length=300, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
47
- elapsed = round(time.time() - start, 2)
48
- final_line = out.strip().split('\n')[-1]
49
- results[name] = {"answer": final_line, "time": elapsed}
50
- return results
51
-
52
- # Формат вывода
53
- def run_models(user_input):
54
- prompt = build_prompt(user_input)
55
- res = generate_answers(prompt)
 
 
 
 
 
 
 
 
56
  return (
57
- res["ruDialoGPT-small"]["answer"], f"{res['ruDialoGPT-small']['time']} сек",
58
- res["ruDialoGPT-medium"]["answer"], f"{res['ruDialoGPT-medium']['time']} сек",
59
- res["ruGPT3-small"]["answer"], f"{res['ruGPT3-small']['time']} сек",
 
 
 
60
  )
61
 
62
  # Интерфейс Gradio
63
  with gr.Blocks() as demo:
64
- gr.Markdown("## 🤖 Банковский помощник: CoT + 3 модели (русский язык)")
65
- inp = gr.Textbox(label="Запрос клиента", placeholder="Например: Я не могу попасть в личный кабинет", lines=2)
66
- btn = gr.Button("Сгенерировать ответы")
67
- out1 = gr.Textbox(label="ruDialoGPT-small")
68
- t1 = gr.Textbox(label="Время")
69
- out2 = gr.Textbox(label="ruDialoGPT-medium")
70
- t2 = gr.Textbox(label="Время")
71
- out3 = gr.Textbox(label="ruGPT3-small")
72
- t3 = gr.Textbox(label="Время")
73
-
74
- btn.click(run_models, inputs=[inp], outputs=[out1, t1, out2, t2, out3, t3])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  demo.launch()
 
3
  from transformers import pipeline
4
  from datasets import load_dataset
5
 
6
+ # Загружаем датасет
7
  dataset = load_dataset("Romjiik/Russian_bank_reviews", split="train")
8
 
9
+ # Примеры для few-shot (без 'rating')
10
  few_shot_examples = []
11
  for row in dataset.select(range(2)):
12
  review = row["review"]
13
+ ex = f"Клиент: {review}\nОтвет: Спасибо за обращение! Уточните, пожалуйста, детали ситуации, чтобы мы могли помочь."
 
14
  few_shot_examples.append(ex)
15
 
16
+ # Системные инструкции
17
+ cot_instruction = (
18
+ "Ты — вежливый банковский помощник. Клиент описывает проблему. "
19
+ "Сначала проанализируй её шаг за шагом, потом сформулируй итоговый ответ."
 
20
  )
21
 
22
+ simple_instruction = (
23
+ "Ты — вежливый банковский помощник. Отвечай кратко и официально, без лишних деталей. "
24
+ "Не используй рассуждение, просто дай понятный клиенту ответ."
25
+ )
26
+
27
+ # Модели
28
  models = {
29
  "ruDialoGPT-small": pipeline("text-generation", model="t-bank-ai/ruDialoGPT-small", tokenizer="t-bank-ai/ruDialoGPT-small", device=-1),
30
  "ruDialoGPT-medium": pipeline("text-generation", model="t-bank-ai/ruDialoGPT-medium", tokenizer="t-bank-ai/ruDialoGPT-medium", device=-1),
31
  "ruGPT3-small": pipeline("text-generation", model="ai-forever/rugpt3small_based_on_gpt2", tokenizer="ai-forever/rugpt3small_based_on_gpt2", device=-1),
32
  }
33
 
34
+ # Промпт CoT
35
+ def build_cot_prompt(user_input):
36
+ examples = "\n\n".join(few_shot_examples)
37
+ return (
38
+ f"{cot_instruction}\n\n{examples}\n\nКлиент: {user_input}\n"
39
+ "Рассуждение и ответ:"
40
+ )
41
+
42
+ # Промпт простой
43
+ def build_simple_prompt(user_input):
44
  examples = "\n\n".join(few_shot_examples)
45
  return (
46
+ f"{simple_instruction}\n\n{examples}\n\nКлиент: {user_input}\n"
47
+ "Ответ:"
 
 
48
  )
49
 
50
+ # Генерация ответов по двум промптам
51
+ def generate_dual_answers(user_input):
52
  results = {}
53
+ prompt_cot = build_cot_prompt(user_input)
54
+ prompt_simple = build_simple_prompt(user_input)
55
+
56
  for name, pipe in models.items():
57
+ # CoT
58
+ start_cot = time.time()
59
+ out_cot = pipe(prompt_cot, max_length=300, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
60
+ end_cot = round(time.time() - start_cot, 2)
61
+ answer_cot = out_cot.strip().split('\n')[-1]
62
+
63
+ # Simple
64
+ start_simple = time.time()
65
+ out_simple = pipe(prompt_simple, max_length=300, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
66
+ end_simple = round(time.time() - start_simple, 2)
67
+ answer_simple = out_simple.strip().split('\n')[-1]
68
+
69
+ results[name] = {
70
+ "cot_answer": answer_cot,
71
+ "cot_time": end_cot,
72
+ "simple_answer": answer_simple,
73
+ "simple_time": end_simple
74
+ }
75
+
76
  return (
77
+ results["ruDialoGPT-small"]["cot_answer"], f"{results['ruDialoGPT-small']['cot_time']} сек",
78
+ results["ruDialoGPT-small"]["simple_answer"], f"{results['ruDialoGPT-small']['simple_time']} сек",
79
+ results["ruDialoGPT-medium"]["cot_answer"], f"{results['ruDialoGPT-medium']['cot_time']} сек",
80
+ results["ruDialoGPT-medium"]["simple_answer"], f"{results['ruDialoGPT-medium']['simple_time']} сек",
81
+ results["ruGPT3-small"]["cot_answer"], f"{results['ruGPT3-small']['cot_time']} сек",
82
+ results["ruGPT3-small"]["simple_answer"], f"{results['ruGPT3-small']['simple_time']} сек",
83
  )
84
 
85
  # Интерфейс Gradio
86
  with gr.Blocks() as demo:
87
+ gr.Markdown("## 🏦 Банковский помощник (2 промпта: рассуждение + краткий ответ)")
88
+
89
+ inp = gr.Textbox(label="Вопрос клиента", placeholder="Например: Я не могу попасть в личный кабинет", lines=2)
90
+ btn = gr.Button("Сгенерировать")
91
+
92
+ gr.Markdown("### ruDialoGPT-small")
93
+ cot1 = gr.Textbox(label="CoT ответ")
94
+ cot1_time = gr.Textbox(label="Время CoT")
95
+ simple1 = gr.Textbox(label="Обычный ответ")
96
+ simple1_time = gr.Textbox(label="Время обычного")
97
+
98
+ gr.Markdown("### ruDialoGPT-medium")
99
+ cot2 = gr.Textbox(label="CoT ответ")
100
+ cot2_time = gr.Textbox(label="Время CoT")
101
+ simple2 = gr.Textbox(label="Обычный ответ")
102
+ simple2_time = gr.Textbox(label="Время обычного")
103
+
104
+ gr.Markdown("### ruGPT3-small")
105
+ cot3 = gr.Textbox(label="CoT ответ")
106
+ cot3_time = gr.Textbox(label="Время CoT")
107
+ simple3 = gr.Textbox(label="Обычный ответ")
108
+ simple3_time = gr.Textbox(label="Время обычного")
109
+
110
+ btn.click(generate_dual_answers, inputs=[inp], outputs=[
111
+ cot1, cot1_time, simple1, simple1_time,
112
+ cot2, cot2_time, simple2, simple2_time,
113
+ cot3, cot3_time, simple3, simple3_time
114
+ ])
115
 
116
  demo.launch()