Spaces:
Running on Zero
Running on Zero
Download gallery.py from fffiloni/fastframes-voice: direct link, hf CLI and curl.
- Browser
- Download file 7.22 kB
-
https://huggingface.co/spaces/fffiloni/fastframes-voice/resolve/main/gallery.py
- Command line
-
hf download hf://spaces/fffiloni/fastframes-voice/gallery.py
-
curl -L -o gallery.py https://huggingface.co/spaces/fffiloni/fastframes-voice/resolve/main/gallery.py
7.22 kB
| """Final recordings and their private gallery index.""" | |
| from contextlib import contextmanager | |
| import base64 | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import shutil | |
| import tempfile | |
| import threading | |
| import subprocess | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| import takes | |
| MOUNT = Path(os.environ.get("GALLERY_ROOT","/data/fastframes-sessions")) | |
| LEGACY_FORMAT = "ff-s-aa099ef-16fps-v1" | |
| FORMAT = "final-mp4-v2" | |
| POSTER_BYTES = 256 * 1024 | |
| # Gradio may resume a synchronous generator on another worker thread. | |
| LOCKS = [threading.Lock() for _ in range(64)] | |
| def lock_for(value): | |
| return LOCKS[int(hashlib.sha256(value.encode()).hexdigest()[:8],16) % len(LOCKS)] | |
| def owners(device, profile): | |
| keys = [] | |
| if profile: | |
| subject = profile.get("sub") or profile.get("preferred_username") | |
| if subject: | |
| keys.append("hf:"+str(subject)) | |
| if isinstance(device,str) and re.fullmatch("[0-9a-f]{64}",device): | |
| keys.append("browser:"+device) | |
| if not keys: | |
| raise ValueError("Gallery identity missing") | |
| return [hashlib.sha256(k.encode()).hexdigest() for k in keys] | |
| def root(): | |
| if not MOUNT.is_dir(): | |
| raise OSError("Gallery volume is unavailable") | |
| return MOUNT/"sessions-v1" | |
| def jpeg(path): | |
| return "data:image/jpeg;base64," + base64.b64encode(path.read_bytes()).decode("ascii") | |
| def find(identities, archive): | |
| if not isinstance(archive,str) or not re.fullmatch("[0-9a-f]{32}",archive): | |
| raise ValueError("Invalid session ID") | |
| for owner in identities: | |
| folder = root()/owner/archive | |
| if (folder/"manifest.json").is_file(): | |
| return folder | |
| raise FileNotFoundError("Saved session unavailable") | |
| def first_frame(prefix): | |
| # The exported MP4 has a fast-start header. Only read enough for its first frame. | |
| process = subprocess.run([ | |
| "ffmpeg", "-nostdin", "-loglevel", "error", "-threads", "1", "-f", "mov", "-i", "pipe:0", | |
| "-frames:v", "1", "-vf", "scale=300:-2", "-threads", "1", "-f", "image2pipe", | |
| "-c:v", "mjpeg", "pipe:1", | |
| ], input=prefix, capture_output=True, timeout=8) | |
| if not process.stdout or process.returncode: | |
| return "" | |
| return "data:image/jpeg;base64," + base64.b64encode(process.stdout).decode("ascii") | |
| def entries(identities, offset=0, personal=None): | |
| if type(offset) is not int or offset < 0: | |
| raise ValueError("Invalid gallery page") | |
| records = [] | |
| for owner in identities: | |
| for file in (root()/owner).glob("*/manifest.json"): | |
| try: | |
| data = json.loads(file.read_text()) | |
| if data["format"] in (LEGACY_FORMAT, FORMAT): | |
| records.append((data["saved_at"], file.parent, data, False)) | |
| except (ValueError, KeyError, FileNotFoundError): | |
| continue | |
| if personal is not None: | |
| indexed = {} | |
| for file in (root()/identities[0]).glob("*/receipt.json"): | |
| try: | |
| data = json.loads(file.read_text()) | |
| indexed[file.parent.name] = (data["saved_at"], file.parent, data, True) | |
| except (ValueError, KeyError, FileNotFoundError): | |
| continue | |
| records.extend(indexed[k] for k in personal.existing(indexed)) | |
| records.sort(key=lambda record: record[0], reverse=True) | |
| items = [] | |
| with tempfile.TemporaryDirectory() as tmp: | |
| for date, folder, data, remote in records[offset:offset+12]: | |
| ident = folder.name | |
| if data["format"] == LEGACY_FORMAT: | |
| if remote: | |
| folder = Path(tmp)/ident | |
| personal.download([(ident, n, folder/n, data["files"][n]) for n in ("manifest.json", "thumb.jpg")]) | |
| data = json.loads((folder/"manifest.json").read_text()) | |
| clips = data["clips"] | |
| items.append(dict(id=ident, date=date, title=data["title"], thumb=jpeg(folder/"thumb.jpg"), | |
| count=len(clips), seconds=sum(c["seconds"] for c in clips))) | |
| continue | |
| thumb = "" | |
| try: | |
| if remote: | |
| prefix = personal.prefix(ident, POSTER_BYTES) | |
| if hashlib.sha256(prefix).hexdigest() != data["prefix_sha256"]: | |
| raise ValueError("Recording changed") | |
| else: | |
| with (folder/"session.mp4").open("rb") as movie: | |
| prefix = movie.read(POSTER_BYTES) | |
| thumb = first_frame(prefix) | |
| except (ValueError, OSError, subprocess.SubprocessError): | |
| pass # The recording can still be opened when a poster is unavailable. | |
| items.append(dict(id=ident, date=date, title="", thumb=thumb, count=data["count"], seconds=data["seconds"])) | |
| return items, len(records) | |
| def save(key, identities, movie, personal=None): | |
| ident = key[:32] | |
| folder = root()/identities[0]/ident | |
| marker = folder/("receipt.json" if personal else "manifest.json") | |
| if marker.is_file(): | |
| if json.loads(marker.read_text()).get("format") in (LEGACY_FORMAT, FORMAT): | |
| return ident | |
| if takes.get(key).get("phase") != "stopped": | |
| raise ValueError("Session still active") | |
| clips = takes.clip_list(key) | |
| record = dict(format=FORMAT, saved_at=datetime.now(timezone.utc).isoformat(timespec="seconds"), | |
| count=len(clips), seconds=sum(c["seconds"] for c in clips)) | |
| folder.mkdir(parents=True, exist_ok=True) | |
| if personal: | |
| with movie.open("rb") as source: | |
| record["prefix_sha256"] = hashlib.sha256(source.read(POSTER_BYTES)).hexdigest() | |
| record["files"] = {"session.mp4": personal.publish(ident, movie)} | |
| else: | |
| shutil.copyfile(movie, folder/"session.mp4") | |
| # Publish the listing only after the final video is available. | |
| with tempfile.NamedTemporaryFile(mode="w", dir=folder, delete=False) as tmp: | |
| json.dump(record, tmp) | |
| draft = Path(tmp.name) | |
| try: | |
| draft.replace(marker) | |
| finally: | |
| draft.unlink(missing_ok=True) | |
| return ident | |
| def opened(identities, archive, personal): | |
| if not isinstance(archive,str) or not re.fullmatch("[0-9a-f]{32}",archive): | |
| raise ValueError("Invalid recording ID") | |
| receipt = root()/identities[0]/archive/"receipt.json" | |
| if personal is None or not receipt.is_file(): | |
| yield find(identities, archive) | |
| return | |
| signature = json.loads(receipt.read_text())["files"]["session.mp4"] | |
| with tempfile.TemporaryDirectory(dir=takes.ROOT) as temp: | |
| folder = Path(temp)/archive | |
| personal.download([(archive, "session.mp4", folder/"session.mp4", signature)]) | |
| yield folder | |
| def viewing_copy(folder, session_hash): | |
| cache=takes.ROOT/"viewing"/hashlib.sha256(session_hash.encode()).hexdigest() | |
| cache.mkdir(parents=True,exist_ok=True) | |
| target=cache/(folder.name+".mp4") | |
| if not target.is_file(): | |
| with tempfile.TemporaryDirectory(dir=cache) as tmp: | |
| tmpfile=Path(tmp)/"view.mp4" | |
| shutil.copyfile(folder/"session.mp4",tmpfile) | |
| tmpfile.replace(target) | |
| return str(target) | |