Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,47 +1,103 @@
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import pickle
|
| 4 |
+
import numpy as np
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
|
| 7 |
+
# 1. Configuraci贸n segura
|
| 8 |
+
DEFAULT_INPUT_SIZE = 4 # Basado en tu error anterior
|
| 9 |
+
DEFAULT_HIDDEN_SIZE = 64 # Tama帽o com煤n para modelos peque帽os
|
| 10 |
+
|
| 11 |
+
# 2. Funci贸n segura para cargar modelos
|
| 12 |
+
def safe_load_model(path):
|
| 13 |
+
try:
|
| 14 |
+
# Intentar cargar con pickle
|
| 15 |
+
with open(path, 'rb') as f:
|
| 16 |
+
data = pickle.load(f)
|
| 17 |
+
|
| 18 |
+
# Verificar estructura
|
| 19 |
+
if not all(k in data for k in ['model', 'vocab', 'idx_to_word']):
|
| 20 |
+
raise ValueError("Estructura inv谩lida del archivo .pkl")
|
| 21 |
+
|
| 22 |
+
return data
|
| 23 |
+
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"Error cargando modelo: {e}")
|
| 26 |
+
# Crear datos dummy seguros
|
| 27 |
+
vocab = defaultdict(lambda: 0, {"<unk>": 0, "hola": 1, "mundo": 2, "adi贸s": 3})
|
| 28 |
+
return {
|
| 29 |
+
'model': torch.nn.LSTM(
|
| 30 |
+
input_size=DEFAULT_INPUT_SIZE,
|
| 31 |
+
hidden_size=DEFAULT_HIDDEN_SIZE,
|
| 32 |
+
num_layers=2
|
| 33 |
+
).float(),
|
| 34 |
+
'vocab': vocab,
|
| 35 |
+
'idx_to_word': {v: k for k, v in vocab.items()}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
# 3. Cargar modelo
|
| 39 |
+
model_data = safe_load_model('model.pkl')
|
| 40 |
+
model = model_data['model']
|
| 41 |
+
vocab = model_data['vocab']
|
| 42 |
+
idx_to_word = model_data['idx_to_word']
|
| 43 |
+
|
| 44 |
+
print(f"Modelo cargado. Input size: {model.input_size}, Hidden size: {model.hidden_size}")
|
| 45 |
+
|
| 46 |
+
# 4. Preprocesamiento seguro
|
| 47 |
+
def preprocess(text, seq_length=5):
|
| 48 |
+
words = text.lower().split()[-seq_length:]
|
| 49 |
+
embeddings = []
|
| 50 |
+
|
| 51 |
+
for word in words:
|
| 52 |
+
# Embedding b谩sico con exactamente input_size caracter铆sticas
|
| 53 |
+
embedding = [
|
| 54 |
+
len(word),
|
| 55 |
+
sum(ord(c) for c in word),
|
| 56 |
+
len(word) * sum(ord(c) for c in word),
|
| 57 |
+
1 if word.isalpha() else 0
|
| 58 |
+
][:model.input_size]
|
| 59 |
+
|
| 60 |
+
# Rellenar si es necesario
|
| 61 |
+
if len(embedding) < model.input_size:
|
| 62 |
+
embedding += [0] * (model.input_size - len(embedding))
|
| 63 |
+
|
| 64 |
+
embeddings.append(embedding)
|
| 65 |
+
|
| 66 |
+
# Rellenar secuencia
|
| 67 |
+
while len(embeddings) < seq_length:
|
| 68 |
+
embeddings.append([0] * model.input_size)
|
| 69 |
+
|
| 70 |
+
return torch.tensor([embeddings], dtype=torch.float32)
|
| 71 |
+
|
| 72 |
+
# 5. Funci贸n de predicci贸n robusta
|
| 73 |
+
def predict_next_word(text):
|
| 74 |
+
try:
|
| 75 |
+
inputs = preprocess(text)
|
| 76 |
+
print(f"Input shape: {inputs.shape}")
|
| 77 |
+
|
| 78 |
+
with torch.no_grad():
|
| 79 |
+
outputs, _ = model(inputs)
|
| 80 |
+
|
| 81 |
+
if outputs.shape[-1] != len(vocab):
|
| 82 |
+
proj = torch.nn.Linear(outputs.shape[-1], len(vocab)).float()
|
| 83 |
+
outputs = proj(outputs)
|
| 84 |
+
|
| 85 |
+
probs = torch.softmax(outputs[:, -1, :], dim=1)
|
| 86 |
+
pred_idx = probs.argmax().item()
|
| 87 |
+
|
| 88 |
+
return f"Predicci贸n: {idx_to_word.get(pred_idx, '<unk>')} ({probs[0][pred_idx].item():.2%})"
|
| 89 |
+
|
| 90 |
+
except Exception as e:
|
| 91 |
+
return f"Error en predicci贸n: {str(e)}"
|
| 92 |
+
|
| 93 |
+
# 6. Interfaz simplificada
|
| 94 |
+
interface = gr.Interface(
|
| 95 |
+
fn=predict_next_word,
|
| 96 |
+
inputs=gr.Textbox(label="Contexto", placeholder="Escribe 3-5 palabras..."),
|
| 97 |
+
outputs="text",
|
| 98 |
+
examples=[["El cielo es"], ["Mi nombre es"], ["Qu茅 hora es"]],
|
| 99 |
+
title="Predictor de Siguiente Palabra",
|
| 100 |
+
description="Escribe un contexto y predice la siguiente palabra"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
interface.launch(share=True)
|