Abs6187 commited on
Commit
ef60eb5
·
verified ·
1 Parent(s): 721e23a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -150
app.py CHANGED
@@ -7,188 +7,188 @@ import logging
7
  from datetime import datetime
8
  from pathlib import Path
9
 
10
- # Configure logging
11
  logging.basicConfig(
12
- level=logging.INFO,
13
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
14
- handlers=[
15
- logging.FileHandler('app.log'),
16
- logging.StreamHandler()
17
- ]
18
  )
19
- logger = logging.getLogger(__name__)
20
 
21
- # Add the project root to Python path
22
- project_root = os.path.dirname(os.path.abspath(__file__))
23
  sys.path.append(project_root)
24
 
 
25
  from ANPR_IND.scripts.charExtraction import CharExtraction
26
  from ANPR_IND.scripts.bboxAnnotator import BBOXAnnotator
27
  from ultralytics import YOLO
28
 
29
- # Initialize ANPR models and classes
30
  wPathPlat = os.path.join(project_root, "ANPR_IND", "licence_plat.pt")
31
  wPathChar = os.path.join(project_root, "ANPR_IND", "licence_character.pt")
32
- classList = np.array(['A','B','C','D','E','F','G','H','I','J','K','L','M',
33
- 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
34
- '0','1','2','3','4','5','6','7','8','9'])
35
- sizePlat = (416,200)
 
 
36
 
37
- # Initialize Helmet Detection model
38
  helmet_model_path = os.path.join(project_root, "Helmet-Detect-model", "best.pt")
39
 
40
- # Verify model files exist
41
  required_files = [wPathPlat, wPathChar, helmet_model_path]
42
  for file_path in required_files:
43
- if not os.path.exists(file_path):
44
- logger.error(f"Required model file not found: {file_path}")
45
- raise FileNotFoundError(f"Required model file not found: {file_path}")
46
 
47
- # Initialize models
48
  try:
49
- logger.info("Initializing models...")
50
- helmet_model = YOLO(helmet_model_path)
51
- extractor = CharExtraction(wPlatePath=wPathPlat, wCharacterPath=wPathChar,
52
- classList=classList, sizePlate=sizePlat, conf=0.5)
53
- annotator = BBOXAnnotator()
54
- logger.info("Models initialized successfully")
 
 
 
 
 
55
  except Exception as e:
56
- logger.error(f"Error initializing models: {str(e)}")
57
- raise
58
 
59
  def process_image(image, conf=0.45):
60
- start_time = datetime.now()
61
- logger.info(f"Processing image with confidence threshold: {conf}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if image is None:
64
- logger.warning("No image provided")
65
- return None, "No image provided", "No image provided"
 
 
 
 
66
 
 
 
 
 
67
  try:
68
- # Convert PIL Image to cv2 format if needed
69
- if isinstance(image, str):
70
- if not os.path.exists(image):
71
- raise FileNotFoundError(f"Image file not found: {image}")
72
- image = cv2.imread(image)
73
- if image is None:
74
- raise ValueError(f"Failed to read image: {image}")
75
- else:
76
- image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
77
-
78
- # ANPR Detection
79
- logger.info("Running ANPR detection")
80
- bbox, plateNum, confidence = extractor.predict(image=image, conf=conf)
81
- anpr_image, plateNum = annotator.draw_bbox(image.copy(), bbox, plateNum)
82
- plate_text = ", ".join(plateNum) if plateNum else "No plate detected"
83
- logger.info(f"ANPR result: {plate_text}")
84
-
85
- # Helmet Detection
86
- logger.info("Running helmet detection")
87
- results = helmet_model(image)
88
- helmet_detected = len(results[0].boxes) > 0
89
- helmet_status = "Helmet Detected" if helmet_detected else "No Helmet Detected"
90
- logger.info(f"Helmet detection result: {helmet_status}")
91
-
92
- # Get annotated image from helmet detection
93
- helmet_image = results[0].plot()
94
-
95
- # Combine annotations
96
- try:
97
- combined_image = cv2.addWeighted(anpr_image, 0.5, helmet_image, 0.5, 0)
98
- except Exception as e:
99
- logger.warning(f"Failed to combine annotations: {str(e)}")
100
- combined_image = helmet_image
101
-
102
- # Convert BGR to RGB for display
103
- if isinstance(combined_image, np.ndarray):
104
- combined_image = cv2.cvtColor(combined_image, cv2.COLOR_BGR2RGB)
105
-
106
- processing_time = (datetime.now() - start_time).total_seconds()
107
- logger.info(f"Processing completed in {processing_time:.2f} seconds")
108
-
109
- return combined_image, plate_text, helmet_status
110
-
111
  except Exception as e:
112
- logger.error(f"Error processing image: {str(e)}")
113
- return image, f"Error: {str(e)}", "Error processing image"
114
-
115
- # Create example images array
 
 
 
 
 
 
 
 
 
 
 
 
116
  example_images = [
117
- os.path.join(project_root, "ANPR_IND", "sample_image2.jpg"),
118
- os.path.join(project_root, "ANPR_IND", "sample_image3.jpg"),
119
- os.path.join(project_root, "ANPR_IND", "sample_image5.jpg"),
120
- os.path.join(project_root, "ANPR_IND", "sample_image6.jpg")
121
  ]
122
 
123
- # Verify example images exist
124
- for img_path in example_images:
125
- if not os.path.exists(img_path):
126
- logger.warning(f"Example image not found: {img_path}")
127
- example_images.remove(img_path)
128
 
129
- # Create Gradio interface
130
  def create_interface():
131
- with gr.Blocks(title="Traffic Violation Detection System", theme=gr.themes.Soft()) as demo:
132
- gr.Markdown("# Combined ANPR and Helmet Detection System")
133
- gr.Markdown("Upload an image to detect license plates and check for helmet usage.")
134
-
135
- with gr.Row():
136
- with gr.Column():
137
- input_image = gr.Image(label="Input Image", type="pil")
138
- conf_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.45,
139
- label="Confidence Threshold")
140
- detect_button = gr.Button("Detect", variant="primary")
141
-
142
- with gr.Column():
143
- output_image = gr.Image(label="Annotated Image")
144
- plate_output = gr.Textbox(label="License Plate")
145
- helmet_output = gr.Textbox(label="Helmet Status")
146
-
147
- # Set up example images
148
- if example_images:
149
- gr.Examples(
150
- examples=[[img, 0.45] for img in example_images],
151
- inputs=[input_image, conf_slider],
152
- outputs=[output_image, plate_output, helmet_output],
153
- fn=process_image,
154
- cache_examples=True
155
  )
156
-
157
- # Set up the click event
158
- detect_button.click(
159
- fn=process_image,
 
 
 
 
 
 
160
  inputs=[input_image, conf_slider],
161
- outputs=[output_image, plate_output, helmet_output]
 
 
162
  )
163
 
164
- return demo
 
 
 
 
 
165
 
166
- if __name__ == "__main__":
167
- try:
168
- logger.info("Starting application...")
169
- demo = create_interface()
170
- demo.queue() # Enable queue separately
171
-
172
- # Configure FastAPI app with custom settings
173
- demo.launch(
174
- share=True, # Disable share link by default
175
- server_name="127.0.0.1", # Use localhost instead of 0.0.0.0
176
- server_port=7860,
177
- favicon_path=None,
178
- auth=None,
179
- ssl_keyfile=None,
180
- ssl_certfile=None,
181
- ssl_verify=True,
182
- quiet=False,
183
- show_api=True,
184
- root_path="",
185
- _frontend=True,
186
- prevent_thread_lock=False,
187
- allowed_paths=None,
188
- blocked_paths=None,
189
- max_threads=40,
190
- debug=True # Enable debug mode for better error reporting
191
- )
192
- except Exception as e:
193
- logger.error(f"Failed to start application: {str(e)}")
194
- sys.exit(1)
 
7
  from datetime import datetime
8
  from pathlib import Path
9
 
10
+ Configure logging
11
  logging.basicConfig(
12
+ level=logging.INFO,
13
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
14
+ handlers=[
15
+ logging.FileHandler('app.log'),
16
+ logging.StreamHandler()
17
+ ]
18
  )
19
+ logger = logging.getLogger(name)
20
 
21
+ #Add the project root to Python path
22
+ project_root = os.path.dirname(os.path.abspath(file))
23
  sys.path.append(project_root)
24
 
25
+ #Import custom modules and models
26
  from ANPR_IND.scripts.charExtraction import CharExtraction
27
  from ANPR_IND.scripts.bboxAnnotator import BBOXAnnotator
28
  from ultralytics import YOLO
29
 
30
+ #Initialize ANPR models and classes
31
  wPathPlat = os.path.join(project_root, "ANPR_IND", "licence_plat.pt")
32
  wPathChar = os.path.join(project_root, "ANPR_IND", "licence_character.pt")
33
+ classList = np.array([
34
+ 'A','B','C','D','E','F','G','H','I','J','K','L','M',
35
+ 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
36
+ '0','1','2','3','4','5','6','7','8','9'
37
+ ])
38
+ sizePlat = (416, 200)
39
 
40
+ #Initialize Helmet Detection model path
41
  helmet_model_path = os.path.join(project_root, "Helmet-Detect-model", "best.pt")
42
 
43
+ #Verify that the required model files exist
44
  required_files = [wPathPlat, wPathChar, helmet_model_path]
45
  for file_path in required_files:
46
+ if not os.path.exists(file_path):
47
+ logger.error(f"Required model file not found: {file_path}")
48
+ raise FileNotFoundError(f"Required model file not found: {file_path}")
49
 
50
+ #Initialize models
51
  try:
52
+ logger.info("Initializing models...")
53
+ helmet_model = YOLO(helmet_model_path)
54
+ extractor = CharExtraction(
55
+ wPlatePath=wPathPlat,
56
+ wCharacterPath=wPathChar,
57
+ classList=classList,
58
+ sizePlate=sizePlat,
59
+ conf=0.5
60
+ )
61
+ annotator = BBOXAnnotator()
62
+ logger.info("Models initialized successfully")
63
  except Exception as e:
64
+ logger.error(f"Error initializing models: {str(e)}")
65
+ raise
66
 
67
  def process_image(image, conf=0.45):
68
+ start_time = datetime.now()
69
+ logger.info(f"Processing image with confidence threshold: {conf}")
70
+
71
+ text
72
+ if image is None:
73
+ logger.warning("No image provided")
74
+ return None, "No image provided", "No image provided"
75
+
76
+ try:
77
+ # Convert PIL Image to OpenCV BGR format if necessary
78
+ if isinstance(image, str):
79
+ if not os.path.exists(image):
80
+ raise FileNotFoundError(f"Image file not found: {image}")
81
+ image = cv2.imread(image)
82
+ if image is None:
83
+ raise ValueError("Failed to read image from the provided path.")
84
+ else:
85
+ image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
86
+
87
+ # Run ANPR detection
88
+ logger.info("Running ANPR detection")
89
+ bbox, plateNum, confidence = extractor.predict(image=image, conf=conf)
90
+ anpr_image, plateNum = annotator.draw_bbox(image.copy(), bbox, plateNum)
91
+ plate_text = ", ".join(plateNum) if plateNum else "No plate detected"
92
+ logger.info(f"ANPR result: {plate_text}")
93
 
94
+ # Run Helmet detection
95
+ logger.info("Running helmet detection")
96
+ results = helmet_model(image)
97
+ # Ensure accessing the correct results container; the first element usually holds the detection info
98
+ helmet_detected = len(results.boxes) > 0
99
+ helmet_status = "Helmet Detected" if helmet_detected else "No Helmet Detected"
100
+ logger.info(f"Helmet detection result: {helmet_status}")
101
 
102
+ # Retrieve annotated image from helmet detection
103
+ helmet_image = results.plot()
104
+
105
+ # Combine annotations from both detections
106
  try:
107
+ combined_image = cv2.addWeighted(anpr_image, 0.5, helmet_image, 0.5, 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  except Exception as e:
109
+ logger.warning(f"Failed to combine annotations: {str(e)}")
110
+ combined_image = helmet_image
111
+
112
+ # Convert image from BGR to RGB for proper display in Gradio
113
+ if isinstance(combined_image, np.ndarray):
114
+ combined_image = cv2.cvtColor(combined_image, cv2.COLOR_BGR2RGB)
115
+
116
+ processing_time = (datetime.now() - start_time).total_seconds()
117
+ logger.info(f"Processing completed in {processing_time:.2f} seconds")
118
+
119
+ return combined_image, plate_text, helmet_status
120
+
121
+ except Exception as e:
122
+ logger.error(f"Error processing image: {str(e)}")
123
+ return image, f"Error: {str(e)}", "Error processing image"
124
+ #Create an array of example image paths
125
  example_images = [
126
+ os.path.join(project_root, "ANPR_IND", "sample_image2.jpg"),
127
+ os.path.join(project_root, "ANPR_IND", "sample_image3.jpg"),
128
+ os.path.join(project_root, "ANPR_IND", "sample_image5.jpg"),
129
+ os.path.join(project_root, "ANPR_IND", "sample_image6.jpg")
130
  ]
131
 
132
+ #Verify example images exist, and remove any that aren't found
133
+ for img_path in example_images.copy():
134
+ if not os.path.exists(img_path):
135
+ logger.warning(f"Example image not found: {img_path}")
136
+ example_images.remove(img_path)
137
 
 
138
  def create_interface():
139
+ with gr.Blocks(title="Traffic Violation Detection System", theme=gr.themes.Soft()) as demo:
140
+ gr.Markdown("# Combined ANPR and Helmet Detection System")
141
+ gr.Markdown("Upload an image to detect license plates and check for helmet usage.")
142
+
143
+ text
144
+ with gr.Row():
145
+ with gr.Column():
146
+ input_image = gr.Image(label="Input Image", type="pil")
147
+ conf_slider = gr.Slider(
148
+ minimum=0.1,
149
+ maximum=1.0,
150
+ value=0.45,
151
+ label="Confidence Threshold"
 
 
 
 
 
 
 
 
 
 
 
152
  )
153
+ detect_button = gr.Button("Detect", variant="primary")
154
+ with gr.Column():
155
+ output_image = gr.Image(label="Annotated Image")
156
+ plate_output = gr.Textbox(label="License Plate")
157
+ helmet_output = gr.Textbox(label="Helmet Status")
158
+
159
+ # Configure example images if available
160
+ if example_images:
161
+ gr.Examples(
162
+ examples=[[img, 0.45] for img in example_images],
163
  inputs=[input_image, conf_slider],
164
+ outputs=[output_image, plate_output, helmet_output],
165
+ fn=process_image,
166
+ cache_examples=True
167
  )
168
 
169
+ # Set up the click event to trigger detection
170
+ detect_button.click(
171
+ fn=process_image,
172
+ inputs=[input_image, conf_slider],
173
+ outputs=[output_image, plate_output, helmet_output]
174
+ )
175
 
176
+ return demo
177
+ if name == "main":
178
+ try:
179
+ logger.info("Starting application...")
180
+ demo = create_interface()
181
+ demo.queue() # Enable request queuing if your tasks are long-running
182
+
183
+ text
184
+ # Launch application on Hugging Face Spaces
185
+ # - Use server_name="0.0.0.0" to allow external connections.
186
+ # - Do not include share=True (Spaces already provides your public URL).
187
+ demo.launch(
188
+ server_name="0.0.0.0",
189
+ server_port=7860,
190
+ debug=True
191
+ )
192
+ except Exception as e:
193
+ logger.error(f"Failed to start application: {str(e)}")
194
+ sys.exit(1)