Spaces:
Running on Zero
Running on Zero
Download media_access.py from fffiloni/fastframes-voice: direct link, hf CLI and curl.
- Browser
- Download file 3.78 kB
-
https://huggingface.co/spaces/fffiloni/fastframes-voice/resolve/main/media_access.py
- Command line
-
hf download hf://spaces/fffiloni/fastframes-voice/media_access.py
-
curl -L -o media_access.py https://huggingface.co/spaces/fffiloni/fastframes-voice/resolve/main/media_access.py
3.78 kB
| """Serve session media outside Gradio's shared cache.""" | |
| import hashlib | |
| import hmac | |
| import re | |
| import secrets | |
| from pathlib import Path | |
| from starlette.requests import Request | |
| from starlette.responses import FileResponse, Response | |
| import takes | |
| PREFIX = "/studio-media/" | |
| HEADER = "x-fastframes-key" | |
| COOKIE = "__Host-ffv-media" | |
| SECRET = secrets.token_bytes(32) | |
| KEY = re.compile(r"[0-9a-f]{64}") | |
| PRIVATE = {"Cache-Control": "private, no-store", "Vary": "Cookie, X-FastFrames-Key", | |
| "Cross-Origin-Resource-Policy": "same-origin", "X-Content-Type-Options": "nosniff"} | |
| with takes.connection() as db: | |
| db.execute("""CREATE TABLE media ( | |
| id TEXT PRIMARY KEY, owner TEXT NOT NULL, session TEXT NOT NULL, path TEXT NOT NULL, | |
| strips INTEGER NOT NULL, touched INTEGER NOT NULL DEFAULT (unixepoch()), | |
| UNIQUE (owner, session, path))""") | |
| def digest(key): | |
| return hashlib.sha256(key.encode()).hexdigest() | |
| def credential(payload, request): | |
| value = payload.get("media_key") or (getattr(request,"headers",None) or {}).get(HEADER) | |
| if value is None: | |
| return hmac.digest(SECRET, request.session_hash.encode(), "sha256").hex() | |
| if not isinstance(value, str) or not KEY.fullmatch(value): | |
| raise ValueError("Invalid media credential") | |
| return value | |
| def register(path, key, session, strips=False): | |
| path = Path(path).resolve().relative_to(takes.ROOT.resolve()).as_posix() | |
| with takes.connection() as db: | |
| row = db.execute("""INSERT INTO media(id,owner,session,path,strips) VALUES (?,?,?,?,?) | |
| ON CONFLICT(owner,session,path) DO UPDATE SET touched=unixepoch() RETURNING id""", | |
| (secrets.token_hex(18),digest(key),session,path,int(strips))).fetchone() | |
| return PREFIX + row[0] + ("" if strips else "/clip.mp4") | |
| def file_info(url): | |
| return {"video":{"path":url,"url":url,"orig_name":"FastFrames-Voice.mp4","mime_type":"video/mp4"},"subtitles":None} | |
| class PrivateMedia: | |
| def __init__(self, app): | |
| self.app = app | |
| async def __call__(self, scope, receive, send): | |
| if scope["type"] != "http" or not scope["path"].startswith(PREFIX): | |
| return await self.app(scope,receive,send) | |
| request = Request(scope) | |
| key = request.headers.get(HEADER) or request.cookies.get(COOKIE,"") | |
| response = Response(status_code=404, headers=PRIVATE) | |
| path = scope["path"][len(PREFIX):] | |
| if KEY.fullmatch(key): | |
| if path == "bind" and request.method == "POST" and request.headers.get(HEADER): | |
| headers = {**PRIVATE, "Set-Cookie": f"{COOKIE}={key}; Path=/; Secure; HttpOnly; SameSite=None; Partitioned"} | |
| response = Response(status_code=204, headers=headers) | |
| elif path == "check" and request.method == "HEAD": | |
| response = Response(status_code=204,headers={**PRIVATE,"X-Media-Owner":digest(key)}) | |
| elif request.method in ("GET","HEAD"): | |
| match = re.fullmatch(r"([0-9a-f]{36})/(clip\.mp4|[0-9]{1,3}\.jpg)", path) | |
| if match: | |
| with takes.connection() as db: | |
| row = db.execute("SELECT path,strips FROM media WHERE id=? AND owner=?", | |
| (match[1],digest(key))).fetchone() | |
| if row and bool(row["strips"]) == match[2].endswith(".jpg"): | |
| file = takes.ROOT / row["path"] | |
| if row["strips"]: | |
| file = file / match[2] | |
| if file.is_file(): | |
| response = FileResponse(file, media_type="image/jpeg" if row["strips"] else "video/mp4", | |
| headers=PRIVATE) | |
| await response(scope,receive,send) | |