SimrusDenuvo commited on
Commit
22c5acd
·
verified ·
1 Parent(s): 88dd26b

Update app.py

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