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: when a shot has several takes with the same cuts, the built-in director takes the best...
Bowen Xue66377add3d14
diff --git a/freevideo_engine/agent/builtin_director.py b/freevideo_engine/agent/builtin_director.pyindex 3879ba8..172e60b 100644--- a/freevideo_engine/agent/builtin_director.py+++ b/freevideo_engine/agent/builtin_director.py@@ -17,7 +17,7 @@ job interface. All asks return a schema-checked object or None."""import base64from copy import deepcopy-from dataclasses import dataclass+from dataclasses import dataclass, replaceimport hashlibimport ipaddressimport json@@ -428,6 +428,46 @@ def judge(shot_view, sheets, *, ask):return uncertain+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.++ 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.+ images = {row['take']: row['image'] for row in sheets['takes']}+ if any(s['take'] not in images for s in segments):+ return None+ count = len(segments[0]['cuts']) + 1+ numbers = [s['take'] for s in segments]+ rating = _object(dict(take=dict(type='integer', enum=numbers),+ scores=dict(type='array', minItems=count, maxItems=count,+ items=dict(type='number', minimum=0, maximum=10))), ('take', 'scores'))+ schema = _object(dict(ratings=dict(type='array', minItems=len(numbers), maxItems=len(numbers), items=rating)),+ ('ratings',))+ parts = ''.join('\n版%d:%s' % (s['take'], '、'.join('第%d段 %.2f–%.2f 秒' % (i + 1, a, b) for i, (a, b) in enumerate(+ zip([0.0] + s['cuts'], s['cuts'] + [s['seconds']])))) for s in segments)+ prompt = ('同一镜头有几个版本,每版在画面硬切处分成相同的几段。按图上的时间标注,给每版的每一段打 0–10 分'+ '(人物变形、多余的字、和描述不符都扣分),scores 按段的顺序给出。'+ '\n镜头描述:' + _dump({k: shot_view[k] for k in ('screenplay', 'characters', 'style') if k in shot_view})+ + '\n图片顺序对应版号:' + _dump(numbers) + '\n各版的分段:' + parts)+ 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']}+ candidates = [dict(s, scores=scores[s['take']]) for s in segments]+ result = cut_pick.stitch(candidates)+ if result['fallback'] or len(result['pieces']) < 2:+ return None+ return result++def revise(view, sentence, *, ask):"""Translate one request into one checked reshoot, or ask for clarification."""unclear = Problem('unclear', '请说明要改哪一镜,以及画面或时长要怎样改?')@@ -480,6 +520,18 @@ 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."""+ 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+ if 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])++def run(tools, production_id, *, ask, stop, wait=25):"""Yield {shot, action, reason}; stop never cancels generation jobs.@@ -489,7 +541,7 @@ def run(tools, production_id, *, ask, stop, wait=25):"""wait = max(0, min(25, wait))since, errors, conflicts = None, 0, 0- handed_off = set()+ handed_off, stitched = set(), {}while not stop():try:view = tools.get(production_id, since=since, wait=wait if since is not None else 0)@@ -506,7 +558,12 @@ def run(tools, production_id, *, ask, stop, wait=25):for s in view['shots']):continuesnapshot = [(s['id'], s['chosen']) for s in view['shots']]- tools.finish(production_id, by='builtin', ref=_ref(production_id, 'finish', snapshot))+ 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 {}))yield dict(shot=None, action='finish', reason='每镜已选定,开始接成影片。')returnif action not in ('choose', 'reshoot'):@@ -534,6 +591,7 @@ 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)else:tools.reshoot(production_id, shot['id'], by='builtin', note=decision.note,diff --git a/freevideo_engine/agent/cut_pick.py b/freevideo_engine/agent/cut_pick.pynew file mode 100644index 0000000..bbcd36e--- /dev/null+++ b/freevideo_engine/agent/cut_pick.py@@ -0,0 +1,202 @@+"""Cut detection, per-segment checks and stitching of same-shot takes.++Pure CPU helpers: `detect_cuts` finds the picture cuts of a take, `segment_qa` applies the take checks to one+segment, `seam` measures how a join between two takes sounds and `stitch` picks the best take for every+segment. Thresholds are those of take_qa.+"""+from functools import lru_cache+from pathlib import Path++import numpy as np++from . import take_qa+from .take_qa import _db, _runs++CUT_DIFF = 25.0 # 0-255 mean change between consecutive frames of a hard cut+CUT_SPIKE = 3.0 # a cut stands out this much from the frame changes around it+MATCH_DIFF = 12.0 # weakest change accepted as an expected cut+SEAM_LEVEL_DB = 20.0 # level step at which the sound penalty is full+SEAM_CLICK = 0.5 # sample jump at which the click penalty is full+SEAM_SPEECH = 0.4 # penalty added for a join inside speech+SEAM_QUIET = 0.25 # weight of level and click at a join in silence+++@lru_cache(maxsize=4)+def _decoded(path, stamp):+ return take_qa._pictures(path)+++@lru_cache(maxsize=4)+def _heard(path, stamp):+ return take_qa._samples(path)+++def _stamp(path):+ stat = Path(path).stat()+ return stat.st_mtime_ns, stat.st_size+++def _pictures(path):+ """take_qa's frames, decoded once while the same file is checked part by part."""+ return _decoded(str(path), _stamp(path))+++def _samples(path):+ return _heard(str(path), _stamp(path))+++def _changes(small):+ return [0.0] + [float(np.abs(small[i] - small[i - 1]).mean()) for i in range(1, len(small))]+++def _spike(diffs, index, lo, hi, floor):+ """Whether frame `index` is a cut: a large change that stands out from its neighbours in lo..hi."""+ around = [diffs[i] for i in range(lo, hi) if i != index]+ return diffs[index] >= floor and diffs[index] >= CUT_SPIKE * (float(np.median(around)) if around else 0.0)+++def detect_cuts(path, expected=None, *, tolerance=0.6):+ """Seconds of the hard picture cuts, ascending, excluding 0 and the end. With `expected`, each expected cut+ takes the strongest frame change within `tolerance` s; one with no such change is None, not guessed."""+ _, small, times = _pictures(path)+ diffs = _changes(small)+ if not expected:+ return [round(times[i], 3) for i in range(1, len(times))+ if (diffs[i] >= CUT_DIFF and diffs[i] >= diffs[i - 1] and diffs[i] > (diffs[i + 1] if i + 1 < len(diffs) else -1)+ and _spike(diffs, i, max(1, i - 3), min(len(diffs), i + 4), CUT_DIFF))]+ found = []+ for wanted in expected:+ 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))+ else:+ found.append(None)+ return found+++def segment_qa(path, start, end):+ """Black picture, frozen picture and a long silence in the middle of speech, inside [start, end)."""+ problems, notes = [], []+ means, small, times = _pictures(path)+ keep = [i for i, t in enumerate(times) if start <= t < end]+ if keep:+ means, small, times = [means[i] for i in keep], [small[i] for i in keep], [times[i] for i in keep]+ black = _runs([m < take_qa.BLACK_LUMA and float(g.std()) < take_qa.BLACK_SPREAD for m, g in zip(means, small)],+ times, take_qa.BLACK_SECONDS)+ flags = [False] * len(small)+ for index in range(1, len(small)):+ if float(np.abs(small[index] - small[index - 1]).mean()) <= take_qa.FREEZE_DIFF:+ flags[index] = flags[index - 1] = True+ frozen = _runs(flags, times, take_qa.FREEZE_SECONDS)+ if black:+ problems.append('black picture at %s' % ', '.join('%.1f-%.1f s' % s for s in black))+ if frozen:+ problems.append('frozen picture at %s' % ', '.join('%.1f-%.1f s' % s for s in frozen))+ samples = _samples(path)[int(start * take_qa.SAMPLE_RATE):int(end * take_qa.SAMPLE_RATE)]+ step = int(take_qa.SAMPLE_RATE * take_qa.WINDOW)+ count = samples.size // step+ if count:+ levels = [_db(np.sqrt(np.mean(samples[i * step:(i + 1) * step] ** 2))) for i in range(count)]+ moments = [start + i * take_qa.WINDOW for i in range(count)]+ if any(level > take_qa.SPEECH_DB for level in levels):+ gaps = [(a, b) for a, b in _runs([level < take_qa.GAP_DB for level in levels], moments, take_qa.GAP_SECONDS)+ if a > start + take_qa.GAP_EDGE and b < moments[-1] - take_qa.GAP_EDGE]+ if gaps:+ problems.append('silent gap at %s' % ', '.join('%.1f-%.1f s' % g for g in gaps))+ return dict(problems=problems, notes=notes, ok=not problems)+++def _side(samples, at, span, before):+ rate = take_qa.SAMPLE_RATE+ n = max(1, int(span * rate))+ cut = min(samples.size, max(0, int(round(at * rate))))+ return samples[max(0, cut - n):cut] if before else samples[cut:cut + n]+++def _seam(a, a_end, b, b_start, span):+ left, right = _side(a, a_end, span, True), _side(b, b_start, span, False)+ if not left.size or not right.size:+ return dict(level_db=0.0, click=0.0, in_speech=False, penalty=0.0)+ levels = [_db(np.sqrt(np.mean(x ** 2))) for x in (left, right)]+ level_db = abs(levels[0] - levels[1])+ click = float(abs(right[0] - left[-1]))+ in_speech = any(level > take_qa.SPEECH_DB for level in levels)+ base = 0.6 * min(1.0, level_db / SEAM_LEVEL_DB) + 0.4 * min(1.0, click / SEAM_CLICK)+ penalty = base + SEAM_SPEECH if in_speech else base * SEAM_QUIET+ return dict(level_db=round(level_db, 2), click=round(click, 4), in_speech=in_speech,+ penalty=round(min(1.0, penalty), 4))+++def seam(a_path, a_end, b_path, b_start, *, span=0.1):+ """How a join sounds: level step over `span` s each side, sample jump, whether it falls in speech, penalty 0..1."""+ return _seam(_samples(a_path), a_end, _samples(b_path), b_start, span)+++def _whole(candidates):+ best = min(candidates, key=lambda c: (-sum(c.get('scores') or [0]), c['take']))+ return dict(pieces=[dict(take=best['take'], start=0.0, end=best['seconds'])],+ score=round(float(sum(best.get('scores') or [0])), 6), fallback=True)+++def stitch(candidates, *, seam_weight=0.5):+ """Choose a take for every segment, maximizing segment scores minus seam_weight * 10 * seam penalties.+ A join between different takes inside speech is not allowed. Falls back to the best whole take when cut counts+ differ, a segment has no usable candidate or no allowed sequence of takes exists."""+ if not candidates:+ return dict(pieces=[], score=0.0, fallback=True)+ candidates = sorted(candidates, key=lambda c: c['take'])+ count = len(candidates[0]['cuts']) + 1+ 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}+ usable = [[c for c in candidates if c['qa'][k]] for k in range(count)]+ if not all(usable):+ return _whole(candidates)+ audio, joins = {}, {}++ def penalty(a, b, k):+ """The seam penalty, or None when the join is not allowed: a join between takes inside speech, or unreadable."""+ key = (a['take'], b['take'], k)+ if key not in joins:+ try:+ for c in (a, b):+ if c['take'] not in audio:+ audio[c['take']] = _samples(c['path'])+ row = _seam(audio[a['take']], bounds[a['take']][k + 1], audio[b['take']], bounds[b['take']][k + 1], 0.1)+ joins[key] = None if row['in_speech'] else row['penalty']+ except Exception:+ joins[key] = None+ return joins[key]++ # state: candidate take -> (score, takes so far); ties keep the smaller take sequence+ state = {c['take']: (float(c['scores'][0]), [c['take']]) for c in usable[0]}+ for k in range(1, count):+ step = {}+ for c in usable[k]:+ options = []+ for p in usable[k - 1]:+ if p['take'] not in state:+ continue+ score, path = state[p['take']]+ cost = 0.0+ if p['take'] != c['take']:+ seam_penalty = penalty(p, c, k - 1)+ if seam_penalty is None:+ continue+ cost = seam_weight * 10 * seam_penalty+ options.append((round(score + float(c['scores'][k]) - cost, 9), path + [c['take']]))+ if options:+ step[c['take']] = min(options, key=lambda o: (-o[0], o[1]))+ if not step:+ return _whole(candidates)+ state = step+ score, takes = min(state.values(), key=lambda o: (-o[0], o[1]))+ pieces = []+ for k, take in enumerate(takes):+ start, end = bounds[take][k], bounds[take][k + 1]+ if pieces and pieces[-1]['take'] == take:+ pieces[-1]['end'] = end+ else:+ pieces.append(dict(take=take, start=start, end=end))+ return dict(pieces=pieces, score=round(score, 6), fallback=False)diff --git a/freevideo_engine/agent/production.py b/freevideo_engine/agent/production.pyindex 5229df8..a91b470 100644--- a/freevideo_engine/agent/production.py+++ b/freevideo_engine/agent/production.py@@ -486,7 +486,7 @@ def advance(state, children, *, now):if join.get('cancel_requested'):actions.append({'cancel': join['ref']})elif not state.get('paused') and join['ref'] not in children:- actions.append({'join': {key: deepcopy(join[key]) for key in ('ref', 'takes', 'transition')}})+ actions.append({'join': {key: deepcopy(join[key]) for key in ('ref', 'takes', 'transition', 'pieces') if key in join}})return actions@@ -623,8 +623,40 @@ def _missing(state):return result-def finish(state, *, by, transition=None, now):- """Snapshot the chosen refs for a new join, retaining every previous output."""+def _pieces(state, pieces):+ """Validate the parts to join for some shots; returns {shot id: [{job, start, end}]} or None."""+ if not pieces:+ return None+ result, problems = {}, []+ for shot in state['shots']:+ rows = pieces.get(shot['id'])+ if rows is None:+ continue+ found = []+ for row in rows if isinstance(rows, list) else ():+ take = next((t for t in shot['takes'] if t['take'] == row.get('take')+ and t['state'] == 'succeeded' and not t['stale']), None)+ start, end = row.get('start'), row.get('end')+ if take 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/' + shot['id'], message='needs succeeded takes and 0 <= start < end'))+ break+ found.append(dict(job=take['job'], start=float(start), end=float(end)))+ else:+ if found:+ result[shot['id']] = found+ continue+ problems.append(dict(path='/pieces/' + shot['id'], message='must list at least one part'))+ unknown = sorted(set(pieces) - {s['id'] for s in state['shots']})+ problems += [dict(path='/pieces/' + str(k), message='is not a shot') for k in unknown]+ if problems:+ _invalid(problems)+ return result or None+++def finish(state, *, by, transition=None, pieces=None, now):+ """Snapshot the chosen refs for a new join, retaining every previous output.++ `pieces` maps a shot id to [{take, start, end}] to join those parts of its takes instead of the chosen take."""_editable(state, by)missing = _missing(state)if missing:@@ -634,13 +666,16 @@ def finish(state, *, by, transition=None, now):if transition not in ('cut', 'crossfade'):_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 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:+ if current and current['state'] in ACTIVE and current['takes'] == refs and current['transition'] == transition and current.get('pieces') == parts:returndraft = deepcopy(state)ref = '%s:join%d' % (state['id'], len(state['joins']) + 1)draft['joins'].append(dict(ref=ref, takes=refs, transition=transition, state='waiting', by=by,- revision=state['revision'] + 1, library_id=None, seconds=None, error=None))+ revision=state['revision'] + 1, library_id=None, seconds=None, error=None,+ **({'pieces': parts} if parts else {})))draft['current_join'], draft['cancelled'] = ref, False_commit(state, draft, now)diff --git a/freevideo_engine/agent/productions.py b/freevideo_engine/agent/productions.pyindex 0b9ca03..68b100f 100644--- a/freevideo_engine/agent/productions.py+++ b/freevideo_engine/agent/productions.py@@ -1012,8 +1012,14 @@ class Productions:if len(set(children) | set(record['children'])) >= MAX_CHILDREN:raise JobError('production_limit', 'Too many child jobs')if 'join' in action:- item = dict(kind='assemble', clips=[children[r]['id'] for r in item['takes']],- transition=item['transition'],+ parts = item.get('pieces') or {}+ shots = {t['job']: s['id'] for s in record['state']['shots'] for t in s['takes']}+ 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]+ if rows else [children[r]['id']])+ item = dict(kind='assemble', clips=clips, transition=item['transition'],transition_seconds=record['state']['screenplay'].get('transition_seconds', .5))else:take = next(t for s in record['state']['shots'] for t in s['takes'] if t['job'] == ref)@@ -1125,6 +1131,33 @@ class Productions:result['previous'] = output.read_bytes()return result+ def segments(self, identity, shot):+ """The picture cuts of each usable take of a shot, with each part checked: what the director needs to+ take the best part of every cut from different takes."""+ from . import cut_pick+ with self.changed:+ record = self._record(identity)+ row = _domain(production._shot, record['state'], shot)+ takes = [(t['take'], t['library_id'], t.get('seconds'), spec.cut_times((t.get('spec') or {}).get('prompt')),+ (record.get('qa') or {}).get(t['job'])) for t in row['takes']+ if t['state'] == 'succeeded' and not t['stale']]+ result = []+ with self.jobs.cpu:+ for number, library, seconds, expected, qa in takes:+ if not library or not (qa or {}).get('ok', False):+ continue+ path = self.jobs.port.library_video(library)+ cuts = cut_pick.detect_cuts(path, [t for t in expected if t > 0])+ 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+ if total is None:+ continue+ bounds = [0.0] + cuts + [total]+ checks = [cut_pick.segment_qa(path, bounds[i], bounds[i + 1])['ok'] for i in range(len(bounds) - 1)]+ result.append(dict(take=number, path=str(path), cuts=cuts, seconds=total, qa=checks))+ return result+def adapter(self):return DirectorAdapter(self)@@ -1142,6 +1175,6 @@ class DirectorAdapter:return self.productions.get(identity, since=since, wait=wait, compact=False)def __getattr__(self, name):- if name in ('plan', 'start', 'sheet', 'choose', 'reshoot', 'finish', 'cancel', 'pause', 'resume'):+ if name in ('plan', 'start', 'sheet', 'segments', 'choose', 'reshoot', 'finish', 'cancel', 'pause', 'resume'):return getattr(self.productions, name)raise AttributeError(name)