mustafa2ak's picture
Update app.py
0681bc1 verified
raw
history blame
4.46 kB
"""
app.py - Hugging Face Gradio App
"""
import os
import tempfile
import gradio as gr
from PIL import Image
from datetime import datetime
from detector import RoadsideDetector
from utils import (
extract_gps_from_image,
save_detection_to_history,
load_detection_history,
create_detection_map,
generate_statistics,
format_statistics_text,
get_debug_messages,
add_debug, # โœ… include this
)
detector = RoadsideDetector()
def process_image(image_input, use_gps=True):
if not image_input:
return None, "โŒ Please upload an image!", None, "๐Ÿ“Š No statistics yet", ""
# --- 1๏ธโƒฃ Normalize input: ensure we have a file path ---
if isinstance(image_input, str):
# Desktop: already a file path
image_path = image_input
else:
# Mobile/web: BytesIO or PIL.Image -> save to a temp file
if isinstance(image_input, Image.Image):
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
image_input.save(temp_file.name, format="JPEG")
image_path = temp_file.name
else:
# e.g. BytesIO
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
temp_file.write(image_input.read())
temp_file.flush()
image_path = temp_file.name
add_debug(f"โœ… Using image file: {image_path}")
# --- 2๏ธโƒฃ Load image for YOLO detection ---
image = Image.open(image_path)
detections = detector.detect_items(image)
annotated = detector.draw_boxes(image, detections)
severity = detector.calculate_severity(detections)
# --- 3๏ธโƒฃ GPS extraction ---
gps_data = {"coords": None, "address": None}
if use_gps:
try:
gps_data = extract_gps_from_image(image_path)
if gps_data.get("coords"):
add_debug(f"โœ… GPS extracted: {gps_data['coords']}")
else:
add_debug("โš  No GPS data found")
except Exception as e:
add_debug(f"โŒ GPS extraction failed: {e}")
# --- 4๏ธโƒฃ Save detection to history ---
detection_entry = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"count": len(detections),
"severity": severity,
"gps": gps_data,
}
save_detection_to_history(detection_entry)
# --- 5๏ธโƒฃ Map + stats ---
history = load_detection_history()
map_html = create_detection_map(history)
stats = generate_statistics()
stats_text = format_statistics_text(stats)
debug_log = get_debug_messages()
return (
annotated,
f"๐Ÿ” Severity: {severity}\n๐Ÿ“ฆ Items: {len(detections)}"
+ (f"\n๐Ÿ“ GPS: {gps_data['coords']}" if gps_data.get("coords") else "\n๐Ÿ“ No GPS/location data available"),
map_html,
stats_text,
debug_log,
)
def create_interface():
with gr.Blocks(title="๐Ÿšฎ RoadsideClean") as demo:
gr.Markdown("# ๐Ÿšฎ RoadsideClean - Illegal Dumping Detector")
with gr.Tabs():
with gr.TabItem("๐Ÿ“ธ Detect"):
with gr.Row():
with gr.Column():
input_img = gr.Image(
type="filepath",
label="๐Ÿ“ท Take/Upload Photo",
sources=["upload", "webcam"],
)
gps_toggle = gr.Checkbox("๐Ÿ“ Extract GPS", value=True)
detect_btn = gr.Button("๐Ÿ” Detect", variant="primary")
with gr.Column():
out_img = gr.Image(label="Detection Results", type="pil")
summary = gr.Textbox(label="Summary", lines=6)
with gr.TabItem("๐Ÿ—บ๏ธ Map"):
map_display = gr.HTML("<p>๐Ÿ—บ๏ธ No detections yet</p>")
with gr.TabItem("๐Ÿ“Š Statistics"):
stats_display = gr.Markdown("๐Ÿ“Š No statistics yet")
with gr.TabItem("๐Ÿž Debug"):
debug_output = gr.Textbox(label="Debug Logs", lines=12)
detect_btn.click(
process_image,
inputs=[input_img, gps_toggle],
outputs=[out_img, summary, map_display, stats_display, debug_output],
)
return demo
if __name__ == "__main__":
app = create_interface()
app.launch(server_name="0.0.0.0", server_port=7860)