Spaces:
Running
Running
Update app.py
Browse files
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 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
|
|
15 |
|
16 |
# Инструкции
|
17 |
cot_instruction = (
|
18 |
-
"Ты —
|
19 |
-
"
|
20 |
-
" Дай только итоговую классификацию."
|
21 |
)
|
22 |
|
23 |
simple_instruction = (
|
24 |
-
"Ты —
|
25 |
-
" Ответ должен быть кратким: только категория."
|
26 |
)
|
27 |
|
28 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
def build_cot_prompt(user_input):
|
30 |
examples = "\n\n".join(few_shot_examples)
|
31 |
-
return
|
|
|
|
|
32 |
|
33 |
-
# Промпт простой
|
34 |
def build_simple_prompt(user_input):
|
35 |
examples = "\n\n".join(few_shot_examples)
|
36 |
-
return
|
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 "
|
|
|
54 |
start = time.time()
|
55 |
-
|
56 |
end = round(time.time() - start, 2)
|
57 |
results[name] = {
|
58 |
-
"
|
59 |
-
"cot_time":
|
60 |
-
"
|
61 |
-
"simple_time":
|
62 |
}
|
63 |
else:
|
|
|
64 |
start_cot = time.time()
|
65 |
-
out_cot = pipe(prompt_cot,
|
66 |
end_cot = round(time.time() - start_cot, 2)
|
67 |
-
|
68 |
|
|
|
69 |
start_simple = time.time()
|
70 |
-
out_simple = pipe(prompt_simple,
|
71 |
end_simple = round(time.time() - start_simple, 2)
|
72 |
-
|
73 |
|
74 |
results[name] = {
|
75 |
-
"
|
76 |
-
"cot_time":
|
77 |
-
"
|
78 |
-
"simple_time":
|
79 |
}
|
80 |
|
81 |
return (
|
82 |
-
results["
|
83 |
-
results["
|
84 |
-
results["
|
|
|
|
|
|
|
85 |
)
|
86 |
|
87 |
-
#
|
88 |
with gr.Blocks() as demo:
|
89 |
-
gr.Markdown("## 🏦 Классификация клиентских обращений
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
gr.
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
gr.
|
102 |
-
|
103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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,
|