Spaces:
Sleeping
Sleeping
Commit ·
75d15f3
1
Parent(s): 4a9f781
feat(ui): implement audio loading and cache cleanup functionality in Gradio app
Browse files- README.md +1 -0
- src/ui/app_factory.py +101 -1
- tests/unit/test_app_factory_audio_helpers.py +79 -0
README.md
CHANGED
|
@@ -50,3 +50,4 @@ Estrutura base criada por projeto/dataset:
|
|
| 50 |
- Sprint 1: CLI create-project, sync-audio, build-index, verify-project
|
| 51 |
- Sprint 2 (inicial): fila paginada de deteccoes com filtros basicos em demo local Gradio
|
| 52 |
- Sprint 2 (backend): AudioFetchService com download sob demanda por audio_id + cache efemero com cleanup pos-validacao
|
|
|
|
|
|
| 50 |
- Sprint 1: CLI create-project, sync-audio, build-index, verify-project
|
| 51 |
- Sprint 2 (inicial): fila paginada de deteccoes com filtros basicos em demo local Gradio
|
| 52 |
- Sprint 2 (backend): AudioFetchService com download sob demanda por audio_id + cache efemero com cleanup pos-validacao
|
| 53 |
+
- Sprint 2 (UI): carregar audio da deteccao selecionada e limpar cache apos validacao
|
src/ui/app_factory.py
CHANGED
|
@@ -1,10 +1,25 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
|
|
|
|
| 3 |
from src.domain.models import Detection
|
| 4 |
from src.repositories.in_memory_detection_repository import InMemoryDetectionRepository
|
|
|
|
| 5 |
from src.services.detection_queue_service import DetectionQueueService
|
| 6 |
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
def _seed_service() -> DetectionQueueService:
|
| 9 |
repo = InMemoryDetectionRepository()
|
| 10 |
demo_items = [
|
|
@@ -70,12 +85,65 @@ def _page_to_table(service: DetectionQueueService, page: int, scientific_name: s
|
|
| 70 |
return rows, status, page_obj.page
|
| 71 |
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
def create_app() -> gr.Blocks:
|
| 74 |
service = _seed_service()
|
|
|
|
| 75 |
|
| 76 |
with gr.Blocks(title="BirdNET Validator HF") as demo:
|
| 77 |
gr.Markdown("# BirdNET Validator HF")
|
| 78 |
-
gr.Markdown("Sprint 2
|
|
|
|
|
|
|
| 79 |
|
| 80 |
with gr.Row():
|
| 81 |
species_filter = gr.Textbox(label="Filtro especie", placeholder="Ex: Cyanocorax cyanopogon")
|
|
@@ -92,6 +160,14 @@ def create_app() -> gr.Blocks:
|
|
| 92 |
label="Deteccoes",
|
| 93 |
interactive=False,
|
| 94 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
status = gr.Textbox(label="Status", interactive=False)
|
| 96 |
|
| 97 |
def refresh(page: int, species: str, confidence: float):
|
|
@@ -103,6 +179,13 @@ def create_app() -> gr.Blocks:
|
|
| 103 |
def go_prev(page: int, species: str, confidence: float):
|
| 104 |
return refresh(max(1, page - 1), species, confidence)
|
| 105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
demo.load(
|
| 107 |
fn=refresh,
|
| 108 |
inputs=[page_state, species_filter, min_confidence],
|
|
@@ -123,5 +206,22 @@ def create_app() -> gr.Blocks:
|
|
| 123 |
inputs=[page_state, species_filter, min_confidence],
|
| 124 |
outputs=[table, status, page_state],
|
| 125 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
return demo
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from typing import Protocol
|
| 3 |
|
| 4 |
+
from src.cache.ephemeral_cache_manager import EphemeralCacheManager
|
| 5 |
from src.domain.models import Detection
|
| 6 |
from src.repositories.in_memory_detection_repository import InMemoryDetectionRepository
|
| 7 |
+
from src.services.audio_fetch_service import AudioFetchService
|
| 8 |
from src.services.detection_queue_service import DetectionQueueService
|
| 9 |
|
| 10 |
|
| 11 |
+
class _AudioFetchResultProtocol(Protocol):
|
| 12 |
+
cache_key: str
|
| 13 |
+
local_path: str
|
| 14 |
+
source: str
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class _AudioServiceProtocol(Protocol):
|
| 18 |
+
def fetch(self, dataset_repo: str, audio_id: str) -> _AudioFetchResultProtocol: ...
|
| 19 |
+
|
| 20 |
+
def cleanup_after_validation(self, cache_key: str) -> None: ...
|
| 21 |
+
|
| 22 |
+
|
| 23 |
def _seed_service() -> DetectionQueueService:
|
| 24 |
repo = InMemoryDetectionRepository()
|
| 25 |
demo_items = [
|
|
|
|
| 85 |
return rows, status, page_obj.page
|
| 86 |
|
| 87 |
|
| 88 |
+
def _extract_audio_id(rows: object, selected_index: int) -> str:
|
| 89 |
+
normalized_rows: list[list[object]]
|
| 90 |
+
|
| 91 |
+
if hasattr(rows, "values"):
|
| 92 |
+
normalized_rows = [list(item) for item in rows.values.tolist()]
|
| 93 |
+
else:
|
| 94 |
+
normalized_rows = [list(item) for item in rows] if rows else []
|
| 95 |
+
|
| 96 |
+
if not normalized_rows:
|
| 97 |
+
raise ValueError("Nenhuma deteccao carregada na tabela")
|
| 98 |
+
if selected_index < 0 or selected_index >= len(normalized_rows):
|
| 99 |
+
raise ValueError("Selecione uma deteccao valida na tabela")
|
| 100 |
+
|
| 101 |
+
value = normalized_rows[selected_index][1]
|
| 102 |
+
audio_id = str(value).strip()
|
| 103 |
+
if not audio_id:
|
| 104 |
+
raise ValueError("audio_id invalido na deteccao selecionada")
|
| 105 |
+
return audio_id
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _fetch_selected_audio(
|
| 109 |
+
audio_service: _AudioServiceProtocol,
|
| 110 |
+
dataset_repo: str,
|
| 111 |
+
rows: object,
|
| 112 |
+
selected_index: int,
|
| 113 |
+
previous_cache_key: str,
|
| 114 |
+
) -> tuple[str | None, str, str]:
|
| 115 |
+
repo = dataset_repo.strip()
|
| 116 |
+
if not repo:
|
| 117 |
+
return None, "", "Informe dataset repo no formato owner/repo"
|
| 118 |
+
|
| 119 |
+
try:
|
| 120 |
+
audio_id = _extract_audio_id(rows=rows, selected_index=selected_index)
|
| 121 |
+
result = audio_service.fetch(dataset_repo=repo, audio_id=audio_id)
|
| 122 |
+
status = f"Audio carregado ({result.source}) para audio_id={audio_id}"
|
| 123 |
+
return result.local_path, result.cache_key, status
|
| 124 |
+
except Exception as exc:
|
| 125 |
+
if previous_cache_key:
|
| 126 |
+
return None, previous_cache_key, f"Falha ao carregar audio: {exc}"
|
| 127 |
+
return None, "", f"Falha ao carregar audio: {exc}"
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _cleanup_selected_audio(audio_service: _AudioServiceProtocol, cache_key: str) -> tuple[str, str | None]:
|
| 131 |
+
if not cache_key:
|
| 132 |
+
return "Nenhum audio em cache para limpar", None
|
| 133 |
+
|
| 134 |
+
audio_service.cleanup_after_validation(cache_key=cache_key)
|
| 135 |
+
return "Cache de audio limpo apos validacao", None
|
| 136 |
+
|
| 137 |
+
|
| 138 |
def create_app() -> gr.Blocks:
|
| 139 |
service = _seed_service()
|
| 140 |
+
audio_service = AudioFetchService(EphemeralCacheManager(ttl_seconds=300, max_files=128))
|
| 141 |
|
| 142 |
with gr.Blocks(title="BirdNET Validator HF") as demo:
|
| 143 |
gr.Markdown("# BirdNET Validator HF")
|
| 144 |
+
gr.Markdown("Sprint 2: fila paginada + audio sob demanda com cache efemero.")
|
| 145 |
+
|
| 146 |
+
dataset_repo = gr.Textbox(label="Dataset repo", value="SEU_USUARIO/birdnet-projeto-dataset")
|
| 147 |
|
| 148 |
with gr.Row():
|
| 149 |
species_filter = gr.Textbox(label="Filtro especie", placeholder="Ex: Cyanocorax cyanopogon")
|
|
|
|
| 160 |
label="Deteccoes",
|
| 161 |
interactive=False,
|
| 162 |
)
|
| 163 |
+
selected_index = gr.Number(label="Linha selecionada", value=0, precision=0)
|
| 164 |
+
|
| 165 |
+
with gr.Row():
|
| 166 |
+
load_audio_btn = gr.Button("Carregar audio selecionado")
|
| 167 |
+
clear_audio_btn = gr.Button("Limpar cache apos validacao")
|
| 168 |
+
|
| 169 |
+
audio_player = gr.Audio(label="Audio sob demanda", type="filepath")
|
| 170 |
+
cache_key_state = gr.State(value="")
|
| 171 |
status = gr.Textbox(label="Status", interactive=False)
|
| 172 |
|
| 173 |
def refresh(page: int, species: str, confidence: float):
|
|
|
|
| 179 |
def go_prev(page: int, species: str, confidence: float):
|
| 180 |
return refresh(max(1, page - 1), species, confidence)
|
| 181 |
|
| 182 |
+
def on_select(evt):
|
| 183 |
+
if isinstance(evt.index, tuple):
|
| 184 |
+
return int(evt.index[0])
|
| 185 |
+
if isinstance(evt.index, int):
|
| 186 |
+
return int(evt.index)
|
| 187 |
+
return 0
|
| 188 |
+
|
| 189 |
demo.load(
|
| 190 |
fn=refresh,
|
| 191 |
inputs=[page_state, species_filter, min_confidence],
|
|
|
|
| 206 |
inputs=[page_state, species_filter, min_confidence],
|
| 207 |
outputs=[table, status, page_state],
|
| 208 |
)
|
| 209 |
+
table.select(fn=on_select, inputs=None, outputs=[selected_index])
|
| 210 |
+
load_audio_btn.click(
|
| 211 |
+
fn=lambda repo, rows, idx, cache_key: _fetch_selected_audio(
|
| 212 |
+
audio_service=audio_service,
|
| 213 |
+
dataset_repo=repo,
|
| 214 |
+
rows=rows,
|
| 215 |
+
selected_index=int(idx),
|
| 216 |
+
previous_cache_key=cache_key,
|
| 217 |
+
),
|
| 218 |
+
inputs=[dataset_repo, table, selected_index, cache_key_state],
|
| 219 |
+
outputs=[audio_player, cache_key_state, status],
|
| 220 |
+
)
|
| 221 |
+
clear_audio_btn.click(
|
| 222 |
+
fn=lambda cache_key: _cleanup_selected_audio(audio_service=audio_service, cache_key=cache_key),
|
| 223 |
+
inputs=[cache_key_state],
|
| 224 |
+
outputs=[status, audio_player],
|
| 225 |
+
)
|
| 226 |
|
| 227 |
return demo
|
tests/unit/test_app_factory_audio_helpers.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
|
| 6 |
+
from src.ui.app_factory import _cleanup_selected_audio, _extract_audio_id, _fetch_selected_audio
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@dataclass
|
| 10 |
+
class FakeFetchResult:
|
| 11 |
+
cache_key: str
|
| 12 |
+
local_path: str
|
| 13 |
+
source: str
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class FakeAudioService:
|
| 17 |
+
def __init__(self) -> None:
|
| 18 |
+
self.cleaned: list[str] = []
|
| 19 |
+
|
| 20 |
+
def fetch(self, dataset_repo: str, audio_id: str) -> FakeFetchResult:
|
| 21 |
+
_ = dataset_repo
|
| 22 |
+
return FakeFetchResult(cache_key=f"key:{audio_id}", local_path=f"/tmp/{audio_id}.wav", source="remote")
|
| 23 |
+
|
| 24 |
+
def cleanup_after_validation(self, cache_key: str) -> None:
|
| 25 |
+
self.cleaned.append(cache_key)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_extract_audio_id_from_list_rows() -> None:
|
| 29 |
+
rows = [["k1", "audio_01", "sp", 0.9, 0.0, 1.0]]
|
| 30 |
+
assert _extract_audio_id(rows, 0) == "audio_01"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_extract_audio_id_from_dataframe_rows() -> None:
|
| 34 |
+
frame = pd.DataFrame([["k1", "audio_02", "sp", 0.9, 0.0, 1.0]])
|
| 35 |
+
assert _extract_audio_id(frame, 0) == "audio_02"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_fetch_selected_audio_success() -> None:
|
| 39 |
+
service = FakeAudioService()
|
| 40 |
+
rows = [["k1", "audio_03", "sp", 0.9, 0.0, 1.0]]
|
| 41 |
+
|
| 42 |
+
path, cache_key, status = _fetch_selected_audio(
|
| 43 |
+
audio_service=service,
|
| 44 |
+
dataset_repo="org/dataset",
|
| 45 |
+
rows=rows,
|
| 46 |
+
selected_index=0,
|
| 47 |
+
previous_cache_key="",
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
assert path == "/tmp/audio_03.wav"
|
| 51 |
+
assert cache_key == "key:audio_03"
|
| 52 |
+
assert "Audio carregado" in status
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_fetch_selected_audio_validates_repo() -> None:
|
| 56 |
+
service = FakeAudioService()
|
| 57 |
+
rows = [["k1", "audio_03", "sp", 0.9, 0.0, 1.0]]
|
| 58 |
+
|
| 59 |
+
path, cache_key, status = _fetch_selected_audio(
|
| 60 |
+
audio_service=service,
|
| 61 |
+
dataset_repo=" ",
|
| 62 |
+
rows=rows,
|
| 63 |
+
selected_index=0,
|
| 64 |
+
previous_cache_key="old-key",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
assert path is None
|
| 68 |
+
assert cache_key == ""
|
| 69 |
+
assert "Informe dataset repo" in status
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_cleanup_selected_audio() -> None:
|
| 73 |
+
service = FakeAudioService()
|
| 74 |
+
|
| 75 |
+
status, player_value = _cleanup_selected_audio(service, "key:audio_03")
|
| 76 |
+
|
| 77 |
+
assert "Cache de audio limpo" in status
|
| 78 |
+
assert player_value is None
|
| 79 |
+
assert service.cleaned == ["key:audio_03"]
|