Spaces:
Sleeping
Sleeping
Commit ·
e37709f
1
Parent(s): b17d8d1
feat: add HF token auth, invite lifecycle, and project token controls
Browse files- src/auth/auth_service.py +266 -7
- src/config/runtime_config.py +14 -0
- src/domain/models.py +3 -0
- src/services/audio_fetch_service.py +42 -5
- src/ui/admin_panel.py +51 -0
- src/ui/app_factory.py +522 -38
- src/ui/login_page.py +15 -3
- tests/unit/test_app_factory_audio_helpers.py +4 -0
- tests/unit/test_auth_service.py +96 -0
src/auth/auth_service.py
CHANGED
|
@@ -5,6 +5,8 @@ from datetime import UTC, datetime, timedelta
|
|
| 5 |
from typing import Dict, List, Optional
|
| 6 |
import uuid
|
| 7 |
|
|
|
|
|
|
|
| 8 |
from src.domain.models import Role, User
|
| 9 |
|
| 10 |
|
|
@@ -28,6 +30,7 @@ class Session:
|
|
| 28 |
created_at: datetime
|
| 29 |
last_activity: datetime
|
| 30 |
expires_at: datetime
|
|
|
|
| 31 |
|
| 32 |
def is_expired(self) -> bool:
|
| 33 |
"""Check if session has expired."""
|
|
@@ -39,18 +42,45 @@ class Session:
|
|
| 39 |
self.expires_at = datetime.now(UTC) + timedelta(minutes=ttl_minutes)
|
| 40 |
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
class AuthService:
|
| 43 |
"""Manages user authentication, sessions, and project access control."""
|
| 44 |
|
| 45 |
-
def __init__(self, session_ttl_minutes: int = 120):
|
| 46 |
"""Initialize AuthService with session TTL.
|
| 47 |
|
| 48 |
Args:
|
| 49 |
session_ttl_minutes: Session time-to-live in minutes (default: 2 hours)
|
| 50 |
"""
|
| 51 |
self.session_ttl_minutes = session_ttl_minutes
|
|
|
|
| 52 |
self._sessions: Dict[str, Session] = {} # session_id -> Session
|
| 53 |
self._user_access: Dict[str, UserProjectAccess] = {} # username -> UserProjectAccess
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
def register_user_project_access(
|
| 56 |
self, username: str, project_access: Dict[str, Role]
|
|
@@ -126,19 +156,37 @@ class AuthService:
|
|
| 126 |
Returns:
|
| 127 |
Session if user exists and is active, None otherwise
|
| 128 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
if username not in self._user_access:
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
access = self._user_access[username]
|
| 133 |
if not access.is_active:
|
| 134 |
return None
|
| 135 |
|
| 136 |
# Determine highest role across all projects (admin > validator)
|
| 137 |
-
role = Role.validator
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
|
|
|
| 142 |
|
| 143 |
session_id = str(uuid.uuid4())
|
| 144 |
now = datetime.now(UTC)
|
|
@@ -150,11 +198,42 @@ class AuthService:
|
|
| 150 |
created_at=now,
|
| 151 |
last_activity=now,
|
| 152 |
expires_at=now + timedelta(minutes=self.session_ttl_minutes),
|
|
|
|
| 153 |
)
|
| 154 |
|
| 155 |
self._sessions[session_id] = session
|
| 156 |
return session
|
| 157 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
def get_session(self, session_id: str) -> Optional[Session]:
|
| 159 |
"""Retrieve an active session by ID.
|
| 160 |
|
|
@@ -239,6 +318,26 @@ class AuthService:
|
|
| 239 |
for sid in expired:
|
| 240 |
self._sessions.pop(sid)
|
| 241 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
def set_user_active(self, username: str, active: bool) -> None:
|
| 243 |
"""Enable or disable a user account.
|
| 244 |
|
|
@@ -248,3 +347,163 @@ class AuthService:
|
|
| 248 |
"""
|
| 249 |
if username in self._user_access:
|
| 250 |
self._user_access[username].is_active = active
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from typing import Dict, List, Optional
|
| 6 |
import uuid
|
| 7 |
|
| 8 |
+
from huggingface_hub import HfApi
|
| 9 |
+
|
| 10 |
from src.domain.models import Role, User
|
| 11 |
|
| 12 |
|
|
|
|
| 30 |
created_at: datetime
|
| 31 |
last_activity: datetime
|
| 32 |
expires_at: datetime
|
| 33 |
+
hf_token: str | None = None
|
| 34 |
|
| 35 |
def is_expired(self) -> bool:
|
| 36 |
"""Check if session has expired."""
|
|
|
|
| 42 |
self.expires_at = datetime.now(UTC) + timedelta(minutes=ttl_minutes)
|
| 43 |
|
| 44 |
|
| 45 |
+
@dataclass
|
| 46 |
+
class ProjectInvite:
|
| 47 |
+
username: str
|
| 48 |
+
project_slug: str
|
| 49 |
+
role: Role
|
| 50 |
+
invited_by: str
|
| 51 |
+
created_at: datetime
|
| 52 |
+
expires_at: datetime
|
| 53 |
+
|
| 54 |
+
def is_expired(self) -> bool:
|
| 55 |
+
return datetime.now(UTC) > self.expires_at
|
| 56 |
+
|
| 57 |
+
|
| 58 |
class AuthService:
|
| 59 |
"""Manages user authentication, sessions, and project access control."""
|
| 60 |
|
| 61 |
+
def __init__(self, session_ttl_minutes: int = 120, invite_ttl_hours: int = 72):
|
| 62 |
"""Initialize AuthService with session TTL.
|
| 63 |
|
| 64 |
Args:
|
| 65 |
session_ttl_minutes: Session time-to-live in minutes (default: 2 hours)
|
| 66 |
"""
|
| 67 |
self.session_ttl_minutes = session_ttl_minutes
|
| 68 |
+
self.invite_ttl_hours = max(1, int(invite_ttl_hours))
|
| 69 |
self._sessions: Dict[str, Session] = {} # session_id -> Session
|
| 70 |
self._user_access: Dict[str, UserProjectAccess] = {} # username -> UserProjectAccess
|
| 71 |
+
self._pending_invites: Dict[str, Dict[str, ProjectInvite]] = {}
|
| 72 |
+
|
| 73 |
+
def _prune_expired_invites(self) -> None:
|
| 74 |
+
expired_users: list[str] = []
|
| 75 |
+
for username, invites_by_project in self._pending_invites.items():
|
| 76 |
+
expired_projects = [project_slug for project_slug, invite in invites_by_project.items() if invite.is_expired()]
|
| 77 |
+
for project_slug in expired_projects:
|
| 78 |
+
del invites_by_project[project_slug]
|
| 79 |
+
if not invites_by_project:
|
| 80 |
+
expired_users.append(username)
|
| 81 |
+
|
| 82 |
+
for username in expired_users:
|
| 83 |
+
self._pending_invites.pop(username, None)
|
| 84 |
|
| 85 |
def register_user_project_access(
|
| 86 |
self, username: str, project_access: Dict[str, Role]
|
|
|
|
| 156 |
Returns:
|
| 157 |
Session if user exists and is active, None otherwise
|
| 158 |
"""
|
| 159 |
+
return self.login_internal(username=username)
|
| 160 |
+
|
| 161 |
+
def login_internal(
|
| 162 |
+
self,
|
| 163 |
+
username: str,
|
| 164 |
+
hf_token: str | None = None,
|
| 165 |
+
auto_promote_to_admin: bool = False,
|
| 166 |
+
) -> Optional[Session]:
|
| 167 |
if username not in self._user_access:
|
| 168 |
+
if not auto_promote_to_admin:
|
| 169 |
+
self._prune_expired_invites()
|
| 170 |
+
pending_for_user = self._pending_invites.get(username, {})
|
| 171 |
+
if not pending_for_user:
|
| 172 |
+
return None
|
| 173 |
+
self._user_access[username] = UserProjectAccess(
|
| 174 |
+
username=username,
|
| 175 |
+
project_slugs={},
|
| 176 |
+
is_active=True,
|
| 177 |
+
)
|
| 178 |
|
| 179 |
access = self._user_access[username]
|
| 180 |
if not access.is_active:
|
| 181 |
return None
|
| 182 |
|
| 183 |
# Determine highest role across all projects (admin > validator)
|
| 184 |
+
role = Role.admin if auto_promote_to_admin else Role.validator
|
| 185 |
+
if role != Role.admin:
|
| 186 |
+
for proj_role in access.project_slugs.values():
|
| 187 |
+
if proj_role == Role.admin:
|
| 188 |
+
role = Role.admin
|
| 189 |
+
break
|
| 190 |
|
| 191 |
session_id = str(uuid.uuid4())
|
| 192 |
now = datetime.now(UTC)
|
|
|
|
| 198 |
created_at=now,
|
| 199 |
last_activity=now,
|
| 200 |
expires_at=now + timedelta(minutes=self.session_ttl_minutes),
|
| 201 |
+
hf_token=hf_token,
|
| 202 |
)
|
| 203 |
|
| 204 |
self._sessions[session_id] = session
|
| 205 |
return session
|
| 206 |
|
| 207 |
+
def login_with_hf_token(self, token: str) -> tuple[Optional[Session], str]:
|
| 208 |
+
"""Authenticate using Hugging Face personal token and resolve username via whoami."""
|
| 209 |
+
token_value = (token or "").strip()
|
| 210 |
+
if not token_value:
|
| 211 |
+
return None, "❌ Please provide a Hugging Face token"
|
| 212 |
+
|
| 213 |
+
try:
|
| 214 |
+
whoami = HfApi().whoami(token=token_value)
|
| 215 |
+
except Exception:
|
| 216 |
+
return None, "❌ Invalid Hugging Face token or network error"
|
| 217 |
+
|
| 218 |
+
username = str(whoami.get("name") or "").strip()
|
| 219 |
+
if not username:
|
| 220 |
+
return None, "❌ Unable to resolve Hugging Face username from token"
|
| 221 |
+
|
| 222 |
+
is_first_user = len(self._user_access) == 0
|
| 223 |
+
session = self.login_internal(
|
| 224 |
+
username=username,
|
| 225 |
+
hf_token=token_value,
|
| 226 |
+
auto_promote_to_admin=is_first_user,
|
| 227 |
+
)
|
| 228 |
+
if session is None:
|
| 229 |
+
return None, f"❌ User '{username}' is not invited to any project yet"
|
| 230 |
+
|
| 231 |
+
if is_first_user:
|
| 232 |
+
return session, f"✅ Welcome, {username}! (Admin bootstrap)"
|
| 233 |
+
if session.role == Role.admin:
|
| 234 |
+
return session, f"✅ Welcome, {username}! (Admin)"
|
| 235 |
+
return session, f"✅ Welcome, {username}! (Validator)"
|
| 236 |
+
|
| 237 |
def get_session(self, session_id: str) -> Optional[Session]:
|
| 238 |
"""Retrieve an active session by ID.
|
| 239 |
|
|
|
|
| 318 |
for sid in expired:
|
| 319 |
self._sessions.pop(sid)
|
| 320 |
|
| 321 |
+
def refresh_session_authorizations(self, session_id: str) -> Optional[Session]:
|
| 322 |
+
"""Refresh a session with latest role and project assignments."""
|
| 323 |
+
session = self._sessions.get(session_id)
|
| 324 |
+
if session is None:
|
| 325 |
+
return None
|
| 326 |
+
if session.is_expired():
|
| 327 |
+
self._sessions.pop(session_id, None)
|
| 328 |
+
return None
|
| 329 |
+
|
| 330 |
+
access = self._user_access.get(session.username)
|
| 331 |
+
if access is None or not access.is_active:
|
| 332 |
+
self._sessions.pop(session_id, None)
|
| 333 |
+
return None
|
| 334 |
+
|
| 335 |
+
projects = list(access.project_slugs.keys())
|
| 336 |
+
session.authorized_projects = projects
|
| 337 |
+
session.role = Role.admin if any(role == Role.admin for role in access.project_slugs.values()) else Role.validator
|
| 338 |
+
session.update_activity(self.session_ttl_minutes)
|
| 339 |
+
return session
|
| 340 |
+
|
| 341 |
def set_user_active(self, username: str, active: bool) -> None:
|
| 342 |
"""Enable or disable a user account.
|
| 343 |
|
|
|
|
| 347 |
"""
|
| 348 |
if username in self._user_access:
|
| 349 |
self._user_access[username].is_active = active
|
| 350 |
+
|
| 351 |
+
def create_project_invite(
|
| 352 |
+
self,
|
| 353 |
+
username: str,
|
| 354 |
+
project_slug: str,
|
| 355 |
+
role: Role,
|
| 356 |
+
invited_by: str,
|
| 357 |
+
) -> tuple[bool, str]:
|
| 358 |
+
invited_username = (username or "").strip()
|
| 359 |
+
if not invited_username:
|
| 360 |
+
return False, "Username is required"
|
| 361 |
+
|
| 362 |
+
self._prune_expired_invites()
|
| 363 |
+
|
| 364 |
+
user_invites = self._pending_invites.setdefault(invited_username, {})
|
| 365 |
+
if project_slug in user_invites:
|
| 366 |
+
return False, f"Invite for {invited_username} to {project_slug} already exists"
|
| 367 |
+
|
| 368 |
+
now = datetime.now(UTC)
|
| 369 |
+
expires_at = now + timedelta(hours=self.invite_ttl_hours)
|
| 370 |
+
|
| 371 |
+
user_invites[project_slug] = ProjectInvite(
|
| 372 |
+
username=invited_username,
|
| 373 |
+
project_slug=project_slug,
|
| 374 |
+
role=role,
|
| 375 |
+
invited_by=invited_by,
|
| 376 |
+
created_at=now,
|
| 377 |
+
expires_at=expires_at,
|
| 378 |
+
)
|
| 379 |
+
return True, f"✅ Invite sent to {invited_username} for {project_slug} as {role.value} (expires {expires_at.isoformat()})"
|
| 380 |
+
|
| 381 |
+
def list_pending_invites(self, username: str) -> List[ProjectInvite]:
|
| 382 |
+
self._prune_expired_invites()
|
| 383 |
+
invites = list(self._pending_invites.get(username, {}).values())
|
| 384 |
+
invites.sort(key=lambda item: item.created_at)
|
| 385 |
+
return invites
|
| 386 |
+
|
| 387 |
+
def list_all_pending_invites(self) -> List[ProjectInvite]:
|
| 388 |
+
self._prune_expired_invites()
|
| 389 |
+
invites: list[ProjectInvite] = []
|
| 390 |
+
for invites_by_project in self._pending_invites.values():
|
| 391 |
+
invites.extend(invites_by_project.values())
|
| 392 |
+
invites.sort(key=lambda item: item.created_at)
|
| 393 |
+
return invites
|
| 394 |
+
|
| 395 |
+
def accept_project_invite(self, username: str, project_slug: str) -> tuple[bool, str]:
|
| 396 |
+
self._prune_expired_invites()
|
| 397 |
+
pending = self._pending_invites.get(username, {})
|
| 398 |
+
invite = pending.get(project_slug)
|
| 399 |
+
if invite is None:
|
| 400 |
+
return False, f"Invite not found for {username} in {project_slug}"
|
| 401 |
+
|
| 402 |
+
self.upsert_user_project_role(username, project_slug, invite.role)
|
| 403 |
+
del pending[project_slug]
|
| 404 |
+
if not pending:
|
| 405 |
+
self._pending_invites.pop(username, None)
|
| 406 |
+
return True, f"✅ Invite accepted for {project_slug} as {invite.role.value}"
|
| 407 |
+
|
| 408 |
+
def reject_project_invite(self, username: str, project_slug: str) -> tuple[bool, str]:
|
| 409 |
+
self._prune_expired_invites()
|
| 410 |
+
pending = self._pending_invites.get(username, {})
|
| 411 |
+
invite = pending.get(project_slug)
|
| 412 |
+
if invite is None:
|
| 413 |
+
return False, f"Invite not found for {username} in {project_slug}"
|
| 414 |
+
|
| 415 |
+
del pending[project_slug]
|
| 416 |
+
if not pending:
|
| 417 |
+
self._pending_invites.pop(username, None)
|
| 418 |
+
return True, f"✅ Invite rejected for {project_slug}"
|
| 419 |
+
|
| 420 |
+
def accept_all_project_invites(self, username: str) -> tuple[int, int, str]:
|
| 421 |
+
self._prune_expired_invites()
|
| 422 |
+
pending = self._pending_invites.get(username, {})
|
| 423 |
+
if not pending:
|
| 424 |
+
return 0, 0, "No pending invites"
|
| 425 |
+
|
| 426 |
+
accepted = 0
|
| 427 |
+
failed = 0
|
| 428 |
+
for project_slug in list(pending.keys()):
|
| 429 |
+
ok, _ = self.accept_project_invite(username, project_slug)
|
| 430 |
+
if ok:
|
| 431 |
+
accepted += 1
|
| 432 |
+
else:
|
| 433 |
+
failed += 1
|
| 434 |
+
return accepted, failed, f"Accepted {accepted} invites" + (f", {failed} failed" if failed else "")
|
| 435 |
+
|
| 436 |
+
def revoke_project_invite(self, username: str, project_slug: str) -> tuple[bool, str]:
|
| 437 |
+
self._prune_expired_invites()
|
| 438 |
+
pending = self._pending_invites.get(username, {})
|
| 439 |
+
if project_slug not in pending:
|
| 440 |
+
return False, f"Invite not found for {username} in {project_slug}"
|
| 441 |
+
del pending[project_slug]
|
| 442 |
+
if not pending:
|
| 443 |
+
self._pending_invites.pop(username, None)
|
| 444 |
+
return True, f"✅ Invite revoked for {username} in {project_slug}"
|
| 445 |
+
|
| 446 |
+
def export_user_access_map(self, include_inactive: bool = False) -> Dict[str, Dict[str, str]]:
|
| 447 |
+
"""Export user/project role mapping for persistence."""
|
| 448 |
+
exported: Dict[str, Dict[str, str]] = {}
|
| 449 |
+
for username in self.list_usernames(include_inactive=include_inactive):
|
| 450 |
+
access = self._user_access.get(username)
|
| 451 |
+
if access is None:
|
| 452 |
+
continue
|
| 453 |
+
exported[username] = {project_slug: role.value for project_slug, role in access.project_slugs.items()}
|
| 454 |
+
return exported
|
| 455 |
+
|
| 456 |
+
def export_pending_invites_map(self) -> Dict[str, Dict[str, Dict[str, str]]]:
|
| 457 |
+
self._prune_expired_invites()
|
| 458 |
+
payload: Dict[str, Dict[str, Dict[str, str]]] = {}
|
| 459 |
+
for username, invites_by_project in self._pending_invites.items():
|
| 460 |
+
payload[username] = {}
|
| 461 |
+
for project_slug, invite in invites_by_project.items():
|
| 462 |
+
payload[username][project_slug] = {
|
| 463 |
+
"role": invite.role.value,
|
| 464 |
+
"invited_by": invite.invited_by,
|
| 465 |
+
"created_at": invite.created_at.isoformat(),
|
| 466 |
+
"expires_at": invite.expires_at.isoformat(),
|
| 467 |
+
}
|
| 468 |
+
return payload
|
| 469 |
+
|
| 470 |
+
def load_pending_invites_map(self, payload: Dict[str, Dict[str, Dict[str, str]]]) -> None:
|
| 471 |
+
self._pending_invites = {}
|
| 472 |
+
for username, invites_by_project in (payload or {}).items():
|
| 473 |
+
if not isinstance(invites_by_project, dict):
|
| 474 |
+
continue
|
| 475 |
+
user_invites: Dict[str, ProjectInvite] = {}
|
| 476 |
+
for project_slug, invite_payload in invites_by_project.items():
|
| 477 |
+
if not isinstance(invite_payload, dict):
|
| 478 |
+
continue
|
| 479 |
+
role_text = str(invite_payload.get("role", "")).strip().lower()
|
| 480 |
+
if role_text not in {"admin", "validator"}:
|
| 481 |
+
continue
|
| 482 |
+
invited_by = str(invite_payload.get("invited_by", "")).strip() or "admin"
|
| 483 |
+
created_at_raw = str(invite_payload.get("created_at", "")).strip()
|
| 484 |
+
expires_at_raw = str(invite_payload.get("expires_at", "")).strip()
|
| 485 |
+
try:
|
| 486 |
+
created_at = datetime.fromisoformat(created_at_raw) if created_at_raw else datetime.now(UTC)
|
| 487 |
+
except Exception:
|
| 488 |
+
created_at = datetime.now(UTC)
|
| 489 |
+
try:
|
| 490 |
+
expires_at = datetime.fromisoformat(expires_at_raw) if expires_at_raw else (created_at + timedelta(hours=self.invite_ttl_hours))
|
| 491 |
+
except Exception:
|
| 492 |
+
expires_at = created_at + timedelta(hours=self.invite_ttl_hours)
|
| 493 |
+
if created_at.tzinfo is None:
|
| 494 |
+
created_at = created_at.replace(tzinfo=UTC)
|
| 495 |
+
if expires_at.tzinfo is None:
|
| 496 |
+
expires_at = expires_at.replace(tzinfo=UTC)
|
| 497 |
+
user_invites[str(project_slug)] = ProjectInvite(
|
| 498 |
+
username=str(username),
|
| 499 |
+
project_slug=str(project_slug),
|
| 500 |
+
role=Role(role_text),
|
| 501 |
+
invited_by=invited_by,
|
| 502 |
+
created_at=created_at,
|
| 503 |
+
expires_at=expires_at,
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
if user_invites:
|
| 507 |
+
self._pending_invites[str(username)] = user_invites
|
| 508 |
+
|
| 509 |
+
self._prune_expired_invites()
|
src/config/runtime_config.py
CHANGED
|
@@ -11,6 +11,8 @@ class RuntimeConfig:
|
|
| 11 |
page_size: int
|
| 12 |
projects_file_path: str | None
|
| 13 |
user_access_file_path: str | None
|
|
|
|
|
|
|
| 14 |
enable_demo_bootstrap: bool
|
| 15 |
|
| 16 |
@classmethod
|
|
@@ -34,6 +36,16 @@ class RuntimeConfig:
|
|
| 34 |
|
| 35 |
projects_file_path = (os.getenv("BIRDNET_PROJECTS_FILE") or "").strip() or None
|
| 36 |
user_access_file_path = (os.getenv("BIRDNET_USER_ACCESS_FILE") or "").strip() or None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
raw_enable_demo_bootstrap = (os.getenv("BIRDNET_ENABLE_DEMO_BOOTSTRAP") or "").strip().lower()
|
| 39 |
enable_demo_bootstrap = raw_enable_demo_bootstrap in {"1", "true", "yes", "on"}
|
|
@@ -44,5 +56,7 @@ class RuntimeConfig:
|
|
| 44 |
page_size=page_size,
|
| 45 |
projects_file_path=projects_file_path,
|
| 46 |
user_access_file_path=user_access_file_path,
|
|
|
|
|
|
|
| 47 |
enable_demo_bootstrap=enable_demo_bootstrap,
|
| 48 |
)
|
|
|
|
| 11 |
page_size: int
|
| 12 |
projects_file_path: str | None
|
| 13 |
user_access_file_path: str | None
|
| 14 |
+
invites_file_path: str | None
|
| 15 |
+
invite_ttl_hours: int
|
| 16 |
enable_demo_bootstrap: bool
|
| 17 |
|
| 18 |
@classmethod
|
|
|
|
| 36 |
|
| 37 |
projects_file_path = (os.getenv("BIRDNET_PROJECTS_FILE") or "").strip() or None
|
| 38 |
user_access_file_path = (os.getenv("BIRDNET_USER_ACCESS_FILE") or "").strip() or None
|
| 39 |
+
invites_file_path = (os.getenv("BIRDNET_INVITES_FILE") or "").strip() or None
|
| 40 |
+
raw_invite_ttl_hours = (os.getenv("BIRDNET_INVITE_TTL_HOURS") or "").strip()
|
| 41 |
+
invite_ttl_hours = 72
|
| 42 |
+
if raw_invite_ttl_hours:
|
| 43 |
+
try:
|
| 44 |
+
parsed = int(raw_invite_ttl_hours)
|
| 45 |
+
if parsed > 0:
|
| 46 |
+
invite_ttl_hours = parsed
|
| 47 |
+
except ValueError:
|
| 48 |
+
invite_ttl_hours = 72
|
| 49 |
|
| 50 |
raw_enable_demo_bootstrap = (os.getenv("BIRDNET_ENABLE_DEMO_BOOTSTRAP") or "").strip().lower()
|
| 51 |
enable_demo_bootstrap = raw_enable_demo_bootstrap in {"1", "true", "yes", "on"}
|
|
|
|
| 56 |
page_size=page_size,
|
| 57 |
projects_file_path=projects_file_path,
|
| 58 |
user_access_file_path=user_access_file_path,
|
| 59 |
+
invites_file_path=invites_file_path,
|
| 60 |
+
invite_ttl_hours=invite_ttl_hours,
|
| 61 |
enable_demo_bootstrap=enable_demo_bootstrap,
|
| 62 |
)
|
src/domain/models.py
CHANGED
|
@@ -19,6 +19,9 @@ class Project(BaseModel):
|
|
| 19 |
project_slug: str = Field(min_length=3)
|
| 20 |
name: str = Field(min_length=1)
|
| 21 |
dataset_repo_id: str = Field(min_length=3)
|
|
|
|
|
|
|
|
|
|
| 22 |
active: bool = True
|
| 23 |
|
| 24 |
|
|
|
|
| 19 |
project_slug: str = Field(min_length=3)
|
| 20 |
name: str = Field(min_length=1)
|
| 21 |
dataset_repo_id: str = Field(min_length=3)
|
| 22 |
+
visibility: str = Field(default="collaborative", pattern="^(private|collaborative)$")
|
| 23 |
+
owner_username: Optional[str] = None
|
| 24 |
+
dataset_token: Optional[str] = None
|
| 25 |
active: bool = True
|
| 26 |
|
| 27 |
|
src/services/audio_fetch_service.py
CHANGED
|
@@ -24,7 +24,13 @@ class AudioFetchService:
|
|
| 24 |
def __init__(self, cache_manager: EphemeralCacheManager) -> None:
|
| 25 |
self._cache = cache_manager
|
| 26 |
|
| 27 |
-
def fetch(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
cache_key = f"{dataset_repo}:{audio_id}"
|
| 29 |
cached_path = self._cache.get(cache_key)
|
| 30 |
if cached_path:
|
|
@@ -36,7 +42,11 @@ class AudioFetchService:
|
|
| 36 |
return AudioFetchResult(cache_key=cache_key, local_path=str(local_path), source="demo-fallback")
|
| 37 |
|
| 38 |
try:
|
| 39 |
-
target_filename, downloaded_path = self._resolve_remote_filename(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
except FileNotFoundError:
|
| 41 |
if not allow_demo_fallback:
|
| 42 |
raise
|
|
@@ -46,7 +56,11 @@ class AudioFetchService:
|
|
| 46 |
return AudioFetchResult(cache_key=cache_key, local_path=str(local_path), source="demo-fallback")
|
| 47 |
|
| 48 |
if downloaded_path is None:
|
| 49 |
-
downloaded =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
downloaded_path = Path(downloaded)
|
| 51 |
|
| 52 |
suffix = downloaded_path.suffix if downloaded_path.suffix else ".bin"
|
|
@@ -85,7 +99,12 @@ class AudioFetchService:
|
|
| 85 |
def cleanup_after_validation(self, cache_key: str) -> None:
|
| 86 |
self._cache.cleanup_key(cache_key)
|
| 87 |
|
| 88 |
-
def _resolve_remote_filename(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
audio_path = Path(audio_id)
|
| 90 |
if audio_path.suffix:
|
| 91 |
return f"audio/{audio_id}", None
|
|
@@ -93,7 +112,11 @@ class AudioFetchService:
|
|
| 93 |
for extension in SUPPORTED_AUDIO_EXTENSIONS:
|
| 94 |
candidate = f"audio/{audio_id}{extension}"
|
| 95 |
try:
|
| 96 |
-
downloaded =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
return candidate, Path(downloaded)
|
| 98 |
except Exception:
|
| 99 |
continue
|
|
@@ -131,3 +154,17 @@ class AudioFetchService:
|
|
| 131 |
def _is_seeded_demo_audio_id(self, audio_id: str) -> bool:
|
| 132 |
normalized = audio_id.strip().lower()
|
| 133 |
return "_audio_" in normalized and normalized.endswith(("1001", "1002", "1003", "1004"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
def __init__(self, cache_manager: EphemeralCacheManager) -> None:
|
| 25 |
self._cache = cache_manager
|
| 26 |
|
| 27 |
+
def fetch(
|
| 28 |
+
self,
|
| 29 |
+
dataset_repo: str,
|
| 30 |
+
audio_id: str,
|
| 31 |
+
allow_demo_fallback: bool = False,
|
| 32 |
+
hf_token: str | None = None,
|
| 33 |
+
) -> AudioFetchResult:
|
| 34 |
cache_key = f"{dataset_repo}:{audio_id}"
|
| 35 |
cached_path = self._cache.get(cache_key)
|
| 36 |
if cached_path:
|
|
|
|
| 42 |
return AudioFetchResult(cache_key=cache_key, local_path=str(local_path), source="demo-fallback")
|
| 43 |
|
| 44 |
try:
|
| 45 |
+
target_filename, downloaded_path = self._resolve_remote_filename(
|
| 46 |
+
dataset_repo=dataset_repo,
|
| 47 |
+
audio_id=audio_id,
|
| 48 |
+
hf_token=hf_token,
|
| 49 |
+
)
|
| 50 |
except FileNotFoundError:
|
| 51 |
if not allow_demo_fallback:
|
| 52 |
raise
|
|
|
|
| 56 |
return AudioFetchResult(cache_key=cache_key, local_path=str(local_path), source="demo-fallback")
|
| 57 |
|
| 58 |
if downloaded_path is None:
|
| 59 |
+
downloaded = self._download_dataset_file(
|
| 60 |
+
dataset_repo=dataset_repo,
|
| 61 |
+
filename=target_filename,
|
| 62 |
+
hf_token=hf_token,
|
| 63 |
+
)
|
| 64 |
downloaded_path = Path(downloaded)
|
| 65 |
|
| 66 |
suffix = downloaded_path.suffix if downloaded_path.suffix else ".bin"
|
|
|
|
| 99 |
def cleanup_after_validation(self, cache_key: str) -> None:
|
| 100 |
self._cache.cleanup_key(cache_key)
|
| 101 |
|
| 102 |
+
def _resolve_remote_filename(
|
| 103 |
+
self,
|
| 104 |
+
dataset_repo: str,
|
| 105 |
+
audio_id: str,
|
| 106 |
+
hf_token: str | None = None,
|
| 107 |
+
) -> tuple[str, Path | None]:
|
| 108 |
audio_path = Path(audio_id)
|
| 109 |
if audio_path.suffix:
|
| 110 |
return f"audio/{audio_id}", None
|
|
|
|
| 112 |
for extension in SUPPORTED_AUDIO_EXTENSIONS:
|
| 113 |
candidate = f"audio/{audio_id}{extension}"
|
| 114 |
try:
|
| 115 |
+
downloaded = self._download_dataset_file(
|
| 116 |
+
dataset_repo=dataset_repo,
|
| 117 |
+
filename=candidate,
|
| 118 |
+
hf_token=hf_token,
|
| 119 |
+
)
|
| 120 |
return candidate, Path(downloaded)
|
| 121 |
except Exception:
|
| 122 |
continue
|
|
|
|
| 154 |
def _is_seeded_demo_audio_id(self, audio_id: str) -> bool:
|
| 155 |
normalized = audio_id.strip().lower()
|
| 156 |
return "_audio_" in normalized and normalized.endswith(("1001", "1002", "1003", "1004"))
|
| 157 |
+
|
| 158 |
+
def _download_dataset_file(self, dataset_repo: str, filename: str, hf_token: str | None = None) -> str:
|
| 159 |
+
if hf_token:
|
| 160 |
+
return hf_hub_download(
|
| 161 |
+
repo_id=dataset_repo,
|
| 162 |
+
repo_type="dataset",
|
| 163 |
+
filename=filename,
|
| 164 |
+
token=hf_token,
|
| 165 |
+
)
|
| 166 |
+
return hf_hub_download(
|
| 167 |
+
repo_id=dataset_repo,
|
| 168 |
+
repo_type="dataset",
|
| 169 |
+
filename=filename,
|
| 170 |
+
)
|
src/ui/admin_panel.py
CHANGED
|
@@ -46,6 +46,9 @@ class AdminPanelManager:
|
|
| 46 |
"project_slug": p.project_slug,
|
| 47 |
"name": p.name,
|
| 48 |
"dataset_repo_id": p.dataset_repo_id,
|
|
|
|
|
|
|
|
|
|
| 49 |
"active": p.active,
|
| 50 |
}
|
| 51 |
for p in self._projects.values()
|
|
@@ -98,10 +101,58 @@ class AdminPanelManager:
|
|
| 98 |
if role not in ["admin", "validator"]:
|
| 99 |
return False, f"Invalid role: {role}"
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
self.auth_service.upsert_user_project_role(username, project_slug, Role(role))
|
| 102 |
|
| 103 |
return True, f"✅ Assigned {username} to {project_slug} as {role}"
|
| 104 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
def remove_user_from_project(self, username: str, project_slug: str) -> Tuple[bool, str]:
|
| 106 |
"""Remove a user's access to a project.
|
| 107 |
|
|
|
|
| 46 |
"project_slug": p.project_slug,
|
| 47 |
"name": p.name,
|
| 48 |
"dataset_repo_id": p.dataset_repo_id,
|
| 49 |
+
"visibility": p.visibility,
|
| 50 |
+
"owner_username": p.owner_username,
|
| 51 |
+
"dataset_token_set": bool((p.dataset_token or "").strip()),
|
| 52 |
"active": p.active,
|
| 53 |
}
|
| 54 |
for p in self._projects.values()
|
|
|
|
| 101 |
if role not in ["admin", "validator"]:
|
| 102 |
return False, f"Invalid role: {role}"
|
| 103 |
|
| 104 |
+
project = self._projects[project_slug]
|
| 105 |
+
if project.visibility == "private" and project.owner_username and username != project.owner_username:
|
| 106 |
+
return False, "Private projects only allow the owner"
|
| 107 |
+
|
| 108 |
self.auth_service.upsert_user_project_role(username, project_slug, Role(role))
|
| 109 |
|
| 110 |
return True, f"✅ Assigned {username} to {project_slug} as {role}"
|
| 111 |
|
| 112 |
+
def invite_user_to_project(
|
| 113 |
+
self,
|
| 114 |
+
invited_by: str,
|
| 115 |
+
username: str,
|
| 116 |
+
project_slug: str,
|
| 117 |
+
role: str,
|
| 118 |
+
) -> Tuple[bool, str]:
|
| 119 |
+
if project_slug not in self._projects:
|
| 120 |
+
return False, f"Project '{project_slug}' not found"
|
| 121 |
+
|
| 122 |
+
if role not in ["admin", "validator"]:
|
| 123 |
+
return False, f"Invalid role: {role}"
|
| 124 |
+
|
| 125 |
+
project = self._projects[project_slug]
|
| 126 |
+
if project.visibility == "private":
|
| 127 |
+
return False, "Private projects do not accept collaborators"
|
| 128 |
+
|
| 129 |
+
return self.auth_service.create_project_invite(
|
| 130 |
+
username=username,
|
| 131 |
+
project_slug=project_slug,
|
| 132 |
+
role=Role(role),
|
| 133 |
+
invited_by=invited_by,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
def list_pending_invites(self, project_slug: str | None = None) -> List[dict]:
|
| 137 |
+
invites = self.auth_service.list_all_pending_invites()
|
| 138 |
+
rows: list[dict] = []
|
| 139 |
+
for invite in invites:
|
| 140 |
+
if project_slug and invite.project_slug != project_slug:
|
| 141 |
+
continue
|
| 142 |
+
rows.append(
|
| 143 |
+
{
|
| 144 |
+
"username": invite.username,
|
| 145 |
+
"project_slug": invite.project_slug,
|
| 146 |
+
"role": invite.role.value,
|
| 147 |
+
"invited_by": invite.invited_by,
|
| 148 |
+
"expires_at": invite.expires_at.isoformat(),
|
| 149 |
+
}
|
| 150 |
+
)
|
| 151 |
+
return rows
|
| 152 |
+
|
| 153 |
+
def revoke_invite(self, username: str, project_slug: str) -> Tuple[bool, str]:
|
| 154 |
+
return self.auth_service.revoke_project_invite(username=username, project_slug=project_slug)
|
| 155 |
+
|
| 156 |
def remove_user_from_project(self, username: str, project_slug: str) -> Tuple[bool, str]:
|
| 157 |
"""Remove a user's access to a project.
|
| 158 |
|
src/ui/app_factory.py
CHANGED
|
@@ -35,6 +35,7 @@ class _AudioServiceProtocol(Protocol):
|
|
| 35 |
dataset_repo: str,
|
| 36 |
audio_id: str,
|
| 37 |
allow_demo_fallback: bool = False,
|
|
|
|
| 38 |
) -> _AudioFetchResultProtocol: ...
|
| 39 |
|
| 40 |
def cleanup_after_validation(self, cache_key: str) -> None: ...
|
|
@@ -310,6 +311,9 @@ def _load_projects_from_file(projects_file_path: str | None) -> list[Project]:
|
|
| 310 |
project_slug=str(row.get("project_slug", "")).strip(),
|
| 311 |
name=str(row.get("name", "")).strip(),
|
| 312 |
dataset_repo_id=str(row.get("dataset_repo_id", "")).strip(),
|
|
|
|
|
|
|
|
|
|
| 313 |
active=bool(row.get("active", True)),
|
| 314 |
)
|
| 315 |
)
|
|
@@ -344,14 +348,78 @@ def _load_user_access_from_file(user_access_file_path: str | None) -> dict[str,
|
|
| 344 |
if role_text not in {"admin", "validator"}:
|
| 345 |
continue
|
| 346 |
normalized_roles[str(project_slug)] = Role(role_text)
|
| 347 |
-
|
| 348 |
-
result[str(username)] = normalized_roles
|
| 349 |
return result
|
| 350 |
|
| 351 |
|
| 352 |
-
def
|
| 353 |
-
|
| 354 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
|
| 356 |
used_demo_fallback = False
|
| 357 |
if not projects and runtime_config.enable_demo_bootstrap:
|
|
@@ -368,16 +436,18 @@ def _bootstrap_auth_and_projects(auth_service: AuthService, admin_manager: Admin
|
|
| 368 |
for username, access in user_access.items():
|
| 369 |
auth_service.register_user_project_access(username, access)
|
| 370 |
|
|
|
|
|
|
|
| 371 |
if used_demo_fallback:
|
| 372 |
return (
|
| 373 |
"⚠️ Demo bootstrap enabled via BIRDNET_ENABLE_DEMO_BOOTSTRAP. "
|
| 374 |
"Use BIRDNET_PROJECTS_FILE and BIRDNET_USER_ACCESS_FILE for production auth/project setup."
|
| 375 |
)
|
| 376 |
|
| 377 |
-
if not projects
|
| 378 |
return (
|
| 379 |
-
"⚠️ Production bootstrap incomplete.
|
| 380 |
-
"BIRDNET_USER_ACCESS_FILE (or enable demo bootstrap for local testing)."
|
| 381 |
)
|
| 382 |
|
| 383 |
return ""
|
|
@@ -607,6 +677,7 @@ def _fetch_selected_audio(
|
|
| 607 |
selected_index: int,
|
| 608 |
previous_cache_key: str,
|
| 609 |
allow_demo_fallback: bool = False,
|
|
|
|
| 610 |
) -> tuple[str | None, str, str]:
|
| 611 |
repo = dataset_repo.strip()
|
| 612 |
if not repo:
|
|
@@ -619,6 +690,7 @@ def _fetch_selected_audio(
|
|
| 619 |
dataset_repo=repo,
|
| 620 |
audio_id=audio_id,
|
| 621 |
allow_demo_fallback=allow_demo_fallback,
|
|
|
|
| 622 |
)
|
| 623 |
except TypeError:
|
| 624 |
# Backward compatibility for fake/mocked services used in tests.
|
|
@@ -733,6 +805,7 @@ def _fetch_selected_audio_with_spectrogram(
|
|
| 733 |
selected_index: int,
|
| 734 |
previous_cache_key: str,
|
| 735 |
allow_demo_fallback: bool = False,
|
|
|
|
| 736 |
) -> tuple[str | None, str, str, str | None]:
|
| 737 |
audio_path, cache_key, status = _fetch_selected_audio(
|
| 738 |
audio_service=audio_service,
|
|
@@ -741,6 +814,7 @@ def _fetch_selected_audio_with_spectrogram(
|
|
| 741 |
selected_index=selected_index,
|
| 742 |
previous_cache_key=previous_cache_key,
|
| 743 |
allow_demo_fallback=allow_demo_fallback,
|
|
|
|
| 744 |
)
|
| 745 |
spectrogram_path = _build_spectrogram_image(audio_path)
|
| 746 |
if audio_path and spectrogram_path is None:
|
|
@@ -778,6 +852,7 @@ def _autofetch_first_row(
|
|
| 778 |
rows: object,
|
| 779 |
cache_key: str,
|
| 780 |
allow_demo_fallback: bool = False,
|
|
|
|
| 781 |
) -> tuple[int, str | None, str, str, str | None]:
|
| 782 |
normalized_rows = _normalize_rows(rows)
|
| 783 |
if not normalized_rows:
|
|
@@ -790,6 +865,7 @@ def _autofetch_first_row(
|
|
| 790 |
selected_index=0,
|
| 791 |
previous_cache_key=cache_key,
|
| 792 |
allow_demo_fallback=allow_demo_fallback,
|
|
|
|
| 793 |
)
|
| 794 |
return 0, audio_path, updated_cache_key, status, spectrogram_path
|
| 795 |
|
|
@@ -801,6 +877,7 @@ def _select_and_fetch_audio(
|
|
| 801 |
cache_key: str,
|
| 802 |
evt: gr.SelectData,
|
| 803 |
allow_demo_fallback: bool = False,
|
|
|
|
| 804 |
) -> tuple[int, str | None, str, str, str | None]:
|
| 805 |
if isinstance(evt.index, tuple):
|
| 806 |
selected_index = int(evt.index[0])
|
|
@@ -816,6 +893,7 @@ def _select_and_fetch_audio(
|
|
| 816 |
selected_index=selected_index,
|
| 817 |
previous_cache_key=cache_key,
|
| 818 |
allow_demo_fallback=allow_demo_fallback,
|
|
|
|
| 819 |
)
|
| 820 |
return selected_index, audio_path, updated_cache_key, status, spectrogram_path
|
| 821 |
|
|
@@ -882,6 +960,7 @@ def _fetch_selected_audio_with_title(
|
|
| 882 |
selected_index: int,
|
| 883 |
previous_cache_key: str,
|
| 884 |
allow_demo_fallback: bool = False,
|
|
|
|
| 885 |
) -> tuple[str | None, str, str, str | None, str]:
|
| 886 |
audio_path, cache_key, status, spectrogram_path = _fetch_selected_audio_with_spectrogram(
|
| 887 |
audio_service=audio_service,
|
|
@@ -890,6 +969,7 @@ def _fetch_selected_audio_with_title(
|
|
| 890 |
selected_index=selected_index,
|
| 891 |
previous_cache_key=previous_cache_key,
|
| 892 |
allow_demo_fallback=allow_demo_fallback,
|
|
|
|
| 893 |
)
|
| 894 |
return audio_path, cache_key, status, spectrogram_path, _spectrogram_title(audio_path)
|
| 895 |
|
|
@@ -901,6 +981,7 @@ def _select_and_fetch_audio_with_title(
|
|
| 901 |
cache_key: str,
|
| 902 |
evt: gr.SelectData,
|
| 903 |
allow_demo_fallback: bool = False,
|
|
|
|
| 904 |
) -> tuple[int, str | None, str, str, str | None, str]:
|
| 905 |
selected_index, audio_path, updated_cache_key, status, spectrogram_path = _select_and_fetch_audio(
|
| 906 |
audio_service=audio_service,
|
|
@@ -909,6 +990,7 @@ def _select_and_fetch_audio_with_title(
|
|
| 909 |
cache_key=cache_key,
|
| 910 |
evt=evt,
|
| 911 |
allow_demo_fallback=allow_demo_fallback,
|
|
|
|
| 912 |
)
|
| 913 |
return (
|
| 914 |
selected_index,
|
|
@@ -926,6 +1008,7 @@ def _autofetch_first_row_with_title(
|
|
| 926 |
rows: object,
|
| 927 |
cache_key: str,
|
| 928 |
allow_demo_fallback: bool = False,
|
|
|
|
| 929 |
) -> tuple[int, str | None, str, str, str | None, str]:
|
| 930 |
selected_index, audio_path, updated_cache_key, status, spectrogram_path = _autofetch_first_row(
|
| 931 |
audio_service=audio_service,
|
|
@@ -933,6 +1016,7 @@ def _autofetch_first_row_with_title(
|
|
| 933 |
rows=rows,
|
| 934 |
cache_key=cache_key,
|
| 935 |
allow_demo_fallback=allow_demo_fallback,
|
|
|
|
| 936 |
)
|
| 937 |
return (
|
| 938 |
selected_index,
|
|
@@ -951,6 +1035,7 @@ def _advance_to_next_row_with_title(
|
|
| 951 |
selected_index: int,
|
| 952 |
cache_key: str,
|
| 953 |
allow_demo_fallback: bool = False,
|
|
|
|
| 954 |
) -> tuple[int, str | None, str, str, str | None, str]:
|
| 955 |
normalized_rows = _normalize_rows(rows)
|
| 956 |
if not normalized_rows:
|
|
@@ -964,6 +1049,7 @@ def _advance_to_next_row_with_title(
|
|
| 964 |
selected_index=safe_index,
|
| 965 |
previous_cache_key=cache_key,
|
| 966 |
allow_demo_fallback=allow_demo_fallback,
|
|
|
|
| 967 |
)
|
| 968 |
return safe_index, audio_path, updated_cache_key, status, spectrogram_path, _spectrogram_title(audio_path)
|
| 969 |
|
|
@@ -1870,14 +1956,26 @@ def create_app() -> gr.Blocks:
|
|
| 1870 |
Returns:
|
| 1871 |
Gradio Blocks with full auth-integrated app
|
| 1872 |
"""
|
|
|
|
|
|
|
| 1873 |
# Initialize auth service
|
| 1874 |
-
auth_service = AuthService(
|
|
|
|
|
|
|
|
|
|
| 1875 |
|
| 1876 |
# Initialize admin panel manager
|
| 1877 |
admin_manager = AdminPanelManager(auth_service)
|
| 1878 |
|
| 1879 |
-
|
| 1880 |
-
bootstrap_warning = _bootstrap_auth_and_projects(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1881 |
queue_service, seed_warning = _build_detection_repository(
|
| 1882 |
[project["project_slug"] for project in admin_manager.list_projects()],
|
| 1883 |
seed_file_path=runtime_config.detection_seed_path,
|
|
@@ -1906,6 +2004,9 @@ def create_app() -> gr.Blocks:
|
|
| 1906 |
p["project_slug"],
|
| 1907 |
p["name"],
|
| 1908 |
p["dataset_repo_id"],
|
|
|
|
|
|
|
|
|
|
| 1909 |
"yes" if bool(p["active"]) else "no",
|
| 1910 |
]
|
| 1911 |
for p in projects
|
|
@@ -1914,6 +2015,19 @@ def create_app() -> gr.Blocks:
|
|
| 1914 |
def _project_slugs() -> list[str]:
|
| 1915 |
return [p["project_slug"] for p in admin_manager.list_projects()]
|
| 1916 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1917 |
with gr.Tabs():
|
| 1918 |
# ===== TAB 1: Login =====
|
| 1919 |
with gr.Tab("🔐 Login", id="login_tab"):
|
|
@@ -1971,24 +2085,41 @@ def create_app() -> gr.Blocks:
|
|
| 1971 |
label="HF Dataset Repo ID",
|
| 1972 |
placeholder="ex: birdnet/amazonas-2026-dataset",
|
| 1973 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1974 |
|
| 1975 |
create_project_message = gr.Markdown()
|
| 1976 |
|
| 1977 |
-
def create_project(session, slug: str, name: str, repo_id: str):
|
| 1978 |
if session is None or session.role.value != "admin":
|
| 1979 |
-
return "❌ Access denied. Only admin can create projects.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
|
| 1980 |
|
| 1981 |
slug = (slug or "").strip()
|
| 1982 |
name = (name or "").strip()
|
| 1983 |
repo_id = (repo_id or "").strip()
|
|
|
|
|
|
|
| 1984 |
if not slug or not name or not repo_id:
|
| 1985 |
-
return "⚠️ Fill slug, name, and repo id.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
|
|
|
|
|
|
|
| 1986 |
|
| 1987 |
created = admin_manager.register_project(
|
| 1988 |
Project(
|
| 1989 |
project_slug=slug,
|
| 1990 |
name=name,
|
| 1991 |
dataset_repo_id=repo_id,
|
|
|
|
|
|
|
|
|
|
| 1992 |
active=True,
|
| 1993 |
)
|
| 1994 |
)
|
|
@@ -2001,28 +2132,49 @@ def create_app() -> gr.Blocks:
|
|
| 2001 |
gr.update(),
|
| 2002 |
gr.update(),
|
| 2003 |
gr.update(),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2004 |
)
|
| 2005 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2006 |
refreshed_service, refreshed_warning = _build_detection_repository(
|
| 2007 |
_project_slugs(),
|
| 2008 |
seed_file_path=runtime_config.detection_seed_path,
|
| 2009 |
)
|
| 2010 |
service_ref["queue"] = refreshed_service
|
|
|
|
| 2011 |
|
| 2012 |
return (
|
| 2013 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2014 |
_project_rows(),
|
| 2015 |
gr.update(choices=_project_slugs(), value=slug),
|
| 2016 |
gr.update(value=""),
|
| 2017 |
gr.update(value=""),
|
| 2018 |
gr.update(value=""),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2019 |
refreshed_warning,
|
|
|
|
| 2020 |
)
|
| 2021 |
|
| 2022 |
create_project_btn = gr.Button("➕ Create Project", variant="primary")
|
| 2023 |
projects_table = gr.Dataframe(
|
| 2024 |
value=_project_rows(),
|
| 2025 |
-
headers=["project_slug", "name", "dataset_repo_id", "active"],
|
| 2026 |
interactive=False,
|
| 2027 |
)
|
| 2028 |
refresh_projects_btn = gr.Button("🔄 Refresh List")
|
|
@@ -2038,6 +2190,50 @@ def create_app() -> gr.Blocks:
|
|
| 2038 |
outputs=[projects_table],
|
| 2039 |
)
|
| 2040 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2041 |
with gr.Group(visible=False) as admin_users_controls:
|
| 2042 |
gr.Markdown("#### Assign User to Project")
|
| 2043 |
with gr.Row():
|
|
@@ -2055,6 +2251,7 @@ def create_app() -> gr.Blocks:
|
|
| 2055 |
)
|
| 2056 |
|
| 2057 |
admin_message = gr.Markdown()
|
|
|
|
| 2058 |
|
| 2059 |
def assign_user(session, username: str, project: str, role: str):
|
| 2060 |
if session is None or session.role.value != "admin":
|
|
@@ -2063,7 +2260,9 @@ def create_app() -> gr.Blocks:
|
|
| 2063 |
username, project, role
|
| 2064 |
)
|
| 2065 |
if success:
|
| 2066 |
-
|
|
|
|
|
|
|
| 2067 |
return msg, gr.update(), gr.update(), gr.update()
|
| 2068 |
|
| 2069 |
assign_btn = gr.Button("✅ Assign", variant="primary")
|
|
@@ -2073,9 +2272,117 @@ def create_app() -> gr.Blocks:
|
|
| 2073 |
outputs=[admin_message, admin_username, admin_project, admin_role],
|
| 2074 |
)
|
| 2075 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2076 |
create_project_btn.click(
|
| 2077 |
fn=create_project,
|
| 2078 |
-
inputs=[session_state, create_project_slug, create_project_name, create_project_repo],
|
| 2079 |
outputs=[
|
| 2080 |
create_project_message,
|
| 2081 |
projects_table,
|
|
@@ -2083,7 +2390,13 @@ def create_app() -> gr.Blocks:
|
|
| 2083 |
create_project_slug,
|
| 2084 |
create_project_name,
|
| 2085 |
create_project_repo,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2086 |
seed_warning_state,
|
|
|
|
| 2087 |
],
|
| 2088 |
)
|
| 2089 |
|
|
@@ -2109,6 +2422,13 @@ def create_app() -> gr.Blocks:
|
|
| 2109 |
label="Authorized Project",
|
| 2110 |
interactive=False,
|
| 2111 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2112 |
|
| 2113 |
def update_project_selector(session):
|
| 2114 |
"""Update project dropdown when user logs in."""
|
|
@@ -2141,10 +2461,145 @@ def create_app() -> gr.Blocks:
|
|
| 2141 |
dataset_repo_id,
|
| 2142 |
)
|
| 2143 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2144 |
session_state.change(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2145 |
fn=update_project_selector,
|
| 2146 |
inputs=[session_state],
|
| 2147 |
outputs=[project_selector, project_info_display, selected_project_state, selected_dataset_repo_state],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2148 |
)
|
| 2149 |
|
| 2150 |
def update_selected_project(selected: str, session):
|
|
@@ -2352,6 +2807,19 @@ def create_app() -> gr.Blocks:
|
|
| 2352 |
conflict_detection_key_state = gr.State(value="")
|
| 2353 |
report_box = gr.Textbox(label="Report", interactive=False)
|
| 2354 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2355 |
def refresh(
|
| 2356 |
project_slug: str,
|
| 2357 |
page: int,
|
|
@@ -2615,7 +3083,7 @@ def create_app() -> gr.Blocks:
|
|
| 2615 |
updated_map[project_slug] = sorted(project_favs)
|
| 2616 |
return f"Deteccao {detection_key} {action}", updated_map
|
| 2617 |
|
| 2618 |
-
def on_table_select(repo: str, rows: object, cache_key: str, evt: gr.SelectData):
|
| 2619 |
return _select_and_fetch_audio_with_title(
|
| 2620 |
audio_service=audio_service,
|
| 2621 |
dataset_repo=repo,
|
|
@@ -2623,6 +3091,7 @@ def create_app() -> gr.Blocks:
|
|
| 2623 |
cache_key=cache_key,
|
| 2624 |
evt=evt,
|
| 2625 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
|
|
|
| 2626 |
)
|
| 2627 |
|
| 2628 |
refresh_event = refresh_btn.click(
|
|
@@ -2705,33 +3174,35 @@ def create_app() -> gr.Blocks:
|
|
| 2705 |
inputs=[table],
|
| 2706 |
outputs=[validation_summary_cards],
|
| 2707 |
).then(
|
| 2708 |
-
fn=lambda repo, rows, cache_key: _autofetch_first_row_with_title(
|
| 2709 |
audio_service=audio_service,
|
| 2710 |
dataset_repo=repo,
|
| 2711 |
rows=rows,
|
| 2712 |
cache_key=cache_key,
|
| 2713 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
|
|
|
| 2714 |
),
|
| 2715 |
-
inputs=[selected_dataset_repo_state, table, cache_key_state],
|
| 2716 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 2717 |
)
|
| 2718 |
|
| 2719 |
table.select(
|
| 2720 |
fn=on_table_select,
|
| 2721 |
-
inputs=[selected_dataset_repo_state, table, cache_key_state],
|
| 2722 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 2723 |
)
|
| 2724 |
|
| 2725 |
load_audio_btn.click(
|
| 2726 |
-
fn=lambda repo, rows, idx, cache_key: _fetch_selected_audio_with_title(
|
| 2727 |
audio_service=audio_service,
|
| 2728 |
dataset_repo=repo,
|
| 2729 |
rows=rows,
|
| 2730 |
selected_index=int(idx),
|
| 2731 |
previous_cache_key=cache_key,
|
| 2732 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
|
|
|
| 2733 |
),
|
| 2734 |
-
inputs=[selected_dataset_repo_state, table, selected_index, cache_key_state],
|
| 2735 |
outputs=[audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 2736 |
)
|
| 2737 |
clear_audio_btn.click(
|
|
@@ -2749,14 +3220,15 @@ def create_app() -> gr.Blocks:
|
|
| 2749 |
inputs=[table],
|
| 2750 |
outputs=[validation_summary_cards],
|
| 2751 |
).then(
|
| 2752 |
-
fn=lambda repo, rows, cache_key: _autofetch_first_row_with_title(
|
| 2753 |
audio_service=audio_service,
|
| 2754 |
dataset_repo=repo,
|
| 2755 |
rows=rows,
|
| 2756 |
cache_key=cache_key,
|
| 2757 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
|
|
|
| 2758 |
),
|
| 2759 |
-
inputs=[selected_dataset_repo_state, table, cache_key_state],
|
| 2760 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 2761 |
)
|
| 2762 |
next_event.then(
|
|
@@ -2764,14 +3236,15 @@ def create_app() -> gr.Blocks:
|
|
| 2764 |
inputs=[table],
|
| 2765 |
outputs=[validation_summary_cards],
|
| 2766 |
).then(
|
| 2767 |
-
fn=lambda repo, rows, cache_key: _autofetch_first_row_with_title(
|
| 2768 |
audio_service=audio_service,
|
| 2769 |
dataset_repo=repo,
|
| 2770 |
rows=rows,
|
| 2771 |
cache_key=cache_key,
|
| 2772 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
|
|
|
| 2773 |
),
|
| 2774 |
-
inputs=[selected_dataset_repo_state, table, cache_key_state],
|
| 2775 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 2776 |
)
|
| 2777 |
prev_event.then(
|
|
@@ -2779,14 +3252,15 @@ def create_app() -> gr.Blocks:
|
|
| 2779 |
inputs=[table],
|
| 2780 |
outputs=[validation_summary_cards],
|
| 2781 |
).then(
|
| 2782 |
-
fn=lambda repo, rows, cache_key: _autofetch_first_row_with_title(
|
| 2783 |
audio_service=audio_service,
|
| 2784 |
dataset_repo=repo,
|
| 2785 |
rows=rows,
|
| 2786 |
cache_key=cache_key,
|
| 2787 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
|
|
|
| 2788 |
),
|
| 2789 |
-
inputs=[selected_dataset_repo_state, table, cache_key_state],
|
| 2790 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 2791 |
)
|
| 2792 |
|
|
@@ -3046,57 +3520,67 @@ def create_app() -> gr.Blocks:
|
|
| 3046 |
)
|
| 3047 |
|
| 3048 |
approve_event.then(
|
| 3049 |
-
fn=lambda repo, rows, idx, cache_key: _advance_to_next_row_with_title(
|
| 3050 |
audio_service=audio_service,
|
| 3051 |
dataset_repo=repo,
|
| 3052 |
rows=rows,
|
| 3053 |
selected_index=int(idx),
|
| 3054 |
cache_key=cache_key,
|
| 3055 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
|
|
|
| 3056 |
),
|
| 3057 |
-
inputs=[selected_dataset_repo_state, table, selected_index, cache_key_state],
|
| 3058 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3059 |
).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3060 |
|
| 3061 |
reject_event.then(
|
| 3062 |
-
fn=lambda repo, rows, idx, cache_key: _advance_to_next_row_with_title(
|
| 3063 |
audio_service=audio_service,
|
| 3064 |
dataset_repo=repo,
|
| 3065 |
rows=rows,
|
| 3066 |
selected_index=int(idx),
|
| 3067 |
cache_key=cache_key,
|
| 3068 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
|
|
|
| 3069 |
),
|
| 3070 |
-
inputs=[selected_dataset_repo_state, table, selected_index, cache_key_state],
|
| 3071 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3072 |
).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3073 |
|
| 3074 |
uncertain_event.then(
|
| 3075 |
-
fn=lambda repo, rows, idx, cache_key: _advance_to_next_row_with_title(
|
| 3076 |
audio_service=audio_service,
|
| 3077 |
dataset_repo=repo,
|
| 3078 |
rows=rows,
|
| 3079 |
selected_index=int(idx),
|
| 3080 |
cache_key=cache_key,
|
| 3081 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
|
|
|
| 3082 |
),
|
| 3083 |
-
inputs=[selected_dataset_repo_state, table, selected_index, cache_key_state],
|
| 3084 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3085 |
).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3086 |
|
| 3087 |
skip_event.then(
|
| 3088 |
-
fn=lambda repo, rows, idx, cache_key: _advance_to_next_row_with_title(
|
| 3089 |
audio_service=audio_service,
|
| 3090 |
dataset_repo=repo,
|
| 3091 |
rows=rows,
|
| 3092 |
selected_index=int(idx),
|
| 3093 |
cache_key=cache_key,
|
| 3094 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
|
|
|
| 3095 |
),
|
| 3096 |
-
inputs=[selected_dataset_repo_state, table, selected_index, cache_key_state],
|
| 3097 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3098 |
).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3099 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3100 |
reapply_event.then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3101 |
batch_approve_event.then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3102 |
batch_reject_event.then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
|
|
|
| 35 |
dataset_repo: str,
|
| 36 |
audio_id: str,
|
| 37 |
allow_demo_fallback: bool = False,
|
| 38 |
+
hf_token: str | None = None,
|
| 39 |
) -> _AudioFetchResultProtocol: ...
|
| 40 |
|
| 41 |
def cleanup_after_validation(self, cache_key: str) -> None: ...
|
|
|
|
| 311 |
project_slug=str(row.get("project_slug", "")).strip(),
|
| 312 |
name=str(row.get("name", "")).strip(),
|
| 313 |
dataset_repo_id=str(row.get("dataset_repo_id", "")).strip(),
|
| 314 |
+
visibility=str(row.get("visibility", "collaborative")).strip() or "collaborative",
|
| 315 |
+
owner_username=(str(row.get("owner_username", "")).strip() or None),
|
| 316 |
+
dataset_token=(str(row.get("dataset_token", "")).strip() or None),
|
| 317 |
active=bool(row.get("active", True)),
|
| 318 |
)
|
| 319 |
)
|
|
|
|
| 348 |
if role_text not in {"admin", "validator"}:
|
| 349 |
continue
|
| 350 |
normalized_roles[str(project_slug)] = Role(role_text)
|
| 351 |
+
result[str(username)] = normalized_roles
|
|
|
|
| 352 |
return result
|
| 353 |
|
| 354 |
|
| 355 |
+
def _load_pending_invites_from_file(invites_file_path: str | None) -> dict[str, dict[str, dict[str, str]]]:
|
| 356 |
+
if not invites_file_path:
|
| 357 |
+
return {}
|
| 358 |
+
|
| 359 |
+
path = Path(invites_file_path)
|
| 360 |
+
if not path.exists():
|
| 361 |
+
return {}
|
| 362 |
+
|
| 363 |
+
try:
|
| 364 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 365 |
+
except Exception:
|
| 366 |
+
return {}
|
| 367 |
+
|
| 368 |
+
return payload if isinstance(payload, dict) else {}
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def _resolve_bootstrap_file_paths(runtime_config: RuntimeConfig) -> tuple[Path, Path, Path]:
|
| 372 |
+
bootstrap_dir = Path(runtime_config.validation_base_dir) / "bootstrap"
|
| 373 |
+
projects_path = Path(runtime_config.projects_file_path) if runtime_config.projects_file_path else (bootstrap_dir / "projects.json")
|
| 374 |
+
user_access_path = Path(runtime_config.user_access_file_path) if runtime_config.user_access_file_path else (bootstrap_dir / "user_access.json")
|
| 375 |
+
invites_path = Path(runtime_config.invites_file_path) if runtime_config.invites_file_path else (bootstrap_dir / "invites.json")
|
| 376 |
+
return projects_path, user_access_path, invites_path
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _persist_bootstrap_state(
|
| 380 |
+
projects_path: Path,
|
| 381 |
+
user_access_path: Path,
|
| 382 |
+
invites_path: Path,
|
| 383 |
+
admin_manager: AdminPanelManager,
|
| 384 |
+
auth_service: AuthService,
|
| 385 |
+
) -> None:
|
| 386 |
+
projects_path.parent.mkdir(parents=True, exist_ok=True)
|
| 387 |
+
user_access_path.parent.mkdir(parents=True, exist_ok=True)
|
| 388 |
+
invites_path.parent.mkdir(parents=True, exist_ok=True)
|
| 389 |
+
|
| 390 |
+
project_rows = admin_manager.list_projects()
|
| 391 |
+
projects_payload = [
|
| 392 |
+
{
|
| 393 |
+
"project_slug": str(project.get("project_slug", "")).strip(),
|
| 394 |
+
"name": str(project.get("name", "")).strip(),
|
| 395 |
+
"dataset_repo_id": str(project.get("dataset_repo_id", "")).strip(),
|
| 396 |
+
"visibility": str(project.get("visibility", "collaborative")).strip() or "collaborative",
|
| 397 |
+
"owner_username": str(project.get("owner_username", "")).strip() or None,
|
| 398 |
+
"dataset_token": str(project.get("dataset_token", "")).strip() or None,
|
| 399 |
+
"active": bool(project.get("active", True)),
|
| 400 |
+
}
|
| 401 |
+
for project in project_rows
|
| 402 |
+
]
|
| 403 |
+
projects_path.write_text(json.dumps(projects_payload, indent=2), encoding="utf-8")
|
| 404 |
+
|
| 405 |
+
access_payload = auth_service.export_user_access_map(include_inactive=True)
|
| 406 |
+
user_access_path.write_text(json.dumps(access_payload, indent=2), encoding="utf-8")
|
| 407 |
+
|
| 408 |
+
invites_payload = auth_service.export_pending_invites_map()
|
| 409 |
+
invites_path.write_text(json.dumps(invites_payload, indent=2), encoding="utf-8")
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def _bootstrap_auth_and_projects(
|
| 413 |
+
auth_service: AuthService,
|
| 414 |
+
admin_manager: AdminPanelManager,
|
| 415 |
+
runtime_config: RuntimeConfig,
|
| 416 |
+
projects_file_path: str | None = None,
|
| 417 |
+
user_access_file_path: str | None = None,
|
| 418 |
+
invites_file_path: str | None = None,
|
| 419 |
+
) -> str:
|
| 420 |
+
projects = _load_projects_from_file(projects_file_path or runtime_config.projects_file_path)
|
| 421 |
+
user_access = _load_user_access_from_file(user_access_file_path or runtime_config.user_access_file_path)
|
| 422 |
+
pending_invites = _load_pending_invites_from_file(invites_file_path or runtime_config.invites_file_path)
|
| 423 |
|
| 424 |
used_demo_fallback = False
|
| 425 |
if not projects and runtime_config.enable_demo_bootstrap:
|
|
|
|
| 436 |
for username, access in user_access.items():
|
| 437 |
auth_service.register_user_project_access(username, access)
|
| 438 |
|
| 439 |
+
auth_service.load_pending_invites_map(pending_invites)
|
| 440 |
+
|
| 441 |
if used_demo_fallback:
|
| 442 |
return (
|
| 443 |
"⚠️ Demo bootstrap enabled via BIRDNET_ENABLE_DEMO_BOOTSTRAP. "
|
| 444 |
"Use BIRDNET_PROJECTS_FILE and BIRDNET_USER_ACCESS_FILE for production auth/project setup."
|
| 445 |
)
|
| 446 |
|
| 447 |
+
if not projects:
|
| 448 |
return (
|
| 449 |
+
"⚠️ Production bootstrap incomplete. Create your first project in Admin, or configure "
|
| 450 |
+
"BIRDNET_PROJECTS_FILE and BIRDNET_USER_ACCESS_FILE (or enable demo bootstrap for local testing)."
|
| 451 |
)
|
| 452 |
|
| 453 |
return ""
|
|
|
|
| 677 |
selected_index: int,
|
| 678 |
previous_cache_key: str,
|
| 679 |
allow_demo_fallback: bool = False,
|
| 680 |
+
hf_token: str | None = None,
|
| 681 |
) -> tuple[str | None, str, str]:
|
| 682 |
repo = dataset_repo.strip()
|
| 683 |
if not repo:
|
|
|
|
| 690 |
dataset_repo=repo,
|
| 691 |
audio_id=audio_id,
|
| 692 |
allow_demo_fallback=allow_demo_fallback,
|
| 693 |
+
hf_token=hf_token,
|
| 694 |
)
|
| 695 |
except TypeError:
|
| 696 |
# Backward compatibility for fake/mocked services used in tests.
|
|
|
|
| 805 |
selected_index: int,
|
| 806 |
previous_cache_key: str,
|
| 807 |
allow_demo_fallback: bool = False,
|
| 808 |
+
hf_token: str | None = None,
|
| 809 |
) -> tuple[str | None, str, str, str | None]:
|
| 810 |
audio_path, cache_key, status = _fetch_selected_audio(
|
| 811 |
audio_service=audio_service,
|
|
|
|
| 814 |
selected_index=selected_index,
|
| 815 |
previous_cache_key=previous_cache_key,
|
| 816 |
allow_demo_fallback=allow_demo_fallback,
|
| 817 |
+
hf_token=hf_token,
|
| 818 |
)
|
| 819 |
spectrogram_path = _build_spectrogram_image(audio_path)
|
| 820 |
if audio_path and spectrogram_path is None:
|
|
|
|
| 852 |
rows: object,
|
| 853 |
cache_key: str,
|
| 854 |
allow_demo_fallback: bool = False,
|
| 855 |
+
hf_token: str | None = None,
|
| 856 |
) -> tuple[int, str | None, str, str, str | None]:
|
| 857 |
normalized_rows = _normalize_rows(rows)
|
| 858 |
if not normalized_rows:
|
|
|
|
| 865 |
selected_index=0,
|
| 866 |
previous_cache_key=cache_key,
|
| 867 |
allow_demo_fallback=allow_demo_fallback,
|
| 868 |
+
hf_token=hf_token,
|
| 869 |
)
|
| 870 |
return 0, audio_path, updated_cache_key, status, spectrogram_path
|
| 871 |
|
|
|
|
| 877 |
cache_key: str,
|
| 878 |
evt: gr.SelectData,
|
| 879 |
allow_demo_fallback: bool = False,
|
| 880 |
+
hf_token: str | None = None,
|
| 881 |
) -> tuple[int, str | None, str, str, str | None]:
|
| 882 |
if isinstance(evt.index, tuple):
|
| 883 |
selected_index = int(evt.index[0])
|
|
|
|
| 893 |
selected_index=selected_index,
|
| 894 |
previous_cache_key=cache_key,
|
| 895 |
allow_demo_fallback=allow_demo_fallback,
|
| 896 |
+
hf_token=hf_token,
|
| 897 |
)
|
| 898 |
return selected_index, audio_path, updated_cache_key, status, spectrogram_path
|
| 899 |
|
|
|
|
| 960 |
selected_index: int,
|
| 961 |
previous_cache_key: str,
|
| 962 |
allow_demo_fallback: bool = False,
|
| 963 |
+
hf_token: str | None = None,
|
| 964 |
) -> tuple[str | None, str, str, str | None, str]:
|
| 965 |
audio_path, cache_key, status, spectrogram_path = _fetch_selected_audio_with_spectrogram(
|
| 966 |
audio_service=audio_service,
|
|
|
|
| 969 |
selected_index=selected_index,
|
| 970 |
previous_cache_key=previous_cache_key,
|
| 971 |
allow_demo_fallback=allow_demo_fallback,
|
| 972 |
+
hf_token=hf_token,
|
| 973 |
)
|
| 974 |
return audio_path, cache_key, status, spectrogram_path, _spectrogram_title(audio_path)
|
| 975 |
|
|
|
|
| 981 |
cache_key: str,
|
| 982 |
evt: gr.SelectData,
|
| 983 |
allow_demo_fallback: bool = False,
|
| 984 |
+
hf_token: str | None = None,
|
| 985 |
) -> tuple[int, str | None, str, str, str | None, str]:
|
| 986 |
selected_index, audio_path, updated_cache_key, status, spectrogram_path = _select_and_fetch_audio(
|
| 987 |
audio_service=audio_service,
|
|
|
|
| 990 |
cache_key=cache_key,
|
| 991 |
evt=evt,
|
| 992 |
allow_demo_fallback=allow_demo_fallback,
|
| 993 |
+
hf_token=hf_token,
|
| 994 |
)
|
| 995 |
return (
|
| 996 |
selected_index,
|
|
|
|
| 1008 |
rows: object,
|
| 1009 |
cache_key: str,
|
| 1010 |
allow_demo_fallback: bool = False,
|
| 1011 |
+
hf_token: str | None = None,
|
| 1012 |
) -> tuple[int, str | None, str, str, str | None, str]:
|
| 1013 |
selected_index, audio_path, updated_cache_key, status, spectrogram_path = _autofetch_first_row(
|
| 1014 |
audio_service=audio_service,
|
|
|
|
| 1016 |
rows=rows,
|
| 1017 |
cache_key=cache_key,
|
| 1018 |
allow_demo_fallback=allow_demo_fallback,
|
| 1019 |
+
hf_token=hf_token,
|
| 1020 |
)
|
| 1021 |
return (
|
| 1022 |
selected_index,
|
|
|
|
| 1035 |
selected_index: int,
|
| 1036 |
cache_key: str,
|
| 1037 |
allow_demo_fallback: bool = False,
|
| 1038 |
+
hf_token: str | None = None,
|
| 1039 |
) -> tuple[int, str | None, str, str, str | None, str]:
|
| 1040 |
normalized_rows = _normalize_rows(rows)
|
| 1041 |
if not normalized_rows:
|
|
|
|
| 1049 |
selected_index=safe_index,
|
| 1050 |
previous_cache_key=cache_key,
|
| 1051 |
allow_demo_fallback=allow_demo_fallback,
|
| 1052 |
+
hf_token=hf_token,
|
| 1053 |
)
|
| 1054 |
return safe_index, audio_path, updated_cache_key, status, spectrogram_path, _spectrogram_title(audio_path)
|
| 1055 |
|
|
|
|
| 1956 |
Returns:
|
| 1957 |
Gradio Blocks with full auth-integrated app
|
| 1958 |
"""
|
| 1959 |
+
runtime_config = RuntimeConfig.from_env()
|
| 1960 |
+
|
| 1961 |
# Initialize auth service
|
| 1962 |
+
auth_service = AuthService(
|
| 1963 |
+
session_ttl_minutes=120,
|
| 1964 |
+
invite_ttl_hours=runtime_config.invite_ttl_hours,
|
| 1965 |
+
)
|
| 1966 |
|
| 1967 |
# Initialize admin panel manager
|
| 1968 |
admin_manager = AdminPanelManager(auth_service)
|
| 1969 |
|
| 1970 |
+
projects_file_path, user_access_file_path, invites_file_path = _resolve_bootstrap_file_paths(runtime_config)
|
| 1971 |
+
bootstrap_warning = _bootstrap_auth_and_projects(
|
| 1972 |
+
auth_service,
|
| 1973 |
+
admin_manager,
|
| 1974 |
+
runtime_config,
|
| 1975 |
+
projects_file_path=str(projects_file_path),
|
| 1976 |
+
user_access_file_path=str(user_access_file_path),
|
| 1977 |
+
invites_file_path=str(invites_file_path),
|
| 1978 |
+
)
|
| 1979 |
queue_service, seed_warning = _build_detection_repository(
|
| 1980 |
[project["project_slug"] for project in admin_manager.list_projects()],
|
| 1981 |
seed_file_path=runtime_config.detection_seed_path,
|
|
|
|
| 2004 |
p["project_slug"],
|
| 2005 |
p["name"],
|
| 2006 |
p["dataset_repo_id"],
|
| 2007 |
+
p.get("visibility", "collaborative"),
|
| 2008 |
+
p.get("owner_username", ""),
|
| 2009 |
+
"yes" if bool(p.get("dataset_token_set", False)) else "no",
|
| 2010 |
"yes" if bool(p["active"]) else "no",
|
| 2011 |
]
|
| 2012 |
for p in projects
|
|
|
|
| 2015 |
def _project_slugs() -> list[str]:
|
| 2016 |
return [p["project_slug"] for p in admin_manager.list_projects()]
|
| 2017 |
|
| 2018 |
+
def _persist_admin_state() -> tuple[bool, str]:
|
| 2019 |
+
try:
|
| 2020 |
+
_persist_bootstrap_state(
|
| 2021 |
+
projects_path=projects_file_path,
|
| 2022 |
+
user_access_path=user_access_file_path,
|
| 2023 |
+
invites_path=invites_file_path,
|
| 2024 |
+
admin_manager=admin_manager,
|
| 2025 |
+
auth_service=auth_service,
|
| 2026 |
+
)
|
| 2027 |
+
return True, ""
|
| 2028 |
+
except Exception as exc:
|
| 2029 |
+
return False, str(exc)
|
| 2030 |
+
|
| 2031 |
with gr.Tabs():
|
| 2032 |
# ===== TAB 1: Login =====
|
| 2033 |
with gr.Tab("🔐 Login", id="login_tab"):
|
|
|
|
| 2085 |
label="HF Dataset Repo ID",
|
| 2086 |
placeholder="ex: birdnet/amazonas-2026-dataset",
|
| 2087 |
)
|
| 2088 |
+
create_project_visibility = gr.Dropdown(
|
| 2089 |
+
label="Visibility",
|
| 2090 |
+
choices=["private", "collaborative"],
|
| 2091 |
+
value="collaborative",
|
| 2092 |
+
)
|
| 2093 |
+
create_project_token = gr.Textbox(
|
| 2094 |
+
label="Project HF Token (optional)",
|
| 2095 |
+
placeholder="hf_xxx...",
|
| 2096 |
+
type="password",
|
| 2097 |
+
)
|
| 2098 |
|
| 2099 |
create_project_message = gr.Markdown()
|
| 2100 |
|
| 2101 |
+
def create_project(session, slug: str, name: str, repo_id: str, visibility: str, project_token: str):
|
| 2102 |
if session is None or session.role.value != "admin":
|
| 2103 |
+
return "❌ Access denied. Only admin can create projects.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), session
|
| 2104 |
|
| 2105 |
slug = (slug or "").strip()
|
| 2106 |
name = (name or "").strip()
|
| 2107 |
repo_id = (repo_id or "").strip()
|
| 2108 |
+
visibility_value = (visibility or "collaborative").strip().lower()
|
| 2109 |
+
project_token_value = (project_token or "").strip() or None
|
| 2110 |
if not slug or not name or not repo_id:
|
| 2111 |
+
return "⚠️ Fill slug, name, and repo id.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), session
|
| 2112 |
+
if visibility_value not in {"private", "collaborative"}:
|
| 2113 |
+
return "⚠️ Visibility must be private or collaborative.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), session
|
| 2114 |
|
| 2115 |
created = admin_manager.register_project(
|
| 2116 |
Project(
|
| 2117 |
project_slug=slug,
|
| 2118 |
name=name,
|
| 2119 |
dataset_repo_id=repo_id,
|
| 2120 |
+
visibility=visibility_value,
|
| 2121 |
+
owner_username=session.username,
|
| 2122 |
+
dataset_token=project_token_value,
|
| 2123 |
active=True,
|
| 2124 |
)
|
| 2125 |
)
|
|
|
|
| 2132 |
gr.update(),
|
| 2133 |
gr.update(),
|
| 2134 |
gr.update(),
|
| 2135 |
+
gr.update(),
|
| 2136 |
+
gr.update(),
|
| 2137 |
+
gr.update(),
|
| 2138 |
+
gr.update(),
|
| 2139 |
+
gr.update(),
|
| 2140 |
+
session,
|
| 2141 |
)
|
| 2142 |
|
| 2143 |
+
# Project creator is always admin of the project.
|
| 2144 |
+
auth_service.upsert_user_project_role(session.username, slug, Role.admin)
|
| 2145 |
+
persisted, persist_error = _persist_admin_state()
|
| 2146 |
+
|
| 2147 |
refreshed_service, refreshed_warning = _build_detection_repository(
|
| 2148 |
_project_slugs(),
|
| 2149 |
seed_file_path=runtime_config.detection_seed_path,
|
| 2150 |
)
|
| 2151 |
service_ref["queue"] = refreshed_service
|
| 2152 |
+
refreshed_session = auth_service.refresh_session_authorizations(session.session_id) or session
|
| 2153 |
|
| 2154 |
return (
|
| 2155 |
+
(
|
| 2156 |
+
f"✅ Project '{slug}' created successfully."
|
| 2157 |
+
if persisted
|
| 2158 |
+
else f"✅ Project '{slug}' created, but could not persist bootstrap files: {persist_error}"
|
| 2159 |
+
),
|
| 2160 |
_project_rows(),
|
| 2161 |
gr.update(choices=_project_slugs(), value=slug),
|
| 2162 |
gr.update(value=""),
|
| 2163 |
gr.update(value=""),
|
| 2164 |
gr.update(value=""),
|
| 2165 |
+
gr.update(value="collaborative"),
|
| 2166 |
+
gr.update(value=""),
|
| 2167 |
+
gr.update(choices=_project_slugs(), value=slug),
|
| 2168 |
+
gr.update(choices=_project_slugs(), value=slug),
|
| 2169 |
+
gr.update(choices=["all", *_project_slugs()], value="all"),
|
| 2170 |
refreshed_warning,
|
| 2171 |
+
refreshed_session,
|
| 2172 |
)
|
| 2173 |
|
| 2174 |
create_project_btn = gr.Button("➕ Create Project", variant="primary")
|
| 2175 |
projects_table = gr.Dataframe(
|
| 2176 |
value=_project_rows(),
|
| 2177 |
+
headers=["project_slug", "name", "dataset_repo_id", "visibility", "owner_username", "dataset_token_set", "active"],
|
| 2178 |
interactive=False,
|
| 2179 |
)
|
| 2180 |
refresh_projects_btn = gr.Button("🔄 Refresh List")
|
|
|
|
| 2190 |
outputs=[projects_table],
|
| 2191 |
)
|
| 2192 |
|
| 2193 |
+
gr.Markdown("#### Project Token Management")
|
| 2194 |
+
with gr.Row():
|
| 2195 |
+
token_project_select = gr.Dropdown(
|
| 2196 |
+
choices=_project_slugs(),
|
| 2197 |
+
label="Project",
|
| 2198 |
+
)
|
| 2199 |
+
token_new_value = gr.Textbox(
|
| 2200 |
+
label="New token",
|
| 2201 |
+
placeholder="hf_xxx...",
|
| 2202 |
+
type="password",
|
| 2203 |
+
)
|
| 2204 |
+
token_clear_checkbox = gr.Checkbox(label="Clear token", value=False)
|
| 2205 |
+
token_update_message = gr.Markdown()
|
| 2206 |
+
token_update_btn = gr.Button("Update Project Token")
|
| 2207 |
+
|
| 2208 |
+
def update_project_token(session, project_slug: str, new_token: str, clear_token: bool):
|
| 2209 |
+
if session is None or session.role.value != "admin":
|
| 2210 |
+
return "❌ Access denied. Only admin can update project tokens.", gr.update(), gr.update()
|
| 2211 |
+
project = admin_manager.get_project(project_slug)
|
| 2212 |
+
if project is None:
|
| 2213 |
+
return "⚠️ Select a valid project.", gr.update(), gr.update()
|
| 2214 |
+
|
| 2215 |
+
if bool(clear_token):
|
| 2216 |
+
project.dataset_token = None
|
| 2217 |
+
message = f"✅ Project token cleared for {project_slug}"
|
| 2218 |
+
else:
|
| 2219 |
+
candidate = (new_token or "").strip()
|
| 2220 |
+
if not candidate:
|
| 2221 |
+
return "⚠️ Provide a token or select clear token.", gr.update(), gr.update()
|
| 2222 |
+
project.dataset_token = candidate
|
| 2223 |
+
message = f"✅ Project token updated for {project_slug}"
|
| 2224 |
+
|
| 2225 |
+
persisted, persist_error = _persist_admin_state()
|
| 2226 |
+
if not persisted:
|
| 2227 |
+
message = f"{message} | ⚠️ Persistence failed: {persist_error}"
|
| 2228 |
+
|
| 2229 |
+
return message, gr.update(value=""), _project_rows()
|
| 2230 |
+
|
| 2231 |
+
token_update_btn.click(
|
| 2232 |
+
fn=update_project_token,
|
| 2233 |
+
inputs=[session_state, token_project_select, token_new_value, token_clear_checkbox],
|
| 2234 |
+
outputs=[token_update_message, token_new_value, projects_table],
|
| 2235 |
+
)
|
| 2236 |
+
|
| 2237 |
with gr.Group(visible=False) as admin_users_controls:
|
| 2238 |
gr.Markdown("#### Assign User to Project")
|
| 2239 |
with gr.Row():
|
|
|
|
| 2251 |
)
|
| 2252 |
|
| 2253 |
admin_message = gr.Markdown()
|
| 2254 |
+
invite_btn = gr.Button("✉️ Invite")
|
| 2255 |
|
| 2256 |
def assign_user(session, username: str, project: str, role: str):
|
| 2257 |
if session is None or session.role.value != "admin":
|
|
|
|
| 2260 |
username, project, role
|
| 2261 |
)
|
| 2262 |
if success:
|
| 2263 |
+
persisted, persist_error = _persist_admin_state()
|
| 2264 |
+
final_message = msg if persisted else f"{msg} | ⚠️ Persistence failed: {persist_error}"
|
| 2265 |
+
return final_message, gr.update(value=""), gr.update(value=None), gr.update(value="validator")
|
| 2266 |
return msg, gr.update(), gr.update(), gr.update()
|
| 2267 |
|
| 2268 |
assign_btn = gr.Button("✅ Assign", variant="primary")
|
|
|
|
| 2272 |
outputs=[admin_message, admin_username, admin_project, admin_role],
|
| 2273 |
)
|
| 2274 |
|
| 2275 |
+
def invite_user(session, username: str, project: str, role: str):
|
| 2276 |
+
if session is None or session.role.value != "admin":
|
| 2277 |
+
return "❌ Access denied. Only admin can invite users.", gr.update(), gr.update(), gr.update()
|
| 2278 |
+
success, msg = admin_manager.invite_user_to_project(
|
| 2279 |
+
invited_by=session.username,
|
| 2280 |
+
username=username,
|
| 2281 |
+
project_slug=project,
|
| 2282 |
+
role=role,
|
| 2283 |
+
)
|
| 2284 |
+
if success:
|
| 2285 |
+
persisted, persist_error = _persist_admin_state()
|
| 2286 |
+
final_message = msg if persisted else f"{msg} | ⚠️ Persistence failed: {persist_error}"
|
| 2287 |
+
return final_message, gr.update(value=""), gr.update(value=None), gr.update(value="validator")
|
| 2288 |
+
return msg, gr.update(), gr.update(), gr.update()
|
| 2289 |
+
|
| 2290 |
+
invite_btn.click(
|
| 2291 |
+
fn=invite_user,
|
| 2292 |
+
inputs=[session_state, admin_username, admin_project, admin_role],
|
| 2293 |
+
outputs=[admin_message, admin_username, admin_project, admin_role],
|
| 2294 |
+
)
|
| 2295 |
+
|
| 2296 |
+
gr.Markdown("#### Pending Invites")
|
| 2297 |
+
with gr.Row():
|
| 2298 |
+
pending_invites_filter_project = gr.Dropdown(
|
| 2299 |
+
choices=["all", *_project_slugs()],
|
| 2300 |
+
value="all",
|
| 2301 |
+
label="Filter by project",
|
| 2302 |
+
)
|
| 2303 |
+
pending_invite_username = gr.Textbox(label="Invite username", placeholder="validator_001")
|
| 2304 |
+
pending_invite_project = gr.Dropdown(choices=_project_slugs(), label="Invite project")
|
| 2305 |
+
pending_invites_table = gr.Dataframe(
|
| 2306 |
+
value=[],
|
| 2307 |
+
headers=["username", "project_slug", "role", "invited_by", "expires_at", "expires_in"],
|
| 2308 |
+
interactive=False,
|
| 2309 |
+
)
|
| 2310 |
+
pending_invites_message = gr.Markdown()
|
| 2311 |
+
with gr.Row():
|
| 2312 |
+
refresh_pending_invites_btn = gr.Button("Refresh Pending Invites")
|
| 2313 |
+
revoke_invite_btn = gr.Button("Revoke Invite")
|
| 2314 |
+
|
| 2315 |
+
def _pending_invites_rows(project_filter: str):
|
| 2316 |
+
def _remaining_from_iso(iso_value: str) -> str:
|
| 2317 |
+
raw = str(iso_value or "").strip()
|
| 2318 |
+
if not raw:
|
| 2319 |
+
return "unknown"
|
| 2320 |
+
try:
|
| 2321 |
+
expires_at = datetime.fromisoformat(raw)
|
| 2322 |
+
except Exception:
|
| 2323 |
+
return "unknown"
|
| 2324 |
+
if expires_at.tzinfo is None:
|
| 2325 |
+
now = datetime.now()
|
| 2326 |
+
else:
|
| 2327 |
+
now = datetime.now(expires_at.tzinfo)
|
| 2328 |
+
remaining_seconds = int((expires_at - now).total_seconds())
|
| 2329 |
+
if remaining_seconds <= 0:
|
| 2330 |
+
return "expired"
|
| 2331 |
+
days = remaining_seconds // 86400
|
| 2332 |
+
hours = (remaining_seconds % 86400) // 3600
|
| 2333 |
+
minutes = (remaining_seconds % 3600) // 60
|
| 2334 |
+
if days > 0:
|
| 2335 |
+
return f"{days}d {hours}h"
|
| 2336 |
+
if hours > 0:
|
| 2337 |
+
return f"{hours}h {minutes}m"
|
| 2338 |
+
return f"{minutes}m"
|
| 2339 |
+
|
| 2340 |
+
selected = (project_filter or "all").strip().lower()
|
| 2341 |
+
project = None if selected == "all" else project_filter
|
| 2342 |
+
invites = admin_manager.list_pending_invites(project_slug=project)
|
| 2343 |
+
return [
|
| 2344 |
+
[
|
| 2345 |
+
row.get("username", ""),
|
| 2346 |
+
row.get("project_slug", ""),
|
| 2347 |
+
row.get("role", ""),
|
| 2348 |
+
row.get("invited_by", ""),
|
| 2349 |
+
row.get("expires_at", ""),
|
| 2350 |
+
_remaining_from_iso(str(row.get("expires_at", ""))),
|
| 2351 |
+
]
|
| 2352 |
+
for row in invites
|
| 2353 |
+
]
|
| 2354 |
+
|
| 2355 |
+
refresh_pending_invites_btn.click(
|
| 2356 |
+
fn=_pending_invites_rows,
|
| 2357 |
+
inputs=[pending_invites_filter_project],
|
| 2358 |
+
outputs=[pending_invites_table],
|
| 2359 |
+
)
|
| 2360 |
+
|
| 2361 |
+
def revoke_invite(session, username: str, project_slug: str, project_filter: str):
|
| 2362 |
+
if session is None or session.role.value != "admin":
|
| 2363 |
+
return "❌ Access denied. Only admin can revoke invites.", _pending_invites_rows(project_filter)
|
| 2364 |
+
success, msg = admin_manager.revoke_invite(username=username, project_slug=project_slug)
|
| 2365 |
+
if success:
|
| 2366 |
+
persisted, persist_error = _persist_admin_state()
|
| 2367 |
+
if not persisted:
|
| 2368 |
+
msg = f"{msg} | ⚠️ Persistence failed: {persist_error}"
|
| 2369 |
+
return msg, _pending_invites_rows(project_filter)
|
| 2370 |
+
|
| 2371 |
+
revoke_invite_btn.click(
|
| 2372 |
+
fn=revoke_invite,
|
| 2373 |
+
inputs=[session_state, pending_invite_username, pending_invite_project, pending_invites_filter_project],
|
| 2374 |
+
outputs=[pending_invites_message, pending_invites_table],
|
| 2375 |
+
)
|
| 2376 |
+
|
| 2377 |
+
pending_invites_filter_project.change(
|
| 2378 |
+
fn=_pending_invites_rows,
|
| 2379 |
+
inputs=[pending_invites_filter_project],
|
| 2380 |
+
outputs=[pending_invites_table],
|
| 2381 |
+
)
|
| 2382 |
+
|
| 2383 |
create_project_btn.click(
|
| 2384 |
fn=create_project,
|
| 2385 |
+
inputs=[session_state, create_project_slug, create_project_name, create_project_repo, create_project_visibility, create_project_token],
|
| 2386 |
outputs=[
|
| 2387 |
create_project_message,
|
| 2388 |
projects_table,
|
|
|
|
| 2390 |
create_project_slug,
|
| 2391 |
create_project_name,
|
| 2392 |
create_project_repo,
|
| 2393 |
+
create_project_visibility,
|
| 2394 |
+
create_project_token,
|
| 2395 |
+
token_project_select,
|
| 2396 |
+
pending_invite_project,
|
| 2397 |
+
pending_invites_filter_project,
|
| 2398 |
seed_warning_state,
|
| 2399 |
+
session_state,
|
| 2400 |
],
|
| 2401 |
)
|
| 2402 |
|
|
|
|
| 2422 |
label="Authorized Project",
|
| 2423 |
interactive=False,
|
| 2424 |
)
|
| 2425 |
+
invitations_info = gr.Markdown(value="")
|
| 2426 |
+
invite_selector = gr.Dropdown(choices=[], label="Pending Invites", interactive=False)
|
| 2427 |
+
with gr.Row():
|
| 2428 |
+
refresh_invites_btn = gr.Button("Refresh Invites")
|
| 2429 |
+
accept_invite_btn = gr.Button("Accept Invite", variant="primary")
|
| 2430 |
+
accept_all_invites_btn = gr.Button("Accept All")
|
| 2431 |
+
reject_invite_btn = gr.Button("Reject Invite")
|
| 2432 |
|
| 2433 |
def update_project_selector(session):
|
| 2434 |
"""Update project dropdown when user logs in."""
|
|
|
|
| 2461 |
dataset_repo_id,
|
| 2462 |
)
|
| 2463 |
|
| 2464 |
+
def _format_invite_option(invite) -> str:
|
| 2465 |
+
return f"{invite.project_slug}|{invite.role.value}|{invite.invited_by}|{invite.expires_at.isoformat()}"
|
| 2466 |
+
|
| 2467 |
+
def _format_invite_remaining(expires_at: datetime) -> str:
|
| 2468 |
+
now = datetime.now(expires_at.tzinfo) if expires_at.tzinfo else datetime.utcnow()
|
| 2469 |
+
delta = expires_at - now
|
| 2470 |
+
remaining_seconds = int(delta.total_seconds())
|
| 2471 |
+
if remaining_seconds <= 0:
|
| 2472 |
+
return "expired"
|
| 2473 |
+
|
| 2474 |
+
days = remaining_seconds // 86400
|
| 2475 |
+
hours = (remaining_seconds % 86400) // 3600
|
| 2476 |
+
minutes = (remaining_seconds % 3600) // 60
|
| 2477 |
+
|
| 2478 |
+
if days > 0:
|
| 2479 |
+
return f"{days}d {hours}h"
|
| 2480 |
+
if hours > 0:
|
| 2481 |
+
return f"{hours}h {minutes}m"
|
| 2482 |
+
return f"{minutes}m"
|
| 2483 |
+
|
| 2484 |
+
def _build_invite_label(invite) -> str:
|
| 2485 |
+
remaining = _format_invite_remaining(invite.expires_at)
|
| 2486 |
+
return (
|
| 2487 |
+
f"{invite.project_slug} ({invite.role.value})"
|
| 2488 |
+
f" - invited by {invite.invited_by}"
|
| 2489 |
+
f" - expires in {remaining}"
|
| 2490 |
+
)
|
| 2491 |
+
|
| 2492 |
+
def _build_invites_ui(session):
|
| 2493 |
+
if session is None:
|
| 2494 |
+
return gr.update(value="", visible=False), gr.update(choices=[], value=None, interactive=False)
|
| 2495 |
+
invites = auth_service.list_pending_invites(session.username)
|
| 2496 |
+
if not invites:
|
| 2497 |
+
return gr.update(value="No pending invites", visible=True), gr.update(choices=[], value=None, interactive=False)
|
| 2498 |
+
encoded = [_format_invite_option(item) for item in invites]
|
| 2499 |
+
labeled_choices = [(_build_invite_label(invite), encoded_value) for invite, encoded_value in zip(invites, encoded)]
|
| 2500 |
+
return (
|
| 2501 |
+
gr.update(value=f"Pending invites: {len(labeled_choices)}", visible=True),
|
| 2502 |
+
gr.update(choices=labeled_choices, value=encoded[0], interactive=True),
|
| 2503 |
+
)
|
| 2504 |
+
|
| 2505 |
+
def _parse_invite_option(raw_option: str) -> tuple[str, str, str]:
|
| 2506 |
+
"""Compatibility parser: supports old and new encoded invite strings."""
|
| 2507 |
+
value = str(raw_option or "").strip()
|
| 2508 |
+
parts = value.split("|")
|
| 2509 |
+
if len(parts) < 3:
|
| 2510 |
+
return "", "", ""
|
| 2511 |
+
return parts[0].strip(), parts[1].strip(), parts[2].strip()
|
| 2512 |
+
|
| 2513 |
+
def _accept_invite(session, selected_option: str):
|
| 2514 |
+
if session is None:
|
| 2515 |
+
return "❌ Login first", session
|
| 2516 |
+
project_slug, _, _ = _parse_invite_option(selected_option)
|
| 2517 |
+
if not project_slug:
|
| 2518 |
+
return "⚠️ Select an invite", session
|
| 2519 |
+
success, message = auth_service.accept_project_invite(session.username, project_slug)
|
| 2520 |
+
refreshed = auth_service.refresh_session_authorizations(session.session_id) or session
|
| 2521 |
+
if success:
|
| 2522 |
+
_persist_admin_state()
|
| 2523 |
+
return message, refreshed
|
| 2524 |
+
|
| 2525 |
+
def _reject_invite(session, selected_option: str):
|
| 2526 |
+
if session is None:
|
| 2527 |
+
return "❌ Login first", session
|
| 2528 |
+
project_slug, _, _ = _parse_invite_option(selected_option)
|
| 2529 |
+
if not project_slug:
|
| 2530 |
+
return "⚠️ Select an invite", session
|
| 2531 |
+
success, message = auth_service.reject_project_invite(session.username, project_slug)
|
| 2532 |
+
refreshed = auth_service.refresh_session_authorizations(session.session_id) or session
|
| 2533 |
+
if success:
|
| 2534 |
+
_persist_admin_state()
|
| 2535 |
+
return message, refreshed
|
| 2536 |
+
|
| 2537 |
+
def _accept_all_invites(session):
|
| 2538 |
+
if session is None:
|
| 2539 |
+
return "❌ Login first", session
|
| 2540 |
+
accepted, failed, message = auth_service.accept_all_project_invites(session.username)
|
| 2541 |
+
refreshed = auth_service.refresh_session_authorizations(session.session_id) or session
|
| 2542 |
+
if accepted > 0:
|
| 2543 |
+
_persist_admin_state()
|
| 2544 |
+
detail = f"{message}"
|
| 2545 |
+
if failed:
|
| 2546 |
+
detail = f"{detail} | failed={failed}"
|
| 2547 |
+
return detail, refreshed
|
| 2548 |
+
|
| 2549 |
+
session_state.change(
|
| 2550 |
+
fn=update_project_selector,
|
| 2551 |
+
inputs=[session_state],
|
| 2552 |
+
outputs=[project_selector, project_info_display, selected_project_state, selected_dataset_repo_state],
|
| 2553 |
+
)
|
| 2554 |
+
|
| 2555 |
session_state.change(
|
| 2556 |
+
fn=_build_invites_ui,
|
| 2557 |
+
inputs=[session_state],
|
| 2558 |
+
outputs=[invitations_info, invite_selector],
|
| 2559 |
+
)
|
| 2560 |
+
|
| 2561 |
+
refresh_invites_btn.click(
|
| 2562 |
+
fn=_build_invites_ui,
|
| 2563 |
+
inputs=[session_state],
|
| 2564 |
+
outputs=[invitations_info, invite_selector],
|
| 2565 |
+
)
|
| 2566 |
+
|
| 2567 |
+
accept_invite_btn.click(
|
| 2568 |
+
fn=_accept_invite,
|
| 2569 |
+
inputs=[session_state, invite_selector],
|
| 2570 |
+
outputs=[project_info_display, session_state],
|
| 2571 |
+
).then(
|
| 2572 |
+
fn=update_project_selector,
|
| 2573 |
+
inputs=[session_state],
|
| 2574 |
+
outputs=[project_selector, project_info_display, selected_project_state, selected_dataset_repo_state],
|
| 2575 |
+
).then(
|
| 2576 |
+
fn=_build_invites_ui,
|
| 2577 |
+
inputs=[session_state],
|
| 2578 |
+
outputs=[invitations_info, invite_selector],
|
| 2579 |
+
)
|
| 2580 |
+
|
| 2581 |
+
accept_all_invites_btn.click(
|
| 2582 |
+
fn=_accept_all_invites,
|
| 2583 |
+
inputs=[session_state],
|
| 2584 |
+
outputs=[project_info_display, session_state],
|
| 2585 |
+
).then(
|
| 2586 |
fn=update_project_selector,
|
| 2587 |
inputs=[session_state],
|
| 2588 |
outputs=[project_selector, project_info_display, selected_project_state, selected_dataset_repo_state],
|
| 2589 |
+
).then(
|
| 2590 |
+
fn=_build_invites_ui,
|
| 2591 |
+
inputs=[session_state],
|
| 2592 |
+
outputs=[invitations_info, invite_selector],
|
| 2593 |
+
)
|
| 2594 |
+
|
| 2595 |
+
reject_invite_btn.click(
|
| 2596 |
+
fn=_reject_invite,
|
| 2597 |
+
inputs=[session_state, invite_selector],
|
| 2598 |
+
outputs=[project_info_display, session_state],
|
| 2599 |
+
).then(
|
| 2600 |
+
fn=_build_invites_ui,
|
| 2601 |
+
inputs=[session_state],
|
| 2602 |
+
outputs=[invitations_info, invite_selector],
|
| 2603 |
)
|
| 2604 |
|
| 2605 |
def update_selected_project(selected: str, session):
|
|
|
|
| 2807 |
conflict_detection_key_state = gr.State(value="")
|
| 2808 |
report_box = gr.Textbox(label="Report", interactive=False)
|
| 2809 |
|
| 2810 |
+
def _session_hf_token(session) -> str | None:
|
| 2811 |
+
if session is None:
|
| 2812 |
+
return None
|
| 2813 |
+
return getattr(session, "hf_token", None)
|
| 2814 |
+
|
| 2815 |
+
def _project_fetch_token(project_slug: str, session) -> str | None:
|
| 2816 |
+
project = admin_manager.get_project(project_slug) if project_slug else None
|
| 2817 |
+
if project is not None:
|
| 2818 |
+
project_token = (project.dataset_token or "").strip()
|
| 2819 |
+
if project_token:
|
| 2820 |
+
return project_token
|
| 2821 |
+
return _session_hf_token(session)
|
| 2822 |
+
|
| 2823 |
def refresh(
|
| 2824 |
project_slug: str,
|
| 2825 |
page: int,
|
|
|
|
| 3083 |
updated_map[project_slug] = sorted(project_favs)
|
| 3084 |
return f"Deteccao {detection_key} {action}", updated_map
|
| 3085 |
|
| 3086 |
+
def on_table_select(project_slug: str, repo: str, rows: object, cache_key: str, session, evt: gr.SelectData):
|
| 3087 |
return _select_and_fetch_audio_with_title(
|
| 3088 |
audio_service=audio_service,
|
| 3089 |
dataset_repo=repo,
|
|
|
|
| 3091 |
cache_key=cache_key,
|
| 3092 |
evt=evt,
|
| 3093 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
| 3094 |
+
hf_token=_project_fetch_token(project_slug, session),
|
| 3095 |
)
|
| 3096 |
|
| 3097 |
refresh_event = refresh_btn.click(
|
|
|
|
| 3174 |
inputs=[table],
|
| 3175 |
outputs=[validation_summary_cards],
|
| 3176 |
).then(
|
| 3177 |
+
fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
|
| 3178 |
audio_service=audio_service,
|
| 3179 |
dataset_repo=repo,
|
| 3180 |
rows=rows,
|
| 3181 |
cache_key=cache_key,
|
| 3182 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
| 3183 |
+
hf_token=_project_fetch_token(project_slug, session),
|
| 3184 |
),
|
| 3185 |
+
inputs=[selected_project_state, selected_dataset_repo_state, table, cache_key_state, session_state],
|
| 3186 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3187 |
)
|
| 3188 |
|
| 3189 |
table.select(
|
| 3190 |
fn=on_table_select,
|
| 3191 |
+
inputs=[selected_project_state, selected_dataset_repo_state, table, cache_key_state, session_state],
|
| 3192 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3193 |
)
|
| 3194 |
|
| 3195 |
load_audio_btn.click(
|
| 3196 |
+
fn=lambda project_slug, repo, rows, idx, cache_key, session: _fetch_selected_audio_with_title(
|
| 3197 |
audio_service=audio_service,
|
| 3198 |
dataset_repo=repo,
|
| 3199 |
rows=rows,
|
| 3200 |
selected_index=int(idx),
|
| 3201 |
previous_cache_key=cache_key,
|
| 3202 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
| 3203 |
+
hf_token=_project_fetch_token(project_slug, session),
|
| 3204 |
),
|
| 3205 |
+
inputs=[selected_project_state, selected_dataset_repo_state, table, selected_index, cache_key_state, session_state],
|
| 3206 |
outputs=[audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3207 |
)
|
| 3208 |
clear_audio_btn.click(
|
|
|
|
| 3220 |
inputs=[table],
|
| 3221 |
outputs=[validation_summary_cards],
|
| 3222 |
).then(
|
| 3223 |
+
fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
|
| 3224 |
audio_service=audio_service,
|
| 3225 |
dataset_repo=repo,
|
| 3226 |
rows=rows,
|
| 3227 |
cache_key=cache_key,
|
| 3228 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
| 3229 |
+
hf_token=_project_fetch_token(project_slug, session),
|
| 3230 |
),
|
| 3231 |
+
inputs=[selected_project_state, selected_dataset_repo_state, table, cache_key_state, session_state],
|
| 3232 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3233 |
)
|
| 3234 |
next_event.then(
|
|
|
|
| 3236 |
inputs=[table],
|
| 3237 |
outputs=[validation_summary_cards],
|
| 3238 |
).then(
|
| 3239 |
+
fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
|
| 3240 |
audio_service=audio_service,
|
| 3241 |
dataset_repo=repo,
|
| 3242 |
rows=rows,
|
| 3243 |
cache_key=cache_key,
|
| 3244 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
| 3245 |
+
hf_token=_project_fetch_token(project_slug, session),
|
| 3246 |
),
|
| 3247 |
+
inputs=[selected_project_state, selected_dataset_repo_state, table, cache_key_state, session_state],
|
| 3248 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3249 |
)
|
| 3250 |
prev_event.then(
|
|
|
|
| 3252 |
inputs=[table],
|
| 3253 |
outputs=[validation_summary_cards],
|
| 3254 |
).then(
|
| 3255 |
+
fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
|
| 3256 |
audio_service=audio_service,
|
| 3257 |
dataset_repo=repo,
|
| 3258 |
rows=rows,
|
| 3259 |
cache_key=cache_key,
|
| 3260 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
| 3261 |
+
hf_token=_project_fetch_token(project_slug, session),
|
| 3262 |
),
|
| 3263 |
+
inputs=[selected_project_state, selected_dataset_repo_state, table, cache_key_state, session_state],
|
| 3264 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3265 |
)
|
| 3266 |
|
|
|
|
| 3520 |
)
|
| 3521 |
|
| 3522 |
approve_event.then(
|
| 3523 |
+
fn=lambda project_slug, repo, rows, idx, cache_key, session: _advance_to_next_row_with_title(
|
| 3524 |
audio_service=audio_service,
|
| 3525 |
dataset_repo=repo,
|
| 3526 |
rows=rows,
|
| 3527 |
selected_index=int(idx),
|
| 3528 |
cache_key=cache_key,
|
| 3529 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
| 3530 |
+
hf_token=_project_fetch_token(project_slug, session),
|
| 3531 |
),
|
| 3532 |
+
inputs=[selected_project_state, selected_dataset_repo_state, table, selected_index, cache_key_state, session_state],
|
| 3533 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3534 |
).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3535 |
|
| 3536 |
reject_event.then(
|
| 3537 |
+
fn=lambda project_slug, repo, rows, idx, cache_key, session: _advance_to_next_row_with_title(
|
| 3538 |
audio_service=audio_service,
|
| 3539 |
dataset_repo=repo,
|
| 3540 |
rows=rows,
|
| 3541 |
selected_index=int(idx),
|
| 3542 |
cache_key=cache_key,
|
| 3543 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
| 3544 |
+
hf_token=_project_fetch_token(project_slug, session),
|
| 3545 |
),
|
| 3546 |
+
inputs=[selected_project_state, selected_dataset_repo_state, table, selected_index, cache_key_state, session_state],
|
| 3547 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3548 |
).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3549 |
|
| 3550 |
uncertain_event.then(
|
| 3551 |
+
fn=lambda project_slug, repo, rows, idx, cache_key, session: _advance_to_next_row_with_title(
|
| 3552 |
audio_service=audio_service,
|
| 3553 |
dataset_repo=repo,
|
| 3554 |
rows=rows,
|
| 3555 |
selected_index=int(idx),
|
| 3556 |
cache_key=cache_key,
|
| 3557 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
| 3558 |
+
hf_token=_project_fetch_token(project_slug, session),
|
| 3559 |
),
|
| 3560 |
+
inputs=[selected_project_state, selected_dataset_repo_state, table, selected_index, cache_key_state, session_state],
|
| 3561 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3562 |
).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3563 |
|
| 3564 |
skip_event.then(
|
| 3565 |
+
fn=lambda project_slug, repo, rows, idx, cache_key, session: _advance_to_next_row_with_title(
|
| 3566 |
audio_service=audio_service,
|
| 3567 |
dataset_repo=repo,
|
| 3568 |
rows=rows,
|
| 3569 |
selected_index=int(idx),
|
| 3570 |
cache_key=cache_key,
|
| 3571 |
allow_demo_fallback=runtime_config.enable_demo_bootstrap,
|
| 3572 |
+
hf_token=_project_fetch_token(project_slug, session),
|
| 3573 |
),
|
| 3574 |
+
inputs=[selected_project_state, selected_dataset_repo_state, table, selected_index, cache_key_state, session_state],
|
| 3575 |
outputs=[selected_index, audio_player, cache_key_state, status, spectrogram_image, spectrogram_title],
|
| 3576 |
).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3577 |
|
| 3578 |
+
session_state.change(
|
| 3579 |
+
fn=lambda s: gr.update(value=(s.username if s is not None else "")),
|
| 3580 |
+
inputs=[session_state],
|
| 3581 |
+
outputs=[validator_name],
|
| 3582 |
+
)
|
| 3583 |
+
|
| 3584 |
reapply_event.then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3585 |
batch_approve_event.then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
| 3586 |
batch_reject_event.then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
|
src/ui/login_page.py
CHANGED
|
@@ -26,6 +26,12 @@ def create_login_page(auth_service: AuthService) -> Tuple[gr.Blocks, gr.Textbox,
|
|
| 26 |
placeholder="Enter your username",
|
| 27 |
lines=1,
|
| 28 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
error_message = gr.Markdown()
|
| 31 |
|
|
@@ -37,7 +43,7 @@ def create_login_page(auth_service: AuthService) -> Tuple[gr.Blocks, gr.Textbox,
|
|
| 37 |
visible=False,
|
| 38 |
)
|
| 39 |
|
| 40 |
-
def perform_login(username: str) -> Tuple[str, str]:
|
| 41 |
"""Attempt login and return session ID or error message.
|
| 42 |
|
| 43 |
Args:
|
|
@@ -46,8 +52,14 @@ def create_login_page(auth_service: AuthService) -> Tuple[gr.Blocks, gr.Textbox,
|
|
| 46 |
Returns:
|
| 47 |
Tuple of (session_id, error_message)
|
| 48 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
if not username or not username.strip():
|
| 50 |
-
return "", "❌ Please enter a username"
|
| 51 |
|
| 52 |
username = username.strip()
|
| 53 |
session = auth_service.login(username)
|
|
@@ -59,7 +71,7 @@ def create_login_page(auth_service: AuthService) -> Tuple[gr.Blocks, gr.Textbox,
|
|
| 59 |
|
| 60 |
login_button.click(
|
| 61 |
fn=perform_login,
|
| 62 |
-
inputs=[username_input],
|
| 63 |
outputs=[session_output, error_message],
|
| 64 |
)
|
| 65 |
|
|
|
|
| 26 |
placeholder="Enter your username",
|
| 27 |
lines=1,
|
| 28 |
)
|
| 29 |
+
hf_token_input = gr.Textbox(
|
| 30 |
+
label="Hugging Face Token (recommended)",
|
| 31 |
+
placeholder="hf_xxx...",
|
| 32 |
+
type="password",
|
| 33 |
+
lines=1,
|
| 34 |
+
)
|
| 35 |
|
| 36 |
error_message = gr.Markdown()
|
| 37 |
|
|
|
|
| 43 |
visible=False,
|
| 44 |
)
|
| 45 |
|
| 46 |
+
def perform_login(username: str, hf_token: str) -> Tuple[str, str]:
|
| 47 |
"""Attempt login and return session ID or error message.
|
| 48 |
|
| 49 |
Args:
|
|
|
|
| 52 |
Returns:
|
| 53 |
Tuple of (session_id, error_message)
|
| 54 |
"""
|
| 55 |
+
if hf_token and hf_token.strip():
|
| 56 |
+
session, message = auth_service.login_with_hf_token(hf_token)
|
| 57 |
+
if session is None:
|
| 58 |
+
return "", message
|
| 59 |
+
return session.session_id, message
|
| 60 |
+
|
| 61 |
if not username or not username.strip():
|
| 62 |
+
return "", "❌ Please enter a username or provide a Hugging Face token"
|
| 63 |
|
| 64 |
username = username.strip()
|
| 65 |
session = auth_service.login(username)
|
|
|
|
| 71 |
|
| 72 |
login_button.click(
|
| 73 |
fn=perform_login,
|
| 74 |
+
inputs=[username_input, hf_token_input],
|
| 75 |
outputs=[session_output, error_message],
|
| 76 |
)
|
| 77 |
|
tests/unit/test_app_factory_audio_helpers.py
CHANGED
|
@@ -799,6 +799,8 @@ def test_bootstrap_auth_and_projects_uses_config_files_without_demo_fallback(tmp
|
|
| 799 |
page_size=25,
|
| 800 |
projects_file_path=str(projects_file),
|
| 801 |
user_access_file_path=str(users_file),
|
|
|
|
|
|
|
| 802 |
enable_demo_bootstrap=False,
|
| 803 |
)
|
| 804 |
auth_service = AuthService()
|
|
@@ -818,6 +820,8 @@ def test_bootstrap_auth_and_projects_warns_when_not_configured(tmp_path: Path) -
|
|
| 818 |
page_size=25,
|
| 819 |
projects_file_path=None,
|
| 820 |
user_access_file_path=None,
|
|
|
|
|
|
|
| 821 |
enable_demo_bootstrap=False,
|
| 822 |
)
|
| 823 |
auth_service = AuthService()
|
|
|
|
| 799 |
page_size=25,
|
| 800 |
projects_file_path=str(projects_file),
|
| 801 |
user_access_file_path=str(users_file),
|
| 802 |
+
invites_file_path=None,
|
| 803 |
+
invite_ttl_hours=72,
|
| 804 |
enable_demo_bootstrap=False,
|
| 805 |
)
|
| 806 |
auth_service = AuthService()
|
|
|
|
| 820 |
page_size=25,
|
| 821 |
projects_file_path=None,
|
| 822 |
user_access_file_path=None,
|
| 823 |
+
invites_file_path=None,
|
| 824 |
+
invite_ttl_hours=72,
|
| 825 |
enable_demo_bootstrap=False,
|
| 826 |
)
|
| 827 |
auth_service = AuthService()
|
tests/unit/test_auth_service.py
CHANGED
|
@@ -249,6 +249,102 @@ class TestAuthService:
|
|
| 249 |
auth_service.logout(session_admin.session_id)
|
| 250 |
assert auth_service.get_session(session_validator.session_id) is not None
|
| 251 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
class TestUserProjectAccess:
|
| 254 |
"""Test UserProjectAccess model."""
|
|
|
|
| 249 |
auth_service.logout(session_admin.session_id)
|
| 250 |
assert auth_service.get_session(session_validator.session_id) is not None
|
| 251 |
|
| 252 |
+
def test_invite_accept_flow_grants_access(self, auth_service):
|
| 253 |
+
auth_service.register_user_project_access("owner", {"proj-1": Role.admin})
|
| 254 |
+
|
| 255 |
+
ok, _ = auth_service.create_project_invite(
|
| 256 |
+
username="validator_new",
|
| 257 |
+
project_slug="proj-1",
|
| 258 |
+
role=Role.validator,
|
| 259 |
+
invited_by="owner",
|
| 260 |
+
)
|
| 261 |
+
assert ok is True
|
| 262 |
+
|
| 263 |
+
pending = auth_service.list_pending_invites("validator_new")
|
| 264 |
+
assert len(pending) == 1
|
| 265 |
+
assert pending[0].project_slug == "proj-1"
|
| 266 |
+
|
| 267 |
+
accepted, _ = auth_service.accept_project_invite("validator_new", "proj-1")
|
| 268 |
+
assert accepted is True
|
| 269 |
+
assert auth_service.get_user_role_for_project("validator_new", "proj-1") == Role.validator
|
| 270 |
+
assert auth_service.list_pending_invites("validator_new") == []
|
| 271 |
+
|
| 272 |
+
def test_invited_user_can_login_before_accepting(self, auth_service):
|
| 273 |
+
ok, _ = auth_service.create_project_invite(
|
| 274 |
+
username="pending_user",
|
| 275 |
+
project_slug="proj-1",
|
| 276 |
+
role=Role.validator,
|
| 277 |
+
invited_by="owner",
|
| 278 |
+
)
|
| 279 |
+
assert ok is True
|
| 280 |
+
|
| 281 |
+
session = auth_service.login_internal("pending_user")
|
| 282 |
+
assert session is not None
|
| 283 |
+
assert session.username == "pending_user"
|
| 284 |
+
assert session.authorized_projects == []
|
| 285 |
+
|
| 286 |
+
def test_reject_invite_removes_pending(self, auth_service):
|
| 287 |
+
ok, _ = auth_service.create_project_invite(
|
| 288 |
+
username="pending_user",
|
| 289 |
+
project_slug="proj-1",
|
| 290 |
+
role=Role.validator,
|
| 291 |
+
invited_by="owner",
|
| 292 |
+
)
|
| 293 |
+
assert ok is True
|
| 294 |
+
|
| 295 |
+
rejected, _ = auth_service.reject_project_invite("pending_user", "proj-1")
|
| 296 |
+
assert rejected is True
|
| 297 |
+
assert auth_service.list_pending_invites("pending_user") == []
|
| 298 |
+
|
| 299 |
+
def test_accept_all_project_invites(self, auth_service):
|
| 300 |
+
ok1, _ = auth_service.create_project_invite(
|
| 301 |
+
username="pending_user",
|
| 302 |
+
project_slug="proj-1",
|
| 303 |
+
role=Role.validator,
|
| 304 |
+
invited_by="owner",
|
| 305 |
+
)
|
| 306 |
+
ok2, _ = auth_service.create_project_invite(
|
| 307 |
+
username="pending_user",
|
| 308 |
+
project_slug="proj-2",
|
| 309 |
+
role=Role.admin,
|
| 310 |
+
invited_by="owner",
|
| 311 |
+
)
|
| 312 |
+
assert ok1 and ok2
|
| 313 |
+
|
| 314 |
+
accepted, failed, _ = auth_service.accept_all_project_invites("pending_user")
|
| 315 |
+
assert accepted == 2
|
| 316 |
+
assert failed == 0
|
| 317 |
+
assert auth_service.get_user_role_for_project("pending_user", "proj-1") == Role.validator
|
| 318 |
+
assert auth_service.get_user_role_for_project("pending_user", "proj-2") == Role.admin
|
| 319 |
+
|
| 320 |
+
def test_revoke_project_invite(self, auth_service):
|
| 321 |
+
ok, _ = auth_service.create_project_invite(
|
| 322 |
+
username="pending_user",
|
| 323 |
+
project_slug="proj-1",
|
| 324 |
+
role=Role.validator,
|
| 325 |
+
invited_by="owner",
|
| 326 |
+
)
|
| 327 |
+
assert ok is True
|
| 328 |
+
|
| 329 |
+
revoked, _ = auth_service.revoke_project_invite("pending_user", "proj-1")
|
| 330 |
+
assert revoked is True
|
| 331 |
+
assert auth_service.list_pending_invites("pending_user") == []
|
| 332 |
+
|
| 333 |
+
def test_expired_invite_is_pruned(self):
|
| 334 |
+
service = AuthService(session_ttl_minutes=120, invite_ttl_hours=1)
|
| 335 |
+
ok, _ = service.create_project_invite(
|
| 336 |
+
username="pending_user",
|
| 337 |
+
project_slug="proj-1",
|
| 338 |
+
role=Role.validator,
|
| 339 |
+
invited_by="owner",
|
| 340 |
+
)
|
| 341 |
+
assert ok is True
|
| 342 |
+
|
| 343 |
+
invite = service.list_pending_invites("pending_user")[0]
|
| 344 |
+
invite.expires_at = datetime.now(UTC) - timedelta(seconds=1)
|
| 345 |
+
|
| 346 |
+
assert service.list_pending_invites("pending_user") == []
|
| 347 |
+
|
| 348 |
|
| 349 |
class TestUserProjectAccess:
|
| 350 |
"""Test UserProjectAccess model."""
|