JAYNESTV commited on
Commit
d54b8c5
Β·
verified Β·
1 Parent(s): 2bf6aca

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -141
app.py CHANGED
@@ -1,17 +1,10 @@
1
- """
2
- JAYNES MAX β€” HLS Bridge (Hugging Face Space, Gradio + FastAPI + ffmpeg)
3
 
4
- Inapokea MPD + ClearKey kutoka kwenye app, inasimbua kwa ffmpeg (bila ku-encode video)
5
- na kuhudumia HLS (.m3u8 + .ts) ambayo iPhone/Safari inacheza asili.
6
 
7
- POST /start {"mpd": "...", "kid": "...", "key": "..."} -> {"url": ".../hls/<id>/index.m3u8"}
8
- GET /hls/<id>/index.m3u8 (+ segments)
9
- POST /stop/<id>
10
- GET /health
11
- """
12
  import hashlib
13
  import ipaddress
14
- import os
15
  import re
16
  import shutil
17
  import socket
@@ -22,36 +15,64 @@ import time
22
  from urllib.parse import urlparse
23
 
24
  import gradio as gr
25
- import uvicorn
26
- from fastapi import FastAPI, HTTPException
27
- from fastapi.middleware.cors import CORSMiddleware
28
- from fastapi.responses import FileResponse
29
- from pydantic import BaseModel
30
-
31
- # ── Mipangilio (weka kwenye Space β†’ Settings β†’ Variables and secrets) ──
32
- MAX_SESSIONS = int(os.getenv("MAX_SESSIONS", "3")) # channel zinazoweza kuchezwa kwa wakati mmoja
33
- IDLE_TIMEOUT = int(os.getenv("IDLE_TIMEOUT", "45")) # sekunde bila mtazamaji -> ffmpeg inazimwa
34
- START_TOKEN = os.getenv("START_TOKEN", "") # (hiari) token ya kulinda /start
35
- ID_SECRET = os.getenv("ID_SECRET", "change-me") # chumvi ya kutengeneza session id
36
- ALLOWED_ORIGINS = [o.strip() for o in os.getenv("ALLOWED_ORIGINS", "*").split(",") if o.strip()]
37
- READY_TIMEOUT = int(os.getenv("READY_TIMEOUT", "35")) # sekunde za kusubiri playlist ya kwanza
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  ROOT = os.path.join(tempfile.gettempdir(), "hls_bridge")
40
  os.makedirs(ROOT, exist_ok=True)
41
 
42
  UA = "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome/124.0 Mobile Safari/537.36"
43
 
44
- sessions: dict = {}
45
- lock = threading.Lock()
46
- _key_opt_cache = None
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
 
 
48
 
49
- # ─────────────────────────── ffmpeg helpers ───────────────────────────
 
50
  def key_option() -> str:
51
- """Jina la option ya ufunguo hutofautiana kati ya matoleo ya ffmpeg."""
52
- global _key_opt_cache
53
- if _key_opt_cache:
54
- return _key_opt_cache
55
  opt = "-decryption_key"
56
  try:
57
  out = subprocess.run(["ffmpeg", "-hide_banner", "-h", "demuxer=dash"],
@@ -60,24 +81,24 @@ def key_option() -> str:
60
  opt = "-cenc_decryption_key"
61
  except Exception:
62
  pass
63
- _key_opt_cache = opt
64
  return opt
65
 
66
 
67
  def check_public_url(url: str) -> None:
68
  p = urlparse(url)
69
  if p.scheme not in ("http", "https") or not p.hostname:
70
- raise HTTPException(400, "MPD lazima iwe URL ya http/https")
71
  try:
72
  for info in socket.getaddrinfo(p.hostname, None):
73
  ip = ipaddress.ip_address(info[4][0])
74
  if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
75
- raise HTTPException(400, "Anwani hairuhusiwi")
76
  except socket.gaierror:
77
- raise HTTPException(400, "Host haipatikani")
78
 
79
 
80
- def clean_hex(s: str | None) -> str:
81
  return re.sub(r"[^0-9a-fA-F]", "", s or "").lower()
82
 
83
 
@@ -94,20 +115,15 @@ def spawn_ffmpeg(sid: str, mpd: str, key: str) -> dict:
94
  shutil.rmtree(d, ignore_errors=True)
95
  os.makedirs(d, exist_ok=True)
96
  log = os.path.join(d, "ffmpeg.log")
97
- cmd = [
98
- "ffmpeg", "-hide_banner", "-loglevel", "warning", "-nostdin",
99
- "-protocol_whitelist", "http,https,tcp,tls,crypto",
100
- "-user_agent", UA,
101
- ]
102
  if key:
103
  cmd += [key_option(), key]
104
  cmd += [
105
  "-i", mpd,
106
- "-c:v", "copy", # video haibadilishwi (CPU ndogo)
107
- "-c:a", "aac", "-b:a", "128k", "-ac", "2", # sauti -> AAC kwa iPhone
108
- "-f", "hls",
109
- "-hls_time", "4",
110
- "-hls_list_size", "8",
111
  "-hls_flags", "delete_segments+independent_segments",
112
  "-hls_segment_filename", os.path.join(d, "seg_%05d.ts"),
113
  os.path.join(d, "index.m3u8"),
@@ -116,14 +132,31 @@ def spawn_ffmpeg(sid: str, mpd: str, key: str) -> dict:
116
  return {"proc": proc, "dir": d, "log": log, "last": time.time(), "mpd": mpd}
117
 
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  def wait_ready(sid: str) -> None:
120
- s = sessions[sid]
121
  playlist = os.path.join(s["dir"], "index.m3u8")
122
  t0 = time.time()
123
  while time.time() - t0 < READY_TIMEOUT:
124
  if s["proc"].poll() is not None:
 
125
  stop_session(sid)
126
- raise HTTPException(502, "ffmpeg imeshindwa: " + (tail(s["log"]) or "hakuna maelezo"))
127
  try:
128
  with open(playlist) as f:
129
  if f.read().count(".ts") >= 2:
@@ -131,160 +164,167 @@ def wait_ready(sid: str) -> None:
131
  except FileNotFoundError:
132
  pass
133
  time.sleep(0.5)
134
- err = tail(s["log"])
135
  stop_session(sid)
136
- raise HTTPException(504, "Muda umeisha kusubiri stream. " + err)
137
 
138
 
139
- # ─────────────────────────── sessions ───────────────────────────
140
- def stop_session(sid: str) -> None:
141
- with lock:
142
- s = sessions.pop(sid, None)
143
- if not s:
144
- return
145
- try:
146
- s["proc"].terminate()
147
- s["proc"].wait(timeout=5)
148
- except Exception:
149
- try:
150
- s["proc"].kill()
151
- except Exception:
152
- pass
153
- shutil.rmtree(s["dir"], ignore_errors=True)
154
-
155
-
156
- def start_session(mpd: str, kid: str | None, key: str | None) -> str:
157
  mpd = (mpd or "").strip()
158
  check_public_url(mpd)
159
  k = clean_hex(key)
160
  if key and not re.fullmatch(r"[0-9a-f]{32}", k):
161
- raise HTTPException(400, "Key lazima iwe hex ya herufi 32")
162
  sid = hashlib.sha256(f"{ID_SECRET}|{mpd}|{k}".encode()).hexdigest()[:24]
163
- with lock:
164
- s = sessions.get(sid)
165
  if s and s["proc"].poll() is None:
166
  s["last"] = time.time()
167
  fresh = False
168
  else:
169
- if s:
170
- sessions.pop(sid, None)
171
- live = sum(1 for x in sessions.values() if x["proc"].poll() is None)
172
  if live >= MAX_SESSIONS:
173
- raise HTTPException(503, "Server ina shughuli nyingi, jaribu tena baadaye")
174
- sessions[sid] = spawn_ffmpeg(sid, mpd, k)
175
  fresh = True
176
  if fresh:
177
  wait_ready(sid)
178
  return sid
179
 
180
 
181
- def reaper():
 
 
 
 
 
182
  while True:
183
  time.sleep(10)
184
  now = time.time()
185
- for sid, s in list(sessions.items()):
186
  if now - s["last"] > IDLE_TIMEOUT or s["proc"].poll() is not None:
187
  stop_session(sid)
 
 
 
 
 
 
188
 
189
 
190
- threading.Thread(target=reaper, daemon=True).start()
191
 
192
 
193
- def public_url(sid: str) -> str:
194
- host = os.getenv("SPACE_HOST")
195
- base = f"https://{host}" if host else "http://localhost:7860"
196
- return f"{base}/hls/{sid}/index.m3u8"
197
-
198
-
199
- # ─────────────────────────── API (FastAPI) ───────────────────────────
200
- api = FastAPI(title="JAYNES MAX HLS Bridge")
201
- api.add_middleware(
202
- CORSMiddleware,
203
- allow_origins=ALLOWED_ORIGINS,
204
- allow_methods=["GET", "POST", "OPTIONS"],
205
- allow_headers=["*"],
206
- allow_credentials=False,
207
- )
208
-
209
-
210
- class StartReq(BaseModel):
211
- mpd: str
212
- kid: str | None = None
213
- key: str | None = None
214
- token: str | None = None
215
 
216
 
217
- @api.post("/start")
218
- def api_start(req: StartReq): # def (si async) -> inaendeshwa kwenye threadpool
219
- if START_TOKEN and req.token != START_TOKEN:
220
- raise HTTPException(401, "Token si sahihi")
221
- sid = start_session(req.mpd, req.kid, req.key)
222
- return {"id": sid, "url": public_url(sid)}
223
 
224
 
225
- @api.post("/stop/{sid}")
226
- def api_stop(sid: str):
227
  if re.fullmatch(r"[a-f0-9]{24}", sid):
228
- stop_session(sid)
229
- return {"ok": True}
230
 
231
 
232
- @api.get("/hls/{sid}/{name}")
233
- def api_hls(sid: str, name: str):
234
  if not re.fullmatch(r"[a-f0-9]{24}", sid) or not re.fullmatch(r"index\.m3u8|seg_\d{5}\.ts", name):
235
- raise HTTPException(404)
236
- s = sessions.get(sid)
237
  if not s:
238
- raise HTTPException(404, "Session haipo")
239
  s["last"] = time.time()
240
  path = os.path.join(s["dir"], name)
241
  if not os.path.exists(path):
242
- raise HTTPException(404)
243
  if name.endswith(".m3u8"):
244
- return FileResponse(path, media_type="application/vnd.apple.mpegurl",
245
- headers={"Cache-Control": "no-store"})
246
- return FileResponse(path, media_type="video/mp2t", headers={"Cache-Control": "max-age=30"})
 
 
247
 
248
 
249
- @api.get("/health")
250
- def api_health():
251
- return {"ok": True, "sessions": len(sessions), "key_option": key_option()}
 
 
 
 
252
 
253
 
254
- # ─────────────────────────── UI (Gradio) ───────────────────────────
255
- def ui_start(mpd, kid, key):
256
  try:
257
- sid = start_session(mpd, kid, key)
258
  return public_url(sid), "βœ… Imeanza"
259
- except HTTPException as e:
260
  return "", f"❌ {e.detail}"
261
 
262
 
263
  def ui_list():
264
  now = time.time()
265
- return [[sid, s["mpd"][:60], f"{int(now - s['last'])}s", "ndio" if s["proc"].poll() is None else "hapana"]
266
- for sid, s in sessions.items()]
267
 
268
 
269
  def ui_stop_all():
270
- for sid in list(sessions):
271
  stop_session(sid)
272
- return ui_list()
 
273
 
 
 
274
 
275
- with gr.Blocks(title="JAYNES MAX HLS Bridge") as demo:
 
276
  gr.Markdown("## JAYNES MAX β€” HLS Bridge\nMPD + ClearKey β†’ HLS kwa iPhone")
277
  mpd_in = gr.Textbox(label="MPD URL")
278
- kid_in = gr.Textbox(label="KID (hiari)")
279
  key_in = gr.Textbox(label="KEY (hex 32)")
280
  go = gr.Button("Anza", variant="primary")
281
  out_url = gr.Textbox(label="HLS URL", interactive=False)
282
  out_msg = gr.Markdown()
283
- go.click(ui_start, [mpd_in, kid_in, key_in], [out_url, out_msg], api_name=False)
284
- table = gr.Dataframe(headers=["id", "mpd", "idle", "hai"], value=ui_list, every=5, interactive=False)
285
- gr.Button("Zima zote").click(ui_stop_all, None, table, api_name=False)
286
-
287
- app = gr.mount_gradio_app(api, demo, path="/")
288
-
289
- if __name__ == "__main__":
290
- uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
 
2
 
3
+ # Zima SSR ya Gradio (Node proxy) ili routes zetu zifike moja kwa moja.
4
+ os.environ.setdefault("GRADIO_SSR_MODE", "False")
5
 
 
 
 
 
 
6
  import hashlib
7
  import ipaddress
 
8
  import re
9
  import shutil
10
  import socket
 
15
  from urllib.parse import urlparse
16
 
17
  import gradio as gr
18
+ import requests
19
+ from fastapi import Request
20
+ from fastapi.responses import FileResponse, JSONResponse, Response
21
+ from starlette.concurrency import run_in_threadpool
22
+
23
+ # ZeroGPU inahitaji angalau function moja yenye @spaces.GPU wakati wa startup.
24
+ # Placeholder tu; haiitwi kamwe. (Kama Space iko kwenye CPU basic, haina madhara.)
25
+ try:
26
+ import spaces
27
+
28
+ @spaces.GPU
29
+ def _gpu_placeholder() -> str:
30
+ return "ok"
31
+ except ImportError:
32
+ pass
33
+
34
+ SPACE_HOST = os.environ.get("SPACE_HOST", "")
35
+ SELF_URL = f"https://{SPACE_HOST}" if SPACE_HOST else os.environ.get("SELF_URL", "")
36
+
37
+ # ── Mipangilio (Space β†’ Settings β†’ Variables and secrets) ──
38
+ BRIDGE_TOKEN = os.environ.get("BRIDGE_TOKEN", "") # hiari: ulinzi wa /bridge/start
39
+ ID_SECRET = os.environ.get("ID_SECRET", "change-me")
40
+ MAX_SESSIONS = int(os.environ.get("MAX_SESSIONS", "3"))
41
+ IDLE_TIMEOUT = int(os.environ.get("IDLE_TIMEOUT", "45"))
42
+ READY_TIMEOUT = int(os.environ.get("READY_TIMEOUT", "35"))
43
+ PING_INTERVAL_SECONDS = 300
44
 
45
  ROOT = os.path.join(tempfile.gettempdir(), "hls_bridge")
46
  os.makedirs(ROOT, exist_ok=True)
47
 
48
  UA = "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome/124.0 Mobile Safari/537.36"
49
 
50
+ SESSIONS: dict = {}
51
+ LOCK = threading.Lock()
52
+ _key_opt = None
53
+
54
+
55
+ class BridgeError(Exception):
56
+ def __init__(self, status: int, detail: str):
57
+ super().__init__(detail)
58
+ self.status, self.detail = status, detail
59
+
60
+
61
+ def cors(resp: Response) -> Response:
62
+ resp.headers["Access-Control-Allow-Origin"] = "*"
63
+ resp.headers["Access-Control-Expose-Headers"] = "*"
64
+ return resp
65
+
66
 
67
+ def err(status: int, detail: str) -> Response:
68
+ return cors(JSONResponse({"detail": detail}, status_code=status))
69
 
70
+
71
+ # ───────────────────────── ffmpeg ─────────────────────────
72
  def key_option() -> str:
73
+ global _key_opt
74
+ if _key_opt:
75
+ return _key_opt
 
76
  opt = "-decryption_key"
77
  try:
78
  out = subprocess.run(["ffmpeg", "-hide_banner", "-h", "demuxer=dash"],
 
81
  opt = "-cenc_decryption_key"
82
  except Exception:
83
  pass
84
+ _key_opt = opt
85
  return opt
86
 
87
 
88
  def check_public_url(url: str) -> None:
89
  p = urlparse(url)
90
  if p.scheme not in ("http", "https") or not p.hostname:
91
+ raise BridgeError(400, "MPD lazima iwe URL ya http/https")
92
  try:
93
  for info in socket.getaddrinfo(p.hostname, None):
94
  ip = ipaddress.ip_address(info[4][0])
95
  if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
96
+ raise BridgeError(400, "Anwani hairuhusiwi")
97
  except socket.gaierror:
98
+ raise BridgeError(400, "Host haipatikani")
99
 
100
 
101
+ def clean_hex(s) -> str:
102
  return re.sub(r"[^0-9a-fA-F]", "", s or "").lower()
103
 
104
 
 
115
  shutil.rmtree(d, ignore_errors=True)
116
  os.makedirs(d, exist_ok=True)
117
  log = os.path.join(d, "ffmpeg.log")
118
+ cmd = ["ffmpeg", "-hide_banner", "-loglevel", "warning", "-nostdin",
119
+ "-protocol_whitelist", "http,https,tcp,tls,crypto", "-user_agent", UA]
 
 
 
120
  if key:
121
  cmd += [key_option(), key]
122
  cmd += [
123
  "-i", mpd,
124
+ "-c:v", "copy", # video haibadilishwi
125
+ "-c:a", "aac", "-b:a", "128k", "-ac", "2", # sauti -> AAC kwa iPhone
126
+ "-f", "hls", "-hls_time", "4", "-hls_list_size", "8",
 
 
127
  "-hls_flags", "delete_segments+independent_segments",
128
  "-hls_segment_filename", os.path.join(d, "seg_%05d.ts"),
129
  os.path.join(d, "index.m3u8"),
 
132
  return {"proc": proc, "dir": d, "log": log, "last": time.time(), "mpd": mpd}
133
 
134
 
135
+ def stop_session(sid: str) -> None:
136
+ with LOCK:
137
+ s = SESSIONS.pop(sid, None)
138
+ if not s:
139
+ return
140
+ try:
141
+ s["proc"].terminate()
142
+ s["proc"].wait(timeout=5)
143
+ except Exception:
144
+ try:
145
+ s["proc"].kill()
146
+ except Exception:
147
+ pass
148
+ shutil.rmtree(s["dir"], ignore_errors=True)
149
+
150
+
151
  def wait_ready(sid: str) -> None:
152
+ s = SESSIONS[sid]
153
  playlist = os.path.join(s["dir"], "index.m3u8")
154
  t0 = time.time()
155
  while time.time() - t0 < READY_TIMEOUT:
156
  if s["proc"].poll() is not None:
157
+ msg = tail(s["log"]) or "hakuna maelezo"
158
  stop_session(sid)
159
+ raise BridgeError(502, "ffmpeg imeshindwa: " + msg)
160
  try:
161
  with open(playlist) as f:
162
  if f.read().count(".ts") >= 2:
 
164
  except FileNotFoundError:
165
  pass
166
  time.sleep(0.5)
167
+ msg = tail(s["log"])
168
  stop_session(sid)
169
+ raise BridgeError(504, "Muda umeisha kusubiri stream. " + msg)
170
 
171
 
172
+ def start_session(mpd: str, key: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  mpd = (mpd or "").strip()
174
  check_public_url(mpd)
175
  k = clean_hex(key)
176
  if key and not re.fullmatch(r"[0-9a-f]{32}", k):
177
+ raise BridgeError(400, "Key lazima iwe hex ya herufi 32")
178
  sid = hashlib.sha256(f"{ID_SECRET}|{mpd}|{k}".encode()).hexdigest()[:24]
179
+ with LOCK:
180
+ s = SESSIONS.get(sid)
181
  if s and s["proc"].poll() is None:
182
  s["last"] = time.time()
183
  fresh = False
184
  else:
185
+ SESSIONS.pop(sid, None)
186
+ live = sum(1 for x in SESSIONS.values() if x["proc"].poll() is None)
 
187
  if live >= MAX_SESSIONS:
188
+ raise BridgeError(503, "Server ina shughuli nyingi, jaribu tena baadaye")
189
+ SESSIONS[sid] = spawn_ffmpeg(sid, mpd, k)
190
  fresh = True
191
  if fresh:
192
  wait_ready(sid)
193
  return sid
194
 
195
 
196
+ def public_url(sid: str) -> str:
197
+ return f"{SELF_URL or 'http://localhost:7860'}/hls/{sid}/index.m3u8"
198
+
199
+
200
+ def housekeeping_loop():
201
+ last_ping = time.time()
202
  while True:
203
  time.sleep(10)
204
  now = time.time()
205
+ for sid, s in list(SESSIONS.items()):
206
  if now - s["last"] > IDLE_TIMEOUT or s["proc"].poll() is not None:
207
  stop_session(sid)
208
+ if SELF_URL and now - last_ping > PING_INTERVAL_SECONDS:
209
+ last_ping = now
210
+ try:
211
+ requests.get(SELF_URL, timeout=15)
212
+ except Exception:
213
+ pass
214
 
215
 
216
+ threading.Thread(target=housekeeping_loop, daemon=True).start()
217
 
218
 
219
+ # ───────────────────────── Routes ─────────────────────────
220
+ # /bridge/start inakubali POST ya JSON (Content-Type: text/plain inaepuka preflight ya CORS).
221
+ async def bridge_start(request: Request):
222
+ try:
223
+ body = await request.json()
224
+ except Exception:
225
+ return err(400, "JSON si sahihi.")
226
+ if BRIDGE_TOKEN and body.get("token") != BRIDGE_TOKEN:
227
+ return err(401, "Token si sahihi.")
228
+ try:
229
+ sid = await run_in_threadpool(start_session, body.get("mpd"), body.get("key"))
230
+ except BridgeError as e:
231
+ return err(e.status, e.detail)
232
+ return cors(JSONResponse({"id": sid, "url": public_url(sid)}))
 
 
 
 
 
 
 
 
233
 
234
 
235
+ async def bridge_options(request: Request):
236
+ r = Response(status_code=204)
237
+ r.headers["Access-Control-Allow-Origin"] = "*"
238
+ r.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
239
+ r.headers["Access-Control-Allow-Headers"] = request.headers.get("access-control-request-headers", "*")
240
+ return r
241
 
242
 
243
+ async def bridge_stop(sid: str):
 
244
  if re.fullmatch(r"[a-f0-9]{24}", sid):
245
+ await run_in_threadpool(stop_session, sid)
246
+ return cors(JSONResponse({"ok": True}))
247
 
248
 
249
+ async def hls_file(sid: str, name: str):
 
250
  if not re.fullmatch(r"[a-f0-9]{24}", sid) or not re.fullmatch(r"index\.m3u8|seg_\d{5}\.ts", name):
251
+ return err(404, "Haipatikani")
252
+ s = SESSIONS.get(sid)
253
  if not s:
254
+ return err(404, "Session haipo")
255
  s["last"] = time.time()
256
  path = os.path.join(s["dir"], name)
257
  if not os.path.exists(path):
258
+ return err(404, "Haipatikani")
259
  if name.endswith(".m3u8"):
260
+ r = FileResponse(path, media_type="application/vnd.apple.mpegurl",
261
+ headers={"Cache-Control": "no-store"})
262
+ else:
263
+ r = FileResponse(path, media_type="video/mp2t", headers={"Cache-Control": "max-age=30"})
264
+ return cors(r)
265
 
266
 
267
+ async def bridge_health():
268
+ r = subprocess.run(["ffmpeg", "-version"], capture_output=True, text=True)
269
+ first = (r.stdout or r.stderr or "").splitlines()[:1]
270
+ return cors(JSONResponse({
271
+ "ok": True, "sessions": len(SESSIONS), "key_option": key_option(),
272
+ "ffmpeg": first[0] if first else "haijulikani",
273
+ }))
274
 
275
 
276
+ # ───────────────────────── UI ─────────────────────────
277
+ def ui_start(mpd, key):
278
  try:
279
+ sid = start_session(mpd, key)
280
  return public_url(sid), "βœ… Imeanza"
281
+ except BridgeError as e:
282
  return "", f"❌ {e.detail}"
283
 
284
 
285
  def ui_list():
286
  now = time.time()
287
+ return "\n".join(f"{sid} idle={int(now - s['last'])}s {s['mpd'][:70]}" for sid, s in SESSIONS.items()) or "Hakuna session."
 
288
 
289
 
290
  def ui_stop_all():
291
+ for sid in list(SESSIONS):
292
  stop_session(sid)
293
+ return "Zimezimwa."
294
+
295
 
296
+ def health_check() -> str:
297
+ return "ok"
298
 
299
+
300
+ with gr.Blocks(title="JAYNES MAX β€” HLS Bridge") as demo:
301
  gr.Markdown("## JAYNES MAX β€” HLS Bridge\nMPD + ClearKey β†’ HLS kwa iPhone")
302
  mpd_in = gr.Textbox(label="MPD URL")
 
303
  key_in = gr.Textbox(label="KEY (hex 32)")
304
  go = gr.Button("Anza", variant="primary")
305
  out_url = gr.Textbox(label="HLS URL", interactive=False)
306
  out_msg = gr.Markdown()
307
+ go.click(ui_start, [mpd_in, key_in], [out_url, out_msg], api_name=False)
308
+ sess_out = gr.Textbox(label="Sessions", interactive=False, lines=3)
309
+ with gr.Row():
310
+ gr.Button("Onyesha sessions").click(ui_list, None, sess_out, api_name=False)
311
+ gr.Button("Zima zote").click(ui_stop_all, None, sess_out, api_name=False)
312
+ health_out = gr.Textbox(visible=False)
313
+ demo.load(fn=health_check, outputs=health_out, api_name="health")
314
+
315
+
316
+ demo.queue(max_size=20)
317
+ demo.launch(prevent_thread_lock=True)
318
+
319
+ # Ongeza routes zetu mbele ya routes za Gradio ili zipate kipaumbele
320
+ _fastapi = demo.app
321
+ _before = len(_fastapi.router.routes)
322
+ _fastapi.add_api_route("/bridge/start", bridge_start, methods=["POST"])
323
+ _fastapi.add_api_route("/bridge/start", bridge_options, methods=["OPTIONS"])
324
+ _fastapi.add_api_route("/bridge/stop/{sid}", bridge_stop, methods=["POST"])
325
+ _fastapi.add_api_route("/bridge/health", bridge_health, methods=["GET"])
326
+ _fastapi.add_api_route("/hls/{sid}/{name}", hls_file, methods=["GET"])
327
+ _new = _fastapi.router.routes[_before:]
328
+ _fastapi.router.routes[:] = _new + _fastapi.router.routes[:_before]
329
+
330
+ demo.block_thread()