Spaces:
Running
Running
File size: 5,246 Bytes
57645e8 66fabfa f4f65e1 4fb6307 1267d48 f5f461a 4fb6307 e66857b f5f461a 4fb6307 f5f461a 4fb6307 39ebd04 f5f461a 39ebd04 66fabfa f5f461a 4fb6307 66fabfa f5f461a 4fb6307 f5f461a 66fabfa f5f461a 079a9a0 f5f461a 66fabfa f5f461a 66fabfa f5f461a 079a9a0 f5f461a 079a9a0 f5f461a 66fabfa f5f461a 66fabfa 4fb6307 1267d48 f5f461a a4bd38b 079a9a0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
import gradio as gr
import time
from transformers import pipeline
from datasets import load_dataset
# Загружаем датасет
dataset = load_dataset("Romjiik/Russian_bank_reviews", split="train")
# Примеры для few-shot (без 'rating')
few_shot_examples = []
for row in dataset.select(range(2)):
review = row["review"]
ex = f"Клиент: {review}\nОтвет: Спасибо за обращение! Уточните, пожалуйста, детали ситуации, чтобы мы могли помочь."
few_shot_examples.append(ex)
# Системные инструкции
cot_instruction = (
"Ты — вежливый банковский помощник. Клиент описывает проблему. "
"Сначала проанализируй её шаг за шагом, потом сформулируй итоговый ответ."
)
simple_instruction = (
"Ты — вежливый банковский помощник. Отвечай кратко и официально, без лишних деталей. "
"Не используй рассуждение, просто дай понятный клиенту ответ."
)
# Модели
models = {
"ruDialoGPT-small": pipeline("text-generation", model="t-bank-ai/ruDialoGPT-small", tokenizer="t-bank-ai/ruDialoGPT-small", device=-1),
"ruDialoGPT-medium": pipeline("text-generation", model="t-bank-ai/ruDialoGPT-medium", tokenizer="t-bank-ai/ruDialoGPT-medium", device=-1),
"ruGPT3-small": pipeline("text-generation", model="ai-forever/rugpt3small_based_on_gpt2", tokenizer="ai-forever/rugpt3small_based_on_gpt2", device=-1),
}
# Промпт CoT
def build_cot_prompt(user_input):
examples = "\n\n".join(few_shot_examples)
return (
f"{cot_instruction}\n\n{examples}\n\nКлиент: {user_input}\n"
"Рассуждение и ответ:"
)
# Промпт простой
def build_simple_prompt(user_input):
examples = "\n\n".join(few_shot_examples)
return (
f"{simple_instruction}\n\n{examples}\n\nКлиент: {user_input}\n"
"Ответ:"
)
# Генерация ответов по двум промптам
def generate_dual_answers(user_input):
results = {}
prompt_cot = build_cot_prompt(user_input)
prompt_simple = build_simple_prompt(user_input)
for name, pipe in models.items():
# CoT
start_cot = time.time()
out_cot = pipe(prompt_cot, max_new_tokens=100, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
end_cot = round(time.time() - start_cot, 2)
answer_cot = out_cot.strip().split('\n')[-1]
# Simple
start_simple = time.time()
out_simple = pipe(prompt_simple, max_new_tokens=100, do_sample=True, top_p=0.9, temperature=0.7)[0]["generated_text"]
end_simple = round(time.time() - start_simple, 2)
answer_simple = out_simple.strip().split('\n')[-1]
results[name] = {
"cot_answer": answer_cot,
"cot_time": end_cot,
"simple_answer": answer_simple,
"simple_time": end_simple
}
return (
results["ruDialoGPT-small"]["cot_answer"], f"{results['ruDialoGPT-small']['cot_time']} сек",
results["ruDialoGPT-small"]["simple_answer"], f"{results['ruDialoGPT-small']['simple_time']} сек",
results["ruDialoGPT-medium"]["cot_answer"], f"{results['ruDialoGPT-medium']['cot_time']} сек",
results["ruDialoGPT-medium"]["simple_answer"], f"{results['ruDialoGPT-medium']['simple_time']} сек",
results["ruGPT3-small"]["cot_answer"], f"{results['ruGPT3-small']['cot_time']} сек",
results["ruGPT3-small"]["simple_answer"], f"{results['ruGPT3-small']['simple_time']} сек",
)
# Интерфейс Gradio
with gr.Blocks() as demo:
gr.Markdown("## 🏦 Банковский помощник (2 промпта: рассуждение + краткий ответ)")
inp = gr.Textbox(label="Вопрос клиента", placeholder="Например: Я не могу попасть в личный кабинет", lines=2)
btn = gr.Button("Сгенерировать")
gr.Markdown("### ruDialoGPT-small")
cot1 = gr.Textbox(label="CoT ответ")
cot1_time = gr.Textbox(label="Время CoT")
simple1 = gr.Textbox(label="Обычный ответ")
simple1_time = gr.Textbox(label="Время обычного")
gr.Markdown("### ruDialoGPT-medium")
cot2 = gr.Textbox(label="CoT ответ")
cot2_time = gr.Textbox(label="Время CoT")
simple2 = gr.Textbox(label="Обычный ответ")
simple2_time = gr.Textbox(label="Время обычного")
gr.Markdown("### ruGPT3-small")
cot3 = gr.Textbox(label="CoT ответ")
cot3_time = gr.Textbox(label="Время CoT")
simple3 = gr.Textbox(label="Обычный ответ")
simple3_time = gr.Textbox(label="Время обычного")
btn.click(generate_dual_answers, inputs=[inp], outputs=[
cot1, cot1_time, simple1, simple1_time,
cot2, cot2_time, simple2, simple2_time,
cot3, cot3_time, simple3, simple3_time
])
demo.launch() |