Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
| 3 |
from datasets import load_dataset
|
|
|
|
| 4 |
|
| 5 |
-
# 1. Загрузка датасета
|
| 6 |
try:
|
| 7 |
dataset = load_dataset("blinoff/ru_customer_support", split="train[:50]")
|
| 8 |
examples = [d["question"] for d in dataset]
|
|
@@ -15,40 +16,55 @@ except Exception as e:
|
|
| 15 |
"Ошибка при оплате картой"
|
| 16 |
]
|
| 17 |
|
| 18 |
-
# 2. Загрузка модели
|
| 19 |
try:
|
| 20 |
-
model_name = "ai-forever/rugpt3small_based_on_gpt2"
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
|
|
|
| 25 |
generator = pipeline(
|
| 26 |
"text-generation",
|
| 27 |
model=model,
|
| 28 |
tokenizer=tokenizer,
|
| 29 |
-
device="cpu"
|
| 30 |
)
|
|
|
|
| 31 |
except Exception as e:
|
| 32 |
raise RuntimeError(f"Ошибка загрузки модели: {str(e)}")
|
| 33 |
|
| 34 |
# 3. Функция генерации ответа
|
| 35 |
-
def generate_response(message):
|
| 36 |
prompt = f"""Ты оператор поддержки. Ответь клиенту вежливо на русском.
|
| 37 |
|
|
|
|
|
|
|
| 38 |
Клиент: {message}
|
| 39 |
Оператор:"""
|
| 40 |
|
| 41 |
try:
|
| 42 |
response = generator(
|
| 43 |
prompt,
|
| 44 |
-
max_new_tokens=
|
| 45 |
-
temperature=0.
|
| 46 |
do_sample=True,
|
| 47 |
-
top_p=0.9
|
|
|
|
| 48 |
)
|
| 49 |
return response[0]["generated_text"].split("Оператор:")[-1].strip()
|
| 50 |
except Exception as e:
|
| 51 |
-
return f"
|
| 52 |
|
| 53 |
# 4. Интерфейс Gradio
|
| 54 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
@@ -56,14 +72,15 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 56 |
|
| 57 |
with gr.Row():
|
| 58 |
with gr.Column():
|
| 59 |
-
chatbot = gr.Chatbot(height=350)
|
| 60 |
-
msg = gr.Textbox(label="Опишите проблему")
|
| 61 |
btn = gr.Button("Отправить", variant="primary")
|
| 62 |
|
| 63 |
with gr.Column():
|
| 64 |
gr.Examples(examples, inputs=msg, label="Примеры обращений")
|
| 65 |
-
gr.Markdown("
|
| 66 |
|
| 67 |
-
btn.click(
|
|
|
|
| 68 |
|
| 69 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
| 3 |
from datasets import load_dataset
|
| 4 |
+
import torch
|
| 5 |
|
| 6 |
+
# 1. Загрузка датасета
|
| 7 |
try:
|
| 8 |
dataset = load_dataset("blinoff/ru_customer_support", split="train[:50]")
|
| 9 |
examples = [d["question"] for d in dataset]
|
|
|
|
| 16 |
"Ошибка при оплате картой"
|
| 17 |
]
|
| 18 |
|
| 19 |
+
# 2. Загрузка модели с обработкой ошибок
|
| 20 |
try:
|
| 21 |
+
model_name = "ai-forever/rugpt3small_based_on_gpt2"
|
| 22 |
|
| 23 |
+
# Явно указываем доверенный источник
|
| 24 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 25 |
+
model_name,
|
| 26 |
+
trust_remote_code=True
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 30 |
+
model_name,
|
| 31 |
+
trust_remote_code=True,
|
| 32 |
+
torch_dtype=torch.float16,
|
| 33 |
+
device_map="auto"
|
| 34 |
+
)
|
| 35 |
|
| 36 |
+
# Создаем pipeline с правильными параметрами
|
| 37 |
generator = pipeline(
|
| 38 |
"text-generation",
|
| 39 |
model=model,
|
| 40 |
tokenizer=tokenizer,
|
| 41 |
+
device="cuda" if torch.cuda.is_available() else "cpu"
|
| 42 |
)
|
| 43 |
+
|
| 44 |
except Exception as e:
|
| 45 |
raise RuntimeError(f"Ошибка загрузки модели: {str(e)}")
|
| 46 |
|
| 47 |
# 3. Функция генерации ответа
|
| 48 |
+
def generate_response(message, history):
|
| 49 |
prompt = f"""Ты оператор поддержки. Ответь клиенту вежливо на русском.
|
| 50 |
|
| 51 |
+
История диалога:
|
| 52 |
+
{history}
|
| 53 |
Клиент: {message}
|
| 54 |
Оператор:"""
|
| 55 |
|
| 56 |
try:
|
| 57 |
response = generator(
|
| 58 |
prompt,
|
| 59 |
+
max_new_tokens=200,
|
| 60 |
+
temperature=0.7,
|
| 61 |
do_sample=True,
|
| 62 |
+
top_p=0.9,
|
| 63 |
+
repetition_penalty=1.1
|
| 64 |
)
|
| 65 |
return response[0]["generated_text"].split("Оператор:")[-1].strip()
|
| 66 |
except Exception as e:
|
| 67 |
+
return f"Ошибка генерации ответа: {str(e)}"
|
| 68 |
|
| 69 |
# 4. Интерфейс Gradio
|
| 70 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
|
|
| 72 |
|
| 73 |
with gr.Row():
|
| 74 |
with gr.Column():
|
| 75 |
+
chatbot = gr.Chatbot(height=350, label="Диалог")
|
| 76 |
+
msg = gr.Textbox(label="Опишите проблему", placeholder="Введите ваше сообщение...")
|
| 77 |
btn = gr.Button("Отправить", variant="primary")
|
| 78 |
|
| 79 |
with gr.Column():
|
| 80 |
gr.Examples(examples, inputs=msg, label="Примеры обращений")
|
| 81 |
+
gr.Markdown("**Рекомендации:**\n1. Укажите номер заказа\n2. Опишите проблему подробно")
|
| 82 |
|
| 83 |
+
btn.click(generate_response, [msg, chatbot], [chatbot])
|
| 84 |
+
msg.submit(generate_response, [msg, chatbot], [chatbot])
|
| 85 |
|
| 86 |
demo.launch()
|