Nishal235 commited on
Commit
de1c760
·
verified ·
1 Parent(s): 5a35457

Update app.py

Browse files

STILL RESOLVING THE OUTPUT ISSUE

Files changed (1) hide show
  1. app.py +40 -8
app.py CHANGED
@@ -1,21 +1,53 @@
1
  import gradio as gr
2
- from fastai.vision.all import load_learner
3
 
4
- # Re-declare custom function from training (needed to load the model)
5
  def is_cat(x):
6
  return x[0].isupper()
7
 
8
- # Load your trained model
9
  learn = load_learner("model.pkl")
10
 
11
- # Prediction function
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  def predict(img):
 
 
 
 
 
 
 
13
  pred, pred_idx, probs = learn.predict(img)
14
- # Get the class name (instead of boolean)
15
- label = learn.dls.vocab[pred_idx]
 
 
 
 
 
16
  confidence = float(probs[pred_idx]) * 100
 
17
  return f"This is a {label} with {confidence:.2f}% confidence."
18
 
19
- # Gradio app
20
- iface = gr.Interface(fn=predict, inputs="image", outputs="text")
21
  iface.launch()
 
1
  import gradio as gr
2
+ from fastai.vision.all import load_learner, PILImage
3
 
4
+ # Re-declare custom function used during training (needed by load_learner)
5
  def is_cat(x):
6
  return x[0].isupper()
7
 
8
+ # Load your exported learner
9
  learn = load_learner("model.pkl")
10
 
11
+ # Build a reliable mapping from raw vocab entries -> friendly class names
12
+ vocab = list(learn.dls.vocab)
13
+
14
+ # Default mapping - try to detect boolean labels first
15
+ class_name_map = {}
16
+ if all(isinstance(v, bool) for v in vocab):
17
+ # Most likely True == Cat, False == Dog (this matches the fastbook pattern)
18
+ class_name_map = {True: "Cat 🐱", False: "Dog 🐶"}
19
+ else:
20
+ # If vocab contains strings (or other values), map by content
21
+ for v in vocab:
22
+ s = str(v).lower()
23
+ if "cat" in s:
24
+ class_name_map[v] = "Cat 🐱"
25
+ elif "dog" in s:
26
+ class_name_map[v] = "Dog 🐶"
27
+ else:
28
+ # fallback to string version of the vocab entry
29
+ class_name_map[v] = str(v)
30
+
31
  def predict(img):
32
+ # Accept either an image file path or PIL image depending on Gradio input
33
+ if not isinstance(img, PILImage):
34
+ try:
35
+ img = PILImage.create(img)
36
+ except Exception:
37
+ pass
38
+
39
  pred, pred_idx, probs = learn.predict(img)
40
+
41
+ # raw label from the learner's vocab (might be bool)
42
+ raw_label = learn.dls.vocab[pred_idx]
43
+
44
+ # map to friendly string (fallback to str(raw_label))
45
+ label = class_name_map.get(raw_label, str(raw_label))
46
+
47
  confidence = float(probs[pred_idx]) * 100
48
+
49
  return f"This is a {label} with {confidence:.2f}% confidence."
50
 
51
+ # Gradio UI (single-text output)
52
+ iface = gr.Interface(fn=predict, inputs=gr.Image(type="pil"), outputs="text")
53
  iface.launch()