SimrusDenuvo commited on
Commit
66fabfa
·
verified ·
1 Parent(s): 1267d48

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -43
app.py CHANGED
@@ -1,53 +1,77 @@
1
  import gradio as gr
 
2
  from transformers import pipeline
 
3
 
4
- # Инициализация двух бесплатных русскоязычных моделей из Hugging Face
5
- # 1) ruDialoGPT-small — диалоговая модель на GPT-2 (MIT-лицензия) ([huggingface.co](https://huggingface.co/t-bank-ai/ruDialoGPT-small?utm_source=chatgpt.com))
6
- # 2) ruGPT3-small семейство русскоязычных GPT-3 моделей от SberDevices (open-source) ([huggingface.co](https://huggingface.co/ai-forever/rugpt3small_based_on_gpt2?utm_source=chatgpt.com))
7
-
8
- pipe_dialo = pipeline(
9
- task="text-generation",
10
- model="t-bank-ai/ruDialoGPT-small",
11
- tokenizer="t-bank-ai/ruDialoGPT-small",
12
- device=-1 # CPU
13
- )
14
-
15
- pipe_rugpt3 = pipeline(
16
- task="text-generation",
17
- model="ai-forever/rugpt3small_based_on_gpt2",
18
- tokenizer="ai-forever/rugpt3small_based_on_gpt2",
19
- device=-1 # CPU
20
- )
21
-
22
- # Функция обработки пользовательского запроса
23
- # Возвращает генерацию от обеих моделей
24
-
25
- def generate_responses(prompt: str):
26
- # Настройки генерации можно подкорректировать по потребностям
27
- kwargs = {
28
- "max_length": 200,
29
- "do_sample": True,
30
- "top_p": 0.9,
31
- "temperature": 0.7
32
- }
33
- out1 = pipe_dialo(prompt, **kwargs)[0]["generated_text"]
34
- out2 = pipe_rugpt3(prompt, **kwargs)[0]["generated_text"]
35
- return out1, out2
36
-
37
- # Gradio-интерфейс
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  with gr.Blocks() as demo:
40
- gr.Markdown("## Русскоязычный чат с бесплатными моделями")
41
- txt = gr.Textbox(label="Ваш вопрос", placeholder="Введите текст на русском языке...", lines=2)
42
- out1 = gr.Textbox(label="ruDialoGPT-small")
43
- out2 = gr.Textbox(label="ruGPT3-small")
44
- btn = gr.Button("Сгенерировать ответы")
45
- btn.click(fn=generate_responses, inputs=txt, outputs=[out1, out2])
46
-
47
- # Запуск (для локального запуска и в Hugging Face Spaces)
48
- if __name__ == "__main__":
 
49
  demo.launch()
50
 
51
 
52
 
53
 
 
 
1
  import gradio as gr
2
+ import time
3
  from transformers import pipeline
4
+ from datasets import load_dataset
5
 
6
+ # Загрузка бесплатных русскоязычных моделей
7
+ models = {
8
+ 'ruDialoGPT-small': pipeline('text-generation', model='t-bank-ai/ruDialoGPT-small', tokenizer='t-bank-ai/ruDialoGPT-small', device=-1),
9
+ 'ruDialoGPT-medium': pipeline('text-generation', model='t-bank-ai/ruDialoGPT-medium', tokenizer='t-bank-ai/ruDialoGPT-medium', device=-1),
10
+ 'ruGPT3-small': pipeline('text-generation', model='ai-forever/rugpt3small_based_on_gpt2', tokenizer='ai-forever/rugpt3small_based_on_gpt2', device=-1)
11
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ # Загрузка банковского датасета с диалогами
14
+ bank_data = load_dataset('ai-lab/MBD', split='train')
15
+ # Определяем колонку с диалогами
16
+ col = next((c for c in bank_data.column_names if 'dialog' in c), None)
17
+ if col is None:
18
+ raise ValueError('В датасете не найдена колонка с диалогами')
19
+ # Берём первые два примера для few-shot
20
+ examples = [item[col] for item in bank_data.select(range(2))]
21
+
22
+ # Функция построения запроса с CoT и few-shot примерами
23
+
24
+ def build_prompt(question):
25
+ few_shot = '\n\n'.join(f'Диалог:\n{ex}' for ex in examples)
26
+ prompt = (
27
+ f"{few_shot}\n\n"
28
+ f"Вопрос: {question}\n"
29
+ "Сначала подробно опишите рассуждения шаг за шагом, а затем дайте краткий связный ответ."
30
+ )
31
+ return prompt
32
+
33
+ # Генерация ответов и снятие тайминга
34
+
35
+ def generate(question):
36
+ prompt = build_prompt(question)
37
+ results = {}
38
+ for name, pipe in models.items():
39
+ start = time.time()
40
+ out = pipe(prompt, max_length=300, do_sample=True, top_p=0.9, temperature=0.7)[0]['generated_text']
41
+ elapsed = round(time.time() - start, 2)
42
+ # Извлечение финального ответа после рассуждений
43
+ if 'Ответ:' in out:
44
+ answer = out.split('Ответ:')[-1].strip()
45
+ else:
46
+ answer = out.strip().split('\n')[-1]
47
+ results[name] = {'answer': answer, 'time': elapsed}
48
+ return results
49
+
50
+ # Форматируем вывод для Gradio
51
+
52
+ def format_outputs(question):
53
+ res = generate(question)
54
+ return (
55
+ res['ruDialoGPT-small']['answer'], f"{res['ruDialoGPT-small']['time']}s",
56
+ res['ruDialoGPT-medium']['answer'], f"{res['ruDialoGPT-medium']['time']}s",
57
+ res['ruGPT3-small']['answer'], f"{res['ruGPT3-small']['time']}s"
58
+ )
59
+
60
+ # Интерфейс Gradio
61
  with gr.Blocks() as demo:
62
+ gr.Markdown('## CoT на трёх моделях и банковский датасет')
63
+ txt = gr.Textbox(label='Ваш вопрос', placeholder='Введите вопрос, связанный с банковскими услугами', lines=2)
64
+ btn = gr.Button('Сгенерировать')
65
+ out1 = gr.Textbox(label='ruDialoGPT-small Ответ')
66
+ t1 = gr.Textbox(label='ruDialoGPT-small Время')
67
+ out2 = gr.Textbox(label='ruDialoGPT-medium Ответ')
68
+ t2 = gr.Textbox(label='ruDialoGPT-medium Время')
69
+ out3 = gr.Textbox(label='ruGPT3-small Ответ')
70
+ t3 = gr.Textbox(label='ruGPT3-small Время')
71
+ btn.click(format_outputs, inputs=[txt], outputs=[out1, t1, out2, t2, out3, t3])
72
  demo.launch()
73
 
74
 
75
 
76
 
77
+