JohnJoelMota commited on
Commit
c19796e
·
verified ·
1 Parent(s): d43dcb1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -41
app.py CHANGED
@@ -6,6 +6,7 @@ import numpy as np
6
  import matplotlib.pyplot as plt
7
  import gradio as gr
8
  import os
 
9
 
10
  # Load the pre-trained model once
11
  model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.DEFAULT)
@@ -29,48 +30,113 @@ COCO_INSTANCE_CATEGORY_NAMES = [
29
 
30
  # Gradio-compatible detection function
31
  def detect_objects(image, threshold=0.5):
32
- transform = FasterRCNN_ResNet50_FPN_Weights.DEFAULT.transforms()
33
- image_tensor = transform(image).unsqueeze(0)
34
-
35
- with torch.no_grad():
36
- prediction = model(image_tensor)[0]
37
-
38
- boxes = prediction['boxes'].cpu().numpy()
39
- labels = prediction['labels'].cpu().numpy()
40
- scores = prediction['scores'].cpu().numpy()
41
-
42
- image_np = np.array(image)
43
- plt.figure(figsize=(10, 10))
44
- plt.imshow(image_np)
45
- ax = plt.gca()
46
-
47
- for box, label, score in zip(boxes, labels, scores):
48
- if score >= threshold:
49
- x1, y1, x2, y2 = box
50
- ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1,
51
- fill=False, color='red', linewidth=2))
52
- class_name = COCO_INSTANCE_CATEGORY_NAMES[label]
53
- ax.text(x1, y1, f'{class_name}: {score:.2f}', bbox=dict(facecolor='yellow', alpha=0.5),
54
- fontsize=12, color='black')
55
-
56
- plt.axis('off')
57
- plt.tight_layout()
 
58
 
59
- # Save the figure to return
60
- plt.savefig("output.png")
61
- plt.close()
62
- return "output.png"
 
 
 
 
 
 
 
63
 
64
- # Define the example image paths correctly for Hugging Face Spaces
65
- # Images are in the Object-Detection subdirectory
66
- examples_dir = os.path.join(os.path.dirname(__file__), "Object-Detection")
67
- example_images = [
68
- [os.path.join(examples_dir, "TEST_IMG_1.jpg")],
69
- [os.path.join(examples_dir, "TEST_IMG_2.JPG")], # Note: preserving the uppercase JPG extension
70
- [os.path.join(examples_dir, "TEST_IMG_3.jpg")],
71
- [os.path.join(examples_dir, "TEST_IMG_4.jpg")]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  ]
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  # Create Gradio interface
75
  interface = gr.Interface(
76
  fn=detect_objects,
@@ -81,9 +147,10 @@ interface = gr.Interface(
81
  outputs=gr.Image(type="filepath"),
82
  examples=example_images,
83
  title="Faster R-CNN Object Detection",
84
- description="Upload an image to detect objects using a pretrained Faster R-CNN model."
85
- )
 
86
 
87
  # Launch with specific configuration for Hugging Face
88
  if __name__ == "__main__":
89
- interface.launch()
 
6
  import matplotlib.pyplot as plt
7
  import gradio as gr
8
  import os
9
+ import sys
10
 
11
  # Load the pre-trained model once
12
  model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.DEFAULT)
 
30
 
31
  # Gradio-compatible detection function
32
  def detect_objects(image, threshold=0.5):
33
+ if image is None:
34
+ return None
35
+
36
+ try:
37
+ transform = FasterRCNN_ResNet50_FPN_Weights.DEFAULT.transforms()
38
+ image_tensor = transform(image).unsqueeze(0)
39
+
40
+ with torch.no_grad():
41
+ prediction = model(image_tensor)[0]
42
+
43
+ boxes = prediction['boxes'].cpu().numpy()
44
+ labels = prediction['labels'].cpu().numpy()
45
+ scores = prediction['scores'].cpu().numpy()
46
+
47
+ image_np = np.array(image)
48
+ plt.figure(figsize=(10, 10))
49
+ plt.imshow(image_np)
50
+ ax = plt.gca()
51
+
52
+ for box, label, score in zip(boxes, labels, scores):
53
+ if score >= threshold:
54
+ x1, y1, x2, y2 = box
55
+ ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1,
56
+ fill=False, color='red', linewidth=2))
57
+ class_name = COCO_INSTANCE_CATEGORY_NAMES[label]
58
+ ax.text(x1, y1, f'{class_name}: {score:.2f}', bbox=dict(facecolor='yellow', alpha=0.5),
59
+ fontsize=12, color='black')
60
 
61
+ plt.axis('off')
62
+ plt.tight_layout()
63
+
64
+ # Save the figure to return
65
+ output_path = "output.png"
66
+ plt.savefig(output_path)
67
+ plt.close()
68
+ return output_path
69
+ except Exception as e:
70
+ print(f"Error in detect_objects: {e}", file=sys.stderr)
71
+ return None
72
 
73
+ # Function to check if a file exists
74
+ def file_exists(filepath):
75
+ return os.path.isfile(filepath)
76
+
77
+ # Find base directory for examples
78
+ # For Hugging Face Spaces, this is typically the root directory of the repository
79
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
80
+
81
+ # Check all possible locations for the example images
82
+ possible_dirs = [
83
+ BASE_DIR, # Root directory
84
+ os.path.join(BASE_DIR, "Object-Detection"), # Subdirectory
85
+ os.path.join(BASE_DIR, "images"), # Common image directory name
86
+ os.path.join(os.path.dirname(BASE_DIR), "Object-Detection") # Parent/sibling directory
87
+ ]
88
+
89
+ # Test image filenames with different case combinations
90
+ test_image_variations = [
91
+ ["TEST_IMG_1.jpg"],
92
+ ["TEST_IMG_1.JPG"],
93
+ ["test_img_1.jpg"],
94
+ ["Test_Img_1.jpg"]
95
  ]
96
 
97
+ # Find working examples by testing different combinations
98
+ working_examples = []
99
+
100
+ # Check all possible combinations of directories and filenames
101
+ for directory in possible_dirs:
102
+ print(f"Checking directory: {directory}", file=sys.stderr)
103
+ if os.path.isdir(directory):
104
+ for variation in test_image_variations:
105
+ filepath = os.path.join(directory, variation[0])
106
+ if file_exists(filepath):
107
+ print(f"Found example image: {filepath}", file=sys.stderr)
108
+ working_examples.append([filepath])
109
+ # If we found the first image, try the others with the same pattern
110
+ base_pattern = variation[0].split("1")[0]
111
+ ext = variation[0].split(".")[-1]
112
+ for i in range(2, 5): # Test images 2-4
113
+ test_path = os.path.join(directory, f"{base_pattern}{i}.{ext}")
114
+ if file_exists(test_path):
115
+ print(f"Found additional example: {test_path}", file=sys.stderr)
116
+ working_examples.append([test_path])
117
+
118
+ # If we found all 4 examples, break the loop
119
+ if len(working_examples) >= 4:
120
+ break
121
+
122
+ # If we found examples in this directory, no need to check others
123
+ if working_examples:
124
+ break
125
+
126
+ # If no working examples found, try hard-coded paths
127
+ if not working_examples:
128
+ print("No examples found automatically. Using hard-coded paths.", file=sys.stderr)
129
+ example_images = [
130
+ ["TEST_IMG_1.jpg"],
131
+ ["TEST_IMG_2.JPG"],
132
+ ["TEST_IMG_3.jpg"],
133
+ ["TEST_IMG_4.jpg"]
134
+ ]
135
+ else:
136
+ example_images = working_examples[:4] # Use first 4 found examples
137
+
138
+ print(f"Final example images: {example_images}", file=sys.stderr)
139
+
140
  # Create Gradio interface
141
  interface = gr.Interface(
142
  fn=detect_objects,
 
147
  outputs=gr.Image(type="filepath"),
148
  examples=example_images,
149
  title="Faster R-CNN Object Detection",
150
+ description="Upload an image to detect objects using a pretrained Faster R-CNN model.",
151
+ allow_flagging="never" # Disable flagging to avoid potential issues
152
+ )
153
 
154
  # Launch with specific configuration for Hugging Face
155
  if __name__ == "__main__":
156
+ interface.launch(debug=True)