File size: 2,935 Bytes
9c9ef1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read-only upstream Swagger inspector. Does not run model inference.

Usage:
    python scripts/inspect_upstreams.py

Loads service URLs from environment variables when available.
"""

import os
import sys
from urllib.parse import urlparse, urlunparse

import httpx

STAGES = {
    "progression": os.getenv("PROGRESSION_API_URL", "https://mjpsm-activity-progression-api.hf.space"),
    "composition": os.getenv("COMPOSITION_API_URL", "https://mjpsm-activity-composition-api.hf.space"),
    "instruction": os.getenv("INSTRUCTION_API_URL", "https://mjpsm-activity-instruction-api.hf.space"),
}


def dereference(spec, schema):
    for _ in range(5):
        if not isinstance(schema, dict) or "$ref" not in schema:
            return schema
        ref = schema["$ref"]
        if not ref.startswith("#/components/schemas/"):
            return schema
        name = ref.split("/")[-1]
        schema = spec.get("components", {}).get("schemas", {}).get(name, {})
    return schema


def inspect(stage, url):
    parsed = urlparse(url)
    base = urlunparse(parsed._replace(path="", query="", fragment="")).rstrip("/")
    schema_url = base + "/openapi.json"
    headers = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"} if os.getenv("HF_TOKEN") else {}
    print(f"\n[{stage.upper()}] {schema_url}")
    try:
        with httpx.Client(timeout=40, follow_redirects=True, headers=headers) as client:
            response = client.get(schema_url)
            response.raise_for_status()
            spec = response.json()
        operations = [
            (path, methods["post"])
            for path, methods in spec.get("paths", {}).items()
            if isinstance(methods, dict) and "post" in methods
        ]
        if not operations:
            print("  No POST paths advertised")
        for path, post in operations:
            body = (post.get("requestBody") or {}).get("content", {}).get("application/json", {})
            schema = dereference(spec, body.get("schema", {}))
            props = schema.get("properties", {})
            print("  POST", base + path)
            print("  Request properties:", ", ".join(props) if props else "(not specified)")
            print("  Required properties:", ", ".join(schema.get("required", [])) or "(not specified)")
            for key, prop in props.items():
                sub = dereference(spec, prop)
                if sub.get("properties"):
                    print(f"    {key} nested properties:", ", ".join(sub["properties"]))
    except (httpx.HTTPError, ValueError, TypeError) as exc:
        print(f"  Could not inspect: {type(exc).__name__}: {exc}")
        return False
    return True


def main():
    successful = sum(inspect(stage, url) for stage, url in STAGES.items())
    print(f"\nInspected {successful} of {len(STAGES)} upstream specifications.")
    return 0 if successful == len(STAGES) else 1


if __name__ == "__main__":
    sys.exit(main())