Edupy commited on
Commit
79724de
·
1 Parent(s): 436af78

Usando from_pretrained_fastai para carga limpia

Browse files
Files changed (1) hide show
  1. app.py +30 -43
app.py CHANGED
@@ -1,52 +1,39 @@
1
 
2
- from fastai.vision.all import *
3
  import gradio as gr
4
- import timm
5
- import torch
 
 
 
 
 
6
 
7
- categories = ['Bug', 'Dark', 'Dragon', 'Electric', 'Fairy', 'Fighting',
8
- 'Fire', 'Flying', 'Ghost', 'Grass', 'Ground', 'Ice',
9
- 'Normal', 'Poison', 'Psychic', 'Rock', 'Steel', 'Water']
10
 
11
- def load_pokemon_model(weights_path):
12
- model = timm.create_model('convnext_tiny', pretrained=False, num_classes=len(categories))
13
- state_dict = torch.load(weights_path, map_location='cpu', weights_only=False)
14
- if 'model' in state_dict: state_dict = state_dict['model']
15
- new_state_dict = {k.replace('0.model.', ''): v for k, v in state_dict.items()}
16
- model.load_state_dict(new_state_dict, strict=False)
17
- model.eval()
18
- return model
19
 
20
- model = load_pokemon_model('checkpoint_1.pth')
21
 
22
  def predict(img):
23
- try:
24
- # 1. Procesar imagen PIL
25
- img = PILImage.create(img).resize((126, 126))
26
-
27
- # 2. Convertir a tensor manualmente para tener control total
28
- # image2tensor devuelve un tensor de [3, 126, 126]
29
- timg = image2tensor(img)
30
- timg = timg.float()/255.0 # Normalizar a 0-1
31
-
32
- # 3. Aplicar normalización de ImageNet (Media y Desviación estándar)
33
- stats = imagenet_stats
34
- timg = (timg - tensor(stats[0])[:,None,None]) / tensor(stats[1])[:,None,None]
35
-
36
- # 4. Añadir dimensión de batch -> Resultado: [1, 3, 126, 126]
37
- batch_img = timg.unsqueeze(0)
38
-
39
- with torch.no_grad():
40
- output = model(batch_img)
41
- probs = torch.softmax(output, dim=1)[0]
42
-
43
- return {categories[i]: float(probs[i]) for i in range(len(categories))}
44
- except Exception as e:
45
- return {f"Error: {str(e)}": 0.0}
46
-
47
- gr.Interface(
48
  fn=predict,
49
- inputs=gr.Image(),
50
  outputs=gr.Label(num_top_classes=3),
51
- title="Detector de Tipos Pokémon"
52
- ).launch()
 
 
 
 
 
1
 
 
2
  import gradio as gr
3
+ from fastai.vision.all import *
4
+ from huggingface_hub import from_pretrained_fastai
5
+ import torch, os
6
+
7
+ # Optimizaciones de CPU para el servidor
8
+ os.environ.setdefault("OMP_NUM_THREADS", "1")
9
+ torch.set_num_threads(1)
10
 
11
+ # --- REEMPLAZA CON TU REPO_ID ---
12
+ # Ejemplo: "Edupy/pokemon-1class-classifier-26"
13
+ learn = from_pretrained_fastai("Edupy/pokemon-1class-classifier-26")
14
 
15
+ try:
16
+ learn.to_fp32()
17
+ except:
18
+ pass
 
 
 
 
19
 
20
+ labels = learn.dls.vocab
21
 
22
  def predict(img):
23
+ img = PILImage.create(img)
24
+ pred, pred_idx, probs = learn.predict(img)
25
+ return {labels[i]: float(probs[i]) for i in range(len(labels))}
26
+
27
+ title = "Detector de Tipos Pokémon"
28
+ description = "Modelo profesional cargado desde el Hub para identificar tipos elementales."
29
+
30
+ demo = gr.Interface(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  fn=predict,
32
+ inputs=gr.Image(type="pil"),
33
  outputs=gr.Label(num_top_classes=3),
34
+ title=title,
35
+ description=description
36
+ )
37
+
38
+ # Configuración de cola para evitar que el Space se cuelgue con muchas peticiones
39
+ demo.queue(max_size=8).launch(show_error=True, debug=True)