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