| import gradio as gr |
| from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline |
|
|
| |
| MODEL_NAME = "PlanTL-GOB-ES/gpt2-base-bne" |
|
|
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) |
| model = AutoModelForCausalLM.from_pretrained(MODEL_NAME) |
| generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device=-1) |
|
|
| |
| def answer(history, message): |
| if not message.strip(): |
| return history, "" |
|
|
| |
| system_prompt = ( |
| "Eres un asistente virtual que siempre responde en español de forma lógica y natural. " |
| "No hagas listas ni repitas palabras innecesariamente.\n" |
| ) |
|
|
| context = system_prompt |
| for user, bot in history[-6:]: |
| context += f"Usuario: {user}\nIA: {bot}\n" |
| context += f"Usuario: {message}\nIA:" |
|
|
| output = generator( |
| context, |
| max_new_tokens=80, |
| do_sample=True, |
| top_k=20, |
| top_p=0.8, |
| temperature=0.7 |
| )[0]["generated_text"] |
|
|
| |
| if "IA:" in output: |
| response = output.split("IA:")[-1].strip() |
| else: |
| response = output |
|
|
| history.append((message, response)) |
| return history, "" |
|
|
| |
| with gr.Blocks() as demo: |
| gr.Markdown("# 🤖 Chatbot en Español - Coherente") |
| chat = gr.Chatbot() |
| msg = gr.Textbox(placeholder="Escribe tu mensaje…") |
| clear_btn = gr.Button("Limpiar") |
| state = gr.State([]) |
|
|
| msg.submit(answer, [state, msg], [chat, msg]) |
| clear_btn.click(lambda: [], None, chat) |
|
|
| demo.launch() |
|
|