Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c931fb843e | ||
|
|
59e2883afe |
@@ -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.
|
||||
@@ -166,3 +166,33 @@ 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.
|
||||
|
||||
+37
@@ -206,3 +206,40 @@ try:
|
||||
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,310 @@
|
||||
"""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()
|
||||
|
||||
|
||||
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}, 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)
|
||||
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 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),)
|
||||
|
||||
|
||||
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,data['prefix'],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(data['prefix'],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."""
|
||||
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]}
|
||||
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,'frontend':frontend_modules(PromptServer.instance.web_root),'version':'1.0.54'})
|
||||
|
||||
@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))
|
||||
return web.json_response({'path':str(path)})
|
||||
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);access.local(request)
|
||||
if os.name!='nt':raise web.HTTPBadRequest(text='Usa il browser delle cartelle sul server.')
|
||||
data=await request.json();initial=str(data.get('path') or _output())
|
||||
script="""[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$dialog = New-Object System.Windows.Forms.FolderBrowserDialog
|
||||
$dialog.Description = 'DOGMA / Scegli la cartella di lavoro'
|
||||
$dialog.SelectedPath = $env:DOGMA_FOLDER_INITIAL
|
||||
$dialog.ShowNewFolderButton = $true
|
||||
if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Write($dialog.SelectedPath) }
|
||||
"""
|
||||
def select():
|
||||
env=os.environ.copy();env['DOGMA_FOLDER_INITIAL']=initial
|
||||
result=subprocess.run(['powershell.exe','-NoProfile','-STA','-WindowStyle','Hidden','-Command',script],capture_output=True,env=env,encoding='utf8',timeout=300,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
|
||||
if result.returncode:raise ValueError('La scelta cartella non è riuscita.')
|
||||
return result.stdout.strip()
|
||||
try:
|
||||
selected=await asyncio.to_thread(select)
|
||||
if selected:_WORKSPACES.add(str(Path(selected).resolve()))
|
||||
return web.json_response({'path':selected,'cancelled':not selected})
|
||||
except (ValueError,OSError,subprocess.TimeoutExpired) as exc:raise web.HTTPBadRequest(text=str(exc))
|
||||
|
||||
@routes.get('/dogma/api/v2/folders')
|
||||
async def folders(request):
|
||||
access.browser(request)
|
||||
try:
|
||||
path=access.output_path(request,request.query.get('path'),_output())
|
||||
if not path.is_dir():raise ValueError('Cartella inesistente.')
|
||||
dirs=[{'name':p.name,'path':str(p.resolve())} for p in path.iterdir() if p.is_dir() and (access.is_local(request) or p.resolve().is_relative_to(_output()))]
|
||||
parent=str(path.parent) if access.is_local(request) or path.parent.is_relative_to(_output()) else None
|
||||
return web.json_response({'path':str(path),'parent':parent,'directories':sorted(dirs,key=lambda d:d['name'].lower())})
|
||||
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);access.local(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.')
|
||||
if os.name=='nt':subprocess.Popen(['explorer.exe','/select,',str(file)],creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
|
||||
else:raise ValueError('Esplora risorse è disponibile sul Comfy Windows locale.')
|
||||
return web.json_response({'ok':True})
|
||||
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=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,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()}
|
||||
+27
-13
@@ -27,7 +27,7 @@ from comfy_api.latest._input_impl.video_types import (
|
||||
)
|
||||
from comfy_extras import nodes_images as ni
|
||||
|
||||
VERSION = "1.0.51"
|
||||
VERSION = "1.0.52"
|
||||
SPACES = ["sRGB", "HDR", "HDR ACEScct", "HDR LogC3", "HDR PQ", "linear", "linear ACEScg"]
|
||||
log = logging.getLogger("DOGMA.HDR")
|
||||
|
||||
@@ -77,6 +77,8 @@ class DogmaHDRColorChunked(io.ComfyNode):
|
||||
|
||||
|
||||
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:
|
||||
@@ -128,7 +130,8 @@ def encode_audio(container, audio, count, rate):
|
||||
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):
|
||||
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:
|
||||
@@ -137,19 +140,28 @@ def export_frames(images, source_width, source_height, source_frames, fps,
|
||||
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 / "DOGMA_4K_HDR_HLG.mov"
|
||||
mov_temporary = job / "DOGMA_4K_HDR_HLG.partial.mov"
|
||||
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="ACEScg AP1/D60 RGB HALF EXR ZIP16", source_width=source_width,
|
||||
master=f"{exr_label} RGB HALF EXR ZIP16", source_width=source_width,
|
||||
source_height=source_height, decoded_frames=len(images),
|
||||
mov="ProRes 4444 BT.2020 HLG; 10-bit encoding input; PCM24 original audio" if save_mov else None,
|
||||
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
|
||||
@@ -162,7 +174,7 @@ def export_frames(images, source_width, source_height, source_frames, fps,
|
||||
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, "HDR")
|
||||
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:
|
||||
@@ -172,24 +184,26 @@ def export_frames(images, source_width, source_height, source_frames, fps,
|
||||
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)
|
||||
if not torch.isfinite(linear).all():
|
||||
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 linear.abs().max() > 65504:
|
||||
if master.abs().max() > 65504:
|
||||
raise ValueError(f"Frame {index}: range oltre HALF (+-65504). Serve EXR float32 per questi valori.")
|
||||
encoded = ni._encode_image(linear[0], "exr", "16-bit float", "linear ACEScg")
|
||||
encoded = ni.inject_exr_metadata(encoded, None, None, "linear ACEScg")
|
||||
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", "HDR")[0]
|
||||
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, "HDR")
|
||||
set_video_color_properties(frame, mov_color_space)
|
||||
frame.time_base = 1 / rate
|
||||
frame.pts = index
|
||||
container.mux(stream.encode(frame))
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "comfyui-dogma-nodes"
|
||||
description = "Custom ComfyUI nodes for DOGMA AI video workflows."
|
||||
version = "1.0.51"
|
||||
version = "1.0.54"
|
||||
license = { file = "LICENSE" }
|
||||
dependencies = ["scipy>=1.10"]
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
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 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=2;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;
|
||||
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'};}
|
||||
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 activeReferences(s){return s.references.filter(r=>r.enabled&&(!r.modes||r.modes.includes(s.mode))&&(s.mode==='video'||r.kind!=='video'));}
|
||||
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)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": 2,
|
||||
"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": "*"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Geometry follows the supplied DOGMA artwork. No font glyph substitutes.
|
||||
export function icon(name){
|
||||
const ns='http://www.w3.org/2000/svg',s=document.createElementNS(ns,'svg');s.setAttribute('viewBox','0 0 24 24');s.setAttribute('aria-hidden','true');s.classList.add('dap-icon');
|
||||
const paths={
|
||||
image:[['rect',{x:3,y:3,width:18,height:18,rx:2}],['circle',{cx:8,cy:8,r:1.1,fill:'currentColor'}],['path',{d:'M3 17l6-6 4 3 8-8'}]],
|
||||
video:[['rect',{x:3,y:3,width:18,height:18,rx:1}],['path',{d:'M3 7h18M3 17h18M7 3v4m5-4v4m5-4v4M7 17v4m5-4v4m5-4v4'}]],
|
||||
chevron:[['path',{d:'m7 10 5 5 5-5'}]],
|
||||
lines:[['path',{d:'M8 9h8M8 12h8M8 15h8'}]],
|
||||
single:[['rect',{x:3,y:4,width:18,height:16,rx:.6}]],
|
||||
grid:[['path',{d:'M2 4h5v6H2zM10 4h5v6h-5zM18 4h5v6h-5zM2 14h5v6H2zM10 14h5v6h-5zM18 14h5v6h-5z'}]],
|
||||
compare:[['rect',{x:2,y:4,width:20,height:16,rx:1}],['path',{d:'M12 4v16M4 17l3-10 3 10M5 13h4M15 7h2.5a2.5 2.5 0 0 1 0 5H15m0-5v10h3a2.5 2.5 0 0 0 0-5h-3'}]],
|
||||
play:[['path',{d:'M7 3l15 9L7 21z',fill:'currentColor',stroke:'none'}]],
|
||||
plus:[['path',{d:'M12 4v16M4 12h16'}]],
|
||||
close:[['path',{d:'m6 6 12 12M18 6 6 18'}]],
|
||||
folder:[['path',{d:'M2 6h8l2 3h10l-2 11H3zM2 6V4h8l2 2h8v3'}]],
|
||||
download:[['path',{d:'M12 3v12m-5-5 5 5 5-5M4 17v4h16v-4'}]],
|
||||
edit:[['path',{d:'m4 16 12-12 4 4L8 20H4zm10-10 4 4M4 20h16'}]],
|
||||
zoomIn:[['circle',{cx:10,cy:10,r:7}],['path',{d:'m15 15 7 7M6 10h8M10 6v8'}]],
|
||||
zoomOut:[['circle',{cx:10,cy:10,r:7}],['path',{d:'m15 15 7 7M6 10h8'}]],
|
||||
fit:[['path',{d:'M3 9V3h6m6 0h6v6M3 15v6h6m6 0h6v-6'}]],
|
||||
refresh:[['path',{d:'M20 8a9 9 0 1 0 0 9M20 3v6h-6'}]],
|
||||
filter:[['path',{d:'M3 5h18l-7 8v7l-4-2v-5z'}]],
|
||||
arrow:[['path',{d:'m14 5-7 7 7 7'}]],
|
||||
};
|
||||
for(const [tag,attributes] of paths[name]||paths.plus){const p=document.createElementNS(ns,tag);for(const [k,v] of Object.entries(attributes))p.setAttribute(k,String(v));s.append(p);}
|
||||
return s;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.3 KiB |
@@ -0,0 +1,23 @@
|
||||
.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)}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { app } from '../../scripts/app.js';
|
||||
import { api } from '../../scripts/api.js';
|
||||
import { PlatformUI } from './dogma_api_ui.js?v=1.0.54';
|
||||
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec } from './dogma_api_core.js?v=1.0.54';
|
||||
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.54',ROOT);document.head.append(css);
|
||||
let opened=null,queueLock=false;
|
||||
|
||||
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_V2.json.');return migrateState(s);}
|
||||
async initialize(state){
|
||||
const defaults=await (await fetch(new URL('dogma_api_defaults.json?v=1.0.54',ROOT))).json();
|
||||
for(const [key,value] of Object.entries(defaults.models))state.models[key] ||= copy(value);
|
||||
state.prompts.video ||= defaults.prompts.video;
|
||||
this.catalog=await this.request('/catalog');
|
||||
this.defs=await (await api.fetchApi('/object_info')).json();
|
||||
if(state.workspace){try{await this.workspace(state.workspace);}catch{state.workspace='';}}
|
||||
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?.url)return file.url;const p=new URLSearchParams(typeof file==='string'?{filename:file,type:'input'}:{filename:file.filename,subfolder:file.subfolder||'',type:file.type||'output'});return api.apiURL('/view?'+p);}
|
||||
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(path){if(this.catalog?.access?.open_folder)return this.request('/choose-folder',{path});return {browse:true};}
|
||||
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);}
|
||||
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'){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){
|
||||
this.defs=await (await api.fetchApi('/object_info')).json();const missing=[...new Set(Object.values(compiled.output).map(n=>n.class_type))].filter(type=>!this.defs[type]);if(missing.length)throw new Error('Nodi mancanti: '+missing.join(', '));
|
||||
for(const ref of activeReferences(state))for(const file of [ref.file,ref.process?.maskFile].filter(Boolean)){const r=await api.fetchApi('/view?'+new URLSearchParams({filename:file,type:'input'}),{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'])api.addEventListener(name,e=>handler(name,e.detail),{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){if(typeof api.cancelJob==='function')return api.cancelJob(id);return api.interrupt(id);}
|
||||
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.54';
|
||||
import {icon} from './dogma_api_icons.js?v=1.0.54';
|
||||
|
||||
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);preview.hidden=false;status.textContent=`${result.width} × ${result.height} · Anteprima aggiornata`;}catch(e){status.textContent=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();
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import {ALL_FAMILIES,copy,families,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences} from './dogma_api_core.js?v=1.0.54';
|
||||
import {icon} from './dogma_api_icons.js?v=1.0.54';
|
||||
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.54';
|
||||
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.54';
|
||||
|
||||
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(){
|
||||
await this.bridge.initialize?.(this.state);this.state=migrateState(this.state);
|
||||
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));
|
||||
await 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'));
|
||||
actions.append(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=el('div','','dap-project');
|
||||
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);
|
||||
main.append(toolbar,this.filters,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.project,s.scene].filter(Boolean).join(' / ')||'Tutti gli output';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.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([String(value),...opts.choices])]){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 work=el('section','','dap-section dap-work');work.append(el('div','FILENAME / WORKSPACE','dap-label'));
|
||||
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));
|
||||
c.append(refs,prompt,work,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=this.state.references.filter(r=>!r.modes||r.modes.includes(this.state.mode));
|
||||
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'&&r.kind==='image'){
|
||||
const select=el('select','','dap-ref-role');select.setAttribute('aria-label',`Ruolo reference ${i+1}`);for(const [key,text] of [['reference','Reference'],['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 add=ib('plus','Aggiungi immagini o video',()=>this.pickReferences(),'dap-add');add.append(el('span','Immagini / Video'));this.refs.append(add);
|
||||
}
|
||||
pickReferences(replace=null){const i=el('input');i.type='file';i.accept='image/*,video/*';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 uploaded=await this.bridge.upload(file);if(this.closed)return;const r={...uploaded,enabled:true,modes:[this.state.mode],role:'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'));
|
||||
if(f.key==='seedance')this.field(body,'WORKFLOW',m.engine,v=>{m.engine=v;this.save();wrap.replaceWith(this.model(f));this.refreshPrices();},{choices:['reference','frames']});
|
||||
const values=m.engine==='frames'?m.frames:m.parameters;
|
||||
for(const [key,value] of Object.entries(values)){
|
||||
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(spec[0]==='COMBO')opts.choices=info.options;if(info.min!==undefined)opts.min=info.min;if(info.max!==undefined)opts.max=info.max;if(info.step!==undefined)opts.step=info.step;}
|
||||
this.field(body,displayName(key),value,v=>{values[key]=typeof value==='boolean'?v:typeof value==='number'?Number(v):v;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','Reference: genera, modifica o estende un video. Frames: usa i ruoli First / Last delle 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');card.append(el('div','','dap-spinner'),el('span','','dap-job-state'));}
|
||||
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(){for(const job of this.allResults())for(const card of this.cards.get(job.id)||[]){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{await this.bridge.openOutput(job.id,index);}catch(e){this.note(e.message,true);if(this.modal){let note=this.modal.querySelector('.dap-operation-note');if(!note){note=el('p','','dap-operation-note');this.modal.append(note);}note.textContent=e.message;}}}
|
||||
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(){
|
||||
try{const chosen=await this.bridge.chooseFolder(this.state.workspace);if(chosen.cancelled)return;if(chosen.path){this.state.workspace=chosen.path;this.save();this.renderControls();this.note('Cartella di lavoro selezionata.');return;}if(chosen.browse)await this.folderBrowser();}catch(e){this.note(e.message,true);}
|
||||
}
|
||||
async folderBrowser(){const box=this.modalBox('CARTELLA DI LAVORO'),list=el('div','','dap-folder-list');box.append(list);const render=async path=>{try{const data=await this.bridge.folders(path);list.replaceChildren(el('div',data.path,'dap-folder-path'));if(data.parent)list.append(btn('↑ Cartella superiore',()=>render(data.parent),'dap-outline'));for(const dir of data.directories){const b=ib('folder',dir.name,()=>render(dir.path));b.append(el('span',dir.name));list.append(b);}list.append(btn('Usa questa cartella',async()=>{try{const result=await this.bridge.workspace(data.path);this.state.workspace=result.path;this.save();box.close();this.renderControls();}catch(e){this.note(e.message,true);}},'dap-outline'));}catch(e){list.replaceChildren(el('p',e.message));}};await render(this.state.workspace);}
|
||||
async refreshLibrary(){if(!this.bridge.library||this.closed)return;try{this.library=await this.bridge.library();if(this.closed)return;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.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)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';}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)return;
|
||||
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;}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.54';
|
||||
|
||||
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});
|
||||
}
|
||||
Reference in New Issue
Block a user