SimrusDenuvo commited on
Commit
34db0e6
·
verified ·
1 Parent(s): 8519047

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -85
app.py CHANGED
@@ -4,127 +4,120 @@ 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
- "Ты — банковский помощник. Твоя задача классифицировать клиентское обращение.\n"
19
- "Проанализируй обращение пошагово, выдели ключевые слова, выясни намерение клиента,\n"
20
- "и отнеси его к одной из категорий: вход в ЛК, SMS, заявка, ошибка, перевод, карта, другое."
21
  )
22
 
23
  simple_instruction = (
24
- "Ты — банковский помощник. Классифицируй обращение пользователя кратко и по существу,\n"
25
- "укажи одну категорию: вход в ЛК, SMS, заявка, ошибка, перевод, карта, другое."
26
  )
27
 
28
- # Модели
29
  models = {
30
- "ChatGPT-like (ruGPT3-small)": pipeline("text-generation", model="ai-forever/rugpt3small_based_on_gpt2", tokenizer="ai-forever/rugpt3small_based_on_gpt2", device=-1),
31
- "DeepSeek-like (rubert-tiny2)": pipeline("text-classification", model="cointegrated/rubert-tiny2", tokenizer="cointegrated/rubert-tiny2", device=-1),
32
- "GigaChat-like (sberbank-ai/rugpt3medium_based_on_gpt2)": pipeline("text-generation", model="sberbank-ai/rugpt3medium_based_on_gpt2", tokenizer="sberbank-ai/rugpt3medium_based_on_gpt2", device=-1),
33
  }
34
 
35
- # Промпт CoT
 
36
  def build_cot_prompt(user_input):
37
  examples = "\n\n".join(few_shot_examples)
38
  return (
39
- f"{cot_instruction}\n\n{examples}\n\nКлиент: {user_input}\n"
40
- "Рассуждение и классификация:"
41
  )
42
 
43
- # Промпт простой
44
  def build_simple_prompt(user_input):
45
  examples = "\n\n".join(few_shot_examples)
46
  return (
47
- f"{simple_instruction}\n\n{examples}\n\nКлиент: {user_input}\n"
48
- "Категория:"
49
  )
50
 
51
- # Генерация ответов по двум промптам
 
52
  def generate_dual_answers(user_input):
53
  results = {}
54
  prompt_cot = build_cot_prompt(user_input)
55
  prompt_simple = build_simple_prompt(user_input)
56
 
57
  for name, pipe in models.items():
58
- if name.startswith("DeepSeek-like"):
59
- # Text-classification модель
60
- start_simple = time.time()
61
- classification = pipe(user_input)[0]['label']
62
- end_simple = round(time.time() - start_simple, 2)
63
- results[name] = {
64
- "cot_answer": "(CoT не поддерживается)",
65
- "cot_time": "-",
66
- "simple_answer": classification,
67
- "simple_time": end_simple
68
- }
69
- else:
70
  # CoT
71
  start_cot = time.time()
72
- out_cot = pipe(prompt_cot, max_length=200, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
73
  end_cot = round(time.time() - start_cot, 2)
74
  answer_cot = out_cot.strip().split("\n")[-1]
75
 
76
  # Simple
77
  start_simple = time.time()
78
- out_simple = pipe(prompt_simple, max_length=150, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
79
  end_simple = round(time.time() - start_simple, 2)
80
  answer_simple = out_simple.strip().split("\n")[-1]
81
 
82
- results[name] = {
83
- "cot_answer": answer_cot,
84
- "cot_time": end_cot,
85
- "simple_answer": answer_simple,
86
- "simple_time": end_simple
87
- }
88
 
89
- return (
90
- results["ChatGPT-like (ruGPT3-small)"]["cot_answer"], f"{results['ChatGPT-like (ruGPT3-small)']['cot_time']} сек",
91
- results["ChatGPT-like (ruGPT3-small)"]["simple_answer"], f"{results['ChatGPT-like (ruGPT3-small)']['simple_time']} сек",
92
- results["DeepSeek-like (rubert-tiny2)"]["cot_answer"], results["DeepSeek-like (rubert-tiny2)"]["cot_time"],
93
- results["DeepSeek-like (rubert-tiny2)"]["simple_answer"], f"{results['DeepSeek-like (rubert-tiny2)']['simple_time']} сек",
94
- results["GigaChat-like (sberbank-ai/rugpt3medium_based_on_gpt2)"]["cot_answer"], f"{results['GigaChat-like (sberbank-ai/rugpt3medium_based_on_gpt2)']['cot_time']} сек",
95
- results["GigaChat-like (sberbank-ai/rugpt3medium_based_on_gpt2)"]["simple_answer"], f"{results['GigaChat-like (sberbank-ai/rugpt3medium_based_on_gpt2)']['simple_time']} сек",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  )
97
 
98
- # Интерфейс Gradio
 
99
  with gr.Blocks() as demo:
100
- gr.Markdown("## 🏦 Классификация клиентских обращений (CoT + обычный)")
101
-
102
- inp = gr.Textbox(label="Обращение клиента", placeholder="Например: Я не могу попасть в личный кабинет", lines=2)
103
- btn = gr.Button("Классифицировать")
104
-
105
- gr.Markdown("### ChatGPT-like (ruGPT3-small)")
106
- cot1 = gr.Textbox(label="CoT ответ")
107
- cot1_time = gr.Textbox(label="Время CoT")
108
- simple1 = gr.Textbox(label="Обычный ответ")
109
- simple1_time = gr.Textbox(label="Время обычного")
110
-
111
- gr.Markdown("### DeepSeek-like (rubert-tiny2)")
112
- cot2 = gr.Textbox(label="CoT ответ")
113
- cot2_time = gr.Textbox(label="Время CoT")
114
- simple2 = gr.Textbox(label="Обычный ответ")
115
- simple2_time = gr.Textbox(label="Время обычного")
116
-
117
- gr.Markdown("### GigaChat-like (ruGPT3-medium)")
118
- cot3 = gr.Textbox(label="CoT ответ")
119
- cot3_time = gr.Textbox(label="Время CoT")
120
- simple3 = gr.Textbox(label="Обычный ответ")
121
- simple3_time = gr.Textbox(label="Время обычного")
122
-
123
- btn.click(generate_dual_answers, inputs=[inp], outputs=[
124
- cot1, cot1_time, simple1, simple1_time,
125
- cot2, cot2_time, simple2, simple2_time,
126
- cot3, cot3_time, simple3, simple3_time
127
- ])
128
-
129
- if __name__ == '__main__':
130
- demo.launch()
 
4
  from datasets import load_dataset
5
 
6
  # Загружаем датасет
7
+ DATASET_NAME = "Romjiik/Russian_bank_reviews"
8
+ dataset = load_dataset(DATASET_NAME, split="train")
9
+
10
+ # Краткий список примеров для подстановки в промпт (для классификации)
11
+ few_shot_examples = [
12
+ "Клиент: Не могу войти в приложение.\nКлассификация: Техническая проблема",
13
+ "Клиент: Почему с меня сняли деньги дважды?\nКлассификация: Ошибка транзакции",
14
+ "Клиент: Хочу оформить кредит.\nКлассификация: Запрос на продукт",
15
+ "Клиент: У меня украли карту.\nКлассификация: Безопасность",
16
+ "Клиент: Не приходит СМС для входа.\nКлассификация: Проблема авторизации"
17
+ ]
18
+
19
+ # Инструкции
20
  cot_instruction = (
21
+ "Ты — банковский помощник. Клиент описывает ситуацию. "
22
+ "Проанализируй обращение шаг за шагом и определи категорию (например: 'Техническая проблема', 'Запрос на продукт', 'Безопасность' и т.п.)"
 
23
  )
24
 
25
  simple_instruction = (
26
+ "Ты — банковский помощник. Клиент описывает обращение. "
27
+ "Кратко укажи категорию обращения (например: 'Техническая проблема', 'Запрос на продукт', 'Безопасность' и т.п.)."
28
  )
29
 
30
+ # Используемые модели (CPU-compatible, ≤16GB)
31
  models = {
32
+ "ChatGPT-like (FRED-T5-small)": pipeline("text2text-generation", model="ai-forever/FRED-T5-Base", tokenizer="ai-forever/FRED-T5-Base", device=-1),
33
+ "DeepSeek-like (ruGPT3-small)": pipeline("text-generation", model="ai-forever/rugpt3small_based_on_gpt2", tokenizer="ai-forever/rugpt3small_based_on_gpt2", device=-1),
34
+ "GigaChat-like (RuBERT-tiny2-clf)": pipeline("text-classification", model="cointegrated/rubert-tiny2", tokenizer="cointegrated/rubert-tiny2", device=-1)
35
  }
36
 
37
+ # Построение промптов
38
+
39
  def build_cot_prompt(user_input):
40
  examples = "\n\n".join(few_shot_examples)
41
  return (
42
+ f"{cot_instruction}\n\n{examples}\n\nКлиент: {user_input}\nРассуждение и классификация:"
 
43
  )
44
 
 
45
  def build_simple_prompt(user_input):
46
  examples = "\n\n".join(few_shot_examples)
47
  return (
48
+ f"{simple_instruction}\n\n{examples}\n\nКлиент: {user_input}\nКлассификация:"
 
49
  )
50
 
51
+ # Генерация классификаций
52
+
53
  def generate_dual_answers(user_input):
54
  results = {}
55
  prompt_cot = build_cot_prompt(user_input)
56
  prompt_simple = build_simple_prompt(user_input)
57
 
58
  for name, pipe in models.items():
59
+ if "text-generation" in str(pipe.task):
 
 
 
 
 
 
 
 
 
 
 
60
  # CoT
61
  start_cot = time.time()
62
+ out_cot = pipe(prompt_cot, max_length=256, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
63
  end_cot = round(time.time() - start_cot, 2)
64
  answer_cot = out_cot.strip().split("\n")[-1]
65
 
66
  # Simple
67
  start_simple = time.time()
68
+ out_simple = pipe(prompt_simple, max_length=128, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
69
  end_simple = round(time.time() - start_simple, 2)
70
  answer_simple = out_simple.strip().split("\n")[-1]
71
 
72
+ elif "text2text-generation" in str(pipe.task):
73
+ start_cot = time.time()
74
+ out_cot = pipe(prompt_cot, max_new_tokens=50)[0]["generated_text"]
75
+ end_cot = round(time.time() - start_cot, 2)
 
 
76
 
77
+ start_simple = time.time()
78
+ out_simple = pipe(prompt_simple, max_new_tokens=30)[0]["generated_text"]
79
+ end_simple = round(time.time() - start_simple, 2)
80
+
81
+ answer_cot = out_cot.strip()
82
+ answer_simple = out_simple.strip()
83
+
84
+ elif "text-classification" in str(pipe.task):
85
+ # Для классификации используем только сам ввод без промпта
86
+ start = time.time()
87
+ answer = pipe(user_input)[0]['label']
88
+ end = round(time.time() - start, 2)
89
+ answer_cot = answer
90
+ answer_simple = answer
91
+ end_cot = end_simple = end
92
+
93
+ results[name] = {
94
+ "cot_answer": answer_cot,
95
+ "cot_time": end_cot,
96
+ "simple_answer": answer_simple,
97
+ "simple_time": end_simple
98
+ }
99
+
100
+ return tuple(
101
+ results[model][key] for model in models for key in ["cot_answer", "cot_time", "simple_answer", "simple_time"]
102
  )
103
 
104
+ # Gradio UI
105
+
106
  with gr.Blocks() as demo:
107
+ gr.Markdown("## 🧠 Классификация клиентских обращений в банке (CoT vs обычный промпт)")
108
+
109
+ inp = gr.Textbox(label="Вопрос клиента", placeholder="Например: У меня не проходит оплата картой", lines=2)
110
+ btn = gr.Button("Сгенерировать")
111
+
112
+ results_blocks = []
113
+ for name in models:
114
+ gr.Markdown(f"### {name}")
115
+ cot = gr.Textbox(label="CoT ответ")
116
+ cot_time = gr.Textbox(label="Время CoT")
117
+ simple = gr.Textbox(label="Обычный ответ")
118
+ simple_time = gr.Textbox(label="Время обычного")
119
+ results_blocks.extend([cot, cot_time, simple, simple_time])
120
+
121
+ btn.click(generate_dual_answers, inputs=[inp], outputs=results_blocks)
122
+
123
+ demo.launch()