Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -4,127 +4,120 @@ from transformers import pipeline
|
|
4 |
from datasets import load_dataset
|
5 |
|
6 |
# Загружаем датасет
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
|
|
|
|
|
|
17 |
cot_instruction = (
|
18 |
-
"Ты — банковский помощник.
|
19 |
-
"Проанализируй обращение
|
20 |
-
"и отнеси его к одной из категорий: вход в ЛК, SMS, заявка, ошибка, перевод, карта, другое."
|
21 |
)
|
22 |
|
23 |
simple_instruction = (
|
24 |
-
"Ты — банковский помощник.
|
25 |
-
"укажи
|
26 |
)
|
27 |
|
28 |
-
#
|
29 |
models = {
|
30 |
-
"ChatGPT-like (
|
31 |
-
"DeepSeek-like (
|
32 |
-
"GigaChat-like (
|
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 |
|
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
|
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=
|
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=
|
79 |
end_simple = round(time.time() - start_simple, 2)
|
80 |
answer_simple = out_simple.strip().split("\n")[-1]
|
81 |
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
"simple_time": end_simple
|
87 |
-
}
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
)
|
97 |
|
98 |
-
#
|
|
|
99 |
with gr.Blocks() as demo:
|
100 |
-
gr.Markdown("##
|
101 |
-
|
102 |
-
inp = gr.Textbox(label="
|
103 |
-
btn = gr.Button("
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
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__':
|
130 |
-
demo.launch()
|
|
|
4 |
from datasets import load_dataset
|
5 |
|
6 |
# Загружаем датасет
|
7 |
+
DATASET_NAME = "Romjiik/Russian_bank_reviews"
|
8 |
+
dataset = load_dataset(DATASET_NAME, split="train")
|
9 |
+
|
10 |
+
# Краткий список примеров для подстановки в промпт (для классификации)
|
11 |
+
few_shot_examples = [
|
12 |
+
"Клиент: Не могу войти в приложение.\nКлассификация: Техническая проблема",
|
13 |
+
"Клиент: Почему с меня сняли деньги дважды?\nКлассификация: Ошибка транзакции",
|
14 |
+
"Клиент: Хочу оформить кредит.\nКлассификация: Запрос на продукт",
|
15 |
+
"Клиент: У меня украли карту.\nКлассификация: Безопасность",
|
16 |
+
"Клиент: Не приходит СМС для входа.\nКлассификация: Проблема авторизации"
|
17 |
+
]
|
18 |
+
|
19 |
+
# Инструкции
|
20 |
cot_instruction = (
|
21 |
+
"Ты — банковский помощник. Клиент описывает ситуацию. "
|
22 |
+
"Проанализируй обращение шаг за шагом и определи категорию (например: 'Техническая проблема', 'Запрос на продукт', 'Безопасность' и т.п.)"
|
|
|
23 |
)
|
24 |
|
25 |
simple_instruction = (
|
26 |
+
"Ты — банковский помощник. Клиент описывает обращение. "
|
27 |
+
"Кратко укажи категорию обращения (например: 'Техническая проблема', 'Запрос на продукт', 'Безопасность' и т.п.)."
|
28 |
)
|
29 |
|
30 |
+
# Используемые модели (CPU-compatible, ≤16GB)
|
31 |
models = {
|
32 |
+
"ChatGPT-like (FRED-T5-small)": pipeline("text2text-generation", model="ai-forever/FRED-T5-Base", tokenizer="ai-forever/FRED-T5-Base", device=-1),
|
33 |
+
"DeepSeek-like (ruGPT3-small)": pipeline("text-generation", model="ai-forever/rugpt3small_based_on_gpt2", tokenizer="ai-forever/rugpt3small_based_on_gpt2", device=-1),
|
34 |
+
"GigaChat-like (RuBERT-tiny2-clf)": pipeline("text-classification", model="cointegrated/rubert-tiny2", tokenizer="cointegrated/rubert-tiny2", device=-1)
|
35 |
}
|
36 |
|
37 |
+
# Построение промптов
|
38 |
+
|
39 |
def build_cot_prompt(user_input):
|
40 |
examples = "\n\n".join(few_shot_examples)
|
41 |
return (
|
42 |
+
f"{cot_instruction}\n\n{examples}\n\nКлиент: {user_input}\nРассуждение и классификация:"
|
|
|
43 |
)
|
44 |
|
|
|
45 |
def build_simple_prompt(user_input):
|
46 |
examples = "\n\n".join(few_shot_examples)
|
47 |
return (
|
48 |
+
f"{simple_instruction}\n\n{examples}\n\nКлиент: {user_input}\nКлассификация:"
|
|
|
49 |
)
|
50 |
|
51 |
+
# Генерация классификаций
|
52 |
+
|
53 |
def generate_dual_answers(user_input):
|
54 |
results = {}
|
55 |
prompt_cot = build_cot_prompt(user_input)
|
56 |
prompt_simple = build_simple_prompt(user_input)
|
57 |
|
58 |
for name, pipe in models.items():
|
59 |
+
if "text-generation" in str(pipe.task):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
# CoT
|
61 |
start_cot = time.time()
|
62 |
+
out_cot = pipe(prompt_cot, max_length=256, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
|
63 |
end_cot = round(time.time() - start_cot, 2)
|
64 |
answer_cot = out_cot.strip().split("\n")[-1]
|
65 |
|
66 |
# Simple
|
67 |
start_simple = time.time()
|
68 |
+
out_simple = pipe(prompt_simple, max_length=128, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
|
69 |
end_simple = round(time.time() - start_simple, 2)
|
70 |
answer_simple = out_simple.strip().split("\n")[-1]
|
71 |
|
72 |
+
elif "text2text-generation" in str(pipe.task):
|
73 |
+
start_cot = time.time()
|
74 |
+
out_cot = pipe(prompt_cot, max_new_tokens=50)[0]["generated_text"]
|
75 |
+
end_cot = round(time.time() - start_cot, 2)
|
|
|
|
|
76 |
|
77 |
+
start_simple = time.time()
|
78 |
+
out_simple = pipe(prompt_simple, max_new_tokens=30)[0]["generated_text"]
|
79 |
+
end_simple = round(time.time() - start_simple, 2)
|
80 |
+
|
81 |
+
answer_cot = out_cot.strip()
|
82 |
+
answer_simple = out_simple.strip()
|
83 |
+
|
84 |
+
elif "text-classification" in str(pipe.task):
|
85 |
+
# Для классификации используем только сам ввод без промпта
|
86 |
+
start = time.time()
|
87 |
+
answer = pipe(user_input)[0]['label']
|
88 |
+
end = round(time.time() - start, 2)
|
89 |
+
answer_cot = answer
|
90 |
+
answer_simple = answer
|
91 |
+
end_cot = end_simple = end
|
92 |
+
|
93 |
+
results[name] = {
|
94 |
+
"cot_answer": answer_cot,
|
95 |
+
"cot_time": end_cot,
|
96 |
+
"simple_answer": answer_simple,
|
97 |
+
"simple_time": end_simple
|
98 |
+
}
|
99 |
+
|
100 |
+
return tuple(
|
101 |
+
results[model][key] for model in models for key in ["cot_answer", "cot_time", "simple_answer", "simple_time"]
|
102 |
)
|
103 |
|
104 |
+
# Gradio UI
|
105 |
+
|
106 |
with gr.Blocks() as demo:
|
107 |
+
gr.Markdown("## 🧠 Классификация клиентских обращений в банке (CoT vs обычный промпт)")
|
108 |
+
|
109 |
+
inp = gr.Textbox(label="Вопрос клиента", placeholder="Например: У меня не проходит оплата картой", lines=2)
|
110 |
+
btn = gr.Button("Сгенерировать")
|
111 |
+
|
112 |
+
results_blocks = []
|
113 |
+
for name in models:
|
114 |
+
gr.Markdown(f"### {name}")
|
115 |
+
cot = gr.Textbox(label="CoT ответ")
|
116 |
+
cot_time = gr.Textbox(label="Время CoT")
|
117 |
+
simple = gr.Textbox(label="Обычный ответ")
|
118 |
+
simple_time = gr.Textbox(label="Время обычного")
|
119 |
+
results_blocks.extend([cot, cot_time, simple, simple_time])
|
120 |
+
|
121 |
+
btn.click(generate_dual_answers, inputs=[inp], outputs=results_blocks)
|
122 |
+
|
123 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|