Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6895201c8 | ||
|
|
c931fb843e | ||
|
|
59e2883afe | ||
|
|
42a976ae63 | ||
|
|
9d3241a272 |
@@ -0,0 +1,10 @@
|
||||
DOGMA Nodes 1.0.50
|
||||
|
||||
- One workflow and one node package for desktop/local and remote/cloud ComfyUI. No SimplePod-only fork, model sampling changes, model downloads or new runtime dependencies.
|
||||
- Fix the local-only 403 on restitch preview, detail, job polling and apply. The loaded H3 catalog supplies an ephemeral browser proof, sent only in a custom header. Require it with JSON for state changes, reject cross-site/opaque requests, do not trust forwarded headers for privileges, do not put the proof into URLs or saved workflows. The catalog response is non-cacheable. This complements existing Comfy/proxy authentication; it is not a new public-server authentication system.
|
||||
- Distinguish localhost desktop requests from public Host/proxy requests at runtime. Native Windows folder opening remains localhost-only. On remote or Linux servers the same Open saved folder button shows an internal browser rooted in the actual Comfy output directory with downloadable media files.
|
||||
- Preserve existing desktop folder selection including drives and paths outside Comfy output. Remote folder selection starts in the server output directory, remembers selections within it and allows subfolders. Remote copies are bounded to output and cannot navigate through symlinks outside it. Sessions and other non-media files are not listed in the media browser.
|
||||
- When importing desktop settings on a POSIX server, replace Windows output paths with the actual server output and let final-specific paths inherit it. Do not alter normal local paths or require a separate JSON. Existing sessions, saved videos and current workflow can continue after node update and page reload.
|
||||
- Missing mask dependency now names the Manager package MaskVidExperiments as well as MVEx_MaskToLatentSpace. Respect HTML hidden controls in action styles, including view-only folder panels.
|
||||
|
||||
Validation: local and proxy/remote tests against production route registration and actual 97-frame CPU restitch, including preview/poll/apply, final copy, output-boundary rejection, stale/missing proof, request origin checks and local Windows OS-call dispatch (mocked to avoid opening Explorer). The same frontend was exercised in an isolated browser with a rewritten internal Host and non-loopback client address, then in localhost mode: server folder selection and media listing, all seven restitch previews without 403, Windows path adaptation and retained local drives/folder navigation. No real SimplePod instance or live local installation was modified during verification. No new H3 sampling was required or run.
|
||||
@@ -0,0 +1,10 @@
|
||||
DOGMA Nodes 1.0.51
|
||||
|
||||
- Integrate HDR finishing into the existing comfyui-dogma-nodes Manager package. No separate node pack, installer, Torch/CUDA update or model download.
|
||||
- Add DOGMAHDRColorChunkedV1 for per-frame SDR-to-ACEScct conversion using the native Comfy colour transform and fp32 intermediates.
|
||||
- Add DOGMAHDRSaveStreamingV1: consume raw decoded ACEScct one frame at a time, restore source proportions in UHD, save ACEScg RGB HALF EXRs with ZIP16 and AP1/D60 chromaticities, and optionally write ProRes 4444 HLG with original PCM24 audio. Preserve original frame count and rational frame rate; omit only LTX temporal padding. Return paths rather than additional complete IMAGE batches. Unique output folders, completion manifest and atomic final MOV name.
|
||||
- Add DOGMAHDRCheckpointV1 before decode; its lazy recovery branch loads a saved latent without running the samplers again. Recovery requires the same source video and compatible VAE.
|
||||
- Preserve previous node IDs, modules, frontend and H3 workflows. HDR registration is optional on older Comfy versions: failure to import the new HDR module does not remove existing DOGMA nodes. HDR requires ComfyUI >=0.45.0; no new declared runtime dependency.
|
||||
- Updated HDR workflow keeps the existing BF16 model, HDR LoRA and scene embedding, fp32 VAE, tile settings and two-stage 8+3 sampling.
|
||||
|
||||
Validation: graph consistency, native colour equivalence, actual HALF EXR round-trip including negative/extended values, ACES metadata, actual ProRes HLG and PCM24 audio, exact rational timestamps, trim/padding, latent save/recovery, unique folders and output boundaries. The unchanged finishing function was additionally exercised on a synthetic shared-frame UHD 144-frame/6-second export, with 0.43 GiB additional peak process RAM. This measurement isolates finishing and is not a full LTX inference/decode or a SimplePod run. Live Comfy installations were not modified.
|
||||
@@ -0,0 +1,12 @@
|
||||
DOGMA Nodes 1.0.52
|
||||
|
||||
- Clear HDR V4 front panel: choose final resolution, input colour encoding, linear EXR master primaries, optional MOV transfer, seed and output prefix in one visible settings node.
|
||||
- Original resolution is a genuine single-stage native-resolution path: canvas follows source dimensions aligned to LTX's grid, final export restores the exact original dimensions. A lazy selector skips the latent upsampler, stage-2 guide/sampler and associated model branches. It does not run a 4K render then downscale the result.
|
||||
- Optional 4K retains the existing full-HD stage 1, latent x2 upscale, three-step stage 2 and UHD fitting/letterboxing.
|
||||
- Input choices distinguish SDR sRGB, Rec.709 gamma 2.4, linear Rec.709/ACEScg, ACEScct, Rec.709-primaries LogC3, BT.2020 HLG/PQ. Internal model encoding is always ACEScct and is no longer presented as an output colour selector.
|
||||
- EXR master: linear ACEScg AP1/D60 (default) or linear Rec.709 D65, always RGB HALF with matching chromaticities and ZIP16. MOV: BT.2020 HLG (default), BT.2020 PQ, or disabled; both movie transfers use ProRes 4444 with 10-bit 4:4:4 encoder input and original PCM24 audio.
|
||||
- Keep generation and delivery producers separate inside the visible settings group. Changing only EXR primaries, MOV transfer or output prefix reuses the model branch through Comfy's normal cache when available, rather than invalidating it through a combined settings object. The summary uses the actual delivery choices.
|
||||
- Existing 1.0.51 node IDs remain available. Their export helper retains the prior default resolution, colour, filenames and signature; new keyword-only colour/delivery controls are optional. No changes to H3 workflows, Torch/CUDA, model files, or declared runtime dependencies.
|
||||
- Same Manager package and JSON for Windows and Linux. No separate node pack or one-off installer. Automatic pre-decode checkpoint is retained inside the processing group; no manual resume path appears in the main panel.
|
||||
|
||||
Validation uses native Comfy schemas/loader, complete previous package registration, both lazy-resolution branches, graph endpoints and the backend canvas/guide wiring, original/4K geometry, actual HALF EXR colour/metadata and HLG/PQ MOV headers/timestamps/audio. Model inference on a remote pod is not part of the local verification.
|
||||
@@ -0,0 +1,10 @@
|
||||
# DOGMA Nodes 1.0.54 / API Platform V2
|
||||
|
||||
- Native asynchronous API branches in one batch: Quantity is parallel repeats with distinct seeds; no Variant control.
|
||||
- Native Seedance reference/edit/extend and first/last-frame video workflows.
|
||||
- Shared native Comfy account balance, credit formatting and node price expressions.
|
||||
- Exact geometry SVG icons, independent vertical scrolling and wrapping reference tiles.
|
||||
- Reference paint/crop/flip/invert/resize/grow/blur/hole filling and optional native SAM3 prompt masks.
|
||||
- Workspace selection, filename/date/project/scene, output sidecars and project library filters.
|
||||
- rgthree-style generated/original hover comparison, shared-transform pan/zoom viewer, click-outside close and reveal output in Explorer.
|
||||
- Preserve previous DOGMA IDs and original source graphs. No new Python dependencies.
|
||||
@@ -0,0 +1,3 @@
|
||||
# DOGMA 1.0.55 / API Platform V3
|
||||
|
||||
Immediate UI shell; one-node workflow; native model dropdowns and sorted resolutions; separate video reference and first/last modes; input-only image references; fixed nested reference preview URL; in-browser folder selection and reveal; server-enforced project/scene hierarchy; Stop; progress/estimated time; luminous trail; original A/B geometry; collapsible filename controls. Preset and Custom dimensions retain native behavior.
|
||||
@@ -147,3 +147,56 @@ comfy node install comfyui-dogma-nodes
|
||||
## Notes
|
||||
|
||||
The nodes use only PyTorch and ComfyUI's built-in sampler APIs. No extra Python dependencies are required.
|
||||
|
||||
|
||||
## HDR finishing (DOGMA Nodes 1.0.51)
|
||||
|
||||
The HDR master workflow uses the same DOGMA Nodes Manager package on Windows and Linux.
|
||||
`DOGMAHDRColorChunkedV1`, `DOGMAHDRCheckpointV1`, and `DOGMAHDRSaveStreamingV1`
|
||||
require ComfyUI 0.45.0 or later. Update the existing package; no separate HDR pack
|
||||
or installer is required. Existing H3 workflows and node identifiers are unchanged.
|
||||
|
||||
The master is a 3840x2160 ACEScg RGB HALF EXR sequence (ZIP lossless, AP1/D60).
|
||||
The optional MOV is ProRes 4444 HLG / BT.2020 with 10-bit 4:4:4 encoder input
|
||||
and original PCM24 audio; the EXR sequence is the 16-bit floating-point master.
|
||||
Finishing is sequential per frame, but native VAE decode still returns a complete batch.
|
||||
Output is under the actual Comfy output folder in `DOGMA_HDR_4K/master_XXXXX/`.
|
||||
|
||||
The checkpoint is saved before decode in `DOGMA_HDR_4K/checkpoints/`.
|
||||
To recover an interrupted export, keep the same source loaded and enter the saved
|
||||
`.latent` path (relative to Comfy output) in `resume_from`; leave it empty for a new generation.
|
||||
Do not use `--fp16-intermediates` for the HDR master path.
|
||||
|
||||
|
||||
## HDR controls (DOGMA Nodes 1.0.52 / workflow V4)
|
||||
|
||||
Choose everything in the main settings node: final resolution, source colour,
|
||||
EXR master colour, optional MOV transfer, seed, output directory/prefix.
|
||||
The model's internal ACEScct conversion is automatic and is separate from the
|
||||
linear ACEScg/Rec.709 EXR output and BT.2020 HLG/PQ MOV delivery.
|
||||
|
||||
Original resolution means native source canvas (aligned internally to LTX),
|
||||
single-stage eight-step HDR generation and exact original output dimensions.
|
||||
The latent upsampler and second stage are skipped through a lazy selector.
|
||||
4K retains the official eight-plus-three two-stage path and UHD final geometry.
|
||||
Source transfer must match the source's export; sRGB and Rec.709 gamma 2.4 are
|
||||
different choices. EXRs remain linear 16-bit float; selecting a MOV transfer
|
||||
does not change the EXR master or the model's working encoding.
|
||||
The single visible settings group contains independent generation and delivery
|
||||
producers. Delivery-only changes reuse the model branch while Comfy's relevant
|
||||
cache is available; this is not persistent recovery across server restarts.
|
||||
|
||||
|
||||
## API Platform V2 / 1.0.54
|
||||
|
||||
Open DOGMA_API_PLATFORM_V2.json and press APRI DOGMA / API PLATFORM.
|
||||
Quantity creates independent native asynchronous partner-node branches inside
|
||||
one prompt, with a distinct seed per request. Provider limits still apply.
|
||||
The original graphs are retained but inactive; use Run in the DOGMA panel.
|
||||
Includes image/video references, per-reference preparation, Seedance video,
|
||||
project library, workspace copies, Comfy credits/pricing and zoom comparison.
|
||||
Existing DOGMA and H3 workflows keep their identifiers.
|
||||
|
||||
|
||||
## API Platform V3 / 1.0.55
|
||||
Open DOGMA_API_PLATFORM_V3.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.
|
||||
|
||||
+49
@@ -194,3 +194,52 @@ try:
|
||||
del _H3_134, _H3_134_NAMES
|
||||
except Exception as _h3_134_error:
|
||||
print("[DOGMA H3 Director V2] Unavailable; existing nodes preserved:", _h3_134_error)
|
||||
|
||||
|
||||
# Optional HDR finishing. Older Comfy versions retain all previous DOGMA nodes.
|
||||
try:
|
||||
from .dogma_hdr_streaming import NODE_CLASS_MAPPINGS as _HDR151, NODE_DISPLAY_NAME_MAPPINGS as _HDR151_NAMES
|
||||
if set(_HDR151).intersection(NODE_CLASS_MAPPINGS):
|
||||
raise RuntimeError("DOGMA HDR: node ID collision")
|
||||
NODE_CLASS_MAPPINGS.update(_HDR151)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(_HDR151_NAMES)
|
||||
del _HDR151, _HDR151_NAMES
|
||||
except Exception as _hdr151_error:
|
||||
print("[DOGMA HDR] HDR nodes unavailable (requires ComfyUI >= 0.45.0); previous DOGMA nodes preserved:", _hdr151_error)
|
||||
|
||||
|
||||
# Explicit HDR source/master/delivery controls, additive to the 1.0.51 nodes.
|
||||
try:
|
||||
from .dogma_hdr_controls import NODE_CLASS_MAPPINGS as _HDR152, NODE_DISPLAY_NAME_MAPPINGS as _HDR152_NAMES
|
||||
if set(_HDR152).intersection(NODE_CLASS_MAPPINGS):
|
||||
raise RuntimeError("DOGMA HDR controls: node ID collision")
|
||||
NODE_CLASS_MAPPINGS.update(_HDR152)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(_HDR152_NAMES)
|
||||
del _HDR152, _HDR152_NAMES
|
||||
except Exception as _hdr152_error:
|
||||
print("[DOGMA HDR controls] Unavailable; existing DOGMA nodes preserved:", _hdr152_error)
|
||||
|
||||
|
||||
# API Platform: additive launcher; all existing node identifiers remain valid.
|
||||
try:
|
||||
from .dogma_api_platform import NODE_CLASS_MAPPINGS as _API153, NODE_DISPLAY_NAME_MAPPINGS as _API153_NAMES
|
||||
if set(_API153).intersection(NODE_CLASS_MAPPINGS):
|
||||
raise RuntimeError("DOGMA API Platform: node ID collision")
|
||||
NODE_CLASS_MAPPINGS.update(_API153)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(_API153_NAMES)
|
||||
del _API153, _API153_NAMES
|
||||
except Exception as _api153_error:
|
||||
print("[DOGMA API Platform] Launcher unavailable; previous DOGMA nodes preserved:", _api153_error)
|
||||
|
||||
|
||||
# API Platform V2: reference preparation, project library and native video output.
|
||||
try:
|
||||
from .dogma_api_platform_v2 import NODE_CLASS_MAPPINGS as _APIV2, NODE_DISPLAY_NAME_MAPPINGS as _APIV2_NAMES, register_routes as _APIV2_ROUTES
|
||||
if set(_APIV2).intersection(NODE_CLASS_MAPPINGS):
|
||||
raise RuntimeError("DOGMA API V2: node ID collision")
|
||||
_APIV2_ROUTES()
|
||||
NODE_CLASS_MAPPINGS.update(_APIV2)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(_APIV2_NAMES)
|
||||
del _APIV2, _APIV2_NAMES, _APIV2_ROUTES
|
||||
except Exception as _apiv2_error:
|
||||
print("[DOGMA API V2] Unavailable; previous DOGMA nodes preserved:", _apiv2_error)
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
"""DOGMA API Platform: additive, frontend-only launcher for native partner nodes."""
|
||||
|
||||
|
||||
class DOGMAAPIPlatformV1:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {"config": ("STRING", {"default": "{}", "multiline": True})}}
|
||||
|
||||
RETURN_TYPES = ()
|
||||
OUTPUT_NODE = True
|
||||
FUNCTION = "settings"
|
||||
CATEGORY = "DOGMA/API Platform"
|
||||
DESCRIPTION = "Open DOGMA API Platform. Generation uses the existing Comfy partner API nodes."
|
||||
|
||||
def settings(self, config):
|
||||
return {"ui": {"text": ["Apri DOGMA / API Platform e usa Run nel pannello."]}, "result": ()}
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"DOGMAAPIPlatformV1": DOGMAAPIPlatformV1}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"DOGMAAPIPlatformV1": "DOGMA / API Platform"}
|
||||
@@ -0,0 +1,374 @@
|
||||
"""Reference preparation, project output records and local workspace operations.
|
||||
|
||||
Generation remains in native partner API nodes, in independent async branches.
|
||||
"""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
_WORKSPACES = set()
|
||||
_FRONTEND_CACHE = {}
|
||||
|
||||
|
||||
def _output():
|
||||
import folder_paths
|
||||
return Path(folder_paths.get_output_directory()).resolve()
|
||||
|
||||
|
||||
def _library():
|
||||
path = _output() / 'DOGMA' / 'API' / '.library'
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _clean(value):
|
||||
return re.sub(r'[^\w.-]+', '_', str(value or '').strip(), flags=re.UNICODE).strip('.')[:100]
|
||||
|
||||
|
||||
def _record(metadata, files, kind):
|
||||
data = json.loads(metadata)
|
||||
identifier = str(data.get('id', ''))
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}', identifier):
|
||||
raise ValueError('Identificatore output non valido.')
|
||||
data.update(kind=kind, images=files, status='completed', finished=int(time.time()*1000))
|
||||
root = _output()
|
||||
exported = []
|
||||
warning = ''
|
||||
workspace = Path(data['workspace']).expanduser().resolve() if data.get('workspace') else None
|
||||
# Only a directory selected through this browser session may be outside output.
|
||||
if workspace and not (workspace.is_relative_to(root) or str(workspace) in _WORKSPACES):
|
||||
warning = 'Copia nella cartella di lavoro non eseguita: riseleziona la cartella. Il file è salvato in Comfy output.'
|
||||
workspace = None
|
||||
if workspace:
|
||||
try:
|
||||
target = workspace
|
||||
for field in ('project', 'scene'):
|
||||
if _clean(data.get(field)):target /= _clean(data[field])
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
for file in files:
|
||||
source = (root / file.get('subfolder', '') / file['filename']).resolve()
|
||||
if not source.is_relative_to(root):raise ValueError('Output non valido.')
|
||||
destination = target / source.name
|
||||
if destination != source:
|
||||
# Job IDs prevent a different project/run from replacing a file.
|
||||
if destination.exists():destination = target / (source.stem+'_'+identifier[:8]+source.suffix)
|
||||
shutil.copy2(source, destination)
|
||||
exported.append(str(destination))
|
||||
sidecar = target / (identifier+'.dogma.json')
|
||||
sidecar.write_text(json.dumps({**data, 'exported': exported, 'dogma_schema':3, 'workspace_relative':target.relative_to(workspace).as_posix()}, ensure_ascii=False, indent=2), encoding='utf8')
|
||||
except (OSError, ValueError) as exc:
|
||||
warning = 'File salvato in Comfy; copia nella cartella di lavoro non riuscita: '+str(exc)
|
||||
if not workspace:
|
||||
for file in files:
|
||||
target=root/file.get('subfolder','')
|
||||
(target/(identifier+'.dogma.json')).write_text(json.dumps({**data,'dogma_schema':3},ensure_ascii=False,indent=2),encoding='utf8')
|
||||
data['exported'] = exported
|
||||
if warning:data['warning'] = warning
|
||||
path = _library() / (identifier+'.json')
|
||||
temporary = path.with_suffix('.tmp')
|
||||
with _LOCK:
|
||||
temporary.write_text(json.dumps(data, ensure_ascii=False), encoding='utf8')
|
||||
temporary.replace(path)
|
||||
return data
|
||||
|
||||
|
||||
def _import_workspace(root):
|
||||
"""Portable sidecars travel with the output; no inference from filename tags."""
|
||||
root=Path(root).resolve();records=[];seen=set()
|
||||
from itertools import chain
|
||||
legacy=(p for directory in root.rglob('.library') if directory.is_dir() for p in directory.glob('*.json'))
|
||||
for path in chain(root.rglob('*.dogma.json'),legacy):
|
||||
if len(records)>=5000:break
|
||||
if not path.resolve().is_relative_to(root):continue
|
||||
try:
|
||||
data=json.loads(path.read_text('utf8'));identifier=str(data.get('id',''))
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}',identifier):continue
|
||||
if identifier in seen:continue
|
||||
files=[];exported=[]
|
||||
for index,original in enumerate(data.get('images',[])):
|
||||
copies=data.get('exported',[])
|
||||
name=Path(copies[index].replace('\\','/')).name if index<len(copies) else Path(original.get('filename','')).name
|
||||
if path.parent.name=='.library':
|
||||
subfolder=str(original.get('subfolder','')).replace('\\','/')
|
||||
relative=subfolder.removeprefix('DOGMA/API').lstrip('/')
|
||||
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'})
|
||||
exported.append(str(candidate))
|
||||
if not files:continue
|
||||
data.update(workspace=str(root),images=files,exported=exported,status='completed',imported=True)
|
||||
(_library()/(identifier+'.json')).write_text(json.dumps(data,ensure_ascii=False),encoding='utf8')
|
||||
records.append(data);seen.add(identifier)
|
||||
except (ValueError,OSError,KeyError,TypeError):continue
|
||||
return records
|
||||
|
||||
|
||||
def process_reference(image, mask, settings):
|
||||
"""Shared Pillow operation used by the node and by the no-generation preview."""
|
||||
import numpy as np
|
||||
from PIL import Image, ImageOps, ImageFilter, ImageColor
|
||||
from scipy import ndimage
|
||||
cfg = json.loads(settings) if isinstance(settings, str) else settings
|
||||
image = image.convert('RGB')
|
||||
mask = mask.convert('L').resize(image.size, Image.Resampling.NEAREST)
|
||||
if cfg.get('flip'):
|
||||
image = ImageOps.mirror(image);mask = ImageOps.mirror(mask)
|
||||
if cfg.get('resizeMpx'):
|
||||
megapixels = max(.01, min(64, float(cfg.get('megapixels', 1))))
|
||||
scale = (megapixels*1e6/(image.width*image.height))**.5
|
||||
size = (max(1, round(image.width*scale)), max(1, round(image.height*scale)))
|
||||
image = image.resize(size, Image.Resampling.LANCZOS);mask = mask.resize(size, Image.Resampling.NEAREST)
|
||||
if cfg.get('invert'):mask = ImageOps.invert(mask)
|
||||
if cfg.get('fillHoles'):
|
||||
arr = np.asarray(mask);filled = ndimage.binary_fill_holes(arr>127)
|
||||
mask = Image.fromarray(np.maximum(arr, filled.astype(np.uint8)*255))
|
||||
grow = max(-512, min(512, int(cfg.get('expand', 0))))
|
||||
if grow:
|
||||
array = np.asarray(mask)
|
||||
fun = ndimage.maximum_filter if grow>0 else ndimage.minimum_filter
|
||||
mask = Image.fromarray(fun(array, size=abs(grow)*2+1))
|
||||
blur = max(0, min(128, float(cfg.get('blur', 0))))
|
||||
if blur:mask = mask.filter(ImageFilter.GaussianBlur(blur))
|
||||
crop_box = None
|
||||
if cfg.get('crop'):
|
||||
rect = cfg.get('cropRect')
|
||||
if rect:
|
||||
x,y,w,h = [max(0,min(1,float(n))) for n in rect]
|
||||
if cfg.get('flip'):x=max(0,1-x-w)
|
||||
crop_box = (round(x*image.width),round(y*image.height),round(min(1,x+w)*image.width),round(min(1,y+h)*image.height))
|
||||
else:crop_box = mask.point(lambda v:255 if v>25 else 0).getbbox()
|
||||
if not crop_box or crop_box[2]<=crop_box[0] or crop_box[3]<=crop_box[1]:
|
||||
raise ValueError('Crop vuoto: seleziona un’area o dipingi una maschera.')
|
||||
if cfg.get('mask'):
|
||||
background = Image.new('RGB', image.size, ImageColor.getrgb(cfg.get('background') or '#00ff00'))
|
||||
image = Image.composite(background,image,mask) if cfg.get('maskMode')=='edit' else Image.composite(image,background,mask)
|
||||
if crop_box:image=image.crop(crop_box);mask=mask.crop(crop_box)
|
||||
width,height = int(cfg.get('targetWidth') or 0),int(cfg.get('targetHeight') or 0)
|
||||
if cfg.get('crop') and width>0 and height>0:
|
||||
if width>16384 or height>16384:raise ValueError('Dimensioni crop troppo grandi.')
|
||||
image=image.resize((width,height),Image.Resampling.LANCZOS);mask=mask.resize((width,height),Image.Resampling.NEAREST)
|
||||
return image,mask
|
||||
|
||||
|
||||
class DOGMAAPIReferenceV2:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {'required': {'image':('IMAGE',), 'mask':('MASK',), 'settings':('STRING',{'default':'{}'})}}
|
||||
RETURN_TYPES=('IMAGE',)
|
||||
FUNCTION='prepare'
|
||||
CATEGORY='DOGMA/API Platform'
|
||||
|
||||
def prepare(self,image,mask,settings):
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
results=[]
|
||||
for index in range(image.shape[0]):
|
||||
pil=Image.fromarray((image[index].detach().cpu().numpy().clip(0,1)*255).astype(np.uint8))
|
||||
alpha=Image.fromarray((mask[min(index,len(mask)-1)].detach().cpu().numpy().clip(0,1)*255).astype(np.uint8))
|
||||
processed,_=process_reference(pil,alpha,settings)
|
||||
results.append(torch.from_numpy(np.asarray(processed).copy()).float()/255)
|
||||
return (torch.stack(results),)
|
||||
|
||||
|
||||
def _save_prefix(data):
|
||||
basename=Path(str(data.get('prefix') or 'DOGMA').replace('\\','/')).name
|
||||
return '/'.join(['DOGMA','API',*[_clean(data.get(k)) for k in ('project','scene') if _clean(data.get(k))],basename])
|
||||
|
||||
|
||||
class DOGMAAPIImageOutputV2:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {'required':{'images':('IMAGE',),'metadata':('STRING',)},'hidden':{'prompt':'PROMPT','extra_pnginfo':'EXTRA_PNGINFO'}}
|
||||
RETURN_TYPES=()
|
||||
OUTPUT_NODE=True
|
||||
FUNCTION='save'
|
||||
CATEGORY='DOGMA/API Platform'
|
||||
|
||||
def save(self,images,metadata,prompt=None,extra_pnginfo=None):
|
||||
from nodes import SaveImage
|
||||
data=json.loads(metadata)
|
||||
# Same output and metadata behavior as the native SaveImage node.
|
||||
result=SaveImage().save_images(images,_save_prefix(data),prompt,extra_pnginfo)
|
||||
record=_record(metadata,result['ui']['images'],'image')
|
||||
return {'ui':{**result['ui'],'dogma_records':[record]},'result':()}
|
||||
|
||||
|
||||
class DOGMAAPIVideoOutputV2:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {'required':{'video':('VIDEO',),'metadata':('STRING',)},'hidden':{'prompt':'PROMPT','extra_pnginfo':'EXTRA_PNGINFO'}}
|
||||
RETURN_TYPES=()
|
||||
OUTPUT_NODE=True
|
||||
FUNCTION='save'
|
||||
CATEGORY='DOGMA/API Platform'
|
||||
|
||||
def save(self,video,metadata,prompt=None,extra_pnginfo=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'
|
||||
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)
|
||||
files=[{'filename':filename,'subfolder':subfolder,'type':'output','format':'video/mp4'}]
|
||||
record=_record(metadata,files,'video')
|
||||
return {'ui':{'images':files,'animated':(True,),'dogma_records':[record]},'result':()}
|
||||
|
||||
|
||||
def frontend_modules(web_root):
|
||||
"""Discover the installed frontend's own shared billing/pricing modules."""
|
||||
cache_key=str(web_root)
|
||||
if cache_key in _FRONTEND_CACHE:return _FRONTEND_CACHE[cache_key]
|
||||
assets=Path(web_root)/'assets';result={}
|
||||
for path in assets.glob('*.js'):
|
||||
if path.name.startswith('useBillingContext-'):
|
||||
text=path.read_text('utf8');exports=text[text.rfind('export{'):]
|
||||
match=re.search(r'useNodePricing as (\w+)',exports)
|
||||
shared=re.search(r'(\w+)=\w+\(useBillingContextInternal\)',text)
|
||||
alias=re.search(r'\b'+re.escape(shared[1])+r' as (\w+)',exports) if shared else None
|
||||
if match and alias:result['billing']={'file':path.name,'context':alias[1],'pricing':match[1]}
|
||||
elif path.name.startswith('creditsUtil-'):
|
||||
text=path.read_text('utf8');match=re.search(r'formatCreditsFromCents as (\w+)',text)
|
||||
if match:result['credits']={'file':path.name,'format':match[1]}
|
||||
_FRONTEND_CACHE[cache_key]=result
|
||||
return result
|
||||
|
||||
|
||||
def register_routes():
|
||||
from aiohttp import web
|
||||
from server import PromptServer
|
||||
from .dogma_h3_access import H3Access
|
||||
import folder_paths
|
||||
access=H3Access();routes=PromptServer.instance.routes
|
||||
|
||||
@routes.get('/dogma/api/v2/catalog')
|
||||
async def catalog(request):
|
||||
capabilities=access.catalog(request,_output())
|
||||
return web.json_response({'access':{**capabilities,'output_root':str(_output()/'DOGMA'/'API')},'frontend':frontend_modules(PromptServer.instance.web_root),'version':'1.0.55'})
|
||||
|
||||
@routes.post('/dogma/api/v2/workspace')
|
||||
async def workspace(request):
|
||||
access.browser(request);data=await request.json()
|
||||
try:
|
||||
path=access.output_path(request,data.get('path'),_output())
|
||||
if not path.is_dir():raise ValueError('Scegli una cartella esistente.')
|
||||
_WORKSPACES.add(str(path))
|
||||
records=await asyncio.to_thread(_import_workspace,path)
|
||||
return web.json_response({'path':str(path),'records':records})
|
||||
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.post('/dogma/api/v2/choose-folder')
|
||||
async def choose(request):
|
||||
access.browser(request)
|
||||
return web.json_response({'browse':True})
|
||||
|
||||
@routes.get('/dogma/api/v2/folders')
|
||||
async def folders(request):
|
||||
access.browser(request)
|
||||
try:
|
||||
path=access.output_path(request,request.query.get('path') or str(_library().parent),_output())
|
||||
if not path.is_dir():raise ValueError('Cartella inesistente.')
|
||||
local=access.is_local(request)
|
||||
def scan():
|
||||
dirs=[];files=[]
|
||||
for p in path.iterdir():
|
||||
if p.name.startswith('.'):continue
|
||||
try:
|
||||
if not local and not p.resolve().is_relative_to(_output()):continue
|
||||
if p.is_dir():dirs.append({'name':p.name,'path':str(p.resolve())})
|
||||
elif p.is_file():files.append({'name':p.name})
|
||||
except OSError:continue
|
||||
parent=str(path.parent) if path.parent!=path and (local or path.parent.is_relative_to(_output())) else None
|
||||
roots=[]
|
||||
if local and os.name=='nt':
|
||||
roots=[{'name':letter+':','path':letter+':/'} for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if Path(letter+':/').is_dir()]
|
||||
return {'path':str(path),'parent':parent,'roots':roots,'directories':sorted(dirs,key=lambda d:d['name'].lower()),'files':sorted(files,key=lambda d:d['name'].lower())[:5000]}
|
||||
return web.json_response(await asyncio.to_thread(scan))
|
||||
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.post('/dogma/api/v2/mkdir')
|
||||
async def mkdir(request):
|
||||
access.browser(request);data=await request.json()
|
||||
try:
|
||||
parent=access.output_path(request,data.get('path'),_output())
|
||||
name=str(data.get('name','')).strip()
|
||||
if not name or name in ('.','..') or re.search(r'[<>:"/\\|?*]',name) or name.endswith(('.', ' ')):raise ValueError('Nome cartella non valido.')
|
||||
target=parent/name
|
||||
if not parent.is_dir():raise ValueError('Cartella superiore inesistente.')
|
||||
target.mkdir(exist_ok=False)
|
||||
return web.json_response({'path':str(target.resolve())})
|
||||
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.get('/dogma/api/v2/workspace-media')
|
||||
async def workspace_media(request):
|
||||
access.fetch_site(request)
|
||||
try:
|
||||
root=access.output_path(request,request.query.get('workspace'),_output())
|
||||
if str(root) not in _WORKSPACES:raise ValueError('Riseleziona la cartella di lavoro.')
|
||||
relative=request.query.get('relative','');file=(root/relative).resolve()
|
||||
if not file.is_relative_to(root) or file.suffix.lower() not in ('.png','.jpg','.jpeg','.webp','.mp4','.webm','.mov'):raise ValueError('File non valido.')
|
||||
if not file.is_file():raise ValueError('File non disponibile.')
|
||||
return web.FileResponse(file)
|
||||
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.get('/dogma/api/v2/library')
|
||||
async def library(request):
|
||||
access.browser(request)
|
||||
def read():
|
||||
records=[]
|
||||
for path in sorted(_library().glob('*.json'),key=lambda p:p.stat().st_mtime,reverse=True)[:5000]:
|
||||
try:records.append(json.loads(path.read_text('utf8')))
|
||||
except (ValueError,OSError):continue
|
||||
return records
|
||||
return web.json_response({'records':await asyncio.to_thread(read)})
|
||||
|
||||
@routes.post('/dogma/api/v2/open-output')
|
||||
async def open_output(request):
|
||||
access.browser(request)
|
||||
data=await request.json();identifier=str(data.get('id',''))
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}',identifier):raise web.HTTPBadRequest(text='Output non valido.')
|
||||
try:
|
||||
record=json.loads((_library()/(identifier+'.json')).read_text('utf8'))
|
||||
index=max(0,int(data.get('index',0)));copies=record.get('exported',[])
|
||||
file=Path(copies[index]) if index<len(copies) else _output()/record['images'][index].get('subfolder','')/record['images'][index]['filename']
|
||||
if not file.is_file():raise ValueError('Il file è stato spostato o rimosso.')
|
||||
access.output_path(request,str(file.parent),_output())
|
||||
return web.json_response({'path':str(file.parent),'filename':file.name})
|
||||
except (ValueError,OSError,IndexError,KeyError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.post('/dogma/api/v2/reference-preview')
|
||||
async def preview(request):
|
||||
access.browser(request);data=await request.json()
|
||||
from PIL import Image,ImageOps
|
||||
def prepare():
|
||||
source=Path(folder_paths.get_annotated_filepath(data['file'])).resolve()
|
||||
if not source.is_relative_to(Path(folder_paths.get_input_directory()).resolve()):raise ValueError('Reference esterna a input.')
|
||||
rgba=ImageOps.exif_transpose(Image.open(source)).convert('RGBA');mask=ImageOps.invert(rgba.getchannel('A'))
|
||||
settings=data['settings']
|
||||
if settings.get('source')=='prompt' and settings.get('mask'):raise ValueError('La maschera da testo viene calcolata da SAM3 durante Run. Per l’anteprima usa una maschera dipinta.')
|
||||
if settings.get('maskFile'):
|
||||
mask_path=Path(folder_paths.get_annotated_filepath(settings['maskFile'])).resolve()
|
||||
if not mask_path.is_relative_to(Path(folder_paths.get_input_directory()).resolve()):raise ValueError('Maschera esterna a input.')
|
||||
mask=Image.open(mask_path).convert('L')
|
||||
result,_=process_reference(rgba,mask,settings)
|
||||
directory=Path(folder_paths.get_input_directory())/'DOGMA_API'/'previews';directory.mkdir(parents=True,exist_ok=True)
|
||||
filename='ref_'+uuid.uuid4().hex+'.png';result.save(directory/filename)
|
||||
return {'file':'DOGMA_API/previews/'+filename,'width':result.width,'height':result.height}
|
||||
try:return web.json_response(await asyncio.to_thread(prepare))
|
||||
except (ValueError,OSError,KeyError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS={'DOGMAAPIReferenceV2':DOGMAAPIReferenceV2,'DOGMAAPIImageOutputV2':DOGMAAPIImageOutputV2,'DOGMAAPIVideoOutputV2':DOGMAAPIVideoOutputV2}
|
||||
NODE_DISPLAY_NAME_MAPPINGS={'DOGMAAPIReferenceV2':'DOGMA / Reference preparation','DOGMAAPIImageOutputV2':'DOGMA / Image output','DOGMAAPIVideoOutputV2':'DOGMA / Video output'}
|
||||
@@ -13,9 +13,10 @@ def versioned_urls(urls, extension_dirs, web_directory):
|
||||
result = []
|
||||
for url in urls:
|
||||
parts = urlsplit(url)
|
||||
# This package has one entry module. Do not rewrite third-party URLs.
|
||||
if any(parts.path == prefix + "dogma_categories.js" for prefix in prefixes):
|
||||
digest = hashlib.sha256((root / "dogma_categories.js").read_bytes()).hexdigest()[:20]
|
||||
# Version only this package's own entry modules. Do not rewrite third-party URLs.
|
||||
entry = parts.path.rsplit("/", 1)[-1]
|
||||
if entry in ("dogma_categories.js", "dogma_api_platform.js") and any(parts.path == prefix + entry for prefix in prefixes):
|
||||
digest = hashlib.sha256((root / entry).read_bytes()).hexdigest()[:20]
|
||||
query = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True)
|
||||
if k != "dogma_build"]
|
||||
query.append(("dogma_build", digest))
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Browser request proof for H3 data operations; OS actions remain local-only.
|
||||
|
||||
The token complements the deployment's existing Comfy/proxy authentication.
|
||||
It is not a replacement for authentication on a publicly exposed Comfy server.
|
||||
Forwarded headers never grant access or widen the filesystem scope.
|
||||
"""
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
from aiohttp import web
|
||||
|
||||
class H3Access:
|
||||
def __init__(self):self.token=secrets.token_urlsafe(32)
|
||||
|
||||
@staticmethod
|
||||
def fetch_site(request):
|
||||
site=request.headers.get('Sec-Fetch-Site','').lower()
|
||||
if site and site not in ('same-origin','none'):
|
||||
raise web.HTTPForbidden(text='Richiesta da un altro sito non consentita.')
|
||||
origin=request.headers.get('Origin')
|
||||
if origin:
|
||||
try:valid=origin!='null' and urlsplit(origin).scheme in ('http','https') and bool(urlsplit(origin).netloc)
|
||||
except ValueError:valid=False
|
||||
if not valid:raise web.HTTPForbidden(text='Origine non valida.')
|
||||
|
||||
def is_local(self,request):
|
||||
if request.remote not in ('127.0.0.1','::1'):return False
|
||||
try:
|
||||
host=urlsplit('//'+request.host)
|
||||
if host.hostname not in ('127.0.0.1','::1','localhost'):return False
|
||||
origin=request.headers.get('Origin')
|
||||
if origin and urlsplit(origin).netloc.lower()!=host.netloc.lower():return False
|
||||
self.fetch_site(request)
|
||||
except (ValueError,web.HTTPForbidden):return False
|
||||
return True
|
||||
|
||||
def local(self,request):
|
||||
if not self.is_local(request):
|
||||
raise web.HTTPForbidden(text='Questa azione del sistema è disponibile solo da localhost sul computer Comfy.')
|
||||
|
||||
def browser(self,request):
|
||||
self.fetch_site(request)
|
||||
token=request.headers.get('X-Dogma-Access','')
|
||||
if not token or not secrets.compare_digest(token.encode('utf8'),self.token.encode('ascii')):
|
||||
raise web.HTTPForbidden(text='Accesso DOGMA scaduto o pannello precedente. Ricarica la pagina e riapri H3 Director.')
|
||||
if request.method=='POST' and request.content_type!='application/json':
|
||||
raise web.HTTPUnsupportedMediaType(text='Richiesta JSON necessaria.')
|
||||
|
||||
def catalog(self,request,output):
|
||||
self.fetch_site(request)
|
||||
import os
|
||||
return {'token':self.token,'local_files':self.is_local(request),
|
||||
'open_folder':self.is_local(request) and os.name=='nt',
|
||||
'output_directory':str(Path(output).resolve()),'platform':os.name}
|
||||
|
||||
def output_path(self,request,path,root):
|
||||
root=Path(root).expanduser().resolve()
|
||||
destination=Path(path).expanduser().resolve() if path else root
|
||||
if not self.is_local(request) and not destination.is_relative_to(root):
|
||||
raise ValueError('Da remoto scegli una cartella dentro l’output di Comfy: '+str(root))
|
||||
return destination
|
||||
+31
-19
@@ -612,17 +612,13 @@ def register_routes():
|
||||
from .dogma_h3_video_edit import register_edit_routes
|
||||
cleanup=register_edit_routes(routes,input_file)
|
||||
PromptServer.instance.app.on_cleanup.append(cleanup)
|
||||
def local_request(request):
|
||||
from urllib.parse import urlparse
|
||||
if request.remote not in ('127.0.0.1','::1'):
|
||||
raise web.HTTPForbidden(text='Disponibile solo sul computer Comfy.')
|
||||
origin=request.headers.get('Origin')
|
||||
if origin and urlparse(origin).netloc!=request.host:
|
||||
raise web.HTTPForbidden(text='Origine non valida.')
|
||||
from .dogma_h3_access import H3Access
|
||||
access=H3Access()
|
||||
local_request=access.local
|
||||
|
||||
import sys
|
||||
from .dogma_h3_restitch import register_routes as register_restitch
|
||||
PromptServer.instance.app.on_cleanup.append(register_restitch(routes,sys.modules[__name__],local_request))
|
||||
PromptServer.instance.app.on_cleanup.append(register_restitch(routes,sys.modules[__name__],access.browser))
|
||||
|
||||
@routes.post('/dogma/h3/v2/open-folder')
|
||||
async def open_folder(request):
|
||||
@@ -639,10 +635,12 @@ def register_routes():
|
||||
|
||||
@routes.post('/dogma/h3/v2/edit/export-copy')
|
||||
async def export_edit_copy(request):
|
||||
local_request(request)
|
||||
access.browser(request)
|
||||
import asyncio
|
||||
data=await request.json()
|
||||
try:return web.json_response(await asyncio.to_thread(export_saved_edit,data))
|
||||
try:
|
||||
data['output_dir']=str(access.output_path(request,data.get('output_dir','').strip(),folder_paths.get_output_directory()))
|
||||
return web.json_response(await asyncio.to_thread(export_saved_edit,data))
|
||||
except (ValueError,OSError,KeyError) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.post('/dogma/h3/v2/choose-folder')
|
||||
@@ -652,26 +650,39 @@ def register_routes():
|
||||
|
||||
@routes.get('/dogma/h3/v2/folders')
|
||||
async def folders(request):
|
||||
local_request(request)
|
||||
access.browser(request)
|
||||
import asyncio
|
||||
def browse():
|
||||
directory=Path(request.query.get('path') or folder_paths.get_output_directory()).expanduser().resolve()
|
||||
output=Path(folder_paths.get_output_directory()).resolve()
|
||||
local=access.is_local(request)
|
||||
directory=access.output_path(request,request.query.get('path'),output)
|
||||
if not directory.is_dir(): raise ValueError('Cartella inesistente. Inserisci un percorso valido.')
|
||||
directories=[]
|
||||
directories=[];files=[]
|
||||
media={'.mp4','.mov','.webm','.mkv','.png','.jpg','.jpeg','.webp','.gif','.wav','.mp3','.flac'}
|
||||
with os.scandir(directory) as entries:
|
||||
for entry in entries:
|
||||
try:
|
||||
if entry.is_dir(): directories.append({'name':entry.name,'path':entry.path})
|
||||
if entry.is_dir() and (local or Path(entry.path).resolve().is_relative_to(output)):
|
||||
directories.append({'name':entry.name,'path':entry.path})
|
||||
elif request.query.get('files')=='1' and entry.is_file() and Path(entry.name).suffix.lower() in media:
|
||||
resolved=Path(entry.path).resolve()
|
||||
if resolved.is_relative_to(output):
|
||||
rel=resolved.relative_to(output)
|
||||
files.append({'name':entry.name,'size':entry.stat().st_size,
|
||||
'video':{'filename':rel.name,'subfolder':rel.parent.as_posix(),'type':'output'}})
|
||||
except OSError: continue
|
||||
if len(directories)>500: break
|
||||
if len(directories)+len(files)>500: break
|
||||
directories.sort(key=lambda x:x['name'].casefold())
|
||||
files.sort(key=lambda x:x['name'].casefold())
|
||||
drives=[]
|
||||
if os.name=='nt':
|
||||
if local and os.name=='nt':
|
||||
import ctypes
|
||||
bits=ctypes.windll.kernel32.GetLogicalDrives()
|
||||
drives=[{'name':chr(65+i)+':','path':chr(65+i)+':/'} for i in range(26) if bits & (1<<i)]
|
||||
return {'path':str(directory),'parent':str(directory.parent) if directory.parent!=directory else None,
|
||||
'drives':drives,'directories':directories[:500],'truncated':len(directories)>500}
|
||||
parent=str(directory.parent) if directory.parent!=directory and (local or directory.parent.is_relative_to(output)) else None
|
||||
return {'path':str(directory),'parent':parent,'restricted':not local,
|
||||
'drives':drives,'directories':directories[:500],'files':files[:500],
|
||||
'truncated':len(directories)+len(files)>500}
|
||||
try: return web.json_response(await asyncio.to_thread(browse))
|
||||
except (ValueError,OSError) as exc: raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@@ -689,10 +700,11 @@ def register_routes():
|
||||
async def catalog(request):
|
||||
import asyncio,time
|
||||
nonlocal catalog_task,catalog_time
|
||||
capabilities=access.catalog(request,folder_paths.get_output_directory())
|
||||
if catalog_task is None or (catalog_task.done() and (catalog_task.exception() is not None or time.monotonic()-catalog_time>30)):
|
||||
catalog_time=time.monotonic()
|
||||
catalog_task=asyncio.create_task(asyncio.to_thread(build_catalog))
|
||||
return web.json_response(await asyncio.shield(catalog_task))
|
||||
return web.json_response({**await asyncio.shield(catalog_task),'access':capabilities},headers={'Cache-Control':'no-store'})
|
||||
|
||||
@routes.get('/dogma/h3/v2/session/{session}')
|
||||
async def session(request):
|
||||
|
||||
@@ -115,7 +115,7 @@ def apply_restitch(core,data):
|
||||
return current
|
||||
finally:temp.unlink(missing_ok=True)
|
||||
|
||||
def register_routes(routes,core,local_request):
|
||||
def register_routes(routes,core,authorize_request):
|
||||
from aiohttp import web
|
||||
jobs={};slot=asyncio.Semaphore(1)
|
||||
async def launch(kind,data):
|
||||
@@ -132,12 +132,12 @@ def register_routes(routes,core,local_request):
|
||||
except Exception as exc:job.update(status='error',message=str(exc))
|
||||
job['task']=asyncio.create_task(run());return web.json_response({'id':job['id']})
|
||||
@routes.post('/dogma/h3/v2/edit/restitch/preview')
|
||||
async def preview(request):local_request(request);return await launch('preview',await request.json())
|
||||
async def preview(request):authorize_request(request);return await launch('preview',await request.json())
|
||||
@routes.post('/dogma/h3/v2/edit/restitch/apply')
|
||||
async def apply(request):local_request(request);return await launch('apply',await request.json())
|
||||
async def apply(request):authorize_request(request);return await launch('apply',await request.json())
|
||||
@routes.get('/dogma/h3/v2/edit/restitch/job/{id}')
|
||||
async def status(request):
|
||||
local_request(request);job=jobs.get(request.match_info['id'])
|
||||
authorize_request(request);job=jobs.get(request.match_info['id'])
|
||||
if not job:raise web.HTTPNotFound(text='Lavorazione non disponibile.')
|
||||
return web.json_response({k:v for k,v in job.items() if k!='task'})
|
||||
async def cleanup(app):await asyncio.gather(*(j['task'] for j in jobs.values()),return_exceptions=True)
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
"""Clear HDR controls for the existing DOGMA Nodes package.
|
||||
|
||||
The source transfer, internal model working encoding, EXR primaries and MOV
|
||||
transfer are deliberately separate. The model always receives ACEScct.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from pathlib import Path
|
||||
import torch
|
||||
import folder_paths
|
||||
import comfy.utils
|
||||
import nodes
|
||||
from comfy.cli_args import args
|
||||
from comfy_api.latest import io, ui
|
||||
from .dogma_hdr_streaming import convert_frame, export_frames, require_fp32
|
||||
|
||||
CONFIG_TYPE = io.Custom("DOGMA_HDR_CONFIG")
|
||||
ORIGINAL = "Originale - senza upscale"
|
||||
UHD = "4K UHD - 3840 x 2160"
|
||||
RESOLUTIONS = [UHD, ORIGINAL]
|
||||
SOURCE_SPACES = {
|
||||
"SDR - sRGB": "sRGB",
|
||||
"SDR - Rec.709 gamma 2.4": "Rec709 gamma24",
|
||||
"HDR - Rec.2020 HLG": "HDR",
|
||||
"HDR - Rec.2020 PQ": "HDR PQ",
|
||||
"Lineare - ACEScg": "linear ACEScg",
|
||||
"Lineare - Rec.709": "linear",
|
||||
"Log - ACEScct": "HDR ACEScct",
|
||||
"Log - LogC3 con primarie Rec.709": "HDR LogC3",
|
||||
}
|
||||
EXR_SPACES = {"ACEScg lineare - 16 bit float": "linear ACEScg", "Rec.709 lineare - 16 bit float": "linear"}
|
||||
MOV_SPACES = {"HLG - Rec.2020 / ProRes 4444": "HDR", "PQ - Rec.2020 / ProRes 4444": "HDR PQ",
|
||||
"Disattivato - solo EXR": None}
|
||||
|
||||
|
||||
def checked_config(settings):
|
||||
if not isinstance(settings, dict) or settings.get("version") != 1:
|
||||
raise ValueError("Impostazioni HDR mancanti: collega il nodo DOGMA Impostazioni HDR.")
|
||||
for key, options in [("resolution", RESOLUTIONS), ("source", SOURCE_SPACES),
|
||||
("exr", EXR_SPACES), ("mov", MOV_SPACES)]:
|
||||
if settings.get(key) not in options:
|
||||
raise ValueError(f"Impostazione HDR non valida: {key}.")
|
||||
return settings
|
||||
|
||||
|
||||
class DOGMAHDRSettings(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(node_id="DOGMAHDRSettingsV1", display_name="DOGMA HDR | Impostazioni di generazione",
|
||||
category="DOGMA/HDR", description="Risoluzione, colore sorgente e seed. I controlli di export restano separati per riutilizzare la cache del modello.",
|
||||
inputs=[
|
||||
io.Combo.Input("resolution", display_name="Risoluzione finale", options=RESOLUTIONS, default=UHD,
|
||||
tooltip="Originale: generazione alle dimensioni del sorgente, senza upsampler e senza stadio 2. 4K: percorso 8+3 con upscale latente e consegna UHD."),
|
||||
io.Combo.Input("source", display_name="Colore del video sorgente", options=list(SOURCE_SPACES), default=next(iter(SOURCE_SPACES)),
|
||||
tooltip="Descrive i pixel in ingresso. Scegli in base all'export del sorgente; sRGB e Rec.709 gamma 2.4 hanno curve diverse. Non cambia il formato interno richiesto dalla LoRA."),
|
||||
io.Int.Input("seed", display_name="Seed", default=42, min=0, max=0xffffffffffffffff, control_after_generate=False),
|
||||
], outputs=[CONFIG_TYPE.Output("settings"), io.Int.Output("seed")])
|
||||
|
||||
@classmethod
|
||||
def execute(cls, resolution=UHD, source=next(iter(SOURCE_SPACES)), seed=42):
|
||||
settings=checked_config(dict(version=1,resolution=resolution,source=source,
|
||||
exr=next(iter(EXR_SPACES)),mov=next(iter(MOV_SPACES)),
|
||||
seed=int(seed),filename_prefix="DOGMA_HDR/master"))
|
||||
return io.NodeOutput(settings, int(seed))
|
||||
|
||||
|
||||
class DOGMAHDRDeliverySettings(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(node_id="DOGMAHDRDeliverySettingsV1",display_name="DOGMA HDR | Impostazioni di esportazione",
|
||||
category="DOGMA/HDR", inputs=[CONFIG_TYPE.Input("settings"),
|
||||
io.Combo.Input("exr", display_name="Colore del master EXR", options=list(EXR_SPACES), default=next(iter(EXR_SPACES)),
|
||||
tooltip="EXR sempre RGB 16 bit float, lineare. ACEScg AP1/D60 e il master consigliato per la pipeline ACES."),
|
||||
io.Combo.Input("mov", display_name="Video MOV aggiuntivo", options=list(MOV_SPACES), default=next(iter(MOV_SPACES)),
|
||||
tooltip="HLG o PQ in Rec.2020, oppure nessun MOV. Il MOV ProRes usa input encoder 10 bit; il master 16 bit resta l'EXR."),
|
||||
io.String.Input("filename_prefix", display_name="Cartella / prefisso output", default="DOGMA_HDR/master")],
|
||||
outputs=[CONFIG_TYPE.Output("settings")])
|
||||
|
||||
@classmethod
|
||||
def execute(cls,settings,exr=next(iter(EXR_SPACES)),mov=next(iter(MOV_SPACES)),filename_prefix="DOGMA_HDR/master"):
|
||||
value={**checked_config(settings),"exr":exr,"mov":mov,"filename_prefix":filename_prefix}
|
||||
return io.NodeOutput(checked_config(value))
|
||||
|
||||
|
||||
class DOGMAHDRPrepareSource(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(node_id="DOGMAHDRPrepareSourceV1", display_name="DOGMA HDR | Ingresso automatico ACEScct",
|
||||
category="DOGMA/HDR", inputs=[io.Image.Input("image"), CONFIG_TYPE.Input("settings")],
|
||||
outputs=[io.Image.Output()])
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, settings):
|
||||
source=SOURCE_SPACES[checked_config(settings)["source"]]
|
||||
require_fp32()
|
||||
if source == "HDR ACEScct":
|
||||
return io.NodeOutput(image.to(device="cpu",dtype=torch.float32))
|
||||
output=torch.empty(image.shape,device="cpu",dtype=torch.float32)
|
||||
progress=comfy.utils.ProgressBar(len(image))
|
||||
with torch.inference_mode():
|
||||
for i in range(len(image)):
|
||||
nodes.before_node_execution()
|
||||
frame=image[i:i+1]
|
||||
if source == "Rec709 gamma24":
|
||||
frame=frame.to(device="cpu",dtype=torch.float32).clamp_min(0).pow(2.4)
|
||||
value=convert_frame(frame,"linear","HDR ACEScct")
|
||||
else:
|
||||
value=convert_frame(frame,source,"HDR ACEScct")
|
||||
output[i:i+1].copy_(value)
|
||||
progress.update(1)
|
||||
return io.NodeOutput(output)
|
||||
|
||||
|
||||
def canvas_plan(width, height, planned_width, planned_height, settings):
|
||||
settings=checked_config(settings)
|
||||
upscale=settings["resolution"] == UHD
|
||||
if min(width,height,planned_width,planned_height) < 1:
|
||||
raise ValueError("Dimensioni sorgente/piano HDR non valide.")
|
||||
if upscale:
|
||||
canvas_width,canvas_height=planned_width,planned_height
|
||||
target_width,target_height=3840,2160
|
||||
description="Upscale 4K attivo - campionamento 8 + 3"
|
||||
else:
|
||||
canvas_width=max(32,32*math.floor(width/32+.5))
|
||||
canvas_height=max(32,32*math.floor(height/32+.5))
|
||||
target_width,target_height=width,height
|
||||
description="Originale - nessun upscale e nessuno stadio 2 - 8 passaggi"
|
||||
summary=(f"{description}\nSorgente: {width} x {height}\n"
|
||||
f"Canvas modello: {canvas_width} x {canvas_height}\nUscita: {target_width} x {target_height}\n"
|
||||
f"Sorgente colore: {settings['source']}\nInterno LTX: ACEScct (automatico)")
|
||||
return canvas_width,canvas_height,upscale,summary
|
||||
|
||||
|
||||
class DOGMAHDRCanvas(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(node_id="DOGMAHDRCanvasV1",display_name="DOGMA HDR | Piano risoluzione",
|
||||
category="DOGMA/HDR",inputs=[io.Image.Input("image"),
|
||||
io.Int.Input("planned_width",force_input=True),io.Int.Input("planned_height",force_input=True),
|
||||
CONFIG_TYPE.Input("settings")],
|
||||
outputs=[io.Int.Output("canvas_width"),io.Int.Output("canvas_height"),
|
||||
io.Boolean.Output("upscale"),io.String.Output("summary")])
|
||||
|
||||
@classmethod
|
||||
def execute(cls,image,planned_width,planned_height,settings):
|
||||
return io.NodeOutput(*canvas_plan(image.shape[2],image.shape[1],planned_width,planned_height,settings))
|
||||
|
||||
|
||||
class DOGMAHDRResolutionSelect(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(node_id="DOGMAHDRResolutionSelectV1",display_name="DOGMA HDR | Selezione risoluzione automatica",
|
||||
category="DOGMA/HDR",inputs=[CONFIG_TYPE.Input("settings"),
|
||||
io.Latent.Input("original",lazy=True),io.Latent.Input("upscaled",lazy=True)],
|
||||
outputs=[io.Latent.Output()])
|
||||
|
||||
@classmethod
|
||||
def check_lazy_status(cls, settings, original=None, upscaled=None):
|
||||
branch="upscaled" if checked_config(settings)["resolution"]==UHD else "original"
|
||||
return [branch] if (upscaled if branch=="upscaled" else original) is None else []
|
||||
|
||||
@classmethod
|
||||
def execute(cls, settings, original=None, upscaled=None):
|
||||
result=upscaled if checked_config(settings)["resolution"]==UHD else original
|
||||
if result is None:
|
||||
raise ValueError("Latente del ramo selezionato non disponibile.")
|
||||
return io.NodeOutput(result)
|
||||
|
||||
|
||||
class DOGMAHDRSaveConfigured(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(node_id="DOGMAHDRSaveConfiguredV1",display_name="DOGMA HDR | Salva master e video",
|
||||
category="DOGMA/HDR",is_output_node=True,
|
||||
inputs=[io.Image.Input("images"),CONFIG_TYPE.Input("settings"),
|
||||
io.Int.Input("source_width",force_input=True),io.Int.Input("source_height",force_input=True),
|
||||
io.Int.Input("source_frames",force_input=True),io.Float.Input("fps",force_input=True),
|
||||
io.Audio.Input("audio",optional=True)],hidden=[io.Hidden.prompt,io.Hidden.extra_pnginfo],
|
||||
outputs=[io.String.Output("exr_directory"),io.String.Output("mov_path")])
|
||||
|
||||
@classmethod
|
||||
def execute(cls,images,settings,source_width,source_height,source_frames,fps,audio=None):
|
||||
cfg=checked_config(settings)
|
||||
target=(3840,2160) if cfg["resolution"]==UHD else (source_width,source_height)
|
||||
transfer=MOV_SPACES[cfg["mov"]]
|
||||
metadata={"dogma_hdr_settings":cfg,"model_working_space":"ACEScct"}
|
||||
if not args.disable_metadata and cls.hidden is not None:
|
||||
if cls.hidden.extra_pnginfo:metadata.update(cls.hidden.extra_pnginfo)
|
||||
if cls.hidden.prompt:metadata["prompt"]=cls.hidden.prompt
|
||||
job,mov=export_frames(images,source_width,source_height,source_frames,fps,
|
||||
cfg["filename_prefix"],transfer is not None,audio,target_width=target[0],target_height=target[1],
|
||||
progress=comfy.utils.ProgressBar(source_frames),metadata=metadata,
|
||||
exr_color_space=EXR_SPACES[cfg["exr"]],mov_color_space=transfer or "HDR",
|
||||
mov_stem="DOGMA_HDR_PQ" if transfer=="HDR PQ" else "DOGMA_HDR_HLG")
|
||||
preview=None
|
||||
if mov:
|
||||
subfolder=str(job.relative_to(Path(folder_paths.get_output_directory()))).replace('\\','/')
|
||||
preview=ui.PreviewVideo([ui.SavedResult(mov.name,subfolder,io.FolderType.output)])
|
||||
return io.NodeOutput(str(job/'EXR'),str(mov) if mov else "",ui=preview)
|
||||
|
||||
|
||||
class DOGMAHDRSummary(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(node_id="DOGMAHDRSummaryV1",display_name="DOGMA HDR | Riepilogo scelte",
|
||||
category="DOGMA/HDR",inputs=[io.String.Input("generation_summary",force_input=True),CONFIG_TYPE.Input("settings")],
|
||||
outputs=[io.String.Output("summary")])
|
||||
|
||||
@classmethod
|
||||
def execute(cls,generation_summary,settings):
|
||||
cfg=checked_config(settings)
|
||||
return io.NodeOutput(f"{generation_summary}\nMaster EXR: {cfg['exr']}\nMOV: {cfg['mov']}")
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS={
|
||||
"DOGMAHDRSettingsV1":DOGMAHDRSettings,
|
||||
"DOGMAHDRPrepareSourceV1":DOGMAHDRPrepareSource,
|
||||
"DOGMAHDRCanvasV1":DOGMAHDRCanvas,
|
||||
"DOGMAHDRResolutionSelectV1":DOGMAHDRResolutionSelect,
|
||||
"DOGMAHDRSaveConfiguredV1":DOGMAHDRSaveConfigured,
|
||||
"DOGMAHDRDeliverySettingsV1":DOGMAHDRDeliverySettings,
|
||||
"DOGMAHDRSummaryV1":DOGMAHDRSummary,
|
||||
}
|
||||
NODE_DISPLAY_NAME_MAPPINGS={key:node.GET_SCHEMA().display_name for key,node in NODE_CLASS_MAPPINGS.items()}
|
||||
@@ -0,0 +1,328 @@
|
||||
"""DOGMA Nodes: bounded-working-memory HDR finishing for ComfyUI >= 0.45.0.
|
||||
|
||||
No models, dependencies, monkey patches, or changes to ComfyUI are installed.
|
||||
The native VAE still returns a complete batch; finishing consumes one frame
|
||||
at a time and returns file paths, never another complete IMAGE batch.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
from fractions import Fraction
|
||||
from pathlib import Path
|
||||
|
||||
import av
|
||||
import numpy as np
|
||||
import torch
|
||||
import safetensors.torch
|
||||
import folder_paths
|
||||
import nodes
|
||||
import comfy.utils
|
||||
from comfy.cli_args import args
|
||||
from comfy_api.latest import io, ui
|
||||
from comfy_api.latest._input_impl.video_types import (
|
||||
BT2020_NCL, set_video_color_properties,
|
||||
)
|
||||
from comfy_extras import nodes_images as ni
|
||||
|
||||
VERSION = "1.0.52"
|
||||
SPACES = ["sRGB", "HDR", "HDR ACEScct", "HDR LogC3", "HDR PQ", "linear", "linear ACEScg"]
|
||||
log = logging.getLogger("DOGMA.HDR")
|
||||
|
||||
|
||||
def require_fp32():
|
||||
if args.fp16_intermediates:
|
||||
raise ValueError("HDR 16-bit float: rimuovi --fp16-intermediates dall'avvio di Comfy. La conversione colore richiede intermedi fp32.")
|
||||
|
||||
|
||||
def convert_frame(frame, source, destination):
|
||||
require_fp32()
|
||||
return ni.ImageColorSpace.execute(
|
||||
frame.to(device="cpu", dtype=torch.float32), source, destination
|
||||
).result[0].to(device="cpu", dtype=torch.float32)
|
||||
|
||||
|
||||
class DogmaHDRColorChunked(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="DOGMAHDRColorChunkedV1", display_name="DOGMA HDR | Colore per fotogramma",
|
||||
category="DOGMA/HDR",
|
||||
description="Stessa trasformazione colore Comfy, con temporanei limitati a un fotogramma. Non riduce risoluzione o precisione.",
|
||||
inputs=[io.Image.Input("image"),
|
||||
io.Combo.Input("source", options=SPACES, default="sRGB"),
|
||||
io.Combo.Input("destination", options=SPACES, default="HDR ACEScct")],
|
||||
outputs=[io.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, source, destination):
|
||||
require_fp32()
|
||||
# Per-frame tone mapping would differ from the native batch transform.
|
||||
# This node is intentionally limited to the non-tone-mapping HDR path.
|
||||
if destination == "sRGB" or (source == "HDR PQ" and destination == "HDR"):
|
||||
raise ValueError("Questa conversione usa statistiche dell'intero batch: usa ImageColorSpace nativo per il tonemapping SDR/PQ-HLG.")
|
||||
if source == destination:
|
||||
return io.NodeOutput(image.to(device="cpu", dtype=torch.float32))
|
||||
output = torch.empty(image.shape, device="cpu", dtype=torch.float32)
|
||||
progress = comfy.utils.ProgressBar(len(image))
|
||||
with torch.inference_mode():
|
||||
for index in range(len(image)):
|
||||
nodes.before_node_execution()
|
||||
output[index:index + 1].copy_(convert_frame(image[index:index + 1], source, destination))
|
||||
progress.update(1)
|
||||
return io.NodeOutput(output)
|
||||
|
||||
|
||||
def fit_frame(frame, source_width, source_height, target_width, target_height):
|
||||
if (source_width, source_height) == (target_width, target_height):
|
||||
return nodes.ImageScale().upscale(frame, "bicubic", target_width, target_height, "disabled")[0]
|
||||
width = 2 * math.floor(min(target_width, target_height * source_width / source_height) / 2)
|
||||
height = 2 * math.floor(min(target_height, target_width * source_height / source_width) / 2)
|
||||
if min(width, height) < 2:
|
||||
raise ValueError("Proporzioni del sorgente non valide.")
|
||||
frame = nodes.ImageScale().upscale(frame, "bicubic", width, height, "disabled")[0]
|
||||
return ni.ResizeAndPadImage.execute(frame, target_width, target_height, "black", "area").result[0]
|
||||
|
||||
|
||||
def create_job(prefix, output_directory):
|
||||
# Comfy validates that the requested prefix remains inside its output root.
|
||||
directory, name, counter, _, _ = folder_paths.get_save_image_path(prefix, output_directory)
|
||||
while True:
|
||||
job = Path(directory) / f"{name}_{counter:05d}"
|
||||
try:
|
||||
job.mkdir()
|
||||
return job
|
||||
except FileExistsError:
|
||||
counter += 1
|
||||
|
||||
|
||||
def write_json(path, data):
|
||||
temporary = path.with_suffix(path.suffix + ".partial")
|
||||
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def encode_audio(container, audio, count, rate):
|
||||
if audio is None:
|
||||
return
|
||||
sample_rate = int(audio["sample_rate"])
|
||||
wave = audio["waveform"][0]
|
||||
layouts = {1: "mono", 2: "stereo", 3: "2.1", 4: "quad", 6: "5.1", 8: "7.1"}
|
||||
if wave.shape[0] not in layouts:
|
||||
raise ValueError(f"Audio: {wave.shape[0]} canali non supportati; nessun downmix automatico.")
|
||||
layout = layouts[wave.shape[0]]
|
||||
stream = container.add_stream("pcm_s24le", rate=sample_rate, layout=layout)
|
||||
n = min(wave.shape[-1], math.ceil(Fraction(sample_rate * count, 1) / rate))
|
||||
# Audio is also chunked, avoiding an extra full-length contiguous copy.
|
||||
for offset in range(0, n, 8192):
|
||||
part = wave[:, offset:min(n, offset + 8192)].float().cpu().contiguous().numpy()
|
||||
frame = av.AudioFrame.from_ndarray(part, format="fltp", layout=layout)
|
||||
frame.sample_rate = sample_rate
|
||||
frame.time_base = Fraction(1, sample_rate)
|
||||
frame.pts = offset
|
||||
container.mux(stream.encode(frame))
|
||||
container.mux(stream.encode(None))
|
||||
|
||||
|
||||
def export_frames(images, source_width, source_height, source_frames, fps,
|
||||
filename_prefix="DOGMA_HDR_4K/master", save_mov=True, audio=None,
|
||||
target_width=3840, target_height=2160, output_directory=None,
|
||||
progress=None, metadata=None, exr_color_space="linear ACEScg",
|
||||
mov_color_space="HDR", mov_stem=None):
|
||||
"""Sequential finishing; target size override is for isolated CPU QA only."""
|
||||
require_fp32()
|
||||
if images.ndim != 4 or images.shape[-1] != 3:
|
||||
raise ValueError("Atteso IMAGE RGB [fotogrammi, altezza, larghezza, 3] in ACEScct.")
|
||||
if source_width < 1 or source_height < 1 or source_frames < 1 or source_frames > len(images):
|
||||
raise ValueError(f"Conteggio/proporzioni non validi: richiesti {source_frames} frame, decode disponibile {len(images)}.")
|
||||
if not math.isfinite(float(fps)) or fps <= 0:
|
||||
raise ValueError("FPS sorgente non valido.")
|
||||
if exr_color_space not in ("linear ACEScg", "linear"):
|
||||
raise ValueError("Il master EXR richiede ACEScg lineare o Rec.709 lineare.")
|
||||
if mov_color_space not in ("HDR", "HDR PQ"):
|
||||
raise ValueError("Il MOV HDR richiede HLG o PQ.")
|
||||
mov_stem = mov_stem or "DOGMA_4K_HDR_HLG"
|
||||
if Path(mov_stem).name != mov_stem or any(c in mov_stem for c in ('/', '\\')):
|
||||
raise ValueError("Nome MOV non valido.")
|
||||
# Recover standard rational rates without rounding 24000/1001 to 23.976.
|
||||
rate = Fraction(float(fps)).limit_denominator(1000000)
|
||||
output_directory = output_directory or folder_paths.get_output_directory()
|
||||
job = create_job(filename_prefix, output_directory)
|
||||
exr_dir = job / "EXR"
|
||||
exr_dir.mkdir()
|
||||
mov_path = job / f"{mov_stem}.mov"
|
||||
mov_temporary = job / f"{mov_stem}.partial.mov"
|
||||
exr_label = "ACEScg AP1/D60" if exr_color_space == "linear ACEScg" else "Rec.709 D65"
|
||||
mov_label = "HLG" if mov_color_space == "HDR" else "PQ"
|
||||
manifest = dict(version=VERSION, status="incomplete", completed_frames=0,
|
||||
frames=source_frames, fps=str(rate), width=target_width, height=target_height,
|
||||
master=f"{exr_label} RGB HALF EXR ZIP16", source_width=source_width,
|
||||
source_height=source_height, decoded_frames=len(images),
|
||||
mov=f"ProRes 4444 BT.2020 {mov_label}; 10-bit encoding input; PCM24 original audio" if save_mov else None,
|
||||
metadata=metadata or {})
|
||||
write_json(job / "manifest.json", manifest)
|
||||
container = None
|
||||
try:
|
||||
if save_mov:
|
||||
container = av.open(str(mov_temporary), mode="w", format="mov", options={"movflags": "use_metadata_tags+faststart"})
|
||||
stream = container.add_stream("prores_ks", rate=rate)
|
||||
stream.width, stream.height = target_width, target_height
|
||||
stream.pix_fmt = "yuv444p10le"
|
||||
stream.options = {"profile": "4444", "alpha_bits": "16"}
|
||||
stream.codec_context.thread_count = 2
|
||||
stream.time_base = 1 / rate
|
||||
set_video_color_properties(stream.codec_context, mov_color_space)
|
||||
# Register audio before the muxer writes the MOV header.
|
||||
# The PCM stream is created below by encode_audio, before video encode.
|
||||
if audio is not None:
|
||||
encode_audio(container, audio, source_frames, rate)
|
||||
with torch.inference_mode():
|
||||
for index in range(source_frames):
|
||||
nodes.before_node_execution()
|
||||
linear = convert_frame(images[index:index + 1], "HDR ACEScct", "linear ACEScg")
|
||||
linear = fit_frame(linear, source_width, source_height, target_width, target_height)
|
||||
master = linear if exr_color_space == "linear ACEScg" else convert_frame(linear, "linear ACEScg", exr_color_space)
|
||||
if not torch.isfinite(master).all():
|
||||
raise ValueError(f"Frame {index}: valori HDR NaN/Inf. Il file non viene dichiarato completo.")
|
||||
# HALF cannot represent values outside +-65504. Do not silently clip.
|
||||
if master.abs().max() > 65504:
|
||||
raise ValueError(f"Frame {index}: range oltre HALF (+-65504). Serve EXR float32 per questi valori.")
|
||||
encoded = ni._encode_image(master[0], "exr", "16-bit float", exr_color_space)
|
||||
encoded = ni.inject_exr_metadata(encoded, None, None, exr_color_space)
|
||||
del master
|
||||
exr = exr_dir / f"frame_{index:06d}.exr"
|
||||
temporary = exr.with_suffix(".exr.partial")
|
||||
temporary.write_bytes(encoded)
|
||||
os.replace(temporary, exr)
|
||||
del encoded
|
||||
if container is not None:
|
||||
hlg = convert_frame(linear, "linear ACEScg", mov_color_space)[0]
|
||||
pixels = (hlg * 65535).clamp(0, 65535).numpy().astype(np.uint16)
|
||||
frame = av.VideoFrame.from_ndarray(pixels, format="rgb48le")
|
||||
frame = frame.reformat(format="yuv444p10le", dst_colorspace=BT2020_NCL)
|
||||
set_video_color_properties(frame, mov_color_space)
|
||||
frame.time_base = 1 / rate
|
||||
frame.pts = index
|
||||
container.mux(stream.encode(frame))
|
||||
del hlg, pixels, frame
|
||||
del linear
|
||||
manifest["completed_frames"] = index + 1
|
||||
if (index + 1) % 12 == 0 or index + 1 == source_frames:
|
||||
write_json(job / "manifest.json", manifest)
|
||||
log.info("HDR export: %d/%d frame; %s", index + 1, source_frames, job)
|
||||
if progress is not None:
|
||||
progress.update(1)
|
||||
if container is not None:
|
||||
container.mux(stream.encode(None))
|
||||
container.close()
|
||||
container = None
|
||||
os.replace(mov_temporary, mov_path)
|
||||
manifest["status"] = "complete"
|
||||
write_json(job / "manifest.json", manifest)
|
||||
except BaseException as error:
|
||||
manifest["error"] = str(error)
|
||||
write_json(job / "manifest.json", manifest)
|
||||
raise
|
||||
finally:
|
||||
if container is not None:
|
||||
container.close()
|
||||
return job, mov_path if save_mov else None
|
||||
|
||||
|
||||
class DogmaHDRSaveStreaming(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="DOGMAHDRSaveStreamingV1", display_name="DOGMA HDR | Salva 4K EXR16 + MOV progressivo",
|
||||
category="DOGMA/HDR", is_output_node=True,
|
||||
description="Converte ACEScct, ripristina proporzioni, elimina la sola coda temporale e salva un frame alla volta. Nessun secondo batch IMAGE completo.",
|
||||
inputs=[io.Image.Input("images"), io.Int.Input("source_width", force_input=True),
|
||||
io.Int.Input("source_height", force_input=True), io.Int.Input("source_frames", force_input=True),
|
||||
io.Float.Input("fps", force_input=True),
|
||||
io.String.Input("filename_prefix", default="DOGMA_HDR_4K/master"),
|
||||
io.Boolean.Input("save_mov", default=True), io.Audio.Input("audio", optional=True)],
|
||||
hidden=[io.Hidden.prompt, io.Hidden.extra_pnginfo],
|
||||
outputs=[io.String.Output("exr_directory"), io.String.Output("mov_path")],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, images, source_width, source_height, source_frames, fps,
|
||||
filename_prefix="DOGMA_HDR_4K/master", save_mov=True, audio=None):
|
||||
metadata = {}
|
||||
if not args.disable_metadata and cls.hidden is not None:
|
||||
if cls.hidden.extra_pnginfo:
|
||||
metadata.update(cls.hidden.extra_pnginfo)
|
||||
if cls.hidden.prompt:
|
||||
metadata["prompt"] = cls.hidden.prompt
|
||||
job, mov = export_frames(images, source_width, source_height, source_frames, fps,
|
||||
filename_prefix, save_mov, audio,
|
||||
progress=comfy.utils.ProgressBar(source_frames), metadata=metadata)
|
||||
preview = None
|
||||
if mov:
|
||||
subfolder = str(job.relative_to(Path(folder_paths.get_output_directory()))).replace("\\", "/")
|
||||
preview = ui.PreviewVideo([ui.SavedResult(mov.name, subfolder, io.FolderType.output)])
|
||||
return io.NodeOutput(str(job / "EXR"), str(mov) if mov else "", ui=preview)
|
||||
|
||||
|
||||
class DogmaHDRCheckpoint(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="DOGMAHDRCheckpointV1", display_name="DOGMA HDR | Checkpoint prima del decode",
|
||||
category="DOGMA/HDR",
|
||||
description="Salva il latente prima del decode. Per riprendere lo stesso video inserisci il percorso del checkpoint: i sampler vengono saltati.",
|
||||
inputs=[io.Latent.Input("samples", lazy=True),
|
||||
io.String.Input("filename_prefix", default="DOGMA_HDR_4K/checkpoints/HDR"),
|
||||
io.String.Input("resume_from", default="", tooltip="Lascia vuoto per una nuova generazione. Percorso .latent relativo a output, oppure assoluto dentro input/output Comfy.")],
|
||||
outputs=[io.Latent.Output(), io.String.Output("checkpoint_path")],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def check_lazy_status(cls, filename_prefix, resume_from, samples=None):
|
||||
return [] if resume_from.strip() or samples is not None else ["samples"]
|
||||
|
||||
@classmethod
|
||||
def execute(cls, filename_prefix, resume_from="", samples=None):
|
||||
if resume_from.strip():
|
||||
path = Path(resume_from.strip()).expanduser()
|
||||
if not path.is_absolute():
|
||||
path = Path(folder_paths.get_output_directory()) / path
|
||||
path = path.resolve()
|
||||
roots = [Path(folder_paths.get_output_directory()).resolve(), Path(folder_paths.get_input_directory()).resolve()]
|
||||
if not any(path.is_relative_to(root) for root in roots) or path.suffix != ".latent":
|
||||
raise ValueError("Il checkpoint deve essere un file .latent nella cartella input/output di Comfy.")
|
||||
saved = safetensors.torch.load_file(str(path), device="cpu")
|
||||
if "latent_format_version_0" not in saved or "latent_tensor" not in saved:
|
||||
raise ValueError("Checkpoint non compatibile: atteso formato latente Comfy attuale.")
|
||||
return io.NodeOutput({"samples": saved["latent_tensor"]}, str(path))
|
||||
if samples is None or "samples" not in samples:
|
||||
raise ValueError("Nessun latente ricevuto dal sampler.")
|
||||
directory, name, counter, _, _ = folder_paths.get_save_image_path(filename_prefix, folder_paths.get_output_directory())
|
||||
path = Path(directory) / f"{name}_{counter:05d}_.latent"
|
||||
temporary = path.with_suffix(".latent.partial")
|
||||
saved = {"latent_tensor": samples["samples"].detach().contiguous(),
|
||||
"latent_format_version_0": torch.tensor([])}
|
||||
comfy.utils.save_torch_file(saved, str(temporary), metadata={"dogma_hdr_streaming": VERSION})
|
||||
os.replace(temporary, path)
|
||||
log.info("Checkpoint HDR salvato prima del decode: %s", path)
|
||||
return io.NodeOutput(samples, str(path))
|
||||
|
||||
|
||||
# Registered through the existing DOGMA package, not a separate extension.
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"DOGMAHDRColorChunkedV1": DogmaHDRColorChunked,
|
||||
"DOGMAHDRSaveStreamingV1": DogmaHDRSaveStreaming,
|
||||
"DOGMAHDRCheckpointV1": DogmaHDRCheckpoint,
|
||||
}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"DOGMAHDRColorChunkedV1": "DOGMA HDR | Colore per fotogramma",
|
||||
"DOGMAHDRSaveStreamingV1": "DOGMA HDR | Salva 4K EXR16 + MOV progressivo",
|
||||
"DOGMAHDRCheckpointV1": "DOGMA HDR | Checkpoint prima del decode",
|
||||
}
|
||||
# Initialize V3 schema fields while retaining explicit, Registry-readable IDs.
|
||||
for _node in NODE_CLASS_MAPPINGS.values():
|
||||
_node.GET_SCHEMA()
|
||||
del _node
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "comfyui-dogma-nodes"
|
||||
description = "Custom ComfyUI nodes for DOGMA AI video workflows."
|
||||
version = "1.0.49"
|
||||
version = "1.0.55"
|
||||
license = { file = "LICENSE" }
|
||||
dependencies = ["scipy>=1.10"]
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
export const copy=x=>JSON.parse(JSON.stringify(x));
|
||||
export const FAMILIES=[
|
||||
{key:'nano',name:'Nanobanana',short:'NB',type:'GeminiImage2Node'},
|
||||
{key:'gpt',name:'GPT Image',short:'GPT',type:'OpenAIGPTImageNodeV2'},
|
||||
{key:'flux',name:'Flux 3',short:'F3',type:'Flux3ImageNode'},
|
||||
{key:'seedream',name:'Seedream',short:'SD',type:'ByteDanceSeedreamNodeV3'},
|
||||
];
|
||||
export const VIDEO_FAMILIES=[{key:'seedance',name:'Seedance',short:'V',type:'ByteDance2ReferenceNodeV2'}];
|
||||
export const ALL_FAMILIES=[...FAMILIES,...VIDEO_FAMILIES];
|
||||
export const families=s=>s.mode==='video'?VIDEO_FAMILIES:FAMILIES;
|
||||
export const safeName=s=>String(s||'').trim().replace(/[^\p{L}\p{N}_.-]+/gu,'_').replace(/^\.+/,'').slice(0,100);
|
||||
export function inputSpec(def,values,name){
|
||||
const parts=name.split('.');let inputs=def?.input;
|
||||
for(let i=0;i<parts.length;i++){
|
||||
const spec=inputs?.required?.[parts[i]]||inputs?.optional?.[parts[i]];if(!spec)return null;
|
||||
if(i===parts.length-1)return spec;
|
||||
if(spec[0]==='COMFY_DYNAMICCOMBO_V3'){const key=values[parts.slice(0,i+1).join('.')];inputs=spec[1].options.find(o=>o.key===key)?.inputs;}else return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
export function viewParameters(file){
|
||||
if(typeof file!=='string')return {filename:file.filename,subfolder:file.subfolder||'',type:file.type||'output'};
|
||||
const parts=file.replaceAll('\\','/').split('/');return {filename:parts.pop(),subfolder:parts.join('/'),type:'input'};
|
||||
}
|
||||
export function choicesFor(spec){if(!spec)return null;if(Array.isArray(spec[0]))return spec[0];if(spec[0]==='COMBO')return spec[1].options;if(spec[0]==='COMFY_DYNAMICCOMBO_V3')return spec[1].options.map(o=>o.key);return null;}
|
||||
export function parameterSpecs(def,values){
|
||||
const result={};const walk=(inputs,prefix='')=>{for(const [key,spec] of Object.entries({...inputs?.required,...inputs?.optional})){
|
||||
const name=prefix+key;const choices=choicesFor(spec);
|
||||
if(choices||['INT','FLOAT','BOOLEAN','STRING'].includes(spec[0]))result[name]=spec;
|
||||
if(spec[0]==='COMFY_DYNAMICCOMBO_V3')walk(spec[1].options.find(o=>o.key===values[name])?.inputs,name+'.');
|
||||
}};walk(def?.input);return result;
|
||||
}
|
||||
export function modelValues(def,values){
|
||||
const specs=parameterSpecs(def,values),next={};for(const [key,spec] of Object.entries(specs)){
|
||||
const choices=choicesFor(spec),value=values[key];next[key]=value!==undefined&&(!choices||choices.includes(value))?value:spec[1]?.default??choices?.[0]??(spec[0]==='BOOLEAN'?false:spec[0]==='STRING'?'':0);
|
||||
}return next;
|
||||
}
|
||||
export function sortedChoices(key,values){
|
||||
const list=[...new Set(values.map(String))];if(!/resolution|size_preset|size$/.test(key))return list;
|
||||
const score=v=>{if(key==='model.size_preset'){const tier=v.match(/([\d.]+)K/i);return tier?+tier[1]:Infinity;}const dims=v.match(/(\d+)x(\d+)/);if(dims)return +dims[1]*+dims[2];const k=v.match(/([\d.]+)\s*[kK]/);if(k)return +k[1]*1000;const p=v.match(/(\d+)p/i);if(p)return +p[1];return Infinity;};return list.sort((a,b)=>score(a)-score(b));
|
||||
}
|
||||
export function todayCode(){const parts=new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/Rome',day:'2-digit',month:'2-digit',year:'2-digit'}).formatToParts(new Date());return ['day','month','year'].map(k=>parts.find(p=>p.type===k).value).join('');}
|
||||
export function titleParts(s){return [s.project,s.scene,s.filename||'DOGMA',s.appendDate?(s.dateMode==='today'?todayCode():s.date||todayCode()):''].map(safeName).filter(Boolean);}
|
||||
export function prefix(s,f){return ['DOGMA/API',safeName(s.project),safeName(s.scene),titleParts(s).join('_')+'_'+f.short].filter(Boolean).join('/');}
|
||||
export function migrateState(raw){
|
||||
const s=copy(raw);s.schema=3;s.session ||= crypto.randomUUID();s.prompts ||= {image:s.prompt||'',video:''};s.mode ||= 'image';s.imageEdit ??= true;s.appendDate ??= false;s.date ||= todayCode();
|
||||
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;}
|
||||
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:legacyMask?'edit':'isolate',invert:false,flip:false,crop:false,resizeMpx:false,megapixels:1,expand:0,blur:0,fillHoles:true,targetWidth:0,targetHeight:0,source:'paint',prompt:'',segment:0,background:legacyMask?'#ff00ff':'#00ff00'};}
|
||||
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';
|
||||
return s;
|
||||
}
|
||||
export function plannedJobs(s){return families(s).flatMap(f=>{const m=s.models[f.key];if(!m?.enabled)return[];const n=Number(m.quantity);if(!Number.isInteger(n)||n<1||n>64)throw new Error('Quantity deve essere da 1 a 64.');return Array.from({length:n},(_,i)=>({family:f.key,index:i,kind:s.mode==='video'?'video':'image'}));});}
|
||||
export function visibleReferences(s){return s.references.filter(r=>(!r.modes||r.modes.includes(s.mode))&&(s.mode==='video'?(s.models.seedance?.engine==='frames'?r.kind==='image'&&['first','last'].includes(r.role):r.role!=='first'&&r.role!=='last'):r.kind!=='video'));}
|
||||
export function activeReferences(s){return visibleReferences(s).filter(r=>r.enabled);}
|
||||
export function validateState(s){
|
||||
if(!s.prompts[s.mode]?.trim())throw new Error('Scrivi un prompt.');
|
||||
if(!plannedJobs(s).length)throw new Error('Attiva almeno un modello.');
|
||||
const refs=activeReferences(s),imgs=refs.filter(r=>r.kind==='image'),videos=refs.filter(r=>r.kind==='video');
|
||||
if(refs.some(r=>!r.file))throw new Error('Ricarica le reference mancanti.');
|
||||
if(s.mode==='image'){
|
||||
if(s.imageEdit&&!imgs.length)throw new Error('Image Edit richiede Image 1.');
|
||||
const limits={nano:14,gpt:16,flux:10,seedream:10},max=Math.min(...FAMILIES.filter(f=>s.models[f.key]?.enabled).map(f=>limits[f.key]));if(imgs.length>max)throw new Error(`I modelli attivi supportano fino a ${max} reference.`);
|
||||
}else {
|
||||
const m=s.models.seedance;
|
||||
if(m.engine==='frames'&&imgs.length>2)throw new Error('Usa al massimo un First frame e un Last frame.');
|
||||
if(m.engine==='frames'&&['first','last'].some(role=>imgs.filter(r=>r.role===role).length>1))throw new Error('Assegna un solo First frame e un solo Last frame.');
|
||||
if(m.engine==='frames'&&!imgs.length)throw new Error('Aggiungi almeno un frame immagine.');
|
||||
if(m.engine!=='frames'&&!refs.length)throw new Error('Aggiungi una reference immagine o video.');
|
||||
const p=m.engine==='frames'?m.frames:m.parameters;
|
||||
if(m.engine!=='frames'&&['edit','extend'].includes(p['model.task_type'])&&!videos.length)throw new Error('Video Edit ed Extend richiedono un video sorgente.');
|
||||
if(imgs.length>30||videos.length>10)throw new Error('Troppe reference per Seedance 2.5.');
|
||||
}
|
||||
for(const f of families(s)){
|
||||
const m=s.models[f.key];if(!m.enabled)continue;const p=m.engine==='frames'?m.frames:m.parameters;
|
||||
for(const [k,v] of Object.entries(p))if(/(?:width|height)$/.test(k)){
|
||||
const n=Number(v),min=f.key==='gpt'?480:240,max=f.key==='gpt'?3840:8594,step=f.key==='gpt'?16:2;
|
||||
if(!Number.isInteger(n)||n<min||n>max||n%step)throw new Error(`${f.name}: dimensioni da ${min} a ${max}, multiple di ${step}.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
export function compileBatch(s,jobs,baseSeed){
|
||||
validateState(s);const output={},refs=activeReferences(s),images=[],videos=[];
|
||||
refs.forEach((ref,i)=>{
|
||||
const id=String(9000+i*10);output[id]={class_type:ref.kind==='video'?'LoadVideo':'LoadImage',inputs:{[ref.kind==='video'?'file':'image']:ref.file}};
|
||||
if(ref.kind==='video'){videos.push({ref,link:[id,0]});return;}
|
||||
let link=[id,0];const p=ref.process;
|
||||
if(p?.enabled){
|
||||
let mask=[id,1];
|
||||
if(p.maskFile){const mid=String(9001+i*10);output[mid]={class_type:'LoadImage',inputs:{image:p.maskFile}};const tid=String(9002+i*10);output[tid]={class_type:'ImageToMask',inputs:{image:[mid,0],channel:'red'}};mask=[tid,0];}
|
||||
if(p.source==='prompt'&&p.mask){const sid=String(9003+i*10);output[sid]={class_type:'SAM3Segment',inputs:{image:[id,0],prompt:p.prompt,output_mode:'Merged',confidence_threshold:.5,max_segments:0,segment_pick:Number(p.segment||0),mask_blur:0,mask_offset:0,device:'Auto',invert_output:false,unload_model:false,background:'Alpha',background_color:'#222222'}};mask=[sid,1];}
|
||||
const pid=String(9004+i*10);output[pid]={class_type:'DOGMAAPIReferenceV2',inputs:{image:[id,0],mask,settings:JSON.stringify(p)}};link=[pid,0];
|
||||
}
|
||||
images.push({ref,link});
|
||||
});
|
||||
let nanoBatch=null;
|
||||
if(s.mode==='image'&&s.models.nano?.enabled&&images.length){nanoBatch=images[0].link;images.slice(1).forEach((img,i)=>{const id=String(9800+i);output[id]={class_type:'ImageBatch',inputs:{image1:nanoBatch,image2:img.link}};nanoBatch=[id,0];});}
|
||||
jobs.forEach((job,i)=>{
|
||||
const f=ALL_FAMILIES.find(f=>f.key===job.family),m=s.models[f.key],inputs=copy(m.engine==='frames'?m.frames:m.parameters);
|
||||
for(const k of Object.keys(inputs))if(k.startsWith('control_after_generate')||k==='n')delete inputs[k];
|
||||
const seed=(Number(baseSeed)+i)%2147483647;inputs[f.key==='seedream'?'model.seed':'seed']=seed;
|
||||
const prompt=s.prompts[s.mode];inputs[s.mode==='video'?'model.prompt':'prompt']=prompt;
|
||||
let type=f.type;
|
||||
if(s.mode==='video'){
|
||||
if(m.engine==='frames'){
|
||||
type='ByteDance2FirstLastFrameNode';
|
||||
const first=images.find(x=>x.ref.role==='first')||images.find(x=>x.ref.role!=='last');const last=images.find(x=>x.ref.role==='last')||images.filter(x=>x!==first)[0];
|
||||
if(first)inputs.first_frame=first.link;if(last)inputs.last_frame=last.link;
|
||||
}else{images.forEach((x,j)=>inputs[`model.reference_images.image_${j+1}`]=x.link);videos.forEach((x,j)=>inputs[`model.reference_videos.video_${j+1}`]=x.link);}
|
||||
}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)});
|
||||
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;
|
||||
output[save]={class_type:s.mode==='video'?'DOGMAAPIVideoOutputV2':'DOGMAAPIImageOutputV2',inputs:{[s.mode==='video'?'video':'images']:[gen,0],metadata:JSON.stringify(metadata)}};
|
||||
});
|
||||
return {output,jobs};
|
||||
}
|
||||
export function filterResults(results,filters){return results.filter(r=>(!filters.models.length||filters.models.includes(r.family))&&(filters.project==='*'||(r.project||'')===filters.project)&&(filters.scene==='*'||(r.scene||'')===filters.scene)&&(filters.workspace==='*'||(r.workspace||'')===filters.workspace)&&(filters.kind==='all'||r.kind===filters.kind));}
|
||||
@@ -0,0 +1,112 @@
|
||||
{
|
||||
"schema": 3,
|
||||
"session": "",
|
||||
"mode": "image",
|
||||
"imageEdit": true,
|
||||
"project": "",
|
||||
"scene": "",
|
||||
"filename": "DOGMA",
|
||||
"date": "",
|
||||
"appendDate": false,
|
||||
"workspace": "",
|
||||
"prompts": {
|
||||
"image": "",
|
||||
"video": ""
|
||||
},
|
||||
"density": 55,
|
||||
"models": {
|
||||
"nano": {
|
||||
"enabled": true,
|
||||
"expanded": false,
|
||||
"quantity": 2,
|
||||
"parameters": {
|
||||
"model": "gemini-3-pro-image-preview",
|
||||
"seed": 637339876168947,
|
||||
"aspect_ratio": "16:9",
|
||||
"resolution": "2K",
|
||||
"response_modalities": "IMAGE",
|
||||
"system_prompt": "Follow the user prompt and the assigned roles of the reference images precisely."
|
||||
}
|
||||
},
|
||||
"gpt": {
|
||||
"enabled": true,
|
||||
"expanded": false,
|
||||
"quantity": 2,
|
||||
"parameters": {
|
||||
"model": "gpt-image-2",
|
||||
"model.size": "2048x1152",
|
||||
"model.custom_width": 1920,
|
||||
"model.custom_height": 1088,
|
||||
"model.background": "auto",
|
||||
"model.quality": "high",
|
||||
"n": 1,
|
||||
"seed": 726834962
|
||||
}
|
||||
},
|
||||
"flux": {
|
||||
"enabled": true,
|
||||
"expanded": false,
|
||||
"quantity": 2,
|
||||
"parameters": {
|
||||
"aspect_ratio": "auto",
|
||||
"resolution": "2K",
|
||||
"grounding": true,
|
||||
"safety_tolerance": 4,
|
||||
"seed": 390115469
|
||||
}
|
||||
},
|
||||
"seedream": {
|
||||
"enabled": true,
|
||||
"expanded": true,
|
||||
"quantity": 2,
|
||||
"parameters": {
|
||||
"model": "seedream 5.5",
|
||||
"model.size_preset": "Custom",
|
||||
"model.width": 2048,
|
||||
"model.height": 1152,
|
||||
"model.background": "auto",
|
||||
"model.seed": 42,
|
||||
"model.watermark": false
|
||||
}
|
||||
},
|
||||
"seedance": {
|
||||
"enabled": true,
|
||||
"expanded": true,
|
||||
"quantity": 1,
|
||||
"engine": "reference",
|
||||
"parameters": {
|
||||
"model": "Seedance 2.5",
|
||||
"model.resolution": "1080p",
|
||||
"model.ratio": "adaptive",
|
||||
"model.duration": 15,
|
||||
"model.generate_audio": false,
|
||||
"model.task_type": "edit",
|
||||
"model.output_format": "mp4",
|
||||
"model.auto_downscale": false,
|
||||
"model.auto_upscale": false,
|
||||
"seed": 1982892718,
|
||||
"watermark": false
|
||||
},
|
||||
"frames": {
|
||||
"model": "Seedance 2.5",
|
||||
"model.resolution": "720p",
|
||||
"model.duration": 4,
|
||||
"model.generate_audio": false,
|
||||
"model.output_format": "mp4",
|
||||
"seed": 1439633762,
|
||||
"watermark": false,
|
||||
"first_frame_asset_id": "",
|
||||
"last_frame_asset_id": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
"references": [],
|
||||
"results": [],
|
||||
"filters": {
|
||||
"models": [],
|
||||
"project": "*",
|
||||
"scene": "*",
|
||||
"kind": "all",
|
||||
"workspace": "*"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 3.3 KiB |
@@ -0,0 +1,32 @@
|
||||
.dap,.dap-modal{--orange:#ff6626;--line:#292929;--muted:#777;--ink:#d4d4d4;box-sizing:border-box;background:#000;color:var(--ink);font-family:Arial,Helvetica,sans-serif;font-size:13px;color-scheme:dark}
|
||||
.dap *,.dap-modal *{box-sizing:border-box}.dap [hidden],.dap-modal [hidden]{display:none!important}.dap button,.dap input,.dap select,.dap textarea,.dap-modal button,.dap-modal input,.dap-modal select,.dap-modal textarea{font:inherit;color:inherit}.dap button,.dap-modal button{cursor:pointer}.dap button:disabled,.dap-modal button:disabled{opacity:.35;cursor:default}.dap-icon{display:block;width:19px;height:19px;flex:none;fill:none;stroke:currentColor;stroke-width:1.35;stroke-linecap:round;stroke-linejoin:round;pointer-events:none}
|
||||
.dap button,.dap summary,.dap select,.dap input,.dap textarea,.dap-modal button,.dap-modal summary,.dap-modal input,.dap-modal select{transition:color .15s,border-color .15s,background-color .15s,box-shadow .15s,filter .15s}.dap button:hover:not(:disabled),.dap summary:hover,.dap-modal button:hover:not(:disabled),.dap-modal summary:hover{color:var(--orange);border-color:#9d4826}.dap button:active:not(:disabled),.dap-modal button:active:not(:disabled){filter:brightness(1.2)}.dap input:hover,.dap select:hover,.dap textarea:hover,.dap-modal input:hover,.dap-modal select:hover{border-color:#9d4826}.dap input:focus,.dap textarea:focus,.dap select:focus,.dap-modal input:focus,.dap-modal select:focus{outline:none;color:#fff}.dap button:focus-visible,.dap summary:focus-visible,.dap input:focus-visible,.dap select:focus-visible,.dap textarea:focus-visible,.dap-modal button:focus-visible,.dap-modal input:focus-visible,.dap-modal select:focus-visible{outline:1px solid var(--orange);outline-offset:3px}
|
||||
.dap{position:fixed;inset:0;width:100vw;height:100dvh;max-width:none;max-height:none;margin:0;border:0;padding:0;overflow:hidden}.dap::backdrop,.dap-modal::backdrop{background:#000c}.dap-header{height:142px;display:flex;justify-content:space-between;align-items:flex-start;padding:18px 22px 0;gap:20px}.dap-brand{display:flex;align-items:flex-end;gap:8px;white-space:nowrap}.dap-brand img{width:163px;height:34px;object-fit:contain}.dap-brand>span{font:16px/1 'Courier New',monospace;color:var(--orange);transform:translateY(3px)}.dap-actions{display:flex;align-items:center;gap:14px}.dap-credit{border:0;background:none;color:#777;font:10px 'Courier New',monospace!important;padding:7px}.dap-credit:hover{color:#aaa!important}.dap-run{display:flex;align-items:center;justify-content:space-between;gap:25px;min-width:144px;height:28px;padding:4px 12px;border:1px solid var(--orange);border-radius:30px;background:var(--orange);color:#000!important;font-weight:bold!important}.dap-run .dap-icon{height:18px;width:18px}.dap-run:hover:not(:disabled){background:#ff813f!important;border-color:#ff813f!important;box-shadow:0 0 20px #ff662621}.dap-icon-button{display:inline-flex;align-items:center;justify-content:center;gap:8px;background:transparent;border:1px solid transparent;padding:4px;color:#888}.dap-icon-button:hover{color:var(--orange)}
|
||||
.dap-layout{height:calc(100dvh - 142px);display:grid;grid-template-columns:minmax(320px,24.25%) minmax(0,1fr);padding:0 10px;min-height:0;overflow:hidden}.dap-side{height:100%;min-height:0;min-width:0;overflow-y:auto;overflow-x:hidden;border-right:1px solid #191919;padding:0 12px 32px 0;scrollbar-width:thin;scrollbar-color:#72351d #000;overscroll-behavior:contain}.dap-tabs{display:flex;gap:12px;min-height:30px;margin-bottom:11px}.dap-tabs button{display:flex;align-items:center;gap:8px;flex:1;min-width:0;height:29px;padding:3px 12px;border:1px solid #602c17;border-radius:30px;background:none;color:#804121;text-align:left}.dap-tabs button .dap-icon{width:15px;height:15px;stroke-width:1.5}.dap-tabs button.active{color:var(--orange);border-color:var(--orange)}.dap-tabs button:hover{background:#ff662608}.dap-edit-mode{display:flex;align-items:center;gap:10px;padding:0 12px 0;min-height:29px;margin-bottom:24px;color:#aaa;font-size:11px}.dap-edit-mode small{margin-left:auto;font:9px 'Courier New',monospace;color:#666}.dap-controls{padding-left:12px;overflow:visible;min-width:0}.dap-section{margin-bottom:28px}.dap-label{font:10px 'Courier New',monospace;color:#7a7a7a;margin:0 0 11px;letter-spacing:.03em}
|
||||
.dap-toggle{display:inline-block;position:relative;flex:0 0 48px;width:48px;height:27px;min-width:48px;border:1px solid #292929;border-radius:20px;background:#000;padding:0;color:#555}.dap-toggle-knob{position:absolute;left:2px;top:2px;width:21px;height:21px;display:flex;align-items:center;justify-content:center;border:1px solid #3a3a3a;border-radius:50%;transition:transform .18s ease,border-color .15s,color .15s,box-shadow .15s}.dap-toggle-knob .dap-icon{width:14px;height:14px;stroke-width:1}.dap-toggle.on .dap-toggle-knob{transform:translateX(21px);color:var(--orange);border-color:var(--orange)}.dap-toggle:hover .dap-toggle-knob{color:var(--orange);border-color:var(--orange);box-shadow:0 0 9px #ff66261c}
|
||||
.dap-refs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px;min-width:0}.dap-ref,.dap-add{position:relative;min-width:0;border:1px solid #272727;border-radius:13px;overflow:hidden;aspect-ratio:1.65;background:#040404}.dap-ref>img,.dap-ref>video{width:100%;height:100%;object-fit:cover;display:block;cursor:crosshair;transition:filter .18s}.dap-ref:hover>img,.dap-ref:hover>video{filter:brightness(1.08)}.dap-ref.disabled>img,.dap-ref.disabled>video{opacity:.23}.dap-ref-order{position:absolute;top:8px;left:8px;font:8px 'Courier New',monospace;color:#eee;text-shadow:0 1px 3px #000;pointer-events:none}.dap-ref-edited{position:absolute;top:8px;right:8px;font:8px 'Courier New',monospace;color:var(--orange)}.dap-ref-tools{position:absolute;bottom:0;left:0;right:0;display:flex;align-items:center;justify-content:flex-end;gap:4px;padding:17px 5px 5px;background:linear-gradient(transparent,#000d)}.dap-ref-tools .dap-icon-button{padding:2px;color:#e5784b}.dap-ref-tools .dap-icon{width:14px;height:14px}.dap-ref-tools .dap-toggle{margin-right:auto;width:34px;min-width:34px;height:20px;flex-basis:34px}.dap-ref-tools .dap-toggle-knob{width:14px;height:14px;top:2px;left:2px}.dap-ref-tools .dap-toggle.on .dap-toggle-knob{transform:translateX(14px)}.dap-ref-tools .dap-toggle-knob .dap-icon{width:10px;height:10px}.dap-ref-role{position:absolute;left:5px;right:5px;top:25px;width:calc(100% - 10px);background:#000a;border:1px solid #444;border-radius:10px;font:8px 'Courier New',monospace!important;padding:2px 4px}.dap-ref.missing:after{content:'RICARICA FILE';position:absolute;top:44%;left:0;right:0;text-align:center;color:var(--orange);font:9px 'Courier New',monospace;pointer-events:none}.dap-add{display:flex;flex-direction:column;gap:7px;justify-content:center;align-items:center;color:#555;padding:12px}.dap-add .dap-icon{width:24px;height:24px;stroke-width:.6}.dap-add span{font:8px 'Courier New',monospace}.dap-add:hover{background:#ff662608;border-color:#8f4224}
|
||||
.dap-prompt-wrap{position:relative}.dap textarea{display:block;width:100%;min-height:105px;max-height:none;resize:none;border:1px solid #282828;border-radius:14px;background:#000;padding:9px 10px;font:12px/1.4 Arial,Helvetica,sans-serif;scrollbar-width:thin;scrollbar-color:#74331b #000}.dap textarea:hover{border-color:#68402a}.dap textarea:focus{border-color:#a84b23}.dap-resize-handle{position:absolute;bottom:5px;right:6px;width:12px;height:12px;cursor:ns-resize;background:repeating-linear-gradient(135deg,transparent 0 3px,var(--orange) 3px 4px,transparent 4px 6px);clip-path:polygon(100% 0,100% 100%,0 100%);opacity:.65;touch-action:none}.dap-resize-handle:hover{opacity:1;filter:brightness(1.2)}
|
||||
.dap-field{position:relative;display:flex;align-items:center;gap:7px;min-height:28px;margin-bottom:8px;padding:3px 11px;border:1px solid #252525;border-radius:25px;min-width:0;font:10px 'Courier New',monospace;transition:border-color .15s,background .15s}.dap-field:hover{border-color:#5a3929;background:#ff662604}.dap-field:focus-within{border-color:#8c421f}.dap-field>span{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#777;font-size:9px}.dap-field input,.dap-field select{min-width:0;max-width:64%;padding:0;border:0;background:transparent;color:#d1d1d1;text-align:right;font:10px 'Courier New',monospace;outline:none}.dap-field input[type=text]{width:65%}.dap-field input[type=number]{width:95px;appearance:textfield;-moz-appearance:textfield}.dap-field input[type=number]::-webkit-inner-spin-button{display:none}.dap-field input[type=checkbox]{height:15px;width:15px;margin:0;accent-color:var(--orange);cursor:pointer}.dap-field input[type=color]{height:18px;width:35px;padding:0;border-radius:5px;cursor:pointer}.dap-field select{appearance:none;padding-right:16px;cursor:pointer}.dap-field.has-select>.dap-icon{position:absolute;right:8px;width:11px;height:11px;color:#aaa}.dap-field input[readonly]{color:#aaa;cursor:default}.dap-field input::placeholder{color:#494949}.dap-field select option{background:#080808;color:#ddd}.dap-field-hint{font:9px/1.5 'Courier New',monospace;color:#666;margin:0 7px 10px}.dap-date-row{display:flex;align-items:center;gap:10px;margin:10px 0 12px;font:10px 'Courier New',monospace;color:#999}.dap-date-row small{margin-left:auto;color:#805339}.dap-workspace-button{display:flex;width:100%;border:1px solid #303030;border-radius:20px;padding:7px 10px;text-align:left;justify-content:flex-start;color:#aaa}.dap-workspace-button .dap-icon{width:16px;height:16px;color:var(--orange)}.dap-workspace-button span{min-width:0;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font:10px 'Courier New',monospace}.dap-filename-preview{font:9px/1.5 'Courier New',monospace;color:#76513d;overflow-wrap:anywhere;padding:9px 7px 0}
|
||||
.dap-model{margin-bottom:8px}.dap-model-head{display:flex;align-items:flex-start;gap:7px;min-width:0}.dap-model details{flex:1;min-width:0}.dap summary{list-style:none;cursor:pointer}.dap summary::-webkit-details-marker{display:none}.dap-model summary{display:flex;align-items:center;gap:10px;min-height:27px;max-width:100%;padding:4px 10px 4px 11px;border:1px solid #292929;border-radius:22px;color:#999}.dap-model.enabled summary{color:var(--orange)}.dap-model summary>span{white-space:nowrap}.dap-model summary>small{font:8px 'Courier New',monospace;color:#676767;min-width:0;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.dap-model summary>.dap-icon{margin-left:auto;height:13px;width:13px;color:var(--orange);transform:rotate(0);transition:transform .16s}.dap-model details[open]>summary>.dap-icon{transform:rotate(180deg)}.dap-model summary:hover{background:#ff662607}.dap-model-body{padding:10px 0 3px}.dap-advanced summary{font:9px 'Courier New',monospace;border:0;border-radius:0;color:#777!important;padding:7px}.dap-advanced textarea{height:170px;font-size:11px}
|
||||
.dap-main{min-width:0;min-height:0;display:flex;flex-direction:column;height:100%;padding:0 10px 0 17px;overflow:hidden}.dap-toolbar{display:flex;align-items:center;justify-content:space-between;gap:14px;min-height:30px;margin-bottom:12px;flex-shrink:0}.dap-project{font-size:13px;color:#995330;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.dap-views{display:flex;align-items:center;gap:18px}.dap-views .dap-icon{height:21px;width:21px}.dap-views .active{color:var(--orange)}.dap-views input[type=range]{width:180px;appearance:none;background:#272727;height:1px;outline:none;cursor:ew-resize}.dap-views input[type=range]::-webkit-slider-thumb{appearance:none;width:24px;height:24px;border:1px solid var(--orange);border-radius:50%;background:#000;transition:background .15s,box-shadow .15s;cursor:ew-resize}.dap-views input[type=range]:hover::-webkit-slider-thumb{background:#1b0c05;box-shadow:0 0 10px #ff662622}.dap-filters{display:flex;align-items:center;justify-content:flex-end;gap:10px;min-height:28px;flex-shrink:0;margin-bottom:9px;flex-wrap:wrap}.dap-filter,.dap-filter-models>summary{display:flex;align-items:center;gap:8px;position:relative;border:1px solid #282828;border-radius:20px;min-height:25px;padding:3px 9px;font:9px 'Courier New',monospace;color:#888}.dap-filter:hover,.dap-filter-models>summary:hover{border-color:#7b3a20}.dap-filter>span{font-size:8px;color:#555}.dap-filter select{max-width:160px;min-width:65px;border:0;background:none;appearance:none;padding-right:14px;color:#aaa;outline:0;cursor:pointer;font:9px 'Courier New',monospace}.dap-filter>.dap-icon{width:10px;height:10px;position:absolute;right:7px}.dap-filter select option{background:#080808}.dap-filter-models{position:relative}.dap-filter-models>summary>.dap-icon{width:11px;height:11px}.dap-filter-models>summary>span{max-width:260px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.dap-filter-menu{position:absolute;top:31px;right:0;z-index:20;min-width:210px;padding:10px;background:#080808;border:1px solid #67321b;border-radius:13px;box-shadow:0 12px 40px #000}.dap-filter-menu>label,.dap-filter-menu>button{display:flex;align-items:center;gap:10px;padding:8px;border:0;background:none;color:#bbb;width:100%;font:11px 'Courier New',monospace;text-align:left;border-radius:6px;cursor:pointer}.dap-filter-menu>label:hover,.dap-filter-menu>button:hover{background:#ff662610;color:var(--orange)}.dap-filter-menu input{accent-color:var(--orange)}.dap-notice{font:9px/1.5 'Courier New',monospace;color:#6d6d6d;min-height:17px;flex-shrink:0;margin-bottom:9px}.dap-notice.is-error{color:var(--orange)}
|
||||
.dap-gallery-viewport{flex:1;min-height:0;overflow-y:scroll;overflow-x:hidden;overscroll-behavior:contain;scrollbar-width:thin;scrollbar-color:#72351d #000;padding-right:3px}.dap-gallery{column-width:var(--card-min,420px);column-gap:14px;padding-bottom:20px;min-height:101%;overflow:visible}.dap-card{position:relative;break-inside:avoid;min-width:0;width:100%;overflow:hidden;border:1px solid #23170f;border-radius:16px;background:#030303;margin:0 0 14px;transition:border-color .15s,box-shadow .15s}.dap-card:hover{border-color:#6b351f;box-shadow:0 0 18px #ff662609}.dap-card-media{position:relative;min-height:100px;cursor:zoom-in;overflow:hidden;background:#030303;line-height:0}.dap-card-media>video{display:block;width:100%;height:auto;min-height:130px}.dap-card-media>.dap-icon{position:absolute;inset:0;margin:auto;width:30px;height:30px;color:#fff7;filter:drop-shadow(0 1px 4px #000)}.dap-compare-host>.dap-generated{display:block;width:100%;height:auto;min-height:120px;user-select:none}.dap-original-cover{position:absolute;inset:0;opacity:0;pointer-events:none}.dap-original-cover>img{display:block;width:100%;height:100%;object-fit:contain;user-select:none}.dap-compare-line{position:absolute;top:0;bottom:0;width:1px;background:white;mix-blend-mode:difference;opacity:0;pointer-events:none}.dap-compare-host.comparing>.dap-original-cover,.dap-compare-host.comparing>.dap-compare-line{opacity:1}.dap-card-tools{position:absolute;top:8px;right:8px;display:flex;gap:5px;opacity:0;transform:translateY(-3px);transition:opacity .15s,transform .15s}.dap-card:hover>.dap-card-tools,.dap-card:focus-within>.dap-card-tools,.dap-card-tools:has(.selected){opacity:1;transform:translateY(0)}.dap-card-tools .dap-icon-button{background:#000b;border:1px solid #59321e;border-radius:20px;padding:5px;color:#cf7a51}.dap-card-tools .dap-icon{width:14px;height:14px}.dap-card-tools .selected{background:var(--orange);color:#000}.dap-card-tools .dap-icon-button:hover{background:#180a03;color:#ff8950}.dap-card-footer{display:flex;justify-content:space-between;gap:8px;padding:8px 11px;font-size:11px;color:#898989;line-height:1.3}.dap-card-footer>span:first-child{overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.dap-elapsed{font:9px 'Courier New',monospace;color:#686868;white-space:nowrap}.dap-card-tags{font:8px 'Courier New',monospace;color:#74513d;padding:0 11px 8px}.dap-study{position:absolute;left:10px;top:10px;font:8px 'Courier New',monospace;color:#fffb;text-shadow:0 1px 3px #000;pointer-events:none}.dap-card.pending{aspect-ratio:1.65;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px}.dap-card.pending>.dap-card-footer{position:absolute;bottom:0;left:0;right:0}.dap-job-state{font:10px 'Courier New',monospace;color:#8c5a41}.dap-spinner{width:26px;height:26px;border:4px dotted #653015;border-top-color:var(--orange);border-right-color:#bf4e1b;border-radius:50%;animation:dap-spin 1.3s linear infinite}.dap-card.stopped .dap-spinner{display:none}.dap-card-error{font:10px/1.5 'Courier New',monospace;color:var(--orange);padding:0 11px 9px;margin:0;max-height:90px;overflow:auto}.dap-empty{column-span:all;min-height:65vh;border-top:1px solid #381b0e;padding:50px 10px;color:#777}.dap-empty>span{font:10px 'Courier New',monospace;color:#bd5e2e}.dap-empty h2{font-size:27px;font-weight:normal;color:#aaa;margin-top:24px}.dap-empty p{font:11px/1.6 'Courier New',monospace;max-width:600px}
|
||||
.dap-modal{border:1px solid #63301a;border-radius:17px;width:min(1400px,94vw);max-width:96vw;max-height:94dvh;padding:18px;overflow:auto}.dap-modal>header{display:flex;align-items:center;justify-content:space-between;gap:15px;font:11px 'Courier New',monospace;color:#dd743f;margin-bottom:15px}.dap-modal>header>span{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}.dap-modal>header .dap-icon{width:16px;height:16px}.dap-outline,.dap-primary{border:1px solid #63351e;border-radius:20px;background:#000;color:#d67544;padding:7px 14px;font:10px 'Courier New',monospace!important;cursor:pointer}.dap-primary{background:var(--orange);border-color:var(--orange);color:#000!important}.dap-primary:hover{background:#ff854b}.dap-viewer-modal{width:96vw;max-width:96vw;height:94dvh;max-height:94dvh;overflow:hidden;display:flex;flex-direction:column;padding:15px}.dap-viewer-modal>header{margin-bottom:7px;flex-shrink:0}.dap-viewer-tools{display:flex;align-items:center;justify-content:center;gap:10px;flex-wrap:wrap;flex-shrink:0;margin-bottom:10px}.dap-viewer-tools>button{display:flex;align-items:center;justify-content:center;gap:7px;border:1px solid #282828;border-radius:20px;background:#030303;color:#aaa;padding:6px 11px;min-height:30px;font:10px 'Courier New',monospace}.dap-viewer-tools .dap-icon{width:16px;height:16px}.dap-zoom-value{display:flex;align-items:center;gap:2px;font:10px 'Courier New',monospace;color:#aaa}.dap-zoom-value input{width:45px;appearance:textfield;-moz-appearance:textfield;padding:5px 1px;background:transparent;border:0;text-align:right;font:10px 'Courier New',monospace}.dap-zoom-value input::-webkit-inner-spin-button{display:none}.dap-viewer-stage{position:relative;flex:1;min-height:0;background:#010101;overflow:hidden;touch-action:none;outline:none;cursor:zoom-in}.dap-viewer-stage.zoomed{cursor:grab}.dap-viewer-stage:active{cursor:grabbing}.dap-viewer-surface{position:absolute;left:0;top:0;transform-origin:0 0;line-height:0;will-change:transform;user-select:none}.dap-viewer-surface>.dap-generated{width:100%;height:100%;min-height:0}.dap-viewer-surface>.dap-original-cover img{object-fit:contain}.dap-viewer-hint{font:9px 'Courier New',monospace;color:#666;text-align:center;margin:10px 0 0;flex-shrink:0}.dap-viewer-video{width:100%;height:100%;object-fit:contain;display:block}
|
||||
.dap-reference-modal{width:96vw}.dap-reference-layout{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:25px}.dap-reference-left{min-width:0}.dap-reference-tools{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:14px}.dap-editor-tool{padding:7px 12px;border:1px solid #333;border-radius:20px;background:#000;color:#aaa;font:10px 'Courier New',monospace!important}.dap-editor-tool.active{border-color:var(--orange);color:var(--orange)}.dap-reference-tools>input[type=range]{width:90px;accent-color:var(--orange)}.dap-mask-stage{position:relative;max-width:100%;margin:0 auto;line-height:0;background:#131313}.dap-mask-stage canvas{display:block;width:100%;height:auto}.dap-mask-stage canvas+canvas{position:absolute;inset:0;touch-action:none;cursor:crosshair}.dap-reference-options{max-height:69vh;overflow-y:auto;overflow-x:hidden;scrollbar-width:thin;scrollbar-color:#7f351a #000;padding-right:4px}.dap-reference-options .dap-field{min-height:28px}.dap-reference-options .dap-field-hint{line-height:1.6}.dap-reference-preview{width:100%;height:auto;display:block;margin-top:12px;border:1px solid #3e281a;border-radius:8px}.dap-reference-footer{display:flex;justify-content:flex-end;gap:10px;margin-top:18px}.dap-editor-status{font:10px/1.5 'Courier New',monospace;color:#b06c46;margin:12px 0}.dap-folder-list{display:flex;flex-direction:column;gap:8px}.dap-folder-list>.dap-icon-button{justify-content:flex-start;border:1px solid #222;border-radius:8px;padding:10px}.dap-folder-path{font:11px 'Courier New',monospace;color:#888;overflow-wrap:anywhere;padding:10px 0 20px}
|
||||
@keyframes dap-spin{to{transform:rotate(360deg)}}
|
||||
@media(min-width:2200px){.dap-header{height:160px}.dap-layout{height:calc(100dvh - 160px)}}
|
||||
@media(max-width:1250px){.dap-header{height:105px}.dap-layout{height:calc(100dvh - 105px);grid-template-columns:320px minmax(0,1fr)}.dap-views{gap:10px}.dap-views input[type=range]{width:100px}.dap-main{padding-left:12px}.dap-credit{font-size:9px!important}.dap-filters{justify-content:flex-start}.dap-filter>span{display:none}.dap-model summary>small{max-width:105px}}
|
||||
@media(max-width:760px){.dap-header{height:85px;padding:14px 12px 0;gap:8px}.dap-brand{display:block}.dap-brand img{width:115px;height:24px}.dap-brand>span{display:block;transform:none;font-size:11px;margin-top:6px}.dap-actions{gap:5px}.dap-actions>.dap-icon-button{display:none}.dap-credit{font-size:8px!important;max-width:95px;text-align:right}.dap-run{min-width:95px;padding:4px 10px;gap:6px}.dap-layout{height:calc(100dvh - 85px);display:flex;flex-direction:column;overflow-y:auto;padding:0 12px}.dap-side{height:auto;max-height:65vh;overflow-y:auto;flex-shrink:0;border-right:0;border-bottom:1px solid #2b1b12;padding-right:4px}.dap-controls{padding-left:0}.dap-main{height:75vh;min-height:400px;padding:15px 0 0;flex-shrink:0}.dap-refs{grid-template-columns:repeat(2,minmax(0,1fr))}.dap-views input[type=range]{width:80px}.dap-toolbar{gap:8px}.dap-project{font-size:11px}.dap-filters{gap:6px}.dap-filter select{max-width:120px;font-size:8px}.dap-filter-models>summary>span{max-width:140px}.dap-reference-layout{grid-template-columns:1fr}.dap-reference-options{max-height:none}.dap-reference-modal{max-height:95dvh}.dap-viewer-modal{height:95dvh}.dap-viewer-tools{gap:5px}.dap-viewer-tools>button{font-size:9px;padding:5px 7px}.dap-viewer-hint{font-size:8px;line-height:1.5}.dap-empty h2{font-size:21px}}
|
||||
@media(prefers-reduced-motion:reduce){.dap *,.dap-modal *{animation:none!important;transition:none!important}}
|
||||
|
||||
.dap-date-row input[type=date]{margin-left:auto;min-width:0;width:105px;border:0;background:transparent;color:#9a623f;font:9px Courier New,monospace;cursor:pointer}.dap-date-row input[type=date]:hover{color:var(--orange)}.dap-operation-note{flex-shrink:0;font:10px/1.4 Courier New,monospace;color:var(--orange);margin:8px 0 0;text-align:center}
|
||||
|
||||
.dap-field-step{width:10px;min-width:10px;height:16px;flex:none;border:0;padding:0;color:#999}.dap-field-step .dap-icon{width:9px;height:13px;stroke-width:1.4}.dap-field-step.next{transform:rotate(180deg)}.dap-field select{padding-right:0}.dap-field input[type=checkbox]{appearance:none;border:1px solid #454545;border-radius:50%;background:#000}.dap-field input[type=checkbox]:checked{border-color:var(--orange);background:var(--orange);box-shadow:inset 0 0 0 3px #000}.dap-field input[type=checkbox]:hover{border-color:var(--orange)}
|
||||
|
||||
/* 1.0.55: immediate shell, in-panel folders and live progress */
|
||||
.dap-stop{border:1px solid #ef382e;background:#cf2922;color:white!important;border-radius:25px;padding:8px 22px;font-weight:bold!important;min-width:100px;cursor:pointer}.dap-stop:hover{background:#f34135;box-shadow:0 0 20px #ee302733}.dap-stop:disabled{opacity:.24;cursor:default}.dap-project{background:none;border:0;text-align:left;cursor:pointer;max-width:55%}.dap-project:hover{color:var(--orange)}
|
||||
.dap-work>summary{display:flex;align-items:center;justify-content:space-between;cursor:pointer;padding:8px 0;border-bottom:1px solid #292018}.dap-work>summary:hover{color:var(--orange)}.dap-work>summary .dap-icon{width:12px;height:12px}.dap-work[open]>summary .dap-icon{transform:rotate(180deg)}.dap-work>div{padding-top:10px}.dap-video-choice{margin:0 0 25px}.dap-video-choice>button{background:#000;border:1px solid #333;border-radius:22px;color:#aaa;padding:9px 16px;margin-right:8px;font:11px Courier New,monospace}.dap-video-choice>button.active{border-color:var(--orange);color:var(--orange)}
|
||||
.dap-views>button:first-child .dap-icon{width:40px;height:24px}.dap-card-tools .dap-icon-button:first-child .dap-icon{width:23px}
|
||||
.dap-folder-modal{width:min(1000px,90vw);height:75vh;display:flex;flex-direction:column}.dap-folder-navigation,.dap-folder-footer{display:flex;gap:10px;flex-shrink:0;margin:10px 0}.dap-folder-navigation input{flex:1;min-width:0}.dap-folder-navigation input,.dap-folder-footer input{background:#111;color:#ccc;border:1px solid #444;border-radius:8px;padding:9px;font:12px Courier New,monospace}.dap-folder-list{flex:1;overflow:auto;min-height:0}.dap-folder-file{padding:10px 14px;color:#999;font:12px Courier New,monospace;border:1px solid transparent;border-radius:6px}.dap-folder-file.selected{background:#ff662622;border-color:var(--orange);color:#eee}.dap-folder-footer{flex-wrap:wrap}
|
||||
.dap-progress-track{height:3px;background:#271308;overflow:hidden;border-radius:2px}.dap-progress-track>i{display:block;height:100%;width:0;background:#ff6626;box-shadow:0 0 7px #ff6626;transition:width .7s linear}.dap-total-progress{margin:0 0 12px;flex-shrink:0}.dap-total-progress>span{display:block;text-align:right;font:10px Courier New,monospace;color:#b47753;margin-top:8px}.dap-card-progress{position:absolute;bottom:0;left:0;right:0}.dap-progress-track.indeterminate>i{width:28%!important;animation:dap-progress 1.8s ease-in-out infinite}.dap-spinner{border:0;animation:none;width:38px;height:38px;position:relative}.dap-spinner>i{position:absolute;left:17px;top:17px;width:4px;height:4px;border-radius:50%;background:#ff742d;transform:rotate(calc(var(--i)*22.5deg)) translateY(-16px);box-shadow:0 0 6px #ff6626,0 0 12px #ff662666;opacity:0;animation:dap-light 1.25s linear infinite;animation-delay:calc(var(--i)*.078125s)}
|
||||
@keyframes dap-light{0%{opacity:1}70%,100%{opacity:0}}@keyframes dap-progress{from{transform:translateX(-110%)}to{transform:translateX(470%)}}
|
||||
.dap-generated{opacity:1;transition:opacity .2s}.dap-reference-preview[hidden],.dap-total-progress[hidden]{display:none}.dap-field select{min-width:35%;cursor:pointer}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { app } from '../../scripts/app.js';
|
||||
import { api } from '../../scripts/api.js';
|
||||
import { PlatformUI } from './dogma_api_ui.js?v=1.0.55';
|
||||
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.55';
|
||||
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.55',ROOT);document.head.append(css);
|
||||
let opened=null,queueLock=false;
|
||||
const cachedSchemas=fetch(new URL('dogma_api_schemas.json?v=1.0.55',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_V3.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.55',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]];}));
|
||||
for(const r of live)if(r.status==='fulfilled'&&r.value[1])this.defs[r.value[0]]=r.value[1];
|
||||
if(state.workspace){try{await this.workspace(state.workspace);}catch(e){this.workspaceError=e.message;}}
|
||||
try{
|
||||
const script=[...document.querySelectorAll('script[type=module][src]')].find(x=>x.src.includes('/assets/'));
|
||||
const base=script?.src||new URL('/assets/index.js',location.href).href;
|
||||
const names=this.catalog.frontend;
|
||||
if(names.billing&&names.credits){
|
||||
const [billing,credits]=await Promise.all([import(new URL(names.billing.file,base).href),import(new URL(names.credits.file,base).href)]);
|
||||
this.billing=billing[names.billing.context]();this.nativePricing=billing[names.billing.pricing]();this.formatCredits=credits[names.credits.format];
|
||||
}
|
||||
}catch(e){console.warn('DOGMA: servizi crediti/prezzi non disponibili in questo frontend.');}
|
||||
}
|
||||
save(s){this.widget.value=JSON.stringify(s);this.node.setDirtyCanvas?.(true,true);clearTimeout(this.saveTimer);this.saveTimer=setTimeout(()=>{if(this.node.graph===app.graph)app.graph.change?.();},250);}
|
||||
logo(){return new URL('dogma_api_logo.png',ROOT).href;}
|
||||
view(file){if(file?.workspace&&file?.relative)return api.apiURL('/dogma/api/v2/workspace-media?'+new URLSearchParams({workspace:file.workspace,relative:file.relative}));if(file?.url)return file.url;return api.apiURL('/view?'+new URLSearchParams(viewParameters(file)));}
|
||||
async request(path,body){const headers={};if(this.catalog?.access?.token)headers['X-Dogma-Access']=this.catalog.access.token;if(body!==undefined)headers['Content-Type']='application/json';const response=await api.fetchApi('/dogma/api/v2'+path,{method:body===undefined?'GET':'POST',headers,...(body!==undefined?{body:JSON.stringify(body)}:{})});if(!response.ok)throw new Error((await response.text()).slice(0,800));return response.json();}
|
||||
async upload(file){const body=new FormData();body.append('image',file,file.name);body.append('type','input');body.append('subfolder','DOGMA_API');body.append('overwrite','false');const r=await api.fetchApi('/upload/image',{method:'POST',body});if(!r.ok)throw new Error('Caricamento non riuscito.');const d=await r.json();return {file:[d.subfolder,d.name].filter(Boolean).join('/'),kind:file.type.startsWith('video/')?'video':'image'};}
|
||||
async workspace(path){return this.request('/workspace',{path});}
|
||||
async chooseFolder(){return {browse:true};}
|
||||
async mkdir(path,name){return this.request('/mkdir',{path,name});}
|
||||
async folders(path){return this.request('/folders?'+new URLSearchParams({path:path||''}));}
|
||||
async library(){return (await this.request('/library')).records;}
|
||||
async previewReference(ref,settings){return this.request('/reference-preview',{file:ref.file,settings});}
|
||||
async openOutput(id,index){return this.request('/open-output',{id,index});}
|
||||
async credits(){
|
||||
if(!this.billing||!this.formatCredits)return {text:'CREDITS —',title:'Saldo non disponibile. Apri l’account Comfy.'};
|
||||
try{await this.billing.fetchBalance();const raw=this.billing.balance,b=raw&&'value' in raw?raw.value:raw;const amount=b?.effectiveBalanceMicros??b?.amountMicros;if(!Number.isFinite(amount))return {text:'ACCEDI A COMFY',title:'Accedi all’account da Comfy per vedere i crediti.'};return {text:this.formatCredits({cents:amount,locale:'it-IT',numberOptions:{minimumFractionDigits:0,maximumFractionDigits:2}})+' CREDITS LEFT',title:'Saldo dello stesso account e workspace di Comfy'};}catch{return {text:'CREDITS —',title:'Saldo temporaneamente non disponibile. Clicca per aggiornare.'};}
|
||||
}
|
||||
inputSpec(state,f,key){const m=state.models[f.key],frames=m.engine==='frames';return inputSpec(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],frames?m.frames:m.parameters,key);}
|
||||
parameterSpecs(state,f){const m=state.models[f.key],frames=m.engine==='frames';return parameterSpecs(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],frames?m.frames:m.parameters);}
|
||||
changeModel(state,f){const m=state.models[f.key],frames=m.engine==='frames',key=frames?'frames':'parameters';m[key]=modelValues(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],m[key]);}
|
||||
price(state,f){
|
||||
if(!this.nativePricing||!this.defs)return '';
|
||||
const m=state.models[f.key],frames=f.key==='seedance'&&m.engine==='frames',type=frames?'ByteDance2FirstLastFrameNode':f.type,def=this.defs[type];if(!def)return '';
|
||||
let n=this.pricingNodes.get(type);if(!n){n={constructor:{nodeData:def},inputs:[],widgets:[],isInputConnected:i=>!!n.inputs[i]?.link};this.pricingNodes.set(type,n);}
|
||||
const refs=activeReferences(state),images=refs.filter(r=>r.kind==='image'),videos=refs.filter(r=>r.kind==='video');
|
||||
const values=frames?m.frames:m.parameters;n.widgets=Object.entries(values).map(([name,value])=>({name,value}));
|
||||
n.inputs=[];
|
||||
if(f.key==='nano'&&images.length)n.inputs.push({name:'images',link:1});
|
||||
else if(f.key==='seedance'&&frames){for(const r of images)n.inputs.push({name:r.role==='last'?'last_frame':'first_frame',link:1});}
|
||||
else if(f.key==='seedance'){images.forEach((r,i)=>n.inputs.push({name:`model.reference_images.image_${i+1}`,link:1}));videos.forEach((r,i)=>n.inputs.push({name:`model.reference_videos.video_${i+1}`,link:1}));}
|
||||
else images.forEach((r,i)=>n.inputs.push({name:`${f.key==='flux'?'':'model.'}images.image_${i+1}`,link:1}));
|
||||
try{return this.nativePricing.getNodeDisplayPrice(n,new Map(Object.entries(values)))||'';}catch{return '';}
|
||||
}
|
||||
async check(state,compiled){
|
||||
const types=[...new Set(Object.values(compiled.output).map(n=>n.class_type))];
|
||||
const available=await Promise.all(types.map(async type=>{const r=await api.fetchApi('/object_info/'+encodeURIComponent(type));return r.ok&&(await r.json())[type]?type:null;}));
|
||||
const missing=types.filter(t=>!available.includes(t));if(missing.length)throw new Error('Nodi mancanti: '+missing.join(', '));
|
||||
await Promise.all(activeReferences(state).flatMap(ref=>[ref.file,ref.process?.maskFile].filter(Boolean)).map(async file=>{const r=await fetch(this.view(file),{method:'HEAD'});if(!r.ok)throw new Error('Reference assente: '+file+'. Ricaricala dal pannello.');}));
|
||||
}
|
||||
async queue(compiled,batch,state){
|
||||
if(queueLock||app.processingQueue||app.queueItems?.length)throw new Error('Comfy sta già inviando una richiesta. Riprova tra un momento.');
|
||||
queueLock=true;let result=null,used=false;const workflow=copy(app.graph.serialize());workflow.extra ||= {};workflow.extra.dogma_api_batch={session:state.session,id:batch,jobs:copy(compiled.jobs)};
|
||||
const nativeBuild=app.graphToPrompt,nativeQueue=api.queuePrompt;
|
||||
const build=function(...args){if(used)return nativeBuild.apply(this,args);used=true;return Promise.resolve({workflow,output:compiled.output});};
|
||||
const capture=async function(...args){const r=await nativeQueue.apply(this,args);if(args[1]?.workflow===workflow)result=r;return r;};
|
||||
app.graphToPrompt=build;api.queuePrompt=capture;
|
||||
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();}
|
||||
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);}
|
||||
close(){opened=null;}
|
||||
}
|
||||
app.registerExtension({name:'DOGMA.APIPlatform.2',async beforeRegisterNodeDef(type,data){if(data.name!=='DOGMAAPIPlatformV1')return;const previous=type.prototype.onNodeCreated;type.prototype.onNodeCreated=function(...args){const result=previous?.apply(this,args),config=this.widgets?.find(w=>w.name==='config');if(config){config.type='hidden';config.computeSize=()=>[0,-4];}this.addWidget('button','APRI DOGMA / API PLATFORM',null,()=>{if(opened){opened.root?.focus();return;}try{opened=new PlatformUI(new ComfyBridge(this));opened.open().catch(e=>{opened?.close();opened=null;app.ui.dialog.show(e.message);});}catch(e){opened=null;app.ui.dialog.show(e.message);}},{serialize:false});this.size=[390,110];return result;};}});
|
||||
@@ -0,0 +1,49 @@
|
||||
import {copy} from './dogma_api_core.js?v=1.0.55';
|
||||
import {icon} from './dogma_api_icons.js?v=1.0.55';
|
||||
|
||||
export async function referenceEditor(ui,ref){
|
||||
const make=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
|
||||
const button=(text,fn,cls='dap-outline')=>{const b=make('button',text,cls);b.type='button';b.onclick=fn;return b;};
|
||||
const box=ui.modalBox('REFERENCE / CROP / MASK','dap-reference-modal'),layout=make('div','','dap-reference-layout'),left=make('div','','dap-reference-left'),right=make('div','','dap-reference-options');
|
||||
const tools=make('div','','dap-reference-tools'),stage=make('div','','dap-mask-stage'),base=make('canvas'),overlay=make('canvas');stage.append(base,overlay);left.append(tools,stage);
|
||||
const draft={enabled:true,mask:false,source:'paint',maskMode:'isolate',flip:false,invert:false,crop:false,resizeMpx:false,megapixels:1,expand:0,blur:0,fillHoles:true,targetWidth:0,targetHeight:0,segment:0,prompt:'',background:'#00ff00',...copy(ref.process||{})};
|
||||
layout.append(left,right);box.append(layout);
|
||||
const status=make('div','','dap-editor-status');left.append(status);
|
||||
let tool='brush',brush=40,down=null,maskChanged=false,previewFile=ref.processedPreview||null;const undo=[],fields=new Map();
|
||||
const mask=make('canvas'),mc=mask.getContext('2d',{willReadFrequently:true}),oc=overlay.getContext('2d',{willReadFrequently:true}),bc=base.getContext('2d',{willReadFrequently:true});
|
||||
const image=new Image();image.crossOrigin='anonymous';image.src=ref.preview||ui.bridge.view(ref.file);
|
||||
try{await image.decode();if(!box.isConnected)return;}catch{status.textContent='Reference assente. Sostituiscila per modificarla.';left.append(button('Sostituisci reference',()=>{box.close();ui.pickReferences(ref);}));return;}
|
||||
base.width=overlay.width=mask.width=image.naturalWidth;base.height=overlay.height=mask.height=image.naturalHeight;
|
||||
stage.style.width=`min(100%, ${55*image.naturalWidth/image.naturalHeight}vh)`;
|
||||
bc.drawImage(image,0,0);const source=bc.getImageData(0,0,base.width,base.height),initial=mc.createImageData(mask.width,mask.height);
|
||||
for(let i=0;i<source.data.length;i+=4){const value=255-source.data[i+3];initial.data[i]=initial.data[i+1]=initial.data[i+2]=255;initial.data[i+3]=value;source.data[i+3]=255;}bc.putImageData(source,0,0);mc.putImageData(initial,0,0);
|
||||
if(draft.maskFile){try{const saved=new Image();saved.crossOrigin='anonymous';saved.src=ui.bridge.view(draft.maskFile);await saved.decode();const temp=make('canvas');temp.width=mask.width;temp.height=mask.height;const ctx=temp.getContext('2d');ctx.drawImage(saved,0,0,mask.width,mask.height);const pixels=ctx.getImageData(0,0,mask.width,mask.height);for(let i=0;i<pixels.data.length;i+=4){pixels.data[i+3]=pixels.data[i];pixels.data[i]=pixels.data[i+1]=pixels.data[i+2]=255;}mc.putImageData(pixels,0,0);}catch{status.textContent='Maschera salvata non disponibile.';}}
|
||||
const draw=()=>{
|
||||
const pixels=mc.getImageData(0,0,mask.width,mask.height);for(let i=0;i<pixels.data.length;i+=4){pixels.data[i]=255;pixels.data[i+1]=100;pixels.data[i+2]=37;pixels.data[i+3]=Math.round((draft.invert?255-pixels.data[i+3]:pixels.data[i+3])*.5);}oc.putImageData(pixels,0,0);
|
||||
if(draft.cropRect&&draft.crop){const [x,y,w,h]=draft.cropRect;oc.strokeStyle='#fff';oc.lineWidth=Math.max(1,mask.width/700);oc.setLineDash([mask.width/100,mask.width/150]);oc.strokeRect(x*mask.width,y*mask.height,w*mask.width,h*mask.height);oc.setLineDash([]);}
|
||||
};
|
||||
const mark=()=>{previewFile=null;status.textContent='Impostazioni modificate · Anteprima per controllare il risultato.';draw();};
|
||||
const saveUndo=()=>{undo.push({pixels:mc.getImageData(0,0,mask.width,mask.height),rect:draft.cropRect?copy(draft.cropRect):null});if(undo.length>10)undo.shift();};
|
||||
const setTool=value=>{tool=value;for(const b of tools.querySelectorAll('[data-tool]'))b.classList.toggle('active',b.dataset.tool===value);overlay.style.cursor=value==='brush'||value==='erase'?'crosshair':'cell';};
|
||||
for(const [key,title] of [['brush','Pennello'],['erase','Gomma'],['crop','Crop rettangolare']]){const b=button(title,()=>setTool(key),'dap-editor-tool');b.dataset.tool=key;tools.append(b);}
|
||||
const size=make('input');size.type='range';size.min='2';size.max='180';size.value='40';size.setAttribute('aria-label','Dimensione pennello');size.oninput=()=>brush=Number(size.value);tools.append(size);
|
||||
tools.append(button('Undo',()=>{const previous=undo.pop();if(!previous)return;mc.putImageData(previous.pixels,0,0);draft.cropRect=previous.rect;maskChanged=true;mark();}),button('Pulisci',()=>{saveUndo();mc.clearRect(0,0,mask.width,mask.height);delete draft.cropRect;maskChanged=true;mark();}));
|
||||
const point=e=>{const r=overlay.getBoundingClientRect();return [Math.max(0,Math.min(mask.width,(e.clientX-r.left)*mask.width/r.width)),Math.max(0,Math.min(mask.height,(e.clientY-r.top)*mask.height/r.height))];};
|
||||
const stroke=(from,to)=>{mc.globalCompositeOperation=tool==='erase'?'destination-out':'source-over';mc.lineWidth=brush*mask.width/1000;mc.strokeStyle='#fff';mc.lineCap='round';mc.beginPath();mc.moveTo(...from);mc.lineTo(...to);mc.stroke();mc.globalCompositeOperation='source-over';maskChanged=true;draft.mask=true;draft.source='paint';if(fields.has('mask'))fields.get('mask').checked=true;if(fields.has('source'))fields.get('source').value='paint';};
|
||||
overlay.onpointerdown=e=>{saveUndo();down={first:point(e),last:point(e)};overlay.setPointerCapture(e.pointerId);if(tool!=='crop')stroke(down.first,[down.first[0]+.01,down.first[1]]);draw();};
|
||||
overlay.onpointermove=e=>{if(!down)return;const p=point(e);if(tool==='crop'){draft.crop=true;if(fields.has('crop'))fields.get('crop').checked=true;const x=Math.min(p[0],down.first[0]),y=Math.min(p[1],down.first[1]);draft.cropRect=[x/mask.width,y/mask.height,Math.abs(p[0]-down.first[0])/mask.width,Math.abs(p[1]-down.first[1])/mask.height];}else stroke(down.last,p);down.last=p;draw();};
|
||||
overlay.onpointerup=overlay.onpointercancel=()=>{if(down){down=null;mark();}};
|
||||
const field=(name,key,opts={})=>{const input=ui.field(right,name,draft[key],v=>{draft[key]=typeof draft[key]==='number'?Number(v):v;mark();},opts);fields.set(key,input);return input;};
|
||||
right.append(make('div','PREPARAZIONE REFERENCE','dap-label'));
|
||||
field('MASK', 'mask',{type:'checkbox'});field('MASK MODE','maskMode',{choices:['isolate','edit']});field('MASK SOURCE','source',{choices:['paint','prompt']});
|
||||
field('MASK PROMPT','prompt');field('SEGMENT','segment',{type:'number',min:0,max:100});field('INVERT MASK','invert',{type:'checkbox'});field('HORIZONTAL FLIP','flip',{type:'checkbox'});field('CROP','crop',{type:'checkbox'});
|
||||
field('EXPAND / PX','expand',{type:'number',min:-512,max:512});field('BLUR / PX','blur',{type:'number',min:0,max:128,step:.1});field('FILL HOLES','fillHoles',{type:'checkbox'});
|
||||
field('RESIZE TO MPX','resizeMpx',{type:'checkbox'});field('MEGAPIXELS','megapixels',{type:'number',min:.01,max:64,step:.1});field('CROP WIDTH','targetWidth',{type:'number',min:0,max:16384});field('CROP HEIGHT','targetHeight',{type:'number',min:0,max:16384});field('BACKGROUND','background',{type:'color'});
|
||||
right.append(make('p','Isolate mantiene l’area dipinta e colora il resto. Edit colora l’area dipinta. Crop usa il rettangolo o i bordi della maschera; dimensioni 0 mantengono il crop originale. Prompt usa il nodo SAM3 del workflow.','dap-field-hint'));
|
||||
const preview=make('img','','dap-reference-preview');preview.alt='Anteprima della reference preparata';preview.hidden=!previewFile;if(previewFile)preview.src=ui.bridge.view(previewFile);right.append(preview);
|
||||
async function uploadMask(){if(!maskChanged)return;const out=make('canvas');out.width=mask.width;out.height=mask.height;const ctx=out.getContext('2d'),pixels=mc.getImageData(0,0,mask.width,mask.height);for(let i=0;i<pixels.data.length;i+=4){const v=pixels.data[i+3];pixels.data[i]=pixels.data[i+1]=pixels.data[i+2]=v;pixels.data[i+3]=255;}ctx.putImageData(pixels,0,0);const blob=await new Promise(resolve=>out.toBlob(resolve,'image/png'));if(!blob)throw new Error('Maschera non esportata.');const result=await ui.bridge.upload(new File([blob],'DOGMA_mask_'+Date.now()+'.png',{type:'image/png'}));draft.maskFile=result.file;maskChanged=false;}
|
||||
const footer=make('div','','dap-reference-footer');
|
||||
const previewButton=button('Anteprima',async()=>{previewButton.disabled=true;try{await uploadMask();const result=await ui.bridge.previewReference(ref,draft);if(!box.isConnected)return;previewFile=result.file;preview.src=ui.bridge.view(previewFile);await preview.decode();preview.hidden=false;status.textContent=`${result.width} × ${result.height} · Anteprima aggiornata`;}catch(e){preview.hidden=true;status.textContent='Anteprima non disponibile: '+e.message;}finally{previewButton.disabled=false;}});
|
||||
footer.append(button('Sostituisci file',()=>{box.close();ui.pickReferences(ref);}),previewButton,button('Applica',async()=>{try{await uploadMask();ref.process=copy(draft);ref.process.enabled=true;ref.processedPreview=previewFile;ui.save();ui.renderRefs();ui.refreshPrices();box.close();ui.note('Preparazione reference salvata.');}catch(e){status.textContent=e.message;}},'dap-primary'));
|
||||
box.append(footer);setTool('brush');draw();
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,259 @@
|
||||
import {ALL_FAMILIES,copy,families,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName} from './dogma_api_core.js?v=1.0.55';
|
||||
import {icon} from './dogma_api_icons.js?v=1.0.55';
|
||||
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.55';
|
||||
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.55';
|
||||
|
||||
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;};
|
||||
export const ib=(name,label,fn,cls='')=>{const b=btn('',fn,'dap-icon-button '+cls,label);b.append(icon(name));return b;};
|
||||
const terminal=new Set(['completed','failed','cancelled','missing']);
|
||||
const enumValues={aspect_ratio:['auto','1:1','2:3','3:2','3:4','4:3','4:5','5:4','9:16','16:9','21:9'],resolution:['1K','2K','4K'],'model.background':['auto','opaque','transparent'],'model.quality':['low','medium','high'],'model.size':['auto','1024x1024','1536x1024','1024x1536','2048x2048','2048x1152','1152x2048','3840x2160','2160x3840','Custom'],'model.size_preset':['Custom'],'model.resolution':['480p','720p','1080p','4k'],'model.ratio':['adaptive','16:9','4:3','1:1','3:4','9:16','21:9'],'model.task_type':['reference','edit','extend','auto'],'model.output_format':['mp4'],response_modalities:['IMAGE','IMAGE+TEXT']};
|
||||
const displayName=k=>({'model.task_type':'TASK','model.generate_audio':'AUDIO','model.duration':'DURATION / SEC','model.auto_downscale':'AUTO DOWNSCALE','model.auto_upscale':'AUTO UPSCALE'})[k]||k.replace(/^model\./,'').replaceAll('_',' ').toUpperCase();
|
||||
export class PlatformUI {
|
||||
constructor(bridge){this.bridge=bridge;this.state=bridge.load();this.library=[];this.selection=[];this.cards=new Map();this.urls=new Set();this.closed=false;this.busy=false;}
|
||||
save(){if(!this.closed)this.bridge.save(this.state);}
|
||||
async open(){
|
||||
this.ready=false;
|
||||
this.root=el('dialog','','dap');this.root.setAttribute('aria-label','DOGMA API Platform');
|
||||
this.root.addEventListener('cancel',e=>{e.preventDefault();this.close();});
|
||||
this.root.addEventListener('dragover',e=>{if([...e.dataTransfer.types].includes('Files'))e.preventDefault();});
|
||||
this.root.addEventListener('drop',e=>{e.preventDefault();if(e.dataTransfer.files.length)this.addReferences([...e.dataTransfer.files]);});
|
||||
document.body.append(this.root);this.build();this.root.tabIndex=-1;this.root.showModal();this.root.focus({preventScroll:true});
|
||||
this.unsubscribe=this.bridge.subscribe?.((name,d)=>this.event(name,d));
|
||||
this.note('Apertura · Collegamento a Comfy…');
|
||||
await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
|
||||
try{await this.bridge.initialize?.(this.state);if(this.closed)return;this.ready=true;this.renderControls();this.updateHeader();this.refreshPrices();this.note(this.bridge.preview?'ANTEPRIMA · Nessuna richiesta API':'Pronto.');}catch(e){this.note('Collegamento non riuscito: '+e.message,true);}
|
||||
Promise.allSettled([this.recover(),this.refreshLibrary(),this.refreshCredits()]);
|
||||
this.timer=setInterval(()=>{this.updateCards();this.refreshPrices();if(this.state.results.some(r=>!terminal.has(r.status)))this.recover();},1800);
|
||||
this.creditTimer=setInterval(()=>this.refreshCredits(),30000);
|
||||
}
|
||||
close(){if(this.closed)return;this.save();this.closed=true;clearInterval(this.timer);clearInterval(this.creditTimer);this.unsubscribe?.();this.modal?.close();this.root.close();this.root.remove();for(const u of this.urls)URL.revokeObjectURL(u);this.bridge.close?.();}
|
||||
note(text,bad=false){if(!this.notice)return;this.notice.textContent=text;this.notice.classList.toggle('is-error',bad);}
|
||||
build(){
|
||||
const header=el('header','','dap-header'),brand=el('div','','dap-brand'),logo=el('img');logo.src=this.bridge.logo();logo.alt='DOGMA';brand.append(logo,el('span','API Platform'));
|
||||
const actions=el('div','','dap-actions');this.credit=btn('CREDITS —',()=>this.refreshCredits(),'dap-credit','Aggiorna crediti');
|
||||
this.runButton=btn('',()=>this.run(),'dap-run','Avvia generazioni in parallelo');this.runLabel=el('span','Run');this.runButton.append(this.runLabel,icon('play'));
|
||||
this.stopButton=btn('■ Stop',()=>this.stop(),'dap-stop','Ferma le generazioni DOGMA');this.stopButton.disabled=true;
|
||||
actions.append(this.stopButton,this.credit,ib('download','Salva sessione e workflow',()=>this.bridge.download(this.state)),ib('close','Torna a Comfy',()=>this.close()),this.runButton);header.append(brand,actions);
|
||||
const layout=el('div','','dap-layout');this.side=el('aside','','dap-side');const tabs=el('nav','','dap-tabs');
|
||||
this.imageTab=btn('',()=>this.switchMode('image'),'','Image');this.imageTab.append(icon('image'),el('span','Image'));this.videoTab=btn('',()=>this.switchMode('video'),'','Video');this.videoTab.append(icon('video'),el('span','Video'));tabs.append(this.imageTab,this.videoTab);
|
||||
this.editRow=el('div','','dap-edit-mode');this.editRow.append(this.toggle('Image Edit',this.state.imageEdit,v=>{this.state.imageEdit=v;this.save();}),el('span','Image Edit'),el('small','Image 1 → compare'));
|
||||
this.controls=el('div','','dap-controls');this.side.append(tabs,this.editRow,this.controls);
|
||||
const main=el('main','','dap-main'),toolbar=el('div','','dap-toolbar');this.context=btn('',()=>this.folderBrowser(false),'dap-project','Apri cartella di lavoro');
|
||||
const views=el('div','','dap-views');this.ab=ib('compare','Confronta due risultati',()=>this.compare());
|
||||
const slider=this.slider=el('input');slider.type='range';slider.min='0';slider.max='100';slider.step='any';slider.value=String(this.state.density);slider.setAttribute('aria-label','Dimensione delle immagini');
|
||||
slider.oninput=()=>{this.state.density=Number(slider.value);this.applyDensity();this.save();};
|
||||
views.append(this.ab,ib('single','Una immagine grande',()=>{slider.value='0';slider.oninput();}),slider,ib('grid','Griglia compatta',()=>{slider.value='100';slider.oninput();}));toolbar.append(this.context,views);
|
||||
this.filters=el('div','','dap-filters');this.notice=el('div','','dap-notice');this.notice.setAttribute('role','status');
|
||||
this.galleryViewport=el('div','','dap-gallery-viewport');this.gallery=el('div','','dap-gallery');this.galleryViewport.append(this.gallery);
|
||||
this.totalProgress=el('div','','dap-total-progress');this.totalBar=el('div','','dap-progress-track');this.totalFill=el('i');this.totalBar.append(this.totalFill);this.totalText=el('span');this.totalProgress.append(this.totalBar,this.totalText);this.totalProgress.hidden=true;main.append(toolbar,this.filters,this.totalProgress,this.notice,this.galleryViewport);layout.append(this.side,main);this.root.append(header,layout);
|
||||
this.renderControls();this.renderFilters();this.renderGallery();this.updateHeader();this.applyDensity();
|
||||
this.resize=new ResizeObserver(()=>this.applyDensity());this.resize.observe(this.galleryViewport);this.root.addEventListener('close',()=>this.resize.disconnect(),{once:true});
|
||||
this.note(this.bridge.preview?'ANTEPRIMA · Immagini dal tuo design · Nessuna richiesta API':'Reference, parametri e cartella pronti.');
|
||||
}
|
||||
applyDensity(){if(!this.gallery)return;const columns=1+3*Number(this.state.density)/100,width=(this.galleryViewport.clientWidth||1400)/columns;this.gallery.style.setProperty('--card-min',Math.max(170,width-18)+'px');this.slider.title=`Dimensione galleria / ${Math.round(width)} px`;}
|
||||
updateHeader(){const s=this.state;this.context.textContent=[s.workspace||this.bridge.catalog?.access?.output_root||'Comfy output / DOGMA / API',safeName(s.project),safeName(s.scene)].filter(Boolean).join(' / ');this.context.title=this.context.textContent;this.imageTab.classList.toggle('active',s.mode==='image');this.videoTab.classList.toggle('active',s.mode==='video');this.editRow.hidden=s.mode==='video';let n=0;try{n=plannedJobs(s).length;}catch{}this.runLabel.textContent=this.busy?'Invio…':`Run${n?' / '+n:''}`;this.runButton.disabled=this.busy||!n||!this.ready;this.updateProgress();this.runButton.title=`${n} generazioni API indipendenti, in parallelo`;}
|
||||
switchMode(mode){this.state.mode=mode;this.save();this.renderControls();this.updateHeader();this.refreshPrices();}
|
||||
toggle(label,checked,onchange){const b=btn('',()=>{checked=!checked;b.classList.toggle('on',checked);b.setAttribute('aria-checked',String(checked));onchange(checked);},'dap-toggle'+(checked?' on':''),label);b.setAttribute('role','switch');b.setAttribute('aria-checked',String(checked));const knob=el('span','','dap-toggle-knob');knob.append(icon('lines'));b.append(knob);return b;}
|
||||
field(parent,name,value,onchange,opts={}){
|
||||
const row=el('label','','dap-field');row.append(el('span',name));let input;
|
||||
if(opts.choices){input=el('select');for(const choice of [...new Set([...opts.choices.map(String),...(!opts.choices.map(String).includes(String(value))?[String(value)]:[])])]){const o=el('option',choice);o.value=choice;input.append(o);}input.value=String(value);row.classList.add('has-select');}
|
||||
else{input=el('input');input.type=opts.type||'text';if(input.type==='checkbox')input.checked=!!value;else input.value=String(value??'');}
|
||||
input.setAttribute('aria-label',name);if(opts.min!==undefined)input.min=String(opts.min);if(opts.max!==undefined)input.max=String(opts.max);if(opts.step!==undefined)input.step=String(opts.step);if(opts.placeholder)input.placeholder=opts.placeholder;if(opts.readonly)input.readOnly=true;
|
||||
input.onchange=()=>onchange(input.type==='checkbox'?input.checked:input.value);row.append(input);
|
||||
if(input.tagName==='INPUT'&&['text','number','color'].includes(input.type)&&!opts.readonly)input.oninput=()=>input.onchange();
|
||||
if(!opts.readonly&&(opts.choices||opts.type==='number')){
|
||||
const step=direction=>{if(opts.choices){input.selectedIndex=(input.selectedIndex+direction+input.options.length)%input.options.length;}else{const next=Number(input.value||0)+direction*Number(opts.step||1);input.value=String(Math.min(opts.max??Infinity,Math.max(opts.min??-Infinity,next)));}input.onchange();};
|
||||
const previous=ib('arrow','Riduci / precedente '+name,e=>step(-1),'dap-field-step'),next=ib('arrow','Aumenta / successivo '+name,e=>step(1),'dap-field-step next');
|
||||
previous.addEventListener('click',e=>e.preventDefault());next.addEventListener('click',e=>e.preventDefault());row.prepend(previous);row.append(next);
|
||||
}
|
||||
parent.append(row);return input;
|
||||
}
|
||||
renderControls(){
|
||||
const c=this.controls,s=this.state;c.replaceChildren();
|
||||
const refs=el('section','','dap-section');refs.append(el('div','REFERENCES','dap-label'));this.refs=el('div','','dap-refs');refs.append(this.refs);this.renderRefs();
|
||||
const prompt=el('section','','dap-section dap-prompt');prompt.append(el('div','PROMPT','dap-label'));const wrap=el('div','','dap-prompt-wrap'),area=el('textarea');area.value=s.prompts[s.mode]||'';area.setAttribute('aria-label','Prompt');area.placeholder='Scrivi il prompt…';area.oninput=()=>{s.prompts[s.mode]=area.value;this.save();};
|
||||
const resize=el('div','','dap-resize-handle');resize.title='Trascina per ingrandire il prompt';let start=null;
|
||||
resize.onpointerdown=e=>{e.preventDefault();start={y:e.clientY,height:area.offsetHeight};resize.setPointerCapture(e.pointerId);};resize.onpointermove=e=>{if(start)area.style.height=Math.max(90,start.height+e.clientY-start.y)+'px';};resize.onpointerup=resize.onpointercancel=()=>start=null;wrap.append(area,resize);prompt.append(wrap);
|
||||
const workSection=el('details','','dap-section dap-work');workSection.open=!!s.workExpanded;workSection.ontoggle=()=>{s.workExpanded=workSection.open;this.save();};const workTitle=el('summary','FILENAME / WORKSPACE','dap-label');workTitle.append(icon('chevron'));const work=el('div');workSection.append(workTitle,work);
|
||||
this.field(work,'FILENAME',s.filename,v=>{s.filename=v;this.save();this.namePreview.textContent=this.filenamePreview();},{placeholder:'DOGMA'});
|
||||
this.field(work,'PROJECT',s.project,v=>{s.project=v;this.save();this.updateHeader();this.namePreview.textContent=this.filenamePreview();},{placeholder:'Facoltativo'});
|
||||
this.field(work,'SCENE',s.scene,v=>{s.scene=v;this.save();this.updateHeader();this.namePreview.textContent=this.filenamePreview();},{placeholder:'Facoltativo'});
|
||||
const date=el('div','','dap-date-row'),datePicker=el('input');datePicker.type='date';const code=s.date||todayCode();datePicker.value=`20${code.slice(4,6)}-${code.slice(2,4)}-${code.slice(0,2)}`;datePicker.setAttribute('aria-label','Data del filename');datePicker.onchange=()=>{const [year,month,day]=datePicker.value.split('-');if(!year)return;s.date=day+month+year.slice(-2);s.dateMode='manual';this.save();this.namePreview.textContent=this.filenamePreview();};date.append(this.toggle('Aggiungi data al filename',s.appendDate,v=>{s.appendDate=v;s.date ||= todayCode();this.save();this.namePreview.textContent=this.filenamePreview();}),el('span','Aggiungi data'),datePicker);work.append(date);
|
||||
const choose=ib('folder','Scegli cartella di lavoro',()=>this.chooseWorkspace(),'dap-workspace-button');choose.append(el('span',s.workspace||'Scegli cartella di lavoro'));work.append(choose);
|
||||
this.namePreview=el('div',this.filenamePreview(),'dap-filename-preview');work.append(this.namePreview);
|
||||
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);}
|
||||
c.append(refs,prompt,workSection,models);
|
||||
}
|
||||
filenamePreview(){return [...titleParts(this.state),'MODEL',this.state.mode==='video'?'00001.mp4':'00001.png'].filter(Boolean).join('_');}
|
||||
renderRefs(){
|
||||
if(!this.refs)return;this.refs.replaceChildren();
|
||||
const visible=visibleReferences(this.state);
|
||||
visible.forEach((r,i)=>{
|
||||
const tile=el('article','','dap-ref');tile.classList.toggle('disabled',!r.enabled);tile.dataset.ref=String(i);
|
||||
const media=el(r.kind==='video'?'video':'img');media.src=r.processedPreview?this.bridge.view(r.processedPreview):r.preview||this.bridge.view(r.file);media.draggable=false;if(r.kind==='video'){media.muted=true;media.preload='metadata';media.onpointerenter=()=>media.play().catch(()=>{});media.onpointerleave=()=>media.pause();}else media.alt=`Image ${i+1}`;
|
||||
media.onclick=()=>r.kind==='video'?this.referenceVideo(r):referenceEditor(this,r);
|
||||
media.onerror=()=>tile.classList.add('missing');
|
||||
const tools=el('div','','dap-ref-tools');tools.append(this.toggle(`Attiva reference ${i+1}`,r.enabled,v=>{r.enabled=v;this.save();this.renderRefs();this.refreshPrices();}));
|
||||
if(r.kind==='image')tools.append(ib('edit',`Modifica reference ${i+1}`,()=>referenceEditor(this,r)));
|
||||
else tools.append(ib('play',`Apri video reference ${i+1}`,()=>this.referenceVideo(r)));
|
||||
if(i>0)tools.append(ib('arrow',`Sposta prima reference ${i+1}`,()=>{const a=this.state.references.indexOf(visible[i-1]),b=this.state.references.indexOf(r);[this.state.references[a],this.state.references[b]]=[r,visible[i-1]];this.save();this.renderRefs();}));
|
||||
tools.append(ib('close',`Rimuovi reference ${i+1}`,()=>{this.state.references.splice(this.state.references.indexOf(r),1);this.save();this.renderRefs();this.refreshPrices();}));
|
||||
tile.append(media,el('span',`${String(i+1).padStart(2,'0')} / ${r.kind==='video'?'VIDEO':'IMAGE'}`,'dap-ref-order'),tools);
|
||||
if(r.process?.enabled)tile.append(el('span','EDIT','dap-ref-edited'));
|
||||
if(this.state.mode==='video'&&this.state.models.seedance.engine==='frames'&&r.kind==='image'){
|
||||
const select=el('select','','dap-ref-role');select.setAttribute('aria-label',`Ruolo reference ${i+1}`);for(const [key,text] of [['first','First frame'],['last','Last frame']]){const o=el('option',text);o.value=key;select.append(o);}select.value=r.role||'reference';select.onchange=()=>{r.role=select.value;this.save();};tile.append(select);
|
||||
}
|
||||
this.refs.append(tile);
|
||||
});
|
||||
const frames=this.state.mode==='video'&&this.state.models.seedance.engine==='frames',mixed=this.state.mode==='video'&&!frames;const add=ib('plus',mixed?'Aggiungi immagini o video':'Aggiungi immagine',()=>this.pickReferences(),'dap-add');add.append(el('span',mixed?'Immagini / Video':frames?'First / Last frame':'Immagini'));if(!frames||visible.length<2)this.refs.append(add);
|
||||
}
|
||||
pickReferences(replace=null){const i=el('input');i.type='file';i.accept=this.state.mode==='video'&&this.state.models.seedance.engine!=='frames'?'image/*,video/*':'image/*';i.multiple=!replace;i.hidden=true;this.root.append(i);i.onchange=()=>{this.addReferences([...i.files],replace);i.remove();};i.addEventListener('cancel',()=>i.remove(),{once:true});i.click();}
|
||||
async addReferences(files,replace=null){try{this.note('Caricamento reference…');for(const file of files){if(!/^(image|video)\//.test(file.type))throw new Error('Scegli immagini o video.');const frames=this.state.mode==='video'&&this.state.models.seedance.engine==='frames';if(file.type.startsWith('video/')&&(this.state.mode==='image'||frames))throw new Error('In questa modalità puoi caricare solo immagini.');if(frames&&!replace&&visibleReferences(this.state).length>=2)throw new Error('First / Last frame accetta due immagini.');const uploaded=await this.bridge.upload(file);if(this.closed)return;const r={...uploaded,enabled:true,modes:[this.state.mode],role:frames?(replace?.role|| (visibleReferences(this.state).some(r=>r.role==='first')?'last':'first')):'reference',process:{enabled:false,mask:false,maskMode:'isolate',source:'paint',flip:false,invert:false,crop:false,fillHoles:true,expand:0,blur:0,targetWidth:0,targetHeight:0,background:'#00ff00'}};if(replace){const at=this.state.references.indexOf(replace);this.state.references.splice(at,1,r);}else this.state.references.push(r);}this.save();this.renderRefs();this.refreshPrices();this.note('Reference aggiornate. L’ordine è quello mostrato.');}catch(e){this.note(e.message,true);}}
|
||||
referenceVideo(ref){openViewer(this,{job:{kind:'video',label:ref.file,study:true},file:{url:ref.preview||this.bridge.view(ref.file)},index:0});}
|
||||
model(f){
|
||||
const m=this.state.models[f.key],wrap=el('div','','dap-model'),row=el('div','','dap-model-head');wrap.setAttribute('role','group');wrap.setAttribute('aria-label',f.name);
|
||||
const toggle=this.toggle(`Attiva ${f.name}`,m.enabled,v=>{m.enabled=v;wrap.classList.toggle('enabled',v);this.save();this.updateHeader();});wrap.classList.toggle('enabled',m.enabled);
|
||||
const details=el('details');details.open=!!m.expanded;details.ontoggle=()=>{m.expanded=details.open;this.save();};
|
||||
const summary=el('summary');this.priceLabels ||= new Map();const price=el('small','— CREDITS / '+(f.key==='seedance'?'RUN':'IMAGE'));this.priceLabels.set(f.key,price);summary.append(el('span',f.name),price,icon('chevron'));details.append(summary);
|
||||
const body=el('div','','dap-model-body');
|
||||
this.field(body,'QUANTITY',m.quantity,v=>{m.quantity=Number(v);this.save();this.updateHeader();},{type:'number',min:1,max:64});
|
||||
body.append(el('div','Richieste in parallelo · Seed diversi','dap-field-hint'));
|
||||
|
||||
const values=m.engine==='frames'?m.frames:m.parameters;
|
||||
const nativeSpecs=this.bridge.parameterSpecs?.(this.state,f);const entries=nativeSpecs&&Object.keys(nativeSpecs).length?Object.keys(nativeSpecs).map(key=>[key,values[key]??nativeSpecs[key][1]?.default??choicesFor(nativeSpecs[key])?.[0]??'']):Object.entries(values);
|
||||
for(const [key,value] of entries){
|
||||
if(['prompt','model.prompt','system_prompt','seed','model.seed','n'].includes(key)||key.startsWith('control_after_generate')||key.endsWith('asset_id'))continue;
|
||||
const opts={};if(enumValues[key])opts.choices=enumValues[key];
|
||||
if(key==='model'){if(f.key==='nano')opts.choices=['gemini-3-pro-image-preview','Nano Banana 2 (Gemini 3.1 Flash Image)'];else opts.readonly=true;}
|
||||
if(key==='resolution'&&f.key==='flux')opts.choices=['0.75K','1K','1.5K','2K','4K'];
|
||||
if(typeof value==='boolean')opts.type='checkbox';if(typeof value==='number'){opts.type='number';opts.min=key==='model.duration'?4:0;opts.max=key==='model.duration'?30:8594;}
|
||||
const spec=this.bridge.inputSpec?.(this.state,f,key);
|
||||
if(spec){const info=spec[1]||{};if(Array.isArray(spec[0]))opts.choices=spec[0];else if(choicesFor(spec))opts.choices=choicesFor(spec);if(info.min!==undefined)opts.min=info.min;if(info.max!==undefined)opts.max=info.max;if(info.step!==undefined)opts.step=info.step;}
|
||||
if(opts.choices){opts.choices=sortedChoices(key,opts.choices);delete opts.readonly;}
|
||||
this.field(body,displayName(key),value,v=>{values[key]=typeof value==='boolean'?v:typeof value==='number'?Number(v):v;if(key==='model'){this.bridge.changeModel?.(this.state,f);this.renderControls();}this.save();this.refreshPrices();},opts);
|
||||
}
|
||||
if(values.system_prompt!==undefined){const advanced=el('details','','dap-advanced');advanced.append(el('summary','SYSTEM PROMPT'));const text=el('textarea');text.value=values.system_prompt;text.setAttribute('aria-label',f.name+' system prompt');text.oninput=()=>{values.system_prompt=text.value;this.save();};advanced.append(text);body.append(advanced);}
|
||||
if(f.key==='seedance')body.append(el('div',m.engine==='frames'?'Usa un First frame, un Last frame o entrambi. Sono accettate soltanto immagini.':'Usa immagini o video come reference. In Edit la durata segue il video sorgente.','dap-field-hint'));
|
||||
details.append(body);row.append(toggle,details);wrap.append(row);return wrap;
|
||||
}
|
||||
async refreshCredits(){if(this.creditBusy||this.closed)return;this.creditBusy=true;try{const result=await this.bridge.credits();if(!this.closed){this.credit.textContent=result.text;this.credit.title=result.title;}}catch{}finally{this.creditBusy=false;}}
|
||||
refreshPrices(){if(this.closed)return;for(const f of families(this.state)){const text=this.bridge.price?.(this.state,f);const node=this.priceLabels?.get(f.key);if(node&&text){node.textContent=text;node.title='Stima calcolata dalle stesse regole di Comfy per questi parametri';}}}
|
||||
allResults(){const map=new Map;for(const r of [...this.library,...this.state.results])map.set(r.id,r);return [...map.values()].sort((a,b)=>(b.started||b.finished||0)-(a.started||a.finished||0));}
|
||||
renderFilters(){
|
||||
if(!this.filters)return;const s=this.state,all=this.allResults();this.filters.replaceChildren();
|
||||
const model=el('details','','dap-filter-models');const summary=el('summary');summary.append(icon('filter'),el('span',s.filters.models.length?s.filters.models.map(k=>ALL_FAMILIES.find(f=>f.key===k)?.name||k).join(', '):'Tutti i modelli'),icon('chevron'));const menu=el('div','','dap-filter-menu');
|
||||
const any=btn('Tutti i modelli',()=>{s.filters.models=[];this.save();this.renderFilters();this.renderGallery();});menu.append(any);
|
||||
for(const f of ALL_FAMILIES){const item=el('label'),check=el('input');check.type='checkbox';check.checked=s.filters.models.includes(f.key);check.onchange=()=>{s.filters.models=check.checked?[...s.filters.models,f.key]:s.filters.models.filter(k=>k!==f.key);this.save();this.renderGallery();summary.querySelector('span').textContent=s.filters.models.length?s.filters.models.map(k=>ALL_FAMILIES.find(f=>f.key===k)?.name).join(', '):'Tutti i modelli';};item.append(check,el('span',f.name));menu.append(item);}model.append(summary,menu);this.filters.append(model);
|
||||
const select=(name,current,choices,change)=>{const box=el('label','','dap-filter');box.append(el('span',name));const input=el('select');input.setAttribute('aria-label',name);for(const [value,text] of choices){const option=el('option',text);option.value=value;input.append(option);}input.value=current;input.onchange=()=>{change(input.value);this.save();this.renderFilters();this.renderGallery();};box.append(input,icon('chevron'));this.filters.append(box);};
|
||||
const projects=[...new Set(all.map(r=>r.project||''))].sort();select('Progetto',s.filters.project,[['*','Tutti i progetti'],...projects.map(p=>[p,p||'Senza progetto'])],v=>{s.filters.project=v;s.filters.scene='*';});
|
||||
const scenes=[...new Set(all.filter(r=>s.filters.project==='*'||(r.project||'')===s.filters.project).map(r=>r.scene||''))].sort();select('Scena',s.filters.scene,[['*','Tutte le scene'],...scenes.map(v=>[v,v||'Senza scena'])],v=>s.filters.scene=v);
|
||||
select('Output',s.filters.kind,[['all','Immagini e video'],['image','Immagini'],['video','Video']],v=>s.filters.kind=v);
|
||||
const ws=[...new Set(all.map(r=>r.workspace||''))];if(ws.length>1)select('Cartella',s.filters.workspace,[['*','Tutte le cartelle'],...ws.map(v=>[v,v.split(/[\\/]/).filter(Boolean).at(-1)||'Comfy output'])],v=>s.filters.workspace=v);
|
||||
this.filters.append(ib('refresh','Aggiorna libreria',()=>this.refreshLibrary()));
|
||||
}
|
||||
renderGallery(){
|
||||
const scroll=this.galleryViewport?.scrollTop||0;this.gallery.replaceChildren();this.cards.clear();const list=filterResults(this.allResults(),this.state.filters);
|
||||
if(!list.length){const empty=el('div','','dap-empty');empty.append(el('span','DOGMA / OUTPUT'),el('h2',this.allResults().length?'Nessun risultato con questi filtri.':'Pronto per il prossimo frame.'),el('p',this.allResults().length?'Cambia progetto, scena o modelli per vedere gli altri output.':'Scegli i modelli e la quantità. Run avvia le richieste API in parallelo.'));this.gallery.append(empty);return;}
|
||||
for(const job of list){const files=job.images?.length?job.images:[null];files.forEach((file,i)=>this.gallery.append(this.card(job,file,i)));}
|
||||
this.updateCards();this.galleryViewport.scrollTop=scroll;this.applyDensity();
|
||||
}
|
||||
card(job,file,index){
|
||||
const card=el('article','','dap-card');card.dataset.job=job.id;const f=ALL_FAMILIES.find(f=>f.key===job.family),title=job.label||f?.name||'Output';
|
||||
if(file){
|
||||
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;media.append(video);media.onpointerenter=()=>video.play().catch(()=>{});media.onpointerleave=()=>video.pause();media.append(icon('play'));}
|
||||
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.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);
|
||||
const tools=el('div','','dap-card-tools'),item={id:job.id+':'+index,job,file,index};
|
||||
const select=ib('compare','Seleziona per confronto A/B',()=>{const at=this.selection.findIndex(x=>x.id===item.id);if(at>=0){this.selection.splice(at,1);select.classList.remove('selected');}else if(this.selection.length<2){this.selection.push(item);select.classList.add('selected');}this.ab.classList.toggle('active',this.selection.length===2);this.note(`${this.selection.length}/2 risultati selezionati per A/B.`);});
|
||||
tools.append(select,ib('plus','Usa come reference',()=>this.reuse(file,job.kind)),ib('download','Scarica file',()=>this.downloadImage(file)));card.append(tools);
|
||||
if(job.study)card.append(el('span','DESIGN REFERENCE','dap-study'));
|
||||
}else{card.classList.add('pending');const spinner=el('div','','dap-spinner');for(let i=0;i<16;i++){const dot=el('i');dot.style.setProperty('--i',i);spinner.append(dot);}const track=el('div','','dap-progress-track dap-card-progress');track.append(el('i'));card.append(spinner,el('span','','dap-job-state'),track);}
|
||||
const footer=el('footer','','dap-card-footer');footer.append(el('span',title+(job.index!==undefined?' / '+(job.index+1):'')),el('span','','dap-elapsed'));card.append(footer);
|
||||
const tags=[job.project,job.scene].filter(Boolean);if(tags.length)card.append(el('div',tags.join(' / '),'dap-card-tags'));
|
||||
if(job.warning||job.error)card.append(el('p',job.warning||job.error,'dap-card-error'));
|
||||
if(!this.cards.has(job.id))this.cards.set(job.id,[]);this.cards.get(job.id).push(card);return card;
|
||||
}
|
||||
updateCards(){this.updateProgress();for(const job of this.allResults())for(const card of this.cards.get(job.id)||[]){const bar=card.querySelector('.dap-card-progress>i');if(bar){const p=this.jobProgress(job);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 di Comfy',running:'Generazione API',failed:'Errore',cancelled:'Interrotta'})[job.status]||job.status;card.classList.toggle('stopped',terminal.has(job.status));const elapsed=card.querySelector('.dap-elapsed');elapsed.textContent=job.study?'LAYOUT':job.started?Math.floor(((job.finished||Date.now())-job.started)/1000)+'s':'';if(job.error&&!card.querySelector('.dap-card-error'))card.append(el('p',job.error,'dap-card-error'));}}
|
||||
modalBox(title,cls=''){
|
||||
this.modal?.close();const dialog=this.modal=el('dialog','','dap-modal '+cls);dialog.setAttribute('aria-label',title);const header=el('header');header.append(el('span',title),ib('close','Chiudi',()=>dialog.close()));dialog.append(header);this.root.append(dialog);
|
||||
let down=false;dialog.addEventListener('pointerdown',e=>down=e.target===dialog);dialog.addEventListener('click',e=>{if(down&&e.target===dialog)dialog.close();down=false;});
|
||||
dialog.addEventListener('cancel',e=>e.stopPropagation());dialog.addEventListener('keydown',e=>{if(e.key==='Escape'){e.preventDefault();e.stopPropagation();dialog.close();}});dialog.addEventListener('close',()=>{dialog.remove();if(this.modal===dialog)this.modal=null;});dialog.tabIndex=-1;dialog.showModal();dialog.focus({preventScroll:true});return dialog;
|
||||
}
|
||||
compare(){if(this.selection.length!==2){this.note('Seleziona due immagini con il bottone A/B sulle miniature.');return;}if(this.selection.some(x=>x.job.kind==='video')){this.note('Il confronto A/B è disponibile per le immagini.');return;}openViewer(this,this.selection[0],this.selection[1]);}
|
||||
async openOutput(job,index){try{const target=await this.bridge.openOutput(job.id,index);await this.folderBrowser(false,target.path,target.filename);}catch(e){this.note(e.message,true);if(this.modal)this.modal.append(el('p',e.message,'dap-operation-note'));}}
|
||||
async downloadImage(file){try{const r=await fetch(this.bridge.view(file));if(!r.ok)throw new Error('File non disponibile.');const url=URL.createObjectURL(await r.blob());this.urls.add(url);const a=el('a');a.href=url;a.download=file.filename||'DOGMA_output';a.click();}catch(e){this.note(e.message,true);}}
|
||||
async reuse(file,kind){try{const r=await fetch(this.bridge.view(file));if(!r.ok)throw new Error('File non disponibile.');const blob=await r.blob();await this.addReferences([new File([blob],file.filename||'DOGMA_reference.png',{type:blob.type|| (kind==='video'?'video/mp4':'image/png')})]);}catch(e){this.note(e.message,true);}}
|
||||
async chooseWorkspace(){return this.folderBrowser(true);}
|
||||
async folderBrowser(choose=true,initial=null,selected=''){
|
||||
const box=this.modalBox(choose?'SCEGLI CARTELLA DI LAVORO':'CARTELLA / FILE','dap-folder-modal'),bar=el('div','','dap-folder-navigation'),address=el('input'),list=el('div','','dap-folder-list'),footer=el('div','','dap-folder-footer'),error=el('p','','dap-operation-note');address.setAttribute('aria-label','Percorso cartella');bar.append(address,btn('Apri',()=>render(address.value),'dap-outline'));box.append(bar,list,error,footer);
|
||||
const render=async path=>{list.replaceChildren(el('p','Caricamento cartella…'));error.textContent='';try{const data=await this.bridge.folders(path);if(!box.isConnected)return;address.value=data.path;list.replaceChildren();footer.replaceChildren();
|
||||
if(data.parent)list.append(btn('↑ Cartella superiore',()=>render(data.parent),'dap-outline'));
|
||||
for(const root of data.roots||[]){const b=ib('folder',root.name,()=>render(root.path));b.append(el('span',root.name));list.append(b);}
|
||||
for(const dir of data.directories){const b=ib('folder',dir.name,()=>render(dir.path));b.append(el('span',dir.name));list.append(b);}
|
||||
for(const file of data.files||[]){const row=el('div',file.name,'dap-folder-file'+(file.name===selected?' selected':''));if(file.name===selected)row.setAttribute('aria-current','true');list.append(row);}
|
||||
const name=el('input');name.placeholder='Nome nuova cartella';name.setAttribute('aria-label','Nome nuova cartella');footer.append(name,btn('Crea cartella',async()=>{try{const d=await this.bridge.mkdir(data.path,name.value);await render(d.path);}catch(e){error.textContent=e.message;}},'dap-outline'));
|
||||
if(choose)footer.append(btn('Usa questa cartella',async()=>{try{const result=await this.bridge.workspace(data.path);this.state.workspace=result.path;for(const record of result.records||[]){const existing=this.state.results.find(j=>j.id===record.id);if(existing)Object.assign(existing,record);}this.library=[...this.library.filter(r=>!(result.records||[]).some(x=>x.id===r.id)),...(result.records||[])];this.save();this.renderFilters();this.renderGallery();box.close();this.renderControls();this.updateHeader();this.note('Cartella di lavoro selezionata.');}catch(e){error.textContent=e.message;}},'dap-primary'));
|
||||
list.querySelector('[aria-current]')?.scrollIntoView({block:'center'});
|
||||
}catch(e){list.replaceChildren();error.textContent=e.message;}};address.onkeydown=e=>{if(e.key==='Enter')render(address.value);};await render(initial??this.state.workspace);
|
||||
}
|
||||
jobProgress(job){
|
||||
if(terminal.has(job.status))return {percent:100,label:job.status,remaining:0};
|
||||
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};
|
||||
const expected=samples.reduce((a,b)=>a+b,0)/samples.length,elapsed=(Date.now()-job.started)/1000;
|
||||
return {percent:Math.min(94,100*elapsed/expected),remaining:Math.max(0,Math.round(expected-elapsed)),label:elapsed<expected?'~'+Math.round(expected-elapsed)+'s rimanenti · stima':'Finalizzazione · stima superata'};
|
||||
}
|
||||
updateProgress(){
|
||||
if(!this.totalProgress)return;const jobs=this.state.results.filter(j=>!terminal.has(j.status)),ids=new Set(jobs.map(j=>j.batch));const batch=this.state.results.filter(j=>ids.has(j.batch));
|
||||
this.stopButton.disabled=!jobs.length&&!this.busy;this.totalProgress.hidden=!jobs.length;if(!jobs.length)return;
|
||||
const points=batch.map(j=>this.jobProgress(j));this.totalFill.style.width=points.reduce((s,p)=>s+p.percent,0)/points.length+'%';this.totalBar.classList.toggle('indeterminate',points.some(p=>p.indeterminate));
|
||||
const known=jobs.map(j=>this.jobProgress(j).remaining);this.totalText.textContent=`${batch.filter(j=>terminal.has(j.status)).length} / ${batch.length} completate · `+(known.every(n=>n!==null)?`~${Math.max(...known)}s rimanenti · stima`:'Calcolo in corso · tempo residuo non ancora disponibile');
|
||||
}
|
||||
async stop(){
|
||||
this.stopRequested=true;const jobs=this.state.results.filter(j=>!terminal.has(j.status));const ids=[...new Set(jobs.map(j=>j.promptId).filter(Boolean))];this.stopButton.disabled=true;this.note('Interruzione richiesta…');
|
||||
const results=await Promise.allSettled(ids.map(id=>this.bridge.cancel(id)));for(let i=0;i<ids.length;i++)if(results[i].status==='fulfilled')for(const job of jobs.filter(j=>j.promptId===ids[i]))if(!terminal.has(job.status)){job.status='cancelled';job.finished=Date.now();}
|
||||
this.save();this.updateCards();this.note(results.some(r=>r.status==='rejected')?'Una richiesta di stop non è riuscita. Riprova.':'Stop inviato a Comfy. Le richieste già completate dal servizio possono essere addebitate.',results.some(r=>r.status==='rejected'));
|
||||
}
|
||||
async refreshLibrary(){if(!this.bridge.library||this.closed)return;try{this.library=await this.bridge.library();if(this.closed)return;for(const r of this.library.filter(r=>r.imported)){const existing=this.state.results.find(j=>j.id===r.id);if(existing)Object.assign(existing,r);}this.renderFilters();this.renderGallery();}catch(e){this.note('Libreria temporaneamente non disponibile.',true);}}
|
||||
async run(){
|
||||
if(this.busy)return;try{validateState(this.state);}catch(e){this.note(e.message,true);return;}
|
||||
this.stopRequested=false;this.busy=true;this.updateHeader();const snapshot=copy(this.state),batch=crypto.randomUUID(),started=Date.now();
|
||||
const jobs=plannedJobs(snapshot).map(p=>({...p,id:crypto.randomUUID(),batch,started,status:'submitting',images:[]}));
|
||||
try{
|
||||
const primary=activeReferences(snapshot).find(r=>r.kind==='image');
|
||||
if(snapshot.mode==='image'&&snapshot.imageEdit&&primary?.process?.enabled&&primary.process.source!=='prompt'){
|
||||
this.note('Preparazione Image 1 per il confronto…');const prepared=await this.bridge.previewReference(primary,primary.process);primary.processedPreview=prepared.file;
|
||||
}
|
||||
const seed=new Uint32Array(1);crypto.getRandomValues(seed);const compiled=compileBatch(snapshot,jobs,seed[0]%2147483647);
|
||||
this.note('Controllo reference e nodi…');await this.bridge.check(snapshot,compiled);if(this.closed||this.stopRequested)return;
|
||||
this.state.results.push(...jobs);this.save();this.renderFilters();this.renderGallery();this.galleryViewport.scrollTop=0;
|
||||
const promptId=await this.bridge.queue(compiled,batch,this.state);for(const job of jobs){job.promptId=promptId;if(job.status==='submitting')job.status='queued';}for(const [name,d] of this.pendingEvents||[])this.event(name,d);this.pendingEvents=[];if(this.stopRequested)await this.stop();this.save();this.updateCards();this.note(`${jobs.length} generazioni indipendenti inviate in un unico batch parallelo.`);
|
||||
}catch(e){for(const j of jobs){if(!terminal.has(j.status)){j.status='failed';j.error=e.message;j.finished=Date.now();}}this.save();this.updateCards();this.note(e.message,true);}finally{this.busy=false;if(!this.closed)this.updateHeader();}
|
||||
}
|
||||
event(name,d){
|
||||
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==='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();}
|
||||
}
|
||||
if(name==='execution_error'){const failed=jobs.find(j=>j.generator===String(d.node_id)||j.output===String(d.node_id));for(const job of jobs)if(!terminal.has(job.status)){job.status=job===failed?'failed':'cancelled';job.error=job===failed?d.exception_message:'Batch arrestato da Comfy. Nessun retry automatico.';job.finished=Date.now();}this.note(d.exception_message||'Errore nel batch.',true);}
|
||||
if(name==='execution_interrupted')for(const job of jobs)if(!terminal.has(job.status)){job.status='cancelled';job.finished=Date.now();}
|
||||
if(name==='execution_success'){this.recover();this.refreshCredits();this.refreshLibrary();}this.save();this.updateCards();
|
||||
}
|
||||
async recover(){
|
||||
if(this.recovering||!this.bridge.history||this.closed)return;this.recovering=true;
|
||||
try{const history=await this.bridge.history();if(this.closed)return;let changed=false;
|
||||
for(const record of Object.values(history||{})){
|
||||
const meta=record.prompt?.[3]?.extra_pnginfo?.workflow?.extra?.dogma_api_batch;if(meta?.session!==this.state.session)continue;
|
||||
for(const saved of meta.jobs){let job=this.state.results.find(x=>x.id===saved.id);if(!job){job=copy(saved);this.state.results.push(job);changed=true;}if(job.imported)continue;job.promptId=record.prompt[1];const ui=record.outputs?.[job.output];if(ui?.images?.length){const result=ui.dogma_records?.[0]||{images:ui.images,status:'completed',finished:Date.now()};if(JSON.stringify(job.images)!==JSON.stringify(result.images))changed=true;Object.assign(job,result);}else if(record.status?.completed&&!terminal.has(job.status)){job.status=record.status.status_str==='success'?'missing':'failed';job.finished=Date.now();job.error='Comfy non ha restituito questo output.';}}
|
||||
}
|
||||
this.save();if(changed){this.renderFilters();this.renderGallery();}else this.updateCards();
|
||||
}catch{this.note('La cronologia non è momentaneamente disponibile. I batch già accettati continuano in Comfy.',true);}finally{this.recovering=false;}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { icon } from './dogma_api_icons.js?v=1.0.55';
|
||||
|
||||
export function hoverCompare(host,generated,original){
|
||||
const a=document.createElement('img');a.src=generated;a.alt='Generata';a.draggable=false;a.className='dap-generated';host.append(a);host.classList.add('dap-compare-host');
|
||||
let cover=null,line=null;
|
||||
if(original){
|
||||
cover=document.createElement('div');cover.className='dap-original-cover';const b=document.createElement('img');b.src=original;b.alt='Image 1 / originale';b.draggable=false;cover.append(b);
|
||||
line=document.createElement('div');line.className='dap-compare-line';host.append(cover,line);
|
||||
const move=e=>{const rect=host.getBoundingClientRect();const percent=Math.max(0,Math.min(100,(e.clientX-rect.left)/rect.width*100));cover.style.clipPath=`inset(0 ${100-percent}% 0 0)`;line.style.left=percent+'%';};
|
||||
host.addEventListener('pointerenter',()=>host.classList.add('comparing'));host.addEventListener('pointermove',move);host.addEventListener('pointerleave',()=>host.classList.remove('comparing'));
|
||||
}
|
||||
return {image:a,cover,line};
|
||||
}
|
||||
|
||||
export function openViewer(ui,item,other=null){
|
||||
const {job,file,index=0}=item,bridge=ui.bridge;
|
||||
const title=job.filename||job.label||'DOGMA';
|
||||
const dialog=ui.modalBox(title,'dap-viewer-modal'),toolbar=document.createElement('div');toolbar.className='dap-viewer-tools';
|
||||
const stage=document.createElement('div');stage.className='dap-viewer-stage';stage.setAttribute('aria-label','Immagine ingrandita: rotella per zoom, trascina per spostare');stage.tabIndex=0;
|
||||
const surface=document.createElement('div');surface.className='dap-viewer-surface';stage.append(surface);
|
||||
const button=(name,label,fn)=>{const b=document.createElement('button');b.type='button';b.title=label;b.setAttribute('aria-label',label);b.append(icon(name));b.onclick=fn;return b;};
|
||||
let scale=1,fitScale=1,x=0,y=0,width=0,height=0,drag=null,pinch=null;const points=new Map();
|
||||
const zoom=document.createElement('input');zoom.type='number';zoom.min='1';zoom.max='1600';zoom.setAttribute('aria-label','Zoom percentuale');
|
||||
const percent=document.createElement('label');percent.className='dap-zoom-value';percent.append(zoom,document.createTextNode('%'));
|
||||
const update=()=>{surface.style.transform=`translate(${x}px,${y}px) scale(${scale})`;zoom.value=String(Math.round(scale*100));stage.classList.toggle('zoomed',scale>fitScale*1.01);};
|
||||
const at=(next,cx=stage.clientWidth/2,cy=stage.clientHeight/2)=>{next=Math.max(Math.min(fitScale,.1)*.5,Math.min(16,next));const ratio=next/scale;x=cx-(cx-x)*ratio;y=cy-(cy-y)*ratio;scale=next;update();};
|
||||
const fit=()=>{if(!width)return;fitScale=Math.min((stage.clientWidth-30)/width,(stage.clientHeight-30)/height);scale=fitScale;x=(stage.clientWidth-width*scale)/2;y=(stage.clientHeight-height*scale)/2;update();};
|
||||
toolbar.append(button('zoomOut','Riduci zoom',()=>at(scale/1.3)),percent,button('zoomIn','Aumenta zoom',()=>at(scale*1.3)),button('fit','Adatta alla finestra',fit));
|
||||
const one=button('single','Dimensione reale 100%',()=>at(1));one.append(document.createTextNode('100%'));toolbar.append(one);
|
||||
const folder=button('folder','Mostra nella cartella',()=>ui.openOutput(job,index));folder.append(document.createTextNode('Mostra nella cartella'));toolbar.append(folder);
|
||||
const download=button('download','Scarica file',()=>ui.downloadImage(file));toolbar.append(download);
|
||||
const hint=document.createElement('p');hint.className='dap-viewer-hint';hint.textContent='Rotella: zoom sul punto · Trascina: sposta · Doppio clic: 100% · Esc o clic nel vuoto: chiudi';
|
||||
dialog.append(toolbar,stage,hint);
|
||||
if(job.kind==='video'){
|
||||
const video=document.createElement('video');video.src=bridge.view(file);video.controls=true;video.autoplay=true;video.className='dap-viewer-video';stage.append(video);surface.remove();toolbar.querySelectorAll('button').forEach(b=>{if(b.title.includes('zoom')||b.title.includes('100%')||b.title.includes('Adatta'))b.remove();});percent.remove();hint.textContent='Esc o clic nel vuoto per chiudere';
|
||||
dialog.addEventListener('close',()=>{video.pause();video.removeAttribute('src');video.load();},{once:true});return;
|
||||
}
|
||||
const original=other?bridge.view(other.file):job.imageEdit&&job.baseReference?(job.baseReference.comparePreview||bridge.view(job.baseReference.processedPreview||job.baseReference.file)):null;
|
||||
const compare=hoverCompare(surface,bridge.view(file),original);
|
||||
compare.image.onload=()=>{width=compare.image.naturalWidth;height=compare.image.naturalHeight;surface.style.width=width+'px';surface.style.height=height+'px';fit();};
|
||||
if(compare.image.complete&&compare.image.naturalWidth)compare.image.onload();
|
||||
compare.image.onerror=()=>{hint.textContent='File non disponibile. Potrebbe essere stato spostato.';};
|
||||
zoom.onchange=()=>{const value=Number(zoom.value);if(Number.isFinite(value)&&value>0)at(value/100);};
|
||||
stage.addEventListener('wheel',e=>{e.preventDefault();const r=stage.getBoundingClientRect();at(scale*Math.exp(-e.deltaY*.0017),e.clientX-r.left,e.clientY-r.top);},{passive:false});
|
||||
stage.addEventListener('dblclick',e=>{const r=stage.getBoundingClientRect();if(Math.abs(scale-1)<.02)fit();else at(1,e.clientX-r.left,e.clientY-r.top);});
|
||||
stage.addEventListener('pointerdown',e=>{
|
||||
const rect=surface.getBoundingClientRect();const inImage=e.clientX>=rect.left&&e.clientX<=rect.right&&e.clientY>=rect.top&&e.clientY<=rect.bottom;
|
||||
if(!inImage&&e.target===stage){drag={blank:true,startX:e.clientX,startY:e.clientY};return;}
|
||||
stage.setPointerCapture(e.pointerId);points.set(e.pointerId,{x:e.clientX,y:e.clientY});drag={startX:e.clientX,startY:e.clientY,x,y};
|
||||
if(points.size===2){const [a,b]=[...points.values()];pinch={distance:Math.hypot(a.x-b.x,a.y-b.y),scale};}
|
||||
});
|
||||
stage.addEventListener('pointermove',e=>{
|
||||
if(points.has(e.pointerId))points.set(e.pointerId,{x:e.clientX,y:e.clientY});
|
||||
if(points.size===2&&pinch){const [a,b]=[...points.values()],r=stage.getBoundingClientRect();at(pinch.scale*Math.hypot(a.x-b.x,a.y-b.y)/pinch.distance,(a.x+b.x)/2-r.left,(a.y+b.y)/2-r.top);return;}
|
||||
if(drag&&!drag.blank&&points.size===1){x=drag.x+e.clientX-drag.startX;y=drag.y+e.clientY-drag.startY;update();}
|
||||
});
|
||||
const up=e=>{if(drag?.blank&&Math.hypot(e.clientX-drag.startX,e.clientY-drag.startY)<5)dialog.close();points.delete(e.pointerId);drag=null;pinch=null;};
|
||||
stage.addEventListener('pointerup',up);stage.addEventListener('pointercancel',up);
|
||||
stage.addEventListener('keydown',e=>{if(e.key==='+'||e.key==='='){e.preventDefault();at(scale*1.3);}if(e.key==='-'){e.preventDefault();at(scale/1.3);}if(e.key==='0'){e.preventDefault();fit();}});
|
||||
const observer=new ResizeObserver(()=>{if(Math.abs(scale-fitScale)<.01)fit();});observer.observe(stage);dialog.addEventListener('close',()=>observer.disconnect(),{once:true});
|
||||
}
|
||||
@@ -67,4 +67,7 @@
|
||||
.dg-studio .dg-upload-status{font-size:12px;margin:6px 0;overflow-wrap:anywhere;min-height:0}
|
||||
.dg-studio .dg-file-drop[data-upload-state=error]>.dg-upload-status{color:#ffbb98}
|
||||
.dg-studio .dg-file-drop[aria-busy=true]>.dg-drop-hint{color:#ffd2b8;border-style:solid}
|
||||
.dg-studio .dg-folders a{display:flex;align-items:center;gap:8px;padding:10px 14px;margin:4px 6px 4px 0;border:1px solid #505256;border-radius:7px;background:#26282b;text-decoration:none;overflow-wrap:anywhere}
|
||||
.dg-studio .dg-folders a:hover{border-color:var(--orange)}
|
||||
.dg-studio [hidden]{display:none!important}
|
||||
.dg-studio .dg-upload-toast{position:fixed;bottom:45px;left:50%;transform:translateX(-50%);z-index:20;max-width:80vw;padding:10px 18px;border:1px solid var(--orange);border-radius:7px;background:#30231d;box-shadow:0 4px 20px #0008;color:#fff}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
import {actionButton,decorateActions,setAction} from './dogma_h3_actions.js?v=studio-1-0-49';
|
||||
import {assetField,referenceDrop,guardFileNavigation} from './dogma_h3_uploads.js?v=studio-1-0-49';
|
||||
import { renderEditor, renderEditResults, renderEditTrials } from './dogma_h3_video_edit.js?v=studio-1-0-49';
|
||||
import {actionButton,decorateActions,setAction} from './dogma_h3_actions.js?v=studio-1-0-50';
|
||||
import {assetField,referenceDrop,guardFileNavigation} from './dogma_h3_uploads.js?v=studio-1-0-50';
|
||||
import { renderEditor, renderEditResults, renderEditTrials } from './dogma_h3_video_edit.js?v=studio-1-0-50';
|
||||
|
||||
import { inputFile, viewURL, mediaPreview, releaseMedia } from './dogma_h3_media.js?v=studio-1-0-49';
|
||||
import { inputFile, viewURL, mediaPreview, releaseMedia } from './dogma_h3_media.js?v=studio-1-0-50';
|
||||
|
||||
const ROOT=new URL('.',import.meta.url);
|
||||
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_h3_director_v134.css?v=studio-1-0-49',ROOT);document.head.append(css);
|
||||
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_h3_director_v134.css?v=studio-1-0-50',ROOT);document.head.append(css);
|
||||
const clone=x=>JSON.parse(JSON.stringify(x));
|
||||
const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
|
||||
const button=actionButton;
|
||||
@@ -40,6 +40,12 @@ export class DirectorStudio {
|
||||
let stored;try{stored=JSON.parse(this.widget.value);}catch{stored={};}
|
||||
this.config=merge(clone(this.catalog.defaults),stored);
|
||||
this.config.session ||= crypto.randomUUID();
|
||||
const access=this.catalog.access;
|
||||
if(access?.local_files===false&&access.platform!=='nt'&&access.output_directory){
|
||||
for(const [object,key]of [[this.config,'output_dir'],[this.config.edit,'final_output_dir']]){
|
||||
if(/^(?:[a-z]:[\\/]|\\\\)/i.test(object[key]||''))object[key]=key==='final_output_dir'?'':access.output_directory;
|
||||
}
|
||||
}
|
||||
}
|
||||
family(task){return ['ref2v','edit'].includes(task)?'ref2v':'fl2v';}
|
||||
turbo(task,steps){
|
||||
@@ -97,10 +103,12 @@ export class DirectorStudio {
|
||||
clearTimeout(this.saveTimer);this.saveTimer=setTimeout(()=>{try{app.graph?.change?.();}catch(e){console.warn('DOGMA: aggiornamento workflow',e);}},250);
|
||||
}
|
||||
async request(path,opts={}){
|
||||
const headers=Object.fromEntries(new Headers(opts.headers||{}).entries());
|
||||
if(path.startsWith('/dogma/h3/v2/')&&this.catalog?.access?.token)headers['X-Dogma-Access']=this.catalog.access.token;
|
||||
const controller=new AbortController(),epoch=this.epoch;this.requests.add(controller);let expired=false;
|
||||
const timeout=opts.body instanceof FormData?null:setTimeout(()=>{expired=true;controller.abort();},20000);
|
||||
try{
|
||||
const r=await api.fetchApi(path,{...opts,signal:opts.signal?AbortSignal.any([controller.signal,opts.signal]):controller.signal});
|
||||
const r=await api.fetchApi(path,{...opts,headers,signal:opts.signal?AbortSignal.any([controller.signal,opts.signal]):controller.signal});
|
||||
if(!r.ok)throw new Error(`Comfy: ${r.status} ${await r.text()}`);
|
||||
const result=await r.json();
|
||||
if(epoch!==this.epoch){const e=new Error('Pannello chiuso');e.name='AbortError';throw e;}
|
||||
@@ -146,27 +154,32 @@ export class DirectorStudio {
|
||||
this.save();
|
||||
}
|
||||
destroy(){this.close();clearTimeout(this.saveTimer);this.abort.abort();}
|
||||
async browseFolders(scope='general'){
|
||||
async browseFolders(scope='general',options={}){
|
||||
if(this.folderPanel||!this.dialog)return;
|
||||
const epoch=this.epoch,panel=el('section','','dg-folder-browser');this.folderPanel=panel;
|
||||
panel.setAttribute('role','region');panel.setAttribute('aria-label','Scegli cartella output');
|
||||
panel.setAttribute('role','region');panel.setAttribute('aria-label',options.viewOnly?'Cartella del video salvato':'Scegli cartella output');
|
||||
const main=this.dialog.querySelector('main');main.prepend(panel);
|
||||
const target=scope==='edit'?this.config.edit:this.config,key=scope==='edit'?'final_output_dir':'output_dir';
|
||||
const input=el('input');input.type='text';input.value=target[key]||this.config.output_dir||'';input.setAttribute('aria-label','Percorso cartella');
|
||||
const remote=this.catalog.access?.local_files===false;
|
||||
const serverRoot=(this.catalog.access?.output_directory||'').replaceAll('\\','/').replace(/\/$/,'');
|
||||
const preferred=(target[key]||this.config.output_dir||'').replaceAll('\\','/');
|
||||
const initial=remote&&preferred!==serverRoot&&!preferred.startsWith(serverRoot+'/')?serverRoot:preferred;
|
||||
const input=el('input');input.type='text';input.value=options.initialPath||initial;input.setAttribute('aria-label','Percorso cartella');
|
||||
const info=el('p'),list=el('div','','dg-folders');let busy=false,current='';
|
||||
const done=()=>{panel.remove();if(this.folderPanel===panel)this.folderPanel=null;};
|
||||
const use=button('Usa questa cartella',async()=>{if(input.value!==current&&!await load(input.value))return;target[key]=current;this.save();done();this.render();},'dg-primary');use.disabled=true;
|
||||
const use=button('Usa questa cartella',async()=>{if(input.value!==current&&!await load(input.value))return;target[key]=current;this.save();done();this.render();},'dg-primary');use.disabled=true;use.hidden=!!options.viewOnly;
|
||||
const go=button('Vai',()=>load(input.value));
|
||||
panel.append(el('h2','Cartella di salvataggio'),el('p','Naviga nelle cartelle del computer che esegue Comfy.'),input,go,button('Annulla',done),use,info,list);
|
||||
panel.append(el('h2',options.viewOnly?'Cartella del video salvato':'Cartella di salvataggio'),el('p',remote?'Cartelle del server che esegue Comfy. La navigazione parte dalla sua cartella output.':'Naviga nelle cartelle del computer che esegue Comfy.'),input,go,button(options.viewOnly?'Chiudi':'Annulla',done),use,info,list);
|
||||
const load=async path=>{
|
||||
if(busy)return;busy=true;go.disabled=true;use.disabled=true;info.textContent='Caricamento cartelle…';list.replaceChildren();
|
||||
try{
|
||||
const r=await this.request('/dogma/h3/v2/folders?'+new URLSearchParams({path:path||''}));
|
||||
const r=await this.request('/dogma/h3/v2/folders?'+new URLSearchParams({path:path||'',files:options.viewOnly?'1':'0'}));
|
||||
if(epoch!==this.epoch||this.folderPanel!==panel)return;
|
||||
current=r.path;input.value=current;info.textContent=r.truncated?'Mostrate le prime 500 cartelle. Puoi inserire il percorso completo.':'Seleziona una sottocartella oppure conferma questa cartella.';
|
||||
current=r.path;input.value=current;info.textContent=r.truncated?'Mostrati i primi 500 elementi.':options.viewOnly?'File della cartella: clicca un nome per scaricarlo.':'Seleziona una sottocartella oppure conferma questa cartella.';
|
||||
if(r.parent)list.append(button('↑ Cartella superiore',()=>load(r.parent)));
|
||||
for(const d of r.drives||[])list.append(button(d.name,()=>load(d.path)));
|
||||
for(const d of r.directories||[])list.append(button('📁 '+d.name,()=>load(d.path)));
|
||||
for(const f of r.files||[]){const link=el('a');setAction(link,f.name+' · '+(f.size/1024/1024).toFixed(1)+' MB','download');link.href=viewURL(f.video);link.download=f.name;list.append(link);}
|
||||
use.disabled=false;return true;
|
||||
}catch(e){if(epoch===this.epoch&&this.folderPanel===panel&&e.name!=='AbortError')info.textContent=e.message;return false;}
|
||||
finally{busy=false;go.disabled=false;}
|
||||
@@ -254,7 +267,7 @@ export class DirectorStudio {
|
||||
if(previewEnabled)required.push('ModelPreviewOverrideKJ');
|
||||
if(action==='finish'&&this.config.task!=='edit'&&this.config.finish.stages!=='ultimate')required.push('MinimaxH3LatentUpscaler3D');
|
||||
if(action==='finish'&&this.config.task!=='edit'&&this.config.finish.stages!=='latent')required.push('UltimateSDUpscaleNoUpscaleGuider');
|
||||
const missing=required.filter(n=>!this.catalog.nodes.includes(n));if(missing.length)throw new Error('Installa dal Manager i nodi richiesti: '+missing.join(', '));
|
||||
const missing=required.filter(n=>!this.catalog.nodes.includes(n));if(missing.length)throw new Error('Installa dal Manager: '+missing.map(n=>n==='MVEx_MaskToLatentSpace'?'MaskVidExperiments (nodo '+n+')':n).join(', '));
|
||||
const q=await this.request('/queue');if(q.queue_running?.length||q.queue_pending?.length)throw new Error('Comfy sta già lavorando. Attendi la fine della coda.');
|
||||
this.config.action=action;this.config.nonce++;this.save();
|
||||
if(this.config.task==='edit'&&action==='draft'){delete this.data.edit_batch;this.promotedTrial=null;this.editFinishWaiting=null;}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {mediaPreview,inputFile} from './dogma_h3_media.js?v=studio-1-0-49';
|
||||
import {frameIndex,frameTime,frameCount,stepTime} from './dogma_h3_timing.js?v=studio-1-0-49';
|
||||
import {actionButton,setAction,loraLabel} from './dogma_h3_actions.js?v=studio-1-0-49';
|
||||
import {mediaPreview,inputFile} from './dogma_h3_media.js?v=studio-1-0-50';
|
||||
import {frameIndex,frameTime,frameCount,stepTime} from './dogma_h3_timing.js?v=studio-1-0-50';
|
||||
import {actionButton,setAction,loraLabel} from './dogma_h3_actions.js?v=studio-1-0-50';
|
||||
const el=(tag,text='')=>{const e=document.createElement(tag);e.textContent=text;return e;};
|
||||
const button=actionButton;
|
||||
const clamp=(v,a,b)=>Math.min(b,Math.max(a,v));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mediaPreview } from './dogma_h3_media.js?v=studio-1-0-49';
|
||||
import { mediaPreview } from './dogma_h3_media.js?v=studio-1-0-50';
|
||||
|
||||
const el=(tag,text='')=>{const e=document.createElement(tag);e.textContent=text;return e;};
|
||||
export function maskKey(c){
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {viewURL} from './dogma_h3_media.js?v=studio-1-0-49';
|
||||
import {actionButton,setAction} from './dogma_h3_actions.js?v=studio-1-0-49';
|
||||
import {RestitchHover} from './dogma_h3_restitch_hover.js?v=studio-1-0-49';
|
||||
import {viewURL} from './dogma_h3_media.js?v=studio-1-0-50';
|
||||
import {actionButton,setAction} from './dogma_h3_actions.js?v=studio-1-0-50';
|
||||
import {RestitchHover} from './dogma_h3_restitch_hover.js?v=studio-1-0-50';
|
||||
const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
|
||||
const clamp=(x,a,b)=>Math.min(b,Math.max(a,x));
|
||||
export class RestitchPanel{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {viewURL} from './dogma_h3_media.js?v=studio-1-0-49';
|
||||
import {viewURL} from './dogma_h3_media.js?v=studio-1-0-50';
|
||||
const clamp=(x,a,b)=>Math.min(b,Math.max(a,x));
|
||||
const el=(tag,cls='')=>{const e=document.createElement(tag);e.className=cls;return e;};
|
||||
export class RestitchHover{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {mediaPreview,inputFile} from './dogma_h3_media.js?v=studio-1-0-49';
|
||||
import {actionButton,setAction} from './dogma_h3_actions.js?v=studio-1-0-49';
|
||||
import {mediaPreview,inputFile} from './dogma_h3_media.js?v=studio-1-0-50';
|
||||
import {actionButton,setAction} from './dogma_h3_actions.js?v=studio-1-0-50';
|
||||
const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
|
||||
const extensions={image:new Set(['png','jpg','jpeg','webp','gif','bmp','tif','tiff','avif','heic','heif']),video:new Set(['mp4','mov','m4v','mkv','webm','avi','mpeg','mpg','wmv','flv','ts','mts','m2ts','mxf','ogv','3gp'])};
|
||||
export function mediaKind(file){const mime=String(file.type||'').toLowerCase();if(mime.startsWith('image/'))return 'image';if(mime.startsWith('video/'))return 'video';const ext=String(file.name||'').split('.').pop().toLowerCase();return Object.keys(extensions).find(kind=>extensions[kind].has(ext));}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { MaskEditor, compositeControls } from './dogma_h3_edit_mask.js?v=studio-1-0-49';
|
||||
import { EditComparison } from './dogma_h3_edit_compare.js?v=studio-1-0-49';
|
||||
import { MaskEditor, compositeControls } from './dogma_h3_edit_mask.js?v=studio-1-0-50';
|
||||
import { EditComparison } from './dogma_h3_edit_compare.js?v=studio-1-0-50';
|
||||
import { api } from '../../scripts/api.js';
|
||||
import {actionButton,setAction,loraLabel} from './dogma_h3_actions.js?v=studio-1-0-49';
|
||||
import {RestitchPanel} from './dogma_h3_restitch.js?v=studio-1-0-49';
|
||||
import {assetField,referenceDrop} from './dogma_h3_uploads.js?v=studio-1-0-49';
|
||||
import { inputFile, viewURL, mediaPreview } from './dogma_h3_media.js?v=studio-1-0-49';
|
||||
import { frameIndex, frameTime, frameCount, snapSelection, stepTime, parseSelection } from './dogma_h3_timing.js?v=studio-1-0-49';
|
||||
export { snapSelection } from './dogma_h3_timing.js?v=studio-1-0-49';
|
||||
import {actionButton,setAction,loraLabel} from './dogma_h3_actions.js?v=studio-1-0-50';
|
||||
import {RestitchPanel} from './dogma_h3_restitch.js?v=studio-1-0-50';
|
||||
import {assetField,referenceDrop} from './dogma_h3_uploads.js?v=studio-1-0-50';
|
||||
import { inputFile, viewURL, mediaPreview } from './dogma_h3_media.js?v=studio-1-0-50';
|
||||
import { frameIndex, frameTime, frameCount, snapSelection, stepTime, parseSelection } from './dogma_h3_timing.js?v=studio-1-0-50';
|
||||
export { snapSelection } from './dogma_h3_timing.js?v=studio-1-0-50';
|
||||
|
||||
const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
|
||||
const button=actionButton;
|
||||
@@ -131,7 +131,14 @@ export function renderEditResults(studio,body){
|
||||
studio.editCompare=new EditComparison(studio,card,selected);
|
||||
card.append(el('small',selected.saved_path));
|
||||
if(selected.export_error)card.append(el('p','Il video completo è conservato nella sessione. La copia nella cartella scelta non è riuscita: '+selected.export_error));
|
||||
card.append(button('Apri cartella del video salvato',async()=>{try{await studio.request('/dogma/h3/v2/open-folder',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session:studio.config.session,id:selected.id})});}catch(e){studio.fail(e.message);}}));
|
||||
card.append(button('Apri cartella del video salvato',async()=>{try{
|
||||
if(studio.catalog.access?.open_folder===false){
|
||||
const base=studio.catalog.access.output_directory.replaceAll('\\','/');
|
||||
const saved=String(selected.saved_path||'').replaceAll('\\','/'),directory=saved.slice(0,saved.lastIndexOf('/'));
|
||||
const initialPath=directory===base||directory.startsWith(base+'/')?directory:base+'/'+(selected.video.subfolder||'');
|
||||
await studio.browseFolders('edit',{initialPath,viewOnly:true});
|
||||
}else await studio.request('/dogma/h3/v2/open-folder',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session:studio.config.session,id:selected.id})});
|
||||
}catch(e){studio.fail(e.message);}}));
|
||||
const copy=button('Copia questo finale nella cartella scelta',async()=>{if(copy.disabled)return;copy.disabled=true;try{const result=await studio.request('/dogma/h3/v2/edit/export-copy',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session:studio.config.session,id:selected.id,output_dir:studio.config.edit.final_output_dir||studio.config.output_dir})});for(const item of studio.data.edits||[])if(item.id===result.id){item.saved_path=result.saved_path;delete item.export_error;}studio.data.status='done';studio.data.message='Video completo copiato nella cartella scelta.';studio.render();}catch(e){studio.fail(e.message);}finally{copy.disabled=false;}});copy.disabled=studio.pending;card.append(copy);
|
||||
card.append(el('small','La copia usa il video già completato, senza ricalcolarlo. Destinazione: '+(studio.config.edit.final_output_dir||studio.config.output_dir||'cartella output Comfy')));
|
||||
card.append(button('Cambia cartella di destinazione…',()=>studio.browseFolders('edit')));
|
||||
|
||||
Reference in New Issue
Block a user