|
| 1 | +""" |
| 2 | +OpenCut OpenAPI Spec Generator |
| 3 | +
|
| 4 | +Introspects the Flask app's url_map to produce an OpenAPI 3.0.x JSON spec. |
| 5 | +Schema classes from opencut.schemas are mapped to known endpoints for |
| 6 | +response definitions. |
| 7 | +""" |
| 8 | + |
| 9 | +from dataclasses import fields as dc_fields |
| 10 | +from typing import Any, Dict, List, Optional, get_args, get_origin |
| 11 | + |
| 12 | +from opencut import __version__ |
| 13 | +from opencut.schemas import ( |
| 14 | + AutoZoomResult, |
| 15 | + BeatMarkersResult, |
| 16 | + ChaptersResult, |
| 17 | + ColorMatchResult, |
| 18 | + DeliverableResult, |
| 19 | + ExportMarkersResult, |
| 20 | + IndexResult, |
| 21 | + JobResponse, |
| 22 | + LoudnessMatchResult, |
| 23 | + MulticamResult, |
| 24 | + RepeatDetectResult, |
| 25 | + SearchResult, |
| 26 | + SilenceResult, |
| 27 | + UpdateCheckResult, |
| 28 | +) |
| 29 | + |
| 30 | +# --------------------------------------------------------------------------- |
| 31 | +# Endpoint -> schema mapping (known response schemas) |
| 32 | +# --------------------------------------------------------------------------- |
| 33 | +_ENDPOINT_SCHEMAS: Dict[str, type] = { |
| 34 | + "/health": None, # ad-hoc dict |
| 35 | + "/system/update-check": UpdateCheckResult, |
| 36 | + "/search/footage": SearchResult, |
| 37 | + "/search/index": IndexResult, |
| 38 | + "/deliverables/vfx-sheet": DeliverableResult, |
| 39 | + "/deliverables/adr-list": DeliverableResult, |
| 40 | + "/deliverables/music-cue-sheet": DeliverableResult, |
| 41 | + "/deliverables/asset-list": DeliverableResult, |
| 42 | + "/timeline/export-from-markers": ExportMarkersResult, |
| 43 | + "/silence": SilenceResult, |
| 44 | + "/audio/loudness-match": LoudnessMatchResult, |
| 45 | + "/audio/beat-markers": BeatMarkersResult, |
| 46 | + "/video/color-match": ColorMatchResult, |
| 47 | + "/video/auto-zoom": AutoZoomResult, |
| 48 | + "/video/multicam-cuts": MulticamResult, |
| 49 | + "/captions/chapters": ChaptersResult, |
| 50 | + "/captions/repeat-detect": RepeatDetectResult, |
| 51 | +} |
| 52 | + |
| 53 | +# Endpoints that return a JobResponse (async job-based routes) |
| 54 | +_JOB_ENDPOINTS = { |
| 55 | + "/silence", "/search/index", "/timeline/export-from-markers", |
| 56 | + "/install-whisper", "/whisper/reinstall", |
| 57 | + "/video/color-match", "/video/auto-zoom", "/video/multicam-cuts", |
| 58 | + "/audio/loudness-match", "/audio/beat-markers", |
| 59 | + "/captions/chapters", "/captions/repeat-detect", |
| 60 | +} |
| 61 | + |
| 62 | +# Methods to skip (HEAD is auto-added by Flask; OPTIONS for CORS) |
| 63 | +_SKIP_METHODS = {"HEAD", "OPTIONS"} |
| 64 | + |
| 65 | + |
| 66 | +def _python_type_to_json(tp) -> dict: |
| 67 | + """Convert a Python type annotation to a JSON Schema fragment.""" |
| 68 | + origin = get_origin(tp) |
| 69 | + |
| 70 | + if tp is str or tp is Optional[str]: |
| 71 | + return {"type": "string"} |
| 72 | + if tp is int: |
| 73 | + return {"type": "integer"} |
| 74 | + if tp is float: |
| 75 | + return {"type": "number"} |
| 76 | + if tp is bool: |
| 77 | + return {"type": "boolean"} |
| 78 | + if tp is dict or tp is Dict or origin is dict: |
| 79 | + return {"type": "object"} |
| 80 | + if origin is list or origin is List: |
| 81 | + args = get_args(tp) |
| 82 | + if args: |
| 83 | + return {"type": "array", "items": _python_type_to_json(args[0])} |
| 84 | + return {"type": "array", "items": {}} |
| 85 | + if tp is list: |
| 86 | + return {"type": "array", "items": {}} |
| 87 | + if tp is type(None): |
| 88 | + return {"type": "string", "nullable": True} |
| 89 | + # Optional[X] -> X with nullable |
| 90 | + if origin is type(None) or str(tp).startswith("typing.Optional"): |
| 91 | + args = get_args(tp) |
| 92 | + if args: |
| 93 | + schema = _python_type_to_json(args[0]) |
| 94 | + schema["nullable"] = True |
| 95 | + return schema |
| 96 | + return {"type": "string"} |
| 97 | + |
| 98 | + |
| 99 | +def _dataclass_to_schema(cls) -> dict: |
| 100 | + """Convert a dataclass to an OpenAPI schema object.""" |
| 101 | + props = {} |
| 102 | + for f in dc_fields(cls): |
| 103 | + props[f.name] = _python_type_to_json(f.type) |
| 104 | + return { |
| 105 | + "type": "object", |
| 106 | + "properties": props, |
| 107 | + } |
| 108 | + |
| 109 | + |
| 110 | +def generate_openapi_spec(app) -> dict: |
| 111 | + """Build an OpenAPI 3.0.3 spec dict from a Flask app's url_map.""" |
| 112 | + paths: Dict[str, dict] = {} |
| 113 | + |
| 114 | + for rule in app.url_map.iter_rules(): |
| 115 | + path = rule.rule |
| 116 | + # Skip static endpoint |
| 117 | + if path.startswith("/static"): |
| 118 | + continue |
| 119 | + |
| 120 | + methods = sorted(rule.methods - _SKIP_METHODS) |
| 121 | + if not methods: |
| 122 | + continue |
| 123 | + |
| 124 | + # Look up the view function for docstring extraction |
| 125 | + view_func = app.view_functions.get(rule.endpoint) |
| 126 | + docstring = (view_func.__doc__ or "").strip() if view_func else "" |
| 127 | + |
| 128 | + path_item = paths.setdefault(path, {}) |
| 129 | + |
| 130 | + for method in methods: |
| 131 | + operation: Dict[str, Any] = { |
| 132 | + "summary": docstring.split("\n")[0] if docstring else rule.endpoint, |
| 133 | + "operationId": f"{rule.endpoint}_{method.lower()}", |
| 134 | + "tags": [rule.endpoint.split(".")[0] if "." in rule.endpoint else "default"], |
| 135 | + "responses": {}, |
| 136 | + } |
| 137 | + |
| 138 | + if docstring: |
| 139 | + operation["description"] = docstring |
| 140 | + |
| 141 | + # Build response schema |
| 142 | + schema_cls = _ENDPOINT_SCHEMAS.get(path) |
| 143 | + if schema_cls is not None: |
| 144 | + response_schema = _dataclass_to_schema(schema_cls) |
| 145 | + elif path in _JOB_ENDPOINTS and method == "POST": |
| 146 | + response_schema = _dataclass_to_schema(JobResponse) |
| 147 | + else: |
| 148 | + response_schema = {"type": "object"} |
| 149 | + |
| 150 | + operation["responses"]["200"] = { |
| 151 | + "description": "Successful response", |
| 152 | + "content": { |
| 153 | + "application/json": {"schema": response_schema} |
| 154 | + }, |
| 155 | + } |
| 156 | + |
| 157 | + # Add 400/403 for POST endpoints |
| 158 | + if method == "POST": |
| 159 | + operation["responses"]["400"] = { |
| 160 | + "description": "Validation error", |
| 161 | + "content": { |
| 162 | + "application/json": { |
| 163 | + "schema": { |
| 164 | + "type": "object", |
| 165 | + "properties": {"error": {"type": "string"}}, |
| 166 | + } |
| 167 | + } |
| 168 | + }, |
| 169 | + } |
| 170 | + operation["responses"]["403"] = { |
| 171 | + "description": "Missing or invalid CSRF token", |
| 172 | + "content": { |
| 173 | + "application/json": { |
| 174 | + "schema": { |
| 175 | + "type": "object", |
| 176 | + "properties": {"error": {"type": "string"}}, |
| 177 | + } |
| 178 | + } |
| 179 | + }, |
| 180 | + } |
| 181 | + |
| 182 | + path_item[method.lower()] = operation |
| 183 | + |
| 184 | + return { |
| 185 | + "openapi": "3.0.3", |
| 186 | + "info": { |
| 187 | + "title": "OpenCut API", |
| 188 | + "description": "Premiere Pro video editing automation backend", |
| 189 | + "version": __version__, |
| 190 | + }, |
| 191 | + "servers": [{"url": "http://127.0.0.1:5679"}], |
| 192 | + "paths": paths, |
| 193 | + } |
0 commit comments