Spaces:
Running on Zero

File size: 16,423 Bytes
d661e9f
 
58c9f90
d661e9f
58c9f90
 
 
d661e9f
58c9f90
 
d661e9f
 
 
 
 
58c9f90
d661e9f
e69fff2
58c9f90
d661e9f
 
58c9f90
d661e9f
 
 
 
 
 
 
58c9f90
d661e9f
58c9f90
d661e9f
 
 
 
 
 
 
 
58c9f90
d661e9f
864df58
 
d661e9f
 
 
 
2ce1bea
d661e9f
 
 
 
 
 
 
 
58c9f90
d661e9f
 
 
 
 
 
 
 
58c9f90
d661e9f
58c9f90
d661e9f
 
58c9f90
d661e9f
58c9f90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
864df58
58c9f90
 
 
e69fff2
58c9f90
d661e9f
58c9f90
 
 
 
 
 
 
 
 
d661e9f
58c9f90
 
f24d58f
d661e9f
58c9f90
d661e9f
b007371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87746a8
d661e9f
 
 
 
 
b007371
d661e9f
b007371
d661e9f
 
b007371
 
 
 
 
 
 
d661e9f
b007371
 
d661e9f
 
 
 
 
 
 
 
 
58c9f90
d661e9f
58c9f90
d661e9f
 
 
 
 
 
 
 
 
 
 
 
58c9f90
d661e9f
 
 
b007371
d661e9f
 
 
 
 
 
58c9f90
b007371
 
d661e9f
 
 
58c9f90
d661e9f
58c9f90
d661e9f
b007371
d661e9f
 
58c9f90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d661e9f
 
 
 
 
b007371
d661e9f
 
 
 
 
 
58c9f90
b007371
 
d661e9f
 
 
 
58c9f90
d661e9f
58c9f90
d661e9f
 
b007371
d661e9f
 
58c9f90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d661e9f
58c9f90
 
 
 
d661e9f
58c9f90
d661e9f
 
58c9f90
 
d661e9f
58c9f90
d661e9f
 
58c9f90
d661e9f
58c9f90
 
 
 
 
 
 
 
d661e9f
 
 
8f49833
 
58c9f90
d661e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
58c9f90
 
 
 
d661e9f
 
 
 
 
58c9f90
d661e9f
 
 
 
 
 
58c9f90
d661e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58c9f90
 
d661e9f
 
 
 
 
 
 
 
 
 
 
 
8ebe488
f397b58
d661e9f
a33a20f
d661e9f
 
b007371
 
 
a33a20f
b007371
a33a20f
37ddb13
d661e9f
 
 
a33a20f
 
b007371
d661e9f
58c9f90
d661e9f
 
 
 
 
 
 
 
58c9f90
a33a20f
d661e9f
a33a20f
d661e9f
523edfe
d661e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e69fff2
d661e9f
58c9f90
d661e9f
e69fff2
91e38e3
 
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
"""
=============================================================================
Wiguel-AI - Hugging Face Space (ZeroGPU + Transformers Native)
=============================================================================
- Sin llama-cpp-python: Utiliza PyTorch + Hugging Face Transformers nativo
  con la librería ligera 'gguf' para carga directa en ZeroGPU (A100/H100).
- Modelo: Miguelms13/Wiguel-AI-GGUF (archivo: Wiguel-AI.gguf)
- Tokenizer: deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B
- Interfaz: Gradio compatible con Gradio 4.x / 5.x / 6.x
- Endpoint API: '/predict' para clientes web remotos
=============================================================================
"""

import os
import sys
import threading
import torch
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer

# ---------------------------------------------------------------------------
# 1. Integración con Hugging Face ZeroGPU
# ---------------------------------------------------------------------------
try:
    import spaces
    HAS_ZEROGPU = True
    print("🚀 Módulo 'spaces' (ZeroGPU) detectado y activado.")
except ImportError:
    HAS_ZEROGPU = False
    print("ℹ️ ZeroGPU no detectado. Operando en modo local/CPU/GPU.")

    # Mock de seguridad si se ejecuta fuera de Hugging Face ZeroGPU
    class spaces:
        @staticmethod
        def GPU(func=None, duration=60):
            if func is None:
                return lambda f: f
            return func

# ---------------------------------------------------------------------------
# 2. Configuración y Constantes
# ---------------------------------------------------------------------------
REPO_ID_GGUF = "Miguelms13/11toAI"
FILENAME_GGUF = "11toai.gguf"
TOKENIZER_ID = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"

DEFAULT_SYSTEM_PROMPT = (
    "Eres Wiguel-AI, un asistente de inteligencia artificial avanzado y conversacional "
    "en español, diseñado por Wiguel-AI.\n"
    "Responde siempre en español con rigor, claridad, empatía y usando formato Markdown limpio."
)

print(f"📌 Repositorio GGUF: {REPO_ID_GGUF}")
print(f"📌 Archivo GGUF: {FILENAME_GGUF}")
print(f"📌 Tokenizer: {TOKENIZER_ID}")

# ---------------------------------------------------------------------------
# 3. Carga del Tokenizer (DeepSeek R1 Distill 1.5B)
# ---------------------------------------------------------------------------
print("⏳ Cargando tokenizer de DeepSeek R1 Distill 1.5B...")
tokenizer = None
try:
    tokenizer = AutoTokenizer.from_pretrained(
        TOKENIZER_ID,
        trust_remote_code=True
    )
    print("✅ Tokenizer cargado exitosamente.")
except Exception as e:
    print(f"⚠️ Error cargando tokenizer {TOKENIZER_ID}: {e}", file=sys.stderr)

# ---------------------------------------------------------------------------
# 4. Carga del Modelo mediante Transformers (Lazy Loading para ZeroGPU)
# ---------------------------------------------------------------------------
_model = None
_model_lock = threading.Lock()

def get_model():
    """
    Carga el modelo en memoria dentro del contexto @spaces.GPU.
    Evita llama-cpp-python usando directamente Transformers + gguf nativo.
    """
    global _model
    if _model is not None:
        return _model

    with _model_lock:
        if _model is not None:
            return _model

        device = "cuda" if torch.cuda.is_available() else "cpu"
        dtype = torch.float16 if torch.cuda.is_available() else torch.float32
        print(f"⚙️ Cargando modelo en device='{device}', dtype={dtype}...")

        # Intento 1: Carga nativa de GGUF en Transformers usando 'gguf'
        try:
            print(f"📥 Cargando {REPO_ID_GGUF} con gguf_file='{FILENAME_GGUF}'...")
            _model = AutoModelForCausalLM.from_pretrained(
                REPO_ID_GGUF,
                gguf_file=FILENAME_GGUF,
                torch_dtype=dtype,
                device_map="auto",
                trust_remote_code=True
            )
            print("✅ Modelo 11toAI (GGUF) cargado exitosamente con Transformers.")
            return _model
        except Exception as e1:
            print(f"⚠️ No se pudo cargar directamente como gguf_file: {e1}")

        # Intento 2: Carga directa desde repositorio base de DeepSeek R1 Distill 1.5B (Garantía de alta disponibilidad)
        try:
            print(f"🔄 Cargando fallback seguro desde {TOKENIZER_ID}...")
            _model = AutoModelForCausalLM.from_pretrained(
                TOKENIZER_ID,
                torch_dtype=dtype,
                device_map="auto",
                trust_remote_code=True
            )
            print("✅ Modelo cargado exitosamente desde base DeepSeek R1.")
            return _model
        except Exception as e2:
            print(f"❌ Error crítico al cargar modelo: {e2}")
            raise e2

# ---------------------------------------------------------------------------
# 5. Formateo de Prompt con DeepSeek R1 Tokenizer
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# 5. Utilidad de Extracción de Texto y Formateo de Prompt
# ---------------------------------------------------------------------------
def extract_text(val) -> str:
    """Extrae texto plano de forma segura de strings, listas o diccionarios de Gradio."""
    if val is None:
        return ""
    if isinstance(val, str):
        return val.strip()
    if isinstance(val, (list, tuple)):
        extracted = []
        for item in val:
            if item is None:
                continue
            if isinstance(item, str):
                extracted.append(item.strip())
            elif isinstance(item, dict):
                extracted.append(str(item.get("text", item.get("content", ""))).strip())
            else:
                extracted.append(str(item).strip())
        return " ".join([x for x in extracted if x])
    if isinstance(val, dict):
        return str(val.get("text", val.get("content", ""))).strip()
    return str(val).strip()

def format_prompt(message, history=None, system_prompt: str = DEFAULT_SYSTEM_PROMPT) -> str:
    msg_str = extract_text(message)
    messages = []
    if system_prompt and system_prompt.strip():
        messages.append({"role": "system", "content": system_prompt.strip()})

    if history:
        for turn in history:
            if isinstance(turn, dict):
                r = turn.get("role", "user")
                c = extract_text(turn.get("content", ""))
                if c:
                    messages.append({"role": r, "content": c})
            elif isinstance(turn, (list, tuple)) and len(turn) >= 2:
                u = extract_text(turn[0])
                a = extract_text(turn[1])
                if u:
                    messages.append({"role": "user", "content": u})
                if a:
                    messages.append({"role": "assistant", "content": a})

    if msg_str:
        messages.append({"role": "user", "content": msg_str})

    if tokenizer and hasattr(tokenizer, "apply_chat_template"):
        try:
            return tokenizer.apply_chat_template(
                messages,
                tokenize=False,
                add_generation_prompt=True
            )
        except Exception as e:
            print(f"⚠️ Fallback al aplicar chat_template: {e}")

    # Fallback con sintaxis DeepSeek R1
    parts = []
    if system_prompt:
        parts.append(f"<|System|>{system_prompt}")
    for m in messages:
        if m["role"] == "user":
            parts.append(f"<|User|>{m['content']}")
        elif m["role"] == "assistant":
            parts.append(f"<|Assistant|>{m['content']}")
    parts.append("<|Assistant|>")
    return "\n".join(parts)

# ---------------------------------------------------------------------------
# 6. Funciones de Inferencia decoradas con @spaces.GPU
# ---------------------------------------------------------------------------
@spaces.GPU(duration=120)
def predict_raw(
    message,
    history=None,
    system_prompt: str = DEFAULT_SYSTEM_PROMPT,
    temperature: float = 0.6,
    max_tokens: int = 1024,
    top_p: float = 0.95
) -> str:
    """Inferencia directa síncrona optimizada para ZeroGPU."""
    message_text = extract_text(message)
    if not message_text:
        return "Por favor ingresa un mensaje válido."

    try:
        model = get_model()
    except Exception as e:
        return f"⚠️ Error iniciando modelo: {str(e)}"

    prompt_text = format_prompt(message_text, history, system_prompt)

    try:
        device = next(model.parameters()).device
        inputs = tokenizer(prompt_text, return_tensors="pt").to(device)

        with torch.no_grad():
            outputs = model.generate(
                **inputs,
                max_new_tokens=int(max_tokens),
                temperature=float(temperature) if temperature > 0 else None,
                top_p=float(top_p) if temperature > 0 else None,
                do_sample=True if temperature > 0 else False,
                pad_token_id=tokenizer.eos_token_id if tokenizer.eos_token_id else 0
            )

        new_tokens = outputs[0][inputs.input_ids.shape[1]:]
        return tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
    except Exception as e:
        return f"❌ Error de inferencia: {str(e)}"

@spaces.GPU(duration=120)
def predict_stream(
    message,
    history,
    system_prompt: str,
    temperature: float,
    max_tokens: int,
    top_p: float
):
    """Generación de texto en tiempo real con streaming."""
    message_text = extract_text(message)
    if not message_text:
        yield "Por favor ingresa un mensaje."
        return

    try:
        model = get_model()
    except Exception as e:
        yield f"⚠️ Error cargando modelo: {str(e)}"
        return

    prompt_text = format_prompt(message_text, history, system_prompt)

    try:
        device = next(model.parameters()).device
        inputs = tokenizer(prompt_text, return_tensors="pt").to(device)

        streamer = TextIteratorStreamer(
            tokenizer,
            skip_prompt=True,
            skip_special_tokens=True
        )

        generation_kwargs = dict(
            **inputs,
            streamer=streamer,
            max_new_tokens=int(max_tokens),
            temperature=float(temperature) if temperature > 0 else None,
            top_p=float(top_p) if temperature > 0 else None,
            do_sample=True if temperature > 0 else False,
            pad_token_id=tokenizer.eos_token_id if tokenizer.eos_token_id else 0
        )

        thread = threading.Thread(target=model.generate, kwargs=generation_kwargs)
        thread.start()

        accumulated_text = ""
        for delta in streamer:
            accumulated_text += delta
            yield accumulated_text

        thread.join()
    except Exception as e:
        yield f"❌ Error en streaming: {str(e)}"

# ---------------------------------------------------------------------------
# 7. Interfaz Gradio (Compatible con Gradio 4, 5 y 6)
# ---------------------------------------------------------------------------
with gr.Blocks(title="Wiguel-AI Space") as demo:
    gr.Markdown(
        """
        # ⚡ Wiguel-AI
        ### Inferencia nativa Transformers + ZeroGPU • Tokenizer DeepSeek R1 Distill 1.5B
        *Desarrollado por el ingeniero español Miguel Molina*
        """
    )

    with gr.Row():
        with gr.Column(scale=4):
            # Constructor compatible con Gradio (los mensajes se gestionan como dicts {'role', 'content'})
            chatbot = gr.Chatbot(value=[], height=520)

            with gr.Row():
                msg_input = gr.Textbox(
                    placeholder="Escribe tu consulta para Wiguel-AI...",
                    show_label=False,
                    scale=8,
                    container=False
                )
                submit_btn = gr.Button("Enviar 🚀", variant="primary", scale=2)

            with gr.Row():
                clear_btn = gr.ClearButton([msg_input, chatbot], value="Limpiar Chat")

            gr.Examples(
                examples=[
                    "Hola Wiguel-AI, ¿quién eres y en qué me puedes colaborar?",
                    "Explícame cómo funciona ZeroGPU en Hugging Face con Transformers.",
                    "Escribe una función en TypeScript para conectarse a este Space.",
                    "¿Cuáles son las recomendaciones clave para optimizar una base de datos?"
                ],
                inputs=msg_input
            )

        with gr.Column(scale=1):
            with gr.Accordion("⚙️ Parámetros", open=False):
                system_box = gr.Textbox(
                    label="System Prompt",
                    value=DEFAULT_SYSTEM_PROMPT,
                    lines=4
                )
                temp_slider = gr.Slider(
                    minimum=0.0,
                    maximum=1.2,
                    value=0.6,
                    step=0.05,
                    label="Temperature"
                )
                tokens_slider = gr.Slider(
                    minimum=128,
                    maximum=2048,
                    value=1024,
                    step=64,
                    label="Max Tokens"
                )
                top_p_slider = gr.Slider(
                    minimum=0.1,
                    maximum=1.0,
                    value=0.95,
                    step=0.05,
                    label="Top P"
                )

    # -----------------------------------------------------------------------
    # Endpoint API '/predict' para llamadas desde server.ts (@gradio/client)
    # Formato esperado: client.predict('/predict', [userQuery])
    # -----------------------------------------------------------------------
    def api_predict_endpoint(query: str) -> str:
        return predict_raw(message=query, history=None)

    api_in = gr.Textbox(visible=False, label="query")
    api_out = gr.Textbox(visible=False, label="response")
    api_trigger = gr.Button("API Trigger", visible=False)
    api_trigger.click(
        fn=api_predict_endpoint,
        inputs=[api_in],
        outputs=[api_out],
        api_name="predict"
    )

    # -----------------------------------------------------------------------
    # Flujo de Conversación Web (formato messages {'role': ..., 'content': ...})
    # -----------------------------------------------------------------------
    def user_step(user_message, history):
        msg_str = extract_text(user_message)
        if not msg_str:
            return "", history or []
        history = list(history or [])
        history.append({"role": "user", "content": msg_str})
        return "", history

    def bot_step(history, sys_prompt, temp, max_toks, top_p):
        if not history:
            return
        
        last_item = history[-1]
        user_msg = extract_text(last_item.get("content", "") if isinstance(last_item, dict) else last_item)
        past_turns = history[:-1]

        generator = predict_stream(
            message=user_msg,
            history=past_turns,
            system_prompt=sys_prompt,
            temperature=temp,
            max_tokens=max_toks,
            top_p=top_p
        )

        history.append({"role": "assistant", "content": ""})
        for partial_text in generator:
            history[-1]["content"] = partial_text
            yield history

    msg_input.submit(
        user_step,
        inputs=[msg_input, chatbot],
        outputs=[msg_input, chatbot],
        queue=False
    ).then(
        bot_step,
        inputs=[chatbot, system_box, temp_slider, tokens_slider, top_p_slider],
        outputs=chatbot
    )

    submit_btn.click(
        user_step,
        inputs=[msg_input, chatbot],
        outputs=[msg_input, chatbot],
        queue=False
    ).then(
        bot_step,
        inputs=[chatbot, system_box, temp_slider, tokens_slider, top_p_slider],
        outputs=chatbot
    )

# ---------------------------------------------------------------------------
# 8. Arranque del Servidor Gradio
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    # Arranque estándar y compatible con el entorno ZeroGPU de Hugging Face Spaces
    demo.launch()