SimrusDenuvo commited on
Commit
c43dd36
·
verified ·
1 Parent(s): ead8089

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -40
app.py CHANGED
@@ -1,39 +1,54 @@
1
  import gradio as gr
2
  import time
3
  from transformers import pipeline
 
4
 
5
- # Подключаем модели (проверенные, лёгкие и с поддержкой русского)
6
- models = {
7
- "ChatGPT-like (saiga2_7b_lora)": pipeline("text2text-generation", model="IlyaGusev/saiga2_7b_lora", tokenizer="IlyaGusev/saiga2_7b_lora", device=-1),
8
- "DeepSeek-like (ruGPT3small)": pipeline("text-generation", model="ai-forever/ruGPT3Small", tokenizer="ai-forever/ruGPT3Small", device=-1),
9
- "GigaChat-like (rubert-base-sentiment)": pipeline("text2text-generation", model="blanchefort/rubert-base-cased-sentiment", tokenizer="blanchefort/rubert-base-cased-sentiment", device=-1),
10
- }
11
 
12
- # Промпты
 
 
 
 
 
 
 
13
  cot_instruction = (
14
- "Ты — банковский помощник. Клиент описал проблему. Проанализируй шаг за шагом:\n"
15
- "1. Что произошло?\n"
16
- "2. Возможные причины?\n"
17
- "3. Что делать клиенту?\n"
18
- "В конце выдай: Категория обращения (доступ, платежи, безопасность, перевод и т.д.).\n"
19
- "\nЗапрос клиента: {user_input}\n"
20
  )
21
 
22
  simple_instruction = (
23
- "Ты — банковский помощник. Определи, к какой категории относится обращение клиента: доступ, платежи, безопасность, перевод и т.д.\n"
24
- "Запрос клиента: {user_input}\n"
25
- "Категория:"
26
  )
27
 
28
- # Функции построения промптов
 
 
 
 
 
 
 
29
  def build_cot_prompt(user_input):
30
- return cot_instruction.format(user_input=user_input)
 
 
 
 
31
 
 
32
  def build_simple_prompt(user_input):
33
- return simple_instruction.format(user_input=user_input)
34
-
35
- # Генерация
 
 
36
 
 
37
  def generate_dual_answers(user_input):
38
  results = {}
39
  prompt_cot = build_cot_prompt(user_input)
@@ -42,13 +57,13 @@ def generate_dual_answers(user_input):
42
  for name, pipe in models.items():
43
  # CoT
44
  start_cot = time.time()
45
- out_cot = pipe(prompt_cot, max_length=300, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
46
  end_cot = round(time.time() - start_cot, 2)
47
  answer_cot = out_cot.strip().split('\n')[-1]
48
 
49
  # Simple
50
  start_simple = time.time()
51
- out_simple = pipe(prompt_simple, max_length=200, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
52
  end_simple = round(time.time() - start_simple, 2)
53
  answer_simple = out_simple.strip().split('\n')[-1]
54
 
@@ -59,37 +74,40 @@ def generate_dual_answers(user_input):
59
  "simple_time": end_simple
60
  }
61
 
62
- return (
63
- results["ChatGPT-like (saiga2_7b_lora)"]["cot_answer"], f"{results['ChatGPT-like (saiga2_7b_lora)']['cot_time']} сек",
64
- results["ChatGPT-like (saiga2_7b_lora)"]["simple_answer"], f"{results['ChatGPT-like (saiga2_7b_lora)']['simple_time']} сек",
65
-
66
- results["DeepSeek-like (ruGPT3small)"]["cot_answer"], f"{results['DeepSeek-like (ruGPT3small)']['cot_time']} сек",
67
- results["DeepSeek-like (ruGPT3small)"]["simple_answer"], f"{results['DeepSeek-like (ruGPT3small)']['simple_time']} сек",
68
-
69
- results["GigaChat-like (rubert-base-sentiment)"]["cot_answer"], f"{results['GigaChat-like (rubert-base-sentiment)']['cot_time']} сек",
70
- results["GigaChat-like (rubert-base-sentiment)"]["simple_answer"], f"{results['GigaChat-like (rubert-base-sentiment)']['simple_time']} сек",
 
 
 
71
  )
72
 
73
- # Интерфейс
74
  with gr.Blocks() as demo:
75
- gr.Markdown("## Сравнение моделей: ruGPT3small, saiga2, ruBERT (Классификация обращений)")
76
 
77
- inp = gr.Textbox(label="Вопрос клиента", placeholder="Например: Я не могу оплатить картой в магазине, пишет «техническая ошибка»")
78
  btn = gr.Button("Сгенерировать")
79
 
80
- gr.Markdown("### ChatGPT-like (saiga2_7b_lora)")
81
  cot1 = gr.Textbox(label="CoT ответ")
82
  cot1_time = gr.Textbox(label="Время CoT")
83
  simple1 = gr.Textbox(label="Обычный ответ")
84
  simple1_time = gr.Textbox(label="Время обычного")
85
 
86
- gr.Markdown("### DeepSeek-like (ruGPT3small)")
87
  cot2 = gr.Textbox(label="CoT ответ")
88
  cot2_time = gr.Textbox(label="Время CoT")
89
  simple2 = gr.Textbox(label="Обычный ответ")
90
  simple2_time = gr.Textbox(label="Время обычного")
91
 
92
- gr.Markdown("### GigaChat-like (rubert-base-sentiment)")
93
  cot3 = gr.Textbox(label="CoT ответ")
94
  cot3_time = gr.Textbox(label="Время CoT")
95
  simple3 = gr.Textbox(label="Обычный ответ")
@@ -101,6 +119,5 @@ with gr.Blocks() as demo:
101
  cot3, cot3_time, simple3, simple3_time
102
  ])
103
 
104
-
105
- if __name__ == '__main__':
106
  demo.launch()
 
1
  import gradio as gr
2
  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 (без '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
+ " Проанализируй обращение пошагово: 1. Что случилось? 2. Почему это могло произойти? 3. Как клиенту поступить?"
20
+ " Вывод: укажи категорию обращения (например: доступ, безопасность, платежи, перевод и т.д.)"
 
 
 
21
  )
22
 
23
  simple_instruction = (
24
+ "Ты — вежливый банковский помощник. Определи кратко, к какой категории относится обращение клиента"
25
+ " (например: доступ, платежи, безопасность и т.д.)."
 
26
  )
27
 
28
+ # Модели
29
+ models = {
30
+ "ChatGPT-like (saiga_mistral)": pipeline("text-generation", model="IlyaGusev/saiga_mistral_7b_merged", tokenizer="IlyaGusev/saiga_mistral_7b_merged", device=-1),
31
+ "DeepSeek-like (ruGPT3-medium)": pipeline("text-generation", model="ai-forever/rugpt3medium_based_on_gpt2", tokenizer="ai-forever/rugpt3medium_based_on_gpt2", device=-1),
32
+ "GigaChat-like (rubert-tiny2)": pipeline("text-generation", model="cointegrated/rubert-tiny2", tokenizer="cointegrated/rubert-tiny2", 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)
 
57
  for name, pipe in models.items():
58
  # CoT
59
  start_cot = time.time()
60
+ out_cot = pipe(prompt_cot, max_new_tokens=300, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
61
  end_cot = round(time.time() - start_cot, 2)
62
  answer_cot = out_cot.strip().split('\n')[-1]
63
 
64
  # Simple
65
  start_simple = time.time()
66
+ out_simple = pipe(prompt_simple, max_new_tokens=300, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
67
  end_simple = round(time.time() - start_simple, 2)
68
  answer_simple = out_simple.strip().split('\n')[-1]
69
 
 
74
  "simple_time": end_simple
75
  }
76
 
77
+ return tuple(
78
+ [
79
+ results[m]["cot_answer"], f"{results[m]['cot_time']} сек",
80
+ results[m]["simple_answer"], f"{results[m]['simple_time']} сек"
81
+ ]
82
+ for m in models
83
+ )[0] + tuple(
84
+ [
85
+ results[m]["cot_answer"], f"{results[m]['cot_time']} сек",
86
+ results[m]["simple_answer"], f"{results[m]['simple_time']} сек"
87
+ ]
88
+ for m in list(models)[1:]
89
  )
90
 
91
+ # Интерфейс Gradio
92
  with gr.Blocks() as demo:
93
+ gr.Markdown("## 🏦 Сравнение моделей (Классификация клиентских обращений): ChatGPT-like, DeepSeek-like, GigaChat-like")
94
 
95
+ inp = gr.Textbox(label="Вопрос клиента", placeholder="Например: Я не могу попасть в личный кабинет", lines=2)
96
  btn = gr.Button("Сгенерировать")
97
 
98
+ gr.Markdown("### ChatGPT-like (saiga_mistral)")
99
  cot1 = gr.Textbox(label="CoT ответ")
100
  cot1_time = gr.Textbox(label="Время CoT")
101
  simple1 = gr.Textbox(label="Обычный ответ")
102
  simple1_time = gr.Textbox(label="Время обычного")
103
 
104
+ gr.Markdown("### DeepSeek-like (ruGPT3-medium)")
105
  cot2 = gr.Textbox(label="CoT ответ")
106
  cot2_time = gr.Textbox(label="Время CoT")
107
  simple2 = gr.Textbox(label="Обычный ответ")
108
  simple2_time = gr.Textbox(label="Время обычного")
109
 
110
+ gr.Markdown("### GigaChat-like (rubert-tiny2)")
111
  cot3 = gr.Textbox(label="CoT ответ")
112
  cot3_time = gr.Textbox(label="Время CoT")
113
  simple3 = gr.Textbox(label="Обычный ответ")
 
119
  cot3, cot3_time, simple3, simple3_time
120
  ])
121
 
122
+ if __name__ == "__main__":
 
123
  demo.launch()