mustafa2ak's picture
Update app.py
e32a780 verified
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,
add_debug,
dump_exif_tags,
)
import tempfile
detector = RoadsideDetector()
def process_image(image_input, use_gps=True):
if not image_input:
return None, None, "ℹ️ Lütfen bir fotoğraf yükleyin!", None, "📊 Henüz istatistik yok"
# --- Görüntüyü dosya yoluna çevir ---
if isinstance(image_input, str):
image_path = image_input
elif 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:
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
temp_file.write(image_input.read())
temp_file.flush()
image_path = temp_file.name
# --- YOLO tespiti ---
image = Image.open(image_path)
detections = detector.detect_items(image)
annotated = detector.draw_boxes(image, detections)
severity = detector.calculate_severity(detections)
# --- GPS verisi ---
gps_data = {"coords": None, "address": None}
gps_message = ""
if use_gps:
try:
gps_data = extract_gps_from_image(image_path)
if gps_data.get("coords") and gps_data["coords"] != (0.0, 0.0):
gps_message = f"📍 Konum: {gps_data['coords']}"
else:
gps_message = (
"ℹ️ Fotoğrafta konum bilgisi bulunamadı."
)
except Exception:
gps_message = (
"ℹ️ Konum bilgisi okunamadı. Lütfen tekrar deneyin."
)
# EXIF dump debug log
exif_dump = dump_exif_tags(image_path)
add_debug("📸 RAW EXIF:\n" + exif_dump)
# --- Tespiti kaydet ---
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)
# --- Harita + istatistik ---
history = load_detection_history()
map_html = create_detection_map(history)
stats = generate_statistics()
stats_text = format_statistics_text(stats)
return (
annotated,
None, # download file path eklenecek
f"📊 Öncelik seviyesi: {severity}\n📦 Tespit edilen nesne sayısı: {len(detections)}\n{gps_message}",
map_html,
stats_text,
)
def create_interface():
# Custom CSS to change the drop zone text to Turkish
custom_css = """
/* Hide the original English text */
.image-container .wrap .wrap-inner.svelte-1sbaa03 span[data-testid="block-info"] {
visibility: hidden;
}
/* Add Turkish text */
.image-container .wrap .wrap-inner.svelte-1sbaa03::after {
content: 'Buraya sürükleyin veya tıklayın';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #999;
font-size: 1.2em;
pointer-events: none;
}
/* Alternative styling for the upload area */
.image-container {
position: relative;
}
"""
with gr.Blocks(title="Çöp kutusu, taşan çöp ve açıkta bırakılan çöp tespiti", css=custom_css) as demo:
gr.Markdown(
"## 🚮 Çöp kutusu, taşan çöp ve açıkta bırakılan çöp tespiti\n"
"Bu uygulama yol kenarındaki **çöp kutularını**, **taşan çöpleri** ve **açıkta bırakılan çöpleri** tespit eder.\n\n"
"🗺️ **Özellikler:**\n"
"- Çöp kutusu ve taşan çöp tespiti yapar.\n"
"- Tespit edilen konumları ve çöp yoğunluğunu harita üzerinde gösterir.\n"
"- Toplanan verileri istatistiksel olarak raporlar.\n\n"
)
with gr.Tabs():
with gr.TabItem("📸 Çek / Yükle ve Tespit Et"):
with gr.Row():
with gr.Column():
input_img = gr.Image(
type="filepath",
label="📷 Kamera ile Çek veya 📁 Dosyadan Yükle",
sources=["upload", "webcam"],
mirror_webcam=False # Fix for flipped camera image
)
gps_toggle = gr.Checkbox("📍 GPS Verisini Kullan", value=True)
detect_btn = gr.Button("🔍 Tespit Et", variant="primary")
with gr.Column():
out_img = gr.Image(label="📊 Tespit Sonucu", type="pil")
download_file = gr.File(label="⬇️ Sonucu Dosya Olarak İndir")
summary = gr.Textbox(label="📝 Özet", lines=6)
with gr.TabItem("🗺️ Harita"):
map_display = gr.HTML("<p>🗺️ Henüz tespit yok</p>")
with gr.TabItem("📊 İstatistikler"):
stats_display = gr.Markdown("📊 Henüz istatistik yok")
# process and prepare file for download
def process_and_prepare(image_input, use_gps):
annotated, _, text, map_html, stats_text = process_image(image_input, use_gps)
if annotated is None:
return None, None, None, None, None
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
annotated.save(temp_file.name, format="JPEG")
return annotated, temp_file.name, text, map_html, stats_text
detect_btn.click(
process_and_prepare,
inputs=[input_img, gps_toggle],
outputs=[out_img, download_file, summary, map_display, stats_display],
)
gr.Markdown(
"- Fotoğraf çekerken konum servisinizin açık olduğundan emin olun.\n"
"- Bazı tarayıcılar kamera ve dosyadan yüklenen fotoğrafın konum bilgisini silebilir.\n\n"
"📂 **Kaynak kodlara 'Files' dosyası üzerinden ulaşabilirsiniz.**\n\n"
)
return demo
if __name__ == "__main__":
app = create_interface()
# Enable HTTPS for camera access
app.launch(
server_name="0.0.0.0",
server_port=7860,
ssl_verify=False, # Allows self-signed certificates
share=True # Creates a public HTTPS link via Gradio
)