Spaces:
Sleeping
Sleeping
Commit ·
f5f630b
1
Parent(s): 1f97573
feat(ui): integrate auth into main app with multi-project tabs
Browse files- Renamed create_app to build_demo_app (project-specific validation UI)
- Created new create_app that returns auth-integrated wrapper
- Added tabs: Login → Project Selection → Admin → Validation
- Session state management across tabs
- Project-based context propagation
- Admin panel with project and user management
- Backward compatible with existing demo app structure
All 74 tests passing
- src/ui/app_factory.py +241 -3
src/ui/app_factory.py
CHANGED
|
@@ -5,12 +5,16 @@ from pathlib import Path
|
|
| 5 |
from typing import Protocol
|
| 6 |
|
| 7 |
from src.cache.ephemeral_cache_manager import EphemeralCacheManager
|
| 8 |
-
from src.domain.models import Detection
|
| 9 |
from src.repositories.append_only_validation_repository import AppendOnlyValidationRepository, OptimisticLockError
|
| 10 |
from src.repositories.in_memory_detection_repository import InMemoryDetectionRepository
|
| 11 |
from src.services.audio_fetch_service import AudioFetchService
|
| 12 |
from src.services.detection_queue_service import DetectionQueueService
|
| 13 |
from src.services.validation_service import ValidationService
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
class _AudioFetchResultProtocol(Protocol):
|
|
@@ -665,8 +669,15 @@ def _batch_reapply_all_pending(
|
|
| 665 |
return status, "", None, refreshed_rows, refreshed_page
|
| 666 |
|
| 667 |
|
| 668 |
-
def
|
| 669 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 670 |
service = _seed_service()
|
| 671 |
audio_service = AudioFetchService(EphemeralCacheManager(ttl_seconds=300, max_files=128))
|
| 672 |
validation_base_dir = str(Path(tempfile.gettempdir()) / "birdnet-validator-validations")
|
|
@@ -1178,3 +1189,230 @@ def create_app() -> gr.Blocks:
|
|
| 1178 |
)
|
| 1179 |
|
| 1180 |
return demo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from typing import Protocol
|
| 6 |
|
| 7 |
from src.cache.ephemeral_cache_manager import EphemeralCacheManager
|
| 8 |
+
from src.domain.models import Detection, Project, Role
|
| 9 |
from src.repositories.append_only_validation_repository import AppendOnlyValidationRepository, OptimisticLockError
|
| 10 |
from src.repositories.in_memory_detection_repository import InMemoryDetectionRepository
|
| 11 |
from src.services.audio_fetch_service import AudioFetchService
|
| 12 |
from src.services.detection_queue_service import DetectionQueueService
|
| 13 |
from src.services.validation_service import ValidationService
|
| 14 |
+
from src.auth.auth_service import AuthService
|
| 15 |
+
from src.ui.login_page import create_login_page
|
| 16 |
+
from src.ui.project_selector import create_project_selector
|
| 17 |
+
from src.ui.admin_panel import AdminPanelManager, create_admin_panel
|
| 18 |
|
| 19 |
|
| 20 |
class _AudioFetchResultProtocol(Protocol):
|
|
|
|
| 669 |
return status, "", None, refreshed_rows, refreshed_page
|
| 670 |
|
| 671 |
|
| 672 |
+
def build_demo_app(project_slug: str = "demo-project") -> gr.Blocks:
|
| 673 |
+
"""Build the demo validation app for a given project.
|
| 674 |
+
|
| 675 |
+
Args:
|
| 676 |
+
project_slug: Project identifier (default: demo-project)
|
| 677 |
+
|
| 678 |
+
Returns:
|
| 679 |
+
Gradio Blocks with validation interface
|
| 680 |
+
"""
|
| 681 |
service = _seed_service()
|
| 682 |
audio_service = AudioFetchService(EphemeralCacheManager(ttl_seconds=300, max_files=128))
|
| 683 |
validation_base_dir = str(Path(tempfile.gettempdir()) / "birdnet-validator-validations")
|
|
|
|
| 1189 |
)
|
| 1190 |
|
| 1191 |
return demo
|
| 1192 |
+
|
| 1193 |
+
|
| 1194 |
+
def create_app() -> gr.Blocks:
|
| 1195 |
+
"""Build the BirdNET Validator app with multi-project auth integration.
|
| 1196 |
+
|
| 1197 |
+
Returns multi-tab interface with:
|
| 1198 |
+
- Login tab for user authentication
|
| 1199 |
+
- Project selection for authorized projects
|
| 1200 |
+
- Admin panel for project/user management (admin only)
|
| 1201 |
+
- Validation interface for selected project
|
| 1202 |
+
|
| 1203 |
+
Returns:
|
| 1204 |
+
Gradio Blocks with full auth-integrated app
|
| 1205 |
+
"""
|
| 1206 |
+
# Initialize auth service
|
| 1207 |
+
auth_service = AuthService(session_ttl_minutes=120)
|
| 1208 |
+
|
| 1209 |
+
# Setup demo users (in production: database/LDAP/OAuth)
|
| 1210 |
+
auth_service.register_user_project_access(
|
| 1211 |
+
"admin_user",
|
| 1212 |
+
{"kenya-2024": Role.admin, "nairobi-2023": Role.admin},
|
| 1213 |
+
)
|
| 1214 |
+
auth_service.register_user_project_access(
|
| 1215 |
+
"validator_demo",
|
| 1216 |
+
{"dem o-project": Role.validator, "kenya-2024": Role.validator},
|
| 1217 |
+
)
|
| 1218 |
+
auth_service.register_user_project_access(
|
| 1219 |
+
"validator_other",
|
| 1220 |
+
{"nairobi-2023": Role.validator},
|
| 1221 |
+
)
|
| 1222 |
+
|
| 1223 |
+
# Initialize admin panel manager
|
| 1224 |
+
admin_manager = AdminPanelManager(auth_service)
|
| 1225 |
+
|
| 1226 |
+
# Register projects
|
| 1227 |
+
admin_manager.register_project(
|
| 1228 |
+
Project(
|
| 1229 |
+
project_slug="kenya-2024",
|
| 1230 |
+
name="Kenya Survey 2024",
|
| 1231 |
+
dataset_repo_id="birdnet/kenya-2024-dataset",
|
| 1232 |
+
active=True,
|
| 1233 |
+
)
|
| 1234 |
+
)
|
| 1235 |
+
admin_manager.register_project(
|
| 1236 |
+
Project(
|
| 1237 |
+
project_slug="nairobi-2023",
|
| 1238 |
+
name="Nairobi Survey 2023",
|
| 1239 |
+
dataset_repo_id="birdnet/nairobi-2023-dataset",
|
| 1240 |
+
active=True,
|
| 1241 |
+
)
|
| 1242 |
+
)
|
| 1243 |
+
admin_manager.register_project(
|
| 1244 |
+
Project(
|
| 1245 |
+
project_slug="demo-project",
|
| 1246 |
+
name="Demo Project",
|
| 1247 |
+
dataset_repo_id="birdnet/demo-dataset",
|
| 1248 |
+
active=True,
|
| 1249 |
+
)
|
| 1250 |
+
)
|
| 1251 |
+
|
| 1252 |
+
with gr.Blocks(title="BirdNET Validator HF - Multi-Project") as wrapper:
|
| 1253 |
+
gr.Markdown("# BirdNET Validator HF - Sprint 4: Segurança Multi-Projeto")
|
| 1254 |
+
gr.Markdown("**Versão com autenticação, autorização por projeto, e painel admin**")
|
| 1255 |
+
|
| 1256 |
+
# Session state
|
| 1257 |
+
session_state = gr.State(value=None)
|
| 1258 |
+
selected_project_state = gr.State(value=None)
|
| 1259 |
+
|
| 1260 |
+
with gr.Tabs():
|
| 1261 |
+
# ===== TAB 1: Login =====
|
| 1262 |
+
with gr.Tab("🔐 Login", id="login_tab"):
|
| 1263 |
+
login_block, username_input, session_output, login_button, error_message = (
|
| 1264 |
+
create_login_page(auth_service)
|
| 1265 |
+
)
|
| 1266 |
+
|
| 1267 |
+
# Store session ID when login succeeds
|
| 1268 |
+
def handle_login_success(session_id: str):
|
| 1269 |
+
"""Process successful login and store session."""
|
| 1270 |
+
if session_id:
|
| 1271 |
+
return auth_service.get_session(session_id)
|
| 1272 |
+
return None
|
| 1273 |
+
|
| 1274 |
+
session_output.change(
|
| 1275 |
+
fn=handle_login_success,
|
| 1276 |
+
inputs=[session_output],
|
| 1277 |
+
outputs=[session_state],
|
| 1278 |
+
)
|
| 1279 |
+
|
| 1280 |
+
# ===== TAB 2: Project Selection =====
|
| 1281 |
+
with gr.Tab("📁 Selecionar Projeto", id="project_tab"):
|
| 1282 |
+
project_info_display = gr.Markdown(
|
| 1283 |
+
value="⚠️ Faça login primeiro na aba **Login**"
|
| 1284 |
+
)
|
| 1285 |
+
project_selector = gr.Dropdown(
|
| 1286 |
+
choices=[],
|
| 1287 |
+
label="Projeto Autorizado",
|
| 1288 |
+
interactive=False,
|
| 1289 |
+
)
|
| 1290 |
+
|
| 1291 |
+
def update_project_selector(session):
|
| 1292 |
+
"""Update project dropdown when user logs in."""
|
| 1293 |
+
if session is None:
|
| 1294 |
+
return (
|
| 1295 |
+
gr.Dropdown(choices=[], interactive=False),
|
| 1296 |
+
"❌ Not logged in. Please login first.",
|
| 1297 |
+
)
|
| 1298 |
+
|
| 1299 |
+
return create_project_selector(auth_service, session)
|
| 1300 |
+
|
| 1301 |
+
session_state.change(
|
| 1302 |
+
fn=update_project_selector,
|
| 1303 |
+
inputs=[session_state],
|
| 1304 |
+
outputs=[project_selector, project_info_display],
|
| 1305 |
+
)
|
| 1306 |
+
|
| 1307 |
+
def update_selected_project(selected: str, session):
|
| 1308 |
+
"""Update state when project is selected."""
|
| 1309 |
+
if session and selected:
|
| 1310 |
+
return selected
|
| 1311 |
+
return None
|
| 1312 |
+
|
| 1313 |
+
project_selector.change(
|
| 1314 |
+
fn=update_selected_project,
|
| 1315 |
+
inputs=[project_selector, session_state],
|
| 1316 |
+
outputs=[selected_project_state],
|
| 1317 |
+
)
|
| 1318 |
+
|
| 1319 |
+
# ===== TAB 3: Admin Panel =====
|
| 1320 |
+
with gr.Tab("⚙️ Admin", id="admin_tab"):
|
| 1321 |
+
admin_info = gr.Markdown(value="⚠️ Faça login primeiro")
|
| 1322 |
+
|
| 1323 |
+
def create_admin_display(session):
|
| 1324 |
+
"""Show admin panel or access denied message."""
|
| 1325 |
+
if session is None:
|
| 1326 |
+
return "❌ **Not Logged In** — Please login first in the Login tab."
|
| 1327 |
+
if session.role.value != "admin":
|
| 1328 |
+
return "❌ **Access Denied** — Only administrators can access this panel."
|
| 1329 |
+
return f"✅ **Admin Panel** — Welcome {session.username}! Click below to manage projects and users."
|
| 1330 |
+
|
| 1331 |
+
session_state.change(
|
| 1332 |
+
fn=create_admin_display,
|
| 1333 |
+
inputs=[session_state],
|
| 1334 |
+
outputs=[admin_info],
|
| 1335 |
+
)
|
| 1336 |
+
|
| 1337 |
+
# Admin controls (always rendered, but backend enforces access)
|
| 1338 |
+
with gr.Group():
|
| 1339 |
+
gr.Markdown("#### Projetos Cadastrados")
|
| 1340 |
+
projects_table = gr.Dataframe(
|
| 1341 |
+
value=admin_manager.list_projects(),
|
| 1342 |
+
headers=["project_slug", "name", "dataset_repo_id", "active"],
|
| 1343 |
+
interactive=False,
|
| 1344 |
+
)
|
| 1345 |
+
refresh_projects_btn = gr.Button("🔄 Atualizar Lista")
|
| 1346 |
+
refresh_projects_btn.click(
|
| 1347 |
+
fn=lambda: admin_manager.list_projects(),
|
| 1348 |
+
outputs=[projects_table],
|
| 1349 |
+
)
|
| 1350 |
+
|
| 1351 |
+
with gr.Group():
|
| 1352 |
+
gr.Markdown("#### Assignar Usuário a Projeto")
|
| 1353 |
+
with gr.Row():
|
| 1354 |
+
admin_username = gr.Textbox(
|
| 1355 |
+
label="Usuário", placeholder="validator_001"
|
| 1356 |
+
)
|
| 1357 |
+
admin_project = gr.Dropdown(
|
| 1358 |
+
choices=[p["project_slug"] for p in admin_manager.list_projects()],
|
| 1359 |
+
label="Projeto",
|
| 1360 |
+
)
|
| 1361 |
+
admin_role = gr.Dropdown(
|
| 1362 |
+
choices=["admin", "validator"],
|
| 1363 |
+
value="validator",
|
| 1364 |
+
label="Role",
|
| 1365 |
+
)
|
| 1366 |
+
|
| 1367 |
+
admin_message = gr.Markdown()
|
| 1368 |
+
|
| 1369 |
+
def assign_user(username: str, project: str, role: str):
|
| 1370 |
+
success, msg = admin_manager.assign_user_to_project(
|
| 1371 |
+
username, project, role
|
| 1372 |
+
)
|
| 1373 |
+
return msg
|
| 1374 |
+
|
| 1375 |
+
assign_btn = gr.Button("✅ Assignar", variant="primary")
|
| 1376 |
+
assign_btn.click(
|
| 1377 |
+
fn=assign_user,
|
| 1378 |
+
inputs=[admin_username, admin_project, admin_role],
|
| 1379 |
+
outputs=[admin_message],
|
| 1380 |
+
)
|
| 1381 |
+
|
| 1382 |
+
# ===== TAB 4: Validation =====
|
| 1383 |
+
with gr.Tab("✓ Validação", id="validation_tab"):
|
| 1384 |
+
validation_status = gr.Markdown(
|
| 1385 |
+
value="ℹ️ Faça login e selecione um projeto para começar"
|
| 1386 |
+
)
|
| 1387 |
+
|
| 1388 |
+
def get_validation_status(session, selected_project):
|
| 1389 |
+
"""Show status message based on login/project state."""
|
| 1390 |
+
if session is None:
|
| 1391 |
+
return "❌ **Não autenticado** — Faça login na aba **Login** primeiro"
|
| 1392 |
+
if selected_project is None:
|
| 1393 |
+
return f"⚠️ **Projeto não selecionado** — Selecione um projeto na aba **Selecionar Projeto**"
|
| 1394 |
+
return f"✅ **Pronto para validar** — Projeto: **{selected_project}** | Usuário: **{session.username}**\n\n(Validação será carregada abaixo)"
|
| 1395 |
+
|
| 1396 |
+
session_state.change(
|
| 1397 |
+
fn=lambda s, p: get_validation_status(s, p),
|
| 1398 |
+
inputs=[session_state, selected_project_state],
|
| 1399 |
+
outputs=[validation_status],
|
| 1400 |
+
)
|
| 1401 |
+
|
| 1402 |
+
selected_project_state.change(
|
| 1403 |
+
fn=lambda s, p: get_validation_status(s, p),
|
| 1404 |
+
inputs=[session_state, selected_project_state],
|
| 1405 |
+
outputs=[validation_status],
|
| 1406 |
+
)
|
| 1407 |
+
|
| 1408 |
+
# Note: In a real implementation, we would load build_demo_app(selected_project) here
|
| 1409 |
+
# For now, we show a placeholder since Gradio tabs don't support dynamic nested Blocks
|
| 1410 |
+
gr.Markdown("---")
|
| 1411 |
+
validation_placeholder = gr.Textbox(
|
| 1412 |
+
label="Validação",
|
| 1413 |
+
value="📋 Interface de validação será carregada aqui para o projeto selecionado",
|
| 1414 |
+
interactive=False,
|
| 1415 |
+
lines=10,
|
| 1416 |
+
)
|
| 1417 |
+
|
| 1418 |
+
return wrapper
|