Download app.py from roundb/Web: direct link, hf CLI and curl.
- Browser
- Download file 19.8 kB
-
https://huggingface.co/spaces/roundb/Web/resolve/main/app.py
- Command line
-
hf download hf://spaces/roundb/Web/app.py
-
curl -L -o app.py https://huggingface.co/spaces/roundb/Web/resolve/main/app.py
19.8 kB
| # app_demo.py — DEMO (somente interface Gradio, sem executar IA/processamento) | |
| # Requisitos: gradio>=4.26.0 | |
| # | |
| # Este app: | |
| # - Mantém a mesma ideia das 5 abas (GPX → Frames → Segmentação → Resize → Inferência) | |
| # - NÃO usa torch/cv2/transformers/pandas/exiftool | |
| # - Gera arquivos “mock” (GPX/ZIP/CSV/GEOJSON) só para download e para a UI ficar funcional | |
| import os | |
| import json | |
| import time | |
| import zipfile | |
| import tempfile | |
| from datetime import datetime | |
| import gradio as gr | |
| STATE = {} # guarda caminhos dos “artefatos” demo | |
| # ------------------------- | |
| # Helpers (gera arquivos falsos) | |
| # ------------------------- | |
| def _tmpdir(prefix="demo_"): | |
| return tempfile.mkdtemp(prefix=prefix) | |
| def _write_text(path, text, encoding="utf-8"): | |
| os.makedirs(os.path.dirname(path), exist_ok=True) | |
| with open(path, "w", encoding=encoding) as f: | |
| f.write(text) | |
| def _create_dummy_gpx(out_path: str, track_name="demo_track"): | |
| gpx = f"""<?xml version="1.0" encoding="UTF-8"?> | |
| <gpx version="1.1" creator="DEMO - Gradio" xmlns="http://www.topografix.com/GPX/1/1"> | |
| <metadata> | |
| <name>{track_name}</name> | |
| <time>{datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")}</time> | |
| </metadata> | |
| <trk> | |
| <name>{track_name}</name> | |
| <trkseg> | |
| <trkpt lat="38.722252" lon="-9.139337"><time>{datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")}</time></trkpt> | |
| <trkpt lat="38.722300" lon="-9.139200"><time>{datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")}</time></trkpt> | |
| <trkpt lat="38.722380" lon="-9.139050"><time>{datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")}</time></trkpt> | |
| </trkseg> | |
| </trk> | |
| </gpx> | |
| """ | |
| _write_text(out_path, gpx) | |
| def _create_dummy_zip(out_path: str, kind="frames"): | |
| """ | |
| kind: | |
| - "frames": zip com 3 jpg “fake” | |
| - "segmentacao": zip com pastas class_6_road, class_11_sidewalk, class_9_grass e jpg “fake” | |
| - "224": zip com as mesmas pastas, mas “redimensionadas” | |
| """ | |
| tmp = _tmpdir("demo_zip_") | |
| if kind == "frames": | |
| files = ["frame_000000_lat_38.722252_lon_-9.139337.jpg", | |
| "frame_000030_lat_38.722300_lon_-9.139200.jpg", | |
| "frame_000060_lat_38.722380_lon_-9.139050.jpg"] | |
| for name in files: | |
| _write_text(os.path.join(tmp, name), "DEMO IMAGE BYTES PLACEHOLDER\n") | |
| else: | |
| mapping = { | |
| "class_6_road": ["img_001_class_6_road.jpg", "img_002_class_6_road.jpg"], | |
| "class_11_sidewalk": ["img_003_class_11_sidewalk.jpg"], | |
| "class_9_grass": ["img_004_class_9_grass.jpg"], | |
| } | |
| for folder, imgs in mapping.items(): | |
| folder_path = os.path.join(tmp, folder) | |
| os.makedirs(folder_path, exist_ok=True) | |
| for img in imgs: | |
| _write_text(os.path.join(folder_path, img), f"DEMO {kind} PLACEHOLDER\n") | |
| # incluir um csv fake no zip (no caso de segmentacao/224) | |
| _write_text(os.path.join(tmp, "resultados_segmentacao.csv"), | |
| "imagem,classe_id,classe_nome,latitude,longitude,pixels_classe,pixels_totais,proporcao_classe_%\n" | |
| "img_001_class_6_road.jpg,6,road,38.722252,-9.139337,12345,50176,24.60\n") | |
| # zipar | |
| with zipfile.ZipFile(out_path, "w", zipfile.ZIP_DEFLATED) as zf: | |
| for root, _, files in os.walk(tmp): | |
| for f in files: | |
| full = os.path.join(root, f) | |
| arc = os.path.relpath(full, tmp) | |
| zf.write(full, arc) | |
| def _create_dummy_csv_and_geojson(out_dir: str, classe: str): | |
| csv_path = os.path.join(out_dir, f"inferencia_{classe}_vit.csv") | |
| geojson_path = os.path.join(out_dir, f"inferencia_{classe}_vit.geojson") | |
| csv_text = ( | |
| "imagem,classe_predita,confianca,latitude,longitude,timestamp\n" | |
| f"img_001_{classe}.jpg,{classe},0.91,38.722252,-9.139337,{datetime.utcnow().isoformat()}\n" | |
| f"img_002_{classe}.jpg,{classe},0.88,38.722300,-9.139200,{datetime.utcnow().isoformat()}\n" | |
| ) | |
| _write_text(csv_path, csv_text) | |
| geo = { | |
| "type": "FeatureCollection", | |
| "features": [ | |
| { | |
| "type": "Feature", | |
| "geometry": {"type": "Point", "coordinates": [-9.139337, 38.722252]}, | |
| "properties": {"imagem": f"img_001_{classe}.jpg", "classe_predita": classe, "confianca": 0.91} | |
| }, | |
| { | |
| "type": "Feature", | |
| "geometry": {"type": "Point", "coordinates": [-9.139200, 38.722300]}, | |
| "properties": {"imagem": f"img_002_{classe}.jpg", "classe_predita": classe, "confianca": 0.88} | |
| }, | |
| ], | |
| } | |
| _write_text(geojson_path, json.dumps(geo, indent=2, ensure_ascii=False)) | |
| return csv_path, geojson_path | |
| # ------------------------- | |
| # Aba 1 — DEMO GPX | |
| # ------------------------- | |
| def aba1_demo_extrair_gpx(video_file, exiftool_path, progress=gr.Progress()): | |
| logs = [] | |
| def log(msg): | |
| logs.append(msg) | |
| progress(0.2, desc=msg) | |
| if not video_file: | |
| log("❌ DEMO: Nenhum vídeo selecionado.") | |
| return None, "\n".join(logs) | |
| # Só para simular | |
| log("🎬 DEMO: Recebi um vídeo (não será processado).") | |
| time.sleep(0.2) | |
| log("🛰️ DEMO: Simulando extração de telemetria...") | |
| time.sleep(0.2) | |
| out_dir = _tmpdir("demo_gpx_") | |
| base = "demo_video" | |
| out_gpx = os.path.join(out_dir, f"{base}.gpx") | |
| _create_dummy_gpx(out_gpx, track_name=base) | |
| STATE["gpx_path"] = out_gpx | |
| log("✅ DEMO: GPX gerado com sucesso (arquivo mock).") | |
| progress(1.0, desc="Concluído!") | |
| return out_gpx, "\n".join(logs) | |
| # ------------------------- | |
| # Aba 2 — DEMO Frames ZIP | |
| # ------------------------- | |
| def aba2_demo_extrair_frames(video_file, gpx_file, frame_interval, progress=gr.Progress()): | |
| logs = [] | |
| def log(msg): | |
| logs.append(msg) | |
| if not video_file: | |
| log("❌ DEMO: Nenhum vídeo selecionado.") | |
| return None, "\n".join(logs) | |
| if not gpx_file: | |
| log("❌ DEMO: Nenhum GPX selecionado.") | |
| return None, "\n".join(logs) | |
| progress(0.2, desc="DEMO: Simulando extração de frames...") | |
| time.sleep(0.2) | |
| zip_path = os.path.join(tempfile.gettempdir(), "frames_georreferenciados_DEMO.zip") | |
| _create_dummy_zip(zip_path, kind="frames") | |
| STATE["frames_zip"] = zip_path | |
| log(f"✅ DEMO: ZIP de frames gerado (mock). Intervalo solicitado: {frame_interval}") | |
| progress(1.0, desc="Concluído!") | |
| return zip_path, "\n".join(logs) | |
| # ------------------------- | |
| # Aba 3 — DEMO Segmentação ZIP + CSV | |
| # ------------------------- | |
| def aba3_demo_segmentacao(zip_file, batch_size, progress=gr.Progress()): | |
| logs = [] | |
| def log(msg): | |
| logs.append(msg) | |
| if not zip_file: | |
| log("❌ DEMO: Nenhum ZIP selecionado.") | |
| return None, None, "\n".join(logs) | |
| progress(0.2, desc="DEMO: Carregando modelo (fake)...") | |
| time.sleep(0.2) | |
| progress(0.5, desc="DEMO: Segmentando imagens (fake)...") | |
| time.sleep(0.2) | |
| out_dir = _tmpdir("demo_seg_") | |
| csv_path = os.path.join(out_dir, "resultados_segmentacao.csv") | |
| _write_text(csv_path, | |
| "imagem,classe_id,classe_nome,latitude,longitude,pixels_classe,pixels_totais,proporcao_classe_%\n" | |
| "img_001_class_6_road.jpg,6,road,38.722252,-9.139337,12345,50176,24.60\n" | |
| "img_003_class_11_sidewalk.jpg,11,sidewalk,38.722300,-9.139200,8000,50176,15.94\n" | |
| "img_004_class_9_grass.jpg,9,grass,38.722380,-9.139050,6000,50176,11.96\n") | |
| zip_output = os.path.join(tempfile.gettempdir(), "segmentacao_classes_DEMO.zip") | |
| _create_dummy_zip(zip_output, kind="segmentacao") | |
| STATE["segmentacao_zip"] = zip_output | |
| log(f"✅ DEMO: Segmentação concluída (mock). Batch solicitado: {batch_size}") | |
| progress(1.0, desc="Concluído!") | |
| return zip_output, csv_path, "\n".join(logs) | |
| # ------------------------- | |
| # Aba 4 — DEMO Resize 224 ZIP + Manifest CSV | |
| # ------------------------- | |
| def aba4_demo_redimensionar(zip_file, progress=gr.Progress()): | |
| logs = [] | |
| def log(msg): | |
| logs.append(msg) | |
| if not zip_file: | |
| log("❌ DEMO: Nenhum ZIP selecionado.") | |
| return None, None, "\n".join(logs) | |
| progress(0.3, desc="DEMO: Redimensionando para 224×224 (fake)...") | |
| time.sleep(0.2) | |
| out_dir = _tmpdir("demo_224_") | |
| csv_path = os.path.join(out_dir, "manifest_224x224.csv") | |
| _write_text(csv_path, | |
| "original_path,output_path,latitude,longitude,size\n" | |
| "class_6_road/img_001_class_6_road.jpg,class_6_road/img_001_class_6_road.jpg,38.722252,-9.139337,224x224\n" | |
| "class_11_sidewalk/img_003_class_11_sidewalk.jpg,class_11_sidewalk/img_003_class_11_sidewalk.jpg,38.722300,-9.139200,224x224\n" | |
| "class_9_grass/img_004_class_9_grass.jpg,class_9_grass/img_004_class_9_grass.jpg,38.722380,-9.139050,224x224\n") | |
| zip_output = os.path.join(tempfile.gettempdir(), "segmentacao_224x224_DEMO.zip") | |
| _create_dummy_zip(zip_output, kind="224") | |
| STATE["zip_224"] = zip_output | |
| log("✅ DEMO: ZIP 224×224 gerado (mock).") | |
| progress(1.0, desc="Concluído!") | |
| return zip_output, csv_path, "\n".join(logs) | |
| # ------------------------- | |
| # Aba 5 — DEMO Preparar ZIPs por classe | |
| # ------------------------- | |
| def aba5_demo_preparar_zips(zip_file_224, progress=gr.Progress()): | |
| logs = [] | |
| def log(msg): | |
| logs.append(msg) | |
| if not zip_file_224: | |
| log("❌ DEMO: Nenhum ZIP 224×224 selecionado.") | |
| return "\n".join(logs), None, None, None, gr.update(choices=[]) | |
| progress(0.4, desc="DEMO: Preparando ZIPs por classe (fake)...") | |
| time.sleep(0.2) | |
| # Criar 3 zips mock | |
| zip_paths = {} | |
| for classe in ("road", "sidewalk", "grass"): | |
| zp = os.path.join(tempfile.gettempdir(), f"{classe}_224x224_DEMO.zip") | |
| _create_dummy_zip(zp, kind="224") | |
| zip_paths[classe] = zp | |
| STATE["class_zips"] = zip_paths | |
| log("✅ DEMO: ZIPs separados por classe prontos (mock).") | |
| progress(1.0, desc="Concluído!") | |
| choices = list(zip_paths.keys()) | |
| return ( | |
| "\n".join(logs), | |
| zip_paths.get("road"), | |
| zip_paths.get("sidewalk"), | |
| zip_paths.get("grass"), | |
| gr.update(choices=choices, value=choices[0] if choices else None), | |
| ) | |
| # ------------------------- | |
| # Aba 5 — DEMO Inferência (gera CSV + GeoJSON) | |
| # ------------------------- | |
| def aba5_demo_inferencia(classe_selecionada, model_file, metadata_file, progress=gr.Progress()): | |
| logs = [] | |
| def log(msg): | |
| logs.append(msg) | |
| if not classe_selecionada: | |
| log("❌ DEMO: Nenhuma classe selecionada.") | |
| return None, None, "\n".join(logs) | |
| progress(0.3, desc="DEMO: Carregando modelo ViT (fake)...") | |
| time.sleep(0.2) | |
| progress(0.6, desc="DEMO: Inferindo (fake)...") | |
| time.sleep(0.2) | |
| out_dir = _tmpdir("demo_infer_") | |
| csv_path, geojson_path = _create_dummy_csv_and_geojson(out_dir, classe_selecionada) | |
| log("✅ DEMO: Inferência concluída (mock).") | |
| log(f"📄 CSV: {os.path.basename(csv_path)}") | |
| log(f"🗺️ GeoJSON: {os.path.basename(geojson_path)}") | |
| progress(1.0, desc="Concluído!") | |
| return csv_path, geojson_path, "\n".join(logs) | |
| # ------------------------- | |
| # Interface | |
| # ------------------------- | |
| def create_interface(): | |
| with gr.Blocks(title="Processador de Vídeos (DEMO)", theme=gr.themes.Soft()) as app: | |
| gr.Markdown( | |
| """ | |
| # 🗺️ ROUNDB - Processador de Vídeos - IA (DEMO) | |
| ✅ **Este é um DEMO de interface.** | |
| - Não executa IA, não usa ExifTool, não processa vídeo. | |
| - Os botões geram **arquivos “mock”** para download (GPX/ZIP/CSV/GeoJSON) e logs para demonstrar o fluxo. | |
| **Fluxo sugerido:** Aba 1 → 2 → 3 → 4 → 5 | |
| """ | |
| ) | |
| with gr.Tabs(): | |
| # -------- Aba 1 | |
| with gr.Tab("1️⃣ Extração de GPX (DEMO)"): | |
| gr.Markdown("## 📍 Extrator de GPX (DEMO)") | |
| with gr.Row(): | |
| with gr.Column(): | |
| video_input_1 = gr.File(label="📹 Vídeo", file_types=["video"], type="filepath") | |
| exiftool_input_1 = gr.Textbox( | |
| label="🔧 Caminho do ExifTool (opcional, DEMO)", | |
| placeholder="C:/exiftool", | |
| value="", | |
| ) | |
| btn1 = gr.Button("🚀 Extrair GPX (DEMO)", variant="primary") | |
| with gr.Column(): | |
| log1 = gr.Textbox(label="📋 Log", lines=16, interactive=False) | |
| gpx_out = gr.File(label="📥 Download do GPX (mock)") | |
| btn1.click( | |
| fn=aba1_demo_extrair_gpx, | |
| inputs=[video_input_1, exiftool_input_1], | |
| outputs=[gpx_out, log1], | |
| ) | |
| # -------- Aba 2 | |
| with gr.Tab("2️⃣ Frames Georreferenciados (DEMO)"): | |
| gr.Markdown("## 🎬 Extrator de Frames (DEMO)") | |
| with gr.Row(): | |
| with gr.Column(): | |
| video_input_2 = gr.File(label="📹 Vídeo (mesmo da Aba 1)", file_types=["video"], type="filepath") | |
| gpx_input_2 = gr.File(label="🗺️ GPX (gerado na Aba 1)", file_types=[".gpx"], type="filepath") | |
| frame_interval = gr.Slider(1, 300, value=30, step=1, label="📸 Intervalo de Frames (DEMO)") | |
| btn2 = gr.Button("🚀 Extrair Frames (DEMO)", variant="primary") | |
| with gr.Column(): | |
| log2 = gr.Textbox(label="📋 Log", lines=16, interactive=False) | |
| frames_zip = gr.File(label="📥 Download (ZIP frames mock)") | |
| gpx_out.change(fn=lambda v, g: (v, g), inputs=[video_input_1, gpx_out], outputs=[video_input_2, gpx_input_2]) | |
| btn2.click( | |
| fn=aba2_demo_extrair_frames, | |
| inputs=[video_input_2, gpx_input_2, frame_interval], | |
| outputs=[frames_zip, log2], | |
| ) | |
| # -------- Aba 3 | |
| with gr.Tab("3️⃣ Segmentação (ADE20K) (DEMO)"): | |
| gr.Markdown("## 🤖 Segmentação Semântica (DEMO)") | |
| with gr.Row(): | |
| with gr.Column(): | |
| zip_in_3 = gr.File(label="📦 ZIP de frames (Aba 2)", file_types=[".zip"], type="filepath") | |
| batch = gr.Slider(1, 16, value=4, step=1, label="📊 Batch size (DEMO)") | |
| btn3 = gr.Button("🚀 Processar Segmentação (DEMO)", variant="primary") | |
| with gr.Column(): | |
| log3 = gr.Textbox(label="📋 Log", lines=16, interactive=False) | |
| zip_out_3 = gr.File(label="📥 ZIP (segmentação mock)") | |
| csv_out_3 = gr.File(label="📊 CSV (mock)") | |
| frames_zip.change(fn=lambda x: x, inputs=[frames_zip], outputs=[zip_in_3]) | |
| btn3.click( | |
| fn=aba3_demo_segmentacao, | |
| inputs=[zip_in_3, batch], | |
| outputs=[zip_out_3, csv_out_3, log3], | |
| ) | |
| # -------- Aba 4 | |
| with gr.Tab("4️⃣ Redimensionar 224×224 (DEMO)"): | |
| gr.Markdown("## 🧰 Redimensionar para 224×224 (DEMO)") | |
| with gr.Row(): | |
| with gr.Column(): | |
| zip_in_4 = gr.File(label="📦 ZIP da Aba 3", file_types=[".zip"], type="filepath") | |
| btn4 = gr.Button("🚀 Redimensionar (DEMO)", variant="primary") | |
| with gr.Column(): | |
| log4 = gr.Textbox(label="📋 Log", lines=16, interactive=False) | |
| zip_out_4 = gr.File(label="📥 ZIP 224×224 (mock)") | |
| csv_out_4 = gr.File(label="📊 Manifest CSV (mock)") | |
| zip_out_3.change(fn=lambda x: x, inputs=[zip_out_3], outputs=[zip_in_4]) | |
| btn4.click( | |
| fn=aba4_demo_redimensionar, | |
| inputs=[zip_in_4], | |
| outputs=[zip_out_4, csv_out_4, log4], | |
| ) | |
| # -------- Aba 5 | |
| with gr.Tab("5️⃣ Inferência (ViT) (DEMO)"): | |
| gr.Markdown( | |
| """ | |
| ## 🧪 Inferência com ViT (DEMO) | |
| **Passo 1:** Preparar ZIPs por classe (mock) | |
| **Passo 2:** Selecionar classe e gerar CSV/GeoJSON (mock) | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("### 📦 Passo 1: Preparar ZIPs por Classe (DEMO)") | |
| zip_in_5 = gr.File(label="📦 ZIP 224×224 (Aba 4)", file_types=[".zip"], type="filepath") | |
| btn5_prep = gr.Button("🔧 Preparar ZIPs (DEMO)", variant="secondary") | |
| with gr.Column(): | |
| log5_prep = gr.Textbox(label="📋 Log Preparação", lines=8, interactive=False) | |
| road_zip = gr.File(label="🛣️ Road ZIP (mock)", visible=False) | |
| sidewalk_zip = gr.File(label="🚶 Sidewalk ZIP (mock)", visible=False) | |
| grass_zip = gr.File(label="🌱 Grass ZIP (mock)", visible=False) | |
| zip_out_4.change(fn=lambda x: x, inputs=[zip_out_4], outputs=[zip_in_5]) | |
| gr.Markdown("---") | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("### 🧠 Passo 2: Executar Inferência (DEMO)") | |
| classe_dd = gr.Dropdown(label="🎯 Selecione a Classe", choices=[], value=None, interactive=True) | |
| model_in = gr.File(label="🧠 Modelo ViT (.pth) (opcional, ignorado no DEMO)", file_types=[".pth"], type="filepath") | |
| meta_in = gr.File(label="📄 metadata.json (opcional, ignorado no DEMO)", file_types=[".json"], type="filepath") | |
| btn5_inf = gr.Button("🚀 Executar Inferência (DEMO)", variant="primary") | |
| with gr.Column(): | |
| log5_inf = gr.Textbox(label="📋 Log Inferência", lines=12, interactive=False) | |
| csv_out_5 = gr.File(label="📊 CSV Resultados (mock)") | |
| geo_out_5 = gr.File(label="🗺️ GeoJSON (mock)") | |
| btn5_prep.click( | |
| fn=aba5_demo_preparar_zips, | |
| inputs=[zip_in_5], | |
| outputs=[log5_prep, road_zip, sidewalk_zip, grass_zip, classe_dd], | |
| ) | |
| btn5_inf.click( | |
| fn=aba5_demo_inferencia, | |
| inputs=[classe_dd, model_in, meta_in], | |
| outputs=[csv_out_5, geo_out_5, log5_inf], | |
| ) | |
| gr.Markdown( | |
| """ | |
| --- | |
| ### 📖 Observação | |
| Este Space é um **DEMO de interface**. Se você quiser a versão “real” (processamento + segmentação + inferência), | |
| aí sim entra torch/transformers/opencv/exiftool e (idealmente) Docker. | |
| """ | |
| ) | |
| return app | |
| if __name__ == "__main__": | |
| app = create_interface() | |
| app.launch(server_name="0.0.0.0", server_port=7860, share=False, show_error=True) | |