p3cyc's picture
Upload 78 files
26cba34 verified
Raw History Blame Contribute Delete
35.4 kB
from __future__ import annotations
import hashlib
import json
import logging
import time
from . import storage, project, recovery, hq, cache, continuity
from .native import NativeRunner
from .runtime.direct_core import apply_direct_latent_head
from .runtime.prefix_guard import restore_protected_prefix
from .preview import preview_scene
from .export.streaming import export_chain
from .version import VERSION
from .core.audio_transition import TRANSITION_KEY, normalize_settings, make_transition
from .runtime.last_frame import HANDOVER_KEY, METHOD as LAST_FRAME
LOG = logging.getLogger('LongForge')
GENERATE_ACTIONS = {'GENERATE NEXT', 'REGENERATE LAST', 'REGENERATE SELECTED', 'VARY SELECTED'}
def _has_active_audio_reference(media, use_references):
"""Whether this REF2VA call will actually present audio reference rows."""
if not use_references or not isinstance(media, dict):
return False
if media.get('use_reference_audio', True) is False:
return False
return any(
value is not None
for group in ('ref_audios', 'ref_video_audios')
for value in (media.get(group) or {}).values()
)
def _will_present_audio_reference(media, include_static):
"""Resolve bundles before loading continuation history.
Static audio obeys the reference policy. Follow-scenes audio is presented
on every scene, even when ordinary references are limited to scene one.
"""
if not isinstance(media, dict) or media.get('use_reference_audio', True) is False:
return False
from .references import prepare_media
from .audio_timeline import is_track
resolved = prepare_media(media, validate_audio=False)
if include_static and _has_active_audio_reference(resolved, True):
return True
return any(is_track(value) for value in resolved.get('ref_audios', {}).values())
def _meta_seed(meta):
sampling = ((meta or {}).get('provenance') or {}).get('sampling') or {}
value = sampling.get('actual_seed', sampling.get('seed'))
try:
return int(value)
except (TypeError, ValueError):
return None
def _saved_actual_seed(name, head, scene_index):
"""Seed stored with that scene when it was last saved."""
try:
_, meta = project.scene_take(name, head, scene_index)
except (TypeError, ValueError, OSError):
return None
return _meta_seed(meta)
def _next_seed(job, settings, name, index, previous_meta):
widget = int(settings['seed']) % (2**64)
if not settings.get('increment_seed'):
if job['action'] == 'VARY SELECTED' and index == job['start_cursor']:
saved = _saved_actual_seed(name, job['head'], index + 1)
return ((saved if saved is not None else widget) + 1) % (2**64)
if job['action'] in ('REGENERATE LAST', 'REGENERATE SELECTED') and index == job['start_cursor']:
saved = _saved_actual_seed(name, job['head'], index + 1)
return saved % (2**64) if saved is not None else widget
return widget
if job['action'] in ('REGENERATE LAST', 'REGENERATE SELECTED', 'VARY SELECTED') and index == job['start_cursor']:
saved = _saved_actual_seed(name, job['head'], index + 1)
if saved is not None:
return (saved + (1 if job['action'] == 'VARY SELECTED' else 0)) % (2**64)
prev = _meta_seed(previous_meta)
if prev is not None:
return (prev + 1) % (2**64)
return (widget + index) % (2**64)
def make_job(name, action, run_mode, story, selected_scene=1):
project.project_dir(name)
head = project.read_head(name)
if action == 'IMPORT VIDEO' and head:
raise ValueError('Import needs an empty project. Choose a new project name.')
if head is None and project.has_saved_takes(name) and action not in ('GENERATE NEXT', 'IMPORT VIDEO'):
raise ValueError('This project has saved takes without an active head. Click Recover project, or GENERATE NEXT to start a new film under the same name.')
cursor = (head or {}).get('cursor', 0)
if action == 'REGENERATE LAST':
if not head:
raise ValueError('No saved scene to regenerate')
cursor -= 1
if action in ('REGENERATE SELECTED', 'VARY SELECTED'):
if not head or not 1 <= int(selected_scene) <= head['cursor']:
raise ValueError('Select an already saved scene to regenerate')
cursor = int(selected_scene) - 1
reading = action in ('EXPORT FILM', 'PREVIEW SELECTED', 'SEAM LAB', 'IMPORT VIDEO')
if action == 'SEAM LAB' and (not head or head['cursor'] < 2):
raise ValueError('Generate at least two scenes before using Seam Lab.')
if not reading and cursor > len(story):
raise ValueError('The editor has fewer scenes than the saved film. Click “Open project” to load its scene list.')
if action == 'EXPORT FILM' and not head:
raise ValueError('Generate at least one scene before exporting')
if action == 'PREVIEW SELECTED' and (not head or not 1 <= int(selected_scene) <= head['cursor']):
raise ValueError('Select a saved scene to preview')
if reading:
indices = []
elif run_mode == 'ONE SCENE':
indices = list(range(cursor, min(cursor+1, len(story))))
else:
indices = list(range(cursor, len(story)))
# GENERATE NEXT never remakes saved scenes. A completed film is a no-op;
# remakes are explicit (REGENERATE / VARY) and earlier chains stay restorable.
saved_story = (head or {}).get('story') or [{}]
if indices and indices[0] == 0 and isinstance(saved_story[0], dict) and saved_story[0].get('imported'):
raise ValueError('Scene 1 is an imported source. Regenerate a continuation from Scene 2, or import a replacement into a new project.')
for index in indices:
if not story[index]['prompt'].strip():
raise ValueError(f'Scene {index+1} is empty. Write its prompt before running.')
LOG.info('LongForge %s · %s · scenes %s', VERSION, action, [i+1 for i in indices])
return {'name': name, 'action': action, 'head': head, 'indices': indices, 'story': story,
'start_cursor': cursor, 'selected_scene': int(selected_scene),
'vary_nonce': 0,
'story_hash': hashlib.sha256(json.dumps(story, ensure_ascii=False, sort_keys=True).encode()).hexdigest()}
def required_models(job, metadata_mode='RECOVERY'):
if job['action'] == 'IMPORT VIDEO':
return ['video_settings', 'source_video', 'video_vae', 'audio_vae']
if job['action'] == 'PREVIEW SELECTED':
from .preview import available_preview_paths
ref, _ = project.scene_take(job['name'], job['head'], job['selected_scene'])
return [] if available_preview_paths(ref, metadata_mode)['preview'].is_file() else ['video_vae', 'audio_vae']
if job['action'] in ('EXPORT FILM', 'SEAM LAB'):
return ['video_vae', 'audio_vae']
return ['model', 'clip', 'video_vae', 'audio_vae'] if job['indices'] else []
def _preflight_soft_queue(job, video):
"""Check every deterministic MANUAL boundary before any scene is generated."""
if (video.get('duration_mode', 'WINDOW FRAMES') == 'NEW SECONDS' or video.get('audio_continuity') != 'SOFT' or
str(video.get('continuity_mode', continuity.MANUAL)).upper() != continuity.MANUAL):
return
from .runtime.direct_core import resolve_context_frames
from .core.timeline import audio_latent_boundary
previous = (job.get('head') or {}).get('take')
if job['action'].startswith('REGENERATE') or job['action'] == 'VARY SELECTED':
previous = project.scene_take(job['name'], job['head'], job['start_cursor'])[0] if job['start_cursor'] else None
if previous:
timeline = storage.read_take_header(previous)['timeline']
end, available = timeline['end_frame'], timeline['end_frame'] - timeline['start_frame']
else:
end, available = None, 0
for index in job['indices']:
frames = int(video['frames'])
if end is None:
end = frames
else:
overlap = resolve_context_frames(video['overlap_frames'], available, frames)
try:
make_transition(end-overlap, overlap, video['audio_soft_steps'])
except ValueError as exc:
count = audio_latent_boundary(end) - audio_latent_boundary(end-overlap)
raise ValueError(f"Scene {index+1}: SOFT {video['audio_soft_steps']*25} ms needs a hard protected core, "
f"but {overlap}F overlap has only {count} audio tokens at this film position. "
"Use 22F overlap or SOFT 100 ms. No scene was generated by this run.") from exc
end += frames - overlap
available = frames
def preflight(job, video, settings, model=None, media=None):
warnings = []
if settings:
if float(settings.get('cfg', 1)) != 1.0:
warnings.append('H3 normally uses CFG 1. Other values can change audio/video timing.')
if float(settings.get('denoise', 1)) != 1.0:
warnings.append('Denoise below 1 can desync audio from video on continuation.')
manual_continuity = bool(
video and str(video.get('continuity_mode', continuity.MANUAL)).upper() == continuity.MANUAL
)
if manual_continuity and video.get('duration_mode', 'WINDOW FRAMES') == 'WINDOW FRAMES' and int(video.get('overlap_frames', 0)) >= int(video.get('frames', 1)):
raise ValueError('Overlap must be shorter than the scene length.')
if manual_continuity and int(video.get('overlap_frames', 0)) < 22:
warnings.append(
'5F overlap is the phase-safe minimum, but it can let motion or generated audio reset at a join. '
'Use 22F for normal continuity.'
)
if video:
_preflight_soft_queue(job, video)
if media and video and video.get('pipeline') != 'REF2VA':
from .audio_timeline import is_track
tracks = [key for key, value in (media.get('ref_audios') or {}).items() if is_track(value)]
if tracks:
raise ValueError('Follow scenes audio needs REF2VA.')
return warnings
@project.exclusive_operation
def run(job, video, settings, model=None, clip=None, video_vae=None, audio_vae=None, media=None,
preview=True, crf=18, repair_audio=True, repair_video=False, fade_edges=True,
encoding_speed='medium', runner=None, provenance=None, notify=None, status=None,
graph_snapshot=None, metadata_mode='RECOVERY', hq_settings=None, refiner_model=None,
api_prompt=None, render_node_id=None, diagnostic_wavs=False, seam_request='{}', refmods=None,
api_workflow=None, source_video=None, export_settings=None, interpolation_model=None):
runner = runner or NativeRunner()
head, name, timings = job['head'], job['name'], []
warnings = []
# One RGB image, scoped to this run and its connected VAE.
frame_cache = {}
def phase(label, scene=None):
if status:
status(label, scene)
try:
from .audio_timeline import cleanup_pcm_cache
cleanup_pcm_cache()
except Exception:
pass
if job['action'] == 'IMPORT VIDEO':
from .video_source import import_project
phase('Encoding source video')
head, info = import_project(job, video, source_video, video_vae, audio_vae, hq_settings, api_prompt, render_node_id)
if notify: notify(head, {'scene': 1, 'source_import': info}, None)
return {'project': name, 'head': head, 'preview': None, 'timings': [], 'kind': 'import', 'version': VERSION,
'summary': f"Imported {info['decoded_frames']/24:.2f}s. Add a prompt to Scene 2, then GENERATE NEXT."}
if job['action'] == 'SEAM LAB':
from .seam_lab import build
manifest = build(name, head, seam_request, video_vae, audio_vae, repair_audio,
repair_video, fade_edges, crf, encoding_speed, status)
return {'project': name, 'head': head, 'preview': None, 'timings': [],
'kind': 'seam_lab', 'version': VERSION, 'seam_lab': manifest,
'summary': f"Seam Lab: {len(manifest['joins'])} join preview(s) ready"}
if job['action'] == 'PREVIEW SELECTED':
from .preview import available_preview_paths
index = job['selected_scene']
phase('Preparing scene preview', index)
ref, meta = project.scene_take(name, head, index)
path = available_preview_paths(ref, metadata_mode)['preview']
if not path.is_file():
latent, meta, ref = storage.load_output_latent(ref)
path = preview_scene(latent, video_vae, audio_vae, ref, meta.get('context_frames', 0), crf, meta, metadata_mode)
return {'project': name, 'head': head, 'preview': str(path), 'timings': [],
'kind': 'preview', 'scene': index, 'version': VERSION,
'summary': f"Preview scene {index} · {meta.get('label', '')}"}
if job['action'] == 'EXPORT FILM':
started = time.perf_counter()
phase('Exporting film')
path, qa = export_chain(head['take'], video_vae, audio_vae, repair_audio, repair_video, crf,
encoding_speed=encoding_speed, fade_edges=fade_edges, status=status,
metadata_mode=metadata_mode, diagnostic_wavs=diagnostic_wavs, export_settings=export_settings, interpolation_model=interpolation_model)
broad_audio_joins = sum(bool(item.get('broad_level_jump')) for item in qa.get('audio_seams', []))
summary = f"Export: {qa['total_frames']/24:.2f}s · {len(qa['takes'])} scenes"
if diagnostic_wavs:
summary += ' · two lossless diagnostic WAVs saved beside MP4'
if broad_audio_joins:
summary += (
f" · warning: {broad_audio_joins} generated-audio level reset(s) remain; "
'regenerate those joins with 22F overlap'
)
recommendations = qa.get('recommendations') or []
scenes = sorted({int(item['join_to_scene']) for item in recommendations
if item.get('join_to_scene') is not None})
if scenes:
summary += ' · seam review: before scene(s) ' + ', '.join(map(str, scenes))
return {'project': name, 'head': head, 'preview': str(qa.get('browser_preview') or path), 'timings': [{'export_seconds': time.perf_counter()-started}],
'kind': 'export', 'export_file': str(path), 'version': VERSION,
'summary': summary, 'qa': qa}
if not job['indices']:
saved = int((head or {}).get('cursor', 0))
summary = (f'All {saved} scene(s) are saved; nothing was generated. Add a scene (+) to continue, '
'choose REGENERATE SELECTED or VARY SELECTED to remake one, or EXPORT FILM.'
if head else 'There is no scene to generate. Add a scene prompt first.')
return {'project': name, 'head': head, 'preview': storage.media_path((head or {}).get('preview')),
'timings': [], 'version': VERSION, 'kind': 'idle', 'summary': summary}
hq_mode = str((hq_settings or {}).get('mode', 'OFF')).upper()
if hq_mode == 'UPSCALE + REFINE' and refiner_model is None:
raise ValueError(
'UPSCALE + REFINE needs the clean refiner model input. Connect the shared '
'attention-patched H3 model before all LoRAs to Render & Export → refiner_model.'
)
video = normalize_settings(video)
warnings.extend(preflight(job, video, settings, model, media))
from . import refmods as refmod_support
refmod_config = refmod_support.settings(**{k:v for k,v in (refmods or {}).items() if k in refmod_support.FIELDS})
# Validate ALL queued selections before the first scene is generated.
refmod_plans = {i:refmod_support.plan(refmod_config, job['story'][i], i, video['pipeline'],
(media or {}).get('use_reference_audio', True)) for i in job['indices']}
refmod_session = refmod_support.Session()
refmod_session.validate(refmod_plans.values())
if (hq_mode == 'UPSCALE + REFINE' and refiner_model is model
and getattr(refiner_model, 'patches', None)):
warnings.append(
'The refiner uses the same patched model object as generation. Connect the clean '
'shared-attention branch before the LoRA loaders to avoid refining with Turbo/other LoRAs.'
)
from .core.duration import duration_plan
requested_video = dict(video)
previous_ref = (head or {}).get('take')
if job['action'].startswith('REGENERATE') or job['action'] == 'VARY SELECTED':
previous_ref = project.scene_take(name, head, job['start_cursor'])[0] if job['start_cursor'] else None
for index in job['indices']:
import comfy.model_management as mm
mm.throw_exception_if_processing_interrupted()
if not project.same_head(project.read_head(name), head):
raise RuntimeError("The project changed before this scene started. Open the project again and run from its current scene. No sampling was started.")
started = time.perf_counter()
phase('Reading saved context', index+1)
video = dict(requested_video)
plan_context = int(video['overlap_frames']) if previous_ref and video.get('duration_mode') == 'NEW SECONDS' else 0
video['frames'] = duration_plan(video, plan_context)['frames']
source = None
frame_handover = None
continuation_frame = None
window_start = 0
context = 0
requested_continuity = str(video.get('continuity_mode', continuity.MANUAL)).upper()
continuity_report = {
'mode': requested_continuity,
'selected_frames': 0,
'candidates': [],
'risk': 'FIRST SCENE',
'risk_score': None,
'video': None,
'audio': None,
'preserve_audio': bool(video['preserve_audio']),
'reason': 'first scene has no preceding latent context',
}
refs = not previous_ref or video['reference_policy'] == 'EVERY SCENE'
refmod_plan = refmod_plans[index]
refmod_audio = any(e['kind']=='audio' for e in refmod_plan['entries'])
effective_audio_history = int(video['audio_history_frames'])
if (previous_ref and video['pipeline'] == 'REF2VA' and video['preserve_audio']
and effective_audio_history > 0
and (_will_present_audio_reference(media, refs) or refmod_audio)):
# Native H3 currently cannot safely pack an audio-history keyframe
# together with REF2VA audio-reference rows. Keep the exact
# protected overlap, but omit only the optional older history so a
# known upstream row-count mismatch cannot reach the sampler.
effective_audio_history = 0
warnings.append(
f'Scene {index+1}: Extra audio history was automatically disabled because '
'native H3 cannot safely combine it with active REF2VA audio references. '
'Protected audio overlap remains enabled.'
)
LOG.warning(warnings[-1])
if previous_ref:
source_meta = storage.read_take_header(previous_ref)
saved_video = ((source_meta.get('provenance') or {}).get('video') or {})
if saved_video.get('width') and saved_video.get('height'):
if int(video['width']) != int(saved_video['width']) or int(video['height']) != int(saved_video['height']):
raise ValueError(
f"Resolution changed after reload: project is {saved_video['width']}×{saved_video['height']}, "
f"node is {video['width']}×{video['height']}. Open project (settings restore) or set the same size."
)
source_time = source_meta['timeline']
available = source_time['end_frame'] - source_time['start_frame']
from .runtime.direct_core import resolve_context_frames
continuity_mode = str(video.get('continuity_mode', continuity.MANUAL)).upper()
if continuity_mode == continuity.MANUAL:
context = resolve_context_frames(video['overlap_frames'], available, video['frames'])
probe = context
else:
# Optional audio history occupies the span immediately before
# the protected AV prefix, so reserve it before choosing the
# largest AUTO candidate that can be loaded safely.
context_available = available - (effective_audio_history if video['preserve_audio'] else 0)
probe = continuity.probe_frames(
continuity_mode, context_available, video['frames'], video['overlap_frames']
)
# Extra audio history belongs immediately before the protected AV
# prefix. Keep both spans so the history does not overlap or
# duplicate the prefix presented in the target latent.
audio_keep = probe + effective_audio_history if video['preserve_audio'] else 0
source, source_meta, previous_ref = storage.load_latent_tail(previous_ref, probe, audio_keep)
if continuity_mode == continuity.MANUAL:
continuity_report = continuity.manual_report(context, bool(video['preserve_audio']))
else:
continuity_report = continuity.choose_overlap(
source, video['frames'], continuity_mode, video['preserve_audio'],
max_context_frames=probe,
audio_soft_steps=video['audio_soft_steps'] if video['audio_continuity'] == 'SOFT' else None,
)
context = resolve_context_frames(
continuity_report['selected_frames'], available, video['frames']
)
source_time = source_meta['timeline']
window_start = source_time['end_frame'] - context
else:
source_meta = None
duration = duration_plan(requested_video, context)
video['frames'] = duration['frames']
if previous_ref and video.get('continuation_method') == LAST_FRAME:
from .runtime.last_frame import decode_source
phase('Decoding last base-video frame', index+1)
continuation_frame, frame_handover = decode_source(previous_ref, video_vae, context, frame_cache)
frame_cache.clear()
LOG.info('LAST FRAME: one RGB image from scene %s, source frame %s; guide at %s, hidden context %sF; audio %s',
index, frame_handover['source_frame'], frame_handover['guide_frame'], context, video['audio_continuity'])
if source is not None and video['audio_continuity'] == 'SOFT':
# This check belongs before prompt/reference conditioning, including AUTO.
make_transition(window_start, context, video['audio_soft_steps'])
scene_hq = hq.validate_chain(hq_settings, video['width'], video['height'], source_meta)
t_read = time.perf_counter()
seed = _next_seed(job, settings, name, index, source_meta if previous_ref else None)
item = job['story'][index]
snapshot = recovery.scene_snapshot(graph_snapshot, job, index, video, settings, seed, scene_hq) if recovery.enabled(metadata_mode) else None
scene_video = dict(
video,
_has_source=bool(previous_ref),
_is_last_scene=index == len(job['story'])-1,
_effective_overlap_frames=context,
)
phase('Preparing prompt and references', index+1)
from .references import scene_audio_references
scene_media, scene_refs, audio_windows = scene_audio_references(media, refs, video['pipeline'], window_start, window_start + video['frames'],
protected_audio_frames=context if video['preserve_audio'] else 0)
if any(w.get('padded_samples') for w in audio_windows):
warnings.append(f'Scene {index+1}: follow-scenes audio ended early and was padded with silence.')
if refmod_plan['entries'] or refmod_support.PROMPT_ALIAS.search(item['prompt']):
scene_media = dict(scene_media or {}, _refmods=refmod_plan, _refmod_session=refmod_session)
if continuation_frame is not None:
scene_media = dict(scene_media or {}, _continuation_frame=continuation_frame)
conditioning, target = runner.condition(clip, video_vae, audio_vae, item['prompt'], scene_video, scene_media, scene_refs)
overlap = 0
guide_protected = None
if source is not None:
if video.get('continuation_method', 'PROTECTED') == 'GUIDE':
from .runtime.tail_guide import prepare as prepare_guide
conditioning, target, guide_protected, overlap, _ = prepare_guide(
conditioning, target, source, context, video['preserve_audio'], effective_audio_history,
audio_continuity=video['audio_continuity'], audio_soft_steps=video['audio_soft_steps'])
else:
conditioning, target, overlap, _ = apply_direct_latent_head(
conditioning, target, source, context,
video['preserve_audio'], effective_audio_history,
audio_continuity=video['audio_continuity'], audio_soft_steps=video['audio_soft_steps'],
copy_video=video.get('continuation_method') != LAST_FRAME)
target[storage.PARENT_KEY] = previous_ref
target[storage.CONTEXT_KEY] = overlap
target[storage.PRESERVE_KEY] = video['preserve_audio']
if frame_handover is not None:
target[HANDOVER_KEY] = frame_handover
del source
t_cond = time.perf_counter()
phase('Generating scene', index+1)
scene_model = refmod_support.prepare_model(model, refmod_plan)
dynamic_refs = bool(refmod_plan['entries'] and refmod_plan.get('controls', {}).get('step_enabled'))
cache_token = f"{name}:{index+1}:{seed}:{time.monotonic_ns()}"
cache_preflight = cache.prepare_run(scene_model, cache_token, settings,
prompt=api_prompt, render_node_id=render_node_id,
workflow=api_workflow,
block_reason='RefMod Step Curve changes conditioning during sampling.' if dynamic_refs else None)
cache_report = None
try:
sampled = runner.sample(scene_model, conditioning, target, settings, seed)
except BaseException as exc:
cache.finish_run(scene_model, aborted=True)
if any(word in str(exc).lower() for word in ('size', 'shape', 'tensor', 'dimension')):
audio_enabled = (media or {}).get('use_reference_audio', True)
raise RuntimeError(f"Scene {index+1} ({video['pipeline']}): {exc}\n"
f"Reference audio: {'on' if audio_enabled else 'off'}; audio history: {video['audio_history_frames']} frames. "
"Please include the full traceback and workflow when reporting this shape error.") from exc
raise
cache_report = cache.finish_run(scene_model)
inactive_cache = cache_report if cache_report and not cache_report.get('active') else (
cache_preflight if cache_preflight and not cache_preflight.get('active') else None
)
if inactive_cache:
warning = f"Native Cache bypassed: {inactive_cache.get('reason')}"
if warning not in warnings:
warnings.append(warning)
t_sample = time.perf_counter()
result, guard = restore_protected_prefix(guide_protected if guide_protected is not None else target, sampled)
for key in (storage.PARENT_KEY, storage.CONTEXT_KEY, storage.PRESERVE_KEY, TRANSITION_KEY, HANDOVER_KEY):
if key in target:
result[key] = target[key]
if scene_hq['mode'] == 'OFF':
phase('Keeping native delivery', index+1)
elif scene_hq['mode'] == 'UPSCALE':
phase('Upscaling scene', index+1)
else:
phase('Upscaling and refining scene', index+1)
delivery, hq_report = hq.finish_video(result, conditioning, scene_hq, settings, seed, runner, refiner_model,
previous_ref=previous_ref, context_frames=overlap, video_vae=video_vae, scene_video=scene_video, media=scene_media)
if delivery is not None:
result[storage.DELIVERY_VIDEO_KEY] = delivery
t_hq = time.perf_counter()
phase('Saving scene', index+1)
diagnostics = {
'scene': index + 1,
'duration': duration,
'continuation_method': video.get('continuation_method', 'PROTECTED'),
'video_handover': frame_handover,
'actual_seed': seed,
'continuity': continuity_report,
'effective_overlap_frames': overlap,
'configured_overlap_frames': int(video['overlap_frames']),
'effective_audio_history_frames': effective_audio_history,
'audio_history_suppressed': effective_audio_history != int(video['audio_history_frames']),
'audio_continuity': video['audio_continuity'] if overlap else 'FIRST SCENE',
'audio_transition': result.get(TRANSITION_KEY),
'prefix_guard': guard,
'hq': hq_report,
'refmods': refmod_plan,
}
if cache_report:
diagnostics['native_cache'] = cache_report
record = {'prompt': item['prompt'], 'video': requested_video, 'sampling': dict(settings, actual_seed=seed),
'hq': scene_hq, 'hq_report': hq_report,
'prefix_guard': guard, 'effective_audio_history_frames': effective_audio_history,
'diagnostics': diagnostics,
'longforge_version': VERSION}
record['refmod_settings'] = refmod_config
# Source hashes identify exact saved content. Avoid copying each
# member's full metadata/description into the take for every copy.
record['refmods'] = dict(refmod_plan, entries=[{k:v for k,v in e.items() if k != 'metadata'}
for e in refmod_plan['entries']])
record['scene_refmods'] = item.get('refmods', {'mode':'INHERIT'})
if cache_report:
record['native_cache'] = cache_report
if snapshot:
record['recovery'] = snapshot
if audio_windows:
record['audio_reference_windows'] = audio_windows
head = project.commit(name, head, result, item['name'], index+1, job['story'], record, job['story_hash'])
t_save = time.perf_counter()
preview_path, preview_error = None, None
if preview:
phase('Preparing scene preview', index+1)
try:
def capture_base_frame(image):
frame_cache.clear()
frame_cache.update(source_sha256=head['take']['sha256'], image=image)
extra = {'capture_base_frame': capture_base_frame} if video.get('continuation_method') == LAST_FRAME else {}
path = preview_scene(result, video_vae, audio_vae, head['take'], overlap, metadata_mode=metadata_mode, **extra)
preview_path = str(path)
head = project.attach_preview(name, head, storage.media_reference(path))
except mm.InterruptProcessingException:
# The take is committed, but cancellation must still stop this
# queue rather than being reported as an ordinary preview error.
raise
except Exception as exc:
preview_error = f'{type(exc).__name__}: {exc}'
LOG.warning('Scene saved; preview failed: %s', preview_error)
end = time.perf_counter()
row = {'scene': index+1, 'seed': seed, 'source_read_seconds': t_read-started, 'conditioning_seconds': t_cond-t_read,
'sampling_seconds': t_sample-t_cond, 'hq_seconds': t_hq-t_sample,
'save_seconds': t_save-t_hq, 'preview_seconds': end-t_save,
'hq_report': hq_report,
'continuity': continuity_report,
'diagnostics': diagnostics,
'effective_audio_history_frames': effective_audio_history,
'audio_history_suppressed': effective_audio_history != int(video['audio_history_frames'])}
if cache_report:
row['native_cache'] = cache_report
if audio_windows:
row['audio_reference_windows'] = audio_windows
if preview_error:
row['preview_error'] = preview_error
timings.append(row)
LOG.info('[LongForge %s] scene %s · source %.2fs · conditioning %.2fs · sampler %.2fs · HQ %.2fs · save %.2fs · preview %.2fs',
VERSION, index+1, *[row[k] for k in ['source_read_seconds', 'conditioning_seconds', 'sampling_seconds', 'hq_seconds', 'save_seconds', 'preview_seconds']])
if notify:
notify(head, row, preview_path)
previous_ref = head['take']
del conditioning, target, sampled, result
summary = f"Saved scene {head['cursor']}/{len(job['story'])} · film {head['end_frame']/24:.2f}s"
if job['action'] == 'VARY SELECTED':
summary += f" · seed {timings[-1]['seed']} (previous + 1)"
elif job['action'].startswith('REGENERATE'):
summary += f" · seed {timings[-1]['seed']} (same)"
if timings[-1].get('hq_report') and scene_hq['mode'] != 'OFF':
summary += f" · {timings[-1]['hq_report']}"
last_cache = timings[-1].get('native_cache')
if last_cache and last_cache.get('active'):
profile_label = last_cache['profile'].lower()
if last_cache.get('profile') == 'AUTO':
profile_label += '→' + str(last_cache.get('effective_profile', 'unknown')).lower()
summary += (
f" · cache {profile_label} reused "
f"{last_cache['reused']}/{last_cache['calls']} calls ({last_cache['reuse_percent']:.1f}%)"
)
saved = last_cache.get('time_saved_seconds') or 0
if saved:
summary += f" · ~{saved:.0f}s potential forward time avoided (estimate)"
if any(w['padded_samples'] for w in timings[-1].get('audio_reference_windows', [])):
summary += ' · audio reference tail padded with silence'
if timings[-1].get('audio_history_suppressed'):
summary += ' · Extra audio history disabled for REF2VA audio compatibility'
if timings[-1].get('preview_error'):
summary += ' · preview failed; scene is saved'
selected_continuity = timings[-1].get('continuity') or {}
if selected_continuity.get('mode'):
summary += (
f" · continuity {str(selected_continuity['mode']).lower()} "
f"{int(selected_continuity.get('selected_frames', 0))}F"
)
if warnings:
summary += ' · ' + warnings[-1]
return {'project': name, 'head': head, 'preview': storage.media_path(head.get('preview')),
'timings': timings, 'summary': summary, 'warnings': warnings, 'version': VERSION}