Spaces:
Paused
Paused
Download app.py from haxwitcher/restest: direct link, hf CLI and curl.
- Browser
- Download file 2.13 kB
-
https://huggingface.co/spaces/haxwitcher/restest/resolve/main/app.py
- Command line
-
hf download hf://spaces/haxwitcher/restest/app.py
-
curl -L -o app.py https://huggingface.co/spaces/haxwitcher/restest/resolve/main/app.py
2.13 kB
| # app.py | |
| import os | |
| import subprocess | |
| import pathlib | |
| from typing import Dict | |
| from fastapi import FastAPI | |
| from fastapi.responses import FileResponse, JSONResponse | |
| app = FastAPI() | |
| ffmpeg_processes: Dict[str, subprocess.Popen] = {} | |
| HLS_ROOT = pathlib.Path("hls") | |
| HLS_ROOT.mkdir(exist_ok=True) | |
| def stop_stream(stream_id: str): | |
| process = ffmpeg_processes.get(stream_id) | |
| if process and process.poll() is None: | |
| print(f"[INFO] Zaustavljam prethodni stream: {stream_id}") | |
| process.terminate() | |
| try: | |
| process.wait(timeout=5) | |
| except subprocess.TimeoutExpired: | |
| process.kill() | |
| def start_stream(stream_id: str, source_url: str): | |
| stop_stream(stream_id) # zaustavi prethodni ako postoji | |
| stream_dir = HLS_ROOT / stream_id | |
| if stream_dir.exists(): | |
| for f in stream_dir.glob("*"): | |
| f.unlink() | |
| stream_dir.mkdir(parents=True, exist_ok=True) | |
| ffmpeg_cmd = [ | |
| "ffmpeg", | |
| "-fflags", "+genpts", | |
| "-i", source_url, | |
| "-c:v", "copy", | |
| "-c:a", "copy", | |
| "-f", "hls", | |
| "-hls_time", "4", | |
| "-hls_list_size", "5", | |
| "-hls_flags", "delete_segments+program_date_time", | |
| str(stream_dir / "stream.m3u8") | |
| ] | |
| print(f"[INFO] Pokrećem stream: {stream_id}") | |
| process = subprocess.Popen( | |
| ffmpeg_cmd, | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.STDOUT | |
| ) | |
| ffmpeg_processes[stream_id] = process | |
| # Učitaj sve STREAM_* varijable i pokreni | |
| for key, value in os.environ.items(): | |
| if key.startswith("STREAM_"): | |
| stream_id = key[len("STREAM_"):].lower() | |
| start_stream(stream_id, value) | |
| def serve_hls(stream_id: str, path: str): | |
| file_path = HLS_ROOT / stream_id / path | |
| if file_path.exists(): | |
| return FileResponse(file_path) | |
| return JSONResponse({"error": "ne postoji"}, status_code=404) | |
| def index(): | |
| links = { | |
| stream_id: f"/hls/{stream_id}/stream.m3u8" | |
| for stream_id in ffmpeg_processes | |
| } | |
| return {"status": "aktivni streamovi", "streams": links} | |