Spaces:
Paused
Paused
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535 unmodified lines5960616263646566676869707172737475# 1. 'import spaces' SIEMPRE debe ser la primera importaciónimport spacesimport gradio as grimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamerfrom threading import Threadmodel_id = "Qwen/Qwen2.5-Coder-7B-Instruct"# 2. Carga del tokenizador a nivel global (en el proceso principal)tokenizer = AutoTokenizer.from_pretrained(model_id)# 3. Carga del modelo SIN device_map. Usamos .to("cuda") explícitamente# para que ZeroGPU intercepte y posponga la asignación real a la GPU.model = AutoModelForCausalLM.from_pretrained(model_id,torch_dtype=torch.bfloat16).to("cuda")SYSTEM_PROMPT = """Eres un Ingeniero de IA Senior y experto programador.Tu especialidad es escribir código en Python para Inteligencia Artificial, Machine Learning y Deep Learning.Tienes un conocimiento profundo de:- PyTorch, TensorFlow y JAX.- Librerías de Hugging Face (Transformers, Diffusers, Datasets, PEFT).- Frameworks de agentes (LangChain, LlamaIndex, AutoGen).- Fine-tuning (LoRA, QLoRA) y RAG (Retrieval-Augmented Generation).- Despliegue de modelos y APIs (FastAPI, vLLM).Instrucciones:1. Proporciona siempre código limpio, comentado y listo para producción.2. Si hay un error en el código del usuario, explica por qué ocurre y da la solución.3. Sugiere las mejores prácticas y optimizaciones de memoria/velocidad.4. Responde en el idioma del usuario (normalmente español)."""@spaces.GPUdef predict(message, history):messages = [{"role": "system", "content": SYSTEM_PROMPT}]for user_msg, assistant_msg in history:messages.append({"role": "user", "content": user_msg})messages.append({"role": "assistant", "content": assistant_msg})messages.append({"role": "user", "content": message})text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)model_inputs = tokenizer([text], return_tensors="pt").to("cuda") # forzamos 'cuda' stringstreamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)generate_kwargs = dict(model_inputs, streamer=streamer, max_new_tokens=2048,temperature=0.2, top_p=0.9, do_sample=True,)t = Thread(target=model.generate, kwargs=generate_kwargs)5 unmodified linespartial_message += new_tokenyield partial_messagewith gr.Blocks(theme=gr.themes.Monochrome()) as demo:gr.ChatInterface(fn=predict,title="🤖 Mi Asistente Experto en IA",description="Pregúntame sobre PyTorch, Transformers, Diffusers, Fine-tuning, RAG o cualquier cosa de código para IA.",examples=[["¿Cómo puedo cargar un modelo en 4-bit usando BitsAndBytes?"],["Escríbeme un script en Python para hacer fine-tuning con LoRA de un modelo Llama."],["Tengo este error en mi código de PyTorch: 'RuntimeError: Expected all tensors to be on the same device'. ¿Cómo lo arreglo?"],["Crea un pipeline básico de RAG usando LangChain y ChromaDB."]])demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515 unmodified lines57585960616263646566676869707172737475767778798081828384858687888990919293import spacesimport gradio as grimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, pipelinefrom threading import Threadfrom gtts import gTTSimport tempfile# 1. Modelo de texto (el mismo de antes)model_id = "Qwen/Qwen2.5-Coder-7B-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_id)model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16).to("cuda")# 2. Modelo para entender tu voz (Whisper en CPU para no llenar la GPU)stt = pipeline("automatic-speech-recognition", model="openai/whisper-base", device="cpu")# 3. El nuevo prompt: amigable, sencillo y sin tecnicismosSYSTEM_PROMPT = """Eres un asistente amigable y paciente.Te gusta programar y ayudar a la gente, pero hablas de forma sencilla y sin tecnicismos.Explicas las cosas paso a paso y con ejemplos fáciles. Responde siempre en español."""@spaces.GPUdef predict(message, history):user_text = ""# Si el mensaje viene con un audio (usando el micrófono), lo transcribimos a textoif isinstance(message, dict):user_text = message.get("text", "")if message.get("files"):audio_path = message["files"][0]user_text += " " + stt(audio_path)["text"]else:user_text = message# Preparamos la conversaciónmessages = [{"role": "system", "content": SYSTEM_PROMPT}]for user_msg, assistant_msg in history:messages.append({"role": "user", "content": user_msg})messages.append({"role": "assistant", "content": assistant_msg})messages.append({"role": "user", "content": user_text})text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)model_inputs = tokenizer([text], return_tensors="pt").to("cuda")streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)generate_kwargs = dict(model_inputs, streamer=streamer, max_new_tokens=1024,temperature=0.7, top_p=0.9, do_sample=True,)t = Thread(target=model.generate, kwargs=generate_kwargs)5 unmodified linespartial_message += new_tokenyield partial_message# 4. Función para generar la voz del asistentedef text_to_speech(text):tts = gTTS(text=text, lang='es')temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")tts.save(temp_file.name)return temp_file.name# 5. Interfaz con micrófono y altavozwith gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 🗣️ Asistente conversacional")gr.Markdown("Puedes escribir o usar el micrófono. ¡Hablemos de código!")chatbot = gr.Chatbot(type="messages")with gr.Row():# El MultimodalTextbox añade el botón del micrófono automáticamentemsg = gr.MultimodalTextbox(show_label=False, placeholder="Escribe o graba tu mensaje...", sources=["microphone", "upload"])# Reproductor de audio para las respuestasaudio_output = gr.Audio(label="Escuchar última respuesta", autoplay=True)def respond(user_message, history):response = ""for chunk in predict(user_message, history):response = chunk# Mostramos el texto mientras se escribeyield "", history + [{"role": "user", "content": str(user_message)}, {"role": "assistant", "content": response}], None# Al terminar, generamos el audio de la respuestaaudio_path = text_to_speech(response)yield "", history + [{"role": "user", "content": str(user_message)}, {"role": "assistant", "content": response}], audio_pathmsg.submit(respond, [msg, chatbot], [msg, chatbot, audio_output])demo.launch()
app.py+60-42