Compare commits

...
17 Commits
Author SHA1 Message Date
axior a9aa91bb0a DOGMA 1.0.58: standalone Seedance video fix [skip ci] 2026-11-25 19:44:58 +01:00
axior 4b51685cfd DOGMA 1.0.57: API Platform V5 selective video stutter repair [skip ci] 2026-11-25 19:20:36 +01:00
axior 3e51759574 DOGMA 1.0.56: API Platform V4 parallel API image and video workflow [skip ci] 2026-11-25 15:23:39 +01:00
axior a6895201c8 DOGMA 1.0.55: API Platform V3 parallel API image and video workflow [skip ci] 2026-11-23 23:25:07 +01:00
axior c931fb843e DOGMA 1.0.54: API Platform V2 parallel API image and video workflow [skip ci] 2026-11-23 22:31:39 +01:00
axior 59e2883afe DOGMA 1.0.52: Add clear HDR colour controls and native-resolution upscale bypass [skip ci] 2026-11-17 13:38:08 +01:00
axior 42a976ae63 DOGMA 1.0.51: Add bounded-memory HDR finishing and recoverable export [skip ci] 2026-11-14 00:07:54 +01:00
axior 9d3241a272 DOGMA 1.0.50: Fix proxy restitch access and unify desktop and server folder controls [skip ci] 2026-11-13 17:50:59 +01:00
axior 463878c802 DOGMA 1.0.49: Add media drag and drop and synchronized floating restitch detail [skip ci] 2026-11-13 16:28:10 +01:00
axior 91e692ced7 DOGMA 1.0.48: Add synchronized restitch previews, custom mattes, action icons and edit LoRA variants [skip ci] 2026-11-13 15:58:55 +01:00
axior 70641ca408 DOGMA 1.0.47: Fix frame cadence, preserve source colour and separate generation and final mattes [skip ci] 2026-11-13 14:50:23 +01:00
axior ad83bb4917 DOGMA 1.0.46: Develop approved edits, validate masks and save finals to the chosen folder [skip ci] 2026-11-13 13:30:27 +01:00
axior 59ac90acc5 DOGMA 1.0.45: Add fast edit trials, immediate promotion and looping AB comparison [skip ci] 2026-11-12 21:16:32 +01:00
axior e694bead16 DOGMA 1.0.43: Add native masked video edits, mask overlay preview and 512px edit trials [skip ci] 2026-11-12 20:07:11 +01:00
axior 7b4b2ebe65 DOGMA 1.0.41: Fix media preview paths and free edit intervals [skip ci] 2026-11-12 18:51:49 +01:00
axior a3fda9f153 DOGMA 1.0.40: H3 Director Video Edit, visual timeline, source-size compositing and prompt scroll fix [skip ci] 2026-11-12 17:08:32 +01:00
axior 9814f66aa7 DOGMA 1.0.39: H3 Director V2 fullscreen studio, persistent trials and staged finishing [skip ci] 2026-10-31 15:43:03 +01:00
62 changed files with 6035 additions and 103 deletions
+18
View File
@@ -0,0 +1,18 @@
# DOGMA Nodes 1.0.40 — H3 Director Video Edit
Adds a fourth Director mode for a bounded edit of a long source clip. The editor
offers draggable timeline handles, thumbnails, live seek, zoom and additional
references. H3 Ref2VA generates only the selection at the original canvas size
(temporary padding is cropped), without upscale, RIFE or staged finishing.
The edited selection is composited into a full-length export with original audio.
The source video is re-encoded; it is not a bit-exact stream copy. Native H3 is
24 fps; source timestamps are retained without motion interpolation. Selection
lengths follow the supported frame grid and available reference budget.
Adding test prompts preserves scroll and focuses the new prompt. Existing
Director modes and node IDs remain available. No additional custom-node pack.
Requires FFmpeg on PATH or imageio-ffmpeg, and the existing H3 dependencies.
Validation: nine media/integration tests, 291 timeline constraints, browser
interaction checks. Full H3 GPU inference and visual seam quality remain untested.
Use DOGMA_H3_DIRECTOR_V4.json. Restart ComfyUI and reload the browser after updating.
+3
View File
@@ -0,0 +1,3 @@
DOGMA Nodes 1.0.41
Fix previews of uploaded media in subfolders. Allow manually entered edit times with comma or dot decimals. Select intervals down to one source frame; pad H3 temporal inputs and trim the generated tail during composition.
+14
View File
@@ -0,0 +1,14 @@
DOGMA Nodes 1.0.43
Includes the preview/timing/comparison fixes prepared for 1.0.42.
- Optional user-uploaded B/W video mask, matching the full source. White regenerates, black preserves.
- Source-pixel grow/contract and Gaussian feather, shared by mask preparation and final composition.
- Native H3 masked generation: source-seeded AV latent plus nested noise mask, with Ref2VA conditioning retained. Uses MaskVidExperiments mask geometry; no global model patches.
- Asynchronous CPU overlay video preview, cache invalidation after mask, source, selection or settings changes.
- Edit trials up to 512 px, multiple seeds or prompt variants; final original-size regeneration from the selected trial's saved configuration.
- Original audio retained in final output; trials and mask previews are silent.
Requires current native H3 masking support in ComfyUI and MVEx_MaskToLatentSpace from MaskVidExperiments. This node is present in the user's running ComfyUI.
Validation: real mask processing and export tests, installed MaskVidExperiments CPU temporal/spatial mapping, source/reference/noise-mask wiring with a deterministic H3 stand-in, frozen trial settings, 512x384 trial to 640x480 final, isolated browser tests. No new GPU H3 generation was run.
+13
View File
@@ -0,0 +1,13 @@
DOGMA Nodes 1.0.45
Includes the full-duration rounding and visible overlay-validation fixes from 1.0.44.
- Fast edit trials use installed Ref2Video Turbo 4-step sampling; final quality settings remain separate and frozen in the selected trial.
- Trial sizes 256/384/512 px; optional live previews are disabled by default for trials.
- Source, references, text conditioning and native mask preparation are reused for identical prompts across seed trials. Reference images/video are reduced for draft preparation only.
- Selecting a completed trial during a batch abandons the unfinished trial at the next local checkpoint, skips the remaining trials and immediately regenerates the selected trial at original size. No global Comfy interrupt is used.
- Source and comparison playback loop by default; one click restarts playback after a non-looping finish.
- Independent A/B selectors compare original, trials and completed versions from the same source with synchronized source-time offsets. A or B can be selected for the final render.
- A newly completed trial no longer replaces a trial the user is already inspecting.
Validation uses real file processing and deterministic CPU H3 stand-ins, including interruption during sampling, exact frozen selection, separate 4/20-step settings, preparation reuse and browser loop/promotion/A-B tests. No new GPU H3 performance benchmark was run.
+19
View File
@@ -0,0 +1,19 @@
DOGMA Nodes 1.0.46
- Explicit original-size edit sampling: match selected trial (default), Turbo Ref2Video 4-step, or standard without Turbo with a chosen step count. Existing saved trials are supported.
- Final mode reaches both the normal finish action and immediate promotion during an active trial batch, while source/prompt/seed/references/mask stay frozen to the chosen trial.
- Save complete effective sampling settings with new trials and recover the known Turbo preset for 1.0.45 trial records.
- Validate the native joint AV edit mask before sampling: grid shape, finite range, nonempty video edit area and zero audio mask. Record the sampled mask coverage in the output metadata.
- Preserve an existing video mask when audio locking is requested. This fixes a fragile generic sampler branch; current edit calls already keep audio locking off and use the native audio mask.
- Show each saved final's originating trial, seed and sampling mode; distinguish historical outputs while a new final is still running.
- Develop the approved edit using its saved generated AV latents, a learned latent upscale and partial denoise under the original native edit mask. Older trials explicitly encode their approved video; missing new checkpoints stop without falling back to the source.
- Use the approved trial as Video 1 in guided development, at its existing reference resolution, instead of reintroducing the source wall or inflating reference tokens.
- Default to preserve mode: resize the approved edited video inside its saved mask without new inference or applying feather/fades twice. Keep H3 development and source-based regeneration as explicit options.
- Save new trial checkpoints and file fingerprints. Retain full prompt/seed/source/reference/mask provenance on each final.
- Always copy completed edit finals to the selected destination (the Comfy output root when empty). Show the path and allow opening the folder or copying a completed final elsewhere without regenerating it.
- Commit manually typed folder paths in one confirmation and propagate the latest destination when promoting a trial during an active batch.
- Include edit results in the open-folder lookup; update displayed paths when an existing final is copied.
Validation: native mask/export regressions, explicit final-mode switching, method/destination propagation during active-batch promotion, production sample() handoff with audio locking off/on and missing-mask rejection, isolated browser Standard and preserve finals and copy controls. A real 1664x1248 H3 Turbo 4-step guided render from the user's legacy approved trial completed; the native mask was present. Both preserve and guided exports retain all 97 source timestamps and unchanged audio packets. GPU guided development took 213.7 seconds in the isolated verification, including preparation and export. The guided result still introduced wall artifacts: it is optional, not the default. CPU neural stand-ins were used for the wider regression matrix; Standard sampling was not separately rerun on the real GPU.
Guided refinement can change generated details. Preserve mode keeps the approved appearance by resizing pixels; it does not synthesize new high-resolution detail.
+13
View File
@@ -0,0 +1,13 @@
DOGMA Nodes 1.0.47
- Fix frame content, not just timestamps: exact-timestamp NUT intermediates and nearest-frame matching replace millisecond Matroska / floor matching, which repeated and skipped every third frame at 24 fps.
- Restitch by decoding each original frame exactly once. Preserve its timestamp, time base and protected native colour samples; replace only the selected matte area. Export H264 losslessly, retaining source audio packets where MP4 supports their codec. Files are larger than the previous CRF16 export.
- Keep raw generated frames for new trials. Recover 1.0.46 trials from their saved generated latents using VAE decode only; do not rerun H3 or use a preview that already lost frames. Update the recovered preview pointer. Older trials without saved latents stop explicitly instead of falling back to the original.
- Separate H3 generation-mask grow/feather from the final compositing matte. Default final matte uses the uploaded mask with 0-pixel grow and 8-pixel inward feather, preserving black window bars and carriage geometry even when H3 needs a larger generation area. Original shared-mask behaviour remains an explicit option.
- Preview either the H3 generation area or the exact final compositing area. Carry final matte settings through ordinary and early trial selection, without altering the frozen source/prompt/seed/reference/generation mask. Preserve mode can change final matte settings without new H3 sampling.
- Add independent H3 processing resolution: native 768-short-edge / about 1 MP (1024x768 at 4:3), chosen-trial resolution, or original resolution explicitly marked experimental. The exported master always retains the source geometry and timing. Size references consistently with the processing canvas.
- Record processing/export sizes, final matte settings, lossless encoding and file fingerprints. Clearly label older finals that lack these export fixes.
Validation: production-path CPU edit regressions (including masked/unmasked edit, saved-trial promotion, Turbo/standard selection, raw-latent recovery and no-sampling preservation); frame-identity tests for all 97 frames, VFR and fractional rates; 10-bit YUV and grayscale sources with nonzero timestamp origins; expanded generation mask with protected frame geometry; real user-trial recovery and restitch of all 97 original frames, zero changed protected RGB pixels, exact protected YUV samples and unchanged audio packets. Both mask preview areas were exercised in an isolated browser with the real uploaded mask. No live installation or publication is performed by preparing this release.
Visual limits: the earlier diagnostic export still showed the expanded matte over the carriage. The new separate matte addresses that compositing defect; the final edge remains adjustable. A real 1024x768 Turbo 4-step source-based edit completed with the native mask present but still retained wall/grid artifacts. Native resolution is not a guaranteed cure for instruction adherence. Preserve mode retains the selected generation's appearance, including any flaws and low-resolution detail. H3 development/regeneration can change or fail the requested edit. No test result here is a claim of artistic approval of the wall replacement.
+14
View File
@@ -0,0 +1,14 @@
DOGMA Nodes 1.0.48
- Optional collapsed restitch refinement below completed masked edits: six named presets plus one user-defined variant with grow/contract and inward-feather controls.
- All seven live views share a single browser video decode and frame clock. They loop and scrub together. Edits stay in the preview until Apply is selected. The grid is released when closed.
- Build one small temporary preview atlas, not seven encoded videos. Live grow/feather changes require no server render. Retain one raw generated segment per new H3 edit; preserve finals reuse the trial segment. Cache is shared across variants and repeated openings.
- Apply the selected contour at full source resolution without H3 inference. Replace the same completed master and its unchanged exported copy atomically, retaining source timestamps, protected samples and original audio. No per-preset final copies or new gallery versions. Reject stale requests, invalid settings and external file modifications.
- Match live contour offsets with distance-based full-resolution restitch. Preview sampling is deliberately reduced to 320-pixel-long-edge images; exact edges and encoding are evaluated in the original-size final.
- Play buttons toggle pause and resume in the source selection and synchronized comparison. Remove the redundant separate pause button; preserve restart/loop and cancellation behavior.
- Add consistent orange SVG action icons throughout the workflow: loading, generation, selection, comparison, frame stepping, folders, save/download, removal, recovery, LoRA stacks and restitch refinement. Maintain text labels and primary-action hierarchy.
- Expose additional LoRA stacks and weights on every edit variant. Add LoRA comparison with the same common prompt and seed; optional text can carry character trigger words. Common LoRAs remain available. The chosen combined stack is frozen with the trial and retained for the final even after later UI changes. A blank variant can use the common prompt as a baseline.
Validation: full CPU production-path edit regressions; distinct same-seed LoRA variants and selected-stack promotion; exact frame identity/VFR checks; real 97-frame masked source restitch with custom settings, unchanged protected colour planes, source timestamps and coherent master/export hashes; stale/invalid request rejection and no duplicate finals. Real cold preparation measured 2.92 seconds on the user's 4.04-second clip. The browser displayed all seven synchronized views in 3.24 seconds, exercised custom controls, applied a choice, reopened the cache and verified play/pause in selection/comparison. One temporary atlas was about 3.4 MB. This timing is measured for that clip and machine, not a universal limit for longer videos.
Older regenerated/guided finals whose raw generated segment was deleted by earlier versions must be prepared again before this refinement is available. Preserve finals can reuse an existing saved trial segment. Refinement changes the restitch; it does not repair flaws already present in the generated wall. Native model quality and training-resolution findings from 1.0.47 still apply. No new H3 sampling or character-weight downloads were performed for this UX release.
+12
View File
@@ -0,0 +1,12 @@
DOGMA Nodes 1.0.49
- Add drag and drop to the source video, uploaded mask, first/last images and image/video reference slots. Retain picker buttons. File drops outside these targets cannot navigate away from the workflow.
- Accept ordered batches of mixed image/video references in the reference section, reusing empty matching slots. Validate type, nonempty content, single-slot counts and reference limits before upload. Nested slot drops do not also add references. Report partial batch failures; preserve completed uploads and previous selections on invalid drops. Ignore late responses after session changes or closure.
- Remove duplicated plus signs beside SVG icons. Use Aggiungi immagine / Aggiungi video, direct multi-file pickers, clear previous/next-frame and zoom labels.
- Restitch preset hover opens a large floating video preview, including the custom preset. Damped cursor following, viewport bounds, short flyby delay, smooth switching, pointer-transparent interaction, keyboard focus and Escape dismissal; honor reduced-motion settings. Close/panel navigation releases the detail decoder and renderer.
- Keep the existing 320px shared grid preparation. On first hover, prepare one additional shared 960px-long-edge temporary atlas (or source size if smaller), rather than magnifying only the thumbnail. Display the actual preview resolution and loading state. Every preset reuses the same detail data and renderer; no encoded video per preset or duplicate final. Detail stays synchronized with the grid, loop, seek and pause. Until detail loads, show the existing preview. Both preview resolutions approximate the full-resolution matte; the saved final still uses original-resolution restitch.
- Retain all 1.0.48 LoRA, timing, colour preservation, restitch and export behavior. No model sampling changes, new dependencies or node identifiers.
Validation: JavaScript/Python syntax; 13 browser integration checks for upload validation, picker parity, ordered mixed batches, nested drops, partial failures, busy state, stale responses, directories and navigation guards. Isolated real-media browser check of all seven synchronized previews, 960x720 detail, viewport-edge placement, pause, preset switching, Escape and cleanup. Real 97-frame preview atlas dimensions and timestamps verified at both resolutions. Live Comfy workflow, source media and saved final remain untouched. No H3 generation, installation or publication performed by preparation.
The first detailed preview requires a separate one-time preparation; it is not included in the under-five-second grid timing previously measured for the 4-second example. The detail atlas is cached once per edit in Comfy temporary storage (about 26.7 MB for the tested 4.04-second clip), not in the chosen export directory. Existing generated-wall quality limitations still apply.
+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.
+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.
+75
View File
@@ -147,3 +147,78 @@ 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.
+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
+171 -43
View File
@@ -14,28 +14,33 @@ import shutil
_STATE_LOCK=threading.RLock()
from pathlib import Path
from .dogma_h3_video_edit import edit_defaults, run_edit
def defaults():
return dict(version=2, session=str(uuid.uuid4()), action="draft", selected="", nonce=0,
generate_audio=True, output_dir="", job="DOGMA", task="i2v", exploration="seeds", count=2, seed=64,
prompt="", variants=[{"text":"", "loras":[]}], trial_loras={},
first="", last="", refs=[], common_loras=[], seconds=5,
auto_aspect=True, long_edge=672, width=672, height=384, sound=True,
first="", last="", refs=[], common_loras=[], seconds=5, edit=edit_defaults(),
auto_aspect=True, long_edge=512, width=512, height=288, sound=True,
models={"i2v":"minimax_h3_fl2va_pruned_int8_convrot.safetensors",
"t2v":"minimax_h3_fl2va_pruned_int8_convrot.safetensors", "ref2v":"minimax_h3_ref2va_pruned_int8_convrot.safetensors", "clip":"qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
"vae":"minimax_h3_video_vae_fp16.safetensors", "audio":"minimax_h3_audio_vae_fp32.safetensors"},
draft={"turbo":"minimax_h3_fl2v_turbo_4step_v1.0_768p_comfyui_bf16.safetensors",
"turbo_strength":1., "steps":4, "sampler":"euler", "scheduler":"simple",
"shift_video":12., "shift_audio":3., "lying":0., "lying_start":.1,"lying_end":.9},
finish={"stages":"both", "resolution":"2k", "scale":2., "turbo":"minimax_h3_fl2v_turbo_8step_v1.0_comfyui_bf16.safetensors",
develop={"mode":"guided", "long_edge":960, "turbo":"", "turbo_strength":1.,
"steps":20, "sampler":"res_multistep", "scheduler":"simple", "denoise":.65,
"shift_video":12., "shift_audio":3., "lying":-.01, "lying_start":.1, "lying_end":.9},
selected_development="",
finish={"stages":"both", "resolution":"2k", "scale":2., "turbo":"",
"turbo_strength":1., "sampler":"er_sde", "scheduler":"simple", "steps":8,
"sigmas":"0.9035, 0.8000, 0.6316, 0.3158, 0.0000", "denoise":.35,
"shift_video":12.,"shift_audio":3.,"lying":0.,"lying_start":.1,"lying_end":.9,
"upscaler":"minimax_h3_latent_upscaler_3d_bf16.safetensors",
"ultimate_scale":1., "tile_width":768,"tile_height":512,"tile_padding":64,
"mask_blur":16,"ultimate_steps":8,"ultimate_denoise":.14,
"ultimate_model":"minimax_h3_fl2va_pruned_int8_convrot.safetensors",
"ultimate_model":"minimax_h3_ref2va_pruned_int8_convrot.safetensors", "ultimate_sampler":"res_multistep", "ultimate_seed":42, "refine_seed":444,
"ultimate_turbo":"minimax_h3_fl2v_turbo_8step_v1.0_comfyui_bf16.safetensors",
"ultimate_strength":1.},
rife={"enabled":True,"fps":48,"model":"flownet.pkl","scale":1.,"batch_size":1,"fp16":True},
@@ -57,9 +62,10 @@ def parse_config(raw):
if c['finish']['resolution'] not in ('1k','2k','3k','4k'):
raise ValueError('Risoluzione: scegli 1K, 2K, 3K o 4K.')
c['session']=str(uuid.UUID(c['session']))
if c['action'] not in ('draft','finish'): raise ValueError('Azione non valida.')
if c['task'] not in ('i2v','t2v','ref2v'): raise ValueError('Scegli I2V, T2V o Ref2Video.')
if c['exploration'] not in ('seeds','prompts'): raise ValueError('Modalità provini non valida.')
if c['action'] not in ('draft','develop','finish'): raise ValueError('Azione non valida.')
if c['task'] not in ('i2v','t2v','ref2v','edit'): raise ValueError('Scegli I2V, T2V, Ref2Video o Video Edit.')
if c['task']=='edit' and c['action'] not in ('draft','finish'): raise ValueError('Video Edit usa provini e rigenerazione originale.')
if c['exploration'] not in ('seeds','prompts','loras'): raise ValueError('Modalità provini non valida.')
if not 1<=int(c['count'])<=10: raise ValueError('Scegli da 1 a 10 provini.')
if not 0.2<=float(c['seconds'])<=15: raise ValueError('Durata: da 0,2 a 15 secondi.')
if not 256<=int(c['long_edge'])<=1536: raise ValueError('Lato lungo provini: 256–1536 px.')
@@ -72,7 +78,10 @@ def parse_config(raw):
if not 1<=int(c['rife']['batch_size'])<=32: raise ValueError('RIFE batch: da 1 a 32.')
if float(c['rife']['scale']) not in (.25,.5,1.,2.,4.): raise ValueError('Scala RIFE non valida.')
if not 0<=int(c['seed'])<2**53: raise ValueError('Seed fuori intervallo.')
for phase in ('draft','finish'):
if c['develop']['mode'] not in ('guided','native'): raise ValueError('Modalità sviluppo non valida.')
if not 512<=int(c['develop']['long_edge'])<=1536: raise ValueError('Sviluppo: lato lungo 512–1536 px.')
if not 0<float(c['develop']['denoise'])<1: raise ValueError('Sviluppo guidato: denoise maggiore di 0 e minore di 1.')
for phase in ('draft','develop','finish'):
s=c[phase]
if not 0<=float(s['lying_start'])<=float(s['lying_end'])<=1: raise ValueError('Intervallo Lying Sigma non valido.')
if not 1<=int(s['steps'])<=100: raise ValueError('Step: da 1 a 100.')
@@ -88,11 +97,12 @@ def parse_config(raw):
def make_plan(c):
common=c['prompt'].strip()
if c['exploration']=='prompts':
if c['exploration'] in ('prompts','loras'):
variants=c['variants']
if not 1<=len(variants)<=10: raise ValueError('Inserisci da 1 a 10 schede prompt.')
if any(not v.get('text','').strip() for v in variants): raise ValueError('Ogni scheda prompt deve contenere testo.')
return [dict(prompt='\n\n'.join(x for x in (common,v['text'].strip()) if x),
if c['exploration']=='prompts' and not common and any(not v.get('text','').strip() for v in variants): raise ValueError('Ogni scheda prompt deve contenere testo oppure usare le istruzioni comuni.')
if c['exploration']=='loras' and not common:raise ValueError('Scrivi le istruzioni di edit comuni prima di confrontare le LoRA.')
return [dict(prompt='\n\n'.join(x for x in (common,v.get('text','').strip()) if x),
seed=int(c['seed']),loras=c['common_loras']+v.get('loras',[])) for v in variants]
if not common: raise ValueError('Scrivi il prompt prima di generare.')
return [dict(prompt=common,seed=(int(c['seed'])+i)%(2**53-1),
@@ -154,10 +164,34 @@ def export_file(path,c):
if not directory.is_absolute(): raise ValueError('La cartella output deve avere un percorso assoluto.')
directory.mkdir(parents=True,exist_ok=True)
dest=directory/(path.stem+'_'+uuid.uuid4().hex[:8]+path.suffix)
shutil.copy2(path,dest)
temp=dest.with_suffix(dest.suffix+'.tmp')
try:
shutil.copy2(path,temp)
if temp.stat().st_size!=Path(path).stat().st_size:raise OSError('Copia del video finale incompleta.')
temp.replace(dest)
finally:temp.unlink(missing_ok=True)
return str(dest.resolve())
def export_saved_edit(data):
import folder_paths
with _STATE_LOCK:
st=state(data['session'])
if st.get('status')=='running':raise ValueError('Attendi la fine della lavorazione prima di ricopiare un finale.')
item=next((x for x in st.get('edits',[]) if x.get('id')==data.get('id') and x.get('complete')),None)
if not item:raise ValueError('Finale completo non disponibile.')
f=item['video'];source=(Path(folder_paths.get_output_directory())/f.get('subfolder','')/f['filename']).resolve()
if not source.is_relative_to(manifest_root(data['session']).resolve()) or not source.is_file():
raise ValueError('File finale non disponibile. Non verrà esportato il sorgente al suo posto.')
destination=data.get('output_dir','').strip() or folder_paths.get_output_directory()
saved=export_file(source,dict(output_dir=destination))
item['saved_path']=saved;item.pop('export_error',None);item.setdefault('exports',[]).append(saved)
if st.get('message','').startswith('Video pronto e conservato nella sessione; copia'):
st.update(status='done',message='Video completo copiato nella cartella scelta.')
write_json(manifest_root(data['session'])/'session.json',st)
return dict(saved_path=saved,id=item['id'])
def call(name,uid='dogma',**kwargs):
import nodes
cls=nodes.NODE_CLASS_MAPPINGS.get(name)
@@ -231,7 +265,7 @@ def condition(c,a,res,prompt,w,h,n):
def load_resources(c):
import nodes
m=c['models']; name=m[c['task']]
m=c['models']; name=m['ref2v' if c['task']=='edit' else c['task']]
if not name: raise ValueError(f'Seleziona il modello {c["task"]} nelle impostazioni avanzate.')
return {'model':nodes.UNETLoader().load_unet(name,'default')[0],
'clip':nodes.CLIPLoader().load_clip(m['clip'],'minimax','default')[0],
@@ -248,7 +282,8 @@ def prepare_model(res,c,trial,phase,uid):
for l in stack:
if l.get('name') and l.get('enabled',True) and float(l.get('strength',1))!=0:
model=nodes.LoraLoaderModelOnly().load_lora_model_only(model,l['name'],float(l.get('strength',1)))[0]
model=MiniMaxH3SigmaShift.execute(model,float(s['shift_video']),float(s['shift_audio']))[0]
if not s.get('native_shift',False):
model=MiniMaxH3SigmaShift.execute(model,float(s['shift_video']),float(s['shift_audio']))[0]
p=c['preview']
if p['enabled']:
model=call('ModelPreviewOverrideKJ',uid,model=model,max_resolution=int(p['max_resolution']),
@@ -269,6 +304,9 @@ def sampler_for(s):
def sample(model,cond,latent,s,seed,manual=False,progress=None):
import torch
if s.get('require_edit_mask'):
from .dogma_h3_edit_mask import inspect_native_mask
inspect_native_mask(latent)
from comfy_extras.nodes_custom_sampler import BasicScheduler,Guider_Basic,Noise_RandomNoise,SamplerCustomAdvanced
guider=Guider_Basic(model); guider.set_conds(cond)
if manual and s.get('sigmas','').strip():
@@ -286,9 +324,22 @@ def sample(model,cond,latent,s,seed,manual=False,progress=None):
def callback(step,x0,x,total):
if preview: preview(step,x0,x,total)
progress(step+1,total)
result=guider.sample(Noise_RandomNoise(seed).generate_noise(latent),tensor,sampler_for(s),sigmas,
noise=Noise_RandomNoise(seed).generate_noise(latent)
if s.get('lock_audio'):
from comfy.nested_tensor import NestedTensor
video,audio=tensor.unbind(); nv,na=noise.unbind()
noise=NestedTensor([nv,torch.zeros_like(na)])
existing_mask=latent.get('noise_mask')
video_mask=existing_mask.unbind()[0] if existing_mask is not None else torch.ones_like(video)
latent['noise_mask']=NestedTensor([video_mask,torch.zeros_like(audio)])
if s.get('require_edit_mask'):
from .dogma_h3_edit_mask import inspect_native_mask
inspect_native_mask(latent)
result=guider.sample(noise,tensor,sampler_for(s),sigmas,
denoise_mask=latent.get('noise_mask'),callback=callback,
disable_pbar=not comfy.utils.PROGRESS_BAR_ENABLED,seed=seed)
if s.get('lock_audio'):
result=NestedTensor([result.unbind()[0],audio.to(result.unbind()[1].device)])
latent['samples']=result.to(comfy.model_management.intermediate_device())
latent.pop('downscale_ratio_spacial',None);latent.pop('downscale_ratio_temporal',None)
return latent
@@ -354,10 +405,11 @@ class DOGMAH3DirectorEngineV2:
import torch
from .dogma_h3_director_v133 import pack,unpack
c=parse_config(sessione); root=manifest_root(c['session']); root.mkdir(parents=True,exist_ok=True)
st=state(c['session']); st['engine']=str(unique_id); st['session']=c['session']
st=state(c['session']); st['engine']=str(unique_id); st['session']=c['session'];st['action']=c['action']
def update(status,message,**extra):
from server import PromptServer
st.update(status=status,message=message,action=c['action'],progress=None,**extra)
values=dict(status=status,message=message,action=st.get('action',c['action']),progress=None)
values.update(extra);st.update(values)
write_json(root/'session.json',st)
PromptServer.instance.send_sync('dogma.h3.v2',st)
def progress(step,total):
@@ -366,13 +418,15 @@ class DOGMAH3DirectorEngineV2:
PromptServer.instance.send_sync('dogma.h3.v2.progress',{'session':c['session'],'engine':str(unique_id),'step':step,'total':total})
try:
update('running','Preparazione risorse…')
if c['action']=='draft':
if c['task']=='edit':
run_edit(c,root,st,update,progress,unique_id)
elif c['action']=='draft':
plan=make_plan(c); a=assets(c)
first=next((x for x in [a['first'],a['last'],*a['images'].values(),*a['videos'].values()] if x is not None),None)
w,h=dimensions(c,(first.shape[2],first.shape[1]) if first is not None else None)
n=frames(c['seconds']); res=load_resources(c)
run=str(uuid.uuid4()); dest=root/run; dest.mkdir()
update('running','Preparazione prompt…',candidates=[],finals=[],run=run,width=w,height=h,frames=n,total_trials=len(plan))
update('running','Preparazione prompt…',candidates=[],developments=[],finals=[],run=run,width=w,height=h,frames=n,total_trials=len(plan))
# Encode once for shared prompts; different prompt cards preserve all paragraphs.
encoded={}
for i,p in enumerate(plan):
@@ -395,10 +449,56 @@ class DOGMAH3DirectorEngineV2:
st['candidates'].append(candidate)
update('running',f'Provino {i+1}/{len(plan)} pronto')
del result,images,audio,model
update('ready','Provini pronti. Scegli quello da finalizzare.',active=None)
else:
update('ready','Bozze pronte. Scegli quale sviluppare in qualità.',active=None)
elif c['action']=='develop':
candidate=next((p for p in st.get('candidates',[]) if p['id']==c['selected']),None)
if candidate is None: raise ValueError('Seleziona un provino disponibile nella galleria.')
if candidate is None: raise ValueError('Scegli una bozza da sviluppare.')
frozen=parse_config(candidate['config']); frozen['develop']=copy.deepcopy(c['develop']); frozen['preview']=c['preview']
# No Turbo from the draft is inherited. Only the chosen additional LoRAs persist.
d=frozen['develop']; frozen['long_edge']=int(d['long_edge'])
res=load_resources(frozen); a=assets(frozen)
w,h=dimensions(dict(auto_aspect=True,long_edge=d['long_edge']), (candidate['width'],candidate['height']))
n=candidate['frames']; folder=root/'developments'/str(uuid.uuid4()); folder.mkdir(parents=True)
update('running','Sviluppo · preparazione alla risoluzione di qualità')
cond,empty=condition(frozen,a,res,candidate['prompt'],w,h,n)
settings=copy.deepcopy(d)
if d['mode']=='guided':
from comfy.nested_tensor import NestedTensor
path=(root/candidate['latent']).resolve()
if not path.is_relative_to(root.resolve()): raise ValueError('Percorso latenti non valido.')
saved=unpack(torch.load(path,map_location='cpu',weights_only=True))
video,audio_lat=saved['samples'].unbind()
update('running','Sviluppo · trasferimento dei latenti della bozza scelta')
up=call('MinimaxH3LatentUpscaler3D',latent={'samples':video},model_name=c['finish']['upscaler'],
mode={'mode':'target dimensions','width':w,'height':h},align=32,keep_proportion=False,
device='cuda',precision='fp16',offload_after_upscale=True)[0]
v=up['samples']; h,w=v.shape[-2]*16,v.shape[-1]*16
if tuple(v.shape)!=tuple(empty['samples'].unbind()[0].shape):
cond,empty=condition(frozen,a,res,candidate['prompt'],w,h,n)
expected_video,expected_audio=empty['samples'].unbind()
if tuple(v.shape)!=tuple(expected_video.shape) or tuple(audio_lat.shape)!=tuple(expected_audio.shape):
raise ValueError('Dimensioni dei latenti incompatibili con lo sviluppo. Rigenera la bozza con la stessa durata e modalità.')
latent={'samples':NestedTensor([v,audio_lat])}; settings['lock_audio']=True
else:
latent=empty; settings['denoise']=1.
model=prepare_model(res,frozen,candidate,'develop',unique_id)
update('running','Sviluppo · campionamento di qualità',active='develop')
started=time.monotonic()
result=sample(model,cond,latent,settings,candidate['seed'],progress=progress)
torch.save(pack(result),folder/'developed.pt')
update('running','Sviluppo · decodifica e salvataggio')
images,audio=decode(res,result,c['generate_audio'])
job=re.sub(r'[^\w.-]+','_',c['job'])[:80] or 'DOGMA'
movie=folder/(job+'_H3_SVILUPPO.mp4'); save_video(images,audio,movie,candidate)
item=dict(id=uuid.uuid4().hex,candidate=candidate['id'],label=candidate['label']+' · sviluppo',
video=view_file(movie),saved_path=export_file(movie,c),latent=str((folder/'developed.pt').relative_to(root)),
width=images.shape[2],height=images.shape[1],frames=n,config=frozen,mode=d['mode'],
elapsed_seconds=round(time.monotonic()-started,2),prompt=candidate['prompt'],seed=candidate['seed'],loras=candidate['loras'])
st.setdefault('developments',[]).append(item)
update('developed','Sviluppo pronto. Controllalo e scegli quale finalizzare.',active=None)
else:
candidate=next((p for p in st.get('developments',[]) if p['id']==c.get('selected_development') and p['candidate']==c['selected']),None)
if candidate is None: raise ValueError('Sviluppa prima la bozza e seleziona uno sviluppo disponibile.')
if c['rife']['enabled']: rife_preflight(c['rife'])
# Freeze source/prompt/model/LoRAs to selected trial; only finishing controls are editable.
frozen=parse_config(candidate['config']); frozen['finish']=c['finish']; frozen['preview']=c['preview']
@@ -426,7 +526,7 @@ class DOGMAH3DirectorEngineV2:
cond=condition(frozen,a,res,candidate['prompt'],w,h,n)[0]
model=prepare_model(res,frozen,candidate,'finish',unique_id)
update('running','Finalizzazione · raffinamento dei latenti')
latent=sample(model,cond,latent,fin,candidate['seed'],True,progress=progress)
latent=sample(model,cond,latent,dict(fin,lock_audio=True),int(fin['refine_seed']),True,progress=progress)
torch.save(pack(latent),folder/'latent_refined.pt')
update('running','Finalizzazione · decodifica')
images,audio=decode(res,latent,c['generate_audio'])
@@ -467,13 +567,14 @@ class DOGMAH3DirectorEngineV2:
ultimate_config=copy.deepcopy(frozen)
ultimate_config['finish']['turbo']=fin['ultimate_turbo']
ultimate_config['finish']['turbo_strength']=fin['ultimate_strength']
model=prepare_model(ultimate_res,ultimate_config,candidate,'finish',unique_id)
ultimate_config['finish']['native_shift']=True
model=prepare_model(ultimate_res,ultimate_config,dict(candidate,loras=[]),'finish',unique_id)
from comfy_extras.nodes_minimax_h3 import MiniMaxH3ImageToVideo
cond=MiniMaxH3ImageToVideo.execute(res['clip'],res['vae'],candidate['prompt'],w,h,padded_n,None,None)[0]
guider=Guider_Basic(model); guider.set_conds(cond)
sigmas=BasicScheduler.execute(model,fin['scheduler'],int(fin['ultimate_steps']),float(fin['ultimate_denoise']))[0]
images=call('UltimateSDUpscaleNoUpscaleGuider',unique_id,upscaled_image=padded,guider=guider,sampler=sampler_for(fin),sigmas=sigmas,
vae=res['vae'],seed=candidate['seed'],mode_type='Chess',tile_width=int(fin['tile_width']),tile_height=int(fin['tile_height']),
images=call('UltimateSDUpscaleNoUpscaleGuider',unique_id,upscaled_image=padded,guider=guider,sampler=sampler_for(dict(fin,sampler=fin['ultimate_sampler'],lying=0)),sigmas=sigmas,
vae=res['vae'],seed=int(fin['ultimate_seed']),mode_type='Chess',tile_width=int(fin['tile_width']),tile_height=int(fin['tile_height']),
mask_blur=int(fin['mask_blur']),tile_padding=int(fin['tile_padding']),seam_fix_mode='None',seam_fix_denoise=.15,
seam_fix_mask_blur=8,seam_fix_width=64,seam_fix_padding=16,tile_overlap_mode='Reprocess Overlap',tiled_decode=True,batch_size=1,anchor_context=False)[0][:count]
out=folder/(job+f'_H3_ULTIMATE_{fps}fps.mp4')
@@ -508,20 +609,23 @@ def register_routes():
from aiohttp import web
import folder_paths, comfy.samplers, nodes
routes=PromptServer.instance.routes
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_video_edit import register_edit_routes
cleanup=register_edit_routes(routes,input_file)
PromptServer.instance.app.on_cleanup.append(cleanup)
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__],access.browser))
@routes.post('/dogma/h3/v2/open-folder')
async def open_folder(request):
local_request(request)
import asyncio
data=await request.json(); st=await asyncio.to_thread(state,data['session'])
item=next((x for x in st.get('finals',[])+st.get('candidates',[]) if x.get('id')==data.get('id')),None)
item=next((x for x in st.get('edits',[])+st.get('finals',[])+st.get('developments',[])+st.get('candidates',[]) if x.get('id')==data.get('id')),None)
if not item or not item.get('saved_path'): raise web.HTTPNotFound(text='Risultato non disponibile.')
directory=Path(item['saved_path']).parent
if not directory.is_dir(): raise web.HTTPNotFound(text='Cartella non disponibile.')
@@ -529,6 +633,16 @@ def register_routes():
os.startfile(str(directory))
return web.json_response({'ok':True})
@routes.post('/dogma/h3/v2/edit/export-copy')
async def export_edit_copy(request):
access.browser(request)
import asyncio
data=await request.json()
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')
async def choose_folder(request):
local_request(request)
@@ -536,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))
@@ -573,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):
+72
View File
@@ -0,0 +1,72 @@
"""Per-session edit promotion, without interrupting Comfy's other jobs."""
import threading
import uuid
from .dogma_h3_edit_sampling import validate_final_options
_LOCK=threading.RLock()
_ACTIVE={}
class PromoteEdit(Exception):
pass
class EditBatch:
def __init__(self,session,total,available):
self.session=session;self.id=uuid.uuid4().hex;self.total=total
self.available=set(available);self.chosen=None;self.phase='draft';self.current=0;self.completed=0;self.final_options=None
def snapshot(self):
with _LOCK:
return dict(id=self.id,phase=self.phase,total=self.total,current=self.current,completed=self.completed,chosen=self.chosen,final_options=self.final_options)
def checkpoint(self):
with _LOCK:
if self.phase=='draft' and self.chosen:raise PromoteEdit()
def add(self,trial):
with _LOCK:self.available.add(trial);self.completed+=1
def request(self,trial,batch_id=None,options=None):
options=validate_final_options(options) if options is not None else None
with _LOCK:
if batch_id and batch_id!=self.id:raise ValueError('Il gruppo di provini è cambiato. Riapri la scelta.')
if trial not in self.available:raise ValueError('Il provino deve essere già completo prima di sceglierlo.')
if self.chosen and options!=self.final_options:raise ValueError('La modalità finale è già stata confermata. Attendi questa lavorazione.')
if self.phase=='finish':
if trial==self.chosen:return self.snapshot()
raise ValueError('È già in corso la rigenerazione del provino scelto.')
if self.phase!='draft':return None
if self.chosen and self.chosen!=trial:raise ValueError('È già stato scelto un provino per la rigenerazione.')
self.chosen=trial;self.final_options=options
return self.snapshot()
def seal(self):
with _LOCK:
self.phase='finish' if self.chosen else 'ready'
return self.chosen
def close(self):
with _LOCK:
if _ACTIVE.get(self.session) is self:_ACTIVE.pop(self.session)
def begin_batch(session,total,available):
session=str(uuid.UUID(session))
with _LOCK:
if session in _ACTIVE:raise ValueError('Questa sessione ha già un gruppo di provini in esecuzione.')
batch=EditBatch(session,total,available);_ACTIVE[session]=batch
return batch
def request_promotion(session,trial,batch_id=None,options=None):
session=str(uuid.UUID(session))
with _LOCK:
batch=_ACTIVE.get(session)
return batch.request(trial,batch_id,options) if batch else None
def register_promotion_route(routes):
from aiohttp import web
@routes.post('/dogma/h3/v2/edit/promote')
async def promote(request):
try:
data=await request.json()
result=request_promotion(data['session'],data['trial'],data.get('batch'),data.get('options'))
return web.json_response({'status':'accepted' if result else 'idle','batch':result})
except (ValueError,KeyError) as exc:raise web.HTTPBadRequest(text=str(exc))
+79
View File
@@ -0,0 +1,79 @@
"""Develop the approved edit, rather than silently regenerating its source."""
from pathlib import Path
import hashlib
def pack(value):
import torch
from comfy.nested_tensor import NestedTensor
if isinstance(value,NestedTensor):return {'__dogma_nested__':[pack(x) for x in value.unbind()]}
if isinstance(value,torch.Tensor):return value.detach().cpu().contiguous()
if isinstance(value,dict):return {k:pack(v) for k,v in value.items()}
if isinstance(value,(tuple,list)):return [pack(v) for v in value]
if value is None or isinstance(value,(str,int,float,bool)):return value
raise TypeError('Metadati latenti non supportati.')
def unpack(value):
from comfy.nested_tensor import NestedTensor
if isinstance(value,dict):
if set(value)=={'__dogma_nested__'}:return NestedTensor([unpack(x) for x in value['__dogma_nested__']])
return {k:unpack(v) for k,v in value.items()}
if isinstance(value,list):return [unpack(x) for x in value]
return value
def fingerprint(path):
digest=hashlib.sha256()
with Path(path).open('rb') as stream:
for chunk in iter(lambda:stream.read(1024*1024),b''):digest.update(chunk)
return digest.hexdigest()
def approved_movie(root,trial):
path=Path(trial['saved_path']).resolve()
if not path.is_relative_to(Path(root).resolve()) or not path.is_file():
raise ValueError('Video del provino scelto assente. Il sorgente non verrà usato al suo posto.')
if trial.get('video_sha256') and fingerprint(path)!=trial['video_sha256']:
raise ValueError('Il file del provino scelto è cambiato: finale annullato.')
return path
def reference_movie(root,trial):
path=trial.get('corrected_path')
if not path:return approved_movie(root,trial)
path=Path(path).resolve()
if not path.is_relative_to(Path(root).resolve()) or not path.is_file():raise ValueError('Anteprima del provino recuperato non disponibile.')
if trial.get('corrected_video_sha256') and fingerprint(path)!=trial['corrected_video_sha256']:raise ValueError('Anteprima recuperata modificata.')
return path
def guide_latent(director,root,trial,vae,plate,width,height,read_trial,interrupt):
import torch
from comfy.nested_tensor import NestedTensor
movie=approved_movie(root,trial)
video_path=trial.get('latent')
if video_path:
path=(Path(root)/video_path).resolve()
if not path.is_relative_to(Path(root).resolve()) or not path.is_file():
raise ValueError('Latenti del provino assenti. Rigenera il provino oppure scegli Mantieni edit.')
if trial.get('latent_sha256') and fingerprint(path)!=trial['latent_sha256']:
raise ValueError('Latenti del provino modificati: finale annullato.')
saved=unpack(torch.load(path,map_location='cpu',weights_only=True))
video=saved['samples'].unbind()[0]
origin='saved_latent'
else:
# Older trials have only their video. Encode that approved result explicitly.
frames=read_trial(reference_movie(root,trial))
video=vae.encode(frames[:,:,:,:3]);del frames
origin='encoded_legacy_trial'
interrupt()
if video.shape[-2:]!=(height//16,width//16):
up=director.call('MinimaxH3LatentUpscaler3D',latent={'samples':video},
model_name=trial['config']['finish']['upscaler'],
mode={'mode':'target dimensions','width':width,'height':height},align=32,keep_proportion=False,
device='cuda',precision='fp16',offload_after_upscale=True)[0]
video=up['samples']
target,audio=plate['samples'].unbind()
if tuple(video.shape)!=tuple(target.shape):
raise ValueError('Il provino scelto e il finale hanno griglie diverse. Nessuna rigenerazione dal sorgente eseguita.')
out=plate.copy();video=video.to(device=target.device,dtype=target.dtype)
if plate.get('noise_mask') is not None:
vm,_=plate['noise_mask'].unbind();vm=vm.to(video)
video=video*vm+target*(1-vm)
out['samples']=NestedTensor((video,audio))
return out,dict(method='guided',trial=trial['id'],input=origin,video_sha256=fingerprint(movie))
+99
View File
@@ -0,0 +1,99 @@
"""Frame-exact restitch and lossless export in the source colour planes."""
from pathlib import Path
from fractions import Fraction
import subprocess,tempfile,time,itertools
import av
import numpy as np
from .dogma_h3_edit_mask import FrameReader,composite_mask,composite_settings,resize_rgb,resize_alpha,fade_weight
YUV_FORMATS={'yuv420p','yuv422p','yuv444p','yuvj420p','yuvj422p','yuvj444p','yuv420p10le','yuv422p10le','yuv444p10le','gray','gray10le'}
def output_format(frame):
name=frame.format.name
name={'nv12':'yuv420p','nv21':'yuv420p','nv16':'yuv422p','nv20le':'yuv422p10le','gray8':'gray'}.get(name,name)
if name in YUV_FORMATS:return name,'libx264'
if name in ('rgb24','bgr24','rgba','bgra','bgr0','rgb0','0rgb','0bgr'):return 'rgb24','libx264rgb'
raise ValueError('Export senza perdita non disponibile per '+frame.format.name+'. Usa un sorgente SDR YUV a 8/10 bit o RGB a 8 bit.')
def plane_array(plane,fmt):
dtype=np.dtype('<u2') if '10le' in fmt else np.dtype('u1')
channels=3 if fmt=='rgb24' else 1
return np.ndarray((plane.height,plane.line_size//dtype.itemsize),dtype=dtype,buffer=plane)[:,:plane.width*channels]
def plane_mask(alpha,width,height):
if alpha.shape==(height,width):return alpha
sy=(alpha.shape[0]+height-1)//height;sx=(alpha.shape[1]+width-1)//width
padded=np.pad(alpha,((0,height*sy-alpha.shape[0]),(0,width*sx-alpha.shape[1])),mode='edge')
result=padded.reshape(height,sy,width,sx).min(axis=(1,3))
# Decoder chroma interpolation also reads adjacent samples. Keep that small
# shared neighbourhood original so protected RGB pixels remain untouched.
from scipy.ndimage import minimum_filter
return minimum_filter(result,size=(3 if sy>1 else 1,3 if sx>1 else 1),mode='nearest')
def blend_frame(original,replacement,alpha,fmt):
base=original if original.format.name==fmt else original.reformat(format=fmt)
if not np.any(alpha):return base
rgb=av.VideoFrame.from_ndarray(resize_rgb(replacement,(original.width,original.height)),format='rgb24')
if fmt=='rgb24':patch=rgb
else:
matrix=original.colorspace if original.colorspace not in (0,2) else 5
full_range=original.color_range==2 or (fmt.startswith('gray') and original.color_range==0)
patch=rgb.reformat(format=fmt,dst_colorspace=matrix,dst_color_range='JPEG' if full_range else 'MPEG')
out=av.VideoFrame(original.width,original.height,fmt)
for source,generated,dest in zip(base.planes,patch.planes,out.planes):
a=plane_array(source,fmt);b=plane_array(generated,fmt);d=plane_array(dest,fmt)
weight=plane_mask(alpha,source.width,source.height)
if fmt=='rgb24':weight=np.repeat(weight,3,axis=1)
d[:]=np.rint(a.astype(np.float32)*(1-weight)+b.astype(np.float32)*weight).astype(d.dtype)
out.colorspace=original.colorspace;out.color_range=2 if fmt.startswith('gray') and original.color_range==0 else original.color_range
return out
def compose_lossless(source,patch,dest,meta,plan,fade,ffmpeg,interrupt=lambda:None,mask_path=None,settings=None):
"""Decode each original frame once; never framesync a rounded overlay."""
intermediate=Path(dest).with_suffix('.video.nut');readers=[]
try:
gen=FrameReader(patch);readers.append(gen)
mask=FrameReader(mask_path,plan['start']) if mask_path else None
if mask:readers.append(mask)
with av.open(str(source)) as src,av.open(str(intermediate),'w',format='nut') as out:
s=src.streams.video[0];decoded=src.decode(s);first=next(decoded)
fmt,codec=output_format(first)
stream=out.add_stream(codec,rate=Fraction(meta['fps_ratio']));stream.width=s.width;stream.height=s.height;stream.pix_fmt=fmt
stream.time_base=s.time_base;stream.codec_context.time_base=s.time_base;stream.options={'qp':'0','preset':'medium','bf':'0'}
for key in ('color_range','colorspace','color_trc','color_primaries'):setattr(stream.codec_context,key,getattr(s.codec_context,key))
# FFV1 gray has implicit full-range luma. x264 emits a neutral-chroma
# YUV stream; signal that range or protected greys become darker.
if fmt.startswith('gray') and stream.codec_context.color_range==0:stream.codec_context.color_range=2
for i,frame in enumerate(itertools.chain((first,),decoded)):
interrupt();stamp=frame.pts;tb=frame.time_base;second=float(frame.time)-meta['video_start']
final=frame if frame.format.name==fmt else frame.reformat(format=fmt)
if plan['start_frame']<=i<plan['end_frame']:
alpha=composite_mask(mask.at(second,nearest=True),settings) if mask else np.ones((s.height,s.width),np.float32)
alpha=resize_alpha(alpha,(s.width,s.height))
times=meta['frame_times'];next_time=times[i+1] if i+1<len(times) else meta['duration']
alpha*=fade_weight(second,plan,fade,next_time-second)
if np.any(alpha):final=blend_frame(frame,gen.at(second-plan['start'],nearest=True),alpha,fmt)
final.pts=stamp;final.time_base=tb
for packet in stream.encode(final):out.mux(packet)
for packet in stream.encode():out.mux(packet)
copy_audio=all(x in ('aac','mp3','alac','ac3','eac3') for x in meta['audio_codecs'])
args=[ffmpeg(),'-hide_banner','-loglevel','error','-nostdin','-y','-copyts','-i',str(source),'-i',str(intermediate),
'-map','1:v:0','-map','0:a?','-map_metadata','0','-map_chapters','0','-c:v','copy','-c:a','copy' if copy_audio else 'aac']
if not copy_audio:args+=['-b:a','320k']
args+=['-video_track_timescale',str(Fraction(meta.get('time_base','1/1000000')).denominator),'-movflags','+faststart',str(dest)]
with tempfile.TemporaryFile() as log:
process=subprocess.Popen(args,stdout=subprocess.DEVNULL,stderr=log)
try:
while process.poll() is None:interrupt();time.sleep(.1)
if process.returncode:
log.seek(0);raise ValueError('Salvataggio finale fallito: '+log.read().decode(errors='replace')[-2500:])
except BaseException:
if process.poll() is None:process.kill();process.wait()
raise
return dict(audio_copied=copy_audio,fps=meta['fps'],width=meta['width'],height=meta['height'],
export_encoding='lossless_h264',source_planes_preserved=True,timing_version=2,
composite_mask_version=1,composite_mask_settings=composite_settings(settings) if mask else None)
except BaseException:Path(dest).unlink(missing_ok=True);raise
finally:
intermediate.unlink(missing_ok=True)
for reader in readers:reader.close()
+329
View File
@@ -0,0 +1,329 @@
"""User-supplied video masks, spatial adjustments and bounded edit compositing."""
import asyncio
import hashlib
import inspect
import json
import math
from pathlib import Path
import threading
import uuid
from fractions import Fraction
import av
import numpy as np
from scipy.ndimage import maximum_filter, minimum_filter, gaussian_filter
def mask_defaults():
return dict(enabled=False, source='', grow=0, feather=0., opacity=.55, view='overlay',
composite_mode='source', composite_grow=0, composite_feather=8., preview_area='composite')
def mask_settings(value):
settings = {**mask_defaults(), **(value or {})}
if not settings['enabled']:
return settings
grow, feather, opacity, cg, cf = (float(settings[k]) for k in ('grow', 'feather', 'opacity', 'composite_grow', 'composite_feather'))
if not all(math.isfinite(x) for x in (grow, feather, opacity, cg, cf)) or min(feather,cf) < 0 or not 0 <= opacity <= 1:
raise ValueError('Regolazioni maschera non valide: sfumatura positiva e opacità da 0 a 1.')
settings.update(grow=round(grow), feather=feather, opacity=opacity,composite_grow=round(cg),composite_feather=cf)
if settings['composite_mode'] not in ('source','generation') or settings['preview_area'] not in ('composite','generation'):
raise ValueError('Area maschera non valida.')
if settings['view'] not in ('overlay', 'mask', 'source'):
raise ValueError('Vista maschera non valida.')
return settings
def composite_settings(settings):
"""Generation context must not silently replace protected frame geometry."""
if settings.get('composite_mode','source') == 'generation':return settings
return {**settings,'grow':settings.get('composite_grow',0),'feather':settings.get('composite_feather',8.)}
def composite_mask(rgb,settings):
effective=composite_settings(settings)
if settings.get('composite_mode','source')=='generation':return processed_mask(rgb,effective)
if settings.get('composite_metric')=='distance':
# Match the continuously offset contour used by the live restitch grid.
# Old exports retain their square morphology unless explicitly restitched.
from scipy.ndimage import distance_transform_edt
base=processed_mask(rgb,{**effective,'grow':0,'feather':0.})
support=base>0
if not support.any():return base
distance=distance_transform_edt(np.pad(support,1))[1:-1,1:-1]-distance_transform_edt(~support)
distance+=effective['grow']
radius=float(effective['feather'])
if radius:
x=np.clip(distance/radius,0,1).astype(np.float32);weight=x*x*(3-2*x)
else:weight=(distance>=0).astype(np.float32)
opacity=maximum_filter(base,size=2*effective['grow']+1,mode='constant',cval=0) if effective['grow']>0 else base
return opacity*weight
alpha=processed_mask(rgb,{**effective,'feather':0.})
radius=float(effective['feather'])
if radius:
# Feather inward: never extend replacement over protected window bars
# or carriage walls merely to soften the moving matte edge.
from scipy.ndimage import distance_transform_edt
distance=distance_transform_edt(np.pad(alpha>0,1))[1:-1,1:-1]
x=np.clip(distance/radius,0,1).astype(np.float32)
alpha*=x*x*(3-2*x)
return alpha
def validate_alignment(source, mask):
if (source['width'], source['height']) != (mask['width'], mask['height']):
raise ValueError('La maschera deve avere le stesse dimensioni del video originale.')
a, b = source['frame_times'], mask['frame_times']
tolerance = max(.001, .25/source['fps'])
if len(a) != len(b) or abs(source['duration']-mask['duration']) > tolerance or any(abs(x-y) > tolerance for x,y in zip(a,b)):
raise ValueError('La maschera deve coprire tutto il sorgente con gli stessi fotogrammi e tempi.')
def processed_mask(rgb, settings):
alpha = (rgb.astype(np.float32) @ np.array([.2126, .7152, .0722], np.float32))/255.
alpha[alpha < 1/255] = 0
alpha[alpha > 254/255] = 1
grow = settings['grow']
if grow:
fn = maximum_filter if grow > 0 else minimum_filter
alpha = fn(alpha, size=2*abs(grow)+1, mode='constant', cval=0)
if settings['feather']:
alpha = gaussian_filter(alpha, sigma=settings['feather'], mode='constant', cval=0)
return np.clip(alpha, 0, 1)
def fade_weight(second, plan, fade, frame_duration):
fade = min(float(fade), plan['duration']/2)
if fade <= 0 or plan['source_frames'] <= 1:
return 1.
return max(0., min(1., (second-plan['start']+frame_duration)/fade, (plan['end']-second)/fade))
class FrameReader:
def __init__(self, path, start=0):
self.container = av.open(str(path))
self.stream = self.container.streams.video[0]
self.origin = float(self.stream.start_time*self.stream.time_base) if self.stream.start_time is not None else 0.
self.container.seek(int((self.origin+start)/float(self.stream.time_base)), stream=self.stream, backward=True)
self.frames = self.container.decode(self.stream)
self.current = next(self.frames, None)
self.following = next(self.frames, None)
if self.current is None:
self.close()
raise ValueError('Video privo di fotogrammi leggibili.')
def at(self, second, nearest=False, size=None):
while self.following is not None and float(self.following.time)-self.origin <= second+1e-6:
self.current = self.following
self.following = next(self.frames, None)
selected=self.current
if nearest and self.following is not None and abs(float(self.following.time)-self.origin-second)<abs(float(self.current.time)-self.origin-second):selected=self.following
if size is not None:return selected.reformat(width=size[0],height=size[1],format='rgb24').to_ndarray()
return selected.to_ndarray(format='rgb24')
def close(self):
self.container.close()
def resize_rgb(rgb, size):
if (rgb.shape[1], rgb.shape[0]) == size:
return rgb
return av.VideoFrame.from_ndarray(rgb, format='rgb24').reformat(width=size[0], height=size[1]).to_ndarray(format='rgb24')
def resize_alpha(alpha, size):
if (alpha.shape[1], alpha.shape[0]) == size:
return alpha
from PIL import Image
return np.asarray(Image.fromarray(alpha).resize(size, Image.Resampling.BILINEAR), dtype=np.float32)
def prepare_masked_latent(director, latent, vae, selected, mask_path, settings, plan, content_size, interrupt):
import torch
import nodes
from comfy.nested_tensor import NestedTensor
# Native per-row masking must be available; do not patch the global model.
try:
from comfy.ldm.minimax.model import mask_row_values
except ImportError:
raise ValueError('Aggiorna ComfyUI: il masking nativo H3 richiesto non è disponibile.') from None
node = nodes.NODE_CLASS_MAPPINGS.get('MVEx_MaskToLatentSpace')
if node is None:
raise ValueError('La maschera H3 richiede MaskVidExperiments aggiornato dal Manager.')
empty_video, audio = latent['samples'].unbind()
width, height = selected.shape[2], selected.shape[1]
masks = torch.empty((len(selected),height,width),dtype=torch.float32)
reader = FrameReader(mask_path,plan['start'])
try:
for i in range(len(selected)):
interrupt()
second = min(plan['start']+i/24,plan['last_source_time'])
alpha = resize_alpha(processed_mask(reader.at(second,nearest=True),settings),content_size)
alpha = np.pad(alpha,((0,height-alpha.shape[0]),(0,width-alpha.shape[1])),mode='constant')
masks[i] = torch.from_numpy(alpha)
finally:
reader.close()
kwargs = dict(masks=masks,compression={'compression':'auto'},spatial_method='max',temporal_method='max',
grow_spatial=0,grow_temporal=0,vae=vae)
# This input was added by MaskVidExperiments after the version in this install.
if 'grow_temp_mode' in inspect.signature(node.execute).parameters:
kwargs['grow_temp_mode'] = 'both'
reduced = director.call('MVEx_MaskToLatentSpace',**kwargs)[0]
plate = vae.encode(selected[:,:,:,:3])
if tuple(plate.shape) != tuple(empty_video.shape) or tuple(reduced.shape) != tuple(plate.shape[-3:]):
raise ValueError('Video, maschera e griglia temporale H3 non coincidono. Aggiorna ComfyUI e MaskVidExperiments.')
result = latent.copy()
result['samples'] = NestedTensor((plate,audio))
result['noise_mask'] = NestedTensor((reduced[None,None].to(dtype=plate.dtype),torch.zeros_like(audio)))
return result
def inspect_native_mask(latent):
"""Validate the actual AV mask handed to sampling, not only the preview."""
import torch
mask=latent.get('noise_mask')
if mask is None or not getattr(mask,'is_nested',hasattr(mask,'unbind')):
raise ValueError('Maschera edit assente dai latenti: campionamento annullato.')
try:
video,audio=latent['samples'].unbind();vm,am=mask.unbind()
except (ValueError,TypeError,AttributeError):
raise ValueError('Maschera edit AV non valida.') from None
if vm.ndim!=video.ndim or vm.shape[0]!=video.shape[0] or vm.shape[1] not in (1,video.shape[1]) or tuple(vm.shape[2:])!=tuple(video.shape[2:]):
raise ValueError('La maschera non coincide con la griglia video del campionamento.')
if tuple(am.shape)!=tuple(audio.shape) or not torch.isfinite(am).all() or torch.count_nonzero(am):
raise ValueError('La maschera audio deve restare a zero durante l’edit.')
if not torch.isfinite(vm).all() or vm.min()<0 or vm.max()>1:
raise ValueError('La maschera video contiene valori non validi.')
if not torch.count_nonzero(vm):raise ValueError('La selezione non contiene aree bianche nella maschera: nessun edit da applicare.')
return dict(enabled=True,shape=list(vm.shape),coverage=round(float(vm.float().mean()),6),audio_locked=True)
def write_segment(source, generated, dest, meta, plan, *, mask_path=None, settings=None,
size=None, fade=0., preview=False, precomposited=False, interrupt=lambda:None, progress=lambda a,b:None):
"""Only the selected interval is decoded; mask adjustments use source pixels."""
size = size or (meta['width'], meta['height'])
readers = []
try:
src = FrameReader(source, plan['start']); readers.append(src)
gen = FrameReader(generated) if generated else None
if gen: readers.append(gen)
mask = FrameReader(mask_path, plan['start']) if mask_path else None
if mask: readers.append(mask)
times = meta['frame_times'][plan['start_frame']:plan['end_frame']]
with av.open(str(dest), 'w') as out:
codec = 'libx264' if preview else 'ffv1'
stream = out.add_stream(codec, rate=Fraction(meta['fps_ratio']))
stream.width, stream.height = size
stream.pix_fmt = 'yuv420p' if preview else 'bgr0'
stream.time_base = Fraction(meta.get('time_base','1/1000000'))
if preview: stream.options = {'crf':'18', 'preset':'veryfast'}
for i, second in enumerate(times):
interrupt()
original = resize_rgb(src.at(second,nearest=True), size)
mask_fn=processed_mask if preview and settings.get('preview_area')=='generation' else composite_mask
alpha = mask_fn(mask.at(second,nearest=True), settings) if mask else np.ones((size[1],size[0]),np.float32)
next_time = times[i+1] if i+1 < len(times) else plan['end']
alpha = resize_alpha(alpha, size)*fade_weight(second, plan, fade, next_time-second)
# An approved trial already includes feather and temporal fades.
# Applying their alpha twice would bring the old wall back.
if precomposited:alpha=(alpha>0).astype(np.float32)
if preview:
if settings['view'] == 'mask':
rgb = np.repeat(np.rint(alpha[...,None]*255).astype(np.uint8), 3, axis=2)
elif settings['view'] == 'source':
rgb = original
else:
mix = alpha[...,None]*settings['opacity']
rgb = np.rint(original*(1-mix)+np.array([255,80,35])*mix).astype(np.uint8)
else:
replacement = resize_rgb(gen.at(second-plan['start'],nearest=True), size)
mix = alpha[...,None]
rgb = np.rint(original*(1-mix)+replacement*mix).clip(0,255).astype(np.uint8)
frame = av.VideoFrame.from_ndarray(rgb, format='rgb24')
frame.time_base = Fraction(meta.get('time_base','1/1000000'))
frame.pts = round((second-plan['start'])/frame.time_base)
for packet in stream.encode(frame): out.mux(packet)
progress(i+1,len(times))
for packet in stream.encode(): out.mux(packet)
except BaseException:
Path(dest).unlink(missing_ok=True)
raise
finally:
for reader in readers: reader.close()
def register_mask_routes(routes, input_file, probe, plan_interval):
from aiohttp import web
import folder_paths
jobs = {}
slot = asyncio.Semaphore(1)
def describe(data):
settings = mask_settings(data.get('mask'))
source, mask = input_file(data['source']), input_file(settings['source'])
meta, mask_meta = probe(source), probe(mask)
validate_alignment(meta, mask_meta)
plan = plan_interval(meta,data['start'],data['end'])
fade = float(data.get('fade',0))
if not math.isfinite(fade) or not 0 <= fade <= .5:
raise ValueError('Raccordo maschera non valido.')
stamps = [(str(p),p.stat().st_size,p.stat().st_mtime_ns) for p in (source,mask)]
key = hashlib.sha256(json.dumps([stamps,settings,plan,fade],sort_keys=True).encode()).hexdigest()
return source,mask,meta,plan,settings,fade,key
async def work(job, data):
try:
async with slot:
if job['cancel'].is_set(): job['status']='cancelled';return
source,mask,meta,plan,settings,fade,key = await asyncio.to_thread(describe,data)
directory = Path(folder_paths.get_temp_directory())/'DOGMA_MASK_PREVIEW'
directory.mkdir(parents=True,exist_ok=True)
dest = directory/(key+'.mp4')
job['status'] = 'running'
if not dest.is_file():
scale = min(1.,960/max(meta['width'],meta['height']))
size = tuple(max(2,round(x*scale/2)*2) for x in (meta['width'],meta['height']))
def interrupt():
if job['cancel'].is_set(): raise InterruptedError('Anteprima annullata.')
def progress(done,total): job.update(done=done,total=total)
temp = directory/(key+'.'+job['id']+'.mp4')
await asyncio.to_thread(write_segment,source,None,temp,meta,plan,mask_path=mask,settings=settings,
size=size,fade=fade,preview=True,interrupt=interrupt,progress=progress)
temp.replace(dest)
job.update(status='done',file={'filename':dest.name,'subfolder':'DOGMA_MASK_PREVIEW','type':'temp'},
selection=plan,settings=settings)
except InterruptedError:
job['status'] = 'cancelled'
except Exception as exc:
job.update(status='error',message=str(exc))
@routes.post('/dogma/h3/v2/edit/mask-preview')
async def start_preview(request):
data = await request.json()
# Bound completed job records; video files live in Comfy's temporary folder.
for key in list(jobs):
if len(jobs)<32: break
if jobs[key]['status'] in ('done','error','cancelled'): jobs.pop(key)
if len(jobs)>=32: raise web.HTTPTooManyRequests(text='Attendi le anteprime già in corso.')
uid = uuid.uuid4().hex
job = {'id':uid,'status':'queued','done':0,'total':0,'cancel':threading.Event()}
jobs[uid] = job
job['task'] = asyncio.create_task(work(job,data))
return web.json_response({'id':uid,'status':'queued'})
@routes.get('/dogma/h3/v2/edit/mask-preview/{id}')
async def preview_status(request):
job = jobs.get(request.match_info['id'])
if not job: raise web.HTTPNotFound(text='Anteprima non disponibile.')
return web.json_response({k:v for k,v in job.items() if k not in ('cancel','task')})
@routes.delete('/dogma/h3/v2/edit/mask-preview/{id}')
async def cancel_preview(request):
job = jobs.get(request.match_info['id'])
if job: job['cancel'].set()
return web.json_response({'ok':True})
async def cleanup(app):
for job in jobs.values(): job['cancel'].set()
await asyncio.gather(*(j['task'] for j in jobs.values()),return_exceptions=True)
# The server owns task lifetime; cancellation is also available per preview.
return cleanup
+45
View File
@@ -0,0 +1,45 @@
"""Explicit original-size edit sampling choices, separate from frozen edit inputs."""
SAMPLING_KEYS=('turbo','turbo_strength','steps','sampler','scheduler','shift_video','shift_audio',
'lying','lying_start','lying_end','native_shift','denoise')
def final_options(edit):
return validate_final_options({'mode':edit.get('final_mode','match'),'steps':edit.get('final_steps',20),
'method':edit.get('final_method','preserve'),'denoise':edit.get('final_denoise',.25),
'output_dir':edit.get('final_output_dir',''),'resolution':edit.get('final_resolution','native'),
'matte':{k:v for k,v in (edit.get('mask') or {}).items() if k.startswith('composite_')}})
def validate_final_options(value):
value=value or {}
mode=value.get('mode','match')
if mode not in ('match','turbo','standard'):raise ValueError('Finale edit: scegli Come il provino, Turbo o Standard.')
steps=float(value.get('steps',20))
if not steps.is_integer() or not 1<=steps<=100:raise ValueError('Passaggi finale standard: un intero da 1 a 100.')
method=value.get('method','preserve')
if method not in ('guided','preserve','regenerate'):raise ValueError('Scegli come preparare il finale edit.')
denoise=float(value.get('denoise',.25))
if not .01<=denoise<=1:raise ValueError('Raffinamento finale: intensità tra 0,01 e 1.')
directory=value.get('output_dir','')
if not isinstance(directory,str):raise ValueError('Cartella finale non valida.')
resolution=value.get('resolution','native')
if resolution not in ('native','trial','source'):raise ValueError('Risoluzione H3: scegli nativa, provino o originale.')
from .dogma_h3_edit_mask import mask_settings
matte=mask_settings({**value.get('matte',{}),'enabled':True})
return dict(mode=mode,steps=int(steps),method=method,denoise=denoise,output_dir=directory.strip(),resolution=resolution,
matte={k:v for k,v in matte.items() if k.startswith('composite_')})
def generation_size(meta,edit,trial=False):
import math
w,h=meta['width'],meta['height']
if trial or edit.get('final_resolution')=='trial':scale=min(1.,int(edit.get('trial_edge',512))/max(w,h))
elif edit.get('final_resolution','native')=='source':scale=1.
else:
# Match native H3's 768-short-edge / 768*1344 canvas policy, while
# preserving the source aspect and retaining small technical padding.
ratio=w/h
nw,nh=(768*ratio,768) if ratio>=1 else (768,768/ratio)
factor=min(1.,math.sqrt((768*1344)/(nw*nh)))
scale=min(1.,nw*factor/w,nh*factor/h)
return max(2,round(w*scale/2)*2),max(2,round(h*scale/2)*2)
def is_ref_turbo(name):
return str(name).replace('\\','/').split('/')[-1].startswith('minimax_h3_ref2v_turbo_')
+144
View File
@@ -0,0 +1,144 @@
"""Shared preview atlas and CPU-only, in-place restitch of a completed edit."""
from pathlib import Path
from fractions import Fraction
import asyncio,copy,hashlib,json,math,os,shutil,time,uuid
import av
import numpy as np
from scipy.ndimage import distance_transform_edt
from .dogma_h3_edit_mask import FrameReader,processed_mask,mask_settings,composite_settings,validate_alignment
from .dogma_h3_edit_develop import fingerprint
def inputs(core,session,item_id):
st=core.state(session);root=core.manifest_root(session).resolve()
item=next((x for x in st.get('edits',[]) if x.get('id')==item_id and x.get('complete')),None)
if not item:raise ValueError('Video completo non disponibile.')
c=item['config'];settings=mask_settings(c['edit'].get('mask'))
if not settings['enabled']:raise ValueError('Le varianti di restitch richiedono una maschera video.')
relative=item.get('raw_patch');sha=item.get('raw_patch_sha256')
if not relative:
trial=next((x for x in st.get('edit_trials',[]) if x.get('id')==item.get('trial')),None)
if item.get('development',{}).get('method')=='preserve' and trial:
relative=trial.get('raw_patch');sha=trial.get('raw_patch_sha256')
if not relative:raise ValueError('Questo finale precedente non conserva il tratto generato necessario. Preparalo di nuovo dal provino con i nodi aggiornati; nessuna sostituzione con il video originale.')
raw=(root/relative).resolve()
if not raw.is_relative_to(root) or not raw.is_file():raise ValueError('Tratto generato non disponibile per il restitch.')
f=item['video'];master=(root.parent.parent/f.get('subfolder','')/f['filename']).resolve()
if not master.is_relative_to(root) or not master.is_file():raise ValueError('Master della sessione non disponibile.')
return st,item,root,core.input_file(c['edit']['source']),core.input_file(settings['source']),raw,master,sha
def preview_atlas(core,session,item_id,edge=320):
from .dogma_h3_video_edit import cached_probe,plan_interval
import folder_paths
if edge not in (320,960):raise ValueError('Risoluzione anteprima non disponibile.')
st,item,root,source,mask,raw,master,sha=inputs(core,session,item_id)
meta=cached_probe(source);validate_alignment(meta,cached_probe(mask));e=item['config']['edit'];plan=plan_interval(meta,e['start'],e['end'])
marks=[(str(p),p.stat().st_size,p.stat().st_mtime_ns) for p in (source,mask,raw)]
key=hashlib.sha256(json.dumps([marks,plan,'atlas-v2-'+str(edge)],sort_keys=True).encode()).hexdigest()
folder=Path(folder_paths.get_temp_directory())/'DOGMA_RESTITCH';folder.mkdir(parents=True,exist_ok=True)
path=folder/(key+'.mp4');ratio=min(1.,edge/max(meta['width'],meta['height']))
w,h=(max(2,round(meta[k]*ratio/2)*2) for k in ('width','height'))
field_range=256.;started=time.monotonic()
if not path.exists():
if sha and fingerprint(raw)!=sha:raise ValueError('Il tratto generato è stato modificato.')
readers=[];temp=path.with_name(key+'.'+uuid.uuid4().hex+'.mp4')
try:
src=FrameReader(source,plan['start']);gen=FrameReader(raw);mr=FrameReader(mask,plan['start']);readers=[src,gen,mr]
with av.open(str(temp),'w') as out:
s=out.add_stream('libx264',rate=Fraction(meta['fps_ratio']));s.width=w*4;s.height=h;s.pix_fmt='yuv420p';s.time_base=Fraction(meta['time_base']);s.options={'qp':'0','preset':'ultrafast','bf':'0'}
for second in meta['frame_times'][plan['start_frame']:plan['end_frame']]:
original=src.at(second,nearest=True,size=(w,h));generated=gen.at(second-plan['start'],nearest=True,size=(w,h))
mask_rgb=mr.at(second,nearest=True,size=(w,h));alpha=processed_mask(mask_rgb,{'grow':0,'feather':0})
support=alpha>1/255
if support.any():
inside=distance_transform_edt(np.pad(support,1))[1:-1,1:-1]
outside=distance_transform_edt(~support)
distance=(inside-outside)/(w/meta['width'])
else:distance=np.full((h,w),-field_range)
sdf=np.repeat(np.rint(np.clip(distance/field_range*.5+.5,0,1)*255).astype(np.uint8)[...,None],3,axis=2)
a=np.repeat(np.rint(alpha*255).astype(np.uint8)[...,None],3,axis=2)
atlas=np.concatenate((original,generated,sdf,a),axis=1)
frame=av.VideoFrame.from_ndarray(atlas,format='rgb24');frame.time_base=s.time_base;frame.pts=round((second-plan['start'])/frame.time_base)
for packet in s.encode(frame):out.mux(packet)
for packet in s.encode():out.mux(packet)
temp.replace(path)
finally:
temp.unlink(missing_ok=True)
for reader in readers:reader.close()
base=composite_settings(mask_settings(e.get('mask')))
return dict(file={'filename':path.name,'subfolder':'DOGMA_RESTITCH','type':'temp'},width=w,height=h,
source_width=meta['width'],source_height=meta['height'],fps=meta['fps'],duration=plan['duration'],fade=e['fade'],
field_range=field_range,base={'grow':base['grow'],'feather':base['feather']},revision=item.get('restitch_revision',0),
elapsed_seconds=round(time.monotonic()-started,3),cache_key=key)
def validate_choice(data):
grow,feather=(float(data.get(k,0)) for k in ('grow','feather'))
if not all(math.isfinite(x) for x in (grow,feather)) or abs(grow)>256 or not 0<=feather<=256:
raise ValueError('Restitch: espansione da −256 a +256 px e feather da 0 a 256 px.')
return dict(composite_mode='source',composite_grow=round(grow),composite_feather=feather,composite_metric='distance')
def apply_restitch(core,data):
from .dogma_h3_video_edit import cached_probe,plan_interval,compose
choice=validate_choice(data)
st,item,root,source,mask,raw,master,sha=inputs(core,data['session'],data['id'])
if st.get('status')=='running':raise ValueError('Attendi la fine della generazione prima di applicare il restitch.')
revision=int(item.get('restitch_revision',0))
if int(data.get('revision',revision))!=revision:raise ValueError('Il finale è stato aggiornato. Riapri le varianti di restitch.')
if sha and fingerprint(raw)!=sha:raise ValueError('Il tratto generato è stato modificato.')
previous_hash=item.get('video_sha256') or fingerprint(master)
if fingerprint(master)!=previous_hash:raise ValueError('Il master è stato modificato esternamente. Nessun file sovrascritto.')
c=copy.deepcopy(item['config']);settings=mask_settings({**c['edit']['mask'],**choice});c['edit']['mask']=settings
meta=cached_probe(source);validate_alignment(meta,cached_probe(mask));plan=plan_interval(meta,c['edit']['start'],c['edit']['end'])
temp=master.with_name(master.stem+'.restitch-'+uuid.uuid4().hex+'.mp4')
try:
info=compose(source,raw,temp,meta,plan,c['edit']['fade'],mask_path=mask,settings=settings)
new_hash=fingerprint(temp)
with core._STATE_LOCK:
latest=core.state(data['session']);current=next((x for x in latest.get('edits',[]) if x['id']==item['id']),None)
if not current or latest.get('status')=='running' or current.get('restitch_revision',0)!=revision or fingerprint(master)!=previous_hash:
raise ValueError('La sessione è cambiata durante il restitch. Il finale precedente è conservato.')
temp.replace(master)
saved=Path(current.get('saved_path',str(master)));error=None
if saved.resolve()!=master.resolve():
transfer=saved.with_name(saved.name+'.'+uuid.uuid4().hex+'.tmp')
try:
if not saved.is_file() or fingerprint(saved)!=previous_hash:raise ValueError('La copia esportata è stata spostata o modificata. Il nuovo master resta nella sessione.')
shutil.copy2(master,transfer);transfer.replace(saved)
except (OSError,ValueError) as exc:error=str(exc);saved=master
finally:transfer.unlink(missing_ok=True)
current.setdefault('restitch_initial',{'grow':composite_settings(mask_settings(current['config']['edit']['mask']))['grow'],'feather':composite_settings(mask_settings(current['config']['edit']['mask']))['feather']})
current.update(config=c,video_sha256=new_hash,saved_path=str(saved.resolve()),restitch_revision=revision+1,**info)
current['video']={**current['video'],'dg_revision':revision+1}
if error:current['export_error']=error
else:current.pop('export_error',None)
latest['message']='Restitch applicato al finale.' if not error else error
core.write_json(root/'session.json',latest)
return current
finally:temp.unlink(missing_ok=True)
def register_routes(routes,core,authorize_request):
from aiohttp import web
jobs={};slot=asyncio.Semaphore(1)
async def launch(kind,data):
for k in list(jobs):
if len(jobs)<24:break
if jobs[k]['status'] in ('done','error'):jobs.pop(k)
if len(jobs)>=24:raise web.HTTPTooManyRequests(text='Attendi le lavorazioni già avviate.')
job={'id':uuid.uuid4().hex,'status':'running'};jobs[job['id']]=job
async def run():
try:
async with slot:
result=await asyncio.to_thread(preview_atlas,core,data['session'],data['id'],960 if data.get('detail') is True else 320) if kind=='preview' else await asyncio.to_thread(apply_restitch,core,data)
job.update(status='done',result=result)
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):authorize_request(request);return await launch('preview',await request.json())
@routes.post('/dogma/h3/v2/edit/restitch/apply')
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):
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)
return cleanup
+616
View File
@@ -0,0 +1,616 @@
"""Bounded H3 Ref2VA edits and a streaming, timestamp-preserving full-video export.
No model downloads. Only the selected interval enters the generation tensors.
"""
import math
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import time
from fractions import Fraction
from bisect import bisect_left
import copy
import json
from functools import lru_cache
from .dogma_h3_edit_mask import mask_defaults, mask_settings, validate_alignment, write_segment, register_mask_routes, prepare_masked_latent, inspect_native_mask
from .dogma_h3_edit_control import begin_batch, PromoteEdit, register_promotion_route
from .dogma_h3_edit_sampling import SAMPLING_KEYS, final_options, is_ref_turbo, generation_size
from .dogma_h3_edit_develop import approved_movie, reference_movie, guide_latent, fingerprint
# Native H3 temporal grid; the selected interval is independent of this grid.
# 362/24 exceeds the 15 s reference budget; keep the source reference <=15 s.
EDIT_FRAMES = tuple(range(5, 346, 17))
def edit_defaults():
return dict(source='', start=0., end=107/24, fade=.125, anchor_edges=True,
mask=mask_defaults(), selected_trial='', trial_edge=512, trial_mode='fast', trial_live_preview=False,final_mode='match',final_steps=20,
final_method='preserve',final_denoise=.25,final_output_dir='',final_resolution='native',
turbo='', turbo_strength=1., steps=20, sampler='res_multistep',
scheduler='simple', shift_video=12., shift_audio=3.,
lying=0., lying_start=.1, lying_end=.9)
def ffmpeg():
executable = shutil.which('ffmpeg')
if not executable:
try:
import imageio_ffmpeg
executable = imageio_ffmpeg.get_ffmpeg_exe()
except (ImportError, RuntimeError):
pass
if not executable or not Path(executable).is_file():
raise ValueError('Video Edit richiede FFmpeg (oppure imageio-ffmpeg) sul computer Comfy.')
return executable
def probe(path):
import av
with av.open(str(path)) as container:
if not container.streams.video:
raise ValueError('Il file non contiene una traccia video.')
s = container.streams.video[0]
rate = s.average_rate or s.guessed_rate
if not rate or rate <= 0:
raise ValueError('FPS del sorgente non leggibili.')
duration = float(s.duration * s.time_base) if s.duration else float((container.duration or 0)/av.time_base)
if not math.isfinite(duration) or duration <= 0:
raise ValueError('Durata del video non leggibile.')
# Reject formats that need a separate color-managed / orientation workflow.
rotation = int(float(s.metadata.get('rotate', '0'))) % 360
decoded = container.decode(s)
first = next(decoded, None)
if first is None:
raise ValueError('Video privo di fotogrammi decodificabili.')
rotation = int(getattr(first, 'rotation', rotation) or rotation) % 360
if rotation:
raise ValueError('Video con rotazione metadata: esportalo con rotazione applicata prima di editarlo.')
if s.sample_aspect_ratio and s.sample_aspect_ratio != 1:
raise ValueError('Video anamorfico: esporta prima una versione con pixel quadrati.')
# AVColorTransferCharacteristic: SMPTE2084 / ARIB_STD_B67.
if s.codec_context.color_trc in (16, 18):
raise ValueError('Sorgente HDR: questa versione Video Edit richiede un master SDR.')
start = float(s.start_time * s.time_base) if s.start_time is not None else float(first.time or 0)
origin = float(container.start_time/av.time_base) if container.start_time is not None else start
times = [0.]
for frame in decoded:
if frame.time is None:
raise ValueError('Il video non ha timestamp utilizzabili per una selezione precisa.')
second = float(frame.time)-start
if second > times[-1]:
times.append(second)
if duration <= times[-1]:
duration = times[-1]+1/float(rate)
return dict(width=s.width, height=s.height, fps=float(rate), fps_ratio=str(rate),
duration=duration, frames=len(times), frame_times=times, video_start=start,
video_offset=start-origin, audio=bool(container.streams.audio),
audio_codecs=[x.codec_context.name for x in container.streams.audio],
time_base=str(s.time_base),generation_frames=list(EDIT_FRAMES), generation_fps=24,
min_seconds=EDIT_FRAMES[0]/24, max_seconds=EDIT_FRAMES[-1]/24)
def plan_interval(meta, start, end):
start, end = float(start), float(end)
if not all(math.isfinite(v) for v in (start, end)):
raise ValueError('Selezione temporale non valida.')
fps = Fraction(meta['fps_ratio'])
times = meta.get('frame_times')
def nearest(second):
if times is None:
return math.floor(second*float(fps)+.5)
boundaries = [*times, meta['duration']]
i = bisect_left(boundaries, second)
if i >= len(boundaries):
return len(times)
if i > 0 and second-boundaries[i-1] < boundaries[i]-second:
i -= 1
return i
start_frame, end_frame = nearest(start), nearest(end)
total = len(times) if times is not None else math.floor(meta['duration']*float(fps)+1e-6)
if start < 0 or end > meta['duration']+1e-6 or start_frame < 0 or end_frame > total:
raise ValueError('La selezione supera il video sorgente.')
if end_frame <= start_frame:
raise ValueError('Seleziona almeno un fotogramma.')
start = times[start_frame] if times is not None else start_frame/float(fps)
end = (times[end_frame] if end_frame < total else meta['duration']) if times is not None else end_frame/float(fps)
required = math.ceil((end-start)*24-1e-8)
generation_frames = next((n for n in EDIT_FRAMES if n >= required), None)
if generation_frames is None:
raise ValueError('La selezione supera la durata disponibile per H3.')
last_time = times[end_frame-1] if times is not None else (end_frame-1)/float(fps)
return dict(start=start, end=end, duration=end-start, generation_frames=generation_frames,
source_frames=end_frame-start_frame, start_frame=start_frame, end_frame=end_frame,
last_source_time=last_time)
@lru_cache(maxsize=64)
def _cached_probe(path,size,mtime):
return probe(Path(path))
def cached_probe(path):
path=Path(path);stat=path.stat()
return _cached_probe(str(path.resolve()),stat.st_size,stat.st_mtime_ns)
def trial_sampling(c):
settings=copy.deepcopy(c['edit'])
mode=settings.get('trial_mode','fast')
if mode=='same':return settings
if mode!='fast':raise ValueError('Modalità provini edit non valida.')
import folder_paths
name='minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors'
turbo=next((p for p in folder_paths.get_filename_list('loras') if p.replace('\\','/').split('/')[-1]==name),None)
if turbo is None:raise ValueError('Provini rapidi: Turbo Ref2Video 4 step non trovato. Seleziona "Stessa qualità del finale" oppure configura questa LoRA.')
settings.update(turbo=turbo,turbo_strength=1.,steps=4,sampler='euler',scheduler='simple',lying=0.)
return settings
def final_sampling(selected,options):
config=copy.deepcopy(selected['config']);settings=copy.deepcopy(config['edit'])
mode=options['mode']
if mode=='standard':
settings.update(turbo='',steps=options['steps'])
elif mode=='turbo':
config['edit']['trial_mode']='fast';settings=trial_sampling(config)
elif selected.get('sampling'):
saved=copy.deepcopy(selected['sampling'])
# Version 1.0.45 saved only steps/sampler/turbo. Recover its known Turbo preset.
if is_ref_turbo(saved.get('turbo','')) and int(saved.get('steps',0))==4:
config['edit']['trial_mode']='fast';settings=trial_sampling(config)
saved.pop('turbo',None)
settings.update({k:v for k,v in saved.items() if k in SAMPLING_KEYS})
return settings
def check_config(c, input_file):
e = c['edit']
if not e.get('source'):
raise ValueError('Carica il video da modificare.')
meta = cached_probe(input_file(e['source']))
plan = plan_interval(meta,e['start'],e['end'])
settings = mask_settings(e.get('mask'))
if settings['enabled']:
if not settings['source']: raise ValueError('Carica il video maschera bianco e nero.')
validate_alignment(meta,cached_probe(input_file(settings['source'])))
import nodes
if 'MVEx_MaskToLatentSpace' not in nodes.NODE_CLASS_MAPPINGS:
raise ValueError('Installa o aggiorna MaskVidExperiments dal Manager per usare la maschera H3.')
if not 0 <= float(e['fade']) <= .5:
raise ValueError('Raccordo: da 0 a 0,5 secondi.')
if not 1 <= int(e['steps']) <= 100:
raise ValueError('Step edit: da 1 a 100.')
if not 0 <= float(e['lying_start']) <= float(e['lying_end']) <= 1:
raise ValueError('Intervallo Lying Sigma non valido.')
if not c['prompt'].strip():
raise ValueError('Descrivi la modifica da applicare.')
videos = [r for r in c['refs'] if r.get('kind') == 'video']
if len(videos)>2 or len(c['refs'])>11:
raise ValueError('Il sorgente occupa Video 1: restano 2 video e 9 immagini reference (11 file).')
reference_duration = 0.
for r in c['refs']:
if r.get('kind') not in ('image','video') or not r.get('name'):
raise ValueError('Carica o rimuovi le reference vuote.')
path = input_file(r['name'])
if r['kind']=='video':
ref = cached_probe(path)
if not 2 <= ref['duration'] <= 15:
raise ValueError('Ogni video reference aggiuntivo deve durare da 2 a 15 secondi.')
plan['generation_frames'] = max(plan['generation_frames'], max(5,math.floor((ref['duration']*24-5)/17)*17+5))
reference_duration += ref['duration']
duration = plan['generation_frames']/24 + reference_duration
if duration>15+1e-6:
raise ValueError(f'Sorgente selezionato + video reference: {duration:.2f} s. Il limite H3 è 15 s totali; accorcia la selezione o le reference.')
ffmpeg() # Fail before loading models.
if int(e.get('trial_edge',512)) not in (256,384,512):raise ValueError('Dimensione provini edit: 256, 384 o 512 px.')
return meta,plan
def segment_tensor(path, start, n, width, height, interrupt=lambda:None, end=None, source_fps=24, last_time=None, resize_size=None):
"""Seek near the selection; sample by timestamps, with no temporal stretch."""
import av
import numpy as np
import torch
with av.open(str(path)) as container:
stream = container.streams.video[0]
origin = float(stream.start_time*stream.time_base) if stream.start_time is not None else 0.
container.seek(int((origin+start)/float(stream.time_base)),stream=stream,backward=True)
last = last_time if last_time is not None else (max(start, end-1/source_fps) if end is not None else float('inf'))
targets = [origin+min(start+i/24,last) for i in range(n)]
result = torch.empty((n,height,width,3),dtype=torch.float32)
prev = None; pos = 0
def put(frame):
nonlocal pos
if resize_size: frame = frame.reformat(width=resize_size[0],height=resize_size[1])
arr = frame.to_ndarray(format='rgb24')
h,w = arr.shape[:2]
if w>width or h>height:
raise ValueError('Dimensioni sorgente cambiate durante la lettura.')
arr = np.pad(arr,((0,height-h),(0,width-w),(0,0)),mode='edge')
result[pos] = torch.from_numpy(arr.astype(np.float32)/255.)
pos+=1
for frame in container.decode(stream):
interrupt()
if frame.time is None:
raise ValueError('Il sorgente non ha timestamp utilizzabili.')
t = float(frame.time)
while pos<n and targets[pos]<t-1e-7:
put(prev if prev is not None else frame)
prev=frame
if pos==n: break
if prev is None:
raise ValueError('Impossibile decodificare la selezione.')
while pos<n: put(prev)
return result
def thumbnail(path, second):
import av
import io
with av.open(str(path)) as container:
s=container.streams.video[0]
origin=float(s.start_time*s.time_base) if s.start_time is not None else 0.
target=origin+max(0.,float(second))
container.seek(int(target/float(s.time_base)),stream=s,backward=True)
chosen=None
for frame in container.decode(s):
chosen=frame
if float(frame.time or 0)>=target: break
if chosen is None: raise ValueError('Fotogramma non disponibile.')
image=chosen.to_image(); image.thumbnail((256,144))
data=io.BytesIO(); image.save(data,format='JPEG',quality=78)
return data.getvalue()
def save_patch(images,path,width,height,n,interrupt=lambda:None):
import av
import numpy as np
if len(images)<n or images.shape[1]<height or images.shape[2]<width:
raise ValueError('H3 ha restituito dimensioni o durata inferiori a quelle richieste.')
with av.open(str(path),'w') as out:
stream=out.add_stream('ffv1',rate=24)
stream.width=width; stream.height=height; stream.pix_fmt='bgr0'
for i,img in enumerate(images[:n]):
interrupt()
arr=(img[:height,:width,:3].detach().cpu().numpy().clip(0,1)*255).round().astype(np.uint8)
frame=av.VideoFrame.from_ndarray(arr,format='rgb24');frame.pts=i;frame.time_base=Fraction(1,24)
for packet in stream.encode(frame): out.mux(packet)
for packet in stream.encode(): out.mux(packet)
def compose(source,patch,dest,meta,plan,fade,interrupt=lambda:None,mask_path=None,settings=None):
from .dogma_h3_edit_export import compose_lossless
return compose_lossless(source,patch,dest,meta,plan,fade,ffmpeg,interrupt,mask_path,settings)
def render_edit(c,root,st,update,progress,uid,trial=False,resources=None,prepared=None,checkpoint=lambda:None,sampling=None,guide=None):
from . import dogma_h3_director_v134 as director
import comfy.model_management as mm
from comfy_extras.nodes_minimax_h3 import MiniMaxH3ReferenceToVideo,MiniMaxH3AddGuide
import uuid
import re
started=time.monotonic();timings={}
def interrupt():
mm.throw_exception_if_processing_interrupted();checkpoint()
def report(step,total):
interrupt();progress(step,total)
interrupt()
meta,plan=check_config(c,director.input_file)
source=director.input_file(c['edit']['source'])
content_width,content_height=generation_size(meta,c['edit'],trial)
width=math.ceil(content_width/32)*32; height=math.ceil(content_height/32)*32
n=plan['generation_frames']
res=resources if resources is not None else director.load_resources(c)
if guide:ensure_trial_patch(director,root,guide,interrupt,vae=res['vae'])
prompt=('integrated_multimodal_description:\n[Shot 1]\n'
'The target video is an edited version of <Video 1>. Preserve its shot, camera, '
'timing, motion and all elements not explicitly requested to change. '
'Keep the beginning and ending visually continuous with the source. '
'Apply only the following edit, using additional references as specified:\n'+c['prompt'].strip())
settings=mask_settings(c['edit'].get('mask'))
key=json.dumps([str(source),plan,width,height,prompt,c['refs'],settings,c['edit']['anchor_edges']],sort_keys=True)
reused=prepared is not None and prepared.get('key')==key
if reused:
cond,latent=prepared['cond'],prepared['latent']
update('running','Provino · riuso di video, prompt e maschera già preparati',active='edit')
else:
if prepared is not None:prepared.clear()
update('running','Lettura della sola selezione…',active='edit')
selected=segment_tensor(source,plan['start'],n,width,height,interrupt,
end=plan['end'],source_fps=meta['fps'],last_time=plan['last_source_time'],resize_size=(content_width,content_height))
images={};videos={'ref_video_1':selected}
if guide:
# The reference must also show the approved edit; the old source wall
# would otherwise keep competing with the transferred draft latent.
gw,gh=guide['width'],guide['height']
videos['ref_video_1']=segment_tensor(reference_movie(root,guide),0,n,math.ceil(gw/32)*32,math.ceil(gh/32)*32,interrupt,
end=plan['duration'],last_time=plan['last_source_time']-plan['start'])
for r in c['refs']:
if r['kind']=='image':
image=director.load_image(r['name'])
ref_edge=max(guide['width'],guide['height']) if guide else max(content_width,content_height)
if ref_edge and max(image.shape[1:3])>ref_edge:
import torch.nn.functional as F
ratio=ref_edge/max(image.shape[1:3])
size=tuple(max(32,round(d*ratio/32)*32) for d in image.shape[1:3])
image=F.interpolate(image.movedim(-1,1),size=size,mode='area').movedim(1,-1)
images[f'ref_image_{len(images)+1}']=image
else:
p=director.input_file(r['name']);m=cached_probe(p)
rn=max(5,math.floor((m['duration']*24-5)/17)*17+5)
if rn>n:raise ValueError('Un video reference è più lungo del tratto editato: accorcialo prima di caricarlo.')
ratio=min(1.,max(content_width,content_height)/max(m['width'],m['height']))
rw,rh=(max(32,round(m[k]*ratio/32)*32) for k in ('width','height'))
videos[f'ref_video_{len(videos)+1}']=segment_tensor(p,0,rn,rw,rh,interrupt,resize_size=(rw,rh))
interrupt();update('running',f'Video Edit · {content_width} × {content_height} · preparazione Ref2VA')
cond,latent=MiniMaxH3ReferenceToVideo.execute(res['clip'],prompt,width,height,n,'match',
vae=res['vae'],audio_vae=res['audio'],ref_images=images,ref_videos=videos)
interrupt()
if settings['enabled']:
update('running','Codifica del sorgente e maschera nativa H3')
latent=prepare_masked_latent(director,latent,res['vae'],selected,director.input_file(settings['source']),settings,plan,
(content_width,content_height),interrupt)
if c['edit']['anchor_edges'] and not settings['enabled']:
cond=MiniMaxH3AddGuide.execute(cond,latent,0,vae=res['vae'],image=selected[:1])[0]
cond=MiniMaxH3AddGuide.execute(cond,latent,-1,vae=res['vae'],image=selected[-1:])[0]
del selected,images,videos
if prepared is not None:prepared.update(key=key,cond=cond,latent=latent)
interrupt();timings['prepare']=round(time.monotonic()-started,2)
effective=copy.deepcopy(sampling if sampling is not None else (trial_sampling(c) if trial else c['edit']))
model_config=copy.deepcopy(c);model_config['edit']=effective
if trial:model_config['preview']['enabled']=bool(c['edit'].get('trial_live_preview',False))
model=director.prepare_model(res,model_config,{'loras':c['common_loras']},'edit',uid)
phase='Provino edit' if trial else 'Video Edit'
update('running',f'{phase} · {content_width} × {content_height} · {effective["steps"]} passaggi')
sampled=time.monotonic()
mask_report=inspect_native_mask(latent) if settings['enabled'] else dict(enabled=False)
development=dict(method='regenerate')
if guide:
update('running','Sviluppo edit · trasferimento del provino approvato e della sua maschera')
def read_trial(movie):
tw,th=guide['width'],guide['height'];pw=math.ceil(tw/32)*32;ph=math.ceil(th/32)*32
return segment_tensor(movie,0,n,pw,ph,interrupt,end=plan['duration'],
last_time=plan['last_source_time']-plan['start'])
latent,development=guide_latent(director,root,guide,res['vae'],latent,width,height,read_trial,interrupt)
if settings['enabled']:mask_report=inspect_native_mask(latent)
result=director.sample(model,cond,latent,{**effective,'lock_audio':False,'require_edit_mask':settings['enabled']},int(c['seed']),progress=report)
interrupt();timings['sample']=round(time.monotonic()-sampled,2);decoded=time.monotonic()
update('running',phase+' · decodifica')
output,_=director.decode(res,result,False)
interrupt();timings['decode']=round(time.monotonic()-decoded,2);exported=time.monotonic()
folder=root/'edits'/uuid.uuid4().hex;folder.mkdir(parents=True)
latent_path=None
if trial:
import torch
from .dogma_h3_edit_develop import pack
latent_path=folder/'approved.pt'
torch.save(pack(result),latent_path)
patch=folder/'generated.nut'
update('running','Video Edit · rimozione bordi tecnici e raccordo')
job=re.sub(r'[^\w.-]+','_',c['job'])[:80] or 'DOGMA'
settings=mask_settings(c['edit'].get('mask'))
mask_path=director.input_file(settings['source']) if settings['enabled'] else None
mixed=folder/'composited.nut'
final=folder/(job+('_H3_EDIT_TRIAL.mp4' if trial else '_H3_VIDEO_EDIT.mp4'))
update('running','Composizione del provino' if trial else 'Ricostruzione del video completo · audio originale')
try:
save_patch(output,patch,content_width,content_height,n,interrupt)
del result,output,cond,latent,model,res
if trial:
write_segment(source,patch,mixed,meta,plan,mask_path=mask_path,settings=settings,
size=(content_width,content_height),fade=c['edit']['fade'],
interrupt=interrupt)
if trial:
encode_trial(mixed,final,plan['duration'],interrupt)
info=dict(audio_copied=False,fps=meta['fps'],width=content_width,height=content_height)
else:
info=compose(source,patch,final,meta,plan,c['edit']['fade'],interrupt,mask_path=mask_path,settings=settings)
except BaseException:
patch.unlink(missing_ok=True)
if latent_path:latent_path.unlink(missing_ok=True)
raise
finally:
mixed.unlink(missing_ok=True)
timings['export']=round(time.monotonic()-exported,2)
saved_path,export_error=(str(final.resolve()),None) if trial else export_final(director,final,c)
return dict(id=uuid.uuid4().hex,label='Provino edit' if trial else 'Video completo · edit applicato',video=director.view_file(final),
saved_path=saved_path,export_error=export_error,complete=True,kind='edit_trial' if trial else 'edit',
selection=plan,duration=plan['duration'] if trial else meta['duration'],config=copy.deepcopy(c),
segment_only=trial,prompt=c['prompt'],seed=int(c['seed']),loras=copy.deepcopy(c['common_loras']),sampling={k:effective[k] for k in SAMPLING_KEYS if k in effective},mask_report=mask_report,
elapsed_seconds=round(time.monotonic()-started,2),timings=timings,prepared_reused=reused,
latent=str(latent_path.relative_to(root)) if latent_path else None,
latent_sha256=fingerprint(latent_path) if latent_path else None,video_sha256=fingerprint(final),development=development,
raw_patch=str(patch.relative_to(root)),raw_patch_sha256=fingerprint(patch),
generation_width=content_width,generation_height=content_height,
**{**info,'timing_version':2})
def export_final(director,final,c):
try:return director.export_file(final,c),None
except (OSError,ValueError) as exc:
# The completed master stays registered even if its extra copy fails.
return str(final.resolve()),str(exc)
def preserve_trial(c,root,selected,update,interrupt):
"""Restitch the raw approved generation; never upscale a lossy/stuttering preview."""
from . import dogma_h3_director_v134 as director
import uuid
source=director.input_file(c['edit']['source']);meta,plan=check_config(c,director.input_file)
approved=approved_movie(root,selected)
raw=ensure_trial_patch(director,root,selected,interrupt)
folder=root/'edits'/uuid.uuid4().hex;folder.mkdir(parents=True)
final=folder/((__import__('re').sub(r'[^\w.-]+','_',c['job'])[:80] or 'DOGMA')+'_H3_VIDEO_EDIT.mp4')
settings=mask_settings(c['edit'].get('mask'))
mask_path=director.input_file(settings['source']) if settings['enabled'] else None
update('running','Mantieni edit · ingrandimento del provino scelto, senza nuova generazione')
info=compose(source,raw,final,meta,plan,c['edit']['fade'],interrupt,mask_path=mask_path,settings=settings)
saved_path,export_error=export_final(director,final,c)
return dict(id=uuid.uuid4().hex,complete=True,kind='edit',video=director.view_file(final),
saved_path=saved_path,export_error=export_error,config=copy.deepcopy(c),selection=plan,segment_only=False,
duration=meta['duration'],prompt=c['prompt'],seed=c['seed'],video_sha256=fingerprint(final),
raw_patch=str(raw.relative_to(root)),raw_patch_sha256=fingerprint(raw),
generation_width=selected['width'],generation_height=selected['height'],
development=dict(method='preserve',trial=selected['id'],input='raw_approved_generation',raw_patch_sha256=fingerprint(raw),video_sha256=fingerprint(approved)),**info)
def ensure_trial_patch(director,root,trial,interrupt,vae=None):
"""1.0.46 kept raw latents: recover their original frames without rerunning H3."""
import uuid
raw=trial.get('raw_patch')
if raw:
path=(root/raw).resolve()
if not path.is_relative_to(root.resolve()) or not path.is_file():raise ValueError('Fotogrammi originali del provino non disponibili.')
if trial.get('raw_patch_sha256') and fingerprint(path)!=trial['raw_patch_sha256']:raise ValueError('Fotogrammi del provino modificati.')
return path
relative=trial.get('latent')
if not relative:raise ValueError('Questo vecchio provino non ha i latenti per recuperare i fotogrammi persi. Rigenera soltanto il provino con i nodi aggiornati.')
path=(root/relative).resolve()
if not path.is_relative_to(root.resolve()) or not path.is_file():raise ValueError('Latenti del provino non disponibili; nessuna sostituzione con il sorgente.')
if trial.get('latent_sha256') and fingerprint(path)!=trial['latent_sha256']:raise ValueError('Latenti del provino modificati.')
import torch
from .dogma_h3_edit_develop import unpack
latent=unpack(torch.load(path,map_location='cpu',weights_only=True))
if vae is None:
import nodes
vae=nodes.VAELoader().load_vae(trial['config']['models']['vae'])[0]
interrupt();images,_=director.decode({'vae':vae},latent,False)
directory=root/'recovered'/uuid.uuid4().hex;directory.mkdir(parents=True)
raw=directory/'generated.nut';n=trial['selection']['generation_frames']
save_patch(images,raw,trial['width'],trial['height'],n,interrupt);del images,latent
c=trial['config'];settings=mask_settings(c['edit'].get('mask'));source=director.input_file(c['edit']['source'])
meta=cached_probe(source);plan=plan_interval(meta,c['edit']['start'],c['edit']['end'])
mixed=directory/'composited.nut';preview=directory/'RECOVERED_EDIT_TRIAL.mp4'
try:
write_segment(source,raw,mixed,meta,plan,mask_path=director.input_file(settings['source']) if settings['enabled'] else None,
settings=settings,size=(trial['width'],trial['height']),fade=c['edit']['fade'],interrupt=interrupt)
encode_trial(mixed,preview,plan['duration'],interrupt)
finally:mixed.unlink(missing_ok=True)
trial.update(raw_patch=str(raw.relative_to(root)),raw_patch_sha256=fingerprint(raw),timing_repaired=True,
corrected_video=director.view_file(preview),corrected_path=str(preview.resolve()),corrected_video_sha256=fingerprint(preview))
return raw
def encode_trial(source,dest,duration,interrupt):
args=[ffmpeg(),'-hide_banner','-loglevel','error','-nostdin','-y','-i',str(source),'-t',str(duration),
'-an','-c:v','libx264','-crf','18','-preset','veryfast','-pix_fmt','yuv420p','-fps_mode','passthrough',
'-enc_time_base:v','1:1000000','-movflags','+faststart',str(dest)]
with tempfile.TemporaryFile() as log:
process=subprocess.Popen(args,stdout=subprocess.DEVNULL,stderr=log)
try:
while process.poll() is None: interrupt();time.sleep(.1)
if process.returncode:
log.seek(0);raise ValueError('Provino non codificato: '+log.read().decode(errors='replace')[-2000:])
except BaseException:
if process.poll() is None: process.kill();process.wait()
dest.unlink(missing_ok=True);raise
def run_edit(c,root,st,update,progress,uid):
from . import dogma_h3_director_v134 as director
def finish(trial_id,resources=None,batch=None):
selected=next((x for x in st.get('edit_trials',[]) if x['id']==trial_id),None)
if selected is None:raise ValueError('Scegli prima un provino edit.')
config=copy.deepcopy(selected['config']);config['action']='finish';config['output_dir']=c['output_dir'];config['job']=c['job']
options=batch.final_options if batch and batch.final_options is not None else final_options(c['edit'])
config['output_dir']=options['output_dir'] or c['output_dir']
if not config['output_dir'].strip():
import folder_paths
config['output_dir']=folder_paths.get_output_directory()
effective=final_sampling(selected,options)
if options['method']=='guided':effective['denoise']=options['denoise']
else:effective['denoise']=1.
config['edit'].update({k:effective[k] for k in SAMPLING_KEYS if k in effective},final_mode=options['mode'],final_steps=options['steps'],
final_method=options['method'],final_denoise=options['denoise'],final_output_dir=config['output_dir'],final_resolution=options['resolution'])
config['edit']['mask']={**(config['edit'].get('mask') or {}),**options['matte']}
if options['mode']=='standard' or is_ref_turbo(effective.get('turbo','')):
config['common_loras']=[x for x in config['common_loras'] if not is_ref_turbo(x.get('name',''))]
if config.get('models')!=c.get('models'):resources=None
if batch:st['edit_batch']=batch.snapshot()
st['edit_target']=dict(trial=selected['id'],label=selected['label'],seed=selected['seed'],mode=options['mode'],sampling={k:effective[k] for k in SAMPLING_KEYS if k in effective})
if options['method']!='regenerate':approved_movie(root,selected)
update('running','Provino scelto · '+('sviluppo alla dimensione originale' if options['method']=='guided' else 'ingrandimento senza rigenerazione' if options['method']=='preserve' else 'nuova generazione dal sorgente'),action='finish',active='edit')
if options['method']=='preserve':
import comfy.model_management as mm
item=preserve_trial(config,root,selected,update,mm.throw_exception_if_processing_interrupted)
else:
item=render_edit(config,root,st,update,progress,uid,trial=False,resources=resources,sampling=effective,
guide=selected if options['method']=='guided' else None)
item.update(trial=selected['id'],origin_trial_label=selected['label'],label='Video completo · da '+selected['label'])
st.setdefault('edits',[]).append(item)
if batch:batch.phase='done';st['edit_batch']=batch.snapshot()
update('error' if item.get('export_error') else 'done',
'Video pronto e conservato nella sessione; copia nella cartella scelta non riuscita: '+item['export_error'] if item.get('export_error') else 'Video completo salvato. Il percorso è riportato sotto il confronto.',action='finish',active=None)
if c['action']=='draft':
trials=director.make_plan(c)
# Validate all trials before loading a model or erasing a previous result.
configs=[]
for trial in trials:
config=copy.deepcopy(c);config['prompt']=trial['prompt'];config['seed']=trial['seed'];config['common_loras']=trial['loras']
check_config(config,director.input_file);configs.append(config)
sampling=trial_sampling(c)
batch=begin_batch(c['session'],len(configs),(x['id'] for x in st.get('edit_trials',[]) if x.get('complete')))
prepared={};resources=None
try:
st['edit_batch']=batch.snapshot();update('running','Provini edit · caricamento condiviso del modello')
try:
batch.checkpoint();resources=director.load_resources(configs[0])
for i,config in enumerate(configs):
batch.checkpoint();batch.current=i+1;st['edit_batch']=batch.snapshot()
update('running',f'Provino edit {i+1}/{len(configs)} · {config["edit"].get("trial_edge",512)} px · {sampling["steps"]} passaggi')
item=render_edit(config,root,st,update,progress,uid,trial=True,resources=resources,prepared=prepared,
checkpoint=batch.checkpoint,sampling=sampling)
item['label']=f'Provino edit {len(st.get("edit_trials",[]))+1}'
st.setdefault('edit_trials',[]).append(item);batch.add(item['id']);st['edit_batch']=batch.snapshot()
update('running',f'Provino edit {i+1}/{len(configs)} pronto',active=None)
except PromoteEdit:
pass # Only this session's unfinished draft is abandoned.
chosen=batch.seal();prepared.clear();st['edit_batch']=batch.snapshot()
if chosen:
finish(chosen,resources,batch)
else:update('ready','Provini edit pronti. Scegli quale rigenerare alla dimensione originale.',active=None)
finally:
prepared.clear();batch.close()
else:
finish(c['edit'].get('selected_trial'))
def register_edit_routes(routes,input_file):
from aiohttp import web
import asyncio
from functools import lru_cache
slots=asyncio.Semaphore(3)
cleanup=register_mask_routes(routes,input_file,probe,plan_interval)
register_promotion_route(routes)
@lru_cache(maxsize=128)
def metadata_cached(path,size,mtime):
return probe(Path(path))
@lru_cache(maxsize=256)
def thumbnail_cached(path,size,mtime,second):
return thumbnail(Path(path),second)
@routes.get('/dogma/h3/v2/edit/metadata')
async def metadata_route(request):
try:
path=input_file(request.query.get('name',''));s=path.stat()
async with slots:
data=await asyncio.to_thread(metadata_cached,str(path),s.st_size,s.st_mtime_ns)
return web.json_response(data)
except (ValueError,OSError) as exc:
raise web.HTTPBadRequest(text=str(exc))
@routes.get('/dogma/h3/v2/edit/thumbnail')
async def thumbnail_route(request):
try:
path=input_file(request.query.get('name',''));s=path.stat()
second=float(request.query.get('time','0'))
if not math.isfinite(second) or not 0<=second<=86400*7:
raise ValueError('Tempo anteprima non valido.')
async with slots:
data=await asyncio.to_thread(thumbnail_cached,str(path),s.st_size,s.st_mtime_ns,round(second,4))
return web.Response(body=data,content_type='image/jpeg',headers={'Cache-Control':'private, max-age=60'})
except (ValueError,OSError) as exc:
raise web.HTTPBadRequest(text=str(exc))
return cleanup
+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"}
+557
View File
@@ -0,0 +1,557 @@
"""Selective motion repair. Original timestamps, frame count, audio and size survive.
Detection uses low-resolution tracked motion, never a hard-coded Seedance cadence.
RIFE 4.26 reconstructs only selected times, on the machine running ComfyUI.
"""
from __future__ import annotations
import hashlib
import json
import math
import os
from pathlib import Path
import shutil
import tempfile
import threading
import time
import urllib.request
import zipfile
from fractions import Fraction
import numpy as np
MODEL_URL = 'https://huggingface.co/hzwer/RIFE/resolve/01fdc7e97404120c243c3ea7b427046e5dc7643e/RIFEv4.26_0921.zip'
ARCHIVE_SHA256 = '1fa9b9cda3d9b8c3e301359e2595960902f97bf926c08598b0e9957a3f3f760e'
WEIGHT_SHA256 = '45c7f74156704769dc9f85cfcaf8552e1e926f9399dcfa3a553dee88fac6f53f'
_MODEL_LOCK = threading.Lock()
_RENDER_LOCK = threading.Lock()
class RepairCancelled(Exception):
pass
def _check(cancel):
if cancel:
cancel()
def _digest(path):
result=hashlib.sha256()
with open(path, 'rb') as f:
while block:=f.read(1024*1024):result.update(block)
return result.hexdigest()
def model_file(directory, cancel=None, progress=None):
"""Only verified weights are downloaded; remote Python is never executed."""
directory = Path(directory)
path = directory / 'rife426.pkl'
while not _MODEL_LOCK.acquire(timeout=.1):_check(cancel)
try:
_check(cancel)
if path.is_file() and _digest(path) == WEIGHT_SHA256:
return path
directory.mkdir(parents=True, exist_ok=True)
if progress:
progress('Download modello · solo al primo utilizzo', 0)
with tempfile.TemporaryDirectory(prefix='rife-', dir=directory) as temp:
archive = Path(temp) / 'model.zip'
with urllib.request.urlopen(MODEL_URL, timeout=30) as response, archive.open('wb') as out:
size = 0
while block := response.read(1024 * 1024):
_check(cancel)
size += len(block)
if size > 30_000_000:
raise ValueError('Download RIFE di dimensione inattesa.')
out.write(block)
if _digest(archive) != ARCHIVE_SHA256:
raise ValueError('Verifica del modello RIFE non riuscita. Riprova il download.')
weight = Path(temp) / 'weights.pkl'
with zipfile.ZipFile(archive) as z:
weight.write_bytes(z.read('RIFEv4.26_0921/flownet.pkl'))
if _digest(weight) != WEIGHT_SHA256:
raise ValueError('Pesi RIFE non validi.')
_check(cancel)
weight.replace(path)
return path
finally:
_MODEL_LOCK.release()
def measure_pair(a, b):
"""Track real displacements; pixel differences alone confuse light and motion."""
import cv2
af, bf = a.astype(np.float32), b.astype(np.float32)
diff = float(np.mean(np.abs(bf-af)))
light = float(abs(np.mean(bf)-np.mean(af)))
row = dict(diff=diff, brightness=light, motion=0., x=0., y=0., reliability=0., cut=False)
points = cv2.goodFeaturesToTrack(a, 500, .015, 5)
if points is None or len(points) < 12:
row['cut'] = diff > 18
return row
q, ok, _ = cv2.calcOpticalFlowPyrLK(a, b, points, None, winSize=(21,21), maxLevel=3)
back, ok2, _ = cv2.calcOpticalFlowPyrLK(b, a, q, None, winSize=(21,21), maxLevel=3)
good = (ok[:,0] > 0) & (ok2[:,0] > 0) & (np.linalg.norm(back[:,0]-points[:,0], axis=1) < .6)
row['reliability'] = float(good.mean())
vectors = (q[:,0]-points[:,0])[good]
if len(vectors) >= 12:
# A camera estimate needs agreement across the image, not just one subject.
p, tracked = points[good,0], q[good,0]
transform, inside = cv2.estimateAffinePartial2D(p, tracked, method=cv2.RANSAC,
ransacReprojThreshold=.25, maxIters=500, confidence=.995, refineIters=5)
if transform is not None and inside is not None:
selected=p[inside[:,0]>0];h,w=a.shape
occupied={(min(3,int(x*4/w)),min(2,int(y*3/h))) for x,y in selected}
center=np.array([w/2,h/2]);delta=transform[:,:2]@center+transform[:,2]-center
coverage=float(np.prod(np.ptp(selected,axis=0)/[w,h])) if len(selected)>1 else 0.
row['camera']=dict(x=float(delta[0]),y=float(delta[1]),
inliers=float(inside.mean()),coverage=coverage,cells=len(occupied),
scale=float(np.sqrt(abs(np.linalg.det(transform[:,:2])))),
angle=float(np.degrees(np.arctan2(transform[1,0],transform[0,0]))))
magnitudes=np.linalg.norm(vectors,axis=1)
moving=vectors[magnitudes>max(.05,float(np.percentile(magnitudes,90))*.35)]
# A moving subject can occupy less than half of an otherwise static shot.
if np.median(magnitudes)<.04 and len(moving)>=max(12,len(vectors)*.1):vectors=moving
row['motion'] = float(np.percentile(np.linalg.norm(vectors, axis=1), 75))
row['x'], row['y'] = map(float, np.median(vectors, axis=0))
# Histogram changes plus failed tracking distinguish cuts from fast pans.
ha = cv2.calcHist([a],[0],None,[32],[0,256]); hb = cv2.calcHist([b],[0],None,[32],[0,256])
ha /= max(1., float(ha.sum())); hb /= max(1., float(hb.sum()))
hist = cv2.compareHist(ha, hb, cv2.HISTCMP_BHATTACHARYYA)
row['cut'] = bool((diff > 24 and row['reliability'] < .45) or (diff > 36 and hist > .4))
return row
def analyze(source, cancel=None, progress=None):
import av
import cv2
start = time.perf_counter()
with av.open(str(source)) as c:
v = c.streams.video[0]
v.thread_type = 'AUTO';v.thread_count=4
fps = v.average_rate or v.base_rate
if not fps or fps <= 0:
raise ValueError('Il video non dichiara un framerate valido.')
meta = dict(fps=str(fps), time_base=str(v.time_base), width=v.width, height=v.height,
pixel_format=v.format.name, bit_depth=max(x.bits for x in v.format.components),
color_range=v.codec_context.color_range, colorspace=v.codec_context.colorspace,
color_primaries=v.codec_context.color_primaries, color_trc=v.codec_context.color_trc,
audio_streams=len(c.streams.audio), sample_aspect_ratio=str(v.sample_aspect_ratio or Fraction(1)),
duration=float(v.duration*v.time_base) if v.duration else None)
frames, pts, durations, metrics = [], [], [], []
width = min(384, v.width); height = max(16, round(v.height * width / v.width))
for i, f in enumerate(c.decode(v)):
_check(cancel)
# swscale shrinks before transferring the ndarray.
gray = f.reformat(width=width, height=height, format='gray').to_ndarray()
metrics.append(measure_pair(frames[-1], gray) if frames else dict(diff=0.,brightness=0.,motion=0.,x=0.,y=0.,reliability=1.,cut=False))
frames.append(gray)
pts.append(int(f.pts) if f.pts is not None else round(i/fps/v.time_base))
durations.append(int(f.duration or round(1/fps/v.time_base)))
if progress and i % 12 == 0:
progress('Analisi movimento', .18 * min(1., (i+1)/max(1,v.frames or i+12)))
if not frames:
raise ValueError('Il video non contiene fotogrammi decodificabili.')
if any(b <= a for a,b in zip(pts,pts[1:])):
raise ValueError('I timestamp del video non sono crescenti.')
meta.update(frames=len(frames), pts=pts, durations=durations,
analysis_seconds=round(time.perf_counter()-start,3))
return meta, frames, metrics
def plan_repair(metrics, times, fps):
"""Infer held frames and isolated/periodic jumps, with fixed local endpoints."""
n = len(metrics)
positions = np.arange(n, dtype=float)
motion = np.array([x['motion'] for x in metrics])
cuts = {i for i,m in enumerate(metrics) if m['cut']}
ratios = np.ones(n)
eligible = np.zeros(n, dtype=bool)
for i in range(3,n-3):
if any(x in cuts for x in range(i-3,i+4)):
continue
nearby = np.r_[motion[i-3:i], motion[i+1:i+4]]
base = float(np.median(nearby))
if base < .045:
continue
ratios[i] = motion[i]/base
before = np.array([np.median([metrics[j][k] for j in range(i-3,i)]) for k in ('x','y')])
after = np.array([np.median([metrics[j][k] for j in range(i+1,i+4)]) for k in ('x','y')])
current = np.array([metrics[i]['x'],metrics[i]['y']])
cosine = lambda x,y: float(np.dot(x,y)/max(1e-8,np.linalg.norm(x)*np.linalg.norm(y)))
eligible[i] = (metrics[i]['reliability'] > .65 and cosine(before,after) > .9
and cosine(current,before+after) > .75
and .6 < np.median(motion[i-3:i])/max(.01,np.median(motion[i+1:i+4])) < 1.67
and metrics[i]['brightness'] < max(.8,metrics[i]['diff']*.65))
spikes = {i for i in range(n) if eligible[i] and 1.65 < ratios[i] < 3.1}
patterns = []
# Search the cadence; do not assume 24 frames, 24 fps, or phase zero.
eligible_indices=np.flatnonzero(eligible);spike_indices=np.array(sorted(spikes),dtype=int)
for period in range(2, min(121, n//3+1)):
counts=np.bincount(eligible_indices%period,minlength=period)
hits=np.bincount(spike_indices%period,minlength=period)
for phase in np.flatnonzero((hits>=3)&(hits/np.maximum(1,counts)>=.65)):
patterns.append(dict(period=period,phase=int(phase),support=int(hits[phase]),count=int(counts[phase])))
patterns.sort(key=lambda x:(x['support']/x['count'],x['support'],-x['period']),reverse=True)
pattern = patterns[0] if patterns else None
if pattern:
spikes.update(i for i in range(3,n-3) if eligible[i] and i%pattern['period']==pattern['phase'] and ratios[i]>1.22)
pattern['seconds'] = round(pattern['period']/float(fps),6)
duplicates = []
i = 2
while i < n-2:
rest = float(np.median(motion[max(1,i-3):i]))
if rest < .06 or metrics[i]['diff'] > .65 or motion[i] > rest*.16:
i += 1; continue
first = i
while i < n-1 and metrics[i]['diff'] < .65 and motion[i] < rest*.16:
i += 1
last = i-1
# Long pauses and the beginning/end of a shot remain intentional holds.
if (last-first < max(1,min(4,round(float(fps)*.15))) and i<n-1
and not any(j in cuts for j in range(first-1,i+2))
and motion[i] > rest*1.45 and metrics[i]['reliability']>.65):
duplicates.append((first,last))
spikes.discard(i)
groups = []
for i in sorted(spikes):
left, right = i-3, i+2
if groups and left <= groups[-1][1]:
groups[-1] = (groups[-1][0],max(right,groups[-1][1]))
else:
groups.append((left,right))
for left,right in groups:
durations = np.diff(times[left:right+1])
units = durations.copy()
for j in range(left+1,right+1):
if j in spikes:
units[j-left-1] *= min(2.5, max(1.22,ratios[j]))
physical = np.r_[0., np.cumsum(units)]
target = (times[left:right+1]-times[left])/(times[right]-times[left])*physical[-1]
positions[left:right+1] = np.interp(target,physical,np.arange(left,right+1))
for first,last in duplicates:
left,right = first-1,last+1
positions[first:last+1] = left+(times[first:last+1]-times[left])/(times[right]-times[left])*(right-left)
requests = {}
for i, pos in enumerate(positions):
run = next(((a,b) for a,b in duplicates if a<=i<=b),None)
if abs(pos-i) < .025 and run is None:
continue
left = int(math.floor(pos)); right = left+1; alpha = float(pos-left)
# Held runs must interpolate between the two distinct endpoint images.
if run:
left,right = run[0]-1,run[1]+1
alpha = float((times[i]-times[left])/(times[right]-times[left]))
if alpha < .025 or alpha > .975 or right in cuts:
continue
requests[i] = (left,right,alpha)
return requests, dict(jump_frames=sorted(spikes),held_ranges=[list(x) for x in duplicates],
cadence=pattern, cuts=sorted(cuts), repaired_frames=sorted(requests),
regions=[list(x) for x in groups],
jump_ratios={str(i):round(float(ratios[i]),3) for i in sorted(spikes)})
def plan_camera(metrics, times, fps, details, shape):
"""Small translation refinement only in reliably tracked, stuttering pans.
This is not general stabilization: clean shots, cuts, handheld movement,
zoom/rotation and large corrections are deliberately left alone.
"""
from scipy.signal import savgol_filter
n=len(metrics);actual=np.zeros((n,2));target=np.zeros((n,2));enabled=np.zeros(n,dtype=bool)
h,w=shape;limit=np.array([w,h])*.004
shots=list(zip([0,*details['cuts']],[*details['cuts'],n]))
accepted=[]
for first,end in shots:
count=end-first
events=[i for i in details['jump_frames'] if first<i<end]
if count<max(12,float(fps)*.6) or len(events)<2:continue
cameras=[m.get('camera') for m in metrics[first+1:end]]
if any(c is None for c in cameras):continue
reliable=[c['inliers']>=.55 and c['coverage']>=.3 and c['cells']>=6
and abs(c['scale']-1)<.003 and abs(c['angle'])<.15 for c in cameras]
if np.mean(reliable)<.95:continue
velocity=np.array([[c['x'],c['y']] for c in cameras])
axis=int(np.argmax(np.abs(np.median(velocity,axis=0))))
speed=velocity[:,axis];direction=np.sign(np.median(speed))
if np.median(np.abs(speed))<.08 or np.mean(speed*direction>=-.025)<.95:continue
path=np.vstack([np.zeros(2),np.cumsum(velocity,axis=0)])
grid=np.linspace(times[first],times[end-1],count)
uniform=np.stack([np.interp(grid,times[first:end],path[:,a]) for a in range(2)],axis=1)
window=min(count if count%2 else count-1,max(7,round(float(fps))//2*2+1))
smooth=savgol_filter(uniform,window,3,axis=0)
smooth=np.stack([np.interp(times[first:end],grid,smooth[:,a]) for a in range(2)],axis=1)
smooth-=smooth[0]
smooth+=((times[first:end]-times[first])/(times[end-1]-times[first]))[:,None]*(path[-1]-smooth[-1])
offset=smooth-path
# Reject the whole shot instead of clipping shifts and creating new jerks.
if np.any(np.max(np.abs(offset),axis=0)>limit):continue
actual[first:end]=path;target[first:end]=smooth;enabled[first:end]=True
accepted.append([first,end-1])
return actual,target,enabled,dict(shots=accepted,limit_fraction=.004)
def _matrix(meta):
# swscale's matrix IDs differ from AVColorSpace for SMPTE170M.
return {1:1,4:4,5:5,6:5,7:7,9:9,10:9}.get(meta['colorspace'],5)
class Interpolator:
def __init__(self, weights, device=None, meta=None):
import torch
from .dogma_rife_arch import IFNet
self.device = torch.device(device or ('cuda' if torch.cuda.is_available() else 'cpu'))
self.meta=meta
if self.device.type=='cuda':
try:
import comfy.model_management as management
# Release other Comfy models only when this render actually needs VRAM.
pixels=(meta['width']*meta['height']) if meta else 2073600
management.free_memory(max(2_500_000_000,pixels*1200),self.device)
except ImportError:pass
self.model = IFNet()
state = torch.load(weights,map_location='cpu',weights_only=True)
state = {k.removeprefix('module.'):v for k,v in state.items()}
state = {k:v for k,v in state.items() if not k.startswith(('teacher.','caltime.'))}
self.model.load_state_dict(state,strict=True)
self.model.eval().to(self.device)
self.cache = {}
def frame(self, first, second, alpha):
import torch
import torch.nn.functional as F
import av
h,w = first.height,first.width
def tensor(frame):
key = frame.pts
if key not in self.cache:
if self.meta:
rgb=frame.reformat(format='rgb48le',src_colorspace=_matrix(self.meta),src_color_range=self.meta['color_range'] or 1,dst_color_range=2)
a=rgb.to_ndarray().astype(np.float32)/65535.
else:a = frame.to_ndarray(format='rgb48le').astype(np.float32)/65535.
self.cache[key] = torch.from_numpy(a).permute(2,0,1).unsqueeze(0).to(self.device)
return self.cache[key]
a,b = tensor(first),tensor(second)
self.cache = {k:v for k,v in self.cache.items() if k in (first.pts,second.pts)}
x = F.pad(torch.cat((a,b),1),(0,(-w)%64,0,(-h)%64),mode='replicate')
with torch.inference_mode():
result = self.model(x,alpha,[16,8,4,2,1])[2][-1][0,:,:h,:w]
rgb=result.permute(1,2,0).cpu().numpy()
# CPU conversion avoids several seconds of first-use CUDA kernel compilation.
if not np.isfinite(rgb).all():
raise ValueError('RIFE ha prodotto un fotogramma non valido.')
rgb=np.rint(np.clip(rgb,0,1)*65535).astype(np.uint16)
return av.VideoFrame.from_ndarray(rgb,format='rgb48le')
def close(self):
from .dogma_rife_arch import backwarp_tenGrid
self.cache.clear();backwarp_tenGrid.clear()
self.model.to('cpu')
def _encoder(path, meta):
import av
depth = meta['bit_depth'] > 8
candidates = [('hevc_nvenc','p010le' if depth else 'yuv420p',dict(preset='p5',tune='hq',rc='vbr',cq='16',b='0',profile='main10' if depth else 'main')),
('libx265','yuv420p10le' if depth else 'yuv420p',dict(preset='fast',crf='14',**{'x265-params':'log-level=error:pools=4'}))]
errors = []
for codec,pixel,options in candidates:
container = None
try:
container = av.open(str(path),'w',format='mp4',options={'movflags':'+faststart'})
stream = container.add_stream(codec,rate=Fraction(meta['fps']))
stream.width=meta['width'];stream.height=meta['height'];stream.pix_fmt=pixel;stream.options=options
stream.time_base=Fraction(meta['time_base']);stream.codec_context.time_base=stream.time_base
stream.codec_context.codec_tag='hvc1'
stream.codec_context.sample_aspect_ratio=Fraction(meta['sample_aspect_ratio'])
for name in ('color_range','colorspace','color_primaries','color_trc'):
setattr(stream.codec_context,name,meta[name])
stream.codec_context.open()
return container,stream,codec
except Exception as exc:
errors.append(str(exc))
if container:
container.close()
raise RuntimeError('Codifica video non disponibile: '+'; '.join(errors))
def _translate_frame(frame, shift, meta):
"""Shift native YUV planes: avoid two full RGB conversions per camera frame."""
import av
import cv2
deep=meta['bit_depth']>8;pixel='yuv420p10le' if deep else 'yuv420p'
if frame.format.name=='rgb48le':
frame=frame.reformat(format=pixel,src_colorspace=_matrix(meta),dst_colorspace=_matrix(meta),src_color_range=2,dst_color_range=meta['color_range'] or 1)
else:frame=frame.reformat(format=pixel)
result=av.VideoFrame(frame.width,frame.height,pixel)
dtype=np.uint16 if deep else np.uint8;itemsize=2 if deep else 1
for source,destination in zip(frame.planes,result.planes):
a=np.ndarray((source.height,source.line_size//itemsize),dtype=dtype,buffer=source)[:,:source.width]
matrix=np.array([[1,0,shift[0]*source.width/frame.width],[0,1,shift[1]*source.height/frame.height]],dtype=np.float32)
moved=cv2.warpAffine(a,matrix,(source.width,source.height),flags=cv2.INTER_LANCZOS4,borderMode=cv2.BORDER_REFLECT_101)
if deep:np.minimum(moved,1023,out=moved)
target=np.ndarray((destination.height,destination.line_size//itemsize),dtype=dtype,buffer=destination)
target[:,:destination.width]=moved
for name in ('color_range','colorspace','color_primaries','color_trc'):setattr(result,name,meta[name])
return result
def _verify(source, output, meta):
import av
with av.open(str(output)) as c:
v=c.streams.video[0]
frames=list((f.pts*f.time_base) for f in c.decode(v))
expected=[p*Fraction(meta['time_base']) for p in meta['pts']]
tolerance=max(Fraction(meta['time_base']),v.time_base)
if len(frames)!=len(expected) or any(abs(a-b)>tolerance for a,b in zip(frames,expected)):
raise ValueError('La verifica dei fotogrammi o della sincronizzazione non è riuscita.')
if (v.width,v.height)!=(meta['width'],meta['height']):
raise ValueError('La risoluzione del file corretto è cambiata.')
if max(x.bits for x in v.format.components)<meta['bit_depth']:
raise ValueError('La profondità colore del file corretto è cambiata.')
for name in ('color_range','colorspace','color_primaries','color_trc'):
if meta[name]!=(0 if name=='color_range' else 2) and getattr(v.codec_context,name)!=meta[name]:
raise ValueError('I metadati colore del file corretto sono cambiati.')
if len(set(np.diff(meta['pts'])))==1 and v.average_rate!=Fraction(meta['fps']):
raise ValueError('Il framerate del file corretto è cambiato.')
if meta['duration'] is not None and v.duration and abs(float(v.duration*v.time_base)-meta['duration'])>float(tolerance)*2:
raise ValueError('La durata del file corretto è cambiata.')
if len(c.streams.audio)!=meta['audio_streams']:
raise ValueError('Una traccia audio è assente dal file corretto.')
def audio_signature(path):
signatures=[]
with av.open(str(path)) as c:
states={s.index:[hashlib.sha256(),[]] for s in c.streams.audio}
for pk in c.demux(list(c.streams.audio)) if c.streams.audio else []:
if not pk.size:continue
h,ts=states[pk.stream.index];h.update(bytes(pk));ts.append((str(pk.pts*pk.time_base) if pk.pts is not None else None,str(pk.duration*pk.time_base)))
signatures=[(h.hexdigest(),ts) for h,ts in states.values()]
return signatures
if audio_signature(source)!=audio_signature(output):
raise ValueError('La verifica audio non è riuscita: originale conservato.')
def repair_video(source, output, model_directory, cancel=None, progress=None, device=None):
"""Write a second file atomically. Failure never damages the original."""
import av
source,output=Path(source).resolve(),Path(output).resolve()
if source==output or output.exists():
raise ValueError('Il fix richiede un nuovo file, distinto dall’originale.')
start=time.perf_counter()
meta,thumbs,metrics=analyze(source,cancel,progress)
times=np.array(meta['pts'],dtype=float)*float(Fraction(meta['time_base']))
requests,details=plan_repair(metrics,times,Fraction(meta['fps']))
camera_actual,camera_target,camera_enabled,camera_details=plan_camera(metrics,times,Fraction(meta['fps']),details,thumbs[0].shape)
report=dict(version=2,engine='RIFE 4.26 + restrained camera refinement',**{k:meta[k] for k in ('frames','fps','width','height','bit_depth','duration','audio_streams','analysis_seconds')},**details,
camera_refinement=camera_details)
output.parent.mkdir(parents=True,exist_ok=True)
fd,temp=tempfile.mkstemp(prefix='.dogma-fix-',suffix='.mp4',dir=output.parent);os.close(fd);temp=Path(temp)
interpolator=None;out=None
try:
if not requests:
shutil.copyfile(source,temp)
report.update(status='unchanged',interpolated_frames=0,encoder='stream copy')
else:
weights=model_file(model_directory,cancel,progress)
if progress:progress('Attesa correzione video',.2)
# Bound GPU/RAM use when several API branches finish together.
while not _RENDER_LOCK.acquire(timeout=.1):_check(cancel)
try:
_check(cancel)
interpolator=Interpolator(weights,device,meta)
out,video_out,codec=_encoder(temp,meta)
report['encoder']=codec;report['device']=str(interpolator.device)
render_start=time.perf_counter();cache={};current=-1;corrected_thumbs=list(thumbs);shifted=[];largest_shift=np.zeros(2)
with av.open(str(source)) as incoming:
original_video=incoming.streams.video[0];original_video.thread_type='AUTO';original_video.thread_count=4
audio={s.index:out.add_stream_from_template(s) for s in incoming.streams.audio}
def decoded():
for packet in incoming.demux([original_video,*incoming.streams.audio]):
_check(cancel)
if packet.stream.index==original_video.index:
yield from packet.decode()
elif packet.size and packet.dts is not None:
packet.stream=audio[packet.stream.index];out.mux(packet)
frames=iter(decoded())
for i in range(meta['frames']):
_check(cancel)
left,right,alpha=requests.get(i,(i,i,0.))
while current<max(i,right):
current+=1;cache[current]=next(frames)
if i in requests:
frame=interpolator.frame(cache[left],cache[right],alpha)
else:frame=cache[i]
if camera_enabled[i]:
pose=camera_actual[i]
if i in requests:
small=frame.reformat(width=thumbs[i].shape[1],height=thumbs[i].shape[0],format='gray').to_ndarray()
measured=measure_pair(thumbs[left],small).get('camera')
if measured and measured['inliers']>=.55:
pose=camera_actual[left]+[measured['x'],measured['y']]
else:pose=camera_actual[left]*(1-alpha)+camera_actual[right]*alpha
shift=(camera_target[i]-pose)*[meta['width']/thumbs[i].shape[1],meta['height']/thumbs[i].shape[0]]
if np.max(np.abs(shift))>.04:
# At most a narrow edge strip is extended; no crop or zoom.
frame=_translate_frame(frame,shift,meta);shifted.append(i)
largest_shift=np.maximum(largest_shift,np.abs(shift))
if frame.format.name=='rgb48le':
frame=frame.reformat(format=video_out.pix_fmt,src_colorspace=_matrix(meta),dst_colorspace=_matrix(meta),src_color_range=2,dst_color_range=meta['color_range'] or 1)
for name in ('color_range','colorspace','color_primaries','color_trc'):setattr(frame,name,meta[name])
if i in requests or camera_enabled[i]:
corrected_thumbs[i]=frame.reformat(width=thumbs[i].shape[1],height=thumbs[i].shape[0],format='gray').to_ndarray()
frame=frame.reformat(format=video_out.pix_fmt)
frame.pts=meta['pts'][i];frame.time_base=Fraction(meta['time_base'])
for packet in video_out.encode(frame):out.mux(packet)
# Keep endpoints of a held run until its last replacement.
upcoming=[requests[j][0] for j in range(i+1,min(i+7,meta['frames'])) if j in requests]
keep=min([i+1,*upcoming])
cache={k:v for k,v in cache.items() if k>=keep}
if progress and i%4==0:progress('Correzione scatti',.2+.65*(i+1)/meta['frames'])
# Drain trailing audio packets after the final video frame.
for _ in frames:pass
for packet in video_out.encode():out.mux(packet)
out.close();out=None
report['render_seconds']=round(time.perf_counter()-render_start,3)
report['interpolated_frames']=len(requests)
report['camera_refinement'].update(adjusted_frames=len(shifted),max_shift_pixels=largest_shift.tolist(),edge_fill='reflect, narrow edge strip only')
report['status']='repaired'
# A motion-only acceptance gate prevents a worse cadence from being labelled fixed.
after=list(metrics)
affected=sorted({j for i in {*requests,*shifted} for j in (i,i+1) if 0<j<len(thumbs)})
for i in affected:after[i]=measure_pair(corrected_thumbs[i-1],corrected_thumbs[i])
def jitter(rows):
value=[]
for left,right in details['regions']+[(a-1,b+1) for a,b in details['held_ranges']]:
v=np.array([rows[j]['motion'] for j in range(left+1,right+1)])
if v.size>2:value.append(float(np.std(v)/max(.01,np.mean(v))))
return float(np.mean(value)) if value else None
report['motion_jitter_before']=jitter(metrics);report['motion_jitter_after']=jitter(after)
def camera_jerk(rows):
values=[]
for first,last in camera_details['shots']:
velocity=np.array([[r.get('camera',{}).get('x',r['x']),r.get('camera',{}).get('y',r['y'])] for r in rows[first+1:last+1]])
acceleration=np.linalg.norm(np.diff(velocity,axis=0),axis=1)
if acceleration.size:values.extend(acceleration.tolist())
return dict(rms=float(np.sqrt(np.mean(np.square(values)))),peak=float(max(values))) if values else None
report['camera_jerk_before']=camera_jerk(metrics);report['camera_jerk_after']=camera_jerk(after)
camera_worse=np.any(largest_shift>np.array([meta['width'],meta['height']])*.004) or (report['camera_jerk_before'] and (report['camera_jerk_after']['rms']>report['camera_jerk_before']['rms']*.9
or report['camera_jerk_after']['peak']>report['camera_jerk_before']['peak']))
if camera_worse or (report['motion_jitter_before'] is not None and report['motion_jitter_after']>report['motion_jitter_before']*.95):
shutil.copyfile(source,temp)
report.update(status='skipped_quality',interpolated_frames=0)
report['camera_refinement']['adjusted_frames']=0
finally:
if interpolator:interpolator.close()
_RENDER_LOCK.release()
_check(cancel)
if progress:progress('Verifica sincronizzazione',.9)
_verify(source,temp,meta)
_check(cancel)
temp.replace(output)
report['total_seconds']=round(time.perf_counter()-start,3)
if progress:progress('Correzione completata',1.)
return report
finally:
if out:out.close()
if temp.exists():temp.unlink()
+2 -2
View File
@@ -1,9 +1,9 @@
[project]
name = "comfyui-dogma-nodes"
description = "Custom ComfyUI nodes for DOGMA AI video workflows."
version = "1.0.38"
version = "1.0.58"
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.
+127
View File
@@ -0,0 +1,127 @@
export const copy=x=>JSON.parse(JSON.stringify(x));
export const FAMILIES=[
{key:'nano',name:'Nanobanana',short:'NB',type:'GeminiImage2Node'},
{key:'gpt',name:'GPT Image',short:'GPT',type:'OpenAIGPTImageNodeV2'},
{key:'flux',name:'Flux 3',short:'F3',type:'Flux3ImageNode'},
{key:'seedream',name:'Seedream',short:'SD',type:'ByteDanceSeedreamNodeV3'},
];
export const VIDEO_FAMILIES=[{key:'seedance',name:'Seedance',short:'V',type:'ByteDance2ReferenceNodeV2'}];
export const ALL_FAMILIES=[...FAMILIES,...VIDEO_FAMILIES];
export const families=s=>s.mode==='video'?VIDEO_FAMILIES:FAMILIES;
export const safeName=s=>String(s||'').trim().replace(/[^\p{L}\p{N}_.-]+/gu,'_').replace(/^\.+/,'').slice(0,100);
export function inputSpec(def,values,name){
const parts=name.split('.');let inputs=def?.input;
for(let i=0;i<parts.length;i++){
const spec=inputs?.required?.[parts[i]]||inputs?.optional?.[parts[i]];if(!spec)return null;
if(i===parts.length-1)return spec;
if(spec[0]==='COMFY_DYNAMICCOMBO_V3'){const key=values[parts.slice(0,i+1).join('.')];inputs=spec[1].options.find(o=>o.key===key)?.inputs;}else return null;
}
return null;
}
export function viewParameters(file){
if(typeof file!=='string')return {filename:file.filename,subfolder:file.subfolder||'',type:file.type||'output'};
const parts=file.replaceAll('\\','/').split('/');return {filename:parts.pop(),subfolder:parts.join('/'),type:'input'};
}
export function choicesFor(spec){if(!spec)return null;if(Array.isArray(spec[0]))return spec[0];if(spec[0]==='COMBO')return spec[1].options;if(spec[0]==='COMFY_DYNAMICCOMBO_V3')return spec[1].options.map(o=>o.key);return null;}
export function parameterSpecs(def,values){
const result={};const walk=(inputs,prefix='')=>{for(const [key,spec] of Object.entries({...inputs?.required,...inputs?.optional})){
const name=prefix+key;const choices=choicesFor(spec);
if(choices||['INT','FLOAT','BOOLEAN','STRING'].includes(spec[0]))result[name]=spec;
if(spec[0]==='COMFY_DYNAMICCOMBO_V3')walk(spec[1].options.find(o=>o.key===values[name])?.inputs,name+'.');
}};walk(def?.input);return result;
}
export function modelValues(def,values){
const specs=parameterSpecs(def,values),next={};for(const [key,spec] of Object.entries(specs)){
const choices=choicesFor(spec),value=values[key];next[key]=value!==undefined&&(!choices||choices.includes(value))?value:spec[1]?.default??choices?.[0]??(spec[0]==='BOOLEAN'?false:spec[0]==='STRING'?'':0);
}return next;
}
export function sortedChoices(key,values){
const list=[...new Set(values.map(String))];if(!/resolution|size_preset|size$/.test(key))return list;
const score=v=>{if(key==='model.size_preset'){const tier=v.match(/([\d.]+)K/i);return tier?+tier[1]:Infinity;}const dims=v.match(/(\d+)x(\d+)/);if(dims)return +dims[1]*+dims[2];const k=v.match(/([\d.]+)\s*[kK]/);if(k)return +k[1]*1000;const p=v.match(/(\d+)p/i);if(p)return +p[1];return Infinity;};return list.sort((a,b)=>score(a)-score(b));
}
export function todayCode(){const parts=new Intl.DateTimeFormat('en-GB',{timeZone:'Europe/Rome',day:'2-digit',month:'2-digit',year:'2-digit'}).formatToParts(new Date());return ['day','month','year'].map(k=>parts.find(p=>p.type===k).value).join('');}
export function titleParts(s){return [s.project,s.scene,s.filename||'DOGMA',s.appendDate?(s.dateMode==='today'?todayCode():s.date||todayCode()):''].map(safeName).filter(Boolean);}
export function prefix(s,f){return ['DOGMA/API',safeName(s.project),safeName(s.scene),titleParts(s).join('_')+'_'+f.short].filter(Boolean).join('/');}
export function migrateState(raw){
const s=copy(raw);s.schema=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;
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 validateState(s){
if(!s.prompts[s.mode]?.trim())throw new Error('Scrivi un prompt.');
if(!plannedJobs(s).length)throw new Error('Attiva almeno un modello.');
const refs=activeReferences(s),imgs=refs.filter(r=>r.kind==='image'),videos=refs.filter(r=>r.kind==='video');
if(refs.some(r=>!r.file))throw new Error('Ricarica le reference mancanti.');
if(s.mode==='image'){
if(s.imageEdit&&!imgs.length)throw new Error('Image Edit richiede Image 1.');
const limits={nano:14,gpt:16,flux:10,seedream:10},max=Math.min(...FAMILIES.filter(f=>s.models[f.key]?.enabled).map(f=>limits[f.key]));if(imgs.length>max)throw new Error(`I modelli attivi supportano fino a ${max} reference.`);
}else {
const m=s.models.seedance;
if(m.engine==='frames'&&imgs.length>2)throw new Error('Usa al massimo un First frame e un Last frame.');
if(m.engine==='frames'&&['first','last'].some(role=>imgs.filter(r=>r.role===role).length>1))throw new Error('Assegna un solo First frame e un solo Last frame.');
if(m.engine==='frames'&&!imgs.length)throw new Error('Aggiungi almeno un frame immagine.');
if(m.engine!=='frames'&&!refs.length)throw new Error('Aggiungi una reference immagine o video.');
const p=m.engine==='frames'?m.frames:m.parameters;
if(m.engine!=='frames'&&['edit','extend'].includes(p['model.task_type'])&&!videos.length)throw new Error('Video Edit ed Extend richiedono un video sorgente.');
if(imgs.length>30||videos.length>10)throw new Error('Troppe reference per Seedance 2.5.');
}
for(const f of families(s)){
const m=s.models[f.key];if(!m.enabled)continue;const p=m.engine==='frames'?m.frames:m.parameters;
for(const [k,v] of Object.entries(p))if(/(?:width|height)$/.test(k)){
const n=Number(v),min=f.key==='gpt'?480:240,max=f.key==='gpt'?3840:8594,step=f.key==='gpt'?16:2;
if(!Number.isInteger(n)||n<min||n>max||n%step)throw new Error(`${f.name}: dimensioni da ${min} a ${max}, multiple di ${step}.`);
}
}
}
export function compileBatch(s,jobs,baseSeed){
validateState(s);const output={},refs=activeReferences(s),images=[],videos=[];
refs.forEach((ref,i)=>{
const id=String(9000+i*10);output[id]={class_type:ref.kind==='video'?'LoadVideo':'LoadImage',inputs:{[ref.kind==='video'?'file':'image']:ref.file}};
if(ref.kind==='video'){videos.push({ref,link:[id,0]});return;}
let link=[id,0];const p=ref.process;
if(p?.enabled){
let mask=[id,1];
if(p.maskFile){const mid=String(9001+i*10);output[mid]={class_type:'LoadImage',inputs:{image:p.maskFile}};const tid=String(9002+i*10);output[tid]={class_type:'ImageToMask',inputs:{image:[mid,0],channel:'red'}};mask=[tid,0];}
if(p.source==='prompt'&&p.mask&&!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

+189
View File
@@ -0,0 +1,189 @@
@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}
+87
View File
@@ -0,0 +1,87 @@
import { app } from '../../scripts/app.js';
import { api } from '../../scripts/api.js';
import { PlatformUI } from './dogma_api_ui.js?v=1.0.57';
import { ALL_FAMILIES,copy,migrateState,activeReferences,inputSpec,viewParameters,parameterSpecs,modelValues } from './dogma_api_core.js?v=1.0.57';
const ROOT=new URL('.',import.meta.url);
const css=document.createElement('link');css.rel='stylesheet';css.href=new URL('dogma_api_platform.css?v=1.0.57',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;const workflow=copy(app.graph.serialize());workflow.extra ||= {};workflow.extra.dogma_api_batch={session:state.session,id:batch,jobs:copy(compiled.jobs)};
const nativeBuild=app.graphToPrompt,nativeQueue=api.queuePrompt;
const build=function(...args){if(used)return nativeBuild.apply(this,args);used=true;return Promise.resolve({workflow,output:compiled.output});};
const capture=async function(...args){const r=await nativeQueue.apply(this,args);if(args[1]?.workflow===workflow)result=r;return r;};
app.graphToPrompt=build;api.queuePrompt=capture;
try{await app.queuePrompt(0,1);if(!result?.prompt_id)throw new Error('Comfy non ha accettato il batch. Controlla accesso e messaggi di Comfy.');return result.prompt_id;}
finally{if(app.graphToPrompt===build)app.graphToPrompt=nativeBuild;if(api.queuePrompt===capture)api.queuePrompt=nativeQueue;queueLock=false;}
}
subscribe(handler){const controller=new AbortController();for(const name of ['execution_start','executing','executed','execution_success','execution_error','execution_interrupted','progress','progress_state','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
+298
View File
@@ -0,0 +1,298 @@
import {ALL_FAMILIES,copy,families,plannedJobs,compileBatch,validateState,titleParts,todayCode,filterResults,migrateState,activeReferences,visibleReferences,choicesFor,sortedChoices,safeName,orderResults,savedFilename,preparedMask} from './dogma_api_core.js?v=1.0.57';
import {icon} from './dogma_api_icons.js?v=1.0.57';
import {hoverCompare,openViewer} from './dogma_api_viewer.js?v=1.0.57';
import {referenceEditor} from './dogma_api_reference_editor.js?v=1.0.57';
export const el=(tag,text='',cls='')=>{const e=document.createElement(tag);e.textContent=text;e.className=cls;return e;};
export const btn=(text,fn,cls='',aria=text)=>{const b=el('button',text,cls);b.type='button';b.onclick=fn;b.setAttribute('aria-label',aria);b.title=aria;return b;};
export const ib=(name,label,fn,cls='')=>{const b=btn('',fn,'dap-icon-button '+cls,label);b.append(icon(name));return b;};
const terminal=new Set(['completed','failed','cancelled','missing']);
const enumValues={aspect_ratio:['auto','1:1','2:3','3:2','3:4','4:3','4:5','5:4','9:16','16:9','21:9'],resolution:['1K','2K','4K'],'model.background':['auto','opaque','transparent'],'model.quality':['low','medium','high'],'model.size':['auto','1024x1024','1536x1024','1024x1536','2048x2048','2048x1152','1152x2048','3840x2160','2160x3840','Custom'],'model.size_preset':['Custom'],'model.resolution':['480p','720p','1080p','4k'],'model.ratio':['adaptive','16:9','4:3','1:1','3:4','9:16','21:9'],'model.task_type':['reference','edit','extend','auto'],'model.output_format':['mp4'],response_modalities:['IMAGE','IMAGE+TEXT']};
const displayName=k=>({'model.task_type':'TASK','model.generate_audio':'AUDIO','model.duration':'DURATION / SEC','model.auto_downscale':'AUTO DOWNSCALE','model.auto_upscale':'AUTO UPSCALE'})[k]||k.replace(/^model\./,'').replaceAll('_',' ').toUpperCase();
export class PlatformUI {
constructor(bridge){this.bridge=bridge;this.state=bridge.load();this.library=[];this.selection=[];this.cards=new Map();this.urls=new Set();this.closed=false;this.busy=false;}
save(){if(!this.closed)this.bridge.save(this.state);}
async open(){
this.ready=false;
this.root=el('dialog','','dap');this.root.setAttribute('aria-label','DOGMA API Platform');
this.root.addEventListener('cancel',e=>{e.preventDefault();this.close();});
this.root.addEventListener('dragover',e=>{if([...e.dataTransfer.types].includes('Files'))e.preventDefault();});
this.root.addEventListener('drop',e=>{e.preventDefault();if(e.dataTransfer.files.length)this.addReferences([...e.dataTransfer.files]);});
document.body.append(this.root);this.build();this.root.tabIndex=-1;this.root.showModal();this.root.focus({preventScroll:true});
this.unsubscribe=this.bridge.subscribe?.((name,d)=>this.event(name,d));
this.note('Apertura · Collegamento a Comfy…');
await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
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 families(s))models.append(this.model(f));
if(s.mode==='video'){const choice=el('section','','dap-video-choice');choice.append(el('div','WORKFLOW VIDEO','dap-label'));for(const [key,label] of [['reference','Ref → Video'],['frames','First / Last frame']]){const b=btn(label,()=>{s.models.seedance.engine=key;this.save();this.renderControls();this.refreshPrices();},key===s.models.seedance.engine?'active':'');choice.append(b);}c.append(choice);}
if(s.mode==='video'){const fix=el('label','','dap-video-repair');fix.append(this.toggle('Correggi scatti',s.videoRepair,v=>{s.videoRepair=v;this.save();},'span'),el('span','Correggi scatti'));fix.append(el('small','Salva anche una seconda copia · durata e fps originali'));c.append(fix);}
c.append(refs,prompt,workLabel,workSection,models);
}
filenamePreview(){return [...titleParts(this.state),'MODEL',this.state.mode==='video'?'00001.mp4':'00001.png'].filter(Boolean).join('_');}
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();}
async addReferences(files,replace=null){try{this.note('Caricamento reference…');for(const file of files){if(!/^(image|video)\//.test(file.type))throw new Error('Scegli immagini o video.');const frames=this.state.mode==='video'&&this.state.models.seedance.engine==='frames';if(file.type.startsWith('video/')&&(this.state.mode==='image'||frames))throw new Error('In questa modalità puoi caricare solo immagini.');if(frames&&!replace&&visibleReferences(this.state).length>=2)throw new Error('First / Last frame accetta due immagini.');const uploaded=await this.bridge.upload(file);if(this.closed)return;const r={...uploaded,enabled:true,modes:[this.state.mode],role:frames?(replace?.role|| (visibleReferences(this.state).some(r=>r.role==='first')?'last':'first')):'reference',process:{enabled:false,mask:false,maskMode:'edit',source:'paint',flip:false,invert:false,crop:false,fillHoles:false,expand:0,blur:0,targetWidth:0,targetHeight:0,background:'#ff00ff'}};if(replace){const at=this.state.references.indexOf(replace);this.state.references.splice(at,1,r);}else this.state.references.push(r);}this.save();this.renderRefs();this.refreshPrices();this.note('Reference aggiornate. L’ordine è quello mostrato.');}catch(e){this.note(e.message,true);}}
referenceVideo(ref){openViewer(this,{job:{kind:'video',label:ref.file,study:true},file:{url:ref.preview||this.bridge.view(ref.file)},index:0});}
model(f){
const m=this.state.models[f.key],wrap=el('div','','dap-model'),row=el('div','','dap-model-head');wrap.setAttribute('role','group');wrap.setAttribute('aria-label',f.name);
const toggle=this.toggle(`Attiva ${f.name}`,m.enabled,v=>{m.enabled=v;wrap.classList.toggle('enabled',v);this.save();this.updateHeader();});wrap.classList.toggle('enabled',m.enabled);
const details=el('details');details.open=!!m.expanded;details.ontoggle=()=>{m.expanded=details.open;this.save();};
const summary=el('summary');this.priceLabels ||= new Map();const price=el('small','— CREDITS / '+(f.key==='seedance'?'RUN':'IMAGE'));this.priceLabels.set(f.key,price);summary.append(el('span',f.name),price,icon('chevron'));details.append(summary);
const body=el('div','','dap-model-body');
this.field(body,'QUANTITY',m.quantity,v=>{m.quantity=Number(v);this.save();this.updateHeader();},{type:'number',min:1,max:64});
body.append(el('div','Richieste in parallelo · Seed diversi','dap-field-hint'));
const values=m.engine==='frames'?m.frames:m.parameters;
const nativeSpecs=this.bridge.parameterSpecs?.(this.state,f);const entries=nativeSpecs&&Object.keys(nativeSpecs).length?Object.keys(nativeSpecs).map(key=>[key,values[key]??nativeSpecs[key][1]?.default??choicesFor(nativeSpecs[key])?.[0]??'']):Object.entries(values);
for(const [key,value] of entries){
if(['prompt','model.prompt','system_prompt','seed','model.seed','n'].includes(key)||key.startsWith('control_after_generate')||key.endsWith('asset_id'))continue;
const opts={};if(enumValues[key])opts.choices=enumValues[key];
if(key==='model'){if(f.key==='nano')opts.choices=['gemini-3-pro-image-preview','Nano Banana 2 (Gemini 3.1 Flash Image)'];else opts.readonly=true;}
if(key==='resolution'&&f.key==='flux')opts.choices=['0.75K','1K','1.5K','2K','4K'];
if(typeof value==='boolean')opts.type='checkbox';if(typeof value==='number'){opts.type='number';opts.min=key==='model.duration'?4:0;opts.max=key==='model.duration'?30:8594;}
const spec=this.bridge.inputSpec?.(this.state,f,key);
if(spec){const info=spec[1]||{};if(Array.isArray(spec[0]))opts.choices=spec[0];else if(choicesFor(spec))opts.choices=choicesFor(spec);if(info.min!==undefined)opts.min=info.min;if(info.max!==undefined)opts.max=info.max;if(info.step!==undefined)opts.step=info.step;}
if(opts.choices){opts.choices=sortedChoices(key,opts.choices);delete opts.readonly;}
this.field(body,displayName(key),value,v=>{values[key]=typeof value==='boolean'?v:typeof value==='number'?Number(v):v;if(key==='model'){this.bridge.changeModel?.(this.state,f);this.renderControls();}this.save();this.refreshPrices();},opts);
}
if(values.system_prompt!==undefined){const advanced=el('details','','dap-advanced');advanced.append(el('summary','SYSTEM PROMPT'));const text=el('textarea');text.value=values.system_prompt;text.setAttribute('aria-label',f.name+' system prompt');text.oninput=()=>{values.system_prompt=text.value;this.save();};advanced.append(text);body.append(advanced);}
if(f.key==='seedance')body.append(el('div',m.engine==='frames'?'Usa un First frame, un Last frame o entrambi. Sono accettate soltanto immagini.':'Usa immagini o video come reference. In Edit la durata segue il video sorgente.','dap-field-hint'));
details.append(body);row.append(toggle,details);wrap.append(row);return wrap;
}
async refreshCredits(){if(this.creditBusy||this.closed)return;this.creditBusy=true;try{const result=await this.bridge.credits();if(!this.closed){this.credit.textContent=result.text;this.credit.title=result.title;}}catch{}finally{this.creditBusy=false;}}
refreshPrices(){if(this.closed)return;for(const f of families(this.state)){const text=this.bridge.price?.(this.state,f);const node=this.priceLabels?.get(f.key);if(node&&text){node.textContent=text;node.title='Stima calcolata dalle stesse regole di Comfy per questi parametri';}}}
allResults(){const map=new Map;for(const r of [...this.library,...this.state.results])map.set(r.id,r);return 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,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);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;
}
compare(){if(this.selection.length===2)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);}}
async run(){
if(this.busy)return;try{validateState(this.state);}catch(e){this.note(e.message,true);return;}
this.stopRequested=false;this.busy=true;this.updateHeader();const snapshot=copy(this.state),batch=crypto.randomUUID(),started=Date.now();
const jobs=plannedJobs(snapshot).map((p,ordinal)=>({...p,id:crypto.randomUUID(),batch,started,batchStarted:started,ordinal,status:'submitting',images:[]}));
try{
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);
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.note(e.message,true);}finally{this.busy=false;if(!this.closed)this.updateHeader();}
}
event(name,d){
if(name==='dogma_video_repair'){const job=this.state.results.find(j=>j.id===d?.job_id);if(job&&!terminal.has(job.status)){job.status='repairing';job.repairProgress=d.value;job.repairStage=d.stage;this.save();this.updateCards();}return;}
if(!d?.prompt_id)return;const jobs=this.state.results.filter(j=>j.promptId===d.prompt_id);if(!jobs.length){this.pendingEvents ||= [];if(this.busy&&this.pendingEvents.length<200)this.pendingEvents.push([name,d]);return;}
if(name==='progress_state'){for(const [id,n] of Object.entries(d.nodes||{})){const j=jobs.find(x=>x.generator===String(id));if(j&&!terminal.has(j.status)&&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;}
}
}
+87
View File
@@ -0,0 +1,87 @@
import { icon } from './dogma_api_icons.js?v=1.0.57';
import {savedFilename} from './dogma_api_core.js?v=1.0.57';
export async function copyFullImage(url){
if(!navigator.clipboard?.write||!globalThis.ClipboardItem)throw new Error('La copia immagini richiede HTTPS o localhost. Puoi scaricare il file a piena risoluzione.');
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){
const a=document.createElement('img');a.src=generated;a.alt='Generata';a.draggable=false;a.className='dap-generated';host.append(a);host.classList.add('dap-compare-host');
let cover=null,line=null;
if(original){
cover=document.createElement('div');cover.className='dap-original-cover';const b=document.createElement('img');b.src=original;b.alt='Image 1 / originale';b.draggable=false;cover.append(b);
line=document.createElement('div');line.className='dap-compare-line';host.append(cover,line);
const move=e=>{const rect=host.getBoundingClientRect();const percent=Math.max(0,Math.min(100,(e.clientX-rect.left)/rect.width*100));cover.style.clipPath=`inset(0 ${100-percent}% 0 0)`;line.style.left=percent+'%';};
host.addEventListener('pointerenter',()=>host.classList.add('comparing'));host.addEventListener('pointermove',move);host.addEventListener('pointerleave',()=>host.classList.remove('comparing'));
}
return {image:a,cover,line};
}
export function openViewer(ui,item,other=null){
const {job,file,index=0}=item,bridge=ui.bridge;
const title=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;
const compare=hoverCompare(surface,bridge.view(file),original);
compare.image.onload=()=>{width=compare.image.naturalWidth;height=compare.image.naturalHeight;surface.style.width=width+'px';surface.style.height=height+'px';fit();};
if(compare.image.complete&&compare.image.naturalWidth)compare.image.onload();
compare.image.onerror=()=>{hint.textContent='File non disponibile. Potrebbe essere stato spostato.';};
zoom.onchange=()=>{const value=Number(zoom.value);if(Number.isFinite(value)&&value>0)at(value/100);};
stage.addEventListener('wheel',e=>{e.preventDefault();const r=stage.getBoundingClientRect();at(scale*Math.exp(-e.deltaY*.0017),e.clientX-r.left,e.clientY-r.top);},{passive:false});
stage.addEventListener('dblclick',e=>{const r=stage.getBoundingClientRect();if(Math.abs(scale-1)<.02)fit();else at(1,e.clientX-r.left,e.clientY-r.top);});
stage.addEventListener('pointerdown',e=>{
const rect=surface.getBoundingClientRect();const inImage=e.clientX>=rect.left&&e.clientX<=rect.right&&e.clientY>=rect.top&&e.clientY<=rect.bottom;
if(!inImage&&e.target===stage){drag={blank:true,startX:e.clientX,startY:e.clientY};return;}
stage.setPointerCapture(e.pointerId);points.set(e.pointerId,{x:e.clientX,y:e.clientY});drag={startX:e.clientX,startY:e.clientY,x,y};
if(points.size===2){const [a,b]=[...points.values()];pinch={distance:Math.hypot(a.x-b.x,a.y-b.y),scale};}
});
stage.addEventListener('pointermove',e=>{
if(points.has(e.pointerId))points.set(e.pointerId,{x:e.clientX,y:e.clientY});
if(points.size===2&&pinch){const [a,b]=[...points.values()],r=stage.getBoundingClientRect();at(pinch.scale*Math.hypot(a.x-b.x,a.y-b.y)/pinch.distance,(a.x+b.x)/2-r.left,(a.y+b.y)/2-r.top);return;}
if(drag&&!drag.blank&&points.size===1){x=drag.x+e.clientX-drag.startX;y=drag.y+e.clientY-drag.startY;update();}
});
const up=e=>{if(drag?.blank&&Math.hypot(e.clientX-drag.startX,e.clientY-drag.startY)<5)dialog.close();points.delete(e.pointerId);drag=null;pinch=null;};
stage.addEventListener('pointerup',up);stage.addEventListener('pointercancel',up);
stage.addEventListener('keydown',e=>{if(e.key==='+'||e.key==='='){e.preventDefault();at(scale*1.3);}if(e.key==='-'){e.preventDefault();at(scale/1.3);}if(e.key==='0'){e.preventDefault();fit();}});
const observer=new ResizeObserver(()=>{if(Math.abs(scale-fitScale)<.01)fit();});observer.observe(stage);dialog.addEventListener('close',()=>observer.disconnect(),{once:true});
}
+22
View File
@@ -0,0 +1,22 @@
const paths={play:'M8 5l11 7-11 7z',pause:'M8 5v14M16 5v14',upload:'M12 16V3m-5 5 5-5 5 5M4 15v6h16v-6',download:'M12 3v13m-5-5 5 5 5-5M4 17v4h16v-4',folder:'M3 7V5h7l2 2h9v13H3z',plus:'M12 5v14M5 12h14',trash:'M3 6h18M9 6V3h6v3M6 6l1 15h10l1-15M10 10v7M14 10v7',stop:'M6 6h12v12H6z',check:'M4 12l5 5L20 6',compare:'M3 4h18v16H3zM12 4v16',settings:'M4 7h16M4 17h16M9 4v6M15 14v6',refresh:'M20 7v5h-5M4 17v-5h5M6 7a7 7 0 0 1 12-1l2 3M4 15l2 3a7 7 0 0 0 12-1',back:'M20 12H4m7-7-7 7 7 7',next:'M8 5l10 7-10 7M20 5v14',previous:'M16 5 6 12l10 7M4 5v14',film:'M3 4h18v16H3zM7 4v16M17 4v16M3 9h4M3 15h4M17 9h4M17 15h4',save:'M5 3h12l4 4v14H3V3zM7 3v6h10V3M7 21v-8h10v8',zoom:'M10 3a7 7 0 1 0 0 14 7 7 0 0 0 0-14M15 15l6 6M7 10h6',layers:'m12 3 10 6-10 6L2 9zM2 13l10 6 10-6M2 17l10 6 10-6'};
paths.zoomIn=paths.zoom+'M10 7v6';
export function inferIcon(text){
const s=text.toLowerCase();
if(/ripristina|ricarica|riprova|nuovi seed/.test(s))return 'refresh';
if(/02 provini|02 scegli/.test(s))return 'layers';if(/video edit/.test(s))return 'settings';
if(/pausa/.test(s))return 'pause';if(/riproduci/.test(s))return 'play';if(/interrompi|annulla/.test(s))return 'stop';
if(/rimuovi|elimina|libera/.test(s))return 'trash';if(/scarica/.test(s))return 'download';if(/carica|cambia file|cambia video/.test(s))return 'upload';
if(/cartella/.test(s))return 'folder';if(/salva|applica/.test(s))return 'save';if(/scegli|usa|conferma/.test(s))return 'check';
if(/confront|affiancati/.test(s))return 'compare';if(/ingrandisci/.test(s))return 'zoomIn';if(/riduci/.test(s))return 'zoom';if(/zoom/.test(s))return s.includes('+')?'zoomIn':'zoom';if(/−1 fotogramma|fotogramma precedente/.test(s))return 'previous';if(/\+1 fotogramma|fotogramma successivo/.test(s))return 'next';
if(/lora/.test(s))return 'layers';if(/maschera|impostazioni/.test(s))return 'settings';
if(/torna|vai all/.test(s))return 'back';if(/ripristina|ricarica|riprova|nuovi seed/.test(s))return 'refresh';
if(/^\+|aggiungi|nuova sessione/.test(s))return 'plus';if(/genera|provini|video|final|prepara|svilupp/.test(s))return 'film';return null;
}
export function setAction(button,text,icon=inferIcon(text)){
const label=document.createElement('span');label.textContent=icon==='plus'?text.replace(/^\+\s+/,''):text;button.replaceChildren();button.classList.add('dg-action');
if(icon&&paths[icon]){const svg=document.createElementNS('http://www.w3.org/2000/svg','svg');svg.classList.add('dg-icon');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('fill','none');svg.setAttribute('stroke','currentColor');svg.setAttribute('stroke-width','1.8');svg.setAttribute('stroke-linecap','round');svg.setAttribute('stroke-linejoin','round');svg.setAttribute('aria-hidden','true');const p=document.createElementNS(svg.namespaceURI,'path');p.setAttribute('d',paths[icon]);svg.append(p);button.append(svg);}
button.append(label);return button;
}
export function actionButton(text,fn,cls=''){const b=document.createElement('button');b.type='button';b.className=cls;b.onclick=fn;return setAction(b,text);}
export function loraLabel(item){const stack=(item.loras||item.config?.common_loras||[]).filter(l=>l.name&&l.enabled!==false&&Number(l.strength??1)!==0),last=stack.at(-1);return last?last.name.replaceAll('\\','/').split('/').pop().replace(/\.safetensors$/i,'')+' · '+Number(last.strength??1).toLocaleString('it-IT'):'Senza LoRA';}
export function decorateActions(root){for(const b of root.querySelectorAll('button,a[download],summary'))if(!b.classList.contains('dg-edit-handle')&&!b.querySelector('.dg-icon')){const text=b.textContent,icon=inferIcon(text);if(icon)setAction(b,text,icon);}}
+67
View File
@@ -4,3 +4,70 @@
.dg-studio .dg-state{padding:8px 20px;background:#302820}.dg-studio .dg-state .dg-status{padding:0}.dg-studio .dg-progress{width:100%;height:10px;accent-color:#ff6018}.dg-studio .dg-progress-label{display:block;color:#ddd;margin-top:4px}.dg-studio .dg-saved-path{overflow-wrap:anywhere;font-family:monospace}.dg-studio .dg-header{position:relative;z-index:10}
.dg-studio .dg-folder-browser{position:sticky;top:0;z-index:8;padding:22px;background:#202225;border:2px solid var(--orange);border-radius:10px;box-shadow:0 12px 50px #000b;margin-bottom:24px;max-height:85%;overflow:auto}.dg-studio .dg-folders{display:flex;flex-wrap:wrap;gap:4px;max-height:260px;overflow:auto;margin:12px 0}.dg-studio .dg-folder-browser input{font-family:Consolas,monospace}.dg-studio .dg-folder-browser p{overflow-wrap:anywhere}
.dg-studio .dg-edit-player{height:360px;max-height:45vh;background:#080808}
.dg-studio .dg-edit-track{position:relative;height:96px;background:#0b0c0e;margin:12px 16px;touch-action:none;user-select:none;overflow:visible;border-radius:6px}
.dg-studio .dg-edit-thumbs{position:absolute;inset:0;display:grid;grid-template-columns:repeat(8,1fr);overflow:hidden;border-radius:6px;opacity:.7}
.dg-studio .dg-edit-thumbs img{width:100%;height:96px;object-fit:cover;pointer-events:none}
.dg-studio .dg-edit-selection{position:absolute;top:0;bottom:0;border:3px solid var(--orange);background:#ff5b1422;cursor:grab;min-width:2px}
.dg-studio .dg-edit-selection:active{cursor:grabbing}
.dg-studio .dg-edit-handle{position:absolute!important;top:-5px;bottom:-5px;width:24px;padding:0;margin:0!important;transform:translateX(-50%);background:var(--orange);border:2px solid #ffb48c;cursor:ew-resize;color:white;z-index:3;touch-action:none;border-radius:5px}
.dg-studio .dg-edit-handle[hidden]{display:none}
.dg-studio .dg-edit-playhead{position:absolute;top:0;bottom:0;width:2px;background:white;pointer-events:none;z-index:2}
.dg-studio .dg-edit-scale{display:flex;justify-content:space-between;color:#b9bec6;font-variant-numeric:tabular-nums;margin:0 16px 15px}
.dg-studio .dg-edit-controls{display:flex;gap:4px;flex-wrap:wrap}
.dg-studio .dg-edit-panel{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:10px 20px;align-items:start}
.dg-studio .dg-edit-panel>:not(video){grid-column:2;min-width:0;margin-top:0}
.dg-studio .dg-edit-panel>.dg-edit-player{grid-column:1;grid-row:1 / span 8;position:sticky;top:0;height:320px;max-height:45vh}
.dg-studio .dg-edit-panel .dg-edit-controls button{padding:7px 10px;font-size:13px}
.dg-studio .dg-edit-panel .dg-edit-track{width:calc(100% - 32px)}
@media(max-width:900px){.dg-studio .dg-edit-panel{display:block}.dg-studio .dg-edit-panel>.dg-edit-player{height:180px;z-index:5;margin-bottom:10px}}
.dg-studio input[type=range]{accent-color:var(--orange);padding:8px 0;cursor:ew-resize}
.dg-studio .dg-media-preview{position:relative;min-width:0;background:#080808;border-radius:5px;overflow:hidden}
.dg-studio .dg-media-preview img{display:block;max-width:100%;object-fit:contain}
.dg-studio .dg-media-status{padding:8px 12px;color:#bbb;background:#161719;font-size:13px}
.dg-studio .dg-media-status[hidden]{display:none}
.dg-studio .dg-media-status button{padding:5px 10px;font-size:12px}
.dg-studio .dg-media-preview[data-state=error] .dg-media-status{color:#ffd2bc}
.dg-studio .dg-edit-panel>.dg-media-preview{grid-column:1;grid-row:1 / span 9;position:sticky;top:0}
.dg-studio .dg-edit-panel>.dg-media-preview video{height:320px;max-height:45vh}
.dg-studio .dg-edit-compare{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:16px}
.dg-studio .dg-edit-compare strong{display:block;padding:8px 0}
.dg-studio .dg-edit-compare[data-mode=original],.dg-studio .dg-edit-compare[data-mode=result]{grid-template-columns:1fr}
.dg-studio .dg-edit-compare[data-mode=original]>:last-child,.dg-studio .dg-edit-compare[data-mode=result]>:first-child{display:none}
@media(max-width:900px){.dg-studio .dg-edit-panel>.dg-media-preview{position:relative;margin-bottom:10px}.dg-studio .dg-edit-panel>.dg-media-preview video{height:220px}}
@media(max-width:600px){.dg-studio .dg-edit-compare{grid-template-columns:1fr}}
.dg-studio .dg-icon{width:18px;height:18px;flex:0 0 18px;color:var(--orange);vertical-align:middle;pointer-events:none}
.dg-studio button:has(>.dg-icon),.dg-studio a:has(>.dg-icon){display:inline-flex;align-items:center;justify-content:center;gap:8px}
.dg-studio summary>.dg-icon{margin-right:8px}.dg-studio .dg-primary>.dg-icon,.dg-studio .is-active>.dg-icon{color:currentColor}
.dg-studio .dg-edit-controls button{padding:8px 12px;font-size:13px}.dg-studio .dg-edit-controls{align-items:center;gap:6px}
.dg-studio .dg-edit-controls button:first-of-type{border-color:#ad572c;background:#3a291f}
.dg-studio .dg-restitch-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin:14px 0}
.dg-studio button.dg-restitch-choice{display:block;min-width:0;width:100%;margin:0;padding:8px;background:#17181a;text-align:left;border:2px solid transparent}
.dg-studio .dg-restitch-choice[aria-pressed=true]{border-color:var(--orange);background:#30231d}
.dg-studio .dg-restitch-choice canvas{display:block;width:100%;height:clamp(95px,17vh,160px);object-fit:contain;margin:7px 0;background:#050505;border-radius:4px}
.dg-studio .dg-restitch-choice strong{display:block;font-size:13px}.dg-studio .dg-restitch-choice small{font-size:11px}
.dg-studio .dg-restitch-source{position:absolute!important;width:1px!important;height:1px!important;opacity:.01;pointer-events:none}
.dg-studio .dg-restitch-hover{position:fixed;top:0;left:0;z-index:100;box-sizing:border-box;padding:12px;border:1px solid #ff641dcc;border-radius:12px;background:#1b1b1df5;box-shadow:0 18px 70px #000b;pointer-events:none;opacity:0;visibility:hidden;transition:opacity .12s,visibility .12s;will-change:transform;contain:layout paint}
.dg-studio .dg-restitch-hover[data-open=true]{opacity:1;visibility:visible}
.dg-studio .dg-restitch-hover strong{display:block;margin:0 0 8px;font-size:15px;color:#fff}
.dg-studio .dg-restitch-hover canvas{display:block;width:100%;height:auto;max-height:calc(76vh - 72px);object-fit:contain;background:#050505;border-radius:6px}
.dg-studio .dg-restitch-hover small{display:block;margin-top:8px;font-size:12px;color:#d4c9c3;white-space:nowrap}
.dg-studio .dg-restitch-choice{cursor:zoom-in}
@media(prefers-reduced-motion:reduce){.dg-studio .dg-restitch-hover{transition:none}}
.dg-studio .dg-restitch h3{font-size:15px;margin:18px 0 10px}.dg-studio .dg-restitch .dg-grid{max-width:700px}
@media(max-width:1100px){.dg-studio .dg-restitch-grid{grid-template-columns:repeat(3,minmax(0,1fr))}}
@media(max-width:750px){.dg-studio .dg-restitch-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:420px){.dg-studio .dg-restitch-grid{grid-template-columns:1fr}}
.dg-studio .dg-file-drop{transition:outline-color .12s,background-color .12s;outline:1px dashed #57504a;outline-offset:-5px}
.dg-studio .dg-file-drop[data-dragging=true]{outline:2px solid var(--orange);outline-offset:-3px;background:#3b281e;box-shadow:inset 0 0 0 5px #ff5b1422}
.dg-studio .dg-drop-hint{display:flex;align-items:center;gap:9px;padding:10px 12px;margin:10px 0;border:1px dashed #665045;border-radius:6px;color:#d2b9aa;font-size:13px;background:#1b1918}
.dg-studio .dg-file-drop[data-dragging=true]>.dg-drop-hint{color:#fff;border-color:var(--orange);background:#4b2c1c}
.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}
+149 -55
View File
@@ -1,14 +1,17 @@
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-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-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=1.0.38',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=(text,fn,cls='')=>{const b=el('button',text,cls);b.type='button';b.onclick=fn;return b;};
const inputURL=name=>api.apiURL('/view?'+new URLSearchParams({filename:name,type:'input'}));
const viewURL=file=>api.apiURL('/view?'+new URLSearchParams(file));
const film=file=>{const v=el('video');v.controls=true;v.loop=true;v.playsInline=true;v.preload='metadata';v.src=viewURL(file);return v;};
const button=actionButton;
const film=file=>mediaPreview(file,{loop:true}).root;
let active=null;
export class DirectorStudio {
@@ -37,8 +40,14 @@ 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 task==='ref2v'?'ref2v':'fl2v';}
family(task){return ['ref2v','edit'].includes(task)?'ref2v':'fl2v';}
turbo(task,steps){
const name=this.family(task)==='ref2v'?'minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors':`minimax_h3_fl2v_turbo_${steps}step_v1.0${steps===4?'_768p':''}_comfyui_bf16.safetensors`;
return this.catalog.loras.find(x=>x.replaceAll('\\','/').split('/').pop()===name)||name;
@@ -46,7 +55,7 @@ export class DirectorStudio {
presetValues(phase,kind='dogma',task=this.config.task){
const s={},base=this.catalog.defaults[phase];
for(const k of ['sampler','scheduler','steps','shift_video','shift_audio','lying','lying_start','lying_end','turbo_strength'])s[k]=base[k];
s.turbo=this.turbo(task,phase==='draft'?4:8);
s.turbo=phase==='draft'?this.turbo(task,4):base.turbo;
if(phase==='finish'){
s.sigmas=kind==='conservative'?'':'0.9035, 0.8000, 0.6316, 0.3158, 0.0000';s.denoise=kind==='conservative'?.18:.35;
if(this.family(task)==='ref2v')s.steps=4;
@@ -79,6 +88,7 @@ export class DirectorStudio {
}
switchTask(previous){
const c=this.config,old=this.family(previous),next=this.family(c.task);
if(c.task!=='edit'&&c.exploration==='loras')c.exploration='prompts';
if(old!==next){
c.sampling_banks ||= {};c.sampling_banks[old]={draft:clone(c.draft),finish:clone(c.finish)};
const saved=c.sampling_banks[next];
@@ -93,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=setTimeout(()=>{expired=true;controller.abort();},20000);
const timeout=opts.body instanceof FormData?null:setTimeout(()=>{expired=true;controller.abort();},20000);
try{
const r=await api.fetchApi(path,{...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;}
@@ -115,6 +127,7 @@ export class DirectorStudio {
if(this.dialog?.open)return;
active=this;const epoch=++this.epoch;this.loading=true;
const dialog=this.dialog=el('dialog','','dg-studio');dialog.setAttribute('aria-label','DOGMA H3 Director');
guardFileNavigation(dialog);
dialog.addEventListener('cancel',e=>{e.preventDefault();this.close();});
// Keep Comfy shortcuts away from text fields; never synthesize keyboard events.
for(const name of ['keydown','keyup'])dialog.addEventListener(name,e=>e.stopPropagation());
@@ -132,6 +145,8 @@ export class DirectorStudio {
}
}
close(){
this.restitchPanel?.destroy();this.restitchPanel=null;this.editTimeline?.destroy();this.editTimeline=null;this.editCompare?.destroy();this.editCompare=null;this.maskEditor?.destroy();this.maskEditor=null;
releaseMedia(this.dialog);
++this.epoch;clearInterval(this.poll);this.recovering=false;
for(const c of this.requests)c.abort();this.requests.clear();
const dialog=this.dialog;this.dialog=null;this.folderPanel=null;if(active===this)active=null;
@@ -139,28 +154,34 @@ export class DirectorStudio {
this.save();
}
destroy(){this.close();clearTimeout(this.saveTimer);this.abort.abort();}
async browseFolders(){
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 input=el('input');input.type='text';input.value=this.config.output_dir||'';input.setAttribute('aria-label','Percorso cartella');
const target=scope==='edit'?this.config.edit:this.config,key=scope==='edit'?'final_output_dir':'output_dir';
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',()=>{this.config.output_dir=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)));
use.disabled=false;
}catch(e){if(epoch===this.epoch&&this.folderPanel===panel&&e.name!=='AbortError')info.textContent=e.message;}
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;}
};
input.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();load(input.value);}});
@@ -174,9 +195,12 @@ export class DirectorStudio {
}
armSound(){if(this.config.sound){try{this.audio ||= new(window.AudioContext||window.webkitAudioContext)();this.audio.resume();}catch{}}}
applyState(d){
const change=this.data.status!==d.status||this.data.candidates?.length!==d.candidates?.length||this.data.finals?.length!==d.finals?.length;
const change=this.data.status!==d.status||this.data.edit_batch?.phase!==d.edit_batch?.phase||this.data.candidates?.length!==d.candidates?.length||this.data.finals?.length!==d.finals?.length||this.data.edits?.length!==d.edits?.length||this.data.edit_trials?.length!==d.edit_trials?.length||JSON.stringify(this.data.edits?.map(x=>[x.id,x.saved_path]))!==JSON.stringify(d.edits?.map(x=>[x.id,x.saved_path]));
if((d.edit_trials?.length||0)>(this.data.edit_trials?.length||0)&&!d.edit_trials.some(x=>x.id===this.editTrialId)){this.editTrialId=d.edit_trials.at(-1).id;this.editComparePosition=null;}
if((d.edits?.length||0)>(this.data.edits?.length||0)){this.editResultId=d.edits.at(-1).id;this.editComparePosition=null;}
this.data=d;
if(['ready','done','error'].includes(d.status)){this.pending=false;d.progress=null;const key=d.run+':'+d.status+':'+d.message;if(key!==this.lastNotice){this.lastNotice=key;this.sound();}}
if(this.promotedTrial&&d.edit_batch?.phase==='finish')this.page='finish';
if(['ready','developed','done','error'].includes(d.status)){this.pending=false;d.progress=null;const key=d.run+':'+d.status+':'+d.message;if(key!==this.lastNotice){this.lastNotice=key;this.sound();}}
if(change&&this.page!=='prepare')this.render();else this.status();
}
async recover(render=true){
@@ -192,23 +216,38 @@ export class DirectorStudio {
}else if(!owned)this.pending=false;
if(owned&&d.status==='running'&&d.run===this.data.run&&d.message===this.data.message&&!d.progress)d.progress=this.data.progress;
if(render||JSON.stringify(d)!==JSON.stringify(this.data))this.applyState(d);else this.status();
if(this.editFinishWaiting&&!jobs.length&&!this.submitting){const intent=this.editFinishWaiting;this.editFinishWaiting=null;this.config.edit.selected_trial=intent.id;for(const [key,name]of Object.entries({mode:'final_mode',steps:'final_steps',method:'final_method',denoise:'final_denoise',output_dir:'final_output_dir',resolution:'final_resolution'}))this.config.edit[name]=intent.options[key];this.config.edit.mask={...this.config.edit.mask,...intent.options.matte};this.pending=false;this.queue('finish');}
}catch(e){if(epoch===this.epoch&&e.name!=='AbortError'){this.data.message='Stato non disponibile: '+e.message;this.status();}}
finally{if(epoch===this.epoch)this.recovering=false;}
}
fail(message){this.pending=false;this.data.status='error';this.data.progress=null;this.data.message=message;this.status();this.sound();}
status(){
const s=this.dialog?.querySelector('.dg-status');if(s){s.textContent=this.data.message||'Prepara il lavoro, genera i provini e scegli quale continuare.';s.dataset.state=this.data.status;}
this.dialog?.querySelectorAll('[data-queue]').forEach(b=>b.disabled=this.pending||this.submitting);
const s=this.dialog?.querySelector('.dg-status');if(s){s.textContent=this.data.message||(this.config?.task==='edit'?'Seleziona un tratto, prepara la maschera se serve e genera i provini edit.':'Prepara il lavoro, genera i provini e scegli quale continuare.');s.dataset.state=this.data.status;}
this.dialog?.querySelectorAll('[data-queue]').forEach(b=>b.disabled=this.pending||this.submitting||this.uploads>0);
this.dialog?.querySelectorAll('[data-edit-finish]').forEach(b=>{
b.disabled=this.promoting||this.submitting||this.uploads>0||!!this.editFinishWaiting||this.pending&&this.data.edit_batch?.phase==='finish';
setAction(b,this.pending&&this.data.edit_batch?.phase!=='finish'?'Usa questo provino e salta gli altri':'Prepara questo provino alla dimensione originale');
});
const bar=this.dialog?.querySelector('.dg-progress');if(bar){const p=this.data.progress;bar.hidden=!this.pending;bar.max=p?.total||1;bar.value=p?.step||0;}
const detail=this.dialog?.querySelector('.dg-progress-label');if(detail)detail.textContent=this.pending?(this.data.progress?`Passaggio corrente: ${this.data.progress.step} / ${this.data.progress.total}`:'Elaborazione in corso · attendo avanzamento o anteprima') : '';
// Always allow a fresh queue check: UI state can lag behind a failed job.
const stop=this.dialog?.querySelector('[data-stop]');if(stop){stop.disabled=!!this.stopping;stop.textContent=this.pending?'Interrompi':'Verifica / interrompi';}
const stop=this.dialog?.querySelector('[data-stop]');if(stop){stop.disabled=!!this.stopping;setAction(stop,this.pending?'Interrompi':'Verifica / interrompi');}
}
async queue(action){
if(this.pending||this.submitting)return;this.submitting=true;this.armSound();
if(this.pending||this.submitting||this.uploads>0)return;this.submitting=true;this.armSound();
try{
if(action==='finish'&&!this.config.selected)throw new Error('Scegli prima un provino.');
if(action==='draft'){
if(this.config.task!=='edit'&&action!=='draft'&&!this.config.selected)throw new Error('Scegli prima un provino.');
if(action==='draft'&&this.config.task==='edit'){
if(!this.config.edit.source||!this.editMeta)throw new Error('Carica un video e attendi la timeline.');
if(!this.editTimeline?.commitInputs())throw new Error(this.editTimeline?.inputError||'Attendi la preparazione della timeline.');
if((this.editTimeline.video?.readyState||0)<2)throw new Error('Attendi l’anteprima video o ricaricala prima di applicare l’edit.');
if(this.config.exploration==='seeds'&&!this.config.prompt.trim())throw new Error('Descrivi la modifica da applicare.');
if(this.config.exploration==='prompts'&&this.config.variants.some(v=>!v.text.trim()))throw new Error('Completa o rimuovi le varianti prompt vuote.');
if(this.config.edit.mask?.enabled&&!this.config.edit.mask.source)throw new Error('Carica il video maschera oppure disattiva la maschera.');
if(!this.catalog.models.includes(this.config.models.ref2v))throw new Error('Seleziona un checkpoint Ref2VA installato.');
if(this.config.refs.some(r=>!r.name))throw new Error('Carica o rimuovi le reference vuote.');
}
if(action==='draft'&&this.config.task!=='edit'){
if(this.config.task==='i2v'&&!this.config.first&&!this.config.last)throw new Error('Carica il primo o l’ultimo fotogramma.');
if(this.config.task==='ref2v'&&!this.config.refs.length)throw new Error('Carica almeno una reference.');
if(this.config.exploration==='prompts'&&this.config.variants.some(v=>!v.text.trim()))throw new Error('Completa o rimuovi le schede prompt vuote.');
@@ -217,22 +256,52 @@ export class DirectorStudio {
if(!this.catalog.models.includes(checkpoint))throw new Error('Seleziona un checkpoint installato per '+this.config.task.toUpperCase()+' nelle impostazioni avanzate.');
if(this.config.refs.some(r=>!r.name)&&this.config.task==='ref2v')throw new Error('Carica o rimuovi le reference vuote.');
}
if(action==='finish'&&this.config.task==='edit'&&!this.data.edit_trials?.some(p=>p.id===this.config.edit.selected_trial))throw new Error('Scegli prima un provino edit.');
if(action==='finish'&&this.config.task!=='edit'&&!this.data.developments?.some(p=>p.id===this.config.selected_development&&p.candidate===this.config.selected))throw new Error('Scegli prima uno sviluppo di qualità.');
const executionConfig=this.config.task==='edit'&&action==='finish'?this.data.edit_trials.find(p=>p.id===this.config.edit.selected_trial).config:this.config;
const required=[];
if(this.config.preview.enabled)required.push('ModelPreviewOverrideKJ');
if(action==='finish'&&this.config.finish.stages!=='ultimate')required.push('MinimaxH3LatentUpscaler3D');
if(action==='finish'&&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(', '));
if(executionConfig.task==='edit'&&executionConfig.edit.mask?.enabled)required.push('MVEx_MaskToLatentSpace');
if(this.config.task==='edit'&&action==='finish'&&(this.config.edit.final_method||'preserve')==='guided')required.push('MinimaxH3LatentUpscaler3D');
if(action==='develop'&&this.config.develop.mode==='guided')required.push('MinimaxH3LatentUpscaler3D');
const previewEnabled=executionConfig.preview.enabled&&!(this.config.task==='edit'&&action==='draft'&&!executionConfig.edit.trial_live_preview);
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: '+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;}
this.previewData=null;this.previewVideo=false;
this.pending=true;this.data.status='running';this.data.progress=null;this.data.message='Invio a Comfy…';this.status();
const graph=await app.graphToPrompt();
// Direct API returns a prompt_id; app.queuePrompt() may return false for accepted queued work.
const result=await api.queuePrompt(0,graph);
if(!result?.prompt_id)throw new Error('Comfy non ha restituito un identificativo di esecuzione.');
this.promptId=result.prompt_id;this.page=action==='draft'?'choose':'finish';this.data.message='In coda · attendo il motore';this.render();
this.promptId=result.prompt_id;this.page=action==='draft'?'choose':action==='develop'?'develop':'finish';this.data.message='In coda · attendo il motore';this.render();
}catch(e){if(e.name!=='AbortError'){const detail=e.response?.node_errors||e.response?.error;this.fail(detail?JSON.stringify(detail,null,2):e.message);}}finally{this.submitting=false;this.status();}
}
async useEditTrial(id){
if(this.promoting||this.editFinishWaiting||this.submitting||this.uploads>0)return;
const selected=this.data.edit_trials?.find(x=>x.id===id&&x.complete);if(!selected)return;
this.config.edit.selected_trial=id;this.save();
if(!this.pending){await this.queue('finish');return;}
this.promoting=true;this.status();
try{
const options={mode:this.config.edit.final_mode||'match',steps:Number(this.config.edit.final_steps??20),method:this.config.edit.final_method||'preserve',denoise:Number(this.config.edit.final_denoise??.25),output_dir:this.config.edit.final_output_dir||this.config.output_dir||'',resolution:this.config.edit.final_resolution||'native',matte:Object.fromEntries(Object.entries(this.config.edit.mask||{}).filter(([k])=>k.startsWith('composite_')))};
const result=await this.request('/dogma/h3/v2/edit/promote',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session:this.config.session,trial:id,batch:this.data.edit_batch?.id,options})});
this.promotedTrial=id;
if(result.status==='accepted'){
this.data.edit_batch=result.batch;this.page='finish';this.data.message='Provino scelto · salto gli altri e passo alla dimensione originale';this.render();
}else{
this.editFinishWaiting={id,options};this.data.message='Provino scelto · attendo la chiusura del gruppo e avvio la rigenerazione';
const q=await this.request('/queue');const own=x=>x[1]===this.promptId;
const pending=(q.queue_pending||[]).filter(own).map(x=>x[1]);
if(pending.length)await this.request('/queue',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({delete:pending})});
this.page='finish';this.render();await this.recover(false);
}
}catch(e){if(e.name!=='AbortError'){this.data.message='Scelta del provino non riuscita: '+e.message;this.status();}}
finally{this.promoting=false;this.status();}
}
async stop(){
if(this.stopping)return;this.stopping=true;this.status();
try{
@@ -258,43 +327,48 @@ export class DirectorStudio {
const draw=()=>{
[...d.children].slice(1).forEach(e=>e.remove());d.firstChild.textContent=`${title} · ${stack.length}`;
stack.forEach((l,i)=>{const row=el('div','','dg-lora-row');this.field(row,'LoRA',l,'name',{options:['',...this.catalog.loras]});this.field(row,'Potenza',l,'strength',{type:'number',step:.01,min:-10,max:10});row.append(button('Rimuovi',()=>{stack.splice(i,1);this.save();draw();}));d.append(row);});
d.append(button('+ Aggiungi LoRA',()=>{stack.push({name:'',strength:1});this.save();draw();}));
d.append(button('Aggiungi LoRA',()=>{stack.push({name:'',strength:1});this.save();draw();}));decorateActions(d);
};draw();
}
asset(parent,title,obj,key,kind='image',remove){
const p=this.section(parent,title);const name=obj[key];
if(name){const media=el(kind==='video'?'video':'img');media.src=inputURL(name);if(kind==='video')media.controls=true;media.className='dg-asset';p.append(media,el('small',name));}
const upload=el('input');upload.type='file';upload.accept=kind==='video'?'video/*':'image/*';upload.hidden=true;
upload.onchange=async()=>{const file=upload.files?.[0];if(!file)return;try{const data=new FormData();data.append('image',file);data.append('type','input');data.append('subfolder','DOGMA_DIRECTOR');const res=await this.request('/upload/image',{method:'POST',body:data});obj[key]=(res.subfolder?res.subfolder+'/':'')+res.name;this.save();this.render();}catch(e){if(e.name!=='AbortError')this.fail(e.message);}};
p.append(upload,button(name?'Cambia file':'Carica file',()=>upload.click()));
if(name||remove)p.append(button('Rimuovi',()=>{if(remove)remove();else obj[key]='';this.save();this.render();}));
return p;
asset(parent,title,obj,key,kind='image',remove,onUpload){
return assetField(this,parent,title,obj,key,kind,{remove,onUploaded:onUpload});
}
render(){
if(!this.dialog||this.loading)return;
const scroll=this.dialog.querySelector('main')?.scrollTop||0;
const expanded=new Map();
for(const d of this.dialog.querySelectorAll('details')){const key=d.querySelector('summary')?.textContent.replace(/ · \d+$/,'');if(!expanded.has(key))expanded.set(key,[]);expanded.get(key).push(d.open);}
this.restitchPanel?.destroy();this.restitchPanel=null;this.editTimeline?.destroy();this.editTimeline=null;this.editCompare?.destroy();this.editCompare=null;this.maskEditor?.destroy();this.maskEditor=null;
releaseMedia(this.dialog);
this.folderPanel=null;this.dialog.querySelectorAll('video').forEach(v=>v.pause());this.dialog.replaceChildren();
this.dialog.append(this.header());
const nav=el('nav');for(const [key,label]of[['prepare','01 Prepara'],['choose','02 Scegli'],['finish','03 Finalizza']])nav.append(button(label,()=>{this.page=key;this.render();},this.page===key?'is-active':''));
const fresh=button('Nuova sessione',()=>{if(this.pending)return;if(!window.confirm('Avviare una nuova sessione? I video precedenti restano salvati. Salva il workflow in Comfy per poter riaprire anche la galleria precedente.'))return;this.config.session=crypto.randomUUID();this.config.selected='';this.config.action='draft';this.data={candidates:[],finals:[],status:'new'};this.promptId=null;this.A=this.B=null;this.previewData=null;this.page='prepare';this.save();this.render();});fresh.dataset.queue='';nav.append(fresh);
const isEdit=this.config.task==='edit';
if(isEdit&&!['prepare','choose','finish'].includes(this.page))this.page='prepare';
const nav=el('nav');for(const [key,label]of(isEdit?[['prepare','01 Video Edit'],['choose','02 Provini'],['finish','03 Video completo']]:[['prepare','01 Prepara'],['choose','02 Scegli'],['develop','03 Sviluppa'],['finish','04 Finalizza']]))nav.append(button(label,()=>{this.page=key;this.render();this.dialog.querySelector('main').scrollTop=0;},this.page===key?'is-active':''));
const fresh=button('Nuova sessione',()=>{if(this.pending)return;if(!window.confirm('Avviare una nuova sessione? I video precedenti restano salvati. Salva il workflow in Comfy per poter riaprire anche la galleria precedente.'))return;this.config.session=crypto.randomUUID();this.config.selected='';this.config.action='draft';this.config.selected_development='';this.data={candidates:[],developments:[],finals:[],status:'new'};this.promptId=null;this.A=this.B=null;this.previewData=null;this.page='prepare';this.save();this.render();});fresh.dataset.queue='';nav.append(fresh);
const stop=button('Interrompi',()=>this.stop().catch(e=>{this.data.message='Interruzione non confermata: '+e.message;this.status();}));stop.dataset.stop='';nav.append(stop);const state=el('div','','dg-state');state.append(el('div','','dg-status'),el('progress','','dg-progress'),el('small','','dg-progress-label'));this.dialog.append(nav,state);
const body=el('main');this.dialog.append(body);
if(this.page==='prepare')this.prepare(body);if(this.page==='choose')this.choose(body);if(this.page==='finish')this.finish(body);
const foot=el('footer','Salvataggio automatico della sessione · Cartella output configurabile in Prepara · Esc torna a Comfy');this.dialog.append(foot);this.status();
if(this.page==='prepare')this.prepare(body);if(this.page==='choose'){if(isEdit)renderEditTrials(this,body);else this.choose(body);}if(this.page==='develop')this.develop(body);if(this.page==='finish'){if(isEdit)renderEditResults(this,body);else this.finish(body);}
const foot=el('footer','Salvataggio automatico della sessione · Cartella output configurabile in Prepara · Esc torna a Comfy');this.dialog.append(foot);decorateActions(this.dialog);this.status();
for(const d of this.dialog.querySelectorAll('details')){const key=d.querySelector('summary')?.textContent.replace(/ · \d+$/,'');const states=expanded.get(key);if(states?.length)d.open=states.shift();}
body.scrollTop=scroll;
}
prepare(body){
const c=this.config;const intro=this.section(body,'Il tuo lavoro');const row=el('div','','dg-grid');intro.append(row);
const previousTask=c.task;
this.field(row,'Nome lavoro',c,'job');this.field(row,'Cosa vuoi creare?',c,'task',{options:[['i2v','Da immagini · primo e/o ultimo frame'],['t2v','Da testo · nessuna immagine'],['ref2v','Da reference · immagini e video']],change:()=>this.switchTask(previousTask)});
this.field(row,'Nome lavoro',c,'job');this.field(row,'Cosa vuoi creare?',c,'task',{options:[['i2v','Da immagini · primo e/o ultimo frame'],['t2v','Da testo · nessuna immagine'],['ref2v','Da reference · immagini e video'],['edit','Video Edit · modifica un tratto del video']],change:()=>this.switchTask(previousTask)});
this.field(intro,'Cartella output · vuoto = cartella Comfy',c,'output_dir',{hint:'Percorso assoluto sul computer dove gira Comfy. I video vengono copiati qui e restano visibili nella galleria.'});
intro.append(button('Scegli cartella…',()=>this.browseFolders()));
if(c.task==='edit'){renderEditor(this,body);return;}
this.field(intro,'Genera audio nei video',c,'generate_audio',{type:'checkbox',hint:'Disattivato: provini e finali vengono esportati senza traccia audio. H3 mantiene internamente i latenti audiovisivi.'});
const assets=el('div','','dg-grid');body.append(assets);
if(c.task==='i2v'){this.asset(assets,'Primo fotogramma · facoltativo',c,'first');this.asset(assets,'Ultimo fotogramma · facoltativo',c,'last');}
if(c.task==='ref2v'){
let image=0,video=0;c.refs.forEach((r,i)=>this.asset(assets,r.kind==='image'?`Picture ${++image}`:`Video ${++video}`,r,'name',r.kind,()=>c.refs.splice(i,1)));
const p=this.section(assets,'Reference');p.append(el('p','Nel prompt usa <Picture 1>, <Picture 2>, <Video 1>… Dei video viene usato l’inizio, per la durata richiesta (massimo 15 secondi), ricampionato a 24 fps. Il loro audio non viene usato come reference.'));
if(image<9)p.append(button('+ Immagine',()=>{c.refs.push({kind:'image',name:''});this.save();this.render();}));
if(video<3)p.append(button('+ Video',()=>{c.refs.push({kind:'video',name:''});this.save();this.render();}));
const drop=referenceDrop(this,p,{image:9,video:3}),grid=el('div','','dg-grid');p.append(grid);
let image=0,video=0;c.refs.forEach((r,i)=>this.asset(grid,r.kind==='image'?`Picture ${++image}`:`Video ${++video}`,r,'name',r.kind,()=>c.refs.splice(i,1)));
if(image<9)p.append(button('Aggiungi immagine',()=>drop.choose('image')));
if(video<3)p.append(button('Aggiungi video',()=>drop.choose('video')));
}
const prompt=this.section(body,'Esplora una direzione');this.field(prompt,'Prompt comune',c,'prompt',{multi:true,rows:7,hint:'Può contenere tutti i paragrafi necessari. In modalità Prompt diversi puoi lasciarlo vuoto e scrivere prompt completi nelle schede.'});
this.field(prompt,'Tipo di confronto',c,'exploration',{options:[['seeds','Seed diversi · stesso prompt'],['prompts','Prompt diversi · stesso seed']],change:()=>this.render()});
@@ -306,7 +380,7 @@ export class DirectorStudio {
for(let i=0;i<c.count;i++){c.trial_loras[String(i)] ||= [];this.loras(prompt,c.trial_loras[String(i)],`LoRA aggiuntive · provino ${i+1}`);}
}else{
c.variants.forEach((v,i)=>{const card=this.section(prompt,`Prompt ${i+1}`);this.field(card,'Testo completo',v,'text',{multi:true,rows:7});this.loras(card,v.loras ||= [],'LoRA aggiuntive');if(c.variants.length>1)card.append(button('Elimina questa variante',()=>{c.variants.splice(i,1);this.save();this.render();}));});
if(c.variants.length<10)prompt.append(button('+ Nuovo prompt',()=>{c.variants.push({text:'',loras:[]});this.save();this.render();}));
if(c.variants.length<10)prompt.append(button('Aggiungi prompt',()=>{c.variants.push({text:'',loras:[]});this.save();this.render();const inputs=this.dialog.querySelectorAll('textarea');inputs[inputs.length-1]?.focus({preventScroll:true});}));
}
const size=this.section(body,'Formato dei provini');const sizes=el('div','','dg-grid');size.append(sizes);
this.field(sizes,'Proporzioni automatiche dalla prima immagine disponibile',c,'auto_aspect',{type:'checkbox',change:()=>this.render()});
@@ -351,19 +425,36 @@ export class DirectorStudio {
items.forEach(p=>{
const card=this.section(grid,p.label);if(p.id===this.config.selected)card.classList.add('is-selected');card.append(film(p.video),el('p',`${p.width} × ${p.height} · ${(p.frames/24).toFixed(2)} s · seed ${p.seed}`));
const txt=el('details');txt.append(el('summary','Prompt e LoRA del provino'),el('pre',p.prompt),el('pre',p.loras.map(l=>`${l.name} · ${l.strength}`).join('\n')||'Nessuna LoRA aggiuntiva'));card.append(txt);
card.append(button('Scegli e continua',()=>{this.config.selected=p.id;this.save();this.page='finish';this.render();},'dg-primary'));
card.append(button('Scegli e sviluppa',()=>{this.config.selected=p.id;this.config.selected_development='';this.save();this.page='develop';this.render();},'dg-primary'));
for(const side of ['A','B'])card.append(button('Confronta '+side,()=>{this[side]=p.id;this.render();}));
});
const a=items.find(p=>p.id===this.A),b=items.find(p=>p.id===this.B);
if(a&&b){const compare=this.section(body,'Confronto A / B');const g=el('div','','dg-grid');const av=film(a.video),bv=film(b.video);av.muted=bv.muted=true;g.append(av,bv);compare.append(g,button('Riproduci insieme',()=>{av.currentTime=bv.currentTime=0;av.play();bv.play();}),button('Pausa',()=>{av.pause();bv.pause();}));}
if(a&&b){const compare=this.section(body,'Confronto A / B');const g=el('div','','dg-grid');const ap=mediaPreview(a.video,{loop:true}),bp=mediaPreview(b.video,{loop:true}),av=ap.media,bv=bp.media;av.muted=bv.muted=true;g.append(ap.root,bp.root);compare.append(g,button('Riproduci insieme',()=>{av.currentTime=bv.currentTime=0;av.play();bv.play();}),button('Pausa',()=>{av.pause();bv.pause();}));}
}
develop(body){
const p=this.data.candidates?.find(x=>x.id===this.config.selected);
if(!p){body.append(el('p','Scegli prima una bozza.'));return;}
const src=this.section(body,p.label+' · bozza scelta');src.append(film(p.video));
const s=this.section(body,'Sviluppo di qualità');const d=this.config.develop;
this.field(s,'Metodo',d,'mode',{options:[['guided','Continua la bozza scelta (predefinito)'],['native','Rigenera in qualità · il movimento può cambiare']]});
this.field(s,'Lato lungo dello sviluppo',d,'long_edge',{type:'number',min:512,max:1536,step:32});
s.append(el('p','Standard: circa 960 × 544 per 16:9, 20 step senza Turbo. Continua usa i latenti salvati della bozza; prompt, seed, sorgenti e LoRA vengono ripresi automaticamente. La risoluzione maggiore può cambiare dettagli e movimento.'));
const adv=el('details','','dg-card');adv.append(el('summary','Campionamento dello sviluppo'));body.append(adv);
this.field(adv,'Denoise · solo Continua (maggiore = più cambiamento)',d,'denoise',{type:'number',min:.01,max:.99,step:.01});this.sampleFields(adv,d);
const go=button('Sviluppa questo',()=>this.queue('develop'),'dg-primary');go.dataset.queue='';body.append(go);this.live(body);
const grid=el('div','','dg-gallery');body.append(grid);
for(const item of (this.data.developments||[]).filter(x=>x.candidate===p.id)){
const card=this.section(grid,item.label);card.append(film(item.video),el('p',`${item.width} × ${item.height} · ${item.mode==='guided'?'Continuazione':'Rigenerazione'} · seed ${item.seed}`),el('p',item.saved_path||''));
card.append(button('Usa questo sviluppo → Finalizza',()=>{this.config.selected_development=item.id;this.save();this.page='finish';this.render();},'dg-primary'));
}
}
finish(body){
const p=this.data.candidates?.find(x=>x.id===this.config.selected);
if(!p){body.append(el('p','Scegli un provino dalla sezione Scegli.'));return;}
const p=this.data.developments?.find(x=>x.id===this.config.selected_development&&x.candidate===this.config.selected);
if(!p){body.append(el('p','Scegli uno sviluppo di qualità nella sezione Sviluppa.'));return;}
const selected=this.section(body,p.label+' · selezionato');selected.append(film(p.video),el('p','Prompt, seed, sorgenti, modello e LoRA sono ripresi automaticamente da questo provino.'));
const f=this.config.finish;const s=this.section(body,'Come vuoi finalizzare?');
const task=p.config?.task||this.config.task;
this.field(s,'Passaggi',f,'stages',{options:[['both','Completo · latent upscale + Ultimate'],['latent','Solo latent upscale e raffinamento'],['ultimate','Solo Ultimate dal provino']],change:()=>this.render()});
this.field(s,'Passaggi',f,'stages',{options:[['both','Completo · latent upscale + Ultimate'],['latent','Solo latent upscale e raffinamento'],['ultimate','Solo Ultimate dallo sviluppo']],change:()=>this.render()});
this.field(s,'Risoluzione finale · lato lungo',f,'resolution',{options:[['1k','1K · 1024 px'],['2k','2K · 2048 px'],['3k','3K · 3072 px'],['4k','4K · 4096 px']],change:()=>this.render()});
const edge={ '1k':1024,'2k':2048,'3k':3072,'4k':4096 }[f.resolution];
s.append(el('p',`Uscita: ${Math.max(32,Math.round(p.width/Math.max(p.width,p.height)*edge/32)*32)} × ${Math.max(32,Math.round(p.height/Math.max(p.width,p.height)*edge/32)*32)} px. Proporzioni del provino, allineate a 32 px. Completo usa un passaggio latente fino a ×2 e Ultimate alla risoluzione scelta.`));
@@ -378,7 +469,10 @@ export class DirectorStudio {
}
const d=el('details','','dg-card');d.append(el('summary','Controlli finalizzazione'));body.append(d);this.presetMenu(d,'finish',task);this.sampleFields(d,f);
this.field(d,'Modello latent upscale',f,'upscaler',{options:this.catalog.upscalers});this.field(d,'Sigma del raffinamento · vuoto usa scheduler',f,'sigmas');this.field(d,'Denoise raffinamento · solo senza sigma manuali',f,'denoise',{type:'number',step:.01,min:0,max:1});
this.field(d,'Checkpoint FL2V per Ultimate',f,'ultimate_model',{options:this.catalog.models});this.field(d,'Turbo FL2V per Ultimate',f,'ultimate_turbo',{options:['',...this.catalog.loras]});this.field(d,'Potenza Turbo Ultimate',f,'ultimate_strength',{type:'number',step:.01});
this.field(d,'Sampler Ultimate',f,'ultimate_sampler',{options:this.catalog.samplers});
this.field(d,'Seed raffinamento',f,'refine_seed',{type:'number',step:1});
this.field(d,'Seed Ultimate',f,'ultimate_seed',{type:'number',step:1});
this.field(d,'Checkpoint per Ultimate',f,'ultimate_model',{options:this.catalog.models});this.field(d,'Turbo FL2V per Ultimate',f,'ultimate_turbo',{options:['',...this.catalog.loras]});this.field(d,'Potenza Turbo Ultimate',f,'ultimate_strength',{type:'number',step:.01});
for(const [k,label,step]of[['tile_width','Larghezza tasselli',32],['tile_height','Altezza tasselli',32],['tile_padding','Contesto tasselli',8],['mask_blur','Sfumatura tasselli',1],['ultimate_steps','Step Ultimate',1],['ultimate_denoise','Denoise Ultimate',.01]])this.field(d,label,f,k,{type:'number',step});
this.field(d,'RIFE · batch (1 riduce la memoria)',this.config.rife,'batch_size',{type:'number',min:1,max:32,step:1});
const go=button('Finalizza questo',()=>this.queue('finish'),'dg-primary');go.dataset.queue='';body.append(go,button('Torna ai provini',()=>{this.page='choose';this.render();}));this.live(body);
+140
View File
@@ -0,0 +1,140 @@
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));
const clock=t=>`${String(Math.floor(t/60)).padStart(2,'0')}:${(t%60).toFixed(3).padStart(6,'0')}`;
export class EditComparison{
constructor(studio,root,item){
this.studio=studio;this.item=item;this.closed=false;this.abort=new AbortController();this.playing=false;
const source=item.config?.edit?.source;
if(!source){root.append(el('p','Il sorgente di questa versione non è registrato.'),mediaPreview(item.video,{loop:true}).root);return;}
const items=[...(studio.data.edit_trials||[]),...(studio.data.edits||[])];
const label=x=>{
if(x.segment_only)return `${x.label} · ${x.config?.exploration==='loras'?loraLabel(x)+' · ':''}seed ${x.seed}`;
if(x.development?.method==='preserve')return `Finale da ${x.origin_trial_label||'provino'} · edit mantenuto · seed ${x.seed}`;
const sampling=x.sampling||x.config?.edit;
return `Finale da ${x.origin_trial_label||items.find(t=>t.id===x.trial)?.label||'provino precedente'} · seed ${x.seed}${sampling?' · '+(sampling.turbo?'Turbo':'standard')+' '+sampling.steps:''}`;
};
this.pool=[{id:'original',label:'Originale',video:inputFile(source),offset:0,end:Infinity},...items.filter(x=>x.config?.edit?.source===source).map(x=>({id:x.id,label:label(x),video:x.corrected_video||x.video,offset:x.segment_only?x.selection.start:0,end:x.segment_only?x.selection.end:x.duration}))];
if(!this.pool.some(x=>x.id===item.id))this.pool.push({id:item.id,label:item.label,video:item.video,offset:item.segment_only?item.selection.start:0,end:item.segment_only?item.selection.end:item.duration});
const saved=studio.editCompareChoice;
let left=saved?.source===source?saved.left:'original',right=saved?.source===source&&saved.selected===item.id?saved.right:item.id;
if(!this.pool.some(x=>x.id===left))left='original';if(!this.pool.some(x=>x.id===right))right=item.id;if(left===right)left=right==='original'?item.id:'original';
studio.editCompareChoice={source,selected:item.id,left,right};
this.left=this.pool.find(x=>x.id===left);this.right=this.pool.find(x=>x.id===right);this.key=source+'|'+left+'|'+right;
const selectors=el('div');selectors.className='dg-grid';
for(const [side,label,other]of[['left','Confronto A · sinistra',right],['right','Confronto B · destra',left]]){
const wrap=el('label',label);wrap.className='dg-field';const select=el('select');
for(const entry of this.pool){const option=el('option',entry.label);option.value=entry.id;option.disabled=entry.id===other;select.append(option);}
select.value=side==='left'?left:right;select.onchange=()=>{studio.editCompareChoice[side]=select.value;studio.render();};wrap.append(select);selectors.append(wrap);
}
root.append(selectors);
const pair=this.pair=el('div');pair.className='dg-edit-compare';pair.dataset.mode=studio.editCompareMode||'pair';
this.original=mediaPreview(this.left.video);this.result=mediaPreview(this.right.video);
for(const [side,entry,preview]of[['A',this.left,this.original],['B',this.right,this.result]]){
const panel=el('div');panel.append(el('strong',entry.label),preview.root);
if((studio.data.edit_trials||[]).some(x=>x.id===entry.id))panel.append(button(`Scegli ${side} per il finale`,()=>{studio.editTrialId=entry.id;studio.editCompareChoice.selected=entry.id;studio.page='choose';studio.render();}));
pair.append(panel);preview.media.controls=false;preview.media.muted=true;
}
root.append(pair);this.a=this.original.media;this.b=this.result.media;
const modes=el('div');modes.className='dg-edit-controls';
for(const [mode,label]of[['pair','Affiancati'],['original','Solo A'],['result','Solo B']])modes.append(button(label,()=>{studio.editCompareMode=mode;pair.dataset.mode=mode;}));
const actions=el('div');actions.className='dg-edit-controls';
this.playButton=button('Riproduci edit',()=>this.toggle(true));this.fullButton=button('Riproduci tutto',()=>this.toggle(false));
this.fullButton.hidden=this.left.offset>0||this.right.offset>0||this.left.end!==Infinity&&this.left.end<item.duration||this.right.end<item.duration;
const loopLabel=el('label','Ripeti in loop'),loop=el('input');loop.type='checkbox';loop.checked=studio.editLoop!==false;loop.onchange=()=>{studio.editLoop=loop.checked;};loopLabel.prepend(loop);
actions.append(this.playButton,this.fullButton,button('Vai all’edit',()=>this.seek(item.selection.start)),button('Fotogramma precedente',()=>this.step(-1)),button('Fotogramma successivo',()=>this.step(1)),loopLabel);
this.slider=el('input');this.slider.type='range';this.slider.step='any';this.slider.setAttribute('aria-label','Posizione comune del confronto');this.slider.oninput=()=>this.seek(Number(this.slider.value));
this.position=el('p');this.notice=el('small');this.notice.setAttribute('role','status');
const sound=el('label','Audio del confronto');sound.className='dg-field';const audio=el('select');
for(const [value,label]of[['mute','Muto'],['left','A · '+this.left.label],['right','B · '+this.right.label]]){const option=el('option',label);option.value=value;audio.append(option);}
audio.onchange=()=>{this.a.muted=audio.value!=='left';this.b.muted=audio.value!=='right';};sound.append(audio);root.append(modes,actions,sound,this.slider,this.position,this.notice);
const position=studio.editComparePosition;
this.target=position?.key===this.key?position.time:item.selection.start;this.resumeWanted=position?.key===this.key&&position.playing;this.selectionOnly=position?.key===this.key?position.selectionOnly:true;
for(const v of [this.a,this.b]){
v.addEventListener('loadedmetadata',()=>this.restore(),{signal:this.abort.signal});
v.addEventListener('loadeddata',()=>this.ready(),{signal:this.abort.signal});
v.addEventListener('error',()=>{this.pause();this.ready();},{signal:this.abort.signal});
v.addEventListener('waiting',()=>{if(this.playing&&!this.starting&&!this.restarting){this.resumeAfterBuffer=true;this.pause(false);this.notice.textContent='Attendo entrambe le anteprime…';}},{signal:this.abort.signal});
v.addEventListener('canplay',()=>{this.ready();if(this.resumeAfterBuffer&&this.a.readyState>=3&&this.b.readyState>=3){this.resumeAfterBuffer=false;this.play(this.selectionOnly,false);}},{signal:this.abort.signal});
v.addEventListener('ended',()=>this.reachEnd(),{signal:this.abort.signal});
}
this.ready();this.restore();
studio.request('/dogma/h3/v2/edit/metadata?'+new URLSearchParams({name:source}),{signal:this.abort.signal}).then(meta=>{if(!this.closed){this.meta=meta;this.restore();}}).catch(e=>{if(!this.closed&&e.name!=='AbortError')this.notice.textContent='Tempi sorgente non disponibili. Riapri il confronto.';});
}
bounds(selectionOnly=false){
const low=Math.max(this.left.offset,this.right.offset,selectionOnly?this.item.selection.start:0);
const high=Math.min(this.a.duration+this.left.offset,this.b.duration+this.right.offset,this.left.end,this.right.end,selectionOnly?this.item.selection.end:Infinity);
return [low,high];
}
ready(){
if(this.closed||!this.a)return;
const range=this.bounds(),ready=!!this.meta&&this.a.readyState>=2&&this.b.readyState>=2&&!this.a.error&&!this.b.error&&range[1]>range[0];
this.playButton.disabled=this.fullButton.disabled=this.slider.disabled=!ready;
if(ready&&this.resumeWanted){this.resumeWanted=false;this.play(this.selectionOnly,false);}
}
restore(){
if(this.closed||!this.a||this.a.readyState<1||this.b.readyState<1)return;
const [low,high]=this.bounds();if(!(high>low)){this.notice.textContent='Questi video non condividono un intervallo temporale.';this.ready();return;}
this.target=clamp(this.target,low,high);this.slider.min=low;this.slider.max=high;
this.a.currentTime=Math.max(0,this.target-this.left.offset);this.b.currentTime=Math.max(0,this.target-this.right.offset);this.draw();this.ready();
}
seek(time){
this.pause();this.atEnd=false;const [low,high]=this.bounds();
const last=this.meta?frameTime(this.meta,Math.max(0,frameIndex(this.meta,high)-1)):high-.001;
this.target=clamp(this.meta?frameTime(this.meta,Math.min(frameCount(this.meta)-1,frameIndex(this.meta,time))):time,low,last);this.restore();
}
step(delta){if(this.meta)this.seek(stepTime(this.meta,this.a.currentTime+this.left.offset,delta));}
toggle(selection){if((this.playing||this.starting||this.resumeAfterBuffer)&&this.selectionOnly===selection){this.pause();return;}this.play(selection);}
playbackLabel(){if(!this.playButton)return;setAction(this.playButton,(this.playing||this.starting||this.resumeAfterBuffer)&&this.selectionOnly?'Pausa edit':'Riproduci edit');setAction(this.fullButton,(this.playing||this.starting||this.resumeAfterBuffer)&&!this.selectionOnly?'Pausa video':'Riproduci tutto');}
async play(selectionOnly,restart=true){
if(this.closed||!this.meta||this.a.error||this.b.error)return;
const [low,high]=this.bounds(selectionOnly);if(!(high>low)){this.notice.textContent='Nessun tratto comune da riprodurre.';return;}
const now=this.a.currentTime+this.left.offset;const atEnd=this.atEnd;
this.pause();this.selectionOnly=selectionOnly;this.atEnd=false;this.resumeWanted=false;
if(restart&&(atEnd||now<low||now>=high-.001||this.a.ended||this.b.ended)){this.target=low;this.restore();}
const run=this.playRun;this.starting=true;this.notice.textContent='';
this.playbackLabel();
if(Math.abs(this.b.currentTime+this.right.offset-this.a.currentTime-this.left.offset)>.001)this.b.currentTime=this.a.currentTime+this.left.offset-this.right.offset;
const wait=v=>new Promise((resolve,reject)=>{
if(v.readyState>=2&&!v.seeking){resolve();return;}
const done=()=>{if(v.readyState>=2&&!v.seeking){clean();resolve();}};
const cancelled=()=>{clean();reject(new Error('Confronto chiuso'));};
const timer=setTimeout(()=>{clean();reject(new Error('Caricamento in attesa'));},15000);
const clean=()=>{clearTimeout(timer);v.removeEventListener('seeked',done);v.removeEventListener('loadeddata',done);this.abort.signal.removeEventListener('abort',cancelled);};
v.addEventListener('seeked',done);v.addEventListener('loadeddata',done);this.abort.signal.addEventListener('abort',cancelled,{once:true});
});
try{
await Promise.all([wait(this.a),wait(this.b)]);if(this.closed||run!==this.playRun)return;
this.playing=true;await Promise.all([this.a.play(),this.b.play()]);if(this.closed||run!==this.playRun)return;
this.starting=false;this.playbackLabel();this.tick();
}catch(e){if(!this.closed&&run===this.playRun){this.pause();this.notice.textContent='Riproduzione non avviata: attendi il caricamento e riprova.';}}
}
reachEnd(){
if(this.closed||!this.playing||this.restarting)return;
if(this.studio.editLoop!==false){
this.restarting=true;const selection=this.selectionOnly,[low]=this.bounds(selection);this.pause();this.target=low;this.restore();
this.play(selection,false).finally(()=>{this.restarting=false;});
}else{
const [,high]=this.bounds(this.selectionOnly);this.seek(this.meta?stepTime(this.meta,high,-1):high-.001);this.atEnd=true;
}
}
tick(){
if(this.closed||!this.playing)return;
const t=this.a.currentTime+this.left.offset,[,end]=this.bounds(this.selectionOnly);
if(t>=end-.00001){this.reachEnd();return;}
const drift=this.b.currentTime+this.right.offset-t,frame=1/this.meta.fps;
if(Math.abs(drift)>Math.max(frame,.04))this.b.currentTime=t-this.right.offset;else this.b.playbackRate=clamp(1-drift*.5,.97,1.03);
this.draw();this.raf=requestAnimationFrame(()=>this.tick());
}
pause(clearResume=true){this.playRun=(this.playRun||0)+1;this.starting=false;this.playing=false;if(clearResume){this.resumeAfterBuffer=false;this.resumeWanted=false;}cancelAnimationFrame(this.raf);this.a?.pause();this.b?.pause();if(this.b)this.b.playbackRate=1;this.playbackLabel();}
draw(){const t=this.a.currentTime+this.left.offset;this.target=t;this.slider.value=t;this.position.textContent=`${clock(t)} · edit ${clock(this.item.selection.start)} → ${clock(this.item.selection.end)}${this.meta?' · fotogramma '+frameIndex(this.meta,t):''}`;}
destroy(){
if(this.closed)return;
if(this.a?.readyState>=2)this.studio.editComparePosition={key:this.key,time:this.a.currentTime+this.left.offset,playing:this.playing,selectionOnly:this.selectionOnly};
this.closed=true;this.pause();this.abort.abort();this.original?.destroy();this.result?.destroy();
}
}
+87
View File
@@ -0,0 +1,87 @@
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){
const e=c.edit,m=e.mask;
return JSON.stringify([e.source,e.start,e.end,e.fade,m]);
}
export function compositeControls(studio,root,m){
m.composite_mode??='source';m.composite_grow??=0;m.composite_feather??=8;
studio.field(root,'Area da applicare sull’originale',m,'composite_mode',{options:[['source','Maschera caricata · regolazioni separate'],['generation','Stessa area usata per generare']],change:()=>{studio.save();studio.render();},hint:'L’espansione per H3 può includere il telaio e il vagone. Le regolazioni separate evitano di incollare anche quelle ricostruzioni sul video originale.'});
if(m.composite_mode==='source'){
studio.field(root,'Espandi / contrai il montaggio · pixel del sorgente',m,'composite_grow',{type:'number',step:1,hint:'0 rispetta l’area caricata, anche se la generazione usa un’espansione maggiore.'});
studio.field(root,'Feather del montaggio · pixel del sorgente',m,'composite_feather',{type:'number',min:0,step:1,hint:'Sfumatura verso l’interno: ammorbidisce il contorno senza estendere la modifica nelle aree nere. 0 mantiene il bordo netto.'});
}
}
export class MaskEditor{
constructor(studio,parent){
this.studio=studio;this.closed=false;this.abort=new AbortController();
const c=studio.config,e=c.edit;
e.mask={enabled:false,source:'',grow:0,feather:0,opacity:.55,view:'overlay',preview_area:'composite',...e.mask};
const m=e.mask,root=studio.section(parent,'Maschera video · opzionale');
root.append(el('p','Carica il tuo video bianco e nero, allineato al sorgente completo. Bianco: usa la zona generata. Nero: conserva il video originale. I grigi miscelano i due. La maschera non viene generata dal workflow.'));
studio.field(root,'Usa la maschera video',m,'enabled',{type:'checkbox',change:()=>{studio.save();studio.render();}});
studio.asset(root,'Video maschera caricato da te',m,'source','video',()=>{m.source='';m.enabled=false;},()=>{m.enabled=true;});
if(!m.enabled)return;
studio.field(root,'Espandi / contrai per H3 · pixel del sorgente',m,'grow',{type:'number',step:1,hint:'Solo area di generazione: valori positivi espandono il bianco; negativi lo contraggono.'});
studio.field(root,'Feather per H3 · pixel del sorgente',m,'feather',{type:'number',min:0,step:.5,hint:'Sfumatura della maschera che guida il modello.'});
compositeControls(studio,root,m);
studio.field(root,'Area da verificare nell’overlay',m,'preview_area',{options:[['composite','Montaggio finale sull’originale'],['generation','Area di generazione H3']]});
studio.field(root,'Vista dell’anteprima',m,'view',{options:[['overlay','Video + maschera arancione'],['mask','Solo maschera elaborata'],['source','Solo video originale']]});
studio.field(root,'Opacità overlay · solo anteprima',m,'opacity',{type:'number',min:0,max:1,step:.05});
this.go=el('button','Prepara video overlay');this.go.type='button';this.go.onclick=()=>this.start();
this.notice=el('p');this.notice.setAttribute('role','status');this.progress=el('progress');if(this.progress)this.progress.hidden=true;
this.previewRoot=el('div');root.append(this.go,this.notice,this.progress,this.previewRoot);
root.append(el('small','L’overlay verifica l’area scelta e il raccordo temporale senza avviare H3. Generazione e montaggio possono usare bordi diversi. Il modello usa una griglia più grossa; il montaggio rispetta la maschera nei pixel del sorgente.'));
this.key=maskKey(c);this.refresh();
const saved=studio.maskPreview;
if(saved?.key===this.key)this.show(saved.file);
this.watch=setInterval(()=>{if(maskKey(c)!==this.key){this.key=maskKey(c);this.invalidate();}this.refresh();},350);
}
refresh(){
if(!this.go)return;
const timeline=this.studio.editTimeline;
this.go.disabled=this.busy||!this.studio.config.edit.source||!this.studio.config.edit.mask.source||this.studio.uploads>0||!timeline?.ready;
if(!this.busy&&!timeline?.ready){this.notice.textContent=timeline?.error||'Attendi la preparazione della timeline prima di creare l’overlay.';this.readinessNotice=true;}
else if(this.readinessNotice){this.notice.textContent='';this.readinessNotice=false;}
}
invalidate(){
this.cancel();this.player?.destroy();this.player=null;this.previewRoot.replaceChildren();
this.notice.textContent='Impostazioni o selezione cambiate. Prepara di nuovo l’overlay per vedere l’area aggiornata.';
}
cancel(){
clearTimeout(this.poll);this.busy=false;if(this.progress)this.progress.hidden=true;
if(this.job){const id=this.job;this.job=null;this.studio.request('/dogma/h3/v2/edit/mask-preview/'+id,{method:'DELETE'}).catch(()=>{});}
}
async start(){
if(this.closed||this.busy)return;
try{
const timeline=this.studio.editTimeline;
if(!timeline?.commitInputs())throw new Error(timeline?.inputError||'Attendi la preparazione della timeline.');
this.cancel();this.player?.destroy();this.player=null;this.previewRoot.replaceChildren();
const c=this.studio.config;this.key=maskKey(c);const key=this.key;
const data={source:c.edit.source,start:c.edit.start,end:c.edit.end,fade:c.edit.fade,mask:{...c.edit.mask}};
this.busy=true;this.refresh();this.progress.hidden=false;this.progress.removeAttribute('value');this.notice.textContent='Preparazione overlay della tua maschera…';
const result=await this.studio.request('/dogma/h3/v2/edit/mask-preview',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data),signal:this.abort.signal});
if(this.closed||key!==this.key){this.studio.request('/dogma/h3/v2/edit/mask-preview/'+result.id,{method:'DELETE'}).catch(()=>{});return;}
this.job=result.id;this.pollJob(key);
}catch(e){if(!this.closed&&e.name!=='AbortError'){this.busy=false;if(this.progress)this.progress.hidden=true;this.notice.textContent=e.message;this.refresh();}}
}
async pollJob(key){
if(this.closed||!this.job||key!==this.key)return;
try{
const result=await this.studio.request('/dogma/h3/v2/edit/mask-preview/'+this.job,{signal:this.abort.signal});
if(this.closed||key!==this.key)return;
if(result.status==='done'){
this.job=null;this.busy=false;if(this.progress)this.progress.hidden=true;this.studio.maskPreview={key,file:result.file};this.show(result.file);this.refresh();return;
}
if(result.status==='error'||result.status==='cancelled')throw new Error(result.message||'Anteprima annullata.');
if(result.total){this.progress.max=result.total;this.progress.value=result.done;this.notice.textContent=`Preparazione overlay · ${result.done}/${result.total} fotogrammi`;}
this.poll=setTimeout(()=>this.pollJob(key),500);
}catch(e){if(!this.closed&&e.name!=='AbortError'){this.cancel();this.notice.textContent=e.message;this.refresh();}}
}
show(file){this.player?.destroy();this.player=mediaPreview(file,{loop:true});this.previewRoot.replaceChildren(this.player.root);this.notice.textContent=this.studio.config.edit.mask.preview_area==='generation'?'Overlay pronto: area che guida H3. Può essere più ampia del montaggio finale.':'Overlay pronto: area applicata sull’originale, inclusi i bordi sfumati.';}
destroy(){if(this.closed)return;this.closed=true;clearInterval(this.watch);this.cancel();this.abort.abort();this.player?.destroy();}
}
+48
View File
@@ -0,0 +1,48 @@
import { api } from '../../scripts/api.js';
const el=(tag,text='')=>{const e=document.createElement(tag);e.textContent=text;return e;};
export function inputFile(name){
const path=name.replaceAll('\\','/'),i=path.lastIndexOf('/');
return {filename:path.slice(i+1),subfolder:i<0?'':path.slice(0,i),type:'input'};
}
export const viewURL=file=>api.apiURL('/view?'+new URLSearchParams(file));
export function mediaPreview(file,{kind='video',className='',loop=false}={}){
const root=el('div');root.className='dg-media-preview';
const media=el(kind==='image'?'img':'video');media.className=className;
if(kind==='image')media.alt=file.filename;else{media.controls=true;media.playsInline=true;media.preload='auto';media.loop=loop;}
const status=el('div');status.className='dg-media-status';status.setAttribute('role','status');
const label=el('span'),retry=el('button','Ricarica anteprima');retry.type='button';retry.hidden=true;
status.append(label,retry);root.append(media,status);
const abort=new AbortController();let closed=false,timer,attempt=0,resume=0;
const message=(text,error=false)=>{if(closed)return;root.dataset.state=error?'error':'loading';label.textContent=text;status.hidden=false;retry.hidden=!error;};
const ready=()=>{if(closed)return;clearTimeout(timer);root.dataset.state='ready';status.hidden=true;};
const load=()=>{
clearTimeout(timer);resume=kind==='video'?media.currentTime||0:0;
message('Caricamento anteprima…');
media.src=viewURL({...file,...(attempt?{dg_reload:attempt}: {})});
if(kind!=='image')media.load();
timer=setTimeout(()=>message('Anteprima in attesa. Puoi ricaricarla senza perdere la selezione.',true),15000);
};
retry.onclick=()=>{attempt++;load();};
media.addEventListener(kind==='image'?'load':'loadeddata',ready,{signal:abort.signal});
media.addEventListener('loadedmetadata',()=>{if(resume>0)media.currentTime=Math.min(resume,media.duration);},{signal:abort.signal});
media.addEventListener('error',async()=>{
clearTimeout(timer);const current=attempt;
message('Impossibile aprire l’anteprima. Verifico il file…',true);
try{
const response=await api.fetchApi('/view?'+new URLSearchParams(file),{method:'HEAD',signal:abort.signal});
if(closed||current!==attempt)return;
if(response.status===404)message('File non trovato. Ricarica il file sorgente.',true);
else if(!response.ok)message(`Anteprima non disponibile (errore ${response.status}). Riprova.`,true);
else message(kind==='image'?'Immagine non leggibile dal browser. Prova PNG o JPEG.':'Il file esiste, ma il browser non riesce a decodificarlo. Per l’anteprima usa MP4 H.264.',true);
}catch(e){if(!closed&&current===attempt&&e.name!=='AbortError')message('Connessione interrotta. Ricarica l’anteprima.',true);}
},{signal:abort.signal});
const destroy=()=>{if(closed)return;closed=true;clearTimeout(timer);abort.abort();retry.onclick=null;if(kind!=='image')media.pause();media.removeAttribute('src');if(kind!=='image')media.load();};
root._dogmaMedia={destroy};load();
return {root,media,destroy,reload:()=>{attempt++;load();}};
}
export function releaseMedia(root){
for(const e of root?.querySelectorAll('.dg-media-preview')||[])e._dogmaMedia.destroy();
}
+119
View File
@@ -0,0 +1,119 @@
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{
constructor(studio,parent,item){
this.studio=studio;this.item=item;this.closed=false;this.abort=new AbortController();
this.root=el('details','','dg-card dg-restitch');this.root.append(el('summary','Rifinisci maschera · preset e impostazioni personali'));parent.append(this.root);
this.body=el('div');this.root.append(this.body);this.notice=el('p');this.notice.setAttribute('role','status');this.body.append(this.notice);
this.root.addEventListener('toggle',()=>{if(this.closed)return;if(this.root.open){studio.restitchOpenFor=item.id;this.start();}else{studio.restitchOpenFor=null;this.release();this.started=false;}},{signal:this.abort.signal});
if(studio.restitchOpenFor===item.id)this.root.open=true;
}
async job(path,data){
const request=await this.studio.request(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data),signal:this.abort.signal});
for(;;){
const result=await this.studio.request('/dogma/h3/v2/edit/restitch/job/'+request.id,{signal:this.abort.signal});
if(result.status==='done')return result.result;if(result.status==='error')throw Error(result.message);
await new Promise(resolve=>{this.pollTimer=setTimeout(resolve,250);this.pollResolve=resolve;});
if(this.closed||!this.root.open)throw new DOMException('Pannello chiuso','AbortError');
}
}
async start(){
if(this.started||this.closed)return;this.started=true;delete this.root.dataset.readyMs;this.openedAt=performance.now();this.body.replaceChildren(this.notice);this.notice.textContent='Preparazione delle anteprime condivise…';
const epoch=this.loadEpoch=(this.loadEpoch||0)+1;
try{
const info=await this.job('/dogma/h3/v2/edit/restitch/preview',{session:this.studio.config.session,id:this.item.id});
if(this.closed||!this.root.open||epoch!==this.loadEpoch)return;
this.info=info;this.build();
}catch(e){if(this.closed||e.name==='AbortError')return;this.notice.textContent=e.message;this.body.append(actionButton('Riprova',()=>{this.started=false;this.start();}));}
}
build(){
const info=this.info,scale=Math.max(.25,info.source_width/1664),r=n=>Math.round(n*scale),g=info.base.grow,f=info.base.feather;
this.presets=[{id:'current',label:'Attuale',grow:g,feather:f},{id:'soft',label:'Raccordo morbido',grow:g,feather:f+r(8)},
{id:'expand',label:'Espansione lieve',grow:g+r(4),feather:Math.max(f,r(8))},{id:'expand-soft',label:'Espansione progressiva',grow:g+r(12),feather:f+r(16)},
{id:'contract',label:'Contrazione lieve',grow:g-r(4),feather:Math.max(f,r(8))},{id:'contract-soft',label:'Contrazione progressiva',grow:g-r(12),feather:f+r(8)}];
for(const p of this.presets){p.grow=clamp(p.grow,-256,256);p.feather=clamp(p.feather,0,256);}
this.studio.restitchDrafts??={};const draft=this.studio.restitchDrafts[this.item.id];
this.custom={id:'custom',label:'Personalizzata',grow:draft?.grow??g,feather:draft?.feather??f};this.presets.push(this.custom);this.selected=this.presets.find(p=>p.id===draft?.selected)||this.presets[0];
this.body.replaceChildren();this.body.append(el('p','Tutte le anteprime sono sincronizzate e in loop. Le prove non modificano il file salvato; applica soltanto quella scelta.'));
this.toolbar=el('div','','dg-edit-controls');this.playButton=actionButton('Pausa anteprime',()=>{if(this.video.paused)this.play();else this.video.pause();});
this.scrub=el('input');this.scrub.type='range';this.scrub.min=0;this.scrub.max=info.duration;this.scrub.step=1/info.fps;this.scrub.setAttribute('aria-label','Posizione di tutte le anteprime restitch');
this.scrub.oninput=()=>{this.video.currentTime=Number(this.scrub.value);};this.position=el('span','0.00 s');this.toolbar.append(this.playButton,this.position);this.body.append(this.toolbar,this.scrub);
const grid=el('div','','dg-restitch-grid');this.cards=[];this.canvases=[];
for(const p of this.presets){
const card=actionButton('',()=>this.choose(p));card.className='dg-restitch-choice';card.setAttribute('aria-label','Seleziona '+p.label);card.setAttribute('aria-pressed',String(p===this.selected));
const title=el('strong',p.label),canvas=el('canvas'),settings=el('small');canvas.width=info.width;canvas.height=info.height;canvas.setAttribute('aria-label','Anteprima '+p.label);this.canvases.push(canvas);this.cards.push({card,title,settings,p});card.replaceChildren(title,canvas,settings);grid.append(card);
}
this.body.append(grid);this.hover=new RestitchHover(this,Renderer);this.cards.forEach((c,n)=>this.hover.bind(c.card,c.p,this.canvases[n]));
const manual=el('div','','dg-grid');
for(const [key,label,min,max]of[['grow','Espansione / contrazione · px',-256,256],['feather','Feather interno · px',0,256]]){
const wrap=el('label','','dg-field'),input=el('input');wrap.append(el('span',label));input.type='number';input.min=min;input.max=max;input.step=1;input.value=this.custom[key];
input.oninput=()=>{if(!Number.isFinite(input.valueAsNumber))return;this.custom[key]=clamp(input.valueAsNumber,min,max);this.choose(this.custom);if(this.video.paused)this.draw();};input.onchange=()=>{input.value=this.custom[key];};wrap.append(input);manual.append(wrap);
}
this.body.append(el('h3','Impostazioni personali'),manual);
this.applyButton=actionButton('Applica al finale',()=>this.apply(),'dg-primary');this.body.append(this.applyButton);
this.body.append(el('small',`Passa il mouse su un riquadro per ingrandirlo. Griglia ${info.width} × ${info.height} px; il dettaglio a 960 px viene preparato al primo passaggio e condiviso tra i preset. Il salvataggio usa i pixel e i tempi del sorgente; nessun file finale per ogni prova.`));
this.body.append(this.notice);this.notice.textContent='';this.refresh();
this.video=el('video');this.video.muted=true;this.video.loop=true;this.video.playsInline=true;this.video.preload='auto';this.video.className='dg-restitch-source';this.video.setAttribute('aria-hidden','true');this.body.append(this.video);
this.video.addEventListener('loadeddata',()=>{if(this.closed||!this.root.open)return;try{this.renderer=new Renderer(this.info,this.canvases);this.play();}catch(e){this.notice.textContent=e.message;}},{signal:this.abort.signal});
this.video.addEventListener('error',()=>{this.notice.textContent='Anteprima condivisa non leggibile. Chiudi e riapri la sezione per riprovare.';},{signal:this.abort.signal});
this.video.addEventListener('seeked',()=>this.draw(),{signal:this.abort.signal});
this.video.addEventListener('play',()=>{setAction(this.playButton,'Pausa anteprime');this.schedule();},{signal:this.abort.signal});
this.video.addEventListener('pause',()=>{this.cancelFrame();this.hover?.pause();setAction(this.playButton,'Riproduci anteprime');},{signal:this.abort.signal});
this.video.src=viewURL(info.file);this.video.load();
}
choose(p){this.selected=p;this.studio.restitchDrafts[this.item.id]={grow:this.custom.grow,feather:this.custom.feather,selected:p.id};this.refresh();if(this.video?.paused)this.draw();}
refresh(){
for(const c of this.cards){c.card.setAttribute('aria-pressed',String(c.p===this.selected));c.settings.textContent=`${c.p.grow>0?'+':''}${c.p.grow} px · feather ${c.p.feather} px`;}
if(this.applyButton)this.applyButton.disabled=this.applying||this.studio.pending||this.selected.grow===this.info.base.grow&&this.selected.feather===this.info.base.feather;
}
play(){if(!this.renderer)return;this.studio.editCompare?.pause();this.video.play().catch(()=>{setAction(this.playButton,'Riproduci anteprime');this.notice.textContent='Premi Riproduci anteprime per avviare tutti i riquadri.';});}
schedule(){this.cancelFrame();if(this.closed||!this.video||this.video.paused)return;const next=()=>{if(this.closed||this.video?.paused)return;this.draw();this.schedule();};if(this.video.requestVideoFrameCallback)this.frame=this.video.requestVideoFrameCallback(next);else this.raf=requestAnimationFrame(next);}
cancelFrame(){if(this.frame!=null)this.video?.cancelVideoFrameCallback?.(this.frame);cancelAnimationFrame(this.raf);this.frame=null;}
draw(){if(!this.renderer||!this.video||this.video.readyState<2)return;this.renderer.draw(this.video,this.presets);if(!this.root.dataset.readyMs)this.root.dataset.readyMs=Math.round(performance.now()-this.openedAt);this.scrub.value=this.video.currentTime;this.position.textContent=this.video.currentTime.toFixed(2)+' s';for(const c of this.canvases)c.dataset.time=this.video.currentTime.toFixed(6);this.hover?.draw();}
async apply(){
if(this.applyButton.disabled)return;this.applying=true;this.refresh();this.notice.textContent='Applicazione alla dimensione originale… Nessuna nuova generazione.';
try{
const result=await this.job('/dogma/h3/v2/edit/restitch/apply',{session:this.studio.config.session,id:this.item.id,revision:this.info.revision,grow:this.selected.grow,feather:this.selected.feather});
if(this.closed)return;Object.assign(this.item,result);this.studio.restitchDrafts[this.item.id]={grow:this.selected.grow,feather:this.selected.feather,selected:'current'};this.studio.data.message=result.export_error||'Restitch applicato al finale.';this.applying=false;this.studio.render();
}catch(e){if(this.closed||e.name==='AbortError')return;this.applying=false;this.notice.textContent=e.message;this.refresh();}
}
release(){this.applying=false;this.loadEpoch=(this.loadEpoch||0)+1;this.hover?.destroy();this.hover=null;this.cancelFrame();this.video?.pause();if(this.video){this.video.removeAttribute('src');this.video.load();}this.video=null;this.renderer?.destroy();this.renderer=null;clearTimeout(this.pollTimer);this.pollResolve?.();}
destroy(){if(this.closed)return;this.closed=true;this.release();this.abort.abort();}
}
export class Renderer{
constructor(info,canvases){
this.info=info;this.canvases=canvases;this.contexts=canvases.map(c=>c.getContext('2d'));this.output=document.createElement('canvas');this.output.width=info.width*canvases.length;this.output.height=info.height;
const gl=this.gl=this.output.getContext('webgl',{alpha:false,antialias:false,preserveDrawingBuffer:true});
if(!gl){this.cpu=document.createElement('canvas');this.cpu.width=info.width*4;this.cpu.height=info.height;this.cpuContext=this.cpu.getContext('2d',{willReadFrequently:true});return;}
const vertex='attribute vec2 p;varying vec2 uv;void main(){uv=p*.5+.5;gl_Position=vec4(p,0.,1.);}';
const fragment=`precision highp float;varying vec2 uv;uniform sampler2D atlas;uniform vec2 size;uniform vec2 source;uniform float grow;uniform float feather;uniform float range;uniform float fade;
vec2 coord(vec2 q,float panel){return vec2((clamp(q.x,0.,1.)*(size.x-1.)+.5+panel*size.x)/(4.*size.x),(clamp(q.y,0.,1.)*(size.y-1.)+.5)/size.y);}
float sdf(vec2 q){return (texture2D(atlas,coord(q,2.)).r*2.-1.)*range;}
float mask(vec2 q){return texture2D(atlas,coord(q,3.)).r;}
void main(){float d=sdf(uv);float a=mask(uv);float weight;
if(abs(grow)<.01){weight=a*(feather>.01?smoothstep(0.,feather,max(d,0.)):1.);}
else{vec2 du=1./size;vec2 grad=vec2(sdf(uv+vec2(du.x,0.))-sdf(uv-vec2(du.x,0.)),sdf(uv+vec2(0.,du.y))-sdf(uv-vec2(0.,du.y)));vec2 near=uv+normalize(grad+vec2(.00001))*max(0.,-d+2.*source.x/size.x)/source;float opacity=max(a,mask(near));weight=(feather>.01?smoothstep(0.,feather,d+grow):step(0.,d+grow))*opacity;}
gl_FragColor=vec4(mix(texture2D(atlas,coord(uv,0.)).rgb,texture2D(atlas,coord(uv,1.)).rgb,weight*fade),1.);}`;
const shader=(type,text)=>{const s=gl.createShader(type);gl.shaderSource(s,text);gl.compileShader(s);if(!gl.getShaderParameter(s,gl.COMPILE_STATUS))throw Error('Anteprima GPU non disponibile: '+gl.getShaderInfoLog(s));return s;};
const program=this.program=gl.createProgram();gl.attachShader(program,shader(gl.VERTEX_SHADER,vertex));gl.attachShader(program,shader(gl.FRAGMENT_SHADER,fragment));gl.linkProgram(program);if(!gl.getProgramParameter(program,gl.LINK_STATUS))throw Error('Impossibile preparare le anteprime.');gl.useProgram(program);
this.buffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.buffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);const p=gl.getAttribLocation(program,'p');gl.enableVertexAttribArray(p);gl.vertexAttribPointer(p,2,gl.FLOAT,false,0,0);
this.texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,this.texture);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);
this.u=Object.fromEntries(['size','source','grow','feather','range','fade'].map(k=>[k,gl.getUniformLocation(program,k)]));gl.uniform2f(this.u.size,info.width,info.height);gl.uniform2f(this.u.source,info.source_width,info.source_height);gl.uniform1f(this.u.range,info.field_range);
}
draw(video,presets){
const i=this.info,w=i.width,h=i.height,t=video.currentTime,fade=i.fade>0?clamp(Math.min((t+1/i.fps)/i.fade,(i.duration-t)/i.fade),0,1):1;
if(this.gl){const gl=this.gl;gl.bindTexture(gl.TEXTURE_2D,this.texture);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,video);gl.uniform1f(this.u.fade,fade);
presets.forEach((p,n)=>{gl.viewport(n*w,0,w,h);gl.uniform1f(this.u.grow,p.grow);gl.uniform1f(this.u.feather,p.feather);gl.drawArrays(gl.TRIANGLE_STRIP,0,4);});
this.contexts.forEach((c,n)=>c.drawImage(this.output,n*w,0,w,h,0,0,w,h));
}else{
this.cpuContext.drawImage(video,0,0);const pixels=this.cpuContext.getImageData(0,0,w*4,h).data;
presets.forEach((p,n)=>{const frame=this.contexts[n].createImageData(w,h),a=frame.data;
for(let y=0;y<h;y++)for(let x=0;x<w;x++){const q=(y*w*4+x)*4,k=(y*w+x)*4,d=(pixels[q+w*8]/255*2-1)*i.field_range;let z=clamp((d+p.grow)/Math.max(p.feather,.001),0,1),alpha=z*z*(3-2*z);if(!p.grow)alpha*=pixels[q+w*12]/255;alpha*=fade;for(let c=0;c<3;c++)a[k+c]=Math.round(pixels[q+c]*(1-alpha)+pixels[q+w*4+c]*alpha);a[k+3]=255;}this.contexts[n].putImageData(frame,0,0);});
}
}
destroy(){if(this.gl){this.gl.deleteTexture(this.texture);this.gl.deleteBuffer(this.buffer);this.gl.deleteProgram(this.program);this.gl.getExtension('WEBGL_lose_context')?.loseContext();}this.output.width=1;this.output.height=1;}
}
+81
View File
@@ -0,0 +1,81 @@
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{
constructor(panel,Renderer){
this.panel=panel;this.Renderer=Renderer;this.abort=new AbortController();this.closed=false;
this.root=el('div','dg-restitch-hover');this.root.setAttribute('aria-hidden','true');
this.title=el('strong');this.canvas=el('canvas');this.caption=el('small');this.root.append(this.title,this.canvas,this.caption);
// Keep the floating preview in the dialog's top layer; it never intercepts clicks.
panel.root.closest('dialog').append(this.root);
const signal=this.abort.signal;
window.addEventListener('keydown',e=>{if(e.key==='Escape'&&this.active){this.hide();e.preventDefault();e.stopPropagation();}},{capture:true,signal});
window.addEventListener('scroll',()=>this.hide(),{capture:true,passive:true,signal});
window.addEventListener('resize',()=>this.hide(),{signal});
window.addEventListener('blur',()=>this.hide(),{signal});
}
bind(card,preset,thumbnail){
const signal=this.abort.signal,show=e=>{
if(e.pointerType==='touch')return;clearTimeout(this.showTimer);clearTimeout(this.hideTimer);
this.pointer={x:e.clientX,y:e.clientY};
this.showTimer=setTimeout(()=>this.show(preset,thumbnail),this.active?0:140);
};
card.addEventListener('pointerenter',show,{signal});
card.addEventListener('pointermove',e=>{this.pointer={x:e.clientX,y:e.clientY};if(this.active)this.follow();},{signal});
card.addEventListener('pointerleave',()=>{clearTimeout(this.showTimer);this.hideTimer=setTimeout(()=>this.hide(),65);},{signal});
card.addEventListener('focus',()=>{if(!card.matches(':focus-visible'))return;const r=card.getBoundingClientRect();show({clientX:r.x+r.width/2,clientY:r.y+r.height/2});},{signal});
card.addEventListener('blur',()=>this.hide(),{signal});
}
show(preset,thumbnail){
if(this.closed||!this.panel.root.open)return;
this.active={preset,thumbnail};this.title.textContent=preset.label;this.root.dataset.open='true';
const ratio=this.panel.info.width/this.panel.info.height;
const viewport=window.visualViewport,w=viewport?.width||innerWidth,h=viewport?.height||innerHeight;
const width=Math.max(120,Math.min(1080,w*.62,(h*.76-72)*ratio,w-32));
this.root.style.width=width+'px';this.canvas.style.aspectRatio=ratio;
this.draw();this.follow(true);this.loadDetail();
}
follow(immediate=false){
if(!this.active)return;const viewport=window.visualViewport,ox=viewport?.offsetLeft||0,oy=viewport?.offsetTop||0;
const w=viewport?.width||innerWidth,h=viewport?.height||innerHeight,r=this.root.getBoundingClientRect(),p=this.pointer;
// Anchor opposite the pointer, then add a small, damped vertical follow.
const left=p.x<w/2?p.x+28:p.x-r.width-28;
this.target={x:clamp(left,ox+16,ox+w-r.width-16),y:clamp(p.y-r.height*.48,oy+16,oy+h-r.height-16)};
if(immediate||!this.position){this.position={...this.target};this.place();}
if(!this.motion)this.motion=requestAnimationFrame(()=>this.tick());
}
tick(){this.motion=null;if(!this.active)return;const p=this.position,t=this.target;
const reduced=matchMedia('(prefers-reduced-motion: reduce)').matches,k=reduced?1:.2;p.x+=(t.x-p.x)*k;p.y+=(t.y-p.y)*k;this.place();
if(Math.abs(t.x-p.x)+Math.abs(t.y-p.y)>.3)this.motion=requestAnimationFrame(()=>this.tick());
}
place(){this.root.style.transform=`translate3d(${this.position.x}px,${this.position.y}px,0)`;}
async loadDetail(){
if(this.loading||this.detailInfo||this.detailError||this.closed)return;this.loading=true;
try{
const info=await this.panel.job('/dogma/h3/v2/edit/restitch/preview',{session:this.panel.studio.config.session,id:this.panel.item.id,detail:true});
if(this.closed)return;this.detailInfo=info;this.root.dataset.preparedMs=Math.round(info.elapsed_seconds*1000);const video=this.video=el('video','dg-restitch-source');video.muted=true;video.loop=true;video.playsInline=true;video.preload='auto';this.panel.body.append(video);
video.addEventListener('loadeddata',()=>{if(this.closed)return;try{this.renderer=new this.Renderer(info,[this.canvas]);this.sync();this.draw();}catch(e){this.detailError=e.message;}},{signal:this.abort.signal});
video.addEventListener('seeked',()=>{if(!this.closed)this.draw();},{signal:this.abort.signal});
video.addEventListener('error',()=>{this.detailError='Dettaglio non disponibile';this.draw();},{signal:this.abort.signal});
video.src=viewURL(info.file);video.load();
}catch(e){if(!this.closed&&e.name!=='AbortError'){this.detailError=e.message;this.draw();}}
finally{this.loading=false;}
}
sync(){
const master=this.panel.video,video=this.video;if(!master||!video||!this.renderer||!this.active)return false;
if(video.seeking)return false;
if(Math.abs(video.currentTime-master.currentTime)>.075){video.currentTime=master.currentTime;return false;}
if(master.paused)video.pause();else if(video.paused)video.play().catch(()=>{});
return video.readyState>=2;
}
draw(){
if(!this.active||this.closed)return;const {preset,thumbnail}=this.active,detail=this.sync(),info=detail?this.detailInfo:this.panel.info;
if(this.canvas.width!==info.width||this.canvas.height!==info.height){this.canvas.width=info.width;this.canvas.height=info.height;}
if(detail)this.renderer.draw(this.video,[preset]);else this.canvas.getContext('2d').drawImage(thumbnail,0,0,this.canvas.width,this.canvas.height);
const t=this.panel.video?.currentTime||0;this.canvas.dataset.time=t.toFixed(6);this.root.dataset.quality=detail?'detail':'grid';
this.caption.textContent=`${preset.grow>0?'+':''}${preset.grow} px · feather ${preset.feather} px · ${info.width} × ${info.height} · ${t.toFixed(2)} s`+(!detail?(this.detailError?' · Dettaglio non disponibile':' · Preparazione dettaglio…'):'');
}
pause(){this.video?.pause();}
hide(){clearTimeout(this.showTimer);clearTimeout(this.hideTimer);this.active=null;delete this.root.dataset.open;this.pause();cancelAnimationFrame(this.motion);this.motion=null;}
destroy(){if(this.closed)return;this.closed=true;this.hide();this.abort.abort();this.renderer?.destroy();if(this.video){this.video.removeAttribute('src');this.video.load();this.video.remove();}this.root.remove();}
}
+36
View File
@@ -0,0 +1,36 @@
export function frameTime(meta,index){
if(meta.frame_times)return index>=meta.frame_times.length?meta.duration:meta.frame_times[Math.max(0,index)];
return index/meta.fps;
}
export const frameCount=meta=>meta.frame_times?.length??Math.floor(meta.duration*meta.fps+1e-6);
export function frameIndex(meta,time){
if(!meta.frame_times)return Math.max(0,Math.min(frameCount(meta),Math.floor(time*meta.fps+.5)));
let lo=0,hi=meta.frame_times.length;
while(lo<hi){const mid=(lo+hi)>>1;if(frameTime(meta,mid)<time)lo=mid+1;else hi=mid;}
if(lo>0&&time-frameTime(meta,lo-1)<frameTime(meta,lo)-time)lo--;
return lo;
}
export function snapSelection(start,end,meta,side='end'){
const total=frameCount(meta);let a=Math.max(0,Math.min(total-1,frameIndex(meta,start))),b=Math.max(1,Math.min(total,frameIndex(meta,end)));
if(side==='start')a=Math.min(a,b-1);else b=Math.max(b,a+1);
return {start:frameTime(meta,a),end:frameTime(meta,b)};
}
export function stepTime(meta,time,delta){
return frameTime(meta,Math.max(0,Math.min(frameCount(meta)-1,frameIndex(meta,time)+delta)));
}
export function parseSeconds(value){
const s=value.trim().replace(',','.');
return /^(?:\d+(?:\.\d*)?|\.\d+)$/.test(s)?Number(s):NaN;
}
export function parseSelection(startValue,endValue,meta){
let start=parseSeconds(startValue),end=parseSeconds(endValue);
if(!Number.isFinite(start)||!Number.isFinite(end))throw new Error('Inserisci i secondi usando punto o virgola.');
// The inputs display six decimals; accept their half-unit rounding at EOF.
const tolerance=.5e-6+Number.EPSILON*Math.max(1,meta.duration)*8;
if(start<0||end>meta.duration+tolerance)throw new Error('I tempi devono essere compresi nel video.');
start=Math.max(0,Math.min(meta.duration,start));end=Math.max(0,Math.min(meta.duration,end));
if(start>=end)throw new Error('L’inizio deve precedere la fine. Completa entrambi i tempi.');
const selection=snapSelection(start,end,meta);
if(selection.end-selection.start>meta.generation_frames.at(-1)/24+1e-8)throw new Error('La selezione supera la durata disponibile con queste reference.');
return selection;
}
+92
View File
@@ -0,0 +1,92 @@
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));}
export function validateFiles(files,kind,{multiple=false}={}){
if(!files.length)throw Error('Nessun file da caricare.');
if(!multiple&&files.length!==1)throw Error('Questa area accetta un solo file alla volta.');
for(const f of files){const actual=mediaKind(f);if(!actual||kind!=='media'&&actual!==kind)throw Error(`«${f.name}»: qui puoi caricare ${kind==='image'?'un’immagine':kind==='video'?'un video':'immagini e video'}.`);if(!f.size)throw Error(`«${f.name}» è vuoto e non può essere caricato.`);}
return files;
}
export function referencePlan(refs,files,limits){
validateFiles(files,'media',{multiple:true});
for(const kind of ['image','video']){const present=refs.filter(r=>r.kind===kind&&r.name).length,incoming=files.filter(f=>mediaKind(f)===kind).length;if(present+incoming>limits[kind])throw Error(`Limite reference: massimo ${limits.image} immagini e ${limits.video} video aggiuntivi. Riduci i file selezionati.`);}
return files.map(file=>({file,kind:mediaKind(file)}));
}
const fileTransfer=e=>Array.from(e.dataTransfer?.types||[]).includes('Files')||!!e.dataTransfer?.files?.length;
export function dropTarget(root,kind,submit,notice,{multiple=false,label=''}={}){
root.classList.add('dg-file-drop');root.dataset.fileKind=kind;if(label)root.setAttribute('aria-label',label);
let depth=0;const reset=()=>{depth=0;delete root.dataset.dragging;};
root.addEventListener('dragenter',e=>{if(!fileTransfer(e))return;e.preventDefault();e.stopPropagation();depth++;root.dataset.dragging='true';});
root.addEventListener('dragover',e=>{if(!fileTransfer(e))return;e.preventDefault();e.stopPropagation();e.dataTransfer.dropEffect='copy';root.dataset.dragging='true';});
root.addEventListener('dragleave',e=>{if(!depth)return;e.stopPropagation();depth=Math.max(0,depth-1);if(!depth)delete root.dataset.dragging;});
root.addEventListener('drop',e=>{
if(!fileTransfer(e))return;e.preventDefault();e.stopPropagation();reset();
try{
if(Array.from(e.dataTransfer.items||[]).some(item=>item.webkitGetAsEntry?.()?.isDirectory))throw Error('Trascina i singoli file, senza cartelle.');
const files=Array.from(e.dataTransfer.files||[]);validateFiles(files,kind,{multiple});submit(files);
}catch(error){notice(error.message,true);}
});
return reset;
}
export function guardFileNavigation(dialog){
dialog.addEventListener('dragover',e=>{if(fileTransfer(e)){e.preventDefault();e.dataTransfer.dropEffect='none';}});
dialog.addEventListener('drop',e=>{if(!fileTransfer(e))return;e.preventDefault();const toast=el('div','Rilascia il file in un’area di caricamento.','dg-upload-toast');toast.setAttribute('role','status');dialog.append(toast);setTimeout(()=>toast.remove(),3500);});
}
function current(studio,config,session,epoch){return studio.config===config&&studio.config.session===session&&studio.epoch===epoch;}
async function upload(studio,file){const data=new FormData();data.append('image',file);data.append('type','input');data.append('subfolder','DOGMA_DIRECTOR');const response=await studio.request('/upload/image',{method:'POST',body:data});return (response.subfolder?response.subfolder+'/':'')+response.name;}
function hint(root,text){const h=el('div','','dg-drop-hint');setAction(h,text,'upload');root.append(h);return h;}
export function assetField(studio,parent,title,obj,key,kind='image',options={}){
const root=studio.section(parent,title),name=obj[key];let busy=false;
if(name&&options.preview!==false)root.append(mediaPreview(inputFile(name),{kind,className:'dg-asset'}).root);
if(name)root.append(el('small',name));
hint(root,kind==='video'?'Trascina qui un video':'Trascina qui un’immagine');
const picker=el('input');picker.type='file';picker.accept=kind==='video'?'video/*':'image/*';picker.hidden=true;
const notice=el('p','','dg-upload-status');notice.setAttribute('role','status');
const message=(text,error=false)=>{notice.textContent=text;root.dataset.uploadState=error?'error':busy?'uploading':'idle';};
const choose=actionButton(name?(options.changeLabel||'Cambia file'):(options.loadLabel||'Carica file'),()=>{if(studio.uploads>0)message('Attendi il caricamento già in corso.');else picker.click();});let remove;
if(options.allowRemove!==false&&(name||options.remove))remove=actionButton('Rimuovi',()=>{if(options.remove)options.remove();else obj[key]='';studio.save();studio.render();});
const send=async files=>{
if(busy||studio.uploads>0){message('Attendi il caricamento già in corso.');return;}
try{validateFiles(files,kind);}catch(error){message(error.message,true);return;}
busy=true;choose.disabled=true;if(remove)remove.disabled=true;root.setAttribute('aria-busy','true');studio.uploads=(studio.uploads||0)+1;studio.status();message('Caricamento di '+files[0].name+'…');
const config=studio.config,session=config.session,epoch=studio.epoch;
try{
const name=await upload(studio,files[0]);if(!current(studio,config,session,epoch))return;
obj[key]=name;options.onUploaded?.(name);studio.save();studio.render();
}catch(error){if(error.name!=='AbortError')message(error.message,true);}
finally{busy=false;root.setAttribute('aria-busy','false');choose.disabled=false;if(remove)remove.disabled=false;studio.uploads=Math.max(0,(studio.uploads||1)-1);studio.status();}
};
picker.onchange=()=>{const files=Array.from(picker.files||[]);picker.value='';if(files.length)send(files);};
root.append(picker,choose);if(remove)root.append(remove);root.append(notice);
dropTarget(root,kind,send,message,{label:title});return root;
}
export function referenceDrop(studio,root,{image=9,video=3}={}){
const limits={image,video};let busy=false;
hint(root,'Trascina qui immagini e video di riferimento, anche più file insieme');
const notice=el('p',studio.referenceUploadNotice||'','dg-upload-status');notice.setAttribute('role','status');root.append(notice);
const message=(text,error=false)=>{notice.textContent=text;root.dataset.uploadState=error?'error':busy?'uploading':'idle';};
const send=async files=>{
if(busy||studio.uploads>0){message('Attendi il caricamento già in corso.');return;}
let plan;try{plan=referencePlan(studio.config.refs,files,limits);}catch(error){message(error.message,true);return;}
busy=true;studio.uploads=(studio.uploads||0)+1;studio.status();root.setAttribute('aria-busy','true');
const config=studio.config,session=config.session,epoch=studio.epoch;let done=0;const errors=[];
try{
for(const [i,entry]of plan.entries()){
message(`Caricamento reference ${i+1}/${plan.length}: ${entry.file.name}…`);
try{
const name=await upload(studio,entry.file);if(!current(studio,config,session,epoch))throw new DOMException('Caricamento annullato','AbortError');
const empty=config.refs.find(r=>r.kind===entry.kind&&!r.name);
if(empty)empty.name=name;else config.refs.push({kind:entry.kind,name});done++;studio.save();
}catch(error){if(error.name==='AbortError')throw error;errors.push(entry.file.name+': '+error.message);}
}
studio.referenceUploadNotice=errors.length?`Caricati ${done} file. `+errors.join(' · '):`Caricati ${done} file di riferimento.`;
if(done)studio.render();else message(studio.referenceUploadNotice,true);
}catch(error){if(error.name!=='AbortError')message(error.message,true);}
finally{busy=false;root.setAttribute('aria-busy','false');studio.uploads=Math.max(0,(studio.uploads||1)-1);studio.status();}
};
dropTarget(root,'media',send,message,{multiple:true,label:'Reference: trascina immagini e video'});
const pickers={};for(const kind of ['image','video']){const picker=el('input');picker.type='file';picker.accept=kind+'/*';picker.multiple=true;picker.hidden=true;picker.onchange=()=>{const files=Array.from(picker.files||[]);picker.value='';if(files.length)send(files);};pickers[kind]=picker;root.append(picker);}
return {choose:kind=>{if(!busy&&!studio.uploads)pickers[kind].click();else message('Attendi il caricamento già in corso.');}};
}
+272
View File
@@ -0,0 +1,272 @@
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-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;
const url=(path,params)=>api.apiURL(path+'?'+new URLSearchParams(params));
const clamp=(v,a,b)=>Math.min(b,Math.max(a,v));
export const clock=t=>{const m=Math.floor(t/60),s=t-m*60;return `${String(m).padStart(2,'0')}:${s.toFixed(3).padStart(6,'0')}`;};
export function renderEditor(studio,body){
const c=studio.config,e=c.edit;
const section=assetField(studio,body,'Video originale · scegli il tratto da modificare',e,'source','video',{
preview:false,allowRemove:false,loadLabel:'Carica video',changeLabel:'Cambia video',onUploaded:()=>{e.start=0;e.end=107/24;studio.editMeta=null;}});
if(e.source){
const timeline=el('div','','dg-edit-panel');section.append(timeline);
studio.editTimeline=new EditTimeline(studio,timeline,e);
}
studio.maskEditor=new MaskEditor(studio,body);
const refs=studio.section(body,'Reference per la modifica');
refs.append(el('p','Il tratto selezionato è <Video 1>. Le immagini aggiuntive sono <Picture 1>, <Picture 2>…; gli altri video sono <Video 2> e <Video 3>.'));
const drop=referenceDrop(studio,refs,{image:9,video:2});
const grid=el('div','','dg-grid');refs.append(grid);let pictures=0,videos=1;
c.refs.forEach((r,i)=>studio.asset(grid,r.kind==='image'?`Picture ${++pictures}`:`Video ${++videos}`,r,'name',r.kind,()=>c.refs.splice(i,1)));
if(pictures<9)refs.append(button('Aggiungi immagine',()=>drop.choose('image')));
if(videos<3)refs.append(button('Aggiungi video',()=>drop.choose('video')));
refs.append(el('small','Massimo 9 immagini e 3 video incluso il sorgente. I video aggiuntivi devono durare 2–15 s; la somma, sorgente selezionato incluso, non può superare 15 s.'));
const prompt=studio.section(body,'Cosa vuoi cambiare?');
studio.field(prompt,'Istruzioni di edit',c,'prompt',{multi:true,rows:7,hint:'Descrivi la modifica e il ruolo delle reference. Il sorgente viene inserito automaticamente come Video 1.'});
studio.field(prompt,'Seed',c,'seed',{type:'number',min:0,max:9007199254740990,step:1});
const anchors=studio.field(prompt,'Mantieni i fotogrammi ai due estremi come guida',e,'anchor_edges',{type:'checkbox',hint:e.mask?.enabled?'Con maschera attiva gli estremi non vengono forzati: anche lì può essere richiesta una modifica.':'Aiuta il raccordo. Disattiva se vuoi modificare anche il primo e l’ultimo fotogramma.'});anchors.disabled=!!e.mask?.enabled;
studio.field(prompt,'Raccordo con l’originale · secondi per lato',e,'fade',{type:'number',min:0,max:.5,step:.025,hint:'Sfumatura dentro la selezione. 0 = taglio netto. Una sfumatura troppo lunga può creare doppie immagini.'});
studio.loras(prompt,c.common_loras,'LoRA comuni a tutti i provini edit');
const advanced=el('details','','dg-card');advanced.append(el('summary','Modelli e campionamento personalizzato'));body.append(advanced);
studio.field(advanced,'Checkpoint Ref2VA',c.models,'ref2v',{options:['',...studio.catalog.models]});
for(const [key,label,options]of[['clip','Text encoder',studio.catalog.clip],['vae','Video VAE',studio.catalog.vae],['audio','Audio VAE',studio.catalog.vae]])studio.field(advanced,label,c.models,key,{options});
studio.sampleFields(advanced,e);
studio.field(advanced,'Anteprima durante il calcolo',c.preview,'enabled',{type:'checkbox'});
advanced.append(el('p','Provini alla dimensione scelta, poi sviluppo del provino approvato alla dimensione originale. Eventuali bordi per allineare H3 a 32 px vengono rimossi. Il sorgente può richiedere molta VRAM alla sua risoluzione originale.'));
const trials=studio.section(body,'Provini edit · velocità e varianti');
studio.field(trials,'Velocità dei provini',e,'trial_mode',{options:[['fast','Rapido · Turbo Ref2Video · 4 passaggi'],['same','Personalizzato · parametri avanzati']],hint:'Il rapido usa la LoRA Turbo Ref2Video installata. Il campionamento alla dimensione originale si sceglie nella scheda del provino.'});
studio.field(trials,'Dimensione dei provini · lato lungo',e,'trial_edge',{options:[[256,'256 px · più leggero'],[384,'384 px'],[512,'512 px']],change:()=>studio.render()});
studio.field(trials,'Anteprima durante il calcolo dei provini',e,'trial_live_preview',{type:'checkbox',hint:'Disattivata per velocizzare i provini. Il video completo del provino compare appena pronto.'});
studio.field(trials,'Confronta',c,'exploration',{options:[['seeds','Seed diversi · stesso prompt'],['prompts','Prompt diversi · stesso seed'],['loras','LoRA diverse · stesso prompt e seed']],change:()=>studio.render()});
if(c.exploration==='seeds')studio.field(trials,'Numero di provini',c,'count',{type:'number',min:1,max:10,step:1});
else{
c.variants.forEach((variant,i)=>{const row=studio.section(trials,`${c.exploration==='loras'?'Variante LoRA':'Variante prompt'} ${i+1}`);studio.field(row,'Trigger o istruzioni aggiuntive · facoltative',variant,'text',{multi:true,rows:3});
variant.loras??=[];studio.loras(row,variant.loras,'LoRA della variante');
if(c.variants.length>1)row.append(button('Rimuovi variante',()=>{c.variants.splice(i,1);studio.save();studio.render();}));
});
if(c.variants.length<10)trials.append(button('Aggiungi variante',()=>{c.variants.push({text:'',loras:[]});studio.save();studio.render();}));
}
trials.append(el('p',`I provini elaborano solo la selezione fino a ${e.trial_edge} px. In modalità rapida il primo caricamento e la prima preparazione restano necessari; i seed successivi riusano la preparazione comune. Scegli un provino per rigenerarlo alla dimensione originale con lo stesso prompt, seed e maschera.`));
const go=button(`Genera provini edit a ${e.trial_edge} px`,()=>studio.queue('draft'));go.className='dg-primary';go.dataset.queue='';body.append(go);
body.append(el('p','I provini sono senza audio. Il video completo conserva l’audio originale. La maschera limita la ricomposizione: nero originale, bianco generato.'));
}
export function renderEditTrials(studio,body){
if(studio.pending||studio.previewData)studio.live(body);
const items=studio.data.edit_trials||[];
if(!items.length){body.append(el('p','Qui appariranno i provini edit a 512 px.'));return;}
const selected=items.find(x=>x.id===studio.editTrialId)||items.at(-1);studio.editTrialId=selected.id;
const versions=studio.section(body,'Provini edit disponibili');
for(const [i,item]of items.entries()){
const choose=button(`Provino ${i+1} · ${item.config?.exploration==='loras'?loraLabel(item):'seed '+item.seed}`,()=>{studio.editTrialId=item.id;studio.editComparePosition=null;studio.render();});
if(item.id===selected.id)choose.className='is-active';versions.append(choose);
}
const card=studio.section(body,`${selected.label} · ${selected.width} × ${selected.height}`);
card.append(el('p',`Seed ${selected.seed} · selezione ${clock(selected.selection.start)} → ${clock(selected.selection.end)}`));
const stack=selected.loras||selected.config.common_loras||[];
if(stack.length){const l=el('details');l.append(el('summary',`LoRA del provino · ${stack.length}`));for(const entry of stack)l.append(el('small',`${entry.name} · peso ${entry.strength??1}${entry.enabled===false?' · disattivata':''}`));card.append(l);}
if(selected.sampling)card.append(el('small',`${selected.sampling.steps} passaggi${selected.sampling.turbo?' · Turbo':''}${selected.elapsed_seconds!=null?' · '+selected.elapsed_seconds.toFixed(1)+' s':''}${selected.prepared_reused?' · preparazione riutilizzata':''}`));
if(selected.timing_repaired)card.append(el('p','Fotogrammi recuperati dai latenti salvati. Il confronto usa l’anteprima ricostruita da quei dati, senza una nuova generazione.'));
else if(selected.timing_version!==2)card.append(el('small',selected.latent?'Questo provino precedente verrà recuperato dai latenti salvati per correggere la fluidità, senza rilanciare MiniMax.':'Questo vecchio provino non contiene i dati necessari al recupero dei fotogrammi: genera un nuovo provino.'));
const mask=selected.config.edit.mask;if(mask?.enabled)card.append(el('small',`Maschera del provino: ${mask.source} · generazione: espansione ${mask.grow} px · feather ${mask.feather} px`));
const prompt=el('details');prompt.append(el('summary','Prompt del provino'),el('pre',selected.prompt));card.append(prompt);
studio.editCompare=new EditComparison(studio,card,selected);
card.append(el('p',`Scelto per il finale: ${selected.label} · seed ${selected.seed}`));
studio.config.edit.final_mode ||= 'match';studio.config.edit.final_steps ??= 20;
studio.config.edit.final_method ||= 'preserve';studio.config.edit.final_denoise ??= .25;
studio.field(card,'Come preparare il finale',studio.config.edit,'final_method',{options:[['preserve','Mantieni edit · ingrandisci senza rigenerare'],['guided','Sviluppa con H3 · può cambiare l’edit'],['regenerate','Nuova generazione dal sorgente']],change:()=>studio.render(),hint:'Mantieni edit è predefinito: ingrandisce il risultato approvato senza sintetizzare nuovo dettaglio. Fuori dalla maschera usa il sorgente originale. Sviluppa con H3 parte dal provino, ma può aggiungere artefatti o cambiarne l’aspetto.'});
const actual=selected.sampling||selected.config.edit;
if(mask?.enabled){
studio.config.edit.mask??={};compositeControls(studio,card,studio.config.edit.mask);
card.append(el('small','Il video maschera resta quello salvato nel provino. Queste regolazioni del montaggio si possono cambiare anche scegliendo Mantieni edit, senza una nuova generazione.'));
}
if(studio.config.edit.final_method!=='preserve'){
studio.config.edit.final_resolution ||= 'native';
studio.field(card,'Risoluzione di calcolo H3',studio.config.edit,'final_resolution',{options:[['native','Nativa H3 · fino a 768 px sul lato corto'],['trial',`Come il provino · ${selected.width} × ${selected.height}`],['source','Dimensione originale · sperimentale']],hint:'L’export resta alla dimensione originale. Il calcolo nativo resta nel regime documentato di H3; la zona generata viene adattata al sorgente sotto la maschera. Il calcolo diretto alla dimensione originale può ignorare la modifica.'});
studio.field(card,'Campionamento del passaggio H3',studio.config.edit,'final_mode',{options:[['match',`Come il provino scelto · ${actual.turbo?'Turbo':'standard'} · ${actual.steps} passaggi`],['turbo','Turbo Ref2Video · 4 passaggi'],['standard','Standard · senza Turbo']],change:()=>studio.render(),hint:'Questa scelta vale anche per un provino già generato. Prompt, seed, sorgente, reference e maschera restano quelli del provino scelto.'});
if(studio.config.edit.final_mode==='standard')studio.field(card,'Passaggi del finale standard',studio.config.edit,'final_steps',{type:'number',min:1,max:100,step:1});
if(studio.config.edit.final_method==='guided'){
studio.field(card,'Intensità del raffinamento',studio.config.edit,'final_denoise',{type:'number',min:.01,max:1,step:.05,hint:'0,25 predefinito. Valori più alti danno più libertà al modello e possono cambiare il risultato.'});
card.append(el('small',selected.latent?'Lo sviluppo trasferisce i latenti salvati del provino e mantiene la maschera.':'Questo provino precedente non ha latenti salvati: lo sviluppo codifica il suo video approvato. Il contenuto può cambiare durante il raffinamento.'));
}
}
studio.field(card,'Cartella del finale · vuoto = cartella output Comfy',studio.config.edit,'final_output_dir',{hint:'Il finale viene copiato qui anche quando scegli un provino mentre gli altri sono ancora in calcolo.'});
card.append(button('Scegli cartella del finale…',()=>studio.browseFolders('edit')));
const finish=button('Prepara questo provino alla dimensione originale',()=>studio.useEditTrial(selected.id));finish.className='dg-primary';finish.dataset.editFinish=selected.id;card.append(finish);
card.append(el('small','Puoi scegliere appena un provino è pronto: il calcolo del provino in corso viene fermato al prossimo punto di controllo e gli altri vengono saltati. Prompt, seed e maschera restano quelli salvati nel provino.'));
}
export function renderEditResults(studio,body){
if(studio.pending||studio.previewData)studio.live(body);
if(studio.pending)body.append(el('p','Nuova lavorazione ancora in corso. I video salvati qui sotto appartengono alle lavorazioni precedenti.'));
const items=studio.data.edits||[];
if(!items.length){body.append(el('p','Qui apparirà il video completo con il tratto già sostituito.'));return;}
const selected=items.find(x=>x.id===studio.editResultId)||items.at(-1);studio.editResultId=selected.id;
const controls=studio.section(body,studio.pending?'Risultati precedenti salvati':'Risultati disponibili');
for(const [i,item]of items.entries()){
const origin=items[i].origin_trial_label||studio.data.edit_trials?.find(x=>x.id===item.trial)?.label||'provino precedente';
const choose=button(`Versione ${i+1} · da ${origin} · seed ${item.seed}`,()=>{studio.editResultId=item.id;studio.render();});
if(item.id===selected.id)choose.className='is-active';controls.append(choose);
}
const card=studio.section(body,'Video completo salvato · confronto sincronizzato');
const origin=selected.origin_trial_label||studio.data.edit_trials?.find(x=>x.id===selected.trial)?.label||'provino precedente';
card.append(el('p',`Risultato da ${origin} · seed ${selected.seed}${selected.sampling?' · '+(selected.sampling.turbo?'Turbo':'standard')+' · '+selected.sampling.steps+' passaggi':''}`));
if(selected.mask_report?.enabled)card.append(el('small','Maschera video verificata nel campionamento e applicata alla ricomposizione.'));
if(selected.development)card.append(el('p',selected.development.method==='preserve'?'Edit del provino mantenuto · ingrandimento senza nuova generazione':selected.development.method==='guided'?'Sviluppato dal provino approvato':'Nuova generazione dal sorgente'));
if(selected.export_encoding==='lossless_h264')card.append(el('p','Export senza perdita · fotogrammi originali e campioni colore protetti conservati. Il file può essere più grande.'));
else card.append(el('p','Export precedente: non include le correzioni della fluidità e del salvataggio senza perdita. Prepara nuovamente il finale dal provino.'));
if(selected.composite_mask_settings){const m=selected.composite_mask_settings;card.append(el('small',`Montaggio: ${m.composite_mode==='generation'?'area H3':'maschera separata'} · espansione ${m.grow} px · feather ${m.feather} px`));}
if(selected.generation_width)card.append(el('small',`Calcolo H3: ${selected.generation_width} × ${selected.generation_height} · export: ${selected.width} × ${selected.height}`));
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{
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')));
const link=el('a','Scarica video completo');link.href=viewURL(selected.video);link.download=selected.video.filename;card.append(link);
card.append(button('Torna alla selezione',()=>{studio.page='prepare';studio.render();}));
if(selected.config?.edit?.mask?.enabled)studio.restitchPanel=new RestitchPanel(studio,body,selected);
}
class EditTimeline{
constructor(studio,root,config){
this.studio=studio;this.root=root;this.config=config;this.closed=false;this.ready=false;this.error='';this.inputError='';this.abort=new AbortController();
root.append(el('p','Lettura dei fotogrammi e preparazione della timeline…'));
this.init().catch(e=>{if(!this.closed&&e.name!=='AbortError'){this.error=e.message;root.replaceChildren(el('p',e.message),button('Ricarica timeline',()=>{this.destroy();root.replaceChildren();studio.editTimeline=new EditTimeline(studio,root,config);}));studio.editMeta=null;}});
}
destroy(){if(this.video)this.studio.editPosition={source:this.config.source,time:this.video.currentTime,viewStart:this.viewStart,span:this.span};this.closed=true;this.ready=false;this.abort.abort();clearTimeout(this.thumbTimer);cancelAnimationFrame(this.seekRAF);cancelAnimationFrame(this.playRAF);this.preview?.destroy();}
async init(){
const studio=this.studio,config=this.config;
const base=await this.studio.request('/dogma/h3/v2/edit/metadata?'+new URLSearchParams({name:this.config.source}),{signal:this.abort.signal});
const others=this.studio.config.refs.filter(r=>r.kind==='video'&&r.name);
const refs=others.length?await Promise.all(others.map(r=>this.studio.request('/dogma/h3/v2/edit/metadata?'+new URLSearchParams({name:r.name}),{signal:this.abort.signal}))):[];
if(refs.some(r=>r.duration<2||r.duration>15))throw new Error('Ogni video reference aggiuntivo deve durare da 2 a 15 secondi.');
const budget=15-refs.reduce((sum,r)=>sum+r.duration,0),minimum=Math.max(5,...refs.map(r=>Math.floor((r.duration*24-5)/17)*17+5));
const m={...base,generation_frames:Array.from({length:21},(_,i)=>5+17*i).filter(n=>n>=minimum&&n/24<=budget+1e-8)};
if(this.closed)return;
if(!m.generation_frames.length)throw new Error('Le reference video non lasciano spazio per la selezione: accorciale o rimuovile.');
this.meta=m;this.studio.editMeta={...base,source:this.config.source};
Object.assign(this.config,snapSelection(this.config.start,this.config.end,m));this.studio.save();
this.viewStart=0;this.span=Math.min(m.duration,Math.max(20,this.config.end-this.config.start+6));
this.viewStart=clamp(this.config.start-2,0,m.duration-this.span);
const saved=studio.editPosition?.source===this.config.source?studio.editPosition:null;
if(saved){this.span=Math.min(m.duration,saved.span);this.viewStart=clamp(saved.viewStart,0,m.duration-this.span);}
this.root.replaceChildren();
this.preview=mediaPreview(inputFile(this.config.source),{className:'dg-edit-player'});
const v=this.video=this.preview.media;this.root.append(this.preview.root);
v.loop=studio.editLoop!==false;
this.info=el('p');this.root.append(this.info);
const controls=el('div','','dg-edit-controls');
const loopLabel=el('label','Ripeti in loop'),loop=el('input');loop.type='checkbox';loop.checked=studio.editLoop!==false;loop.onchange=()=>{studio.editLoop=loop.checked;v.loop=loop.checked;};loopLabel.prepend(loop);controls.append(loopLabel);
this.playButton=button('Riproduci selezione',()=>{if(!v.paused){v.pause();return;}if(!this.commitInputs())return;cancelAnimationFrame(this.seekRAF);this.seekRAF=null;if(v.currentTime<this.config.start||v.currentTime>=this.config.end)v.currentTime=this.config.start;this.playingSelection=true;v.play().catch(()=>{this.playingSelection=false;});});controls.append(this.playButton);
controls.append(button('Fotogramma precedente',()=>this.seek(stepTime(m,v.currentTime,-1))),button('Fotogramma successivo',()=>this.seek(stepTime(m,v.currentTime,1))));
controls.append(button('Inizia la selezione da qui',()=>{const t=frameTime(m,Math.min(frameCount(m)-1,frameIndex(m,v.currentTime))),d=this.config.end-this.config.start;this.select(Math.min(t,m.duration-d),Math.min(t+d,m.duration),'end');}));
controls.append(button('Riduci',()=>this.zoom(2)),button('Ingrandisci',()=>this.zoom(.5)),button('Tutto il video',()=>{this.span=m.duration;this.viewStart=0;this.paint(true);}));
this.root.append(controls);
const overviewLabel=el('label','Scorri nel video completo','dg-field');
const overview=this.overview=el('input');overview.type='range';overview.min=0;overview.max=m.duration;overview.step=1/m.fps;
overview.setAttribute('aria-label','Posizione nel video completo');
overview.oninput=()=>{const t=Number(overview.value);this.viewStart=clamp(t-this.span/2,0,m.duration-this.span);this.seek(t);this.paint(true);};
overviewLabel.append(overview);this.root.append(overviewLabel);
const track=this.track=el('div','','dg-edit-track');track.tabIndex=0;track.setAttribute('aria-label','Timeline della selezione');
this.thumbs=el('div','','dg-edit-thumbs');track.append(this.thumbs);
this.band=el('div','','dg-edit-selection');this.band.title='Trascina per spostare tutto l’intervallo';track.append(this.band);
this.left=button('❮',()=>{});this.right=button('❯',()=>{});
for(const [h,side,label]of[[this.left,'start','Inizio selezione'],[this.right,'end','Fine selezione']]){
h.className='dg-edit-handle';h.setAttribute('role','slider');h.setAttribute('aria-label',label);h.title=label;
h.addEventListener('pointerdown',e=>this.drag(e,side),{signal:this.abort.signal});
h.addEventListener('keydown',event=>{if(!['ArrowLeft','ArrowRight'].includes(event.key))return;event.preventDefault();
const delta=event.key==='ArrowLeft'?-1:1;this.select(side==='start'?stepTime(m,this.config.start,delta):this.config.start,side==='end'?frameTime(m,clamp(frameIndex(m,this.config.end)+delta,1,frameCount(m))):this.config.end,side);});
track.append(h);
}
this.band.addEventListener('pointerdown',e=>this.drag(e,'move'),{signal:this.abort.signal});
track.addEventListener('pointerdown',event=>{if(event.target===track||this.thumbs.contains(event.target))this.seek(this.timeAt(event.clientX));},{signal:this.abort.signal});
this.playhead=el('div','','dg-edit-playhead');track.append(this.playhead);this.root.append(track);
this.scale=el('div','','dg-edit-scale');this.root.append(this.scale);
const times=el('div','','dg-grid');this.root.append(times);
const owner=this;
this.startInput=studioField('Da · secondi','start');this.endInput=studioField('A · secondi','end');
function studioField(label,key){
const wrap=el('label',label,'dg-field'),i=el('input');i.type='text';i.inputMode='decimal';wrap.append(i);times.append(wrap);
i.oninput=()=>{owner.inputsDirty=true;i.setCustomValidity('');owner.studio.editInputDraft={source:owner.config.source,start:owner.startInput.value,end:owner.endInput.value};};
i.onchange=()=>owner.commitInputs();
i.onkeydown=event=>{if(event.key==='Enter'){event.preventDefault();owner.commitInputs();}};
return i;
}
const draft=studio.editInputDraft;if(draft?.source===this.config.source){this.inputsDirty=true;this.startInput.value=draft.start;this.endInput.value=draft.end;}
this.inputMessage=el('small');this.inputMessage.setAttribute('role','status');this.root.append(this.inputMessage);
this.root.append(el('small',`Trascina i bordi o inserisci i secondi, anche con la virgola. Selezione libera fino a ${(m.generation_frames.at(-1)/24).toFixed(2)} s, con precisione di un fotogramma e senza minimo di 4 secondi. H3 calcola i fotogrammi aggiuntivi necessari; nell’export viene sostituito solo l’intervallo scelto.`));
v.addEventListener('timeupdate',()=>{
if(this.playingSelection&&(v.currentTime>=this.config.end||v.currentTime<this.config.start)){if(studio.editLoop!==false){v.currentTime=this.config.start;v.play().catch(()=>{});}else{v.pause();this.playingSelection=false;}}
this.playhead.style.left=clamp((v.currentTime-this.viewStart)/this.span*100,0,100)+'%';this.overview.value=v.currentTime;
},{signal:this.abort.signal});
v.addEventListener('play',()=>{
setAction(this.playButton,'Pausa selezione');
const tick=()=>{if(this.closed||v.paused)return;if(this.playingSelection&&v.currentTime>=this.config.end){if(studio.editLoop!==false){v.currentTime=this.config.start;}else{this.seek(stepTime(m,this.config.end,-1));return;}}this.playRAF=requestAnimationFrame(tick);};
cancelAnimationFrame(this.playRAF);tick();
},{signal:this.abort.signal});
v.addEventListener('pause',()=>{cancelAnimationFrame(this.playRAF);setAction(this.playButton,'Riproduci selezione');},{signal:this.abort.signal});
v.addEventListener('loadedmetadata',()=>this.seek(saved?.time??this.config.start),{once:true,signal:this.abort.signal});
this.paint(true);this.ready=true;
}
zoom(factor){const center=(this.config.start+this.config.end)/2;this.span=clamp(this.span*factor,Math.min(.25,this.meta.duration),this.meta.duration);this.viewStart=clamp(center-this.span/2,0,this.meta.duration-this.span);this.paint(true);}
timeAt(x){const r=this.track.getBoundingClientRect();return clamp(this.viewStart+(x-r.left)/r.width*this.span,0,this.meta.duration);}
seek(t){this.seekTarget=frameTime(this.meta,Math.min(frameCount(this.meta)-1,frameIndex(this.meta,t)));if(this.seekRAF)return;
this.seekRAF=requestAnimationFrame(()=>{this.seekRAF=null;if(this.closed)return;this.video.pause();this.playingSelection=false;this.video.currentTime=this.seekTarget;});}
commitInputs(){
if(!this.ready){this.inputError=this.error||'Attendi la preparazione della timeline.';return false;}
let value;
try{value=parseSelection(this.inputsDirty?this.startInput.value:String(this.config.start),this.inputsDirty?this.endInput.value:String(this.config.end),this.meta);}
catch(e){this.inputError=e.message;this.inputMessage.textContent=e.message;this.inputsDirty=true;return false;}
this.inputError='';this.inputMessage.textContent='';
if(!this.inputsDirty)return true;
Object.assign(this.config,value);this.studio.editInputDraft=null;this.inputsDirty=false;this.studio.save();this.paint(false);this.seek(this.config.start);return true;
}
select(a,b,side){
const value=snapSelection(a,b,this.meta,side);
if(value.end-value.start>this.meta.generation_frames.at(-1)/24+1e-8){this.inputMessage.textContent='La selezione supera la durata disponibile con queste reference.';return;}
Object.assign(this.config,value);this.studio.editInputDraft=null;this.inputsDirty=false;this.inputError='';this.inputMessage.textContent='';this.studio.save();this.paint(false);this.seek(side==='start'?this.config.start:stepTime(this.meta,this.config.end,-1));
}
drag(event,side){event.preventDefault();event.stopPropagation();const target=event.currentTarget;target.setPointerCapture(event.pointerId);
const initial={a:this.config.start,b:this.config.end,t:this.timeAt(event.clientX)};
const move=ev=>{if(side==='move'){const delta=clamp(this.timeAt(ev.clientX)-initial.t,-initial.a,this.meta.duration-initial.b);this.select(initial.a+delta,initial.b+delta,'end');}
else this.select(side==='start'?this.timeAt(ev.clientX):this.config.start,side==='end'?this.timeAt(ev.clientX):this.config.end,side);};
const end=()=>{target.removeEventListener('pointermove',move);target.removeEventListener('pointerup',end);target.removeEventListener('pointercancel',end);};
target.addEventListener('pointermove',move);target.addEventListener('pointerup',end);target.addEventListener('pointercancel',end);
}
paint(thumbnails){
const c=this.config,m=this.meta,pct=t=>clamp((t-this.viewStart)/this.span*100,0,100);
const a=pct(c.start),b=pct(c.end);this.band.style.left=a+'%';this.band.style.width=Math.max(0,b-a)+'%';
this.left.style.left=a+'%';this.right.style.left=b+'%';
this.left.hidden=c.start<this.viewStart||c.start>this.viewStart+this.span;this.right.hidden=c.end<this.viewStart||c.end>this.viewStart+this.span;
for(const [h,t]of[[this.left,c.start],[this.right,c.end]]){h.setAttribute('aria-valuenow',t.toFixed(4));h.setAttribute('aria-valuemin','0');h.setAttribute('aria-valuemax',m.duration);h.setAttribute('aria-valuetext',clock(t));}
if(!this.inputsDirty){this.startInput.value=c.start.toFixed(6);this.endInput.value=c.end.toFixed(6);}
this.info.textContent=`${m.width} × ${m.height} · ${m.fps.toFixed(3)} fps · ${clock(c.start)} → ${clock(c.end)} · selezione ${(c.end-c.start).toFixed(3)} s`;
this.scale.replaceChildren(el('span',clock(this.viewStart)),el('span',clock(this.viewStart+this.span)));
this.overview.value=this.video.currentTime;
if(thumbnails){clearTimeout(this.thumbTimer);this.thumbTimer=setTimeout(()=>{if(this.closed)return;this.thumbs.replaceChildren();for(let i=0;i<8;i++){
const t=Math.min(m.duration-1/m.fps,this.viewStart+(i+.5)*this.span/8),img=el('img');img.alt=clock(t);img.loading='lazy';img.draggable=false;
img.src=url('/dogma/h3/v2/edit/thumbnail',{name:c.source,time:t});this.thumbs.append(img);
}},180);}
}
}