Compare commits

...
12 Commits
50 changed files with 3604 additions and 61 deletions
+10
View File
@@ -0,0 +1,10 @@
DOGMA Nodes 1.0.50
- One workflow and one node package for desktop/local and remote/cloud ComfyUI. No SimplePod-only fork, model sampling changes, model downloads or new runtime dependencies.
- Fix the local-only 403 on restitch preview, detail, job polling and apply. The loaded H3 catalog supplies an ephemeral browser proof, sent only in a custom header. Require it with JSON for state changes, reject cross-site/opaque requests, do not trust forwarded headers for privileges, do not put the proof into URLs or saved workflows. The catalog response is non-cacheable. This complements existing Comfy/proxy authentication; it is not a new public-server authentication system.
- Distinguish localhost desktop requests from public Host/proxy requests at runtime. Native Windows folder opening remains localhost-only. On remote or Linux servers the same Open saved folder button shows an internal browser rooted in the actual Comfy output directory with downloadable media files.
- Preserve existing desktop folder selection including drives and paths outside Comfy output. Remote folder selection starts in the server output directory, remembers selections within it and allows subfolders. Remote copies are bounded to output and cannot navigate through symlinks outside it. Sessions and other non-media files are not listed in the media browser.
- When importing desktop settings on a POSIX server, replace Windows output paths with the actual server output and let final-specific paths inherit it. Do not alter normal local paths or require a separate JSON. Existing sessions, saved videos and current workflow can continue after node update and page reload.
- Missing mask dependency now names the Manager package MaskVidExperiments as well as MVEx_MaskToLatentSpace. Respect HTML hidden controls in action styles, including view-only folder panels.
Validation: local and proxy/remote tests against production route registration and actual 97-frame CPU restitch, including preview/poll/apply, final copy, output-boundary rejection, stale/missing proof, request origin checks and local Windows OS-call dispatch (mocked to avoid opening Explorer). The same frontend was exercised in an isolated browser with a rewritten internal Host and non-loopback client address, then in localhost mode: server folder selection and media listing, all seven restitch previews without 403, Windows path adaptation and retained local drives/folder navigation. No real SimplePod instance or live local installation was modified during verification. No new H3 sampling was required or run.
+10
View File
@@ -0,0 +1,10 @@
DOGMA Nodes 1.0.51
- Integrate HDR finishing into the existing comfyui-dogma-nodes Manager package. No separate node pack, installer, Torch/CUDA update or model download.
- Add DOGMAHDRColorChunkedV1 for per-frame SDR-to-ACEScct conversion using the native Comfy colour transform and fp32 intermediates.
- Add DOGMAHDRSaveStreamingV1: consume raw decoded ACEScct one frame at a time, restore source proportions in UHD, save ACEScg RGB HALF EXRs with ZIP16 and AP1/D60 chromaticities, and optionally write ProRes 4444 HLG with original PCM24 audio. Preserve original frame count and rational frame rate; omit only LTX temporal padding. Return paths rather than additional complete IMAGE batches. Unique output folders, completion manifest and atomic final MOV name.
- Add DOGMAHDRCheckpointV1 before decode; its lazy recovery branch loads a saved latent without running the samplers again. Recovery requires the same source video and compatible VAE.
- Preserve previous node IDs, modules, frontend and H3 workflows. HDR registration is optional on older Comfy versions: failure to import the new HDR module does not remove existing DOGMA nodes. HDR requires ComfyUI >=0.45.0; no new declared runtime dependency.
- Updated HDR workflow keeps the existing BF16 model, HDR LoRA and scene embedding, fp32 VAE, tile settings and two-stage 8+3 sampling.
Validation: graph consistency, native colour equivalence, actual HALF EXR round-trip including negative/extended values, ACES metadata, actual ProRes HLG and PCM24 audio, exact rational timestamps, trim/padding, latent save/recovery, unique folders and output boundaries. The unchanged finishing function was additionally exercised on a synthetic shared-frame UHD 144-frame/6-second export, with 0.43 GiB additional peak process RAM. This measurement isolates finishing and is not a full LTX inference/decode or a SimplePod run. Live Comfy installations were not modified.
+12
View File
@@ -0,0 +1,12 @@
DOGMA Nodes 1.0.52
- Clear HDR V4 front panel: choose final resolution, input colour encoding, linear EXR master primaries, optional MOV transfer, seed and output prefix in one visible settings node.
- Original resolution is a genuine single-stage native-resolution path: canvas follows source dimensions aligned to LTX's grid, final export restores the exact original dimensions. A lazy selector skips the latent upsampler, stage-2 guide/sampler and associated model branches. It does not run a 4K render then downscale the result.
- Optional 4K retains the existing full-HD stage 1, latent x2 upscale, three-step stage 2 and UHD fitting/letterboxing.
- Input choices distinguish SDR sRGB, Rec.709 gamma 2.4, linear Rec.709/ACEScg, ACEScct, Rec.709-primaries LogC3, BT.2020 HLG/PQ. Internal model encoding is always ACEScct and is no longer presented as an output colour selector.
- EXR master: linear ACEScg AP1/D60 (default) or linear Rec.709 D65, always RGB HALF with matching chromaticities and ZIP16. MOV: BT.2020 HLG (default), BT.2020 PQ, or disabled; both movie transfers use ProRes 4444 with 10-bit 4:4:4 encoder input and original PCM24 audio.
- Keep generation and delivery producers separate inside the visible settings group. Changing only EXR primaries, MOV transfer or output prefix reuses the model branch through Comfy's normal cache when available, rather than invalidating it through a combined settings object. The summary uses the actual delivery choices.
- Existing 1.0.51 node IDs remain available. Their export helper retains the prior default resolution, colour, filenames and signature; new keyword-only colour/delivery controls are optional. No changes to H3 workflows, Torch/CUDA, model files, or declared runtime dependencies.
- Same Manager package and JSON for Windows and Linux. No separate node pack or one-off installer. Automatic pre-decode checkpoint is retained inside the processing group; no manual resume path appears in the main panel.
Validation uses native Comfy schemas/loader, complete previous package registration, both lazy-resolution branches, graph endpoints and the backend canvas/guide wiring, original/4K geometry, actual HALF EXR colour/metadata and HLG/PQ MOV headers/timestamps/audio. Model inference on a remote pod is not part of the local verification.
+10
View File
@@ -0,0 +1,10 @@
# DOGMA Nodes 1.0.54 / API Platform V2
- Native asynchronous API branches in one batch: Quantity is parallel repeats with distinct seeds; no Variant control.
- Native Seedance reference/edit/extend and first/last-frame video workflows.
- Shared native Comfy account balance, credit formatting and node price expressions.
- Exact geometry SVG icons, independent vertical scrolling and wrapping reference tiles.
- Reference paint/crop/flip/invert/resize/grow/blur/hole filling and optional native SAM3 prompt masks.
- Workspace selection, filename/date/project/scene, output sidecars and project library filters.
- rgthree-style generated/original hover comparison, shared-transform pan/zoom viewer, click-outside close and reveal output in Explorer.
- Preserve previous DOGMA IDs and original source graphs. No new Python dependencies.
+3
View File
@@ -0,0 +1,3 @@
# DOGMA 1.0.55 / API Platform V3
Immediate UI shell; one-node workflow; native model dropdowns and sorted resolutions; separate video reference and first/last modes; input-only image references; fixed nested reference preview URL; in-browser folder selection and reveal; server-enforced project/scene hierarchy; Stop; progress/estimated time; luminous trail; original A/B geometry; collapsible filename controls. Preset and Custom dimensions retain native behavior.
+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.
+109
View File
@@ -147,3 +147,112 @@ comfy node install comfyui-dogma-nodes
## Notes
The nodes use only PyTorch and ComfyUI's built-in sampler APIs. No extra Python dependencies are required.
## HDR finishing (DOGMA Nodes 1.0.51)
The HDR master workflow uses the same DOGMA Nodes Manager package on Windows and Linux.
`DOGMAHDRColorChunkedV1`, `DOGMAHDRCheckpointV1`, and `DOGMAHDRSaveStreamingV1`
require ComfyUI 0.45.0 or later. Update the existing package; no separate HDR pack
or installer is required. Existing H3 workflows and node identifiers are unchanged.
The master is a 3840x2160 ACEScg RGB HALF EXR sequence (ZIP lossless, AP1/D60).
The optional MOV is ProRes 4444 HLG / BT.2020 with 10-bit 4:4:4 encoder input
and original PCM24 audio; the EXR sequence is the 16-bit floating-point master.
Finishing is sequential per frame, but native VAE decode still returns a complete batch.
Output is under the actual Comfy output folder in `DOGMA_HDR_4K/master_XXXXX/`.
The checkpoint is saved before decode in `DOGMA_HDR_4K/checkpoints/`.
To recover an interrupted export, keep the same source loaded and enter the saved
`.latent` path (relative to Comfy output) in `resume_from`; leave it empty for a new generation.
Do not use `--fp16-intermediates` for the HDR master path.
## HDR controls (DOGMA Nodes 1.0.52 / workflow V4)
Choose everything in the main settings node: final resolution, source colour,
EXR master colour, optional MOV transfer, seed, output directory/prefix.
The model's internal ACEScct conversion is automatic and is separate from the
linear ACEScg/Rec.709 EXR output and BT.2020 HLG/PQ MOV delivery.
Original resolution means native source canvas (aligned internally to LTX),
single-stage eight-step HDR generation and exact original output dimensions.
The latent upsampler and second stage are skipped through a lazy selector.
4K retains the official eight-plus-three two-stage path and UHD final geometry.
Source transfer must match the source's export; sRGB and Rec.709 gamma 2.4 are
different choices. EXRs remain linear 16-bit float; selecting a MOV transfer
does not change the EXR master or the model's working encoding.
The single visible settings group contains independent generation and delivery
producers. Delivery-only changes reuse the model branch while Comfy's relevant
cache is available; this is not persistent recovery across server restarts.
## API Platform V2 / 1.0.54
Open DOGMA_API_PLATFORM_V2.json and press APRI DOGMA / API PLATFORM.
Quantity creates independent native asynchronous partner-node branches inside
one prompt, with a distinct seed per request. Provider limits still apply.
The original graphs are retained but inactive; use Run in the DOGMA panel.
Includes image/video references, per-reference preparation, Seedance video,
project library, workspace copies, Comfy credits/pricing and zoom comparison.
Existing DOGMA and H3 workflows keep their identifiers.
## API Platform V3 / 1.0.55
Open DOGMA_API_PLATFORM_V3.json: one launcher node. The panel appears before asynchronous initialization. Folder navigation stays in the browser. Stop cancels DOGMA jobs; provider billing for already completed work still applies. Remaining time is an estimate from completed jobs when available.
## 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.
+61
View File
@@ -194,3 +194,64 @@ try:
del _H3_134, _H3_134_NAMES
except Exception as _h3_134_error:
print("[DOGMA H3 Director V2] Unavailable; existing nodes preserved:", _h3_134_error)
# Optional HDR finishing. Older Comfy versions retain all previous DOGMA nodes.
try:
from .dogma_hdr_streaming import NODE_CLASS_MAPPINGS as _HDR151, NODE_DISPLAY_NAME_MAPPINGS as _HDR151_NAMES
if set(_HDR151).intersection(NODE_CLASS_MAPPINGS):
raise RuntimeError("DOGMA HDR: node ID collision")
NODE_CLASS_MAPPINGS.update(_HDR151)
NODE_DISPLAY_NAME_MAPPINGS.update(_HDR151_NAMES)
del _HDR151, _HDR151_NAMES
except Exception as _hdr151_error:
print("[DOGMA HDR] HDR nodes unavailable (requires ComfyUI >= 0.45.0); previous DOGMA nodes preserved:", _hdr151_error)
# Explicit HDR source/master/delivery controls, additive to the 1.0.51 nodes.
try:
from .dogma_hdr_controls import NODE_CLASS_MAPPINGS as _HDR152, NODE_DISPLAY_NAME_MAPPINGS as _HDR152_NAMES
if set(_HDR152).intersection(NODE_CLASS_MAPPINGS):
raise RuntimeError("DOGMA HDR controls: node ID collision")
NODE_CLASS_MAPPINGS.update(_HDR152)
NODE_DISPLAY_NAME_MAPPINGS.update(_HDR152_NAMES)
del _HDR152, _HDR152_NAMES
except Exception as _hdr152_error:
print("[DOGMA HDR controls] Unavailable; existing DOGMA nodes preserved:", _hdr152_error)
# API Platform: additive launcher; all existing node identifiers remain valid.
try:
from .dogma_api_platform import NODE_CLASS_MAPPINGS as _API153, NODE_DISPLAY_NAME_MAPPINGS as _API153_NAMES
if set(_API153).intersection(NODE_CLASS_MAPPINGS):
raise RuntimeError("DOGMA API Platform: node ID collision")
NODE_CLASS_MAPPINGS.update(_API153)
NODE_DISPLAY_NAME_MAPPINGS.update(_API153_NAMES)
del _API153, _API153_NAMES
except Exception as _api153_error:
print("[DOGMA API Platform] Launcher unavailable; previous DOGMA nodes preserved:", _api153_error)
# API Platform V2: reference preparation, project library and native video output.
try:
from .dogma_api_platform_v2 import NODE_CLASS_MAPPINGS as _APIV2, NODE_DISPLAY_NAME_MAPPINGS as _APIV2_NAMES, register_routes as _APIV2_ROUTES
if set(_APIV2).intersection(NODE_CLASS_MAPPINGS):
raise RuntimeError("DOGMA API V2: node ID collision")
_APIV2_ROUTES()
NODE_CLASS_MAPPINGS.update(_APIV2)
NODE_DISPLAY_NAME_MAPPINGS.update(_APIV2_NAMES)
del _APIV2, _APIV2_NAMES, _APIV2_ROUTES
except Exception as _apiv2_error:
print("[DOGMA API V2] Unavailable; previous DOGMA nodes preserved:", _apiv2_error)
# 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)
+20
View File
@@ -0,0 +1,20 @@
"""DOGMA API Platform: additive, frontend-only launcher for native partner nodes."""
class DOGMAAPIPlatformV1:
@classmethod
def INPUT_TYPES(cls):
return {"required": {"config": ("STRING", {"default": "{}", "multiline": True})}}
RETURN_TYPES = ()
OUTPUT_NODE = True
FUNCTION = "settings"
CATEGORY = "DOGMA/API Platform"
DESCRIPTION = "Open DOGMA API Platform. Generation uses the existing Comfy partner API nodes."
def settings(self, config):
return {"ui": {"text": ["Apri DOGMA / API Platform e usa Run nel pannello."]}, "result": ()}
NODE_CLASS_MAPPINGS = {"DOGMAAPIPlatformV1": DOGMAAPIPlatformV1}
NODE_DISPLAY_NAME_MAPPINGS = {"DOGMAAPIPlatformV1": "DOGMA / API Platform"}
+486
View File
@@ -0,0 +1,486 @@
"""Reference preparation, project output records and local workspace operations.
Generation remains in native partner API nodes, in independent async branches.
"""
import asyncio
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import threading
import time
import uuid
_LOCK = threading.RLock()
_WORKSPACES = set()
_FRONTEND_CACHE = {}
def _output():
import folder_paths
return Path(folder_paths.get_output_directory()).resolve()
def _library():
path = _output() / 'DOGMA' / 'API' / '.library'
path.mkdir(parents=True, exist_ok=True)
return path
def _clean(value):
return re.sub(r'[^\w.-]+', '_', str(value or '').strip(), flags=re.UNICODE).strip('.')[:100]
def _record(metadata, files, kind):
data = json.loads(metadata)
identifier = str(data.get('id', ''))
if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}', identifier):
raise ValueError('Identificatore output non valido.')
data.update(kind=kind, images=files, status='completed', finished=int(time.time()*1000))
root = _output()
exported = []
warning = ''
workspace = Path(data['workspace']).expanduser().resolve() if data.get('workspace') else None
# Only a directory selected through this browser session may be outside output.
if workspace and not (workspace.is_relative_to(root) or str(workspace) in _WORKSPACES):
warning = 'Copia nella cartella di lavoro non eseguita: riseleziona la cartella. Il file è salvato in Comfy output.'
workspace = None
if workspace:
try:
target = workspace
for field in ('project', 'scene'):
if _clean(data.get(field)):target /= _clean(data[field])
target.mkdir(parents=True, exist_ok=True)
for file in files:
source = (root / file.get('subfolder', '') / file['filename']).resolve()
if not source.is_relative_to(root):raise ValueError('Output non valido.')
destination = target / source.name
if destination != source:
# Job IDs prevent a different project/run from replacing a file.
if destination.exists():destination = target / (source.stem+'_'+identifier[:8]+source.suffix)
shutil.copy2(source, destination)
exported.append(str(destination))
sidecar = target / (identifier+'.dogma.json')
sidecar.write_text(json.dumps({**data, 'exported': exported, 'dogma_schema':3, 'workspace_relative':target.relative_to(workspace).as_posix()}, ensure_ascii=False, indent=2), encoding='utf8')
except (OSError, ValueError) as exc:
warning = 'File salvato in Comfy; copia nella cartella di lavoro non riuscita: '+str(exc)
if not workspace:
for file in files:
target=root/file.get('subfolder','')
(target/(identifier+'.dogma.json')).write_text(json.dumps({**data,'dogma_schema':3},ensure_ascii=False,indent=2),encoding='utf8')
data['exported'] = exported
if warning:data['warning'] = warning
path = _library() / (identifier+'.json')
temporary = path.with_suffix('.tmp')
with _LOCK:
temporary.write_text(json.dumps(data, ensure_ascii=False), encoding='utf8')
temporary.replace(path)
return data
def _import_workspace(root):
"""Portable sidecars travel with the output; no inference from filename tags."""
root=Path(root).resolve();records=[];seen=set()
from itertools import chain
legacy=(p for directory in root.rglob('.library') if directory.is_dir() for p in directory.glob('*.json'))
for path in chain(root.rglob('*.dogma.json'),legacy):
if len(records)>=5000:break
if not path.resolve().is_relative_to(root):continue
try:
data=json.loads(path.read_text('utf8'));identifier=str(data.get('id',''))
if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}',identifier):continue
if identifier in seen:continue
files=[];exported=[]
for index,original in enumerate(data.get('images',[])):
copies=data.get('exported',[])
name=Path(copies[index].replace('\\','/')).name if index<len(copies) else Path(original.get('filename','')).name
if path.parent.name=='.library':
subfolder=str(original.get('subfolder','')).replace('\\','/')
relative=subfolder.removeprefix('DOGMA/API').lstrip('/')
candidate=(path.parent.parent/relative/name).resolve()
else:candidate=(path.parent/name).resolve()
if not candidate.is_relative_to(root) or not candidate.is_file():continue
files.append({'filename':name,'workspace':str(root),'relative':candidate.relative_to(root).as_posix(),'type':'workspace',**({'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)
(_library()/(identifier+'.json')).write_text(json.dumps(data,ensure_ascii=False),encoding='utf8')
records.append(data);seen.add(identifier)
except (ValueError,OSError,KeyError,TypeError):continue
return records
_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
from PIL import Image, ImageOps, ImageFilter, ImageColor
from scipy import ndimage
cfg = json.loads(settings) if isinstance(settings, str) else settings
image = image.convert('RGB')
mask = mask.convert('L').resize(image.size, Image.Resampling.NEAREST)
if cfg.get('flip'):
image = ImageOps.mirror(image);mask = ImageOps.mirror(mask)
if cfg.get('resizeMpx'):
megapixels = max(.01, min(64, float(cfg.get('megapixels', 1))))
scale = (megapixels*1e6/(image.width*image.height))**.5
size = (max(1, round(image.width*scale)), max(1, round(image.height*scale)))
image = image.resize(size, Image.Resampling.LANCZOS);mask = mask.resize(size, Image.Resampling.NEAREST)
if cfg.get('invert'):mask = ImageOps.invert(mask)
if cfg.get('fillHoles'):
arr = np.asarray(mask);filled = ndimage.binary_fill_holes(arr>127)
mask = Image.fromarray(np.maximum(arr, filled.astype(np.uint8)*255))
grow = max(-512, min(512, int(cfg.get('expand', 0))))
if grow:
array = np.asarray(mask)
fun = ndimage.maximum_filter if grow>0 else ndimage.minimum_filter
mask = Image.fromarray(fun(array, size=abs(grow)*2+1))
blur = max(0, min(128, float(cfg.get('blur', 0))))
if blur:mask = mask.filter(ImageFilter.GaussianBlur(blur))
crop_box = None
if cfg.get('crop'):
rect = cfg.get('cropRect')
if rect:
x,y,w,h = [max(0,min(1,float(n))) for n in rect]
if cfg.get('flip'):x=max(0,1-x-w)
crop_box = (round(x*image.width),round(y*image.height),round(min(1,x+w)*image.width),round(min(1,y+h)*image.height))
else:crop_box = mask.point(lambda v:255 if v>25 else 0).getbbox()
if not crop_box or crop_box[2]<=crop_box[0] or crop_box[3]<=crop_box[1]:
raise ValueError('Crop vuoto: seleziona un’area o dipingi una maschera.')
if cfg.get('mask'):
background = Image.new('RGB', image.size, ImageColor.getrgb(cfg.get('background') or '#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)
if cfg.get('crop') and width>0 and height>0:
if width>16384 or height>16384:raise ValueError('Dimensioni crop troppo grandi.')
image=image.resize((width,height),Image.Resampling.LANCZOS);mask=mask.resize((width,height),Image.Resampling.NEAREST)
return image,mask
class DOGMAAPIReferenceV2:
@classmethod
def INPUT_TYPES(cls):
return {'required': {'image':('IMAGE',), 'mask':('MASK',), 'settings':('STRING',{'default':'{}'})}}
RETURN_TYPES=('IMAGE',)
FUNCTION='prepare'
CATEGORY='DOGMA/API Platform'
def prepare(self,image,mask,settings):
import numpy as np
import torch
from PIL import Image
results=[]
for index in range(image.shape[0]):
pil=Image.fromarray((image[index].detach().cpu().numpy().clip(0,1)*255).astype(np.uint8))
alpha=Image.fromarray((mask[min(index,len(mask)-1)].detach().cpu().numpy().clip(0,1)*255).astype(np.uint8))
processed,_=process_reference(pil,alpha,settings)
results.append(torch.from_numpy(np.asarray(processed).copy()).float()/255)
return (torch.stack(results),)
def _save_prefix(data):
basename=Path(str(data.get('prefix') or 'DOGMA').replace('\\','/')).name
return '/'.join(['DOGMA','API',*[_clean(data.get(k)) for k in ('project','scene') if _clean(data.get(k))],basename])
class DOGMAAPIImageOutputV2:
@classmethod
def INPUT_TYPES(cls):
return {'required':{'images':('IMAGE',),'metadata':('STRING',)},'hidden':{'prompt':'PROMPT','extra_pnginfo':'EXTRA_PNGINFO'}}
RETURN_TYPES=()
OUTPUT_NODE=True
FUNCTION='save'
CATEGORY='DOGMA/API Platform'
def save(self,images,metadata,prompt=None,extra_pnginfo=None):
from nodes import SaveImage
data=json.loads(metadata)
# Same output and metadata behavior as the native SaveImage node.
result=SaveImage().save_images(images,_save_prefix(data),prompt,extra_pnginfo)
record=_record(metadata,result['ui']['images'],'image')
return {'ui':{**result['ui'],'dogma_records':[record]},'result':()}
class DOGMAAPIVideoOutputV2:
@classmethod
def INPUT_TYPES(cls):
return {'required':{'video':('VIDEO',),'metadata':('STRING',)},'hidden':{'prompt':'PROMPT','extra_pnginfo':'EXTRA_PNGINFO'}}
RETURN_TYPES=()
OUTPUT_NODE=True
FUNCTION='save'
CATEGORY='DOGMA/API Platform'
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()
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}
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'}]
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':()}
def frontend_modules(web_root):
"""Discover the installed frontend's own shared billing/pricing modules."""
cache_key=str(web_root)
if cache_key in _FRONTEND_CACHE:return _FRONTEND_CACHE[cache_key]
assets=Path(web_root)/'assets';result={}
for path in assets.glob('*.js'):
if path.name.startswith('useBillingContext-'):
text=path.read_text('utf8');exports=text[text.rfind('export{'):]
match=re.search(r'useNodePricing as (\w+)',exports)
shared=re.search(r'(\w+)=\w+\(useBillingContextInternal\)',text)
alias=re.search(r'\b'+re.escape(shared[1])+r' as (\w+)',exports) if shared else None
if match and alias:result['billing']={'file':path.name,'context':alias[1],'pricing':match[1]}
elif path.name.startswith('creditsUtil-'):
text=path.read_text('utf8');match=re.search(r'formatCreditsFromCents as (\w+)',text)
if match:result['credits']={'file':path.name,'format':match[1]}
_FRONTEND_CACHE[cache_key]=result
return result
def register_routes():
from aiohttp import web
from server import PromptServer
from .dogma_h3_access import H3Access
import folder_paths
access=H3Access();routes=PromptServer.instance.routes
@routes.get('/dogma/api/v2/catalog')
async def catalog(request):
capabilities=access.catalog(request,_output())
return web.json_response({'access':{**capabilities,'output_root':str(_output()/'DOGMA'/'API')},'frontend':frontend_modules(PromptServer.instance.web_root),'version':'1.0.56'})
@routes.post('/dogma/api/v2/workspace')
async def workspace(request):
access.browser(request);data=await request.json()
try:
path=access.output_path(request,data.get('path'),_output())
if not path.is_dir():raise ValueError('Scegli una cartella esistente.')
_WORKSPACES.add(str(path))
records=await asyncio.to_thread(_import_workspace,path)
return web.json_response({'path':str(path),'records':records})
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.post('/dogma/api/v2/choose-folder')
async def choose(request):
access.browser(request)
return web.json_response({'browse':True})
@routes.get('/dogma/api/v2/folders')
async def folders(request):
access.browser(request)
try:
path=access.output_path(request,request.query.get('path') or str(_library().parent),_output())
if not path.is_dir():raise ValueError('Cartella inesistente.')
local=access.is_local(request)
def scan():
dirs=[];files=[]
for p in path.iterdir():
if p.name.startswith('.'):continue
try:
if not local and not p.resolve().is_relative_to(_output()):continue
if p.is_dir():dirs.append({'name':p.name,'path':str(p.resolve())})
elif p.is_file():files.append({'name':p.name})
except OSError:continue
parent=str(path.parent) if path.parent!=path and (local or path.parent.is_relative_to(_output())) else None
roots=[]
if local and os.name=='nt':
roots=[{'name':letter+':','path':letter+':/'} for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if Path(letter+':/').is_dir()]
return {'path':str(path),'parent':parent,'roots':roots,'directories':sorted(dirs,key=lambda d:d['name'].lower()),'files':sorted(files,key=lambda d:d['name'].lower())[:5000]}
return web.json_response(await asyncio.to_thread(scan))
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.post('/dogma/api/v2/mkdir')
async def mkdir(request):
access.browser(request);data=await request.json()
try:
parent=access.output_path(request,data.get('path'),_output())
name=str(data.get('name','')).strip()
if not name or name in ('.','..') or re.search(r'[<>:"/\\|?*]',name) or name.endswith(('.', ' ')):raise ValueError('Nome cartella non valido.')
target=parent/name
if not parent.is_dir():raise ValueError('Cartella superiore inesistente.')
target.mkdir(exist_ok=False)
return web.json_response({'path':str(target.resolve())})
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.get('/dogma/api/v2/workspace-media')
async def workspace_media(request):
access.fetch_site(request)
try:
root=access.output_path(request,request.query.get('workspace'),_output())
if str(root) not in _WORKSPACES:raise ValueError('Riseleziona la cartella di lavoro.')
relative=request.query.get('relative','');file=(root/relative).resolve()
if not file.is_relative_to(root) or file.suffix.lower() not in ('.png','.jpg','.jpeg','.webp','.mp4','.webm','.mov'):raise ValueError('File non valido.')
if not file.is_file():raise ValueError('File non disponibile.')
return web.FileResponse(file)
except (ValueError,OSError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.get('/dogma/api/v2/library')
async def library(request):
access.browser(request)
def read():
records=[]
for path in sorted(_library().glob('*.json'),key=lambda p:p.stat().st_mtime,reverse=True)[:5000]:
try:records.append(json.loads(path.read_text('utf8')))
except (ValueError,OSError):continue
return records
return web.json_response({'records':await asyncio.to_thread(read)})
@routes.post('/dogma/api/v2/open-output')
async def open_output(request):
access.browser(request)
data=await request.json();identifier=str(data.get('id',''))
if not re.fullmatch(r'[A-Za-z0-9_-]{1,100}',identifier):raise web.HTTPBadRequest(text='Output non valido.')
try:
record=json.loads((_library()/(identifier+'.json')).read_text('utf8'))
index=max(0,int(data.get('index',0)));copies=record.get('exported',[])
file=Path(copies[index]) if index<len(copies) else _output()/record['images'][index].get('subfolder','')/record['images'][index]['filename']
if not file.is_file():raise ValueError('Il file è stato spostato o rimosso.')
access.output_path(request,str(file.parent),_output())
return web.json_response({'path':str(file.parent),'filename':file.name})
except (ValueError,OSError,IndexError,KeyError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.post('/dogma/api/v2/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()
from PIL import Image,ImageOps
def prepare():
source=Path(folder_paths.get_annotated_filepath(data['file'])).resolve()
if not source.is_relative_to(Path(folder_paths.get_input_directory()).resolve()):raise ValueError('Reference esterna a input.')
rgba=ImageOps.exif_transpose(Image.open(source)).convert('RGBA');mask=ImageOps.invert(rgba.getchannel('A'))
settings=data['settings']
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)
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,RuntimeError,ImportError) as exc:raise web.HTTPBadRequest(text=str(exc))
NODE_CLASS_MAPPINGS={'DOGMAAPIReferenceV2':DOGMAAPIReferenceV2,'DOGMAAPIImageOutputV2':DOGMAAPIImageOutputV2,'DOGMAAPIVideoOutputV2':DOGMAAPIVideoOutputV2}
NODE_DISPLAY_NAME_MAPPINGS={'DOGMAAPIReferenceV2':'DOGMA / Reference preparation','DOGMAAPIImageOutputV2':'DOGMA / Image output','DOGMAAPIVideoOutputV2':'DOGMA / Video output'}
+4 -3
View File
@@ -13,9 +13,10 @@ def versioned_urls(urls, extension_dirs, web_directory):
result = []
for url in urls:
parts = urlsplit(url)
# This package has one entry module. Do not rewrite third-party URLs.
if any(parts.path == prefix + "dogma_categories.js" for prefix in prefixes):
digest = hashlib.sha256((root / "dogma_categories.js").read_bytes()).hexdigest()[:20]
# Version only this package's own entry modules. Do not rewrite third-party URLs.
entry = parts.path.rsplit("/", 1)[-1]
if entry in ("dogma_categories.js", "dogma_api_platform.js") and any(parts.path == prefix + entry for prefix in prefixes):
digest = hashlib.sha256((root / entry).read_bytes()).hexdigest()[:20]
query = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True)
if k != "dogma_build"]
query.append(("dogma_build", digest))
+61
View File
@@ -0,0 +1,61 @@
"""Browser request proof for H3 data operations; OS actions remain local-only.
The token complements the deployment's existing Comfy/proxy authentication.
It is not a replacement for authentication on a publicly exposed Comfy server.
Forwarded headers never grant access or widen the filesystem scope.
"""
import secrets
from pathlib import Path
from urllib.parse import urlsplit
from aiohttp import web
class H3Access:
def __init__(self):self.token=secrets.token_urlsafe(32)
@staticmethod
def fetch_site(request):
site=request.headers.get('Sec-Fetch-Site','').lower()
if site and site not in ('same-origin','none'):
raise web.HTTPForbidden(text='Richiesta da un altro sito non consentita.')
origin=request.headers.get('Origin')
if origin:
try:valid=origin!='null' and urlsplit(origin).scheme in ('http','https') and bool(urlsplit(origin).netloc)
except ValueError:valid=False
if not valid:raise web.HTTPForbidden(text='Origine non valida.')
def is_local(self,request):
if request.remote not in ('127.0.0.1','::1'):return False
try:
host=urlsplit('//'+request.host)
if host.hostname not in ('127.0.0.1','::1','localhost'):return False
origin=request.headers.get('Origin')
if origin and urlsplit(origin).netloc.lower()!=host.netloc.lower():return False
self.fetch_site(request)
except (ValueError,web.HTTPForbidden):return False
return True
def local(self,request):
if not self.is_local(request):
raise web.HTTPForbidden(text='Questa azione del sistema è disponibile solo da localhost sul computer Comfy.')
def browser(self,request):
self.fetch_site(request)
token=request.headers.get('X-Dogma-Access','')
if not token or not secrets.compare_digest(token.encode('utf8'),self.token.encode('ascii')):
raise web.HTTPForbidden(text='Accesso DOGMA scaduto o pannello precedente. Ricarica la pagina e riapri H3 Director.')
if request.method=='POST' and request.content_type!='application/json':
raise web.HTTPUnsupportedMediaType(text='Richiesta JSON necessaria.')
def catalog(self,request,output):
self.fetch_site(request)
import os
return {'token':self.token,'local_files':self.is_local(request),
'open_folder':self.is_local(request) and os.name=='nt',
'output_directory':str(Path(output).resolve()),'platform':os.name}
def output_path(self,request,path,root):
root=Path(root).expanduser().resolve()
destination=Path(path).expanduser().resolve() if path else root
if not self.is_local(request) and not destination.is_relative_to(root):
raise ValueError('Da remoto scegli una cartella dentro l’output di Comfy: '+str(root))
return destination
+31 -19
View File
@@ -612,17 +612,13 @@ def register_routes():
from .dogma_h3_video_edit import register_edit_routes
cleanup=register_edit_routes(routes,input_file)
PromptServer.instance.app.on_cleanup.append(cleanup)
def local_request(request):
from urllib.parse import urlparse
if request.remote not in ('127.0.0.1','::1'):
raise web.HTTPForbidden(text='Disponibile solo sul computer Comfy.')
origin=request.headers.get('Origin')
if origin and urlparse(origin).netloc!=request.host:
raise web.HTTPForbidden(text='Origine non valida.')
from .dogma_h3_access import H3Access
access=H3Access()
local_request=access.local
import sys
from .dogma_h3_restitch import register_routes as register_restitch
PromptServer.instance.app.on_cleanup.append(register_restitch(routes,sys.modules[__name__],local_request))
PromptServer.instance.app.on_cleanup.append(register_restitch(routes,sys.modules[__name__],access.browser))
@routes.post('/dogma/h3/v2/open-folder')
async def open_folder(request):
@@ -639,10 +635,12 @@ def register_routes():
@routes.post('/dogma/h3/v2/edit/export-copy')
async def export_edit_copy(request):
local_request(request)
access.browser(request)
import asyncio
data=await request.json()
try:return web.json_response(await asyncio.to_thread(export_saved_edit,data))
try:
data['output_dir']=str(access.output_path(request,data.get('output_dir','').strip(),folder_paths.get_output_directory()))
return web.json_response(await asyncio.to_thread(export_saved_edit,data))
except (ValueError,OSError,KeyError) as exc:raise web.HTTPBadRequest(text=str(exc))
@routes.post('/dogma/h3/v2/choose-folder')
@@ -652,26 +650,39 @@ def register_routes():
@routes.get('/dogma/h3/v2/folders')
async def folders(request):
local_request(request)
access.browser(request)
import asyncio
def browse():
directory=Path(request.query.get('path') or folder_paths.get_output_directory()).expanduser().resolve()
output=Path(folder_paths.get_output_directory()).resolve()
local=access.is_local(request)
directory=access.output_path(request,request.query.get('path'),output)
if not directory.is_dir(): raise ValueError('Cartella inesistente. Inserisci un percorso valido.')
directories=[]
directories=[];files=[]
media={'.mp4','.mov','.webm','.mkv','.png','.jpg','.jpeg','.webp','.gif','.wav','.mp3','.flac'}
with os.scandir(directory) as entries:
for entry in entries:
try:
if entry.is_dir(): directories.append({'name':entry.name,'path':entry.path})
if entry.is_dir() and (local or Path(entry.path).resolve().is_relative_to(output)):
directories.append({'name':entry.name,'path':entry.path})
elif request.query.get('files')=='1' and entry.is_file() and Path(entry.name).suffix.lower() in media:
resolved=Path(entry.path).resolve()
if resolved.is_relative_to(output):
rel=resolved.relative_to(output)
files.append({'name':entry.name,'size':entry.stat().st_size,
'video':{'filename':rel.name,'subfolder':rel.parent.as_posix(),'type':'output'}})
except OSError: continue
if len(directories)>500: break
if len(directories)+len(files)>500: break
directories.sort(key=lambda x:x['name'].casefold())
files.sort(key=lambda x:x['name'].casefold())
drives=[]
if os.name=='nt':
if local and os.name=='nt':
import ctypes
bits=ctypes.windll.kernel32.GetLogicalDrives()
drives=[{'name':chr(65+i)+':','path':chr(65+i)+':/'} for i in range(26) if bits & (1<<i)]
return {'path':str(directory),'parent':str(directory.parent) if directory.parent!=directory else None,
'drives':drives,'directories':directories[:500],'truncated':len(directories)>500}
parent=str(directory.parent) if directory.parent!=directory and (local or directory.parent.is_relative_to(output)) else None
return {'path':str(directory),'parent':parent,'restricted':not local,
'drives':drives,'directories':directories[:500],'files':files[:500],
'truncated':len(directories)+len(files)>500}
try: return web.json_response(await asyncio.to_thread(browse))
except (ValueError,OSError) as exc: raise web.HTTPBadRequest(text=str(exc))
@@ -689,10 +700,11 @@ def register_routes():
async def catalog(request):
import asyncio,time
nonlocal catalog_task,catalog_time
capabilities=access.catalog(request,folder_paths.get_output_directory())
if catalog_task is None or (catalog_task.done() and (catalog_task.exception() is not None or time.monotonic()-catalog_time>30)):
catalog_time=time.monotonic()
catalog_task=asyncio.create_task(asyncio.to_thread(build_catalog))
return web.json_response(await asyncio.shield(catalog_task))
return web.json_response({**await asyncio.shield(catalog_task),'access':capabilities},headers={'Cache-Control':'no-store'})
@routes.get('/dogma/h3/v2/session/{session}')
async def session(request):
+4 -4
View File
@@ -115,7 +115,7 @@ def apply_restitch(core,data):
return current
finally:temp.unlink(missing_ok=True)
def register_routes(routes,core,local_request):
def register_routes(routes,core,authorize_request):
from aiohttp import web
jobs={};slot=asyncio.Semaphore(1)
async def launch(kind,data):
@@ -132,12 +132,12 @@ def register_routes(routes,core,local_request):
except Exception as exc:job.update(status='error',message=str(exc))
job['task']=asyncio.create_task(run());return web.json_response({'id':job['id']})
@routes.post('/dogma/h3/v2/edit/restitch/preview')
async def preview(request):local_request(request);return await launch('preview',await request.json())
async def preview(request):authorize_request(request);return await launch('preview',await request.json())
@routes.post('/dogma/h3/v2/edit/restitch/apply')
async def apply(request):local_request(request);return await launch('apply',await request.json())
async def apply(request):authorize_request(request);return await launch('apply',await request.json())
@routes.get('/dogma/h3/v2/edit/restitch/job/{id}')
async def status(request):
local_request(request);job=jobs.get(request.match_info['id'])
authorize_request(request);job=jobs.get(request.match_info['id'])
if not job:raise web.HTTPNotFound(text='Lavorazione non disponibile.')
return web.json_response({k:v for k,v in job.items() if k!='task'})
async def cleanup(app):await asyncio.gather(*(j['task'] for j in jobs.values()),return_exceptions=True)
+225
View File
@@ -0,0 +1,225 @@
"""Clear HDR controls for the existing DOGMA Nodes package.
The source transfer, internal model working encoding, EXR primaries and MOV
transfer are deliberately separate. The model always receives ACEScct.
"""
from __future__ import annotations
import math
from pathlib import Path
import torch
import folder_paths
import comfy.utils
import nodes
from comfy.cli_args import args
from comfy_api.latest import io, ui
from .dogma_hdr_streaming import convert_frame, export_frames, require_fp32
CONFIG_TYPE = io.Custom("DOGMA_HDR_CONFIG")
ORIGINAL = "Originale - senza upscale"
UHD = "4K UHD - 3840 x 2160"
RESOLUTIONS = [UHD, ORIGINAL]
SOURCE_SPACES = {
"SDR - sRGB": "sRGB",
"SDR - Rec.709 gamma 2.4": "Rec709 gamma24",
"HDR - Rec.2020 HLG": "HDR",
"HDR - Rec.2020 PQ": "HDR PQ",
"Lineare - ACEScg": "linear ACEScg",
"Lineare - Rec.709": "linear",
"Log - ACEScct": "HDR ACEScct",
"Log - LogC3 con primarie Rec.709": "HDR LogC3",
}
EXR_SPACES = {"ACEScg lineare - 16 bit float": "linear ACEScg", "Rec.709 lineare - 16 bit float": "linear"}
MOV_SPACES = {"HLG - Rec.2020 / ProRes 4444": "HDR", "PQ - Rec.2020 / ProRes 4444": "HDR PQ",
"Disattivato - solo EXR": None}
def checked_config(settings):
if not isinstance(settings, dict) or settings.get("version") != 1:
raise ValueError("Impostazioni HDR mancanti: collega il nodo DOGMA Impostazioni HDR.")
for key, options in [("resolution", RESOLUTIONS), ("source", SOURCE_SPACES),
("exr", EXR_SPACES), ("mov", MOV_SPACES)]:
if settings.get(key) not in options:
raise ValueError(f"Impostazione HDR non valida: {key}.")
return settings
class DOGMAHDRSettings(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(node_id="DOGMAHDRSettingsV1", display_name="DOGMA HDR | Impostazioni di generazione",
category="DOGMA/HDR", description="Risoluzione, colore sorgente e seed. I controlli di export restano separati per riutilizzare la cache del modello.",
inputs=[
io.Combo.Input("resolution", display_name="Risoluzione finale", options=RESOLUTIONS, default=UHD,
tooltip="Originale: generazione alle dimensioni del sorgente, senza upsampler e senza stadio 2. 4K: percorso 8+3 con upscale latente e consegna UHD."),
io.Combo.Input("source", display_name="Colore del video sorgente", options=list(SOURCE_SPACES), default=next(iter(SOURCE_SPACES)),
tooltip="Descrive i pixel in ingresso. Scegli in base all'export del sorgente; sRGB e Rec.709 gamma 2.4 hanno curve diverse. Non cambia il formato interno richiesto dalla LoRA."),
io.Int.Input("seed", display_name="Seed", default=42, min=0, max=0xffffffffffffffff, control_after_generate=False),
], outputs=[CONFIG_TYPE.Output("settings"), io.Int.Output("seed")])
@classmethod
def execute(cls, resolution=UHD, source=next(iter(SOURCE_SPACES)), seed=42):
settings=checked_config(dict(version=1,resolution=resolution,source=source,
exr=next(iter(EXR_SPACES)),mov=next(iter(MOV_SPACES)),
seed=int(seed),filename_prefix="DOGMA_HDR/master"))
return io.NodeOutput(settings, int(seed))
class DOGMAHDRDeliverySettings(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(node_id="DOGMAHDRDeliverySettingsV1",display_name="DOGMA HDR | Impostazioni di esportazione",
category="DOGMA/HDR", inputs=[CONFIG_TYPE.Input("settings"),
io.Combo.Input("exr", display_name="Colore del master EXR", options=list(EXR_SPACES), default=next(iter(EXR_SPACES)),
tooltip="EXR sempre RGB 16 bit float, lineare. ACEScg AP1/D60 e il master consigliato per la pipeline ACES."),
io.Combo.Input("mov", display_name="Video MOV aggiuntivo", options=list(MOV_SPACES), default=next(iter(MOV_SPACES)),
tooltip="HLG o PQ in Rec.2020, oppure nessun MOV. Il MOV ProRes usa input encoder 10 bit; il master 16 bit resta l'EXR."),
io.String.Input("filename_prefix", display_name="Cartella / prefisso output", default="DOGMA_HDR/master")],
outputs=[CONFIG_TYPE.Output("settings")])
@classmethod
def execute(cls,settings,exr=next(iter(EXR_SPACES)),mov=next(iter(MOV_SPACES)),filename_prefix="DOGMA_HDR/master"):
value={**checked_config(settings),"exr":exr,"mov":mov,"filename_prefix":filename_prefix}
return io.NodeOutput(checked_config(value))
class DOGMAHDRPrepareSource(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(node_id="DOGMAHDRPrepareSourceV1", display_name="DOGMA HDR | Ingresso automatico ACEScct",
category="DOGMA/HDR", inputs=[io.Image.Input("image"), CONFIG_TYPE.Input("settings")],
outputs=[io.Image.Output()])
@classmethod
def execute(cls, image, settings):
source=SOURCE_SPACES[checked_config(settings)["source"]]
require_fp32()
if source == "HDR ACEScct":
return io.NodeOutput(image.to(device="cpu",dtype=torch.float32))
output=torch.empty(image.shape,device="cpu",dtype=torch.float32)
progress=comfy.utils.ProgressBar(len(image))
with torch.inference_mode():
for i in range(len(image)):
nodes.before_node_execution()
frame=image[i:i+1]
if source == "Rec709 gamma24":
frame=frame.to(device="cpu",dtype=torch.float32).clamp_min(0).pow(2.4)
value=convert_frame(frame,"linear","HDR ACEScct")
else:
value=convert_frame(frame,source,"HDR ACEScct")
output[i:i+1].copy_(value)
progress.update(1)
return io.NodeOutput(output)
def canvas_plan(width, height, planned_width, planned_height, settings):
settings=checked_config(settings)
upscale=settings["resolution"] == UHD
if min(width,height,planned_width,planned_height) < 1:
raise ValueError("Dimensioni sorgente/piano HDR non valide.")
if upscale:
canvas_width,canvas_height=planned_width,planned_height
target_width,target_height=3840,2160
description="Upscale 4K attivo - campionamento 8 + 3"
else:
canvas_width=max(32,32*math.floor(width/32+.5))
canvas_height=max(32,32*math.floor(height/32+.5))
target_width,target_height=width,height
description="Originale - nessun upscale e nessuno stadio 2 - 8 passaggi"
summary=(f"{description}\nSorgente: {width} x {height}\n"
f"Canvas modello: {canvas_width} x {canvas_height}\nUscita: {target_width} x {target_height}\n"
f"Sorgente colore: {settings['source']}\nInterno LTX: ACEScct (automatico)")
return canvas_width,canvas_height,upscale,summary
class DOGMAHDRCanvas(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(node_id="DOGMAHDRCanvasV1",display_name="DOGMA HDR | Piano risoluzione",
category="DOGMA/HDR",inputs=[io.Image.Input("image"),
io.Int.Input("planned_width",force_input=True),io.Int.Input("planned_height",force_input=True),
CONFIG_TYPE.Input("settings")],
outputs=[io.Int.Output("canvas_width"),io.Int.Output("canvas_height"),
io.Boolean.Output("upscale"),io.String.Output("summary")])
@classmethod
def execute(cls,image,planned_width,planned_height,settings):
return io.NodeOutput(*canvas_plan(image.shape[2],image.shape[1],planned_width,planned_height,settings))
class DOGMAHDRResolutionSelect(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(node_id="DOGMAHDRResolutionSelectV1",display_name="DOGMA HDR | Selezione risoluzione automatica",
category="DOGMA/HDR",inputs=[CONFIG_TYPE.Input("settings"),
io.Latent.Input("original",lazy=True),io.Latent.Input("upscaled",lazy=True)],
outputs=[io.Latent.Output()])
@classmethod
def check_lazy_status(cls, settings, original=None, upscaled=None):
branch="upscaled" if checked_config(settings)["resolution"]==UHD else "original"
return [branch] if (upscaled if branch=="upscaled" else original) is None else []
@classmethod
def execute(cls, settings, original=None, upscaled=None):
result=upscaled if checked_config(settings)["resolution"]==UHD else original
if result is None:
raise ValueError("Latente del ramo selezionato non disponibile.")
return io.NodeOutput(result)
class DOGMAHDRSaveConfigured(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(node_id="DOGMAHDRSaveConfiguredV1",display_name="DOGMA HDR | Salva master e video",
category="DOGMA/HDR",is_output_node=True,
inputs=[io.Image.Input("images"),CONFIG_TYPE.Input("settings"),
io.Int.Input("source_width",force_input=True),io.Int.Input("source_height",force_input=True),
io.Int.Input("source_frames",force_input=True),io.Float.Input("fps",force_input=True),
io.Audio.Input("audio",optional=True)],hidden=[io.Hidden.prompt,io.Hidden.extra_pnginfo],
outputs=[io.String.Output("exr_directory"),io.String.Output("mov_path")])
@classmethod
def execute(cls,images,settings,source_width,source_height,source_frames,fps,audio=None):
cfg=checked_config(settings)
target=(3840,2160) if cfg["resolution"]==UHD else (source_width,source_height)
transfer=MOV_SPACES[cfg["mov"]]
metadata={"dogma_hdr_settings":cfg,"model_working_space":"ACEScct"}
if not args.disable_metadata and cls.hidden is not None:
if cls.hidden.extra_pnginfo:metadata.update(cls.hidden.extra_pnginfo)
if cls.hidden.prompt:metadata["prompt"]=cls.hidden.prompt
job,mov=export_frames(images,source_width,source_height,source_frames,fps,
cfg["filename_prefix"],transfer is not None,audio,target_width=target[0],target_height=target[1],
progress=comfy.utils.ProgressBar(source_frames),metadata=metadata,
exr_color_space=EXR_SPACES[cfg["exr"]],mov_color_space=transfer or "HDR",
mov_stem="DOGMA_HDR_PQ" if transfer=="HDR PQ" else "DOGMA_HDR_HLG")
preview=None
if mov:
subfolder=str(job.relative_to(Path(folder_paths.get_output_directory()))).replace('\\','/')
preview=ui.PreviewVideo([ui.SavedResult(mov.name,subfolder,io.FolderType.output)])
return io.NodeOutput(str(job/'EXR'),str(mov) if mov else "",ui=preview)
class DOGMAHDRSummary(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(node_id="DOGMAHDRSummaryV1",display_name="DOGMA HDR | Riepilogo scelte",
category="DOGMA/HDR",inputs=[io.String.Input("generation_summary",force_input=True),CONFIG_TYPE.Input("settings")],
outputs=[io.String.Output("summary")])
@classmethod
def execute(cls,generation_summary,settings):
cfg=checked_config(settings)
return io.NodeOutput(f"{generation_summary}\nMaster EXR: {cfg['exr']}\nMOV: {cfg['mov']}")
NODE_CLASS_MAPPINGS={
"DOGMAHDRSettingsV1":DOGMAHDRSettings,
"DOGMAHDRPrepareSourceV1":DOGMAHDRPrepareSource,
"DOGMAHDRCanvasV1":DOGMAHDRCanvas,
"DOGMAHDRResolutionSelectV1":DOGMAHDRResolutionSelect,
"DOGMAHDRSaveConfiguredV1":DOGMAHDRSaveConfigured,
"DOGMAHDRDeliverySettingsV1":DOGMAHDRDeliverySettings,
"DOGMAHDRSummaryV1":DOGMAHDRSummary,
}
NODE_DISPLAY_NAME_MAPPINGS={key:node.GET_SCHEMA().display_name for key,node in NODE_CLASS_MAPPINGS.items()}
+328
View File
@@ -0,0 +1,328 @@
"""DOGMA Nodes: bounded-working-memory HDR finishing for ComfyUI >= 0.45.0.
No models, dependencies, monkey patches, or changes to ComfyUI are installed.
The native VAE still returns a complete batch; finishing consumes one frame
at a time and returns file paths, never another complete IMAGE batch.
"""
from __future__ import annotations
import json
import logging
import math
import os
from fractions import Fraction
from pathlib import Path
import av
import numpy as np
import torch
import safetensors.torch
import folder_paths
import nodes
import comfy.utils
from comfy.cli_args import args
from comfy_api.latest import io, ui
from comfy_api.latest._input_impl.video_types import (
BT2020_NCL, set_video_color_properties,
)
from comfy_extras import nodes_images as ni
VERSION = "1.0.52"
SPACES = ["sRGB", "HDR", "HDR ACEScct", "HDR LogC3", "HDR PQ", "linear", "linear ACEScg"]
log = logging.getLogger("DOGMA.HDR")
def require_fp32():
if args.fp16_intermediates:
raise ValueError("HDR 16-bit float: rimuovi --fp16-intermediates dall'avvio di Comfy. La conversione colore richiede intermedi fp32.")
def convert_frame(frame, source, destination):
require_fp32()
return ni.ImageColorSpace.execute(
frame.to(device="cpu", dtype=torch.float32), source, destination
).result[0].to(device="cpu", dtype=torch.float32)
class DogmaHDRColorChunked(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="DOGMAHDRColorChunkedV1", display_name="DOGMA HDR | Colore per fotogramma",
category="DOGMA/HDR",
description="Stessa trasformazione colore Comfy, con temporanei limitati a un fotogramma. Non riduce risoluzione o precisione.",
inputs=[io.Image.Input("image"),
io.Combo.Input("source", options=SPACES, default="sRGB"),
io.Combo.Input("destination", options=SPACES, default="HDR ACEScct")],
outputs=[io.Image.Output()],
)
@classmethod
def execute(cls, image, source, destination):
require_fp32()
# Per-frame tone mapping would differ from the native batch transform.
# This node is intentionally limited to the non-tone-mapping HDR path.
if destination == "sRGB" or (source == "HDR PQ" and destination == "HDR"):
raise ValueError("Questa conversione usa statistiche dell'intero batch: usa ImageColorSpace nativo per il tonemapping SDR/PQ-HLG.")
if source == destination:
return io.NodeOutput(image.to(device="cpu", dtype=torch.float32))
output = torch.empty(image.shape, device="cpu", dtype=torch.float32)
progress = comfy.utils.ProgressBar(len(image))
with torch.inference_mode():
for index in range(len(image)):
nodes.before_node_execution()
output[index:index + 1].copy_(convert_frame(image[index:index + 1], source, destination))
progress.update(1)
return io.NodeOutput(output)
def fit_frame(frame, source_width, source_height, target_width, target_height):
if (source_width, source_height) == (target_width, target_height):
return nodes.ImageScale().upscale(frame, "bicubic", target_width, target_height, "disabled")[0]
width = 2 * math.floor(min(target_width, target_height * source_width / source_height) / 2)
height = 2 * math.floor(min(target_height, target_width * source_height / source_width) / 2)
if min(width, height) < 2:
raise ValueError("Proporzioni del sorgente non valide.")
frame = nodes.ImageScale().upscale(frame, "bicubic", width, height, "disabled")[0]
return ni.ResizeAndPadImage.execute(frame, target_width, target_height, "black", "area").result[0]
def create_job(prefix, output_directory):
# Comfy validates that the requested prefix remains inside its output root.
directory, name, counter, _, _ = folder_paths.get_save_image_path(prefix, output_directory)
while True:
job = Path(directory) / f"{name}_{counter:05d}"
try:
job.mkdir()
return job
except FileExistsError:
counter += 1
def write_json(path, data):
temporary = path.with_suffix(path.suffix + ".partial")
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
os.replace(temporary, path)
def encode_audio(container, audio, count, rate):
if audio is None:
return
sample_rate = int(audio["sample_rate"])
wave = audio["waveform"][0]
layouts = {1: "mono", 2: "stereo", 3: "2.1", 4: "quad", 6: "5.1", 8: "7.1"}
if wave.shape[0] not in layouts:
raise ValueError(f"Audio: {wave.shape[0]} canali non supportati; nessun downmix automatico.")
layout = layouts[wave.shape[0]]
stream = container.add_stream("pcm_s24le", rate=sample_rate, layout=layout)
n = min(wave.shape[-1], math.ceil(Fraction(sample_rate * count, 1) / rate))
# Audio is also chunked, avoiding an extra full-length contiguous copy.
for offset in range(0, n, 8192):
part = wave[:, offset:min(n, offset + 8192)].float().cpu().contiguous().numpy()
frame = av.AudioFrame.from_ndarray(part, format="fltp", layout=layout)
frame.sample_rate = sample_rate
frame.time_base = Fraction(1, sample_rate)
frame.pts = offset
container.mux(stream.encode(frame))
container.mux(stream.encode(None))
def export_frames(images, source_width, source_height, source_frames, fps,
filename_prefix="DOGMA_HDR_4K/master", save_mov=True, audio=None,
target_width=3840, target_height=2160, output_directory=None,
progress=None, metadata=None, exr_color_space="linear ACEScg",
mov_color_space="HDR", mov_stem=None):
"""Sequential finishing; target size override is for isolated CPU QA only."""
require_fp32()
if images.ndim != 4 or images.shape[-1] != 3:
raise ValueError("Atteso IMAGE RGB [fotogrammi, altezza, larghezza, 3] in ACEScct.")
if source_width < 1 or source_height < 1 or source_frames < 1 or source_frames > len(images):
raise ValueError(f"Conteggio/proporzioni non validi: richiesti {source_frames} frame, decode disponibile {len(images)}.")
if not math.isfinite(float(fps)) or fps <= 0:
raise ValueError("FPS sorgente non valido.")
if exr_color_space not in ("linear ACEScg", "linear"):
raise ValueError("Il master EXR richiede ACEScg lineare o Rec.709 lineare.")
if mov_color_space not in ("HDR", "HDR PQ"):
raise ValueError("Il MOV HDR richiede HLG o PQ.")
mov_stem = mov_stem or "DOGMA_4K_HDR_HLG"
if Path(mov_stem).name != mov_stem or any(c in mov_stem for c in ('/', '\\')):
raise ValueError("Nome MOV non valido.")
# Recover standard rational rates without rounding 24000/1001 to 23.976.
rate = Fraction(float(fps)).limit_denominator(1000000)
output_directory = output_directory or folder_paths.get_output_directory()
job = create_job(filename_prefix, output_directory)
exr_dir = job / "EXR"
exr_dir.mkdir()
mov_path = job / f"{mov_stem}.mov"
mov_temporary = job / f"{mov_stem}.partial.mov"
exr_label = "ACEScg AP1/D60" if exr_color_space == "linear ACEScg" else "Rec.709 D65"
mov_label = "HLG" if mov_color_space == "HDR" else "PQ"
manifest = dict(version=VERSION, status="incomplete", completed_frames=0,
frames=source_frames, fps=str(rate), width=target_width, height=target_height,
master=f"{exr_label} RGB HALF EXR ZIP16", source_width=source_width,
source_height=source_height, decoded_frames=len(images),
mov=f"ProRes 4444 BT.2020 {mov_label}; 10-bit encoding input; PCM24 original audio" if save_mov else None,
metadata=metadata or {})
write_json(job / "manifest.json", manifest)
container = None
try:
if save_mov:
container = av.open(str(mov_temporary), mode="w", format="mov", options={"movflags": "use_metadata_tags+faststart"})
stream = container.add_stream("prores_ks", rate=rate)
stream.width, stream.height = target_width, target_height
stream.pix_fmt = "yuv444p10le"
stream.options = {"profile": "4444", "alpha_bits": "16"}
stream.codec_context.thread_count = 2
stream.time_base = 1 / rate
set_video_color_properties(stream.codec_context, mov_color_space)
# Register audio before the muxer writes the MOV header.
# The PCM stream is created below by encode_audio, before video encode.
if audio is not None:
encode_audio(container, audio, source_frames, rate)
with torch.inference_mode():
for index in range(source_frames):
nodes.before_node_execution()
linear = convert_frame(images[index:index + 1], "HDR ACEScct", "linear ACEScg")
linear = fit_frame(linear, source_width, source_height, target_width, target_height)
master = linear if exr_color_space == "linear ACEScg" else convert_frame(linear, "linear ACEScg", exr_color_space)
if not torch.isfinite(master).all():
raise ValueError(f"Frame {index}: valori HDR NaN/Inf. Il file non viene dichiarato completo.")
# HALF cannot represent values outside +-65504. Do not silently clip.
if master.abs().max() > 65504:
raise ValueError(f"Frame {index}: range oltre HALF (+-65504). Serve EXR float32 per questi valori.")
encoded = ni._encode_image(master[0], "exr", "16-bit float", exr_color_space)
encoded = ni.inject_exr_metadata(encoded, None, None, exr_color_space)
del master
exr = exr_dir / f"frame_{index:06d}.exr"
temporary = exr.with_suffix(".exr.partial")
temporary.write_bytes(encoded)
os.replace(temporary, exr)
del encoded
if container is not None:
hlg = convert_frame(linear, "linear ACEScg", mov_color_space)[0]
pixels = (hlg * 65535).clamp(0, 65535).numpy().astype(np.uint16)
frame = av.VideoFrame.from_ndarray(pixels, format="rgb48le")
frame = frame.reformat(format="yuv444p10le", dst_colorspace=BT2020_NCL)
set_video_color_properties(frame, mov_color_space)
frame.time_base = 1 / rate
frame.pts = index
container.mux(stream.encode(frame))
del hlg, pixels, frame
del linear
manifest["completed_frames"] = index + 1
if (index + 1) % 12 == 0 or index + 1 == source_frames:
write_json(job / "manifest.json", manifest)
log.info("HDR export: %d/%d frame; %s", index + 1, source_frames, job)
if progress is not None:
progress.update(1)
if container is not None:
container.mux(stream.encode(None))
container.close()
container = None
os.replace(mov_temporary, mov_path)
manifest["status"] = "complete"
write_json(job / "manifest.json", manifest)
except BaseException as error:
manifest["error"] = str(error)
write_json(job / "manifest.json", manifest)
raise
finally:
if container is not None:
container.close()
return job, mov_path if save_mov else None
class DogmaHDRSaveStreaming(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="DOGMAHDRSaveStreamingV1", display_name="DOGMA HDR | Salva 4K EXR16 + MOV progressivo",
category="DOGMA/HDR", is_output_node=True,
description="Converte ACEScct, ripristina proporzioni, elimina la sola coda temporale e salva un frame alla volta. Nessun secondo batch IMAGE completo.",
inputs=[io.Image.Input("images"), io.Int.Input("source_width", force_input=True),
io.Int.Input("source_height", force_input=True), io.Int.Input("source_frames", force_input=True),
io.Float.Input("fps", force_input=True),
io.String.Input("filename_prefix", default="DOGMA_HDR_4K/master"),
io.Boolean.Input("save_mov", default=True), io.Audio.Input("audio", optional=True)],
hidden=[io.Hidden.prompt, io.Hidden.extra_pnginfo],
outputs=[io.String.Output("exr_directory"), io.String.Output("mov_path")],
)
@classmethod
def execute(cls, images, source_width, source_height, source_frames, fps,
filename_prefix="DOGMA_HDR_4K/master", save_mov=True, audio=None):
metadata = {}
if not args.disable_metadata and cls.hidden is not None:
if cls.hidden.extra_pnginfo:
metadata.update(cls.hidden.extra_pnginfo)
if cls.hidden.prompt:
metadata["prompt"] = cls.hidden.prompt
job, mov = export_frames(images, source_width, source_height, source_frames, fps,
filename_prefix, save_mov, audio,
progress=comfy.utils.ProgressBar(source_frames), metadata=metadata)
preview = None
if mov:
subfolder = str(job.relative_to(Path(folder_paths.get_output_directory()))).replace("\\", "/")
preview = ui.PreviewVideo([ui.SavedResult(mov.name, subfolder, io.FolderType.output)])
return io.NodeOutput(str(job / "EXR"), str(mov) if mov else "", ui=preview)
class DogmaHDRCheckpoint(io.ComfyNode):
@classmethod
def define_schema(cls):
return io.Schema(
node_id="DOGMAHDRCheckpointV1", display_name="DOGMA HDR | Checkpoint prima del decode",
category="DOGMA/HDR",
description="Salva il latente prima del decode. Per riprendere lo stesso video inserisci il percorso del checkpoint: i sampler vengono saltati.",
inputs=[io.Latent.Input("samples", lazy=True),
io.String.Input("filename_prefix", default="DOGMA_HDR_4K/checkpoints/HDR"),
io.String.Input("resume_from", default="", tooltip="Lascia vuoto per una nuova generazione. Percorso .latent relativo a output, oppure assoluto dentro input/output Comfy.")],
outputs=[io.Latent.Output(), io.String.Output("checkpoint_path")],
)
@classmethod
def check_lazy_status(cls, filename_prefix, resume_from, samples=None):
return [] if resume_from.strip() or samples is not None else ["samples"]
@classmethod
def execute(cls, filename_prefix, resume_from="", samples=None):
if resume_from.strip():
path = Path(resume_from.strip()).expanduser()
if not path.is_absolute():
path = Path(folder_paths.get_output_directory()) / path
path = path.resolve()
roots = [Path(folder_paths.get_output_directory()).resolve(), Path(folder_paths.get_input_directory()).resolve()]
if not any(path.is_relative_to(root) for root in roots) or path.suffix != ".latent":
raise ValueError("Il checkpoint deve essere un file .latent nella cartella input/output di Comfy.")
saved = safetensors.torch.load_file(str(path), device="cpu")
if "latent_format_version_0" not in saved or "latent_tensor" not in saved:
raise ValueError("Checkpoint non compatibile: atteso formato latente Comfy attuale.")
return io.NodeOutput({"samples": saved["latent_tensor"]}, str(path))
if samples is None or "samples" not in samples:
raise ValueError("Nessun latente ricevuto dal sampler.")
directory, name, counter, _, _ = folder_paths.get_save_image_path(filename_prefix, folder_paths.get_output_directory())
path = Path(directory) / f"{name}_{counter:05d}_.latent"
temporary = path.with_suffix(".latent.partial")
saved = {"latent_tensor": samples["samples"].detach().contiguous(),
"latent_format_version_0": torch.tensor([])}
comfy.utils.save_torch_file(saved, str(temporary), metadata={"dogma_hdr_streaming": VERSION})
os.replace(temporary, path)
log.info("Checkpoint HDR salvato prima del decode: %s", path)
return io.NodeOutput(samples, str(path))
# Registered through the existing DOGMA package, not a separate extension.
NODE_CLASS_MAPPINGS = {
"DOGMAHDRColorChunkedV1": DogmaHDRColorChunked,
"DOGMAHDRSaveStreamingV1": DogmaHDRSaveStreaming,
"DOGMAHDRCheckpointV1": DogmaHDRCheckpoint,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"DOGMAHDRColorChunkedV1": "DOGMA HDR | Colore per fotogramma",
"DOGMAHDRSaveStreamingV1": "DOGMA HDR | Salva 4K EXR16 + MOV progressivo",
"DOGMAHDRCheckpointV1": "DOGMA HDR | Checkpoint prima del decode",
}
# Initialize V3 schema fields while retaining explicit, Registry-readable IDs.
for _node in NODE_CLASS_MAPPINGS.values():
_node.GET_SCHEMA()
del _node
+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.49"
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.
+158
View File
@@ -0,0 +1,158 @@
export const copy=x=>JSON.parse(JSON.stringify(x));
export const FAMILIES=[
{key:'nano',name:'Nanobanana',short:'NB',type:'GeminiImage2Node'},
{key:'gpt',name:'GPT Image',short:'GPT',type:'OpenAIGPTImageNodeV2'},
{key:'flux',name:'Flux 3',short:'F3',type:'Flux3ImageNode'},
{key:'seedream',name:'Seedream',short:'SD',type:'ByteDanceSeedreamNodeV3'},
];
export const VIDEO_FAMILIES=[{key:'seedance',name:'Seedance',short:'V',type:'ByteDance2ReferenceNodeV2'}];
export const ALL_FAMILIES=[...FAMILIES,...VIDEO_FAMILIES];
export const families=s=>s.mode==='video'?VIDEO_FAMILIES:FAMILIES;
export 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;
for(let i=0;i<parts.length;i++){
const spec=inputs?.required?.[parts[i]]||inputs?.optional?.[parts[i]];if(!spec)return null;
if(i===parts.length-1)return spec;
if(spec[0]==='COMFY_DYNAMICCOMBO_V3'){const key=values[parts.slice(0,i+1).join('.')];inputs=spec[1].options.find(o=>o.key===key)?.inputs;}else return null;
}
return null;
}
export function viewParameters(file){
if(typeof file!=='string')return {filename:file.filename,subfolder:file.subfolder||'',type:file.type||'output'};
const parts=file.replaceAll('\\','/').split('/');return {filename:parts.pop(),subfolder:parts.join('/'),type:'input'};
}
export function choicesFor(spec){if(!spec)return null;if(Array.isArray(spec[0]))return spec[0];if(spec[0]==='COMBO')return spec[1].options;if(spec[0]==='COMFY_DYNAMICCOMBO_V3')return spec[1].options.map(o=>o.key);return null;}
export function parameterSpecs(def,values){
const result={};const walk=(inputs,prefix='')=>{for(const [key,spec] of Object.entries({...inputs?.required,...inputs?.optional})){
const name=prefix+key;const choices=choicesFor(spec);
if(choices||['INT','FLOAT','BOOLEAN','STRING'].includes(spec[0]))result[name]=spec;
if(spec[0]==='COMFY_DYNAMICCOMBO_V3')walk(spec[1].options.find(o=>o.key===values[name])?.inputs,name+'.');
}};walk(def?.input);return result;
}
export function modelValues(def,values){
const specs=parameterSpecs(def,values),next={};for(const [key,spec] of Object.entries(specs)){
const choices=choicesFor(spec),value=values[key];next[key]=value!==undefined&&(!choices||choices.includes(value))?value:spec[1]?.default??choices?.[0]??(spec[0]==='BOOLEAN'?false:spec[0]==='STRING'?'':0);
}return next;
}
export function sortedChoices(key,values){
const list=[...new Set(values.map(String))];if(!/resolution|size_preset|size$/.test(key))return list;
const score=v=>{if(key==='model.size_preset'){const tier=v.match(/([\d.]+)K/i);return tier?+tier[1]:Infinity;}const dims=v.match(/(\d+)x(\d+)/);if(dims)return +dims[1]*+dims[2];const k=v.match(/([\d.]+)\s*[kK]/);if(k)return +k[1]*1000;const p=v.match(/(\d+)p/i);if(p)return +p[1];return Infinity;};return list.sort((a,b)=>score(a)-score(b));
}
export function todayCode(){const parts=new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/Rome',day:'2-digit',month:'2-digit',year:'2-digit'}).formatToParts(new Date());return ['day','month','year'].map(k=>parts.find(p=>p.type===k).value).join('');}
export function titleParts(s){return [s.project,s.scene,s.filename||'DOGMA',s.appendDate?(s.dateMode==='today'?todayCode():s.date||todayCode()):''].map(safeName).filter(Boolean);}
export function prefix(s,f){return ['DOGMA/API',safeName(s.project),safeName(s.scene),titleParts(s).join('_')+'_'+f.short].filter(Boolean).join('/');}
export function migrateState(raw){
const s=copy(raw);s.schema=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;}
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){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 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');
if(refs.some(r=>!r.file))throw new Error('Ricarica le reference mancanti.');
if(s.mode==='image'){
if(s.imageEdit&&!imgs.length)throw new Error('Image Edit richiede Image 1.');
const limits={nano:14,gpt:16,flux:10,seedream:10},max=Math.min(...FAMILIES.filter(f=>s.models[f.key]?.enabled).map(f=>limits[f.key]));if(imgs.length>max)throw new Error(`I modelli attivi supportano fino a ${max} reference.`);
}else {
const m=s.models.seedance;
if(m.engine==='frames'&&imgs.length>2)throw new Error('Usa al massimo un First frame e un Last frame.');
if(m.engine==='frames'&&['first','last'].some(role=>imgs.filter(r=>r.role===role).length>1))throw new Error('Assegna un solo First frame e un solo Last frame.');
if(m.engine==='frames'&&!imgs.length)throw new Error('Aggiungi almeno un frame immagine.');
if(m.engine!=='frames'&&!refs.length)throw new Error('Aggiungi una reference immagine o video.');
const p=m.engine==='frames'?m.frames:m.parameters;
if(m.engine!=='frames'&&['edit','extend'].includes(p['model.task_type'])&&!videos.length)throw new Error('Video Edit ed Extend richiedono un video sorgente.');
if(imgs.length>30||videos.length>10)throw new Error('Troppe reference per Seedance 2.5.');
}
for(const f of families(s)){
const m=s.models[f.key];if(!m.enabled)continue;const p=m.engine==='frames'?m.frames:m.parameters;
validateDimensions(f,p,specFor);
}
}
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;}
let link=[id,0];const p=ref.process;
if(p?.enabled){
let mask=[id,1];
if(p.maskFile){const mid=String(9001+i*10);output[mid]={class_type:'LoadImage',inputs:{image:p.maskFile}};const tid=String(9002+i*10);output[tid]={class_type:'ImageToMask',inputs:{image:[mid,0],channel:'red'}};mask=[tid,0];}
if(p.source==='prompt'&&p.mask&&!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});
});
let nanoBatch=null;
if(s.mode==='image'&&s.models.nano?.enabled&&images.length){nanoBatch=images[0].link;images.slice(1).forEach((img,i)=>{const id=String(9800+i);output[id]={class_type:'ImageBatch',inputs:{image1:nanoBatch,image2:img.link}};nanoBatch=[id,0];});}
jobs.forEach((job,i)=>{
const f=ALL_FAMILIES.find(f=>f.key===job.family),m=s.models[f.key],inputs=copy(m.engine==='frames'?m.frames:m.parameters);
for(const k of Object.keys(inputs))if(k.startsWith('control_after_generate')||k==='n')delete inputs[k];
const seed=(Number(baseSeed)+i)%2147483647;inputs[f.key==='seedream'?'model.seed':'seed']=seed;
const prompt=s.prompts[s.mode];inputs[s.mode==='video'?'model.prompt':'prompt']=prompt;
let type=f.type;
if(s.mode==='video'){
if(m.engine==='frames'){
type='ByteDance2FirstLastFrameNode';
const first=images.find(x=>x.ref.role==='first')||images.find(x=>x.ref.role!=='last');const last=images.find(x=>x.ref.role==='last')||images.filter(x=>x!==first)[0];
if(first)inputs.first_frame=first.link;if(last)inputs.last_frame=last.link;
}else{images.forEach((x,j)=>inputs[`model.reference_images.image_${j+1}`]=x.link);videos.forEach((x,j)=>inputs[`model.reference_videos.video_${j+1}`]=x.link);}
}else if(f.key==='nano'){if(nanoBatch)inputs.images=nanoBatch;}
else{if(f.key==='gpt')inputs.n=1;images.forEach((x,j)=>inputs[`${f.key==='flux'?'':'model.'}images.image_${j+1}`]=x.link);}
const gen=String(10000+i*10),save=String(10001+i*10);
Object.assign(job,{seed,generator:gen,output:save,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 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||'';}
+114
View File
@@ -0,0 +1,114 @@
{
"schema": 4,
"runCount": 1,
"session": "",
"mode": "image",
"imageEdit": true,
"project": "",
"scene": "",
"filename": "DOGMA",
"date": "",
"appendDate": false,
"workspace": "",
"prompts": {
"image": "",
"video": ""
},
"density": 55,
"models": {
"nano": {
"enabled": true,
"expanded": false,
"quantity": 2,
"parameters": {
"model": "gemini-3-pro-image-preview",
"seed": 637339876168947,
"aspect_ratio": "16:9",
"resolution": "2K",
"response_modalities": "IMAGE",
"system_prompt": "Follow the user prompt and the assigned roles of the reference images precisely."
}
},
"gpt": {
"enabled": true,
"expanded": false,
"quantity": 2,
"parameters": {
"model": "gpt-image-2",
"model.size": "2048x1152",
"model.custom_width": 1920,
"model.custom_height": 1088,
"model.background": "auto",
"model.quality": "high",
"n": 1,
"seed": 726834962
}
},
"flux": {
"enabled": true,
"expanded": false,
"quantity": 2,
"parameters": {
"aspect_ratio": "auto",
"resolution": "2K",
"grounding": true,
"safety_tolerance": 4,
"seed": 390115469
}
},
"seedream": {
"enabled": true,
"expanded": true,
"quantity": 2,
"parameters": {
"model": "seedream 5.5",
"model.size_preset": "Custom",
"model.width": 2048,
"model.height": 1152,
"model.background": "auto",
"model.seed": 42,
"model.watermark": false
}
},
"seedance": {
"enabled": true,
"expanded": true,
"quantity": 1,
"engine": "reference",
"parameters": {
"model": "Seedance 2.5",
"model.resolution": "1080p",
"model.ratio": "adaptive",
"model.duration": 15,
"model.generate_audio": false,
"model.task_type": "edit",
"model.output_format": "mp4",
"model.auto_downscale": false,
"model.auto_upscale": false,
"seed": 1982892718,
"watermark": false
},
"frames": {
"model": "Seedance 2.5",
"model.resolution": "720p",
"model.duration": 4,
"model.generate_audio": false,
"model.output_format": "mp4",
"seed": 1439633762,
"watermark": false,
"first_frame_asset_id": "",
"last_frame_asset_id": ""
}
}
},
"references": [],
"results": [],
"filters": {
"models": [],
"project": "*",
"scene": "*",
"kind": "all",
"workspace": "*"
},
"videoRepair": false
}
+31
View File
@@ -0,0 +1,31 @@
export function icon(name){
const ns='http://www.w3.org/2000/svg',s=document.createElementNS(ns,'svg');s.setAttribute('viewBox','0 0 24 24');s.setAttribute('aria-hidden','true');s.classList.add('dap-icon');
const paths={
prompt:[['path',{d:'M4 3h16v18H4zM7 7h10M7 11h10M7 15h7'}]],
copy:[['rect',{x:8,y:8,width:13,height:13,rx:1}],['path',{d:'M16 8V3H3v13h5'}]],
image:[['rect',{x:3,y:3,width:18,height:18,rx:2}],['circle',{cx:8,cy:8,r:1.1,fill:'currentColor'}],['path',{d:'M3 17l6-6 4 3 8-8'}]],
media:[['path',{d:'M10 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v5M3 17l6-6 3 3'}],['circle',{cx:8,cy:8,r:1.1,fill:'currentColor'}],['path',{d:'m15 12 7 4.5-7 4.5z'}]],
video:[['rect',{x:3,y:3,width:18,height:18,rx:1}],['path',{d:'M3 7h18M3 17h18M7 3v4m5-4v4m5-4v4M7 17v4m5-4v4m5-4v4'}]],
chevron:[['path',{d:'m7 10 5 5 5-5'}]],
lines:[['path',{d:'M8 9h8M8 12h8M8 15h8'}]],
single:[['rect',{x:3,y:4,width:18,height:16,rx:.6}]],
grid:[['path',{d:'M2 4h5v6H2zM10 4h5v6h-5zM18 4h5v6h-5zM2 14h5v6H2zM10 14h5v6h-5zM18 14h5v6h-5z'}]],
compare:[['path',{d:'M1 6a1 1 0 0 1 1-1h20a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1Z M1.5 6v11a.5.5 0 0 0 .5.5h9V5.5H2a.5.5 0 0 0-.5.5Z M13.2 6.3v10.4h4.1c4 0 4.8-4.5 1.6-5.3 2.5-1.1 1.8-5.1-1.6-5.1Z M14.6 7.6h2.6c2.4 0 2.4 3.1 0 3.1h-2.6Z M14.6 12h2.8c2.7 0 2.7 3.4 0 3.4h-2.8Z M2.6 16.7 6.3 6.3h1.5l3.7 10.4H10l-1-3H5l-1 3Z M5.5 12.4h3L7 8Z',fill:'currentColor',stroke:'none','fill-rule':'evenodd'}]],
play:[['path',{d:'M7 3l15 9L7 21z',fill:'currentColor',stroke:'none'}]],
playCircle:[['circle',{cx:12,cy:12,r:10.5,fill:'none','stroke-width':.9}],['path',{d:'M9 7l8.5 5L9 17z',fill:'currentColor',stroke:'none'}]],
plus:[['path',{d:'M12 4v16M4 12h16'}]],
close:[['path',{d:'m6 6 12 12M18 6 6 18'}]],
folder:[['path',{d:'M2 6h8l2 3h10l-2 11H3zM2 6V4h8l2 2h8v3'}]],
external:[['path',{d:'M14 3h7v7M21 3 11 13M10 5H4v15h15v-6'}]],
download:[['path',{d:'M12 3v12m-5-5 5 5 5-5M4 17v4h16v-4'}]],
edit:[['path',{d:'m4 16 12-12 4 4L8 20H4zm10-10 4 4M4 20h16'}]],
zoomIn:[['circle',{cx:10,cy:10,r:7}],['path',{d:'m15 15 7 7M6 10h8M10 6v8'}]],
zoomOut:[['circle',{cx:10,cy:10,r:7}],['path',{d:'m15 15 7 7M6 10h8'}]],
fit:[['path',{d:'M3 9V3h6m6 0h6v6M3 15v6h6m6 0h6v-6'}]],
refresh:[['path',{d:'M20 8a9 9 0 1 0 0 9M20 3v6h-6'}]],
filter:[['path',{d:'M3 5h18l-7 8v7l-4-2v-5z'}]],
arrow:[['path',{d:'m14 5-7 7 7 7'}]],
};
for(const [tag,attributes] of paths[name]||paths.plus){const p=document.createElementNS(ns,tag);for(const [k,v] of Object.entries(attributes))p.setAttribute(k,String(v));s.append(p);}
return s;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

+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');
}
+205
View File
@@ -0,0 +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 '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 '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}
/* 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 '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}
+90
View File
@@ -0,0 +1,90 @@
import { app } from '../../scripts/app.js';
import { api } from '../../scripts/api.js';
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.62',ROOT);document.head.append(css);
let opened=null,queueLock=false;
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_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.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]];}));
for(const r of live)if(r.status==='fulfilled'&&r.value[1])this.defs[r.value[0]]=r.value[1];
if(state.workspace){try{await this.workspace(state.workspace);}catch(e){this.workspaceError=e.message;}}
try{
const script=[...document.querySelectorAll('script[type=module][src]')].find(x=>x.src.includes('/assets/'));
const base=script?.src||new URL('/assets/index.js',location.href).href;
const names=this.catalog.frontend;
if(names.billing&&names.credits){
const [billing,credits]=await Promise.all([import(new URL(names.billing.file,base).href),import(new URL(names.credits.file,base).href)]);
this.billing=billing[names.billing.context]();this.nativePricing=billing[names.billing.pricing]();this.formatCredits=credits[names.credits.format];
}
}catch(e){console.warn('DOGMA: servizi crediti/prezzi non disponibili in questo frontend.');}
}
save(s){this.widget.value=JSON.stringify(s);this.node.setDirtyCanvas?.(true,true);clearTimeout(this.saveTimer);this.saveTimer=setTimeout(()=>{if(this.node.graph===app.graph)app.graph.change?.();},250);}
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();}
async upload(file){const body=new FormData();body.append('image',file,file.name);body.append('type','input');body.append('subfolder','DOGMA_API');body.append('overwrite','false');const r=await api.fetchApi('/upload/image',{method:'POST',body});if(!r.ok)throw new Error('Caricamento non riuscito.');const d=await r.json();return {file:[d.subfolder,d.name].filter(Boolean).join('/'),kind:file.type.startsWith('video/')?'video':'image'};}
async workspace(path){return this.request('/workspace',{path});}
async chooseFolder(){return {browse:true};}
async mkdir(path,name){return this.request('/mkdir',{path,name});}
async folders(path){return this.request('/folders?'+new URLSearchParams({path:path||''}));}
async library(){return (await this.request('/library')).records;}
async previewReference(ref,settings){return this.request('/reference-preview',{file:ref.file,settings});}
async openOutput(id,index){return this.request('/open-output',{id,index});}
async credits(){
if(!this.billing||!this.formatCredits)return {text:'CREDITS —',title:'Saldo non disponibile. Apri l’account Comfy.'};
try{await this.billing.fetchBalance();const raw=this.billing.balance,b=raw&&'value' in raw?raw.value:raw;const amount=b?.effectiveBalanceMicros??b?.amountMicros;if(!Number.isFinite(amount))return {text:'ACCEDI A COMFY',title:'Accedi all’account da Comfy per vedere i crediti.'};return {text:this.formatCredits({cents:amount,locale:'it-IT',numberOptions:{minimumFractionDigits:0,maximumFractionDigits:2}})+' CREDITS LEFT',title:'Saldo dello stesso account e workspace di Comfy'};}catch{return {text:'CREDITS —',title:'Saldo temporaneamente non disponibile. Clicca per aggiornare.'};}
}
inputSpec(state,f,key){const m=state.models[f.key],frames=m.engine==='frames';return inputSpec(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],frames?m.frames:m.parameters,key);}
parameterSpecs(state,f){const m=state.models[f.key],frames=m.engine==='frames';return parameterSpecs(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],frames?m.frames:m.parameters);}
changeModel(state,f){const m=state.models[f.key],frames=m.engine==='frames',key=frames?'frames':'parameters';m[key]=modelValues(this.defs?.[frames?'ByteDance2FirstLastFrameNode':f.type],m[key]);}
price(state,f){
if(!this.nativePricing||!this.defs)return '';
const m=state.models[f.key],frames=f.key==='seedance'&&m.engine==='frames',type=frames?'ByteDance2FirstLastFrameNode':f.type,def=this.defs[type];if(!def)return '';
let n=this.pricingNodes.get(type);if(!n){n={constructor:{nodeData:def},inputs:[],widgets:[],isInputConnected:i=>!!n.inputs[i]?.link};this.pricingNodes.set(type,n);}
const refs=activeReferences(state),images=refs.filter(r=>r.kind==='image'),videos=refs.filter(r=>r.kind==='video');
const values=frames?m.frames:m.parameters;n.widgets=Object.entries(values).map(([name,value])=>({name,value}));
n.inputs=[];
if(f.key==='nano'&&images.length)n.inputs.push({name:'images',link:1});
else if(f.key==='seedance'&&frames){for(const r of images)n.inputs.push({name:r.role==='last'?'last_frame':'first_frame',link:1});}
else if(f.key==='seedance'){images.forEach((r,i)=>n.inputs.push({name:`model.reference_images.image_${i+1}`,link:1}));videos.forEach((r,i)=>n.inputs.push({name:`model.reference_videos.video_${i+1}`,link:1}));}
else images.forEach((r,i)=>n.inputs.push({name:`${f.key==='flux'?'':'model.'}images.image_${i+1}`,link:1}));
try{return this.nativePricing.getNodeDisplayPrice(n,new Map(Object.entries(values)))||'';}catch{return '';}
}
async check(state,compiled){
const types=[...new Set(Object.values(compiled.output).map(n=>n.class_type))];
const available=await Promise.all(types.map(async type=>{const r=await api.fetchApi('/object_info/'+encodeURIComponent(type));return r.ok&&(await r.json())[type]?type:null;}));
const missing=types.filter(t=>!available.includes(t));if(missing.length)throw new Error('Nodi mancanti: '+missing.join(', '));
await Promise.all(activeReferences(state).flatMap(ref=>[ref.file,ref.process?.maskFile].filter(Boolean)).map(async file=>{const r=await fetch(this.view(file),{method:'HEAD'});if(!r.ok)throw new Error('Reference assente: '+file+'. Ricaricala dal pannello.');}));
}
async queue(compiled,batch,state){
if(queueLock||app.processingQueue||app.queueItems?.length)throw new Error('Comfy sta già inviando una richiesta. Riprova tra un momento.');
queueLock=true;let result=null,used=false,queueError=null,build,capture;
const nativeBuild=app.graphToPrompt,nativeQueue=api.queuePrompt;
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','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);}
close(){opened=null;}
}
app.registerExtension({name:'DOGMA.APIPlatform.2',async beforeRegisterNodeDef(type,data){if(data.name!=='DOGMAAPIPlatformV1')return;const previous=type.prototype.onNodeCreated;type.prototype.onNodeCreated=function(...args){const result=previous?.apply(this,args),config=this.widgets?.find(w=>w.name==='config');if(config){config.type='hidden';config.computeSize=()=>[0,-4];}this.addWidget('button','APRI DOGMA / API PLATFORM',null,()=>{if(opened){opened.root?.focus();return;}try{opened=new PlatformUI(new ComfyBridge(this));opened.open().catch(e=>{opened?.close();opened=null;app.ui.dialog.show(e.message);});}catch(e){opened=null;app.ui.dialog.show(e.message);}},{serialize:false});this.size=[390,110];return result;};}});
+60
View File
@@ -0,0 +1,60 @@
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'),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=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){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=()=>{
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 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==='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: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();
}
File diff suppressed because one or more lines are too long
+364
View File
@@ -0,0 +1,364 @@
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;};
export const ib=(name,label,fn,cls='')=>{const b=btn('',fn,'dap-icon-button '+cls,label);b.append(icon(name));return b;};
const terminal=new Set(['completed','failed','cancelled','missing']);
const enumValues={aspect_ratio:['auto','1:1','2:3','3:2','3:4','4:3','4:5','5:4','9:16','16:9','21:9'],resolution:['1K','2K','4K'],'model.background':['auto','opaque','transparent'],'model.quality':['low','medium','high'],'model.size':['auto','1024x1024','1536x1024','1024x1536','2048x2048','2048x1152','1152x2048','3840x2160','2160x3840','Custom'],'model.size_preset':['Custom'],'model.resolution':['480p','720p','1080p','4k'],'model.ratio':['adaptive','16:9','4:3','1:1','3:4','9:16','21:9'],'model.task_type':['reference','edit','extend','auto'],'model.output_format':['mp4'],response_modalities:['IMAGE','IMAGE+TEXT']};
const displayName=k=>({'model.task_type':'TASK','model.generate_audio':'AUDIO','model.duration':'DURATION / SEC','model.auto_downscale':'AUTO DOWNSCALE','model.auto_upscale':'AUTO UPSCALE'})[k]||k.replace(/^model\./,'').replaceAll('_',' ').toUpperCase();
export class PlatformUI {
constructor(bridge){this.bridge=bridge;this.state=bridge.load();this.library=[];this.selection=[];this.cards=new Map();this.urls=new Set();this.closed=false;this.busy=false;}
save(){if(!this.closed)this.bridge.save(this.state);}
async open(){
this.ready=false;
this.root=el('dialog','','dap');this.root.setAttribute('aria-label','DOGMA API Platform');
this.root.addEventListener('cancel',e=>{e.preventDefault();this.close();});
this.root.addEventListener('dragover',e=>{if([...e.dataTransfer.types].includes('Files'))e.preventDefault();});
this.root.addEventListener('drop',e=>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();},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?.();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()),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');
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(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.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';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,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,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(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();};
const previous=ib('arrow','Riduci / precedente '+name,e=>step(-1),'dap-field-step'),next=ib('arrow','Aumenta / successivo '+name,e=>step(1),'dap-field-step next');
previous.addEventListener('click',e=>e.preventDefault());next.addEventListener('click',e=>e.preventDefault());row.prepend(previous);row.append(next);
}
parent.append(row);return input;
}
renderControls(){
const c=this.controls,s=this.state;c.replaceChildren();
const refs=el('section','','dap-section');refs.append(el('div','REFERENCES','dap-label'));this.refs=el('div','','dap-refs');refs.append(this.refs);this.renderRefs();
const prompt=el('section','','dap-section dap-prompt');prompt.append(el('div','PROMPT','dap-label'));const wrap=el('div','','dap-prompt-wrap'),area=el('textarea');area.value=s.prompts[s.mode]||'';area.setAttribute('aria-label','Prompt');area.placeholder='Scrivi il prompt…';area.oninput=()=>{s.prompts[s.mode]=area.value;this.save();};
const resize=el('div','','dap-resize-handle');resize.title='Trascina per ingrandire il prompt';let start=null;
resize.onpointerdown=e=>{e.preventDefault();start={y:e.clientY,height:area.offsetHeight};resize.setPointerCapture(e.pointerId);};resize.onpointermove=e=>{if(start)area.style.height=Math.max(90,start.height+e.clientY-start.y)+'px';};resize.onpointerup=resize.onpointercancel=()=>start=null;wrap.append(area,resize);prompt.append(wrap);
const workSection=el('details','','dap-section dap-work');workSection.open=!!s.workExpanded;workSection.ontoggle=()=>{s.workExpanded=workSection.open;this.save();};const 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'));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);}
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(){
if(!this.refs)return;this.refs.replaceChildren();
const visible=visibleReferences(this.state);
visible.forEach((r,i)=>{
const tile=el('article','','dap-ref');tile.classList.toggle('disabled',!r.enabled);tile.dataset.ref=String(i);
const media=el(r.kind==='video'?'video':'img');media.src=r.processedPreview?this.bridge.view(r.processedPreview):r.preview||this.bridge.view(r.file);media.draggable=false;if(r.kind==='video'){media.muted=true;media.preload='metadata';media.onpointerenter=()=>media.play().catch(()=>{});media.onpointerleave=()=>media.pause();}else media.alt=`Image ${i+1}`;
media.onclick=()=>r.kind==='video'?this.referenceVideo(r):referenceEditor(this,r);
media.onerror=()=>tile.classList.add('missing');
const tools=el('div','','dap-ref-tools');tools.append(this.toggle(`Attiva reference ${i+1}`,r.enabled,v=>{r.enabled=v;this.save();this.renderRefs();this.refreshPrices();}));
if(r.kind==='image')tools.append(ib('edit',`Modifica reference ${i+1}`,()=>referenceEditor(this,r)));
else tools.append(ib('play',`Apri video reference ${i+1}`,()=>this.referenceVideo(r)));
if(i>0)tools.append(ib('arrow',`Sposta prima reference ${i+1}`,()=>{const a=this.state.references.indexOf(visible[i-1]),b=this.state.references.indexOf(r);[this.state.references[a],this.state.references[b]]=[r,visible[i-1]];this.save();this.renderRefs();}));
tools.append(ib('close',`Rimuovi reference ${i+1}`,()=>{this.state.references.splice(this.state.references.indexOf(r),1);this.save();this.renderRefs();this.refreshPrices();}));
tile.append(media,el('span',`${String(i+1).padStart(2,'0')} / ${r.kind==='video'?'VIDEO':'IMAGE'}`,'dap-ref-order'),tools);
if(r.process?.enabled)tile.append(el('span','EDIT','dap-ref-edited'));
if(this.state.mode==='video'&&this.state.models.seedance.engine==='frames'&&r.kind==='image'){
const select=el('select','','dap-ref-role');select.setAttribute('aria-label',`Ruolo reference ${i+1}`);for(const [key,text] of [['first','First frame'],['last','Last frame']]){const o=el('option',text);o.value=key;select.append(o);}select.value=r.role||'reference';select.onchange=()=>{r.role=select.value;this.save();};tile.append(select);
}
this.refs.append(tile);
});
const frames=this.state.mode==='video'&&this.state.models.seedance.engine==='frames',mixed=this.state.mode==='video'&&!frames;const add=ib('plus',mixed?'Aggiungi immagini o video':'Aggiungi immagine',()=>this.pickReferences(),'dap-add');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();}
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.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);
const body=el('div','','dap-model-body');
this.field(body,'QUANTITY',m.quantity,v=>{m.quantity=Number(v);this.save();this.updateHeader();},{type:'number',min:1,max:64});
body.append(el('div','Richieste in parallelo · Seed diversi','dap-field-hint'));
const values=m.engine==='frames'?m.frames:m.parameters;
const nativeSpecs=this.bridge.parameterSpecs?.(this.state,f);const entries=nativeSpecs&&Object.keys(nativeSpecs).length?Object.keys(nativeSpecs).map(key=>[key,values[key]??nativeSpecs[key][1]?.default??choicesFor(nativeSpecs[key])?.[0]??'']):Object.entries(values);
for(const [key,value] of entries){
if(['prompt','model.prompt','system_prompt','seed','model.seed','n'].includes(key)||key.startsWith('control_after_generate')||key.endsWith('asset_id'))continue;
const opts={};if(enumValues[key])opts.choices=enumValues[key];
if(key==='model'){if(f.key==='nano')opts.choices=['gemini-3-pro-image-preview','Nano Banana 2 (Gemini 3.1 Flash Image)'];else opts.readonly=true;}
if(key==='resolution'&&f.key==='flux')opts.choices=['0.75K','1K','1.5K','2K','4K'];
if(typeof value==='boolean')opts.type='checkbox';if(typeof value==='number'){opts.type='number';opts.min=key==='model.duration'?4:0;opts.max=key==='model.duration'?30:8594;}
const spec=this.bridge.inputSpec?.(this.state,f,key);
if(spec){const info=spec[1]||{};if(Array.isArray(spec[0]))opts.choices=spec[0];else if(choicesFor(spec))opts.choices=choicesFor(spec);if(info.min!==undefined)opts.min=info.min;if(info.max!==undefined)opts.max=info.max;if(info.step!==undefined)opts.step=info.step;}
if(opts.choices){opts.choices=sortedChoices(key,opts.choices);delete opts.readonly;}
this.field(body,displayName(key),value,v=>{values[key]=typeof value==='boolean'?v:typeof value==='number'?Number(v):v;if(key==='model'){this.bridge.changeModel?.(this.state,f);this.renderControls();}this.save();this.refreshPrices();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'));
details.append(body);row.append(toggle,details);wrap.append(row);return wrap;
}
async refreshCredits(){if(this.creditBusy||this.closed)return;this.creditBusy=true;try{const result=await this.bridge.credits();if(!this.closed){this.credit.textContent=result.text;this.credit.title=result.title;}}catch{}finally{this.creditBusy=false;}}
refreshPrices(){if(this.closed)return;for(const f of families(this.state)){const text=this.bridge.price?.(this.state,f);const node=this.priceLabels?.get(f.key);if(node&&text){node.textContent=text;node.title='Stima calcolata dalle stesse regole di Comfy per questi parametri';}}}
allResults(){const map=new Map;for(const r of [...this.library,...this.state.results])map.set(r.id,r);return 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();};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);
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,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;}
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;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=btn('A\\B',()=>this.selectCompare(item),'dap-icon-button dap-ab','Scegli immagine o video per il confronto A/B');select.dataset.compare=item.id;
tools.append(select,ib('plus','Usa come reference',()=>this.reuse(file,job.kind)),ib('prompt','Leggi e copia prompt',()=>this.showPrompt(job)),ib('download','Scarica file',()=>this.downloadImage(file)));card.append(tools);
if(job.study)card.append(el('span','DESIGN REFERENCE','dap-study'));
if(file.variant){const variant=el('span',({original:'ORIGINALE',repaired:'SCATTI CORRETTI',checked:'VERIFICATO · INVARIATO'})[file.variant]||'','dap-video-variant');variant.title=job.repair?.status==='unchanged'?'Nessuno scatto rilevato: copia identica all’originale.':variant.textContent;card.append(variant);}
}else{
card.classList.add('pending');const logo=el('video','','dap-loading-logo');logo.src=this.bridge.loadingLogo();logo.muted=true;logo.loop=true;logo.autoplay=true;logo.playsInline=true;logo.setAttribute('aria-label','Generazione in corso');
const track=el('div','','dap-progress-track dap-card-progress');track.append(el('i'));const error=el('div','','dap-error-content');error.append(el('span','ERRORE'),el('p',job.error||''));card.append(logo,track,error);
}
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();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();
}
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);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);}
for(const file of data.files||[]){const row=el('div',file.name,'dap-folder-file'+(file.name===selected?' selected':''));if(file.name===selected)row.setAttribute('aria-current','true');list.append(row);}
const name=el('input');name.placeholder='Nome nuova cartella';name.setAttribute('aria-label','Nome nuova cartella');footer.append(name,btn('Crea cartella',async()=>{try{const d=await this.bridge.mkdir(data.path,name.value);await render(d.path);}catch(e){error.textContent=e.message;}},'dap-outline'));
if(choose)footer.append(btn('Usa questa cartella',async()=>{try{const result=await this.bridge.workspace(data.path);this.state.workspace=result.path;for(const record of result.records||[]){const existing=this.state.results.find(j=>j.id===record.id);if(existing)Object.assign(existing,record);}this.library=[...this.library.filter(r=>!(result.records||[]).some(x=>x.id===r.id)),...(result.records||[])];this.save();this.renderFilters();this.renderGallery();box.close();this.renderControls();this.updateHeader();this.note('Cartella di lavoro selezionata.');}catch(e){error.textContent=e.message;}},'dap-primary'));
list.querySelector('[aria-current]')?.scrollIntoView({block:'center'});
}catch(e){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: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 {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));
this.stopButton.disabled=!jobs.length&&!this.busy;this.totalProgress.hidden=!jobs.length;if(!jobs.length)return;
const points=batch.map(j=>this.jobProgress(j));this.totalFill.style.width=points.reduce((s,p)=>s+p.percent,0)/points.length+'%';this.totalBar.classList.toggle('indeterminate',points.some(p=>p.indeterminate));
const known=jobs.map(j=>this.jobProgress(j).remaining);this.totalText.textContent=`${batch.filter(j=>terminal.has(j.status)).length} / ${batch.length} completate · `+(known.every(n=>n!==null)?`~${Math.max(...known)}s rimanenti · stima`:'Calcolo in corso · tempo residuo non ancora disponibile');
}
async stop(){
this.stopRequested=true;const jobs=this.state.results.filter(j=>!terminal.has(j.status));const ids=[...new Set(jobs.map(j=>j.promptId).filter(Boolean))];this.stopButton.disabled=true;this.note('Interruzione richiesta…');
const results=await Promise.allSettled(ids.map(id=>this.bridge.cancel(id)));for(let i=0;i<ids.length;i++)if(results[i].status==='fulfilled')for(const job of jobs.filter(j=>j.promptId===ids[i]))if(!terminal.has(job.status)){job.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||!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');
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,(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.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)&&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.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(){
if(this.recovering||!this.bridge.history||this.closed)return;this.recovering=true;
try{const history=await this.bridge.history();if(this.closed)return;let changed=false;
for(const record of Object.values(history||{})){
const meta=record.prompt?.[3]?.extra_pnginfo?.workflow?.extra?.dogma_api_batch;if(meta?.session!==this.state.session)continue;
for(const saved of meta.jobs){let job=this.state.results.find(x=>x.id===saved.id);if(!job){job=copy(saved);this.state.results.push(job);changed=true;}if(job.imported)continue;job.promptId=record.prompt[1];const ui=record.outputs?.[job.output];if(ui?.images?.length){const result=ui.dogma_records?.[0]||{images:ui.images,status:'completed',finished:Date.now()};if(JSON.stringify(job.images)!==JSON.stringify(result.images))changed=true;Object.assign(job,result);}else if(record.status?.completed&&!terminal.has(job.status)){job.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;}
}
}
+88
View File
@@ -0,0 +1,88 @@
import { icon } from './dogma_api_icons.js?v=1.0.57';
import {savedFilename} from './dogma_api_core.js?v=1.0.60';
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 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=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;};
let scale=1,fitScale=1,x=0,y=0,width=0,height=0,drag=null,pinch=null;const points=new Map();
const zoom=document.createElement('input');zoom.type='number';zoom.min='1';zoom.max='1600';zoom.setAttribute('aria-label','Zoom percentuale');
const percent=document.createElement('label');percent.className='dap-zoom-value';percent.append(zoom,document.createTextNode('%'));
const update=()=>{surface.style.transform=`translate(${x}px,${y}px) scale(${scale})`;zoom.value=String(Math.round(scale*100));stage.classList.toggle('zoomed',scale>fitScale*1.01);};
const at=(next,cx=stage.clientWidth/2,cy=stage.clientHeight/2)=>{next=Math.max(Math.min(fitScale,.1)*.5,Math.min(16,next));const ratio=next/scale;x=cx-(cx-x)*ratio;y=cy-(cy-y)*ratio;scale=next;update();};
const fit=()=>{if(!width)return;fitScale=Math.min((stage.clientWidth-30)/width,(stage.clientHeight-30)/height);scale=fitScale;x=(stage.clientWidth-width*scale)/2;y=(stage.clientHeight-height*scale)/2;update();};
toolbar.append(button('zoomOut','Riduci zoom',()=>at(scale/1.3)),percent,button('zoomIn','Aumenta zoom',()=>at(scale*1.3)),button('fit','Adatta alla finestra',fit));
const one=button('single','Dimensione reale 100%',()=>at(1));one.append(document.createTextNode('100%'));toolbar.append(one);
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;
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.';};
zoom.onchange=()=>{const value=Number(zoom.value);if(Number.isFinite(value)&&value>0)at(value/100);};
stage.addEventListener('wheel',e=>{e.preventDefault();const r=stage.getBoundingClientRect();at(scale*Math.exp(-e.deltaY*.0017),e.clientX-r.left,e.clientY-r.top);},{passive:false});
stage.addEventListener('dblclick',e=>{const r=stage.getBoundingClientRect();if(Math.abs(scale-1)<.02)fit();else at(1,e.clientX-r.left,e.clientY-r.top);});
stage.addEventListener('pointerdown',e=>{
const rect=surface.getBoundingClientRect();const inImage=e.clientX>=rect.left&&e.clientX<=rect.right&&e.clientY>=rect.top&&e.clientY<=rect.bottom;
if(!inImage&&e.target===stage){drag={blank:true,startX:e.clientX,startY:e.clientY};return;}
stage.setPointerCapture(e.pointerId);points.set(e.pointerId,{x:e.clientX,y:e.clientY});drag={startX:e.clientX,startY:e.clientY,x,y};
if(points.size===2){const [a,b]=[...points.values()];pinch={distance:Math.hypot(a.x-b.x,a.y-b.y),scale};}
});
stage.addEventListener('pointermove',e=>{
if(points.has(e.pointerId))points.set(e.pointerId,{x:e.clientX,y:e.clientY});
if(points.size===2&&pinch){const [a,b]=[...points.values()],r=stage.getBoundingClientRect();at(pinch.scale*Math.hypot(a.x-b.x,a.y-b.y)/pinch.distance,(a.x+b.x)/2-r.left,(a.y+b.y)/2-r.top);return;}
if(drag&&!drag.blank&&points.size===1){x=drag.x+e.clientX-drag.startX;y=drag.y+e.clientY-drag.startY;update();}
});
const up=e=>{if(drag?.blank&&Math.hypot(e.clientX-drag.startX,e.clientY-drag.startY)<5)dialog.close();points.delete(e.pointerId);drag=null;pinch=null;};
stage.addEventListener('pointerup',up);stage.addEventListener('pointercancel',up);
stage.addEventListener('keydown',e=>{if(e.key==='+'||e.key==='='){e.preventDefault();at(scale*1.3);}if(e.key==='-'){e.preventDefault();at(scale/1.3);}if(e.key==='0'){e.preventDefault();fit();}});
const observer=new ResizeObserver(()=>{if(Math.abs(scale-fitScale)<.01)fit();});observer.observe(stage);dialog.addEventListener('close',()=>observer.disconnect(),{once:true});
}
+3
View File
@@ -67,4 +67,7 @@
.dg-studio .dg-upload-status{font-size:12px;margin:6px 0;overflow-wrap:anywhere;min-height:0}
.dg-studio .dg-file-drop[data-upload-state=error]>.dg-upload-status{color:#ffbb98}
.dg-studio .dg-file-drop[aria-busy=true]>.dg-drop-hint{color:#ffd2b8;border-style:solid}
.dg-studio .dg-folders a{display:flex;align-items:center;gap:8px;padding:10px 14px;margin:4px 6px 4px 0;border:1px solid #505256;border-radius:7px;background:#26282b;text-decoration:none;overflow-wrap:anywhere}
.dg-studio .dg-folders a:hover{border-color:var(--orange)}
.dg-studio [hidden]{display:none!important}
.dg-studio .dg-upload-toast{position:fixed;bottom:45px;left:50%;transform:translateX(-50%);z-index:20;max-width:80vw;padding:10px 18px;border:1px solid var(--orange);border-radius:7px;background:#30231d;box-shadow:0 4px 20px #0008;color:#fff}
+27 -14
View File
@@ -1,13 +1,13 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import {actionButton,decorateActions,setAction} from './dogma_h3_actions.js?v=studio-1-0-49';
import {assetField,referenceDrop,guardFileNavigation} from './dogma_h3_uploads.js?v=studio-1-0-49';
import { renderEditor, renderEditResults, renderEditTrials } from './dogma_h3_video_edit.js?v=studio-1-0-49';
import {actionButton,decorateActions,setAction} from './dogma_h3_actions.js?v=studio-1-0-50';
import {assetField,referenceDrop,guardFileNavigation} from './dogma_h3_uploads.js?v=studio-1-0-50';
import { renderEditor, renderEditResults, renderEditTrials } from './dogma_h3_video_edit.js?v=studio-1-0-50';
import { inputFile, viewURL, mediaPreview, releaseMedia } from './dogma_h3_media.js?v=studio-1-0-49';
import { inputFile, viewURL, mediaPreview, releaseMedia } from './dogma_h3_media.js?v=studio-1-0-50';
const ROOT=new URL('.',import.meta.url);
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_h3_director_v134.css?v=studio-1-0-49',ROOT);document.head.append(css);
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_h3_director_v134.css?v=studio-1-0-50',ROOT);document.head.append(css);
const clone=x=>JSON.parse(JSON.stringify(x));
const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
const button=actionButton;
@@ -40,6 +40,12 @@ export class DirectorStudio {
let stored;try{stored=JSON.parse(this.widget.value);}catch{stored={};}
this.config=merge(clone(this.catalog.defaults),stored);
this.config.session ||= crypto.randomUUID();
const access=this.catalog.access;
if(access?.local_files===false&&access.platform!=='nt'&&access.output_directory){
for(const [object,key]of [[this.config,'output_dir'],[this.config.edit,'final_output_dir']]){
if(/^(?:[a-z]:[\\/]|\\\\)/i.test(object[key]||''))object[key]=key==='final_output_dir'?'':access.output_directory;
}
}
}
family(task){return ['ref2v','edit'].includes(task)?'ref2v':'fl2v';}
turbo(task,steps){
@@ -97,10 +103,12 @@ export class DirectorStudio {
clearTimeout(this.saveTimer);this.saveTimer=setTimeout(()=>{try{app.graph?.change?.();}catch(e){console.warn('DOGMA: aggiornamento workflow',e);}},250);
}
async request(path,opts={}){
const headers=Object.fromEntries(new Headers(opts.headers||{}).entries());
if(path.startsWith('/dogma/h3/v2/')&&this.catalog?.access?.token)headers['X-Dogma-Access']=this.catalog.access.token;
const controller=new AbortController(),epoch=this.epoch;this.requests.add(controller);let expired=false;
const timeout=opts.body instanceof FormData?null:setTimeout(()=>{expired=true;controller.abort();},20000);
try{
const r=await api.fetchApi(path,{...opts,signal:opts.signal?AbortSignal.any([controller.signal,opts.signal]):controller.signal});
const r=await api.fetchApi(path,{...opts,headers,signal:opts.signal?AbortSignal.any([controller.signal,opts.signal]):controller.signal});
if(!r.ok)throw new Error(`Comfy: ${r.status} ${await r.text()}`);
const result=await r.json();
if(epoch!==this.epoch){const e=new Error('Pannello chiuso');e.name='AbortError';throw e;}
@@ -146,27 +154,32 @@ export class DirectorStudio {
this.save();
}
destroy(){this.close();clearTimeout(this.saveTimer);this.abort.abort();}
async browseFolders(scope='general'){
async browseFolders(scope='general',options={}){
if(this.folderPanel||!this.dialog)return;
const epoch=this.epoch,panel=el('section','','dg-folder-browser');this.folderPanel=panel;
panel.setAttribute('role','region');panel.setAttribute('aria-label','Scegli cartella output');
panel.setAttribute('role','region');panel.setAttribute('aria-label',options.viewOnly?'Cartella del video salvato':'Scegli cartella output');
const main=this.dialog.querySelector('main');main.prepend(panel);
const target=scope==='edit'?this.config.edit:this.config,key=scope==='edit'?'final_output_dir':'output_dir';
const input=el('input');input.type='text';input.value=target[key]||this.config.output_dir||'';input.setAttribute('aria-label','Percorso cartella');
const remote=this.catalog.access?.local_files===false;
const serverRoot=(this.catalog.access?.output_directory||'').replaceAll('\\','/').replace(/\/$/,'');
const preferred=(target[key]||this.config.output_dir||'').replaceAll('\\','/');
const initial=remote&&preferred!==serverRoot&&!preferred.startsWith(serverRoot+'/')?serverRoot:preferred;
const input=el('input');input.type='text';input.value=options.initialPath||initial;input.setAttribute('aria-label','Percorso cartella');
const info=el('p'),list=el('div','','dg-folders');let busy=false,current='';
const done=()=>{panel.remove();if(this.folderPanel===panel)this.folderPanel=null;};
const use=button('Usa questa cartella',async()=>{if(input.value!==current&&!await load(input.value))return;target[key]=current;this.save();done();this.render();},'dg-primary');use.disabled=true;
const use=button('Usa questa cartella',async()=>{if(input.value!==current&&!await load(input.value))return;target[key]=current;this.save();done();this.render();},'dg-primary');use.disabled=true;use.hidden=!!options.viewOnly;
const go=button('Vai',()=>load(input.value));
panel.append(el('h2','Cartella di salvataggio'),el('p','Naviga nelle cartelle del computer che esegue Comfy.'),input,go,button('Annulla',done),use,info,list);
panel.append(el('h2',options.viewOnly?'Cartella del video salvato':'Cartella di salvataggio'),el('p',remote?'Cartelle del server che esegue Comfy. La navigazione parte dalla sua cartella output.':'Naviga nelle cartelle del computer che esegue Comfy.'),input,go,button(options.viewOnly?'Chiudi':'Annulla',done),use,info,list);
const load=async path=>{
if(busy)return;busy=true;go.disabled=true;use.disabled=true;info.textContent='Caricamento cartelle…';list.replaceChildren();
try{
const r=await this.request('/dogma/h3/v2/folders?'+new URLSearchParams({path:path||''}));
const r=await this.request('/dogma/h3/v2/folders?'+new URLSearchParams({path:path||'',files:options.viewOnly?'1':'0'}));
if(epoch!==this.epoch||this.folderPanel!==panel)return;
current=r.path;input.value=current;info.textContent=r.truncated?'Mostrate le prime 500 cartelle. Puoi inserire il percorso completo.':'Seleziona una sottocartella oppure conferma questa cartella.';
current=r.path;input.value=current;info.textContent=r.truncated?'Mostrati i primi 500 elementi.':options.viewOnly?'File della cartella: clicca un nome per scaricarlo.':'Seleziona una sottocartella oppure conferma questa cartella.';
if(r.parent)list.append(button('↑ Cartella superiore',()=>load(r.parent)));
for(const d of r.drives||[])list.append(button(d.name,()=>load(d.path)));
for(const d of r.directories||[])list.append(button('📁 '+d.name,()=>load(d.path)));
for(const f of r.files||[]){const link=el('a');setAction(link,f.name+' · '+(f.size/1024/1024).toFixed(1)+' MB','download');link.href=viewURL(f.video);link.download=f.name;list.append(link);}
use.disabled=false;return true;
}catch(e){if(epoch===this.epoch&&this.folderPanel===panel&&e.name!=='AbortError')info.textContent=e.message;return false;}
finally{busy=false;go.disabled=false;}
@@ -254,7 +267,7 @@ export class DirectorStudio {
if(previewEnabled)required.push('ModelPreviewOverrideKJ');
if(action==='finish'&&this.config.task!=='edit'&&this.config.finish.stages!=='ultimate')required.push('MinimaxH3LatentUpscaler3D');
if(action==='finish'&&this.config.task!=='edit'&&this.config.finish.stages!=='latent')required.push('UltimateSDUpscaleNoUpscaleGuider');
const missing=required.filter(n=>!this.catalog.nodes.includes(n));if(missing.length)throw new Error('Installa dal Manager i nodi richiesti: '+missing.join(', '));
const missing=required.filter(n=>!this.catalog.nodes.includes(n));if(missing.length)throw new Error('Installa dal Manager: '+missing.map(n=>n==='MVEx_MaskToLatentSpace'?'MaskVidExperiments (nodo '+n+')':n).join(', '));
const q=await this.request('/queue');if(q.queue_running?.length||q.queue_pending?.length)throw new Error('Comfy sta già lavorando. Attendi la fine della coda.');
this.config.action=action;this.config.nonce++;this.save();
if(this.config.task==='edit'&&action==='draft'){delete this.data.edit_batch;this.promotedTrial=null;this.editFinishWaiting=null;}
+3 -3
View File
@@ -1,6 +1,6 @@
import {mediaPreview,inputFile} from './dogma_h3_media.js?v=studio-1-0-49';
import {frameIndex,frameTime,frameCount,stepTime} from './dogma_h3_timing.js?v=studio-1-0-49';
import {actionButton,setAction,loraLabel} from './dogma_h3_actions.js?v=studio-1-0-49';
import {mediaPreview,inputFile} from './dogma_h3_media.js?v=studio-1-0-50';
import {frameIndex,frameTime,frameCount,stepTime} from './dogma_h3_timing.js?v=studio-1-0-50';
import {actionButton,setAction,loraLabel} from './dogma_h3_actions.js?v=studio-1-0-50';
const el=(tag,text='')=>{const e=document.createElement(tag);e.textContent=text;return e;};
const button=actionButton;
const clamp=(v,a,b)=>Math.min(b,Math.max(a,v));
+1 -1
View File
@@ -1,4 +1,4 @@
import { mediaPreview } from './dogma_h3_media.js?v=studio-1-0-49';
import { mediaPreview } from './dogma_h3_media.js?v=studio-1-0-50';
const el=(tag,text='')=>{const e=document.createElement(tag);e.textContent=text;return e;};
export function maskKey(c){
+3 -3
View File
@@ -1,6 +1,6 @@
import {viewURL} from './dogma_h3_media.js?v=studio-1-0-49';
import {actionButton,setAction} from './dogma_h3_actions.js?v=studio-1-0-49';
import {RestitchHover} from './dogma_h3_restitch_hover.js?v=studio-1-0-49';
import {viewURL} from './dogma_h3_media.js?v=studio-1-0-50';
import {actionButton,setAction} from './dogma_h3_actions.js?v=studio-1-0-50';
import {RestitchHover} from './dogma_h3_restitch_hover.js?v=studio-1-0-50';
const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
const clamp=(x,a,b)=>Math.min(b,Math.max(a,x));
export class RestitchPanel{
+1 -1
View File
@@ -1,4 +1,4 @@
import {viewURL} from './dogma_h3_media.js?v=studio-1-0-49';
import {viewURL} from './dogma_h3_media.js?v=studio-1-0-50';
const clamp=(x,a,b)=>Math.min(b,Math.max(a,x));
const el=(tag,cls='')=>{const e=document.createElement(tag);e.className=cls;return e;};
export class RestitchHover{
+2 -2
View File
@@ -1,5 +1,5 @@
import {mediaPreview,inputFile} from './dogma_h3_media.js?v=studio-1-0-49';
import {actionButton,setAction} from './dogma_h3_actions.js?v=studio-1-0-49';
import {mediaPreview,inputFile} from './dogma_h3_media.js?v=studio-1-0-50';
import {actionButton,setAction} from './dogma_h3_actions.js?v=studio-1-0-50';
const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
const extensions={image:new Set(['png','jpg','jpeg','webp','gif','bmp','tif','tiff','avif','heic','heif']),video:new Set(['mp4','mov','m4v','mkv','webm','avi','mpeg','mpg','wmv','flv','ts','mts','m2ts','mxf','ogv','3gp'])};
export function mediaKind(file){const mime=String(file.type||'').toLowerCase();if(mime.startsWith('image/'))return 'image';if(mime.startsWith('video/'))return 'video';const ext=String(file.name||'').split('.').pop().toLowerCase();return Object.keys(extensions).find(kind=>extensions[kind].has(ext));}
+16 -9
View File
@@ -1,12 +1,12 @@
import { MaskEditor, compositeControls } from './dogma_h3_edit_mask.js?v=studio-1-0-49';
import { EditComparison } from './dogma_h3_edit_compare.js?v=studio-1-0-49';
import { MaskEditor, compositeControls } from './dogma_h3_edit_mask.js?v=studio-1-0-50';
import { EditComparison } from './dogma_h3_edit_compare.js?v=studio-1-0-50';
import { api } from '../../scripts/api.js';
import {actionButton,setAction,loraLabel} from './dogma_h3_actions.js?v=studio-1-0-49';
import {RestitchPanel} from './dogma_h3_restitch.js?v=studio-1-0-49';
import {assetField,referenceDrop} from './dogma_h3_uploads.js?v=studio-1-0-49';
import { inputFile, viewURL, mediaPreview } from './dogma_h3_media.js?v=studio-1-0-49';
import { frameIndex, frameTime, frameCount, snapSelection, stepTime, parseSelection } from './dogma_h3_timing.js?v=studio-1-0-49';
export { snapSelection } from './dogma_h3_timing.js?v=studio-1-0-49';
import {actionButton,setAction,loraLabel} from './dogma_h3_actions.js?v=studio-1-0-50';
import {RestitchPanel} from './dogma_h3_restitch.js?v=studio-1-0-50';
import {assetField,referenceDrop} from './dogma_h3_uploads.js?v=studio-1-0-50';
import { inputFile, viewURL, mediaPreview } from './dogma_h3_media.js?v=studio-1-0-50';
import { frameIndex, frameTime, frameCount, snapSelection, stepTime, parseSelection } from './dogma_h3_timing.js?v=studio-1-0-50';
export { snapSelection } from './dogma_h3_timing.js?v=studio-1-0-50';
const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
const button=actionButton;
@@ -131,7 +131,14 @@ export function renderEditResults(studio,body){
studio.editCompare=new EditComparison(studio,card,selected);
card.append(el('small',selected.saved_path));
if(selected.export_error)card.append(el('p','Il video completo è conservato nella sessione. La copia nella cartella scelta non è riuscita: '+selected.export_error));
card.append(button('Apri cartella del video salvato',async()=>{try{await studio.request('/dogma/h3/v2/open-folder',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session:studio.config.session,id:selected.id})});}catch(e){studio.fail(e.message);}}));
card.append(button('Apri cartella del video salvato',async()=>{try{
if(studio.catalog.access?.open_folder===false){
const base=studio.catalog.access.output_directory.replaceAll('\\','/');
const saved=String(selected.saved_path||'').replaceAll('\\','/'),directory=saved.slice(0,saved.lastIndexOf('/'));
const initialPath=directory===base||directory.startsWith(base+'/')?directory:base+'/'+(selected.video.subfolder||'');
await studio.browseFolders('edit',{initialPath,viewOnly:true});
}else await studio.request('/dogma/h3/v2/open-folder',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session:studio.config.session,id:selected.id})});
}catch(e){studio.fail(e.message);}}));
const copy=button('Copia questo finale nella cartella scelta',async()=>{if(copy.disabled)return;copy.disabled=true;try{const result=await studio.request('/dogma/h3/v2/edit/export-copy',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session:studio.config.session,id:selected.id,output_dir:studio.config.edit.final_output_dir||studio.config.output_dir})});for(const item of studio.data.edits||[])if(item.id===result.id){item.saved_path=result.saved_path;delete item.export_error;}studio.data.status='done';studio.data.message='Video completo copiato nella cartella scelta.';studio.render();}catch(e){studio.fail(e.message);}finally{copy.disabled=false;}});copy.disabled=studio.pending;card.append(copy);
card.append(el('small','La copia usa il video già completato, senza ricalcolarlo. Destinazione: '+(studio.config.edit.final_output_dir||studio.config.output_dir||'cartella output Comfy')));
card.append(button('Cambia cartella di destinazione…',()=>studio.browseFolders('edit')));