Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,188 +7,164 @@ 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(
|
| 20 |
|
| 21 |
-
|
| 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 |
-
|
| 72 |
-
|
| 73 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
except Exception as e:
|
| 109 |
-
logger.
|
| 110 |
-
|
| 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 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
)
|
| 153 |
-
|
| 154 |
-
|
| 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 |
-
|
|
|
|
| 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 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
demo
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 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 |
logging.basicConfig(
|
| 11 |
+
level=logging.INFO,
|
| 12 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 13 |
+
handlers=[
|
| 14 |
+
logging.FileHandler('app.log'),
|
| 15 |
+
logging.StreamHandler()
|
| 16 |
+
]
|
| 17 |
)
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
|
| 20 |
+
project_root = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
| 21 |
sys.path.append(project_root)
|
| 22 |
|
|
|
|
| 23 |
from ANPR_IND.scripts.charExtraction import CharExtraction
|
| 24 |
from ANPR_IND.scripts.bboxAnnotator import BBOXAnnotator
|
| 25 |
from ultralytics import YOLO
|
| 26 |
|
|
|
|
| 27 |
wPathPlat = os.path.join(project_root, "ANPR_IND", "licence_plat.pt")
|
| 28 |
wPathChar = os.path.join(project_root, "ANPR_IND", "licence_character.pt")
|
| 29 |
classList = np.array([
|
| 30 |
+
'A','B','C','D','E','F','G','H','I','J','K','L','M',
|
| 31 |
+
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
|
| 32 |
+
'0','1','2','3','4','5','6','7','8','9'
|
| 33 |
])
|
| 34 |
sizePlat = (416, 200)
|
| 35 |
|
|
|
|
| 36 |
helmet_model_path = os.path.join(project_root, "Helmet-Detect-model", "best.pt")
|
| 37 |
|
|
|
|
| 38 |
required_files = [wPathPlat, wPathChar, helmet_model_path]
|
| 39 |
for file_path in required_files:
|
| 40 |
+
if not os.path.exists(file_path):
|
| 41 |
+
logger.error(f"Required model file not found: {file_path}")
|
| 42 |
+
raise FileNotFoundError(f"Required model file not found: {file_path}")
|
| 43 |
|
|
|
|
| 44 |
try:
|
| 45 |
+
logger.info("Initializing models...")
|
| 46 |
+
helmet_model = YOLO(helmet_model_path)
|
| 47 |
+
extractor = CharExtraction(
|
| 48 |
+
wPlatePath=wPathPlat,
|
| 49 |
+
wCharacterPath=wPathChar,
|
| 50 |
+
classList=classList,
|
| 51 |
+
sizePlate=sizePlat,
|
| 52 |
+
conf=0.5
|
| 53 |
+
)
|
| 54 |
+
annotator = BBOXAnnotator()
|
| 55 |
+
logger.info("Models initialized successfully")
|
| 56 |
except Exception as e:
|
| 57 |
+
logger.error(f"Error initializing models: {str(e)}")
|
| 58 |
+
raise
|
| 59 |
|
| 60 |
def process_image(image, conf=0.45):
|
| 61 |
+
start_time = datetime.now()
|
| 62 |
+
logger.info(f"Processing image with confidence threshold: {conf}")
|
| 63 |
|
| 64 |
+
if image is None:
|
| 65 |
+
logger.warning("No image provided")
|
| 66 |
+
return None, "No image provided", "No image provided"
|
|
|
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
try:
|
| 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("Failed to read image from the provided path.")
|
| 75 |
+
else:
|
| 76 |
+
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 77 |
+
|
| 78 |
+
logger.info("Running ANPR detection")
|
| 79 |
+
bbox, plateNum, confidence = extractor.predict(image=image, conf=conf)
|
| 80 |
+
anpr_image, plateNum = annotator.draw_bbox(image.copy(), bbox, plateNum)
|
| 81 |
+
plate_text = ", ".join(plateNum) if plateNum else "No plate detected"
|
| 82 |
+
logger.info(f"ANPR result: {plate_text}")
|
| 83 |
+
|
| 84 |
+
logger.info("Running helmet detection")
|
| 85 |
+
results = helmet_model(image)
|
| 86 |
+
helmet_detected = len(results.boxes) > 0
|
| 87 |
+
helmet_status = "Helmet Detected" if helmet_detected else "No Helmet Detected"
|
| 88 |
+
logger.info(f"Helmet detection result: {helmet_status}")
|
| 89 |
+
|
| 90 |
+
helmet_image = results.plot()
|
| 91 |
+
|
| 92 |
+
try:
|
| 93 |
+
combined_image = cv2.addWeighted(anpr_image, 0.5, helmet_image, 0.5, 0)
|
| 94 |
+
except Exception as e:
|
| 95 |
+
logger.warning(f"Failed to combine annotations: {str(e)}")
|
| 96 |
+
combined_image = helmet_image
|
| 97 |
+
|
| 98 |
+
if isinstance(combined_image, np.ndarray):
|
| 99 |
+
combined_image = cv2.cvtColor(combined_image, cv2.COLOR_BGR2RGB)
|
| 100 |
+
|
| 101 |
+
processing_time = (datetime.now() - start_time).total_seconds()
|
| 102 |
+
logger.info(f"Processing completed in {processing_time:.2f} seconds")
|
| 103 |
+
|
| 104 |
+
return combined_image, plate_text, helmet_status
|
| 105 |
except Exception as e:
|
| 106 |
+
logger.error(f"Error processing image: {str(e)}")
|
| 107 |
+
return image, f"Error: {str(e)}", "Error processing image"
|
| 108 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
example_images = [
|
| 110 |
+
os.path.join(project_root, "ANPR_IND", "sample_image2.jpg"),
|
| 111 |
+
os.path.join(project_root, "ANPR_IND", "sample_image3.jpg"),
|
| 112 |
+
os.path.join(project_root, "ANPR_IND", "sample_image5.jpg"),
|
| 113 |
+
os.path.join(project_root, "ANPR_IND", "sample_image6.jpg")
|
| 114 |
]
|
| 115 |
|
|
|
|
| 116 |
for img_path in example_images.copy():
|
| 117 |
+
if not os.path.exists(img_path):
|
| 118 |
+
logger.warning(f"Example image not found: {img_path}")
|
| 119 |
+
example_images.remove(img_path)
|
| 120 |
|
| 121 |
def create_interface():
|
| 122 |
+
with gr.Blocks(title="Traffic Violation Detection System", theme=gr.themes.Soft()) as demo:
|
| 123 |
+
gr.Markdown("# Combined ANPR and Helmet Detection System")
|
| 124 |
+
gr.Markdown("Upload an image to detect license plates and check for helmet usage.")
|
| 125 |
+
|
| 126 |
+
with gr.Row():
|
| 127 |
+
with gr.Column():
|
| 128 |
+
input_image = gr.Image(label="Input Image", type="pil")
|
| 129 |
+
conf_slider = gr.Slider(
|
| 130 |
+
minimum=0.1,
|
| 131 |
+
maximum=1.0,
|
| 132 |
+
value=0.45,
|
| 133 |
+
label="Confidence Threshold"
|
| 134 |
+
)
|
| 135 |
+
detect_button = gr.Button("Detect", variant="primary")
|
| 136 |
+
with gr.Column():
|
| 137 |
+
output_image = gr.Image(label="Annotated Image")
|
| 138 |
+
plate_output = gr.Textbox(label="License Plate")
|
| 139 |
+
helmet_output = gr.Textbox(label="Helmet Status")
|
| 140 |
+
|
| 141 |
+
if example_images:
|
| 142 |
+
gr.Examples(
|
| 143 |
+
examples=[[img, 0.45] for img in example_images],
|
| 144 |
+
inputs=[input_image, conf_slider],
|
| 145 |
+
outputs=[output_image, plate_output, helmet_output],
|
| 146 |
+
fn=process_image,
|
| 147 |
+
cache_examples=True
|
| 148 |
)
|
| 149 |
+
|
| 150 |
+
detect_button.click(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
fn=process_image,
|
| 152 |
+
inputs=[input_image, conf_slider],
|
| 153 |
+
outputs=[output_image, plate_output, helmet_output]
|
| 154 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
+
return demo
|
| 157 |
+
|
| 158 |
+
if __name__ == "__main__":
|
| 159 |
+
try:
|
| 160 |
+
logger.info("Starting application...")
|
| 161 |
+
demo = create_interface()
|
| 162 |
+
demo.queue()
|
| 163 |
+
demo.launch(
|
| 164 |
+
server_name="0.0.0.0",
|
| 165 |
+
server_port=7860,
|
| 166 |
+
debug=True
|
| 167 |
+
)
|
| 168 |
+
except Exception as e:
|
| 169 |
+
logger.error(f"Failed to start application: {str(e)}")
|
| 170 |
+
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
|