SimrusDenuvo commited on
Commit
8519047
·
verified ·
1 Parent(s): 6bbd70d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -65
app.py CHANGED
@@ -3,116 +3,127 @@ 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
- # Примеры для few-shot
10
  few_shot_examples = []
11
  for row in dataset.select(range(2)):
12
  review = row["review"]
13
- example = f"Клиент: {review}\nКлассификация: прочее"
14
- few_shot_examples.append(example)
15
 
16
- # Инструкции
17
  cot_instruction = (
18
- "Ты — ассистент банка. Проанализируй обращение клиента и классифицируй его по теме."
19
- " Сначала рассуждай шаг за шагом, затем выведи финальную категорию."
 
20
  )
21
 
22
  simple_instruction = (
23
- "Ты — банковский помощник. Классифицируй обращение клиента одним словом категорией."
 
24
  )
25
 
26
- # Промпты
 
 
 
 
 
27
 
 
28
  def build_cot_prompt(user_input):
29
  examples = "\n\n".join(few_shot_examples)
30
  return (
31
  f"{cot_instruction}\n\n{examples}\n\nКлиент: {user_input}\n"
32
- f"Рассуждение:"
33
  )
34
 
35
-
36
  def build_simple_prompt(user_input):
37
  examples = "\n\n".join(few_shot_examples)
38
  return (
39
  f"{simple_instruction}\n\n{examples}\n\nКлиент: {user_input}\n"
40
- f"Категория:"
41
  )
42
 
43
- # Рабочие модели с поддержкой русского языка и легкие
44
- models = {
45
- "ChatGPT-like (FRED-T5-small)": pipeline("text2text-generation", model="cointegrated/translation-t5-russian-finetuned", tokenizer="cointegrated/translation-t5-russian-finetuned", device=-1),
46
- "DeepSeek-like (ruGPT3-small)": pipeline("text-generation", model="ai-forever/rugpt3small_based_on_gpt2", tokenizer="ai-forever/rugpt3small_based_on_gpt2", device=-1),
47
- "GigaChat-like (RuBERT-tiny2)": pipeline("text-classification", model="cointegrated/rubert-tiny2", tokenizer="cointegrated/rubert-tiny2", device=-1),
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
- # CoT
59
- start_cot = time.time()
60
- try:
61
- out_cot = pipe(prompt_cot, max_new_tokens=150, do_sample=True, top_p=0.9, temperature=0.7)[0]
62
- answer_cot = out_cot.get("generated_text", out_cot.get("label", "-"))
63
- except:
64
- answer_cot = "Ошибка в CoT"
65
- end_cot = round(time.time() - start_cot, 2)
66
-
67
- # Simple
68
- start_simple = time.time()
69
- try:
70
- out_simple = pipe(prompt_simple, max_new_tokens=150, do_sample=True, top_p=0.9, temperature=0.7)[0]
71
- answer_simple = out_simple.get("generated_text", out_simple.get("label", "-"))
72
- except:
73
- answer_simple = "Ошибка в обычном"
74
- end_simple = round(time.time() - start_simple, 2)
75
-
76
- results[name] = {
77
- "cot_answer": answer_cot.strip(),
78
- "cot_time": end_cot,
79
- "simple_answer": answer_simple.strip(),
80
- "simple_time": end_simple
81
- }
 
 
 
 
 
 
82
 
83
  return (
84
- results["ChatGPT-like (FRED-T5-small)"]["cot_answer"], f"{results['ChatGPT-like (FRED-T5-small)']['cot_time']} сек",
85
- results["ChatGPT-like (FRED-T5-small)"]["simple_answer"], f"{results['ChatGPT-like (FRED-T5-small)']['simple_time']} сек",
86
-
87
- results["DeepSeek-like (ruGPT3-small)"]["cot_answer"], f"{results['DeepSeek-like (ruGPT3-small)']['cot_time']} сек",
88
- results["DeepSeek-like (ruGPT3-small)"]["simple_answer"], f"{results['DeepSeek-like (ruGPT3-small)']['simple_time']} сек",
89
-
90
- results["GigaChat-like (RuBERT-tiny2)"]["cot_answer"], f"{results['GigaChat-like (RuBERT-tiny2)']['cot_time']} сек",
91
- results["GigaChat-like (RuBERT-tiny2)"]["simple_answer"], f"{results['GigaChat-like (RuBERT-tiny2)']['simple_time']} сек",
92
  )
93
 
94
  # Интерфейс Gradio
95
  with gr.Blocks() as demo:
96
- gr.Markdown("## 🤖 Классификация клиентских обращений CoT vs обычный промпт")
97
- inp = gr.Textbox(label="Обращение клиента", placeholder="Например: Я не могу войти в личный кабинет", lines=2)
 
98
  btn = gr.Button("Классифицировать")
99
 
100
- gr.Markdown("### ChatGPT-like (FRED-T5-small)")
101
- cot1, cot1_time = gr.Textbox(label="CoT ответ"), gr.Textbox(label="Время CoT")
102
- simple1, simple1_time = gr.Textbox(label="Обычный ответ"), gr.Textbox(label="Время обычного")
 
 
103
 
104
- gr.Markdown("### DeepSeek-like (ruGPT3-small)")
105
- cot2, cot2_time = gr.Textbox(label="CoT ответ"), gr.Textbox(label="Время CoT")
106
- simple2, simple2_time = gr.Textbox(label="Обычный ответ"), gr.Textbox(label="Время обычного")
 
 
107
 
108
- gr.Markdown("### GigaChat-like (RuBERT-tiny2)")
109
- cot3, cot3_time = gr.Textbox(label="CoT ответ"), gr.Textbox(label="Время CoT")
110
- simple3, simple3_time = gr.Textbox(label="Обычный ответ"), gr.Textbox(label="Время обычного")
 
 
111
 
112
  btn.click(generate_dual_answers, inputs=[inp], outputs=[
113
  cot1, cot1_time, simple1, simple1_time,
114
  cot2, cot2_time, simple2, simple2_time,
115
- cot3, cot3_time, simple3, simple3_time,
116
  ])
117
 
118
  if __name__ == '__main__':
 
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
+ "Ты — банковский помощник. Твоя задача классифицировать клиентское обращение.\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__':