diff --git a/__init__.py b/__init__.py index d4ee660f..c4ae5c69 100644 --- a/__init__.py +++ b/__init__.py @@ -30,6 +30,9 @@ async def comfy_entrypoint(): logging.warning('[FreeVideo] Chain routes not registered: %s', error) from .freevideo_engine.comfy_upload import register register() + # A work read back as a generate request (read only; the page does not ask for it yet). + from .freevideo_engine.restore import register as restore_routes + restore_routes() from .freevideo_engine.comfy_setup import register as setup_routes setup_routes() from .freevideo_engine.prompt_vlm.service import register as prompt_routes @@ -66,6 +69,8 @@ async def comfy_entrypoint(): update_routes() from .freevideo_engine.reload_keep import register as reload_keep_routes reload_keep_routes() + from .freevideo_engine.user_store import register as user_store_routes + user_store_routes() from .freevideo_engine.comfy_library import register as library_routes library_routes() from .freevideo_engine.comfy_editor import register as editor_routes diff --git a/freevideo_engine/access_proxy.py b/freevideo_engine/access_proxy.py index 94535ccd..5c559bb4 100644 --- a/freevideo_engine/access_proxy.py +++ b/freevideo_engine/access_proxy.py @@ -14,6 +14,7 @@ import math import time import ipaddress +import logging import os import re from pathlib import Path @@ -275,9 +276,19 @@ async def forward(request): response.content_length = reply.content_length browser_headers(response, request) await response.prepare(request) - async for chunk in reply.content.iter_chunked(1 << 16): - await response.write(chunk) - await response.write_eof() + try: + async for chunk in reply.content.iter_chunked(1 << 16): + await response.write(chunk) + await response.write_eof() + except ConnectionResetError: + # The browser went away mid-way (a closed tab, a video seeking elsewhere): nothing went wrong. + pass + except (client_exceptions.ClientPayloadError, client_exceptions.ServerDisconnectedError) as error: + # ComfyUI stopped in the middle of its answer. The status has been sent, so dropping the connection is + # how the browser learns the answer is incomplete, rather than taking a cut-off file as whole. + logging.getLogger(__name__).warning('[FreeVideo] An answer from ComfyUI ended early (%s).', type(error).__name__) + if request.transport is not None: + request.transport.abort() return response except client_exceptions.ClientConnectorError: return web.json_response(dict(error='ComfyUI is not answering yet.'), status=502) diff --git a/freevideo_engine/agent/builtin_director.py b/freevideo_engine/agent/builtin_director.py index 0d84486e..735d6366 100644 --- a/freevideo_engine/agent/builtin_director.py +++ b/freevideo_engine/agent/builtin_director.py @@ -357,6 +357,11 @@ def _take_count(shot): return max(1, min(8, sum(t['generation'] == first for t in shot['takes']))) +# What the director says about a choice is read by the connected agent and the log, as the rest of the agent's +# interface is: in English. The model writes its reason for a take in English, in one sentence of this length. +REASON_LIMIT = 120 + + def judge(shot_view, sheets, *, ask): """Score all selectable takes; invalid/missing evidence leaves a human choice. @@ -366,22 +371,22 @@ def judge(shot_view, sheets, *, ask): """ shot = shot_view if shot.get('chosen_by') == 'user' or shot.get('chosen') is not None: - return Decision('keep', shot['id'], '保留已选定的版本。') + return Decision('keep', shot['id'], 'The chosen take stays.') shooting = shot.get('state') in ('waiting', 'shooting') - uncertain = Decision('ask_user', shot['id'], '拿不准,请挑一版。') + uncertain = Decision('ask_user', shot['id'], 'No take is clearly best; the user picks one.') 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'], '等待这一镜的各版完成并质检。') + return Decision('wait', shot['id'], 'Waiting for every take of this shot to finish and be checked.') # 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: if shooting: - return Decision('wait', shot['id'], '已完成的版本没有通过质检,等待其余版本。') + return Decision('wait', shot['id'], 'The finished takes failed the check; waiting for the others.') 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'], '各版都没有通过质检。', + return Decision('reshoot', shot['id'], 'No take passed the check.', note=('上一次的问题:' + faults)[:300], takes=_take_count(shot)) try: rows = sheets['takes'] @@ -395,14 +400,14 @@ def judge(shot_view, sheets, *, ask): for start in range(0, len(numbers), batch_size): batch = numbers[start:start + batch_size] rating = _object(dict(take=dict(type='integer', enum=batch), score=dict(type='number', minimum=0, maximum=10), - reason=_string(30), note=_string(300), captions=dict(type='boolean')), + reason=_string(REASON_LIMIT), note=_string(300), captions=dict(type='boolean')), ('take', 'score', 'reason', 'note', 'captions')) schema = _object(dict(ratings=dict(type='array', minItems=len(batch), maxItems=len(batch), items=rating)), ('ratings',)) - prompt = ('评价这一镜的每个版本:0–10 分,reason 用不超过30字的中文指出具体优点或问题' - '(多余的字、人物变形、和描述不符等);note 给下一次生成能用的具体修正。' + prompt = ('评价这一镜的每个版本:0–10 分;reason 用一句英文写出具体的优点或问题' + '(多余的字、人物变形、和描述不符等),%d 个字符以内;note 给下一次生成能用的具体修正。' 'captions 表示有叠加字幕/文字,场景内真实招牌不算。声音由自动质检评价,这里不评价。' - '\n镜头描述:' + _dump({k: shot[k] for k in ('screenplay', 'characters', 'style', 'captions') if k in shot}) + '\n镜头描述:' % REASON_LIMIT + _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')) @@ -412,17 +417,17 @@ def judge(shot_view, sheets, *, ask): return uncertain ratings.extend(reply['ratings']) for row in ratings: - spec._text(row['reason'], '/reason', 30) + spec._text(row['reason'], '/reason', REASON_LIMIT) spec._text(row['note'], '/note', 300) 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'], '已完成的版本不够好,等待其余版本。') + return Decision('wait', shot['id'], 'The finished takes are not good enough; waiting for the others.') if best['score'] >= 7: return Decision('choose', shot['id'], best['reason'], take=best['take']) if _retaken(shot): - return Decision('choose', shot['id'], '重拍后仍不理想:' + best['reason'], take=best['take']) + return Decision('choose', shot['id'], 'Still not good after a reshoot: ' + best['reason'], take=best['take']) return Decision('reshoot', shot['id'], best['reason'], note=best['note'], takes=_take_count(shot)) except (KeyError, TypeError, ValueError): return uncertain @@ -559,7 +564,7 @@ def _with_stitch(tools, production_id, shot, sheets, decision, ask): if pieces is None: 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]), parts + return replace(decision, take=parts[-1]['take'], reason=(decision.reason + '; joined from the best take of each cut')[:300]), parts def run(tools, production_id, *, ask, stop, wait=25): @@ -591,7 +596,7 @@ def run(tools, production_id, *, ask, stop, wait=25): chosen = dict(snapshot) # 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='每镜已选定,开始接成影片。') + yield dict(shot=None, action='finish', reason='Every shot has its take; joining the film.') return if action not in ('choose', 'reshoot'): continue @@ -654,12 +659,12 @@ def run(tools, production_id, *, ask, stop, wait=25): conflicts += 1 errors, since = 0, None if conflicts >= 5: - yield dict(shot=None, action='error', reason='多次和已有的选择冲突,已停止:' + code) + yield dict(shot=None, action='error', reason='Stopped after repeated conflicts with choices already made: ' + code) return continue errors += 1 since = None if errors >= 3: label = code if isinstance(code, str) and re.fullmatch(r'[a-z_]{1,80}', code) else type(error).__name__ - yield dict(shot=None, action='error', reason='连续三次操作失败,已停止:' + label) + yield dict(shot=None, action='error', reason='Stopped after three failed operations in a row: ' + label) return diff --git a/freevideo_engine/agent/editor_runtime.py b/freevideo_engine/agent/editor_runtime.py index 456783fb..02b1cac4 100644 --- a/freevideo_engine/agent/editor_runtime.py +++ b/freevideo_engine/agent/editor_runtime.py @@ -18,7 +18,7 @@ # module still loading is reached only through a namespace import. MODULES = ('chain_rules', 'editor_picture_fields', 'editor_transport_model', 'editor_audio_model', 'editor_speed_model', 'editor_text_model', 'editor_model', 'editor_room', 'editor_actions', 'editor_generation', 'sampling_effort', - 'chain_support', 'editor_store') + 'chain_support', 'random_id', 'editor_store') TIME_LIMIT = 5.0 MEMORY_LIMIT = 256 * 2**20 STACK_LIMIT = 4 * 2**20 diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.py index a5012f26..f2562a5c 100644 --- a/freevideo_engine/agent/jobs.py +++ b/freevideo_engine/agent/jobs.py @@ -1411,12 +1411,18 @@ def run_again(self, identity): replace(row, candidate) return row - def queue_view(self): - """Describe ownership/order without exposing studio workflows or prompts.""" + def queue_view(self, *, wait=True): + """Describe ownership/order without exposing studio workflows or prompts. + + With wait=False the answer is None at once while another thread holds the chain runner (starting a chain + writes its receipts to disk under that lock), instead of waiting for it. + """ runner = self.port.chain_runner() entries, chains, prompts = [], [], {} if runner is not None: - with runner.lock: + if not runner.lock.acquire(blocking=wait): + return None + try: order = runner.active_ids() + runner.queue order += [r['id'] for r in runner.records.values() if r['id'] not in order] records = [runner.records[identity] for identity in dict.fromkeys(order)] @@ -1430,6 +1436,8 @@ def queue_view(self): for block in record['blocks']: if block['prompt_id'] and block['state'] in ('queued', 'running'): prompts[block['prompt_id']] = (record['id'], entry) + finally: + runner.lock.release() for row in self.active(): if row.get('comfy'): prompts[row['comfy']['prompt_id']] = (row['id'], dict(owner='agent', job_id=row['id'], state=row['status'])) @@ -1457,8 +1465,12 @@ def queue_view(self): def queue_note(self, row): """Where a waiting generation stands behind the work holding the GPU, and what a client does meanwhile.""" + # The note only tells a client where it stands, so a status read never waits for it: while another job holds the + # chain runner to write its receipts, this read goes without the note and the next read carries it. try: - queue = self.queue_view() + queue = self.queue_view(wait=False) + if queue is None: + return {} ahead = queue['ahead'].get(row['id']) if not ahead or not ahead['count']: return {} diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py index a0503c2a..32852d1f 100644 --- a/freevideo_engine/agent/routes.py +++ b/freevideo_engine/agent/routes.py @@ -312,15 +312,18 @@ def capabilities(port, jobs): def plan(port, value, jobs=None): - from ..two_pass import plan as sampling_plan + from ..two_pass import plan as sampling_plan, sampling_canvas from ..geometry import geometry spec = specs.normalize(value, port=port) result = dict(spec={k: v for k, v in spec.items() if k != 'depends_on'}, warnings=[]) if spec['kind'] != 'generate' or spec.get('refine_from'): return result - from .jobs import continuation_problems, cut_problems, middle_problems, part_prompt_problems, parts_problems - problems = (continuation_problems(spec) + cut_problems(spec, spec['seconds']) + middle_problems(spec) - + part_prompt_problems(spec)) + from .jobs import (continuation_problems, cut_problems, middle_problems, original_audio_problems, part_prompt_problems, + parts_problems) + # First, as on submit: an audio file used as it is replaces the seconds with its own length for every later check. + problems = original_audio_problems(spec, port.input_root) + problems += (continuation_problems(spec) + cut_problems(spec, spec['seconds']) + middle_problems(spec) + + part_prompt_problems(spec)) if jobs is not None: problems += parts_problems(spec, jobs.port.chain_runner(), work=jobs.continued_work(spec), planned=jobs.planned_parts(spec)) @@ -328,14 +331,18 @@ def plan(port, value, jobs=None): problems += parts_problems(spec, None) if problems: raise specs.SpecError(problems) + result['spec'] = {k: v for k, v in spec.items() if k != 'depends_on'} if jobs is not None: jobs.require_continuation(spec) if spec.get('continue_from') and not jobs.continuation_ready(): from .jobs import continuation_unavailable raise continuation_unavailable() canvas = geometry(spec['width'], spec['height'], seconds=spec['seconds']) - passes = sampling_plan(canvas, spec['two_pass'], spec['task'], base_steps=spec['base_steps'], - refine_steps=spec['refine_steps']) + # What the job will sample, decided as the generation decides it: a preview keeps the requested canvas and its + # half-size first pass; a small size is rendered larger; the factor is the one the job's graph carries. + sampled, _ = sampling_canvas(canvas, staged=spec['preview']) + passes = sampling_plan(sampled, spec['two_pass'], spec['task'], base_steps=spec['base_steps'], + refine_steps=spec['refine_steps'], staged=spec['preview'], scale=specs.upscale_factor(spec)) result['geometry'] = {k: canvas[k] for k in ('width', 'height', 'frames', 'seconds', 'fps', 'latent_frames')} result['sampling'] = dict(two_pass=passes['enabled'], total_steps=passes['total_steps'], first_pass=passes.get('first'), second_pass=passes.get('second') if passes['enabled'] else None) diff --git a/freevideo_engine/agent/spec.py b/freevideo_engine/agent/spec.py index 12f76103..199b746b 100644 --- a/freevideo_engine/agent/spec.py +++ b/freevideo_engine/agent/spec.py @@ -364,6 +364,12 @@ def normalize(value, *, port=None): return result +def upscale_factor(spec): + """The learned upscale factor a generate spec is sampled with: its level's factor for two passes; 2 for one pass + and for a preview, which stays the quick half-size first pass. The job's graph and its plan both read it here.""" + return spec.get('upscale_factor', 2) if spec['two_pass'] and not spec['preview'] else 2 + + def comfy_prompt(spec, node, *, prompt, assets, refine_from=''): """The ComfyUI API-format graph for one generate job; media are files in ComfyUI input.""" from ..lora_triggers import apply_triggers @@ -377,8 +383,8 @@ def comfy_prompt(spec, node, *, prompt, assets, refine_from=''): inputs['first_frame_reference'] = True if spec.get('step_cache'): inputs['step_cache'] = spec['step_cache'] - if spec.get('upscale_factor', 2) != 2 and spec['two_pass'] and not spec['preview']: - inputs['upscale_factor'] = '%g' % spec['upscale_factor'] + if upscale_factor(spec) != 2: + inputs['upscale_factor'] = '%g' % upscale_factor(spec) graph = {node: {'class_type': 'FreeVideoGenerate', 'inputs': inputs, '_meta': {'title': 'FreeVideo · ' + (spec.get('label') or 'Agent job')}}} if assets: @@ -400,3 +406,9 @@ def upscale_prompt(node, preview_video): two_pass=True, base_steps=8, refine_steps=3, force_regenerate=False, preview=False, refine_from=preview_video) return {node: {'class_type': 'FreeVideoGenerate', 'inputs': inputs, '_meta': {'title': 'FreeVideo · Second pass'}}} + + +def from_comfy(source, *, resolve=None): + """The reverse of comfy_prompt: a generate request from an old workflow or a video's tags (agent/spec_comfy.py).""" + from .spec_comfy import from_comfy as read + return read(source, resolve=resolve) diff --git a/freevideo_engine/agent/spec_comfy.py b/freevideo_engine/agent/spec_comfy.py new file mode 100644 index 00000000..b0cf3dec --- /dev/null +++ b/freevideo_engine/agent/spec_comfy.py @@ -0,0 +1,399 @@ +"""Old work back into a request: a FreeVideo graph from ComfyUI read as a generate request. + +The inverse of spec.comfy_prompt. It reads what an old workflow file or a video's `prompt`/`workflow` tags hold: +the API prompt ComfyUI ran (exact inputs), else the workflow as the page saved it (values by widget position). The +generator's own inputs, its FreeVideoMedia and FreeVideoLoRAStack nodes, and LoadImage pictures are understood; +a generator fed by any other node (a community node, say) is not guessed at: the caller says to open it in ComfyUI. +""" +import json + +from . import schema as contract +from .spec import QUALITY, SpecError, fail, sampling +from ..workflow_repairs import repair_inputs + +GENERATOR = 'FreeVideoGenerate' +# Today's FreeVideoGenerate widgets in order, as a saved workflow holds them: a control_after_generate after the seed, +# then the page's three panel values after the last widget. An older save is read by the same positions (as the page +# does), and workflow_repairs resets what lands on a newer widget. tests/test_spec_from_comfy.py keeps this equal to +# the node. Kept here only: nothing else reads a workflow by position. +WIDGETS = ('text', 'width', 'height', 'seconds', 'seed', 'control_after_generate', 'two_pass', 'base_steps', + 'refine_steps', 'force_regenerate', 'preview', 'refine_from', 'continue_from', 'frames', + 'first_frame_reference', 'voice_reference', 'hide_tail', 'step_cache', 'upscale_factor', 'allow_empty_prompt', + 'upscale_from', 'upscale_to', 'fast_mode') +MEDIA_WIDGETS = ('assets', 'audio_use') +LORA_WIDGETS = ('adapters',) +IMAGE_WIDGETS = ('image',) +PRIMITIVES = {'PrimitiveNode', 'PrimitiveString', 'PrimitiveStringMultiline', 'PrimitiveInt', 'PrimitiveFloat', + 'PrimitiveBoolean'} +# Changes whenever what a request or its notes hold for the same graph changes; every result carries it. +FROM_COMFY_VERSION = 2 +OPEN_IN_COMFY = ('This workflow uses nodes that FreeVideo cannot read. Open it in Nodes.', + '这个工作流用到了 FreeVideo 无法读取的节点,请在节点视图中打开。') + + +class OpenInComfy(SpecError): + """The graph needs ComfyUI: `nodes` names what FreeVideo could not read.""" + def __init__(self, nodes): + super().__init__(contract.diagnostic('/', OPEN_IN_COMFY[0], None)) + self.nodes = sorted(set(nodes)) + self.message_zh = OPEN_IN_COMFY[1] + + +def _link(value): + return isinstance(value, list) and len(value) == 2 and isinstance(value[0], (str, int)) + + +def api_graph(source): + """{id: {class_type, inputs}} from an API prompt, a saved workflow, or a video's {prompt, workflow} tags.""" + if isinstance(source, str): + source = json.loads(source) + if not isinstance(source, dict): + fail('/', 'a ComfyUI prompt or workflow (a JSON object)') + if isinstance(source.get('prompt'), (dict, str)) and source['prompt']: + return api_graph(source['prompt']) + if isinstance(source.get('workflow'), (dict, str)) and source['workflow']: + return api_graph(source['workflow']) + if isinstance(source.get('nodes'), list): + return _from_workflow(source) + if source and all(isinstance(node, dict) and 'class_type' in node for node in source.values()): + return {str(key): node for key, node in source.items()} + fail('/', 'a ComfyUI prompt or workflow with a FreeVideo Generate node') + + +def _from_workflow(workflow): + # links: [id, from_node, from_slot, to_node, to_slot, type] + links = {row[0]: [str(row[1]), row[2]] for row in workflow.get('links') or [] if isinstance(row, list) and len(row) >= 3} + graph = {} + for node in workflow['nodes']: + kind, values = node.get('type'), node.get('widgets_values') + names = {GENERATOR: WIDGETS, 'FreeVideoMedia': MEDIA_WIDGETS, 'FreeVideoLoRAStack': LORA_WIDGETS, + 'LoadImage': IMAGE_WIDGETS}.get(kind) + inputs = {} + if isinstance(values, list): + if names: + inputs.update((name, value) for name, value in zip(names, values) if name != 'control_after_generate') + elif kind in PRIMITIVES and values: + inputs['value'] = values[0] + elif isinstance(values, dict): + inputs.update(values) + for slot in node.get('inputs') or []: + if isinstance(slot, dict) and slot.get('link') in links: + inputs[slot.get('name')] = links[slot['link']] + graph[str(node.get('id'))] = {'class_type': kind, 'inputs': inputs} + return graph + + +def _properties(source): + """{node id: properties} of the saved workflow a source holds (a workflow file, or a video's workflow tag). + + The API prompt ComfyUI ran has no properties; its node ids are the workflow's, so both name the same nodes.""" + if isinstance(source, str): + try: + source = json.loads(source) + except ValueError: + return {} + if not isinstance(source, dict): + return {} + workflow = source.get('workflow') if 'workflow' in source else source + if isinstance(workflow, str): + try: + workflow = json.loads(workflow) + except ValueError: + return {} + if not isinstance(workflow, dict) or not isinstance(workflow.get('nodes'), list): + return {} + return {str(node.get('id')): node['properties'] for node in workflow['nodes'] + if isinstance(node, dict) and isinstance(node.get('properties'), dict)} + + +def _text(value): + return value if isinstance(value, str) and value else None + + +def _number(value): + return value if isinstance(value, (int, float)) and not isinstance(value, bool) else None + + +def _page_notes(generator, media, prompt): + """What the page kept on the nodes (node properties) that a generate request has no field for, as notes. + + A property of a shape the page never wrote is noted as unreadable, never guessed at. The request itself is built + from the generator's values alone: these notes say where it differs from what the page would have made.""" + notes, unreadable = [], [] + versions = generator.get('freevideo_prompt_versions') + if isinstance(versions, dict) and isinstance(versions.get('original'), str) and isinstance(versions.get('rewritten'), str): + # The text box holds the selected version (the request's prompt); the other one is kept here. + selected = 'rewritten' if versions.get('selected') == 'rewritten' and versions.get('useOriginal') is not True else 'original' + note = dict(selected=selected, original=versions['original'], rewritten=versions['rewritten'], + enhance=versions.get('enabled') is True) + # A rewrite shown in short goes in its full sections while the box still holds that short text. + sections = _text(versions.get('model' if selected == 'rewritten' else 'originalModel')) + if sections and versions[selected] == prompt: + note['sections'] = sections + # The page keeps this on every generator; with no rewrite and the box as it says, there is nothing else to keep. + if note['enhance'] or note['rewritten'] or sections or versions[selected] != prompt: + notes.append(dict(prompt_versions=note)) + elif versions is not None: + unreadable.append('freevideo_prompt_versions') + + swap = media.get('freevideo_replace_person') + if isinstance(swap, dict): + if swap.get('on') is True: + people = swap.get('people') if isinstance(swap.get('people'), list) else [swap.get('person')] + source = swap.get('source') if isinstance(swap.get('source'), dict) else {} + notes.append(dict(replace_person=dict( + people=[row['file'] for row in people if isinstance(row, dict) and _text(row.get('file'))][:2], + source=_text(source.get('file')), keep_sound=swap.get('keepSound') is True and source.get('audio') is True))) + elif swap is not None: + unreadable.append('freevideo_replace_person') + + extend = generator.get('freevideo_extend') + if isinstance(extend, dict) and isinstance(extend.get('source'), dict): + notes.append(dict(extend=dict(video=_text(extend['source'].get('video')), work=_text(extend['source'].get('id'))))) + elif extend is not None: + unreadable.append('freevideo_extend') + chain = generator.get('freevideo_chain') + if isinstance(chain, dict) and _text(chain.get('id')): + notes.append(dict(chain=dict(id=chain['id']))) + elif chain is not None: + unreadable.append('freevideo_chain') + + # Length: the box holds at most 60 s; a longer video, one run or several parts, is the page's own plan. + length = {} + for key, name, read in (('seconds', 'freevideo_seconds', _number), ('single', 'freevideo_single', lambda v: v if isinstance(v, bool) else None), + ('block_seconds', 'freevideo_block_seconds', _number), ('seconds_before_audio', 'freevideo_seconds_before_audio', _number)): + if name in generator: + value = read(generator[name]) + if value is None: + unreadable.append(name) + else: + length[key] = value + if length: + notes.append(dict(length=length)) + + batch = {} + for key, name, read in (('run_mode', 'freevideo_run_mode', lambda v: v if v in ('single', 'batch', 'loop') else None), + ('count', 'freevideo_batch_count', lambda v: v if isinstance(v, int) and not isinstance(v, bool) else None), + ('lines', 'freevideo_batch_lines', lambda v: v if isinstance(v, bool) else None)): + if name in generator: + value = read(generator[name]) + if value is None: + unreadable.append(name) + else: + batch[key] = value + if batch: + notes.append(dict(batch=batch)) + + # The size buttons: the request keeps the exact width and height; these only choose a button again. + layout = {} + if 'freevideo_aspect' in generator: + if isinstance(generator['freevideo_aspect'], str): + layout['aspect'] = generator['freevideo_aspect'] + else: + unreadable.append('freevideo_aspect') + if 'freevideo_pixels' in generator: + if _number(generator['freevideo_pixels']) is not None: + layout['megapixels'] = generator['freevideo_pixels'] + else: + unreadable.append('freevideo_pixels') + if layout: + notes.append(dict(layout=layout)) + if unreadable: + notes.append(dict(unreadable=unreadable)) + return notes + + +def _value(graph, value, strange): + """A literal, or the value of a primitive it is linked to; anything else is noted as unreadable.""" + if not _link(value): + return value + node = graph.get(str(value[0])) or {} + if node.get('class_type') in PRIMITIVES and 'value' in node.get('inputs', {}): + return node['inputs']['value'] + strange.append(node.get('class_type') or 'missing node') + return None + + +def _rows(text): + try: + rows = json.loads(text) if isinstance(text, str) and text.strip() else text or [] + except ValueError: + return [] + return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else [] + + +def _picture(graph, link, strange): + """The file a LoadImage names; '' when it names none (listed as missing), None for any other node.""" + node = graph.get(str(link[0])) or {} + if node.get('class_type') == 'LoadImage': + image = node['inputs'].get('image') + return image if isinstance(image, str) and image else '' + strange.append(node.get('class_type') or 'missing node') + return None + + +def _quality(two_pass, base, refine, cache, factor): + """The level whose own plan this is, else None (the steps are sent as they are). + + A preview's graph carries no upscale factor (it has no second pass), so levels that differ only in it read as the + first of them: the preview itself is the same.""" + for name in QUALITY: + planned = sampling({'quality': name}) + if (planned['two_pass'], planned['base_steps'], planned['refine_steps'], planned.get('step_cache'), + planned.get('upscale_factor', 2)) == (two_pass, base, refine, cache, factor): + return name + return None + + +def _strip_triggers(prompt, loras): + """comfy_prompt puts each LoRA's trigger words in front of the prompt; the request holds the prompt without them.""" + try: + from ..lora_triggers import get_trigger_words + except Exception: # noqa: BLE001 - no LoRA folders here: nothing was added + return prompt + for row in reversed(loras): + if not row.get('enabled', True) or row.get('strength', 1.) == 0: + continue + try: + words = get_trigger_words(row['name']) + except Exception: # noqa: BLE001 - an unreadable LoRA added nothing either + words = '' + if words and prompt.startswith(words + ', '): + prompt = prompt[len(words) + 2:] + elif words and prompt == words: + prompt = '' + return prompt + + +def from_comfy(source, *, resolve=None): + """A generate request from a FreeVideo graph (API prompt, saved workflow, or a video's tags). + + resolve(file) -> media reference or None: how a picture in ComfyUI's input folder comes in (the caller imports it + into the library by its hash); None marks it missing. Without it the file name is kept as it is. + + Returns dict(request, missing, repaired, notes, version): notes also hold what the saved workflow's node + properties keep that a request has no field for (_page_notes); version is FROM_COMFY_VERSION. Raises OpenInComfy when the generator is fed by a node FreeVideo + cannot read, SpecError when there is no single generator.""" + graph = api_graph(source) + generators = [key for key, node in graph.items() if node.get('class_type') == GENERATOR] + if len(generators) != 1: + fail('/', 'one FreeVideo Generate node (found %d)' % len(generators)) + inputs = dict(graph[generators[0]].get('inputs') or {}) + strange, missing, notes, guides = [], [], [], [] + literal = {name: _value(graph, value, strange) for name, value in inputs.items() + if name not in ('media', 'loras', 'first', 'last', 'conditioning')} + repaired = repair_inputs(literal) + + def media_ref(file, role): + ref = resolve(file) if resolve else {'file': file} + if ref is None: + missing.append(dict(file=file, role=role)) + return ref + + media, middle, references = {}, [], [] + for role in ('first', 'last'): + if _link(inputs.get(role)): + file = _picture(graph, inputs[role], strange) + if file == '': + missing.append(dict(file=None, role=role)) + elif file and (ref := media_ref(file, role)) is not None: + media[role] = ref + if _link(inputs.get('media')): + node = graph.get(str(inputs['media'][0])) or {} + if node.get('class_type') != 'FreeVideoMedia': + strange.append(node.get('class_type') or 'missing node') + else: + media_inputs = node.get('inputs', {}) + for role in ('first', 'last'): + if _link(media_inputs.get(role)): + file = _picture(graph, media_inputs[role], strange) + if file == '': + missing.append(dict(file=None, role=role)) + elif file and (ref := media_ref(file, role)) is not None: + media.setdefault(role, ref) + if _link(media_inputs.get('reference_audio')): + strange.append((graph.get(str(media_inputs['reference_audio'][0])) or {}).get('class_type') or 'missing node') + for row in _rows(_value(graph, media_inputs.get('assets'), strange)): + if row.get('enabled') is False: + continue + if not isinstance(row.get('file'), str) or not row['file']: + # A row that names no file is listed, not dropped. + missing.append(dict(file=None, role=row.get('role') or 'reference')) + continue + ref = media_ref(row['file'], row.get('role') or 'reference') + if ref is None: + continue + role = row.get('role') + if role in ('first', 'last'): + media.setdefault(role, ref) + elif role == 'middle': + middle.append(dict(ref, at=row.get('seconds', row.get('at', 0)))) + elif row.get('guide') is True: + # The source video of Replace person: a request has no field for it, so it is noted, not referenced. + guides.append(dict(replace_person=dict(source=row['file'], keep_sound=row.get('keep_source_audio') is True))) + else: + references.append(dict(ref, **{k: row[k] for k in ('early_steps', 'voice_only', 'use', 'range') if k in row})) + if middle: + media['middle'] = middle + if references: + media['references'] = references + + loras, seen, link = [], set(), inputs.get('loras') + while _link(link) and str(link[0]) not in seen: + seen.add(str(link[0])) + node = graph.get(str(link[0])) or {} + if node.get('class_type') != 'FreeVideoLoRAStack': + strange.append(node.get('class_type') or 'missing node') + break + stack = node.get('inputs', {}) + loras = [dict(name=row['name'], strength=float(row['strength']) if isinstance(row.get('strength'), (int, float)) and not isinstance(row.get('strength'), bool) else 1.) + for row in _rows(_value(graph, stack.get('adapters'), strange)) + if row.get('enabled', True) and isinstance(row.get('name'), str)] + loras + link = next((stack[k] for k in ('loras', 'previous', 'stack') if _link(stack.get(k))), None) + if _link(inputs.get('conditioning')): + strange.append((graph.get(str(inputs['conditioning'][0])) or {}).get('class_type') or 'missing node') + if strange: + raise OpenInComfy(strange) + + for name in ('width', 'height', 'seconds', 'seed'): + value = literal.get(name) + if not isinstance(value, (int, float)) or isinstance(value, bool): + fail('/' + name, 'the generator\'s %s as a number' % name) + request = dict(kind='generate', prompt=_strip_triggers(str(literal.get('text') or ''), loras), + width=literal['width'], height=literal['height'], seconds=float(literal['seconds']), seed=literal['seed']) + for flag in ('preview', 'force_regenerate', 'first_frame_reference'): + if literal.get(flag) is True: + request[flag] = True + two_pass, base, refine = bool(literal.get('two_pass', True)), literal.get('base_steps'), literal.get('refine_steps') + cache = literal.get('step_cache') if literal.get('step_cache') not in (None, '', 'none') else None + factor = float(literal['upscale_factor']) if literal.get('upscale_factor') not in (None, '', '2') else 2 + factor = int(factor) if factor == int(factor) else factor + level = _quality(two_pass, base, refine, cache, factor) + if level: + request['quality'] = level + else: + request['sampling'] = dict(two_pass=two_pass, base_steps=base, refine_steps=refine) + if cache or factor != 2: + notes.append(dict(step_cache=cache, upscale_factor=factor)) + if media: + request['media'] = media + if loras: + request['loras'] = loras + # A file path the request cannot name: the caller (the chain records' reader) decides what it becomes. + for name in ('continue_from', 'refine_from'): + if isinstance(literal.get(name), str) and literal[name]: + notes.append({name: literal[name]}) + if literal.get('frames'): + notes.append(dict(frames=literal['frames'])) + # Settings a generate request has no field for: an upscale of a finished video, and the Fastest mode. + if isinstance(literal.get('upscale_from'), str) and literal['upscale_from']: + notes.append(dict(upscale_from=literal['upscale_from'], upscale_to=literal.get('upscale_to') or '')) + if literal.get('fast_mode') not in (None, '', 'none'): + notes.append(dict(fast_mode=literal['fast_mode'])) + properties = _properties(source) + media_node = str(inputs['media'][0]) if _link(inputs.get('media')) else None + page = _page_notes(properties.get(generators[0], {}), properties.get(media_node, {}) if media_node else {}, request['prompt']) + # The page's own Replace person state says more than the rows it sent (the people too): one note, not two. + notes += page + ([] if any('replace_person' in note for note in page) else guides) + contract.validate_job(request, local=True) + return dict(request=request, missing=missing, repaired=repaired, notes=notes, version=FROM_COMFY_VERSION) diff --git a/freevideo_engine/chain_migrate.py b/freevideo_engine/chain_migrate.py new file mode 100644 index 00000000..d6f47e4b --- /dev/null +++ b/freevideo_engine/chain_migrate.py @@ -0,0 +1,118 @@ +"""An old chain record read as a generate request: the record keeps the ComfyUI graph it was +submitted with (record['snapshot']['prompt']); this reads it back with spec.from_comfy, in memory. The file on disk is +never rewritten. + +What a chain was made with comes from two places: the graph gives the size, quality, pictures, LoRAs and the whole +description; each part's own words, length and seed are in its block (record['blocks'][i]['inputs']), since the page +split the chain before it was submitted. A request has one seed, so a chain of several parts is a remake with the same +settings, seeded by its first part, and is said to differ from the original; a chain of one +part that continues nothing is the same request and can be made again bit for bit on the same machine. + +migrate(record) -> dict(state, request, exact, notes, missing, open_in_comfy, reason): + state 'ready' request is a valid generate request + 'open_in_comfy' the generator is fed by nodes FreeVideo cannot read; open_in_comfy names them + 'unreadable' the record kept no generation settings that can be read; reason says so (never guessed) +""" +import re + +from . import chain_plan + +# A work's file in the output folder: FreeVideo///video.mp4 is the library's /. +WORK_FILE = re.compile(r'^FreeVideo/(\d{4}-\d{2}-\d{2})/([0-9a-f]{32})/[^/]+\.mp4$') +MAX_PART_PROMPTS = 5 + +UNREADABLE = ('This video kept no readable generation settings, so it cannot be generated again.', + '这个视频没有保存可读取的生成设置,无法重新生成。') +UNSUPPORTED = ('This version no longer accepts this video\'s settings as they are (for example, it is longer than one ' + 'generation allows), so it cannot be generated again exactly as before.', + '当前版本不再按原样接受这个视频的设置(例如时长超过单次生成的上限),无法按原样重新生成。') +DIFFERENT = ('Each part had its own seed. Generated again from the first part\'s seed, the result will differ from the original.', + '各段的种子不同;按第一段的种子重新生成,结果会与原视频不同。') + + +def work_of(path): + """The library id of a work file named by its output path, or None.""" + found = WORK_FILE.match(str(path or '').replace('\\', '/')) + return '%s/%s' % found.groups() if found else None + + +def _unreadable(error=None, words=UNREADABLE): + return dict(state='unreadable', request=None, exact=False, notes=[], missing=[], open_in_comfy=[], + reason=dict(en=words[0], zh=words[1]), **({'detail': str(error)} if error else {})) + + +def migrate(record, *, resolve=None, work=work_of): + """The generate request an old chain record stands for. ``resolve(file)`` brings a picture of ComfyUI's input + folder into the library (None: missing), as spec.from_comfy takes it; ``work(path)`` names the library work of a + video the chain continued (None: kept as a note).""" + from .agent import schema as contract + from .agent.spec import SpecError + from .agent.spec_comfy import OPEN_IN_COMFY, OpenInComfy, from_comfy + snapshot = record.get('snapshot') if isinstance(record, dict) else None + blocks = record.get('blocks') if isinstance(record, dict) else None + if not isinstance(snapshot, dict) or not isinstance(snapshot.get('prompt'), dict) or not isinstance(blocks, list) or not blocks: + return _unreadable() + try: + read = from_comfy(snapshot['prompt'], resolve=resolve) + except OpenInComfy as error: + return dict(state='open_in_comfy', request=None, exact=False, notes=[], missing=[], + open_in_comfy=list(error.nodes), reason=dict(en=OPEN_IN_COMFY[0], zh=error.message_zh)) + except (SpecError, ValueError, TypeError, KeyError) as error: + return _unreadable(error) + request, notes = dict(read['request']), [] + # The graph's own length, seed and continuation are the template's, not the chain's: the blocks have them. + notes += [note for note in read['notes'] if not set(note) & {'continue_from', 'frames'}] + ordered = sorted(blocks, key=lambda row: row.get('index', 0) if isinstance(row, dict) else 0) + try: + parts = [row['inputs'] for row in ordered] + texts = [str(part['text']) for part in parts] + frames = [int(part['frames']) for part in parts] + seeds = [int(part['seed']) for part in parts] + new = [int(row.get('new_frames', part['frames'])) for row, part in zip(ordered, parts)] + except (KeyError, TypeError, ValueError) as error: + return _unreadable(error) + first = ordered[0] + request['seed'] = seeds[0] + if len(parts) == 1: + request['seconds'] = frames[0] / chain_plan.FPS + request['prompt'] = texts[0] or request['prompt'] + else: + request['seconds'] = sum(new) / chain_plan.FPS + if len(parts) <= MAX_PART_PROMPTS and all(text.strip() for text in texts): + request['part_prompts'] = texts + else: + # More parts than a request names, or a part without words: the whole description stands, and each part's + # words are kept for the page to show. + notes.append(dict(part_texts=texts)) + if len(set(seeds)) > 1: + notes.append(dict(seeds_differ=True, en=DIFFERENT[0], zh=DIFFERENT[1])) + # Where the chain began and ended: a video of the library, another chain's output, or none. + continued = False + for key, name in (('after', 'continue_from'), ('before', 'continue_to')): + source = first.get(key) if key == 'after' else ordered[-1].get(key) + if isinstance(source, dict) and 'work' in source: + continued = True + library = work(source['work']) if key == 'after' and work else None + if library: + request['continue_from'] = {'library': library} + # A continuation takes only references; its first and last frames came from the video. + media = request.get('media') + if isinstance(media, dict): + media = {k: v for k, v in media.items() if k == 'references'} + if media: + request['media'] = media + else: + request.pop('media', None) + else: + notes.append({name: source['work']}) + elif isinstance(source, dict) and 'chain' in source: + continued = True + notes.append({name: dict(source)}) + # Bit for bit only for one part joined to nothing: continue_to (before) has no field in a request either. + exact = len(parts) == 1 and not continued + try: + contract.validate_job(request, local=True) + except Exception as error: # A record whose values the request no longer takes (too long, say) is said, not guessed. + return _unreadable(error, UNSUPPORTED) + return dict(state='ready', request=request, exact=exact, notes=notes, missing=read['missing'], open_in_comfy=[], + reason=None) diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py index 88cc3add..6a9391c6 100644 --- a/freevideo_engine/comfy_bridge.py +++ b/freevideo_engine/comfy_bridge.py @@ -1494,6 +1494,9 @@ def generate(prompt, width, height, seconds, seed, output_directory, *, step_cache=None, upscale_factor=2, allow_empty_prompt=False, upscale_from=None, upscale_to=None, fast_mode=None, shown_estimate=None): from .comfy_environment import NOT_DISPATCHED, control_process + # Not only under the first `continue_from` check: the second pass of a preview takes continue_from from the + # preview's saved command further down, and the checks after that use this name too. + from .continuation import validate_route if control_process(environ): raise RuntimeError(NOT_DISPATCHED) if upscale_to not in (None, '', '4k', 'fast'): @@ -1518,7 +1521,6 @@ def generate(prompt, width, height, seconds, seed, output_directory, *, if type(hide_tail) is not bool: raise ValueError('Hide tail must be a boolean') if continue_from is not None: - from .continuation import validate_route validate_route(two_pass=two_pass, preview=preview, refine_from=refine_from) if type(two_pass) is not bool: raise ValueError('Two-pass generation must be a boolean') diff --git a/freevideo_engine/comfy_capabilities.py b/freevideo_engine/comfy_capabilities.py index bbecae24..06a9e83a 100644 --- a/freevideo_engine/comfy_capabilities.py +++ b/freevideo_engine/comfy_capabilities.py @@ -7,6 +7,7 @@ import logging from pathlib import Path import platform +import re import sys import threading import time @@ -406,11 +407,29 @@ def upscale_estimates(output_directory, width, height, frames): return dict(seconds=seconds, sizes=sizes) +UPSCALE_QUERY_LIMITS = (('width', 16384), ('height', 16384), ('frames', 24 * 3600)) + + def _upscale_query(query): - values = tuple(int(query.get(name, '')) for name in ('width', 'height', 'frames')) - if not all(0 < value <= limit for value, limit in zip(values, (16384, 16384, 24 * 3600))): - raise ValueError('width, height and frames must be positive') - return values + """(width, height, frames) from the query; otherwise one sentence naming each value that is missing or wrong.""" + values, missing, not_whole, too_large = [], [], [], [] + for name, limit in UPSCALE_QUERY_LIMITS: + text = str(query.get(name) or '').strip() + if not text: + missing.append(name) + elif not re.fullmatch(r'[0-9]+', text) or not text.strip('0'): + not_whole.append(name) + # Only the digits after leading zeros are converted, and only when no longer than the limit: past 4300 digits + # (leading zeros count) int() raises Python's own message. + elif len(text.lstrip('0')) > len(str(limit)) or int(text.lstrip('0')) > limit: + too_large.append('%s above %d' % (name, limit)) + else: + values.append(int(text.lstrip('0'))) + problems = [label + ': ' + ', '.join(names) for label, names in + (('missing', missing), ('not a whole number above 0', not_whole), ('too large', too_large)) if names] + if problems: + raise ValueError('width, height and frames must be whole numbers above 0 (%s)' % '; '.join(problems)) + return tuple(values) def register(): diff --git a/freevideo_engine/comfy_chain.py b/freevideo_engine/comfy_chain.py index 1a09a0e3..e12ee540 100644 --- a/freevideo_engine/comfy_chain.py +++ b/freevideo_engine/comfy_chain.py @@ -422,6 +422,8 @@ def register(host_factory=None): host.runner = runner RUNNER = runner server._freevideo_chain = True + from . import job_record + job_record.adopt_misplaced(runner.store_dir) def response(value, status=200): return web.json_response(value, status=status, headers={'Cache-Control': 'no-store'}) diff --git a/freevideo_engine/comfy_launcher_api.py b/freevideo_engine/comfy_launcher_api.py index 8f6f876d..d8f7a086 100644 --- a/freevideo_engine/comfy_launcher_api.py +++ b/freevideo_engine/comfy_launcher_api.py @@ -18,10 +18,14 @@ def page_report(value): rows = lambda key, count, limit: ([p[:limit] for p in value[key][:count] if isinstance(p, str)] if isinstance(value.get(key), list) else []) text = lambda key, limit: value.get(key)[:limit] if isinstance(value.get(key), str) else '' + # When a launch's cover left and its workspace came to the front, in seconds from the page's start: numbers only. + opening = value.get('opening') if isinstance(value.get('opening'), dict) else {} + times = {key: round(float(opening[key]), 1) for key in ('cover_s', 'workspace_s') + if type(opening.get(key)) in (int, float) and 0 <= opening[key] <= 3600} return dict(state=value['state'], problems=rows('problems', 8, 500), errors=rows('errors', 40, 300), ready=value.get('ready') is True, launch=value.get('launch') is True, view=text('view', 20), agent=text('agent', 300), frontend=text('frontend', 40), page=text('page', 200), - client=text('client', 80), at=time.time()) + client=text('client', 80), **({'opening': times} if times else {}), at=time.time()) PAGE_SCRIPTS_MISSING = ( diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.py index 66278440..e77c9f00 100644 --- a/freevideo_engine/comfy_launcher_runtime.py +++ b/freevideo_engine/comfy_launcher_runtime.py @@ -1447,6 +1447,39 @@ def _open_access_proxy(self): self.state = dict(self.state, selection=dict(self.selection)) self.refresh_access_links() + def _stop_without_cuda_devices(self, command, env, directory, context): + """Stop before ComfyUI starts when the CUDA driver is there and shows no device. + + ComfyUI would import Torch and quit on the same fact ("No CUDA GPUs are available") before it + loads any node, and the launcher could only report that it quit. The count is read in a child + with the environment ComfyUI gets, so a CUDA_VISIBLE_DEVICES that hides every card counts too. + A machine without the CUDA driver library (AMD, Intel, Mac), a read that fails, a CPU-only + control process and a started device executor all go on as before. + """ + if sys.platform == 'darwin' or '--cpu' in command or env.get('FREEVIDEO_EXECUTOR_DEVICE'): + return + from . import cuda_inventory + found = cuda_inventory.count_devices(env) + visible = env.get('CUDA_VISIBLE_DEVICES') + if found is not None: + cuda_inventory.remember(found, visible) + if not cuda_inventory.has_no_devices(found): + return + lines = ['[CUDA_NO_DEVICES] CUDA found no usable NVIDIA graphics card; ComfyUI was not started.', + cuda_inventory.report_line(found, visible)] + if visible is not None: + # Only the variable is the cause when the driver shows a card without it: the card says so then. + free = cuda_inventory.count_devices({name: value for name, value in env.items() if name != 'CUDA_VISIBLE_DEVICES'}) + if free and free.get('library') is True and free.get('init') == 0 and (free.get('count') or 0) > 0: + lines.append('CUDA devices without CUDA_VISIBLE_DEVICES: %d' % free['count']) + card = cuda_inventory.named_card() + if card: + lines.append('nvidia-smi lists: ' + card) + log = io_path(self.server_log) + log.write_text('\n'.join(lines) + '\n', encoding='utf-8') + from .failure_details import startup_failure + raise RuntimeError(startup_failure('ComfyUI could not start.', directory / 'comfy.log', context=context)) + def _connect_comfy(self): retry, self._scope_retry = self._scope_retry, False self.state = {key: value for key, value in self.state.items() @@ -1616,6 +1649,8 @@ def _connect_comfy(self): if runtime_alias.system_long_paths() else command) env = launch_view.environment_view(env, view) from .windows_ux import external_python + if managed: + self._stop_without_cuda_devices(command, env, directory, context) with self._server_lock, external_python(), io_path(self.server_log).open('wb') as log: if self._closed or self.cancelled.is_set(): raise RuntimeError('ComfyUI startup cancelled') diff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.py index 1de517bc..2e2d7b7d 100644 --- a/freevideo_engine/comfy_library.py +++ b/freevideo_engine/comfy_library.py @@ -356,6 +356,105 @@ def _saved_json(path, root): return None +def _media_lists(workflow): + """The media list each generate node of a saved workflow was given: [rows] per generate node ([] for one with no + media), or None when a generate node takes its media from anything but a Media node, or a list cannot be read.""" + nodes = workflow.get('nodes') if isinstance(workflow, dict) else None + links = workflow.get('links') if isinstance(workflow, dict) else None + if not isinstance(nodes, list) or not isinstance(links, list): + return None + by_id = {str(node.get('id')): node for node in nodes if isinstance(node, dict)} + # A link is [id, origin, origin slot, target, target slot, type] in a saved workflow, an object in a newer one. + origins = {} + for link in links: + if isinstance(link, list) and len(link) >= 4: + origins[str(link[0])] = str(link[1]) + elif isinstance(link, dict) and 'id' in link and 'origin_id' in link: + origins[str(link['id'])] = str(link['origin_id']) + lists = [] + for node in nodes: + if not isinstance(node, dict) or node.get('type') != 'FreeVideoGenerate': + continue + media = next((row for row in node.get('inputs') or [] if isinstance(row, dict) and row.get('name') == 'media'), None) + if media is None or media.get('link') is None: + lists.append([]) + continue + source = by_id.get(origins.get(str(media['link']))) + values = source.get('widgets_values') if isinstance(source, dict) and source.get('type') == 'FreeVideoMedia' else None + if not isinstance(values, list) or not values or not isinstance(values[0], str) or len(values[0]) > 128 * 1024: + return None + try: + rows = json.loads(values[0]) + except ValueError: + return None + if (not isinstance(rows, list) or len(rows) > 32 + or not all(isinstance(row, dict) and _input_name(row.get('file')) for row in rows)): + return None + lists.append(rows) + return lists + + +def _input_name(name): + """Whether a media row names a file inside ComfyUI's input folder the way the Media node writes it.""" + return (isinstance(name, str) and 0 < len(name) <= 1024 and '\x00' not in name and '\\' not in name and ':' not in name + and not name.startswith('/') and '..' not in name.split('/')) + + +def saved_media(output_directory, input_directory, identity): + """The media list a saved video was made from, to fill back into the Media node: {rows, missing}, `rows` as the + Media node feeding its generate node held them (cards turned off stay off), `missing` the indexes of rows whose + file is no longer in ComfyUI's input folder. Read from the run's own saved workflow, never from the panel; a run + that kept none (an export, an import, an Agent job, an old receipt) or whose list cannot be told gives None. The + rows go back to this machine's page only: file names are not logged.""" + path = _video(output_directory, identity) + root = Path(output_directory).resolve() / 'FreeVideo' + state = _saved_json(path.with_name('comfy-request.json'), root) + if not isinstance(state, dict) or state.get('status') != 'complete': + return None + lists = _media_lists(_saved_json(path.with_name('workflow.json'), root)) + if not lists: + return None + base = Path(input_directory).resolve() + + def place(row): + try: + found = (base / row['file']).resolve() + return found if found.is_relative_to(base) else None + except (OSError, ValueError): + return None + distinct = list({json.dumps(rows, sort_keys=True): rows for rows in lists}.values()) + if len(distinct) > 1: + # Several generate nodes with different lists: the one whose files that were on are all files the run read. + command = state.get('command') if isinstance(state.get('command'), list) else [] + media = _saved_json(path.with_name('media.json'), root) if '--media' in command else {} + if not isinstance(media, dict): + return None + read = set() + for key in ('first', 'last'): + if isinstance(media.get(key), str): + read.add(media[key]) + for key in ('middle', 'references'): + for row in media.get(key) if isinstance(media.get(key), list) else (): + if isinstance(row, dict) and isinstance(row.get('path'), str): + read.add(row['path']) + read = {str(Path(name).resolve()) for name in read} + def read_all(rows): + on = {str(place(row)) for row in rows if row.get('enabled', True) is not False} + # A list with nothing on fits only a run that read no media. + return on <= read if on else not read + fits = [rows for rows in distinct if read_all(rows)] + if len(fits) != 1: + return None + distinct = fits + rows = distinct[0] + missing = [] + for index, row in enumerate(rows): + found = place(row) + if found is None or not found.is_file(): + missing.append(index) + return dict(rows=rows, missing=missing) + + def run_settings(folder, root): """The settings a saved video was made with, as the page shows them: its quality level, seed, sampling steps (only where they are not a level's own) and LoRAs (file name and strength). Read from what the run itself was given: @@ -1876,7 +1975,14 @@ async def prompt(request): raise web.HTTPNotFound(text='Prompt unavailable') from None # The seed is optional: without it, reusing the settings fills only the prompt and the size. seed = await asyncio.to_thread(prompt_seed, folder_paths.get_output_directory(), request.query.get('id')) - return web.json_response(dict(prompt=text, **({} if seed is None else {'seed': seed})), headers={'Cache-Control': 'no-store'}) + # The media list is optional too: without it, reusing the settings leaves the Media node as it is. + try: + media = await asyncio.to_thread(saved_media, folder_paths.get_output_directory(), folder_paths.get_input_directory(), + request.query.get('id')) + except (OSError, ValueError): + media = None + return web.json_response(dict(prompt=text, **({} if seed is None else {'seed': seed}), **({} if media is None else {'media': media})), + headers={'Cache-Control': 'no-store'}) @server.routes.post('/freevideo/library/favorite') async def favorite(request): diff --git a/freevideo_engine/comfy_upload.py b/freevideo_engine/comfy_upload.py index d29d7344..71c94d8d 100644 --- a/freevideo_engine/comfy_upload.py +++ b/freevideo_engine/comfy_upload.py @@ -199,7 +199,8 @@ def sweep_context(): image = getattr(server, '_freevideo_image_gen', None) return dict(input_root=folder_paths.get_input_directory(), output_root=folder_paths.get_output_directory(), user_root=folder_paths.get_user_directory(), queue=getattr(server, 'prompt_queue', None), - extra=image.held_tokens() if image is not None and hasattr(image, 'held_tokens') else ()) + extra=image.held_tokens() if image is not None and hasattr(image, 'held_tokens') else (), + roots=private_refs.held_roots()) private_refs.start_sweeps(sweep_context) private_refs.register_routes(server, web, folder_paths, sweep_context) diff --git a/freevideo_engine/cuda_inventory.py b/freevideo_engine/cuda_inventory.py index 10a4d2d4..bfcbf4ae 100644 --- a/freevideo_engine/cuda_inventory.py +++ b/freevideo_engine/cuda_inventory.py @@ -6,6 +6,8 @@ import ctypes as C import json import os +import re +import subprocess import sys import uuid @@ -18,6 +20,8 @@ # cuDriverGetVersion of the oldest driver setup accepts (CUDA 13, NVIDIA driver 580). OLDEST_DRIVER_API = 13000 +# cuInit's answer when the driver is loaded and shows no device. +NO_DEVICE = 100 def probe(selector=None): @@ -31,6 +35,79 @@ def probe(selector=None): return json.loads(result.stdout) +def count_devices(env=None, timeout=15): + """What the CUDA driver says about this process's devices, read in a child that exits again. + + Returns dict(library, init, count) or None when it could not be read. `library` is False when + the machine has no CUDA driver library (AMD, Intel, no driver); nothing is claimed then. The child + sees `env` as it is, CUDA_VISIBLE_DEVICES included, so the count is the one Torch would get. + """ + try: + result = subprocess_output.run_python(processes.module_command(__name__, '--count'), + env=env, capture_output=True, timeout=timeout) + value = json.loads(result.stdout.strip().splitlines()[-1]) + if result.returncode or not isinstance(value, dict): + return None + return value + except (OSError, ValueError, IndexError, subprocess.SubprocessError): + return None + + +# The latest read made for a ComfyUI start: (answer, CUDA_VISIBLE_DEVICES the child had). A report that needs the count +# takes this one, so that it never waits for the driver on the window's own thread. +LAST = None + + +def remember(found, visible): + global LAST + LAST = (found, visible) + + +def has_no_devices(found): + """Whether the driver is there and answers that no CUDA device is visible (cuInit 100 is CUDA_ERROR_NO_DEVICE).""" + return bool(found) and found.get('library') is True and ( + found.get('init') == NO_DEVICE or (found.get('init') == 0 and found.get('count') == 0)) + + +def local_count(): + try: + driver = C.WinDLL('nvcuda.dll') if sys.platform == 'win32' else C.CDLL('libcuda.so.1') + except OSError: + return dict(library=False) + driver.cuInit.argtypes, driver.cuInit.restype = [C.c_uint], C.c_int + driver.cuDeviceGetCount.argtypes, driver.cuDeviceGetCount.restype = [C.POINTER(C.c_int)], C.c_int + init = driver.cuInit(0) + count = C.c_int(-1) + if init == 0: + driver.cuDeviceGetCount(C.byref(count)) + return dict(library=True, init=init, count=count.value) + + +def report_line(found, visible): + """The report line: how many CUDA devices were visible, or that this could not be read.""" + shown = 'unset' if visible is None else ('empty' if not visible else visible) + if not found: + return 'CUDA devices: not available (CUDA_VISIBLE_DEVICES %s)' % shown + if found.get('library') is not True: + return 'CUDA devices: no CUDA driver library (CUDA_VISIBLE_DEVICES %s)' % shown + if found.get('init') != 0: + return 'CUDA devices: %s (cuInit status %s, CUDA_VISIBLE_DEVICES %s)' % ( + 0 if found.get('init') == NO_DEVICE else 'unknown', found.get('init'), shown) + return 'CUDA devices: %s (CUDA_VISIBLE_DEVICES %s)' % (found.get('count'), shown) + + +def named_card(): + """`NVIDIA driver ()` for the first card nvidia-smi lists, or '' when it lists none.""" + try: + from .system import nvidia_smi + row = subprocess_output.output_external([nvidia_smi(), '--query-gpu=name,driver_version', '--format=csv,noheader'], + stderr=subprocess.DEVNULL, timeout=5).strip().splitlines()[0] + model, driver = (part.strip() for part in row.rsplit(',', 1)) + return 'NVIDIA driver %s (%s)' % (driver, re.sub(r'[()\r\n]', '', model).strip()) + except Exception: + return '' + + def local_probe(selector=None): driver = C.WinDLL('nvcuda.dll') if sys.platform == 'win32' else C.CDLL('libcuda.so.1') @@ -108,6 +185,9 @@ def call(name, types, *args): if __name__ == '__main__': try: + if sys.argv[1:] == ['--count']: + print(json.dumps(local_count())) + sys.exit(0) print(json.dumps(local_probe(sys.argv[1] if len(sys.argv) > 1 else None))) except (OSError, RuntimeError, ValueError, AttributeError) as error: print(str(error), file=sys.stderr) diff --git a/freevideo_engine/failed_copies.py b/freevideo_engine/failed_copies.py index b1b3aacd..ff05dcf6 100644 --- a/freevideo_engine/failed_copies.py +++ b/freevideo_engine/failed_copies.py @@ -18,10 +18,12 @@ import re import stat -# What network.retain_partial is called with; ``rejected`` is also what a few callers rename by hand. +# What network.retain_partial is called with (``resume-unavailable``: the prefix a source without Range could not continue); +# ``rejected`` is also what a few callers rename by hand. # Not here, so never removed by this module: ``set-aside``, a file that was already on the install path and is not the # pinned one (it may be the user's own), moved aside before the right one is fetched. -REASONS = ('hash-rejected', 'rejected', 'oversized-response', 'oversized', 'restart-approved', 'switch-retained') +REASONS = ('hash-rejected', 'rejected', 'oversized-response', 'oversized', 'resume-unavailable', 'restart-approved', + 'switch-retained') # The tag is the time in nanoseconds (retain_partial), ticks (Windows scripts) or a uuid (cache folders). _TAG = r'(?P[0-9a-f]{6,})' _SUFFIX = re.compile(r'(?:\.partial)?\.(?:%s)-%s' % ('|'.join(REASONS), _TAG)) diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py index 10d78ce9..bb94e00a 100644 --- a/freevideo_engine/failure_details.py +++ b/freevideo_engine/failure_details.py @@ -757,6 +757,44 @@ def vc_runtime_failure(text, zh=False): ) +# CUDA shows no device: the launcher's own check before ComfyUI starts, or Torch's sentence when ComfyUI quit on it. +NO_CUDA_DEVICES = r'\[CUDA_NO_DEVICES\]|^RuntimeError: No CUDA GPUs are available' +NO_CUDA_DEVICES_CARD = ( + ('CUDA found no usable graphics card', 'CUDA 没有找到可用的显卡'), + ('CUDA found no NVIDIA graphics card that FreeVideo can use, so ComfyUI did not start.', + 'CUDA 没有找到 FreeVideo 可以使用的 NVIDIA 显卡,所以 ComfyUI 没有启动。'), + ('Restart the computer and open FreeVideo again. Update the NVIDIA driver to version 580 or newer. ' + 'On a laptop, make sure the NVIDIA graphics card is enabled and not switched off by the graphics mode of the laptop. ' + 'If you are connected through Remote Desktop, open FreeVideo on the computer itself instead. If it still fails, export the report.', + '请重启电脑后重新打开 FreeVideo。请将 NVIDIA 显卡驱动更新到 580 或更新版本。' + '笔记本电脑请确认 NVIDIA 显卡已启用,没有被笔记本的显卡模式关闭。' + '通过远程桌面连接时,请在这台电脑本机上打开 FreeVideo。仍然失败时,可以导出报告。')) + + +# The variable names a list of devices, and one that matches none hides every card: the steps above cannot help then. +NO_CUDA_DEVICES_HIDDEN = ( + ('The environment variable CUDA_VISIBLE_DEVICES is set to "{value}" and hides every graphics card from CUDA. ' + 'Remove it from the environment variables of the system, then open FreeVideo again. If it still fails, export the report.', + '已设置环境变量 CUDA_VISIBLE_DEVICES,值为“{value}”,它把所有显卡都对 CUDA 隐藏了。' + '请在系统的环境变量中删除它,然后重新打开 FreeVideo。仍然失败时,可以导出报告。'), + ('The environment variable CUDA_VISIBLE_DEVICES is set to an empty value and hides every graphics card from CUDA. ' + 'Remove it from the environment variables of the system, then open FreeVideo again. If it still fails, export the report.', + '已设置环境变量 CUDA_VISIBLE_DEVICES,值为空,它把所有显卡都对 CUDA 隐藏了。' + '请在系统的环境变量中删除它,然后重新打开 FreeVideo。仍然失败时,可以导出报告。')) + + +def _no_cuda_devices_card(summary, zh): + title, cause, steps = (part[zh] for part in NO_CUDA_DEVICES_CARD) + found = re.search(r'NVIDIA driver ([\w.]+) \(([^)]*)\)', summary) + seen = fill(DETECTED_DRIVER[zh], dict(model=found[2], version=found[1])) + '\n' if found else '' + # The launcher's own check names the variable it saw and whether the driver shows a card without it; the Torch + # sentence in a log does neither. The value may hold spaces ("0, 1"): it runs to the closing bracket of the line. + hidden = re.search(r'^CUDA devices: .*CUDA_VISIBLE_DEVICES (.+)\)[ \t\r]*$', summary, re.M) + if hidden and hidden[1] != 'unset' and re.search(r'^CUDA devices without CUDA_VISIBLE_DEVICES: [1-9]', summary, re.M): + steps = NO_CUDA_DEVICES_HIDDEN[1][zh] if hidden[1] == 'empty' else fill(NO_CUDA_DEVICES_HIDDEN[0][zh], dict(value=hidden[1][:60])) + return dict(title=title, detail=seen + cause + '\n' + steps, action='', kind='gpu-no-cuda-devices') + + def _startup_cause(summary, zh): """What ComfyUI said when it quit: the exit code, the custom node that last failed to load and, when it is a known one, the last error as a sentence. The raw error line is not shown on the card.""" @@ -1008,7 +1046,7 @@ def source_lines(lines, zh=False): DETECTED = ('Detected: {model}', '检测到:{model}') DETECTED_TWO = ('Detected: {first}, {second}', '检测到:{first}、{second}') INSTALLED_DRIVER = ('Installed driver: {version}', '当前驱动版本:{version}') -VALUE_LINES = (DETECTED_DRIVER, DETECTED, DETECTED_TWO, INSTALLED_DRIVER) +VALUE_LINES = (DETECTED_DRIVER, DETECTED, DETECTED_TWO, INSTALLED_DRIVER, NO_CUDA_DEVICES_HIDDEN[0]) # A card found only in the PCI list has no model name: the line names it in words of the interface language. DETECTED_NVIDIA = ('Detected: NVIDIA graphics card', '检测到:NVIDIA 显卡') @@ -1041,9 +1079,19 @@ def launcher_failure(value, *, zh=False, **options): '如果这台电脑有 NVIDIA 显卡,请安装 580 或更新版本的 NVIDIA 显卡驱动,重启电脑后点击“重试启动”。'), } +# The installation check found the problem before anything was installed: the launcher stays on the check and its button is +# "Check again". The check is not kept, so after a restart the launcher opens on another page; {button} is that page's +# button (Session.restart_button), filled in after the sentence is translated. +CHECK_ACTIONS = { + 'gpu-driver-old': ('Update the NVIDIA driver to version 580 or newer, then click "Check again". If the computer has ' + 'restarted, open FreeVideo and click "{button}".', + '请将 NVIDIA 显卡驱动更新到 580 或更高版本,然后点击“重新检查”。如果电脑已经重启,请打开 FreeVideo,' + '再点击“{button}”。'), +} + def _launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_repair=False, repairs_comfy=False, - unavailable='none', model_package='', exception=None, launch=False): + unavailable='none', model_package='', exception=None, launch=False, check=False): """Short guidance for known failures; callers retain the full error separately. other_disk: the launcher can offer another disk with enough room (macOS). @@ -1178,6 +1226,8 @@ class names and errno, no text), when the message is that exception's str(); it action='重新检查' if zh else 'Check again') # A block by Windows' application control is not a missing file: its own card applies (rules below). if text.startswith('ComfyUI could not start.') and not _stopped_on_application_control(summary): + if re.search(NO_CUDA_DEVICES, summary, re.M): + return _no_cuda_devices_card(summary, zh) if can_repair and repairs_comfy and (_stopped_on_missing_module(summary) or ENVIRONMENT_FILES in summary): return dict(title=DEPENDENCIES[0][zh], detail='', action=DEPENDENCIES[1][zh], kind='dependencies') action = ('完整日志在详情里;使用已有的 ComfyUI 时,请用原来的启动器检查。' if zh else @@ -1486,6 +1536,8 @@ class names and errno, no text), when the message is that exception's str(); it action = WITHOUT_REPAIR[kind].get(unavailable) or WITHOUT_REPAIR[kind].get('none', WITHOUT_REPAIR_NONE) if launch and kind in LAUNCH_ACTIONS: action = LAUNCH_ACTIONS[kind] + elif check and kind in CHECK_ACTIONS: + action = CHECK_ACTIONS[kind] detail = '' if kind == 'gpu-driver-old': version, model = re.search(r'NVIDIA driver(?: ([\w.]+))?(?: \(([^)]*)\))? is older than 580', text, re.I).groups() diff --git a/freevideo_engine/fast_pack.py b/freevideo_engine/fast_pack.py index 2f89defc..486c4eb4 100644 --- a/freevideo_engine/fast_pack.py +++ b/freevideo_engine/fast_pack.py @@ -10,7 +10,6 @@ """ import json from pathlib import Path, PurePosixPath -import re import threading import time @@ -23,10 +22,6 @@ # The receipt beside the files: what each one was when its sha256 last matched (size, times, file id). A file whose identity # is unchanged is not hashed again; one that changed is checked again before it counts. LEDGER = 'download-verified.json' -# A copy that did not pass, as network.retain_partial and its rejections name it: [.partial].-, -# with the reasons they use and nothing else, so a name such as weights.bin.backup-1 is never taken for one. -FAILED = re.compile(r'(?:\.partial)?\.(?:rejected|hash-rejected|oversized|oversized-response|resume-unavailable|restart-approved)' - r'-[0-9]{16,20}') def catalog(): @@ -128,31 +123,14 @@ def _receive(root, spec, ledger, row): pass # without a receipt it is only hashed once more -def failed_copies(path): - """The copies of one catalog file that did not pass, newest first.""" - path = Path(path) - found = [] - try: - entries = list(path.parent.iterdir()) - except OSError: - return [] - for entry in entries: - rest = entry.name[len(path.name):] if entry.name.startswith(path.name) else '' - if rest and FAILED.fullmatch(rest) and entry.is_file() and not entry.is_symlink(): - found.append((int(rest.rsplit('-', 1)[1]), entry)) - return [entry for _, entry in sorted(found, key=lambda item: item[0], reverse=True)] - - def prune_failed(root, spec, row, keep): """Keep at most `keep` failed copies of one of this pack's files (the newest, for diagnosis): one while it is not - in place, none once it is. Nothing but this catalog's own names in its own folder is touched.""" + in place, none once it is. The rule and the names it knows are failed_copies', the same as every other download's. + Nothing but this catalog's own names in its own folder is touched.""" if not _ours(spec, row): return - for entry in failed_copies(_target(root, row))[keep:]: - try: - entry.unlink() - except OSError: - pass + from . import failed_copies + failed_copies.prune(_target(root, row), keep) def missing_bytes(root, spec=None): diff --git a/freevideo_engine/job_record.py b/freevideo_engine/job_record.py index 2454eeda..7f59fe9e 100644 --- a/freevideo_engine/job_record.py +++ b/freevideo_engine/job_record.py @@ -126,16 +126,29 @@ def chain(record, store_dir): if status == 'done' and record.get('output_state') == 'failed': status = 'failed' client = str(record.get('client_id') or '') - try: - root = Path(store_dir).parents[1] # /FreeVideo/.chains - except IndexError: - return created = record.get('created') + # The output folder, as for every other job: the chain store is in the installation, not under the output. ended(record.get('id'), 'chain', status, origin='agent' if client.startswith('agent:') else 'page', created_at=created if isinstance(created, (int, float)) else None, result=library_id(record.get('output')) if status == 'done' else None, - failure='join_failed' if status == 'failed' and record.get('output_error') else None, - root=root) + failure='join_failed' if status == 'failed' and record.get('output_error') else None) + + +def adopt_misplaced(store_dir, root=None): + """Bring a long video's lines that earlier versions wrote beside the installation into the record the job list reads. + + Those versions put a chain's line two folders above its store, which is the folder holding the installation. + The file there is moved in only when everything in it is what that code wrote; anything else is left alone. + Never raises.""" + try: + root = root if root is not None else output_root() + if root is None: + return False + from . import jobs_journal + return jobs_journal.adopt(Path(store_dir).parent.parent / jobs_journal.NAME, root=Path(root), kinds=('chain',)) + except Exception: + _LOG.warning('An earlier finished-job record could not be read.', exc_info=True) + return False IMAGE_STATUS = dict(complete='done', failed='failed', cancelled='cancelled') diff --git a/freevideo_engine/jobs_journal.py b/freevideo_engine/jobs_journal.py index 8c7b5bf8..9ad632c5 100644 --- a/freevideo_engine/jobs_journal.py +++ b/freevideo_engine/jobs_journal.py @@ -8,8 +8,10 @@ import math import os import re +import stat import threading import time +import uuid from .long_paths import io_path from . import monitoring @@ -135,6 +137,101 @@ def forget(results, *, root): _LOG.warning('The finished-job record could not be updated.', exc_info=True) +ADOPT_BYTES = 256 * 1024 + + +def _written_here(value, kinds): + """The rows of a file this module wrote with only these kinds of job, or None for anything else.""" + if not isinstance(value, dict) or set(value) != {'jobs'} or not isinstance(value['jobs'], list): + return None + rows = value['jobs'] + if not rows or len(rows) > LIMIT: + return None + for row in rows: + # Every field must survive clean() unchanged: a file with any other field or value is not ours. + if not isinstance(row, dict) or clean(row) != row or row.get('kind') not in kinds or row.get('status') not in FINAL \ + or 'finished_at' not in row: + return None + return rows + + +_ADOPT_SKIPPED = set() + + +def _plain_file(path): + """The lstat of a regular file with one name, or None: a symbolic link, a junction or other reparse point, or a + file with another name elsewhere (a hard link) is never read or moved.""" + try: + info = os.lstat(path) + except OSError: + return None + reparse = getattr(info, 'st_file_attributes', 0) & getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0) + return info if stat.S_ISREG(info.st_mode) and not reparse and info.st_nlink == 1 else None + + +def _same_file(first, second): + try: + return os.path.samefile(first, second) + except OSError: + return False + + +def _read_written_here(path, kinds): + try: + if os.path.getsize(path) > ADOPT_BYTES: + return None + with open(path, encoding='utf-8') as stream: + return _written_here(json.load(stream), kinds) + except (OSError, ValueError): + return None + + +def adopt(stray, *, root, kinds=CHOICES['kind']): + """Move the rows of a record file written in the wrong folder into the one at root, then remove that file. + + Only a regular file with one name whose whole content is this module's own format is touched; any other file of + that name, a link, or the record at root itself reached by another path stays as it is. The file is first renamed + beside itself, so a folder it cannot leave adds nothing to the record. A row whose id the record already has keeps + the record's row. Returns whether the file was moved. Never raises.""" + claimed = None + try: + source, target = io_path(stray), io_path(root / NAME) + if _plain_file(source) is None or _same_file(source, target) or _read_written_here(source, kinds) is None: + return False + claimed = source.with_name(source.name + '.adopting-' + uuid.uuid4().hex[:12]) + try: + os.rename(source, claimed) + except OSError: + claimed = None + if str(source) not in _ADOPT_SKIPPED: + _ADOPT_SKIPPED.add(str(source)) + _LOG.info('An earlier finished-job record could not be moved from its folder; it is left as it is.') + return False + # What was renamed is read again: it is the file that will be removed. + rows = _read_written_here(claimed, kinds) if _plain_file(claimed) is not None else None + if rows is None: + os.rename(claimed, source) + claimed = None + return False + with _LOCK: + present = _rows(root) + known = {row['id'] for row in present} + merged = sorted(present + [row for row in rows if row['id'] not in known], key=lambda row: row['finished_at']) + monitoring.save(root / NAME, dict(jobs=_recent(merged, time.time()))) + os.unlink(claimed) + claimed = None + return True + except Exception: + _LOG.warning('An earlier finished-job record could not be moved.', exc_info=True) + return False + finally: + if claimed is not None: + try: + os.rename(claimed, source) + except OSError: + pass + + def mark_interrupted(*, root): """At start-up: a row still queued or running belongs to a process that is gone.""" try: diff --git a/freevideo_engine/launcher_issue.py b/freevideo_engine/launcher_issue.py index 354d397e..c81b7c64 100644 --- a/freevideo_engine/launcher_issue.py +++ b/freevideo_engine/launcher_issue.py @@ -81,6 +81,33 @@ def adapter_line(): return 'Display adapters: not available' +# Errors a CUDA device count helps to read; for any other error the report stays as it was. +GPU_ERROR = re.compile(r'CUDA|NVIDIA|\bGPU\b|nvidia-smi|graphics card|ComfyUI could not start', re.I) + + +def cuda_lines(error, read=False): + """The CUDA device count line for an error about the GPU or the start of ComfyUI: [] for any other error. + + It says how many devices the driver showed this program and the CUDA_VISIBLE_DEVICES it was started with: the + answer of the latest ComfyUI start when there is one. Without one, nothing is read unless `read` is true, and only + a worker thread passes that: cuInit can take seconds on a driver that is not well, and the window must not wait. + A machine without a CUDA driver library says so in the same line; a failed read says it could not read. + """ + import os + if not GPU_ERROR.search(str(error)) or 'CUDA devices:' in str(error): + return [] + try: + from . import cuda_inventory + seen = cuda_inventory.LAST + if seen is None: + if not read: + return [] + seen = (cuda_inventory.count_devices(timeout=5), os.environ.get('CUDA_VISIBLE_DEVICES')) + return [scrub(cuda_inventory.report_line(*seen))[:300]] + except Exception: + return ['CUDA devices: not available'] + + def update_source_lines(root, count=UPDATE_SOURCE_LINES): """A heading and the last lines of the update-source failure log, redacted once more; [] when there is no readable line.""" try: diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py index ef224d76..686315e5 100644 --- a/freevideo_engine/launcher_session.py +++ b/freevideo_engine/launcher_session.py @@ -1035,6 +1035,33 @@ def retry_kind(self): return 'install' return '' + def restart_button(self): + """(English, Chinese) of the main button the launcher shows when it opens again after a restart, as Main.qml names + it: an installation it can open starts it; a kept installation run resumes; a new installation starts on its first + page, which asks for the environment package first when one is needed.""" + if self.selected: + return ('Update & launch', '更新并启动') if self._engine_update_after_restart() else ('Launch FreeVideo', '启动 FreeVideo') + if self.saved_setup.get('status') in ('running', 'failed', 'cancelled'): + return ('Check & resume', '检查并继续') + if self.runtime_needed(): + return ('Choose environment package', '选择运行环境包') + return ('Continue', '继续') + + def _engine_update_after_restart(self): + """What engine_update_pending() will say when a restart has read the installation again: restore marks an + engine update when this launcher's source differs from the installed one, and an older bundle is never offered.""" + source = (self.selected or {}).get('source') + if not source: + return False + from .desktop_runtime import matching_source + from .release_notes import older + try: + if matching_source(self.source, Path(source)): + return False + except (OSError, ValueError): + return False + return not older(self.stamped(self.source, self.bundled_identity)[1], self.stamped(source, self.engine_identity)[1]) + def cleanup_downloads(self, remove=False): if not self.can_manage() or self.updater and self.updater.busy: self.explain_busy() @@ -1687,6 +1714,9 @@ def diagnostic_error(self): # Six reports said the driver was missing without saying whether a card was there. from .display_adapters import adapters, report_line raw += ('\n' if raw else '') + report_line(adapters()) + from .launcher_issue import cuda_lines + # A failure about the GPU or the start of ComfyUI also says how many CUDA devices the driver showed. + raw += ''.join('\n' + line for line in cuda_lines(raw)) pack_report = self.image_pack_report() if pack_report: # The existing ZIP exporter retains launcher/error.txt in full. @@ -1720,8 +1750,11 @@ def work(): partial = target.with_name('.%s.%s.partial.zip' % (target.name, uuid.uuid4().hex[:8])) if overwrite else target replacing = False try: + # The count is read here, off the window's thread, when no ComfyUI start has read it. + from .launcher_issue import cuda_lines + text = notes + ''.join('\n' + line for line in cuda_lines(notes, read=True)) result = collect(root, root / 'machine.json', None, partial, - complete=True, extra_files=logs, notes=notes, progress=packed) + complete=True, extra_files=logs, notes=text, progress=packed) if partial != target: replacing = True os.replace(io_path(partial), io_path(target)) @@ -3010,9 +3043,15 @@ def snapshot(self): own = (bool(row.get('error')) and not (self.error or self.browser_error or self.page_error) and not self.offline_page()) repair_state = dict(can_repair=self.can_repair(), repairs_comfy=self.repairs_comfy(), unavailable=self.repair_unavailable()) - launch = self.retry_kind() == 'launch' + retry = self.retry_kind() + launch = retry == 'launch' failure = self.both(lambda zh: launcher_failure(error, zh=zh, **repair_state, model_package=model_mismatch_package(raw_error, zh), - exception=row.get('exception') if own else None, launch=launch)) + exception=row.get('exception') if own else None, launch=launch, + check=retry == 'check')) + if retry == 'check' and '{button}' in failure.get('detail', ''): + # The sentence was translated with the placeholder; the button keeps its own name in the interface language. + from .i18n import fill + failure['detail'] = fill(failure['detail'], dict(button=self.t(*self.restart_button()))) if failure.get('kind') == 'gpu-driver-missing': from .display_adapters import adapters, line, nvidia_driver_listed, only_other_vendors names = adapters() diff --git a/freevideo_engine/lora_check.py b/freevideo_engine/lora_check.py index 33d052d6..ccb4359f 100644 --- a/freevideo_engine/lora_check.py +++ b/freevideo_engine/lora_check.py @@ -110,7 +110,9 @@ def _find(target): FAMILIES = (('wan', re.compile(r'\.(?:self_attn|cross_attn)\.|\.ffn\.\d|^head\.head')), ('hunyuan', re.compile(r'double_blocks|single_blocks')), - ('ltx', re.compile(r'\.attn[12]\.')), + # LTX: its video attention (attn1, attn2) and its audio branch (audio_attn1/2, the audio-video cross + # attention both ways, audio_ff). This model's own layers are attn.orig.*, audio_proj_in/out. + ('ltx', re.compile(r'\.(?:audio_)?attn[12]\.|\.(?:audio_to_video|video_to_audio)_attn\.|\.audio_ff\.')), ('sd', re.compile(r'down_blocks|up_blocks|input_blocks|lora_te|text_model'))) diff --git a/freevideo_engine/model_transfer.py b/freevideo_engine/model_transfer.py index f0aebdda..0aaa4dfa 100644 --- a/freevideo_engine/model_transfer.py +++ b/freevideo_engine/model_transfer.py @@ -380,8 +380,9 @@ def stage_overflow(directory, row, part_bytes): target = directory / row['file'] prefixes = (target, target.with_suffix(target.suffix + '.partial'), target.with_suffix(target.suffix + '.parallel_tmp'), directory / 'model.xet.incomplete') - ignored = ('.rejected-', '.hash-rejected-', '.interrupted-merge-', - '.restart-approved-', '.switch-retained-', '.oversized-', '.oversized-response-') + # Copies kept after a failure, by the names failed_copies knows (one list for every download), and merges stopped halfway. + from .failed_copies import REASONS + ignored = tuple('.%s-' % reason for reason in REASONS) + ('.interrupted-merge-',) for root, directories, files in os.walk(directory): directories[:] = [name for name in directories if name not in ('xet-cache', 'ms-cache', 'ms-home', 'hub-cache') and not any(marker in name for marker in ignored)] diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.py index f24745a4..57c63649 100644 --- a/freevideo_engine/modern_launcher.py +++ b/freevideo_engine/modern_launcher.py @@ -476,14 +476,14 @@ def reportProblem(self, error, title): def openReport(self, error, title): from . import __version__ - from .launcher_issue import adapter_line, environment_line, issue_url, machine_hardware, product_version, update_report_lines + from .launcher_issue import adapter_line, cuda_lines, environment_line, issue_url, machine_hardware, product_version, update_report_lines from .windows_ux import open_browser # The release (0.4.x) is named, not the build number; only fields that carry no path or user name travel. version = session.installed_product_version() or product_version(__version__) engine = session.installation_engine() url = issue_url(error, version, title, zh=session.chinese(), environment=environment_line(version, machine_hardware(engine) if engine else {}), - diagnostics=[adapter_line()] + update_report_lines(title)) + diagnostics=[adapter_line(), *cuda_lines(error)] + update_report_lines(title)) self.invoke(open_browser, url) @Slot() diff --git a/freevideo_engine/package_layout.py b/freevideo_engine/package_layout.py index 0ea3d725..ef0065f9 100644 --- a/freevideo_engine/package_layout.py +++ b/freevideo_engine/package_layout.py @@ -200,6 +200,25 @@ def ensure_container(path): directory_identity(path) +def folders_between(target, root, spell=None): + """The folders below ``root`` down to the one holding ``target``, outermost first. + + Both are spelled the same way first (on Windows the extended ``\\\\?\\`` form), so a root written without the prefix is + still met; a root that is not above ``target`` is an error, not a walk past the top of the drive. + """ + spell = spell or io_path + root = spell(root) + current = spell(target).parent + folders = [] + while current != root: + if current == current.parent: + raise ValueError('Package file %s is not inside the package folder %s' % (plain(target), plain(root))) + folders.append(current) + current = current.parent + folders.reverse() + return folders + + class DirectoryGuard: """Pin real directories; a replaced name must never become an import target.""" def __init__(self): @@ -259,12 +278,7 @@ def parent(self, target, root): # Windows) held once while files keep landing in it, and every file re-checks the innermost # one. Its identity is only reached through the folders above it, so a swapped ancestor # shows there; walking every ancestor per file cost several times the file write itself. - parents = [] - current = io_path(target).parent - while current != root: - parents.append(current) - current = current.parent - parents.reverse() + parents = folders_between(target, root) try: shared = 0 while shared < min(len(parents), len(self.chain)) and self.chain[shared][0] == parents[shared]: diff --git a/freevideo_engine/private_refs.py b/freevideo_engine/private_refs.py index 2b954943..acd1be51 100644 --- a/freevideo_engine/private_refs.py +++ b/freevideo_engine/private_refs.py @@ -82,6 +82,13 @@ def _walk(folder, suffixes, *, skip=()): yield os.path.join(parent, leaf) +def _holds(path): + """Whether a record in one of the extra folders keeps the files it names. A card's tombstone does not, nor the + backup of ComfyUI's unsaved workflow tabs (in the browser they never kept a file either).""" + posix = Path(path).as_posix() + return '/cast/.deleted/' not in posix and not Path(path).name.startswith('comfy-workflow-draft~') + + def _is_draft(path): """The creation draft the page keeps in the user folder. It names the pictures last set up, only so a start without the browser's copy can offer them again: it never keeps a file alive, and what is gone leaves it.""" @@ -146,7 +153,7 @@ def scan(*, output_root=None, user_root=None, queue=None, extra=(), roots=()): found = set(extra) for folder in roots: for path in _walk(Path(folder), ('.json', '.jsonl')): - if '/cast/.deleted/' not in Path(path).as_posix(): + if _holds(path): found |= tokens(_read_text(path)) if output_root is not None: root = Path(output_root) / 'FreeVideo' @@ -195,16 +202,19 @@ def released(output_root): return found -def run_sweep(*, input_root, output_root=None, user_root=None, queue=None, extra=(), root=None, now=None): +def run_sweep(*, input_root, output_root=None, user_root=None, queue=None, extra=(), roots=(), root=None, now=None): """One scan of earlier files; nothing is removed when any record cannot be read.""" from . import private_store try: - referenced = scan(output_root=output_root, user_root=user_root, queue=queue, extra=extra) + referenced = scan(output_root=output_root, user_root=user_root, queue=queue, extra=extra, roots=roots) except OSError as error: logging.warning('[FreeVideo] Private file cleanup skipped: a record could not be read (%s).', type(error).__name__) return None summary = private_store.sweep(input_root, referenced, root=root, now=now, released=released(output_root)) + # A prompt a deleted creation had and that could not yet be taken out of the histories kept for the page. + if root is None: + private_store.retry_forget(now=now) if not summary.get('dry_run'): scrub_draft(user_root, input_root) if output_root is not None: @@ -390,6 +400,10 @@ def legacy_delete(context, name): def _record_texts(context): output_root, user_root = context.get('output_root'), context.get('user_root') + for folder in context.get('roots', ()): + for path in _walk(Path(folder), ('.json', '.jsonl')): + if _holds(path): + yield _read_text(path) if output_root is not None: root = Path(output_root) / 'FreeVideo' for path in _walk(root, ('.json', '.jsonl'), skip=('.private',)): @@ -643,7 +657,15 @@ def default_context(): image = getattr(server, '_freevideo_image_gen', None) return dict(input_root=folder_paths.get_input_directory(), output_root=folder_paths.get_output_directory(), user_root=folder_paths.get_user_directory(), queue=getattr(server, 'prompt_queue', None), - extra=image.held_tokens() if image is not None and hasattr(image, 'held_tokens') else ()) + extra=image.held_tokens() if image is not None and hasattr(image, 'held_tokens') else (), + roots=held_roots()) + + +def held_roots(): + """Folders of records outside ComfyUI's own: what the page keeps in the engine's user data (its unsent editor + saves name uploaded files).""" + from . import user_store + return (user_store.root(),) def release_tokens(context, tokens): diff --git a/freevideo_engine/private_store.py b/freevideo_engine/private_store.py index 3fcca968..388a25c9 100644 --- a/freevideo_engine/private_store.py +++ b/freevideo_engine/private_store.py @@ -636,7 +636,7 @@ def last_sweep(root=None): FORGOTTEN_DAYS = 30 -def forget_prompts(hashes, *, root=None, now=None): +def forget_prompts(hashes, *, root=None, now=None, user_data=None): hashes = {h for h in hashes if isinstance(h, str) and re.fullmatch('[0-9a-f]{64}', h)} if not hashes: return @@ -648,6 +648,55 @@ def forget_prompts(hashes, *, root=None, now=None): if isinstance(when, (int, float)) and now - when < FORGOTTEN_DAYS * 86400} value.update(dict.fromkeys(hashes, now)) _write(path, value) + # The histories kept for the page (user_store) lose those prompts now, not when a page next asks; a store of + # another root (a test's) is left to its own caller. + if root is None or user_data is not None: + _pending_forget(hashes, root=root) + retry_forget(root=root, user_data=user_data, now=now) + + +# Prompts still to take out of the histories kept for the page: noted before the files are changed and cleared once +# they are, with no time limit, so a forget that fails (a file held open, a full disk) is tried again by every cleanup, +# and until then a read of those histories leaves the prompts out (user_store reads this list). +FORGET_PENDING = 'user-data-forget.json' + + +def forget_pending(*, root=None): + value = _read(store_root(root) / FORGET_PENDING) + return {key for key in value or () if isinstance(key, str) and re.fullmatch('[0-9a-f]{64}', key)} if isinstance(value, dict) else set() + + +def _pending_forget(hashes, *, root=None, done=False): + path = store_root(root) / FORGET_PENDING + with LOCK: + value = _read(path) or {} + if done: + value = {key: when for key, when in value.items() if key not in hashes} + else: + value.update(dict.fromkeys(hashes, time.time())) + if value: + _write(path, value) + else: + try: + os.unlink(path) + except FileNotFoundError: + pass + + +def retry_forget(*, root=None, user_data=None, now=None): + """Take the pending prompts out of the kept histories; returns whether none is left pending.""" + waiting = forget_pending(root=root) + if not waiting: + return True + from . import user_store + try: + user_store.forget(waiting, folder=user_data, salt_root=root, now=now) + except OSError as error: + logging.warning('[FreeVideo] Kept prompt histories were not updated yet (%s); the next cleanup tries again.', + type(error).__name__) + return False + _pending_forget(waiting, root=root, done=True) + return True def forgotten(texts, *, root=None, now=None): diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.json index 9bbcf509..edd91e88 100644 --- a/freevideo_engine/release_notes.json +++ b/freevideo_engine/release_notes.json @@ -1,41 +1,78 @@ { "schema": 1, - "product_version": "0.6.17", + "product_version": "0.6.18", "en": { - "summary": "0.6.17 shows the settings each video was made with, completes prompt enhancement when the rewrite leaves out a reference, explains graphics driver, installation and update problems more clearly, fits narrow phone screens, and fixes several messages, layouts and keyboard behaviours.", + "summary": "0.6.18 brings back the media of an earlier video with Reuse settings, gives characters their own voices, lets each line of a batch use its own media, fits notices and the character dialog to narrow windows, keeps what the page saved in FreeVideo's own data, explains why ComfyUI does not start when CUDA finds no graphics card, and fixes the second pass after Preview first when extending a video.", "changes": [ - "Prompts: When the rewrite still leaves out a reference after its correction, the missing label is added at the end of the scene and a note says so, instead of the enhancement failing; an incomplete rewrite now suggests using the original or editing the prompt instead of trying again. When a prompt asks someone to speak but does not include the words, a line under the prompt suggests putting the exact words in quotation marks.", - "Run settings: The Info tab in Create and Run details in Creations now show the quality level, seed and LoRAs a video was made with, and the sampling steps when they differ from the level's own; a video made with \"Preview first\" shows \"Light (Preview first)\". Compare shows the quality level and seed of both videos. On a phone, each item's label sits above its two values, and the Compare buttons move to a second row instead of being squeezed.", - "Image editing: An edit that needs only slightly more graphics memory than is free now starts, instead of being refused before it begins. When an image still cannot start, the message says how much graphics memory it needs and how much is free, and suggests closing other apps that use the graphics card or using fewer reference images, instead of mentioning the smallest size. On a Mac, the message does not give figures.", - "Image models: On a computer without an NVIDIA graphics card, the Models page in Settings and the image view's model picker now say \"Needs an NVIDIA graphics card\" instead of \"Not available on this computer\", and a failed generation suggests using Qwen-Image 2.1 instead.", - "Graphics driver cards: When the graphics card check stops without a reason and the NVIDIA driver is older than 580, the launcher asks you to update it and names the card and the driver version. An offline package checks the driver before it verifies its files. When the driver is installed but not running, the card says whether the card is disabled, its driver did not start, or Windows does not detect it, with the step for each. When FreeVideo is starting, the driver cards name the \"Retry launch\" button, and all their text appears in the interface language.", - "Setup and updates: On Linux, if the disk of the chosen installation folder cannot keep the files the FreeVideo environment needs, setup says so before anything is downloaded and suggests a folder in your home folder. The video model's code is downloaded in about 1 MB instead of about 56 MB. With an offline package, an engine update whose code is already in place returns to the start page instead of failing, and unreadable engine files no longer bring an update offer.", - "Multiple graphics cards: When FreeVideo is using one card because not every card was detected at startup, the Run status panel now says so and suggests restarting FreeVideo.", - "Assistant: When an assistant plans a film whose continued shots are too long for one video, the plan is refused at once with the shot named, instead of failing partway through filming; films started earlier can still reshoot their other shots, and the director in Autopilot reshoots such a shot as a new shot that starts from the last frame of the previous shot. In Autopilot, a task without a name is called \"Video\" or \"Image\" and shows its own prompt, instead of an earlier chat message.", - "Edit view: In the panel opened from \"Adjust\", the volume and text size sliders now have their own tips, instead of the tip for zooming. Esc closes the pop-up you are using first, such as prompt history, the @ reference list or the menu beside Generate, then the tour card, and only then clears the timeline selection.", - "Phone screens: At widths down to 320 px, the top bar shows the FreeVideo icon instead of the full logo so the view names fit, the buttons of Edit image move under the title instead of covering it, and a long hint in its prompt box shows on two lines. In the image view, the Generate area at the foot of the panel has a solid background and no longer covers the last settings. In the edit view, the player bar and the timeline tools take a second row instead of covering each other, and the prompt beside Generate shows whole lines.", - "Keyboard focus: Text boxes, menu items and options show one focus ring inside their edge, instead of a ring that was partly hidden or drawn twice, and the image view's prompt box shows its focus clearly in the light theme. Folding or opening the side panels of the image view, or the creations column, from the keyboard keeps the focus on the same control instead of sending it to the top of the page.", - "Layout: In the image view, when a download fails, \"Report a problem\" moves under the message when the two do not fit side by side, and words are no longer split. In the three-column layout, \"Video model not installed.\" above the Generate button is left-aligned like the line under it. Model names such as Qwen-Image 2.1 no longer break across lines, and they copy and search as written." + "Reuse settings: Reuse settings now also brings back the media an earlier video was made with; cards that were turned off stay turned off, and one Undo puts the whole panel back. When a file no longer exists, the notice names it and the rest is filled in. Reuse settings from Creations closes Creations first, so its notice can be seen. If you change the media afterwards, the \"Filled in\" notice and its Undo go away, as they already did when you change the prompt.", + "Characters: The New character and Edit character dialogs have a Voice section: choose audio or a video with sound in which only this person speaks, choose where the kept part starts, listen to it, and replace or remove it. Naming the character with @ in a prompt then adds its voice together with its pictures. After you save, the character details keep the current picture until the new one is ready, instead of flashing.", + "Media in prompts: When you turn off a media card, its place in the prompt is kept by name, such as [Turned off: cat.png], and the card is not sent to the model; turning it on again brings the label back. With One prompt per line, a line that names media with @ uses only that media, and the other lines use all media that is on; a character named with @ brings its own pictures and is written into the prompt as the subject. When a line names media that is turned off, not in Media or removed, the batch does not start and the message says which line and what to do.", + "Notices: A notice stays on one line when it fits and otherwise puts its buttons on a second row, also after the window is resized. Its words are never cut off; only a long file name is shortened. Between about 720 and 1064 px wide, notices are no longer squeezed. Closing an empty edit that is open elsewhere or still generating now keeps it without a notice. When making a prompt from a picture or video waits for another job, a plain note says so, without Report a problem, and clears itself. Once clicked, Report a problem reads \"Opened\" and does not open the same form again right away.", + "Narrow windows: In the character dialog, the tabs, view names and clothing options show whole words in every language at widths down to 320 px; when a word does not fit its tab, the tabs stand in a column, and the views go two by two. Under the prompt box, when the keys still do not fit after the AI and audio keys fold, \"From creations\" also shows only its icon.", + "Page check and opening screen: On a slow first start, the opening screen stays for up to two minutes instead of reporting that the creative workspace did not open; if the workspace opens after the card appeared, the card goes away by itself. FreeVideo's own scripts are no longer listed as errors of other ComfyUI extensions, and the card names the step that failed. The counting line on the opening screen follows the interface language.", + "Saved data and privacy: Prompt history, drafts and the other things the page keeps in the browser are now also kept in FreeVideo's user data, so they come back when you open FreeVideo at another address or in another browser. Deleting a creation also removes its prompt from the history; after the last creation is deleted, its prompt is also removed from ComfyUI's backup of unsaved workflow tabs, even when the page is not open.", + "Launcher: When CUDA cannot see any graphics card, the launcher no longer starts ComfyUI; it explains why and what to do: restart the computer, update the NVIDIA driver to 580 or newer, make sure the NVIDIA graphics card is enabled on a laptop, and open FreeVideo on the computer itself when connected through Remote Desktop. If the CUDA_VISIBLE_DEVICES environment variable hides every card, the message names it. When the driver is too old during the installation check, the message names the buttons on the page: Check again, and Continue after a restart.", + "Extending videos: After Preview first, running the second pass on the preview now finishes instead of stopping with an error. Long videos that have finished now appear in the job list.", + "LoRA check: A LoRA made only for the audio part of another model, such as one trained for the LTX-2.3 audio layers, is now reported as made for another model at every precision, instead of failing to merge in int8 or being let through in fp8 and bf16.", + "Connected assistants: Planning and generating a project's parts over HTTP, MCP and the command line works again. The planning report gives the same first and second passes that the jobs actually run, at every quality level and for previews. Reading a queued job no longer waits while another job is starting.", + "Downloads and offline packages: Pieces left by failed downloads for the Fast level are cleaned up by the same rule as other downloads, so they no longer pile up when a source cannot resume, and checking the transfer size no longer counts copies kept after a failure. An offline package is recognized even when its folder name differs in letter case or prefix; when the package folder is not above its files, an error is shown at once instead of waiting." ] }, "zh": { - "summary": "0.6.17 写出每个视频所用的生成设置;提示词增强在改写漏掉素材引用时自动补全;显卡驱动、安装和更新的问题说明得更清楚;窄屏手机上也能完整显示;多处提示、排版和键盘操作得到修正。", + "summary": "0.6.18 的“复用设置”会带回早先视频用过的素材;人物可以有自己的声音;批量生成时每一行可以用自己的素材;提示条和人物对话框在窄窗口下也能完整显示;页面保存在浏览器里的内容也保存到 FreeVideo 自己的数据里;CUDA 找不到显卡时启动器会说明原因;延长视频时“先出预览”后继续二采不再出错。", "changes": [ - "提示词:改写纠正后仍漏掉素材引用时,漏掉的标签会补在场景末尾并提示已补上,不再报错;改写结果不完整时,提示改为建议使用原文或修改提示词,不再让人重试。提示词要人说话却没有写出要说的话时,提示词下方会显示一行,建议用引号写出原话。", - "生成设置:创作面板的“信息”页和作品库的“运行详情”会写出视频所用的质量档位、种子和 LoRA,采样步数与档位默认不同时也会写出;用“先出预览”生成的视频写作“轻量(先出预览)”。“对比”会列出两个视频的质量档位和种子。在手机上,每一项的名称在上、两个值在下,对比工具栏的按钮放不下时换到第二排,不再被挤压。", - "图片编辑:所需显存只比可用显存多一点的编辑,现在可以开始生成,不再在开始前被拒绝。仍然无法开始时,提示会写明需要多少显存、当前可用多少,并建议关闭其他占用显卡的程序或减少参考图,不再提“最小尺寸”。在 Mac 上提示不写数字。", - "图像模型:在没有 NVIDIA 显卡的电脑上,设置的“模型”页和图片视图的模型选择器现在写“需要 NVIDIA 显卡”,不再写“这台电脑不支持”;生成失败时会建议改用 Qwen-Image 2.1。", - "显卡驱动提示:显卡检测没有给出原因就停止、而 NVIDIA 显卡驱动早于 580 时,启动器会显示要求更新驱动的卡片,并写明显卡型号和驱动版本;离线包会先检查驱动再校验文件。驱动已安装但未运行时,卡片会按 Windows 的设备状态说明是显卡被禁用、驱动未正常工作,还是 Windows 当前检测不到显卡,并给出对应的办法。启动 FreeVideo 时,驱动卡片中的按钮名为页面上实际的“重试启动”;卡片的全部文字(包括“检测到”一行)按界面语言显示。", - "安装与更新:在 Linux 上,所选安装位置所在的磁盘无法保存运行环境需要的文件时,安装程序会在下载之前说明,并建议改选主文件夹中的文件夹。下载视频模型代码时只需约 1 MB,不再是约 56 MB。使用离线包时,引擎代码已是最新的更新会回到启动页,不再显示失败;读不出引擎文件时,不再提示更新引擎。", - "多张显卡:启动时未能识别全部显卡、只使用一张显卡时,“运行状态”面板会写明这一点,并建议重启 FreeVideo。", - "助手:助手规划短片时,如果连续续接的镜头超过一个视频能容纳的长度,规划时就会拒绝并指出是哪个镜头,不再拍到中途才失败;之前已开拍的短片,其他镜头仍可重拍;AI 全自动里的导演遇到这种镜头,会改为从上一镜的最后一帧开始,作为新镜头重拍。AI 全自动中没有名称的任务显示为“视频”或“图片”,并显示任务自己的提示词,不再借用对话里较早的一条消息。", - "剪辑页:从“调整”打开的面板中,音量和文字大小滑块现在有各自的悬停提示,不再显示缩放的提示。按 Esc 时先关闭正在使用的弹出层(例如提示词历史、@ 引用列表或生成按钮旁的菜单),再关闭导览卡片,最后才清除时间线上的选区。", - "窄屏手机:窗口窄到 320 像素时,顶栏改为只显示 FreeVideo 图标,视图名称能完整显示;编辑图片的按钮移到标题下方,不再盖住标题,提示词框中较长的提示文字分两行显示。图片视图中,面板底部的生成区改为不透明底色,不再盖住最后几项设置。剪辑页的播放条和时间线工具放不下时换到第二行,不再互相遮挡;生成按钮旁的提示词按整行显示。", - "键盘焦点:文字输入框、菜单项和选项的焦点框改为画在框内的一圈,不再被遮住一部分或出现两层;图片视图的提示词框在浅色主题下获得焦点时也能看清。用键盘折叠或展开图片视图的侧栏或作品栏时,焦点留在原来的控件上,不再跳回页面最前面。", - "排版:图片视图中下载失败时,如果提示和“提交问题”放不下一行,“提交问题”会换到提示下面,单词不再从中间断开。三栏布局中,生成按钮上方的“视频模型未安装。”改为左对齐,与下面一行对齐。Qwen-Image 2.1 等模型名不再在中间折行,复制和查找时与原名一致。" + "复用设置:“复用设置”现在会一并带回早先视频用过的素材;当时关掉的卡仍是关闭的,点一次“撤销”就能恢复整个面板。文件已不存在时,提示会写出它的名字,其余内容照常填入。从作品库“复用设置”时会先关闭作品库,提示能看得到。之后再改素材,“已填入”提示和它的“撤销”会消失,和改提示词时一样。", + "人物:“新建角色”和“编辑角色”对话框新增“声音”一栏:选择一段只有这个人说话的音频或带声音的视频,选好保留部分从哪里开始,试听,也可以更换或移除。之后在提示词里用 @ 点名这个人物,声音会和图片一起带上。保存后,人物详情会保留当前的图片,等新图到了再换,不再先闪一下。", + "提示词里的素材:关掉一张素材卡时,提示词里它的位置会按名字保留,例如 [已关闭:cat.png],这张卡不会发送给模型;重新打开后标签恢复。使用“每行一条提示词”时,用 @ 点名素材的那一行只用被点名的素材,其他行使用全部已打开的素材;用 @ 点名的人物会带上自己的图片,并作为主体写进提示词。某一行点名的素材已关闭、不在素材中或已移除时,批量不会开始,提示会写明是哪一行、该怎么做。", + "提示条:整句放得下时提示条保持一行,放不下时按钮换到第二行,调整窗口大小时会重新判断。提示里的文字不再被截断,只有较长的文件名会在末尾省略。窗口宽约 720 到 1064 像素时,提示条不再被挤得看不见。关闭一个空的剪辑时,如果它还在另一个窗口打开着,或者还有片段正在生成,会直接关闭并保留这个剪辑,不再弹出提示。从图片或视频生成提示词时,如果要等别的任务,会显示一行普通提示,不带“提交问题”按钮,任务结束后自动消失。点过“提交问题”后按钮显示“已打开”,短时间内不会重复打开同一张表单。", + "窄窗口:人物对话框在窄到 320 像素时,标签页、视角名和服装选项在各种语言中都显示完整的词;某个词在标签里放不下时,标签改为上下排列,视角改为两列两行。提示词框下方的按键在 AI 和音频按键折叠后仍放不下时,“从作品库选择”也只显示图标。", + "页面检查和开场画面:较慢的电脑第一次启动时,开场画面最多保留两分钟,不再先报“创作面板未能打开”;卡片出现后面板又打开了,卡片会自动消失。FreeVideo 自己的脚本不再被列为其他 ComfyUI 扩展的错误,卡片会写明是哪一步失败。开场画面上那行计数文字按界面语言显示。", + "保存的内容和隐私:页面保存在浏览器里的提示词历史、草稿等内容,现在也会保存到 FreeVideo 的用户数据中,换一个地址或换一个浏览器打开 FreeVideo 也能找回。删除作品时,它的提示词也会从历史中清除;删除最后一个作品后,ComfyUI 未保存工作流标签的备份里如果还留着那条提示词,也会一并删除,页面没打开时也一样。", + "启动器:CUDA 找不到任何显卡时,不再启动 ComfyUI,而是说明原因和下一步:重启电脑、把 NVIDIA 驱动更新到 580 或更新版本、笔记本请确认 NVIDIA 显卡已启用、通过远程桌面连接时请在这台电脑本机上打开 FreeVideo。如果是环境变量 CUDA_VISIBLE_DEVICES 把显卡都隐藏了,提示会写出这个变量。安装检查时显卡驱动太旧,提示里写的是页面上真实的按钮:“重新检查”,以及重启后点的“继续”。", + "延长视频:选“先出预览”后,再对预览继续二采能正常完成,不再中途报错。已结束的长视频会出现在任务列表里。", + "LoRA 检查:只针对其他模型音频部分的 LoRA(例如为 LTX-2.3 音频层训练的),在各种精度下都会提示“这是为其他模型制作的 LoRA”,不再在 int8 下报无法合并,也不会在 fp8、bf16 下被放行。", + "已连接的助手:通过 HTTP、MCP 和命令行规划并生成项目的各段,又能正常使用。规划报告里写的第一遍、第二遍与实际生成时一致,各档位和预览都是如此。读取排队中的任务时,不再因为另一个任务正在启动而等待。", + "下载和离线包:极速档下载失败留下的残片按其他下载同样的规则清理,下载源无法续传时不再越积越多;检查传输大小时,失败后保留的副本不再计入。离线包所在文件夹的名称大小写或前缀和文件不同时也能认出;包文件夹不在文件上方时会立即报错,不再一直等待。" ] }, "history": [ + { + "product_version": "0.6.17", + "en": { + "summary": "0.6.17 shows the settings each video was made with, completes prompt enhancement when the rewrite leaves out a reference, explains graphics driver, installation and update problems more clearly, fits narrow phone screens, and fixes several messages, layouts and keyboard behaviours.", + "changes": [ + "Prompts: When the rewrite still leaves out a reference after its correction, the missing label is added at the end of the scene and a note says so, instead of the enhancement failing; an incomplete rewrite now suggests using the original or editing the prompt instead of trying again. When a prompt asks someone to speak but does not include the words, a line under the prompt suggests putting the exact words in quotation marks.", + "Run settings: The Info tab in Create and Run details in Creations now show the quality level, seed and LoRAs a video was made with, and the sampling steps when they differ from the level's own; a video made with \"Preview first\" shows \"Light (Preview first)\". Compare shows the quality level and seed of both videos. On a phone, each item's label sits above its two values, and the Compare buttons move to a second row instead of being squeezed.", + "Image editing: An edit that needs only slightly more graphics memory than is free now starts, instead of being refused before it begins. When an image still cannot start, the message says how much graphics memory it needs and how much is free, and suggests closing other apps that use the graphics card or using fewer reference images, instead of mentioning the smallest size. On a Mac, the message does not give figures.", + "Image models: On a computer without an NVIDIA graphics card, the Models page in Settings and the image view's model picker now say \"Needs an NVIDIA graphics card\" instead of \"Not available on this computer\", and a failed generation suggests using Qwen-Image 2.1 instead.", + "Graphics driver cards: When the graphics card check stops without a reason and the NVIDIA driver is older than 580, the launcher asks you to update it and names the card and the driver version. An offline package checks the driver before it verifies its files. When the driver is installed but not running, the card says whether the card is disabled, its driver did not start, or Windows does not detect it, with the step for each. When FreeVideo is starting, the driver cards name the \"Retry launch\" button, and all their text appears in the interface language.", + "Setup and updates: On Linux, if the disk of the chosen installation folder cannot keep the files the FreeVideo environment needs, setup says so before anything is downloaded and suggests a folder in your home folder. The video model's code is downloaded in about 1 MB instead of about 56 MB. With an offline package, an engine update whose code is already in place returns to the start page instead of failing, and unreadable engine files no longer bring an update offer.", + "Multiple graphics cards: When FreeVideo is using one card because not every card was detected at startup, the Run status panel now says so and suggests restarting FreeVideo.", + "Assistant: When an assistant plans a film whose continued shots are too long for one video, the plan is refused at once with the shot named, instead of failing partway through filming; films started earlier can still reshoot their other shots, and the director in Autopilot reshoots such a shot as a new shot that starts from the last frame of the previous shot. In Autopilot, a task without a name is called \"Video\" or \"Image\" and shows its own prompt, instead of an earlier chat message.", + "Edit view: In the panel opened from \"Adjust\", the volume and text size sliders now have their own tips, instead of the tip for zooming. Esc closes the pop-up you are using first, such as prompt history, the @ reference list or the menu beside Generate, then the tour card, and only then clears the timeline selection.", + "Phone screens: At widths down to 320 px, the top bar shows the FreeVideo icon instead of the full logo so the view names fit, the buttons of Edit image move under the title instead of covering it, and a long hint in its prompt box shows on two lines. In the image view, the Generate area at the foot of the panel has a solid background and no longer covers the last settings. In the edit view, the player bar and the timeline tools take a second row instead of covering each other, and the prompt beside Generate shows whole lines.", + "Keyboard focus: Text boxes, menu items and options show one focus ring inside their edge, instead of a ring that was partly hidden or drawn twice, and the image view's prompt box shows its focus clearly in the light theme. Folding or opening the side panels of the image view, or the creations column, from the keyboard keeps the focus on the same control instead of sending it to the top of the page.", + "Layout: In the image view, when a download fails, \"Report a problem\" moves under the message when the two do not fit side by side, and words are no longer split. In the three-column layout, \"Video model not installed.\" above the Generate button is left-aligned like the line under it. Model names such as Qwen-Image 2.1 no longer break across lines, and they copy and search as written." + ] + }, + "zh": { + "summary": "0.6.17 写出每个视频所用的生成设置;提示词增强在改写漏掉素材引用时自动补全;显卡驱动、安装和更新的问题说明得更清楚;窄屏手机上也能完整显示;多处提示、排版和键盘操作得到修正。", + "changes": [ + "提示词:改写纠正后仍漏掉素材引用时,漏掉的标签会补在场景末尾并提示已补上,不再报错;改写结果不完整时,提示改为建议使用原文或修改提示词,不再让人重试。提示词要人说话却没有写出要说的话时,提示词下方会显示一行,建议用引号写出原话。", + "生成设置:创作面板的“信息”页和作品库的“运行详情”会写出视频所用的质量档位、种子和 LoRA,采样步数与档位默认不同时也会写出;用“先出预览”生成的视频写作“轻量(先出预览)”。“对比”会列出两个视频的质量档位和种子。在手机上,每一项的名称在上、两个值在下,对比工具栏的按钮放不下时换到第二排,不再被挤压。", + "图片编辑:所需显存只比可用显存多一点的编辑,现在可以开始生成,不再在开始前被拒绝。仍然无法开始时,提示会写明需要多少显存、当前可用多少,并建议关闭其他占用显卡的程序或减少参考图,不再提“最小尺寸”。在 Mac 上提示不写数字。", + "图像模型:在没有 NVIDIA 显卡的电脑上,设置的“模型”页和图片视图的模型选择器现在写“需要 NVIDIA 显卡”,不再写“这台电脑不支持”;生成失败时会建议改用 Qwen-Image 2.1。", + "显卡驱动提示:显卡检测没有给出原因就停止、而 NVIDIA 显卡驱动早于 580 时,启动器会显示要求更新驱动的卡片,并写明显卡型号和驱动版本;离线包会先检查驱动再校验文件。驱动已安装但未运行时,卡片会按 Windows 的设备状态说明是显卡被禁用、驱动未正常工作,还是 Windows 当前检测不到显卡,并给出对应的办法。启动 FreeVideo 时,驱动卡片中的按钮名为页面上实际的“重试启动”;卡片的全部文字(包括“检测到”一行)按界面语言显示。", + "安装与更新:在 Linux 上,所选安装位置所在的磁盘无法保存运行环境需要的文件时,安装程序会在下载之前说明,并建议改选主文件夹中的文件夹。下载视频模型代码时只需约 1 MB,不再是约 56 MB。使用离线包时,引擎代码已是最新的更新会回到启动页,不再显示失败;读不出引擎文件时,不再提示更新引擎。", + "多张显卡:启动时未能识别全部显卡、只使用一张显卡时,“运行状态”面板会写明这一点,并建议重启 FreeVideo。", + "助手:助手规划短片时,如果连续续接的镜头超过一个视频能容纳的长度,规划时就会拒绝并指出是哪个镜头,不再拍到中途才失败;之前已开拍的短片,其他镜头仍可重拍;AI 全自动里的导演遇到这种镜头,会改为从上一镜的最后一帧开始,作为新镜头重拍。AI 全自动中没有名称的任务显示为“视频”或“图片”,并显示任务自己的提示词,不再借用对话里较早的一条消息。", + "剪辑页:从“调整”打开的面板中,音量和文字大小滑块现在有各自的悬停提示,不再显示缩放的提示。按 Esc 时先关闭正在使用的弹出层(例如提示词历史、@ 引用列表或生成按钮旁的菜单),再关闭导览卡片,最后才清除时间线上的选区。", + "窄屏手机:窗口窄到 320 像素时,顶栏改为只显示 FreeVideo 图标,视图名称能完整显示;编辑图片的按钮移到标题下方,不再盖住标题,提示词框中较长的提示文字分两行显示。图片视图中,面板底部的生成区改为不透明底色,不再盖住最后几项设置。剪辑页的播放条和时间线工具放不下时换到第二行,不再互相遮挡;生成按钮旁的提示词按整行显示。", + "键盘焦点:文字输入框、菜单项和选项的焦点框改为画在框内的一圈,不再被遮住一部分或出现两层;图片视图的提示词框在浅色主题下获得焦点时也能看清。用键盘折叠或展开图片视图的侧栏或作品栏时,焦点留在原来的控件上,不再跳回页面最前面。", + "排版:图片视图中下载失败时,如果提示和“提交问题”放不下一行,“提交问题”会换到提示下面,单词不再从中间断开。三栏布局中,生成按钮上方的“视频模型未安装。”改为左对齐,与下面一行对齐。Qwen-Image 2.1 等模型名不再在中间折行,复制和查找时与原名一致。" + ] + } + }, { "product_version": "0.6.16", "en": { @@ -403,35 +440,6 @@ "教程补充:新增导出 48 或 60 fps 视频的方法,以及 MOSS-Image 布局框的用法。" ] } - }, - { - "product_version": "0.6.5", - "en": { - "summary": "Image model downloads no longer pause while the image view only warms a model; export supports 48 and 60 fps; pictures are also saved to the output folder; LoRA choice uses FreeVideo's own menu; and face close-ups and failure messages are improved.", - "changes": [ - "Image models: a download no longer pauses as if a video were generating when the image view only keeps or warms a model, a paused download says why, and Continue download starts it at once; a model folder or its files may be symbolic links (junctions on Windows) to another drive; a link that leads nowhere or to a damaged or different file says why and what to do next, and only that model fails; MOSS-Image warms up from its own files and renders normally on Windows with less than 24 GB of video memory; and when opened from ComfyUI, H3 Image allocates GPU memory as video generation does.", - "Export at 48 or 60 fps: Frame rate in the Export window now offers 48 and 60, with the frames in between made on the graphics card, cuts and still frames kept as they are and the sound copied unchanged; a full disk is reported as a full disk, and plainly too little space is said before the graphics card starts.", - "Face pictures of a character after a change of clothes: a Face picture framed too wide is redrawn larger once, a repaint that kept the old clothes is tried again, and when no face box is found the clothes are repainted inside a fixed area.", - "Pictures and seeds: each picture made or imported is also copied into the output folder as a file of its own, removed when the picture is deleted for good and switchable off in Settings; the dice next to Seed in the Image view fills in a random seed, and an empty Seed still draws a new one each time.", - "Choosing a LoRA: the LoRA choice opens FreeVideo's own menu, where a long list scrolls, typing filters it, LoRAs are grouped by folder and the keyboard works, in the dark and light themes and in narrow windows.", - "Failures say why and what to do next, continued: in the Edit view, the Image view, the Create panel, the generation progress card and notifications a failure states the cause and the next step and offers Report a problem, never a raw failure code; an engine stop, a failed model download and a video closed from its history name their reason, and a full disk during a download is named; a LoRA that stores one alpha for layers of different ranks is marked unusable before generation with the reason; an out-of-range picture setting is named.", - "Report a problem: for a known failure with a clear fix, that fix is shown first and the report can still be sent after it; the issue text the launcher fills in starts with the display adapter model for every kind of error.", - "Edit view subtitles: when the subtitle track holds only an empty line just added, Auto subtitles places the lines it heard without saying they replaced the subtitles there; when the lines there have words, the notice and its Undo are as before." - ] - }, - "zh": { - "summary": "图像模型下载不再在预热时误停;导出支持 48 和 60 fps;图片同时保存到 output 文件夹;LoRA 选择改用 FreeVideo 自己的菜单,脸部特写与失败说明更完善。", - "changes": [ - "图像模型:图像视图只是预热或保留模型时,图像模型下载不再以“视频生成中”暂停,暂停时写明实际原因,可用“继续下载”立即开始;模型文件夹、其子文件夹或模型文件通过符号链接(Windows 上也可用目录联接)放在其他磁盘时照常使用,链接失效或指向损坏、不同的文件时说明原因和下一步,图片页只把该模型标为出错;MOSS-Image 预热只读取自己的模型文件,Windows 上显存小于 24 GB 时可以正常出图;由 ComfyUI 打开时,H3 Image 使用与视频生成相同的显存分配方式。", - "导出 48 或 60 fps:导出窗口的“帧率”新增 48 和 60,中间帧在显卡上补出,剪切处和静止画面保持原样,声音原样复制;磁盘写满时直接说明磁盘已满,空间明显不足时在显卡开始工作前就会提示。", - "角色更换服装后的脸部特写:脸部特写取景过宽时放大重画一次;重画后仍是原来的衣服时自动重试;识别不到脸部位置时,在固定区域内重画衣服。", - "图片保存与种子:生成或导入的图片同时复制一份到 output 文件夹,副本是独立文件,图片永久删除时一并删除,可在设置中关闭;图像视图种子旁的骰子会填入一个随机种子,留空时仍每次随机。", - "LoRA 选择:选择 LoRA 时打开 FreeVideo 自己的菜单,长列表可以滚动,输入文字即可筛选,按文件夹分组,可用键盘操作,深色、浅色主题和窄窗口下都能正常使用。", - "失败时说明原因和下一步(续):剪辑视图、图像视图、创作面板、生成进度卡片和通知中的失败都写明原因和下一步并可提交问题,不再显示原始错误代码;引擎停止、模型下载失败、从历史中关闭的视频也说明原因,下载时磁盘已满会直接说明;同一个 alpha 对应不同秩的 LoRA 在生成前即标为不可用并说明原因;图片设置超出范围时分别说明是哪一项。", - "提交问题:已知错误且已有明确建议时,先显示该建议,看完仍可继续提交;启动器预填的问题正文对各类错误都以显示适配器型号开头。", - "剪辑视图的字幕:字幕轨上只有刚添加的空字幕时,自动字幕直接写入识别结果,不再提示“识别出的字幕已替换原有字幕”;原有字幕带文字时,提示与“撤销”照旧。" - ] - } } ] } diff --git a/freevideo_engine/restore.py b/freevideo_engine/restore.py new file mode 100644 index 00000000..1cbffd5a --- /dev/null +++ b/freevideo_engine/restore.py @@ -0,0 +1,456 @@ +"""A work back as a generate request, from what its file keeps: read only, nothing is made. + +A FreeVideo video keeps the ComfyUI prompt it ran and the canvas workflow as two QuickTime keys in its moov box +(comfy_metadata.embed_comfy_metadata); a PNG keeps them as text chunks, as ComfyUI writes them; a work in the library +also keeps the canvas workflow beside the video (workflow.json). spec.from_comfy turns them into a request. + +A dropped file is untrusted: it is read here, never by a media library, and only the boxes and chunks that can hold +the two keys are read, each within a limit. Anything malformed, truncated or over a limit reads as "nothing to +restore", never as an error of the reader. +""" +import json +import logging +import os +from pathlib import Path +import re +import struct +import zlib + +from .agent import spec_comfy +from .agent.spec import SpecError + +KEYS = ('prompt', 'workflow') +MAX_MOOV = 64 * 1024 * 1024 # the moov box read into memory +MAX_VALUE = 32 * 1024 * 1024 # one key's value, also once decompressed +MAX_BOXES = 4096 # boxes walked in one file +MAX_DEPTH = 8 # boxes inside boxes +MAX_CHUNKS = 100000 # PNG chunks walked +MAX_KEYS = 64 # names in a QuickTime keys box (FreeVideo writes two) +# A key's JSON: values in it (objects, arrays and scalars) and the longest string. The largest seen in 6,409 real +# works and saves is 2,430 values and 10,522 characters; these are about 20 and 95 times that. +MAX_NODES = 50000 +MAX_STRING = 1000000 +CONTAINERS = {b'moov', b'udta', b'meta', b'trak', b'mdia', b'minf', b'stbl', b'edts', b'dinf'} +PNG_SIGNATURE = b'\x89PNG\r\n\x1a\n' +WORK = re.compile(r'^(\d{4}-\d{2}-\d{2})/([0-9a-f]{32})$') +NOTHING = ('This file has no FreeVideo settings that can be restored.', '这个文件中没有可以还原的 FreeVideo 设置。') +UNREADABLE = ('The settings in this file could not be read.', '无法读取这个文件中的设置。') + + +class Unreadable(ValueError): + """The file is malformed, truncated or over a limit.""" + + +def _box_header(stream, end): + """(type, start of body, end of box) of the box at the stream's position, or None at the end.""" + start = stream.tell() + if start + 8 > end: + return None + head = stream.read(8) + if len(head) < 8: + raise Unreadable('truncated box header') + size, kind = struct.unpack('>I4s', head) + body = start + 8 + if size == 1: + large = stream.read(8) + if len(large) < 8: + raise Unreadable('truncated box size') + size = struct.unpack('>Q', large)[0] + body += 8 + elif size == 0: + size = end - start + if size < body - start or start + size > end: + raise Unreadable('box size outside its parent') + return kind, body, start + size + + +def _mdta_values(moov): + """{key: value} of the QuickTime keys under moov (moov/meta or moov/udta/meta with handler mdta). ``moov`` is + a memoryview: boxes are views of it, never copies.""" + found, walked = {}, [0] + + def count(number=1): + walked[0] += number + if walked[0] > MAX_BOXES: + raise Unreadable('too many boxes') + + def walk(data, depth): + if depth > MAX_DEPTH: + raise Unreadable('boxes nested too deep') + at, boxes = 0, [] + while at + 8 <= len(data): + count() + size, kind = struct.unpack_from('>I4s', data, at) + head = 8 + if size == 1: + if at + 16 > len(data): + raise Unreadable('truncated box size') + size, head = struct.unpack_from('>Q', data, at + 8)[0], 16 + elif size == 0: + size = len(data) - at + if size < head or at + size > len(data): + raise Unreadable('box size outside its parent') + boxes.append((kind, data[at + head:at + size])) + at += size + return boxes + + def meta(body, depth): + # A QuickTime meta box has no version field; an ISO one has four bytes of it first. + for offset in (0, 4): + try: + boxes = walk(body[offset:], depth) + except Unreadable: + continue + kinds = [kind for kind, _ in boxes] + if b'keys' in kinds and b'ilst' in kinds: + return boxes + return [] + + def keys_of(body): + if len(body) < 8: + raise Unreadable('short keys box') + number = struct.unpack_from('>I', body, 4)[0] + if number > MAX_KEYS: + raise Unreadable('too many keys') + count(number) + names, at = [], 8 + for _ in range(number): + if at + 8 > len(body): + raise Unreadable('truncated keys box') + size, space = struct.unpack_from('>I4s', body, at) + if size < 8 or at + size > len(body): + raise Unreadable('key size outside its box') + names.append(bytes(body[at + 8:at + size]).decode('utf-8', 'replace') if space == b'mdta' else None) + at += size + return names + + def search(data, depth): + for kind, body in walk(data, depth): + if kind == b'meta': + boxes = meta(body, depth + 1) + handler = next((b for k, b in boxes if k == b'hdlr'), memoryview(b'')) + if len(handler) >= 12 and bytes(handler[8:12]) != b'mdta': + continue + names = next((keys_of(b) for k, b in boxes if k == b'keys'), []) + for kind_item, item in walk(next((b for k, b in boxes if k == b'ilst'), memoryview(b'')), depth + 2): + index = struct.unpack('>I', kind_item)[0] - 1 + if not 0 <= index < len(names) or names[index] not in KEYS or names[index] in found: + continue + for kind_data, data_box in walk(item, depth + 3): + # data box: type indicator (1 = UTF-8), locale, then the value. + if kind_data == b'data' and len(data_box) >= 8 and bytes(data_box[:4]) == b'\x00\x00\x00\x01': + value = data_box[8:] + if len(value) > MAX_VALUE: + raise Unreadable('value over the limit') + found[names[index]] = str(value, 'utf-8', 'replace') # decoded from the view, no copy + break + elif kind == b'udta': + search(body, depth + 1) + + search(moov, 0) + return found + + +def mp4_tags(path): + """{'prompt': text, 'workflow': text} an MP4 keeps (either may be absent). Raises Unreadable.""" + with open(path, 'rb') as stream: + end = os.fstat(stream.fileno()).st_size + boxes = 0 + while True: + boxes += 1 + if boxes > MAX_BOXES: + raise Unreadable('too many top-level boxes') + header = _box_header(stream, end) + if header is None: + return {} + kind, body, stop = header + if boxes == 1 and kind != b'ftyp': + raise Unreadable('not an MP4 file') + if kind == b'moov': + if stop - body > MAX_MOOV: + raise Unreadable('moov over the limit') + data = stream.read(stop - body) + if len(data) < stop - body: + raise Unreadable('truncated moov') + return _mdta_values(memoryview(data)) + stream.seek(stop) + + +def png_tags(path): + """{'prompt': text, 'workflow': text} a PNG keeps as text chunks (tEXt, iTXt, zTXt). Raises Unreadable.""" + found = {} + with open(path, 'rb') as stream: + if stream.read(8) != PNG_SIGNATURE: + raise Unreadable('not a PNG file') + for _ in range(MAX_CHUNKS): + head = stream.read(8) + if len(head) < 8: + raise Unreadable('truncated chunk') + length, kind = struct.unpack('>I4s', head) + if kind == b'IEND': + return found + if kind not in (b'tEXt', b'iTXt', b'zTXt'): + stream.seek(length + 4, os.SEEK_CUR) + continue + if length > MAX_VALUE + 1024: + raise Unreadable('text chunk over the limit') + data = stream.read(length) + stream.seek(4, os.SEEK_CUR) + if len(data) < length: + raise Unreadable('truncated chunk') + name, _, rest = data.partition(b'\x00') + key = name.decode('latin-1') + if key not in KEYS or key in found: + continue + if kind == b'tEXt': + found[key] = rest.decode('latin-1') + elif kind == b'zTXt': + found[key] = _inflate(rest[1:]).decode('latin-1') + else: + if len(rest) < 2: + raise Unreadable('short iTXt chunk') + compressed, text = rest[0], rest[2:] + # language tag and translated keyword, each ended by a zero byte + parts = text.split(b'\x00', 2) + if len(parts) < 3: + raise Unreadable('short iTXt chunk') + found[key] = (_inflate(parts[2]) if compressed else parts[2]).decode('utf-8', 'replace') + raise Unreadable('too many chunks') + + +def _inflate(data): + inflater = zlib.decompressobj() + try: + value = inflater.decompress(data, MAX_VALUE + 1) + except zlib.error as error: + raise Unreadable('compressed text does not inflate') from error + if len(value) > MAX_VALUE or inflater.unconsumed_tail: + raise Unreadable('text over the limit once inflated') + return value + + +def file_tags(path): + """The keys of a dropped MP4 or PNG, by its first bytes (not its name). Raises Unreadable.""" + with open(path, 'rb') as stream: + start = stream.read(12) + if start[:8] == PNG_SIGNATURE: + return png_tags(path), 'png' + if start[4:8] == b'ftyp': + return mp4_tags(path), 'mp4' + raise Unreadable('neither an MP4 nor a PNG file') + + +def _json(text, *, limits=False): + """The JSON object ``text`` holds, or None. With ``limits`` (a file's keys), a value with more values than + MAX_NODES or a string longer than MAX_STRING raises Unreadable. The values are bounded before anything is parsed: + JSON never holds more than one value more than it has brackets and commas.""" + if not isinstance(text, str): + return None + if limits and text.count('{') + text.count('[') + text.count(',') > MAX_NODES: + raise Unreadable('too many values') + try: + value = json.loads(text) + except (ValueError, RecursionError): + return None + if not isinstance(value, dict): + return None + if limits: + stack = [value] + while stack: + item = stack.pop() + if isinstance(item, dict): + if any(len(key) > MAX_STRING for key in item): + raise Unreadable('string over the limit') + stack.extend(item.values()) + elif isinstance(item, list): + stack.extend(item) + elif isinstance(item, str) and len(item) > MAX_STRING: + raise Unreadable('string over the limit') + return value + + +def _read_json(path): + try: + return _json(Path(path).read_text(encoding='utf-8')) + except (OSError, UnicodeDecodeError): + return None + + +def _answer(state, words=None, **extra): + value = dict(state=state, request=None, notes=[], missing=[], open_in_comfy=[], version=spec_comfy.FROM_COMFY_VERSION) + if words: + value['reason'] = dict(en=words[0], zh=words[1]) + value.update(extra) + return value + + +def from_tags(tags, *, resolve=None, source='file'): + """The answer for the keys a file keeps: ready (with the request), open_in_comfy, or unreadable.""" + try: + prompt, workflow = _json(tags.get('prompt'), limits=True), _json(tags.get('workflow'), limits=True) + except Unreadable as error: + return _answer('unreadable', UNREADABLE, source=source, detail=str(error)) + if not prompt and not workflow: + return _answer('unreadable', NOTHING, source=source) + graph = {key: value for key, value in (('prompt', prompt), ('workflow', workflow)) if value} + try: + try: + read = spec_comfy.from_comfy(graph, resolve=resolve) + except spec_comfy.OpenInComfy: + raise + except SpecError: + # A prompt key that names no FreeVideo generator (another tool wrote it): the canvas workflow may still. + if not (prompt and workflow): + raise + read = spec_comfy.from_comfy({'workflow': workflow}, resolve=resolve) + except spec_comfy.OpenInComfy as error: + return _answer('open_in_comfy', spec_comfy.OPEN_IN_COMFY, source=source, open_in_comfy=error.nodes) + except SpecError as error: + return _answer('unreadable', NOTHING, source=source, detail=str(error)[:500]) + return dict(_answer('ready', source=source), request=read['request'], notes=read['notes'], missing=read['missing'], + repaired=read['repaired'], version=read['version']) + + +def _malformed(error, source): + """The answer for a file whose content broke a reader: only the kind of failure is logged, nothing of the file.""" + logging.info('[FreeVideo] A file to restore could not be read (%s).', type(error).__name__) + return _answer('unreadable', UNREADABLE, source=source, detail='malformed') + + +def inside(root, relative): + """The real path of `relative` under `root`, or None when it leaves it (.., an absolute path, a link outward).""" + if not isinstance(relative, str) or not relative or '\x00' in relative: + return None + root = Path(root).resolve() + path = (root / relative).resolve() + try: + path.relative_to(root) + except ValueError: + return None + return path + + +def input_resolver(input_root): + """resolve(file) for from_comfy: a file in ComfyUI's input folder comes in as it is; one that is not there is + missing (None).""" + def resolve(file): + path = inside(input_root, file) if isinstance(file, str) else None + return {'file': file} if path is not None and path.is_file() else None + return resolve + + +def restore_file(path, *, input_root=None): + """The answer for a dropped file (an upload in the input folder). Never raises.""" + try: + tags, kind = file_tags(path) + except (Unreadable, OSError) as error: + return _answer('unreadable', UNREADABLE, source='file', detail=str(error)[:200]) + except Exception as error: # noqa: BLE001 + return _malformed(error, 'file') + try: + return from_tags(tags, resolve=input_resolver(input_root) if input_root else None, source=kind) + except Exception as error: # noqa: BLE001 + return _malformed(error, kind) + + +def restore_work(work, *, output_root, input_root=None): + """The answer for a work of the library; never raises (see _restore_work).""" + try: + return _restore_work(work, output_root=output_root, input_root=input_root) + except Exception as error: # noqa: BLE001 + return _malformed(error, 'library') + + +def _restore_work(work, *, output_root, input_root=None): + """The answer for a work of the library ('YYYY-MM-DD/'): the video's own keys first (they hold the exact + prompt), else the canvas workflow kept beside it. What kind of run it was is noted.""" + if not isinstance(work, str) or not WORK.match(work): + return _answer('unreadable', NOTHING, source='library', detail='not a library work') + folder = inside(Path(output_root) / 'FreeVideo', work) + if folder is None or not folder.is_dir(): + return _answer('unreadable', NOTHING, source='library', detail='no such work') + resolve = input_resolver(input_root) if input_root else None + tags = {} + video = folder / 'video.mp4' + if video.is_file() and inside(folder, 'video.mp4') is not None: + try: + tags = mp4_tags(video) + except (Unreadable, OSError): + tags = {} + if not _json(tags.get('prompt')) and not _json(tags.get('workflow')): + from .comfy_metadata import saved_workflow + workflow = saved_workflow(folder / 'workflow.json') if inside(folder, 'workflow.json') is not None else None + tags = {'workflow': json.dumps(workflow)} if workflow else {} + answer = from_tags(tags, resolve=resolve, source='library') + state = _read_json(folder / 'comfy-request.json') if inside(folder, 'comfy-request.json') is not None else None + run = {} + if isinstance(state, dict): + if state.get('preview') is True: + run['preview'] = True + if isinstance(state.get('command'), list) and '--upscale-from' in state['command']: + run['upscale'] = True + if isinstance(state.get('status'), str) and state['status'] != 'complete': + run['status'] = state['status'] + if (folder / 'media.json').is_file() and inside(folder, 'media.json') is not None: + run['media_kept'] = True + if run and answer['state'] == 'ready': + answer['notes'] = answer['notes'] + [dict(run=run)] + return answer + + +def register(server=None, *, input_root=None, output_root=None): + """POST /freevideo/restore {file: an upload's path in the input folder} or {work: a library work}: read only. + The folders default to ComfyUI's input and output folders, read on each request.""" + import asyncio + from aiohttp import web + if server is None: + from server import PromptServer + server = PromptServer.instance + if server is None or getattr(server, '_freevideo_restore_registered', False): + return + server._freevideo_restore_registered = True + + def folders(): + if input_root is not None and output_root is not None: + return input_root, output_root + import folder_paths + return (input_root or folder_paths.get_input_directory(), output_root or folder_paths.get_output_directory()) + + def reply(value, status=200): + return web.json_response(value, status=status, headers={'Cache-Control': 'no-store'}) + + # One file is read at a time (a reader holds up to a moov and a value in memory); the request body is read first, + # outside it, so a slow sender holds nothing up. + gate = asyncio.Semaphore(1) + + @server.routes.post('/freevideo/restore') + async def restore(request): + # It reads an upload: a page of this server only, as the editor's writes (another site's form or script is + # refused, a signed-in device through the sign-in proxy is not). + from .comfy_editor import _local_page + if not _local_page(request): + return reply({'error': 'Not allowed', 'code': 'forbidden'}, 403) + try: + return await answer_for(request) + except Exception as error: # noqa: BLE001 - only a fixed sentence goes back + logging.info('[FreeVideo] A restore request failed (%s).', type(error).__name__) + return reply({'error': 'The file could not be read.', 'code': 'unreadable'}, 422) + + async def answer_for(request): + try: + body = await request.json() + except (ValueError, RecursionError): + body = None + if not isinstance(body, dict) or (('file' in body) == ('work' in body)): + return reply({'error': 'Send file or work', 'code': 'invalid_request'}, 400) + inputs, outputs = folders() + if 'file' in body: + path = inside(inputs, body['file']) + if path is None or not path.is_file(): + return reply({'error': 'No such file in the input folder', 'code': 'not_found'}, 404) + async with gate: + answer = await asyncio.to_thread(restore_file, path, input_root=inputs) + else: + async with gate: + answer = await asyncio.to_thread(restore_work, body['work'], output_root=outputs, input_root=inputs) + return reply(answer) diff --git a/freevideo_engine/user_store.py b/freevideo_engine/user_store.py new file mode 100644 index 00000000..cf943c0d --- /dev/null +++ b/freevideo_engine/user_store.py @@ -0,0 +1,518 @@ +"""What the page keeps only in its browser, also kept here: one file per key under the engine's own user-data folder. + +The folder does not follow the page's address or port, so the page finds its prompts, presets, tags and unsent +editor saves again when the address changes or the browser's site data is cleared. The page stays the owner: it +writes here what it holds and reads back only when it holds nothing (s0-browser-store-mirror). + +Each file is {key, rev, sha256, value, updated_at}: ``value`` is the page's stored string as it is, ``sha256`` its +UTF-8 digest, ``rev`` counts the writes (a key never written is rev 0). A write names the rev it read; another rev +is a conflict. Files are written whole (a staging file replaced into place) and only keys on the list below are +taken, each up to its own size. + +Prompts are private: the histories here count as records for the private file cleanup, a prompt that only deleted +works had is taken out of them (``forget``), and nothing of a value is ever logged or reported, only keys and error +codes. +""" +import hashlib +import json +import logging +import os +import re +import threading +import time +from pathlib import Path + +from .long_paths import io_path + +KB, MB = 1024, 1024 * 1024 +# The keys the page keeps only in its browser, each with the most it may hold. +KEYS = { + 'freevideo.prompts.history': 2 * MB, 'freevideo.prompts.presets': 2 * MB, + 'freevideo.imageView.prompts': 2 * MB, 'freevideo.imageView.presets': 2 * MB, 'freevideo.imageView.meta': 2 * MB, + 'freevideo.library.tags': MB, 'freevideo.library.picture-favorites': MB, + 'freevideo.subtitle-presets': 256 * KB, 'freevideo.editor.export-settings': 256 * KB, + 'freevideo_lora_recent': 256 * KB, 'freevideo_image_loras': 256 * KB, +} +# Keys with a part of their own after a fixed start: the editor's unsent saves (one per session) and a backup of +# ComfyUI's unsaved workflow tabs. Each family holds at most COPIES keys. +FAMILIES = ( + ('fv-editor-outbox', re.compile(r'fv-editor-outbox(?::[A-Za-z0-9_-]{1,64})?'), 8 * MB), + ('comfy-workflow-draft', re.compile(r'Comfy\.Workflow\.Draft[^\x00-\x1f\x7f]{0,200}'), 8 * MB), +) +COPIES = 32 +# The prompt histories, and the presets whose prompts stay in them when a deleted work had them too +# (the page's own rule, prompt_library.js and image_view_prompts.js). +HISTORIES = {'freevideo.prompts.history': 'freevideo.prompts.presets', + 'freevideo.imageView.prompts': 'freevideo.imageView.presets'} +FILE = re.compile(r'[A-Za-z0-9._~-]+\.json') +_LOCKS = {} +# Listing rows by file, with the file's (mtime, size) they were read at. +_ROWS = {} +_LOCKS_LOCK = threading.Lock() + + +class StoreError(Exception): + """A refused request: ``status`` and a short ``code`` the page can act on; never a value.""" + + def __init__(self, status, code, **facts): + super().__init__(code) + self.status, self.code, self.facts = status, code, facts + + def answer(self): + return dict(error=self.code, **self.facts) + + +def root(folder=None): + if folder is not None: + return Path(folder) + from .paths import data_root + return data_root() / 'user-data' + + +def limit(key): + """The most bytes ``key`` may hold, or None for a key that is not kept here.""" + if not isinstance(key, str): + return None + if key in KEYS: + return KEYS[key] + for _, pattern, most in FAMILIES: + if pattern.fullmatch(key): + return most + return None + + +def family(key): + for name, pattern, _ in FAMILIES: + if key not in KEYS and pattern.fullmatch(key): + return name + return None + + +def file_name(key): + """A fixed, safe file name for ``key``: the key itself where it is plain, else its family and a digest of it + (a draft's key carries a workflow's name, which never becomes a file name).""" + if key in KEYS: + return key + '.json' + name = family(key) + return '%s~%s.json' % (name, hashlib.sha256(key.encode('utf-8')).hexdigest()[:24]) + + +def digest(value): + return hashlib.sha256(value.encode('utf-8')).hexdigest() + + +def _lock(path): + with _LOCKS_LOCK: + return _LOCKS.setdefault(str(path), threading.RLock()) + + +def _path(key, folder): + if limit(key) is None: + raise StoreError(404, 'unknown_key') + return io_path(root(folder) / file_name(key)) + + +def _load(path): + """The stored record, or None when there is none. A file that is not a whole record is removed (it may hold + prompts, and the page keeps the copy it reads): no part of it is kept anywhere. A file that cannot be opened now + raises OSError: the caller answers 'unavailable', and a forget tries again later.""" + try: + with open(path, encoding='utf-8') as stream: + record = json.load(stream) + except FileNotFoundError: + return None + except ValueError: + record = None + if (not isinstance(record, dict) or not isinstance(record.get('value'), str) or type(record.get('rev')) is not int + or record.get('sha256') != digest(record['value'])): + logging.warning('[FreeVideo] A user-data file did not hold a whole record; it was removed.') + path.unlink(missing_ok=True) + return None + return record + + +def _save(path, record): + from .monitoring import save + _ROWS.pop(str(path), None) # a file system with coarse times may leave (mtime, size) as they were + save(path, record, plain_paths=False, durable=True) + if os.name == 'posix': + # The rename itself reaches the disk too, so a power loss cannot bring back the file a write replaced. + try: + descriptor = os.open(path.parent, os.O_RDONLY) + except OSError: + return + try: + os.fsync(descriptor) + except OSError: + pass + finally: + os.close(descriptor) + + +def get(key, *, folder=None, salt_root=None, now=None): + """{key, rev, sha256, value}; StoreError 404 'absent' when nothing is kept for it.""" + path = _path(key, folder) + with _lock(path): + record = _load(path) + if record is None: + raise StoreError(404, 'absent', rev=0) + value = record['value'] + if key in HISTORIES: + # A forget that could not write the file yet: the read already leaves those prompts out. + value, _ = _without_forgotten(value, _stored_value(HISTORIES[key], folder), salt_root=salt_root, now=now) + elif family(key) == 'comfy-workflow-draft' and _forgotten_in(value, salt_root=salt_root, now=now): + # A backup the forget could not remove yet reads as gone, as it will be. + raise StoreError(404, 'absent', rev=0) + return dict(key=key, rev=record['rev'], sha256=digest(value), value=value) + + +def listing(*, folder=None): + """Every kept key with its rev, sha256 and size; no values.""" + rows = [] + base = io_path(root(folder)) + try: + names = sorted(os.listdir(base)) + except FileNotFoundError: + return rows + for name in names: + if not FILE.fullmatch(name): + continue + path = base / name + try: + with _lock(path): + info = os.stat(path) + # A file is read whole only when it changed since the last listing (a draft may be 8 MB). + stamp = (info.st_mtime_ns, info.st_size) + cached = _ROWS.get(str(path)) + if cached and cached[0] == stamp: + row = cached[1] + else: + record = _load(path) + row = None if (record is None or limit(record.get('key')) is None or file_name(record['key']) != name) else dict( + key=record['key'], rev=record['rev'], sha256=record['sha256'], bytes=len(record['value'].encode('utf-8'))) + _ROWS[str(path)] = (stamp, row) + except OSError: + continue # gone meanwhile, or not readable now: listed again next time + if row is not None: + rows.append(dict(row)) + return rows + + +def put(key, value, rev, *, folder=None, salt_root=None, now=None): + """Keep ``value`` for ``key`` when ``rev`` is the rev kept now. Returns {rev, sha256, filtered}: ``filtered`` counts + history rows not kept because only deleted works had their prompt (the page drops them too when it next asks).""" + most = limit(key) + if most is None: + raise StoreError(404, 'unknown_key') + if not isinstance(value, str): + raise StoreError(400, 'bad_value') + if type(rev) is not int or rev < 0: + raise StoreError(400, 'bad_rev') + if len(value.encode('utf-8')) > most: + raise StoreError(413, 'too_large', limit=most) + path = _path(key, folder) + with _lock(path): + record = _load(path) + current = record['rev'] if record else 0 + if rev != current: + raise StoreError(409, 'stale_revision', rev=current, sha256=record['sha256'] if record else None) + if family(key) == 'comfy-workflow-draft' and _forgotten_in(value, salt_root=salt_root, now=now): + # An older copy of a tab that still has a deleted creation's prompt (another browser, a phone): not kept, + # and what was kept for it goes too. Nothing is kept now, so its next write starts from rev 0. + _ROWS.pop(str(path), None) + path.unlink(missing_ok=True) + return dict(rev=0, sha256=digest(value), filtered=1) + if record is None and family(key) is not None and _family_count(family(key), folder) >= COPIES: + raise StoreError(413, 'too_many', limit=COPIES) + kept, filtered = value, 0 + if key in HISTORIES: + kept, filtered = _without_forgotten(value, _stored_value(HISTORIES[key], folder), salt_root=salt_root, now=now) + fresh = dict(key=key, rev=current + 1, sha256=digest(kept), value=kept, updated_at=time.time() if now is None else now) + _save(path, fresh) + return dict(rev=fresh['rev'], sha256=fresh['sha256'], filtered=filtered) + + +def delete(key, *, folder=None): + """Remove what is kept for ``key`` (the page cleared it). Returns whether there was anything.""" + path = _path(key, folder) + with _lock(path): + _ROWS.pop(str(path), None) + try: + path.unlink() + return True + except FileNotFoundError: + return False + + +def clear(keys=None, *, folder=None): + """Remove the given keys, or every kept key; returns how many files went.""" + removed = 0 + for row in listing(folder=folder): + if keys is None or row['key'] in keys: + removed += delete(row['key'], folder=folder) + return removed + + +def _family_count(name, folder): + try: + return sum(1 for entry in os.listdir(io_path(root(folder))) if entry.startswith(name + '~') and FILE.fullmatch(entry)) + except FileNotFoundError: + return 0 + + +def _stored_value(key, folder): + path = _path(key, folder) + with _lock(path): + record = _load(path) + return record['value'] if record else None + + +def _rows(value): + try: + rows = json.loads(value) if isinstance(value, str) else None + except ValueError: + return None + return rows if isinstance(rows, list) else None + + +def _texts(value): + return {row['text'].strip() for row in _rows(value) or () if isinstance(row, dict) and isinstance(row.get('text'), str)} + + +def _without_forgotten(value, presets, *, salt_root=None, now=None, hashes=None): + """The history ``value`` without the rows whose prompt only deleted works had, unless a preset keeps that prompt. + ``hashes`` names those prompts (the ones being forgotten now); otherwise the private store's list says which. + A history that is not a list of {text} rows stays as it is.""" + rows = _rows(value) + if not rows: + return value, 0 + from . import private_store + texts = [row.get('text') if isinstance(row, dict) else None for row in rows] + if hashes is None: + gone = set(private_store.forgotten(texts, root=salt_root, now=now)) + waiting = private_store.forget_pending(root=salt_root) + if waiting: + gone |= {index for index, text in enumerate(texts) if isinstance(text, str) and text.strip() + and private_store.name('prompt', text.strip(), root=salt_root) in waiting} + else: + gone = {index for index, text in enumerate(texts) if isinstance(text, str) and text.strip() + and private_store.name('prompt', text.strip(), root=salt_root) in hashes} + saved = _texts(presets) + gone = {index for index in gone if texts[index].strip() not in saved} + if not gone: + return value, 0 + return json.dumps([row for index, row in enumerate(rows) if index not in gone], ensure_ascii=False), len(gone) + + +def _strings(value, depth=0): + """Every string in a JSON value; a string that itself holds JSON is opened too (a few levels deep).""" + if isinstance(value, str): + yield value + if depth < 4 and value.lstrip()[:1] in ('{', '['): + try: + inner = json.loads(value) + except ValueError: + return + yield from _strings(inner, depth + 1) + elif isinstance(value, dict): + for item in value.values(): + yield from _strings(item, depth) + elif isinstance(value, list): + for item in value: + yield from _strings(item, depth) + + +def _holds(value, hashes, salt_root): + """Whether a kept value has, anywhere in it, a prompt that is one of ``hashes``.""" + from . import private_store + keyed = private_store.hasher('prompt', root=salt_root) + try: + found = {text.strip() for text in _strings(json.loads(value))} + except ValueError: + found = {value.strip()} + for text in found: + if text: + one = keyed.copy() + one.update(text.encode('utf-8')) + if one.hexdigest() in hashes: + return True + return False + + +def _forgotten_in(value, *, salt_root=None, now=None): + """Whether a kept value has a prompt only deleted works had: forgotten (the last 30 days) or still to forget.""" + from . import private_store + try: + texts = sorted({text.strip() for text in _strings(json.loads(value))} - {''}) + except ValueError: + texts = [value.strip()] + if private_store.forgotten(texts, root=salt_root, now=now): + return True + waiting = private_store.forget_pending(root=salt_root) + return bool(waiting) and _holds(value, waiting, salt_root) + + +def forget(hashes, *, folder=None, salt_root=None, now=None): + """Take out of the kept histories every row whose prompt is one of ``hashes`` (keyed hashes of prompts only + deleted works had), unless the matching presets keep it. Each changed history gets a new rev. A backup of + ComfyUI's unsaved workflow tabs that has one of those prompts anywhere in it is removed whole: it is never written + back, and the page sends it again, without the words, when the tab next changes. Returns how many history rows and + backups went. A file that cannot be changed now raises OSError, and the caller's next cleanup tries again.""" + hashes = {h for h in hashes or () if isinstance(h, str) and re.fullmatch('[0-9a-f]{64}', h)} + if not hashes: + return 0 + removed = 0 + base = io_path(root(folder)) + try: + names = sorted(os.listdir(base)) + except FileNotFoundError: + names = [] + for name in names: + if not (name.startswith('comfy-workflow-draft~') and FILE.fullmatch(name)): + continue + path = base / name + with _lock(path): + _ROWS.pop(str(path), None) + record = _load(path) # one that cannot be read now raises: not passed over in silence + if record is not None and _holds(record['value'], hashes, salt_root): + try: + path.unlink() + removed += 1 + except FileNotFoundError: + pass + for key, presets_key in HISTORIES.items(): + path = _path(key, folder) + with _lock(path): + record = _load(path) + if record is None: + continue + kept, count = _without_forgotten(record['value'], _stored_value(presets_key, folder), + salt_root=salt_root, hashes=hashes) + if count: + _save(path, dict(record, rev=record['rev'] + 1, sha256=digest(kept), value=kept, + updated_at=time.time() if now is None else now)) + removed += count + return removed + + +def sweep_staging(*, folder=None): + """Staging files a write left when the process stopped halfway: removed at startup, before any write.""" + base = io_path(root(folder)) + try: + names = os.listdir(base) + except FileNotFoundError: + return 0 + removed = 0 + for name in names: + if name.endswith('.tmp'): + try: + (base / name).unlink() + removed += 1 + except OSError: + pass + return removed + + +async def _read_json(request, most): + """The request's JSON body, refused past what a value of ``most`` bytes can take when sent as JSON.""" + # A JSON string spends up to 6 bytes on one byte of value (\\u0001). + ceiling = 6 * most + 4096 + if (request.content_length or 0) > ceiling: + raise StoreError(413, 'too_large', limit=most) + # A read returns what has arrived so far: read on until the end, or past the ceiling. + chunks, size = [], 0 + while True: + chunk = await request.content.read(64 * KB) + if not chunk: + break + chunks.append(chunk) + size += len(chunk) + if size > ceiling: + raise StoreError(413, 'too_large', limit=most) + body = b''.join(chunks) + try: + value = json.loads(body) + except ValueError: + raise StoreError(400, 'bad_json') from None + if not isinstance(value, dict): + raise StoreError(400, 'bad_json') + return value + + +def key_of(request, prefix='/freevideo/user-store/'): + """The key from the request's path, decoded once (a draft's key may hold '/' as %2F).""" + from urllib.parse import unquote + raw = request.rel_url.raw_path + return unquote(raw[len(prefix):]) if raw.startswith(prefix) else '' + + +def writes_allowed(request): + """A page on this machine writes as the others do; through the sign-in proxy a write also carries the device's + CSRF proof, as the Agent's writes do.""" + from . import proxy_identity + return not proxy_identity.trusted(request) or proxy_identity.check_csrf(request) + + +def register(server=None, *, folder=None): + import asyncio + from aiohttp import web + if server is None: + from server import PromptServer + server = PromptServer.instance + if server is None or getattr(server, '_freevideo_user_store', False): + return + server._freevideo_user_store = True + headers = {'Cache-Control': 'no-store'} + try: + sweep_staging(folder=folder) + except OSError as error: + logging.warning('[FreeVideo] User-data staging files were not tidied (%s).', type(error).__name__) + + def reply(status, value): + return web.json_response(value, status=status, headers=headers) + + async def guarded(work): + try: + return reply(200, await work()) + except StoreError as error: + return reply(error.status, error.answer()) + except OSError as error: + # Only the kind of failure is said or logged, never a key's value. + logging.warning('[FreeVideo] User data could not be read or written (%s).', type(error).__name__) + return reply(503, dict(error='unavailable')) + + @server.routes.get('/freevideo/user-store') + async def user_store_list(request): + return await guarded(lambda: _list(folder)) + + async def _list(folder): + return dict(keys=await asyncio.to_thread(listing, folder=folder)) + + @server.routes.get('/freevideo/user-store/{key:.+}') + async def user_store_get(request): + key = key_of(request) + return await guarded(lambda: asyncio.to_thread(get, key, folder=folder)) + + @server.routes.put('/freevideo/user-store/{key:.+}') + async def user_store_put(request): + key = key_of(request) + + async def work(): + if not writes_allowed(request): + raise StoreError(403, 'forbidden') + most = limit(key) + if most is None: + raise StoreError(404, 'unknown_key') + body = await _read_json(request, most) + return await asyncio.to_thread(put, key, body.get('value'), body.get('rev', 0), folder=folder) + return await guarded(work) + + @server.routes.delete('/freevideo/user-store/{key:.+}') + async def user_store_delete(request): + key = key_of(request) + + async def work(): + if not writes_allowed(request): + raise StoreError(403, 'forbidden') + return dict(deleted=await asyncio.to_thread(delete, key, folder=folder)) + return await guarded(work) diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjs index a63f9402..16b92707 100644 --- a/scripts/test_freevideo_entry.mjs +++ b/scripts/test_freevideo_entry.mjs @@ -10,7 +10,7 @@ import {mediaName, uploadMedia} from '../web/media_upload.js'; import {plainText} from '../web/i18n.js'; import {outputDownloadURL, checkedDownload, anchoredNotice, unreadableVideoText} from '../web/output_download.js'; import * as studioQueue from '../web/studio_queue.js'; -import {referenceInputs, mediaRows} from '../web/prompt_references.js'; +import {referenceInputs, mediaRows, requestRow} from '../web/prompt_references.js'; import {expandCast} from '../web/cast_mention.js'; import {cleanAudioUse, cleanOptionalPrompt, cleanOptionalWidgets, optionalInputValue} from '../web/optional_inputs.js'; @@ -108,7 +108,7 @@ test('main browser entry registers both views and preserves node hooks', async t installNavigation: callback => installed.push(callback), refreshNavigation: () => refreshed++, preferredView: () => rememberedView, beginWorkspaceRestore: () => { openingEvents.push(['begin']); return opening; }, finishWorkspaceRestore: () => { restoreReleases++; }, waitForLauncherRestore: () => launchReady, - attachReferencePicker() {}, referenceItems: () => [], syncReferencePrompt() {}, + attachReferencePicker() {}, referenceItems: () => [], syncReferencePrompt() {}, requestRow, shareButton: () => new Element('button'), reportFileName: () => 'FreeVideo-report-20261008-101530.json', rememberPromptDraft() {}, savePromptDraft: async () => false, openImageEditor: async () => null, icon: () => '', AUDIO_USE: {reference: 'reference', original: 'original'}, usesOriginal: row => row?.use === 'original', checkOriginal: async () => ({ok: true}), @@ -149,6 +149,8 @@ test('main browser entry registers both views and preserves node hooks', async t source = source.replace("from './cut_tip.js'", `from '${new URL('../web/cut_tip.js', import.meta.url).href}'`); source = source.replace("from './middle_frames.js'", `from '${new URL('../web/middle_frames.js', import.meta.url).href}'`); source = source.replace("from './workflow_drafts.js'", `from '${new URL('../web/workflow_drafts.js', import.meta.url).href}'`); + // The storage mirror wraps the page's localStorage; here each load only says it was asked to (user_store_mirror.mjs tests it). + source = source.replace("import { installMirror } from './user_store_mirror.js';", 'const installMirror = () => { globalThis.__freevideoEntryTest.mirrors = (globalThis.__freevideoEntryTest.mirrors || 0) + 1; };'); source = source .replace("import { createErrorPanel, errorText, createErrorReport, adviceFor } from './error_panel.js';", 'const {createErrorPanel,errorText,createErrorReport,adviceFor} = globalThis.__freevideoEntryTest;') .replace('import { app } from "../../scripts/app.js";', 'const {app} = globalThis.__freevideoEntryTest;') @@ -161,7 +163,7 @@ test('main browser entry registers both views and preserves node hooks', async t .replace("import { startUpdateChecks, productVersion } from './updates.js';", 'const {startUpdateChecks,productVersion} = globalThis.__freevideoEntryTest;') .replace("import { startWhatsNew } from './whatsnew.js';", 'const {startWhatsNew} = globalThis.__freevideoEntryTest;') .replace("import { startDoneNotify, askDesktopPermission, DESKTOP_SETTING } from './done_notify.js';", 'const {startDoneNotify} = globalThis.__freevideoEntryTest; const askDesktopPermission = (...args) => globalThis.__permissionAsks.push(args); const DESKTOP_SETTING = "FreeVideo.DoneNotify.Desktop";') - .replace("import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mediaRows, mediaNodeOf } from './prompt_references.js';", 'const {attachReferencePicker,referenceItems,syncReferencePrompt,referenceInputs,mediaRows} = globalThis.__freevideoEntryTest; const mediaNodeOf = () => null;') + .replace("import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mediaRows, mediaNodeOf, withoutReferenceGaps, requestRow } from './prompt_references.js';", 'const {attachReferencePicker,referenceItems,syncReferencePrompt,referenceInputs,mediaRows,requestRow} = globalThis.__freevideoEntryTest; const mediaNodeOf = () => null; const withoutReferenceGaps = text => text;') .replace("import { timedText } from './timed_prompt.js';", 'const timedText = text => text;') .replace("import { openReferenceMenu } from './image_library.js';", 'const openReferenceMenu = () => {};') .replace("import { pinSoon } from './private_pin.js';", 'const pinSoon = () => {};') diff --git a/web/batch_line_media.js b/web/batch_line_media.js new file mode 100644 index 00000000..a7976714 --- /dev/null +++ b/web/batch_line_media.js @@ -0,0 +1,95 @@ +// One prompt per line: the media each line's video takes. A line that names media with @ (a ,