Edupy commited on
Commit
4530bc5
·
1 Parent(s): bca1dfd

Arquitectura modular con funciones get_x/y reales

Browse files
Files changed (2) hide show
  1. app.py +19 -37
  2. utils.py +17 -0
app.py CHANGED
@@ -1,49 +1,31 @@
1
 
2
  import gradio as gr
3
- import torch
4
- import timm
5
- from PIL import Image
6
  from fastai.vision.all import *
 
7
 
8
- # 1. Categorías (Asegúrate de que el orden sea el mismo que dls.vocab en Colab)
9
- categories = ['Bug', 'Dark', 'Dragon', 'Electric', 'Fairy', 'Fighting',
10
- 'Fire', 'Flying', 'Ghost', 'Grass', 'Ground', 'Ice',
11
- 'Normal', 'Poison', 'Psychic', 'Rock', 'Steel', 'Water']
12
 
13
- def load_model_fastai_style(weights_path):
14
- # Creamos dls mínimos
15
- empty_ds = Datasets([None], [[]])
16
- dls = DataLoaders.from_dsets(empty_ds, empty_ds, path='.', bs=1, device='cpu')
17
- dls.vocab = categories
18
-
19
- # Especificamos loss_func explícitamente para evitar el AssertionError
20
- learn = vision_learner(dls, 'convnext_tiny', pretrained=False, loss_func=CrossEntropyLossFlat())
21
-
22
- # Cargar pesos
23
- state = torch.load(weights_path, map_location='cpu', weights_only=False)
24
- if isinstance(state, dict) and 'model' in state:
25
- learn.model.load_state_dict(state['model'])
26
- else:
27
- learn.model.load_state_dict(state)
28
-
29
- learn.model.eval()
30
- return learn
31
 
32
- # Carga
33
- learn = load_model_fastai_style('checkpoint_1.pth')
 
 
 
34
 
35
  def predict(img):
36
- img = PILImage.create(img).resize((126, 126))
 
37
  pred, pred_idx, probs = learn.predict(img)
38
- return {categories[i]: float(probs[i]) for i in range(len(categories))}
39
 
40
- # Interfaz
41
- demo = gr.Interface(
42
  fn=predict,
43
- inputs=gr.Image(type="pil"),
44
  outputs=gr.Label(num_top_classes=3),
45
- title="Pokemon Type Classifier",
46
- description="Identifica el tipo principal de tu Pokémon."
47
- )
48
-
49
- demo.launch()
 
1
 
2
  import gradio as gr
 
 
 
3
  from fastai.vision.all import *
4
+ import __main__
5
 
6
+ # 1. Importar las funciones reales del archivo utils
7
+ from utils import get_x, get_y, ds_combined
 
 
8
 
9
+ # 2. Inyectarlas en el Namespace principal
10
+ __main__.get_x = get_x
11
+ __main__.get_y = get_y
12
+ __main__.ds_combined = ds_combined
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ # 3. Carga del modelo exportado (.pkl)
15
+ # Asegúrate de que el archivo se llame 'modelo_pokemon.pkl' en tu repo
16
+ learn = load_learner('modelo_pokemon.pkl')
17
+
18
+ labels = learn.dls.vocab
19
 
20
  def predict(img):
21
+ img = PILImage.create(img)
22
+ # Al usar el predict del learner cargado, usará las funciones get_x/y que inyectamos
23
  pred, pred_idx, probs = learn.predict(img)
24
+ return {labels[i]: float(probs[i]) for i in range(len(labels))}
25
 
26
+ gr.Interface(
 
27
  fn=predict,
28
+ inputs=gr.Image(),
29
  outputs=gr.Label(num_top_classes=3),
30
+ title="Detector de Tipos Pokémon (Espejo de Colab)"
31
+ ).launch()
 
 
 
utils.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from fastai.vision.all import *
3
+
4
+ # Simulamos el objeto que tenías en Colab para que las funciones no den NameError
5
+ # Pero lo dejamos vacío porque en la App predeciremos imágenes nuevas, no del dataset
6
+ ds_combined = {}
7
+
8
+ def get_x(i):
9
+ # En entrenamiento usabas: ds_combined[i]['image_data'].convert('RGB')
10
+ # En la App, el 'i' que recibirá será la imagen que subas directamente
11
+ if isinstance(i, (PILImage, Image.Image)): return i.convert('RGB')
12
+ return ds_combined[i]['image_data'].convert('RGB')
13
+
14
+ def get_y(i):
15
+ # En entrenamiento: ds_combined[i]['Type 1']
16
+ if isinstance(ds_combined, dict) and len(ds_combined) == 0: return "Unknown"
17
+ return ds_combined[i]['Type 1']