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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -60
app.py CHANGED
@@ -2,104 +2,105 @@ import gradio as gr
2
  import time
3
  from transformers import pipeline
4
 
5
- # Проверенные лёгкие русскоязычные модели, работающие в Hugging Face Spaces
6
  models = {
7
- "ChatGPT-like (ruGPT3small)": pipeline("text-generation", model="ai-forever/rugpt3small_based_on_gpt2", tokenizer="ai-forever/rugpt3small_based_on_gpt2", device=-1),
8
- "DeepSeek-like (ruGPT3large)": pipeline("text-generation", model="ai-forever/rugpt3large_based_on_gpt2", tokenizer="ai-forever/rugpt3large_based_on_gpt2", device=-1),
9
- "GigaChat-like (rubert-tiny2)": pipeline("text-generation", model="cointegrated/rubert-tiny2", tokenizer="cointegrated/rubert-tiny2", device=-1),
10
  }
11
 
12
  # Промпты
13
- cot_instruction = """Ты — банковский помощник. Клиент описал проблему.
14
- Проанализируй обращение шаг за шагом:
15
- 1. Что случилось?
16
- 2. Почему это могло произойти?
17
- 3. Как клиенту поступить?
18
- Вывод: укажи категорию обращения (например: доступ, безопасность, платежи, перевод и т.д.)"""
19
-
20
- simple_instruction = "Ты — банковский помощник. Определи кратко, к какой категории относится обращение клиента (например: доступ, платежи, безопасность и т.д.)."
21
-
22
- # Формирование промптов
23
-
24
- def build_prompt(instruction, user_input):
25
- return f"{instruction}\n\nКлиент: {user_input}"
26
-
27
- # Генерация вывода с защитой
28
-
29
- def get_output(pipe, prompt, max_tokens=200):
30
- try:
31
- output = pipe(prompt, max_new_tokens=max_tokens, truncation=True, do_sample=True, temperature=0.7)[0]
32
- return output.get("generated_text") or output.get("output_text") or "(нет ответа)"
33
- except Exception as e:
34
- return f"Ошибка: {e}"
35
-
36
- # Основная функция сравнения
37
-
38
- def generate_comparison(user_input):
39
- result = {}
40
- prompt_cot = build_prompt(cot_instruction, user_input)
41
- prompt_simple = build_prompt(simple_instruction, user_input)
42
 
43
  for name, pipe in models.items():
44
- # CoT ответ
45
  start_cot = time.time()
46
- answer_cot = get_output(pipe, prompt_cot)
47
- time_cot = round(time.time() - start_cot, 2)
 
48
 
49
- # Обычный ответ
50
  start_simple = time.time()
51
- answer_simple = get_output(pipe, prompt_simple)
52
- time_simple = round(time.time() - start_simple, 2)
53
-
54
- result[name] = {
55
- "cot_answer": answer_cot.strip(),
56
- "cot_time": f"{time_cot} сек",
57
- "simple_answer": answer_simple.strip(),
58
- "simple_time": f"{time_simple} сек"
 
59
  }
60
 
61
  return (
62
- result["ChatGPT-like (ruGPT3small)"]["cot_answer"], result["ChatGPT-like (ruGPT3small)"]["cot_time"],
63
- result["ChatGPT-like (ruGPT3small)"]["simple_answer"], result["ChatGPT-like (ruGPT3small)"]["simple_time"],
64
- result["DeepSeek-like (ruGPT3large)"]["cot_answer"], result["DeepSeek-like (ruGPT3large)"]["cot_time"],
65
- result["DeepSeek-like (ruGPT3large)"]["simple_answer"], result["DeepSeek-like (ruGPT3large)"]["simple_time"],
66
- result["GigaChat-like (rubert-tiny2)"]["cot_answer"], result["GigaChat-like (rubert-tiny2)"]["cot_time"],
67
- result["GigaChat-like (rubert-tiny2)"]["simple_answer"], result["GigaChat-like (rubert-tiny2)"]["simple_time"]
 
 
68
  )
69
 
70
  # Интерфейс
71
  with gr.Blocks() as demo:
72
- gr.Markdown("## Сравнение моделей: ruGPT3small, ruGPT3large, rubert-tiny2 (Классификация обращений)")
73
 
74
- inp = gr.Textbox(label="Вопрос клиента", placeholder="Например: Я не могу войти в личный кабинет", lines=2)
75
  btn = gr.Button("Сгенерировать")
76
 
77
- # ChatGPT-like
78
- gr.Markdown("### ChatGPT-like (ruGPT3small)")
79
  cot1 = gr.Textbox(label="CoT ответ")
80
  cot1_time = gr.Textbox(label="Время CoT")
81
  simple1 = gr.Textbox(label="Обычный ответ")
82
  simple1_time = gr.Textbox(label="Время обычного")
83
 
84
- # DeepSeek-like
85
- gr.Markdown("### DeepSeek-like (ruGPT3large)")
86
  cot2 = gr.Textbox(label="CoT ответ")
87
  cot2_time = gr.Textbox(label="Время CoT")
88
  simple2 = gr.Textbox(label="Обычный ответ")
89
  simple2_time = gr.Textbox(label="Время обычного")
90
 
91
- # GigaChat-like
92
- gr.Markdown("### GigaChat-like (rubert-tiny2)")
93
  cot3 = gr.Textbox(label="CoT ответ")
94
  cot3_time = gr.Textbox(label="Время CoT")
95
  simple3 = gr.Textbox(label="Обычный ответ")
96
  simple3_time = gr.Textbox(label="Время обычного")
97
 
98
- btn.click(generate_comparison, inputs=[inp], outputs=[
99
  cot1, cot1_time, simple1, simple1_time,
100
  cot2, cot2_time, simple2, simple2_time,
101
  cot3, cot3_time, simple3, simple3_time
102
  ])
103
 
 
104
  if __name__ == '__main__':
105
  demo.launch()
 
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)
40
+ prompt_simple = build_simple_prompt(user_input)
 
41
 
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
+
55
+ results[name] = {
56
+ "cot_answer": answer_cot,
57
+ "cot_time": end_cot,
58
+ "simple_answer": answer_simple,
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="Обычный ответ")
96
  simple3_time = gr.Textbox(label="Время обычного")
97
 
98
+ btn.click(generate_dual_answers, inputs=[inp], outputs=[
99
  cot1, cot1_time, simple1, simple1_time,
100
  cot2, cot2_time, simple2, simple2_time,
101
  cot3, cot3_time, simple3, simple3_time
102
  ])
103
 
104
+
105
  if __name__ == '__main__':
106
  demo.launch()