jrrribeiro commited on
Commit
2a425c9
·
verified ·
1 Parent(s): c7d81f9

Sync app from GitHub Actions (feature/project-state-security-privacy-review)

Browse files
src/services/hf_project_resource_deletion.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Permanent deletion helpers for administrator-owned Hugging Face project resources."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Protocol
5
+
6
+ from huggingface_hub import HfApi
7
+
8
+ from src.domain.models import Project
9
+
10
+
11
+ class HfProjectResourceDeletionError(RuntimeError):
12
+ """Raised when project resources cannot be safely deleted."""
13
+
14
+
15
+ class _DeletionApi(Protocol):
16
+ def whoami(self, *, token: str | bool | None = None) -> dict[str, object]: ...
17
+
18
+ def delete_repo(
19
+ self,
20
+ repo_id: str,
21
+ *,
22
+ token: str | bool | None = None,
23
+ repo_type: str | None = None,
24
+ missing_ok: bool = False,
25
+ ) -> None: ...
26
+
27
+ def delete_bucket(
28
+ self,
29
+ bucket_id: str,
30
+ *,
31
+ token: str | bool | None = None,
32
+ missing_ok: bool = False,
33
+ ) -> None: ...
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class HfProjectResourceDeletionResult:
38
+ deleted_bucket_id: str | None
39
+ deleted_state_repo_id: str | None
40
+ deleted_dataset_repo_id: str
41
+
42
+
43
+ def _repo_namespace(repo_id: str) -> str:
44
+ value = (repo_id or "").strip()
45
+ if "/" not in value:
46
+ raise HfProjectResourceDeletionError(f"Repository id '{value}' must be in owner/name format.")
47
+ namespace, name = value.split("/", 1)
48
+ if not namespace.strip() or not name.strip():
49
+ raise HfProjectResourceDeletionError(f"Repository id '{value}' must be in owner/name format.")
50
+ return namespace.strip()
51
+
52
+
53
+ def _ensure_same_namespace(*, label: str, resource_id: str, namespace: str) -> None:
54
+ resource_namespace = _repo_namespace(resource_id)
55
+ if resource_namespace.casefold() != namespace.casefold():
56
+ raise HfProjectResourceDeletionError(
57
+ f"Refusing to delete {label} '{resource_id}' because it is not in namespace '{namespace}'."
58
+ )
59
+
60
+
61
+ class HfProjectResourceDeleter:
62
+ """Delete the dataset, companion state repo, and validation Bucket for a project."""
63
+
64
+ def __init__(self, api: _DeletionApi | None = None) -> None:
65
+ self._api = api or HfApi()
66
+
67
+ def delete_project_resources(
68
+ self,
69
+ *,
70
+ project: Project,
71
+ actor_username: str,
72
+ storage_token: str | None,
73
+ confirmed_slug: str,
74
+ confirmation_checked: bool,
75
+ ) -> HfProjectResourceDeletionResult:
76
+ actor = (actor_username or "").strip()
77
+ token = (storage_token or "").strip()
78
+ expected_slug = (project.project_slug or "").strip()
79
+ typed_slug = (confirmed_slug or "").strip()
80
+ owner = (project.owner_username or "").strip()
81
+ dataset_repo_id = (project.dataset_repo_id or "").strip()
82
+ state_repo_id = (project.state_repo_id or "").strip() or None
83
+ bucket_id = (project.validation_bucket_id or "").strip() or None
84
+
85
+ if not actor:
86
+ raise HfProjectResourceDeletionError("Login is required before deleting a project.")
87
+ if not token:
88
+ raise HfProjectResourceDeletionError(
89
+ "Permanent deletion requires the configured administrator storage token."
90
+ )
91
+ if not expected_slug or typed_slug != expected_slug or not confirmation_checked:
92
+ raise HfProjectResourceDeletionError(
93
+ "Deletion was not confirmed. Type the exact project slug and check the confirmation box."
94
+ )
95
+ if not owner:
96
+ raise HfProjectResourceDeletionError("Project owner is missing; deletion is blocked.")
97
+ if actor.casefold() != owner.casefold():
98
+ raise HfProjectResourceDeletionError("Only the project creator can permanently delete this project.")
99
+ if not dataset_repo_id:
100
+ raise HfProjectResourceDeletionError("Project dataset repository is missing; deletion is blocked.")
101
+
102
+ namespace = _repo_namespace(dataset_repo_id)
103
+ if namespace.casefold() != owner.casefold():
104
+ raise HfProjectResourceDeletionError(
105
+ "Refusing to delete project resources because the dataset namespace does not match the project owner."
106
+ )
107
+ if state_repo_id:
108
+ _ensure_same_namespace(label="state repository", resource_id=state_repo_id, namespace=namespace)
109
+ if bucket_id:
110
+ _ensure_same_namespace(label="validation Bucket", resource_id=bucket_id, namespace=namespace)
111
+
112
+ identity = self._api.whoami(token=token)
113
+ token_owner = str(identity.get("name") or identity.get("fullname") or "").strip()
114
+ if token_owner and token_owner.casefold() != namespace.casefold():
115
+ raise HfProjectResourceDeletionError(
116
+ "The configured storage token does not belong to the project owner namespace."
117
+ )
118
+
119
+ if bucket_id:
120
+ self._api.delete_bucket(bucket_id, token=token, missing_ok=True)
121
+ if state_repo_id:
122
+ self._api.delete_repo(state_repo_id, repo_type="dataset", token=token, missing_ok=True)
123
+ self._api.delete_repo(dataset_repo_id, repo_type="dataset", token=token, missing_ok=True)
124
+
125
+ return HfProjectResourceDeletionResult(
126
+ deleted_bucket_id=bucket_id,
127
+ deleted_state_repo_id=state_repo_id,
128
+ deleted_dataset_repo_id=dataset_repo_id,
129
+ )
src/ui/app_factory.py CHANGED
@@ -48,12 +48,13 @@ from src.services.hf_project_state_store import (
48
  HfProjectStateStoreLoader,
49
  HfProjectStateStoreSync,
50
  )
 
51
  from src.services.validation_service import ValidationService
52
  from src.services.invite_email_notifier import EmailJSInviteEmailNotifier, InviteEmailNotifier
53
  from src.auth.auth_service import AuthService
54
  from src.ui.login_page import create_login_page
55
  from src.ui.admin_panel import AdminPanelManager
56
- from src.ui.components import admin_overview_html, compact_metric_grid, coverage_bars_html, inline_hint_html, invite_panel_html, paged_activity_html, project_context_html, project_overview_html, section_header_html, selected_segment_html, settings_health_html
57
  from src.ui.theme import APP_CSS, app_header_html
58
 
59
 
@@ -1579,8 +1580,6 @@ def _bootstrap_auth_and_projects(
1579
  warnings.append(f"⚠️ {discovery_message}")
1580
  if hf_load_errors:
1581
  warnings.append("⚠️ Some HF project-state repos could not be loaded: " + " | ".join(hf_load_errors))
1582
- if hf_loaded_state:
1583
- warnings.append(f"Loaded {len(hf_loaded_state)} project(s) from HF project-state repo(s).")
1584
  return "\n\n".join(warnings)
1585
 
1586
 
@@ -2178,6 +2177,77 @@ def _build_validation_summary_cards(rows: object) -> str:
2178
  )
2179
 
2180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2181
  def _autofetch_first_row(
2182
  audio_service: _AudioServiceProtocol,
2183
  dataset_repo: str,
@@ -3086,6 +3156,7 @@ def create_app() -> gr.Blocks:
3086
  validation_service = ValidationService(validation_repository)
3087
  hf_state_initializer = HfProjectStateStoreInitializer()
3088
  hf_bucket_initializer = HfBucketValidationInitializer()
 
3089
  hf_state_connector = HfProjectStateStoreConnector()
3090
  hf_state_sync = HfProjectStateStoreSync()
3091
  report_cache: dict[tuple[str, int, int, str], tuple[float, tuple[object, ...]]] = {}
@@ -3400,7 +3471,7 @@ def create_app() -> gr.Blocks:
3400
  "Administrative actions are scoped by project role. Keep dataset tokens restricted to the projects that need them.",
3401
  )
3402
  )
3403
- admin_info = gr.Markdown(value="Login required")
3404
  admin_scope_info = gr.Markdown(value="")
3405
  admin_overview = gr.HTML(value=admin_overview_html(username=None, total_projects=0, admin_projects=0, validator_projects=0, pending_invites=0))
3406
 
@@ -3431,16 +3502,11 @@ def create_app() -> gr.Blocks:
3431
  """Show admin panel or access denied message."""
3432
  if session is None:
3433
  return (
3434
- "**Not authenticated** - Login first in the **Login** tab.",
3435
  gr.update(visible=False),
3436
  )
3437
- admin_projects = _admin_projects_for_session(session)
3438
  return (
3439
- (
3440
- f"**Admin workspace** - Welcome, {session.username}. "
3441
- f"You are admin in {len(admin_projects)} project(s). "
3442
- "You can always create a new project and become its admin."
3443
- ),
3444
  gr.update(visible=True),
3445
  )
3446
 
@@ -3987,30 +4053,56 @@ def create_app() -> gr.Blocks:
3987
  outputs=[token_update_message, token_new_value, token_clear_checkbox, projects_table, seed_warning_state],
3988
  )
3989
 
3990
- def delete_project(session, project_slug: str):
3991
  if session is None:
3992
- return "Access denied. Login required.", gr.update(), gr.update(), gr.update(), session, gr.update(), gr.update()
3993
  if not _is_admin_for_project(session, project_slug):
3994
- return "Access denied. You must be admin of the selected project.", gr.update(), gr.update(), gr.update(), session, gr.update(), gr.update()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3995
 
3996
- project_to_archive = admin_manager.get_project(project_slug)
3997
- archived_project = (
3998
- project_to_archive.model_copy(update={"active": False, "state_status": "archived"})
3999
- if project_to_archive is not None
4000
- else None
4001
- )
4002
  success, msg = admin_manager.delete_project(session.username, project_slug)
4003
  if not success:
4004
- return msg, _project_rows(), gr.update(choices=_project_slugs()), gr.update(choices=_project_slugs()), session, gr.update(), gr.update()
4005
 
4006
  persisted, persist_error = _persist_admin_state(
4007
  allowed_removed_project_slugs={project_slug},
4008
  session=session,
4009
- sync_project_slugs={project_slug},
4010
- archived_projects=[archived_project] if archived_project is not None else [],
4011
  )
4012
  if not persisted:
4013
  msg = f"{msg} | Persistence failed: {persist_error}"
 
 
 
 
 
 
 
4014
 
4015
  _invalidate_project_queue(project_slug)
4016
  refreshed_warning = ""
@@ -4025,6 +4117,8 @@ def create_app() -> gr.Blocks:
4025
  refreshed_session,
4026
  refreshed_warning,
4027
  gr.update(choices=admin_projects, value=None),
 
 
4028
  )
4029
 
4030
  with gr.Column(visible=False, elem_classes=["bn-admin-section", "bn-admin-delete-section"]) as admin_delete_controls:
@@ -4033,15 +4127,23 @@ def create_app() -> gr.Blocks:
4033
  section_header_html(
4034
  "Project",
4035
  "Delete project",
4036
- "Remove a project from this validator workspace without deleting its Hugging Face dataset.",
4037
  class_name="bn-panel-soft",
4038
  )
4039
  )
4040
- gr.HTML(inline_hint_html("Deleting a project removes assignments and pending invites.", "danger"))
4041
  delete_project_slug = gr.Dropdown(
4042
  choices=_project_slugs(),
4043
  label="Project to delete",
4044
  )
 
 
 
 
 
 
 
 
4045
  delete_project_message = gr.Markdown()
4046
  delete_project_btn = gr.Button(
4047
  "Delete Project",
@@ -4306,7 +4408,12 @@ def create_app() -> gr.Blocks:
4306
 
4307
  delete_project_btn.click(
4308
  fn=delete_project,
4309
- inputs=[session_state, delete_project_slug],
 
 
 
 
 
4310
  outputs=[
4311
  delete_project_message,
4312
  projects_table,
@@ -4315,6 +4422,8 @@ def create_app() -> gr.Blocks:
4315
  session_state,
4316
  seed_warning_state,
4317
  delete_project_slug,
 
 
4318
  ],
4319
  )
4320
 
@@ -4416,7 +4525,7 @@ def create_app() -> gr.Blocks:
4416
  "Project access is filtered by your role. Invitations can be accepted here before validation starts.",
4417
  )
4418
  )
4419
- project_overview = gr.HTML(value=project_overview_html([], []), visible=False)
4420
  project_info_display = gr.Markdown(
4421
  value="Login first in the **Login** tab"
4422
  )
@@ -4427,21 +4536,22 @@ def create_app() -> gr.Blocks:
4427
  interactive=False,
4428
  allow_custom_value=True,
4429
  )
4430
- invitations_info = gr.Markdown(value="")
4431
- invitations_overview = gr.HTML(value=invite_panel_html(0))
4432
- invite_selector = gr.Dropdown(choices=[], label="Pending Invites", interactive=False)
4433
- with gr.Row():
4434
- refresh_invites_btn = gr.Button("Refresh invites", elem_classes=["bn-soft-action"])
4435
- accept_invite_btn = gr.Button("Accept Invite", elem_classes=["bn-soft-action"])
4436
- accept_all_invites_btn = gr.Button("Accept All", elem_classes=["bn-soft-action"])
4437
- reject_invite_btn = gr.Button("Reject Invite", elem_classes=["bn-soft-action"])
 
4438
 
4439
  def update_project_selector(session):
4440
  """Update project dropdown when user logs in."""
4441
  if session is None:
4442
  return (
4443
  gr.update(choices=[], value=None, interactive=False),
4444
- project_overview_html([], []),
4445
  "Not authenticated. Login first.",
4446
  project_context_html(None),
4447
  None,
@@ -4452,7 +4562,7 @@ def create_app() -> gr.Blocks:
4452
  if not projects:
4453
  return (
4454
  gr.update(choices=[], value=None, interactive=False),
4455
- project_overview_html(_project_rows(), []),
4456
  (
4457
  "**No projects available yet**\n\n"
4458
  "To get started:\n"
@@ -4474,7 +4584,7 @@ def create_app() -> gr.Blocks:
4474
  project_row = next((row for row in _project_rows() if row and str(row[0]) == selected), None)
4475
  return (
4476
  gr.update(choices=projects, value=selected, interactive=True),
4477
- project_overview_html(_project_rows(), projects, selected),
4478
  "",
4479
  project_context_html(project_row, role_label),
4480
  selected,
@@ -4511,16 +4621,17 @@ def create_app() -> gr.Blocks:
4511
 
4512
  def _build_invites_ui(session):
4513
  if session is None:
4514
- return gr.update(value="", visible=False), invite_panel_html(0), gr.update(choices=[], value=None, interactive=False)
4515
  invites = auth_service.list_pending_invites(session.username)
4516
  if not invites:
4517
- return gr.update(value="No pending invites", visible=True), invite_panel_html(0), gr.update(choices=[], value=None, interactive=False)
4518
  encoded = [_format_invite_option(item) for item in invites]
4519
  labeled_choices = [(_build_invite_label(invite), encoded_value) for invite, encoded_value in zip(invites, encoded)]
4520
  return (
4521
  gr.update(value=f"Pending invites: {len(labeled_choices)}", visible=True),
4522
- invite_panel_html(len(labeled_choices)),
4523
  gr.update(choices=labeled_choices, value=encoded[0], interactive=True),
 
4524
  )
4525
 
4526
  def _parse_invite_option(raw_option: str) -> tuple[str, str, str]:
@@ -4594,13 +4705,13 @@ def create_app() -> gr.Blocks:
4594
  session_state.change(
4595
  fn=_build_invites_ui,
4596
  inputs=[session_state],
4597
- outputs=[invitations_info, invitations_overview, invite_selector],
4598
  )
4599
 
4600
  refresh_invites_btn.click(
4601
  fn=_build_invites_ui,
4602
  inputs=[session_state],
4603
- outputs=[invitations_info, invitations_overview, invite_selector],
4604
  )
4605
 
4606
  accept_invite_btn.click(
@@ -4614,7 +4725,7 @@ def create_app() -> gr.Blocks:
4614
  ).then(
4615
  fn=_build_invites_ui,
4616
  inputs=[session_state],
4617
- outputs=[invitations_info, invitations_overview, invite_selector],
4618
  )
4619
 
4620
  accept_all_invites_btn.click(
@@ -4628,7 +4739,7 @@ def create_app() -> gr.Blocks:
4628
  ).then(
4629
  fn=_build_invites_ui,
4630
  inputs=[session_state],
4631
- outputs=[invitations_info, invitations_overview, invite_selector],
4632
  )
4633
 
4634
  reject_invite_btn.click(
@@ -4638,7 +4749,7 @@ def create_app() -> gr.Blocks:
4638
  ).then(
4639
  fn=_build_invites_ui,
4640
  inputs=[session_state],
4641
- outputs=[invitations_info, invitations_overview, invite_selector],
4642
  )
4643
 
4644
  def update_selected_project(selected: str, session):
@@ -4649,8 +4760,8 @@ def create_app() -> gr.Blocks:
4649
  role = auth_service.get_user_role_for_project(session.username, selected)
4650
  role_label = role.value.upper() if role else "UNKNOWN"
4651
  project_row = next((row for row in _project_rows() if row and str(row[0]) == selected), None)
4652
- return selected, dataset_repo_id, project_overview_html(_project_rows(), session.authorized_projects, selected), project_context_html(project_row, role_label)
4653
- return None, "", project_overview_html([], []), project_context_html(None)
4654
 
4655
  project_selector.change(
4656
  fn=update_selected_project,
@@ -4665,7 +4776,7 @@ def create_app() -> gr.Blocks:
4665
  ).then(
4666
  fn=_build_invites_ui,
4667
  inputs=[session_state],
4668
- outputs=[invitations_info, invitations_overview, invite_selector],
4669
  ).then(
4670
  fn=_render_admin_overview,
4671
  inputs=[session_state],
@@ -4823,6 +4934,7 @@ def create_app() -> gr.Blocks:
4823
  selected_index = gr.Number(label="Selected row", value=0, precision=0, visible=False)
4824
 
4825
  with gr.Column(scale=4, elem_classes=["bn-sidebar-panel"]):
 
4826
  dataset_repo = gr.Textbox(label="Dataset repo", interactive=False)
4827
  species_filter = gr.Dropdown(
4828
  label="Species",
@@ -4836,18 +4948,17 @@ def create_app() -> gr.Blocks:
4836
  prev_btn = gr.Button("Previous")
4837
  next_btn = gr.Button("Next")
4838
 
4839
- with gr.Group(elem_classes=["bn-filter-panel"]):
4840
- gr.Markdown("### Filters")
4841
- min_confidence = gr.Slider(label="Minimum confidence", minimum=0.0, maximum=1.0, step=0.01, value=0.0)
4842
- validation_status_filter = gr.Dropdown(
4843
- label="Status",
4844
- choices=["all", "pending", "positive", "negative", "uncertain", "skip"],
4845
- value="all",
4846
- )
4847
- validator_filter = gr.Textbox(label="Validator", placeholder="Ex: validator_001")
4848
- updated_after_filter = gr.DateTime(label="Updated since", include_time=False, type="string")
4849
- show_conflicts_only = gr.Checkbox(label="Show only conflicts", value=False)
4850
- refresh_btn = gr.Button("Apply filters", variant="primary")
4851
 
4852
  gr.Markdown("### Review details")
4853
  validator_name = gr.Textbox(label="Validator", value="", interactive=False)
@@ -5219,6 +5330,18 @@ def create_app() -> gr.Blocks:
5219
  hf_token=_project_fetch_token(project_slug, session),
5220
  )
5221
 
 
 
 
 
 
 
 
 
 
 
 
 
5222
  refresh_event = refresh_btn.click(
5223
  fn=refresh,
5224
  inputs=[
@@ -5300,8 +5423,8 @@ def create_app() -> gr.Blocks:
5300
  ],
5301
  outputs=[table, status, page_state],
5302
  ).then(
5303
- fn=lambda rows: _build_validation_summary_cards(rows),
5304
- inputs=[table],
5305
  outputs=[validation_summary_cards],
5306
  ).then(
5307
  fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
@@ -5353,8 +5476,8 @@ def create_app() -> gr.Blocks:
5353
  )
5354
 
5355
  refresh_event.then(
5356
- fn=lambda rows: _build_validation_summary_cards(rows),
5357
- inputs=[table],
5358
  outputs=[validation_summary_cards],
5359
  ).then(
5360
  fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
@@ -5377,8 +5500,8 @@ def create_app() -> gr.Blocks:
5377
  outputs=[favorite_btn],
5378
  )
5379
  next_event.then(
5380
- fn=lambda rows: _build_validation_summary_cards(rows),
5381
- inputs=[table],
5382
  outputs=[validation_summary_cards],
5383
  ).then(
5384
  fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
@@ -5401,8 +5524,8 @@ def create_app() -> gr.Blocks:
5401
  outputs=[favorite_btn],
5402
  )
5403
  prev_event.then(
5404
- fn=lambda rows: _build_validation_summary_cards(rows),
5405
- inputs=[table],
5406
  outputs=[validation_summary_cards],
5407
  ).then(
5408
  fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
@@ -5602,7 +5725,11 @@ def create_app() -> gr.Blocks:
5602
  fn=update_favorite_button_state,
5603
  inputs=[selected_project_state, table, selected_index, favorite_detection_state],
5604
  outputs=[favorite_btn],
5605
- ).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
 
 
 
 
5606
 
5607
  reject_event.then(
5608
  fn=lambda project_slug, repo, rows, idx, cache_key, session: _advance_to_next_row_with_title(
@@ -5624,7 +5751,11 @@ def create_app() -> gr.Blocks:
5624
  fn=update_favorite_button_state,
5625
  inputs=[selected_project_state, table, selected_index, favorite_detection_state],
5626
  outputs=[favorite_btn],
5627
- ).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
 
 
 
 
5628
 
5629
  uncertain_event.then(
5630
  fn=lambda project_slug, repo, rows, idx, cache_key, session: _advance_to_next_row_with_title(
@@ -5646,7 +5777,11 @@ def create_app() -> gr.Blocks:
5646
  fn=update_favorite_button_state,
5647
  inputs=[selected_project_state, table, selected_index, favorite_detection_state],
5648
  outputs=[favorite_btn],
5649
- ).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
 
 
 
 
5650
 
5651
  skip_event.then(
5652
  fn=lambda project_slug, repo, rows, idx, cache_key, session: _advance_to_next_row_with_title(
@@ -5668,7 +5803,11 @@ def create_app() -> gr.Blocks:
5668
  fn=update_favorite_button_state,
5669
  inputs=[selected_project_state, table, selected_index, favorite_detection_state],
5670
  outputs=[favorite_btn],
5671
- ).then(fn=lambda rows: _build_validation_summary_cards(rows), inputs=[table], outputs=[validation_summary_cards])
 
 
 
 
5672
 
5673
  session_state.change(
5674
  fn=lambda s: gr.update(value=(s.username if s is not None else "")),
 
48
  HfProjectStateStoreLoader,
49
  HfProjectStateStoreSync,
50
  )
51
+ from src.services.hf_project_resource_deletion import HfProjectResourceDeleter, HfProjectResourceDeletionError
52
  from src.services.validation_service import ValidationService
53
  from src.services.invite_email_notifier import EmailJSInviteEmailNotifier, InviteEmailNotifier
54
  from src.auth.auth_service import AuthService
55
  from src.ui.login_page import create_login_page
56
  from src.ui.admin_panel import AdminPanelManager
57
+ from src.ui.components import admin_overview_html, compact_metric_grid, coverage_bars_html, inline_hint_html, invite_panel_html, paged_activity_html, project_context_html, section_header_html, selected_segment_html, settings_health_html
58
  from src.ui.theme import APP_CSS, app_header_html
59
 
60
 
 
1580
  warnings.append(f"⚠️ {discovery_message}")
1581
  if hf_load_errors:
1582
  warnings.append("⚠️ Some HF project-state repos could not be loaded: " + " | ".join(hf_load_errors))
 
 
1583
  return "\n\n".join(warnings)
1584
 
1585
 
 
2177
  )
2178
 
2179
 
2180
+ def _build_validation_summary_cards_for_species(
2181
+ *,
2182
+ queue_service: _QueueServiceProtocol,
2183
+ snapshot_reader: _ValidationReadRepositoryProtocol,
2184
+ project_slug: str,
2185
+ scientific_name: str,
2186
+ min_confidence: float,
2187
+ actor_username: str = "",
2188
+ ) -> str:
2189
+ slug = (project_slug or "").strip()
2190
+ species_name = (scientific_name or "").strip()
2191
+ if not slug or not species_name:
2192
+ return _build_validation_summary_cards([])
2193
+
2194
+ list_all = getattr(queue_service, "list_all_detections", None)
2195
+ if callable(list_all):
2196
+ detections = list_all(
2197
+ project_slug=slug,
2198
+ scientific_name=species_name,
2199
+ min_confidence=min_confidence,
2200
+ max_confidence=None,
2201
+ )
2202
+ else:
2203
+ page_result = queue_service.get_page(
2204
+ project_slug=slug,
2205
+ page=1,
2206
+ page_size=1,
2207
+ scientific_name=species_name,
2208
+ min_confidence=min_confidence,
2209
+ )
2210
+ total_items = int(getattr(page_result, "total_items", 0))
2211
+ page_result = queue_service.get_page(
2212
+ project_slug=slug,
2213
+ page=1,
2214
+ page_size=max(1, total_items),
2215
+ scientific_name=species_name,
2216
+ min_confidence=min_confidence,
2217
+ )
2218
+ detections = list(getattr(page_result, "items", []))
2219
+
2220
+ snapshot = snapshot_reader.load_current_snapshot(project_slug=slug, actor_username=actor_username)
2221
+ total = len(detections)
2222
+ positive = 0
2223
+ negative = 0
2224
+ uncertain = 0
2225
+ skipped = 0
2226
+ for detection in detections:
2227
+ status_value = str(snapshot.get(detection.detection_key, {}).get("status", "pending")).strip().lower()
2228
+ if status_value == "positive":
2229
+ positive += 1
2230
+ elif status_value == "negative":
2231
+ negative += 1
2232
+ elif status_value == "uncertain":
2233
+ uncertain += 1
2234
+ elif status_value == "skip":
2235
+ skipped += 1
2236
+
2237
+ reviewed = positive + negative + uncertain + skipped
2238
+ pending = max(0, total - reviewed)
2239
+ reviewed_pct = round((reviewed / total) * 100, 1) if total else 0.0
2240
+
2241
+ return compact_metric_grid(
2242
+ [
2243
+ ("Queue total", str(total), "segments in species", "info"),
2244
+ ("Accepted", str(positive), "positive validations", "positive"),
2245
+ ("Rejected", str(negative), "negative validations", "negative"),
2246
+ ("Reviewed", f"{reviewed_pct}%", f"{pending} pending in species", "warning"),
2247
+ ]
2248
+ )
2249
+
2250
+
2251
  def _autofetch_first_row(
2252
  audio_service: _AudioServiceProtocol,
2253
  dataset_repo: str,
 
3156
  validation_service = ValidationService(validation_repository)
3157
  hf_state_initializer = HfProjectStateStoreInitializer()
3158
  hf_bucket_initializer = HfBucketValidationInitializer()
3159
+ hf_resource_deleter = HfProjectResourceDeleter()
3160
  hf_state_connector = HfProjectStateStoreConnector()
3161
  hf_state_sync = HfProjectStateStoreSync()
3162
  report_cache: dict[tuple[str, int, int, str], tuple[float, tuple[object, ...]]] = {}
 
3471
  "Administrative actions are scoped by project role. Keep dataset tokens restricted to the projects that need them.",
3472
  )
3473
  )
3474
+ admin_info = gr.Markdown(value="", visible=False)
3475
  admin_scope_info = gr.Markdown(value="")
3476
  admin_overview = gr.HTML(value=admin_overview_html(username=None, total_projects=0, admin_projects=0, validator_projects=0, pending_invites=0))
3477
 
 
3502
  """Show admin panel or access denied message."""
3503
  if session is None:
3504
  return (
3505
+ "",
3506
  gr.update(visible=False),
3507
  )
 
3508
  return (
3509
+ "",
 
 
 
 
3510
  gr.update(visible=True),
3511
  )
3512
 
 
4053
  outputs=[token_update_message, token_new_value, token_clear_checkbox, projects_table, seed_warning_state],
4054
  )
4055
 
4056
+ def delete_project(session, project_slug: str, confirm_slug: str, confirm_checked: bool):
4057
  if session is None:
4058
+ return "Access denied. Login required.", gr.update(), gr.update(), gr.update(), session, gr.update(), gr.update(), gr.update(value=""), gr.update(value=False)
4059
  if not _is_admin_for_project(session, project_slug):
4060
+ return "Access denied. You must be admin of the selected project.", gr.update(), gr.update(), gr.update(), session, gr.update(), gr.update(), gr.update(value=""), gr.update(value=False)
4061
+
4062
+ project_to_delete = admin_manager.get_project(project_slug)
4063
+ if project_to_delete is None:
4064
+ return "Select a valid project.", gr.update(), gr.update(), gr.update(), session, gr.update(), gr.update(), gr.update(value=""), gr.update(value=False)
4065
+ if (project_to_delete.owner_username or "").strip().casefold() != session.username.casefold():
4066
+ return "Only the project creator can permanently delete this project.", gr.update(), gr.update(), gr.update(), session, gr.update(), gr.update(), gr.update(), gr.update()
4067
+
4068
+ if runtime_config.hf_admin_storage_mode_enabled:
4069
+ try:
4070
+ delete_result = hf_resource_deleter.delete_project_resources(
4071
+ project=project_to_delete,
4072
+ actor_username=session.username,
4073
+ storage_token=_storage_hf_token(),
4074
+ confirmed_slug=confirm_slug,
4075
+ confirmation_checked=bool(confirm_checked),
4076
+ )
4077
+ except HfProjectResourceDeletionError as exc:
4078
+ return str(exc), gr.update(), gr.update(), gr.update(), session, gr.update(), gr.update(), gr.update(), gr.update()
4079
+ except Exception as exc:
4080
+ return f"Could not permanently delete Hugging Face project resources: {exc}", gr.update(), gr.update(), gr.update(), session, gr.update(), gr.update(), gr.update(), gr.update()
4081
+ else:
4082
+ typed_slug = (confirm_slug or "").strip()
4083
+ if typed_slug != project_slug or not bool(confirm_checked):
4084
+ return "Deletion was not confirmed. Type the exact project slug and check the confirmation box.", gr.update(), gr.update(), gr.update(), session, gr.update(), gr.update(), gr.update(), gr.update()
4085
+ delete_result = None
4086
 
 
 
 
 
 
 
4087
  success, msg = admin_manager.delete_project(session.username, project_slug)
4088
  if not success:
4089
+ return msg, _project_rows(), gr.update(choices=_project_slugs()), gr.update(choices=_project_slugs()), session, gr.update(), gr.update(), gr.update(value=""), gr.update(value=False)
4090
 
4091
  persisted, persist_error = _persist_admin_state(
4092
  allowed_removed_project_slugs={project_slug},
4093
  session=session,
4094
+ sync_project_slugs=set(),
4095
+ sync_hf_state=False,
4096
  )
4097
  if not persisted:
4098
  msg = f"{msg} | Persistence failed: {persist_error}"
4099
+ if delete_result is not None:
4100
+ msg = (
4101
+ f"Project '{project_slug}' and its Hugging Face resources were permanently deleted "
4102
+ f"(dataset: {delete_result.deleted_dataset_repo_id}, "
4103
+ f"state: {delete_result.deleted_state_repo_id or 'none'}, "
4104
+ f"bucket: {delete_result.deleted_bucket_id or 'none'})."
4105
+ )
4106
 
4107
  _invalidate_project_queue(project_slug)
4108
  refreshed_warning = ""
 
4117
  refreshed_session,
4118
  refreshed_warning,
4119
  gr.update(choices=admin_projects, value=None),
4120
+ gr.update(value=""),
4121
+ gr.update(value=False),
4122
  )
4123
 
4124
  with gr.Column(visible=False, elem_classes=["bn-admin-section", "bn-admin-delete-section"]) as admin_delete_controls:
 
4127
  section_header_html(
4128
  "Project",
4129
  "Delete project",
4130
+ "Permanently delete the project, source dataset, private state repo, and validation Bucket.",
4131
  class_name="bn-panel-soft",
4132
  )
4133
  )
4134
+ gr.HTML(inline_hint_html("This cannot be undone. Only the project creator can delete a project.", "danger"))
4135
  delete_project_slug = gr.Dropdown(
4136
  choices=_project_slugs(),
4137
  label="Project to delete",
4138
  )
4139
+ delete_project_confirm_slug = gr.Textbox(
4140
+ label="Type the project slug to confirm",
4141
+ placeholder="Exact project slug",
4142
+ )
4143
+ delete_project_confirm_checkbox = gr.Checkbox(
4144
+ label="I understand this permanently deletes the project resources",
4145
+ value=False,
4146
+ )
4147
  delete_project_message = gr.Markdown()
4148
  delete_project_btn = gr.Button(
4149
  "Delete Project",
 
4408
 
4409
  delete_project_btn.click(
4410
  fn=delete_project,
4411
+ inputs=[
4412
+ session_state,
4413
+ delete_project_slug,
4414
+ delete_project_confirm_slug,
4415
+ delete_project_confirm_checkbox,
4416
+ ],
4417
  outputs=[
4418
  delete_project_message,
4419
  projects_table,
 
4422
  session_state,
4423
  seed_warning_state,
4424
  delete_project_slug,
4425
+ delete_project_confirm_slug,
4426
+ delete_project_confirm_checkbox,
4427
  ],
4428
  )
4429
 
 
4525
  "Project access is filtered by your role. Invitations can be accepted here before validation starts.",
4526
  )
4527
  )
4528
+ project_overview = gr.HTML(value="", visible=False)
4529
  project_info_display = gr.Markdown(
4530
  value="Login first in the **Login** tab"
4531
  )
 
4536
  interactive=False,
4537
  allow_custom_value=True,
4538
  )
4539
+ invitations_info = gr.Markdown(value="", visible=False)
4540
+ invitations_overview = gr.HTML(value="", visible=False)
4541
+ with gr.Group(visible=False) as invite_controls:
4542
+ invite_selector = gr.Dropdown(choices=[], label="Pending Invites", interactive=False)
4543
+ with gr.Row():
4544
+ refresh_invites_btn = gr.Button("Refresh invites", elem_classes=["bn-soft-action"])
4545
+ accept_invite_btn = gr.Button("Accept Invite", elem_classes=["bn-soft-action"])
4546
+ accept_all_invites_btn = gr.Button("Accept All", elem_classes=["bn-soft-action"])
4547
+ reject_invite_btn = gr.Button("Reject Invite", elem_classes=["bn-soft-action"])
4548
 
4549
  def update_project_selector(session):
4550
  """Update project dropdown when user logs in."""
4551
  if session is None:
4552
  return (
4553
  gr.update(choices=[], value=None, interactive=False),
4554
+ gr.update(value="", visible=False),
4555
  "Not authenticated. Login first.",
4556
  project_context_html(None),
4557
  None,
 
4562
  if not projects:
4563
  return (
4564
  gr.update(choices=[], value=None, interactive=False),
4565
+ gr.update(value="", visible=False),
4566
  (
4567
  "**No projects available yet**\n\n"
4568
  "To get started:\n"
 
4584
  project_row = next((row for row in _project_rows() if row and str(row[0]) == selected), None)
4585
  return (
4586
  gr.update(choices=projects, value=selected, interactive=True),
4587
+ gr.update(value="", visible=False),
4588
  "",
4589
  project_context_html(project_row, role_label),
4590
  selected,
 
4621
 
4622
  def _build_invites_ui(session):
4623
  if session is None:
4624
+ return gr.update(value="", visible=False), gr.update(value="", visible=False), gr.update(choices=[], value=None, interactive=False), gr.update(visible=False)
4625
  invites = auth_service.list_pending_invites(session.username)
4626
  if not invites:
4627
+ return gr.update(value="", visible=False), gr.update(value="", visible=False), gr.update(choices=[], value=None, interactive=False), gr.update(visible=False)
4628
  encoded = [_format_invite_option(item) for item in invites]
4629
  labeled_choices = [(_build_invite_label(invite), encoded_value) for invite, encoded_value in zip(invites, encoded)]
4630
  return (
4631
  gr.update(value=f"Pending invites: {len(labeled_choices)}", visible=True),
4632
+ gr.update(value=invite_panel_html(len(labeled_choices)), visible=True),
4633
  gr.update(choices=labeled_choices, value=encoded[0], interactive=True),
4634
+ gr.update(visible=True),
4635
  )
4636
 
4637
  def _parse_invite_option(raw_option: str) -> tuple[str, str, str]:
 
4705
  session_state.change(
4706
  fn=_build_invites_ui,
4707
  inputs=[session_state],
4708
+ outputs=[invitations_info, invitations_overview, invite_selector, invite_controls],
4709
  )
4710
 
4711
  refresh_invites_btn.click(
4712
  fn=_build_invites_ui,
4713
  inputs=[session_state],
4714
+ outputs=[invitations_info, invitations_overview, invite_selector, invite_controls],
4715
  )
4716
 
4717
  accept_invite_btn.click(
 
4725
  ).then(
4726
  fn=_build_invites_ui,
4727
  inputs=[session_state],
4728
+ outputs=[invitations_info, invitations_overview, invite_selector, invite_controls],
4729
  )
4730
 
4731
  accept_all_invites_btn.click(
 
4739
  ).then(
4740
  fn=_build_invites_ui,
4741
  inputs=[session_state],
4742
+ outputs=[invitations_info, invitations_overview, invite_selector, invite_controls],
4743
  )
4744
 
4745
  reject_invite_btn.click(
 
4749
  ).then(
4750
  fn=_build_invites_ui,
4751
  inputs=[session_state],
4752
+ outputs=[invitations_info, invitations_overview, invite_selector, invite_controls],
4753
  )
4754
 
4755
  def update_selected_project(selected: str, session):
 
4760
  role = auth_service.get_user_role_for_project(session.username, selected)
4761
  role_label = role.value.upper() if role else "UNKNOWN"
4762
  project_row = next((row for row in _project_rows() if row and str(row[0]) == selected), None)
4763
+ return selected, dataset_repo_id, gr.update(value="", visible=False), project_context_html(project_row, role_label)
4764
+ return None, "", gr.update(value="", visible=False), project_context_html(None)
4765
 
4766
  project_selector.change(
4767
  fn=update_selected_project,
 
4776
  ).then(
4777
  fn=_build_invites_ui,
4778
  inputs=[session_state],
4779
+ outputs=[invitations_info, invitations_overview, invite_selector, invite_controls],
4780
  ).then(
4781
  fn=_render_admin_overview,
4782
  inputs=[session_state],
 
4934
  selected_index = gr.Number(label="Selected row", value=0, precision=0, visible=False)
4935
 
4936
  with gr.Column(scale=4, elem_classes=["bn-sidebar-panel"]):
4937
+ gr.Markdown("### Dataset Selection")
4938
  dataset_repo = gr.Textbox(label="Dataset repo", interactive=False)
4939
  species_filter = gr.Dropdown(
4940
  label="Species",
 
4948
  prev_btn = gr.Button("Previous")
4949
  next_btn = gr.Button("Next")
4950
 
4951
+ gr.Markdown("### Filters")
4952
+ min_confidence = gr.Slider(label="Minimum confidence", minimum=0.0, maximum=1.0, step=0.01, value=0.0)
4953
+ validation_status_filter = gr.Dropdown(
4954
+ label="Status",
4955
+ choices=["all", "pending", "positive", "negative", "uncertain", "skip"],
4956
+ value="all",
4957
+ )
4958
+ validator_filter = gr.Textbox(label="Validator", placeholder="Ex: validator_001")
4959
+ updated_after_filter = gr.DateTime(label="Updated since", include_time=False, type="string")
4960
+ show_conflicts_only = gr.Checkbox(label="Show only conflicts", value=False)
4961
+ refresh_btn = gr.Button("Apply filters", variant="primary")
 
4962
 
4963
  gr.Markdown("### Review details")
4964
  validator_name = gr.Textbox(label="Validator", value="", interactive=False)
 
5330
  hf_token=_project_fetch_token(project_slug, session),
5331
  )
5332
 
5333
+ def build_species_summary(project_slug: str, species: str, confidence: float, session=None) -> str:
5334
+ if not project_slug or not species or not _can_access_project(session, project_slug):
5335
+ return _build_validation_summary_cards([])
5336
+ return _build_validation_summary_cards_for_species(
5337
+ queue_service=service_ref["queue"],
5338
+ snapshot_reader=validation_repository,
5339
+ project_slug=project_slug,
5340
+ scientific_name=species,
5341
+ min_confidence=float(confidence or 0.0),
5342
+ actor_username=_validator_name_from_session(session),
5343
+ )
5344
+
5345
  refresh_event = refresh_btn.click(
5346
  fn=refresh,
5347
  inputs=[
 
5423
  ],
5424
  outputs=[table, status, page_state],
5425
  ).then(
5426
+ fn=build_species_summary,
5427
+ inputs=[selected_project_state, species_filter, min_confidence, session_state],
5428
  outputs=[validation_summary_cards],
5429
  ).then(
5430
  fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
 
5476
  )
5477
 
5478
  refresh_event.then(
5479
+ fn=build_species_summary,
5480
+ inputs=[selected_project_state, species_filter, min_confidence, session_state],
5481
  outputs=[validation_summary_cards],
5482
  ).then(
5483
  fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
 
5500
  outputs=[favorite_btn],
5501
  )
5502
  next_event.then(
5503
+ fn=build_species_summary,
5504
+ inputs=[selected_project_state, species_filter, min_confidence, session_state],
5505
  outputs=[validation_summary_cards],
5506
  ).then(
5507
  fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
 
5524
  outputs=[favorite_btn],
5525
  )
5526
  prev_event.then(
5527
+ fn=build_species_summary,
5528
+ inputs=[selected_project_state, species_filter, min_confidence, session_state],
5529
  outputs=[validation_summary_cards],
5530
  ).then(
5531
  fn=lambda project_slug, repo, rows, cache_key, session: _autofetch_first_row_with_title(
 
5725
  fn=update_favorite_button_state,
5726
  inputs=[selected_project_state, table, selected_index, favorite_detection_state],
5727
  outputs=[favorite_btn],
5728
+ ).then(
5729
+ fn=build_species_summary,
5730
+ inputs=[selected_project_state, species_filter, min_confidence, session_state],
5731
+ outputs=[validation_summary_cards],
5732
+ )
5733
 
5734
  reject_event.then(
5735
  fn=lambda project_slug, repo, rows, idx, cache_key, session: _advance_to_next_row_with_title(
 
5751
  fn=update_favorite_button_state,
5752
  inputs=[selected_project_state, table, selected_index, favorite_detection_state],
5753
  outputs=[favorite_btn],
5754
+ ).then(
5755
+ fn=build_species_summary,
5756
+ inputs=[selected_project_state, species_filter, min_confidence, session_state],
5757
+ outputs=[validation_summary_cards],
5758
+ )
5759
 
5760
  uncertain_event.then(
5761
  fn=lambda project_slug, repo, rows, idx, cache_key, session: _advance_to_next_row_with_title(
 
5777
  fn=update_favorite_button_state,
5778
  inputs=[selected_project_state, table, selected_index, favorite_detection_state],
5779
  outputs=[favorite_btn],
5780
+ ).then(
5781
+ fn=build_species_summary,
5782
+ inputs=[selected_project_state, species_filter, min_confidence, session_state],
5783
+ outputs=[validation_summary_cards],
5784
+ )
5785
 
5786
  skip_event.then(
5787
  fn=lambda project_slug, repo, rows, idx, cache_key, session: _advance_to_next_row_with_title(
 
5803
  fn=update_favorite_button_state,
5804
  inputs=[selected_project_state, table, selected_index, favorite_detection_state],
5805
  outputs=[favorite_btn],
5806
+ ).then(
5807
+ fn=build_species_summary,
5808
+ inputs=[selected_project_state, species_filter, min_confidence, session_state],
5809
+ outputs=[validation_summary_cards],
5810
+ )
5811
 
5812
  session_state.change(
5813
  fn=lambda s: gr.update(value=(s.username if s is not None else "")),
src/ui/login_page.py CHANGED
@@ -92,17 +92,7 @@ def create_login_page(
92
  gr.Markdown("")
93
  with gr.Column(scale=6):
94
  gr.Markdown("# BirdNET Validation Platform")
95
- gr.Markdown(
96
- (
97
- "Sign in with your Hugging Face identity. Private project storage is accessed only by the app backend."
98
- if admin_storage_mode
99
- else "Sign in with your Hugging Face account to access project validation workflows."
100
- )
101
- )
102
- if auth_mode_label:
103
- gr.Markdown(auth_mode_label)
104
 
105
- error_message = gr.Markdown()
106
  session_output = gr.Textbox(
107
  label="Session ID",
108
  interactive=False,
@@ -110,18 +100,19 @@ def create_login_page(
110
  )
111
 
112
  oauth_continue_button = None
 
 
113
  if enable_oauth_login:
114
  gr.Markdown(
115
  (
116
- "The hosted Space verifies your Hugging Face identity securely. "
117
- "Project access remains controlled by assignments and invitations inside this app."
118
  if admin_storage_mode
119
- else "Sign in securely with your Hugging Face identity to enter the workspace."
120
  )
121
  )
122
- gr.LoginButton("1. Sign in with Hugging Face", logout_value="Sign out ({})")
123
- oauth_continue_button = gr.Button(
124
- "2. Enter workspace",
125
  variant="primary",
126
  )
127
  elif allow_username_login:
@@ -132,15 +123,7 @@ def create_login_page(
132
  lines=1,
133
  )
134
  login_button = gr.Button("Login", variant="primary", scale=1)
135
- login_button.click(
136
- fn=lambda username: perform_login(
137
- auth_service,
138
- username,
139
- allow_username_login=True,
140
- ),
141
- inputs=[username_input],
142
- outputs=[session_output, error_message],
143
- )
144
  with gr.Column(scale=1):
145
  gr.Markdown("")
146
 
@@ -156,5 +139,15 @@ def create_login_page(
156
  inputs=None,
157
  outputs=[session_output, error_message],
158
  )
 
 
 
 
 
 
 
 
 
 
159
 
160
  return session_output, error_message
 
92
  gr.Markdown("")
93
  with gr.Column(scale=6):
94
  gr.Markdown("# BirdNET Validation Platform")
 
 
 
 
 
 
 
 
 
95
 
 
96
  session_output = gr.Textbox(
97
  label="Session ID",
98
  interactive=False,
 
100
  )
101
 
102
  oauth_continue_button = None
103
+ username_input = None
104
+ login_button = None
105
  if enable_oauth_login:
106
  gr.Markdown(
107
  (
108
+ "Secure login with your Hugging Face account. The app verifies your identity and only grants access to projects assigned to you."
 
109
  if admin_storage_mode
110
+ else "Secure login with your Hugging Face account to access your validation workspace."
111
  )
112
  )
113
+ oauth_continue_button = gr.LoginButton(
114
+ "Sign in with Hugging Face",
115
+ logout_value="Signed in as {}",
116
  variant="primary",
117
  )
118
  elif allow_username_login:
 
123
  lines=1,
124
  )
125
  login_button = gr.Button("Login", variant="primary", scale=1)
126
+ error_message = gr.Markdown()
 
 
 
 
 
 
 
 
127
  with gr.Column(scale=1):
128
  gr.Markdown("")
129
 
 
139
  inputs=None,
140
  outputs=[session_output, error_message],
141
  )
142
+ if login_button is not None and username_input is not None:
143
+ login_button.click(
144
+ fn=lambda username: perform_login(
145
+ auth_service,
146
+ username,
147
+ allow_username_login=True,
148
+ ),
149
+ inputs=[username_input],
150
+ outputs=[session_output, error_message],
151
+ )
152
 
153
  return session_output, error_message
tests/unit/test_app_factory_audio_helpers.py CHANGED
@@ -30,6 +30,7 @@ from src.ui.app_factory import (
30
  _build_detection_repository,
31
  _get_project_detection_count,
32
  _build_queue_badge,
 
33
  _load_projects_from_file,
34
  _load_user_access_from_file,
35
  _bootstrap_auth_and_projects,
@@ -245,6 +246,52 @@ class FakeQueueService:
245
  return FakeQueueService._Page()
246
 
247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  def test_initialize_hf_admin_storage_sets_bucket_without_persisting_shared_token() -> None:
249
  project = Project(
250
  project_slug="private-audio",
@@ -1452,7 +1499,7 @@ def test_bootstrap_auth_and_projects_loads_configured_hf_project_state(tmp_path:
1452
  hf_project_state_loader=FakeStateLoader(),
1453
  )
1454
 
1455
- assert "Loaded 1 project" in warning
1456
  assert admin_manager.get_project("project-a") is not None
1457
  assert auth_service.login("owner") is not None
1458
  assert auth_service.get_user_role_for_project("validator", "project-a") == Role.validator
 
30
  _build_detection_repository,
31
  _get_project_detection_count,
32
  _build_queue_badge,
33
+ _build_validation_summary_cards_for_species,
34
  _load_projects_from_file,
35
  _load_user_access_from_file,
36
  _bootstrap_auth_and_projects,
 
246
  return FakeQueueService._Page()
247
 
248
 
249
+ def test_build_validation_summary_cards_for_species_uses_species_total_not_page_rows() -> None:
250
+ class QueueWithListAll(FakeQueueService):
251
+ def list_all_detections(self, **kwargs: object) -> list[object]:
252
+ self.last_kwargs = kwargs
253
+ return [
254
+ SimpleNamespace(
255
+ detection_key="dkey_01",
256
+ audio_id="audio_01",
257
+ scientific_name="sp",
258
+ confidence=0.9,
259
+ start_time=0,
260
+ end_time=1,
261
+ ),
262
+ SimpleNamespace(
263
+ detection_key="dkey_02",
264
+ audio_id="audio_02",
265
+ scientific_name="sp",
266
+ confidence=0.8,
267
+ start_time=1,
268
+ end_time=2,
269
+ ),
270
+ SimpleNamespace(
271
+ detection_key="dkey_03",
272
+ audio_id="audio_03",
273
+ scientific_name="sp",
274
+ confidence=0.7,
275
+ start_time=2,
276
+ end_time=3,
277
+ ),
278
+ ]
279
+
280
+ html = _build_validation_summary_cards_for_species(
281
+ queue_service=QueueWithListAll(),
282
+ snapshot_reader=FakeSnapshotReader(),
283
+ project_slug="project-a",
284
+ scientific_name="sp",
285
+ min_confidence=0.0,
286
+ actor_username="validator",
287
+ )
288
+
289
+ assert "Queue total" in html
290
+ assert "segments in species" in html
291
+ assert "66.7%" in html
292
+ assert "1 pending in species" in html
293
+
294
+
295
  def test_initialize_hf_admin_storage_sets_bucket_without_persisting_shared_token() -> None:
296
  project = Project(
297
  project_slug="private-audio",
 
1499
  hf_project_state_loader=FakeStateLoader(),
1500
  )
1501
 
1502
+ assert warning == ""
1503
  assert admin_manager.get_project("project-a") is not None
1504
  assert auth_service.login("owner") is not None
1505
  assert auth_service.get_user_role_for_project("validator", "project-a") == Role.validator
tests/unit/test_hf_project_resource_deletion.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from src.domain.models import Project
4
+ from src.services.hf_project_resource_deletion import (
5
+ HfProjectResourceDeleter,
6
+ HfProjectResourceDeletionError,
7
+ )
8
+
9
+
10
+ class FakeDeletionApi:
11
+ def __init__(self, username: str = "owner") -> None:
12
+ self.username = username
13
+ self.calls: list[tuple[str, str]] = []
14
+
15
+ def whoami(self, *, token=None): # noqa: ANN001
16
+ assert token == "hf_storage"
17
+ return {"name": self.username}
18
+
19
+ def delete_bucket(self, bucket_id: str, *, token=None, missing_ok: bool = False): # noqa: ANN001
20
+ assert token == "hf_storage"
21
+ assert missing_ok is True
22
+ self.calls.append(("bucket", bucket_id))
23
+
24
+ def delete_repo(self, repo_id: str, *, token=None, repo_type=None, missing_ok: bool = False): # noqa: ANN001
25
+ assert token == "hf_storage"
26
+ assert repo_type == "dataset"
27
+ assert missing_ok is True
28
+ self.calls.append(("repo", repo_id))
29
+
30
+
31
+ def _project() -> Project:
32
+ return Project(
33
+ project_slug="project-a",
34
+ name="Project A",
35
+ dataset_repo_id="owner/project-a",
36
+ owner_username="owner",
37
+ state_repo_id="owner/project-a_state",
38
+ validation_bucket_id="owner/project-a_validation_state",
39
+ )
40
+
41
+
42
+ def test_delete_project_resources_deletes_bucket_state_and_dataset_in_safe_order() -> None:
43
+ api = FakeDeletionApi()
44
+ result = HfProjectResourceDeleter(api=api).delete_project_resources(
45
+ project=_project(),
46
+ actor_username="owner",
47
+ storage_token="hf_storage",
48
+ confirmed_slug="project-a",
49
+ confirmation_checked=True,
50
+ )
51
+
52
+ assert api.calls == [
53
+ ("bucket", "owner/project-a_validation_state"),
54
+ ("repo", "owner/project-a_state"),
55
+ ("repo", "owner/project-a"),
56
+ ]
57
+ assert result.deleted_bucket_id == "owner/project-a_validation_state"
58
+ assert result.deleted_state_repo_id == "owner/project-a_state"
59
+ assert result.deleted_dataset_repo_id == "owner/project-a"
60
+
61
+
62
+ def test_delete_project_resources_requires_exact_confirmation() -> None:
63
+ api = FakeDeletionApi()
64
+ with pytest.raises(HfProjectResourceDeletionError, match="not confirmed"):
65
+ HfProjectResourceDeleter(api=api).delete_project_resources(
66
+ project=_project(),
67
+ actor_username="owner",
68
+ storage_token="hf_storage",
69
+ confirmed_slug="wrong",
70
+ confirmation_checked=True,
71
+ )
72
+
73
+ assert api.calls == []
74
+
75
+
76
+ def test_delete_project_resources_blocks_non_owner_actor() -> None:
77
+ api = FakeDeletionApi()
78
+ with pytest.raises(HfProjectResourceDeletionError, match="Only the project creator"):
79
+ HfProjectResourceDeleter(api=api).delete_project_resources(
80
+ project=_project(),
81
+ actor_username="validator",
82
+ storage_token="hf_storage",
83
+ confirmed_slug="project-a",
84
+ confirmation_checked=True,
85
+ )
86
+
87
+ assert api.calls == []
88
+
89
+
90
+ def test_delete_project_resources_blocks_cross_namespace_resources() -> None:
91
+ api = FakeDeletionApi()
92
+ project = _project().model_copy(update={"state_repo_id": "other/project-a_state"})
93
+
94
+ with pytest.raises(HfProjectResourceDeletionError, match="namespace"):
95
+ HfProjectResourceDeleter(api=api).delete_project_resources(
96
+ project=project,
97
+ actor_username="owner",
98
+ storage_token="hf_storage",
99
+ confirmed_slug="project-a",
100
+ confirmation_checked=True,
101
+ )
102
+
103
+ assert api.calls == []