File size: 6,531 Bytes
021c59c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e882b71
021c59c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37974e4
a13f875
37974e4
 
 
a13f875
 
 
 
 
097dfd6
 
 
 
021c59c
 
 
7ee0711
 
 
 
 
 
 
 
 
 
 
 
021c59c
7ee0711
 
 
021c59c
 
 
 
 
 
 
 
eddd90b
 
021c59c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e882b71
 
 
 
 
 
 
37974e4
 
 
 
 
 
 
 
 
a13f875
 
 
 
 
 
 
 
 
097dfd6
 
 
 
 
 
 
 
 
b9183e9
 
 
 
 
 
 
 
 
021c59c
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
"""FastAPI app factory for the NIGHTWAVE Space orchestrator.

Exposes the same-origin proxy routes the browser radio calls:
  POST /api/broadcast {stage, meter, topic?}
  POST /api/call      {stage, meter, audio_b64}
  POST /api/seek      {meter}

Every proxy call is wrapped in try/except so a Modal hiccup (or cold-start
timeout) NEVER 500s the radio -- we fall back to a canned, stage-appropriate
line and a short silent WAV. The radio must never go silent.

Also provides radio_iframe_html(): reads space/radio.html from disk and wraps
it in a sandboxed <iframe srcdoc=...> for embedding inside the Gradio Blocks
page (gr.HTML does not execute <script>, so the radio must live in an iframe).
"""

import html
import os
from typing import Any, Dict, Optional

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel

import arc
import content
import proxy

_HERE = os.path.dirname(os.path.abspath(__file__))
_RADIO_HTML_PATH = os.path.join(_HERE, "radio.html")


# ---------------------------------------------------------------------------
# Request models
# ---------------------------------------------------------------------------
class BroadcastReq(BaseModel):
    stage: str
    meter: int
    topic: Optional[str] = None


class CallReq(BaseModel):
    stage: str
    meter: int
    audio_b64: str


class SeekReq(BaseModel):
    meter: int


class SegmentReq(BaseModel):
    kind: str  # station_id | thought | weather | local_weather | dedication | song_intro | rejoin | caller_intro
    ctx: Optional[Dict[str, Any]] = None


class LocaleReq(BaseModel):
    lat: float
    lon: float


class SongCardReq(BaseModel):
    ctx: Optional[Dict[str, Any]] = None


# ---------------------------------------------------------------------------
# Graceful fallbacks (never let the radio go silent)
# ---------------------------------------------------------------------------
_FALLBACK_LINES = [
    "It's Sam Dusk -- we had a little hiccup on the signal there, but I'm still with "
    "you. Let's let this next one play.",
    "Sam Dusk here. The line crackled for a second, friend; pay it no mind and stay "
    "with me a while.",
    "You're back with Sam Dusk on NIGHTWAVE. A small bump in the broadcast -- nothing "
    "the night can't smooth over.",
]


def _fallback_payload(stage: str = "", include_caller: bool = False) -> Dict[str, Any]:
    import random
    payload: Dict[str, Any] = {
        "text": random.choice(_FALLBACK_LINES),
        "mood": "warm",
        "arc_cue": "none",
        "audio_b64": proxy._silent_wav_b64(),
        "words": [],
        "wtimes": [],
        "wdurations": [],
    }
    if include_caller:
        payload["caller_text"] = ""
        payload["meter_delta"] = 0
        payload["memory_patch"] = None
        payload["queue_dedication"] = False
    return payload


# ---------------------------------------------------------------------------
# Radio iframe embedding (for the Gradio Blocks page)
# ---------------------------------------------------------------------------
def radio_iframe_html() -> str:
    """Read radio.html and return it wrapped in a sandboxed iframe srcdoc."""
    with open(_RADIO_HTML_PATH, "r", encoding="utf-8") as fh:
        doc = fh.read()
    escaped = html.escape(doc, quote=True)
    return (
        '<iframe srcdoc="' + escaped + '" '
        'width="100%" height="860" '
        'allow="microphone; autoplay" '
        'style="border:0;display:block" '
        'referrerpolicy="no-referrer"></iframe>'
    )


def read_radio_html() -> str:
    """Return the raw radio document (used by devserver to serve at top level)."""
    with open(_RADIO_HTML_PATH, "r", encoding="utf-8") as fh:
        return fh.read()


# ---------------------------------------------------------------------------
# App factory
# ---------------------------------------------------------------------------
def create_api() -> FastAPI:
    api = FastAPI(title="NIGHTWAVE", docs_url=None, redoc_url=None)

    @api.post("/api/broadcast")
    def api_broadcast(req: BroadcastReq):
        stage = arc.meter_to_stage(req.meter)
        try:
            return proxy.broadcast_turn(stage, req.meter, req.topic)
        except Exception:
            return JSONResponse(_fallback_payload(stage))

    @api.post("/api/call")
    def api_call(req: CallReq):
        stage = arc.meter_to_stage(req.meter)
        try:
            return proxy.call_turn(stage, req.meter, req.audio_b64)
        except Exception:
            return JSONResponse(_fallback_payload(stage, include_caller=True))

    @api.post("/api/seek")
    def api_seek(req: SeekReq):
        return {"stage": arc.meter_to_stage(req.meter)}

    @api.get("/api/songs")
    def api_songs():
        # The curated song bank: the browser renders the generative music + the
        # now-playing plate from each song's musical params, and song_intro uses
        # the title/artist. Single source of truth (space/content.py).
        return {"songs": content.SONGS}

    @api.post("/api/segment")
    def api_segment(req: SegmentReq):
        # One DJ show segment (text + audio). Never break the show: on any failure
        # return a templated segment with a short silent clip (the bed covers it).
        try:
            return proxy.segment_turn(req.kind, req.ctx)
        except Exception:
            return JSONResponse(proxy.segment_fallback(req.kind, req.ctx))

    @api.post("/api/locale")
    def api_locale(req: LocaleReq):
        # Resolve real local weather/time/city for the listener. On any failure,
        # report unresolved so the client cleanly falls back to fictional weather.
        try:
            return proxy.resolve_locale(req.lat, req.lon)
        except Exception:
            return JSONResponse({"resolved": False})

    @api.post("/api/song_card")
    def api_song_card(req: SongCardReq):
        # AI invents a fictional record (validated musical params). On any failure,
        # return {card: None} so the client simply skips it.
        try:
            return {"card": proxy.make_song_card(req.ctx)}
        except Exception:
            return JSONResponse({"card": None})

    @api.get("/api/stalls")
    def api_stalls():
        # Pre-synthesized filler clips the radio plays instantly while a real
        # call reply generates (so the call never has dead air).
        try:
            return {"stalls": proxy.get_stalls()}
        except Exception:
            return {"stalls": []}

    return api