jrrribeiro commited on
Commit
0ad3135
·
1 Parent(s): e6485a3

feat(cli): add project bootstrap commands and tests

Browse files
README.md CHANGED
@@ -113,6 +113,48 @@ User access bootstrap file example (`BIRDNET_USER_ACCESS_FILE`):
113
  5. Resolve conflicts when concurrent updates occur.
114
  6. Export or inspect project validation report.
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  ## Repository Structure
117
 
118
  - `app.py`: validator app entrypoint
 
113
  5. Resolve conflicts when concurrent updates occur.
114
  6. Export or inspect project validation report.
115
 
116
+ ## Project CLI (Bootstrap Utilities)
117
+
118
+ The repository now includes a basic project bootstrap CLI:
119
+
120
+ ```bash
121
+ python -m src.cli.project_cli --help
122
+ ```
123
+
124
+ Available commands:
125
+
126
+ - `create-project`: adds a project entry to the projects bootstrap JSON.
127
+ - `init-dataset`: creates the initial local dataset folder structure.
128
+ - `build-index`: builds a confidence-sorted index from `detections.jsonl`.
129
+ - `verify-project`: verifies project config and required local scaffold files.
130
+
131
+ Example flow:
132
+
133
+ ```bash
134
+ python -m src.cli.project_cli create-project \
135
+ --projects-file docs/spaces/projects.sample.json \
136
+ --user-access-file docs/spaces/user_access.sample.json \
137
+ --slug amazonia-2026 \
138
+ --name "Amazonia 2026" \
139
+ --dataset-repo-id birdnet/amazonia-2026 \
140
+ --owner admin_user
141
+
142
+ python -m src.cli.project_cli init-dataset \
143
+ --dataset-root data/projects \
144
+ --slug amazonia-2026 \
145
+ --dataset-repo-id birdnet/amazonia-2026 \
146
+ --name "Amazonia 2026"
147
+
148
+ python -m src.cli.project_cli build-index \
149
+ --dataset-root data/projects \
150
+ --slug amazonia-2026
151
+
152
+ python -m src.cli.project_cli verify-project \
153
+ --projects-file docs/spaces/projects.sample.json \
154
+ --dataset-root data/projects \
155
+ --slug amazonia-2026
156
+ ```
157
+
158
  ## Repository Structure
159
 
160
  - `app.py`: validator app entrypoint
src/cli/__init__.py ADDED
File without changes
src/cli/project_cli.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+
9
+ DEFAULT_DATASET_DIRS = [
10
+ "audio",
11
+ "detections",
12
+ "index",
13
+ "exports",
14
+ ]
15
+
16
+
17
+ def _load_json(path: Path, default: Any) -> Any:
18
+ if not path.exists():
19
+ return default
20
+ return json.loads(path.read_text(encoding="utf-8"))
21
+
22
+
23
+ def _write_json(path: Path, payload: Any) -> None:
24
+ path.parent.mkdir(parents=True, exist_ok=True)
25
+ path.write_text(json.dumps(payload, indent=2, ensure_ascii=True) + "\n", encoding="utf-8")
26
+
27
+
28
+ def _project_exists(projects: list[dict[str, Any]], slug: str) -> bool:
29
+ return any(p.get("project_slug") == slug for p in projects)
30
+
31
+
32
+ def cmd_create_project(args: argparse.Namespace) -> int:
33
+ projects_file = Path(args.projects_file)
34
+ projects: list[dict[str, Any]] = _load_json(projects_file, [])
35
+
36
+ if _project_exists(projects, args.slug):
37
+ print(f"ERROR: project '{args.slug}' already exists")
38
+ return 1
39
+
40
+ project_entry: dict[str, Any] = {
41
+ "project_slug": args.slug,
42
+ "name": args.name,
43
+ "dataset_repo_id": args.dataset_repo_id,
44
+ "visibility": args.visibility,
45
+ "active": not args.inactive,
46
+ }
47
+ if args.owner:
48
+ project_entry["owner_username"] = args.owner
49
+ if args.dataset_token:
50
+ project_entry["dataset_token"] = args.dataset_token
51
+
52
+ projects.append(project_entry)
53
+ projects.sort(key=lambda p: str(p.get("project_slug", "")))
54
+ _write_json(projects_file, projects)
55
+
56
+ if args.user_access_file and args.owner:
57
+ access_file = Path(args.user_access_file)
58
+ access_payload: dict[str, dict[str, str]] = _load_json(access_file, {})
59
+ owner_roles = access_payload.setdefault(args.owner, {})
60
+ owner_roles[args.slug] = "admin"
61
+ _write_json(access_file, access_payload)
62
+
63
+ print(f"OK: project '{args.slug}' created")
64
+ return 0
65
+
66
+
67
+ def cmd_init_dataset(args: argparse.Namespace) -> int:
68
+ root = Path(args.dataset_root) / args.slug
69
+ for dirname in DEFAULT_DATASET_DIRS:
70
+ (root / dirname).mkdir(parents=True, exist_ok=True)
71
+
72
+ detections_file = root / "detections" / "detections.jsonl"
73
+ if not detections_file.exists():
74
+ detections_file.write_text("", encoding="utf-8")
75
+
76
+ metadata = {
77
+ "project_slug": args.slug,
78
+ "dataset_repo_id": args.dataset_repo_id,
79
+ }
80
+ if args.name:
81
+ metadata["name"] = args.name
82
+
83
+ _write_json(root / "index" / "project_metadata.json", metadata)
84
+ print(f"OK: dataset scaffold initialized at {root}")
85
+ return 0
86
+
87
+
88
+ def _read_jsonl(path: Path) -> list[dict[str, Any]]:
89
+ rows: list[dict[str, Any]] = []
90
+ if not path.exists():
91
+ return rows
92
+
93
+ for line_no, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
94
+ line = raw.strip()
95
+ if not line:
96
+ continue
97
+ try:
98
+ rows.append(json.loads(line))
99
+ except json.JSONDecodeError as exc:
100
+ raise ValueError(f"Invalid JSONL at line {line_no}: {exc}") from exc
101
+ return rows
102
+
103
+
104
+ def cmd_build_index(args: argparse.Namespace) -> int:
105
+ project_root = Path(args.dataset_root) / args.slug
106
+ detections_file = project_root / "detections" / "detections.jsonl"
107
+ rows = _read_jsonl(detections_file)
108
+
109
+ sorted_rows = sorted(rows, key=lambda d: float(d.get("confidence", 0.0)), reverse=True)
110
+ index_payload = {
111
+ "project_slug": args.slug,
112
+ "count": len(sorted_rows),
113
+ "detections": [
114
+ {
115
+ "detection_key": r.get("detection_key"),
116
+ "audio_id": r.get("audio_id"),
117
+ "scientific_name": r.get("scientific_name"),
118
+ "confidence": float(r.get("confidence", 0.0)),
119
+ }
120
+ for r in sorted_rows
121
+ ],
122
+ }
123
+
124
+ _write_json(project_root / "index" / "detections_index.json", index_payload)
125
+ print(f"OK: index generated with {len(sorted_rows)} detections")
126
+ return 0
127
+
128
+
129
+ def cmd_verify_project(args: argparse.Namespace) -> int:
130
+ projects_file = Path(args.projects_file)
131
+ projects: list[dict[str, Any]] = _load_json(projects_file, [])
132
+
133
+ if not _project_exists(projects, args.slug):
134
+ print(f"ERROR: project '{args.slug}' not found in {projects_file}")
135
+ return 1
136
+
137
+ project_root = Path(args.dataset_root) / args.slug
138
+ missing: list[str] = []
139
+
140
+ for dirname in DEFAULT_DATASET_DIRS:
141
+ expected = project_root / dirname
142
+ if not expected.exists():
143
+ missing.append(str(expected))
144
+
145
+ required_files = [
146
+ project_root / "detections" / "detections.jsonl",
147
+ project_root / "index" / "project_metadata.json",
148
+ project_root / "index" / "detections_index.json",
149
+ ]
150
+ for required in required_files:
151
+ if not required.exists():
152
+ missing.append(str(required))
153
+
154
+ if missing:
155
+ print("ERROR: project verification failed; missing paths:")
156
+ for item in missing:
157
+ print(f" - {item}")
158
+ return 1
159
+
160
+ print(f"OK: project '{args.slug}' verified")
161
+ return 0
162
+
163
+
164
+ def build_parser() -> argparse.ArgumentParser:
165
+ parser = argparse.ArgumentParser(prog="birdnet-project")
166
+ sub = parser.add_subparsers(dest="command", required=True)
167
+
168
+ create_project = sub.add_parser("create-project", help="Create project in bootstrap JSON")
169
+ create_project.add_argument("--projects-file", required=True)
170
+ create_project.add_argument("--user-access-file")
171
+ create_project.add_argument("--slug", required=True)
172
+ create_project.add_argument("--name", required=True)
173
+ create_project.add_argument("--dataset-repo-id", required=True)
174
+ create_project.add_argument("--visibility", choices=["private", "collaborative"], default="collaborative")
175
+ create_project.add_argument("--owner")
176
+ create_project.add_argument("--dataset-token")
177
+ create_project.add_argument("--inactive", action="store_true")
178
+ create_project.set_defaults(func=cmd_create_project)
179
+
180
+ init_dataset = sub.add_parser("init-dataset", help="Create initial dataset folder scaffold")
181
+ init_dataset.add_argument("--dataset-root", required=True)
182
+ init_dataset.add_argument("--slug", required=True)
183
+ init_dataset.add_argument("--dataset-repo-id", required=True)
184
+ init_dataset.add_argument("--name")
185
+ init_dataset.set_defaults(func=cmd_init_dataset)
186
+
187
+ build_index = sub.add_parser("build-index", help="Build simple index from detections JSONL")
188
+ build_index.add_argument("--dataset-root", required=True)
189
+ build_index.add_argument("--slug", required=True)
190
+ build_index.set_defaults(func=cmd_build_index)
191
+
192
+ verify_project = sub.add_parser("verify-project", help="Verify project config and local scaffold")
193
+ verify_project.add_argument("--projects-file", required=True)
194
+ verify_project.add_argument("--dataset-root", required=True)
195
+ verify_project.add_argument("--slug", required=True)
196
+ verify_project.set_defaults(func=cmd_verify_project)
197
+
198
+ return parser
199
+
200
+
201
+ def main(argv: list[str] | None = None) -> int:
202
+ parser = build_parser()
203
+ args = parser.parse_args(argv)
204
+ return int(args.func(args))
205
+
206
+
207
+ if __name__ == "__main__":
208
+ raise SystemExit(main())
tests/unit/test_project_cli.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+
4
+ from src.cli.project_cli import main
5
+
6
+
7
+ def _read_json(path: Path):
8
+ return json.loads(path.read_text(encoding="utf-8"))
9
+
10
+
11
+ def test_create_project_writes_projects_and_owner_acl(tmp_path: Path) -> None:
12
+ projects_file = tmp_path / "projects.json"
13
+ access_file = tmp_path / "user_access.json"
14
+ projects_file.write_text("[]\n", encoding="utf-8")
15
+ access_file.write_text("{}\n", encoding="utf-8")
16
+
17
+ exit_code = main(
18
+ [
19
+ "create-project",
20
+ "--projects-file",
21
+ str(projects_file),
22
+ "--user-access-file",
23
+ str(access_file),
24
+ "--slug",
25
+ "amazonia-2026",
26
+ "--name",
27
+ "Amazonia 2026",
28
+ "--dataset-repo-id",
29
+ "birdnet/amazonia-2026",
30
+ "--owner",
31
+ "admin_user",
32
+ ]
33
+ )
34
+
35
+ assert exit_code == 0
36
+ projects = _read_json(projects_file)
37
+ assert len(projects) == 1
38
+ assert projects[0]["project_slug"] == "amazonia-2026"
39
+ assert projects[0]["visibility"] == "collaborative"
40
+
41
+ access = _read_json(access_file)
42
+ assert access["admin_user"]["amazonia-2026"] == "admin"
43
+
44
+
45
+ def test_create_project_duplicate_slug_returns_error(tmp_path: Path) -> None:
46
+ projects_file = tmp_path / "projects.json"
47
+ projects_file.write_text(
48
+ json.dumps(
49
+ [
50
+ {
51
+ "project_slug": "p1",
52
+ "name": "Project 1",
53
+ "dataset_repo_id": "org/p1",
54
+ "active": True,
55
+ }
56
+ ]
57
+ ),
58
+ encoding="utf-8",
59
+ )
60
+
61
+ exit_code = main(
62
+ [
63
+ "create-project",
64
+ "--projects-file",
65
+ str(projects_file),
66
+ "--slug",
67
+ "p1",
68
+ "--name",
69
+ "Project 1",
70
+ "--dataset-repo-id",
71
+ "org/p1",
72
+ ]
73
+ )
74
+
75
+ assert exit_code == 1
76
+
77
+
78
+ def test_init_build_and_verify_project_flow(tmp_path: Path) -> None:
79
+ projects_file = tmp_path / "projects.json"
80
+ projects_file.write_text(
81
+ json.dumps(
82
+ [
83
+ {
84
+ "project_slug": "p2",
85
+ "name": "Project 2",
86
+ "dataset_repo_id": "org/p2",
87
+ "active": True,
88
+ }
89
+ ]
90
+ ),
91
+ encoding="utf-8",
92
+ )
93
+ dataset_root = tmp_path / "datasets"
94
+
95
+ init_exit = main(
96
+ [
97
+ "init-dataset",
98
+ "--dataset-root",
99
+ str(dataset_root),
100
+ "--slug",
101
+ "p2",
102
+ "--dataset-repo-id",
103
+ "org/p2",
104
+ "--name",
105
+ "Project 2",
106
+ ]
107
+ )
108
+ assert init_exit == 0
109
+
110
+ detections_file = dataset_root / "p2" / "detections" / "detections.jsonl"
111
+ detections_file.write_text(
112
+ "\n".join(
113
+ [
114
+ json.dumps(
115
+ {
116
+ "detection_key": "k1",
117
+ "audio_id": "a1",
118
+ "scientific_name": "Sp A",
119
+ "confidence": 0.6,
120
+ }
121
+ ),
122
+ json.dumps(
123
+ {
124
+ "detection_key": "k2",
125
+ "audio_id": "a2",
126
+ "scientific_name": "Sp B",
127
+ "confidence": 0.9,
128
+ }
129
+ ),
130
+ ]
131
+ )
132
+ + "\n",
133
+ encoding="utf-8",
134
+ )
135
+
136
+ build_exit = main(
137
+ [
138
+ "build-index",
139
+ "--dataset-root",
140
+ str(dataset_root),
141
+ "--slug",
142
+ "p2",
143
+ ]
144
+ )
145
+ assert build_exit == 0
146
+
147
+ index_payload = _read_json(dataset_root / "p2" / "index" / "detections_index.json")
148
+ assert index_payload["count"] == 2
149
+ assert index_payload["detections"][0]["detection_key"] == "k2"
150
+
151
+ verify_exit = main(
152
+ [
153
+ "verify-project",
154
+ "--projects-file",
155
+ str(projects_file),
156
+ "--dataset-root",
157
+ str(dataset_root),
158
+ "--slug",
159
+ "p2",
160
+ ]
161
+ )
162
+ assert verify_exit == 0