Spaces:
No application file
No application file
Download model.py from ludicolo/modelo-git: direct link, hf CLI and curl.
- Browser
- Download file 2.47 kB
-
https://huggingface.co/spaces/ludicolo/modelo-git/resolve/main/model.py
- Command line
-
hf download hf://spaces/ludicolo/modelo-git/model.py
-
curl -L -o model.py https://huggingface.co/spaces/ludicolo/modelo-git/resolve/main/model.py
2.47 kB
| # model.py | |
| import json | |
| import torch | |
| import sys | |
| from transformers import T5ForConditionalGeneration, T5Tokenizer | |
| # --- CONFIGURACI脫N (Sin cambios) --- | |
| CARPETA_MODELO_FINAL = "./modelo-v1/mi-modelo-entrenado" | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| # --- CARGA DEL MODELO (Sin cambios) --- | |
| print(f"Cargando modelo en: {DEVICE}") | |
| try: | |
| tokenizer = T5Tokenizer.from_pretrained(CARPETA_MODELO_FINAL) | |
| model = T5ForConditionalGeneration.from_pretrained(CARPETA_MODELO_FINAL).to(DEVICE) | |
| model.eval() | |
| except Exception as e: | |
| print(f"ERROR: No se pudo cargar el modelo o el tokenizador. Raz贸n: {e}") | |
| sys.exit(1) | |
| # --- FUNCI脫N DE GENERACI脫N (Contiene toda tu l贸gica original) --- | |
| def generar_respuesta_ia(prompt: str): | |
| """ | |
| Ejecuta la l贸gica completa: recibe un prompt, usa el modelo y devuelve el diccionario parseado. | |
| """ | |
| # L贸gica original sin modificar | |
| print("ESTE ES EL PROMPT " + prompt) | |
| with torch.no_grad(): | |
| # NOTA: Se mantiene la l贸gica original del prompt. | |
| input_text = f"translate English to French: {prompt}" | |
| inputs = tokenizer(input_text, return_tensors="pt", max_length=512, truncation=True) | |
| input_ids = inputs["input_ids"].to(DEVICE) | |
| # NOTA: Se mantiene el par谩metro 'temperature' de tu c贸digo original. | |
| outputs = model.generate( | |
| input_ids, | |
| max_length=512, | |
| num_beams=4, | |
| early_stopping=True, | |
| temperature=0.7 | |
| ) | |
| generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| print("si llego aca") | |
| try: | |
| # L贸gica de parseo original sin modificar | |
| processed_text = generated_text.strip() | |
| if not processed_text.startswith('{'): | |
| processed_text = '{' + processed_text | |
| if not processed_text.endswith('}'): | |
| processed_text = processed_text + '}' | |
| data = json.loads(processed_text) | |
| print(data) | |
| return data | |
| except json.JSONDecodeError as e: | |
| # Lanza una excepci贸n para que el endpoint la capture | |
| raise ValueError(f"El modelo AI gener贸 un JSON inv谩lido. Salida cruda: {generated_text}") | |
| except Exception as e: | |
| # Lanza una excepci贸n para cualquier otro error | |
| raise ValueError(f"Error al procesar la respuesta de la IA. Salida cruda: {generated_text}. Detalle del error: {str(e)}") | |