File size: 3,132 Bytes
57645e8
b87b483
81433b0
a43e0d6
bd826f0
a43e0d6
81433b0
b87b483
81433b0
 
 
 
b87b483
 
 
81433b0
 
fdefd2f
a43e0d6
e0ba145
a43e0d6
b87b483
a43e0d6
 
 
 
 
 
 
 
 
 
 
 
b87b483
a43e0d6
b87b483
e0ba145
b87b483
 
a43e0d6
e0ba145
a43e0d6
e0ba145
 
884ac0c
81433b0
a43e0d6
b87b483
884ac0c
a43e0d6
 
fdefd2f
37f0934
fdefd2f
5dee7eb
b87b483
884ac0c
a43e0d6
 
b87b483
a43e0d6
 
fdefd2f
37f0934
5dee7eb
a43e0d6
5dee7eb
81433b0
884ac0c
37f0934
fdefd2f
 
884ac0c
a43e0d6
 
81433b0
fdefd2f
884ac0c
81433b0
a43e0d6
5dee7eb
a43e0d6
 
5dee7eb
884ac0c
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
import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
from datasets import load_dataset
import torch

# 1. Загрузка датасета
try:
    dataset = load_dataset("blinoff/ru_customer_support", split="train[:50]")
    examples = [d["question"] for d in dataset]
except Exception as e:
    print(f"Ошибка загрузки датасета: {e}")
    examples = [
        "Мой заказ #12345 не пришел",
        "Как оформить возврат товара?",
        "Не приходит SMS-код подтверждения",
        "Ошибка при оплате картой"
    ]

# 2. Загрузка модели с обработкой ошибок
try:
    model_name = "ai-forever/rugpt3small_based_on_gpt2"
    
    # Явно указываем доверенный источник
    tokenizer = AutoTokenizer.from_pretrained(
        model_name,
        trust_remote_code=True
    )
    
    model = AutoModelForCausalLM.from_pretrained(
        model_name,
        trust_remote_code=True,
        torch_dtype=torch.float16,
        device_map="auto"
    )
    
    # Создаем pipeline с правильными параметрами
    generator = pipeline(
        "text-generation",
        model=model,
        tokenizer=tokenizer,
        device="cuda" if torch.cuda.is_available() else "cpu"
    )
    
except Exception as e:
    raise RuntimeError(f"Ошибка загрузки модели: {str(e)}")

# 3. Функция генерации ответа
def generate_response(message, history):
    prompt = f"""Ты оператор поддержки. Ответь клиенту вежливо на русском.
    
История диалога:
{history}
Клиент: {message}
Оператор:"""
    
    try:
        response = generator(
            prompt,
            max_new_tokens=200,
            temperature=0.7,
            do_sample=True,
            top_p=0.9,
            repetition_penalty=1.1
        )
        return response[0]["generated_text"].split("Оператор:")[-1].strip()
    except Exception as e:
        return f"Ошибка генерации ответа: {str(e)}"

# 4. Интерфейс Gradio
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("""<h1><center>📞 Поддержка клиентов</center></h1>""")
    
    with gr.Row():
        with gr.Column():
            chatbot = gr.Chatbot(height=350, label="Диалог")
            msg = gr.Textbox(label="Опишите проблему", placeholder="Введите ваше сообщение...")
            btn = gr.Button("Отправить", variant="primary")
        
        with gr.Column():
            gr.Examples(examples, inputs=msg, label="Примеры обращений")
            gr.Markdown("**Рекомендации:**\n1. Укажите номер заказа\n2. Опишите проблему подробно")

    btn.click(generate_response, [msg, chatbot], [chatbot])
    msg.submit(generate_response, [msg, chatbot], [chatbot])

demo.launch()