File size: 4,459 Bytes
0e84db0
 
 
 
 
0681bc1
 
68b4dc7
55cf4c8
 
 
d747e47
 
 
 
 
 
 
55cf4c8
 
d747e47
 
55cf4c8
e9869ef
0681bc1
 
 
 
 
d747e47
0e84db0
0681bc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9869ef
 
0e84db0
 
 
 
0681bc1
9964097
 
 
0681bc1
 
 
 
 
9964097
d747e47
0e84db0
0681bc1
e9869ef
 
0e84db0
e9869ef
0e84db0
f211c6a
e9869ef
 
0681bc1
0e84db0
 
e9869ef
 
 
0e84db0
55cf4c8
0681bc1
55cf4c8
 
 
 
0681bc1
55cf4c8
d747e47
 
0e84db0
 
 
 
 
 
 
 
 
 
 
 
e9869ef
0e84db0
 
 
e9869ef
 
0e84db0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e358d04
 
0e84db0
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""
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)