File size: 12,887 Bytes
570b87b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Minimal HTTP API so Qwythos / agents can request spatial reports.

Stdlib only (no Flask). Default bind: 127.0.0.1:8765

Endpoints
---------
GET  /health
GET  /v1/spatial/schema          β€” OpenAI-style tool descriptor
POST /v1/spatial/analyze        β€” JSON body β†’ SpatialReport
POST /v1/spatial/analyze_file   β€” {path, mode, az, el, ...}
POST /v1/spatial/demo_scene     β€” synthetic multi-source report
POST /v1/spatial/vision         β€” Phase 3: boxes/rays β†’ spatial report
POST /v1/spatial/fuse           β€” merge audio + vision report dicts

OpenAI tools (for agents with bash): also install ``spatial-report`` on PATH.
"""

from __future__ import annotations

import json
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.parse import urlparse

from . import __version__
from .report import (
    REPORT_SCHEMA_VERSION,
    report_from_ambix_wav,
    report_from_hoa,
    report_from_mono_wav,
    report_from_scene,
)
from .stream import SourceSpec
from .synth import envelope_adsr, tone

DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 8765

TOOL_SCHEMA = {
    "type": "function",
    "function": {
        "name": "spatial_analyze",
        "description": (
            "Analyze spatial audio (Ambix HOA or mono plane-wave) or visual "
            "bounding boxes on the sphere. Returns a compact spatial report "
            "(DOA, bands, frames) from the HOA-7 calculator β€” not an LLM."
        ),
        "parameters": {
            "type": "object",
            "properties": {
                "mode": {
                    "type": "string",
                    "enum": ["ambix_file", "mono_file", "demo_scene", "vision", "fuse"],
                    "description": "Analysis mode",
                },
                "path": {
                    "type": "string",
                    "description": "WAV path for ambix_file or mono_file",
                },
                "az": {
                    "type": "number",
                    "description": "Azimuth degrees for mono plane-wave encode (0=front, +90=left)",
                },
                "el": {
                    "type": "number",
                    "description": "Elevation degrees (0=horizon, +90=zenith)",
                },
                "order": {
                    "type": "integer",
                    "description": "Max HOA order 0..7 (default 3 for speed, 7 full)",
                    "default": 3,
                },
                "boxes": {
                    "type": "array",
                    "description": "Vision boxes: [{az, el, w_deg?, h_deg?, weight?, label?}]",
                    "items": {"type": "object"},
                },
                "audio_report": {
                    "type": "object",
                    "description": "Existing audio SpatialReport dict for fuse mode",
                },
                "vision_report": {
                    "type": "object",
                    "description": "Existing vision SpatialReport dict for fuse mode",
                },
            },
            "required": ["mode"],
        },
    },
}


def _json_response(handler: BaseHTTPRequestHandler, code: int, obj: Any) -> None:
    body = json.dumps(obj, indent=None).encode("utf-8")
    handler.send_response(code)
    handler.send_header("Content-Type", "application/json")
    handler.send_header("Content-Length", str(len(body)))
    handler.send_header("Access-Control-Allow-Origin", "*")
    handler.end_headers()
    handler.wfile.write(body)


def _read_json(handler: BaseHTTPRequestHandler) -> dict:
    n = int(handler.headers.get("Content-Length", "0"))
    raw = handler.rfile.read(n) if n else b"{}"
    if not raw:
        return {}
    return json.loads(raw.decode("utf-8"))


def handle_analyze(body: dict) -> dict:
    mode = body.get("mode", "demo_scene")
    order = int(body.get("order", 3))
    order = max(0, min(7, order))

    if mode == "demo_scene":
        sr = int(body.get("sample_rate", 48000))
        dur = float(body.get("duration", 0.4))
        n = int(sr * dur)
        env = envelope_adsr(n, sr)
        sources = [
            SourceSpec(0.0, 0.0, tone(440, dur, sr, amplitude=0.4) * env, "front"),
            SourceSpec(90.0, 10.0, tone(660, dur, sr, amplitude=0.25) * env, "left"),
        ]
        rep = report_from_scene(sources, sr, max_order=order)
        d = rep.to_dict()
        d["one_liner"] = rep.one_liner()
        return d

    if mode == "ambix_file":
        path = body.get("path") or body.get("file")
        if not path:
            raise ValueError("path required for ambix_file")
        rep = report_from_ambix_wav(path, max_order=order)
        d = rep.to_dict()
        d["one_liner"] = rep.one_liner()
        return d

    if mode == "mono_file":
        path = body.get("path") or body.get("file")
        if not path:
            raise ValueError("path required for mono_file")
        if body.get("az") is None:
            raise ValueError("az required for mono_file plane-wave encode")
        rep = report_from_mono_wav(
            path,
            float(body["az"]),
            float(body.get("el", 0.0)),
            max_order=order,
        )
        d = rep.to_dict()
        d["one_liner"] = rep.one_liner()
        return d

    if mode == "vision":
        from .vision import report_from_boxes

        boxes = body.get("boxes") or []
        rep = report_from_boxes(boxes, max_order=order)
        d = rep.to_dict()
        d["one_liner"] = rep.one_liner()
        return d

    if mode == "fuse":
        from .vision import fuse_reports

        ar = body.get("audio_report") or {}
        vr = body.get("vision_report") or {}
        return fuse_reports(ar, vr)

    if mode == "detect":
        from .detector import detect_to_sphere, load_boxes_json
        from .vision import report_from_boxes

        if body.get("boxes_path"):
            boxes = load_boxes_json(body["boxes_path"])
        elif body.get("image"):
            boxes = detect_to_sphere(
                body["image"],
                backend=body.get("backend", "auto"),
                score_thresh=float(body.get("score", 0.5)),
                hfov_deg=float(body.get("hfov", 90)),
                vfov_deg=float(body.get("vfov", 60)),
            )
        else:
            boxes = body.get("boxes") or []
        rep = report_from_boxes(boxes, max_order=order)
        d = rep.to_dict()
        d["one_liner"] = rep.one_liner()
        d["boxes"] = boxes
        return d

    if mode == "live":
        from .live_audio import live_report

        rep = live_report(
            duration_sec=float(body.get("duration", 2.0)),
            sample_rate=int(body.get("sample_rate", 48000)),
            channels=int(body.get("channels", 1)),
            source=body.get("source"),
            az_deg=float(body.get("az", 0.0)),
            el_deg=float(body.get("el", 0.0)),
            max_order=order,
            keep_wav=body.get("write_wav"),
        )
        d = rep.to_dict()
        d["one_liner"] = rep.one_liner()
        return d

    if mode == "panner":
        # UI spherical panner: az/el + W amplitude β†’ spatial report (+ optional condition)
        from .conditioning import build_conditioning, panner_report

        rep = panner_report(
            float(body.get("az", body.get("az_deg", 0.0))),
            float(body.get("el", body.get("el_deg", 0.0))),
            float(body.get("w", body.get("w_amplitude", body.get("energy", 0.5)))),
        )
        if body.get("condition") or body.get("prompt"):
            return build_conditioning(
                rep,
                base_prompt=str(body.get("prompt", "")),
                style=str(body.get("style", "natural")),
            )
        return rep

    if mode == "condition":
        from .conditioning import build_conditioning, panner_report

        rep = body.get("report")
        if rep is None and (
            "az" in body or "az_deg" in body or "w" in body or "w_amplitude" in body
        ):
            # Convenience: condition directly from panner knobs
            rep = panner_report(
                float(body.get("az", body.get("az_deg", 0.0))),
                float(body.get("el", body.get("el_deg", 0.0))),
                float(body.get("w", body.get("w_amplitude", body.get("energy", 0.5)))),
            )
        else:
            rep = rep or body
        return build_conditioning(
            rep,
            base_prompt=str(body.get("prompt", "")),
            style=str(body.get("style", "natural")),
        )

    if mode == "hoa_vector":
        # raw coefficients list
        import numpy as np

        coeffs = body.get("hoa") or body.get("coefficients")
        if coeffs is None:
            raise ValueError("hoa coefficients required")
        sr = int(body.get("sample_rate", 48000))
        a = np.asarray(coeffs, dtype=np.float64)
        if a.ndim == 1:
            a = a.reshape(-1, 1)
        rep = report_from_hoa(a, sr, max_order=order)
        d = rep.to_dict()
        d["one_liner"] = rep.one_liner()
        return d

    raise ValueError(f"unknown mode: {mode}")


class SpatialHandler(BaseHTTPRequestHandler):
    server_version = f"spatial-hoa/{__version__}"

    def log_message(self, fmt: str, *args) -> None:
        # quieter default
        sys_stderr = __import__("sys").stderr
        sys_stderr.write("%s - %s\n" % (self.address_string(), fmt % args))

    def do_OPTIONS(self) -> None:
        self.send_response(204)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.end_headers()

    def do_GET(self) -> None:
        path = urlparse(self.path).path
        if path in ("/health", "/v1/health"):
            _json_response(
                self,
                200,
                {
                    "status": "ok",
                    "service": "spatial-hoa",
                    "version": __version__,
                    "schema": REPORT_SCHEMA_VERSION,
                },
            )
            return
        if path in ("/v1/spatial/schema", "/v1/tools"):
            _json_response(
                self,
                200,
                {
                    "tools": [TOOL_SCHEMA],
                    "report_schema": REPORT_SCHEMA_VERSION,
                },
            )
            return
        _json_response(self, 404, {"error": "not found", "path": path})

    def do_POST(self) -> None:
        path = urlparse(self.path).path
        try:
            body = _read_json(self)
        except Exception as e:
            _json_response(self, 400, {"error": f"invalid json: {e}"})
            return
        try:
            if path in (
                "/v1/spatial/analyze",
                "/v1/spatial/analyze_file",
                "/v1/spatial/demo_scene",
                "/v1/spatial/vision",
                "/v1/spatial/fuse",
            ):
                # map path to mode if not set
                if path.endswith("demo_scene") and "mode" not in body:
                    body["mode"] = "demo_scene"
                elif path.endswith("vision") and "mode" not in body:
                    body["mode"] = "vision"
                elif path.endswith("fuse") and "mode" not in body:
                    body["mode"] = "fuse"
                elif path.endswith("analyze_file") and "mode" not in body:
                    body["mode"] = "ambix_file" if body.get("ambix") else "mono_file"
                elif "mode" not in body:
                    body["mode"] = "demo_scene"
                result = handle_analyze(body)
                _json_response(self, 200, result)
                return
            _json_response(self, 404, {"error": "not found", "path": path})
        except Exception as e:
            _json_response(
                self,
                400,
                {"error": str(e), "trace": traceback.format_exc()[-800:]},
            )


def serve(host: str = DEFAULT_HOST, port: int = DEFAULT_PORT) -> None:
    httpd = ThreadingHTTPServer((host, port), SpatialHandler)
    print(f"spatial-hoa API http://{host}:{port}  (hoa64 {__version__})")
    print("  GET  /health")
    print("  GET  /v1/spatial/schema")
    print("  POST /v1/spatial/analyze")
    httpd.serve_forever()


def main(argv: list[str] | None = None) -> int:
    import argparse

    p = argparse.ArgumentParser(description="spatial-hoa HTTP API for Qwythos/agents")
    p.add_argument("--host", default=DEFAULT_HOST)
    p.add_argument("--port", type=int, default=DEFAULT_PORT)
    args = p.parse_args(argv)
    serve(args.host, args.port)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())