Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Agent: external Agents can take the best part of every cut too.
Bowen Xuebe7a47a09f09
diff --git a/freevideo_engine/agent/builtin_director.py b/freevideo_engine/agent/builtin_director.pyindex 172e60b..2dc4050 100644--- a/freevideo_engine/agent/builtin_director.py+++ b/freevideo_engine/agent/builtin_director.py@@ -431,18 +431,13 @@ def judge(shot_view, sheets, *, ask):CUT_AGREE = 0.3 # seconds by which the same cut may differ between takes-def stitch_shot(shot_view, segments, sheets, *, ask):- """Pieces taking the best part of every cut from different takes, or None to keep one whole take.+GOOD = 7 # a part is good enough to keep when it scores this or more- Needs two or more takes that passed the check, every one with the same two or more cuts. The last piece- comes from the take that is chosen, so the next shot still continues from the chosen take's last frame."""- from . import cut_pick- if len(segments) < 2 or any(len(s['cuts']) != len(segments[0]['cuts']) for s in segments) or not segments[0]['cuts']:- return None- if any(abs(a - b) > CUT_AGREE for s in segments for a, b in zip(s['cuts'], segments[0]['cuts'])):- return None # The same cut sits at different times: these are not the same parts.++def rate_segments(shot_view, segments, sheets, *, ask):+ """{take: [score of every part]} for takes that share their cuts, or None when the model cannot say."""images = {row['take']: row['image'] for row in sheets['takes']}- if any(s['take'] not in images for s in segments):+ if not segments or any(s['take'] not in images for s in segments):return Nonecount = len(segments[0]['cuts']) + 1numbers = [s['take'] for s in segments]@@ -460,7 +455,35 @@ def stitch_shot(shot_view, segments, sheets, *, ask):reply = _ask(ask, prompt, [images[n] for n in numbers], schema)if reply is None or sorted(r['take'] for r in reply['ratings']) != sorted(numbers):return None- scores = {r['take']: r['scores'] for r in reply['ratings']}+ return {r['take']: r['scores'] for r in reply['ratings']}+++def first_take_is_good(tools, production_id, shot, sheets, take, *, ask):+ """Whether a shot still being filmed may stop at this take: it has no numbered cuts, or every part of it scores+ GOOD. Otherwise the other takes are waited for so each cut can take its best part."""+ try:+ own = [s for s in tools.segments(production_id, shot['id']) if s['take'] == take]+ if not own or not own[0]['cuts']:+ return True+ scores = rate_segments(shot, own, sheets, ask=ask)+ except Exception: # noqa: BLE001 - without the cut scores the whole-take score decides, as before+ return True+ return scores is None or all(x >= GOOD for x in scores.get(take, ()))+++def stitch_shot(shot_view, segments, sheets, *, ask):+ """Pieces taking the best part of every cut from different takes, or None to keep one whole take.++ Needs two or more takes that passed the check, every one with the same two or more cuts. The last piece+ comes from the take that is chosen, so the next shot still continues from the chosen take's last frame."""+ from . import cut_pick+ if len(segments) < 2 or any(len(s['cuts']) != len(segments[0]['cuts']) for s in segments) or not segments[0]['cuts']:+ return None+ if any(abs(a - b) > CUT_AGREE for s in segments for a, b in zip(s['cuts'], segments[0]['cuts'])):+ return None # The same cut sits at different times: these are not the same parts.+ scores = rate_segments(shot_view, segments, sheets, ask=ask)+ if scores is None:+ return Nonecandidates = [dict(s, scores=scores[s['take']]) for s in segments]result = cut_pick.stitch(candidates)if result['fallback'] or len(result['pieces']) < 2:@@ -520,16 +543,17 @@ def _ref(identity, action, snapshot):return identity + ':builtin:' + action + ':' + digest-def _with_stitch(tools, production_id, shot, sheets, decision, stitched, ask):- """Take the best part of every cut when the takes allow it; the choice becomes the take that ends the film part."""+def _with_stitch(tools, production_id, shot, sheets, decision, ask):+ """Take the best part of every cut when the takes allow it; the choice becomes the take that ends the film part.+ Returns the decision and the parts, or None for the parts when one whole take stands."""try:pieces = stitch_shot(shot, tools.segments(production_id, shot['id']), sheets, ask=ask)except Exception: # noqa: BLE001 - stitching is an extra; one whole take is always the fallback- return decision+ return decision, Noneif pieces is None:- return decision- stitched[shot['id']] = [dict(take=p['take'], start=p['start'], end=p['end']) for p in pieces['pieces']]- return replace(decision, take=pieces['pieces'][-1]['take'], reason=(decision.reason + ';各切镜取最好的一版拼接')[:300])+ return decision, None+ parts = [dict(take=p['take'], start=p['start'], end=p['end']) for p in pieces['pieces']]+ return replace(decision, take=parts[-1]['take'], reason=(decision.reason + ';各切镜取最好的一版拼接')[:300]), partsdef run(tools, production_id, *, ask, stop, wait=25):@@ -541,7 +565,7 @@ def run(tools, production_id, *, ask, stop, wait=25):"""wait = max(0, min(25, wait))since, errors, conflicts = None, 0, 0- handed_off, stitched = set(), {}+ handed_off = set()while not stop():try:view = tools.get(production_id, since=since, wait=wait if since is not None else 0)@@ -559,11 +583,8 @@ def run(tools, production_id, *, ask, stop, wait=25):continuesnapshot = [(s['id'], s['chosen']) for s in view['shots']]chosen = dict(snapshot)- # A part list only stands while its last take is still the chosen one.- pieces = {k: v for k, v in stitched.items() if chosen.get(k) == v[-1]['take']}- tools.finish(production_id, by='builtin', ref=_ref(production_id, 'finish', snapshot + sorted(- (k, [(p['take'], p['start'], p['end']) for p in v]) for k, v in pieces.items())),- **({'pieces': pieces} if pieces else {}))+ # The parts of a shot are kept with its chosen take in the production.+ tools.finish(production_id, by='builtin', ref=_ref(production_id, 'finish', snapshot))yield dict(shot=None, action='finish', reason='每镜已选定,开始接成影片。')returnif action not in ('choose', 'reshoot'):@@ -591,8 +612,12 @@ def run(tools, production_id, *, ask, stop, wait=25):elif decision.action in ('choose', 'reshoot'):ref = _ref(production_id, decision.action, shot)if decision.action == 'choose':- decision = _with_stitch(tools, production_id, shot, sheets, decision, stitched, ask)- tools.choose(production_id, shot['id'], decision.take, by='builtin', reason=decision.reason, ref=ref)+ if shot.get('state') in ('waiting', 'shooting') and not first_take_is_good(+ tools, production_id, shot, sheets, decision.take, ask=ask):+ continue # the first take is not good in every cut: wait for the others+ decision, parts = _with_stitch(tools, production_id, shot, sheets, decision, ask)+ tools.choose(production_id, shot['id'], decision.take, by='builtin', reason=decision.reason, ref=ref,+ **({'pieces': parts} if parts else {}))else:tools.reshoot(production_id, shot['id'], by='builtin', note=decision.note,takes=decision.takes, reason=decision.reason, ref=ref)diff --git a/freevideo_engine/agent/cut_pick.py b/freevideo_engine/agent/cut_pick.pyindex 484bf53..9e3f689 100644--- a/freevideo_engine/agent/cut_pick.py+++ b/freevideo_engine/agent/cut_pick.py@@ -75,9 +75,17 @@ def detect_cuts(path, expected=None, *, tolerance=0.6):near = [i for i in range(1, len(times)) if abs(times[i] - wanted) <= tolerance]best = max(near, key=lambda i: (diffs[i], -abs(times[i] - wanted)), default=None)if best is not None and _spike(diffs, best, max(1, min(near) - 1), min(len(diffs), max(near) + 2), MATCH_DIFF):- found.append(round(times[best], 3))+ found.append(times[best])else:found.append(None)+ # one frame cannot be two cuts: the cut nearer its expected time keeps it, the other is not found+ for index, at in enumerate(found):+ for other in range(index):+ if at is not None and found[other] == at:+ loser = index if abs(at - expected[index]) >= abs(at - expected[other]) else other+ found[loser] = None+ if loser == index:+ breakreturn found@@ -156,6 +164,8 @@ def stitch(candidates, *, seam_weight=0.5):if any(len(c['cuts']) + 1 != count or len(c['scores']) != count or len(c['qa']) != count for c in candidates):return _whole(candidates)bounds = {c['take']: [0.0] + [float(t) for t in c['cuts']] + [float(c['seconds'])] for c in candidates}+ if any(b <= a for row in bounds.values() for a, b in zip(row, row[1:])):+ return _whole(candidates) # a cut at or before the previous one leaves an empty pieceusable = [[c for c in candidates if c['qa'][k]] for k in range(count)]if not all(usable):return _whole(candidates)diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.pyindex c96e0d8..b61cf91 100644--- a/freevideo_engine/agent/guide.py+++ b/freevideo_engine/agent/guide.py@@ -197,6 +197,11 @@ GUIDE = {'job (30 s or more, or beyond the device limit, continues and joins automatically); to polish an idea first, run enhance, then generate with "prompt": {"from_job": "<enhance id>"} rather than retyping the text. ''A film is cut into shots: see the rule "Cut by default" before making one long continued video.','Use drama plan → start → get → sheet → choose/reshoot → finish; inspect todo after every change.',+ 'A shot whose prompt has numbered cuts and several takes: do not stop at the first take unless every cut of it is good '+ '(scores 7 or more of 10); wait for the other takes, read segments, and choose with pieces '+ '[{take, start, end}] to take the best part of every cut from different takes. Cut only where the takes cut, '+ 'never inside speech (in_speech), and skip a part with parts_ok false. The last part comes from the chosen take. Pass the cut times back exactly as returned, unrounded. '+ 'finish accepts pieces for any shot too. One whole take stays the fallback.','At start tell the user the estimated total time; on over_budget decide whether to ask them; ''without an estimate report only the current work and elapsed time.','Use get with since=revision and wait=25. changed=false is a compact timeout; retain the last full board.',@@ -353,6 +358,7 @@ CAPABILITIES_ZH = {('GET', '/drama/{id}'): '读取待办事项 todo 和版本 revision;用 since 和 wait=25 等待变化。''paused 有值时停止操作,持续等待用户继续',('GET', '/drama/{id}/shots/{shot}/sheet'): '各条生成完成后,查看带时间标记的画面和前一镜所选片段的末帧',+ ('GET', '/drama/{id}/shots/{shot}/segments'): '镜头有几版且提示词写了同样的编号切镜时,读取每版的切点、各段检查和各版在每个切点处的衔接,再用 pieces 选出每个切镜最好的一段',('POST', '/drama/{id}/shots/{shot}/choose'): '查看画面后选择一条;选定后才能拍摄承接它的下一镜',('POST', '/drama/{id}/shots/{shot}/reshoot'): '按修改要求重拍,再查看画面并重新选片',('POST', '/drama/{id}/finish'): '每一镜都选定后提交拼接,继续查询影片直到成片就绪',diff --git a/freevideo_engine/agent/production.py b/freevideo_engine/agent/production.pyindex a91b470..73f2a1f 100644--- a/freevideo_engine/agent/production.py+++ b/freevideo_engine/agent/production.py@@ -335,12 +335,13 @@ def _reconnect(state, shot):if take['stale'] and take['state'] in ACTIVE + ('paused',):take['cancel_requested'] = Trueif not _chosen(shot):- shot['chosen'] = shot['chosen_by'] = None+ shot['chosen'] = shot['chosen_by'] = shot['pieces'] = Nonechoice = shot.get('choices', {}).get(parent['job']) if parent else Noneif choice:take = _take(shot, choice['take'])if take['state'] == 'succeeded' and not take['stale']:shot['chosen'], shot['chosen_by'] = take['take'], choice['by']+ shot['pieces'] = Noneif _usable(shot):_drop_automatic(shot)@@ -547,8 +548,31 @@ def _withdraw_others(row, chosen):row['pending'] = [g for g in row['pending'] if g[0].get('automatic')]-def choose(state, shot, take, *, by, reason=None, cascade=True, now):- """Choose a current take, optionally reconnecting descendants automatically."""+def _kept_parts(row, take, pieces):+ """The parts to remember with a chosen take: valid takes of this shot, the last one being the chosen take."""+ if pieces is None:+ return None+ problems = []+ if not isinstance(pieces, list) or not pieces:+ problems.append(dict(path='/pieces', message='must list at least one part'))+ else:+ for index, part in enumerate(pieces):+ version = next((t for t in row['takes'] if isinstance(part, dict) and t['take'] == part.get('take')+ and t['state'] == 'succeeded' and not t['stale']), None)+ start, end = (part.get('start'), part.get('end')) if isinstance(part, dict) else (None, None)+ if version is None or type(start) not in (int, float) or type(end) not in (int, float) or not 0 <= start < end:+ problems.append(dict(path='/pieces/%d' % index, message='needs a succeeded take of this shot and 0 <= start < end'))+ if not problems and pieces[-1]['take'] != take:+ problems.append(dict(path='/pieces/%d' % (len(pieces) - 1), message='the last part must come from the chosen take'))+ if problems:+ _invalid(problems)+ return [dict(take=p['take'], start=float(p['start']), end=float(p['end'])) for p in pieces]+++def choose(state, shot, take, *, by, reason=None, cascade=True, pieces=None, now):+ """Choose a current take, optionally reconnecting descendants automatically.++ `pieces` is [{take, start, end}] to join from several takes of this shot; the last one comes from `take`."""_editable(state, by)_optional_text(reason, '/reason')draft = deepcopy(state)@@ -560,13 +584,21 @@ def choose(state, shot, take, *, by, reason=None, cascade=True, now):raise ProductionError('take_not_ready', 'The take is stale or has not succeeded.',details=dict(shot=shot, take=take, state=version['state'], stale=version['stale'],why='stale' if version['stale'] else 'not_succeeded'))+ kept = _kept_parts(row, take, pieces)if row['chosen'] == take:if by == 'user' and row['chosen_by'] != 'user':row['chosen_by'] = by+ row['pieces'] = kept+ _decision(draft, now, by, 'chosen', shot, take, reason)+ _commit(state, draft, now)+ elif pieces is not None and kept != row.get('pieces'):+ _guard(row, by)+ row['pieces'] = kept_decision(draft, now, by, 'chosen', shot, take, reason)_commit(state, draft, now)returnrow['chosen'], row['chosen_by'] = take, by+ row['pieces'] = kept_withdraw_others(row, take)_refresh(draft)if by != 'user':@@ -653,6 +685,13 @@ def _pieces(state, pieces):return result or None+def _kept_standing(shot):+ rows = shot.get('pieces')+ chosen = shot.get('chosen')+ return bool(rows) and rows[-1]['take'] == chosen and all(+ any(t['take'] == r['take'] and t['state'] == 'succeeded' and not t['stale'] for t in shot['takes']) for r in rows)++def finish(state, *, by, transition=None, pieces=None, now):"""Snapshot the chosen refs for a new join, retaining every previous output.@@ -667,7 +706,13 @@ def finish(state, *, by, transition=None, pieces=None, now):_invalid([dict(path='/transition', message='must be "cut" or "crossfade"')])refs = [_chosen(shot)['job'] for shot in state['shots']]# A crossfade overlaps every neighbouring clip, which would dissolve the cuts inside a shot too.- parts = _pieces(state, pieces) if transition == 'cut' else None+ # Parts kept with a chosen take stand while their takes do; parts given now replace them for that shot.+ if by != 'user':+ owned = [shot['id'] for shot in state['shots'] if shot['id'] in (pieces or {}) and shot['chosen_by'] == 'user']+ if owned:+ raise ProductionError('chosen_by_user', 'This shot was chosen by the user.', details={'shots': owned})+ kept = {shot['id']: shot['pieces'] for shot in state['shots'] if _kept_standing(shot)}+ parts = _pieces(state, {**kept, **(pieces or {})}) if transition == 'cut' else Nonecurrent = next((j for j in state['joins'] if j['ref'] == state['current_join']), None)if current and current['state'] in ACTIVE and current['takes'] == refs and current['transition'] == transition and current.get('pieces') == parts:return@@ -774,6 +819,7 @@ def view(state):result['shots'] = []for shot in state['shots']:row = {key: deepcopy(shot[key]) for key in ('id', 'index', 'continues', 'state', 'chosen', 'chosen_by')}+ row['pieces'] = deepcopy(shot.get('pieces'))# The cast of the latest submitted take: cards are read when a take is submitted.latest = next((t for t in reversed(shot['takes']) if 'cast_reference' in t), {})row.update(cast_reference=latest.get('cast_reference'), cast_omitted=deepcopy(latest.get('cast_omitted', [])),diff --git a/freevideo_engine/agent/productions.py b/freevideo_engine/agent/productions.pyindex 32d3329..61cd328 100644--- a/freevideo_engine/agent/productions.py+++ b/freevideo_engine/agent/productions.py@@ -1033,7 +1033,7 @@ class Productions:clips = []for r in item['takes']:rows = parts.get(shots.get(r))- clips += ([dict(from_job=children[x['job']]['id'], start=x['start'], end=x['end']) for x in rows]+ clips += ([dict(from_job=children[x['job']]['id'], **_on_frames(x['start'], x['end'])) for x in rows]if rows else [children[r]['id']])item = dict(kind='assemble', clips=clips, transition=item['transition'],transition_seconds=record['state']['screenplay'].get('transition_seconds', .5))@@ -1163,7 +1163,10 @@ class Productions:if not library or not (qa or {}).get('ok', False):continuepath = self.jobs.port.library_video(library)- cuts = cut_pick.detect_cuts(path, [t for t in expected if t > 0])+ wanted = [t for t in expected if t > 0]+ if not wanted:+ continue # no numbered cuts in the prompt: this take is only ever used whole+ cuts = cut_pick.detect_cuts(path, wanted)if None in cuts:continue # A cut the prompt asks for is not in this take: its parts cannot be matched to the others.total = float(seconds) if seconds else None@@ -1174,10 +1177,40 @@ class Productions:result.append(dict(take=number, path=str(path), cuts=cuts, seconds=total, qa=checks))return result+ def segments_view(self, identity, shot):+ """What an agent needs to take the best part of every cut from different takes: for each usable take its+ cuts, length and the check of each part, and how every join between two takes would sound at each cut.+ Parts and joins use take numbers; finish takes {shot: [{take, start, end}]} (or choose takes pieces)."""+ from . import cut_pick+ rows = self.segments(identity, shot)+ takes = [dict(take=r['take'], cuts=r['cuts'], seconds=r['seconds'], parts_ok=r['qa']) for r in rows]+ joins = []+ with self.jobs.cpu:+ for a in rows:+ for b in rows:+ if a['take'] == b['take'] or len(a['cuts']) != len(b['cuts']):+ continue+ for k, (end, start) in enumerate(zip(a['cuts'], b['cuts'])):+ try:+ heard = cut_pick.seam(a['path'], end, b['path'], start)+ except Exception: # noqa: BLE001 - an unreadable sound is no join to recommend+ continue+ joins.append(dict(cut=k + 1, out_of=a['take'], into=b['take'], penalty=heard['penalty'],+ in_speech=heard['in_speech'], level_step_db=heard['level_db']))+ return dict(shot=shot, takes=takes, joins=joins,+ rule='A join is not allowed inside speech (in_speech) and a part with parts_ok false is not used.')+def adapter(self):return DirectorAdapter(self)+def _on_frames(start, end, fps=24):+ """A cut time rounded by a caller (2.04 for 2.0416..) would leave one frame of the other scene at the join:+ move both ends to the nearest output frame. The stored values stay as given."""+ a, b = round(start * fps) / fps, round(end * fps) / fps+ return dict(start=a, end=b) if b > a else dict(start=start, end=end)++class DirectorAdapter:"""Synchronous in-process operations for builtin_director.run.diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.pyindex 9810b2f..bdfc2b8 100644--- a/freevideo_engine/agent/routes.py+++ b/freevideo_engine/agent/routes.py@@ -2153,6 +2153,8 @@ def register():if operation == 'get':# Long waits are asynchronous: they hold no worker thread, so user controls never queue behind them.return reply(await productions.get_async(identity, **request[query_key]))+ if operation == 'segments':+ return reply(await asyncio.to_thread(productions.segments_view, identity, shot))if operation == 'sheet':value = await asyncio.to_thread(productions.sheet, identity, shot, **request[query_key])def picture(data):diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.pyindex e272e1b..b93dbb1 100644--- a/freevideo_engine/agent/schema.py+++ b/freevideo_engine/agent/schema.py@@ -651,6 +651,7 @@ DRAMA_OPERATIONS = {'list': ('GET', '/drama', 'List films; status=active returns unfinished summaries'),'get': ('GET', '/drama/{id}', 'Read todo and revision; use since and wait=25. If paused, stop acting and long-wait until the user continues'),'sheet': ('GET', '/drama/{id}/shots/{shot}/sheet', 'After takes succeed, review their timed images and the previous chosen last frame'),+ 'segments': ('GET', '/drama/{id}/shots/{shot}/segments', 'When a shot has several takes with the same numbered cuts, read each take\'s cuts and part checks and how takes join at each cut; then choose with pieces to take the best part of every cut, passing the cut times back exactly as returned'),'choose': ('POST', '/drama/{id}/shots/{shot}/choose', 'After reviewing the sheet, choose a take; only then can the next continuation shoot'),'reshoot': ('POST', '/drama/{id}/shots/{shot}/reshoot', 'Request corrected takes, then review the sheet and choose again'),'finish': ('POST', '/drama/{id}/finish', 'After every shot is chosen, accept assembly; get the film until its output is ready'),@@ -668,6 +669,16 @@ SCREENPLAY = {'type': 'object', 'description': ('continue: true to carry on from the previous shot}]; also title, style, aspect, quality; a whole-film score is not written here but imported onto a sound track.')}+PIECES = dict(type='array', minItems=1, maxItems=24, description=(+ 'Parts of this shot\'s takes to join in order instead of one whole take: [{take, start, end}] in seconds, the last '+ 'part from the chosen take. Read segments first; cut where the takes cut, never inside speech.'),+ items=dict(type='object', additionalProperties=False, required=['take', 'start', 'end'],+ properties=dict(take=dict(type='integer', minimum=1), start=dict(type='number', minimum=0),+ end=dict(type='number', exclusiveMinimum=0))))+FINISH_PIECES = dict(type='object', description='Parts for some shots: {shot id: [{take, start, end}]}, replacing the parts chosen with the take.',+ additionalProperties=PIECES)++def drama_schema(name):if name in ('plan', 'start'):return obj(dict(screenplay=SCREENPLAY, takes_per_shot=number(1, 8, integer=True, default=1),@@ -678,14 +689,16 @@ def drama_schema(name):return obj(dict(since=number(1, integer=True), wait=WAIT))if name == 'sheet':return obj(dict(frames=number(2, 24, integer=True, description='Frames per take; default one per second of the take (6 to 24)')))+ if name == 'segments':+ return obj({})if name == 'choose':- return obj(dict(take=number(1, integer=True), reason=string(20000), cascade={'type': 'boolean'}, ref=REF), ('take',))+ return obj(dict(take=number(1, integer=True), reason=string(20000), cascade={'type': 'boolean'}, pieces=PIECES, ref=REF), ('take',))if name == 'reshoot':changes = {key: dict(type='string', maxLength=20000) for key in ('action', 'camera', 'framing', 'prompt')}changes.update(seconds=number(1.625, 60), lines=dict(type='array', items={'type': 'object'}))return obj(dict(note=string(20000), changes=obj(changes), takes=number(1, 8, integer=True, default=1),reason=string(20000), ref=REF))- return obj(dict(ref=REF, **({'transition': enum(('cut', 'crossfade'))} if name == 'finish' else {})))+ return obj(dict(ref=REF, **({'transition': enum(('cut', 'crossfade')), 'pieces': FINISH_PIECES} if name == 'finish' else {})))CAST_OPERATIONS = {