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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -76
app.py CHANGED
@@ -27,13 +27,34 @@ COCO_INSTANCE_CATEGORY_NAMES = [
27
  'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
28
  'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
29
  ]
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
 
@@ -50,6 +71,9 @@ def detect_objects(image, threshold=0.5):
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,
@@ -68,89 +92,52 @@ def detect_objects(image, threshold=0.5):
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,
143
- inputs=[
144
- gr.Image(type="pil"),
145
- gr.Slider(0, 1, value=0.5, label="Confidence Threshold")
146
- ],
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)
 
27
  'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
28
  'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
29
  ]
30
+
31
  # Gradio-compatible detection function
32
  def detect_objects(image, threshold=0.5):
33
  if image is None:
34
+ print("Image is None, returning empty output", file=sys.stderr)
35
+ # Create a blank image as output
36
+ blank_img = Image.new('RGB', (400, 400), color='white')
37
+ plt.figure(figsize=(10, 10))
38
+ plt.imshow(blank_img)
39
+ plt.text(0.5, 0.5, "No image provided",
40
+ horizontalalignment='center', verticalalignment='center',
41
+ transform=plt.gca().transAxes, fontsize=20)
42
+ plt.axis('off')
43
+ output_path = "blank_output.png"
44
+ plt.savefig(output_path)
45
+ plt.close()
46
+ return output_path
47
 
48
  try:
49
+ print(f"Processing image of type {type(image)} and threshold {threshold}", file=sys.stderr)
50
+ # Make sure threshold is a valid number
51
+ if threshold is None:
52
+ threshold = 0.5
53
+ print("Threshold was None, using default 0.5", file=sys.stderr)
54
+
55
+ # Convert threshold to float if it's not already
56
+ threshold = float(threshold)
57
+
58
  transform = FasterRCNN_ResNet50_FPN_Weights.DEFAULT.transforms()
59
  image_tensor = transform(image).unsqueeze(0)
60
 
 
71
  ax = plt.gca()
72
 
73
  for box, label, score in zip(boxes, labels, scores):
74
+ # Explicit debug prints to trace the comparison issue
75
+ print(f"Score: {score}, Threshold: {threshold}, Type: {type(score)}/{type(threshold)}", file=sys.stderr)
76
+
77
  if score >= threshold:
78
  x1, y1, x2, y2 = box
79
  ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1,
 
92
  return output_path
93
  except Exception as e:
94
  print(f"Error in detect_objects: {e}", file=sys.stderr)
95
+ import traceback
96
+ traceback.print_exc(file=sys.stderr)
97
+
98
+ # Create an error image
99
+ error_img = Image.new('RGB', (400, 400), color='white')
100
+ plt.figure(figsize=(10, 10))
101
+ plt.imshow(error_img)
102
+ plt.text(0.5, 0.5, f"Error: {str(e)}",
103
+ horizontalalignment='center', verticalalignment='center',
104
+ transform=plt.gca().transAxes, fontsize=12, wrap=True)
105
+ plt.axis('off')
106
+ error_path = "error_output.png"
107
+ plt.savefig(error_path)
108
+ plt.close()
109
+ return error_path
 
 
110
 
111
+ # Create direct file paths for examples
112
+ # These exact filenames match what's visible in your repository
113
+ examples = [
114
+ os.path.join("/home/user/app", "TEST_IMG_1.jpg"),
115
+ os.path.join("/home/user/app", "TEST_IMG_2.JPG"),
116
+ os.path.join("/home/user/app", "TEST_IMG_3.jpg"),
117
+ os.path.join("/home/user/app", "TEST_IMG_4.jpg")
118
  ]
119
 
120
+ # Create Gradio interface
121
+ # Important: For Gradio examples, we need to create a list of lists
122
+ example_list = [[path] for path in examples if os.path.exists(path)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
+ print(f"Found {len(example_list)} valid examples: {example_list}", file=sys.stderr)
125
 
126
+ # Create Gradio interface with a simplified approach
127
  interface = gr.Interface(
128
  fn=detect_objects,
129
+ inputs=[
130
+ gr.Image(type="pil", label="Input Image"),
131
+ gr.Slider(minimum=0.0, maximum=1.0, value=0.5, step=0.05, label="Confidence Threshold")
132
+ ],
133
+ outputs=gr.Image(type="filepath", label="Detected Objects"),
134
+ title="Faster R-CNN Object Detection",
 
135
  description="Upload an image to detect objects using a pretrained Faster R-CNN model.",
136
+ examples=example_list,
137
+ cache_examples=False # Disable caching to avoid potential issues
138
+ )
139
 
140
  # Launch with specific configuration for Hugging Face
141
  if __name__ == "__main__":
142
+ # Launch with debug mode enabled
143
  interface.launch(debug=True)