framx 0.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- framx/__init__.py +3 -0
- framx/__main__.py +3 -0
- framx/app.py +845 -0
- framx/capcheck.py +1075 -0
- framx/checks.py +63 -0
- framx/cli.py +323 -0
- framx/cloud.py +66 -0
- framx/doctor.py +213 -0
- framx/edit.py +689 -0
- framx/export.py +489 -0
- framx/feedback.py +1542 -0
- framx/follow.py +214 -0
- framx/generate.py +397 -0
- framx/index.py +1044 -0
- framx/init.py +774 -0
- framx/interact.py +105 -0
- framx/jobs.py +238 -0
- framx/lessons.py +114 -0
- framx/listen.swift +65 -0
- framx/look.swift +36 -0
- framx/mcp_app.py +307 -0
- framx/mcp_skills.py +98 -0
- framx/mcp_tasks.py +185 -0
- framx/media.py +263 -0
- framx/ocr.swift +36 -0
- framx/proposals.py +240 -0
- framx/render.py +1305 -0
- framx/review.py +385 -0
- framx/runs.py +997 -0
- framx/server.py +1020 -0
- framx/skill.py +113 -0
- framx/skills/framx/SKILL.md +19 -0
- framx/skills/framx/references/captions.md +21 -0
- framx/skills/framx/references/material.md +22 -0
- framx/skills/framx/references/review-memory.md +19 -0
- framx/skills/framx/references/timelines.md +26 -0
- framx/sound.py +573 -0
- framx/tags.swift +34 -0
- framx/timeline.py +810 -0
- framx/ui/OFL-Inter.txt +93 -0
- framx/ui/api.js +195 -0
- framx/ui/app.css +452 -0
- framx/ui/app.js +623 -0
- framx/ui/draft-preview.js +106 -0
- framx/ui/draft.js +379 -0
- framx/ui/editor.js +1951 -0
- framx/ui/index.html +18 -0
- framx/ui/inter.woff2 +0 -0
- framx/ui/proposal.js +114 -0
- framx/ui/timeline.js +185 -0
- framx/voice.py +99 -0
- framx/words.swift +21 -0
- framx-0.3.1.dist-info/METADATA +392 -0
- framx-0.3.1.dist-info/RECORD +57 -0
- framx-0.3.1.dist-info/WHEEL +4 -0
- framx-0.3.1.dist-info/entry_points.txt +2 -0
- framx-0.3.1.dist-info/licenses/LICENSE +176 -0
framx/app.py
ADDED
|
@@ -0,0 +1,845 @@
|
|
|
1
|
+
"""The framx app: brief an agent, watch it cut, change the edit on its timeline and see what framx remembers.
|
|
2
|
+
A small web server on 127.0.0.1 that answers only requests carrying its random key: in the first address,
|
|
3
|
+
then in a cookie the first page load sets."""
|
|
4
|
+
import hashlib
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import secrets
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
import tempfile
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
import urllib.parse
|
|
16
|
+
import wave
|
|
17
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from . import __version__, checks, cloud, edit, feedback, lessons, proposals, review, runs
|
|
21
|
+
from .runs import uid
|
|
22
|
+
|
|
23
|
+
UI = Path(__file__).with_name("ui")
|
|
24
|
+
ASSETS = {"/app.css": "text/css; charset=utf-8", "/app.js": "text/javascript; charset=utf-8",
|
|
25
|
+
"/api.js": "text/javascript; charset=utf-8", "/draft.js": "text/javascript; charset=utf-8",
|
|
26
|
+
"/timeline.js": "text/javascript; charset=utf-8", "/editor.js": "text/javascript; charset=utf-8",
|
|
27
|
+
"/draft-preview.js": "text/javascript; charset=utf-8", "/proposal.js": "text/javascript; charset=utf-8",
|
|
28
|
+
"/inter.woff2": "font/woff2"}
|
|
29
|
+
SHAPES = ("source", "1920x1080", "1080x1920", "1080x1350", "1080x1080")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def videos_path() -> Path:
|
|
33
|
+
return feedback.data_dir() / "videos.json"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def settings_path() -> Path:
|
|
37
|
+
return feedback.data_dir() / "app.json"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def settings() -> dict:
|
|
41
|
+
s = {"clips": str(Path.home() / "Movies" / "framx"), "agent": "claude", "access": "full"}
|
|
42
|
+
path = settings_path()
|
|
43
|
+
if path.exists():
|
|
44
|
+
s.update(json.loads(path.read_text()))
|
|
45
|
+
return s
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def update_settings(body: dict) -> dict:
|
|
49
|
+
with feedback.locked():
|
|
50
|
+
s = settings()
|
|
51
|
+
if body.get("agent") in runs.NAMES:
|
|
52
|
+
s["agent"] = body["agent"]
|
|
53
|
+
if body.get("clips"):
|
|
54
|
+
s["clips"] = str(Path(body["clips"]).expanduser())
|
|
55
|
+
if body.get("access") in runs.ACCESS:
|
|
56
|
+
s["access"] = body["access"]
|
|
57
|
+
feedback._write(settings_path(), s)
|
|
58
|
+
return s
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def indexed(path) -> dict | None:
|
|
62
|
+
try:
|
|
63
|
+
m = edit.index_dir(path) / "meta.json"
|
|
64
|
+
meta = json.loads(m.read_text()) if m.exists() else None
|
|
65
|
+
except (OSError, ValueError):
|
|
66
|
+
return None
|
|
67
|
+
return meta if meta and meta.get("version") == edit.VERSION else None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def videos() -> list[dict]:
|
|
71
|
+
path = videos_path()
|
|
72
|
+
rows = json.loads(path.read_text()) if path.exists() else []
|
|
73
|
+
out = []
|
|
74
|
+
for v in rows:
|
|
75
|
+
p = Path(v["path"])
|
|
76
|
+
if p.is_file():
|
|
77
|
+
meta = indexed(p)
|
|
78
|
+
out.append({**v, "id": uid(p), "name": p.name, "indexed": bool(meta),
|
|
79
|
+
"sentences": meta["n_sentences"] if meta else None})
|
|
80
|
+
return sorted(out, key=lambda v: -v["added"])
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def add_video(path: str) -> dict:
|
|
84
|
+
from .media import probe
|
|
85
|
+
p = Path(path).expanduser().resolve()
|
|
86
|
+
if not p.is_file():
|
|
87
|
+
raise FileNotFoundError(f"{path}: no such file")
|
|
88
|
+
info = probe(p)
|
|
89
|
+
if not info["width"] or not info["duration"]:
|
|
90
|
+
raise ValueError(f"{p.name} is not a video")
|
|
91
|
+
with feedback.locked():
|
|
92
|
+
vp = videos_path()
|
|
93
|
+
rows = json.loads(vp.read_text()) if vp.exists() else []
|
|
94
|
+
rows = [r for r in rows if r["path"] != str(p)]
|
|
95
|
+
rows.append({"path": str(p), "added": time.time(), "duration": info["duration"],
|
|
96
|
+
"size": f"{info['width']}x{info['height']}"})
|
|
97
|
+
feedback._write(vp, rows)
|
|
98
|
+
return next(v for v in videos() if v["path"] == str(p))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def clips(*, with_checks=False) -> list[dict]:
|
|
102
|
+
"""Every video framx rendered that still exists, newest first."""
|
|
103
|
+
out = []
|
|
104
|
+
for path in (edit.cache_dir() / "renders").glob("*.json"):
|
|
105
|
+
try:
|
|
106
|
+
rec = json.loads(path.read_text())
|
|
107
|
+
o = Path(rec["output"])
|
|
108
|
+
stat = o.stat()
|
|
109
|
+
except (OSError, ValueError, KeyError):
|
|
110
|
+
continue
|
|
111
|
+
if "timeline" not in rec:
|
|
112
|
+
continue
|
|
113
|
+
st = rec["settings"]
|
|
114
|
+
files = list(dict.fromkeys(c.get("source") or c.get("image") for c in rec["timeline"]["video"] if c.get("source") or c.get("image")))
|
|
115
|
+
row = {"id": uid(o), "output": str(o), "name": o.name, "source": rec.get("source"),
|
|
116
|
+
"source_name": Path(files[0]).name if len(files) == 1 else f"{len(files)} files" if files else "titles",
|
|
117
|
+
"size": st.get("size"), "purpose": st.get("purpose"), "duration": round(rec["timeline"]["duration"], 2),
|
|
118
|
+
"captions": st.get("captions"), "time": stat.st_mtime}
|
|
119
|
+
if with_checks:
|
|
120
|
+
report = checks.latest(path, str(stat.st_mtime_ns)) if stat.st_mtime_ns == rec.get("mtime") else None
|
|
121
|
+
row["issues"] = len(report["findings"]) if report else None
|
|
122
|
+
out.append(row)
|
|
123
|
+
return sorted(out, key=lambda c: -c["time"])
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def clip(cid: str) -> dict:
|
|
127
|
+
found = next((c for c in clips() if c["id"] == cid), None)
|
|
128
|
+
if not found:
|
|
129
|
+
raise LookupError("no such clip: it may have been moved or deleted")
|
|
130
|
+
return found
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def clip_state(cid: str) -> dict:
|
|
134
|
+
c = clip(cid)
|
|
135
|
+
st = review.state(c["output"])
|
|
136
|
+
for x in st["clips"]:
|
|
137
|
+
x["source_id"] = uid(x["source"]) if x["source"] else None
|
|
138
|
+
spoken = next((x for x in st["clips"] if x["words"]), None) # the transcript shown beside the clip
|
|
139
|
+
first = spoken or next((x for x in st["clips"] if x["kind"] == "clip"), None)
|
|
140
|
+
# Nanosecond timestamps exceed the exact integer range in a browser.
|
|
141
|
+
version = str(st["version"])
|
|
142
|
+
check = checks.latest(review.record_path(c["output"]), version) if str(Path(c["output"]).stat().st_mtime_ns) == version else None
|
|
143
|
+
st.update(id=cid, version=version, check=check, source_id=first["source_id"] if first else None, runs=runs.for_output(c["output"]))
|
|
144
|
+
return st
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
NAMING = threading.Lock()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def output_for(video: str, purpose: str | None, count: int = 1) -> list[str]:
|
|
151
|
+
"""Where a run's clips go: one name, or for several candidates the same name with -a, -b and so on."""
|
|
152
|
+
folder = Path(settings()["clips"]).expanduser()
|
|
153
|
+
stem = re.sub(r"[^\w-]+", "-", f"{Path(video).stem} {purpose or 'clip'}".lower()).strip("-")[:80]
|
|
154
|
+
taken = {o for m in runs.recent(200) for o in [m.get("output"), *(m.get("outputs") or [])]} # not written yet
|
|
155
|
+
tags = [""] if count == 1 else [f"-{chr(ord('a') + k)}" for k in range(count)]
|
|
156
|
+
n = 1
|
|
157
|
+
while True:
|
|
158
|
+
paths = [folder / f"{stem}{'' if n == 1 else f'-{n}'}{t}.mp4" for t in tags]
|
|
159
|
+
if not any(p.exists() or str(p) in taken for p in paths):
|
|
160
|
+
return [str(p) for p in paths]
|
|
161
|
+
n += 1
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def find_video(vid: str) -> dict:
|
|
165
|
+
"""A recording in the library, or a source clip of a video framx rendered."""
|
|
166
|
+
v = next((v for v in videos() if v["id"] == vid), None)
|
|
167
|
+
if v:
|
|
168
|
+
return v
|
|
169
|
+
src = None
|
|
170
|
+
for c in clips():
|
|
171
|
+
if c.get("source") and uid(c["source"]) == vid:
|
|
172
|
+
src = c["source"]
|
|
173
|
+
break
|
|
174
|
+
try:
|
|
175
|
+
rec = review.record(c["output"])
|
|
176
|
+
except (OSError, ValueError, LookupError):
|
|
177
|
+
continue
|
|
178
|
+
for item in rec.get("timeline", {}).get("video") or []:
|
|
179
|
+
p = item.get("source")
|
|
180
|
+
if p and uid(p) == vid:
|
|
181
|
+
src = p
|
|
182
|
+
break
|
|
183
|
+
if src:
|
|
184
|
+
break
|
|
185
|
+
if not src or not Path(src).is_file():
|
|
186
|
+
raise LookupError("no such recording")
|
|
187
|
+
return {"id": vid, "path": src, "name": Path(src).name, "indexed": bool(indexed(src))}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def transcript(vid: str, words: bool = False) -> dict:
|
|
191
|
+
v = find_video(vid)
|
|
192
|
+
if not v["indexed"]:
|
|
193
|
+
return {**v, "sentences": None}
|
|
194
|
+
idx = edit.Index(v["path"])
|
|
195
|
+
if words:
|
|
196
|
+
v = {**v, "words": review.word_range(idx.words, 0, len(idx.words)), "context": review.CONTEXT}
|
|
197
|
+
return {**v, "sentences": [{k: s[k] for k in ("i", "s", "e", "w0", "w1", "text")} for s in idx.sentences]}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def sentence_audio(path: str, number: int) -> bytes:
|
|
201
|
+
"""The original sound between the same word boundaries that Add sends to the renderer."""
|
|
202
|
+
from . import sound
|
|
203
|
+
idx = edit.Index(path)
|
|
204
|
+
if not 0 <= number < len(idx.sentences):
|
|
205
|
+
raise LookupError("That sentence is no longer in the transcript.")
|
|
206
|
+
s = idx.sentences[number]
|
|
207
|
+
start, end = edit.span(idx.words, s["w0"], s["w1"])
|
|
208
|
+
samples = sound.decode(path, start, end - start)[:round((end - start) * sound.RATE)]
|
|
209
|
+
buffer = io.BytesIO()
|
|
210
|
+
with wave.open(buffer, "wb") as wav:
|
|
211
|
+
wav.setparams((2, 2, sound.RATE, 0, "NONE", "not compressed"))
|
|
212
|
+
wav.writeframes((samples.clip(-1, 1) * 32767).astype("<i2").tobytes())
|
|
213
|
+
return buffer.getvalue()
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def thumb(path: str, t: float) -> bytes:
|
|
217
|
+
"""A small picture of a video, cached by the file's path, size and time."""
|
|
218
|
+
from .media import frames
|
|
219
|
+
p = Path(path)
|
|
220
|
+
st = p.stat()
|
|
221
|
+
key = hashlib.sha1(f"{p}|{st.st_size}|{st.st_mtime_ns}|{t:.1f}|sdr".encode()).hexdigest()[:16]
|
|
222
|
+
cached = edit.cache_dir() / "thumbs" / f"{key}.jpg"
|
|
223
|
+
if not cached.exists():
|
|
224
|
+
cached.parent.mkdir(parents=True, exist_ok=True)
|
|
225
|
+
cached.write_bytes(frames(p, [t], 480)[0][1])
|
|
226
|
+
return cached.read_bytes()
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def remembers() -> dict:
|
|
230
|
+
"""The profile as the page shows it: typed defaults, rules, grounded examples, suggestions and check lessons."""
|
|
231
|
+
rows = [{"id": e["id"], "time": e["time"], "name": Path(e["output"]).name, "purpose": e.get("purpose"),
|
|
232
|
+
"cost": e["cost"]} for e in feedback.edits()]
|
|
233
|
+
sources = feedback.edit_sources()
|
|
234
|
+
prof = feedback.profile()
|
|
235
|
+
clip_ids = {c["output"]: c["id"] for c in clips()}
|
|
236
|
+
for r in prof["rules"]:
|
|
237
|
+
r.update(active=feedback.active(r, sources), videos=feedback.videos_behind(r, sources))
|
|
238
|
+
for d in prof["defaults"]:
|
|
239
|
+
d["group"] = feedback.where(d.get("purpose"))
|
|
240
|
+
for r in prof["rules"]:
|
|
241
|
+
r["group"] = feedback.where(r.get("purpose"))
|
|
242
|
+
for x in prof["examples"]:
|
|
243
|
+
x["group"] = feedback.where(x.get("purpose"))
|
|
244
|
+
if x.get("output") in clip_ids:
|
|
245
|
+
x["clip_id"] = clip_ids[x["output"]]
|
|
246
|
+
pats = lessons.patterns()
|
|
247
|
+
lesson_rows = [{"kind": k, "label": lessons.READS.get(k, k), "found": r["found"], "fixed": r["fixed"],
|
|
248
|
+
"left": r["left"], "pattern": k in pats, "videos": r["videos"][-4:]}
|
|
249
|
+
for k, r in sorted(lessons.summary().items(), key=lambda kv: (-kv[1]["left"], -kv[1]["found"]))
|
|
250
|
+
if r["left"] > 0]
|
|
251
|
+
purposes = list(dict.fromkeys(p for p in [*(c.get("purpose") for c in clips()),
|
|
252
|
+
*(r.get("purpose") for r in prof["rules"]),
|
|
253
|
+
*(d.get("purpose") for d in prof["defaults"]),
|
|
254
|
+
*(x.get("purpose") for x in prof["examples"])] if p))
|
|
255
|
+
return {"profile": prof, "defaults": feedback.display_defaults(prof), "edits": rows,
|
|
256
|
+
"examples": prof["examples"], "suggestions": feedback.suggestions(),
|
|
257
|
+
"lessons": lesson_rows, "proposals": feedback.proposal_stats(), "purposes": purposes}
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def models(app: "App") -> dict:
|
|
261
|
+
"""The model each agent's runs use, and where that comes from."""
|
|
262
|
+
out = {}
|
|
263
|
+
for agent in runs.NAMES:
|
|
264
|
+
if app.models.get(agent):
|
|
265
|
+
out[agent] = {"model": app.models[agent], "from": "the session that opened framx"}
|
|
266
|
+
else:
|
|
267
|
+
got, where = runs.default_model(agent)
|
|
268
|
+
out[agent] = {"model": got, "from": where}
|
|
269
|
+
return out
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def about() -> dict:
|
|
273
|
+
try:
|
|
274
|
+
cfg = cloud.config()
|
|
275
|
+
listener = {"configured": bool(cfg), "host": cfg and cfg["host"], "model": cfg and cfg["model"]}
|
|
276
|
+
except ValueError as e:
|
|
277
|
+
listener = {"configured": False, "error": str(e)}
|
|
278
|
+
from . import generate
|
|
279
|
+
try:
|
|
280
|
+
cfg = generate.config()
|
|
281
|
+
maker = {"configured": bool(cfg), **(generate.describe(cfg) if cfg else {})}
|
|
282
|
+
except ValueError as e:
|
|
283
|
+
maker = {"configured": False, "error": str(e)}
|
|
284
|
+
return {"version": __version__, "data": str(feedback.data_dir()), "cache": str(edit.cache_dir()), "cloud": listener,
|
|
285
|
+
"generator": maker, "settings": settings(), "agents": runs.statuses()}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
PICK = {"video": ("Choose a video to edit", '{"public.movie"}'),
|
|
289
|
+
"reference": ("Choose a finished video as a reference", '{"public.movie"}'),
|
|
290
|
+
"music": ("Choose music or other sound", '{"public.audio"}'),
|
|
291
|
+
"more": ("Choose more videos and pictures to use", '{"public.movie", "public.image"}'),
|
|
292
|
+
"picture": ("Choose a picture to put over the video", '{"public.image"}')}
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def pick(kind="video") -> list[str]:
|
|
296
|
+
"""The Mac's own file picker; empty when the user cancels. "more" takes several files."""
|
|
297
|
+
prompt, types = PICK[kind]
|
|
298
|
+
many = " with multiple selections allowed" if kind == "more" else ""
|
|
299
|
+
script = (f'set chosen to (choose file with prompt "{prompt}" of type {types}{many})\n'
|
|
300
|
+
'if class of chosen is not list then set chosen to {chosen}\nset out to ""\n'
|
|
301
|
+
'repeat with f in chosen\nset out to out & POSIX path of f & linefeed\nend repeat\nout')
|
|
302
|
+
r = subprocess.run(["osascript", "-e", script], capture_output=True, text=True)
|
|
303
|
+
if r.returncode:
|
|
304
|
+
if "-128" in r.stderr:
|
|
305
|
+
return []
|
|
306
|
+
raise RuntimeError(f"the file picker failed: {r.stderr.strip()[:200]}")
|
|
307
|
+
return [line for line in r.stdout.splitlines() if line.strip()]
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def picked(path: str) -> dict:
|
|
311
|
+
"""What a chosen file is, for the page to place it: its length, or that it is a still picture."""
|
|
312
|
+
from .media import probe
|
|
313
|
+
from .timeline import IMAGES
|
|
314
|
+
try:
|
|
315
|
+
info = probe(path)
|
|
316
|
+
except ValueError:
|
|
317
|
+
return {}
|
|
318
|
+
return {"still": path.lower().endswith(IMAGES), "duration": info["duration"], "video": bool(info["width"])}
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def known_path(path: str) -> bool:
|
|
322
|
+
p = Path(path).expanduser().resolve()
|
|
323
|
+
ps = str(p)
|
|
324
|
+
data_root = feedback.data_dir().expanduser().resolve()
|
|
325
|
+
clips_root = Path(settings()["clips"]).expanduser().resolve()
|
|
326
|
+
outputs = [Path(c["output"]).expanduser().resolve() for c in clips()]
|
|
327
|
+
return (any(ps == str(Path(v["path"]).expanduser().resolve()) for v in videos())
|
|
328
|
+
or any(p == o or p.is_relative_to(o.with_name(f"{o.stem} project")) for o in outputs)
|
|
329
|
+
or p.is_relative_to(data_root)
|
|
330
|
+
or p == clips_root)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def app_state_path() -> Path:
|
|
334
|
+
return edit.cache_dir() / "app.json"
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def running_app(route: str = "", eid: str = "") -> str | None:
|
|
338
|
+
"""If a standalone `framx app` process is alive on localhost, return its URL for `route`."""
|
|
339
|
+
path = app_state_path()
|
|
340
|
+
if not path.is_file():
|
|
341
|
+
return None
|
|
342
|
+
try:
|
|
343
|
+
info = json.loads(path.read_text())
|
|
344
|
+
pid, port, key = int(info["pid"]), int(info["port"]), str(info["key"])
|
|
345
|
+
os.kill(pid, 0)
|
|
346
|
+
import socket
|
|
347
|
+
with socket.create_connection(("127.0.0.1", port), timeout=0.5):
|
|
348
|
+
pass
|
|
349
|
+
except (OSError, ValueError, KeyError):
|
|
350
|
+
return None
|
|
351
|
+
q = f"k={key}" + (f"&eid={urllib.parse.quote(eid)}" if eid else "")
|
|
352
|
+
return f"http://127.0.0.1:{port}/?{q}" + (f"#{route}" if route else "")
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
class App:
|
|
356
|
+
"""One server per process; the MCP server starts it on the first review call."""
|
|
357
|
+
|
|
358
|
+
def __init__(self):
|
|
359
|
+
self.server, self.key, self.lock = None, secrets.token_urlsafe(16), threading.Lock()
|
|
360
|
+
self.proposals = {}
|
|
361
|
+
self.models = {} # the model of the harness session that opened the app, per agent
|
|
362
|
+
self._waiter_lock = threading.Lock()
|
|
363
|
+
self._waiters: dict[tuple[str, str], tuple[threading.Event, float]] = {}
|
|
364
|
+
self._published = False
|
|
365
|
+
|
|
366
|
+
def use_model(self, model: str):
|
|
367
|
+
"""Runs this app starts with that agent use the model of the session that opened it: a Claude model for Claude
|
|
368
|
+
Code, an OpenAI one for Codex. Another harness's model (Gemini, DeepSeek) runs on neither, so it is not kept and
|
|
369
|
+
the app's runs keep each agent's own default."""
|
|
370
|
+
m = model.split("/")[-1] # without a provider prefix (anthropic/..., openai/...), which the agents' CLIs refuse
|
|
371
|
+
low = m.lower()
|
|
372
|
+
agent = "claude" if low.startswith(("claude", "sonnet", "opus", "haiku", "fable")) else \
|
|
373
|
+
"codex" if low.startswith(("gpt", "codex", "o1", "o3", "o4", "o5")) else None
|
|
374
|
+
if agent:
|
|
375
|
+
self.models[agent] = m
|
|
376
|
+
|
|
377
|
+
def start(self, port=0) -> int:
|
|
378
|
+
if self.server is not None:
|
|
379
|
+
return self.server.server_address[1]
|
|
380
|
+
with self.lock:
|
|
381
|
+
if not self.server:
|
|
382
|
+
self.server = ThreadingHTTPServer(("127.0.0.1", port), handler(self))
|
|
383
|
+
self.server.daemon_threads = True
|
|
384
|
+
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
|
385
|
+
threading.Thread(target=runs.statuses, daemon=True).start() # so the first page has them ready
|
|
386
|
+
return self.server.server_address[1]
|
|
387
|
+
|
|
388
|
+
def publish(self) -> None:
|
|
389
|
+
"""Record this standalone app's localhost port and key (mode 0600) so MCP sessions can reuse it."""
|
|
390
|
+
port = self.start()
|
|
391
|
+
path = app_state_path()
|
|
392
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
393
|
+
tmp = path.with_suffix(".tmp")
|
|
394
|
+
tmp.write_text(json.dumps({"pid": os.getpid(), "port": port, "key": self.key}))
|
|
395
|
+
tmp.chmod(0o600)
|
|
396
|
+
os.replace(tmp, path)
|
|
397
|
+
self._published = True
|
|
398
|
+
|
|
399
|
+
def unpublish(self) -> None:
|
|
400
|
+
if not self._published:
|
|
401
|
+
return
|
|
402
|
+
path = app_state_path()
|
|
403
|
+
try:
|
|
404
|
+
if path.is_file() and json.loads(path.read_text()).get("pid") == os.getpid():
|
|
405
|
+
path.unlink(missing_ok=True)
|
|
406
|
+
except (OSError, ValueError):
|
|
407
|
+
pass
|
|
408
|
+
self._published = False
|
|
409
|
+
|
|
410
|
+
def register_waiter(self, clip_id: str, eid: str):
|
|
411
|
+
if not eid:
|
|
412
|
+
raise ValueError("a review ID is required")
|
|
413
|
+
now = time.monotonic()
|
|
414
|
+
with self._waiter_lock:
|
|
415
|
+
self._waiters = {k: v for k, v in self._waiters.items() if v[1] > now}
|
|
416
|
+
self._waiters.setdefault((clip_id, eid), (threading.Event(), now + 1800))
|
|
417
|
+
|
|
418
|
+
def has_waiter(self, clip_id: str, eid: str) -> bool:
|
|
419
|
+
with self._waiter_lock:
|
|
420
|
+
return (clip_id, eid) in self._waiters
|
|
421
|
+
|
|
422
|
+
def wait_done(self, clip_id: str, eid: str, timeout: float) -> bool:
|
|
423
|
+
with self._waiter_lock:
|
|
424
|
+
row = self._waiters.get((clip_id, eid))
|
|
425
|
+
if row is None:
|
|
426
|
+
raise LookupError("unknown review")
|
|
427
|
+
return row[0].wait(min(10, max(0, timeout)))
|
|
428
|
+
|
|
429
|
+
def unregister_waiter(self, clip_id: str, eid: str):
|
|
430
|
+
with self._waiter_lock:
|
|
431
|
+
self._waiters.pop((clip_id, eid), None)
|
|
432
|
+
|
|
433
|
+
def notify_done(self, clip_id: str, eid: str | None = None) -> int:
|
|
434
|
+
with self._waiter_lock:
|
|
435
|
+
hits = [event for (cid, key), (event, expires) in self._waiters.items()
|
|
436
|
+
if cid == clip_id and (not eid or key == eid) and expires > time.monotonic()]
|
|
437
|
+
if len(hits) != 1 or hits[0].is_set():
|
|
438
|
+
return 0
|
|
439
|
+
hits[0].set()
|
|
440
|
+
return 1
|
|
441
|
+
|
|
442
|
+
def url(self, route="", port=0, eid: str = "") -> str:
|
|
443
|
+
q = f"k={self.key}" + (f"&eid={urllib.parse.quote(eid)}" if eid else "")
|
|
444
|
+
return f"http://127.0.0.1:{self.start(port)}/?{q}" + (f"#{route}" if route else "")
|
|
445
|
+
|
|
446
|
+
def clip_url(self, output, port=0, eid: str = "") -> str:
|
|
447
|
+
out = str(Path(output).expanduser().resolve())
|
|
448
|
+
review.record(out)
|
|
449
|
+
return self.url(f"/clip/{uid(out)}", port, eid=eid)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def open_page(url: str) -> bool:
|
|
453
|
+
"""Open the page in the default browser, unless FRAMX_NO_BROWSER is set."""
|
|
454
|
+
if os.environ.get("FRAMX_NO_BROWSER"):
|
|
455
|
+
return False
|
|
456
|
+
subprocess.Popen(["open", url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
457
|
+
return True
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def handler(app: App):
|
|
461
|
+
class Handler(BaseHTTPRequestHandler):
|
|
462
|
+
def log_message(self, *args): # stdout belongs to the MCP connection
|
|
463
|
+
pass
|
|
464
|
+
|
|
465
|
+
@property
|
|
466
|
+
def port(self) -> int:
|
|
467
|
+
return app.server.server_address[1]
|
|
468
|
+
|
|
469
|
+
def host_ok(self) -> bool:
|
|
470
|
+
return self.headers.get("Host") in (f"127.0.0.1:{self.port}", f"localhost:{self.port}")
|
|
471
|
+
|
|
472
|
+
def key_ok(self, query: dict) -> bool:
|
|
473
|
+
jar = dict(c.strip().split("=", 1) for c in (self.headers.get("Cookie") or "").split(";") if "=" in c)
|
|
474
|
+
key = query.get("k", [""])[0] or self.headers.get("X-Framx-Key") or jar.get(f"framx{self.port}", "")
|
|
475
|
+
return secrets.compare_digest(key, app.key)
|
|
476
|
+
|
|
477
|
+
def reply(self, code: int, body: bytes, ctype="application/json", headers=()):
|
|
478
|
+
self.send_response(code)
|
|
479
|
+
self.send_header("Content-Type", ctype)
|
|
480
|
+
self.send_header("Content-Length", str(len(body)))
|
|
481
|
+
self.send_header("Cache-Control", "no-store")
|
|
482
|
+
for k, v in headers:
|
|
483
|
+
self.send_header(k, v)
|
|
484
|
+
self.end_headers()
|
|
485
|
+
self.wfile.write(body)
|
|
486
|
+
|
|
487
|
+
def send_json(self, obj, code=200):
|
|
488
|
+
self.reply(code, json.dumps(obj).encode())
|
|
489
|
+
|
|
490
|
+
def body(self) -> dict:
|
|
491
|
+
return json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
|
|
492
|
+
|
|
493
|
+
def route(self):
|
|
494
|
+
url = urllib.parse.urlparse(self.path)
|
|
495
|
+
query, path = urllib.parse.parse_qs(url.query), url.path
|
|
496
|
+
if not self.host_ok():
|
|
497
|
+
return self.reply(403, b"forbidden", "text/plain")
|
|
498
|
+
if path in ASSETS:
|
|
499
|
+
return self.reply(200, (UI / path[1:]).read_bytes(), ASSETS[path])
|
|
500
|
+
if not self.key_ok(query):
|
|
501
|
+
return self.reply(403, b"Open framx with the address `framx app` printed.", "text/plain; charset=utf-8")
|
|
502
|
+
if path == "/":
|
|
503
|
+
cookie = f"framx{self.port}={app.key}; Path=/; HttpOnly; SameSite=Strict"
|
|
504
|
+
return self.reply(200, (UI / "index.html").read_bytes(), "text/html; charset=utf-8",
|
|
505
|
+
[("Set-Cookie", cookie)])
|
|
506
|
+
parts = path.strip("/").split("/")
|
|
507
|
+
if parts[0] != "api" or len(parts) < 2:
|
|
508
|
+
return self.reply(404, b"not found", "text/plain")
|
|
509
|
+
post = self.command == "POST"
|
|
510
|
+
what, rid, sub = parts[1], parts[2] if len(parts) > 2 else None, parts[3] if len(parts) > 3 else None
|
|
511
|
+
if what == "home":
|
|
512
|
+
return self.send_json({"videos": videos(), "clips": clips(with_checks=True), "runs": runs.recent(12),
|
|
513
|
+
"agents": runs.statuses(), "settings": settings()})
|
|
514
|
+
if what == "about":
|
|
515
|
+
if query.get("fresh"):
|
|
516
|
+
runs.statuses(fresh=True)
|
|
517
|
+
return self.send_json({**about(), "models": models(app)})
|
|
518
|
+
if what == "settings" and post:
|
|
519
|
+
return self.send_json(update_settings(self.body()))
|
|
520
|
+
if what == "pick" and post:
|
|
521
|
+
kind = self.body().get("kind", "video")
|
|
522
|
+
chosen = pick(kind if kind in PICK else "video")
|
|
523
|
+
if kind == "video":
|
|
524
|
+
return self.send_json({"video": add_video(chosen[0]) if chosen else None})
|
|
525
|
+
return self.send_json({"files": [{"path": f, "name": Path(f).name, **picked(f)} for f in chosen]})
|
|
526
|
+
if what == "videos" and post and not rid:
|
|
527
|
+
return self.send_json({"video": add_video(self.body()["path"])})
|
|
528
|
+
if what == "videos" and rid:
|
|
529
|
+
v = find_video(rid)
|
|
530
|
+
if sub == "sentence-audio":
|
|
531
|
+
return self.reply(200, sentence_audio(v["path"], int(query["i"][0])), "audio/wav")
|
|
532
|
+
if sub == "file":
|
|
533
|
+
return self.file(v["path"])
|
|
534
|
+
if sub == "thumb":
|
|
535
|
+
return self.reply(200, thumb(v["path"], min(30.0, v.get("duration", 10.0) * 0.1)), "image/jpeg")
|
|
536
|
+
return self.send_json(transcript(rid, words=query.get("words") == ["1"]))
|
|
537
|
+
if what == "runs" and post and not rid:
|
|
538
|
+
return self.send_json(self.new_run(self.body()))
|
|
539
|
+
if what == "proposals" and rid:
|
|
540
|
+
if sub == "discard" and post:
|
|
541
|
+
should_log, row = False, None
|
|
542
|
+
with app.lock:
|
|
543
|
+
closing = app.proposals.pop(rid, None)
|
|
544
|
+
if closing:
|
|
545
|
+
should_log = closing.mark_discard()
|
|
546
|
+
if closing:
|
|
547
|
+
row = closing.finish_discard(should_log)
|
|
548
|
+
return self.send_json({"ok": True, "ask": review.asked(row) if row else None})
|
|
549
|
+
if sub == "accept" and post:
|
|
550
|
+
with app.lock:
|
|
551
|
+
proposal = app.proposals.get(rid)
|
|
552
|
+
if not proposal:
|
|
553
|
+
raise LookupError("This proposal has expired.")
|
|
554
|
+
result = proposal.accept()
|
|
555
|
+
app.proposals.pop(rid, None)
|
|
556
|
+
try:
|
|
557
|
+
state = clip_state(uid(proposal.output))
|
|
558
|
+
finally:
|
|
559
|
+
proposal.close()
|
|
560
|
+
return self.send_json({**result, "state": state})
|
|
561
|
+
with app.lock:
|
|
562
|
+
proposal = app.proposals.get(rid)
|
|
563
|
+
if not proposal:
|
|
564
|
+
raise LookupError("This proposal has expired.")
|
|
565
|
+
if sub == "video" and proposal.run.meta["status"] == "done":
|
|
566
|
+
return self.file(str(proposal.movie))
|
|
567
|
+
raise ValueError("Unknown proposal action.")
|
|
568
|
+
if what == "runs" and rid:
|
|
569
|
+
run = runs.get(rid)
|
|
570
|
+
if sub == "events":
|
|
571
|
+
return self.events(run, int(self.headers.get("Last-Event-ID") or query.get("from", ["-1"])[0]) + 1)
|
|
572
|
+
if sub == "ask" and post:
|
|
573
|
+
runs.ask(run, self.body().get("text", ""))
|
|
574
|
+
return self.send_json({"ok": True})
|
|
575
|
+
if sub == "cancel" and post:
|
|
576
|
+
runs.cancel(run)
|
|
577
|
+
return self.send_json({"ok": True})
|
|
578
|
+
return self.send_json(run.view())
|
|
579
|
+
if what == "clips" and rid:
|
|
580
|
+
if sub == "wait":
|
|
581
|
+
if post:
|
|
582
|
+
body = self.body()
|
|
583
|
+
if body.get("close"):
|
|
584
|
+
app.unregister_waiter(rid, body["eid"])
|
|
585
|
+
else:
|
|
586
|
+
clip(rid)
|
|
587
|
+
app.register_waiter(rid, body["eid"])
|
|
588
|
+
return self.send_json({"ok": True})
|
|
589
|
+
done = app.wait_done(rid, query["eid"][0], float(query.get("timeout", ["5"])[0]))
|
|
590
|
+
return self.send_json({"done": done})
|
|
591
|
+
c = clip(rid)
|
|
592
|
+
if sub is None:
|
|
593
|
+
return self.send_json(clip_state(rid))
|
|
594
|
+
if sub == "video":
|
|
595
|
+
return self.file(c["output"])
|
|
596
|
+
if sub == "thumb": # the rendered video at a time, by default near its start
|
|
597
|
+
t = float(query["t"][0]) if query.get("t") else min(1.5, c["duration"] / 2)
|
|
598
|
+
return self.reply(200, thumb(c["output"], min(t, max(0.0, c["duration"] - 0.05))), "image/jpeg")
|
|
599
|
+
if sub == "frame": # a clip's source at a time, before any crop
|
|
600
|
+
from .media import frames
|
|
601
|
+
video = review.record(c["output"])["timeline"]["video"][int(query.get("i", ["0"])[0])]
|
|
602
|
+
return self.reply(200, frames(video.get("source") or video["image"], [float(query["t"][0])], 640)[0][1], "image/jpeg")
|
|
603
|
+
if sub == "search":
|
|
604
|
+
if not c.get("source"):
|
|
605
|
+
raise LookupError("this clip has no spoken source recording to search")
|
|
606
|
+
idx = edit.Index(c["source"])
|
|
607
|
+
return self.send_json([{k: s[k] for k in ("s", "e", "w0", "w1", "text")}
|
|
608
|
+
for s in edit.rank(idx, query.get("q", [""])[0], 8)])
|
|
609
|
+
if sub == "preview" and post:
|
|
610
|
+
return self.preview(c["output"], self.body())
|
|
611
|
+
if sub == "save" and post:
|
|
612
|
+
body = self.body()
|
|
613
|
+
r = review.save(c["output"], body, app.lock)
|
|
614
|
+
if body.get("check"):
|
|
615
|
+
from .capcheck import check_video
|
|
616
|
+
try:
|
|
617
|
+
check_video(c["output"], expected_version=r["state"]["version"])
|
|
618
|
+
except Exception as err:
|
|
619
|
+
# Rendering and the review log have already succeeded. Retry just the check.
|
|
620
|
+
r["check_error"] = str(err)
|
|
621
|
+
r["state"] = clip_state(rid)
|
|
622
|
+
app.notify_done(rid, body.get("eid"))
|
|
623
|
+
return self.send_json(r)
|
|
624
|
+
if sub == "done" and post:
|
|
625
|
+
body = self.body()
|
|
626
|
+
return self.send_json({"ok": True, "notified": app.notify_done(rid, body.get("eid"))})
|
|
627
|
+
if sub == "export" and post:
|
|
628
|
+
from .export import export
|
|
629
|
+
with app.lock: # not while a save renders this clip again
|
|
630
|
+
return self.send_json(export(c["output"]))
|
|
631
|
+
if sub == "revert" and post:
|
|
632
|
+
r = review.revert(c["output"], str(self.body().get("id") or ""), app.lock)
|
|
633
|
+
r["state"] = clip_state(rid)
|
|
634
|
+
return self.send_json(r)
|
|
635
|
+
if sub == "check":
|
|
636
|
+
output = Path(c["output"])
|
|
637
|
+
if post:
|
|
638
|
+
from .capcheck import check_video
|
|
639
|
+
result = check_video(output, expected_version=self.body().get("version"))
|
|
640
|
+
return self.send_json({"check": result, "report": checks.as_text(result)})
|
|
641
|
+
return self.send_json({"check": checks.latest(review.record_path(output), str(output.stat().st_mtime_ns))})
|
|
642
|
+
if sub == "ask" and post:
|
|
643
|
+
return self.send_json(self.change(c, self.body()))
|
|
644
|
+
if what == "defaults":
|
|
645
|
+
purpose = query.get("purpose", [None])[0]
|
|
646
|
+
return self.send_json({**feedback.defaults(purpose), "group": feedback.where(purpose)})
|
|
647
|
+
if what == "remembers":
|
|
648
|
+
return self.send_json(remembers())
|
|
649
|
+
if what == "keep" and post:
|
|
650
|
+
return self.send_json({"kept": feedback.keep(self.body()["items"]), "profile": feedback.profile()})
|
|
651
|
+
if what == "examples" and post:
|
|
652
|
+
b = self.body()
|
|
653
|
+
if b.get("clip_id"):
|
|
654
|
+
target = clip(b["clip_id"])["output"]
|
|
655
|
+
item = feedback.add_reference(target, purpose=b.get("purpose"), note=b.get("note") or "")
|
|
656
|
+
elif b.get("path"):
|
|
657
|
+
with runs.INDEXING:
|
|
658
|
+
item = feedback.add_reference(b["path"], purpose=b.get("purpose"), note=b.get("note") or "")
|
|
659
|
+
else:
|
|
660
|
+
raise ValueError("give clip_id or path to save a reference cut")
|
|
661
|
+
return self.send_json({"example": item, "profile": feedback.profile()})
|
|
662
|
+
if what == "rules" and post:
|
|
663
|
+
b = self.body()
|
|
664
|
+
item = feedback.remember(b.get("text") or "", purpose=b.get("purpose") or None,
|
|
665
|
+
replaces=b.get("replaces") or (), confirmed=True, origin="note")
|
|
666
|
+
return self.send_json({"rule": item, "profile": feedback.profile()})
|
|
667
|
+
if what == "suggestions" and rid == "dismiss" and post:
|
|
668
|
+
feedback.dismiss(self.body().get("key") or "")
|
|
669
|
+
return self.send_json({"ok": True})
|
|
670
|
+
if what == "confirm" and post:
|
|
671
|
+
return self.send_json({"rule": feedback.confirm(self.body()["id"]), "profile": feedback.profile()})
|
|
672
|
+
if what == "answer" and post: # the user's answer to a review's content question
|
|
673
|
+
b = self.body()
|
|
674
|
+
kept = feedback.answer(b.get("purpose"), b.get("edit"), b.get("text") or "", b.get("replaces") or (), b.get("seconds"))
|
|
675
|
+
return self.send_json({"kept": kept, "profile": feedback.profile()})
|
|
676
|
+
if what == "forget" and post:
|
|
677
|
+
return self.send_json({"said": feedback.forget(self.body()["id"]), "profile": feedback.profile()})
|
|
678
|
+
if what == "reveal" and post:
|
|
679
|
+
target = Path(self.body()["path"]).expanduser().resolve()
|
|
680
|
+
if not known_path(str(target)):
|
|
681
|
+
raise ValueError("framx shows only its own videos and folders in Finder")
|
|
682
|
+
if target == Path(settings()["clips"]).expanduser().resolve():
|
|
683
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
684
|
+
subprocess.run(["open", "-R", str(target)] if target.is_file() else ["open", str(target)], check=False)
|
|
685
|
+
return self.send_json({"ok": True})
|
|
686
|
+
return self.reply(404, b"not found", "text/plain")
|
|
687
|
+
|
|
688
|
+
def new_run(self, b: dict) -> dict:
|
|
689
|
+
v = next((v for v in videos() if v["id"] == b.get("video")), None)
|
|
690
|
+
if not v:
|
|
691
|
+
raise LookupError("choose a video first")
|
|
692
|
+
more = [str(Path(f).expanduser()) for f in b.get("more") or []]
|
|
693
|
+
music = str(Path(b["music"]).expanduser()) if b.get("music") else None
|
|
694
|
+
for f in [*more, *([music] if music else [])]:
|
|
695
|
+
if not Path(f).is_file():
|
|
696
|
+
raise FileNotFoundError(f"{f}: no such file")
|
|
697
|
+
agent = b.get("agent") or settings()["agent"]
|
|
698
|
+
size = b.get("size") or None
|
|
699
|
+
if size not in (None, *SHAPES):
|
|
700
|
+
raise ValueError(f"unknown shape {size}")
|
|
701
|
+
length = float(b["length"]) if b.get("length") not in (None, "") else None
|
|
702
|
+
if length is not None and not 5 <= length <= 600:
|
|
703
|
+
raise ValueError("give a length between 5 and 600 seconds")
|
|
704
|
+
purpose = " ".join(str(b.get("purpose") or "").split()) or None
|
|
705
|
+
want = " ".join(str(b.get("want") or "").split())
|
|
706
|
+
count = int(b.get("count") or 1)
|
|
707
|
+
if not 1 <= count <= 5:
|
|
708
|
+
raise ValueError("ask for 1 to 5 clips")
|
|
709
|
+
with NAMING: # two runs started together get two files
|
|
710
|
+
run = runs.new_run(agent, v["path"], want, purpose, length, size, output_for(v["path"], purpose, count),
|
|
711
|
+
model=app.models.get(agent), more=more, music=music, talk=b.get("talk") is not False)
|
|
712
|
+
runs.start(run)
|
|
713
|
+
return {"id": run.id}
|
|
714
|
+
|
|
715
|
+
def change(self, c: dict, b: dict) -> dict:
|
|
716
|
+
"""Ask for a change to a clip: continue its last run's session, or start a new one from the clip."""
|
|
717
|
+
text = " ".join(str(b.get("text") or "").split())
|
|
718
|
+
if not text:
|
|
719
|
+
raise ValueError("say what to change")
|
|
720
|
+
if "draft" in b:
|
|
721
|
+
body = b["draft"]
|
|
722
|
+
if not isinstance(body, dict) or not body.get("version"):
|
|
723
|
+
raise ValueError("Reopen the clip to send its current draft.")
|
|
724
|
+
agent = b.get("agent") or settings()["agent"]
|
|
725
|
+
with app.lock:
|
|
726
|
+
proposal = proposals.Proposal(c["output"], body, text, agent, app.models.get(agent))
|
|
727
|
+
app.proposals[proposal.run.id] = proposal
|
|
728
|
+
proposal.worker.start()
|
|
729
|
+
return {"id": proposal.run.id}
|
|
730
|
+
last = next((m for m in runs.for_output(c["output"]) if m.get("agent")), None)
|
|
731
|
+
same_agent = not b.get("agent") or b["agent"] == (last or {}).get("agent")
|
|
732
|
+
if last and runs.get(last["id"]).meta.get("session") and same_agent:
|
|
733
|
+
run = runs.get(last["id"])
|
|
734
|
+
runs.ask(run, text, c["output"])
|
|
735
|
+
return {"id": run.id}
|
|
736
|
+
st = review.record(c["output"])["settings"]
|
|
737
|
+
agent = b.get("agent") or settings()["agent"]
|
|
738
|
+
run = runs.new_run(agent, c["source"] or c["output"], text, st.get("purpose"), st.get("length"), st.get("size"),
|
|
739
|
+
c["output"], base={"clip": c["id"]}, model=app.models.get(agent))
|
|
740
|
+
runs.start(run)
|
|
741
|
+
return {"id": run.id}
|
|
742
|
+
|
|
743
|
+
def events(self, run: runs.Run, n: int):
|
|
744
|
+
"""Server-sent events: every event of the run from n on, then new ones until the run finishes."""
|
|
745
|
+
self.send_response(200)
|
|
746
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
747
|
+
self.send_header("Cache-Control", "no-store")
|
|
748
|
+
self.end_headers()
|
|
749
|
+
active = ("starting", "indexing", "working")
|
|
750
|
+
terminal = ("stopped", "cancelled")
|
|
751
|
+
while True:
|
|
752
|
+
with run.cond:
|
|
753
|
+
finished = run.meta["status"] not in active and (
|
|
754
|
+
run.meta["status"] in terminal or (bool(run.events) and run.events[-1].get("kind") == "done"))
|
|
755
|
+
if n >= len(run.events) and not finished:
|
|
756
|
+
run.cond.wait(15)
|
|
757
|
+
batch = run.events[n:]
|
|
758
|
+
finished = run.meta["status"] not in active and (
|
|
759
|
+
run.meta["status"] in terminal or (bool(run.events) and run.events[-1].get("kind") == "done"))
|
|
760
|
+
for ev in batch:
|
|
761
|
+
self.wfile.write(f"id: {ev['n']}\ndata: {json.dumps(ev)}\n\n".encode())
|
|
762
|
+
n += len(batch)
|
|
763
|
+
if finished and n >= len(run.events):
|
|
764
|
+
self.wfile.flush()
|
|
765
|
+
return
|
|
766
|
+
if not batch:
|
|
767
|
+
self.wfile.write(b": still here\n\n")
|
|
768
|
+
self.wfile.flush()
|
|
769
|
+
|
|
770
|
+
def preview(self, output: str, body: dict):
|
|
771
|
+
with tempfile.TemporaryDirectory(prefix="framx-preview-") as tmp:
|
|
772
|
+
movie = Path(tmp) / "preview.mp4"
|
|
773
|
+
timing = review.preview(output, body, movie, app.lock)
|
|
774
|
+
boundary = secrets.token_hex(16)
|
|
775
|
+
fields = "".join(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{json.dumps(value)}\r\n'
|
|
776
|
+
for name, value in timing.items())
|
|
777
|
+
head = (fields + f'--{boundary}\r\nContent-Disposition: form-data; name="video"; filename="preview.mp4"\r\n'
|
|
778
|
+
'Content-Type: video/mp4\r\n\r\n').encode()
|
|
779
|
+
tail = f"\r\n--{boundary}--\r\n".encode()
|
|
780
|
+
self.send_response(200)
|
|
781
|
+
self.send_header("Content-Type", f"multipart/form-data; boundary={boundary}")
|
|
782
|
+
self.send_header("Content-Length", str(len(head) + movie.stat().st_size + len(tail)))
|
|
783
|
+
self.send_header("Cache-Control", "no-store")
|
|
784
|
+
self.end_headers()
|
|
785
|
+
self.wfile.write(head)
|
|
786
|
+
with movie.open("rb") as video:
|
|
787
|
+
shutil.copyfileobj(video, self.wfile)
|
|
788
|
+
self.wfile.write(tail)
|
|
789
|
+
|
|
790
|
+
def file(self, path: str):
|
|
791
|
+
ctype = "video/webm" if path.lower().endswith(".webm") else "video/mp4" # Chrome plays H.264 .mov as mp4
|
|
792
|
+
size = os.path.getsize(path)
|
|
793
|
+
rng = self.headers.get("Range")
|
|
794
|
+
rng_clean = (rng or "").strip()
|
|
795
|
+
single_bytes = rng_clean.startswith("bytes=") and "," not in rng_clean
|
|
796
|
+
if size == 0:
|
|
797
|
+
if single_bytes:
|
|
798
|
+
return self.reply(416, b"", "text/plain", [("Content-Range", "bytes */0")])
|
|
799
|
+
return self.reply(200, b"", ctype, [("Accept-Ranges", "bytes")])
|
|
800
|
+
start, end = 0, size - 1
|
|
801
|
+
m = re.fullmatch(r"bytes=(\d*)-(\d*)", rng_clean)
|
|
802
|
+
if m and (m[1] or m[2]):
|
|
803
|
+
if m[1]:
|
|
804
|
+
start = int(m[1])
|
|
805
|
+
end = int(m[2]) if m[2] else size - 1
|
|
806
|
+
else:
|
|
807
|
+
suffix = int(m[2])
|
|
808
|
+
if suffix == 0:
|
|
809
|
+
return self.reply(416, b"", "text/plain", [("Content-Range", f"bytes */{size}")])
|
|
810
|
+
start, end = max(0, size - suffix), size - 1
|
|
811
|
+
end = min(end, size - 1)
|
|
812
|
+
if start >= size or start > end:
|
|
813
|
+
return self.reply(416, b"", "text/plain", [("Content-Range", f"bytes */{size}")])
|
|
814
|
+
self.send_response(206)
|
|
815
|
+
self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
|
|
816
|
+
elif single_bytes:
|
|
817
|
+
return self.reply(416, b"", "text/plain", [("Content-Range", f"bytes */{size}")])
|
|
818
|
+
else:
|
|
819
|
+
self.send_response(200)
|
|
820
|
+
self.send_header("Accept-Ranges", "bytes")
|
|
821
|
+
self.send_header("Content-Type", ctype)
|
|
822
|
+
self.send_header("Content-Length", str(end - start + 1))
|
|
823
|
+
self.send_header("Cache-Control", "no-store")
|
|
824
|
+
self.end_headers()
|
|
825
|
+
with open(path, "rb") as f:
|
|
826
|
+
f.seek(start)
|
|
827
|
+
left = end - start + 1
|
|
828
|
+
while left > 0 and (chunk := f.read(min(1 << 16, left))):
|
|
829
|
+
self.wfile.write(chunk)
|
|
830
|
+
left -= len(chunk)
|
|
831
|
+
|
|
832
|
+
def handle_one(self):
|
|
833
|
+
try:
|
|
834
|
+
self.route()
|
|
835
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
836
|
+
pass # the browser closed a video range or an event stream it no longer needs
|
|
837
|
+
except (OSError, LookupError, ValueError, RuntimeError, KeyError, subprocess.SubprocessError) as e:
|
|
838
|
+
try:
|
|
839
|
+
self.send_json({"error": str(e)}, 400)
|
|
840
|
+
except OSError:
|
|
841
|
+
pass
|
|
842
|
+
|
|
843
|
+
do_GET = do_POST = handle_one
|
|
844
|
+
|
|
845
|
+
return Handler
|