Release V3.8 source, illustrated manual and Spectrum workflow

This commit is contained in:
ukr8b3g-cmyk
2026-09-07 21:25:51 +09:00
parent 0a7c6703b7
commit 315146946e
208 changed files with 74579 additions and 24542 deletions
+187 -178
View File
@@ -1,54 +1,54 @@
"""Native MiniMax H3 conditioning and latent construction for V2.
All expensive image/VAE work is performed before the sampling phase. Prompt
conditioning is cached per unique prompt and image presentation.
"""
"""Native MiniMax H3 conditioning and latent construction for V2.
All expensive image/VAE work is performed before the sampling phase. Prompt
conditioning is cached per unique prompt and image presentation.
"""
from __future__ import annotations
from collections import OrderedDict
import hashlib
from dataclasses import dataclass
from typing import Any, Callable
import torch
from ..continuation import clone_conditioning
import torch
from ..continuation import clone_conditioning
from ..temporal import audio_latent_t, video_latent_t
_PROMPT_CACHE_ATTR = "_h3_continuum_prompt_conditioning_cache_v1"
_PROMPT_CACHE_VERSION = 1
_PROMPT_CACHE_MAX_ENTRIES = 16
@dataclass(slots=True)
class IdentityAssets:
first_image: torch.Tensor | None
first_latent: torch.Tensor | None
last_image: torch.Tensor | None
last_latent: torch.Tensor | None
identity_hash: str
@property
def first_frame_hash(self) -> str:
"""Version-neutral alias retained alongside the legacy identity hash."""
return self.identity_hash
@property
def last_frame_hash(self) -> str:
"""Fingerprint the resized final keyframe independently from identity."""
return _tensor_fingerprint(self.last_image)
@dataclass(slots=True)
class IdentityAssets:
first_image: torch.Tensor | None
first_latent: torch.Tensor | None
last_image: torch.Tensor | None
last_latent: torch.Tensor | None
identity_hash: str
@property
def first_frame_hash(self) -> str:
"""Version-neutral alias retained alongside the legacy identity hash."""
return self.identity_hash
@property
def last_frame_hash(self) -> str:
"""Fingerprint the resized final keyframe independently from identity."""
return _tensor_fingerprint(self.last_image)
def _tensor_fingerprint(tensor: torch.Tensor | None) -> str:
if tensor is None:
return "none"
sample = tensor.detach().to("cpu").contiguous()
digest = hashlib.sha256()
digest.update(str(tuple(int(value) for value in sample.shape)).encode("ascii"))
digest.update(str(sample.dtype).encode("ascii"))
digest.update(sample.view(torch.uint8).numpy().tobytes(order="C"))
if tensor is None:
return "none"
sample = tensor.detach().to("cpu").contiguous()
digest = hashlib.sha256()
digest.update(str(tuple(int(value) for value in sample.shape)).encode("ascii"))
digest.update(str(sample.dtype).encode("ascii"))
digest.update(sample.view(torch.uint8).numpy().tobytes(order="C"))
return digest.hexdigest()
@@ -199,64 +199,67 @@ def encode_prompt_conditioning_cached(
except Exception:
_cache_event(cache_event, "bypass_cache_error")
return result
def resize_h3_image(image: torch.Tensor, width: int, height: int, crop: str) -> torch.Tensor:
try:
import comfy.utils
except Exception as exc: # pragma: no cover - ComfyUI runtime only
raise RuntimeError(f"ComfyUI resize helper unavailable: {exc}") from exc
if not torch.is_tensor(image) or image.ndim != 4 or image.shape[-1] < 3:
raise ValueError("H3 image input must be [B,H,W,C] with at least three channels")
samples = image[:1, ..., :3].movedim(-1, 1)
resized = comfy.utils.common_upscale(samples, int(width), int(height), "lanczos", crop)
return resized.movedim(1, -1).contiguous()
def prepare_identity_assets(
video_vae: Any,
*,
width: int,
height: int,
first_frame: torch.Tensor | None,
last_frame: torch.Tensor | None,
encode_latents: bool = True,
) -> IdentityAssets:
first_image = first_latent = last_image = last_latent = None
if first_frame is not None:
first_image = resize_h3_image(first_frame, width, height, "disabled")
if encode_latents:
first_latent = video_vae.encode(first_image)
if last_frame is not None:
last_image = resize_h3_image(last_frame, width, height, "center")
if encode_latents:
last_latent = video_vae.encode(last_image)
return IdentityAssets(
first_image=first_image,
first_latent=first_latent,
last_image=last_image,
last_latent=last_latent,
identity_hash=_tensor_fingerprint(first_image),
)
def encode_prompt_conditioning(
clip: Any,
prompt: str,
*,
first_image: torch.Tensor | None,
last_image: torch.Tensor | None,
reference_audio_assets=None,
timeline_video_assets=None,
) -> list:
images = []
if first_image is not None:
images.append(first_image)
if last_image is not None:
images.append(last_image)
def resize_h3_image(image: torch.Tensor, width: int, height: int, crop: str) -> torch.Tensor:
try:
import comfy.utils
except Exception as exc: # pragma: no cover - ComfyUI runtime only
raise RuntimeError(f"ComfyUI resize helper unavailable: {exc}") from exc
if not torch.is_tensor(image) or image.ndim != 4 or image.shape[-1] < 3:
raise ValueError("H3 image input must be [B,H,W,C] with at least three channels")
samples = image[:1, ..., :3].movedim(-1, 1)
resized = comfy.utils.common_upscale(samples, int(width), int(height), "lanczos", crop)
return resized.movedim(1, -1).contiguous()
def prepare_identity_assets(
video_vae: Any,
*,
width: int,
height: int,
first_frame: torch.Tensor | None,
last_frame: torch.Tensor | None,
encode_latents: bool = True,
) -> IdentityAssets:
first_image = first_latent = last_image = last_latent = None
if first_frame is not None:
first_image = resize_h3_image(first_frame, width, height, "disabled")
if encode_latents:
first_latent = video_vae.encode(first_image)
if last_frame is not None:
last_image = resize_h3_image(last_frame, width, height, "center")
if encode_latents:
last_latent = video_vae.encode(last_image)
return IdentityAssets(
first_image=first_image,
first_latent=first_latent,
last_image=last_image,
last_latent=last_latent,
identity_hash=_tensor_fingerprint(first_image),
)
def encode_prompt_conditioning(
clip: Any,
prompt: str,
*,
first_image: torch.Tensor | None,
last_image: torch.Tensor | None,
reference_audio_assets=None,
timeline_video_assets=None,
) -> list:
images = []
if first_image is not None:
images.append(first_image)
if last_image is not None:
images.append(last_image)
tokenize_options = {"images": images}
if reference_audio_assets is not None or timeline_video_assets is not None:
from ..reference_audio import reference_audio_item
from ..reference_audio import (
reference_audio_asset_items,
reference_audio_item,
)
ref_items = [
*({"type": "image", "data": image} for image in images),
@@ -264,90 +267,96 @@ def encode_prompt_conditioning(
if timeline_video_assets is not None:
ref_items.append(dict(timeline_video_assets.item))
if reference_audio_assets is not None:
ref_items.append(reference_audio_item())
tokenize_options = {
"minimax_ref_items": ref_items
}
tokens = clip.tokenize(str(prompt), **tokenize_options)
conditioning = clip.encode_from_tokens_scheduled(tokens)
if reference_audio_assets is None and timeline_video_assets is None:
return conditioning
refs = []
if timeline_video_assets is not None:
refs.append(dict(timeline_video_assets.block))
ref_items.extend(
reference_audio_item()
for _ in reference_audio_asset_items(reference_audio_assets)
)
tokenize_options = {
"minimax_ref_items": ref_items
}
tokens = clip.tokenize(str(prompt), **tokenize_options)
conditioning = clip.encode_from_tokens_scheduled(tokens)
if reference_audio_assets is None and timeline_video_assets is None:
return conditioning
refs = []
if timeline_video_assets is not None:
refs.append(dict(timeline_video_assets.block))
if reference_audio_assets is not None:
from ..reference_audio import reference_audio_block
from ..reference_audio import reference_audio_asset_items, reference_audio_block
refs.append(dict(reference_audio_block(reference_audio_assets)))
return [
[tensor, {**dict(metadata), "minimax_refs": list(refs)}]
for tensor, metadata in conditioning
]
def attach_keyframes(
conditioning: list,
*,
frame_count: int,
first_latent: torch.Tensor | None,
last_latent: torch.Tensor | None,
) -> list:
output = clone_conditioning(conditioning)
keyframes: list[dict[str, Any]] = []
if first_latent is not None:
keyframes.append({"resolved_frame_index": 0, "latent": first_latent})
if last_latent is not None:
keyframes.append(
{"resolved_frame_index": int(frame_count) - 1, "latent": last_latent}
refs.extend(
dict(reference_audio_block(item))
for item in reference_audio_asset_items(reference_audio_assets)
)
for _, metadata in output:
if keyframes:
metadata["minimax_keyframes"] = [dict(item) for item in keyframes]
metadata["minimax_frame_count"] = int(frame_count)
else:
metadata.pop("minimax_keyframes", None)
metadata["minimax_frame_count"] = int(frame_count)
return output
def empty_h3_latent(width: int, height: int, frame_count: int) -> dict[str, Any]:
try:
import comfy.model_management
import comfy.nested_tensor
except Exception as exc: # pragma: no cover - ComfyUI runtime only
raise RuntimeError(f"ComfyUI H3 latent helpers unavailable: {exc}") from exc
width = int(width)
height = int(height)
frame_count = int(frame_count)
if width <= 0 or height <= 0 or width % 32 or height % 32:
raise ValueError("H3 width and height must be positive multiples of 32")
device = comfy.model_management.intermediate_device()
video = torch.zeros(
(1, 24, video_latent_t(frame_count), height // 16, width // 16),
device=device,
dtype=torch.float32,
)
audio = torch.zeros(
(1, 32, 2, audio_latent_t(frame_count)),
device=device,
dtype=torch.float32,
)
return {"samples": comfy.nested_tensor.NestedTensor((video, audio))}
def encode_identity_latents(video_vae: Any, assets: IdentityAssets) -> IdentityAssets:
"""Encode already-resized identity images without changing their fingerprint."""
first_latent = assets.first_latent
last_latent = assets.last_latent
if first_latent is None and assets.first_image is not None:
first_latent = video_vae.encode(assets.first_image)
if last_latent is None and assets.last_image is not None:
last_latent = video_vae.encode(assets.last_image)
return IdentityAssets(
first_image=assets.first_image,
first_latent=first_latent,
last_image=assets.last_image,
last_latent=last_latent,
identity_hash=assets.identity_hash,
)
return [
[tensor, {**dict(metadata), "minimax_refs": list(refs)}]
for tensor, metadata in conditioning
]
def attach_keyframes(
conditioning: list,
*,
frame_count: int,
first_latent: torch.Tensor | None,
last_latent: torch.Tensor | None,
) -> list:
output = clone_conditioning(conditioning)
keyframes: list[dict[str, Any]] = []
if first_latent is not None:
keyframes.append({"resolved_frame_index": 0, "latent": first_latent})
if last_latent is not None:
keyframes.append(
{"resolved_frame_index": int(frame_count) - 1, "latent": last_latent}
)
for _, metadata in output:
if keyframes:
metadata["minimax_keyframes"] = [dict(item) for item in keyframes]
metadata["minimax_frame_count"] = int(frame_count)
else:
metadata.pop("minimax_keyframes", None)
metadata["minimax_frame_count"] = int(frame_count)
return output
def empty_h3_latent(width: int, height: int, frame_count: int) -> dict[str, Any]:
try:
import comfy.model_management
import comfy.nested_tensor
except Exception as exc: # pragma: no cover - ComfyUI runtime only
raise RuntimeError(f"ComfyUI H3 latent helpers unavailable: {exc}") from exc
width = int(width)
height = int(height)
frame_count = int(frame_count)
if width <= 0 or height <= 0 or width % 32 or height % 32:
raise ValueError("H3 width and height must be positive multiples of 32")
device = comfy.model_management.intermediate_device()
video = torch.zeros(
(1, 24, video_latent_t(frame_count), height // 16, width // 16),
device=device,
dtype=torch.float32,
)
audio = torch.zeros(
(1, 32, 2, audio_latent_t(frame_count)),
device=device,
dtype=torch.float32,
)
return {"samples": comfy.nested_tensor.NestedTensor((video, audio))}
def encode_identity_latents(video_vae: Any, assets: IdentityAssets) -> IdentityAssets:
"""Encode already-resized identity images without changing their fingerprint."""
first_latent = assets.first_latent
last_latent = assets.last_latent
if first_latent is None and assets.first_image is not None:
first_latent = video_vae.encode(assets.first_image)
if last_latent is None and assets.last_image is not None:
last_latent = video_vae.encode(assets.last_image)
return IdentityAssets(
first_image=assets.first_image,
first_latent=first_latent,
last_image=assets.last_image,
last_latent=last_latent,
identity_hash=assets.identity_hash,
)
+813 -807
View File
File diff suppressed because it is too large Load Diff
+251 -251
View File
@@ -1,251 +1,251 @@
"""Prompt planning for the integrated H3 Continuum sampler.
The parser is intentionally deterministic and side-effect free so saved workflows
can be reproduced without depending on UI state.
"""
from __future__ import annotations
import hashlib, json, re
from typing import Any
from ..constants import (
CHUNK_SECONDS_MAX,CHUNK_SECONDS_MIN,
PROMPT_FORMAT_AUTO,PROMPT_FORMAT_FIXED,PROMPT_FORMAT_LIST,PROMPT_FORMAT_TIMELINE,
PROMPT_MODE_FIXED,PROMPT_MODE_LIST,PROMPT_MODE_TIMELINE,PROMPT_PLAN_MAGIC,
)
from ..version import PROMPT_PLAN_SCHEMA_VERSION
_TIMELINE_HEADER=re.compile(r"^\s*\[\s*(?P<start>\d+(?:\.\d+)?)\s*(?:s|sec|seconds)?\s*[-–—]\s*(?P<end>\d+(?:\.\d+)?)\s*(?:s|sec|seconds)?\s*\]\s*$",re.IGNORECASE)
_CHUNK_HEADER=re.compile(r"^\s*\[\s*(?:chunk|clip)\s*(?P<index>\d+)\s*\]\s*$",re.IGNORECASE)
_TIMELINE_LIKE_HEADER=re.compile(r"^\s*\[\s*(?:(?:chunk|clip)\b|\d+(?:\.\d+)?[^\]]*(?:[-–—]|\bto\b))",re.IGNORECASE)
_LIST_SEPARATOR=re.compile(r"^\s*---+\s*$",re.MULTILINE)
class PromptPlanError(ValueError): pass
def _prompt_error(code,reason,*,line_number=None,source=None,suggested_fix):
location=f" line {line_number}" if line_number is not None else ""
lines=[f"{code}{location}: {reason}"]
if source is not None: lines.append(f"Source: {source}")
if suggested_fix: lines.append(f"Suggested fix: {suggested_fix}")
raise PromptPlanError("\n".join(lines))
def prompt_hash(prompt:str)->str: return hashlib.sha256(prompt.encode("utf-8")).hexdigest()
def _normalize_prompt(value:str,*,label:str)->str:
return "" if value is None else str(value).strip()
def _parse_json_list(script:str):
stripped=script.lstrip()
if not stripped.startswith("["): return None
try: value=json.loads(script)
except json.JSONDecodeError: return None
if not isinstance(value,list) or not all(isinstance(item,str) for item in value): return None
return [_normalize_prompt(item,label=f"prompt {index+1}") for index,item in enumerate(value)]
def _parse_list(script,chunks):
values=_parse_json_list(script)
if values is None: values=[_normalize_prompt(part,label=f"prompt {index+1}") for index,part in enumerate(_LIST_SEPARATOR.split(script)) if part.strip()]
if not values: values=[str(script)]
source_count=len(values); notes=[]
if len(values)<chunks: notes.append(f"repeated the last prompt for {chunks-len(values)} chunk(s)"); values.extend([values[-1]]*(chunks-len(values)))
elif len(values)>chunks: notes.append(f"ignored {len(values)-chunks} extra prompt(s)"); values=values[:chunks]
sources=[min(index+1,source_count) for index in range(len(values))]
return values,notes,sources
def _timeline_preamble(script,*,ignore_list_separators=False):
body=[]
for line in str(script).splitlines():
if _TIMELINE_HEADER.match(line) or _CHUNK_HEADER.match(line): break
if ignore_list_separators and _LIST_SEPARATOR.fullmatch(line): continue
body.append(line)
return "\n".join(body).strip()
def _parse_timeline_sections(script,*,allow_preamble=True,ignore_list_separators=False):
preamble=_timeline_preamble(script,ignore_list_separators=ignore_list_separators)
sections=[]; current=None; body=[]
def finish():
nonlocal current,body
if current is None:
if any(line.strip() for line in body) and not allow_preamble: raise PromptPlanError("timeline text before the first [0-5s] or [Chunk 1] header is not allowed")
body=[]; return
if not any(line.strip() for line in body):
_prompt_error("H3C-P005","timeline section body is empty",line_number=current["line_number"],source=current["source"],suggested_fix="add prompt text below this header")
prompt=_normalize_prompt("\n".join(body),label="timeline section")
current["prompt"]=f"{preamble}\n\n{prompt}" if preamble else prompt
sections.append(current); current=None; body=[]
for line_number,line in enumerate(str(script).splitlines(),start=1):
time_match=_TIMELINE_HEADER.match(line); chunk_match=_CHUNK_HEADER.match(line)
if time_match or chunk_match:
finish()
if time_match:
start=float(time_match.group("start")); end=float(time_match.group("end"))
if not end>start: _prompt_error("H3C-P002","timeline end must be greater than its start",line_number=line_number,source=line.strip(),suggested_fix="use an increasing range such as [0-5s]")
current={"kind":"time","start":start,"end":end,"line_number":line_number,"source":line.strip()}
else:
index=int(chunk_match.group("index"))
if index<1: _prompt_error("H3C-P004","chunk numbers are one-based",line_number=line_number,source=line.strip(),suggested_fix="use [Chunk 1] or a larger one-based chunk number")
current={"kind":"chunk","index":index,"line_number":line_number,"source":line.strip()}
continue
if _TIMELINE_LIKE_HEADER.match(line):
_prompt_error("H3C-P001","invalid timeline header",line_number=line_number,source=line.strip(),suggested_fix="use [0-5s] or [Chunk 1]")
if ignore_list_separators and _LIST_SEPARATOR.fullmatch(line):
continue
body.append(line)
finish()
if not sections: raise PromptPlanError("timeline contains no sections")
return sections
def parse_sparse_prompt_overrides(script):
sections=_parse_timeline_sections(script,allow_preamble=False); overrides={}
for item in sections:
if item["kind"]!="chunk": raise PromptPlanError("Sparse Clip Overrides only accepts [Clip N] or [Chunk N] sections")
index=int(item["index"])
if index in overrides: raise PromptPlanError(f"Sparse Clip Overrides defines Clip {index} more than once")
overrides[index]=item["prompt"]
return overrides
def validate_sparse_prompt_overrides(overrides,*,chunks):
chunks=int(chunks)
if not isinstance(overrides,dict): raise PromptPlanError("Sparse Clip Overrides must be a dictionary")
validated={}
for index,prompt in overrides.items():
if type(index) is not int: raise PromptPlanError("Sparse Clip Override numbers must be integers")
if not 1<=index<=chunks: raise PromptPlanError(f"Sparse Clip Override {index} is outside the configured 1-{chunks} chunks")
validated[index]=_normalize_prompt(prompt,label=f"Clip {index} Override")
if not validated: raise PromptPlanError("Sparse Clip Overrides contains no overrides")
return validated
def _parse_timeline(script,chunks,chunk_seconds,*,ignore_list_separators=False):
sections=_parse_timeline_sections(script,ignore_list_separators=ignore_list_separators); prompts=[]; notes=[]; diagnostics=[]
if _timeline_preamble(script,ignore_list_separators=ignore_list_separators): notes.append("applied timeline preamble to all chunks")
seen_chunks={}; total_end=chunks*chunk_seconds; usable=[]
for item in sections:
if item["kind"]=="chunk":
index=int(item["index"])
if index in seen_chunks:
_prompt_error("H3C-P003",f"timeline defines Chunk {index} more than once",line_number=item["line_number"],source=item["source"],suggested_fix=f"keep only one [Chunk {index}] section")
seen_chunks[index]=item
if index<=chunks: usable.append(item)
else: diagnostics.append({"level":"warning","code":"H3C-P104","message":f"ignored {item['source']} because the configured sequence has only {chunks} chunk(s)"})
elif min(total_end,item["end"])-max(0.0,item["start"])>0:
usable.append(item)
else:
diagnostics.append({"level":"warning","code":"H3C-P104","message":f"ignored {item['source']} because it is outside 0-{total_end:.3f}s"})
if not usable:
_prompt_error("H3C-P005","timeline contains no usable prompt section for the configured sequence",suggested_fix="add a section such as [0-5s] with non-empty prompt text")
previous_prompt=None; previous_source=None
for chunk_index in range(1,chunks+1):
chunk_sections=[item for item in sections if item["kind"]=="chunk" and item["index"]==chunk_index]
if chunk_sections:
selected=chunk_sections[0]; prompts.append(selected["prompt"]); previous_prompt=selected["prompt"]; previous_source=f"{selected['source']} at line {selected['line_number']}"
diagnostics.append({"level":"info","code":"H3C-P000","message":f"Chunk {chunk_index} source: {previous_source}"}); continue
start=(chunk_index-1)*chunk_seconds; end=chunk_index*chunk_seconds; scored=[]
for order,item in enumerate(sections):
if item["kind"]!="time": continue
overlap=max(0.0,min(end,item["end"])-max(start,item["start"]))
if overlap>0: scored.append((overlap,-order,item))
if not scored:
if previous_prompt is None:
selected=usable[0]; fallback_reason=f"used earliest valid prompt from {selected['source']}"
else:
selected=None; fallback_reason=f"reused previous prompt from {previous_source}"
prompt=selected["prompt"] if selected is not None else previous_prompt
source=f"{selected['source']} at line {selected['line_number']}" if selected is not None else previous_source
prompts.append(prompt); previous_prompt=prompt; previous_source=source
diagnostics.append({"level":"warning","code":"H3C-P101","message":f"Timeline does not cover Chunk {chunk_index} ({start:.3f}-{end:.3f}s); {fallback_reason}."})
diagnostics.append({"level":"info","code":"H3C-P000","message":f"Chunk {chunk_index} source: fallback to {source}"}); continue
scored.sort(reverse=True,key=lambda row:(row[0],row[1])); selected=scored[0][2]; prompts.append(selected["prompt"]); previous_prompt=selected["prompt"]; previous_source=f"{selected['source']} at line {selected['line_number']}"
diagnostics.append({"level":"info","code":"H3C-P000","message":f"Chunk {chunk_index} source: {previous_source}"})
if len(scored)>1 and abs(scored[0][0]-scored[1][0])<1e-9: notes.append(f"chunk {chunk_index} had an equal-overlap timeline tie; used the earlier section")
return prompts,notes,diagnostics
def _has_timeline_header(script):
return any(_TIMELINE_HEADER.match(line) or _CHUNK_HEADER.match(line) for line in str(script).splitlines())
def _has_list_separator(script):
return _LIST_SEPARATOR.search(str(script)) is not None
def _mixed_syntax_diagnostic(*,timeline_active):
message="Mixed Timeline and List prompt syntax detected. Use either [Chunk N] / [0-5s] sections or --- separators, not both."
if timeline_active: message+=" Standalone --- separators were ignored because Timeline syntax is active."
return {"level":"warning","code":"H3C-P105","message":message}
def detect_prompt_mode(script):
text=str(script)
for line in text.splitlines():
if _TIMELINE_HEADER.match(line) or _CHUNK_HEADER.match(line): return PROMPT_MODE_TIMELINE
if _TIMELINE_LIKE_HEADER.match(line): return PROMPT_MODE_FIXED
if _parse_json_list(text) is not None or _LIST_SEPARATOR.search(text): return PROMPT_MODE_LIST
return PROMPT_MODE_FIXED
def resolve_prompt_mode(mode,script):
explicit={PROMPT_FORMAT_FIXED:PROMPT_MODE_FIXED,PROMPT_FORMAT_LIST:PROMPT_MODE_LIST,PROMPT_FORMAT_TIMELINE:PROMPT_MODE_TIMELINE}
if mode==PROMPT_FORMAT_AUTO: return detect_prompt_mode(script)
if mode in explicit: return explicit[mode]
if mode in (PROMPT_MODE_FIXED,PROMPT_MODE_LIST,PROMPT_MODE_TIMELINE): return mode
return PROMPT_MODE_FIXED
def make_prompt_plan(*,mode,script,chunks,chunk_seconds):
chunks=int(chunks); chunk_seconds=float(chunk_seconds)
if not 1<=chunks<=16: raise PromptPlanError("chunks must be between 1 and 16")
if not CHUNK_SECONDS_MIN<=chunk_seconds<=CHUNK_SECONDS_MAX: raise PromptPlanError(f"chunk_seconds must be between {CHUNK_SECONDS_MIN:.1f} and {CHUNK_SECONDS_MAX:.1f}")
notes=[]; diagnostics=[]
try:
resolved_mode=resolve_prompt_mode(mode,script)
if mode==PROMPT_FORMAT_AUTO:
detected={PROMPT_MODE_FIXED:PROMPT_FORMAT_FIXED,PROMPT_MODE_LIST:PROMPT_FORMAT_LIST,PROMPT_MODE_TIMELINE:PROMPT_FORMAT_TIMELINE}[resolved_mode]; notes.append(f"Auto detected {detected}")
if resolved_mode==PROMPT_MODE_FIXED: prompt=_normalize_prompt(script,label="fixed prompt"); prompts=[prompt]*chunks
elif resolved_mode==PROMPT_MODE_LIST:
prompts,parse_notes,list_sources=_parse_list(script,chunks); notes.extend(parse_notes)
if _has_timeline_header(script):
diagnostics.append(_mixed_syntax_diagnostic(timeline_active=False))
diagnostics.extend({"level":"info","code":"H3C-P000","message":f"Chunk {index+1} source: List section {source}"} for index,source in enumerate(list_sources))
elif resolved_mode==PROMPT_MODE_TIMELINE:
mixed_syntax=_has_list_separator(script)
prompts,parse_notes,diagnostics=_parse_timeline(script,chunks,chunk_seconds,ignore_list_separators=mixed_syntax); notes.extend(parse_notes)
if mixed_syntax: diagnostics.insert(0,_mixed_syntax_diagnostic(timeline_active=True))
else: raise PromptPlanError(f"unknown prompt mode: {resolved_mode!r}")
except (PromptPlanError,TypeError,ValueError) as exc:
resolved_mode=PROMPT_MODE_FIXED; prompts=[_normalize_prompt(script,label="fixed prompt")]*chunks
notes.append("Prompt syntax was not recognized; used Fixed prompt fallback")
diagnostics=[{"level":"warning","code":"H3C-P100","message":str(exc)}]
result={"magic":PROMPT_PLAN_MAGIC,"schema_version":PROMPT_PLAN_SCHEMA_VERSION,"mode":resolved_mode,"chunks":chunks,"chunk_seconds":chunk_seconds,"prompts":prompts,"hashes":[prompt_hash(p) for p in prompts],"notes":notes}
if diagnostics: result["diagnostics"]=diagnostics
return result
def validate_prompt_plan(plan):
if not isinstance(plan,dict) or plan.get("magic")!=PROMPT_PLAN_MAGIC: raise PromptPlanError("invalid H3 Continuum prompt plan")
if int(plan.get("schema_version",-1))!=PROMPT_PLAN_SCHEMA_VERSION: raise PromptPlanError(f"unsupported prompt-plan schema {plan.get('schema_version')}; expected {PROMPT_PLAN_SCHEMA_VERSION}")
chunks=int(plan.get("chunks",0)); prompts=plan.get("prompts"); hashes=plan.get("hashes")
if not 1<=chunks<=16: raise PromptPlanError("prompt-plan chunks are invalid")
try: chunk_seconds=float(plan.get("chunk_seconds"))
except (TypeError,ValueError): raise PromptPlanError("prompt-plan chunk_seconds is invalid") from None
if not CHUNK_SECONDS_MIN<=chunk_seconds<=CHUNK_SECONDS_MAX: raise PromptPlanError(f"prompt-plan chunk_seconds must be between {CHUNK_SECONDS_MIN:.1f} and {CHUNK_SECONDS_MAX:.1f}")
if not isinstance(prompts,list) or len(prompts)!=chunks: raise PromptPlanError("prompt-plan prompt count does not match chunks")
if not isinstance(hashes,list) or len(hashes)!=chunks: raise PromptPlanError("prompt-plan hash count does not match chunks")
for index,prompt in enumerate(prompts):
_normalize_prompt(prompt,label=f"prompt {index+1}")
if hashes[index]!=prompt_hash(prompt): raise PromptPlanError(f"prompt-plan hash mismatch at chunk {index+1}")
diagnostics=plan.get("diagnostics")
if diagnostics is not None and (not isinstance(diagnostics,list) or not all(isinstance(item,dict) for item in diagnostics)): raise PromptPlanError("prompt-plan diagnostics are invalid")
return plan
def build_sampler_prompt_plan(*,prompt_mode,prompt_script,sequence_prompt,prompt_plan,chunks,chunk_seconds):
chunks=int(chunks); chunk_seconds=float(chunk_seconds)
if sequence_prompt is not None: return make_prompt_plan(mode=prompt_mode,script=sequence_prompt,chunks=chunks,chunk_seconds=chunk_seconds)
if prompt_plan is not None:
plan=validate_prompt_plan(prompt_plan)
prompts=list(plan["prompts"])
if len(prompts)<chunks: prompts.extend([prompts[-1] if prompts else ""]*(chunks-len(prompts)))
elif len(prompts)>chunks: prompts=prompts[:chunks]
result=dict(plan); result["chunks"]=chunks; result["chunk_seconds"]=chunk_seconds; result["prompts"]=prompts; result["hashes"]=[prompt_hash(p) for p in prompts]
if int(plan["chunks"])!=chunks or abs(float(plan["chunk_seconds"])-chunk_seconds)>1e-6: result["notes"]=list(plan.get("notes") or [])+["adapted connected prompt plan to Sampler chunk settings"]
return validate_prompt_plan(result)
return make_prompt_plan(mode=prompt_mode,script=prompt_script,chunks=chunks,chunk_seconds=chunk_seconds)
def apply_prompt_overrides(plan,overrides):
plan=validate_prompt_plan(plan); prompts=list(plan["prompts"]); replaced=[]
for index,value in enumerate(overrides[:int(plan["chunks"])]):
if value is None: continue
prompts[index]=_normalize_prompt(value,label=f"Clip {index+1} Prompt"); replaced.append(index+1)
if not replaced: return plan
result=dict(plan); result["mode"]=PROMPT_MODE_LIST; result["prompts"]=prompts; result["hashes"]=[prompt_hash(p) for p in prompts]; result["notes"]=list(plan.get("notes") or [])+["external Clip Prompt input(s): "+", ".join(map(str,replaced))]; result.pop("diagnostics",None)
return validate_prompt_plan(result)
def prompt_plan_report(plan):
plan=validate_prompt_plan(plan); unique=len(set(plan["hashes"])); note="; ".join(plan.get("notes") or [])
result=f"Prompt plan: {plan['mode']}; {plan['chunks']} chunks; {unique} unique prompt(s); {plan['chunk_seconds']:.3f}s per chunk."
if note: result+=" "+note+"."
diagnostics=list(plan.get("diagnostics") or [])
if not diagnostics: return result+"\nPrompt Preflight: OK."
warnings=[item for item in diagnostics if str(item.get("level","info")).lower()=="warning"]
info=[item for item in diagnostics if str(item.get("level","info")).lower()!="warning"]
lines=[]
if warnings:
lines.append("PROMPT PREFLIGHT WARNING")
for item in warnings:
code=str(item.get("code","H3C-P000")); message=str(item.get("message",""))
lines.append(f"- WARNING {code}: {message}")
lines.append("")
lines.extend([result,"Prompt Preflight:"])
for item in info:
level=str(item.get("level","info")).upper(); code=str(item.get("code","H3C-P000")); message=str(item.get("message",""))
lines.append(f"- {level} {code}: {message}")
if not info: lines.append("- See warning(s) above.")
return "\n".join(lines)
"""Prompt planning for the integrated H3 Continuum sampler.
The parser is intentionally deterministic and side-effect free so saved workflows
can be reproduced without depending on UI state.
"""
from __future__ import annotations
import hashlib, json, re
from typing import Any
from ..constants import (
CHUNK_SECONDS_MAX,CHUNK_SECONDS_MIN,
PROMPT_FORMAT_AUTO,PROMPT_FORMAT_FIXED,PROMPT_FORMAT_LIST,PROMPT_FORMAT_TIMELINE,
PROMPT_MODE_FIXED,PROMPT_MODE_LIST,PROMPT_MODE_TIMELINE,PROMPT_PLAN_MAGIC,
)
from ..version import PROMPT_PLAN_SCHEMA_VERSION
_TIMELINE_HEADER=re.compile(r"^\s*\[\s*(?P<start>\d+(?:\.\d+)?)\s*(?:s|sec|seconds)?\s*[-–—]\s*(?P<end>\d+(?:\.\d+)?)\s*(?:s|sec|seconds)?\s*\]\s*$",re.IGNORECASE)
_CHUNK_HEADER=re.compile(r"^\s*\[\s*(?:chunk|clip)\s*(?P<index>\d+)\s*\]\s*$",re.IGNORECASE)
_TIMELINE_LIKE_HEADER=re.compile(r"^\s*\[\s*(?:(?:chunk|clip)\b|\d+(?:\.\d+)?[^\]]*(?:[-–—]|\bto\b))",re.IGNORECASE)
_LIST_SEPARATOR=re.compile(r"^\s*---+\s*$",re.MULTILINE)
class PromptPlanError(ValueError): pass
def _prompt_error(code,reason,*,line_number=None,source=None,suggested_fix):
location=f" line {line_number}" if line_number is not None else ""
lines=[f"{code}{location}: {reason}"]
if source is not None: lines.append(f"Source: {source}")
if suggested_fix: lines.append(f"Suggested fix: {suggested_fix}")
raise PromptPlanError("\n".join(lines))
def prompt_hash(prompt:str)->str: return hashlib.sha256(prompt.encode("utf-8")).hexdigest()
def _normalize_prompt(value:str,*,label:str)->str:
return "" if value is None else str(value).strip()
def _parse_json_list(script:str):
stripped=script.lstrip()
if not stripped.startswith("["): return None
try: value=json.loads(script)
except json.JSONDecodeError: return None
if not isinstance(value,list) or not all(isinstance(item,str) for item in value): return None
return [_normalize_prompt(item,label=f"prompt {index+1}") for index,item in enumerate(value)]
def _parse_list(script,chunks):
values=_parse_json_list(script)
if values is None: values=[_normalize_prompt(part,label=f"prompt {index+1}") for index,part in enumerate(_LIST_SEPARATOR.split(script)) if part.strip()]
if not values: values=[str(script)]
source_count=len(values); notes=[]
if len(values)<chunks: notes.append(f"repeated the last prompt for {chunks-len(values)} chunk(s)"); values.extend([values[-1]]*(chunks-len(values)))
elif len(values)>chunks: notes.append(f"ignored {len(values)-chunks} extra prompt(s)"); values=values[:chunks]
sources=[min(index+1,source_count) for index in range(len(values))]
return values,notes,sources
def _timeline_preamble(script,*,ignore_list_separators=False):
body=[]
for line in str(script).splitlines():
if _TIMELINE_HEADER.match(line) or _CHUNK_HEADER.match(line): break
if ignore_list_separators and _LIST_SEPARATOR.fullmatch(line): continue
body.append(line)
return "\n".join(body).strip()
def _parse_timeline_sections(script,*,allow_preamble=True,ignore_list_separators=False):
preamble=_timeline_preamble(script,ignore_list_separators=ignore_list_separators)
sections=[]; current=None; body=[]
def finish():
nonlocal current,body
if current is None:
if any(line.strip() for line in body) and not allow_preamble: raise PromptPlanError("timeline text before the first [0-5s] or [Chunk 1] header is not allowed")
body=[]; return
if not any(line.strip() for line in body):
_prompt_error("H3C-P005","timeline section body is empty",line_number=current["line_number"],source=current["source"],suggested_fix="add prompt text below this header")
prompt=_normalize_prompt("\n".join(body),label="timeline section")
current["prompt"]=f"{preamble}\n\n{prompt}" if preamble else prompt
sections.append(current); current=None; body=[]
for line_number,line in enumerate(str(script).splitlines(),start=1):
time_match=_TIMELINE_HEADER.match(line); chunk_match=_CHUNK_HEADER.match(line)
if time_match or chunk_match:
finish()
if time_match:
start=float(time_match.group("start")); end=float(time_match.group("end"))
if not end>start: _prompt_error("H3C-P002","timeline end must be greater than its start",line_number=line_number,source=line.strip(),suggested_fix="use an increasing range such as [0-5s]")
current={"kind":"time","start":start,"end":end,"line_number":line_number,"source":line.strip()}
else:
index=int(chunk_match.group("index"))
if index<1: _prompt_error("H3C-P004","chunk numbers are one-based",line_number=line_number,source=line.strip(),suggested_fix="use [Chunk 1] or a larger one-based chunk number")
current={"kind":"chunk","index":index,"line_number":line_number,"source":line.strip()}
continue
if _TIMELINE_LIKE_HEADER.match(line):
_prompt_error("H3C-P001","invalid timeline header",line_number=line_number,source=line.strip(),suggested_fix="use [0-5s] or [Chunk 1]")
if ignore_list_separators and _LIST_SEPARATOR.fullmatch(line):
continue
body.append(line)
finish()
if not sections: raise PromptPlanError("timeline contains no sections")
return sections
def parse_sparse_prompt_overrides(script):
sections=_parse_timeline_sections(script,allow_preamble=False); overrides={}
for item in sections:
if item["kind"]!="chunk": raise PromptPlanError("Sparse Clip Overrides only accepts [Clip N] or [Chunk N] sections")
index=int(item["index"])
if index in overrides: raise PromptPlanError(f"Sparse Clip Overrides defines Clip {index} more than once")
overrides[index]=item["prompt"]
return overrides
def validate_sparse_prompt_overrides(overrides,*,chunks):
chunks=int(chunks)
if not isinstance(overrides,dict): raise PromptPlanError("Sparse Clip Overrides must be a dictionary")
validated={}
for index,prompt in overrides.items():
if type(index) is not int: raise PromptPlanError("Sparse Clip Override numbers must be integers")
if not 1<=index<=chunks: raise PromptPlanError(f"Sparse Clip Override {index} is outside the configured 1-{chunks} chunks")
validated[index]=_normalize_prompt(prompt,label=f"Clip {index} Override")
if not validated: raise PromptPlanError("Sparse Clip Overrides contains no overrides")
return validated
def _parse_timeline(script,chunks,chunk_seconds,*,ignore_list_separators=False):
sections=_parse_timeline_sections(script,ignore_list_separators=ignore_list_separators); prompts=[]; notes=[]; diagnostics=[]
if _timeline_preamble(script,ignore_list_separators=ignore_list_separators): notes.append("applied timeline preamble to all chunks")
seen_chunks={}; total_end=chunks*chunk_seconds; usable=[]
for item in sections:
if item["kind"]=="chunk":
index=int(item["index"])
if index in seen_chunks:
_prompt_error("H3C-P003",f"timeline defines Chunk {index} more than once",line_number=item["line_number"],source=item["source"],suggested_fix=f"keep only one [Chunk {index}] section")
seen_chunks[index]=item
if index<=chunks: usable.append(item)
else: diagnostics.append({"level":"warning","code":"H3C-P104","message":f"ignored {item['source']} because the configured sequence has only {chunks} chunk(s)"})
elif min(total_end,item["end"])-max(0.0,item["start"])>0:
usable.append(item)
else:
diagnostics.append({"level":"warning","code":"H3C-P104","message":f"ignored {item['source']} because it is outside 0-{total_end:.3f}s"})
if not usable:
_prompt_error("H3C-P005","timeline contains no usable prompt section for the configured sequence",suggested_fix="add a section such as [0-5s] with non-empty prompt text")
previous_prompt=None; previous_source=None
for chunk_index in range(1,chunks+1):
chunk_sections=[item for item in sections if item["kind"]=="chunk" and item["index"]==chunk_index]
if chunk_sections:
selected=chunk_sections[0]; prompts.append(selected["prompt"]); previous_prompt=selected["prompt"]; previous_source=f"{selected['source']} at line {selected['line_number']}"
diagnostics.append({"level":"info","code":"H3C-P000","message":f"Chunk {chunk_index} source: {previous_source}"}); continue
start=(chunk_index-1)*chunk_seconds; end=chunk_index*chunk_seconds; scored=[]
for order,item in enumerate(sections):
if item["kind"]!="time": continue
overlap=max(0.0,min(end,item["end"])-max(start,item["start"]))
if overlap>0: scored.append((overlap,-order,item))
if not scored:
if previous_prompt is None:
selected=usable[0]; fallback_reason=f"used earliest valid prompt from {selected['source']}"
else:
selected=None; fallback_reason=f"reused previous prompt from {previous_source}"
prompt=selected["prompt"] if selected is not None else previous_prompt
source=f"{selected['source']} at line {selected['line_number']}" if selected is not None else previous_source
prompts.append(prompt); previous_prompt=prompt; previous_source=source
diagnostics.append({"level":"warning","code":"H3C-P101","message":f"Timeline does not cover Chunk {chunk_index} ({start:.3f}-{end:.3f}s); {fallback_reason}."})
diagnostics.append({"level":"info","code":"H3C-P000","message":f"Chunk {chunk_index} source: fallback to {source}"}); continue
scored.sort(reverse=True,key=lambda row:(row[0],row[1])); selected=scored[0][2]; prompts.append(selected["prompt"]); previous_prompt=selected["prompt"]; previous_source=f"{selected['source']} at line {selected['line_number']}"
diagnostics.append({"level":"info","code":"H3C-P000","message":f"Chunk {chunk_index} source: {previous_source}"})
if len(scored)>1 and abs(scored[0][0]-scored[1][0])<1e-9: notes.append(f"chunk {chunk_index} had an equal-overlap timeline tie; used the earlier section")
return prompts,notes,diagnostics
def _has_timeline_header(script):
return any(_TIMELINE_HEADER.match(line) or _CHUNK_HEADER.match(line) for line in str(script).splitlines())
def _has_list_separator(script):
return _LIST_SEPARATOR.search(str(script)) is not None
def _mixed_syntax_diagnostic(*,timeline_active):
message="Mixed Timeline and List prompt syntax detected. Use either [Chunk N] / [0-5s] sections or --- separators, not both."
if timeline_active: message+=" Standalone --- separators were ignored because Timeline syntax is active."
return {"level":"warning","code":"H3C-P105","message":message}
def detect_prompt_mode(script):
text=str(script)
for line in text.splitlines():
if _TIMELINE_HEADER.match(line) or _CHUNK_HEADER.match(line): return PROMPT_MODE_TIMELINE
if _TIMELINE_LIKE_HEADER.match(line): return PROMPT_MODE_FIXED
if _parse_json_list(text) is not None or _LIST_SEPARATOR.search(text): return PROMPT_MODE_LIST
return PROMPT_MODE_FIXED
def resolve_prompt_mode(mode,script):
explicit={PROMPT_FORMAT_FIXED:PROMPT_MODE_FIXED,PROMPT_FORMAT_LIST:PROMPT_MODE_LIST,PROMPT_FORMAT_TIMELINE:PROMPT_MODE_TIMELINE}
if mode==PROMPT_FORMAT_AUTO: return detect_prompt_mode(script)
if mode in explicit: return explicit[mode]
if mode in (PROMPT_MODE_FIXED,PROMPT_MODE_LIST,PROMPT_MODE_TIMELINE): return mode
return PROMPT_MODE_FIXED
def make_prompt_plan(*,mode,script,chunks,chunk_seconds):
chunks=int(chunks); chunk_seconds=float(chunk_seconds)
if not 1<=chunks<=16: raise PromptPlanError("chunks must be between 1 and 16")
if not CHUNK_SECONDS_MIN<=chunk_seconds<=CHUNK_SECONDS_MAX: raise PromptPlanError(f"chunk_seconds must be between {CHUNK_SECONDS_MIN:.1f} and {CHUNK_SECONDS_MAX:.1f}")
notes=[]; diagnostics=[]
try:
resolved_mode=resolve_prompt_mode(mode,script)
if mode==PROMPT_FORMAT_AUTO:
detected={PROMPT_MODE_FIXED:PROMPT_FORMAT_FIXED,PROMPT_MODE_LIST:PROMPT_FORMAT_LIST,PROMPT_MODE_TIMELINE:PROMPT_FORMAT_TIMELINE}[resolved_mode]; notes.append(f"Auto detected {detected}")
if resolved_mode==PROMPT_MODE_FIXED: prompt=_normalize_prompt(script,label="fixed prompt"); prompts=[prompt]*chunks
elif resolved_mode==PROMPT_MODE_LIST:
prompts,parse_notes,list_sources=_parse_list(script,chunks); notes.extend(parse_notes)
if _has_timeline_header(script):
diagnostics.append(_mixed_syntax_diagnostic(timeline_active=False))
diagnostics.extend({"level":"info","code":"H3C-P000","message":f"Chunk {index+1} source: List section {source}"} for index,source in enumerate(list_sources))
elif resolved_mode==PROMPT_MODE_TIMELINE:
mixed_syntax=_has_list_separator(script)
prompts,parse_notes,diagnostics=_parse_timeline(script,chunks,chunk_seconds,ignore_list_separators=mixed_syntax); notes.extend(parse_notes)
if mixed_syntax: diagnostics.insert(0,_mixed_syntax_diagnostic(timeline_active=True))
else: raise PromptPlanError(f"unknown prompt mode: {resolved_mode!r}")
except (PromptPlanError,TypeError,ValueError) as exc:
resolved_mode=PROMPT_MODE_FIXED; prompts=[_normalize_prompt(script,label="fixed prompt")]*chunks
notes.append("Prompt syntax was not recognized; used Fixed prompt fallback")
diagnostics=[{"level":"warning","code":"H3C-P100","message":str(exc)}]
result={"magic":PROMPT_PLAN_MAGIC,"schema_version":PROMPT_PLAN_SCHEMA_VERSION,"mode":resolved_mode,"chunks":chunks,"chunk_seconds":chunk_seconds,"prompts":prompts,"hashes":[prompt_hash(p) for p in prompts],"notes":notes}
if diagnostics: result["diagnostics"]=diagnostics
return result
def validate_prompt_plan(plan):
if not isinstance(plan,dict) or plan.get("magic")!=PROMPT_PLAN_MAGIC: raise PromptPlanError("invalid H3 Continuum prompt plan")
if int(plan.get("schema_version",-1))!=PROMPT_PLAN_SCHEMA_VERSION: raise PromptPlanError(f"unsupported prompt-plan schema {plan.get('schema_version')}; expected {PROMPT_PLAN_SCHEMA_VERSION}")
chunks=int(plan.get("chunks",0)); prompts=plan.get("prompts"); hashes=plan.get("hashes")
if not 1<=chunks<=16: raise PromptPlanError("prompt-plan chunks are invalid")
try: chunk_seconds=float(plan.get("chunk_seconds"))
except (TypeError,ValueError): raise PromptPlanError("prompt-plan chunk_seconds is invalid") from None
if not CHUNK_SECONDS_MIN<=chunk_seconds<=CHUNK_SECONDS_MAX: raise PromptPlanError(f"prompt-plan chunk_seconds must be between {CHUNK_SECONDS_MIN:.1f} and {CHUNK_SECONDS_MAX:.1f}")
if not isinstance(prompts,list) or len(prompts)!=chunks: raise PromptPlanError("prompt-plan prompt count does not match chunks")
if not isinstance(hashes,list) or len(hashes)!=chunks: raise PromptPlanError("prompt-plan hash count does not match chunks")
for index,prompt in enumerate(prompts):
_normalize_prompt(prompt,label=f"prompt {index+1}")
if hashes[index]!=prompt_hash(prompt): raise PromptPlanError(f"prompt-plan hash mismatch at chunk {index+1}")
diagnostics=plan.get("diagnostics")
if diagnostics is not None and (not isinstance(diagnostics,list) or not all(isinstance(item,dict) for item in diagnostics)): raise PromptPlanError("prompt-plan diagnostics are invalid")
return plan
def build_sampler_prompt_plan(*,prompt_mode,prompt_script,sequence_prompt,prompt_plan,chunks,chunk_seconds):
chunks=int(chunks); chunk_seconds=float(chunk_seconds)
if sequence_prompt is not None: return make_prompt_plan(mode=prompt_mode,script=sequence_prompt,chunks=chunks,chunk_seconds=chunk_seconds)
if prompt_plan is not None:
plan=validate_prompt_plan(prompt_plan)
prompts=list(plan["prompts"])
if len(prompts)<chunks: prompts.extend([prompts[-1] if prompts else ""]*(chunks-len(prompts)))
elif len(prompts)>chunks: prompts=prompts[:chunks]
result=dict(plan); result["chunks"]=chunks; result["chunk_seconds"]=chunk_seconds; result["prompts"]=prompts; result["hashes"]=[prompt_hash(p) for p in prompts]
if int(plan["chunks"])!=chunks or abs(float(plan["chunk_seconds"])-chunk_seconds)>1e-6: result["notes"]=list(plan.get("notes") or [])+["adapted connected prompt plan to Sampler chunk settings"]
return validate_prompt_plan(result)
return make_prompt_plan(mode=prompt_mode,script=prompt_script,chunks=chunks,chunk_seconds=chunk_seconds)
def apply_prompt_overrides(plan,overrides):
plan=validate_prompt_plan(plan); prompts=list(plan["prompts"]); replaced=[]
for index,value in enumerate(overrides[:int(plan["chunks"])]):
if value is None: continue
prompts[index]=_normalize_prompt(value,label=f"Clip {index+1} Prompt"); replaced.append(index+1)
if not replaced: return plan
result=dict(plan); result["mode"]=PROMPT_MODE_LIST; result["prompts"]=prompts; result["hashes"]=[prompt_hash(p) for p in prompts]; result["notes"]=list(plan.get("notes") or [])+["external Clip Prompt input(s): "+", ".join(map(str,replaced))]; result.pop("diagnostics",None)
return validate_prompt_plan(result)
def prompt_plan_report(plan):
plan=validate_prompt_plan(plan); unique=len(set(plan["hashes"])); note="; ".join(plan.get("notes") or [])
result=f"Prompt plan: {plan['mode']}; {plan['chunks']} chunks; {unique} unique prompt(s); {plan['chunk_seconds']:.3f}s per chunk."
if note: result+=" "+note+"."
diagnostics=list(plan.get("diagnostics") or [])
if not diagnostics: return result+"\nPrompt Preflight: OK."
warnings=[item for item in diagnostics if str(item.get("level","info")).lower()=="warning"]
info=[item for item in diagnostics if str(item.get("level","info")).lower()!="warning"]
lines=[]
if warnings:
lines.append("PROMPT PREFLIGHT WARNING")
for item in warnings:
code=str(item.get("code","H3C-P000")); message=str(item.get("message",""))
lines.append(f"- WARNING {code}: {message}")
lines.append("")
lines.extend([result,"Prompt Preflight:"])
for item in info:
level=str(item.get("level","info")).upper(); code=str(item.get("code","H3C-P000")); message=str(item.get("message",""))
lines.append(f"- {level} {code}: {message}")
if not info: lines.append("- See warning(s) above.")
return "\n".join(lines)
+710 -458
View File
File diff suppressed because it is too large Load Diff