pagaliv commited on
Commit
a0b6d07
verified
1 Parent(s): 7f3c7b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -47
app.py CHANGED
@@ -1,47 +1,103 @@
1
- runtime error
2
- Exit code: 1. Reason: Error cargando modelo: A load persistent id instruction was encountered,
3
- but no persistent_load function was specified.
4
- Traceback (most recent call last):
5
- File "/home/user/app/app.py", line 10, in <module>
6
- model_data = pickle.load(f)
7
- _pickle.UnpicklingError: A load persistent id instruction was encountered,
8
- but no persistent_load function was specified.
9
-
10
- During handling of the above exception, another exception occurred:
11
-
12
- Traceback (most recent call last):
13
- File "/home/user/app/app.py", line 26, in <module>
14
- model = torch.nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=2).float()
15
- NameError: name 'hidden_size' is not defined
16
- Container logs:
17
-
18
- ===== Application Startup at 2025-05-19 22:20:24 =====
19
-
20
- Error cargando modelo: A load persistent id instruction was encountered,
21
- but no persistent_load function was specified.
22
- Traceback (most recent call last):
23
- File "/home/user/app/app.py", line 10, in <module>
24
- model_data = pickle.load(f)
25
- _pickle.UnpicklingError: A load persistent id instruction was encountered,
26
- but no persistent_load function was specified.
27
-
28
- During handling of the above exception, another exception occurred:
29
-
30
- Traceback (most recent call last):
31
- File "/home/user/app/app.py", line 26, in <module>
32
- model = torch.nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=2).float()
33
- NameError: name 'hidden_size' is not defined
34
- Error cargando modelo: A load persistent id instruction was encountered,
35
- but no persistent_load function was specified.
36
- Traceback (most recent call last):
37
- File "/home/user/app/app.py", line 10, in <module>
38
- model_data = pickle.load(f)
39
- _pickle.UnpicklingError: A load persistent id instruction was encountered,
40
- but no persistent_load function was specified.
41
-
42
- During handling of the above exception, another exception occurred:
43
-
44
- Traceback (most recent call last):
45
- File "/home/user/app/app.py", line 26, in <module>
46
- model = torch.nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=2).float()
47
- NameError: name 'hidden_size' is not defined
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)