Spaces:
Runtime error
Runtime error
File size: 18,528 Bytes
40e0b51 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 | """Generate a Postman v2.1 collection at docs/postman_collection.json.
Reads docs/apispec.json for the route inventory + parameter schemas,
then attaches hand-curated sample responses for every documented status
code. Re-run after editing the spec:
PYTHONPATH=. .venv/bin/python scripts/gen_postman.py
The WebSocket endpoint is exported as a Postman WebSocket request
(url.protocol = "ws", no HTTP method) — Postman 10+ recognises this
and opens it in the WebSocket tab instead of a regular GET form."""
from __future__ import annotations
import json
import sys
import uuid as _uuid
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
SPEC_PATH = ROOT / "docs" / "apispec.json"
OUT_PATH = ROOT / "docs" / "Cakra Intelligence - YOLO Rest.postman_collection.json"
API_PREFIX = "/api/v1"
SAMPLE_REQUEST_ID = "019e5870-f3c4-74a2-9695-5e9f758d5105"
SAMPLE_CAMERA_ID = "cmppqd1670000abcd"
SAMPLE_LOCATION = "01 Tugu Muda"
SAMPLE_LAT = -6.9847
SAMPLE_LNG = 110.4097
def _id(name: str) -> str:
return str(_uuid.uuid5(_uuid.NAMESPACE_URL, "cakra-cctv-yolo:" + name))
# --------------------------------------------------------------------
# Sample bodies — one per endpoint + per status code.
# --------------------------------------------------------------------
def _cam_embed(camera_id: str) -> dict:
return {
"hls": f"http://localhost:8000{API_PREFIX}/cameras/{camera_id}/hls/playlist.m3u8",
}
def _cam_metrics(camera_id: str) -> dict:
return {
"websocket": f"ws://localhost:8000{API_PREFIX}/cameras/{camera_id}/metrics/ws",
}
SAMPLE_CAMERA_INFO: dict[str, Any] = {
"camera_id": SAMPLE_CAMERA_ID,
"name": SAMPLE_LOCATION,
"stream_url": "https://livepantau.semarangkota.go.id/171b8761.../index.m3u8",
"status": "online",
"owner": "KECAMATAN SEMARANG TENGAH",
"city": "Semarang",
"lat": SAMPLE_LAT,
"lng": SAMPLE_LNG,
"is_active": True,
"connected": True,
"last_error": None,
"capture_fps": 22.6,
"embed": _cam_embed(SAMPLE_CAMERA_ID),
"metrics": _cam_metrics(SAMPLE_CAMERA_ID),
}
SAMPLE_CAMERA_INACTIVE = {
**SAMPLE_CAMERA_INFO,
"is_active": False,
"connected": None,
"capture_fps": None,
"last_error": None,
}
# Realistic WS push payload — what hits the client every
# METRICS_WS_INTERVAL seconds. Used as the saved sample for the
# WebSocket request item.
SAMPLE_WS_FRAME: dict[str, Any] = {
"camera_id": SAMPLE_CAMERA_ID,
"location": SAMPLE_LOCATION,
"timestamp": "2026-06-02T13:07:36",
"vehicle_count": 6,
"person_count": 1,
"traffic_status": "SMOOTH",
"crowd_status": "NORMAL",
"fps_capture": 22.6,
"fps_process": 5.2,
"connected": True,
"frame_size": [1920, 1080],
"camera": {
"lat": SAMPLE_LAT,
"lng": SAMPLE_LNG,
"heading_deg": 0.0,
"fov_deg": 70.0,
"max_distance_m": 80.0,
"coverage_polygon": [
[SAMPLE_LAT, SAMPLE_LNG],
[SAMPLE_LAT + 0.00018, SAMPLE_LNG - 0.00026],
[SAMPLE_LAT + 0.00023, SAMPLE_LNG - 0.00015],
[SAMPLE_LAT + 0.00025, SAMPLE_LNG + 0.00000],
[SAMPLE_LAT + 0.00023, SAMPLE_LNG + 0.00015],
[SAMPLE_LAT + 0.00018, SAMPLE_LNG + 0.00026],
],
},
"detections": [
{
"id": 11, "class": "truck", "class_id": 7,
"conf": 0.69, "bbox": [820.4, 320.1, 1060.0, 580.7],
"geo": {"lat": SAMPLE_LAT + 0.00007, "lng": SAMPLE_LNG + 0.00002,
"distance_m": 18.2, "bearing_deg": 1.1, "confidence": 0.51},
},
{
"id": 596, "class": "motorcycle", "class_id": 3,
"conf": 0.49, "bbox": [400.0, 700.0, 510.0, 880.0],
"geo": {"lat": SAMPLE_LAT + 0.00003, "lng": SAMPLE_LNG - 0.00010,
"distance_m": 8.0, "bearing_deg": 343.5, "confidence": 0.62},
},
],
"session": {
"started_at": "2026-05-30T08:12:00+00:00",
"last_captured_at": "2026-06-02T13:07:36+00:00",
"samples_count": 214883,
"duration_seconds": 277536.0,
"avg_vehicles": 4.21,
"avg_people": 0.85,
"max_vehicles": 19,
"max_people": 7,
},
}
SAMPLE_ROOT = {
"service": "cakra-cctv-yolo-analytics",
"version": "0.1.0",
"docs": "/docs",
"openapi": "/openapi.json",
"api_prefix": API_PREFIX,
}
SAMPLE_HEALTH = {"status": "ok", "version": "0.1.0", "cameras": 12}
def _envelope(code: str, message: str, details: dict[str, str]) -> dict:
return {
"success": False,
"error": {
"code": code,
"message": message,
"details": details,
"request_id": SAMPLE_REQUEST_ID,
},
}
ERROR_SAMPLES: dict[str, tuple[str, dict]] = {
"400": ("Bad Request", _envelope(
"bad_request", "malformed request", {})),
"404": ("Not Found", _envelope(
"not_found", "camera_id not found", {"camera_id": "unknown"})),
"422": ("Unprocessable Entity", _envelope(
"validation_error", "request validation failed",
{"page_size": "Input should be less than or equal to 100"})),
"500": ("Internal Server Error", _envelope(
"internal_server_error", "internal server error", {})),
"503": ("Service Unavailable (not_activated)", _envelope(
"not_activated",
"camera exists in catalog but no worker is running",
{"camera_id": SAMPLE_CAMERA_ID,
"active_workers": "12",
"max_streams": "50"})),
}
# Path-suffix → status overrides. The connect endpoint's 503 is pool_full,
# not not_activated, so swap the sample to match.
ERROR_OVERRIDES: dict[tuple[str, str], tuple[str, dict]] = {
("/connect", "503"): ("Service Unavailable (pool_full)", _envelope(
"pool_full",
"active worker pool is full",
{"camera_id": SAMPLE_CAMERA_ID,
"active_workers": "50",
"max_streams": "50"})),
}
# Catalog-list item shape — lean projection (no status/runtime/embed).
def _catalog_item(camera_id: str, name: str) -> dict:
return {
"camera_id": camera_id,
"name": name,
"stream_url": SAMPLE_CAMERA_INFO["stream_url"],
"owner": SAMPLE_CAMERA_INFO["owner"],
"city": SAMPLE_CAMERA_INFO["city"],
"lat": SAMPLE_LAT,
"lng": SAMPLE_LNG,
}
# 200 sample per route → keyed by the OpenAPI path.
SUCCESS_BODY: dict[str, Any] = {
"/": SAMPLE_ROOT,
"/health": SAMPLE_HEALTH,
f"{API_PREFIX}/cameras": {
"pagination": {"page": 1, "page_size": 20, "total": 2351, "total_pages": 118},
"count": 2,
"items": [
_catalog_item(SAMPLE_CAMERA_ID, "01 Tugu Muda"),
_catalog_item("cmppqd1670000xyz", "02 Pandanaran"),
],
},
f"{API_PREFIX}/cameras/{{camera_id}}": SAMPLE_CAMERA_INFO,
f"{API_PREFIX}/cameras/{{camera_id}}/connect": SAMPLE_CAMERA_INFO,
f"{API_PREFIX}/cameras/{{camera_id}}/disconnect": SAMPLE_CAMERA_INACTIVE,
}
# Endpoints whose 200 body is binary / streamed — describe instead of dump.
BINARY_BODY: dict[str, tuple[str, str]] = {
f"{API_PREFIX}/cameras/{{camera_id}}/hls/playlist.m3u8": (
"application/vnd.apple.mpegurl",
"HLS playlist (m3u8) for the camera's annotated stream. Bboxes "
"are baked into the encoded video — plug into hls.js + <video> "
"for plug-and-play embed.",
),
f"{API_PREFIX}/cameras/{{camera_id}}/hls/{{segment}}": (
"video/mp2t",
"MPEG-TS segment bytes referenced by the playlist. Called by the "
"HLS player (hls.js / browser native HLS), not directly by FE.",
),
}
WEBSOCKET_PATH = f"{API_PREFIX}/cameras/{{camera_id}}/metrics/ws"
# --------------------------------------------------------------------
# URL & request builders
# --------------------------------------------------------------------
STATUS_TEXT = {
"101": "Switching Protocols", "200": "OK",
"400": "Bad Request", "401": "Unauthorized", "404": "Not Found",
"422": "Unprocessable Entity", "500": "Internal Server Error",
"503": "Service Unavailable",
}
def _path_segments(path: str) -> list[str]:
return [
seg.replace("{", ":").replace("}", "")
for seg in path.strip("/").split("/")
if seg
]
def _url_block(path: str, queries: list[dict], *, protocol: str | None = None) -> dict:
segments = _path_segments(path)
scheme = protocol or "http"
raw = "{{base_url}}/" + "/".join(segments) if protocol is None else \
f"{scheme}://localhost:8000/" + "/".join(segments)
if queries:
raw += "?" + "&".join(f"{q['key']}={q.get('value', '')}" for q in queries)
url: dict[str, Any] = {"raw": raw, "host": ["{{base_url}}"], "path": segments}
if protocol:
url["protocol"] = protocol
url["host"] = ["localhost"]
url["port"] = "8000"
path_vars = [
{"key": seg[1:], "value": SAMPLE_CAMERA_ID if seg == ":camera_id" else ""}
for seg in segments if seg.startswith(":")
]
if path_vars:
url["variable"] = path_vars
if queries:
url["query"] = queries
return url
def _query_params(parameters: list[dict]) -> list[dict]:
queries: list[dict] = []
for p in parameters or []:
if p.get("in") != "query":
continue
schema = p.get("schema") or {}
default = schema.get("default")
value = (
"" if default is None
else str(default).lower() if isinstance(default, bool)
else str(default)
)
item = {
"key": p["name"],
"value": value,
"description": p.get("description", "") or "",
}
if not p.get("required", False) and default is None:
item["disabled"] = True
queries.append(item)
return queries
def _example_response(name: str, code: str, request_block: dict,
body: Any, content_type: str = "application/json",
note: str | None = None) -> dict:
if isinstance(body, str):
raw_body = body
elif body is None:
raw_body = ""
else:
raw_body = json.dumps(body, indent=2)
response = {
"name": name,
"originalRequest": request_block,
"status": STATUS_TEXT.get(code, ""),
"code": int(code),
"_postman_previewlanguage": "json" if content_type == "application/json" else "text",
"header": [
{"key": "Content-Type", "value": content_type},
{"key": "X-Request-ID", "value": SAMPLE_REQUEST_ID},
],
"cookie": [],
"body": raw_body,
}
if note:
response["description"] = note
return response
def _build_http_request(method: str, path: str, op: dict) -> dict:
queries = _query_params(op.get("parameters", []))
url = _url_block(path, queries)
return {
"method": method.upper(),
"header": [{"key": "Accept", "value": "application/json"}],
"url": url,
"description": op.get("description") or op.get("summary") or "",
}
def _build_responses(path: str, op: dict, request_block: dict) -> list[dict]:
examples: list[dict] = []
declared = op.get("responses", {})
if "200" in declared:
if path in BINARY_BODY:
ctype, note = BINARY_BODY[path]
examples.append(_example_response(
"200 OK (binary)", "200", request_block,
"<binary stream omitted>", content_type=ctype, note=note,
))
elif path in SUCCESS_BODY:
examples.append(_example_response(
"200 OK", "200", request_block, SUCCESS_BODY[path],
))
for code in ("400", "404", "422", "503", "500"):
if code not in declared:
continue
name, body = ERROR_SAMPLES[code]
for (suffix, ovr_code), (ovr_name, ovr_body) in ERROR_OVERRIDES.items():
if path.endswith(suffix) and code == ovr_code:
name, body = ovr_name, ovr_body
break
examples.append(_example_response(
f"{code} {name}", code, request_block, body,
))
return examples
# Short, semantic Postman names per (METHOD, path). Falls back to the
# OpenAPI summary only when a route isn't listed here — keeps Postman's
# sidebar scannable instead of dumping multi-line summaries as labels.
REQUEST_NAMES: dict[tuple[str, str], str] = {
("GET", "/"): "Service Metadata",
("GET", "/health"): "Health Check",
("GET", f"{API_PREFIX}/cameras"): "List Cameras",
("GET", f"{API_PREFIX}/cameras/{{camera_id}}"): "Get Camera",
("POST", f"{API_PREFIX}/cameras/{{camera_id}}/connect"): "Connect Camera",
("POST", f"{API_PREFIX}/cameras/{{camera_id}}/disconnect"): "Disconnect Camera",
("GET", f"{API_PREFIX}/cameras/{{camera_id}}/hls/playlist.m3u8"): "Get HLS Playlist",
("GET", f"{API_PREFIX}/cameras/{{camera_id}}/hls/{{segment}}"): "Get HLS Segment",
}
def _op_label(method: str, path: str, op: dict) -> str:
name = REQUEST_NAMES.get((method.upper(), path))
if name:
return name
summary = op.get("summary")
if summary:
return summary.rstrip(".")
return f"{method.upper()} {path}"
# --------------------------------------------------------------------
# WebSocket item — Postman's v2.1 JSON schema doesn't formally model
# WebSocket requests; the desktop WS workbench is only reachable from
# File → New → WebSocket Request. So we ship a doc-only item with the
# URL pre-formatted for copy-paste + the canonical sample frame.
# --------------------------------------------------------------------
def _build_websocket_doc_item() -> dict:
ws_url = f"ws://localhost:8000{WEBSOCKET_PATH}".replace("{camera_id}", SAMPLE_CAMERA_ID)
http_url = _url_block(WEBSOCKET_PATH, [])
sample_frame = json.dumps(SAMPLE_WS_FRAME, indent=2)
description = (
"## How to test this endpoint\n\n"
"Postman's WebSocket feature is desktop-only and isn't "
"round-trippable via the v2.1 collection JSON. Don't click "
"**Send** here — the HTTP path will return 426 Upgrade Required.\n\n"
"**Postman desktop:** *File → New → WebSocket Request*, paste:\n\n"
f"`{ws_url}`\n\n"
"**Or `wscat` from your terminal:**\n\n"
f"```bash\nwscat -c '{ws_url}'\n```\n\n"
"## Behavior\n"
"The server pushes a JSON frame every `METRICS_WS_INTERVAL` "
"(default 100 ms) while the camera worker is running. Activate "
"the worker first via `POST /cameras/{camera_id}/connect`. The "
"socket closes with code 1008 if the camera isn't activated.\n\n"
"## Sample frame\n\n"
"```json\n" + sample_frame + "\n```"
)
return {
"name": "Realtime Metrics (WebSocket)",
"request": {
"method": "GET",
"header": [{"key": "Accept", "value": "application/json"}],
"url": http_url,
"description": description,
},
"response": [],
}
# --------------------------------------------------------------------
# Main build
# --------------------------------------------------------------------
def build_collection(spec: dict) -> dict:
info = spec.get("info", {})
folders: dict[str, list[dict]] = {}
declared_tags = [t["name"] for t in spec.get("tags", [])]
tag_descriptions = {t["name"]: t.get("description", "") for t in spec.get("tags", [])}
for path, methods in spec.get("paths", {}).items():
# Skip the WS path — exported separately as a WebSocket item.
if path == WEBSOCKET_PATH:
continue
for method, op in methods.items():
if method not in {"get", "post", "put", "delete", "patch"}:
continue
request_block = _build_http_request(method, path, op)
item = {
"name": _op_label(method, path, op),
"request": request_block,
"response": _build_responses(path, op, request_block),
}
tag = (op.get("tags") or ["Misc"])[0]
folders.setdefault(tag, []).append(item)
# WebSocket folder.
folders.setdefault("Metrics (WebSocket)", []).append(_build_websocket_doc_item())
ordered_tags = [t for t in declared_tags if t in folders] + \
[t for t in folders.keys() if t not in declared_tags]
items = []
for tag in ordered_tags:
items.append({
"name": tag,
"description": tag_descriptions.get(tag, ""),
"item": folders[tag],
})
return {
"info": {
"_postman_id": _id("info"),
"name": info.get("title", "Cakra CCTV YOLO Analytics"),
"description": (info.get("description") or "") +
"\n\n**Variables**\n"
"- `base_url` — service base URL (default `http://localhost:8000`)\n"
"- `camera_id` — pre-fill on each request via the Path Variables panel.\n"
"\nAll non-2xx responses follow the canonical error envelope "
"(see any saved 4xx/5xx example).",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "cakra-cctv-yolo",
},
"variable": [
{"key": "base_url", "value": "http://localhost:8000", "type": "string"},
],
"item": items,
}
def main() -> None:
if not SPEC_PATH.exists():
print(f"missing {SPEC_PATH} — run scripts.gen_openapi first", file=sys.stderr)
sys.exit(1)
spec = json.loads(SPEC_PATH.read_text())
collection = build_collection(spec)
OUT_PATH.write_text(json.dumps(collection, indent=2, ensure_ascii=False) + "\n")
print(f"wrote {OUT_PATH.relative_to(ROOT)} "
f"({OUT_PATH.stat().st_size:,} bytes)", file=sys.stderr)
if __name__ == "__main__":
main()
|