Spaces:
Runtime error

File size: 3,735 Bytes
554cc79
ec45541
554cc79
 
 
 
 
ec45541
 
 
 
1cdd03c
 
ec45541
 
 
 
 
 
 
554cc79
ec45541
 
 
 
 
 
 
554cc79
ec45541
554cc79
 
 
 
ec45541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
554cc79
 
 
 
 
 
 
 
 
 
 
 
 
ec45541
 
 
 
 
 
 
 
 
 
 
 
554cc79
 
ec45541
554cc79
 
 
ec45541
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import os
import re
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from transformers import pipeline

# =========================
# Config
# =========================
# Modelo por defecto (mejor calidad que t5-small)
MODEL_NAME = os.environ.get("MODEL_NAME", "google/flan-t5-small")

# Prompt base: instructivo general (T5 funciona mejor con instrucciones en inglés)
SYSTEM_PROMPT = (
    "You are a smart, helpful assistant. "
    "Default to Spanish unless the user asks for another language. "
    "Be concise, clear, and avoid repeating the user's input. "
    "If asked to translate, just return the translation without extra text. "
)

# =========================
# App
# =========================
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")

# Cargamos el pipeline una sola vez
generator = pipeline(
    task="text2text-generation",
    model=MODEL_NAME,
)

def build_prompt(user_text: str) -> str:
    """
    Construye un prompt robusto para casos generales.
    Detecta algunos patrones (traducción/resumen/listas) pero sirve para TODO.
    """
    txt = (user_text or "").strip()

    # Traducción ES->EN (ej: "traduce X al inglés")
    m = re.search(r"(?i)\btraduce\s+(.+?)\s+(?:al|a)\s+ingl[eé]s\b", txt)
    if m:
        phrase = m.group(1).strip()
        return f"{SYSTEM_PROMPT}\nTranslate this to English:\n\"\"\"{phrase}\"\"\""

    # Traducción EN->ES (ej: "translate X to Spanish")
    m = re.search(r"(?i)\btranslate\s+(.+?)\s+to\s+spanish\b", txt)
    if m:
        phrase = m.group(1).strip()
        return f"{SYSTEM_PROMPT}\nTranslate this to Spanish:\n\"\"\"{phrase}\"\"\""

    # Resumen rápido (si el usuario dice 'resume:' o 'resumen de')
    if re.search(r"(?i)\b(resume|resumen de)\b", txt):
        return f"{SYSTEM_PROMPT}\nSummarize in Spanish in 1-3 sentences:\n\"\"\"{txt}\"\"\""

    # Por defecto: responder en español con claridad
    return (
        f"{SYSTEM_PROMPT}\n"
        f"User question (answer in Spanish):\n"
        f"\"\"\"{txt}\"\"\"\n\n"
        f"Assistant:"
    )

def postprocess(prompt: str, output_text: str, user_text: str) -> str:
    """Limpia eco del prompt y salidas vacías."""
    if not output_text:
        return "No tengo una respuesta ahora mismo, ¿puedes reformular?"

    # Quita el prompt si el modelo lo repitió
    reply = output_text.replace(prompt, "").strip()

    # Si todavía quedó prácticamente igual a lo que escribió el usuario, forzamos algo diferente
    if reply.lower() == (user_text or "").strip().lower():
        reply = reply + "."

    # Sanitiza espacios repetidos
    reply = re.sub(r"\n{3,}", "\n\n", reply).strip()
    return reply or "Déjame pensar... ¿puedes decirlo de otra forma?"

@app.get("/", response_class=HTMLResponse)
async def root():
    return FileResponse("static/index.html")

@app.post("/api/chat")
async def chat(req: Request):
    data = await req.json()
    user_text = (data.get("message") or "").strip()
    if not user_text:
        return JSONResponse({"reply": "¿Qué te gustaría preguntar?"})

    prompt = build_prompt(user_text)

    # Generación con muestreo y penalización para reducir eco
    out = generator(
        prompt,
        max_new_tokens=128,
        do_sample=True,
        top_p=0.92,
        temperature=0.8,
        repetition_penalty=1.25,
    )[0]["generated_text"]

    reply = postprocess(prompt, out, user_text)
    return JSONResponse({"reply": reply})

# Ejecuta uvicorn cuando corre como script (Spaces escucha en 7860)
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)