videogen/tools/mac-node/ott_worker.py
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

154 lines
6.2 KiB
Python

"""Menivor OTT Mac node (Wave P PM2.4, MV2): pull long-form jobs, encode with VideoToolbox, package, upload.
Runs on the owner's Mac from a checkout of this repo:
OTT_NODE_TOKEN=ottn_... MENIVOR_API_BASE=https://api.menivor.com \\
SHAKA_PACKAGER_BIN=/usr/local/bin/packager SHAKA_PACKAGER_PLATFORM=osx-arm64 \\
python tools/mac-node/ott_worker.py
Every cycle it sends a heartbeat with the free space of its work folder. It
claims a job only when more than 10 GB is free (the server refuses otherwise
too) and keeps a progress ping going while it works, so a job whose Mac goes
to sleep returns to the queue after 3 minutes. Output files go straight to R2
through presigned PUT URLs; the node never holds an R2 key. The packager's
SHA-256 must match the pinned build before any job starts.
"""
from __future__ import annotations
import argparse
import os
import shutil
import sys
import tempfile
import threading
import time
from pathlib import Path
from typing import Any, Callable
REPO = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO / "apps" / "api"))
MIN_FREE_GB = 10.0
POLL_S = 30.0
PROGRESS_S = 30.0
URL_BATCH = 500
class Api:
def __init__(self, base: str, token: str, session: Any = None) -> None:
import requests
self.base = base.rstrip("/") + "/api/v1/ott/nodes"
self.http = session or requests.Session()
self.headers = {"Authorization": f"Bearer {token}"}
def post(self, path: str, body: dict | None = None) -> dict:
response = self.http.post(f"{self.base}{path}", json=body or {}, headers=self.headers, timeout=60)
response.raise_for_status()
return (response.json() or {}).get("data") or {}
def free_gb(path: str) -> float:
return shutil.disk_usage(path).free / 1e9
def _download(url: str, dest: str) -> None:
import requests
with requests.get(url, stream=True, timeout=600) as response:
response.raise_for_status()
with open(dest, "wb") as fh:
for chunk in response.iter_content(1 << 20):
fh.write(chunk)
def _put(url: str, path: str, content_type: str) -> None:
import requests
with open(path, "rb") as fh:
response = requests.put(url, data=fh, headers={"Content-Type": content_type}, timeout=600)
response.raise_for_status()
def process(api: Api, job: dict, work_root: str, *, ffmpeg: str, packager_bin: str, digest: str,
download: Callable[[str, str], None] = _download, put: Callable[[str, str, str], None] = _put,
progress_s: float = PROGRESS_S) -> dict:
from app.services.ott_package.packager import Protection
from app.services.ott_transcode import pipeline
stop = threading.Event()
def ping() -> None:
while not stop.wait(progress_s):
try:
api.post(f"/jobs/{job['job_id']}/progress")
except Exception: # noqa: BLE001 - the next ping or the requeue handles it
pass
thread = threading.Thread(target=ping, daemon=True)
thread.start()
try:
with tempfile.TemporaryDirectory(prefix="ott-", dir=work_root) as work:
src = os.path.join(work, "source")
download(job["source_url"], src)
protection = Protection(**job["protection"]) if job.get("protection") else None
result = pipeline.run(src, work, ffmpeg=ffmpeg, packager_bin=packager_bin,
encoder=job.get("encoder") or "h264_videotoolbox", protection=protection)
for start in range(0, len(result.files), URL_BATCH):
batch = result.files[start:start + URL_BATCH]
urls = api.post(f"/jobs/{job['job_id']}/upload-urls", {"files": batch})["urls"]
for rel in batch:
put(urls[rel], os.path.join(result.out_dir, rel), pipeline.content_type(rel))
body = {"files": result.files, "cpu_seconds": result.cpu_seconds, "packager_sha256": digest}
seconds = float(result.source.seconds) if result.source is not None else 0.0
if seconds > 0:
body["measured_seconds"] = seconds # the server bills the probed length, not the declared one
return api.post(f"/jobs/{job['job_id']}/complete", body)
except Exception as exc: # noqa: BLE001 - report and let the server requeue or fail it
api.post(f"/jobs/{job['job_id']}/fail", {"error": (str(exc) or type(exc).__name__)[:480]})
return {"status": "failed", "error": str(exc)}
finally:
stop.set()
def cycle(api: Api, work_root: str, *, ffmpeg: str, packager_bin: str, digest: str, **kwargs: Any) -> dict | None:
space = free_gb(work_root)
api.post("/heartbeat", {"free_gb": round(space, 1), "cores": os.cpu_count() or 0})
if space <= MIN_FREE_GB:
return None
job = api.post("/claim").get("job")
if not job:
return None
return process(api, job, work_root, ffmpeg=ffmpeg, packager_bin=packager_bin, digest=digest, **kwargs)
def main(argv: list[str] | None = None) -> int:
from app.services.ott_package.packager import verify_binary
parser = argparse.ArgumentParser(description="Menivor OTT Mac node")
parser.add_argument("--once", action="store_true", help="run one heartbeat/claim cycle and exit")
args = parser.parse_args(argv)
token = os.environ["OTT_NODE_TOKEN"]
base = os.environ.get("MENIVOR_API_BASE", "https://api.menivor.com")
work_root = os.path.expanduser(os.environ.get("OTT_WORK_DIR", "~/menivor-ott-work"))
os.makedirs(work_root, exist_ok=True)
packager_bin = os.environ.get("SHAKA_PACKAGER_BIN", "/usr/local/bin/packager")
digest = verify_binary(packager_bin, os.environ.get("SHAKA_PACKAGER_PLATFORM", "osx-arm64"))
ffmpeg = shutil.which("ffmpeg") or "ffmpeg"
api = Api(base, token)
while True:
try:
done = cycle(api, work_root, ffmpeg=ffmpeg, packager_bin=packager_bin, digest=digest)
if done:
print(f"job {done.get('id', '')}: {done.get('status')}", flush=True)
except Exception as exc: # noqa: BLE001 - keep the node alive across network blips
print(f"cycle failed: {exc}", file=sys.stderr, flush=True)
if args.once:
return 0
time.sleep(POLL_S)
if __name__ == "__main__":
sys.exit(main())