Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
|
| 14 |
-
few_shot_examples.append(
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
"
|
| 79 |
-
|
| 80 |
-
"
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
return (
|
| 84 |
-
results["ChatGPT-like (
|
| 85 |
-
results["ChatGPT-like (
|
| 86 |
-
|
| 87 |
-
results["DeepSeek-like (
|
| 88 |
-
results["
|
| 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("##
|
| 97 |
-
|
|
|
|
| 98 |
btn = gr.Button("Классифицировать")
|
| 99 |
|
| 100 |
-
gr.Markdown("### ChatGPT-like (
|
| 101 |
-
cot1
|
| 102 |
-
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
gr.Markdown("### DeepSeek-like (
|
| 105 |
-
cot2
|
| 106 |
-
|
|
|
|
|
|
|
| 107 |
|
| 108 |
-
gr.Markdown("### GigaChat-like (
|
| 109 |
-
cot3
|
| 110 |
-
|
|
|
|
|
|
|
| 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__':
|