SimrusDenuvo commited on
Commit
607079d
·
verified ·
1 Parent(s): 22c5acd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -55
app.py CHANGED
@@ -6,41 +6,44 @@ from datasets import load_dataset
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
 
@@ -50,57 +53,70 @@ def generate_dual_answers(user_input):
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,
 
6
  # Загружаем датасет
7
  dataset = load_dataset("Romjiik/Russian_bank_reviews", split="train")
8
 
9
+ # Примеры для few-shot
10
+ few_shot_examples = []
11
+ for row in dataset.select(range(3)):
12
+ review = row["review"]
13
+ category = row["category"] if "category" in row else "(Категория)"
14
+ ex = f"Клиент: {review}\nКлассификация: {category}"
15
+ few_shot_examples.append(ex)
16
 
17
  # Инструкции
18
  cot_instruction = (
19
+ "Ты — помощник банка. Клиент задал вопрос. Проанализируй обращение шаг за шагом, "
20
+ "выдели ключевые признаки и выдай итоговую категорию обращения."
 
21
  )
22
 
23
  simple_instruction = (
24
+ "Ты — помощник банка. Определи категорию обращения клиента. Ответ должен быть кратким, без лишнего текста."
 
25
  )
26
 
27
+ # Используемые модели
28
+ models = {
29
+ "ChatGPT-like (ruGPT3small)": pipeline("text-generation", model="ai-forever/rugpt3small_based_on_gpt2", tokenizer="ai-forever/rugpt3small_based_on_gpt2", device=-1),
30
+ "GigaChat-like (ruDialoGPT-medium)": pipeline("text-generation", model="tinkoff-ai/ruDialoGPT-medium", tokenizer="tinkoff-ai/ruDialoGPT-medium", device=-1),
31
+ "DeepSeek-like (RuBERT-tiny2)": pipeline("text-classification", model="cointegrated/rubert-tiny2", tokenizer="cointegrated/rubert-tiny2", device=-1)
32
+ }
33
+
34
+ # Формирование промптов
35
+
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
  def build_simple_prompt(user_input):
43
  examples = "\n\n".join(few_shot_examples)
44
+ return (
45
+ f"{simple_instruction}\n\n{examples}\n\nКлиент: {user_input}\nКлассификация:"
46
+ )
 
 
 
 
 
47
 
48
  # Генерация ответов
49
 
 
53
  prompt_simple = build_simple_prompt(user_input)
54
 
55
  for name, pipe in models.items():
56
+ if name.startswith("DeepSeek"):
57
+ # классификация
58
  start = time.time()
59
+ output = pipe(user_input)[0]
60
  end = round(time.time() - start, 2)
61
  results[name] = {
62
+ "cot_answer": output['label'],
63
+ "cot_time": end,
64
+ "simple_answer": output['label'],
65
+ "simple_time": end
66
  }
67
  else:
68
+ # генерация CoT
69
  start_cot = time.time()
70
+ out_cot = pipe(prompt_cot, max_new_tokens=100, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
71
  end_cot = round(time.time() - start_cot, 2)
72
+ answer_cot = out_cot.split("Классификация:")[-1].strip()
73
 
74
+ # генерация Simple
75
  start_simple = time.time()
76
+ out_simple = pipe(prompt_simple, max_new_tokens=60, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
77
  end_simple = round(time.time() - start_simple, 2)
78
+ answer_simple = out_simple.split("Классификация:")[-1].strip()
79
 
80
  results[name] = {
81
+ "cot_answer": answer_cot,
82
+ "cot_time": end_cot,
83
+ "simple_answer": answer_simple,
84
+ "simple_time": end_simple
85
  }
86
 
87
  return (
88
+ results["ChatGPT-like (ruGPT3small)"]["cot_answer"], f"{results['ChatGPT-like (ruGPT3small)']['cot_time']} сек",
89
+ results["ChatGPT-like (ruGPT3small)"]["simple_answer"], f"{results['ChatGPT-like (ruGPT3small)']['simple_time']} сек",
90
+ results["GigaChat-like (ruDialoGPT-medium)"]["cot_answer"], f"{results['GigaChat-like (ruDialoGPT-medium)']['cot_time']} сек",
91
+ results["GigaChat-like (ruDialoGPT-medium)"]["simple_answer"], f"{results['GigaChat-like (ruDialoGPT-medium)']['simple_time']} сек",
92
+ results["DeepSeek-like (RuBERT-tiny2)"]["cot_answer"], f"{results['DeepSeek-like (RuBERT-tiny2)']['cot_time']} сек",
93
+ results["DeepSeek-like (RuBERT-tiny2)"]["simple_answer"], f"{results['DeepSeek-like (RuBERT-tiny2)']['simple_time']} сек"
94
  )
95
 
96
+ # Gradio интерфейс
97
  with gr.Blocks() as demo:
98
+ gr.Markdown("## 🏦 Классификация клиентских обращений Сравнение моделей и промптов")
99
+
100
+ inp = gr.Textbox(label="Вопрос клиента", placeholder="Например: Не приходит СМС-код для входа в приложение", lines=2)
101
+ btn = gr.Button("Классифицировать")
102
+
103
+ gr.Markdown("### ChatGPT-like (ruGPT3small)")
104
+ cot1 = gr.Textbox(label="CoT ответ")
105
+ cot1_time = gr.Textbox(label="Время CoT")
106
+ simple1 = gr.Textbox(label="Обычный ответ")
107
+ simple1_time = gr.Textbox(label="Время обычного")
108
+
109
+ gr.Markdown("### GigaChat-like (ruDialoGPT-medium)")
110
+ cot2 = gr.Textbox(label="CoT ответ")
111
+ cot2_time = gr.Textbox(label="Время CoT")
112
+ simple2 = gr.Textbox(label="Обычный ответ")
113
+ simple2_time = gr.Textbox(label="Время обычного")
114
+
115
+ gr.Markdown("### DeepSeek-like (RuBERT-tiny2)")
116
+ cot3 = gr.Textbox(label="CoT ответ")
117
+ cot3_time = gr.Textbox(label="Время CoT")
118
+ simple3 = gr.Textbox(label="Обычный ответ")
119
+ simple3_time = gr.Textbox(label="Время обычного")
120
 
121
  btn.click(generate_dual_answers, inputs=[inp], outputs=[
122
  cot1, cot1_time, simple1, simple1_time,