Compare commits

...
1 Commits
16 changed files with 879 additions and 33 deletions
+7
View File
@@ -0,0 +1,7 @@
# DOGMA 1.0.57 / API Platform V5
Optional “Correggi scatti” for both Seedance video workflows. Saves the original plus a separate `_FIX.mp4`; no extra API generation. Content-based motion analysis detects short holds, isolated jumps and recurring cadence at the source framerate. Local timeline repair preserves frame count, timestamps, dimensions and audio packets. Selective RIFE 4.26 inference uses the original resolution and 16-bit RGB intermediates; 10-bit sources stay 10-bit. Reliably tracked pans with repeated jumps also receive restrained camera translation correction in the same encoding pass, bounded to 0.4% of each dimension, with narrow reflected edge fill and no crop/zoom. Camera correction is skipped for clean clips, unreliable tracking, zoom, rotation or reversing camera paths. NVIDIA hardware encoding is preferred, with software encoding fallback. Shot boundaries, intentional holds and motion checks limit unnecessary changes. Unchanged clips are copied without re-encoding. Saving/repair runs outside the async API event loop; concurrent outputs reserve separate filenames. Stop cancels local processing; errors preserve the already generated original. Project/scene library records include both variants and the repair report.
Video preview play overlay follows the supplied design: white filled triangle, thin outline circle, 50% opacity. The Run button is unchanged.
RIFE weights download automatically once (approximately 23 MB) into ComfyUI/models/DOGMA/rife, only when a repair is needed. The pinned model archive and weights are SHA-256 verified; no downloaded Python is executed. RIFE architecture and weights are MIT licensed; see LICENSE_RIFE.txt. Previous node IDs and workflows remain compatible.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 hzwer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+9
View File
@@ -204,3 +204,12 @@ Open DOGMA_API_PLATFORM_V3.json: one launcher node. The panel appears before asy
## API Platform V4 / 1.0.56
Open DOGMA_API_PLATFORM_V4.json: one launcher node. The panel appears before asynchronous initialization. Folder navigation stays in the browser. Stop cancels DOGMA jobs; provider billing for already completed work still applies. Remaining time is an estimate from completed jobs when available.
## API Platform V5 / 1.0.57 — selective video repair
Enable **Correggi scatti** in Video to save both the original and `_FIX.mp4`. Both Ref → Video and First / Last frame use the same local repair. The setting does not change paid API inputs, quantities or seeds. A verified unchanged copy is produced when no reliable problem is detected. If processing fails or is stopped, the original remains available and the panel shows a warning.
The detector operates on small previews; RIFE reconstructs only selected frames at source resolution. Reliable pans with repeated jumps may additionally receive small camera translations, capped at 0.4% of width/height. This extends a thin edge strip by reflection instead of cropping or zooming. Camera refinement and interpolation share one encoding pass. Clean clips, poorly tracked shots, zooms and reversing camera paths are not stabilized. Frame count, timestamps, source bit depth and audio packet identity are checked before accepting the second file. A motion-based quality gate is an additional check, not a guarantee against every possible visual artifact. The method is independent of source fps and has no fixed clip-duration setting; processing time and memory grow with frame count and resolution. It does not impose 24 fps. CUDA and NVIDIA video encoding provide the fast path; CPU/software fallback is slower. First use includes model download and GPU initialization. No video is uploaded to another service. Generative deformations or newly invented content cannot be reliably restored by a cadence repair.
RIFE 4.26 code/weights: https://github.com/hzwer/Practical-RIFE (MIT; LICENSE_RIFE.txt). Verified weights are automatically cached under `models/DOGMA/rife`. Architecture derived from the official model archive, revision `01fdc7e97404120c243c3ea7b427046e5dc7643e`. DOGMA motion detection, timestamp planning and integration are separate from RIFE inference. No other ComfyUI interpolation extension is required.
+54 -6
View File
@@ -103,7 +103,7 @@ def _import_workspace(root):
candidate=(path.parent.parent/relative/name).resolve()
else:candidate=(path.parent/name).resolve()
if not candidate.is_relative_to(root) or not candidate.is_file():continue
files.append({'filename':name,'workspace':str(root),'relative':candidate.relative_to(root).as_posix(),'type':'workspace'})
files.append({'filename':name,'workspace':str(root),'relative':candidate.relative_to(root).as_posix(),'type':'workspace',**({'variant':original['variant']} if original.get('variant') else {})})
exported.append(str(candidate))
if not files:continue
data.update(workspace=str(root),images=files,exported=exported,status='completed',imported=True)
@@ -260,17 +260,65 @@ class DOGMAAPIVideoOutputV2:
FUNCTION='save'
CATEGORY='DOGMA/API Platform'
def save(self,video,metadata,prompt=None,extra_pnginfo=None):
async def save(self,video,metadata,prompt=None,extra_pnginfo=None):
cancelled=threading.Event()
worker=asyncio.create_task(asyncio.to_thread(self._save,video,metadata,prompt,extra_pnginfo,cancelled))
try:
return await asyncio.shield(worker)
except asyncio.CancelledError:
cancelled.set()
# Let the worker retain the generated original and remove its partial fix.
try:await worker
except Exception:pass
raise
def _save(self,video,metadata,prompt=None,extra_pnginfo=None,cancelled=None):
from comfy_api.latest import Types
import folder_paths
from comfy.cli_args import args
data=json.loads(metadata);width,height=video.get_dimensions()
folder,filename,counter,subfolder,_=folder_paths.get_save_image_path(_save_prefix(data),str(_output()),width,height)
filename=f'{filename}_{counter:05}_.mp4'
with _LOCK:
folder,stem,counter,subfolder,_=folder_paths.get_save_image_path(_save_prefix(data),str(_output()),width,height)
while True:
filename=f'{stem}_{counter:05}_.mp4';source=Path(folder)/filename
try:
# Reserve before releasing the lock; async branches must never overwrite.
with source.open('xb'):pass
break
except FileExistsError:counter+=1
saved_metadata=None if args.disable_metadata else {**(extra_pnginfo or {}),'prompt':prompt}
video.save_to(str(Path(folder)/filename),format=Types.VideoContainer('mp4'),codec=Types.VideoCodec('auto'),metadata=saved_metadata)
try:
video.save_to(str(source),format=Types.VideoContainer('mp4'),codec=Types.VideoCodec('auto'),metadata=saved_metadata)
except BaseException:
source.unlink(missing_ok=True)
raise
files=[{'filename':filename,'subfolder':subfolder,'type':'output','format':'video/mp4'}]
record=_record(metadata,files,'video')
if data.get('videoRepair'):
files[0]['variant']='original'
try:
from .dogma_video_repair import repair_video
import comfy.model_management as management
from server import PromptServer
def progress(stage, fraction):
# The job ID is stable before/after the batch receives its prompt ID.
PromptServer.instance.send_sync('dogma_video_repair',{'job_id':data['id'],'stage':stage,'value':fraction})
def check_cancel():
from .dogma_video_repair import RepairCancelled
if cancelled is not None and cancelled.is_set():raise RepairCancelled('Correzione interrotta.')
management.throw_exception_if_processing_interrupted()
fixed=source.with_name(source.stem+'_FIX.mp4')
report=repair_video(source,fixed,Path(folder_paths.models_dir)/'DOGMA'/'rife',
cancel=check_cancel,progress=progress)
data['repair']=report
files.append({'filename':fixed.name,'subfolder':subfolder,'type':'output','format':'video/mp4',
'variant':'repaired' if report['status']=='repaired' else 'checked'})
if report['status']=='skipped_quality':
data['warning']='Fix non applicato: il controllo del movimento non ha confermato un miglioramento. La seconda copia conserva l’originale.'
except Exception as exc:
# Never repeat a paid generation when only local post-processing fails.
data['repair']={'status':'failed','error':str(exc)}
data['warning']='Originale salvato. Correzione scatti non completata: '+(str(exc) or 'interrotta')
record=_record(json.dumps(data,ensure_ascii=False),files,'video')
return {'ui':{'images':files,'animated':(True,),'dogma_records':[record]},'result':()}
+193
View File
@@ -0,0 +1,193 @@
# RIFE 4.26 inference architecture, adapted from hzwer/Practical-RIFE.
# MIT license, Copyright (c) 2021 hzwer. See LICENSE_RIFE.txt.
# Changes: package-local warp, device/dtype-aware bounded grid cache.
import torch
backwarp_tenGrid={}
def warp(tenInput, tenFlow):
flow_device = tenFlow.device
k = (str(flow_device), str(tenFlow.size()), str(tenFlow.dtype))
if k not in backwarp_tenGrid:
tenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3], device=flow_device).view(
1, 1, 1, tenFlow.shape[3]).expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1)
tenVertical = torch.linspace(-1.0, 1.0, tenFlow.shape[2], device=flow_device).view(
1, 1, tenFlow.shape[2], 1).expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3])
backwarp_tenGrid[k] = torch.cat(
[tenHorizontal, tenVertical], 1).to(flow_device)
tenFlow = torch.cat([tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0),
tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0)], 1)
g = (backwarp_tenGrid[k] + tenFlow).permute(0, 2, 3, 1)
if len(backwarp_tenGrid)>8:backwarp_tenGrid.clear()
g=g.to(tenInput.dtype)
return torch.nn.functional.grid_sample(input=tenInput, grid=g, mode='bilinear', padding_mode='border', align_corners=True)
import torch
import torch.nn as nn
import torch.nn.functional as F
# from train_log.refine import *
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation, bias=True),
nn.LeakyReLU(0.2, True)
)
def conv_bn(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation, bias=False),
nn.BatchNorm2d(out_planes),
nn.LeakyReLU(0.2, True)
)
class Head(nn.Module):
def __init__(self):
super(Head, self).__init__()
self.cnn0 = nn.Conv2d(3, 16, 3, 2, 1)
self.cnn1 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn2 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn3 = nn.ConvTranspose2d(16, 4, 4, 2, 1)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x, feat=False):
x0 = self.cnn0(x)
x = self.relu(x0)
x1 = self.cnn1(x)
x = self.relu(x1)
x2 = self.cnn2(x)
x = self.relu(x2)
x3 = self.cnn3(x)
if feat:
return [x0, x1, x2, x3]
return x3
class ResConv(nn.Module):
def __init__(self, c, dilation=1):
super(ResConv, self).__init__()
self.conv = nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1\
)
self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x):
return self.relu(self.conv(x) * self.beta + x)
class IFBlock(nn.Module):
def __init__(self, in_planes, c=64):
super(IFBlock, self).__init__()
self.conv0 = nn.Sequential(
conv(in_planes, c//2, 3, 2, 1),
conv(c//2, c, 3, 2, 1),
)
self.convblock = nn.Sequential(
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
)
self.lastconv = nn.Sequential(
nn.ConvTranspose2d(c, 4*13, 4, 2, 1),
nn.PixelShuffle(2)
)
def forward(self, x, flow=None, scale=1):
x = F.interpolate(x, scale_factor= 1. / scale, mode="bilinear", align_corners=False)
if flow is not None:
flow = F.interpolate(flow, scale_factor= 1. / scale, mode="bilinear", align_corners=False) * 1. / scale
x = torch.cat((x, flow), 1)
feat = self.conv0(x)
feat = self.convblock(feat)
tmp = self.lastconv(feat)
tmp = F.interpolate(tmp, scale_factor=scale, mode="bilinear", align_corners=False)
flow = tmp[:, :4] * scale
mask = tmp[:, 4:5]
feat = tmp[:, 5:]
return flow, mask, feat
class IFNet(nn.Module):
def __init__(self):
super(IFNet, self).__init__()
self.block0 = IFBlock(7+8, c=192)
self.block1 = IFBlock(8+4+8+8, c=128)
self.block2 = IFBlock(8+4+8+8, c=96)
self.block3 = IFBlock(8+4+8+8, c=64)
self.block4 = IFBlock(8+4+8+8, c=32)
self.encode = Head()
# not used during inference
'''
self.teacher = IFBlock(8+4+8+3+8, c=64)
self.caltime = nn.Sequential(
nn.Conv2d(16+9, 8, 3, 2, 1),
nn.LeakyReLU(0.2, True),
nn.Conv2d(32, 64, 3, 2, 1),
nn.LeakyReLU(0.2, True),
nn.Conv2d(64, 64, 3, 1, 1),
nn.LeakyReLU(0.2, True),
nn.Conv2d(64, 64, 3, 1, 1),
nn.LeakyReLU(0.2, True),
nn.Conv2d(64, 1, 3, 1, 1),
nn.Sigmoid()
)
'''
def forward(self, x, timestep=0.5, scale_list=[8, 4, 2, 1], training=False, fastmode=True, ensemble=False):
if training == False:
channel = x.shape[1] // 2
img0 = x[:, :channel]
img1 = x[:, channel:]
if not torch.is_tensor(timestep):
timestep = (x[:, :1].clone() * 0 + 1) * timestep
else:
timestep = timestep.repeat(1, 1, img0.shape[2], img0.shape[3])
f0 = self.encode(img0[:, :3])
f1 = self.encode(img1[:, :3])
flow_list = []
merged = []
mask_list = []
warped_img0 = img0
warped_img1 = img1
flow = None
mask = None
loss_cons = 0
block = [self.block0, self.block1, self.block2, self.block3, self.block4]
for i in range(5):
if flow is None:
flow, mask, feat = block[i](torch.cat((img0[:, :3], img1[:, :3], f0, f1, timestep), 1), None, scale=scale_list[i])
if ensemble:
print("warning: ensemble is not supported since RIFEv4.21")
else:
wf0 = warp(f0, flow[:, :2])
wf1 = warp(f1, flow[:, 2:4])
fd, m0, feat = block[i](torch.cat((warped_img0[:, :3], warped_img1[:, :3], wf0, wf1, timestep, mask, feat), 1), flow, scale=scale_list[i])
if ensemble:
print("warning: ensemble is not supported since RIFEv4.21")
else:
mask = m0
flow = flow + fd
mask_list.append(mask)
flow_list.append(flow)
warped_img0 = warp(img0, flow[:, :2])
warped_img1 = warp(img1, flow[:, 2:4])
merged.append((warped_img0, warped_img1))
mask = torch.sigmoid(mask)
merged[4] = (warped_img0 * mask + warped_img1 * (1 - mask))
if not fastmode:
print('contextnet is removed')
'''
c0 = self.contextnet(img0, flow[:, :2])
c1 = self.contextnet(img1, flow[:, 2:4])
tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1)
res = tmp[:, :3] * 2 - 1
merged[4] = torch.clamp(merged[4] + res, 0, 1)
'''
return flow_list, mask_list[4], merged
+557
View File
@@ -0,0 +1,557 @@
"""Selective motion repair. Original timestamps, frame count, audio and size survive.
Detection uses low-resolution tracked motion, never a hard-coded Seedance cadence.
RIFE 4.26 reconstructs only selected times, on the machine running ComfyUI.
"""
from __future__ import annotations
import hashlib
import json
import math
import os
from pathlib import Path
import shutil
import tempfile
import threading
import time
import urllib.request
import zipfile
from fractions import Fraction
import numpy as np
MODEL_URL = 'https://huggingface.co/hzwer/RIFE/resolve/01fdc7e97404120c243c3ea7b427046e5dc7643e/RIFEv4.26_0921.zip'
ARCHIVE_SHA256 = '1fa9b9cda3d9b8c3e301359e2595960902f97bf926c08598b0e9957a3f3f760e'
WEIGHT_SHA256 = '45c7f74156704769dc9f85cfcaf8552e1e926f9399dcfa3a553dee88fac6f53f'
_MODEL_LOCK = threading.Lock()
_RENDER_LOCK = threading.Lock()
class RepairCancelled(Exception):
pass
def _check(cancel):
if cancel:
cancel()
def _digest(path):
result=hashlib.sha256()
with open(path, 'rb') as f:
while block:=f.read(1024*1024):result.update(block)
return result.hexdigest()
def model_file(directory, cancel=None, progress=None):
"""Only verified weights are downloaded; remote Python is never executed."""
directory = Path(directory)
path = directory / 'rife426.pkl'
while not _MODEL_LOCK.acquire(timeout=.1):_check(cancel)
try:
_check(cancel)
if path.is_file() and _digest(path) == WEIGHT_SHA256:
return path
directory.mkdir(parents=True, exist_ok=True)
if progress:
progress('Download modello · solo al primo utilizzo', 0)
with tempfile.TemporaryDirectory(prefix='rife-', dir=directory) as temp:
archive = Path(temp) / 'model.zip'
with urllib.request.urlopen(MODEL_URL, timeout=30) as response, archive.open('wb') as out:
size = 0
while block := response.read(1024 * 1024):
_check(cancel)
size += len(block)
if size > 30_000_000:
raise ValueError('Download RIFE di dimensione inattesa.')
out.write(block)
if _digest(archive) != ARCHIVE_SHA256:
raise ValueError('Verifica del modello RIFE non riuscita. Riprova il download.')
weight = Path(temp) / 'weights.pkl'
with zipfile.ZipFile(archive) as z:
weight.write_bytes(z.read('RIFEv4.26_0921/flownet.pkl'))
if _digest(weight) != WEIGHT_SHA256:
raise ValueError('Pesi RIFE non validi.')
_check(cancel)
weight.replace(path)
return path
finally:
_MODEL_LOCK.release()
def measure_pair(a, b):
"""Track real displacements; pixel differences alone confuse light and motion."""
import cv2
af, bf = a.astype(np.float32), b.astype(np.float32)
diff = float(np.mean(np.abs(bf-af)))
light = float(abs(np.mean(bf)-np.mean(af)))
row = dict(diff=diff, brightness=light, motion=0., x=0., y=0., reliability=0., cut=False)
points = cv2.goodFeaturesToTrack(a, 500, .015, 5)
if points is None or len(points) < 12:
row['cut'] = diff > 18
return row
q, ok, _ = cv2.calcOpticalFlowPyrLK(a, b, points, None, winSize=(21,21), maxLevel=3)
back, ok2, _ = cv2.calcOpticalFlowPyrLK(b, a, q, None, winSize=(21,21), maxLevel=3)
good = (ok[:,0] > 0) & (ok2[:,0] > 0) & (np.linalg.norm(back[:,0]-points[:,0], axis=1) < .6)
row['reliability'] = float(good.mean())
vectors = (q[:,0]-points[:,0])[good]
if len(vectors) >= 12:
# A camera estimate needs agreement across the image, not just one subject.
p, tracked = points[good,0], q[good,0]
transform, inside = cv2.estimateAffinePartial2D(p, tracked, method=cv2.RANSAC,
ransacReprojThreshold=.25, maxIters=500, confidence=.995, refineIters=5)
if transform is not None and inside is not None:
selected=p[inside[:,0]>0];h,w=a.shape
occupied={(min(3,int(x*4/w)),min(2,int(y*3/h))) for x,y in selected}
center=np.array([w/2,h/2]);delta=transform[:,:2]@center+transform[:,2]-center
coverage=float(np.prod(np.ptp(selected,axis=0)/[w,h])) if len(selected)>1 else 0.
row['camera']=dict(x=float(delta[0]),y=float(delta[1]),
inliers=float(inside.mean()),coverage=coverage,cells=len(occupied),
scale=float(np.sqrt(abs(np.linalg.det(transform[:,:2])))),
angle=float(np.degrees(np.arctan2(transform[1,0],transform[0,0]))))
magnitudes=np.linalg.norm(vectors,axis=1)
moving=vectors[magnitudes>max(.05,float(np.percentile(magnitudes,90))*.35)]
# A moving subject can occupy less than half of an otherwise static shot.
if np.median(magnitudes)<.04 and len(moving)>=max(12,len(vectors)*.1):vectors=moving
row['motion'] = float(np.percentile(np.linalg.norm(vectors, axis=1), 75))
row['x'], row['y'] = map(float, np.median(vectors, axis=0))
# Histogram changes plus failed tracking distinguish cuts from fast pans.
ha = cv2.calcHist([a],[0],None,[32],[0,256]); hb = cv2.calcHist([b],[0],None,[32],[0,256])
ha /= max(1., float(ha.sum())); hb /= max(1., float(hb.sum()))
hist = cv2.compareHist(ha, hb, cv2.HISTCMP_BHATTACHARYYA)
row['cut'] = bool((diff > 24 and row['reliability'] < .45) or (diff > 36 and hist > .4))
return row
def analyze(source, cancel=None, progress=None):
import av
import cv2
start = time.perf_counter()
with av.open(str(source)) as c:
v = c.streams.video[0]
v.thread_type = 'AUTO';v.thread_count=4
fps = v.average_rate or v.base_rate
if not fps or fps <= 0:
raise ValueError('Il video non dichiara un framerate valido.')
meta = dict(fps=str(fps), time_base=str(v.time_base), width=v.width, height=v.height,
pixel_format=v.format.name, bit_depth=max(x.bits for x in v.format.components),
color_range=v.codec_context.color_range, colorspace=v.codec_context.colorspace,
color_primaries=v.codec_context.color_primaries, color_trc=v.codec_context.color_trc,
audio_streams=len(c.streams.audio), sample_aspect_ratio=str(v.sample_aspect_ratio or Fraction(1)),
duration=float(v.duration*v.time_base) if v.duration else None)
frames, pts, durations, metrics = [], [], [], []
width = min(384, v.width); height = max(16, round(v.height * width / v.width))
for i, f in enumerate(c.decode(v)):
_check(cancel)
# swscale shrinks before transferring the ndarray.
gray = f.reformat(width=width, height=height, format='gray').to_ndarray()
metrics.append(measure_pair(frames[-1], gray) if frames else dict(diff=0.,brightness=0.,motion=0.,x=0.,y=0.,reliability=1.,cut=False))
frames.append(gray)
pts.append(int(f.pts) if f.pts is not None else round(i/fps/v.time_base))
durations.append(int(f.duration or round(1/fps/v.time_base)))
if progress and i % 12 == 0:
progress('Analisi movimento', .18 * min(1., (i+1)/max(1,v.frames or i+12)))
if not frames:
raise ValueError('Il video non contiene fotogrammi decodificabili.')
if any(b <= a for a,b in zip(pts,pts[1:])):
raise ValueError('I timestamp del video non sono crescenti.')
meta.update(frames=len(frames), pts=pts, durations=durations,
analysis_seconds=round(time.perf_counter()-start,3))
return meta, frames, metrics
def plan_repair(metrics, times, fps):
"""Infer held frames and isolated/periodic jumps, with fixed local endpoints."""
n = len(metrics)
positions = np.arange(n, dtype=float)
motion = np.array([x['motion'] for x in metrics])
cuts = {i for i,m in enumerate(metrics) if m['cut']}
ratios = np.ones(n)
eligible = np.zeros(n, dtype=bool)
for i in range(3,n-3):
if any(x in cuts for x in range(i-3,i+4)):
continue
nearby = np.r_[motion[i-3:i], motion[i+1:i+4]]
base = float(np.median(nearby))
if base < .045:
continue
ratios[i] = motion[i]/base
before = np.array([np.median([metrics[j][k] for j in range(i-3,i)]) for k in ('x','y')])
after = np.array([np.median([metrics[j][k] for j in range(i+1,i+4)]) for k in ('x','y')])
current = np.array([metrics[i]['x'],metrics[i]['y']])
cosine = lambda x,y: float(np.dot(x,y)/max(1e-8,np.linalg.norm(x)*np.linalg.norm(y)))
eligible[i] = (metrics[i]['reliability'] > .65 and cosine(before,after) > .9
and cosine(current,before+after) > .75
and .6 < np.median(motion[i-3:i])/max(.01,np.median(motion[i+1:i+4])) < 1.67
and metrics[i]['brightness'] < max(.8,metrics[i]['diff']*.65))
spikes = {i for i in range(n) if eligible[i] and 1.65 < ratios[i] < 3.1}
patterns = []
# Search the cadence; do not assume 24 frames, 24 fps, or phase zero.
eligible_indices=np.flatnonzero(eligible);spike_indices=np.array(sorted(spikes),dtype=int)
for period in range(2, min(121, n//3+1)):
counts=np.bincount(eligible_indices%period,minlength=period)
hits=np.bincount(spike_indices%period,minlength=period)
for phase in np.flatnonzero((hits>=3)&(hits/np.maximum(1,counts)>=.65)):
patterns.append(dict(period=period,phase=int(phase),support=int(hits[phase]),count=int(counts[phase])))
patterns.sort(key=lambda x:(x['support']/x['count'],x['support'],-x['period']),reverse=True)
pattern = patterns[0] if patterns else None
if pattern:
spikes.update(i for i in range(3,n-3) if eligible[i] and i%pattern['period']==pattern['phase'] and ratios[i]>1.22)
pattern['seconds'] = round(pattern['period']/float(fps),6)
duplicates = []
i = 2
while i < n-2:
rest = float(np.median(motion[max(1,i-3):i]))
if rest < .06 or metrics[i]['diff'] > .65 or motion[i] > rest*.16:
i += 1; continue
first = i
while i < n-1 and metrics[i]['diff'] < .65 and motion[i] < rest*.16:
i += 1
last = i-1
# Long pauses and the beginning/end of a shot remain intentional holds.
if (last-first < max(1,min(4,round(float(fps)*.15))) and i<n-1
and not any(j in cuts for j in range(first-1,i+2))
and motion[i] > rest*1.45 and metrics[i]['reliability']>.65):
duplicates.append((first,last))
spikes.discard(i)
groups = []
for i in sorted(spikes):
left, right = i-3, i+2
if groups and left <= groups[-1][1]:
groups[-1] = (groups[-1][0],max(right,groups[-1][1]))
else:
groups.append((left,right))
for left,right in groups:
durations = np.diff(times[left:right+1])
units = durations.copy()
for j in range(left+1,right+1):
if j in spikes:
units[j-left-1] *= min(2.5, max(1.22,ratios[j]))
physical = np.r_[0., np.cumsum(units)]
target = (times[left:right+1]-times[left])/(times[right]-times[left])*physical[-1]
positions[left:right+1] = np.interp(target,physical,np.arange(left,right+1))
for first,last in duplicates:
left,right = first-1,last+1
positions[first:last+1] = left+(times[first:last+1]-times[left])/(times[right]-times[left])*(right-left)
requests = {}
for i, pos in enumerate(positions):
run = next(((a,b) for a,b in duplicates if a<=i<=b),None)
if abs(pos-i) < .025 and run is None:
continue
left = int(math.floor(pos)); right = left+1; alpha = float(pos-left)
# Held runs must interpolate between the two distinct endpoint images.
if run:
left,right = run[0]-1,run[1]+1
alpha = float((times[i]-times[left])/(times[right]-times[left]))
if alpha < .025 or alpha > .975 or right in cuts:
continue
requests[i] = (left,right,alpha)
return requests, dict(jump_frames=sorted(spikes),held_ranges=[list(x) for x in duplicates],
cadence=pattern, cuts=sorted(cuts), repaired_frames=sorted(requests),
regions=[list(x) for x in groups],
jump_ratios={str(i):round(float(ratios[i]),3) for i in sorted(spikes)})
def plan_camera(metrics, times, fps, details, shape):
"""Small translation refinement only in reliably tracked, stuttering pans.
This is not general stabilization: clean shots, cuts, handheld movement,
zoom/rotation and large corrections are deliberately left alone.
"""
from scipy.signal import savgol_filter
n=len(metrics);actual=np.zeros((n,2));target=np.zeros((n,2));enabled=np.zeros(n,dtype=bool)
h,w=shape;limit=np.array([w,h])*.004
shots=list(zip([0,*details['cuts']],[*details['cuts'],n]))
accepted=[]
for first,end in shots:
count=end-first
events=[i for i in details['jump_frames'] if first<i<end]
if count<max(12,float(fps)*.6) or len(events)<2:continue
cameras=[m.get('camera') for m in metrics[first+1:end]]
if any(c is None for c in cameras):continue
reliable=[c['inliers']>=.55 and c['coverage']>=.3 and c['cells']>=6
and abs(c['scale']-1)<.003 and abs(c['angle'])<.15 for c in cameras]
if np.mean(reliable)<.95:continue
velocity=np.array([[c['x'],c['y']] for c in cameras])
axis=int(np.argmax(np.abs(np.median(velocity,axis=0))))
speed=velocity[:,axis];direction=np.sign(np.median(speed))
if np.median(np.abs(speed))<.08 or np.mean(speed*direction>=-.025)<.95:continue
path=np.vstack([np.zeros(2),np.cumsum(velocity,axis=0)])
grid=np.linspace(times[first],times[end-1],count)
uniform=np.stack([np.interp(grid,times[first:end],path[:,a]) for a in range(2)],axis=1)
window=min(count if count%2 else count-1,max(7,round(float(fps))//2*2+1))
smooth=savgol_filter(uniform,window,3,axis=0)
smooth=np.stack([np.interp(times[first:end],grid,smooth[:,a]) for a in range(2)],axis=1)
smooth-=smooth[0]
smooth+=((times[first:end]-times[first])/(times[end-1]-times[first]))[:,None]*(path[-1]-smooth[-1])
offset=smooth-path
# Reject the whole shot instead of clipping shifts and creating new jerks.
if np.any(np.max(np.abs(offset),axis=0)>limit):continue
actual[first:end]=path;target[first:end]=smooth;enabled[first:end]=True
accepted.append([first,end-1])
return actual,target,enabled,dict(shots=accepted,limit_fraction=.004)
def _matrix(meta):
# swscale's matrix IDs differ from AVColorSpace for SMPTE170M.
return {1:1,4:4,5:5,6:5,7:7,9:9,10:9}.get(meta['colorspace'],5)
class Interpolator:
def __init__(self, weights, device=None, meta=None):
import torch
from .dogma_rife_arch import IFNet
self.device = torch.device(device or ('cuda' if torch.cuda.is_available() else 'cpu'))
self.meta=meta
if self.device.type=='cuda':
try:
import comfy.model_management as management
# Release other Comfy models only when this render actually needs VRAM.
pixels=(meta['width']*meta['height']) if meta else 2073600
management.free_memory(max(2_500_000_000,pixels*1200),self.device)
except ImportError:pass
self.model = IFNet()
state = torch.load(weights,map_location='cpu',weights_only=True)
state = {k.removeprefix('module.'):v for k,v in state.items()}
state = {k:v for k,v in state.items() if not k.startswith(('teacher.','caltime.'))}
self.model.load_state_dict(state,strict=True)
self.model.eval().to(self.device)
self.cache = {}
def frame(self, first, second, alpha):
import torch
import torch.nn.functional as F
import av
h,w = first.height,first.width
def tensor(frame):
key = frame.pts
if key not in self.cache:
if self.meta:
rgb=frame.reformat(format='rgb48le',src_colorspace=_matrix(self.meta),src_color_range=self.meta['color_range'] or 1,dst_color_range=2)
a=rgb.to_ndarray().astype(np.float32)/65535.
else:a = frame.to_ndarray(format='rgb48le').astype(np.float32)/65535.
self.cache[key] = torch.from_numpy(a).permute(2,0,1).unsqueeze(0).to(self.device)
return self.cache[key]
a,b = tensor(first),tensor(second)
self.cache = {k:v for k,v in self.cache.items() if k in (first.pts,second.pts)}
x = F.pad(torch.cat((a,b),1),(0,(-w)%64,0,(-h)%64),mode='replicate')
with torch.inference_mode():
result = self.model(x,alpha,[16,8,4,2,1])[2][-1][0,:,:h,:w]
rgb=result.permute(1,2,0).cpu().numpy()
# CPU conversion avoids several seconds of first-use CUDA kernel compilation.
if not np.isfinite(rgb).all():
raise ValueError('RIFE ha prodotto un fotogramma non valido.')
rgb=np.rint(np.clip(rgb,0,1)*65535).astype(np.uint16)
return av.VideoFrame.from_ndarray(rgb,format='rgb48le')
def close(self):
from .dogma_rife_arch import backwarp_tenGrid
self.cache.clear();backwarp_tenGrid.clear()
self.model.to('cpu')
def _encoder(path, meta):
import av
depth = meta['bit_depth'] > 8
candidates = [('hevc_nvenc','p010le' if depth else 'yuv420p',dict(preset='p5',tune='hq',rc='vbr',cq='16',b='0',profile='main10' if depth else 'main')),
('libx265','yuv420p10le' if depth else 'yuv420p',dict(preset='fast',crf='14',**{'x265-params':'log-level=error:pools=4'}))]
errors = []
for codec,pixel,options in candidates:
container = None
try:
container = av.open(str(path),'w',format='mp4',options={'movflags':'+faststart'})
stream = container.add_stream(codec,rate=Fraction(meta['fps']))
stream.width=meta['width'];stream.height=meta['height'];stream.pix_fmt=pixel;stream.options=options
stream.time_base=Fraction(meta['time_base']);stream.codec_context.time_base=stream.time_base
stream.codec_context.codec_tag='hvc1'
stream.codec_context.sample_aspect_ratio=Fraction(meta['sample_aspect_ratio'])
for name in ('color_range','colorspace','color_primaries','color_trc'):
setattr(stream.codec_context,name,meta[name])
stream.codec_context.open()
return container,stream,codec
except Exception as exc:
errors.append(str(exc))
if container:
container.close()
raise RuntimeError('Codifica video non disponibile: '+'; '.join(errors))
def _translate_frame(frame, shift, meta):
"""Shift native YUV planes: avoid two full RGB conversions per camera frame."""
import av
import cv2
deep=meta['bit_depth']>8;pixel='yuv420p10le' if deep else 'yuv420p'
if frame.format.name=='rgb48le':
frame=frame.reformat(format=pixel,src_colorspace=_matrix(meta),dst_colorspace=_matrix(meta),src_color_range=2,dst_color_range=meta['color_range'] or 1)
else:frame=frame.reformat(format=pixel)
result=av.VideoFrame(frame.width,frame.height,pixel)
dtype=np.uint16 if deep else np.uint8;itemsize=2 if deep else 1
for source,destination in zip(frame.planes,result.planes):
a=np.ndarray((source.height,source.line_size//itemsize),dtype=dtype,buffer=source)[:,:source.width]
matrix=np.array([[1,0,shift[0]*source.width/frame.width],[0,1,shift[1]*source.height/frame.height]],dtype=np.float32)
moved=cv2.warpAffine(a,matrix,(source.width,source.height),flags=cv2.INTER_LANCZOS4,borderMode=cv2.BORDER_REFLECT_101)
if deep:np.minimum(moved,1023,out=moved)
target=np.ndarray((destination.height,destination.line_size//itemsize),dtype=dtype,buffer=destination)
target[:,:destination.width]=moved
for name in ('color_range','colorspace','color_primaries','color_trc'):setattr(result,name,meta[name])
return result
def _verify(source, output, meta):
import av
with av.open(str(output)) as c:
v=c.streams.video[0]
frames=list((f.pts*f.time_base) for f in c.decode(v))
expected=[p*Fraction(meta['time_base']) for p in meta['pts']]
tolerance=max(Fraction(meta['time_base']),v.time_base)
if len(frames)!=len(expected) or any(abs(a-b)>tolerance for a,b in zip(frames,expected)):
raise ValueError('La verifica dei fotogrammi o della sincronizzazione non è riuscita.')
if (v.width,v.height)!=(meta['width'],meta['height']):
raise ValueError('La risoluzione del file corretto è cambiata.')
if max(x.bits for x in v.format.components)<meta['bit_depth']:
raise ValueError('La profondità colore del file corretto è cambiata.')
for name in ('color_range','colorspace','color_primaries','color_trc'):
if meta[name]!=(0 if name=='color_range' else 2) and getattr(v.codec_context,name)!=meta[name]:
raise ValueError('I metadati colore del file corretto sono cambiati.')
if len(set(np.diff(meta['pts'])))==1 and v.average_rate!=Fraction(meta['fps']):
raise ValueError('Il framerate del file corretto è cambiato.')
if meta['duration'] is not None and v.duration and abs(float(v.duration*v.time_base)-meta['duration'])>float(tolerance)*2:
raise ValueError('La durata del file corretto è cambiata.')
if len(c.streams.audio)!=meta['audio_streams']:
raise ValueError('Una traccia audio è assente dal file corretto.')
def audio_signature(path):
signatures=[]
with av.open(str(path)) as c:
states={s.index:[hashlib.sha256(),[]] for s in c.streams.audio}
for pk in c.demux(list(c.streams.audio)) if c.streams.audio else []:
if not pk.size:continue
h,ts=states[pk.stream.index];h.update(bytes(pk));ts.append((str(pk.pts*pk.time_base) if pk.pts is not None else None,str(pk.duration*pk.time_base)))
signatures=[(h.hexdigest(),ts) for h,ts in states.values()]
return signatures
if audio_signature(source)!=audio_signature(output):
raise ValueError('La verifica audio non è riuscita: originale conservato.')
def repair_video(source, output, model_directory, cancel=None, progress=None, device=None):
"""Write a second file atomically. Failure never damages the original."""
import av
source,output=Path(source).resolve(),Path(output).resolve()
if source==output or output.exists():
raise ValueError('Il fix richiede un nuovo file, distinto dall’originale.')
start=time.perf_counter()
meta,thumbs,metrics=analyze(source,cancel,progress)
times=np.array(meta['pts'],dtype=float)*float(Fraction(meta['time_base']))
requests,details=plan_repair(metrics,times,Fraction(meta['fps']))
camera_actual,camera_target,camera_enabled,camera_details=plan_camera(metrics,times,Fraction(meta['fps']),details,thumbs[0].shape)
report=dict(version=2,engine='RIFE 4.26 + restrained camera refinement',**{k:meta[k] for k in ('frames','fps','width','height','bit_depth','duration','audio_streams','analysis_seconds')},**details,
camera_refinement=camera_details)
output.parent.mkdir(parents=True,exist_ok=True)
fd,temp=tempfile.mkstemp(prefix='.dogma-fix-',suffix='.mp4',dir=output.parent);os.close(fd);temp=Path(temp)
interpolator=None;out=None
try:
if not requests:
shutil.copyfile(source,temp)
report.update(status='unchanged',interpolated_frames=0,encoder='stream copy')
else:
weights=model_file(model_directory,cancel,progress)
if progress:progress('Attesa correzione video',.2)
# Bound GPU/RAM use when several API branches finish together.
while not _RENDER_LOCK.acquire(timeout=.1):_check(cancel)
try:
_check(cancel)
interpolator=Interpolator(weights,device,meta)
out,video_out,codec=_encoder(temp,meta)
report['encoder']=codec;report['device']=str(interpolator.device)
render_start=time.perf_counter();cache={};current=-1;corrected_thumbs=list(thumbs);shifted=[];largest_shift=np.zeros(2)
with av.open(str(source)) as incoming:
original_video=incoming.streams.video[0];original_video.thread_type='AUTO';original_video.thread_count=4
audio={s.index:out.add_stream_from_template(s) for s in incoming.streams.audio}
def decoded():
for packet in incoming.demux([original_video,*incoming.streams.audio]):
_check(cancel)
if packet.stream.index==original_video.index:
yield from packet.decode()
elif packet.size and packet.dts is not None:
packet.stream=audio[packet.stream.index];out.mux(packet)
frames=iter(decoded())
for i in range(meta['frames']):
_check(cancel)
left,right,alpha=requests.get(i,(i,i,0.))
while current<max(i,right):
current+=1;cache[current]=next(frames)
if i in requests:
frame=interpolator.frame(cache[left],cache[right],alpha)
else:frame=cache[i]
if camera_enabled[i]:
pose=camera_actual[i]
if i in requests:
small=frame.reformat(width=thumbs[i].shape[1],height=thumbs[i].shape[0],format='gray').to_ndarray()
measured=measure_pair(thumbs[left],small).get('camera')
if measured and measured['inliers']>=.55:
pose=camera_actual[left]+[measured['x'],measured['y']]
else:pose=camera_actual[left]*(1-alpha)+camera_actual[right]*alpha
shift=(camera_target[i]-pose)*[meta['width']/thumbs[i].shape[1],meta['height']/thumbs[i].shape[0]]
if np.max(np.abs(shift))>.04:
# At most a narrow edge strip is extended; no crop or zoom.
frame=_translate_frame(frame,shift,meta);shifted.append(i)
largest_shift=np.maximum(largest_shift,np.abs(shift))
if frame.format.name=='rgb48le':
frame=frame.reformat(format=video_out.pix_fmt,src_colorspace=_matrix(meta),dst_colorspace=_matrix(meta),src_color_range=2,dst_color_range=meta['color_range'] or 1)
for name in ('color_range','colorspace','color_primaries','color_trc'):setattr(frame,name,meta[name])
if i in requests or camera_enabled[i]:
corrected_thumbs[i]=frame.reformat(width=thumbs[i].shape[1],height=thumbs[i].shape[0],format='gray').to_ndarray()
frame=frame.reformat(format=video_out.pix_fmt)
frame.pts=meta['pts'][i];frame.time_base=Fraction(meta['time_base'])
for packet in video_out.encode(frame):out.mux(packet)
# Keep endpoints of a held run until its last replacement.
upcoming=[requests[j][0] for j in range(i+1,min(i+7,meta['frames'])) if j in requests]
keep=min([i+1,*upcoming])
cache={k:v for k,v in cache.items() if k>=keep}
if progress and i%4==0:progress('Correzione scatti',.2+.65*(i+1)/meta['frames'])
# Drain trailing audio packets after the final video frame.
for _ in frames:pass
for packet in video_out.encode():out.mux(packet)
out.close();out=None
report['render_seconds']=round(time.perf_counter()-render_start,3)
report['interpolated_frames']=len(requests)
report['camera_refinement'].update(adjusted_frames=len(shifted),max_shift_pixels=largest_shift.tolist(),edge_fill='reflect, narrow edge strip only')
report['status']='repaired'
# A motion-only acceptance gate prevents a worse cadence from being labelled fixed.
after=list(metrics)
affected=sorted({j for i in {*requests,*shifted} for j in (i,i+1) if 0<j<len(thumbs)})
for i in affected:after[i]=measure_pair(corrected_thumbs[i-1],corrected_thumbs[i])
def jitter(rows):
value=[]
for left,right in details['regions']+[(a-1,b+1) for a,b in details['held_ranges']]:
v=np.array([rows[j]['motion'] for j in range(left+1,right+1)])
if v.size>2:value.append(float(np.std(v)/max(.01,np.mean(v))))
return float(np.mean(value)) if value else None
report['motion_jitter_before']=jitter(metrics);report['motion_jitter_after']=jitter(after)
def camera_jerk(rows):
values=[]
for first,last in camera_details['shots']:
velocity=np.array([[r.get('camera',{}).get('x',r['x']),r.get('camera',{}).get('y',r['y'])] for r in rows[first+1:last+1]])
acceleration=np.linalg.norm(np.diff(velocity,axis=0),axis=1)
if acceleration.size:values.extend(acceleration.tolist())
return dict(rms=float(np.sqrt(np.mean(np.square(values)))),peak=float(max(values))) if values else None
report['camera_jerk_before']=camera_jerk(metrics);report['camera_jerk_after']=camera_jerk(after)
camera_worse=np.any(largest_shift>np.array([meta['width'],meta['height']])*.004) or (report['camera_jerk_before'] and (report['camera_jerk_after']['rms']>report['camera_jerk_before']['rms']*.9
or report['camera_jerk_after']['peak']>report['camera_jerk_before']['peak']))
if camera_worse or (report['motion_jitter_before'] is not None and report['motion_jitter_after']>report['motion_jitter_before']*.95):
shutil.copyfile(source,temp)
report.update(status='skipped_quality',interpolated_frames=0)
report['camera_refinement']['adjusted_frames']=0
finally:
if interpolator:interpolator.close()
_RENDER_LOCK.release()
_check(cancel)
if progress:progress('Verifica sincronizzazione',.9)
_verify(source,temp,meta)
_check(cancel)
temp.replace(output)
report['total_seconds']=round(time.perf_counter()-start,3)
if progress:progress('Correzione completata',1.)
return report
finally:
if out:out.close()
if temp.exists():temp.unlink()
+2 -2
View File
@@ -1,9 +1,9 @@
[project]
name = "comfyui-dogma-nodes"
description = "Custom ComfyUI nodes for DOGMA AI video workflows."
version = "1.0.56"
version = "1.0.57"
license = { file = "LICENSE" }
dependencies = ["scipy>=1.10"]
dependencies = ["scipy>=1.10", "av>=18.0", "opencv-python>=4.8"]
[project.urls]
Repository = "https://github.com/axior/ComfyUI-DOGMA-Nodes"
+2
View File
@@ -1 +1,3 @@
scipy>=1.10
av>=18.0
opencv-python>=4.8
+2 -2
View File
@@ -47,7 +47,7 @@ export function migrateState(raw){
s.dateMode ||= raw.schema===1?'manual':'today';if(s.dateMode==='today')s.date=todayCode();
s.workspace ||= '';s.library ||= [];s.results ||= [];s.references ||= [];s.filters ||= {models:[],project:'*',scene:'*',kind:'all',workspace:'*'};s.density ??= 45;s.workExpanded ??= false;
for(const m of Object.values(s.models||{})){m.parameters ||= m.variants?.[0]||{};delete m.variants;delete m.editVariant;delete m.seedMode;}
s.filters.hideErrors ??= false;
s.filters.hideErrors ??= false;s.videoRepair ??= false;
for(const [i,r] of s.references.entries()){r.kind ||= 'image';r.role ||= 'reference';const legacyMask=raw.schema===1&&i===0&&!!raw.maskEnabled;r.process ||= {enabled:legacyMask,mask:legacyMask,maskMode:'edit',invert:false,flip:false,crop:false,resizeMpx:false,megapixels:1,expand:0,blur:0,fillHoles:false,targetWidth:0,targetHeight:0,source:'paint',prompt:'',segment:0,background:'#ff00ff'};}
if(raw.schema<3)for(const r of [...s.references])if(r.kind==='image'&&r.modes?.includes('video')&&['first','last'].includes(r.role))s.references.push({...copy(r),role:'reference'});
for(const r of s.results)r.kind ||= 'image';
@@ -114,7 +114,7 @@ export function compileBatch(s,jobs,baseSeed){
}else if(f.key==='nano'){if(nanoBatch)inputs.images=nanoBatch;}
else{if(f.key==='gpt')inputs.n=1;images.forEach((x,j)=>inputs[`${f.key==='flux'?'':'model.'}images.image_${j+1}`]=x.link);}
const gen=String(10000+i*10),save=String(10001+i*10);
Object.assign(job,{seed,generator:gen,output:save,project:s.project||'',scene:s.scene||'',workspace:s.workspace||'',filename:titleParts(s).join('_'),imageEdit:s.mode==='image'&&s.imageEdit,baseReference:s.mode==='image'&&s.imageEdit&&images.length?copy(images[0].ref):null,prompt,parameters:copy(inputs)});
Object.assign(job,{seed,generator:gen,output:save,videoRepair:s.mode==='video'&&!!s.videoRepair,project:s.project||'',scene:s.scene||'',workspace:s.workspace||'',filename:titleParts(s).join('_'),imageEdit:s.mode==='image'&&s.imageEdit,baseReference:s.mode==='image'&&s.imageEdit&&images.length?copy(images[0].ref):null,prompt,parameters:copy(inputs)});
if(job.baseReference)delete job.baseReference.editorDraft;
output[gen]={class_type:type,inputs,_meta:{title:`${f.name} ${job.index+1}`}};
const metadata={...copy(job),session:s.session,prefix:prefix(s,f),date:s.dateMode==='today'?todayCode():s.date,appendDate:s.appendDate};delete metadata.images;delete metadata.parameters;
+2 -1
View File
@@ -109,5 +109,6 @@
"scene": "*",
"kind": "all",
"workspace": "*"
}
},
"videoRepair": false
}
+1
View File
@@ -12,6 +12,7 @@ export function icon(name){
grid:[['path',{d:'M2 4h5v6H2zM10 4h5v6h-5zM18 4h5v6h-5zM2 14h5v6H2zM10 14h5v6h-5zM18 14h5v6h-5z'}]],
compare:[['path',{d:'M1 6a1 1 0 0 1 1-1h20a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1Z M1.5 6v11a.5.5 0 0 0 .5.5h9V5.5H2a.5.5 0 0 0-.5.5Z M13.2 6.3v10.4h4.1c4 0 4.8-4.5 1.6-5.3 2.5-1.1 1.8-5.1-1.6-5.1Z M14.6 7.6h2.6c2.4 0 2.4 3.1 0 3.1h-2.6Z M14.6 12h2.8c2.7 0 2.7 3.4 0 3.4h-2.8Z M2.6 16.7 6.3 6.3h1.5l3.7 10.4H10l-1-3H5l-1 3Z M5.5 12.4h3L7 8Z',fill:'currentColor',stroke:'none','fill-rule':'evenodd'}]],
play:[['path',{d:'M7 3l15 9L7 21z',fill:'currentColor',stroke:'none'}]],
playCircle:[['circle',{cx:12,cy:12,r:10.5,fill:'none','stroke-width':.9}],['path',{d:'M9 7l8.5 5L9 17z',fill:'currentColor',stroke:'none'}]],
plus:[['path',{d:'M12 4v16M4 12h16'}]],
close:[['path',{d:'m6 6 12 12M18 6 6 18'}]],
folder:[['path',{d:'M2 6h8l2 3h10l-2 11H3zM2 6V4h8l2 2h8v3'}]],
+5 -2
View File
@@ -119,8 +119,8 @@
.dap-error-countdown:empty{display:none}
.dap-card-media{cursor:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='3' fill='white' stroke='black' stroke-width='1'/%3E%3C/svg%3E") 8 8,crosshair}
.dap-card-media video{object-fit:contain}
.dap-card-media>.dap-icon{color:var(--orange);width:38px;height:38px;filter:none}
.dap-card-media>.dap-icon path{fill:none;stroke:currentColor;stroke-width:1.4}
.dap-card-media>.dap-icon{color:#fff;opacity:.5;width:clamp(28px,6%,76px);height:auto;aspect-ratio:1;filter:none}
.dap-card-media>.dap-icon path{fill:currentColor;stroke:none}
.dap-card-media.playing>.dap-icon,.dap-card-media:hover>.dap-icon{opacity:0}
.dap-video-duration{position:absolute;bottom:10px;right:10px;font:11px 'Roboto Mono',monospace;color:#eee;line-height:1.4;background:#0009;padding:2px 5px;border-radius:3px}
.dap-card-tools .dap-ab{font:15px Arial,sans-serif;min-width:38px;color:#ccc;border-color:#555}
@@ -184,3 +184,6 @@
.dap-error-filter:hover{background:#181818;color:#ccc}
@media(pointer:coarse){.dap-toggle,.dap-model-head>.dap-toggle,.dap-field.has-toggle>.dap-toggle{height:44px;min-width:44px;width:44px;flex-basis:44px}.dap-model summary{min-height:44px}.dap-advanced summary{min-height:30px}}
@media(prefers-reduced-motion:reduce){.dap-toggle-knob{transition:none}}
.dap-video-repair{display:flex;align-items:center;flex-wrap:wrap;gap:4px;margin:-12px 0 24px;color:#aaa;font:13px Arial,sans-serif;cursor:pointer}
.dap-video-repair small{flex-basis:100%;margin-left:42px;color:#666;font:10px/1.6 Arial,sans-serif}
.dap-video-variant{position:absolute;top:12px;left:12px;padding:4px 7px;border-radius:4px;background:#000a;color:#ccc;font:10px Arial,sans-serif;pointer-events:none}
+7 -7
View File
@@ -1,18 +1,18 @@
import { app } from '../../scripts/app.js';
import { api } from '../../scripts/api.js';
import { PlatformUI } from './dogma_api_ui.js?v=1.0.56';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.56';
import { PlatformUI } from './dogma_api_ui.js?v=1.0.57';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.57';
const ROOT=new URL('.',import.meta.url);
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_api_platform.css?v=1.0.56',ROOT);document.head.append(css);
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_api_platform.css?v=1.0.57',ROOT);document.head.append(css);
let opened=null,queueLock=false;
const cachedSchemas=fetch(new URL('dogma_api_schemas.json?v=1.0.56',ROOT)).then(r=>r.json()).catch(()=>({}));
const cachedSchemas=fetch(new URL('dogma_api_schemas.json?v=1.0.57',ROOT)).then(r=>r.json()).catch(()=>({}));
class ComfyBridge {
constructor(node){this.node=node;this.preview=false;this.pricingNodes=new Map();}
get widget(){return this.node.widgets.find(w=>w.name==='config');}
load(){const s=JSON.parse(this.widget.value||'{}');if(!s.models)throw new Error('Apri DOGMA_API_PLATFORM_V4.json.');return migrateState(s);}
load(){const s=JSON.parse(this.widget.value||'{}');if(!s.models)throw new Error('Apri DOGMA_API_PLATFORM_V5.json.');return migrateState(s);}
async initialize(state){
const [defaults,catalog,cached]=await Promise.all([(await fetch(new URL('dogma_api_defaults.json?v=1.0.56',ROOT))).json(),this.request('/catalog'),cachedSchemas]);
const [defaults,catalog,cached]=await Promise.all([(await fetch(new URL('dogma_api_defaults.json?v=1.0.57',ROOT))).json(),this.request('/catalog'),cachedSchemas]);
for(const [key,value] of Object.entries(defaults.models))state.models[key] ||= copy(value);
this.catalog=catalog;this.defs=cached;
const live=await Promise.allSettled(Object.keys(cached).map(async type=>{const r=await api.fetchApi('/object_info/'+encodeURIComponent(type));if(!r.ok)throw new Error(type);const d=await r.json();return [type,d[type]];}));
@@ -78,7 +78,7 @@ class ComfyBridge {
try{await app.queuePrompt(0,1);if(!result?.prompt_id)throw new Error('Comfy non ha accettato il batch. Controlla accesso e messaggi di Comfy.');return result.prompt_id;}
finally{if(app.graphToPrompt===build)app.graphToPrompt=nativeBuild;if(api.queuePrompt===capture)api.queuePrompt=nativeQueue;queueLock=false;}
}
subscribe(handler){const controller=new AbortController();for(const name of ['execution_start','executing','executed','execution_success','execution_error','execution_interrupted','progress','progress_state'])api.addEventListener(name,e=>{let d=e.detail;if(name==='execution_start')this.activePrompt=d.prompt_id;if(name==='executing'&&(typeof d==='string'||d===null))d={node:d,prompt_id:this.activePrompt};handler(name,d);},{signal:controller.signal});return ()=>controller.abort();}
subscribe(handler){const controller=new AbortController();for(const name of ['execution_start','executing','executed','execution_success','execution_error','execution_interrupted','progress','progress_state','dogma_video_repair'])api.addEventListener(name,e=>{let d=e.detail;if(name==='execution_start')this.activePrompt=d.prompt_id;if(name==='executing'&&(typeof d==='string'||d===null))d={node:d,prompt_id:this.activePrompt};handler(name,d);},{signal:controller.signal});return ()=>controller.abort();}
async history(){const r=await api.fetchApi('/history?max_items=200');if(!r.ok)throw new Error('Cronologia non disponibile.');return r.json();}
async cancel(id){const r=await api.fetchApi('/jobs/'+encodeURIComponent(id)+'/cancel',{method:'POST'});if(r.ok)return r.json();if(r.status!==404)throw new Error('Interruzione non riuscita.');await api.fetchApi('/queue',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({delete:[id]})});const stopped=await api.fetchApi('/interrupt',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt_id:id})});if(!stopped.ok)throw new Error('Interruzione non riuscita.');}
download(state){this.save(state);const url=URL.createObjectURL(new Blob([JSON.stringify(app.graph.serialize(),null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='DOGMA_API_PLATFORM_SESSION.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
+2 -2
View File
@@ -1,5 +1,5 @@
import {copy} from './dogma_api_core.js?v=1.0.56';
import {openViewer,copyFullImage} from './dogma_api_viewer.js?v=1.0.56';
import {copy} from './dogma_api_core.js?v=1.0.57';
import {openViewer,copyFullImage} from './dogma_api_viewer.js?v=1.0.57';
export async function referenceEditor(ui,ref){
const make=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
+13 -9
View File
@@ -1,7 +1,7 @@
import {ALL_FAMILIES,copy,families,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName,orderResults,savedFilename,preparedMask} from './dogma_api_core.js?v=1.0.56';
import {icon} from './dogma_api_icons.js?v=1.0.56';
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.56';
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.56';
import {ALL_FAMILIES,copy,families,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName,orderResults,savedFilename,preparedMask} from './dogma_api_core.js?v=1.0.57';
import {icon} from './dogma_api_icons.js?v=1.0.57';
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.57';
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.57';
export const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
export const btn=(text,fn,cls='',aria=text)=>{const b=el('button',text,cls);b.type='button';b.onclick=fn;b.setAttribute('aria-label',aria);b.title=aria;return b;};
@@ -88,6 +88,7 @@ export class PlatformUI {
const choose=ib('folder','Scegli cartella di lavoro',()=>this.chooseWorkspace(),'dap-workspace-button');choose.append(el('span',s.workspace||'Scegli cartella di lavoro'));const folderRow=el('div','','dap-workspace-row'),explorer=btn('Esplora file',()=>this.openWorkspaceExplorer(),'dap-workspace-explorer','Apri in Esplora file');explorer.append(icon('external'));folderRow.append(choose,explorer);work.append(folderRow);
const models=el('section','','dap-section dap-models');models.append(el('div','MODELS','dap-label'));for(const f of families(s))models.append(this.model(f));
if(s.mode==='video'){const choice=el('section','','dap-video-choice');choice.append(el('div','WORKFLOW VIDEO','dap-label'));for(const [key,label] of [['reference','Ref → Video'],['frames','First / Last frame']]){const b=btn(label,()=>{s.models.seedance.engine=key;this.save();this.renderControls();this.refreshPrices();},key===s.models.seedance.engine?'active':'');choice.append(b);}c.append(choice);}
if(s.mode==='video'){const fix=el('label','','dap-video-repair');fix.append(this.toggle('Correggi scatti',s.videoRepair,v=>{s.videoRepair=v;this.save();},'span'),el('span','Correggi scatti'));fix.append(el('small','Salva anche una seconda copia · durata e fps originali'));c.append(fix);}
c.append(refs,prompt,workLabel,workSection,models);
}
filenamePreview(){return [...titleParts(this.state),'MODEL',this.state.mode==='video'?'00001.mp4':'00001.png'].filter(Boolean).join('_');}
@@ -169,7 +170,7 @@ export class PlatformUI {
const media=el('div','','dap-card-media');
if(job.kind==='video'){
const video=el('video');video.src=this.bridge.view(file);video.muted=true;video.preload='metadata';video.loop=true;video.playsInline=true;media.append(video);
const duration=el('span','','dap-video-duration');video.onloadedmetadata=()=>{duration.textContent=Number.isFinite(video.duration)?`${Math.floor(video.duration/60)}:${String(Math.floor(video.duration%60)).padStart(2,'0')}`:'';};media.append(icon('play'),duration);
const duration=el('span','','dap-video-duration');video.onloadedmetadata=()=>{duration.textContent=Number.isFinite(video.duration)?`${Math.floor(video.duration/60)}:${String(Math.floor(video.duration%60)).padStart(2,'0')}`:'';};media.append(icon('playCircle'),duration);
media.onpointerenter=()=>{video.play().then(()=>media.classList.add('playing')).catch(()=>{});};media.onpointerleave=()=>{video.pause();media.classList.remove('playing');};
}else{const base=job.imageEdit&&job.baseReference?(job.baseReference.comparePreview||this.bridge.view(job.baseReference.processedPreview||job.baseReference.file)):null;const comparison=hoverCompare(media,this.bridge.view(file),base);comparison.image.loading='lazy';comparison.image.decoding='async';comparison.image.alt=title;}
media.onclick=()=>openViewer(this,{job,file,index});media.tabIndex=0;media.setAttribute('role','button');media.setAttribute('aria-label','Apri '+title);media.onkeydown=e=>{if(e.key==='Enter')media.click();};card.append(media);
@@ -177,6 +178,7 @@ export class PlatformUI {
const select=btn('A\\B',()=>this.selectCompare(item),'dap-icon-button dap-ab','Scegli immagine o video per il confronto A/B');select.dataset.compare=item.id;
tools.append(select,ib('plus','Usa come reference',()=>this.reuse(file,job.kind)),ib('prompt','Leggi e copia prompt',()=>this.showPrompt(job)),ib('download','Scarica file',()=>this.downloadImage(file)));card.append(tools);
if(job.study)card.append(el('span','DESIGN REFERENCE','dap-study'));
if(file.variant){const variant=el('span',({original:'ORIGINALE',repaired:'SCATTI CORRETTI',checked:'VERIFICATO · INVARIATO'})[file.variant]||'','dap-video-variant');variant.title=job.repair?.status==='unchanged'?'Nessuno scatto rilevato: copia identica all’originale.':variant.textContent;card.append(variant);}
}else{
card.classList.add('pending');const logo=el('video','','dap-loading-logo');logo.src=this.bridge.loadingLogo();logo.muted=true;logo.loop=true;logo.autoplay=true;logo.playsInline=true;logo.setAttribute('aria-label','Generazione in corso');
const track=el('div','','dap-progress-track dap-card-progress');track.append(el('i'));const error=el('div','','dap-error-content');error.append(el('span','ERRORE'),el('p',job.error||''));card.append(logo,track,error);
@@ -191,7 +193,7 @@ export class PlatformUI {
this.updateProgress();let expired=false;
for(const job of this.allResults())for(const card of this.cards.get(job.id)||[]){
const p=this.jobProgress(job),bar=card.querySelector('.dap-card-progress>i');if(bar){bar.style.width=p.percent+'%';bar.parentElement.classList.toggle('indeterminate',!!p.indeterminate);bar.parentElement.title=p.label;}
const status=card.querySelector('.dap-job-state');if(status)status.textContent=({submitting:'Invio',queued:'In attesa',running:'Generazione API',failed:'Errore',cancelled:'Interrotta',missing:'Output assente'})[job.status]||job.status;
const status=card.querySelector('.dap-job-state');if(status)status.textContent=job.status==='repairing'?(job.repairStage||'Correzione scatti'):({submitting:'Invio',queued:'In attesa',running:'Generazione API',failed:'Errore',cancelled:'Interrotta',missing:'Output assente'})[job.status]||job.status;
card.classList.toggle('stopped',terminal.has(job.status));card.classList.toggle('failed',['failed','missing'].includes(job.status));
const elapsed=card.querySelector('.dap-elapsed'),seconds=job.started?Math.max(0,Math.floor(((job.finished||Date.now())-job.started)/1000)):null;elapsed.textContent=job.study?'LAYOUT':seconds!==null?seconds+'s'+(!terminal.has(job.status)&&p.expected?'/~'+Math.round(p.expected)+'s':''):'';
const error=card.querySelector('.dap-error-content p');if(error)error.textContent=job.error||'';
@@ -233,6 +235,7 @@ export class PlatformUI {
}
jobProgress(job){
if(terminal.has(job.status))return {percent:job.status==='completed'?100:job.stoppedProgress??Math.min(99,(job.progress||0)*100),label:job.status,remaining:0};
if(job.status==='repairing')return {percent:Math.min(99,90+9*(job.repairProgress||0)),label:job.repairStage||'Correzione scatti',remaining:null};
if(Number.isFinite(job.progress)&&job.progress>0)return {percent:Math.min(99,job.progress*100),label:Math.round(job.progress*100)+'% · avanzamento Comfy',remaining:job.progress<1?Math.max(0,Math.round((Date.now()-job.started)/1000*(1-job.progress)/job.progress)):0};
const samples=this.allResults().filter(j=>j.family===job.family&&j.status==='completed'&&j.finished>j.started&&!j.study).slice(0,8).map(j=>(j.finished-j.started)/1000);
if(!samples.length)return {percent:15,indeterminate:true,label:'Tempo trascorso · stima disponibile dopo le prime generazioni',remaining:null};
@@ -270,10 +273,11 @@ export class PlatformUI {
}catch(e){for(const j of jobs){if(!terminal.has(j.status)){j.stoppedProgress=this.jobProgress(j).percent;j.status='failed';j.error=e.message;j.finished=Date.now();j.errorVisibleUntil=Date.now()+5000;}}this.save();this.updateCards();this.note(e.message,true);}finally{this.busy=false;if(!this.closed)this.updateHeader();}
}
event(name,d){
if(name==='dogma_video_repair'){const job=this.state.results.find(j=>j.id===d?.job_id);if(job&&!terminal.has(job.status)){job.status='repairing';job.repairProgress=d.value;job.repairStage=d.stage;this.save();this.updateCards();}return;}
if(!d?.prompt_id)return;const jobs=this.state.results.filter(j=>j.promptId===d.prompt_id);if(!jobs.length){this.pendingEvents ||= [];if(this.busy&&this.pendingEvents.length<200)this.pendingEvents.push([name,d]);return;}
if(name==='progress_state'){for(const [id,n] of Object.entries(d.nodes||{})){const j=jobs.find(x=>x.generator===String(id));if(j&&!terminal.has(j.status)){if(n.state==='running')j.status='running';if(n.max>0&&n.value>0)j.progress=n.value/n.max;}}}
if(name==='progress'){const j=jobs.find(x=>x.generator===String(d.node));if(j&&d.max>0){j.progress=d.value/d.max;j.status='running';}}
if(name==='executing'&&d.node){const j=jobs.find(x=>x.generator===String(d.node));if(j)j.status='running';}
if(name==='progress_state'){for(const [id,n] of Object.entries(d.nodes||{})){const j=jobs.find(x=>x.generator===String(id));if(j&&!terminal.has(j.status)&&j.status!=='repairing'){if(n.state==='running')j.status='running';if(n.max>0&&n.value>0)j.progress=n.value/n.max;}}}
if(name==='progress'){const j=jobs.find(x=>x.generator===String(d.node));if(j&&d.max>0&&!terminal.has(j.status)&&j.status!=='repairing'){j.progress=d.value/d.max;j.status='running';}}
if(name==='executing'&&d.node){const j=jobs.find(x=>x.generator===String(d.node));if(j&&!terminal.has(j.status)&&j.status!=='repairing')j.status='running';}
if(name==='executed'){
const job=jobs.find(x=>x.output===String(d.node));if(job&&d.output?.images){const record=d.output.dogma_records?.[0];Object.assign(job,record||{images:d.output.images,status:'completed',finished:Date.now()});this.renderFilters();this.renderGallery();}
}
+2 -2
View File
@@ -1,5 +1,5 @@
import { icon } from './dogma_api_icons.js?v=1.0.56';
import {savedFilename} from './dogma_api_core.js?v=1.0.56';
import { icon } from './dogma_api_icons.js?v=1.0.57';
import {savedFilename} from './dogma_api_core.js?v=1.0.57';
export async function copyFullImage(url){
if(!navigator.clipboard?.write||!globalThis.ClipboardItem)throw new Error('La copia immagini richiede HTTPS o localhost. Puoi scaricare il file a piena risoluzione.');