Spaces:
Running on Zero
Running on Zero
Download app.py from Miguelms13/11toAI: direct link, hf CLI and curl.
- Browser
- Download file 16.4 kB
-
https://huggingface.co/spaces/Miguelms13/11toAI/resolve/main/app.py
- Command line
-
hf download hf://spaces/Miguelms13/11toAI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Miguelms13/11toAI/resolve/main/app.py
16.4 kB
| """ | |
| ============================================================================= | |
| 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: | |
| 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 | |
| # --------------------------------------------------------------------------- | |
| 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)}" | |
| 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() | |