mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba24b32cd4 |
No files matched your search
@@ -99,3 +99,27 @@ Feature: raea cloud: a synced folder is pictured, understood, embedded and organ
|
||||
When StreetTalk's four Drive syncs run from empty
|
||||
Then every file has a picture, a description and tags; the three client folders are related to their client
|
||||
libraries; a search for a shot finds it by what's in it; and the run says its time and what it cost
|
||||
|
||||
Rule: every video has a light copy to watch and cut from
|
||||
Scenario: IG14. A video's proxy is made once, from the download its index already makes
|
||||
(built 12-02: raea-platform index-run.ts submitProxy/proxyDue, sdk/cloud/deploy/modal/proxy.py)
|
||||
Given a video in a library, uploaded or synced from Drive
|
||||
Then raea makes a 540p proxy of it on Modal (540 lines on the short side and never more than the original,
|
||||
H.264 CRF 28 with a keyframe every second, AAC 96 kbps, faststart) from the same address its index job
|
||||
fetches, so a synced file is downloaded through its tool once for both
|
||||
And the proxy is kept in R2 by the original's SHA-256, written through a ticket for the workspace's proxies
|
||||
alone (the job holds no raea credential), so footage kept twice is made once
|
||||
And an original already that light (H.264 in MP4, 540 lines or fewer, under 2.5 Mbps) is its own proxy
|
||||
And a library indexed before proxies gets them a few at a time, 8 running a workspace
|
||||
|
||||
Scenario: IG15. People watch the proxy
|
||||
When a person opens a video in the library
|
||||
Then it plays from its proxy: no copy of a Drive original through its tool, and no 4K HEVC in the browser
|
||||
And its original stays one click away (Open)
|
||||
|
||||
Scenario: IG16. Agents look and cut from proxies, and finish from originals
|
||||
When an agent searches its libraries for footage
|
||||
Then it finds videos by what's in them (what's seen, heard and said, with the seconds where) and by name
|
||||
And each video comes with its proxy, whose times are the original's, to fetch, watch, transcribe and rough-cut
|
||||
And the original (an upload's link, or a synced file through library_original) is fetched only for the master
|
||||
And drafts on the farm read clip copies at the size they're drawn (CR36); masters read the originals
|
||||
@@ -76,9 +76,6 @@ BLENDER = os.environ.get("RAEA_FARM_BLENDER", "5.3.0")
|
||||
RAEA_GPUS = os.environ.get("RAEA_FARM_RAEA_GPUS", "T4,A10,L4").split(",")
|
||||
BLENDER_GPUS = os.environ.get("RAEA_FARM_BLENDER_GPUS", "L40S,RTX-PRO-6000,L4").split(",")
|
||||
GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit; Team's is 50
|
||||
# one job's GPUs unless it asks for more: a 1,150-frame cut took all 10 (each drawing 10-20 s), so every other render in
|
||||
# the workspace queued behind it with nothing said (11-30, StreetTalk's three agents); 4 lets two or three render at once
|
||||
JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4"))
|
||||
ROOT = "/farm"
|
||||
JOBS = f"{ROOT}/jobs"
|
||||
|
||||
@@ -128,11 +125,7 @@ image = (
|
||||
# the job at once instead of installing it on a GPU's clock
|
||||
"RAEA_TOKENSYNTH": "/models/tokensynth", "RAEA_TOKENSYNTH_DEVICE": "cuda", "RAEA_AUDIO_AUTOSETUP": "0",
|
||||
# Stable Audio Open small on ONNX Runtime with CUDA, as deploy/modal/sao.py installs it (CR25)
|
||||
"RAEA_SAO": "/models/sao",
|
||||
# a video's runs encoded by the ffmpeg CLI's libx264 at the quality's CRF (master 11), not openh264 at a
|
||||
# bitrate: openh264's near-blacks stepped into blocks even at master's 37.7 Mbps, raea check's blotching
|
||||
# failed every Dutch cut, and its agent re-encoded each one with x264 after the render (11-30)
|
||||
"RAEA_MEDIA": "ffmpeg"})
|
||||
"RAEA_SAO": "/models/sao"})
|
||||
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene")
|
||||
)
|
||||
|
||||
@@ -580,7 +573,7 @@ def api():
|
||||
if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
|
||||
raise HTTPException(400, "args must be a JSON array of strings: raea's own arguments")
|
||||
q = req.query_params
|
||||
opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
|
||||
opts = {"gpus": min(int(q.get("gpus", GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
|
||||
id = str(uuid.uuid4())
|
||||
work = f"{JOBS}/{id}/work"
|
||||
async with gate.use():
|
||||
|
||||
@@ -44,34 +44,6 @@ def splittable(args):
|
||||
return out is not None and (out.endswith(VIDEO) or not os.path.splitext(out)[1]) and any(COMPOSITION.search(a) for a in rest[1:])
|
||||
|
||||
|
||||
# how often a job's log says it's still waiting on a GPU run: from outside, a run queued behind the workspace's GPU
|
||||
# limit and one still drawing look the same, and a silent wait read as a stall (11-30: StreetTalk's agents said "stalled
|
||||
# before frame 0" while another app held all 10 of the workspace's GPUs)
|
||||
WAIT_SAY_S = 30
|
||||
|
||||
|
||||
def waited(fn, log, *a, **kw):
|
||||
"""fn.remote(*a, **kw), saying in the log every WAIT_SAY_S that it has no answer yet."""
|
||||
if not hasattr(fn, "spawn"):
|
||||
return fn.remote(*a, **kw)
|
||||
try:
|
||||
import modal.exception as me
|
||||
timeouts = (TimeoutError, me.TimeoutError)
|
||||
except Exception:
|
||||
timeouts = (TimeoutError,)
|
||||
call = fn.spawn(*a, **kw)
|
||||
t = time.time()
|
||||
while True:
|
||||
try:
|
||||
return call.get(timeout=WAIT_SAY_S)
|
||||
except timeouts as e:
|
||||
# Modal's FunctionTimeoutError is a TimeoutError too: the run itself ran out of time, so it goes up as
|
||||
# .remote() raised it, not waited on again (it would answer the same at once, forever)
|
||||
if type(e).__name__ == "FunctionTimeoutError":
|
||||
raise
|
||||
log(f"raea farm: waiting {time.time() - t:.0f} s for a GPU run to answer (queued while the workspace's GPUs are busy, or still drawing)")
|
||||
|
||||
|
||||
def gpus_for(frames, frame_s, start_s, most):
|
||||
"""The GPUs worth starting for `frames` frames of `frame_s` each, when each one first spends `start_s`: the most that
|
||||
keep each one's start at most SHARE of its time, never more than `most`."""
|
||||
@@ -218,7 +190,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
if out.endswith(VIDEO):
|
||||
t = threading.Thread(target=lambda: run(["raea", *rest, "-o", sound], cwd=work, env=cpu_env))
|
||||
t.start()
|
||||
p = bill.add(waited(render, log, id, rest, probe=True))
|
||||
p = bill.add(render.remote(id, rest, probe=True))
|
||||
if p["code"] or not p["length"]:
|
||||
log(p["out"], err=True)
|
||||
if not p["code"]:
|
||||
@@ -228,7 +200,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
log(f"raea farm: {length} frames at {p['w']}x{p['h']}, {fps} fps; frame 0 on a {kind} in {p['s']:.1f} s")
|
||||
video = out.endswith(VIDEO)
|
||||
n0 = min(length, FIRST)
|
||||
r0 = bill.add(waited(render, log, id, rest, list(range(n0)), 0, video=video))
|
||||
r0 = bill.add(render.remote(id, rest, list(range(n0)), 0, video=video))
|
||||
if r0["code"]:
|
||||
log(r0["out"], err=True)
|
||||
return r0["code"]
|
||||
@@ -349,7 +321,7 @@ def blender(args, opts, work, log, render, run, reload=lambda: None, bill=None):
|
||||
if video:
|
||||
o |= {"video": True, "fps": info["fps"]}
|
||||
log(f"raea farm: {blend}, frames {first}-{last} ({info['engine']}), at {info['fps']:g} fps")
|
||||
r0 = bill.add(waited(render, log, id, blend, first, first, o))
|
||||
r0 = bill.add(render.remote(id, blend, first, first, o))
|
||||
if r0["code"]:
|
||||
log(r0["out"], err=True)
|
||||
return r0["code"]
|
||||
@@ -394,7 +366,7 @@ def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload
|
||||
if splittable(args):
|
||||
code = raea_render(args, opts, work, log, render, cpu_env, run, reload, bill)
|
||||
else:
|
||||
r = bill.add(waited(render, log, opts["id"], args))
|
||||
r = bill.add(render.remote(opts["id"], args))
|
||||
log(r["out"], err=bool(r["code"]))
|
||||
code = r["code"]
|
||||
log(bill.line())
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
# raea cloud's library proxies on Modal (index-run.ts, 12-02): a video's 540p copy, made once per version of the file and
|
||||
# kept in R2 by its source's SHA-256. Its own app, beside raea-ingest's indexer, so it deploys without the indexer's
|
||||
# bundle. From sdk/cloud:
|
||||
#
|
||||
# MODAL_PROFILE=raea modal deploy deploy/modal/proxy.py
|
||||
#
|
||||
# POST /v1/proxy-jobs {url, put, ticket} a job: the file fetched from url, its proxy written through the Worker's
|
||||
# put (/u/<prefix>/) with ticket (exp=&sig=) -> {id}
|
||||
# GET /v1/proxy-jobs/ID {state: running} | {state: done, sha256, proxy, bytes...} | {state: failed, error}
|
||||
# GET /healthz
|
||||
#
|
||||
# Every call but /healthz carries Authorization: Bearer RAEA_INGEST_TOKEN (Modal secret raea-ingest, as raea-ingest's).
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import modal
|
||||
|
||||
app = modal.App("raea-proxy", image=modal.Image.debian_slim(python_version="3.12").apt_install("ffmpeg").pip_install("fastapi[standard]"))
|
||||
secret = modal.Secret.from_name("raea-ingest")
|
||||
|
||||
|
||||
@app.function(cpu=1, memory=1024, secrets=[secret], timeout=300, scaledown_window=120)
|
||||
@modal.concurrent(max_inputs=16)
|
||||
@modal.asgi_app()
|
||||
def api():
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import PlainTextResponse
|
||||
|
||||
web = FastAPI()
|
||||
token = os.environ["RAEA_INGEST_TOKEN"]
|
||||
|
||||
def check(req: Request):
|
||||
if req.headers.get("authorization", "").removeprefix("Bearer ") != token:
|
||||
raise HTTPException(401, "a raea ingest token is needed (Authorization: Bearer)")
|
||||
|
||||
@web.post("/v1/proxy-jobs")
|
||||
async def submit(req: Request):
|
||||
check(req)
|
||||
b = await req.json()
|
||||
if not isinstance(b.get("url"), str) or not b["url"].startswith("https://"):
|
||||
raise HTTPException(400, "url is the file's https address")
|
||||
if not isinstance(b.get("put"), str) or not b["put"].startswith("https://") or not b["put"].endswith("/") or not isinstance(b.get("ticket"), str):
|
||||
raise HTTPException(400, "put is the Worker's /u/<prefix>/ and ticket its exp=&sig=")
|
||||
call = await proxy_job.spawn.aio(b["url"], b["put"], b["ticket"])
|
||||
return {"id": call.object_id}
|
||||
|
||||
@web.get("/v1/proxy-jobs/{job}")
|
||||
async def collect(job: str, req: Request):
|
||||
check(req)
|
||||
try:
|
||||
out = await modal.FunctionCall.from_id(job).get.aio(timeout=0)
|
||||
except modal.exception.FunctionTimeoutError:
|
||||
return {"state": "failed", "error": "the file took over an hour"}
|
||||
except (TimeoutError, modal.exception.TimeoutError):
|
||||
return {"state": "running"}
|
||||
except Exception as e:
|
||||
return {"state": "failed", "error": str(e)[:300]}
|
||||
return {"state": "failed", **out} if out.get("error") else {"state": "done", **out}
|
||||
|
||||
@web.get("/healthz")
|
||||
def healthz():
|
||||
return PlainTextResponse("ok")
|
||||
|
||||
return web
|
||||
|
||||
|
||||
# ---- the proxy ----
|
||||
# What people watch and agents look, search and rough-cut from: 540 lines on the short side (never larger than the
|
||||
# original), H.264 CRF 28 veryfast, a keyframe every second so a seek lands anywhere, AAC 96 kbps stereo, faststart. On
|
||||
# one StreetTalk take (4K HEVC, 254 s, 726 MB) it was 45 MB. Written into R2 by its source's SHA-256 through the
|
||||
# Worker's /u/<prefix>/<file id> with a ticket (files.ts putTicket): the job holds no raea credential, and footage kept
|
||||
# twice is made once. A video already that light (H.264 in MP4, 540 lines or fewer, under 2.5 Mbps) is its own proxy.
|
||||
PROXY_SHORT = 540
|
||||
PROXY_LIGHT_BPS = 2_500_000
|
||||
PART = 64 << 20
|
||||
AGENT = {"user-agent": "raea-ingest/1"}
|
||||
|
||||
|
||||
def _probe(path: str) -> dict:
|
||||
import json
|
||||
|
||||
r = subprocess.run(["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", path], capture_output=True, text=True, timeout=120)
|
||||
try:
|
||||
return json.loads(r.stdout or "{}")
|
||||
except ValueError:
|
||||
return {}
|
||||
|
||||
|
||||
def _picture(info: dict):
|
||||
"""(width, height as shown, codec) of its first video stream, or None"""
|
||||
v = next((s for s in info.get("streams", []) if s.get("codec_type") == "video" and s.get("disposition", {}).get("attached_pic") != 1), None)
|
||||
if not v:
|
||||
return None
|
||||
w, h = int(v.get("width") or 0), int(v.get("height") or 0)
|
||||
rot = 0
|
||||
for sd in v.get("side_data_list", []) or []:
|
||||
if "rotation" in sd:
|
||||
rot = int(float(sd["rotation"]))
|
||||
rot = rot or int(float((v.get("tags") or {}).get("rotate", 0) or 0))
|
||||
if abs(rot) % 180 == 90:
|
||||
w, h = h, w
|
||||
return w, h, v.get("codec_name", "")
|
||||
|
||||
|
||||
def _http(method: str, url: str, body=None, json_body=None, timeout=600) -> dict:
|
||||
import json
|
||||
import urllib.request
|
||||
|
||||
headers = dict(AGENT)
|
||||
data = body
|
||||
if json_body is not None:
|
||||
data = json.dumps(json_body).encode()
|
||||
headers["content-type"] = "application/json"
|
||||
if data is not None:
|
||||
headers["content-length"] = str(len(data))
|
||||
with urllib.request.urlopen(urllib.request.Request(url, data=data, method=method, headers=headers), timeout=timeout) as r:
|
||||
return json.loads(r.read() or b"{}")
|
||||
|
||||
|
||||
@app.function(cpu=8, memory=8192, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=60)
|
||||
def proxy_job(url: str, put: str, ticket: str) -> dict:
|
||||
import hashlib
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src, out = os.path.join(d, "in.media"), os.path.join(d, "proxy.mp4")
|
||||
h, got = hashlib.sha256(), 0
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers=AGENT), timeout=300) as r, open(src, "wb") as f:
|
||||
while chunk := r.read(8 << 20):
|
||||
h.update(chunk)
|
||||
got += len(chunk)
|
||||
f.write(chunk)
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"error": f"couldn't fetch the file: {e.code}", "fetched": e.code}
|
||||
except Exception as e:
|
||||
return {"error": f"couldn't fetch the file: {e}"[:300]}
|
||||
sha = h.hexdigest()
|
||||
info = _probe(src)
|
||||
pic = _picture(info)
|
||||
fmt = info.get("format", {})
|
||||
bps = int(float(fmt.get("bit_rate") or 0)) or (int(got * 8 / float(fmt["duration"])) if float(fmt.get("duration") or 0) > 0 else 0)
|
||||
base = {"sha256": sha, "source_bytes": got, "seconds": round(float(fmt.get("duration") or 0), 2)}
|
||||
if not pic:
|
||||
return {**base, "proxy": None, "why": "no picture in it"}
|
||||
w, hgt, codec = pic
|
||||
if min(w, hgt) <= PROXY_SHORT and codec == "h264" and "mp4" in fmt.get("format_name", "") and 0 < bps <= PROXY_LIGHT_BPS:
|
||||
return {**base, "proxy": None, "why": "light enough to be its own", "width": w, "height": hgt}
|
||||
fid = f"file-{sha[:24]}"
|
||||
at = f"{put}{fid}?{ticket}"
|
||||
try:
|
||||
began = _http("POST", f"{at}&step=begin", json_body={})
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"error": f"the Worker refused the proxy's upload: {e.code}"}
|
||||
if began.get("have"):
|
||||
return {**base, "proxy": fid, "kept": True}
|
||||
scale = f"scale='if(gt(iw,ih),-2,trunc(min({PROXY_SHORT},iw)/2)*2)':'if(gt(iw,ih),trunc(min({PROXY_SHORT},ih)/2)*2,-2)',format=yuv420p"
|
||||
r = subprocess.run(
|
||||
["ffmpeg", "-v", "error", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a:0?", "-vf", scale, "-c:v", "libx264", "-preset", "veryfast", "-crf", "28",
|
||||
"-force_key_frames", "expr:gte(t,n_forced*1)", "-c:a", "aac", "-b:a", "96k", "-ac", "2", "-movflags", "+faststart", out],
|
||||
capture_output=True, text=True, timeout=3300,
|
||||
)
|
||||
if r.returncode != 0 or not os.path.exists(out):
|
||||
return {"error": f"ffmpeg stopped ({r.returncode}): {(r.stderr or '')[-300:]}"}
|
||||
size, parts = os.path.getsize(out), []
|
||||
with open(out, "rb") as f:
|
||||
n = 1
|
||||
while chunk := f.read(PART):
|
||||
parts.append(_http("PUT", f"{at}&upload={began['upload']}&part={n}", body=chunk))
|
||||
n += 1
|
||||
done = _http("POST", f"{at}&step=complete&upload={began['upload']}", json_body={"parts": parts})
|
||||
pw = _picture(_probe(out))
|
||||
return {**base, "proxy": done.get("id", fid), "bytes": size, "width": pw[0] if pw else None, "height": pw[1] if pw else None}
|
||||
|
||||
|
||||
@@ -158,35 +158,4 @@ b.add({"code": 1, "out": "no task id"})
|
||||
assert "2 GPU containers up 35 s" in b.line(), b.line()
|
||||
ok("the bill: each container from its boot or the job's start to its last run, plus its boot and idle seconds")
|
||||
|
||||
# a GPU run with no answer yet is said in the log, not waited on in silence; its answer still comes back
|
||||
class SlowCall:
|
||||
def __init__(self, waits): self.waits = waits
|
||||
def get(self, timeout=None):
|
||||
if self.waits:
|
||||
self.waits -= 1
|
||||
raise TimeoutError
|
||||
return {"code": 0, "out": "drawn"}
|
||||
class SlowGpu:
|
||||
def spawn(self, *a, **kw): return SlowCall(2)
|
||||
lines.clear()
|
||||
fp.WAIT_SAY_S = 0.01
|
||||
assert fp.waited(SlowGpu(), log, "j4", ["render"]) == {"code": 0, "out": "drawn"}
|
||||
assert sum("waiting" in l and "GPU run" in l for l in lines) == 2, lines
|
||||
ok("a GPU run that hasn't answered is said in the log every WAIT_SAY_S until it does")
|
||||
|
||||
# a GPU run that ran out of its own time fails the job, as .remote() did, instead of being waited on forever
|
||||
class FunctionTimeoutError(TimeoutError): pass
|
||||
class TimedOutCall:
|
||||
def get(self, timeout=None): raise FunctionTimeoutError("Function timeout")
|
||||
class TimedOutGpu:
|
||||
def spawn(self, *a, **kw): return TimedOutCall()
|
||||
lines.clear()
|
||||
try:
|
||||
fp.waited(TimedOutGpu(), log, "j5", ["render"])
|
||||
raise AssertionError("waited() swallowed a function timeout")
|
||||
except FunctionTimeoutError:
|
||||
pass
|
||||
assert not any("waiting" in l for l in lines), lines
|
||||
ok("a GPU run that timed out fails the job instead of being waited on forever")
|
||||
|
||||
shutil.rmtree(root)
|
||||
Reference in new issue
Block a user