AIOmarRehan commited on
Commit
201816e
·
verified ·
1 Parent(s): 9f43ed3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -8
app.py CHANGED
@@ -4,11 +4,17 @@ from PIL import Image
4
  from model import predict
5
  from datasets import load_dataset
6
 
7
- # Load the HF dataset once
8
- dataset = load_dataset("AIOmarRehan/AnimalsDataset", split="train", streaming=True)
9
 
10
  def classify_image(img: Image.Image):
 
 
 
 
 
11
  label, confidence, probs = predict(img)
 
12
  return (
13
  label,
14
  round(confidence, 3),
@@ -17,14 +23,17 @@ def classify_image(img: Image.Image):
17
 
18
  # Pick a random example
19
  def random_example():
20
- # Choose a random row
21
  idx = random.randint(0, len(dataset) - 1)
22
  item = dataset[idx]
23
- img = item["image"].convert("RGB") # PIL Image
24
- label = item["label"] # numeric label from dataset
25
- label_str = dataset.features["label"].int2str(label) # class name
 
 
26
  return img, label_str
27
 
 
28
  demo = gr.Blocks()
29
 
30
  with demo:
@@ -46,8 +55,16 @@ with demo:
46
  rand_label = gr.Textbox(label="Sample Label")
47
 
48
  # Actions
49
- pred_btn.click(classify_image, inputs=input_img, outputs=[output_label, output_conf, output_probs])
50
- rand_img.click(random_example, outputs=[rand_display, rand_label])
 
 
 
 
 
 
 
 
51
 
52
  if __name__ == "__main__":
53
  demo.launch()
 
4
  from model import predict
5
  from datasets import load_dataset
6
 
7
+ # Load dataset (NO streaming → allows len() and indexing)
8
+ dataset = load_dataset("AIOmarRehan/AnimalsDataset", split="train")
9
 
10
  def classify_image(img: Image.Image):
11
+
12
+ # Handle empty input safely
13
+ if img is None:
14
+ return "No image uploaded", 0, {}
15
+
16
  label, confidence, probs = predict(img)
17
+
18
  return (
19
  label,
20
  round(confidence, 3),
 
23
 
24
  # Pick a random example
25
  def random_example():
26
+
27
  idx = random.randint(0, len(dataset) - 1)
28
  item = dataset[idx]
29
+
30
+ img = item["image"].convert("RGB")
31
+ label = item["label"]
32
+ label_str = dataset.features["label"].int2str(label)
33
+
34
  return img, label_str
35
 
36
+
37
  demo = gr.Blocks()
38
 
39
  with demo:
 
55
  rand_label = gr.Textbox(label="Sample Label")
56
 
57
  # Actions
58
+ pred_btn.click(
59
+ classify_image,
60
+ inputs=input_img,
61
+ outputs=[output_label, output_conf, output_probs]
62
+ )
63
+
64
+ rand_img.click(
65
+ random_example,
66
+ outputs=[rand_display, rand_label]
67
+ )
68
 
69
  if __name__ == "__main__":
70
  demo.launch()