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: automatic QA on finished takes, withdraw other takes when one is chosen, two takes per...
Bowen Xue5bfa754b0f12
diff --git a/freevideo_engine/agent/builtin_director.py b/freevideo_engine/agent/builtin_director.pyindex f530ad5..3879ba8 100644--- a/freevideo_engine/agent/builtin_director.py+++ b/freevideo_engine/agent/builtin_director.py@@ -26,7 +26,7 @@ import reimport urllib.requestfrom urllib.parse import urlsplit-from . import drama, spec+from . import drama, spec, take_qa@dataclass(frozen=True)@@ -367,17 +367,27 @@ def judge(shot_view, sheets, *, ask):shot = shot_viewif shot.get('chosen_by') == 'user' or shot.get('chosen') is not None:return Decision('keep', shot['id'], '保留已选定的版本。')- if shot.get('state') in ('waiting', 'shooting'):- return Decision('wait', shot['id'], '等待这一镜的各版完成。')+ shooting = shot.get('state') in ('waiting', 'shooting')uncertain = Decision('ask_user', shot['id'], '拿不准,请挑一版。')- takes = _selectable(shot)+ finished = _selectable(shot)+ unchecked = any('qa' in t and t['qa'] is None for t in finished)+ if shooting and (not finished or any(t.get('qa') is None for t in finished)) or unchecked:+ return Decision('wait', shot['id'], '等待这一镜的各版完成并质检。')+ # A take that failed the picture or sound check is never chosen; a shot still shooting is judged as takes arrive.+ takes = [t for t in finished if (t.get('qa') or {}).get('ok', True)]if not takes:- return uncertain+ if shooting:+ return Decision('wait', shot['id'], '已完成的版本没有通过质检,等待其余版本。')+ if not finished or _retaken(shot):+ return uncertain+ faults = ';'.join(sorted({p for t in finished for p in t['qa']['problems']}))+ return Decision('reshoot', shot['id'], '各版都没有通过质检。',+ note=('上一次的问题:' + faults)[:300], takes=_take_count(shot))try:rows = sheets['takes']images = {row['take']: row['image'] for row in rows}numbers = [t['take'] for t in takes]- if len(images) != len(rows) or set(images) != set(numbers):+ if len(images) != len(rows) or not set(numbers) <= set(images):return uncertainprevious = sheets.get('previous')batch_size = 15 if previous is not None else 16@@ -391,9 +401,11 @@ def judge(shot_view, sheets, *, ask):('ratings',))prompt = ('评价这一镜的每个版本:0–10 分,reason 用不超过30字的中文指出具体优点或问题''(多余的字、人物变形、和描述不符等);note 给下一次生成能用的具体修正。'- 'captions 表示有叠加字幕/文字,场景内真实招牌不算。不评价声音。'+ 'captions 表示有叠加字幕/文字,场景内真实招牌不算。声音由自动质检评价,这里不评价。''\n镜头描述:' + _dump({k: shot[k] for k in ('screenplay', 'characters', 'style', 'captions') if k in shot})+ '\n图片顺序对应版号:' + _dump(batch)+ + ''.join('\n版%d的%s' % (t['take'], take_qa.summary(t.get('qa'))) for t in takes+ if t['take'] in batch and t.get('qa'))+ (';最后一张是上一镜选定版的末帧,仅供接续参考。' if previous is not None else '。'))reply = _ask(ask, prompt, [images[n] for n in batch] + ([previous] if previous is not None else []), schema)if reply is None or sorted(r['take'] for r in reply['ratings']) != sorted(batch):@@ -405,6 +417,8 @@ def judge(shot_view, sheets, *, ask):if row['captions'] and not shot.get('captions', False):row['score'] = min(row['score'], 3)best = max(ratings, key=lambda r: (r['score'], -r['take']))+ if best['score'] < 7 and shooting:+ return Decision('wait', shot['id'], '已完成的版本不够好,等待其余版本。')if best['score'] >= 7:return Decision('choose', shot['id'], best['reason'], take=best['take'])if _retaken(shot):diff --git a/freevideo_engine/agent/production.py b/freevideo_engine/agent/production.pyindex ca20154..ce05deb 100644--- a/freevideo_engine/agent/production.py+++ b/freevideo_engine/agent/production.py@@ -118,11 +118,12 @@ def plan(request, *, fields=True):problems.extend(dict(path='/screenplay' + p['path'], message=_rule(p)) for p in error.problems)if fields:_fields(play, problems)- count = request.get('takes_per_shot', 1)- count_ok = _count(count, '/takes_per_shot', problems)director = request.get('director', 'agent')if director not in ('agent', 'builtin'):problems.append(dict(path='/director', message='must be "agent" or "builtin"'))+ # The built-in director judges takes as they arrive and withdraws the rest once one is chosen, so two cost little.+ count = request.get('takes_per_shot', 2 if director == 'builtin' else 1)+ count_ok = _count(count, '/takes_per_shot', problems)rows = play.get('shots', []) if isinstance(play, dict) else []total = 0if isinstance(rows, list):@@ -530,6 +531,22 @@ def resume(state, *, by, now):_commit(state, draft, now)+def _withdraw_others(row, chosen):+ """Stop the shot's other unfinished takes and unsent manual batches once one is chosen.++ Finished takes stay, so the choice can still change; automatic reconnects are not ours to drop.+ """+ for other in row['takes']:+ if other['take'] == chosen or other['stale'] or other['cancel_requested']:+ continue+ if other['state'] == 'paused':+ other['state'] = 'cancelled'+ other['cancel_requested'] = True+ elif other['state'] in ACTIVE:+ other['cancel_requested'] = True+ 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."""_editable(state, by)@@ -550,6 +567,7 @@ def choose(state, shot, take, *, by, reason=None, cascade=True, now):_commit(state, draft, now)returnrow['chosen'], row['chosen_by'] = take, by+ _withdraw_others(row, take)_refresh(draft)if by != 'user':affected = [dict(shot=old['id']) for old, child in zip(state['shots'], draft['shots'])diff --git a/freevideo_engine/agent/productions.py b/freevideo_engine/agent/productions.pyindex 6834548..9722bda 100644--- a/freevideo_engine/agent/productions.py+++ b/freevideo_engine/agent/productions.py@@ -21,7 +21,7 @@ import threadingimport timeimport uuid-from . import drama, production, schema, spec, errors, operation_receipts+from . import drama, production, schema, spec, errors, operation_receipts, take_qafrom .jobs import DONE, JobError, iso, parts_problemsfrom .forecast import generation_estimate@@ -173,6 +173,9 @@ class Productions:self._waiter_lock = threading.Lock()# gate(action, *, by, estimate_seconds, refs, question) raises when the user must approve first.self.gate = None+ # transcribe(path) -> heard text, optional; without it the QA does not compare dialogue.+ self.transcribe = None+ self._inspecting = set()self.load()jobs.parent_allowed = self.allows@@ -649,6 +652,7 @@ class Productions:for take, saved in zip(shot['takes'], internal['takes']):take['error'] = contextual(saved.get('error'))take['task'] = tasks.get(take['job'])+ take['qa'] = deepcopy(record.get('qa', {}).get(take['job']))if value['join'] is not None:ref = record['state']['current_join']join = next(j for j in record['state']['joins'] if j['ref'] == ref)@@ -884,6 +888,43 @@ class Productions:self._bump(draft) # Wake since/wait readers when the elapsed reminder appears or clears.if draft != record:self._save(draft)+ self._inspect_takes(identity)++ def _inspect_takes(self, identity):+ """Start the picture and sound check of each finished take that has none; it runs off the lock.++ Only the built-in director reads the result, so films run by an agent are left alone.+ """+ record = self._record(identity)+ if record['state']['director'] != 'builtin':+ return+ for shot in record['state']['shots']:+ for take in shot['takes']:+ job = take['job']+ if (take['state'] != 'succeeded' or take['stale'] or not take['library_id']+ or job in record.get('qa', {}) or (identity, job) in self._inspecting):+ continue+ self._inspecting.add((identity, job))+ lines = [row['line'] for row in shot.get('lines') or [] if row.get('line')]+ threading.Thread(target=self._inspect, daemon=True, args=(+ identity, job, take['library_id'], shot.get('seconds'), lines)).start()++ def _inspect(self, identity, job, library, seconds, lines):+ try:+ with self.jobs.cpu:+ result = take_qa.check(self.jobs.port.library_video(library), seconds=seconds,+ lines=lines, transcribe=self.transcribe)+ except Exception as error: # noqa: BLE001 - a failed check must not block the film; the judge sees it as unchecked+ logging.getLogger(__name__).warning('A take could not be checked (%s)', type(error).__name__)+ result = dict(error=type(error).__name__, problems=[], notes=[], ok=True)+ with self.changed:+ self._inspecting.discard((identity, job))+ if identity not in self.records:+ return+ draft = deepcopy(self._record(identity))+ draft.setdefault('qa', {})[job] = result+ self._bump(draft)+ self._save(draft)def _execute(self, identity, action):"""Carry out one action; True when it changed a child, a receipt or a tombstone."""diff --git a/freevideo_engine/agent/take_qa.py b/freevideo_engine/agent/take_qa.pynew file mode 100644index 0000000..0e2f7e2--- /dev/null+++ b/freevideo_engine/agent/take_qa.py@@ -0,0 +1,153 @@+"""Automatic checks on a finished take: picture, sound and dialogue.++The result is plain data stored next to the take. `problems` lists what makes a take unusable, `notes`+what is only worth a look; the director's judge drops takes with problems and mentions the notes.+"""+import difflib+import re++import numpy as np++from . import media++DURATION_TOLERANCE = 1.5 # s, against the shot's planned length+BLACK_LUMA = 26 # 0-255 mean luma of a black frame+BLACK_SECONDS = 0.3+BLACK_SPREAD = 10.0 # a dark but detailed scene is not a black frame+FREEZE_DIFF = 0.05 # 0-255 mean change between consecutive frames+FREEZE_SECONDS = 1.5+SILENT_DB = -45.0 # whole-take RMS below this is near silence+GAP_DB = -50.0 # 50 ms windows below this are a gap+GAP_SECONDS = 2.0+GAP_EDGE = 0.5 # a gap counts as "in the middle" this far from both ends+SPEECH_DB = -35.0+CLIP_PEAK = 0.999+LINE_MATCH = 0.6+ANALYSIS_WIDTH = 64+SAMPLE_RATE = 16000+WINDOW = 0.05+++def _words(text):+ return re.findall(r"[\w']+", str(text).lower())+++def _pictures(path):+ """Mean luma and a small gray frame for every video frame."""+ means, small, times = [], [], []+ with media._reading(media._file(path)) as container:+ stream = media._video_stream(container)+ for frame in container.decode(stream):+ height = max(2, round(ANALYSIS_WIDTH * frame.height / frame.width))+ gray = frame.reformat(width=ANALYSIS_WIDTH, height=height, format='gray').to_ndarray().astype(np.float32)+ means.append(float(gray.mean()))+ small.append(gray)+ times.append(float(frame.time) if frame.time is not None else len(times) / 24.0)+ return means, small, times+++def _samples(path):+ import av+ with media._reading(media._file(path)) as container:+ stream = next(iter(container.streams.audio), None)+ if stream is None:+ return np.zeros(0, np.float32)+ resampler = av.AudioResampler(format='flt', layout='mono', rate=SAMPLE_RATE)+ chunks = []+ for frame in container.decode(stream):+ for out in resampler.resample(frame):+ chunks.append(out.to_ndarray().reshape(-1))+ for out in resampler.resample(None):+ chunks.append(out.to_ndarray().reshape(-1))+ return np.concatenate(chunks).astype(np.float32) if chunks else np.zeros(0, np.float32)+++def _runs(flags, times, minimum):+ """Spans (start, end) where `flags` stays true for at least `minimum` seconds."""+ spans, start = [], None+ for index, flag in enumerate(flags):+ if flag and start is None:+ start = index+ if start is not None and (not flag or index == len(flags) - 1):+ last = index if flag else index - 1+ if times[last] - times[start] >= minimum:+ spans.append((round(times[start], 2), round(times[last], 2)))+ start = None+ return spans+++def _db(value):+ return float(20 * np.log10(max(float(value), 1e-9)))+++def check(path, *, seconds=None, size=None, lines=None, transcribe=None):+ """Inspect one take. `seconds` is the planned length, `size` the expected (width, height),+ `lines` the spoken lines the shot should contain and `transcribe(path)` returns the heard text."""+ problems, notes = [], []+ info = media.inspect(path)+ if size and (info['width'], info['height']) != tuple(size):+ problems.append('size %dx%d, expected %dx%d' % (info['width'], info['height'], *size))+ if seconds and abs(info['seconds'] - seconds) > DURATION_TOLERANCE:+ problems.append('duration %.1f s, planned %.1f s' % (info['seconds'], seconds))+ result = dict(width=info['width'], height=info['height'], seconds=round(info['seconds'], 2), audio=info['has_audio'])++ means, small, times = _pictures(path)+ black = _runs([m < BLACK_LUMA and float(g.std()) < BLACK_SPREAD for m, g in zip(means, small)], times, BLACK_SECONDS) if means else []+ flags = [False] * len(small)+ for index in range(1, len(small)):+ if float(np.abs(small[index] - small[index - 1]).mean()) <= FREEZE_DIFF:+ flags[index] = flags[index - 1] = True+ frozen = _runs(flags, times, 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))+ result.update(black=black, frozen=frozen)++ if not info['has_audio']:+ problems.append('no audio track')+ else:+ samples = _samples(path)+ if samples.size:+ rms, peak = float(np.sqrt(np.mean(samples ** 2))), float(np.abs(samples).max())+ result.update(rms_db=round(_db(rms), 1), peak=round(peak, 3))+ if _db(rms) < SILENT_DB:+ problems.append('audio nearly silent (%.0f dBFS)' % _db(rms))+ elif peak >= CLIP_PEAK:+ notes.append('audio clips')+ step = int(SAMPLE_RATE * WINDOW)+ count = samples.size // step+ levels = [_db(np.sqrt(np.mean(samples[i * step:(i + 1) * step] ** 2))) for i in range(count)]+ moments = [i * WINDOW for i in range(count)]+ if any(level > SPEECH_DB for level in levels):+ gaps = [(a, b) for a, b in _runs([level < GAP_DB for level in levels], moments, GAP_SECONDS)+ if a > GAP_EDGE and b < moments[-1] - GAP_EDGE]+ if gaps:+ notes.append('silent gap at %s' % ', '.join('%.1f-%.1f s' % g for g in gaps))+ result['gaps'] = gaps++ if lines and transcribe is not None and info['has_audio']:+ heard = _words(transcribe(path))+ missing = []+ for line in lines:+ wanted = _words(line)+ if not wanted:+ continue+ best = max([difflib.SequenceMatcher(None, wanted, heard[i:i + len(wanted) + 2]).ratio()+ for i in range(max(1, len(heard) - len(wanted) + 3))] or [0.0])+ if best < LINE_MATCH:+ missing.append(line)+ result['heard'] = ' '.join(heard)+ if missing:+ problems.append('line not heard: %s' % ' | '.join(missing))+ return dict(result, problems=problems, notes=notes, ok=not problems)+++def summary(qa):+ """One line for the judge's prompt."""+ if not qa:+ return ''+ if qa.get('error'):+ return 'QA unavailable'+ parts = qa['problems'] + qa['notes']+ return 'QA: ' + ('; '.join(parts) if parts else 'clean')