Compare commits

..
7 Commits
28 changed files with 1773 additions and 176 deletions
+3
View File
@@ -0,0 +1,3 @@
# DOGMA 1.0.56 / API Platform V4
DOGMA artwork for controls and generation/error/result cards. Unified compact 28x14 toggles with native keyboard interaction. Neutral 24px reference icons replace the plus on hover without changing the background or border. Small system-prompt labels and gray prompt resize grip. Discreet compare cursor and separate folder selection / Explorer actions. Bundled Roboto Mono OFL font and original DOGMA loading video. Run repetitions with unique seeds in independent API branches. Exact SAM3 preview mask reused at Run. Persistent editor drafts, zoom/pan, full-size copy/preview. Automatic A/B and synchronized video comparison. Stable chronological grid, saved filename, original prompt, video duration, error visibility with five-second grace. Gray scrollbars, full-row menus, top-edge total progress and native Windows folder opener. Portable optional project/scene folders and native preset/Custom behavior preserved.
+7
View File
@@ -0,0 +1,7 @@
# DOGMA 1.0.57 / API Platform V5
Optional “Correggi scatti” for both Seedance video workflows. Saves the original plus a separate `_FIX.mp4`; no extra API generation. Content-based motion analysis detects short holds, isolated jumps and recurring cadence at the source framerate. Local timeline repair preserves frame count, timestamps, dimensions and audio packets. Selective RIFE 4.26 inference uses the original resolution and 16-bit RGB intermediates; 10-bit sources stay 10-bit. Reliably tracked pans with repeated jumps also receive restrained camera translation correction in the same encoding pass, bounded to 0.4% of each dimension, with narrow reflected edge fill and no crop/zoom. Camera correction is skipped for clean clips, unreliable tracking, zoom, rotation or reversing camera paths. NVIDIA hardware encoding is preferred, with software encoding fallback. Shot boundaries, intentional holds and motion checks limit unnecessary changes. Unchanged clips are copied without re-encoding. Saving/repair runs outside the async API event loop; concurrent outputs reserve separate filenames. Stop cancels local processing; errors preserve the already generated original. Project/scene library records include both variants and the repair report.
Video preview play overlay follows the supplied design: white filled triangle, thin outline circle, 50% opacity. The Run button is unchanged.
RIFE weights download automatically once (approximately 23 MB) into ComfyUI/models/DOGMA/rife, only when a repair is needed. The pinned model archive and weights are SHA-256 verified; no downloaded Python is executed. RIFE architecture and weights are MIT licensed; see LICENSE_RIFE.txt. Previous node IDs and workflows remain compatible.
+3
View File
@@ -0,0 +1,3 @@
# DOGMA 1.0.58
Add `DOGMASeedanceVideoFix`, a standalone native VIDEO adapter for the existing 1.0.57 stutter repair. It takes only the generated video and returns the corrected video, with progress, cancellation and a clear result status. No API jobs or original-footage input. Native LoadVideo and SaveVideo complete the three-node workflow. Keep SaveVideo codec auto to avoid a second re-encode. Existing nodes and the API Platform repair engine are unchanged; no new dependencies.
+5
View File
@@ -0,0 +1,5 @@
# DOGMA 1.0.59
Fix **Correggi scatti** rejecting valid videos whose duration is not an exact number of milliseconds. Preserve source-clock precision in both MP4 movie and video track headers instead of using the default 1000 Hz movie clock. Applies to the shared NVIDIA and software repair encoder. Strict duration, frame timestamp, fps, color and audio checks are unchanged; no tolerance is loosened and no extra processing pass is added.
Validation: real API output-node execution, corrected-copy export and UI record; 457-frame 24 fps failure case; 24/25/60 and 24000/1001, 30000/1001, 60000/1001 timing cases through both encoders; fractional-fps audio preserved; a deliberate one-frame duration mismatch still rejected; repair disabled, error retention, cancellation and concurrent output naming. No paid generation requests were made. Existing API Platform and standalone workflows remain compatible.
+8
View File
@@ -0,0 +1,8 @@
# DOGMA 1.0.60
- Add synchronized, persistent Compare ON/OFF switches in gallery filters and the enlarged-image toolbar, using the existing compact lever style.
- Disable image hover comparison immediately when OFF, including an already visible overlay. Explicit A/B selection continues to open and enable comparison automatically. Show the enlarged-image control as unavailable when no comparison image exists.
- Remove only the excess left inset below Image/Video. Preserve the right edge, with references, prompt, workspace and models aligned in both modes.
- Refresh frontend module/style cache versions. No changes to API execution, video repair, dependencies or workflow identifiers.
Verified in the local browser preview with the real UI modules: switch synchronization, OFF persistence after reload, keyboard interaction, overlay ON/OFF, zoom, automatic A/B, missing-reference state, and exact section/tab edge alignment in Image and Video. Package integrity checked without publication or paid generation.
+9
View File
@@ -0,0 +1,9 @@
# DOGMA 1.0.61
- Reorder model blocks by dragging their existing headings vertically, with no additional controls.
- Save model order in the session/workflow and retain it across reloads and Image/Video mode changes. Ignore unknown or duplicated saved keys and include newly available models.
- Preserve expansion, switches and all parameter values while moving existing blocks. Keep ordinary heading clicks and cancel a drag released outside the list. Support Escape and edge scrolling.
- Align the visible sidebar switches with the Image/Video tabs and section dividers while retaining their click-target sizes and the existing text positions.
- Change presentation only: generation planning, seeds, API payloads, video repair and workflow identifiers are unchanged.
Verified with the actual UI in the local browser preview: upward and downward drag, outside-drop cancellation, persistence after reload and mode switching, normal accordion clicks and enable switches. Sidebar switch, divider and tab edges match in Image and Video mode. Generation plans and compiled payloads checked before/after visual reordering. JavaScript syntax and package integrity checked without publication or paid generation.
+9
View File
@@ -0,0 +1,9 @@
# DOGMA 1.0.62
- Fix false Seedream rejection of odd Custom dimensions. Preserve the exact requested width and height, including 2816 × 1485.
- Respect preset precedence over unused Custom fields. Check Seedream's actual megapixel/range/aspect limits before queueing and identify the relevant fields.
- Reveal invalid fields and clear their validation error after correction. Release submission state and queue hooks even when preparation or native submission fails; allow a manual retry without restart.
- Replace a reference when files are dropped onto its thumbnail. Preserve slot/state/role and clear obsolete masks/crops/previews. Keep the original reference if upload fails; validate image/video and First/Last constraints before upload.
- No changes to workflow IDs, API authentication, backend generation or video repair. No paid requests or automatic retries during verification.
Validation: exact Custom payload and preset regression tests; real Seedream limits; upload failures and replacement routing with hidden references; image/video and First/Last roles; Run and queue failure/retry cleanup. Browser preview confirmed invalid-field focus, correction to 2816 × 1485, and successful mocked resubmission after a simulated Comfy error. Package integrity and JavaScript syntax checked.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 hzwer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+56
View File
@@ -200,3 +200,59 @@ Existing DOGMA and H3 workflows keep their identifiers.
## API Platform V3 / 1.0.55
Open DOGMA_API_PLATFORM_V3.json: one launcher node. The panel appears before asynchronous initialization. Folder navigation stays in the browser. Stop cancels DOGMA jobs; provider billing for already completed work still applies. Remaining time is an estimate from completed jobs when available.
## API Platform V4 / 1.0.56
Open DOGMA_API_PLATFORM_V4.json: one launcher node. The panel appears before asynchronous initialization. Folder navigation stays in the browser. Stop cancels DOGMA jobs; provider billing for already completed work still applies. Remaining time is an estimate from completed jobs when available.
## API Platform V5 / 1.0.57 — selective video repair
Enable **Correggi scatti** in Video to save both the original and `_FIX.mp4`. Both Ref → Video and First / Last frame use the same local repair. The setting does not change paid API inputs, quantities or seeds. A verified unchanged copy is produced when no reliable problem is detected. If processing fails or is stopped, the original remains available and the panel shows a warning.
The detector operates on small previews; RIFE reconstructs only selected frames at source resolution. Reliable pans with repeated jumps may additionally receive small camera translations, capped at 0.4% of width/height. This extends a thin edge strip by reflection instead of cropping or zooming. Camera refinement and interpolation share one encoding pass. Clean clips, poorly tracked shots, zooms and reversing camera paths are not stabilized. Frame count, timestamps, source bit depth and audio packet identity are checked before accepting the second file. A motion-based quality gate is an additional check, not a guarantee against every possible visual artifact. The method is independent of source fps and has no fixed clip-duration setting; processing time and memory grow with frame count and resolution. It does not impose 24 fps. CUDA and NVIDIA video encoding provide the fast path; CPU/software fallback is slower. First use includes model download and GPU initialization. No video is uploaded to another service. Generative deformations or newly invented content cannot be reliably restored by a cadence repair.
RIFE 4.26 code/weights: https://github.com/hzwer/Practical-RIFE (MIT; LICENSE_RIFE.txt). Verified weights are automatically cached under `models/DOGMA/rife`. Architecture derived from the official model archive, revision `01fdc7e97404120c243c3ea7b427046e5dc7643e`. DOGMA motion detection, timestamp planning and integration are separate from RIFE inference. No other ComfyUI interpolation extension is required.
## Standalone Seedance fix / 1.0.58
`Load Video → DOGMA / Fix video Seedance → Save Video` uses only the generated video. No original footage, API generation, credentials or credits are needed. The node reuses the unchanged 1.0.57 repair engine and its cached RIFE weights. Progress and a short result message are reported in ComfyUI. Clips without confidently detected stutter are returned unchanged; a rejected correction is explicitly reported as unchanged.
Use MP4 and codec **auto** in Save Video to preserve the corrected stream without another encoding pass. The supplied standalone workflow writes to `output/DOGMA/SeedanceFix/Seedance_FIX_*.mp4`. Duration, fps, frame timestamps, dimensions, color depth and audio are checked by the repair engine. The uploaded source is not overwritten. The fix runs outside the async event loop; Stop cancels processing and removes that attempt's partial files. Intermediate output and diagnostics live in ComfyUI's temp directory, so cached results can be saved again without repeating inference.
Existing API Platform, H3 and HDR workflows remain compatible. The same package supports Windows and the pod. No extra node pack is required.
## Correggi scatti: precise MP4 timing / 1.0.59
Fix the shared repair encoder used by API Platform's **Correggi scatti** switch and the standalone Seedance fix node. MP4's default 1000 Hz movie clock could truncate fractional-second clip ends and trigger "La durata del file corretto è cambiata", even with every frame and timestamp intact. For example, a 457-frame, 24 fps clip was rejected because the reported duration differed by eight video-clock ticks.
Both the NVIDIA and software encoder now use the source video's time base for the MP4 movie and video track clocks. The strict checks on frame count, timestamps, duration, fps, dimensions, color depth and copied audio remain in place. This changes only the container timing; motion analysis, interpolation, quality gates and correction settings are unchanged. It adds no interpolation or encoding pass.
When enabled, API Platform saves the generated original and a second locally processed copy in the existing project/scene workspace. Turning the switch off skips repair. Stop and real processing errors retain the original and report the outcome; an unsuccessful correction is never presented as repaired. Existing workflows and node IDs are compatible, with no new dependencies and the same code on Windows and the pod.
## Compare controls and sidebar alignment / 1.0.60
API Platform now has a compact **Compare** switch next to **Mostra errori** in the gallery filters and at the right of the enlarged image toolbar. Both controls share one saved session preference. OFF removes the original/reference overlay and divider immediately; ON enables the existing pointer comparison. Existing sessions default to ON. Selecting an explicit A/B pair still opens the comparison automatically and enables Compare. The enlarged-image switch is unavailable when there is no second image to compare.
The extra left inset below the Image/Video tabs is removed from the controls and Image Edit row. References, prompt, filename/workspace and model sections now align with the left edge of the tabs; their existing right edge is preserved. Works in Image and Video mode. Existing node IDs, generation behavior, video repair and workflow JSON are unchanged.
## Drag to reorder models / 1.0.61
Drag an existing model heading up or down to change the order of the blocks under **MODELS**. The order is saved with the session/workflow, including when switching between Image and Video. No new buttons or drag handles are added. A normal click still expands or collapses the model; switches, quantities and parameters keep their usual behavior. Drag near the sidebar edge to scroll, or release outside the list / press Escape to cancel.
The visible switches in model headings, Image Edit, the date row and video repair align with the left edge of the Image/Video tabs and section dividers. Their existing click targets and text positions are preserved; switches inside reference thumbnails and parameter fields keep their own inset.
Generation quantities and seeds, API execution, video repair behavior and existing workflow identifiers remain unchanged. Previous workflows load with their original model order.
## Seedream Custom dimensions and reference replacement / 1.0.62
Seedream Custom dimensions such as **2816 × 1485** are submitted exactly as entered. The previous DOGMA check incorrectly treated the native widget's increment of 2 as a mandatory divisibility rule. Selecting a size preset now validates that preset, rather than the unused Custom values. Current Seedream pixel-count and aspect-ratio limits are checked before submission; errors identify and reveal the affected fields. Correcting a value allows Run to be retried without reopening Comfy. Submission cleanup also restores the queue hooks and releases the DOGMA lock after preparation or queue failures. No automatic retries or dimension rounding are introduced.
Drop an image or video file directly on an existing reference thumbnail to replace that slot. Drops elsewhere keep adding references. If multiple files are dropped onto a thumbnail, the first replaces it and the remaining files are added. Replacement preserves position, enabled state, modes and First/Last role; old masks, crops and previews are discarded because they belong to the previous file. A failed upload leaves the old reference intact. Image-only modes still reject video, and First/Last mode still permits at most two images.
Existing workflow JSON, model ordering, compare controls and video-repair behavior remain unchanged.
+12
View File
@@ -243,3 +243,15 @@ try:
del _APIV2, _APIV2_NAMES, _APIV2_ROUTES
except Exception as _apiv2_error:
print("[DOGMA API V2] Unavailable; previous DOGMA nodes preserved:", _apiv2_error)
# Standalone Seedance fix: same engine as API Platform, one VIDEO input.
try:
from .dogma_video_fix_node import NODE_CLASS_MAPPINGS as _FIX158, NODE_DISPLAY_NAME_MAPPINGS as _FIX158_NAMES
if set(_FIX158).intersection(NODE_CLASS_MAPPINGS):
raise RuntimeError("DOGMA Seedance fix: node ID collision")
NODE_CLASS_MAPPINGS.update(_FIX158)
NODE_DISPLAY_NAME_MAPPINGS.update(_FIX158_NAMES)
del _FIX158, _FIX158_NAMES
except Exception as _fix158_error:
print("[DOGMA Seedance fix] Unavailable; previous DOGMA nodes preserved:", _fix158_error)
+124 -12
View File
@@ -103,7 +103,7 @@ def _import_workspace(root):
candidate=(path.parent.parent/relative/name).resolve()
else:candidate=(path.parent/name).resolve()
if not candidate.is_relative_to(root) or not candidate.is_file():continue
files.append({'filename':name,'workspace':str(root),'relative':candidate.relative_to(root).as_posix(),'type':'workspace'})
files.append({'filename':name,'workspace':str(root),'relative':candidate.relative_to(root).as_posix(),'type':'workspace',**({'variant':original['variant']} if original.get('variant') else {})})
exported.append(str(candidate))
if not files:continue
data.update(workspace=str(root),images=files,exported=exported,status='completed',imported=True)
@@ -113,6 +113,53 @@ def _import_workspace(root):
return records
_SAM_LOCK = threading.Lock()
def prompt_mask(source, image, settings):
"""Compute the installed SAM3 node once and retain the exact mask for Run."""
import inspect
import numpy as np
import torch
import nodes
import folder_paths
from PIL import Image
prompt = str(settings.get('prompt', '')).strip()
if not prompt:raise ValueError('Scrivi cosa selezionare in MASK PROMPT.')
node_class = nodes.NODE_CLASS_MAPPINGS.get('SAM3Segment')
if node_class is None:raise ValueError('SAM3 non è disponibile. Installa o abilita il nodo SAM3Segment di ComfyUI-RMBG e riavvia Comfy.')
stat = source.stat()
signature = json.dumps([str(source),stat.st_mtime_ns,stat.st_size,prompt,int(settings.get('segment') or 0),node_class.__module__],ensure_ascii=False)
digest = hashlib.sha256(signature.encode()).hexdigest()
directory = Path(folder_paths.get_input_directory())/'DOGMA_API'/'masks'
directory.mkdir(parents=True,exist_ok=True)
path = directory/('sam3_'+digest+'.png')
with _SAM_LOCK:
if not path.is_file():
instance = node_class()
function = getattr(instance,node_class.FUNCTION)
specs = node_class.INPUT_TYPES()
values = {}
for name,spec in {**specs.get('required',{}),**specs.get('optional',{})}.items():
options=spec[1] if len(spec)>1 and isinstance(spec[1],dict) else {}
if 'default' in options:values[name]=options['default']
elif isinstance(spec[0],list) and spec[0]:values[name]=spec[0][0]
values.update(image=torch.from_numpy(np.asarray(image.convert('RGB')).copy()).float().unsqueeze(0)/255,prompt=prompt,output_mode='Merged',confidence_threshold=.5,max_segments=0,segment_pick=int(settings.get('segment') or 0),mask_blur=0,mask_offset=0,device='Auto',invert_output=False,unload_model=True,background='Alpha',background_color='#222222')
parameters=inspect.signature(function).parameters
values={key:value for key,value in values.items() if key in parameters}
with torch.inference_mode():result=function(**values)
if isinstance(result,dict):result=result.get('result',())
if not result or len(result)<2:raise ValueError('SAM3 non ha restituito una maschera.')
masks=result[1].detach().cpu()
if masks.numel()==0:mask=Image.new('L',image.size,0)
else:
if masks.ndim==3:masks=masks.amax(dim=0)
mask=Image.fromarray((masks.numpy().clip(0,1)*255).astype(np.uint8)).resize(image.size,Image.Resampling.NEAREST)
temporary=path.with_suffix('.tmp')
mask.save(temporary,format='PNG');temporary.replace(path)
return Image.open(path).convert('L'), 'DOGMA_API/masks/'+path.name
def process_reference(image, mask, settings):
"""Shared Pillow operation used by the node and by the no-generation preview."""
import numpy as np
@@ -150,7 +197,7 @@ def process_reference(image, mask, settings):
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'))
background = Image.new('RGB', image.size, ImageColor.getrgb(cfg.get('background') or '#ff00ff'))
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)
@@ -213,17 +260,65 @@ class DOGMAAPIVideoOutputV2:
FUNCTION='save'
CATEGORY='DOGMA/API Platform'
def save(self,video,metadata,prompt=None,extra_pnginfo=None):
async def save(self,video,metadata,prompt=None,extra_pnginfo=None):
cancelled=threading.Event()
worker=asyncio.create_task(asyncio.to_thread(self._save,video,metadata,prompt,extra_pnginfo,cancelled))
try:
return await asyncio.shield(worker)
except asyncio.CancelledError:
cancelled.set()
# Let the worker retain the generated original and remove its partial fix.
try:await worker
except Exception:pass
raise
def _save(self,video,metadata,prompt=None,extra_pnginfo=None,cancelled=None):
from comfy_api.latest import Types
import folder_paths
from comfy.cli_args import args
data=json.loads(metadata);width,height=video.get_dimensions()
folder,filename,counter,subfolder,_=folder_paths.get_save_image_path(_save_prefix(data),str(_output()),width,height)
filename=f'{filename}_{counter:05}_.mp4'
with _LOCK:
folder,stem,counter,subfolder,_=folder_paths.get_save_image_path(_save_prefix(data),str(_output()),width,height)
while True:
filename=f'{stem}_{counter:05}_.mp4';source=Path(folder)/filename
try:
# Reserve before releasing the lock; async branches must never overwrite.
with source.open('xb'):pass
break
except FileExistsError:counter+=1
saved_metadata=None if args.disable_metadata else {**(extra_pnginfo or {}),'prompt':prompt}
video.save_to(str(Path(folder)/filename),format=Types.VideoContainer('mp4'),codec=Types.VideoCodec('auto'),metadata=saved_metadata)
try:
video.save_to(str(source),format=Types.VideoContainer('mp4'),codec=Types.VideoCodec('auto'),metadata=saved_metadata)
except BaseException:
source.unlink(missing_ok=True)
raise
files=[{'filename':filename,'subfolder':subfolder,'type':'output','format':'video/mp4'}]
record=_record(metadata,files,'video')
if data.get('videoRepair'):
files[0]['variant']='original'
try:
from .dogma_video_repair import repair_video
import comfy.model_management as management
from server import PromptServer
def progress(stage, fraction):
# The job ID is stable before/after the batch receives its prompt ID.
PromptServer.instance.send_sync('dogma_video_repair',{'job_id':data['id'],'stage':stage,'value':fraction})
def check_cancel():
from .dogma_video_repair import RepairCancelled
if cancelled is not None and cancelled.is_set():raise RepairCancelled('Correzione interrotta.')
management.throw_exception_if_processing_interrupted()
fixed=source.with_name(source.stem+'_FIX.mp4')
report=repair_video(source,fixed,Path(folder_paths.models_dir)/'DOGMA'/'rife',
cancel=check_cancel,progress=progress)
data['repair']=report
files.append({'filename':fixed.name,'subfolder':subfolder,'type':'output','format':'video/mp4',
'variant':'repaired' if report['status']=='repaired' else 'checked'})
if report['status']=='skipped_quality':
data['warning']='Fix non applicato: il controllo del movimento non ha confermato un miglioramento. La seconda copia conserva l’originale.'
except Exception as exc:
# Never repeat a paid generation when only local post-processing fails.
data['repair']={'status':'failed','error':str(exc)}
data['warning']='Originale salvato. Correzione scatti non completata: '+(str(exc) or 'interrotta')
record=_record(json.dumps(data,ensure_ascii=False),files,'video')
return {'ui':{'images':files,'animated':(True,),'dogma_records':[record]},'result':()}
@@ -256,7 +351,7 @@ def register_routes():
@routes.get('/dogma/api/v2/catalog')
async def catalog(request):
capabilities=access.catalog(request,_output())
return web.json_response({'access':{**capabilities,'output_root':str(_output()/'DOGMA'/'API')},'frontend':frontend_modules(PromptServer.instance.web_root),'version':'1.0.55'})
return web.json_response({'access':{**capabilities,'output_root':str(_output()/'DOGMA'/'API')},'frontend':frontend_modules(PromptServer.instance.web_root),'version':'1.0.56'})
@routes.post('/dogma/api/v2/workspace')
async def workspace(request):
@@ -348,6 +443,19 @@ def register_routes():
return web.json_response({'path':str(file.parent),'filename':file.name})
except (ValueError,OSError,IndexError,KeyError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.post('/dogma/api/v2/explorer')
async def explorer(request):
access.browser(request)
if not access.is_local(request) or os.name!='nt':
raise web.HTTPBadRequest(text='Esplora file è disponibile sul computer Windows che esegue Comfy. Usa il browser cartelle su un server remoto.')
data=await request.json()
try:
path=access.output_path(request,data.get('path'),_output())
if not path.is_dir():raise ValueError('Cartella inesistente.')
os.startfile(str(path))
return web.json_response({'opened':True})
except (ValueError,OSError) 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()
@@ -357,17 +465,21 @@ def register_routes():
if not source.is_relative_to(Path(folder_paths.get_input_directory()).resolve()):raise ValueError('Reference esterna a input.')
rgba=ImageOps.exif_transpose(Image.open(source)).convert('RGBA');mask=ImageOps.invert(rgba.getchannel('A'))
settings=data['settings']
if settings.get('source')=='prompt' and settings.get('mask'):raise ValueError('La maschera da testo viene calcolata da SAM3 durante Run. Per l’anteprima usa una maschera dipinta.')
if settings.get('maskFile'):
sam_file=None
if settings.get('source')=='prompt' and settings.get('mask'):
mask,sam_file=prompt_mask(source,rgba,settings)
elif 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}
response={'file':'DOGMA_API/previews/'+filename,'width':result.width,'height':result.height}
if sam_file:response.update(maskFile=sam_file,samSource=data['file'],samPrompt=settings['prompt'],samSegment=int(settings.get('segment') or 0),emptyMask=not bool(mask.getbbox()))
return response
try:return web.json_response(await asyncio.to_thread(prepare))
except (ValueError,OSError,KeyError) as exc:raise web.HTTPBadRequest(text=str(exc))
except (ValueError,OSError,KeyError,RuntimeError,ImportError) as exc:raise web.HTTPBadRequest(text=str(exc))
NODE_CLASS_MAPPINGS={'DOGMAAPIReferenceV2':DOGMAAPIReferenceV2,'DOGMAAPIImageOutputV2':DOGMAAPIImageOutputV2,'DOGMAAPIVideoOutputV2':DOGMAAPIVideoOutputV2}
+193
View File
@@ -0,0 +1,193 @@
# RIFE 4.26 inference architecture, adapted from hzwer/Practical-RIFE.
# MIT license, Copyright (c) 2021 hzwer. See LICENSE_RIFE.txt.
# Changes: package-local warp, device/dtype-aware bounded grid cache.
import torch
backwarp_tenGrid={}
def warp(tenInput, tenFlow):
flow_device = tenFlow.device
k = (str(flow_device), str(tenFlow.size()), str(tenFlow.dtype))
if k not in backwarp_tenGrid:
tenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3], device=flow_device).view(
1, 1, 1, tenFlow.shape[3]).expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1)
tenVertical = torch.linspace(-1.0, 1.0, tenFlow.shape[2], device=flow_device).view(
1, 1, tenFlow.shape[2], 1).expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3])
backwarp_tenGrid[k] = torch.cat(
[tenHorizontal, tenVertical], 1).to(flow_device)
tenFlow = torch.cat([tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0),
tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0)], 1)
g = (backwarp_tenGrid[k] + tenFlow).permute(0, 2, 3, 1)
if len(backwarp_tenGrid)>8:backwarp_tenGrid.clear()
g=g.to(tenInput.dtype)
return torch.nn.functional.grid_sample(input=tenInput, grid=g, mode='bilinear', padding_mode='border', align_corners=True)
import torch
import torch.nn as nn
import torch.nn.functional as F
# from train_log.refine import *
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation, bias=True),
nn.LeakyReLU(0.2, True)
)
def conv_bn(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation, bias=False),
nn.BatchNorm2d(out_planes),
nn.LeakyReLU(0.2, True)
)
class Head(nn.Module):
def __init__(self):
super(Head, self).__init__()
self.cnn0 = nn.Conv2d(3, 16, 3, 2, 1)
self.cnn1 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn2 = nn.Conv2d(16, 16, 3, 1, 1)
self.cnn3 = nn.ConvTranspose2d(16, 4, 4, 2, 1)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x, feat=False):
x0 = self.cnn0(x)
x = self.relu(x0)
x1 = self.cnn1(x)
x = self.relu(x1)
x2 = self.cnn2(x)
x = self.relu(x2)
x3 = self.cnn3(x)
if feat:
return [x0, x1, x2, x3]
return x3
class ResConv(nn.Module):
def __init__(self, c, dilation=1):
super(ResConv, self).__init__()
self.conv = nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1\
)
self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True)
self.relu = nn.LeakyReLU(0.2, True)
def forward(self, x):
return self.relu(self.conv(x) * self.beta + x)
class IFBlock(nn.Module):
def __init__(self, in_planes, c=64):
super(IFBlock, self).__init__()
self.conv0 = nn.Sequential(
conv(in_planes, c//2, 3, 2, 1),
conv(c//2, c, 3, 2, 1),
)
self.convblock = nn.Sequential(
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
ResConv(c),
)
self.lastconv = nn.Sequential(
nn.ConvTranspose2d(c, 4*13, 4, 2, 1),
nn.PixelShuffle(2)
)
def forward(self, x, flow=None, scale=1):
x = F.interpolate(x, scale_factor= 1. / scale, mode="bilinear", align_corners=False)
if flow is not None:
flow = F.interpolate(flow, scale_factor= 1. / scale, mode="bilinear", align_corners=False) * 1. / scale
x = torch.cat((x, flow), 1)
feat = self.conv0(x)
feat = self.convblock(feat)
tmp = self.lastconv(feat)
tmp = F.interpolate(tmp, scale_factor=scale, mode="bilinear", align_corners=False)
flow = tmp[:, :4] * scale
mask = tmp[:, 4:5]
feat = tmp[:, 5:]
return flow, mask, feat
class IFNet(nn.Module):
def __init__(self):
super(IFNet, self).__init__()
self.block0 = IFBlock(7+8, c=192)
self.block1 = IFBlock(8+4+8+8, c=128)
self.block2 = IFBlock(8+4+8+8, c=96)
self.block3 = IFBlock(8+4+8+8, c=64)
self.block4 = IFBlock(8+4+8+8, c=32)
self.encode = Head()
# not used during inference
'''
self.teacher = IFBlock(8+4+8+3+8, c=64)
self.caltime = nn.Sequential(
nn.Conv2d(16+9, 8, 3, 2, 1),
nn.LeakyReLU(0.2, True),
nn.Conv2d(32, 64, 3, 2, 1),
nn.LeakyReLU(0.2, True),
nn.Conv2d(64, 64, 3, 1, 1),
nn.LeakyReLU(0.2, True),
nn.Conv2d(64, 64, 3, 1, 1),
nn.LeakyReLU(0.2, True),
nn.Conv2d(64, 1, 3, 1, 1),
nn.Sigmoid()
)
'''
def forward(self, x, timestep=0.5, scale_list=[8, 4, 2, 1], training=False, fastmode=True, ensemble=False):
if training == False:
channel = x.shape[1] // 2
img0 = x[:, :channel]
img1 = x[:, channel:]
if not torch.is_tensor(timestep):
timestep = (x[:, :1].clone() * 0 + 1) * timestep
else:
timestep = timestep.repeat(1, 1, img0.shape[2], img0.shape[3])
f0 = self.encode(img0[:, :3])
f1 = self.encode(img1[:, :3])
flow_list = []
merged = []
mask_list = []
warped_img0 = img0
warped_img1 = img1
flow = None
mask = None
loss_cons = 0
block = [self.block0, self.block1, self.block2, self.block3, self.block4]
for i in range(5):
if flow is None:
flow, mask, feat = block[i](torch.cat((img0[:, :3], img1[:, :3], f0, f1, timestep), 1), None, scale=scale_list[i])
if ensemble:
print("warning: ensemble is not supported since RIFEv4.21")
else:
wf0 = warp(f0, flow[:, :2])
wf1 = warp(f1, flow[:, 2:4])
fd, m0, feat = block[i](torch.cat((warped_img0[:, :3], warped_img1[:, :3], wf0, wf1, timestep, mask, feat), 1), flow, scale=scale_list[i])
if ensemble:
print("warning: ensemble is not supported since RIFEv4.21")
else:
mask = m0
flow = flow + fd
mask_list.append(mask)
flow_list.append(flow)
warped_img0 = warp(img0, flow[:, :2])
warped_img1 = warp(img1, flow[:, 2:4])
merged.append((warped_img0, warped_img1))
mask = torch.sigmoid(mask)
merged[4] = (warped_img0 * mask + warped_img1 * (1 - mask))
if not fastmode:
print('contextnet is removed')
'''
c0 = self.contextnet(img0, flow[:, :2])
c1 = self.contextnet(img1, flow[:, 2:4])
tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1)
res = tmp[:, :3] * 2 - 1
merged[4] = torch.clamp(merged[4] + res, 0, 1)
'''
return flow_list, mask_list[4], merged
+81
View File
@@ -0,0 +1,81 @@
"""Standalone VIDEO adapter for the same repair engine used by API Platform."""
import asyncio
import json
from pathlib import Path
import tempfile
import threading
from comfy_api.latest import io, ui, InputImpl, Types
class DOGMASeedanceVideoFix(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="DOGMASeedanceVideoFix",
display_name="DOGMA / Fix video Seedance",
category="DOGMA/Video",
description="Corregge gli scatti del solo video generato da Seedance. "
"Mantiene fps, durata, risoluzione e audio. Non richiede il video originale o API.",
inputs=[io.Video.Input("video", tooltip="Collega il video generato da Seedance.")],
outputs=[io.Video.Output("video_corretto")],
hidden=[io.Hidden.unique_id],
)
@classmethod
async def execute(cls, video):
cancelled=threading.Event()
worker=asyncio.create_task(asyncio.to_thread(cls._repair,video,cancelled,cls.hidden.unique_id))
try:
result,summary=await asyncio.shield(worker)
return io.NodeOutput(result,ui=ui.PreviewText(summary))
except asyncio.CancelledError:
cancelled.set()
try:await worker
except Exception:pass
raise
@staticmethod
def _repair(video,cancelled,node_id=None):
import folder_paths
import comfy.model_management as management
from comfy.utils import ProgressBar
from .dogma_video_repair import RepairCancelled,repair_video
progress=ProgressBar(100,node_id=node_id)
def check():
if cancelled.is_set():raise RepairCancelled("Correzione interrotta.")
management.throw_exception_if_processing_interrupted()
def update(stage,fraction):
check()
progress.update_absolute(round(max(0,min(1,fraction))*100))
check()
root=Path(folder_paths.get_temp_directory());root.mkdir(parents=True,exist_ok=True)
work=Path(tempfile.mkdtemp(prefix="dogma-seedance-fix-",dir=root))
source=work/'input.mp4';fixed=work/'corrected.mp4';report_file=work/'repair.json'
try:
# Native save remuxes uploaded MP4 streams. It also honors VIDEO trims
# if this node is reused in a larger graph, without tensorizing the clip.
video.save_to(str(source),format=Types.VideoContainer.MP4,codec=Types.VideoCodec.AUTO)
check()
report=repair_video(source,fixed,Path(folder_paths.models_dir)/'DOGMA'/'rife',cancel=check,progress=update)
check()
if report['status']=='repaired':
summary=f"Correzione completata · {report['fps']} fps · {report['interpolated_frames']} fotogrammi ricostruiti"
elif report['status']=='unchanged':
summary="Nessuno scatto riconosciuto: il video è rimasto invariato."
else:
summary="Correzione non applicata: il controllo non ha confermato un miglioramento. Video invariato."
report_file.write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf8')
source.unlink()
# The result stays in Comfy's temp directory for SaveVideo and caching.
return InputImpl.VideoFromFile(str(fixed)),summary
except BaseException:
for path in (source,fixed,report_file):path.unlink(missing_ok=True)
work.rmdir()
raise
NODE_CLASS_MAPPINGS={"DOGMASeedanceVideoFix":DOGMASeedanceVideoFix}
NODE_DISPLAY_NAME_MAPPINGS={"DOGMASeedanceVideoFix":"DOGMA / Fix video Seedance"}
+562
View File
@@ -0,0 +1,562 @@
"""Selective motion repair. Original timestamps, frame count, audio and size survive.
Detection uses low-resolution tracked motion, never a hard-coded Seedance cadence.
RIFE 4.26 reconstructs only selected times, on the machine running ComfyUI.
"""
from __future__ import annotations
import hashlib
import json
import math
import os
from pathlib import Path
import shutil
import tempfile
import threading
import time
import urllib.request
import zipfile
from fractions import Fraction
import numpy as np
MODEL_URL = 'https://huggingface.co/hzwer/RIFE/resolve/01fdc7e97404120c243c3ea7b427046e5dc7643e/RIFEv4.26_0921.zip'
ARCHIVE_SHA256 = '1fa9b9cda3d9b8c3e301359e2595960902f97bf926c08598b0e9957a3f3f760e'
WEIGHT_SHA256 = '45c7f74156704769dc9f85cfcaf8552e1e926f9399dcfa3a553dee88fac6f53f'
_MODEL_LOCK = threading.Lock()
_RENDER_LOCK = threading.Lock()
class RepairCancelled(Exception):
pass
def _check(cancel):
if cancel:
cancel()
def _digest(path):
result=hashlib.sha256()
with open(path, 'rb') as f:
while block:=f.read(1024*1024):result.update(block)
return result.hexdigest()
def model_file(directory, cancel=None, progress=None):
"""Only verified weights are downloaded; remote Python is never executed."""
directory = Path(directory)
path = directory / 'rife426.pkl'
while not _MODEL_LOCK.acquire(timeout=.1):_check(cancel)
try:
_check(cancel)
if path.is_file() and _digest(path) == WEIGHT_SHA256:
return path
directory.mkdir(parents=True, exist_ok=True)
if progress:
progress('Download modello · solo al primo utilizzo', 0)
with tempfile.TemporaryDirectory(prefix='rife-', dir=directory) as temp:
archive = Path(temp) / 'model.zip'
with urllib.request.urlopen(MODEL_URL, timeout=30) as response, archive.open('wb') as out:
size = 0
while block := response.read(1024 * 1024):
_check(cancel)
size += len(block)
if size > 30_000_000:
raise ValueError('Download RIFE di dimensione inattesa.')
out.write(block)
if _digest(archive) != ARCHIVE_SHA256:
raise ValueError('Verifica del modello RIFE non riuscita. Riprova il download.')
weight = Path(temp) / 'weights.pkl'
with zipfile.ZipFile(archive) as z:
weight.write_bytes(z.read('RIFEv4.26_0921/flownet.pkl'))
if _digest(weight) != WEIGHT_SHA256:
raise ValueError('Pesi RIFE non validi.')
_check(cancel)
weight.replace(path)
return path
finally:
_MODEL_LOCK.release()
def measure_pair(a, b):
"""Track real displacements; pixel differences alone confuse light and motion."""
import cv2
af, bf = a.astype(np.float32), b.astype(np.float32)
diff = float(np.mean(np.abs(bf-af)))
light = float(abs(np.mean(bf)-np.mean(af)))
row = dict(diff=diff, brightness=light, motion=0., x=0., y=0., reliability=0., cut=False)
points = cv2.goodFeaturesToTrack(a, 500, .015, 5)
if points is None or len(points) < 12:
row['cut'] = diff > 18
return row
q, ok, _ = cv2.calcOpticalFlowPyrLK(a, b, points, None, winSize=(21,21), maxLevel=3)
back, ok2, _ = cv2.calcOpticalFlowPyrLK(b, a, q, None, winSize=(21,21), maxLevel=3)
good = (ok[:,0] > 0) & (ok2[:,0] > 0) & (np.linalg.norm(back[:,0]-points[:,0], axis=1) < .6)
row['reliability'] = float(good.mean())
vectors = (q[:,0]-points[:,0])[good]
if len(vectors) >= 12:
# A camera estimate needs agreement across the image, not just one subject.
p, tracked = points[good,0], q[good,0]
transform, inside = cv2.estimateAffinePartial2D(p, tracked, method=cv2.RANSAC,
ransacReprojThreshold=.25, maxIters=500, confidence=.995, refineIters=5)
if transform is not None and inside is not None:
selected=p[inside[:,0]>0];h,w=a.shape
occupied={(min(3,int(x*4/w)),min(2,int(y*3/h))) for x,y in selected}
center=np.array([w/2,h/2]);delta=transform[:,:2]@center+transform[:,2]-center
coverage=float(np.prod(np.ptp(selected,axis=0)/[w,h])) if len(selected)>1 else 0.
row['camera']=dict(x=float(delta[0]),y=float(delta[1]),
inliers=float(inside.mean()),coverage=coverage,cells=len(occupied),
scale=float(np.sqrt(abs(np.linalg.det(transform[:,:2])))),
angle=float(np.degrees(np.arctan2(transform[1,0],transform[0,0]))))
magnitudes=np.linalg.norm(vectors,axis=1)
moving=vectors[magnitudes>max(.05,float(np.percentile(magnitudes,90))*.35)]
# A moving subject can occupy less than half of an otherwise static shot.
if np.median(magnitudes)<.04 and len(moving)>=max(12,len(vectors)*.1):vectors=moving
row['motion'] = float(np.percentile(np.linalg.norm(vectors, axis=1), 75))
row['x'], row['y'] = map(float, np.median(vectors, axis=0))
# Histogram changes plus failed tracking distinguish cuts from fast pans.
ha = cv2.calcHist([a],[0],None,[32],[0,256]); hb = cv2.calcHist([b],[0],None,[32],[0,256])
ha /= max(1., float(ha.sum())); hb /= max(1., float(hb.sum()))
hist = cv2.compareHist(ha, hb, cv2.HISTCMP_BHATTACHARYYA)
row['cut'] = bool((diff > 24 and row['reliability'] < .45) or (diff > 36 and hist > .4))
return row
def analyze(source, cancel=None, progress=None):
import av
import cv2
start = time.perf_counter()
with av.open(str(source)) as c:
v = c.streams.video[0]
v.thread_type = 'AUTO';v.thread_count=4
fps = v.average_rate or v.base_rate
if not fps or fps <= 0:
raise ValueError('Il video non dichiara un framerate valido.')
meta = dict(fps=str(fps), time_base=str(v.time_base), width=v.width, height=v.height,
pixel_format=v.format.name, bit_depth=max(x.bits for x in v.format.components),
color_range=v.codec_context.color_range, colorspace=v.codec_context.colorspace,
color_primaries=v.codec_context.color_primaries, color_trc=v.codec_context.color_trc,
audio_streams=len(c.streams.audio), sample_aspect_ratio=str(v.sample_aspect_ratio or Fraction(1)),
duration=float(v.duration*v.time_base) if v.duration else None)
frames, pts, durations, metrics = [], [], [], []
width = min(384, v.width); height = max(16, round(v.height * width / v.width))
for i, f in enumerate(c.decode(v)):
_check(cancel)
# swscale shrinks before transferring the ndarray.
gray = f.reformat(width=width, height=height, format='gray').to_ndarray()
metrics.append(measure_pair(frames[-1], gray) if frames else dict(diff=0.,brightness=0.,motion=0.,x=0.,y=0.,reliability=1.,cut=False))
frames.append(gray)
pts.append(int(f.pts) if f.pts is not None else round(i/fps/v.time_base))
durations.append(int(f.duration or round(1/fps/v.time_base)))
if progress and i % 12 == 0:
progress('Analisi movimento', .18 * min(1., (i+1)/max(1,v.frames or i+12)))
if not frames:
raise ValueError('Il video non contiene fotogrammi decodificabili.')
if any(b <= a for a,b in zip(pts,pts[1:])):
raise ValueError('I timestamp del video non sono crescenti.')
meta.update(frames=len(frames), pts=pts, durations=durations,
analysis_seconds=round(time.perf_counter()-start,3))
return meta, frames, metrics
def plan_repair(metrics, times, fps):
"""Infer held frames and isolated/periodic jumps, with fixed local endpoints."""
n = len(metrics)
positions = np.arange(n, dtype=float)
motion = np.array([x['motion'] for x in metrics])
cuts = {i for i,m in enumerate(metrics) if m['cut']}
ratios = np.ones(n)
eligible = np.zeros(n, dtype=bool)
for i in range(3,n-3):
if any(x in cuts for x in range(i-3,i+4)):
continue
nearby = np.r_[motion[i-3:i], motion[i+1:i+4]]
base = float(np.median(nearby))
if base < .045:
continue
ratios[i] = motion[i]/base
before = np.array([np.median([metrics[j][k] for j in range(i-3,i)]) for k in ('x','y')])
after = np.array([np.median([metrics[j][k] for j in range(i+1,i+4)]) for k in ('x','y')])
current = np.array([metrics[i]['x'],metrics[i]['y']])
cosine = lambda x,y: float(np.dot(x,y)/max(1e-8,np.linalg.norm(x)*np.linalg.norm(y)))
eligible[i] = (metrics[i]['reliability'] > .65 and cosine(before,after) > .9
and cosine(current,before+after) > .75
and .6 < np.median(motion[i-3:i])/max(.01,np.median(motion[i+1:i+4])) < 1.67
and metrics[i]['brightness'] < max(.8,metrics[i]['diff']*.65))
spikes = {i for i in range(n) if eligible[i] and 1.65 < ratios[i] < 3.1}
patterns = []
# Search the cadence; do not assume 24 frames, 24 fps, or phase zero.
eligible_indices=np.flatnonzero(eligible);spike_indices=np.array(sorted(spikes),dtype=int)
for period in range(2, min(121, n//3+1)):
counts=np.bincount(eligible_indices%period,minlength=period)
hits=np.bincount(spike_indices%period,minlength=period)
for phase in np.flatnonzero((hits>=3)&(hits/np.maximum(1,counts)>=.65)):
patterns.append(dict(period=period,phase=int(phase),support=int(hits[phase]),count=int(counts[phase])))
patterns.sort(key=lambda x:(x['support']/x['count'],x['support'],-x['period']),reverse=True)
pattern = patterns[0] if patterns else None
if pattern:
spikes.update(i for i in range(3,n-3) if eligible[i] and i%pattern['period']==pattern['phase'] and ratios[i]>1.22)
pattern['seconds'] = round(pattern['period']/float(fps),6)
duplicates = []
i = 2
while i < n-2:
rest = float(np.median(motion[max(1,i-3):i]))
if rest < .06 or metrics[i]['diff'] > .65 or motion[i] > rest*.16:
i += 1; continue
first = i
while i < n-1 and metrics[i]['diff'] < .65 and motion[i] < rest*.16:
i += 1
last = i-1
# Long pauses and the beginning/end of a shot remain intentional holds.
if (last-first < max(1,min(4,round(float(fps)*.15))) and i<n-1
and not any(j in cuts for j in range(first-1,i+2))
and motion[i] > rest*1.45 and metrics[i]['reliability']>.65):
duplicates.append((first,last))
spikes.discard(i)
groups = []
for i in sorted(spikes):
left, right = i-3, i+2
if groups and left <= groups[-1][1]:
groups[-1] = (groups[-1][0],max(right,groups[-1][1]))
else:
groups.append((left,right))
for left,right in groups:
durations = np.diff(times[left:right+1])
units = durations.copy()
for j in range(left+1,right+1):
if j in spikes:
units[j-left-1] *= min(2.5, max(1.22,ratios[j]))
physical = np.r_[0., np.cumsum(units)]
target = (times[left:right+1]-times[left])/(times[right]-times[left])*physical[-1]
positions[left:right+1] = np.interp(target,physical,np.arange(left,right+1))
for first,last in duplicates:
left,right = first-1,last+1
positions[first:last+1] = left+(times[first:last+1]-times[left])/(times[right]-times[left])*(right-left)
requests = {}
for i, pos in enumerate(positions):
run = next(((a,b) for a,b in duplicates if a<=i<=b),None)
if abs(pos-i) < .025 and run is None:
continue
left = int(math.floor(pos)); right = left+1; alpha = float(pos-left)
# Held runs must interpolate between the two distinct endpoint images.
if run:
left,right = run[0]-1,run[1]+1
alpha = float((times[i]-times[left])/(times[right]-times[left]))
if alpha < .025 or alpha > .975 or right in cuts:
continue
requests[i] = (left,right,alpha)
return requests, dict(jump_frames=sorted(spikes),held_ranges=[list(x) for x in duplicates],
cadence=pattern, cuts=sorted(cuts), repaired_frames=sorted(requests),
regions=[list(x) for x in groups],
jump_ratios={str(i):round(float(ratios[i]),3) for i in sorted(spikes)})
def plan_camera(metrics, times, fps, details, shape):
"""Small translation refinement only in reliably tracked, stuttering pans.
This is not general stabilization: clean shots, cuts, handheld movement,
zoom/rotation and large corrections are deliberately left alone.
"""
from scipy.signal import savgol_filter
n=len(metrics);actual=np.zeros((n,2));target=np.zeros((n,2));enabled=np.zeros(n,dtype=bool)
h,w=shape;limit=np.array([w,h])*.004
shots=list(zip([0,*details['cuts']],[*details['cuts'],n]))
accepted=[]
for first,end in shots:
count=end-first
events=[i for i in details['jump_frames'] if first<i<end]
if count<max(12,float(fps)*.6) or len(events)<2:continue
cameras=[m.get('camera') for m in metrics[first+1:end]]
if any(c is None for c in cameras):continue
reliable=[c['inliers']>=.55 and c['coverage']>=.3 and c['cells']>=6
and abs(c['scale']-1)<.003 and abs(c['angle'])<.15 for c in cameras]
if np.mean(reliable)<.95:continue
velocity=np.array([[c['x'],c['y']] for c in cameras])
axis=int(np.argmax(np.abs(np.median(velocity,axis=0))))
speed=velocity[:,axis];direction=np.sign(np.median(speed))
if np.median(np.abs(speed))<.08 or np.mean(speed*direction>=-.025)<.95:continue
path=np.vstack([np.zeros(2),np.cumsum(velocity,axis=0)])
grid=np.linspace(times[first],times[end-1],count)
uniform=np.stack([np.interp(grid,times[first:end],path[:,a]) for a in range(2)],axis=1)
window=min(count if count%2 else count-1,max(7,round(float(fps))//2*2+1))
smooth=savgol_filter(uniform,window,3,axis=0)
smooth=np.stack([np.interp(times[first:end],grid,smooth[:,a]) for a in range(2)],axis=1)
smooth-=smooth[0]
smooth+=((times[first:end]-times[first])/(times[end-1]-times[first]))[:,None]*(path[-1]-smooth[-1])
offset=smooth-path
# Reject the whole shot instead of clipping shifts and creating new jerks.
if np.any(np.max(np.abs(offset),axis=0)>limit):continue
actual[first:end]=path;target[first:end]=smooth;enabled[first:end]=True
accepted.append([first,end-1])
return actual,target,enabled,dict(shots=accepted,limit_fraction=.004)
def _matrix(meta):
# swscale's matrix IDs differ from AVColorSpace for SMPTE170M.
return {1:1,4:4,5:5,6:5,7:7,9:9,10:9}.get(meta['colorspace'],5)
class Interpolator:
def __init__(self, weights, device=None, meta=None):
import torch
from .dogma_rife_arch import IFNet
self.device = torch.device(device or ('cuda' if torch.cuda.is_available() else 'cpu'))
self.meta=meta
if self.device.type=='cuda':
try:
import comfy.model_management as management
# Release other Comfy models only when this render actually needs VRAM.
pixels=(meta['width']*meta['height']) if meta else 2073600
management.free_memory(max(2_500_000_000,pixels*1200),self.device)
except ImportError:pass
self.model = IFNet()
state = torch.load(weights,map_location='cpu',weights_only=True)
state = {k.removeprefix('module.'):v for k,v in state.items()}
state = {k:v for k,v in state.items() if not k.startswith(('teacher.','caltime.'))}
self.model.load_state_dict(state,strict=True)
self.model.eval().to(self.device)
self.cache = {}
def frame(self, first, second, alpha):
import torch
import torch.nn.functional as F
import av
h,w = first.height,first.width
def tensor(frame):
key = frame.pts
if key not in self.cache:
if self.meta:
rgb=frame.reformat(format='rgb48le',src_colorspace=_matrix(self.meta),src_color_range=self.meta['color_range'] or 1,dst_color_range=2)
a=rgb.to_ndarray().astype(np.float32)/65535.
else:a = frame.to_ndarray(format='rgb48le').astype(np.float32)/65535.
self.cache[key] = torch.from_numpy(a).permute(2,0,1).unsqueeze(0).to(self.device)
return self.cache[key]
a,b = tensor(first),tensor(second)
self.cache = {k:v for k,v in self.cache.items() if k in (first.pts,second.pts)}
x = F.pad(torch.cat((a,b),1),(0,(-w)%64,0,(-h)%64),mode='replicate')
with torch.inference_mode():
result = self.model(x,alpha,[16,8,4,2,1])[2][-1][0,:,:h,:w]
rgb=result.permute(1,2,0).cpu().numpy()
# CPU conversion avoids several seconds of first-use CUDA kernel compilation.
if not np.isfinite(rgb).all():
raise ValueError('RIFE ha prodotto un fotogramma non valido.')
rgb=np.rint(np.clip(rgb,0,1)*65535).astype(np.uint16)
return av.VideoFrame.from_ndarray(rgb,format='rgb48le')
def close(self):
from .dogma_rife_arch import backwarp_tenGrid
self.cache.clear();backwarp_tenGrid.clear()
self.model.to('cpu')
def _encoder(path, meta):
import av
depth = meta['bit_depth'] > 8
candidates = [('hevc_nvenc','p010le' if depth else 'yuv420p',dict(preset='p5',tune='hq',rc='vbr',cq='16',b='0',profile='main10' if depth else 'main')),
('libx265','yuv420p10le' if depth else 'yuv420p',dict(preset='fast',crf='14',**{'x265-params':'log-level=error:pools=4'}))]
errors = []
for codec,pixel,options in candidates:
container = None
try:
# MP4's default 1000 Hz movie clock truncates fractional-frame ends
# in edit lists (e.g. 457/24 s became 19.041015625 s). Use the source
# clock for both the movie and video track; keep strict verification.
clock=str(Fraction(meta['time_base']).denominator)
container = av.open(str(path),'w',format='mp4',options={
'movflags':'+faststart','movie_timescale':clock,'video_track_timescale':clock})
stream = container.add_stream(codec,rate=Fraction(meta['fps']))
stream.width=meta['width'];stream.height=meta['height'];stream.pix_fmt=pixel;stream.options=options
stream.time_base=Fraction(meta['time_base']);stream.codec_context.time_base=stream.time_base
stream.codec_context.codec_tag='hvc1'
stream.codec_context.sample_aspect_ratio=Fraction(meta['sample_aspect_ratio'])
for name in ('color_range','colorspace','color_primaries','color_trc'):
setattr(stream.codec_context,name,meta[name])
stream.codec_context.open()
return container,stream,codec
except Exception as exc:
errors.append(str(exc))
if container:
container.close()
raise RuntimeError('Codifica video non disponibile: '+'; '.join(errors))
def _translate_frame(frame, shift, meta):
"""Shift native YUV planes: avoid two full RGB conversions per camera frame."""
import av
import cv2
deep=meta['bit_depth']>8;pixel='yuv420p10le' if deep else 'yuv420p'
if frame.format.name=='rgb48le':
frame=frame.reformat(format=pixel,src_colorspace=_matrix(meta),dst_colorspace=_matrix(meta),src_color_range=2,dst_color_range=meta['color_range'] or 1)
else:frame=frame.reformat(format=pixel)
result=av.VideoFrame(frame.width,frame.height,pixel)
dtype=np.uint16 if deep else np.uint8;itemsize=2 if deep else 1
for source,destination in zip(frame.planes,result.planes):
a=np.ndarray((source.height,source.line_size//itemsize),dtype=dtype,buffer=source)[:,:source.width]
matrix=np.array([[1,0,shift[0]*source.width/frame.width],[0,1,shift[1]*source.height/frame.height]],dtype=np.float32)
moved=cv2.warpAffine(a,matrix,(source.width,source.height),flags=cv2.INTER_LANCZOS4,borderMode=cv2.BORDER_REFLECT_101)
if deep:np.minimum(moved,1023,out=moved)
target=np.ndarray((destination.height,destination.line_size//itemsize),dtype=dtype,buffer=destination)
target[:,:destination.width]=moved
for name in ('color_range','colorspace','color_primaries','color_trc'):setattr(result,name,meta[name])
return result
def _verify(source, output, meta):
import av
with av.open(str(output)) as c:
v=c.streams.video[0]
frames=list((f.pts*f.time_base) for f in c.decode(v))
expected=[p*Fraction(meta['time_base']) for p in meta['pts']]
tolerance=max(Fraction(meta['time_base']),v.time_base)
if len(frames)!=len(expected) or any(abs(a-b)>tolerance for a,b in zip(frames,expected)):
raise ValueError('La verifica dei fotogrammi o della sincronizzazione non è riuscita.')
if (v.width,v.height)!=(meta['width'],meta['height']):
raise ValueError('La risoluzione del file corretto è cambiata.')
if max(x.bits for x in v.format.components)<meta['bit_depth']:
raise ValueError('La profondità colore del file corretto è cambiata.')
for name in ('color_range','colorspace','color_primaries','color_trc'):
if meta[name]!=(0 if name=='color_range' else 2) and getattr(v.codec_context,name)!=meta[name]:
raise ValueError('I metadati colore del file corretto sono cambiati.')
if len(set(np.diff(meta['pts'])))==1 and v.average_rate!=Fraction(meta['fps']):
raise ValueError('Il framerate del file corretto è cambiato.')
if meta['duration'] is not None and v.duration and abs(float(v.duration*v.time_base)-meta['duration'])>float(tolerance)*2:
raise ValueError('La durata del file corretto è cambiata.')
if len(c.streams.audio)!=meta['audio_streams']:
raise ValueError('Una traccia audio è assente dal file corretto.')
def audio_signature(path):
signatures=[]
with av.open(str(path)) as c:
states={s.index:[hashlib.sha256(),[]] for s in c.streams.audio}
for pk in c.demux(list(c.streams.audio)) if c.streams.audio else []:
if not pk.size:continue
h,ts=states[pk.stream.index];h.update(bytes(pk));ts.append((str(pk.pts*pk.time_base) if pk.pts is not None else None,str(pk.duration*pk.time_base)))
signatures=[(h.hexdigest(),ts) for h,ts in states.values()]
return signatures
if audio_signature(source)!=audio_signature(output):
raise ValueError('La verifica audio non è riuscita: originale conservato.')
def repair_video(source, output, model_directory, cancel=None, progress=None, device=None):
"""Write a second file atomically. Failure never damages the original."""
import av
source,output=Path(source).resolve(),Path(output).resolve()
if source==output or output.exists():
raise ValueError('Il fix richiede un nuovo file, distinto dall’originale.')
start=time.perf_counter()
meta,thumbs,metrics=analyze(source,cancel,progress)
times=np.array(meta['pts'],dtype=float)*float(Fraction(meta['time_base']))
requests,details=plan_repair(metrics,times,Fraction(meta['fps']))
camera_actual,camera_target,camera_enabled,camera_details=plan_camera(metrics,times,Fraction(meta['fps']),details,thumbs[0].shape)
report=dict(version=2,engine='RIFE 4.26 + restrained camera refinement',**{k:meta[k] for k in ('frames','fps','width','height','bit_depth','duration','audio_streams','analysis_seconds')},**details,
camera_refinement=camera_details)
output.parent.mkdir(parents=True,exist_ok=True)
fd,temp=tempfile.mkstemp(prefix='.dogma-fix-',suffix='.mp4',dir=output.parent);os.close(fd);temp=Path(temp)
interpolator=None;out=None
try:
if not requests:
shutil.copyfile(source,temp)
report.update(status='unchanged',interpolated_frames=0,encoder='stream copy')
else:
weights=model_file(model_directory,cancel,progress)
if progress:progress('Attesa correzione video',.2)
# Bound GPU/RAM use when several API branches finish together.
while not _RENDER_LOCK.acquire(timeout=.1):_check(cancel)
try:
_check(cancel)
interpolator=Interpolator(weights,device,meta)
out,video_out,codec=_encoder(temp,meta)
report['encoder']=codec;report['device']=str(interpolator.device)
render_start=time.perf_counter();cache={};current=-1;corrected_thumbs=list(thumbs);shifted=[];largest_shift=np.zeros(2)
with av.open(str(source)) as incoming:
original_video=incoming.streams.video[0];original_video.thread_type='AUTO';original_video.thread_count=4
audio={s.index:out.add_stream_from_template(s) for s in incoming.streams.audio}
def decoded():
for packet in incoming.demux([original_video,*incoming.streams.audio]):
_check(cancel)
if packet.stream.index==original_video.index:
yield from packet.decode()
elif packet.size and packet.dts is not None:
packet.stream=audio[packet.stream.index];out.mux(packet)
frames=iter(decoded())
for i in range(meta['frames']):
_check(cancel)
left,right,alpha=requests.get(i,(i,i,0.))
while current<max(i,right):
current+=1;cache[current]=next(frames)
if i in requests:
frame=interpolator.frame(cache[left],cache[right],alpha)
else:frame=cache[i]
if camera_enabled[i]:
pose=camera_actual[i]
if i in requests:
small=frame.reformat(width=thumbs[i].shape[1],height=thumbs[i].shape[0],format='gray').to_ndarray()
measured=measure_pair(thumbs[left],small).get('camera')
if measured and measured['inliers']>=.55:
pose=camera_actual[left]+[measured['x'],measured['y']]
else:pose=camera_actual[left]*(1-alpha)+camera_actual[right]*alpha
shift=(camera_target[i]-pose)*[meta['width']/thumbs[i].shape[1],meta['height']/thumbs[i].shape[0]]
if np.max(np.abs(shift))>.04:
# At most a narrow edge strip is extended; no crop or zoom.
frame=_translate_frame(frame,shift,meta);shifted.append(i)
largest_shift=np.maximum(largest_shift,np.abs(shift))
if frame.format.name=='rgb48le':
frame=frame.reformat(format=video_out.pix_fmt,src_colorspace=_matrix(meta),dst_colorspace=_matrix(meta),src_color_range=2,dst_color_range=meta['color_range'] or 1)
for name in ('color_range','colorspace','color_primaries','color_trc'):setattr(frame,name,meta[name])
if i in requests or camera_enabled[i]:
corrected_thumbs[i]=frame.reformat(width=thumbs[i].shape[1],height=thumbs[i].shape[0],format='gray').to_ndarray()
frame=frame.reformat(format=video_out.pix_fmt)
frame.pts=meta['pts'][i];frame.time_base=Fraction(meta['time_base'])
for packet in video_out.encode(frame):out.mux(packet)
# Keep endpoints of a held run until its last replacement.
upcoming=[requests[j][0] for j in range(i+1,min(i+7,meta['frames'])) if j in requests]
keep=min([i+1,*upcoming])
cache={k:v for k,v in cache.items() if k>=keep}
if progress and i%4==0:progress('Correzione scatti',.2+.65*(i+1)/meta['frames'])
# Drain trailing audio packets after the final video frame.
for _ in frames:pass
for packet in video_out.encode():out.mux(packet)
out.close();out=None
report['render_seconds']=round(time.perf_counter()-render_start,3)
report['interpolated_frames']=len(requests)
report['camera_refinement'].update(adjusted_frames=len(shifted),max_shift_pixels=largest_shift.tolist(),edge_fill='reflect, narrow edge strip only')
report['status']='repaired'
# A motion-only acceptance gate prevents a worse cadence from being labelled fixed.
after=list(metrics)
affected=sorted({j for i in {*requests,*shifted} for j in (i,i+1) if 0<j<len(thumbs)})
for i in affected:after[i]=measure_pair(corrected_thumbs[i-1],corrected_thumbs[i])
def jitter(rows):
value=[]
for left,right in details['regions']+[(a-1,b+1) for a,b in details['held_ranges']]:
v=np.array([rows[j]['motion'] for j in range(left+1,right+1)])
if v.size>2:value.append(float(np.std(v)/max(.01,np.mean(v))))
return float(np.mean(value)) if value else None
report['motion_jitter_before']=jitter(metrics);report['motion_jitter_after']=jitter(after)
def camera_jerk(rows):
values=[]
for first,last in camera_details['shots']:
velocity=np.array([[r.get('camera',{}).get('x',r['x']),r.get('camera',{}).get('y',r['y'])] for r in rows[first+1:last+1]])
acceleration=np.linalg.norm(np.diff(velocity,axis=0),axis=1)
if acceleration.size:values.extend(acceleration.tolist())
return dict(rms=float(np.sqrt(np.mean(np.square(values)))),peak=float(max(values))) if values else None
report['camera_jerk_before']=camera_jerk(metrics);report['camera_jerk_after']=camera_jerk(after)
camera_worse=np.any(largest_shift>np.array([meta['width'],meta['height']])*.004) or (report['camera_jerk_before'] and (report['camera_jerk_after']['rms']>report['camera_jerk_before']['rms']*.9
or report['camera_jerk_after']['peak']>report['camera_jerk_before']['peak']))
if camera_worse or (report['motion_jitter_before'] is not None and report['motion_jitter_after']>report['motion_jitter_before']*.95):
shutil.copyfile(source,temp)
report.update(status='skipped_quality',interpolated_frames=0)
report['camera_refinement']['adjusted_frames']=0
finally:
if interpolator:interpolator.close()
_RENDER_LOCK.release()
_check(cancel)
if progress:progress('Verifica sincronizzazione',.9)
_verify(source,temp,meta)
_check(cancel)
temp.replace(output)
report['total_seconds']=round(time.perf_counter()-start,3)
if progress:progress('Correzione completata',1.)
return report
finally:
if out:out.close()
if temp.exists():temp.unlink()
+2 -2
View File
@@ -1,9 +1,9 @@
[project]
name = "comfyui-dogma-nodes"
description = "Custom ComfyUI nodes for DOGMA AI video workflows."
version = "1.0.55"
version = "1.0.62"
license = { file = "LICENSE" }
dependencies = ["scipy>=1.10"]
dependencies = ["scipy>=1.10", "av>=18.0", "opencv-python>=4.8"]
[project.urls]
Repository = "https://github.com/axior/ComfyUI-DOGMA-Nodes"
+2
View File
@@ -1 +1,3 @@
scipy>=1.10
av>=18.0
opencv-python>=4.8
@@ -0,0 +1,93 @@
Copyright 2015 The Roboto Mono Project Authors (https://github.com/googlefonts/robotomono)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.
+49 -13
View File
@@ -8,6 +8,10 @@ export const FAMILIES=[
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 function orderedFamilies(s){
const available=families(s),order=Array.isArray(s.modelOrder)?s.modelOrder:[];
return [...new Set([...order,...available.map(f=>f.key)])].map(key=>available.find(f=>f.key===key)).filter(Boolean);
}
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;
@@ -43,19 +47,51 @@ export function todayCode(){const parts=new Intl.DateTimeFormat('en-GB',{timeZon
export function titleParts(s){return [s.project,s.scene,s.filename||'DOGMA',s.appendDate?(s.dateMode==='today'?todayCode():s.date||todayCode()):''].map(safeName).filter(Boolean);}
export function prefix(s,f){return ['DOGMA/API',safeName(s.project),safeName(s.scene),titleParts(s).join('_')+'_'+f.short].filter(Boolean).join('/');}
export function migrateState(raw){
const s=copy(raw);s.schema=3;s.session ||= crypto.randomUUID();s.prompts ||= {image:s.prompt||'',video:''};s.mode ||= 'image';s.imageEdit ??= true;s.appendDate ??= false;s.date ||= todayCode();
const s=copy(raw);s.schema=4;s.session ||= crypto.randomUUID();s.prompts ||= {image:s.prompt||'',video:''};s.mode ||= 'image';s.imageEdit ??= true;s.appendDate ??= false;s.date ||= todayCode();s.runCount ||= 1;
s.dateMode ||= raw.schema===1?'manual':'today';if(s.dateMode==='today')s.date=todayCode();
s.workspace ||= '';s.library ||= [];s.results ||= [];s.references ||= [];s.filters ||= {models:[],project:'*',scene:'*',kind:'all',workspace:'*'};s.density ??= 45;s.workExpanded ??= false;
for(const m of Object.values(s.models||{})){m.parameters ||= m.variants?.[0]||{};delete m.variants;delete m.editVariant;delete m.seedMode;}
for(const [i,r] of s.references.entries()){r.kind ||= 'image';r.role ||= 'reference';const legacyMask=raw.schema===1&&i===0&&!!raw.maskEnabled;r.process ||= {enabled:legacyMask,mask:legacyMask,maskMode:legacyMask?'edit':'isolate',invert:false,flip:false,crop:false,resizeMpx:false,megapixels:1,expand:0,blur:0,fillHoles:true,targetWidth:0,targetHeight:0,source:'paint',prompt:'',segment:0,background:legacyMask?'#ff00ff':'#00ff00'};}
s.filters.hideErrors ??= false;s.videoRepair ??= false;s.compareEnabled ??= true;
s.modelOrder=[...new Set([...(Array.isArray(s.modelOrder)?s.modelOrder:[]),...ALL_FAMILIES.map(f=>f.key)])].filter(key=>ALL_FAMILIES.some(f=>f.key===key));
for(const [i,r] of s.references.entries()){r.kind ||= 'image';r.role ||= 'reference';const legacyMask=raw.schema===1&&i===0&&!!raw.maskEnabled;r.process ||= {enabled:legacyMask,mask:legacyMask,maskMode:'edit',invert:false,flip:false,crop:false,resizeMpx:false,megapixels:1,expand:0,blur:0,fillHoles:false,targetWidth:0,targetHeight:0,source:'paint',prompt:'',segment:0,background:'#ff00ff'};}
if(raw.schema<3)for(const r of [...s.references])if(r.kind==='image'&&r.modes?.includes('video')&&['first','last'].includes(r.role))s.references.push({...copy(r),role:'reference'});
for(const r of s.results)r.kind ||= 'image';
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 plannedJobs(s){const repeats=Number(s.runCount??1);if(!Number.isInteger(repeats)||repeats<1||repeats>64)throw new Error('Run deve essere da 1 a 64.');const counts={};return Array.from({length:repeats},(_,repeat)=>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},()=>({family:f.key,index:(counts[f.key]=(counts[f.key]||0)+1)-1,repeat,kind:s.mode==='video'?'video':'image'}));})).flat();}
export const preparedMask=ref=>!!ref.process?.maskFile&&ref.process.samSource===ref.file&&ref.process.samPrompt===ref.process.prompt&&Number(ref.process.samSegment)===Number(ref.process.segment||0);
export function visibleReferences(s){return s.references.filter(r=>(!r.modes||r.modes.includes(s.mode))&&(s.mode==='video'?(s.models.seedance?.engine==='frames'?r.kind==='image'&&['first','last'].includes(r.role):r.role!=='first'&&r.role!=='last'):r.kind!=='video'));}
export function activeReferences(s){return visibleReferences(s).filter(r=>r.enabled);}
export function validateState(s){
export function mediaKind(file){
if(file.type?.startsWith('image/'))return 'image';if(file.type?.startsWith('video/'))return 'video';
if(file.type&&file.type!=='application/octet-stream')return null;
if(/\.(png|jpe?g|webp|avif|gif|bmp|tiff?)$/i.test(file.name||''))return 'image';
if(/\.(mp4|mov|m4v|webm|mkv|avi)$/i.test(file.name||''))return 'video';return null;
}
function dimensionError(f,fields,message){return Object.assign(new Error(`${f.name}: ${message}`),{family:f.key,fields});}
function validateDimensions(f,p,specFor){
const seedream=f.key==='seedream',model=String(p.model||'').toLowerCase();
const modern=seedream&&(/5[.-]5/.test(model)||/5[.-]0.*(?:pro|flash)/.test(model));
const preset=seedream&&p['model.size_preset']&&p['model.size_preset']!=='Custom';
if(!preset)for(const [k,v] of Object.entries(p))if(/(?:width|height)$/.test(k)){
const info=specFor?.(f,k)?.[1]||{},n=Number(v);
const min=info.min??(seedream&&!/5[.-]5/.test(model)?1024:f.key==='gpt'?480:240);
const max=info.max??(seedream?(/5[.-]5/.test(model)?8594:modern?4514:k.endsWith('width')?6240:4992):f.key==='gpt'?3840:8594);
// Seedream's step=2 is a widget increment, not a server-side divisibility rule.
const step=seedream?1:f.key==='gpt'?16:2,label=k.split('.').at(-1).toUpperCase();
if(!Number.isInteger(n)||n<min||n>max||n%step)throw dimensionError(f,[k],`${label} = ${v}. Inserisci un intero da ${min} a ${max}${step>1?`, multiplo di ${step}`:''}.`);
}
if(!seedream)return;
const match=preset&&String(p['model.size_preset']).match(/(\d+)\s*[x×]\s*(\d+)/i);
// Presets retain native precedence over the unused Custom width and height.
const w=Number(match?match[1]:p['model.width']),h=Number(match?match[2]:p['model.height']);
if(preset&&!match)return;
const fields=preset?['model.size_preset']:['model.width','model.height'];
const pixels=w*h,min=modern||/4[.-]0/.test(model)?921600:3686400,max=modern?4624220:16777216;
if(pixels<min||pixels>max)throw dimensionError(f,fields,`${p.model}: ${w} × ${h} = ${(pixels/1e6).toFixed(2)} MP. Il modello richiede da ${(min/1e6).toFixed(2)} a ${(max/1e6).toFixed(2)} MP. Correggi ${preset?'SIZE PRESET':'WIDTH / HEIGHT'} e premi Run.`);
if(/5[.-]5/.test(model)&&(w/h<1/16||w/h>16))throw dimensionError(f,fields,`${w} × ${h}: rapporto consentito da 1:16 a 16:1. Correggi ${preset?'SIZE PRESET':'WIDTH / HEIGHT'} e premi Run.`);
}
export function validateState(s,specFor){
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');
@@ -75,14 +111,11 @@ export function validateState(s){
}
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}.`);
}
validateDimensions(f,p,specFor);
}
}
export function compileBatch(s,jobs,baseSeed){
validateState(s);const output={},refs=activeReferences(s),images=[],videos=[];
export function compileBatch(s,jobs,baseSeed,specFor){
validateState(s,specFor);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;}
@@ -90,7 +123,7 @@ export function compileBatch(s,jobs,baseSeed){
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];}
if(p.source==='prompt'&&p.mask&&!preparedMask(ref)){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});
@@ -112,11 +145,14 @@ export function compileBatch(s,jobs,baseSeed){
}else if(f.key==='nano'){if(nanoBatch)inputs.images=nanoBatch;}
else{if(f.key==='gpt')inputs.n=1;images.forEach((x,j)=>inputs[`${f.key==='flux'?'':'model.'}images.image_${j+1}`]=x.link);}
const gen=String(10000+i*10),save=String(10001+i*10);
Object.assign(job,{seed,generator:gen,output:save,project:s.project||'',scene:s.scene||'',workspace:s.workspace||'',filename:titleParts(s).join('_'),imageEdit:s.mode==='image'&&s.imageEdit,baseReference:s.mode==='image'&&s.imageEdit&&images.length?copy(images[0].ref):null,prompt,parameters:copy(inputs)});
Object.assign(job,{seed,generator:gen,output:save,videoRepair:s.mode==='video'&&!!s.videoRepair,project:s.project||'',scene:s.scene||'',workspace:s.workspace||'',filename:titleParts(s).join('_'),imageEdit:s.mode==='image'&&s.imageEdit,baseReference:s.mode==='image'&&s.imageEdit&&images.length?copy(images[0].ref):null,prompt,parameters:copy(inputs)});
if(job.baseReference)delete job.baseReference.editorDraft;
output[gen]={class_type:type,inputs,_meta:{title:`${f.name} ${job.index+1}`}};
const metadata={...copy(job),session:s.session,prefix:prefix(s,f),date:s.dateMode==='today'?todayCode():s.date,appendDate:s.appendDate};delete metadata.images;delete metadata.parameters;
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));}
export function orderResults(results){const groups=new Map();for(const r of results){const key=r.batch||r.id;groups.set(key,Math.max(groups.get(key)||0,r.batchStarted||r.started||r.finished||0));}return [...results].sort((a,b)=>{const ga=a.batch||a.id,gb=b.batch||b.id;return groups.get(gb)-groups.get(ga)||(ga===gb?(a.ordinal??a.index??0)-(b.ordinal??b.index??0):String(gb).localeCompare(String(ga)))||String(a.id).localeCompare(String(b.id));});}
export function filterResults(results,filters,now=Date.now()){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)&&(!filters.hideErrors||!['failed','missing'].includes(r.status)||(r.errorVisibleUntil||0)>now));}
export function savedFilename(job,index=0){return job.exported?.[index]?.split(/[\\/]/).at(-1)||job.images?.[index]?.filename||job.filename||'';}
+4 -2
View File
@@ -1,5 +1,6 @@
{
"schema": 3,
"schema": 4,
"runCount": 1,
"session": "",
"mode": "image",
"imageEdit": true,
@@ -108,5 +109,6 @@
"scene": "*",
"kind": "all",
"workspace": "*"
}
},
"videoRepair": false
}
File diff suppressed because one or more lines are too long
+65
View File
@@ -0,0 +1,65 @@
// Reorder only the model blocks. Controls and expansion state stay on their DOM nodes.
export function modelReorder(container,saveOrder){
let active=null,frame=0,suppressClick=false,scroller=null;
const models=()=>[...container.children].filter(e=>e.dataset.modelKey);
const inside=()=>{
const r=container.getBoundingClientRect(),s=scroller.getBoundingClientRect();
return active.x>=r.left&&active.x<=r.right&&active.y>=Math.max(r.top,s.top)&&active.y<=Math.min(r.bottom,s.bottom);
};
const place=()=>{
if(!inside())return;
const next=models().find(row=>{
if(row===active.row)return false;
const r=row.querySelector('.dap-model-head>details>summary').getBoundingClientRect();
return active.y<r.top+r.height/2;
});
if(active.row.nextElementSibling!==next&&(next||active.row!==container.lastElementChild))container.insertBefore(active.row,next||null);
};
const scroll=()=>{
if(!active?.dragging)return;
if(!container.isConnected){finish(false);return;}
const r=scroller.getBoundingClientRect();
if(active.x>=r.left&&active.x<=r.right){
const delta=active.y<r.top+36?-Math.min(12,(r.top+36-active.y)/3):active.y>r.bottom-36?Math.min(12,(active.y-r.bottom+36)/3):0;
if(delta){scroller.scrollTop+=delta;place();}
}
frame=requestAnimationFrame(scroll);
};
const finish=(commit=false)=>{
if(!active)return;
const {row,original,dragging,pointerId}=active;
active=null;cancelAnimationFrame(frame);row.classList.remove('dap-model-dragging');
document.removeEventListener('pointermove',move);document.removeEventListener('pointerup',up);document.removeEventListener('pointercancel',cancel);
document.removeEventListener('keydown',key,true);window.removeEventListener('blur',cancel);
if(container.hasPointerCapture(pointerId))container.releasePointerCapture(pointerId);
if(!dragging)return;
suppressClick=true;setTimeout(()=>suppressClick=false,0);
if(!commit){for(const item of original)container.append(item);return;}
const order=models().map(item=>item.dataset.modelKey);
if(order.some((value,i)=>value!==original[i].dataset.modelKey))saveOrder(order);
};
const move=e=>{
if(!active||e.pointerId!==active.pointerId)return;
active.x=e.clientX;active.y=e.clientY;
if(!active.dragging){
if(Math.hypot(e.clientX-active.startX,e.clientY-active.startY)<6)return;
active.dragging=true;container.setPointerCapture(e.pointerId);active.row.classList.add('dap-model-dragging');frame=requestAnimationFrame(scroll);
}
e.preventDefault();place();
};
const up=e=>{if(active&&e.pointerId===active.pointerId){active.x=e.clientX;active.y=e.clientY;if(active.dragging)e.preventDefault();finish(inside());}};
const cancel=()=>finish(false);
const key=e=>{if(e.key==='Escape'){e.preventDefault();e.stopPropagation();cancel();}};
container.addEventListener('pointerdown',e=>{
if(e.button!==0||e.pointerType==='touch'||active)return;
const summary=e.target.closest('.dap-model-head>details>summary');
if(!summary||!container.contains(summary))return;
scroller=container.closest('.dap-side');if(!scroller)return;
active={row:summary.closest('.dap-model'),original:models(),pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,x:e.clientX,y:e.clientY,dragging:false};
document.addEventListener('pointermove',move,{passive:false});document.addEventListener('pointerup',up);document.addEventListener('pointercancel',cancel);
document.addEventListener('keydown',key,true);window.addEventListener('blur',cancel);
});
container.addEventListener('click',e=>{if(suppressClick){e.preventDefault();e.stopPropagation();}},true);
container.addEventListener('dragstart',e=>{if(active)e.preventDefault();});
container.classList.add('dap-models-sortable');
}
+191 -18
View File
@@ -1,32 +1,205 @@
@font-face{font-family:'Roboto Mono';src:url('./dogma_api_assets/RobotoMono-Variable.ttf') format('truetype');font-weight:100 700;font-style:normal;font-display:swap}
.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}
.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 'Roboto Mono',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 'Roboto Mono',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:none}.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:#393939 #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 'Roboto Mono',monospace;color:#666}.dap-controls{padding-left:12px;overflow:visible;min-width:0}.dap-section{margin-bottom:28px}.dap-label{font:10px 'Roboto Mono',monospace;color:#7a7a7a;margin:0 0 11px;letter-spacing:.03em}
.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 'Roboto Mono',monospace;color:#eee;text-shadow:0 1px 3px #000;pointer-events:none}.dap-ref-edited{position:absolute;top:8px;right:8px;font:8px 'Roboto Mono',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-role{position:absolute;left:5px;right:5px;top:25px;width:calc(100% - 10px);background:#000a;border:1px solid #444;border-radius:10px;font:8px 'Roboto Mono',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 'Roboto Mono',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 'Roboto Mono',monospace}
.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:#393939 #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,#777 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 'Roboto Mono',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 'Roboto Mono',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=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 'Roboto Mono',monospace;color:#666;margin:0 7px 10px}.dap-date-row{display:flex;align-items:center;gap:10px;margin:10px 0 12px;font:10px 'Roboto Mono',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 'Roboto Mono',monospace}.dap-filename-preview{font:9px/1.5 'Roboto Mono',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 'Roboto Mono',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 'Roboto Mono',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:none}.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 'Roboto Mono',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 'Roboto Mono',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:none}.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 'Roboto Mono',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 'Roboto Mono',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:#393939 #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:none}.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 'Roboto Mono',monospace;color:#686868;white-space:nowrap}.dap-card-tags{font:8px 'Roboto Mono',monospace;color:#74513d;padding:0 11px 8px}.dap-study{position:absolute;left:10px;top:10px;font:8px 'Roboto Mono',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 'Roboto Mono',monospace;color:#8c5a41}.dap-card.stopped .dap-card-error{font:10px/1.5 'Roboto Mono',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 'Roboto Mono',monospace;color:#bd5e2e}.dap-empty h2{font-size:27px;font-weight:normal;color:#aaa;margin-top:24px}.dap-empty p{font:11px/1.6 'Roboto Mono',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 'Roboto Mono',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 'Roboto Mono',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 'Roboto Mono',monospace}.dap-viewer-tools .dap-icon{width:16px;height:16px}.dap-zoom-value{display:flex;align-items:center;gap:2px;font:10px 'Roboto Mono',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 'Roboto Mono',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 'Roboto Mono',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 'Roboto Mono',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:#393939 #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 'Roboto Mono',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 'Roboto Mono',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-date-row input[type=date]{margin-left:auto;min-width:0;width:105px;border:0;background:transparent;color:#9a623f;font:9px 'Roboto Mono',monospace;cursor:pointer}.dap-date-row input[type=date]:hover{color:var(--orange)}.dap-operation-note{flex-shrink:0;font:10px/1.4 'Roboto Mono',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)}
.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}
/* 1.0.55: immediate shell, in-panel folders and live progress */
.dap-stop{border:1px solid #ef382e;background:#cf2922;color:white!important;border-radius:25px;padding:8px 22px;font-weight:bold!important;min-width:100px;cursor:pointer}.dap-stop:hover{background:#f34135;box-shadow:0 0 20px #ee302733}.dap-stop:disabled{opacity:.24;cursor:default}.dap-project{background:none;border:0;text-align:left;cursor:pointer;max-width:55%}.dap-project:hover{color:var(--orange)}
.dap-work>summary{display:flex;align-items:center;justify-content:space-between;cursor:pointer;padding:8px 0;border-bottom:1px solid #292018}.dap-work>summary:hover{color:var(--orange)}.dap-work>summary .dap-icon{width:12px;height:12px}.dap-work[open]>summary .dap-icon{transform:rotate(180deg)}.dap-work>div{padding-top:10px}.dap-video-choice{margin:0 0 25px}.dap-video-choice>button{background:#000;border:1px solid #333;border-radius:22px;color:#aaa;padding:9px 16px;margin-right:8px;font:11px Courier New,monospace}.dap-video-choice>button.active{border-color:var(--orange);color:var(--orange)}
/* 1.0.56: immediate shell, in-panel folders and live progress */
.dap-stop{border:1px solid #ef382e;background:#cf2922;color:white!important;border-radius:25px;padding:8px 22px;font-weight:bold!important;min-width:100px;cursor:pointer}.dap-stop:hover{background:#f34135;box-shadow:none}.dap-stop:disabled{opacity:.24;cursor:default}.dap-project{background:none;border:0;text-align:left;cursor:pointer;max-width:55%}.dap-project:hover{color:var(--orange)}
.dap-work>summary{display:flex;align-items:center;justify-content:space-between;cursor:pointer;padding:8px 0;border-bottom:1px solid #292018}.dap-work>summary:hover{color:var(--orange)}.dap-work>summary .dap-icon{width:12px;height:12px}.dap-work[open]>summary .dap-icon{transform:rotate(180deg)}.dap-work>div{padding-top:10px}.dap-video-choice{margin:0 0 25px}.dap-video-choice>button{background:#000;border:1px solid #333;border-radius:22px;color:#aaa;padding:9px 16px;margin-right:8px;font:11px 'Roboto Mono',monospace}.dap-video-choice>button.active{border-color:var(--orange);color:var(--orange)}
.dap-views>button:first-child .dap-icon{width:40px;height:24px}.dap-card-tools .dap-icon-button:first-child .dap-icon{width:23px}
.dap-folder-modal{width:min(1000px,90vw);height:75vh;display:flex;flex-direction:column}.dap-folder-navigation,.dap-folder-footer{display:flex;gap:10px;flex-shrink:0;margin:10px 0}.dap-folder-navigation input{flex:1;min-width:0}.dap-folder-navigation input,.dap-folder-footer input{background:#111;color:#ccc;border:1px solid #444;border-radius:8px;padding:9px;font:12px Courier New,monospace}.dap-folder-list{flex:1;overflow:auto;min-height:0}.dap-folder-file{padding:10px 14px;color:#999;font:12px Courier New,monospace;border:1px solid transparent;border-radius:6px}.dap-folder-file.selected{background:#ff662622;border-color:var(--orange);color:#eee}.dap-folder-footer{flex-wrap:wrap}
.dap-progress-track{height:3px;background:#271308;overflow:hidden;border-radius:2px}.dap-progress-track>i{display:block;height:100%;width:0;background:#ff6626;box-shadow:0 0 7px #ff6626;transition:width .7s linear}.dap-total-progress{margin:0 0 12px;flex-shrink:0}.dap-total-progress>span{display:block;text-align:right;font:10px Courier New,monospace;color:#b47753;margin-top:8px}.dap-card-progress{position:absolute;bottom:0;left:0;right:0}.dap-progress-track.indeterminate>i{width:28%!important;animation:dap-progress 1.8s ease-in-out infinite}.dap-spinner{border:0;animation:none;width:38px;height:38px;position:relative}.dap-spinner>i{position:absolute;left:17px;top:17px;width:4px;height:4px;border-radius:50%;background:#ff742d;transform:rotate(calc(var(--i)*22.5deg)) translateY(-16px);box-shadow:0 0 6px #ff6626,0 0 12px #ff662666;opacity:0;animation:dap-light 1.25s linear infinite;animation-delay:calc(var(--i)*.078125s)}
.dap-folder-modal{width:min(1000px,90vw);height:75vh;display:flex;flex-direction:column}.dap-folder-navigation,.dap-folder-footer{display:flex;gap:10px;flex-shrink:0;margin:10px 0}.dap-folder-navigation input{flex:1;min-width:0}.dap-folder-navigation input,.dap-folder-footer input{background:#111;color:#ccc;border:1px solid #444;border-radius:8px;padding:9px;font:12px 'Roboto Mono',monospace}.dap-folder-list{flex:1;overflow:auto;min-height:0}.dap-folder-file{padding:10px 14px;color:#999;font:12px 'Roboto Mono',monospace;border:1px solid transparent;border-radius:6px}.dap-folder-file.selected{background:#ff662622;border-color:var(--orange);color:#eee}.dap-folder-footer{flex-wrap:wrap}
.dap-progress-track{height:3px;background:#271308;overflow:hidden;border-radius:2px}.dap-progress-track>i{display:block;height:100%;width:0;background:#ff6626;box-shadow:none;transition:width .7s linear}.dap-total-progress{margin:0 0 12px;flex-shrink:0}.dap-total-progress>span{display:block;text-align:right;font:10px 'Roboto Mono',monospace;color:#b47753;margin-top:8px}.dap-card-progress{position:absolute;bottom:0;left:0;right:0}.dap-progress-track.indeterminate>i{width:28%!important;animation:dap-progress 1.8s ease-in-out infinite}
@keyframes dap-light{0%{opacity:1}70%,100%{opacity:0}}@keyframes dap-progress{from{transform:translateX(-110%)}to{transform:translateX(470%)}}
.dap-generated{opacity:1;transition:opacity .2s}.dap-reference-preview[hidden],.dap-total-progress[hidden]{display:none}.dap-field select{min-width:35%;cursor:pointer}
/* V4: DOGMA artwork, quiet surfaces and consistent interaction. */
.dap,.dap-modal{--muted:#777;--line:#303030;scrollbar-width:thin;scrollbar-color:#393939 transparent}
.dap *,.dap-modal *{scrollbar-width:thin;scrollbar-color:#393939 transparent}
.dap *::-webkit-scrollbar,.dap-modal *::-webkit-scrollbar{width:4px;height:4px}
.dap *::-webkit-scrollbar-thumb,.dap-modal *::-webkit-scrollbar-thumb{background:#393939;border-radius:4px}
.dap *::-webkit-scrollbar-track,.dap-modal *::-webkit-scrollbar-track{background:transparent}
.dap button,.dap-modal button{box-shadow:none!important}
.dap-run-group{display:flex;align-items:center;border:1px solid #303030;border-radius:30px;height:34px}
.dap-run-counter{display:flex;align-items:center;gap:5px;padding:0 13px 0 14px;height:100%}
.dap-run-counter input{appearance:textfield;background:none;border:0;color:#888;width:24px;text-align:center;padding:0;font:15px Arial,sans-serif}
.dap-run-counter input::-webkit-inner-spin-button{display:none}
.dap-run-counter>div{display:flex;flex-direction:column;gap:0}
.dap-run-counter button{padding:0;width:14px;height:12px;border:0;color:#666}
.dap-run-counter button:hover{color:#ddd}
.dap-run-counter .dap-icon{width:14px;height:12px;stroke-width:2}
.dap-run-up{transform:rotate(180deg)}
.dap-run{height:34px;min-width:165px;margin:-1px;position:relative;font-size:14px!important;padding:4px 14px}
.dap-credit{font-size:10px!important;color:#535353}
.dap-refs{grid-template-columns:repeat(2,minmax(0,1fr))}
.dap button.dap-add{background:#000;color:#777}
.dap button.dap-add:hover:not(:disabled){background:#000;border-color:#272727;color:#777}
.dap-add>.dap-add-hover{display:none;width:24px;height:24px;stroke-width:.6}
.dap-add:hover>.dap-icon:first-child{display:none}
.dap-add:hover>.dap-add-hover{display:block}
.dap-field{border:0;background:transparent;min-height:30px;margin-bottom:5px;padding:4px 10px;border-radius:18px}
.dap-field:hover,.dap-field:focus-within{background:#191919}
.dap-field>span{pointer-events:none;position:relative;z-index:1}
.dap-field input:not([type=checkbox]):not([type=color]){background:transparent}
.dap-field.has-select>select{position:absolute;inset:0;width:100%;height:100%;max-width:none;padding:0 30px 0 40%;text-align:right;cursor:pointer;border-radius:18px}
.dap-field-step{position:relative;z-index:2;width:12px;min-width:12px;flex:0 0 12px}
.dap-field-step .dap-icon{width:10px;height:13px}
.dap-field-step.next{margin-left:auto}
.dap-field.has-select>span{flex:0 0 38%;overflow:hidden}
.dap-work{margin-top:-5px}
.dap-work-label{border-top:1px solid #333;padding-top:12px}
.dap-work>summary{border:0;padding:12px 8px 12px 0;border-radius:0;gap:14px}
.dap-work>summary .dap-icon{color:var(--orange);flex-shrink:0}
.dap-filename-preview{font:11px/1.6 'Roboto Mono',monospace;color:#bababa;padding:0;overflow-wrap:anywhere;white-space:normal}
.dap-work>summary:hover{background:#111}
.dap-workspace-row{display:flex;align-items:center;gap:4px}
.dap-workspace-row>.dap-icon-button{flex:none;color:#777}
.dap-workspace-row>.dap-workspace-button{flex:1;width:auto;min-width:0}
.dap-workspace-button{border:0;border-radius:16px;padding:8px 0;min-width:0;flex:1}
.dap-workspace-button span{font:11px Arial,sans-serif}
.dap-workspace-button:hover{background:#171717}
.dap-model{margin:14px 0 0}
.dap-model-head{gap:10px}
.dap-model summary{border:0;border-top:1px solid #333;border-radius:0;min-height:32px;padding:7px 5px 5px 0;gap:10px;font-size:14px}
.dap-model summary:hover{background:#131313}
.dap-model summary>small{font-size:8px}
.dap-model-body{padding-top:12px}
.dap-advanced summary{border:0}
.dap-field-hint{font-size:8px;color:#4d4d4d}
.dap-project{color:#aaa;max-width:70%}
.dap-views>button:first-child .dap-icon{width:21px;height:21px}
.dap-filters,.dap-filter,.dap-filter-models>summary,.dap-filter-menu>label,.dap-filter-menu>button,.dap-filter select{font-family:Arial,Helvetica,sans-serif!important;font-size:11px}
.dap-filter{padding:0;display:inline-flex;min-width:100px;max-width:260px;overflow:visible}
.dap-filter>span{position:absolute;left:10px;z-index:1;pointer-events:none;font:10px Arial,sans-serif;display:block!important;color:#686868}
.dap-filter select{width:100%;min-width:0;max-width:260px;padding:6px 22px 6px 70px;border-radius:20px;min-height:28px}
.dap-filter>.dap-icon{pointer-events:none}
.dap-filter-models>summary{min-height:29px}
.dap-error-filter{background:transparent;border:1px solid #303030;color:#888;border-radius:20px;padding:6px 11px;font:11px Arial,sans-serif}
.dap-error-filter[aria-pressed=true]{color:#bbb}
.dap-total-progress{position:absolute;inset:0 0 auto;margin:0;z-index:3;height:7px}
.dap-total-progress .dap-progress-track{height:7px;border-radius:0;background:#272727}
.dap-total-progress>span{position:absolute;top:9px;right:22px;color:#777;font:9px 'Roboto Mono',monospace;pointer-events:none;margin:0}
.dap-header{padding-top:31px}
.dap-progress-track>i{box-shadow:none}
.dap-card-progress{top:0;bottom:auto;height:5px;border-radius:0;background:#34251d}
.dap-gallery{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,var(--card-min,420px)),1fr));gap:14px;align-items:start;align-content:start;column-width:auto;min-height:0}
.dap-card{margin:0;background:#181818;border-color:transparent;box-shadow:none;border-radius:18px}
.dap-card:hover{box-shadow:none;border-color:#454545}
.dap-card.pending{aspect-ratio:1.8;display:flex;min-height:215px}
.dap-loading-logo{position:absolute;left:50%;top:47%;transform:translate(-50%,-50%);width:20%;max-width:160px;min-width:65px;mix-blend-mode:screen;pointer-events:none}
.dap-card.stopped .dap-loading-logo{display:none}
.dap-card-footer{display:flex;align-items:center;gap:18px;min-height:36px;padding:10px 12px;color:#686868;background:#181818;font:11px/1.4 Arial,Helvetica,sans-serif}
.dap-result-name{flex:0 1 auto;min-width:0;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}
.dap-elapsed{margin-left:auto;font:10px Arial,Helvetica,sans-serif;color:#696969}
.dap-card-tags{padding:0;color:#626262;white-space:nowrap;font:10px Arial,Helvetica,sans-serif}
.dap-job-state{color:#797979;font:10px Arial,Helvetica,sans-serif;white-space:nowrap}
.dap-error-content{display:none;padding:25px 20px 50px;max-height:100%;width:100%;overflow:auto;color:#ccc;line-height:1.6;font:11px/1.7 'Roboto Mono',monospace}
.dap-error-content>span{display:block;color:#777;margin:0 0 18px;font:11px Arial,sans-serif}
.dap-error-content p{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}
.dap-card.failed .dap-error-content{display:block}
.dap-error-countdown{position:absolute;right:12px;top:14px;color:#ccc;background:#181818;font:10px 'Roboto Mono',monospace}
.dap-error-countdown:empty{display:none}
.dap-card-media{cursor:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='3' fill='white' stroke='black' stroke-width='1'/%3E%3C/svg%3E") 8 8,crosshair}
.dap-card-media video{object-fit:contain}
.dap-card-media>.dap-icon{color:#fff;opacity:.5;width:clamp(28px,6%,76px);height:auto;aspect-ratio:1;filter:none}
.dap-card-media>.dap-icon path{fill:currentColor;stroke:none}
.dap-card-media.playing>.dap-icon,.dap-card-media:hover>.dap-icon{opacity:0}
.dap-video-duration{position:absolute;bottom:10px;right:10px;font:11px 'Roboto Mono',monospace;color:#eee;line-height:1.4;background:#0009;padding:2px 5px;border-radius:3px}
.dap-card-tools .dap-ab{font:15px Arial,sans-serif;min-width:38px;color:#ccc;border-color:#555}
.dap-card-tools .selected{background:var(--orange);color:#000;border-color:var(--orange)}
.dap-card-tools .dap-icon-button:hover{color:var(--orange);background:#181818}
.dap-empty{grid-column:1/-1}
.dap-reference-modal{height:94dvh;max-height:94dvh;display:flex;flex-direction:column}
.dap-reference-layout{flex:1;min-height:0;grid-template-columns:minmax(0,1fr) 300px}
.dap-reference-left{display:flex;flex-direction:column;min-height:0}
.dap-reference-tools{flex-shrink:0}
.dap-mask-viewport{position:relative;overflow:hidden;flex:1;min-height:200px;touch-action:none;outline:0;background:#070707}
.dap-mask-stage{position:absolute;left:0;top:0;margin:0;max-width:none;transform-origin:0 0}
.dap-mask-stage canvas{width:100%;height:100%}
.dap-mask-viewport.pan,.dap-mask-viewport.pan canvas{cursor:grab!important}
.dap-reference-options{height:100%;max-height:none}
.dap-editor-status{flex-shrink:0;min-height:15px;font-size:9px;color:#888}
.dap-reference-footer{flex-shrink:0}
.dap-reference-preview{cursor:pointer;border-color:#333;border-radius:5px}
.dap-reference-preview:hover{border-color:var(--orange)}
.dap-preview-tools{display:flex;gap:8px;margin-top:8px}
.dap-preview-tools button{font:10px Arial,sans-serif!important;padding:7px 10px}
.dap-video-compare{display:grid;grid-template-columns:1fr 1fr;gap:10px;cursor:default}
.dap-video-panel{position:relative;min-width:0;min-height:0;display:flex;align-items:center}
.dap-video-panel>video,.dap-video-panel>img{width:100%;height:100%;object-fit:contain}
.dap-video-panel>span{position:absolute;top:10px;left:12px;font:18px Arial,sans-serif;color:var(--orange)}
.dap-video-sync{display:flex;align-items:center;gap:14px;padding:12px;flex-shrink:0}
.dap-video-sync>input{flex:1;accent-color:var(--orange)}
.dap-video-sync>button{background:#181818;border:1px solid #333;border-radius:15px;padding:6px 15px}
.dap-prompt-modal{width:min(900px,90vw)}
.dap-prompt-modal textarea{width:100%;height:45vh;resize:vertical;background:#111;border:1px solid #333;padding:15px;line-height:1.6;margin-bottom:12px}
@media(max-width:760px){.dap-run{min-width:90px}.dap-run-counter{padding:0 8px;gap:2px}.dap-card-footer{gap:8px}.dap-reference-layout{grid-template-columns:1fr;overflow:auto;display:flex;flex-direction:column}.dap-reference-left{height:55vh;flex-shrink:0}.dap-reference-options{height:auto;overflow:visible}.dap-total-progress>span{display:none}.dap-header{padding-top:24px}.dap-video-compare{grid-template-columns:1fr;grid-template-rows:1fr 1fr}}
.dap-refs:has(>.dap-ref:first-child:nth-last-child(2)){grid-template-columns:1.75fr 1fr}
.dap-refs:has(>.dap-ref:first-child:nth-last-child(2))>.dap-add{aspect-ratio:auto}
.dap-workspace-explorer{display:inline-flex;align-items:center;justify-content:center;gap:5px;flex:none;background:transparent;border:0;border-radius:10px;padding:8px 6px;color:#999;font:10px Arial,sans-serif;white-space:nowrap}
.dap-workspace-explorer .dap-icon{width:13px;height:13px}
.dap-workspace-explorer:hover,.dap-workspace-explorer:focus-visible{color:var(--orange);background:#171717}
/* Shared compact lever: the same 28 × 14 track for every on/off setting. */
.dap-toggle{position:relative;display:inline-flex;align-items:center;justify-content:center;flex:0 0 38px;width:38px;min-width:38px;height:32px;padding:0;border:0;border-radius:6px;background:transparent;vertical-align:middle;cursor:pointer}
.dap-toggle>input[type=checkbox]{position:absolute;inset:0;z-index:1;width:100%;min-width:100%;max-width:none;height:100%;margin:0;padding:0;opacity:0;cursor:pointer}
.dap-toggle-track{display:block;position:relative;flex:none;box-sizing:border-box;width:28px;height:14px;border:1px solid #565656;border-radius:20px;background:#000;pointer-events:none}
.dap-toggle-knob{display:block;position:absolute;left:2px;top:2px;width:8px;height:8px;border:0;border-radius:50%;background:#8a8a8a;transition:left .12s ease,background-color .12s;pointer-events:none}
.dap-toggle>input:checked+.dap-toggle-track{border-color:var(--orange)}
.dap-toggle>input:checked+.dap-toggle-track>.dap-toggle-knob{left:16px;background:var(--orange)}
.dap-toggle:hover{background:#181818}
.dap-toggle>input:focus-visible+.dap-toggle-track{outline:1px solid var(--orange);outline-offset:4px}
.dap-toggle>input:disabled+.dap-toggle-track{opacity:.35}
.dap-toggle:has(>input:disabled),.dap-toggle>input:disabled{cursor:default}
.dap-ref-tools .dap-toggle{margin-right:auto}
.dap-field.has-toggle{padding-top:0;padding-bottom:0}
.dap-field.has-toggle>.dap-toggle{flex:0 0 38px;width:38px;margin-right:-5px;overflow:visible;pointer-events:auto;z-index:auto}
.dap-model-head{border-top:1px solid #333;gap:7px;align-items:flex-start}
.dap-model-head>.dap-toggle{height:34px}
.dap-model summary{border-top:0;min-height:34px;padding:0 5px 0 0}
.dap-model .dap-advanced>summary{min-height:27px;padding:7px;font:9px/1.5 'Roboto Mono',monospace}
.dap-error-filter{display:inline-flex;align-items:center;gap:3px;padding:0 5px 0 0;border:0;border-radius:6px;color:#999;cursor:pointer;white-space:nowrap}
.dap-error-filter:hover{background:#181818;color:#ccc}
@media(pointer:coarse){.dap-toggle,.dap-model-head>.dap-toggle,.dap-field.has-toggle>.dap-toggle{height:44px;min-width:44px;width:44px;flex-basis:44px}.dap-model summary{min-height:44px}.dap-advanced summary{min-height:30px}}
@media(prefers-reduced-motion:reduce){.dap-toggle-knob{transition:none}}
.dap-video-repair{display:flex;align-items:center;flex-wrap:wrap;gap:4px;margin:-12px 0 24px;color:#aaa;font:13px Arial,sans-serif;cursor:pointer}
.dap-video-repair small{flex-basis:100%;margin-left:42px;color:#666;font:10px/1.6 Arial,sans-serif}
.dap-video-variant{position:absolute;top:12px;left:12px;padding:4px 7px;border-radius:4px;background:#000a;color:#ccc;font:10px Arial,sans-serif;pointer-events:none}
/* Match the left edge of Image/Video; keep the existing right edge. */
.dap-controls{padding-left:0}
.dap-edit-mode{padding-left:0}
/* Align the visible sidebar levers with the tabs and section dividers. */
.dap-edit-mode>.dap-toggle,.dap-date-row>.dap-toggle,.dap-model-head>.dap-toggle,.dap-video-repair>.dap-toggle{justify-content:flex-start}
.dap-viewer-tools>.dap-compare-toggle{margin-left:auto;font:11px Arial,Helvetica,sans-serif}
.dap-compare-toggle:has(input:disabled){cursor:default;color:#666}
/* The existing model heading is the drag target; no extra handle or toolbar. */
.dap-models-sortable>.dap-model>.dap-model-head>details>summary{cursor:grab;user-select:none}
.dap-models-sortable>.dap-model>.dap-model-head>details>summary:active{cursor:grabbing}
.dap-model-dragging{opacity:.55}
/* Explain validation in the affected field without adding permanent controls. */
.dap-field:has([aria-invalid="true"]){outline:1px solid var(--orange);outline-offset:-1px}
+18 -13
View File
@@ -1,18 +1,18 @@
import { app } from '../../scripts/app.js';
import { api } from '../../scripts/api.js';
import { PlatformUI } from './dogma_api_ui.js?v=1.0.55';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.55';
import { PlatformUI } from './dogma_api_ui.js?v=1.0.62';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.62';
const ROOT=new URL('.',import.meta.url);
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_api_platform.css?v=1.0.55',ROOT);document.head.append(css);
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_api_platform.css?v=1.0.62',ROOT);document.head.append(css);
let opened=null,queueLock=false;
const cachedSchemas=fetch(new URL('dogma_api_schemas.json?v=1.0.55',ROOT)).then(r=>r.json()).catch(()=>({}));
const cachedSchemas=fetch(new URL('dogma_api_schemas.json?v=1.0.57',ROOT)).then(r=>r.json()).catch(()=>({}));
class ComfyBridge {
constructor(node){this.node=node;this.preview=false;this.pricingNodes=new Map();}
get widget(){return this.node.widgets.find(w=>w.name==='config');}
load(){const s=JSON.parse(this.widget.value||'{}');if(!s.models)throw new Error('Apri DOGMA_API_PLATFORM_V3.json.');return migrateState(s);}
load(){const s=JSON.parse(this.widget.value||'{}');if(!s.models)throw new Error('Apri DOGMA_API_PLATFORM_V5.json.');return migrateState(s);}
async initialize(state){
const [defaults,catalog,cached]=await Promise.all([(await fetch(new URL('dogma_api_defaults.json?v=1.0.55',ROOT))).json(),this.request('/catalog'),cachedSchemas]);
const [defaults,catalog,cached]=await Promise.all([(await fetch(new URL('dogma_api_defaults.json?v=1.0.57',ROOT))).json(),this.request('/catalog'),cachedSchemas]);
for(const [key,value] of Object.entries(defaults.models))state.models[key] ||= copy(value);
this.catalog=catalog;this.defs=cached;
const live=await Promise.allSettled(Object.keys(cached).map(async type=>{const r=await api.fetchApi('/object_info/'+encodeURIComponent(type));if(!r.ok)throw new Error(type);const d=await r.json();return [type,d[type]];}));
@@ -29,6 +29,8 @@ class ComfyBridge {
}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);}
loadingLogo(){return new URL('./dogma_api_assets/dogma-loading.mp4',ROOT).href;}
explorer(path){return this.request('/explorer',{path});}
logo(){return new URL('dogma_api_logo.png',ROOT).href;}
view(file){if(file?.workspace&&file?.relative)return api.apiURL('/dogma/api/v2/workspace-media?'+new URLSearchParams({workspace:file.workspace,relative:file.relative}));if(file?.url)return file.url;return api.apiURL('/view?'+new URLSearchParams(viewParameters(file)));}
async request(path,body){const headers={};if(this.catalog?.access?.token)headers['X-Dogma-Access']=this.catalog.access.token;if(body!==undefined)headers['Content-Type']='application/json';const response=await api.fetchApi('/dogma/api/v2'+path,{method:body===undefined?'GET':'POST',headers,...(body!==undefined?{body:JSON.stringify(body)}:{})});if(!response.ok)throw new Error((await response.text()).slice(0,800));return response.json();}
@@ -68,15 +70,18 @@ class ComfyBridge {
}
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)};
queueLock=true;let result=null,used=false,queueError=null,build,capture;
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;}
try{
const workflow=copy(app.graph.serialize());workflow.extra ||= {};workflow.extra.dogma_api_batch={session:state.session,id:batch,jobs:copy(compiled.jobs)};
build=function(...args){if(used)return nativeBuild.apply(this,args);used=true;return Promise.resolve({workflow,output:compiled.output});};
capture=async function(...args){try{const r=await nativeQueue.apply(this,args);if(args[1]?.workflow===workflow)result=r;return r;}catch(e){if(args[1]?.workflow===workflow)queueError=e;throw e;}};
app.graphToPrompt=build;api.queuePrompt=capture;
await app.queuePrompt(0,1);if(queueError)throw queueError;
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(build&&app.graphToPrompt===build)app.graphToPrompt=nativeBuild;if(capture&&api.queuePrompt===capture)api.queuePrompt=nativeQueue;queueLock=false;}
}
subscribe(handler){const controller=new AbortController();for(const name of ['execution_start','executing','executed','execution_success','execution_error','execution_interrupted','progress','progress_state'])api.addEventListener(name,e=>{let d=e.detail;if(name==='execution_start')this.activePrompt=d.prompt_id;if(name==='executing'&&(typeof d==='string'||d===null))d={node:d,prompt_id:this.activePrompt};handler(name,d);},{signal:controller.signal});return ()=>controller.abort();}
subscribe(handler){const controller=new AbortController();for(const name of ['execution_start','executing','executed','execution_success','execution_error','execution_interrupted','progress','progress_state','dogma_video_repair'])api.addEventListener(name,e=>{let d=e.detail;if(name==='execution_start')this.activePrompt=d.prompt_id;if(name==='executing'&&(typeof d==='string'||d===null))d={node:d,prompt_id:this.activePrompt};handler(name,d);},{signal:controller.signal});return ()=>controller.abort();}
async history(){const r=await api.fetchApi('/history?max_items=200');if(!r.ok)throw new Error('Cronologia non disponibile.');return r.json();}
async cancel(id){const r=await api.fetchApi('/jobs/'+encodeURIComponent(id)+'/cancel',{method:'POST'});if(r.ok)return r.json();if(r.status!==404)throw new Error('Interruzione non riuscita.');await api.fetchApi('/queue',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({delete:[id]})});const stopped=await api.fetchApi('/interrupt',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prompt_id:id})});if(!stopped.ok)throw new Error('Interruzione non riuscita.');}
download(state){this.save(state);const url=URL.createObjectURL(new Blob([JSON.stringify(app.graph.serialize(),null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='DOGMA_API_PLATFORM_SESSION.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
+46 -35
View File
@@ -1,49 +1,60 @@
import {copy} from './dogma_api_core.js?v=1.0.55';
import {icon} from './dogma_api_icons.js?v=1.0.55';
import {copy} from './dogma_api_core.js?v=1.0.57';
import {openViewer,copyFullImage} from './dogma_api_viewer.js?v=1.0.57';
export async function referenceEditor(ui,ref){
const make=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
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 tools=make('div','','dap-reference-tools'),viewport=make('div','','dap-mask-viewport'),stage=make('div','','dap-mask-stage'),base=make('canvas'),overlay=make('canvas');stage.append(base,overlay);viewport.append(stage);left.append(tools,viewport);
const cached=ref.editorDraft||{},draft={enabled:true,mask:false,source:'paint',maskMode:'edit',flip:false,invert:false,crop:false,resizeMpx:false,megapixels:1,expand:0,blur:0,fillHoles:false,targetWidth:0,targetHeight:0,segment:0,prompt:'',background:'#ff00ff',...copy(cached.process||ref.process||{})};
layout.append(left,right);box.append(layout);const status=make('div','','dap-editor-status');left.append(status);
let tool=cached.tool||'brush',brush=cached.brush||12,down=null,maskChanged=!!cached.paint,previewFile=Object.hasOwn(cached,'previewFile')?cached.previewFile:ref.processedPreview||null,scale=1,x=0,y=0,space=false,ready=false,paintData=cached.paint||null,revision=0;
const undo=[],fields=new Map(),mask=make('canvas'),mc=mask.getContext('2d',{willReadFrequently:true}),oc=overlay.getContext('2d',{willReadFrequently:true}),bc=base.getContext('2d',{willReadFrequently:true});
const persist=()=>{if(!ready)return;ref.editorDraft={process:copy(draft),paint:paintData,previewFile,brush,tool,view:{scale,x,y}};ui.save();};
box.addEventListener('close',persist);
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)`;
base.width=overlay.width=mask.width=image.naturalWidth;base.height=overlay.height=mask.height=image.naturalHeight;stage.style.width=mask.width+'px';stage.style.height=mask.height+'px';
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.';}}
for(let i=0;i<source.data.length;i+=4){initial.data[i]=initial.data[i+1]=initial.data[i+2]=255;initial.data[i+3]=255-source.data[i+3];source.data[i+3]=255;}bc.putImageData(source,0,0);mc.putImageData(initial,0,0);
const loadMask=async(url,alpha=false,current=()=>true)=>{const saved=new Image();saved.crossOrigin='anonymous';saved.src=url;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){if(!alpha)pixels.data[i+3]=pixels.data[i];pixels.data[i]=pixels.data[i+1]=pixels.data[i+2]=255;}if(!current())throw new Error('Le modifiche sono cambiate: aggiorna l’anteprima.');mc.putImageData(pixels,0,0);};
try{if(cached.paint)await loadMask(cached.paint,true);else if(draft.maskFile)await loadMask(ui.bridge.view(draft.maskFile));}catch{status.textContent='Maschera salvata non disponibile.';}
if(!box.isConnected)return;ready=true;
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([]);}
oc.clearRect(0,0,mask.width,mask.height);
if(draft.mask){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]=50;pixels.data[i+2]=160;pixels.data[i+3]=Math.round((draft.invert?255-pixels.data[i+3]:pixels.data[i+3])*.4);}oc.putImageData(pixels,0,0);}
if(draft.cropRect&&draft.crop){const [a,b,w,h]=draft.cropRect;oc.strokeStyle='#fff';oc.lineWidth=Math.max(1,2/scale);oc.setLineDash([10/scale,7/scale]);oc.strokeRect(a*mask.width,b*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 updateView=()=>{stage.style.transform=`translate(${x}px,${y}px) scale(${scale})`;draw();};
const fit=()=>{scale=Math.min((viewport.clientWidth-24)/mask.width,(viewport.clientHeight-24)/mask.height);x=(viewport.clientWidth-mask.width*scale)/2;y=(viewport.clientHeight-mask.height*scale)/2;updateView();persist();};
const at=(next,cx,cy)=>{next=Math.max(.03,Math.min(16,next));const ratio=next/scale;x=cx-(cx-x)*ratio;y=cy-(cy-y)*ratio;scale=next;updateView();persist();};
viewport.addEventListener('wheel',e=>{e.preventDefault();const r=viewport.getBoundingClientRect();at(scale*Math.exp(-e.deltaY*.0017),e.clientX-r.left,e.clientY-r.top);},{passive:false});
box.addEventListener('keydown',e=>{if(e.code==='Space'&&!['INPUT','SELECT','TEXTAREA'].includes(e.target.tagName)){e.preventDefault();space=true;viewport.classList.add('pan');}});box.addEventListener('keyup',e=>{if(e.code==='Space'){space=false;viewport.classList.remove('pan');}});
const preview=make('img','','dap-reference-preview');preview.alt='Anteprima della reference preparata';preview.hidden=!previewFile;if(previewFile)preview.src=ui.bridge.view(previewFile);
const previewTools=make('div','','dap-preview-tools');
const mark=()=>{revision++;previewFile=null;preview.hidden=true;previewTools.hidden=true;status.textContent='Modifiche conservate · Anteprima per controllare il risultato.';draw();persist();};
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 setTool=value=>{tool=value;for(const b of tools.querySelectorAll('[data-tool]'))b.classList.toggle('active',b.dataset.tool===value);overlay.style.cursor=value==='hand'?'grab':value==='crop'?'cell':'crosshair';persist();};
for(const [key,title] of [['brush','Pennello'],['erase','Gomma'],['crop','Crop rettangolare'],['hand','Sposta']]){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='1';size.max='180';size.value=String(brush);size.setAttribute('aria-label','Dimensione pennello');size.oninput=()=>{brush=Number(size.value);persist();};tools.append(size);
const changedPaint=()=>{maskChanged=true;paintData=mask.toDataURL('image/png');mark();};
tools.append(button('Undo',()=>{const previous=undo.pop();if(!previous)return;mc.putImageData(previous.pixels,0,0);draft.cropRect=previous.rect;changedPaint();}),button('Pulisci',()=>{saveUndo();mc.clearRect(0,0,mask.width,mask.height);delete draft.cropRect;draft.source='paint';fields.get('source').value='paint';changedPaint();}),button('Adatta',fit));
const point=e=>{const r=overlay.getBoundingClientRect();return [Math.max(0,Math.min(mask.width,(e.clientX-r.left)/scale)),Math.max(0,Math.min(mask.height,(e.clientY-r.top)/scale))];};
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';draft.mask=true;draft.source='paint';fields.get('mask').checked=true;fields.get('source').value='paint';};
viewport.onpointerdown=e=>{if(e.button===2)return;e.preventDefault();viewport.focus();viewport.setPointerCapture(e.pointerId);const pan=tool==='hand'||space||e.button===1;if(pan)down={pan:true,x,y,cx:e.clientX,cy:e.clientY};else{saveUndo();down={first:point(e),last:point(e)};if(tool!=='crop')stroke(down.first,[down.first[0]+.01,down.first[1]]);draw();}};viewport.tabIndex=0;
viewport.onpointermove=e=>{if(!down)return;if(down.pan){x=down.x+e.clientX-down.cx;y=down.y+e.clientY-down.cy;updateView();return;}const p=point(e);if(tool==='crop'){draft.crop=true;fields.get('crop').checked=true;draft.cropRect=[Math.min(p[0],down.first[0])/mask.width,Math.min(p[1],down.first[1])/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();};
viewport.onpointerup=viewport.onpointercancel=()=>{if(!down)return;const pan=down.pan;down=null;if(pan)persist();else changedPaint();};
const field=(name,key,opts={})=>{const input=ui.field(right,name,draft[key],v=>{draft[key]=typeof draft[key]==='number'?Number(v):v;mark();},opts);fields.set(key,input);return input;};
right.append(make('div','PREPARAZIONE REFERENCE','dap-label'));
field('MASK', 'mask',{type:'checkbox'});field('MASK MODE','maskMode',{choices:['isolate','edit']});field('MASK SOURCE','source',{choices:['paint','prompt']});
field('MASK PROMPT','prompt');field('SEGMENT','segment',{type:'number',min:0,max:100});field('INVERT MASK','invert',{type:'checkbox'});field('HORIZONTAL FLIP','flip',{type:'checkbox'});field('CROP','crop',{type:'checkbox'});
field('EXPAND / PX','expand',{type:'number',min:-512,max:512});field('BLUR / PX','blur',{type:'number',min:0,max:128,step:.1});field('FILL HOLES','fillHoles',{type:'checkbox'});
field('RESIZE TO MPX','resizeMpx',{type:'checkbox'});field('MEGAPIXELS','megapixels',{type:'number',min:.01,max:64,step:.1});field('CROP WIDTH','targetWidth',{type:'number',min:0,max:16384});field('CROP HEIGHT','targetHeight',{type:'number',min:0,max:16384});field('BACKGROUND','background',{type:'color'});
right.append(make('p','Isolate mantiene l’area dipinta e colora il resto. Edit colora l’area dipinta. Crop usa il rettangolo o i bordi della maschera; dimensioni 0 mantengono il crop originale. Prompt usa il nodo SAM3 del workflow.','dap-field-hint'));
const preview=make('img','','dap-reference-preview');preview.alt='Anteprima della reference preparata';preview.hidden=!previewFile;if(previewFile)preview.src=ui.bridge.view(previewFile);right.append(preview);
async function uploadMask(){if(!maskChanged)return;const out=make('canvas');out.width=mask.width;out.height=mask.height;const ctx=out.getContext('2d'),pixels=mc.getImageData(0,0,mask.width,mask.height);for(let i=0;i<pixels.data.length;i+=4){const v=pixels.data[i+3];pixels.data[i]=pixels.data[i+1]=pixels.data[i+2]=v;pixels.data[i+3]=255;}ctx.putImageData(pixels,0,0);const blob=await new Promise(resolve=>out.toBlob(resolve,'image/png'));if(!blob)throw new Error('Maschera non esportata.');const result=await ui.bridge.upload(new File([blob],'DOGMA_mask_'+Date.now()+'.png',{type:'image/png'}));draft.maskFile=result.file;maskChanged=false;}
const footer=make('div','','dap-reference-footer');
const previewButton=button('Anteprima',async()=>{previewButton.disabled=true;try{await uploadMask();const result=await ui.bridge.previewReference(ref,draft);if(!box.isConnected)return;previewFile=result.file;preview.src=ui.bridge.view(previewFile);await preview.decode();preview.hidden=false;status.textContent=`${result.width} × ${result.height} · Anteprima aggiornata`;}catch(e){preview.hidden=true;status.textContent='Anteprima non disponibile: '+e.message;}finally{previewButton.disabled=false;}});
footer.append(button('Sostituisci file',()=>{box.close();ui.pickReferences(ref);}),previewButton,button('Applica',async()=>{try{await uploadMask();ref.process=copy(draft);ref.process.enabled=true;ref.processedPreview=previewFile;ui.save();ui.renderRefs();ui.refreshPrices();box.close();ui.note('Preparazione reference salvata.');}catch(e){status.textContent=e.message;}},'dap-primary'));
box.append(footer);setTool('brush');draw();
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:128});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','Edit colora la maschera. Isolate mantiene l’area selezionata. Prompt calcola SAM3 in anteprima; puoi poi rifinire la maschera con il pennello. Rotella per zoom; Spazio o tasto centrale per spostare.','dap-field-hint'),preview,previewTools);
const previewItem=()=>({job:{kind:'image',label:'REFERENCE / ANTEPRIMA',study:true},file:{url:ui.bridge.view(previewFile)},preview:true});
const enlarge=()=>{if(previewFile)openViewer(ui,previewItem());};preview.onclick=enlarge;preview.tabIndex=0;preview.setAttribute('role','button');preview.onkeydown=e=>{if(e.key==='Enter')enlarge();};
previewTools.append(button('Ingrandisci',enlarge),button('Copia immagine',async()=>{if(!previewFile)return;try{await copyFullImage(ui.bridge.view(previewFile));status.textContent='Immagine copiata alla risoluzione originale.';}catch(e){status.textContent=e.message;}}));previewTools.hidden=!previewFile;
async function uploadMask(){const version=revision;if(!maskChanged||draft.source==='prompt')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'}));if(version!==revision)throw new Error('Le modifiche sono cambiate: aggiorna l’anteprima.');draft.maskFile=result.file;maskChanged=false;}
async function buildPreview(){const version=revision;await uploadMask();const result=await ui.bridge.previewReference(ref,copy(draft));if(version!==revision)throw new Error('Le modifiche sono cambiate: aggiorna l’anteprima.');if(result.maskFile){await loadMask(ui.bridge.view(result.maskFile),false,()=>version===revision);Object.assign(draft,{maskFile:result.maskFile,samSource:result.samSource,samPrompt:result.samPrompt,samSegment:result.samSegment});paintData=mask.toDataURL('image/png');maskChanged=false;draw();}previewFile=result.file;preview.src=ui.bridge.view(previewFile);await preview.decode();if(version!==revision){previewFile=null;throw new Error('Le modifiche sono cambiate: aggiorna l’anteprima.');}preview.hidden=false;previewTools.hidden=false;status.textContent=`${result.width} × ${result.height} · ${result.emptyMask?'SAM3 non ha trovato oggetti: prova un altro prompt.':'Anteprima aggiornata'}`;persist();return result;}
const footer=make('div','','dap-reference-footer'),previewButton=button('Anteprima',async()=>{previewButton.disabled=true;status.textContent=draft.source==='prompt'?'SAM3 · Preparazione maschera…':'Preparazione anteprima…';try{await buildPreview();}catch(e){status.textContent='Anteprima non disponibile: '+e.message;}finally{previewButton.disabled=false;}}),apply=button('Applica',async()=>{apply.disabled=true;try{if(!previewFile)await buildPreview();await uploadMask();ref.process=copy(draft);ref.process.enabled=true;ref.processedPreview=previewFile;persist();ui.renderRefs();ui.refreshPrices();box.close();ui.note('Preparazione reference salvata.');}catch(e){status.textContent=e.message;}finally{apply.disabled=false;}},'dap-primary');
footer.append(button('Sostituisci file',()=>{box.close();ui.pickReferences(ref);}),previewButton,apply);box.append(footer);setTool(tool);
if(cached.view){({scale,x,y}=cached.view);updateView();}else fit();
}
+170 -65
View File
@@ -1,7 +1,8 @@
import {ALL_FAMILIES,copy,families,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName} from './dogma_api_core.js?v=1.0.55';
import {icon} from './dogma_api_icons.js?v=1.0.55';
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.55';
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.55';
import {ALL_FAMILIES,copy,families,orderedFamilies,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName,orderResults,savedFilename,preparedMask,mediaKind} from './dogma_api_core.js?v=1.0.62';
import {icon} from './dogma_api_icons.js?v=1.0.57';
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.60';
import {modelReorder} from './dogma_api_model_order.js?v=1.0.61';
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.57';
export const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
export const btn=(text,fn,cls='',aria=text)=>{const b=el('button',text,cls);b.type='button';b.onclick=fn;b.setAttribute('aria-label',aria);b.title=aria;return b;};
@@ -17,50 +18,55 @@ export class PlatformUI {
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]);});
this.root.addEventListener('drop',e=>this.dropReferences(e));
document.body.append(this.root);this.build();this.root.tabIndex=-1;this.root.showModal();this.root.focus({preventScroll:true});
this.unsubscribe=this.bridge.subscribe?.((name,d)=>this.event(name,d));
this.note('Apertura · Collegamento a Comfy…');
await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
if(this.closed)return;this.renderControls();this.renderFilters();this.renderGallery();
try{await this.bridge.initialize?.(this.state);if(this.closed)return;this.ready=true;this.renderControls();this.updateHeader();this.refreshPrices();this.note(this.bridge.preview?'ANTEPRIMA · Nessuna richiesta API':'Pronto.');}catch(e){this.note('Collegamento non riuscito: '+e.message,true);}
Promise.allSettled([this.recover(),this.refreshLibrary(),this.refreshCredits()]);
this.timer=setInterval(()=>{this.updateCards();this.refreshPrices();if(this.state.results.some(r=>!terminal.has(r.status)))this.recover();},1800);
this.timer=setInterval(()=>{this.updateCards();this.refreshPrices();if(this.state.results.some(r=>!terminal.has(r.status)))this.recover();},500);
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?.();}
close(){if(this.closed)return;this.save();this.closed=true;clearInterval(this.timer);clearInterval(this.creditTimer);this.unsubscribe?.();for(const modal of [...(this.modals||[])].reverse())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'));
const runGroup=el('div','','dap-run-group'),counter=el('div','','dap-run-counter'),arrows=el('div');this.runCount=el('input');this.runCount.type='number';this.runCount.min='1';this.runCount.max='64';this.runCount.value=String(this.state.runCount||1);this.runCount.setAttribute('aria-label','Ripetizioni Run');
const setCount=value=>{const n=Number(value);this.state.runCount=Number.isFinite(n)?Math.max(1,Math.min(64,Math.round(n))):1;this.runCount.value=String(this.state.runCount);this.save();this.updateHeader();};
this.runCount.oninput=()=>{if(this.runCount.value!=='')setCount(this.runCount.value);};this.runCount.onchange=()=>setCount(this.runCount.value);arrows.append(ib('chevron','Aumenta ripetizioni',()=>setCount(this.state.runCount+1),'dap-run-up'),ib('chevron','Riduci ripetizioni',()=>setCount(this.state.runCount-1)));counter.append(this.runCount,arrows);runGroup.append(counter,this.runButton);
this.stopButton=btn('■ Stop',()=>this.stop(),'dap-stop','Ferma le generazioni DOGMA');this.stopButton.disabled=true;
actions.append(this.stopButton,this.credit,ib('download','Salva sessione e workflow',()=>this.bridge.download(this.state)),ib('close','Torna a Comfy',()=>this.close()),this.runButton);header.append(brand,actions);
actions.append(this.stopButton,this.credit,ib('download','Salva sessione e workflow',()=>this.bridge.download(this.state)),ib('close','Torna a Comfy',()=>this.close()),runGroup);header.append(brand,actions);
const layout=el('div','','dap-layout');this.side=el('aside','','dap-side');const tabs=el('nav','','dap-tabs');
this.imageTab=btn('',()=>this.switchMode('image'),'','Image');this.imageTab.append(icon('image'),el('span','Image'));this.videoTab=btn('',()=>this.switchMode('video'),'','Video');this.videoTab.append(icon('video'),el('span','Video'));tabs.append(this.imageTab,this.videoTab);
this.editRow=el('div','','dap-edit-mode');this.editRow.append(this.toggle('Image Edit',this.state.imageEdit,v=>{this.state.imageEdit=v;this.save();}),el('span','Image Edit'),el('small','Image 1 → compare'));
this.controls=el('div','','dap-controls');this.side.append(tabs,this.editRow,this.controls);
const main=el('main','','dap-main'),toolbar=el('div','','dap-toolbar');this.context=btn('',()=>this.folderBrowser(false),'dap-project','Apri cartella di lavoro');
const views=el('div','','dap-views');this.ab=ib('compare','Confronta due risultati',()=>this.compare());
const views=el('div','','dap-views');
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);
views.append(ib('single','Una immagine grande',()=>{slider.value='0';slider.oninput();}),slider,ib('grid','Griglia compatta',()=>{slider.value='100';slider.oninput();}));toolbar.append(this.context,views);
this.filters=el('div','','dap-filters');this.notice=el('div','','dap-notice');this.notice.setAttribute('role','status');
this.galleryViewport=el('div','','dap-gallery-viewport');this.gallery=el('div','','dap-gallery');this.galleryViewport.append(this.gallery);
this.totalProgress=el('div','','dap-total-progress');this.totalBar=el('div','','dap-progress-track');this.totalFill=el('i');this.totalBar.append(this.totalFill);this.totalText=el('span');this.totalProgress.append(this.totalBar,this.totalText);this.totalProgress.hidden=true;main.append(toolbar,this.filters,this.totalProgress,this.notice,this.galleryViewport);layout.append(this.side,main);this.root.append(header,layout);
this.renderControls();this.renderFilters();this.renderGallery();this.updateHeader();this.applyDensity();
this.totalProgress=el('div','','dap-total-progress');this.totalBar=el('div','','dap-progress-track');this.totalFill=el('i');this.totalBar.append(this.totalFill);this.totalText=el('span');this.totalProgress.append(this.totalBar,this.totalText);this.totalProgress.hidden=true;main.append(toolbar,this.filters,this.notice,this.galleryViewport);layout.append(this.side,main);this.root.append(this.totalProgress,header,layout);
this.updateHeader();this.applyDensity();
this.resize=new ResizeObserver(()=>this.applyDensity());this.resize.observe(this.galleryViewport);this.root.addEventListener('close',()=>this.resize.disconnect(),{once:true});
this.note(this.bridge.preview?'ANTEPRIMA · Immagini dal tuo design · Nessuna richiesta API':'Reference, parametri e cartella pronti.');
}
applyDensity(){if(!this.gallery)return;const columns=1+3*Number(this.state.density)/100,width=(this.galleryViewport.clientWidth||1400)/columns;this.gallery.style.setProperty('--card-min',Math.max(170,width-18)+'px');this.slider.title=`Dimensione galleria / ${Math.round(width)} px`;}
updateHeader(){const s=this.state;this.context.textContent=[s.workspace||this.bridge.catalog?.access?.output_root||'Comfy output / DOGMA / API',safeName(s.project),safeName(s.scene)].filter(Boolean).join(' / ');this.context.title=this.context.textContent;this.imageTab.classList.toggle('active',s.mode==='image');this.videoTab.classList.toggle('active',s.mode==='video');this.editRow.hidden=s.mode==='video';let n=0;try{n=plannedJobs(s).length;}catch{}this.runLabel.textContent=this.busy?'Invio…':`Run${n?' / '+n:''}`;this.runButton.disabled=this.busy||!n||!this.ready;this.updateProgress();this.runButton.title=`${n} generazioni API indipendenti, in parallelo`;}
updateHeader(){const s=this.state;this.context.textContent=[s.workspace||this.bridge.catalog?.access?.output_root||'Comfy output / DOGMA / API',safeName(s.project),safeName(s.scene)].filter(Boolean).join(' / ');this.context.title=this.context.textContent;this.imageTab.classList.toggle('active',s.mode==='image');this.videoTab.classList.toggle('active',s.mode==='video');this.editRow.hidden=s.mode==='video';let n=0;try{n=plannedJobs(s).length;}catch{}this.runLabel.textContent=this.busy?'Invio…':'Run';this.runCount.disabled=this.busy;this.runButton.disabled=this.busy||!n||!this.ready;this.updateProgress();this.runButton.title=`Run ×${s.runCount||1} · ${n} generazioni totali, con seed diversi`;this.runButton.setAttribute('aria-label',this.runButton.title);}
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;}
toggle(label,checked,onchange,tag='label'){const control=el(tag,'','dap-toggle'),input=el('input'),track=el('span','','dap-toggle-track');input.type='checkbox';input.checked=!!checked;input.setAttribute('role','switch');input.setAttribute('aria-label',label);input.onchange=()=>onchange(input.checked);control.title=label;track.setAttribute('aria-hidden','true');track.append(el('span','','dap-toggle-knob'));control.append(input,track);return control;}
field(parent,name,value,onchange,opts={}){
const row=el('label','','dap-field');row.append(el('span',name));let input;
if(opts.choices){input=el('select');for(const choice of [...new Set([...opts.choices.map(String),...(!opts.choices.map(String).includes(String(value))?[String(value)]:[])])]){const o=el('option',choice);o.value=choice;input.append(o);}input.value=String(value);row.classList.add('has-select');}
const row=el('label','','dap-field');row.append(el('span',name));let input,control;
if(opts.type==='checkbox'){control=this.toggle(name,value,onchange,'span');input=control.querySelector('input');row.classList.add('has-toggle');}
else if(opts.choices){input=el('select');for(const choice of [...new Set([...opts.choices.map(String),...(!opts.choices.map(String).includes(String(value))?[String(value)]:[])])]){const o=el('option',choice);o.value=choice;input.append(o);}input.value=String(value);row.classList.add('has-select');}
else{input=el('input');input.type=opts.type||'text';if(input.type==='checkbox')input.checked=!!value;else input.value=String(value??'');}
input.setAttribute('aria-label',name);if(opts.min!==undefined)input.min=String(opts.min);if(opts.max!==undefined)input.max=String(opts.max);if(opts.step!==undefined)input.step=String(opts.step);if(opts.placeholder)input.placeholder=opts.placeholder;if(opts.readonly)input.readOnly=true;
input.onchange=()=>onchange(input.type==='checkbox'?input.checked:input.value);row.append(input);
input.onchange=()=>onchange(input.type==='checkbox'?input.checked:input.value);row.append(control||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();};
@@ -75,16 +81,17 @@ export class PlatformUI {
const prompt=el('section','','dap-section dap-prompt');prompt.append(el('div','PROMPT','dap-label'));const wrap=el('div','','dap-prompt-wrap'),area=el('textarea');area.value=s.prompts[s.mode]||'';area.setAttribute('aria-label','Prompt');area.placeholder='Scrivi il prompt…';area.oninput=()=>{s.prompts[s.mode]=area.value;this.save();};
const resize=el('div','','dap-resize-handle');resize.title='Trascina per ingrandire il prompt';let start=null;
resize.onpointerdown=e=>{e.preventDefault();start={y:e.clientY,height:area.offsetHeight};resize.setPointerCapture(e.pointerId);};resize.onpointermove=e=>{if(start)area.style.height=Math.max(90,start.height+e.clientY-start.y)+'px';};resize.onpointerup=resize.onpointercancel=()=>start=null;wrap.append(area,resize);prompt.append(wrap);
const workSection=el('details','','dap-section dap-work');workSection.open=!!s.workExpanded;workSection.ontoggle=()=>{s.workExpanded=workSection.open;this.save();};const workTitle=el('summary','FILENAME / WORKSPACE','dap-label');workTitle.append(icon('chevron'));const work=el('div');workSection.append(workTitle,work);
const workSection=el('details','','dap-section dap-work');workSection.open=!!s.workExpanded;workSection.ontoggle=()=>{s.workExpanded=workSection.open;this.save();};const workLabel=el('div','FILENAME / WORKSPACE','dap-label dap-work-label');const workTitle=el('summary');this.namePreview=el('span',this.filenamePreview(),'dap-filename-preview');workTitle.append(this.namePreview,icon('chevron'));const work=el('div');workSection.append(workTitle,work);
this.field(work,'FILENAME',s.filename,v=>{s.filename=v;this.save();this.namePreview.textContent=this.filenamePreview();},{placeholder:'DOGMA'});
this.field(work,'PROJECT',s.project,v=>{s.project=v;this.save();this.updateHeader();this.namePreview.textContent=this.filenamePreview();},{placeholder:'Facoltativo'});
this.field(work,'SCENE',s.scene,v=>{s.scene=v;this.save();this.updateHeader();this.namePreview.textContent=this.filenamePreview();},{placeholder:'Facoltativo'});
const date=el('div','','dap-date-row'),datePicker=el('input');datePicker.type='date';const code=s.date||todayCode();datePicker.value=`20${code.slice(4,6)}-${code.slice(2,4)}-${code.slice(0,2)}`;datePicker.setAttribute('aria-label','Data del filename');datePicker.onchange=()=>{const [year,month,day]=datePicker.value.split('-');if(!year)return;s.date=day+month+year.slice(-2);s.dateMode='manual';this.save();this.namePreview.textContent=this.filenamePreview();};date.append(this.toggle('Aggiungi data al filename',s.appendDate,v=>{s.appendDate=v;s.date ||= todayCode();this.save();this.namePreview.textContent=this.filenamePreview();}),el('span','Aggiungi data'),datePicker);work.append(date);
const choose=ib('folder','Scegli cartella di lavoro',()=>this.chooseWorkspace(),'dap-workspace-button');choose.append(el('span',s.workspace||'Scegli cartella di lavoro'));work.append(choose);
this.namePreview=el('div',this.filenamePreview(),'dap-filename-preview');work.append(this.namePreview);
const models=el('section','','dap-section dap-models');models.append(el('div','MODELS','dap-label'));for(const f of families(s))models.append(this.model(f));
const choose=ib('folder','Scegli cartella di lavoro',()=>this.chooseWorkspace(),'dap-workspace-button');choose.append(el('span',s.workspace||'Scegli cartella di lavoro'));const folderRow=el('div','','dap-workspace-row'),explorer=btn('Esplora file',()=>this.openWorkspaceExplorer(),'dap-workspace-explorer','Apri in Esplora file');explorer.append(icon('external'));folderRow.append(choose,explorer);work.append(folderRow);
const models=el('section','','dap-section dap-models');models.append(el('div','MODELS','dap-label'));for(const f of orderedFamilies(s))models.append(this.model(f));
if(models.querySelectorAll('.dap-model').length>1)modelReorder(models,order=>{s.modelOrder=[...order,...(s.modelOrder||[]).filter(key=>!order.includes(key))];this.save();});
if(s.mode==='video'){const choice=el('section','','dap-video-choice');choice.append(el('div','WORKFLOW VIDEO','dap-label'));for(const [key,label] of [['reference','Ref → Video'],['frames','First / Last frame']]){const b=btn(label,()=>{s.models.seedance.engine=key;this.save();this.renderControls();this.refreshPrices();},key===s.models.seedance.engine?'active':'');choice.append(b);}c.append(choice);}
c.append(refs,prompt,workSection,models);
if(s.mode==='video'){const fix=el('label','','dap-video-repair');fix.append(this.toggle('Correggi scatti',s.videoRepair,v=>{s.videoRepair=v;this.save();},'span'),el('span','Correggi scatti'));fix.append(el('small','Salva anche una seconda copia · durata e fps originali'));c.append(fix);}
c.append(refs,prompt,workLabel,workSection,models);
}
filenamePreview(){return [...titleParts(this.state),'MODEL',this.state.mode==='video'?'00001.mp4':'00001.png'].filter(Boolean).join('_');}
renderRefs(){
@@ -107,13 +114,45 @@ export class PlatformUI {
}
this.refs.append(tile);
});
const frames=this.state.mode==='video'&&this.state.models.seedance.engine==='frames',mixed=this.state.mode==='video'&&!frames;const add=ib('plus',mixed?'Aggiungi immagini o video':'Aggiungi immagine',()=>this.pickReferences(),'dap-add');add.append(el('span',mixed?'Immagini / Video':frames?'First / Last frame':'Immagini'));if(!frames||visible.length<2)this.refs.append(add);
const frames=this.state.mode==='video'&&this.state.models.seedance.engine==='frames',mixed=this.state.mode==='video'&&!frames;const add=ib('plus',mixed?'Aggiungi immagini o video':'Aggiungi immagine',()=>this.pickReferences(),'dap-add');const hoverIcon=icon(mixed?'media':'image');hoverIcon.classList.add('dap-add-hover');add.append(hoverIcon);if(!frames||visible.length<2)this.refs.append(add);
}
pickReferences(replace=null){const i=el('input');i.type='file';i.accept=this.state.mode==='video'&&this.state.models.seedance.engine!=='frames'?'image/*,video/*':'image/*';i.multiple=!replace;i.hidden=true;this.root.append(i);i.onchange=()=>{this.addReferences([...i.files],replace);i.remove();};i.addEventListener('cancel',()=>i.remove(),{once:true});i.click();}
async addReferences(files,replace=null){try{this.note('Caricamento reference…');for(const file of files){if(!/^(image|video)\//.test(file.type))throw new Error('Scegli immagini o video.');const frames=this.state.mode==='video'&&this.state.models.seedance.engine==='frames';if(file.type.startsWith('video/')&&(this.state.mode==='image'||frames))throw new Error('In questa modalità puoi caricare solo immagini.');if(frames&&!replace&&visibleReferences(this.state).length>=2)throw new Error('First / Last frame accetta due immagini.');const uploaded=await this.bridge.upload(file);if(this.closed)return;const r={...uploaded,enabled:true,modes:[this.state.mode],role:frames?(replace?.role|| (visibleReferences(this.state).some(r=>r.role==='first')?'last':'first')):'reference',process:{enabled:false,mask:false,maskMode:'isolate',source:'paint',flip:false,invert:false,crop:false,fillHoles:true,expand:0,blur:0,targetWidth:0,targetHeight:0,background:'#00ff00'}};if(replace){const at=this.state.references.indexOf(replace);this.state.references.splice(at,1,r);}else this.state.references.push(r);}this.save();this.renderRefs();this.refreshPrices();this.note('Reference aggiornate. L’ordine è quello mostrato.');}catch(e){this.note(e.message,true);}}
dropReferences(e){
const files=[...(e.dataTransfer?.files||[])];if(!files.length)return;
e.preventDefault();e.stopPropagation();
const tile=e.target.closest?.('.dap-ref'),replace=tile&&this.refs?.contains(tile)?visibleReferences(this.state)[Number(tile.dataset.ref)]:null;
return this.addReferences(files,replace);
}
async addReferences(files,replace=null){
if(!files.length)return;
try{
const mode=this.state.mode,engine=this.state.models.seedance?.engine,frames=mode==='video'&&engine==='frames';
const kinds=files.map(mediaKind);
if(kinds.some(k=>!k))throw new Error('Scegli immagini o video.');
if(kinds.includes('video')&&(mode==='image'||frames))throw new Error('In questa modalità puoi caricare solo immagini.');
if(replace&&!this.state.references.includes(replace))throw new Error('La reference da sostituire non è più presente.');
if(frames&&visibleReferences(this.state).length+files.length-(replace?1:0)>2)throw new Error('First / Last frame accetta due immagini.');
this.note(replace?'Sostituzione reference…':'Caricamento reference…');
const uploaded=[];for(const file of files)uploaded.push(await this.bridge.upload(file));
if(this.closed)return;
if(this.state.mode!==mode||this.state.models.seedance?.engine!==engine)throw new Error('Modalità cambiata durante il caricamento. Rilascia nuovamente i file.');
const at=replace?this.state.references.indexOf(replace):-1;
if(replace&&at<0)throw new Error('La reference da sostituire è stata rimossa. Rilascia nuovamente il file.');
if(frames&&visibleReferences(this.state).length+files.length-(replace?1:0)>2)throw new Error('First / Last frame accetta due immagini.');
const roles=new Set(visibleReferences(this.state).filter(r=>r!==replace).map(r=>r.role));
const incoming=uploaded.map((item,i)=>{
const previous=i===0?replace:null,role=previous?.role||(frames?(!roles.has('first')?'first':'last'):'reference');roles.add(role);
return {...item,kind:kinds[i],enabled:previous?.enabled??true,modes:previous?.modes?[...previous.modes]:[mode],role,
process:{enabled:false,mask:false,maskMode:'edit',source:'paint',flip:false,invert:false,crop:false,fillHoles:false,expand:0,blur:0,targetWidth:0,targetHeight:0,background:'#ff00ff'}};
});
if(replace){this.state.references.splice(at,1,incoming[0]);this.state.references.push(...incoming.slice(1));}
else this.state.references.push(...incoming);
this.save();this.renderRefs();this.refreshPrices();this.note(replace?'Reference sostituita.':'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 m=this.state.models[f.key],wrap=el('div','','dap-model'),row=el('div','','dap-model-head');wrap.dataset.modelKey=f.key;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);
@@ -132,7 +171,7 @@ export class PlatformUI {
const spec=this.bridge.inputSpec?.(this.state,f,key);
if(spec){const info=spec[1]||{};if(Array.isArray(spec[0]))opts.choices=spec[0];else if(choicesFor(spec))opts.choices=choicesFor(spec);if(info.min!==undefined)opts.min=info.min;if(info.max!==undefined)opts.max=info.max;if(info.step!==undefined)opts.step=info.step;}
if(opts.choices){opts.choices=sortedChoices(key,opts.choices);delete opts.readonly;}
this.field(body,displayName(key),value,v=>{values[key]=typeof value==='boolean'?v:typeof value==='number'?Number(v):v;if(key==='model'){this.bridge.changeModel?.(this.state,f);this.renderControls();}this.save();this.refreshPrices();},opts);
this.field(body,displayName(key),value,v=>{values[key]=typeof value==='boolean'?v:typeof value==='number'?Number(v):v;if(key==='model'){this.bridge.changeModel?.(this.state,f);this.renderControls();}this.save();this.refreshPrices();this.recheckValidation();},opts);
}
if(values.system_prompt!==undefined){const advanced=el('details','','dap-advanced');advanced.append(el('summary','SYSTEM PROMPT'));const text=el('textarea');text.value=values.system_prompt;text.setAttribute('aria-label',f.name+' system prompt');text.oninput=()=>{values.system_prompt=text.value;this.save();};advanced.append(text);body.append(advanced);}
if(f.key==='seedance')body.append(el('div',m.engine==='frames'?'Usa un First frame, un Last frame o entrambi. Sono accettate soltanto immagini.':'Usa immagini o video come reference. In Edit la durata segue il video sorgente.','dap-field-hint'));
@@ -140,56 +179,96 @@ export class PlatformUI {
}
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));}
allResults(){const map=new Map;for(const r of [...this.library,...this.state.results])map.set(r.id,r);return orderResults([...map.values()]);}
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 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();};input.style.paddingLeft=(name.length*.6+1.8)+'em';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()));
const errors=el('label','','dap-error-filter');errors.append(this.toggle('Mostra o nascondi generazioni fallite',!s.filters.hideErrors,checked=>{s.filters.hideErrors=!checked;this.save();this.renderGallery();},'span'),el('span','Mostra errori'));this.filters.append(errors,this.compareToggle(),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);
const scroll=this.galleryViewport?.scrollTop||0,version=this.galleryVersion=(this.galleryVersion||0)+1;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();
const pending=list.flatMap(job=>(job.images?.length?job.images:[null]).map((file,index)=>({job,file,index})));let offset=0;
const append=()=>{if(this.closed||version!==this.galleryVersion)return;const fragment=document.createDocumentFragment();for(const item of pending.slice(offset,offset+40))fragment.append(this.card(item.job,item.file,item.index));this.gallery.append(fragment);offset+=40;this.updateCards();this.updateSelection();if(offset<pending.length)requestAnimationFrame(append);};append();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;}
if(job.kind==='video'){
const video=el('video');video.src=this.bridge.view(file);video.muted=true;video.preload='metadata';video.loop=true;video.playsInline=true;media.append(video);
const duration=el('span','','dap-video-duration');video.onloadedmetadata=()=>{duration.textContent=Number.isFinite(video.duration)?`${Math.floor(video.duration/60)}:${String(Math.floor(video.duration%60)).padStart(2,'0')}`:'';};media.append(icon('playCircle'),duration);
media.onpointerenter=()=>{video.play().then(()=>media.classList.add('playing')).catch(()=>{});};media.onpointerleave=()=>{video.pause();media.classList.remove('playing');};
}else{const base=job.imageEdit&&job.baseReference?(job.baseReference.comparePreview||this.bridge.view(job.baseReference.processedPreview||job.baseReference.file)):null;const comparison=hoverCompare(media,this.bridge.view(file),base,()=>this.state.compareEnabled!==false);comparison.image.loading='lazy';comparison.image.decoding='async';comparison.image.alt=title;}
media.onclick=()=>openViewer(this,{job,file,index});media.tabIndex=0;media.setAttribute('role','button');media.setAttribute('aria-label','Apri '+title);media.onkeydown=e=>{if(e.key==='Enter')media.click();};card.append(media);
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);
const select=btn('A\\B',()=>this.selectCompare(item),'dap-icon-button dap-ab','Scegli immagine o video per il confronto A/B');select.dataset.compare=item.id;
tools.append(select,ib('plus','Usa come reference',()=>this.reuse(file,job.kind)),ib('prompt','Leggi e copia prompt',()=>this.showPrompt(job)),ib('download','Scarica file',()=>this.downloadImage(file)));card.append(tools);
if(job.study)card.append(el('span','DESIGN REFERENCE','dap-study'));
}else{card.classList.add('pending');const spinner=el('div','','dap-spinner');for(let i=0;i<16;i++){const dot=el('i');dot.style.setProperty('--i',i);spinner.append(dot);}const track=el('div','','dap-progress-track dap-card-progress');track.append(el('i'));card.append(spinner,el('span','','dap-job-state'),track);}
const footer=el('footer','','dap-card-footer');footer.append(el('span',title+(job.index!==undefined?' / '+(job.index+1):'')),el('span','','dap-elapsed'));card.append(footer);
const tags=[job.project,job.scene].filter(Boolean);if(tags.length)card.append(el('div',tags.join(' / '),'dap-card-tags'));
if(job.warning||job.error)card.append(el('p',job.warning||job.error,'dap-card-error'));
if(file.variant){const variant=el('span',({original:'ORIGINALE',repaired:'SCATTI CORRETTI',checked:'VERIFICATO · INVARIATO'})[file.variant]||'','dap-video-variant');variant.title=job.repair?.status==='unchanged'?'Nessuno scatto rilevato: copia identica all’originale.':variant.textContent;card.append(variant);}
}else{
card.classList.add('pending');const logo=el('video','','dap-loading-logo');logo.src=this.bridge.loadingLogo();logo.muted=true;logo.loop=true;logo.autoplay=true;logo.playsInline=true;logo.setAttribute('aria-label','Generazione in corso');
const track=el('div','','dap-progress-track dap-card-progress');track.append(el('i'));const error=el('div','','dap-error-content');error.append(el('span','ERRORE'),el('p',job.error||''));card.append(logo,track,error);
}
const footer=el('footer','','dap-card-footer'),caption=el('span',title+(job.index!==undefined?' / '+(job.index+1):'')+(file?' - '+savedFilename(job,index):''),'dap-result-name');caption.title=caption.textContent;
footer.append(caption);if(!file)footer.append(el('span','','dap-job-state'));footer.append(el('span',[job.project,job.scene].filter(Boolean).join(' / '),'dap-card-tags'),el('span','','dap-elapsed'));card.append(footer);
if(job.warning)card.append(el('p',job.warning,'dap-card-error'));
card.append(el('span','','dap-error-countdown'));
if(!this.cards.has(job.id))this.cards.set(job.id,[]);this.cards.get(job.id).push(card);return card;
}
updateCards(){this.updateProgress();for(const job of this.allResults())for(const card of this.cards.get(job.id)||[]){const bar=card.querySelector('.dap-card-progress>i');if(bar){const p=this.jobProgress(job);bar.style.width=p.percent+'%';bar.parentElement.classList.toggle('indeterminate',p.indeterminate);bar.parentElement.title=p.label;}const status=card.querySelector('.dap-job-state');if(status)status.textContent=({submitting:'Invio',queued:'In attesa di Comfy',running:'Generazione API',failed:'Errore',cancelled:'Interrotta'})[job.status]||job.status;card.classList.toggle('stopped',terminal.has(job.status));const elapsed=card.querySelector('.dap-elapsed');elapsed.textContent=job.study?'LAYOUT':job.started?Math.floor(((job.finished||Date.now())-job.started)/1000)+'s':'';if(job.error&&!card.querySelector('.dap-card-error'))card.append(el('p',job.error,'dap-card-error'));}}
modalBox(title,cls=''){
this.modal?.close();const dialog=this.modal=el('dialog','','dap-modal '+cls);dialog.setAttribute('aria-label',title);const header=el('header');header.append(el('span',title),ib('close','Chiudi',()=>dialog.close()));dialog.append(header);this.root.append(dialog);
let down=false;dialog.addEventListener('pointerdown',e=>down=e.target===dialog);dialog.addEventListener('click',e=>{if(down&&e.target===dialog)dialog.close();down=false;});
dialog.addEventListener('cancel',e=>e.stopPropagation());dialog.addEventListener('keydown',e=>{if(e.key==='Escape'){e.preventDefault();e.stopPropagation();dialog.close();}});dialog.addEventListener('close',()=>{dialog.remove();if(this.modal===dialog)this.modal=null;});dialog.tabIndex=-1;dialog.showModal();dialog.focus({preventScroll:true});return dialog;
updateCards(){
this.updateProgress();let expired=false;
for(const job of this.allResults())for(const card of this.cards.get(job.id)||[]){
const p=this.jobProgress(job),bar=card.querySelector('.dap-card-progress>i');if(bar){bar.style.width=p.percent+'%';bar.parentElement.classList.toggle('indeterminate',!!p.indeterminate);bar.parentElement.title=p.label;}
const status=card.querySelector('.dap-job-state');if(status)status.textContent=job.status==='repairing'?(job.repairStage||'Correzione scatti'):({submitting:'Invio',queued:'In attesa',running:'Generazione API',failed:'Errore',cancelled:'Interrotta',missing:'Output assente'})[job.status]||job.status;
card.classList.toggle('stopped',terminal.has(job.status));card.classList.toggle('failed',['failed','missing'].includes(job.status));
const elapsed=card.querySelector('.dap-elapsed'),seconds=job.started?Math.max(0,Math.floor(((job.finished||Date.now())-job.started)/1000)):null;elapsed.textContent=job.study?'LAYOUT':seconds!==null?seconds+'s'+(!terminal.has(job.status)&&p.expected?'/~'+Math.round(p.expected)+'s':''):'';
const error=card.querySelector('.dap-error-content p');if(error)error.textContent=job.error||'';
const countdown=card.querySelector('.dap-error-countdown'),remaining=Math.ceil(((job.errorVisibleUntil||0)-Date.now())/1000);countdown.textContent=this.state.filters.hideErrors&&['failed','missing'].includes(job.status)&&remaining>0?`Si nasconde tra ${remaining}s`:'';
if(this.state.filters.hideErrors&&['failed','missing'].includes(job.status)&&remaining<=0)expired=true;
const logo=card.querySelector('.dap-loading-logo');if(logo&&terminal.has(job.status))logo.pause();
}
if(expired)this.renderGallery();this.updateSelection();
}
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]);}
selectCompare(item){
const at=this.selection.findIndex(x=>x.id===item.id);
if(at>=0)this.selection.splice(at,1);else{if(this.selection.length===2)this.selection=[];this.selection.push(item);}
this.updateSelection();if(this.selection.length===2){this.note('Confronto A/B · seleziona un’altra immagine per iniziare una nuova coppia.');this.compare();}else this.note(this.selection.length?'A selezionata · scegli il secondo risultato per aprire il confronto.':'Selezione confronto rimossa.');
}
updateSelection(){for(const b of this.root?.querySelectorAll('[data-compare]')||[]){const n=this.selection.findIndex(x=>x.id===b.dataset.compare);b.textContent=n<0?'A\\B':n===0?'A':'B';b.classList.toggle('selected',n>=0);b.setAttribute('aria-pressed',String(n>=0));}}
showPrompt(job){const box=this.modalBox('PROMPT','dap-prompt-modal',true),text=el('textarea');text.value=job.prompt||'Prompt non disponibile per questo output.';text.readOnly=true;text.setAttribute('aria-label','Prompt originale');box.append(text,btn('Copia prompt',async e=>{const button=e.currentTarget;try{await navigator.clipboard.writeText(text.value);button.textContent='Copiato';}catch{text.select();}},'dap-outline'));}
async openWorkspaceExplorer(){try{const path=this.state.workspace||this.bridge.catalog?.access?.output_root;await this.bridge.explorer(path);}catch(e){this.note(e.message,true);}}
modalBox(title,cls='',nested=false){
this.modals ||= [];if(!nested)for(const box of [...this.modals].reverse())box.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();this.modals=this.modals.filter(d=>d!==dialog);this.modal=this.modals.at(-1)||null;});this.modals.push(dialog);dialog.tabIndex=-1;dialog.showModal();dialog.focus({preventScroll:true});return dialog;
}
compareToggle(available=true){
const label=el('label','','dap-error-filter dap-compare-toggle'),control=this.toggle('Compare',available&&this.state.compareEnabled!==false,v=>this.setCompareEnabled(v),'span');
const input=control.querySelector('input');input.dataset.compareToggle='';input.disabled=!available;
label.title=available?'Attiva o disattiva il confronto al passaggio del mouse':'Nessuna immagine di confronto disponibile';
label.append(control,el('span','Compare'));return label;
}
setCompareEnabled(enabled){
this.state.compareEnabled=!!enabled;this.save();
for(const input of this.root?.querySelectorAll('[data-compare-toggle]')||[])input.checked=!!enabled&&!input.disabled;
if(!enabled)for(const host of this.root?.querySelectorAll('.dap-compare-host.comparing')||[])host.classList.remove('comparing');
}
compare(){if(this.selection.length===2){this.setCompareEnabled(true);openViewer(this,this.selection[0],this.selection[1]);}}
async openOutput(job,index){try{const target=await this.bridge.openOutput(job.id,index);await this.folderBrowser(false,target.path,target.filename);}catch(e){this.note(e.message,true);if(this.modal)this.modal.append(el('p',e.message,'dap-operation-note'));}}
async downloadImage(file){try{const r=await fetch(this.bridge.view(file));if(!r.ok)throw new Error('File non disponibile.');const url=URL.createObjectURL(await r.blob());this.urls.add(url);const a=el('a');a.href=url;a.download=file.filename||'DOGMA_output';a.click();}catch(e){this.note(e.message,true);}}
async reuse(file,kind){try{const r=await fetch(this.bridge.view(file));if(!r.ok)throw new Error('File non disponibile.');const blob=await r.blob();await this.addReferences([new File([blob],file.filename||'DOGMA_reference.png',{type:blob.type|| (kind==='video'?'video/mp4':'image/png')})]);}catch(e){this.note(e.message,true);}}
async chooseWorkspace(){return this.folderBrowser(true);}
async folderBrowser(choose=true,initial=null,selected=''){
const box=this.modalBox(choose?'SCEGLI CARTELLA DI LAVORO':'CARTELLA / FILE','dap-folder-modal'),bar=el('div','','dap-folder-navigation'),address=el('input'),list=el('div','','dap-folder-list'),footer=el('div','','dap-folder-footer'),error=el('p','','dap-operation-note');address.setAttribute('aria-label','Percorso cartella');bar.append(address,btn('Apri',()=>render(address.value),'dap-outline'));box.append(bar,list,error,footer);
const render=async path=>{list.replaceChildren(el('p','Caricamento cartella…'));error.textContent='';try{const data=await this.bridge.folders(path);if(!box.isConnected)return;address.value=data.path;list.replaceChildren();footer.replaceChildren();
const box=this.modalBox(choose?'SCEGLI CARTELLA DI LAVORO':'CARTELLA / FILE','dap-folder-modal'),bar=el('div','','dap-folder-navigation'),address=el('input'),list=el('div','','dap-folder-list'),footer=el('div','','dap-folder-footer'),error=el('p','','dap-operation-note');address.setAttribute('aria-label','Percorso cartella');bar.append(address);box.append(bar,list,error,footer);
let navigation=0,typing;const render=async path=>{const token=++navigation;error.textContent='';try{const data=await this.bridge.folders(path);if(!box.isConnected||token!==navigation)return;address.value=data.path;list.replaceChildren();footer.replaceChildren();
if(data.parent)list.append(btn('↑ Cartella superiore',()=>render(data.parent),'dap-outline'));
for(const root of data.roots||[]){const b=ib('folder',root.name,()=>render(root.path));b.append(el('span',root.name));list.append(b);}
for(const dir of data.directories){const b=ib('folder',dir.name,()=>render(dir.path));b.append(el('span',dir.name));list.append(b);}
@@ -197,15 +276,16 @@ export class PlatformUI {
const name=el('input');name.placeholder='Nome nuova cartella';name.setAttribute('aria-label','Nome nuova cartella');footer.append(name,btn('Crea cartella',async()=>{try{const d=await this.bridge.mkdir(data.path,name.value);await render(d.path);}catch(e){error.textContent=e.message;}},'dap-outline'));
if(choose)footer.append(btn('Usa questa cartella',async()=>{try{const result=await this.bridge.workspace(data.path);this.state.workspace=result.path;for(const record of result.records||[]){const existing=this.state.results.find(j=>j.id===record.id);if(existing)Object.assign(existing,record);}this.library=[...this.library.filter(r=>!(result.records||[]).some(x=>x.id===r.id)),...(result.records||[])];this.save();this.renderFilters();this.renderGallery();box.close();this.renderControls();this.updateHeader();this.note('Cartella di lavoro selezionata.');}catch(e){error.textContent=e.message;}},'dap-primary'));
list.querySelector('[aria-current]')?.scrollIntoView({block:'center'});
}catch(e){list.replaceChildren();error.textContent=e.message;}};address.onkeydown=e=>{if(e.key==='Enter')render(address.value);};await render(initial??this.state.workspace);
}catch(e){if(token===navigation)error.textContent=e.message;}};address.oninput=()=>{clearTimeout(typing);navigation++;typing=setTimeout(()=>render(address.value.trim().replace(/^"|"$/g,'')),650);};address.onkeydown=e=>{if(e.key==='Enter'){e.preventDefault();clearTimeout(typing);render(address.value.trim().replace(/^"|"$/g,''));}};box.addEventListener('close',()=>{clearTimeout(typing);navigation++;});await render(initial??this.state.workspace);
}
jobProgress(job){
if(terminal.has(job.status))return {percent:100,label:job.status,remaining:0};
if(terminal.has(job.status))return {percent:job.status==='completed'?100:job.stoppedProgress??Math.min(99,(job.progress||0)*100),label:job.status,remaining:0};
if(job.status==='repairing')return {percent:Math.min(99,90+9*(job.repairProgress||0)),label:job.repairStage||'Correzione scatti',remaining:null};
if(Number.isFinite(job.progress)&&job.progress>0)return {percent:Math.min(99,job.progress*100),label:Math.round(job.progress*100)+'% · avanzamento Comfy',remaining:job.progress<1?Math.max(0,Math.round((Date.now()-job.started)/1000*(1-job.progress)/job.progress)):0};
const samples=this.allResults().filter(j=>j.family===job.family&&j.status==='completed'&&j.finished>j.started&&!j.study).slice(0,8).map(j=>(j.finished-j.started)/1000);
if(!samples.length)return {percent:15,indeterminate:true,label:'Tempo trascorso · stima disponibile dopo le prime generazioni',remaining:null};
const expected=samples.reduce((a,b)=>a+b,0)/samples.length,elapsed=(Date.now()-job.started)/1000;
return {percent:Math.min(94,100*elapsed/expected),remaining:Math.max(0,Math.round(expected-elapsed)),label:elapsed<expected?'~'+Math.round(expected-elapsed)+'s rimanenti · stima':'Finalizzazione · stima superata'};
return {expected,percent:Math.min(94,100*elapsed/expected),remaining:Math.max(0,Math.round(expected-elapsed)),label:elapsed<expected?'~'+Math.round(expected-elapsed)+'s rimanenti · stima':'Finalizzazione · stima superata'};
}
updateProgress(){
if(!this.totalProgress)return;const jobs=this.state.results.filter(j=>!terminal.has(j.status)),ids=new Set(jobs.map(j=>j.batch));const batch=this.state.results.filter(j=>ids.has(j.batch));
@@ -215,35 +295,60 @@ export class PlatformUI {
}
async stop(){
this.stopRequested=true;const jobs=this.state.results.filter(j=>!terminal.has(j.status));const ids=[...new Set(jobs.map(j=>j.promptId).filter(Boolean))];this.stopButton.disabled=true;this.note('Interruzione richiesta…');
const results=await Promise.allSettled(ids.map(id=>this.bridge.cancel(id)));for(let i=0;i<ids.length;i++)if(results[i].status==='fulfilled')for(const job of jobs.filter(j=>j.promptId===ids[i]))if(!terminal.has(job.status)){job.status='cancelled';job.finished=Date.now();}
const results=await Promise.allSettled(ids.map(id=>this.bridge.cancel(id)));for(let i=0;i<ids.length;i++)if(results[i].status==='fulfilled')for(const job of jobs.filter(j=>j.promptId===ids[i]))if(!terminal.has(job.status)){job.stoppedProgress=this.jobProgress(job).percent;job.status='cancelled';job.finished=Date.now();}
this.save();this.updateCards();this.note(results.some(r=>r.status==='rejected')?'Una richiesta di stop non è riuscita. Riprova.':'Stop inviato a Comfy. Le richieste già completate dal servizio possono essere addebitate.',results.some(r=>r.status==='rejected'));
}
async refreshLibrary(){if(!this.bridge.library||this.closed)return;try{this.library=await this.bridge.library();if(this.closed)return;for(const r of this.library.filter(r=>r.imported)){const existing=this.state.results.find(j=>j.id===r.id);if(existing)Object.assign(existing,r);}this.renderFilters();this.renderGallery();}catch(e){this.note('Libreria temporaneamente non disponibile.',true);}}
clearValidation(){
this.validationError=null;for(const input of this.controls?.querySelectorAll('[aria-invalid="true"]')||[])input.removeAttribute('aria-invalid');
}
reportValidation(error,focus=true){
this.clearValidation();this.validationError=error;this.note(error.message,true);
if(!error.family)return;
const model=[...(this.controls?.querySelectorAll('.dap-model')||[])].find(e=>e.dataset.modelKey===error.family);if(!model)return;
const fields=new Set((error.fields||[]).map(displayName)),inputs=[...model.querySelectorAll('input,select')].filter(e=>fields.has(e.getAttribute('aria-label')));
for(const input of inputs)input.setAttribute('aria-invalid','true');
if(focus){model.querySelector('details').open=true;this.state.models[error.family].expanded=true;this.save();
if(inputs[0]){inputs[0].focus({preventScroll:true});inputs[0].scrollIntoView({block:'center',inline:'nearest'});}
}
}
recheckValidation(){
if(!this.validationError)return;
try{validateState(this.state,(f,k)=>this.bridge.inputSpec?.(this.state,f,k));this.clearValidation();this.note('Parametri validi. Premi Run per generare.');}
catch(e){this.reportValidation(e,false);}
}
async run(){
if(this.busy)return;try{validateState(this.state);}catch(e){this.note(e.message,true);return;}
this.stopRequested=false;this.busy=true;this.updateHeader();const snapshot=copy(this.state),batch=crypto.randomUUID(),started=Date.now();
const jobs=plannedJobs(snapshot).map(p=>({...p,id:crypto.randomUUID(),batch,started,status:'submitting',images:[]}));
if(this.busy||!this.ready)return;const specFor=(f,k)=>this.bridge.inputSpec?.(this.state,f,k);
try{validateState(this.state,specFor);}catch(e){this.reportValidation(e);return;}
this.clearValidation();let jobs=[];
try{
this.stopRequested=false;this.busy=true;this.pendingEvents=[];this.updateHeader();
const snapshot=copy(this.state),batch=crypto.randomUUID(),started=Date.now();
jobs=plannedJobs(snapshot).map((p,ordinal)=>({...p,id:crypto.randomUUID(),batch,started,batchStarted:started,ordinal,status:'submitting',images:[]}));
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;
for(const ref of activeReferences(snapshot).filter(r=>r.kind==='image'&&r.process?.enabled)){
if((ref.process.source==='prompt'&&ref.process.mask)||(ref===primary&&snapshot.mode==='image'&&snapshot.imageEdit)){
this.note(ref.process.source==='prompt'?'Preparazione maschera SAM3…':'Preparazione Image 1…');const prepared=await this.bridge.previewReference(ref,ref.process);ref.processedPreview=prepared.file;
if(prepared.maskFile)Object.assign(ref.process,{maskFile:prepared.maskFile,samSource:prepared.samSource,samPrompt:prepared.samPrompt,samSegment:prepared.samSegment});
}
}
const seed=new Uint32Array(1);crypto.getRandomValues(seed);const compiled=compileBatch(snapshot,jobs,seed[0]%2147483647);
const seed=new Uint32Array(1);crypto.getRandomValues(seed);const compiled=compileBatch(snapshot,jobs,seed[0]%2147483647,(f,k)=>this.bridge.inputSpec?.(snapshot,f,k));
this.note('Controllo reference e nodi…');await this.bridge.check(snapshot,compiled);if(this.closed||this.stopRequested)return;
this.state.results.push(...jobs);this.save();this.renderFilters();this.renderGallery();this.galleryViewport.scrollTop=0;
const promptId=await this.bridge.queue(compiled,batch,this.state);for(const job of jobs){job.promptId=promptId;if(job.status==='submitting')job.status='queued';}for(const [name,d] of this.pendingEvents||[])this.event(name,d);this.pendingEvents=[];if(this.stopRequested)await this.stop();this.save();this.updateCards();this.note(`${jobs.length} generazioni indipendenti inviate in un unico batch parallelo.`);
}catch(e){for(const j of jobs){if(!terminal.has(j.status)){j.status='failed';j.error=e.message;j.finished=Date.now();}}this.save();this.updateCards();this.note(e.message,true);}finally{this.busy=false;if(!this.closed)this.updateHeader();}
}catch(e){for(const j of jobs){if(!terminal.has(j.status)){j.stoppedProgress=this.jobProgress(j).percent;j.status='failed';j.error=e.message;j.finished=Date.now();j.errorVisibleUntil=Date.now()+5000;}}this.save();this.updateCards();this.reportValidation(e);}finally{this.busy=false;this.pendingEvents=[];if(!this.closed)this.updateHeader();}
}
event(name,d){
if(name==='dogma_video_repair'){const job=this.state.results.find(j=>j.id===d?.job_id);if(job&&!terminal.has(job.status)){job.status='repairing';job.repairProgress=d.value;job.repairStage=d.stage;this.save();this.updateCards();}return;}
if(!d?.prompt_id)return;const jobs=this.state.results.filter(j=>j.promptId===d.prompt_id);if(!jobs.length){this.pendingEvents ||= [];if(this.busy&&this.pendingEvents.length<200)this.pendingEvents.push([name,d]);return;}
if(name==='progress_state'){for(const [id,n] of Object.entries(d.nodes||{})){const j=jobs.find(x=>x.generator===String(id));if(j&&!terminal.has(j.status)){if(n.state==='running')j.status='running';if(n.max>0&&n.value>0)j.progress=n.value/n.max;}}}
if(name==='progress'){const j=jobs.find(x=>x.generator===String(d.node));if(j&&d.max>0){j.progress=d.value/d.max;j.status='running';}}
if(name==='executing'&&d.node){const j=jobs.find(x=>x.generator===String(d.node));if(j)j.status='running';}
if(name==='progress_state'){for(const [id,n] of Object.entries(d.nodes||{})){const j=jobs.find(x=>x.generator===String(id));if(j&&!terminal.has(j.status)&&j.status!=='repairing'){if(n.state==='running')j.status='running';if(n.max>0&&n.value>0)j.progress=n.value/n.max;}}}
if(name==='progress'){const j=jobs.find(x=>x.generator===String(d.node));if(j&&d.max>0&&!terminal.has(j.status)&&j.status!=='repairing'){j.progress=d.value/d.max;j.status='running';}}
if(name==='executing'&&d.node){const j=jobs.find(x=>x.generator===String(d.node));if(j&&!terminal.has(j.status)&&j.status!=='repairing')j.status='running';}
if(name==='executed'){
const job=jobs.find(x=>x.output===String(d.node));if(job&&d.output?.images){const record=d.output.dogma_records?.[0];Object.assign(job,record||{images:d.output.images,status:'completed',finished:Date.now()});this.renderFilters();this.renderGallery();}
}
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_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.stoppedProgress=this.jobProgress(job).percent;job.status=job===failed?'failed':'cancelled';if(job===failed)job.errorVisibleUntil=Date.now()+5000;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.stoppedProgress=this.jobProgress(job).percent;job.status='cancelled';job.finished=Date.now();}
if(name==='execution_success'){this.recover();this.refreshCredits();this.refreshLibrary();}this.save();this.updateCards();
}
async recover(){
@@ -251,7 +356,7 @@ export class PlatformUI {
try{const history=await this.bridge.history();if(this.closed)return;let changed=false;
for(const record of Object.values(history||{})){
const meta=record.prompt?.[3]?.extra_pnginfo?.workflow?.extra?.dogma_api_batch;if(meta?.session!==this.state.session)continue;
for(const saved of meta.jobs){let job=this.state.results.find(x=>x.id===saved.id);if(!job){job=copy(saved);this.state.results.push(job);changed=true;}if(job.imported)continue;job.promptId=record.prompt[1];const ui=record.outputs?.[job.output];if(ui?.images?.length){const result=ui.dogma_records?.[0]||{images:ui.images,status:'completed',finished:Date.now()};if(JSON.stringify(job.images)!==JSON.stringify(result.images))changed=true;Object.assign(job,result);}else if(record.status?.completed&&!terminal.has(job.status)){job.status=record.status.status_str==='success'?'missing':'failed';job.finished=Date.now();job.error='Comfy non ha restituito questo output.';}}
for(const saved of meta.jobs){let job=this.state.results.find(x=>x.id===saved.id);if(!job){job=copy(saved);this.state.results.push(job);changed=true;}if(job.imported)continue;job.promptId=record.prompt[1];const ui=record.outputs?.[job.output];if(ui?.images?.length){const result=ui.dogma_records?.[0]||{images:ui.images,status:'completed',finished:Date.now()};if(JSON.stringify(job.images)!==JSON.stringify(result.images))changed=true;Object.assign(job,result);}else if(record.status?.completed&&!terminal.has(job.status)){job.stoppedProgress=this.jobProgress(job).percent;job.status=record.status.status_str==='success'?'missing':'failed';job.errorVisibleUntil=Date.now()+5000;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;}
+35 -8
View File
@@ -1,21 +1,44 @@
import { icon } from './dogma_api_icons.js?v=1.0.55';
import { icon } from './dogma_api_icons.js?v=1.0.57';
import {savedFilename} from './dogma_api_core.js?v=1.0.60';
export function hoverCompare(host,generated,original){
export async function copyFullImage(url){
if(!navigator.clipboard?.write||!globalThis.ClipboardItem)throw new Error('La copia immagini richiede HTTPS o localhost. Puoi scaricare il file a piena risoluzione.');
const png=(async()=>{const response=await fetch(url);if(!response.ok)throw new Error('Immagine non disponibile.');const blob=await response.blob();if(blob.type==='image/png')return blob;const bitmap=await createImageBitmap(blob),canvas=document.createElement('canvas');canvas.width=bitmap.width;canvas.height=bitmap.height;canvas.getContext('2d').drawImage(bitmap,0,0);bitmap.close();return new Promise((resolve,reject)=>canvas.toBlob(b=>b?resolve(b):reject(new Error('Copia immagine non riuscita.')),'image/png'));})();
await navigator.clipboard.write([new ClipboardItem({'image/png':png})]);
}
function videoComparison(stage,first,second,bridge,dialog,hint){
stage.classList.add('dap-video-compare');const media=[];
for(const [i,item] of [first,second].entries()){
const panel=document.createElement('div');panel.className='dap-video-panel';const label=document.createElement('span');label.textContent=i?'B':'A';const element=document.createElement(item.job.kind==='video'?'video':'img');element.src=bridge.view(item.file);if(element.tagName==='VIDEO'){element.muted=i>0;element.playsInline=true;element.preload='metadata';}panel.append(element,label);stage.append(panel);media.push(element);
}
const videos=media.filter(e=>e.tagName==='VIDEO'),controls=document.createElement('div');let master=videos[0];controls.className='dap-video-sync';
const play=document.createElement('button');play.textContent='Play / Pausa';const seek=document.createElement('input');seek.type='range';seek.min='0';seek.max='0';seek.step='.01';seek.value='0';seek.setAttribute('aria-label','Posizione confronto video');const time=document.createElement('span');
const pause=()=>videos.forEach(v=>v.pause());
const sync=()=>{for(const v of videos)if(v!==master&&Number.isFinite(v.duration)&&Math.abs(v.currentTime-master.currentTime)>.12)v.currentTime=Math.min(master.currentTime,v.duration);};
play.onclick=async()=>{if(!master.paused){pause();return;}if(master.ended)for(const v of videos)v.currentTime=0;sync();try{await Promise.all(videos.filter(v=>!v.ended||v.currentTime===0).map(v=>v.play()));}catch{pause();hint.textContent='Riproduzione non disponibile: controlla i file video.';}};
seek.oninput=()=>{for(const v of videos)if(Number.isFinite(v.duration))v.currentTime=Math.min(Number(seek.value),v.duration);};
const update=()=>{const max=Math.max(0,...videos.map(v=>Number.isFinite(v.duration)?v.duration:0));seek.max=String(max);seek.value=String(master.currentTime);time.textContent=`${master.currentTime.toFixed(1)}s / ${max.toFixed(1)}s`;sync();};
for(const v of videos){v.addEventListener('loadedmetadata',()=>{master=videos.reduce((a,b)=>(b.duration||0)>(a.duration||0)?b:a);update();});v.addEventListener('timeupdate',()=>{if(v===master)update();});v.addEventListener('ended',()=>{if(v===master)pause();});}controls.append(play,seek,time);stage.after(controls);hint.textContent='A / B · Riproduzione e posizione sincronizzate';
dialog.addEventListener('close',()=>{pause();for(const v of videos){v.removeAttribute('src');v.load();}},{once:true});
}
export function hoverCompare(host,generated,original,enabled=()=>true){
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'));
const move=e=>{const active=enabled();host.classList.toggle('comparing',active);if(!active)return;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',move);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 title=savedFilename(job,index)||job.label||'DOGMA';
const dialog=ui.modalBox(title,'dap-viewer-modal',!!item.preview),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;};
@@ -27,16 +50,20 @@ export function openViewer(ui,item,other=null){
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);
if(job.id){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.prompt)toolbar.append(button('prompt','Leggi e copia prompt',()=>ui.showPrompt(job)));
if(job.kind!=='video'){const copy=button('copy','Copia immagine a piena risoluzione',async()=>{try{await copyFullImage(bridge.view(file));hint.textContent='Immagine copiata alla risoluzione originale.';}catch(e){hint.textContent=e.message;}});toolbar.append(copy);}
if(other&&(job.kind==='video'||other.job.kind==='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();videoComparison(stage,item,other,bridge,dialog,hint);return;}
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);
toolbar.append(ui.compareToggle(!!original));
const compare=hoverCompare(surface,bridge.view(file),original,()=>ui.state.compareEnabled!==false);
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.';};