Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,42 +1,51 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import time
|
| 3 |
-
from transformers import pipeline
|
| 4 |
from datasets import load_dataset
|
| 5 |
|
| 6 |
# Инициализация трёх бесплатных русскоязычных моделей
|
| 7 |
-
models = {
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
'
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
device=-1
|
| 25 |
-
)
|
| 26 |
-
}
|
| 27 |
|
| 28 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
bank_data_stream = load_dataset(
|
| 30 |
'ai-lab/MBD-mini',
|
| 31 |
split='train',
|
| 32 |
streaming=True
|
| 33 |
)
|
| 34 |
-
# Определяем колонку с диалогами
|
| 35 |
first_record = next(iter(bank_data_stream))
|
| 36 |
-
col = next((c for c in first_record.keys() if 'dialog' in c or '
|
| 37 |
if col is None:
|
| 38 |
raise ValueError('Не найдена колонка с диалогами в MBD-mini')
|
| 39 |
-
# Собираем два few-shot
|
| 40 |
examples = []
|
| 41 |
for rec in bank_data_stream:
|
| 42 |
examples.append(rec[col])
|
|
@@ -49,7 +58,7 @@ system_instruction = (
|
|
| 49 |
" рассказывать о причинах и способах решения их проблем с банковскими услугами."
|
| 50 |
)
|
| 51 |
|
| 52 |
-
#
|
| 53 |
|
| 54 |
def build_prompt(question: str) -> str:
|
| 55 |
few_shot_text = '\n\n'.join(f"Пример диалога:\n{ex}" for ex in examples)
|
|
@@ -68,7 +77,7 @@ def generate(question: str):
|
|
| 68 |
results = {}
|
| 69 |
for name, pipe in models.items():
|
| 70 |
start = time.time()
|
| 71 |
-
#
|
| 72 |
out = pipe(
|
| 73 |
prompt,
|
| 74 |
max_length=400,
|
|
@@ -77,7 +86,7 @@ def generate(question: str):
|
|
| 77 |
temperature=0.7
|
| 78 |
)[0]['generated_text']
|
| 79 |
elapsed = round(time.time() - start, 2)
|
| 80 |
-
#
|
| 81 |
if 'Ответ:' in out:
|
| 82 |
answer = out.split('Ответ:')[-1].strip()
|
| 83 |
else:
|
|
@@ -85,7 +94,7 @@ def generate(question: str):
|
|
| 85 |
results[name] = {'answer': answer, 'time': elapsed}
|
| 86 |
return results
|
| 87 |
|
| 88 |
-
#
|
| 89 |
|
| 90 |
def format_outputs(question: str):
|
| 91 |
res = generate(question)
|
|
@@ -98,20 +107,25 @@ def format_outputs(question: str):
|
|
| 98 |
# Интерфейс Gradio
|
| 99 |
with gr.Blocks() as demo:
|
| 100 |
gr.Markdown('## Клиентские обращения: CoT на трёх моделях с MBD-mini и тайминг')
|
| 101 |
-
txt = gr.Textbox(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
btn = gr.Button('Сгенерировать ответ')
|
| 103 |
-
# Вывод для трёх моделей
|
| 104 |
out1 = gr.Textbox(label='ruDialoGPT-small Ответ')
|
| 105 |
t1 = gr.Textbox(label='ruDialoGPT-small Время')
|
| 106 |
out2 = gr.Textbox(label='ruGPT3-small Ответ')
|
| 107 |
t2 = gr.Textbox(label='ruGPT3-small Время')
|
| 108 |
out3 = gr.Textbox(label='rut5-small-chitchat Ответ')
|
| 109 |
t3 = gr.Textbox(label='rut5-small-chitchat Время')
|
| 110 |
-
btn.click(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
demo.launch()
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import time
|
| 3 |
+
from transformers import pipeline, AutoTokenizer
|
| 4 |
from datasets import load_dataset
|
| 5 |
|
| 6 |
# Инициализация трёх бесплатных русскоязычных моделей
|
| 7 |
+
models = {}
|
| 8 |
+
|
| 9 |
+
# 1) ruDialoGPT-small
|
| 10 |
+
models['ruDialoGPT-small'] = pipeline(
|
| 11 |
+
'text-generation',
|
| 12 |
+
model='t-bank-ai/ruDialoGPT-small',
|
| 13 |
+
tokenizer='t-bank-ai/ruDialoGPT-small',
|
| 14 |
+
device=-1
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# 2) ruGPT3-small
|
| 18 |
+
models['ruGPT3-small'] = pipeline(
|
| 19 |
+
'text-generation',
|
| 20 |
+
model='ai-forever/rugpt3small_based_on_gpt2',
|
| 21 |
+
tokenizer='ai-forever/rugpt3small_based_on_gpt2',
|
| 22 |
+
device=-1
|
| 23 |
+
)
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
# 3) rut5-small-chitchat (T5 requires text2text и slow tokenizer)
|
| 26 |
+
t5_tokenizer = AutoTokenizer.from_pretrained(
|
| 27 |
+
'cointegrated/rut5-small-chitchat',
|
| 28 |
+
use_fast=False
|
| 29 |
+
)
|
| 30 |
+
models['rut5-small-chitchat'] = pipeline(
|
| 31 |
+
'text2text-generation',
|
| 32 |
+
model='cointegrated/rut5-small-chitchat',
|
| 33 |
+
tokenizer=t5_tokenizer,
|
| 34 |
+
device=-1
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
# Загрузка "мини" банковского датасета для few-shot (стриминг)
|
| 38 |
bank_data_stream = load_dataset(
|
| 39 |
'ai-lab/MBD-mini',
|
| 40 |
split='train',
|
| 41 |
streaming=True
|
| 42 |
)
|
| 43 |
+
# Определяем колонку с диалогами по ключам
|
| 44 |
first_record = next(iter(bank_data_stream))
|
| 45 |
+
col = next((c for c in first_record.keys() if 'dialog' in c.lower() or 'диалог' in c.lower()), None)
|
| 46 |
if col is None:
|
| 47 |
raise ValueError('Не найдена колонка с диалогами в MBD-mini')
|
| 48 |
+
# Собираем два few-shot примера
|
| 49 |
examples = []
|
| 50 |
for rec in bank_data_stream:
|
| 51 |
examples.append(rec[col])
|
|
|
|
| 58 |
" рассказывать о причинах и способах решения их проблем с банковскими услугами."
|
| 59 |
)
|
| 60 |
|
| 61 |
+
# Построение CoT-промпта с few-shot
|
| 62 |
|
| 63 |
def build_prompt(question: str) -> str:
|
| 64 |
few_shot_text = '\n\n'.join(f"Пример диалога:\n{ex}" for ex in examples)
|
|
|
|
| 77 |
results = {}
|
| 78 |
for name, pipe in models.items():
|
| 79 |
start = time.time()
|
| 80 |
+
# для T5 используем text2text, для других text-generation
|
| 81 |
out = pipe(
|
| 82 |
prompt,
|
| 83 |
max_length=400,
|
|
|
|
| 86 |
temperature=0.7
|
| 87 |
)[0]['generated_text']
|
| 88 |
elapsed = round(time.time() - start, 2)
|
| 89 |
+
# Извлечь финальный ответ
|
| 90 |
if 'Ответ:' in out:
|
| 91 |
answer = out.split('Ответ:')[-1].strip()
|
| 92 |
else:
|
|
|
|
| 94 |
results[name] = {'answer': answer, 'time': elapsed}
|
| 95 |
return results
|
| 96 |
|
| 97 |
+
# Подготовка вывода для Gradio
|
| 98 |
|
| 99 |
def format_outputs(question: str):
|
| 100 |
res = generate(question)
|
|
|
|
| 107 |
# Интерфейс Gradio
|
| 108 |
with gr.Blocks() as demo:
|
| 109 |
gr.Markdown('## Клиентские обращения: CoT на трёх моделях с MBD-mini и тайминг')
|
| 110 |
+
txt = gr.Textbox(
|
| 111 |
+
label='Опишите проблему клиента',
|
| 112 |
+
placeholder='Например: "Почему я не могу снять деньги с карты?"',
|
| 113 |
+
lines=2
|
| 114 |
+
)
|
| 115 |
btn = gr.Button('Сгенерировать ответ')
|
|
|
|
| 116 |
out1 = gr.Textbox(label='ruDialoGPT-small Ответ')
|
| 117 |
t1 = gr.Textbox(label='ruDialoGPT-small Время')
|
| 118 |
out2 = gr.Textbox(label='ruGPT3-small Ответ')
|
| 119 |
t2 = gr.Textbox(label='ruGPT3-small Время')
|
| 120 |
out3 = gr.Textbox(label='rut5-small-chitchat Ответ')
|
| 121 |
t3 = gr.Textbox(label='rut5-small-chitchat Время')
|
| 122 |
+
btn.click(
|
| 123 |
+
format_outputs,
|
| 124 |
+
inputs=[txt],
|
| 125 |
+
outputs=[out1, t1, out2, t2, out3, t3]
|
| 126 |
+
)
|
| 127 |
demo.launch()
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
|
|
|
|
|