Skip to content

Whiteboard animations with subject-first coloring, ink-aware color clusters, animated real hands, and a local Gradio UI. Developed in Vietnam.

Python

Initial release

letuandat131c689bf7fd75f
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..32be3cc
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,21 @@
+.venv/
+.venv*/
+venv/
+__pycache__/
+*.py[cod]
+.pytest_cache/
+.coverage
+htmlcov/
+outputs/
+logs/
+*.log
+*.part
+assets/v181d/model.safetensors
+.env
+.env.*
+!.env.example
+.idea/
+.vscode/
+Thumbs.db
+.DS_Store
+handdraw-source.zip
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..0e259d4
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,121 @@
+Creative Commons Legal Code
+
+CC0 1.0 Universal
+
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
+ HEREUNDER.
+
+Statement of Purpose
+
+The laws of most jurisdictions throughout the world automatically confer
+exclusive Copyright and Related Rights (defined below) upon the creator
+and subsequent owner(s) (each and all, an "owner") of an original work of
+authorship and/or a database (each, a "Work").
+
+Certain owners wish to permanently relinquish those rights to a Work for
+the purpose of contributing to a commons of creative, cultural and
+scientific works ("Commons") that the public can reliably and without fear
+of later claims of infringement build upon, modify, incorporate in other
+works, reuse and redistribute as freely as possible in any form whatsoever
+and for any purposes, including without limitation commercial purposes.
+These owners may contribute to the Commons to promote the ideal of a free
+culture and the further production of creative, cultural and scientific
+works, or to gain reputation or greater distribution for their Work in
+part through the use and efforts of others.
+
+For these and/or other purposes and motivations, and without any
+expectation of additional consideration or compensation, the person
+associating CC0 with a Work (the "Affirmer"), to the extent that he or she
+is an owner of Copyright and Related Rights in the Work, voluntarily
+elects to apply CC0 to the Work and publicly distribute the Work under its
+terms, with knowledge of his or her Copyright and Related Rights in the
+Work and the meaning and intended legal effect of CC0 on those rights.
+
+1. Copyright and Related Rights. A Work made available under CC0 may be
+protected by copyright and related or neighboring rights ("Copyright and
+Related Rights"). Copyright and Related Rights include, but are not
+limited to, the following:
+
+ i. the right to reproduce, adapt, distribute, perform, display,
+ communicate, and translate a Work;
+ ii. moral rights retained by the original author(s) and/or performer(s);
+iii. publicity and privacy rights pertaining to a person's image or
+ likeness depicted in a Work;
+ iv. rights protecting against unfair competition in regards to a Work,
+ subject to the limitations in paragraph 4(a), below;
+ v. rights protecting the extraction, dissemination, use and reuse of data
+ in a Work;
+ vi. database rights (such as those arising under Directive 96/9/EC of the
+ European Parliament and of the Council of 11 March 1996 on the legal
+ protection of databases, and under any national implementation
+ thereof, including any amended or successor version of such
+ directive); and
+vii. other similar, equivalent or corresponding rights throughout the
+ world based on applicable law or treaty, and any national
+ implementations thereof.
+
+2. Waiver. To the greatest extent permitted by, but not in contravention
+of, applicable law, Affirmer hereby overtly, fully, permanently,
+irrevocably and unconditionally waives, abandons, and surrenders all of
+Affirmer's Copyright and Related Rights and associated claims and causes
+of action, whether now known or unknown (including existing as well as
+future claims and causes of action), in the Work (i) in all territories
+worldwide, (ii) for the maximum duration provided by applicable law or
+treaty (including future time extensions), (iii) in any current or future
+medium and for any number of copies, and (iv) for any purpose whatsoever,
+including without limitation commercial, advertising or promotional
+purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
+member of the public at large and to the detriment of Affirmer's heirs and
+successors, fully intending that such Waiver shall not be subject to
+revocation, rescission, cancellation, termination, or any other legal or
+equitable action to disrupt the quiet enjoyment of the Work by the public
+as contemplated by Affirmer's express Statement of Purpose.
+
+3. Public License Fallback. Should any part of the Waiver for any reason
+be judged legally invalid or ineffective under applicable law, then the
+Waiver shall be preserved to the maximum extent permitted taking into
+account Affirmer's express Statement of Purpose. In addition, to the
+extent the Waiver is so judged Affirmer hereby grants to each affected
+person a royalty-free, non transferable, non sublicensable, non exclusive,
+irrevocable and unconditional license to exercise Affirmer's Copyright and
+Related Rights in the Work (i) in all territories worldwide, (ii) for the
+maximum duration provided by applicable law or treaty (including future
+time extensions), (iii) in any current or future medium and for any number
+of copies, and (iv) for any purpose whatsoever, including without
+limitation commercial, advertising or promotional purposes (the
+"License"). The License shall be deemed effective as of the date CC0 was
+applied by Affirmer to the Work. Should any part of the License for any
+reason be judged legally invalid or ineffective under applicable law, such
+partial invalidity or ineffectiveness shall not invalidate the remainder
+of the License, and in such case Affirmer hereby affirms that he or she
+will not (i) exercise any of his or her remaining Copyright and Related
+Rights in the Work or (ii) assert any associated claims and causes of
+action with respect to the Work, in either case contrary to Affirmer's
+express Statement of Purpose.
+
+4. Limitations and Disclaimers.
+
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
+ surrendered, licensed or otherwise affected by this document.
+ b. Affirmer offers the Work as-is and makes no representations or
+ warranties of any kind concerning the Work, express, implied,
+ statutory or otherwise, including without limitation warranties of
+ title, merchantability, fitness for a particular purpose, non
+ infringement, or the absence of latent or other defects, accuracy, or
+ the present or absence of errors, whether or not discoverable, all to
+ the greatest extent permissible under applicable law.
+ c. Affirmer disclaims responsibility for clearing rights of other persons
+ that may apply to the Work or any use thereof, including without
+ limitation any person's Copyright and Related Rights in the Work.
+ Further, Affirmer disclaims responsibility for obtaining any necessary
+ consents, permissions or other rights required for any use of the
+ Work.
+ d. Affirmer understands and acknowledges that Creative Commons is not a
+ party to this document and has no duty or obligation with respect to
+ this CC0 or use of the Work.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..4d03d38
--- /dev/null
+++ b/README.md
@@ -0,0 +1,226 @@
+# WHITEBOARD ANIMATION VI
+
+<p align="center">
+ <img src="docs/media/demo-02-d.gif" width="640" alt="Whiteboard animation of a character with a bamboo staff">
+</p>
+
+**CHARACTERS FIRST · COLOR GROUPS · INK-AWARE BOUNDARIES · MOVING REAL HANDS**
+
+Turn an illustration into a whiteboard animation: draw the lines, color the
+characters first, then finish the background with moving photographic hands.
+
+Handdraw combines **subject-first coloring, color-grouped strokes and
+ink-aware region boundaries** in a local Gradio app. Upload an RGB/RGBA image,
+choose the timing and style, and export an MP4.
+
+---
+
+## WHAT MAKES IT DIFFERENT
+
+- **CHARACTERS BEFORE SCENERY.** SkyTNT Anime Segmentation (ISNet) separates
+ the foreground. Coloring completes the detected foreground before moving
+ to the background, keeping the characters visible earlier.
+- **COLOR GROUPS SHAPED BY THE LINES.** Similar colors are grouped in Lab
+ space, and ink boundaries help split connected regions. Brush strokes reveal
+ pixels assigned to their color group. The palette controls the painting order;
+ the output retains the source image's colors and shading.
+- **A DELIBERATE PAINTING ORDER.** Within the foreground, finish one color
+ group before switching colors. **Quick** mode then completes each background
+ cluster in left-to-right order, using the original ink-aware region IDs.
+- **SHORTER, SYNCHRONIZED HAND TRAVEL.** Route refinement reduces travel
+ between strokes while preserving the subject/color order. Brush contact and
+ pixel reveal share one timeline, with eased movement and pen lifts between
+ strokes.
+- **MOVING PHOTOGRAPHIC HANDS AND CLEANER LINES.** Separate drawing/coloring
+ hand assets have wrist, finger and shadow motion. Multiscale contrast filtering
+ and small-component cleanup reduce specks in the extracted line map.
+- **LOCAL UI AND GPU RENDERING.** Native Gradio controls expose timing, lines,
+ colors, hands and export options. CUDA supports palette clustering and frame
+ composition; optional NVENC encodes GPU frames directly. CPU/libx264 export
+ and a Python API are also available. Recent image plans are cached for reuse
+ when adjusting timing or hand settings.
+
+## SEE THE TRANSFORMATION
+
+One original, two animation styles: **ORIGINAL → DETAILED → QUICK**.
+Both modes use the same 8-second duration, a maximum frame size of 1280×720,
+and **50 FPS**. The looping GIFs are 640 pixels wide.
+
+### BAMBOO STAFF
+
+<p align="center"><strong>ORIGINAL → DETAILED → QUICK</strong></p>
+<p align="center">
+ <img src="docs/media/source-02.png" width="180" align="middle" alt="Original bamboo staff illustration"> &nbsp;→&nbsp;
+ <img src="docs/media/demo-02-d.gif" width="270" align="middle" alt="Detailed bamboo staff animation at 50 FPS"> &nbsp;→&nbsp;
+ <img src="docs/media/demo-02.gif" width="270" align="middle" alt="Quick bamboo staff animation at 50 FPS">
+</p>
+
+### TWO CHARACTERS
+
+<p align="center"><strong>ORIGINAL → DETAILED → QUICK</strong></p>
+<p align="center">
+ <img src="docs/media/source-01.png" width="180" align="middle" alt="Original two-character illustration"> &nbsp;→&nbsp;
+ <img src="docs/media/demo-01-d.gif" width="270" align="middle" alt="Detailed two-character animation at 50 FPS"> &nbsp;→&nbsp;
+ <img src="docs/media/demo-01.gif" width="270" align="middle" alt="Quick two-character animation at 50 FPS">
+</p>
+
+### WINTER SCENE
+
+<p align="center"><strong>ORIGINAL → DETAILED → QUICK</strong></p>
+<p align="center">
+ <img src="docs/media/source-03.png" width="180" align="middle" alt="Original winter scene illustration"> &nbsp;→&nbsp;
+ <img src="docs/media/demo-03-d.gif" width="270" align="middle" alt="Detailed winter scene animation at 50 FPS"> &nbsp;→&nbsp;
+ <img src="docs/media/demo-03.gif" width="270" align="middle" alt="Quick winter scene animation at 50 FPS">
+</p>
+
+These sample illustrations are not covered by the project's code license.
+Confirm permission to redistribute them before publishing these previews.
+
+## DRAWING MODES
+
+| Mode | Foreground coloring | Background coloring |
+| --- | --- | --- |
+| **Detailed** | Complete color groups using the refined hand route. | Continue with color-group ordering and refined routing. |
+| **Quick** | Keep the same foreground route and timing as Detailed. | Finish each ink-aware cluster, ordered from left to right. |
+
+Both modes use the chosen duration and retain the same source image detail.
+The difference is the background stroke order.
+
+## HOW IT WORKS
+
+1. Fit the image to the output frame, extract and clean its lines, and detect
+ foreground when subject priority is enabled.
+2. Draw the line map with the Grid path.
+3. Color the detected foreground, completing one color group at a time.
+ Colors are initially ordered by their first substantial occurrence near the
+ top of the foreground; routing shortens travel within that order.
+4. Color the background using the selected mode's route.
+5. Hold the finished image and export MP4 with a JSON render report.
+
+Line extraction uses contrast and multiscale filtering; ISNet supplies the
+foreground mask. Ink boundaries are inferred from that line map.
+
+## INSTALL (WINDOWS)
+
+Use Python 3.11 or 3.12, 64-bit. Run these PowerShell commands from the repository:
+
+```powershell
+py -3.11 -m venv .venv
+.\.venv\Scripts\python.exe -m pip install --upgrade pip
+```
+
+For NVIDIA CUDA rendering, install the matching PyTorch wheels first:
+
+```powershell
+.\.venv\Scripts\python.exe -m pip install torch==2.8.0 torchvision==0.23.0 --index-url https://download.pytorch.org/whl/cu128
+.\.venv\Scripts\python.exe -m pip install -r requirements-gpu.txt
+```
+
+The CUDA wheel command follows the [official PyTorch 2.8 installation instructions](https://pytorch.org/get-started/previous-versions/#v280).
+CUDA rendering requires a compatible NVIDIA driver; NVENC also requires an
+NVENC-capable GPU and the optional `PyNvVideoCodec` package.
+
+For CPU-only use:
+
+```powershell
+.\.venv\Scripts\python.exe -m pip install torch==2.8.0 torchvision==0.23.0 --index-url https://download.pytorch.org/whl/cpu
+.\.venv\Scripts\python.exe -m pip install -r requirements.txt
+```
+
+Select **CPU** and **CPU H.264** in the UI. GPU defaults are not silently changed
+when CUDA or NVENC is unavailable. CPU H.264 export requires FFmpeg with libx264
+available on `PATH`.
+
+## SUBJECT SEGMENTATION MODEL
+
+Download the checkpoint explicitly before using subject segmentation:
+
+```powershell
+.\.venv\Scripts\python.exe scripts\download_model.py
+```
+
+The downloader pins revision `493cb60893f47441b26ec4fb9a306bce9e342982` of
+[`skytnt/anime-seg`](https://huggingface.co/skytnt/anime-seg/tree/493cb60893f47441b26ec4fb9a306bce9e342982),
+streams to a temporary file, verifies size and SHA256, then replaces the target
+atomically. A verified existing file is reused. Network operations use a
+30-second socket timeout and a 10-minute transfer deadline; no automatic retries.
+Rendering does not implicitly download models.
+
+Target: `assets/v181d/model.safetensors` (ignored by Git).
+
+- Size: `203982056` bytes
+- SHA256: `3351563ba8b61a01a66bacb79cf36aabce2da62d88b7606a719f573f23fe5d3e`
+
+## RUN LOCALLY
+
+Double-click `start.bat`, or run:
+
+```powershell
+.\start.ps1
+# Another port:
+.\start.ps1 -Port 7861
+```
+
+The launcher uses this repository's `.venv`, starts a hidden `pythonw.exe`
+process, opens the browser, and continues running after the terminal closes.
+It prints the server PID; use `Stop-Process -Id <PID>` to stop that process.
+Logs are appended to `logs/app.log`.
+
+For a foreground server:
+
+```powershell
+.\.venv\Scripts\python.exe app.py --port 7860 --open --log
+# Optional custom log:
+.\.venv\Scripts\python.exe app.py --log logs\session.log
+```
+
+The UI binds only to [127.0.0.1:7860](http://127.0.0.1:7860), with public sharing
+and Gradio analytics disabled. Rendering is serialized; the queue holds at most
+eight pending jobs. MP4 files are stored in `outputs/` and can be downloaded from
+the UI. Remove old outputs manually when no longer needed.
+
+The default drawing/hold split is 70/30. Independently, ink/fill within the
+drawing phase is 45/55. Every `Settings` dataclass field is editable, using its
+native label, default, bounds, step, and choices. Advanced JSON starts with the
+native rig/filter defaults; protected rig and dedicated wrist keys are excluded.
+The backend validates all settings before rendering.
+
+## TESTS
+
+```powershell
+.\.venv\Scripts\python.exe -m pip install -r requirements-dev.txt
+.\.venv\Scripts\python.exe -m pytest tests -q
+```
+
+Tests cover UI/settings synchronization, native planning, validation, verified
+downloads, and a real CPU MP4 encode/decode. They do not download the checkpoint.
+
+## PYTHON USAGE
+
+```python
+import numpy as np
+from PIL import Image
+from handdraw.settings import Settings
+from handdraw.render import render_video
+
+image = np.asarray(Image.open("input.png").convert("RGBA"))
+settings = Settings(mode="e", duration=10, draw_percent=70, ink_percent=45)
+video_path, report = render_video(image, settings)
+```
+
+Changing timing or hand settings reuses
+the in-memory image plan; only two plans are retained. CPU uses libx264;
+NVENC consumes GPU frames directly. Quick mode changes the background stroke order,
+not the global video duration or the ink/fill split.
+
+## LICENSE
+
+Original project code contributed by `letuandat131` is dedicated to the public
+domain under [CC0 1.0 Universal](LICENSE). It may be used, modified and
+redistributed, including commercially, without requiring attribution for that
+original code.
+
+Third-party and upstream-derived code retains its own license and notices; see
+[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and `vendor_runtime/`.
+The CC0 dedication does not cover hand images, demo artwork or model weights.
+Model weights remain a separate upstream artifact, not part of the Git checkout.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
new file mode 100644
index 0000000..50bbff2
--- /dev/null
+++ b/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,44 @@
+# Third-Party Notices
+
+## Anime Segmentation / ISNet
+
+The vendored ISNet source in `vendor_runtime/anime_segmentation/isnet.py` comes
+from [Anime Segmentation](https://github.com/SkyTNT/anime-segmentation).
+It is licensed under Apache License 2.0. The complete upstream license is
+preserved at `vendor_runtime/anime_segmentation/LICENSE`; retain it when
+redistributing this source.
+
+The optional ISNet checkpoint is downloaded separately from
+[`skytnt/anime-seg`](https://huggingface.co/skytnt/anime-seg) at revision
+`493cb60893f47441b26ec4fb9a306bce9e342982`. Its size and SHA256 are recorded in
+the README and downloader. The source-code notice above does not independently
+grant rights to model weights; consult the upstream model repository for their
+applicable terms. The checkpoint is not included in Git.
+
+## Grid / SRT Whiteboard
+
+The Grid implementation in `handdraw/grid_stream.py` derives from the
+MIT-licensed SRT Whiteboard source. Its complete upstream notice, including
+copyright and permission terms, is preserved at
+`vendor_runtime/srt_whiteboard/LICENSE`. Retain that notice in copies or
+substantial portions of the derived implementation.
+
+## Runtime Dependencies
+
+Gradio, PyTorch, torchvision, NumPy, OpenCV, SciPy, scikit-image, safetensors,
+Pillow, pytest, and optional PyNvVideoCodec are separately installed dependencies.
+Each remains subject to its own upstream license and distribution terms.
+FFmpeg, when installed separately for CPU encoding, also retains its own terms,
+which depend on the chosen build and enabled codecs.
+
+## Original Work
+
+Original project code contributed by `letuandat131` is dedicated to the public
+domain under CC0 1.0 Universal; see [LICENSE](LICENSE). This applies only to the
+author's original code, not to third-party or upstream-derived code described
+above, which retains its own terms and required notices.
+
+Hand images, demo artwork and model weights are excluded from the CC0 dedication.
+No redistribution license has been selected for the hand images or demo artwork;
+confirm their applicable rights before redistributing them. Neither the Apache
+nor MIT notices above should be interpreted as licensing the entire project.
diff --git a/app.py b/app.py
new file mode 100644
index 0000000..1f52866
--- /dev/null
+++ b/app.py
@@ -0,0 +1,142 @@
+from __future__ import annotations
+
+import argparse
+from dataclasses import fields
+import json
+import logging
+from pathlib import Path
+import sys
+
+import gradio as gr
+
+from handdraw.settings import INK_DEFAULTS, RIG_SETTINGS, Settings
+
+ROOT = Path(__file__).resolve().parent
+OUTPUT_DIR = ROOT / 'outputs'
+PROTECTED_RIG_KEYS = {'reference_height', 'native_scale', 'wrist_degrees', 'wrist_frequency'}
+LOGGER = logging.getLogger(__name__)
+
+
+def render_image(image, values, progress=None):
+ try:
+ if image is None:
+ raise ValueError('Upload an input image.')
+ settings = Settings(**values).validate()
+ from handdraw.render import render_video
+
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
+ callback = None if progress is None else lambda fraction, description: progress(fraction, desc=description)
+ output, report = render_video(image, settings, output_dir=OUTPUT_DIR, progress=callback)
+ output = Path(output).resolve()
+ if not output.is_relative_to(OUTPUT_DIR.resolve()) or output.suffix.lower() != '.mp4' or not output.is_file():
+ raise ValueError('Renderer returned an invalid output file.')
+ LOGGER.info('Rendered %s', output.name)
+ return str(output), str(output), report
+ except Exception as exc:
+ LOGGER.exception('Render failed')
+ raise gr.Error(str(exc)) from exc
+
+
+def setting_control(item):
+ spec = item.metadata
+ options = dict(label=spec['label'], value=item.default)
+ if spec['choices']:
+ return gr.Radio(choices=spec['choices'], **options) if item.name == 'mode' else gr.Dropdown(choices=spec['choices'], **options)
+ if isinstance(item.default, bool):
+ return gr.Checkbox(**options)
+ if spec['low'] is not None:
+ options.update(minimum=spec['low'], maximum=spec['high'], step=spec['step'])
+ if item.name == 'seed':
+ return gr.Number(precision=0, **options)
+ return gr.Slider(**options)
+ if item.name == 'paper_color':
+ return gr.ColorPicker(**options)
+ if item.name in ('rig_json', 'ink_json'):
+ defaults = ({key: value for key, value in RIG_SETTINGS.items() if key not in PROTECTED_RIG_KEYS}
+ if item.name == 'rig_json' else INK_DEFAULTS)
+ options['value'] = json.dumps(defaults, indent=2)
+ return gr.Textbox(lines=12, max_lines=24, **options)
+ return gr.Textbox(**options)
+
+
+def build_ui():
+ with gr.Blocks(title='Handdraw', analytics_enabled=False) as demo:
+ controls = {}
+ items_by_name = {item.name: item for item in fields(Settings)}
+ gr.Markdown('## Handdraw\nCreate hand-drawn animations from your images.', elem_id='studio-header')
+ with gr.Row(equal_height=True, elem_id='media-row'):
+ with gr.Column(scale=1, min_width=320):
+ image = gr.Image(label='Original image', type='numpy', image_mode='RGBA', sources=['upload'], height=360)
+ with gr.Column(scale=1, min_width=320):
+ video = gr.Video(label='Rendered video', format='mp4', interactive=False, height=360)
+ with gr.Group(elem_id='quick-settings'):
+ with gr.Row(equal_height=False):
+ with gr.Column(scale=2, min_width=300):
+ controls['mode'] = setting_control(items_by_name['mode'])
+ gr.Markdown('Both modes prioritize characters. **Quick** colors background clusters from left to right.', elem_classes='hint')
+ with gr.Column(scale=2, min_width=300):
+ with gr.Row():
+ for name in ('duration', 'fps'):
+ controls[name] = setting_control(items_by_name[name])
+ with gr.Row():
+ for name in ('show_hand', 'subject_first'):
+ controls[name] = setting_control(items_by_name[name])
+ with gr.Row(elem_id='export-row'):
+ submit = gr.Button('Render & export MP4', variant='primary', size='lg', scale=1, min_width=240)
+ download = gr.File(label='Download MP4', interactive=False, type='filepath', scale=1, min_width=240)
+ group_labels = {'Video': 'Frame & timing', 'Advanced': 'Advanced settings (JSON)'}
+ with gr.Row(elem_id='advanced-settings'):
+ for groups in (('Video', 'Lines & colors', 'Coloring path'), ('Hand & pen', 'Video export', 'Advanced')):
+ with gr.Column(scale=1, min_width=320):
+ for group in groups:
+ with gr.Accordion(group_labels.get(group, group), open=False):
+ if group == 'Video export':
+ gr.Markdown('No NVIDIA GPU? Select **CPU** and **CPU H.264**.', elem_classes='hint')
+ items = [item for item in fields(Settings)
+ if item.metadata['group'] == group and item.name not in controls]
+ for first in range(0, len(items), 2):
+ with gr.Row():
+ for item in items[first:first + 2]:
+ controls[item.name] = setting_control(item)
+ with gr.Accordion('Render details', open=False):
+ report = gr.JSON(label='Report')
+
+ def generate(data, progress=gr.Progress()):
+ return render_image(data[image], {name: data[control] for name, control in controls.items()}, progress)
+
+ submit.click(generate, inputs={image, *controls.values()}, outputs=[video, download, report],
+ concurrency_limit=1, api_name='render')
+ demo.setting_controls = controls
+ demo.queue(default_concurrency_limit=1, max_size=8)
+ return demo
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Local Handdraw UI')
+ parser.add_argument('--port', type=int, default=7860)
+ parser.add_argument('--open', action='store_true', dest='open_browser')
+ parser.add_argument('--log', nargs='?', const=str(ROOT / 'logs' / 'app.log'), metavar='PATH')
+ args = parser.parse_args()
+ if not 1 <= args.port <= 65535:
+ parser.error('--port must be 1..65535')
+ if args.log:
+ path = Path(args.log).resolve()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ stream = path.open('a', encoding='utf-8', buffering=1)
+ sys.stdout = sys.stderr = stream
+ logging.basicConfig(level=logging.INFO, stream=stream,
+ format='%(asctime)s %(levelname)s %(name)s: %(message)s')
+ else:
+ logging.basicConfig(level=logging.INFO)
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
+ build_ui().launch(server_name='127.0.0.1', server_port=args.port, share=False,
+ inbrowser=args.open_browser, allowed_paths=[str(OUTPUT_DIR.resolve())],
+ blocked_paths=[str(ROOT / '.venv'), str(ROOT / 'logs'),
+ str(ROOT / 'assets' / 'v181d' / 'model.safetensors')],
+ max_file_size='20mb', footer_links=[],
+ theme=gr.themes.Default(primary_hue='orange', neutral_hue='slate', font=['Segoe UI', 'sans-serif']),
+ css_paths=ROOT / 'assets' / 'studio.css')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/assets/studio.css b/assets/studio.css
new file mode 100644
index 0000000..2e9f5c5
--- /dev/null
+++ b/assets/studio.css
@@ -0,0 +1,12 @@
+.gradio-container { max-width: 1320px !important; margin: auto; }
+#studio-header { padding: 8px 0; }
+#studio-header h2 { letter-spacing: -.02em; }
+#studio-header p, .hint p { color: var(--body-text-color-subdued); }
+#quick-settings { padding: 12px; }
+.hint p { font-size: 13px; line-height: 1.5; }
+#export-row { align-items: stretch; }
+#export-row > button { min-height: 54px; }
+@media (max-width: 760px) {
+ #media-row, #advanced-settings { flex-direction: column; }
+ #media-row > .column, #advanced-settings > .column { min-width: 0 !important; }
+}
diff --git a/assets/v181d/PROVENANCE.md b/assets/v181d/PROVENANCE.md
new file mode 100644
index 0000000..43876dc
--- /dev/null
+++ b/assets/v181d/PROVENANCE.md
@@ -0,0 +1,22 @@
+# SkyTNT anime segmentation
+
+Official source: https://github.com/SkyTNT/anime-segmentation
+Source revision: `55d874013a2811cdf59c365059174c7823acf5b4`
+Source license: Apache-2.0, retained at `vendor_runtime/anime_segmentation/LICENSE`.
+
+Official checkpoint: https://huggingface.co/skytnt/anime-seg
+Checkpoint revision: `493cb60893f47441b26ec4fb9a306bce9e342982`
+File: `model.safetensors`, FP32, Apache-2.0 per the publisher's model card.
+Size: 203982056 bytes. SHA256:
+`3351563ba8b61a01a66bacb79cf36aabce2da62d88b7606a719f573f23fe5d3e`.
+The adapter loads only `net.*` tensors into official `model/isnet.py:ISNetDIS`.
+Training-only encoder tensors are unused. No pickle checkpoint is loaded.
+
+Bundled model path: `assets/v181d/model.safetensors`.
+The reup adapter requires the local checkpoint and never downloads it implicitly.
+
+Inference follows upstream `inference.py:get_mask`: divide RGB by 255,
+preserve aspect ratio with centered zero padding, sigmoid the first ISNet
+prediction, crop padding, resize to source dimensions, then threshold.
+Inference uses FP32 on CUDA when available, otherwise CPU. It preserves all
+semantic foreground components and may include multiple people.
diff --git a/assets/v181d/color-hand-long.png b/assets/v181d/color-hand-long.png
new file mode 100644
index 0000000..5dd7893
Binary files /dev/null and b/assets/v181d/color-hand-long.png differ
diff --git a/assets/v181d/draw-hand-long.png b/assets/v181d/draw-hand-long.png
new file mode 100644
index 0000000..555520d
Binary files /dev/null and b/assets/v181d/draw-hand-long.png differ
diff --git a/docs/media/demo-01-d.gif b/docs/media/demo-01-d.gif
new file mode 100644
index 0000000..4d43cc7
Binary files /dev/null and b/docs/media/demo-01-d.gif differ
diff --git a/docs/media/demo-01.gif b/docs/media/demo-01.gif
new file mode 100644
index 0000000..760bc7a
Binary files /dev/null and b/docs/media/demo-01.gif differ
diff --git a/docs/media/demo-02-d.gif b/docs/media/demo-02-d.gif
new file mode 100644
index 0000000..875a2ff
Binary files /dev/null and b/docs/media/demo-02-d.gif differ
diff --git a/docs/media/demo-02.gif b/docs/media/demo-02.gif
new file mode 100644
index 0000000..ab7c91b
Binary files /dev/null and b/docs/media/demo-02.gif differ
diff --git a/docs/media/demo-03-d.gif b/docs/media/demo-03-d.gif
new file mode 100644
index 0000000..8a88816
Binary files /dev/null and b/docs/media/demo-03-d.gif differ
diff --git a/docs/media/demo-03.gif b/docs/media/demo-03.gif
new file mode 100644
index 0000000..a8d5892
Binary files /dev/null and b/docs/media/demo-03.gif differ
diff --git a/docs/media/source-01.png b/docs/media/source-01.png
new file mode 100644
index 0000000..99431d3
Binary files /dev/null and b/docs/media/source-01.png differ
diff --git a/docs/media/source-02.png b/docs/media/source-02.png
new file mode 100644
index 0000000..f07e530
Binary files /dev/null and b/docs/media/source-02.png differ
diff --git a/docs/media/source-03.png b/docs/media/source-03.png
new file mode 100644
index 0000000..c616bb5
Binary files /dev/null and b/docs/media/source-03.png differ
diff --git a/handdraw/__init__.py b/handdraw/__init__.py
new file mode 100644
index 0000000..11200b2
--- /dev/null
+++ b/handdraw/__init__.py
@@ -0,0 +1 @@
+"""Standalone image-to-hand-drawing renderer."""
diff --git a/handdraw/grid.py b/handdraw/grid.py
new file mode 100644
index 0000000..c9a6f5b
--- /dev/null
+++ b/handdraw/grid.py
@@ -0,0 +1,32 @@
+"""Native V8 grid ink order."""
+import threading
+import cv2
+import numpy as np
+from . import grid_stream
+_KMEANS_LOCK = threading.Lock()
+
+def _grid_ink(image, visible_mask=None, *, ink_map=None, edge=10, block_size=15, threshold_c=10):
+ h, w = image.shape[:2]
+ if ink_map is None:
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
+ threshold = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, block_size, threshold_c)
+ else:
+ if (not isinstance(ink_map, np.ndarray) or ink_map.shape != (h, w)
+ or ink_map.dtype != np.uint8 or np.any((ink_map != 0) & (ink_map != 255))):
+ raise ValueError("ink_map must be a matching uint8 0/255 mask (0 = ink).")
+ threshold = ink_map.copy()
+ if visible_mask is not None:
+ threshold[~visible_mask] = 255
+ ink = threshold == 0
+ padded = cv2.copyMakeBorder(threshold, 0, (-h)%edge, 0, (-w)%edge, cv2.BORDER_CONSTANT, value=255)
+ backend = grid_stream
+ cells = backend.flatten_streams(backend.cluster_ink_streams(backend._active_mask(padded, edge, 10)))
+ structure = np.full((h, w), 255, np.uint8)
+ ink_path = []
+ for index, (row, col) in enumerate(cells):
+ bounds = np.s_[row*edge:min(h,(row+1)*edge), col*edge:min(w,(col+1)*edge)]
+ structure[bounds][ink[bounds]] = round(index/max(1,len(cells)-1)*254)
+ ink_path.append([index/max(1,len(cells)-1), min(w-1,col*edge+edge//2), min(h-1,row*edge+edge//2)])
+ return ink, structure, ink_path
+
+
diff --git a/handdraw/grid_stream.py b/handdraw/grid_stream.py
new file mode 100644
index 0000000..8c30a9b
--- /dev/null
+++ b/handdraw/grid_stream.py
@@ -0,0 +1,467 @@
+"""Native grid routing extracted from srt-whiteboard; see vendor license."""
+from __future__ import annotations
+from typing import Sequence
+import math
+import cv2
+import numpy as np
+
+def _to_grid_blocks(image: np.ndarray, edge: int) -> np.ndarray:
+ """把 HxW(x C)图像切成 (行数, 列数, edge, edge[, C]) 的分块视图。"""
+ image = np.ascontiguousarray(image)
+ h, w = image.shape[:2]
+ if h % edge or w % edge:
+ raise ValueError(f"图像尺寸 {w}x{h} 必须是 {edge} 的整数倍")
+ rows, cols = h // edge, w // edge
+ if image.ndim == 2:
+ return image.reshape(rows, edge, cols, edge).transpose(0, 2, 1, 3)
+ return image.reshape(rows, edge, cols, edge, image.shape[2]).transpose(0, 2, 1, 3, 4)
+
+
+def _active_mask(threshold_map: np.ndarray, edge: int, threshold: int) -> np.ndarray:
+ """哪些网格含墨迹:块内存在灰度低于阈值的像素即为真。"""
+ blocks = _to_grid_blocks(threshold_map, edge)
+ return np.any(blocks < threshold, axis=(2, 3))
+
+
+def _label_components(active: np.ndarray) -> tuple[np.ndarray, int]:
+ """对墨迹格做 8 连通连通域标记,返回 (标签图, 域数)。"""
+ n, labels = cv2.connectedComponents(active.astype(np.uint8), connectivity=8)
+ return labels, n - 1 # 去掉背景标签 0
+
+
+def _component_cells(labels: np.ndarray, label: int) -> list[tuple[int, int]]:
+ coords = np.argwhere(labels == label)
+ return [(int(r), int(c)) for r, c in coords]
+
+
+def _merge_small_components(
+ components: list[list[tuple[int, int]]],
+ merge_threshold: int,
+) -> list[list[tuple[int, int]]]:
+ """
+ 把小连通域(格数 ≤ merge_threshold)合并到空间最近的大连通域。
+ 避免大量 1-2 格的碎片穿插在大块文字之间,导致“画一块字没画完就跳走”。
+ 若没有大连通域可并入,则保留原样(不丢弃任何墨迹)。
+ """
+ if not components:
+ return components
+ big = [c for c in components if len(c) > merge_threshold]
+ small = [c for c in components if len(c) <= merge_threshold]
+ if not small or not big:
+ return components
+
+ # 预算每个大区域的质心
+ centroids = []
+ for cells in big:
+ rs = [c[0] for c in cells]
+ cs = [c[1] for c in cells]
+ centroids.append((sum(rs) / len(rs), sum(cs) / len(cs)))
+
+ # 每个小碎片并入最近的大区域
+ merged = [list(cells) for cells in big] # 拷贝,可追加
+ for cells in small:
+ rs = [c[0] for c in cells]
+ cs = [c[1] for c in cells]
+ cr = sum(rs) / len(rs)
+ cc = sum(cs) / len(cs)
+ best = min(
+ range(len(big)),
+ key=lambda i: (centroids[i][0] - cr) ** 2 + (centroids[i][1] - cc) ** 2,
+ )
+ merged[best].extend(cells)
+ return merged
+
+
+def _bounds(cells: Sequence[tuple[int, int]]) -> tuple[int, int, int, int]:
+ rows = [row for row, _ in cells]
+ cols = [col for _, col in cells]
+ return min(rows), min(cols), max(rows), max(cols)
+
+
+def _split_bridge_connected_component(
+ cells: list[tuple[int, int]],
+ min_side_cells: int = 20,
+) -> list[list[tuple[int, int]]]:
+ """Split a very wide component when it is connected only by a thin bridge.
+
+ A baseline, arrow, or stray outline can join separate objects into one
+ connected component. Drawing that component with one nearest-neighbour
+ walk makes the pen alternate between those objects. Valleys in the
+ vertical ink projection are reliable weak-bridge signals at grid scale.
+ """
+ if len(cells) < min_side_cells * 2:
+ return [cells]
+
+ min_row, min_col, max_row, max_col = _bounds(cells)
+ height = max_row - min_row + 1
+ width = max_col - min_col + 1
+ if width < 16 or height < 10:
+ return [cells]
+
+ counts = {col: 0 for col in range(min_col, max_col + 1)}
+ for _, col in cells:
+ counts[col] += 1
+ valley_limit = max(3, int(np.ceil(height * 0.30)))
+ edge_guard = 4
+ valleys: list[tuple[int, int]] = []
+ start: int | None = None
+ for col in range(min_col, max_col + 2):
+ low = col <= max_col and counts[col] <= valley_limit
+ if low and start is None:
+ start = col
+ elif not low and start is not None:
+ end = col - 1
+ if (
+ end - start + 1 >= 2
+ and start > min_col + edge_guard
+ and end < max_col - edge_guard
+ ):
+ valleys.append((start, end))
+ start = None
+ if not valleys:
+ return [cells]
+
+ # Prefer the broadest empty corridor. It is much less likely to be an
+ # internal detail of a character than a one-column dip.
+ start, end = max(valleys, key=lambda band: (band[1] - band[0], -band[0]))
+ cut = (start + end) // 2
+ left = [cell for cell in cells if cell[1] <= cut]
+ right = [cell for cell in cells if cell[1] > cut]
+ if len(left) < min_side_cells or len(right) < min_side_cells:
+ return [cells]
+ return (
+ _split_bridge_connected_component(left, min_side_cells)
+ + _split_bridge_connected_component(right, min_side_cells)
+ )
+
+
+def _split_bridge_connected_components(
+ components: list[list[tuple[int, int]]],
+) -> list[list[tuple[int, int]]]:
+ return [
+ piece
+ for cells in components
+ for piece in _split_bridge_connected_component(cells)
+ ]
+
+
+def _boxes_touch(
+ first: tuple[int, int, int, int],
+ second: tuple[int, int, int, int],
+ margin: int = 2,
+) -> bool:
+ """Whether two component boxes belong to the same visual region."""
+ a_top, a_left, a_bottom, a_right = first
+ b_top, b_left, b_bottom, b_right = second
+ return not (
+ a_right + margin < b_left
+ or b_right + margin < a_left
+ or a_bottom + margin < b_top
+ or b_bottom + margin < a_top
+ )
+
+
+def _group_adjacent_stroke_groups(
+ groups: list[tuple[str, list[tuple[int, int]]]],
+) -> list[list[tuple[str, list[tuple[int, int]]]]]:
+ """Keep overlapping label parts and outline pieces in one draw region."""
+ regions: list[list[tuple[str, list[tuple[int, int]]]]] = []
+ boxes: list[tuple[int, int, int, int]] = []
+ for group in groups:
+ group_box = _bounds(group[1])
+ touching = [index for index, box in enumerate(boxes) if _boxes_touch(group_box, box)]
+ if not touching:
+ regions.append([group])
+ boxes.append(group_box)
+ continue
+ target = touching[0]
+ regions[target].append(group)
+ top, left, bottom, right = boxes[target]
+ boxes[target] = (
+ min(top, group_box[0]), min(left, group_box[1]),
+ max(bottom, group_box[2]), max(right, group_box[3]),
+ )
+ # Merge any regions newly bridged by the expanded box.
+ for index in reversed(touching[1:]):
+ regions[target].extend(regions.pop(index))
+ other = boxes.pop(index)
+ top, left, bottom, right = boxes[target]
+ boxes[target] = (
+ min(top, other[0]), min(left, other[1]),
+ max(bottom, other[2]), max(right, other[3]),
+ )
+ return regions
+
+
+def classify_stroke_groups(
+ active: np.ndarray,
+) -> list[tuple[str, list[tuple[int, int]]]]:
+ """Classify connected ink regions as a main subject, text, or local contour."""
+ labels, count = _label_components(active)
+ components = [
+ _component_cells(labels, label)
+ for label in range(1, count + 1)
+ ]
+ components = [cells for cells in components if cells]
+ if not components:
+ return []
+
+ # A long ground line may connect a mountain, a character, and a crowd.
+ # Split that weak connection before any region ordering is decided.
+ components = _split_bridge_connected_components(components)
+
+ # 合并小碎片到最近的大区域,避免碎片打断大块文字的连续绘制
+ total_cells = sum(len(c) for c in components)
+ merge_threshold = max(3, int(total_cells * 0.005))
+ components = _merge_small_components(components, merge_threshold)
+
+ subject_index = max(range(len(components)), key=lambda index: len(components[index]))
+ groups: list[tuple[str, list[tuple[int, int]], tuple[int, int, int]]] = []
+ for index, cells in enumerate(components):
+ min_row, min_col, max_row, max_col = _bounds(cells)
+ height = max_row - min_row + 1
+ width = max_col - min_col + 1
+ density = len(cells) / (height * width)
+ if index == subject_index:
+ kind, rank = "subject", 0
+ elif height >= 2 and width / height >= 2.2 and density >= 0.5:
+ kind, rank = "text", 1
+ else:
+ kind, rank = "contour", 2
+ groups.append((kind, cells, (rank, min_row, min_col)))
+
+ groups.sort(key=lambda group: group[2])
+ return [(kind, cells) for kind, cells, _ in groups]
+
+
+def _density_seed(cells: Sequence[tuple[int, int]], radius: int = 2) -> tuple[int, int]:
+ """挑局部邻居最密的格子作为起笔点,模拟“从墨最浓处下笔”。"""
+ cell_set = set(cells)
+ best = cells[0]
+ best_score = -1
+ for (r, c) in cells:
+ score = sum(
+ 1
+ for dr in range(-radius, radius + 1)
+ for dc in range(-radius, radius + 1)
+ if (r + dr, c + dc) in cell_set
+ )
+ if score > best_score:
+ best_score = score
+ best = (r, c)
+ return best
+
+
+def _gradient_walk(cells: Sequence[tuple[int, int]]) -> list[tuple[int, int]]:
+ """
+ 密度梯度引导的贪心游走:从密度最高的种子格出发,每步选择
+ “未访问邻居中局部密度最高、且与来向夹角最小”的格子,
+ 形成“尽量沿着墨迹、少折返”的连续笔迹。
+ 无邻居可达时跳到全局最近的未访问格继续。
+ """
+ if not cells:
+ return []
+
+ cell_set = set(cells)
+ seed = _density_seed(cells)
+ visited: set[tuple[int, int]] = {seed}
+ path: list[tuple[int, int]] = [seed]
+ current = seed
+ prev_dir = (0, 0)
+
+ while len(visited) < len(cells):
+ neighbors = [
+ (r, c)
+ for dr in (-1, 0, 1)
+ for dc in (-1, 0, 1)
+ if (dr or dc)
+ and (r := current[0] + dr, c := current[1] + dc) in cell_set
+ and (r, c) not in visited
+ ]
+ if neighbors:
+ def cost(cell: tuple[int, int]) -> tuple:
+ # 邻居越多越好(负号取最小)、方向变化越小越好、最后按位置稳定排序
+ local = sum(
+ 1
+ for dr in (-1, 0, 1)
+ for dc in (-1, 0, 1)
+ if (cell[0] + dr, cell[1] + dc) in cell_set
+ and (cell[0] + dr, cell[1] + dc) not in visited
+ )
+ step = (cell[0] - current[0], cell[1] - current[1])
+ turn = (step[0] - prev_dir[0]) ** 2 + (step[1] - prev_dir[1]) ** 2
+ return (-local, turn, cell[0], cell[1])
+
+ nxt = min(neighbors, key=cost)
+ else:
+ # 断笔:跳到最近的未访问格
+ unvisited = [cell for cell in cells if cell not in visited]
+ nxt = min(
+ unvisited,
+ key=lambda cell: (
+ (cell[0] - current[0]) ** 2 + (cell[1] - current[1]) ** 2,
+ cell[0],
+ cell[1],
+ ),
+ )
+
+ prev_dir = (nxt[0] - current[0], nxt[1] - current[1])
+ path.append(nxt)
+ visited.add(nxt)
+ current = nxt
+
+ return path
+
+
+def _nearest_neighbor_order(
+ cells: Sequence[tuple[int, int]], seed: tuple[int, int]
+) -> list[tuple[int, int]]:
+ """从 seed 出发,每步走最近的未访问格,形成连续笔迹。"""
+ if not cells:
+ return []
+ remaining = list(cells)
+ ordered: list[tuple[int, int]] = []
+ current = seed if seed in remaining else remaining[0]
+ while remaining:
+ ordered.append(current)
+ remaining.remove(current)
+ if not remaining:
+ break
+ current = min(
+ remaining,
+ key=lambda cell: (cell[0] - ordered[-1][0]) ** 2
+ + (cell[1] - ordered[-1][1]) ** 2,
+ )
+ return ordered
+
+
+def _text_scan_order(
+ cells: Sequence[tuple[int, int]], segment_cols: int = 4
+) -> list[tuple[int, int]]:
+ """
+ 文字区域的专用画法:横向按段扫描,模拟写字。
+ 把格子按列切成若干段(每段 segment_cols 列宽),段间按列从左到右;
+ 段内用最近邻沿墨迹连续走(而非栅栏式逐行扫),避免“画过一块没画满、
+ 跳到下一段又从顶部开始”的回头补笔感。
+ """
+ if not cells:
+ return []
+ if segment_cols < 1:
+ segment_cols = 1
+ left_col = min(col for _, col in cells)
+ # 按“起始列 // segment_cols”分桶,桶号小(靠左)的先画
+ buckets: dict[int, list[tuple[int, int]]] = {}
+ for cell in cells:
+ bucket_key = (cell[1] - left_col) // segment_cols
+ buckets.setdefault(bucket_key, []).append(cell)
+
+ ordered: list[tuple[int, int]] = []
+ prev_tail: tuple[int, int] | None = None
+ for key in sorted(buckets):
+ seg_cells = buckets[key]
+ # 段的起点:尽量靠近上一段出口,减少段间跳笔
+ if prev_tail is not None:
+ seed = min(
+ seg_cells,
+ key=lambda cell: (cell[0] - prev_tail[0]) ** 2
+ + (cell[1] - prev_tail[1]) ** 2,
+ )
+ else:
+ seed = min(seg_cells, key=lambda cell: (cell[0], cell[1]))
+ seg_order = _nearest_neighbor_order(seg_cells, seed)
+ ordered.extend(seg_order)
+ prev_tail = seg_order[-1]
+ return ordered
+
+
+def _order_stream_by_kind(
+ kind: str, cells: list[tuple[int, int]]
+) -> list[tuple[int, int]]:
+ """按区域类型选画法:文字横向按段扫,主体/轮廓走密度游走。"""
+ if kind == "text":
+ return _text_scan_order(cells)
+ return _gradient_walk(cells)
+
+
+def _chain_region_paths(
+ groups: list[tuple[str, list[tuple[int, int]]]],
+) -> list[tuple[int, int]]:
+ """Finish every component in one visual region before leaving it."""
+ paths = [_order_stream_by_kind(kind, cells) for kind, cells in groups]
+ remaining = [path for path in paths if path]
+ ordered: list[tuple[int, int]] = []
+ tail: tuple[int, int] | None = None
+ while remaining:
+ if tail is None:
+ pick_index = 0 # groups retain subject/text/contour priority.
+ else:
+ pick_index = min(
+ range(len(remaining)),
+ key=lambda index: min(
+ (remaining[index][0][0] - tail[0]) ** 2
+ + (remaining[index][0][1] - tail[1]) ** 2,
+ (remaining[index][-1][0] - tail[0]) ** 2
+ + (remaining[index][-1][1] - tail[1]) ** 2,
+ ),
+ )
+ path = remaining.pop(pick_index)
+ if tail is not None and len(path) > 1:
+ head_distance = (path[0][0] - tail[0]) ** 2 + (path[0][1] - tail[1]) ** 2
+ end_distance = (path[-1][0] - tail[0]) ** 2 + (path[-1][1] - tail[1]) ** 2
+ if end_distance < head_distance:
+ path.reverse()
+ ordered.extend(path)
+ tail = path[-1]
+ return ordered
+
+
+def cluster_ink_streams(active: np.ndarray) -> list[list[tuple[int, int]]]:
+ """
+ 把墨迹格按语义聚成若干条墨流:主体(subject) → 文字(text) → 局部轮廓(contour),
+ 每条内部按类型选画法(文字按段扫、其余密度游走);
+ 墨流之间按“出口到入口最近邻”动态串联,必要时整条反向,减少跳笔。
+ 返回的是已串联排序好的多条笔迹流。
+ """
+ if not active.any():
+ return []
+ groups = classify_stroke_groups(active)
+ # A stream is now a complete visual region, not merely one connected
+ # component. Thus a label's border, its characters, and its arrow cannot
+ # be interrupted by a different object that happens to be closer.
+ regions = _group_adjacent_stroke_groups(groups)
+ streams = [_chain_region_paths(region) for region in regions]
+ streams = [s for s in streams if s]
+ if not streams:
+ return []
+
+ # 串联:主体(第一支)开局,之后每次挑入口离当前出口最近的墨流,
+ # 并视情况把该墨流整体反向,使其起点更靠近上一支的出口。
+ ordered: list[list[tuple[int, int]]] = []
+ remaining = list(streams)
+ tail: tuple[int, int] | None = None
+ while remaining:
+ if tail is None:
+ pick_idx = 0 # classify 已把主体排在最前
+ else:
+ def dist_to_tail(stream: list[tuple[int, int]]) -> int:
+ head = stream[0]
+ return (head[0] - tail[0]) ** 2 + (head[1] - tail[1]) ** 2
+ pick_idx = min(range(len(remaining)), key=lambda i: dist_to_tail(remaining[i]))
+ pick = remaining.pop(pick_idx)
+ # 视情况反向:若尾离 pick 的终点比离起点更近,则反向
+ if tail is not None and len(pick) > 1:
+ head = pick[0]
+ end = pick[-1]
+ d_end = (end[0] - tail[0]) ** 2 + (end[1] - tail[1]) ** 2
+ d_head = (head[0] - tail[0]) ** 2 + (head[1] - tail[1]) ** 2
+ if d_end < d_head:
+ pick = pick[::-1]
+ ordered.append(pick)
+ tail = pick[-1]
+ return ordered
+
+
+def flatten_streams(streams: list[list[tuple[int, int]]]) -> list[tuple[int, int]]:
+ return [cell for stream in streams for cell in stream]
+
+
diff --git a/handdraw/nvenc.py b/handdraw/nvenc.py
new file mode 100644
index 0000000..4502712
--- /dev/null
+++ b/handdraw/nvenc.py
@@ -0,0 +1,231 @@
+"""Native zero-copy Torch/CUDA to NVIDIA H.264 muxer."""
+from __future__ import annotations
+from collections import deque
+import gc
+import os
+import pathlib
+import importlib.util
+from pathlib import Path
+import torch
+VIDEO_TIMEBASE = 90000
+
+class _CudaArray:
+ def __init__(self, tensor: torch.Tensor):
+ self.__cuda_array_interface__ = {
+ "shape": tuple(tensor.shape),
+ "strides": tuple(tensor.stride(i) * tensor.element_size() for i in range(tensor.ndim)),
+ "data": (tensor.data_ptr(), False),
+ "typestr": "|u1",
+ "version": 3,
+ }
+
+
+class _CudaFrame:
+ """Keeps a Torch allocation alive while PyNvVideoCodec reads its CUDA pointer."""
+
+ def __init__(self, tensor: torch.Tensor):
+ self.tensor = tensor
+ self.interface = _CudaArray(tensor)
+
+ def cuda(self):
+ return self.interface
+
+
+def _pack_nvenc_abgr(rgb: torch.Tensor) -> torch.Tensor:
+ """Pack RGB frames into PyNvVideoCodec's ABGR surface byte layout."""
+ rgba = torch.empty((*rgb.shape[:3], 4), dtype=torch.uint8, device=rgb.device)
+ rgba[..., :3] = rgb
+ rgba[..., 3].fill_(255)
+ return rgba
+
+
+def _prepare_nvenc_surface(rgb: torch.Tensor) -> torch.Tensor:
+ if rgb.shape[-1] == 4:
+ return rgb
+ rgba = _pack_nvenc_abgr(rgb)
+ if rgb.is_cuda:
+ # PyNvVideoCodec consumes the raw CUDA pointer outside Torch. Ensure
+ # the asynchronous RGB -> RGBA pack is complete before NVENC reads it.
+ torch.cuda.current_stream(rgb.device).synchronize()
+ return rgba
+
+
+def _load_pynv():
+ torch_lib = pathlib.Path(torch.__file__).resolve().parent / "lib"
+ spec = importlib.util.find_spec('PyNvVideoCodec')
+ if spec is None:
+ raise RuntimeError('Install requirements-gpu.txt to use NVENC.')
+ package = pathlib.Path(spec.origin).parent
+ handles = []
+ if os.name == "nt":
+ for directory in (torch_lib, package):
+ if directory.is_dir():
+ handles.append(os.add_dll_directory(str(directory)))
+ try:
+ import PyNvVideoCodec as nvc
+ except Exception as exc:
+ raise RuntimeError(f"Could not load NVIDIA PyNvVideoCodec: {exc}") from exc
+ # The handles must stay alive while the extension is loaded.
+ nvc._v3_dll_handles = handles
+ return nvc
+
+
+class _NvencMuxer:
+ def __init__(self, output: Path, settings):
+ self.nvc = _load_pynv()
+ self.output = output
+ config = {
+ "gpu_id": 0,
+ "codec": "h264",
+ "preset": str(settings.encoder_preset).upper(),
+ "tuning_info": "high_quality",
+ "fps": str(settings.fps),
+ "gop": str(settings.fps * 2),
+ "bf": "0",
+ "rc": "vbr",
+ }
+ quality_rate_control = settings.encoder_rate_control == "vbr_cq"
+ if quality_rate_control:
+ config["cq"] = str(settings.encoder_cq)
+ else:
+ config["bitrate"] = str(_parse_bitrate(settings.video_bitrate))
+ # PyNvVideoCodec uses maxbitrate (no underscore).
+ config["maxbitrate"] = str(_parse_bitrate(settings.video_maxrate))
+ self.encoder = self.nvc.CreateEncoder(
+ settings.width, settings.height, "ABGR", False, **config
+ )
+ effective = self.encoder.GetEncodeReconfigureParams()
+ requested_bitrate = _parse_bitrate(settings.video_bitrate)
+ requested_max_bitrate = _parse_bitrate(settings.video_maxrate)
+ self.effective_rate_control = {
+ "average_bitrate": int(effective.averageBitrate),
+ "max_bitrate": int(effective.maxBitRate),
+ "mode": str(effective.rateControlMode),
+ "target_quality": int(effective.targetQuality),
+ }
+ if quality_rate_control:
+ if (
+ "VBR" not in self.effective_rate_control["mode"].upper()
+ or self.effective_rate_control["target_quality"] != settings.encoder_cq
+ ):
+ raise RuntimeError(
+ "NVENC did not apply the requested quality mode: "
+ f"requested CQ {settings.encoder_cq}, got "
+ f"{self.effective_rate_control['mode']} / "
+ f"CQ {self.effective_rate_control['target_quality']}."
+ )
+ else:
+ if self.effective_rate_control["average_bitrate"] <= 0:
+ raise RuntimeError("NVENC did not accept the target bitrate; stopped to prevent an oversized output file.")
+ average_error = abs(
+ self.effective_rate_control["average_bitrate"] - requested_bitrate
+ ) / max(1, requested_bitrate)
+ max_error = abs(
+ self.effective_rate_control["max_bitrate"] - requested_max_bitrate
+ ) / max(1, requested_max_bitrate)
+ if average_error > 0.1 or max_error > 0.1:
+ raise RuntimeError(
+ "NVENC did not apply the configured bitrate: "
+ f"requested {requested_bitrate}/{requested_max_bitrate}, got "
+ f"{self.effective_rate_control['average_bitrate']}/"
+ f"{self.effective_rate_control['max_bitrate']}."
+ )
+ self.muxer = self.nvc.FFmpegMuxer(
+ file_path=str(output),
+ media_format=self.nvc.GetMediaFormat(str(output)),
+ codec="h264",
+ width=settings.width,
+ height=settings.height,
+ fps_num=settings.fps,
+ fps_den=1,
+ timebase_num=1,
+ timebase_den=VIDEO_TIMEBASE,
+ extradata=self.encoder.GetSequenceParams(),
+ )
+ self.uniform_pts = not settings.hybrid_vfr
+ self.pts_increment = max(1, VIDEO_TIMEBASE // settings.fps)
+ if self.uniform_pts:
+ self.muxer.SetUniformPtsIncrement(self.pts_increment)
+ self.frame_index = 0
+ self.last_pts = -1
+ self._inflight: deque[_CudaFrame] = deque(maxlen=8)
+
+ def write(self, rgb: torch.Tensor) -> None:
+ self.write_batch(rgb.unsqueeze(0))
+
+ def _record_vfr_timestamp(self, pts: int) -> None:
+ if self.uniform_pts:
+ return
+ source_packet = self.nvc.PacketData()
+ source_packet.pts = pts
+ source_packet.dts = pts
+ source_packet.duration = self.pts_increment
+ source_packet.is_video = 1
+ source_packet.discardable = 0
+ source_packet.stream_index = 0
+ self.muxer.RecordSourceVideoPacket(source_packet)
+
+ def write_batch(self, rgb: torch.Tensor, pts_ticks: list[int] | None = None) -> int:
+ if rgb.dtype != torch.uint8 or not rgb.is_cuda:
+ raise TypeError("NVENC requires a CUDA uint8 batch.")
+ if rgb.ndim != 4 or rgb.shape[-1] not in {3, 4}:
+ raise TypeError(f"NVENC requires BHWC RGB/RGBA, got {tuple(rgb.shape)}")
+ if pts_ticks is not None and len(pts_ticks) != int(rgb.shape[0]):
+ raise ValueError("PTS count does not match the NVENC frame count.")
+ # PyNvVideoCodec names the surface ABGR by its packed 32-bit layout,
+ # while the CUDA bytes it consumes are R,G,B,A. Swapping R/B here
+ # turns every warm frame blue after encode (caught by the RGB parity
+ # gate), so keep the compositor's RGB byte order and only append alpha.
+ rgba = _prepare_nvenc_surface(rgb)
+ for index, surface in enumerate(rgba):
+ params = self.nvc.NV_ENC_PIC_PARAMS()
+ pts = (
+ int(pts_ticks[index])
+ if pts_ticks is not None
+ else self.frame_index * (VIDEO_TIMEBASE // 60 if not self.uniform_pts else 1)
+ )
+ if pts <= self.last_pts:
+ raise RuntimeError(f"NVENC PTS is not increasing: {pts} <= {self.last_pts}")
+ self._record_vfr_timestamp(pts)
+ params.inputTimeStamp = pts
+ frame = _CudaFrame(surface)
+ self._inflight.append(frame)
+ for packet in self.encoder.Encode(frame, params):
+ self.muxer.MuxVideoPacket(
+ bytes(packet["data"]), packet["picture_type"], packet["timestamp"]
+ )
+ self.frame_index += 1
+ self.last_pts = pts
+ return int(rgb.shape[0])
+
+ def close(self) -> None:
+ for packet in self.encoder.EndEncode():
+ self.muxer.MuxVideoPacket(
+ bytes(packet["data"]), packet["picture_type"], packet["timestamp"]
+ )
+ self.muxer.Finalize()
+ # The Windows FFmpeg muxer releases its file handle in the destructor.
+ self.encoder = None
+ self.muxer = None
+ self._inflight.clear()
+ gc.collect()
+
+ def abort(self) -> None:
+ self.encoder = None
+ self.muxer = None
+ self._inflight.clear()
+ gc.collect()
+
+
+def _parse_bitrate(value: str | int) -> int:
+ if isinstance(value, int):
+ return value
+ text = str(value).strip().lower()
+ scale = 1
+ if text.endswith("k"):
+ scale, text = 1000, text[:-1]
+ elif text.endswith("m"):
+ scale, text = 1_000_000, text[:-1]
+ return int(float(text) * scale)
+
+
diff --git a/handdraw/pixels.py b/handdraw/pixels.py
new file mode 100644
index 0000000..4d1d9ed
--- /dev/null
+++ b/handdraw/pixels.py
@@ -0,0 +1,29 @@
+"""Native Torch ink/contact-color compositor."""
+import torch
+
+def draw_batch(state, indices, draw_frames, background=(255, 255, 255)):
+ image = state["image_compact"]
+ t = torch.as_tensor(indices, device=image.device, dtype=torch.float32) / max(1, draw_frames - 1)
+ active = t >= 0
+ if draw_frames <= 1:
+ t.fill_(1)
+ ink_end = float(state["ink_end"])
+ scale = int(state["time_scale"])
+ ink_progress = (t / max(ink_end, 1e-6)).clamp(0, 1)
+ ink_limit = (ink_progress * scale).round().to(torch.int32)
+ ink = state["structure"][None] <= ink_limit[:, None, None]
+ ink &= state["structure"][None] != 255
+ ink &= active[:, None, None]
+ paint_progress = ((t - ink_end) / max(1e-6, 1 - ink_end)).clamp(0, 1)
+ paint_progress.masked_fill_(t >= 1, 1)
+ paint_limit = (paint_progress * scale).round().to(torch.int32)
+ paint = state["residual_time_compact"][None] <= paint_limit[:, None, None]
+ if "color_contact_time" in state:
+ paint = state["color_contact_time"][None] <= paint_progress[:, None, None]
+ paint &= (t >= ink_end)[:, None, None]
+ paint &= active[:, None, None]
+ paper = torch.tensor(background, device=image.device, dtype=torch.uint8).view(1, 3, 1, 1)
+ frames = torch.where(ink[:, None], 0, paper)
+ return torch.where(paint[:, None], image[None], frames)
+
+
diff --git a/handdraw/render.py b/handdraw/render.py
new file mode 100644
index 0000000..77778ca
--- /dev/null
+++ b/handdraw/render.py
@@ -0,0 +1,252 @@
+from __future__ import annotations
+
+from collections import OrderedDict
+from dataclasses import asdict, fields, replace
+import hashlib
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import threading
+import time
+from types import SimpleNamespace
+import uuid
+
+import cv2
+import numpy as np
+from PIL import Image, ImageColor
+import torch
+
+from .pixels import draw_batch
+from .settings import Settings, ink_options, rig_settings
+from .v181d_hand import MovingHand, scheduled_hands
+from .v181d_plan import build_v181d_plan
+
+
+ROOT = Path(__file__).resolve().parents[1]
+OUTPUTS = ROOT / 'outputs'
+_PLAN_CACHE = OrderedDict()
+_RENDER_LOCK = threading.Lock()
+PLAN_FIELDS = ('mode', 'device', 'seed', 'subject_first', 'subject_resolution', 'subject_threshold',
+ 'clean_ink', 'grid_edge', 'adaptive_block', 'adaptive_c', 'clahe_clip', 'palette_colors',
+ 'min_region_area', 'brush_ratio', 'brush_min', 'brush_max', 'stroke_angle',
+ 'travel_speed_ratio', 'path_samples', 'ink_json')
+
+
+def fit_image(image, settings):
+ if (not isinstance(image, np.ndarray) or image.dtype != np.uint8 or image.ndim != 3
+ or image.shape[2] not in (3, 4) or min(image.shape[:2]) < 1 or image.shape[0] * image.shape[1] > 32000000):
+ raise ValueError('A nonempty RGB/RGBA uint8 image of at most 32 megapixels is required')
+ paper = ImageColor.getrgb(settings.paper_color)
+ rgb = image[:, :, :3].copy()
+ if image.shape[2] == 4:
+ alpha = image[:, :, 3:4].astype(np.float32) / 255
+ rgb = np.rint(rgb * alpha + np.asarray(paper) * (1 - alpha)).astype(np.uint8)
+ source = Image.fromarray(rgb)
+ width, height = int(settings.width) // 2 * 2, int(settings.height) // 2 * 2
+ if settings.fit == 'cover':
+ scale = max(width / source.width, height / source.height)
+ size = (max(width, round(source.width * scale)), max(height, round(source.height * scale)))
+ source = source.resize(size, Image.Resampling.LANCZOS)
+ left, top = (source.width - width) // 2, (source.height - height) // 2
+ source = source.crop((left, top, left + width, top + height))
+ else:
+ scale = min(width / source.width, height / source.height)
+ size = (max(2, round(source.width * scale) // 2 * 2), max(2, round(source.height * scale) // 2 * 2))
+ source = source.resize(size, Image.Resampling.LANCZOS)
+ if settings.fit == 'contain':
+ canvas = Image.new('RGB', (width, height), paper)
+ canvas.paste(source, ((width - source.width) // 2, (height - source.height) // 2))
+ source = canvas
+ rgb = np.asarray(source).copy()
+ if settings.saturation != 1:
+ hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
+ hsv[:, :, 1] = np.rint(np.clip(hsv[:, :, 1].astype(float) * settings.saturation, 0, 255)).astype(np.uint8)
+ rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
+ return rgb
+
+
+def build_plan(rgb, settings, *, subject_mask=None):
+ advanced = ink_options(settings)
+ barrier = advanced.pop('barrier_size')
+ if subject_mask is None:
+ if settings.subject_first:
+ from .subject import detect_subject_mask, release_subject_model
+ try:
+ subject_mask, _ = detect_subject_mask(rgb, int(settings.subject_resolution),
+ settings.subject_threshold, device=settings.device)
+ finally:
+ release_subject_model()
+ else:
+ subject_mask = np.zeros(rgb.shape[:2], bool)
+ plan = build_v181d_plan(rgb, int(settings.seed), subject_mask=subject_mask,
+ cluster_backend=settings.device, background_clusters=settings.mode == 'e',
+ grid_edge=int(settings.grid_edge), clean_ink=settings.clean_ink,
+ ink_options=dict(block_size=int(settings.adaptive_block), threshold_c=settings.adaptive_c,
+ clahe_clip=settings.clahe_clip, **advanced),
+ palette_colors=int(settings.palette_colors), min_region_area=int(settings.min_region_area),
+ barrier_size=barrier, path_samples=int(settings.path_samples),
+ fill_options=dict(brush_min=settings.brush_min, brush_max=settings.brush_max,
+ brush_ratio=settings.brush_ratio, stroke_angle=settings.stroke_angle,
+ travel_speed_ratio=settings.travel_speed_ratio))
+ return plan
+
+
+def _cached_plan(rgb, settings):
+ key = hashlib.sha256(rgb.tobytes() + json.dumps(
+ {'shape': rgb.shape, **{name: getattr(settings, name) for name in PLAN_FIELDS}}, sort_keys=True).encode()).hexdigest()
+ cached = _PLAN_CACHE.get(key)
+ if cached is not None:
+ _PLAN_CACHE.move_to_end(key)
+ return cached, True
+ plan = build_plan(rgb, settings)
+ _PLAN_CACHE[key] = plan
+ while len(_PLAN_CACHE) > 2:
+ _PLAN_CACHE.popitem(last=False)
+ return plan, False
+
+
+def _device_state(rgb, plan, settings):
+ end = float(plan['ink_end'])
+ path = plan['pen_path'].copy()
+ if 0 < end < 1 and settings.ink_percent != 45:
+ target = settings.ink_percent / 100
+ times = path[:, 0].copy()
+ path[:, 0] = np.where(times < end, times * target / end,
+ target + (times - end) * (1 - target) / (1 - end))
+ end = target
+ device = torch.device(settings.device)
+ return {'image_compact': torch.from_numpy(rgb.transpose(2, 0, 1).copy()).to(device),
+ 'structure': torch.from_numpy(plan['structure_time']).to(device),
+ 'residual_time_compact': torch.from_numpy(plan['color_reveal_time']).to(device),
+ 'color_contact_time': torch.from_numpy(plan['color_contact_time']).to(device),
+ 'time_scale': 254, 'ink_end': end, 'pen_path': path, 'pen_lift': plan['pen_lift']}
+
+
+def ffmpeg_binary():
+ configured = os.environ.get('FFMPEG_BINARY')
+ if configured:
+ candidate = Path(configured)
+ if not candidate.is_file():
+ raise ValueError('FFMPEG_BINARY does not point to a file')
+ return str(candidate)
+ executable = shutil.which('ffmpeg')
+ if executable:
+ return executable
+ conventional = Path('C:/ffmpeg/bin/ffmpeg.exe')
+ if os.name == 'nt' and conventional.is_file():
+ return str(conventional)
+ raise RuntimeError('FFmpeg is required for the CPU encoder. Add it to PATH or set FFMPEG_BINARY.')
+
+
+class CpuEncoder:
+ def __init__(self, path, width, height, settings):
+ self.error_log = tempfile.TemporaryFile()
+ command = [ffmpeg_binary(), '-hide_banner', '-loglevel', 'error', '-y', '-f', 'rawvideo',
+ '-pixel_format', 'rgb24', '-video_size', f'{width}x{height}', '-framerate', str(settings.fps),
+ '-i', 'pipe:0', '-an', '-c:v', 'libx264', '-preset', settings.cpu_preset,
+ '-crf', str(settings.quality), '-pix_fmt', 'yuv420p', '-movflags', '+faststart', str(path)]
+ self.process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
+ stderr=self.error_log, creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
+
+ def write_batch(self, frames):
+ try:
+ self.process.stdin.write(frames.detach().cpu().contiguous().numpy().tobytes())
+ except BrokenPipeError as exc:
+ self.error_log.seek(0)
+ raise RuntimeError(self.error_log.read().decode('utf-8', errors='replace')[-3000:]) from exc
+
+ def close(self):
+ self.process.stdin.close()
+ result = self.process.wait(timeout=120)
+ self.error_log.seek(0)
+ detail = self.error_log.read().decode('utf-8', errors='replace')
+ self.error_log.close()
+ if result != 0:
+ raise RuntimeError(f'FFmpeg failed: {detail[-3000:]}')
+
+ def abort(self):
+ if self.process.poll() is None:
+ self.process.kill()
+ self.process.wait(timeout=10)
+ if not self.process.stdin.closed:
+ self.process.stdin.close()
+ self.error_log.close()
+
+
+def render_video(image, settings=None, *, output_dir=None, progress=None):
+ settings = (settings or Settings()).validate()
+ integers = {item.name: int(getattr(settings, item.name)) for item in fields(settings)
+ if isinstance(item.default, int) and not isinstance(item.default, bool)}
+ settings = replace(settings, **integers)
+ if settings.device == 'cuda' and not torch.cuda.is_available():
+ raise RuntimeError('CUDA unavailable. Select CPU and the CPU encoder explicitly.')
+ notify = progress or (lambda fraction, description: None)
+ with _RENDER_LOCK, torch.inference_mode():
+ started = time.perf_counter()
+ notify(0, 'Preparing image')
+ rgb = fit_image(image, settings)
+ height, width = rgb.shape[:2]
+ notify(.05, 'Detecting characters and planning strokes')
+ plan, cache_hit = _cached_plan(rgb, settings)
+ state = _device_state(rgb, plan, settings)
+ frames_count = max(1, round(settings.duration * settings.fps))
+ draw_frames = max(1, min(frames_count, round(frames_count * settings.draw_percent / 100)))
+ block = SimpleNamespace(draw_frames=draw_frames, start_frame=0)
+ hands, counts = {}, {'draw': 0, 'color': 0}
+ rig = rig_settings(settings)
+ directory = Path(output_dir or OUTPUTS).resolve()
+ directory.mkdir(parents=True, exist_ok=True)
+ name = f'{settings.mode.upper()}_{settings.draw_percent:g}-{100-settings.draw_percent:g}_{settings.ink_percent:g}-{100-settings.ink_percent:g}_{uuid.uuid4().hex[:10]}'
+ output = directory / f'{name}.mp4'
+ partial = directory / f'.{name}.part.mp4'
+ encoder = None
+ try:
+ notify(.15, 'Initializing encoder')
+ if settings.encoder == 'nvenc':
+ from .nvenc import _NvencMuxer
+ options = SimpleNamespace(width=width, height=height, fps=settings.fps,
+ encoder_preset=settings.encoder_preset, encoder_rate_control='vbr_cq',
+ encoder_cq=settings.quality, video_bitrate='2200k', video_maxrate='4000k', hybrid_vfr=False)
+ encoder = _NvencMuxer(partial, options)
+ else:
+ encoder = CpuEncoder(partial, width, height, settings)
+ for first in range(0, frames_count, settings.render_batch_size):
+ indices = list(range(first, min(frames_count, first + settings.render_batch_size)))
+ frames = draw_batch(state, indices, draw_frames, ImageColor.getrgb(settings.paper_color))
+ frames = frames.permute(0, 2, 3, 1).contiguous()
+ if settings.show_hand:
+ events = scheduled_hands(state, block, indices, {'x': 0, 'y': 0}, 0, settings.fps)
+ for slot, mode, point, seconds, lift in events:
+ if mode not in hands:
+ hands[mode] = MovingHand(mode, width, height, settings.device, rig)
+ hands[mode].stamp(frames[slot], point, seconds, (0, 0, width, height), lift)
+ counts[mode] += 1
+ encoder.write_batch(frames)
+ notify(.15 + .8 * (indices[-1] + 1) / frames_count, 'Exporting video')
+ encoder.close()
+ encoder = None
+ os.replace(partial, output)
+ ink = float(state['ink_end']) * draw_frames / settings.fps
+ report = {'settings': asdict(settings), 'device': settings.device, 'encoder': settings.encoder,
+ 'width': width, 'height': height, 'fps': settings.fps, 'frames': frames_count,
+ 'duration': frames_count / settings.fps, 'phase_seconds': {
+ 'draw': ink, 'color': draw_frames / settings.fps - ink,
+ 'hold': (frames_count - draw_frames) / settings.fps},
+ 'hand_frames': counts, 'plan_cache_hit': cache_hit,
+ 'wall_seconds': time.perf_counter() - started, 'bytes': output.stat().st_size,
+ 'plan': plan['metadata']}
+ output.with_suffix('.json').write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding='utf-8')
+ notify(1, 'Done')
+ return output, report
+ except BaseException:
+ if encoder is not None:
+ encoder.abort()
+ partial.unlink(missing_ok=True)
+ raise
+ finally:
+ hands.clear()
+ if settings.device == 'cuda':
+ torch.cuda.empty_cache()
diff --git a/handdraw/settings.py b/handdraw/settings.py
new file mode 100644
index 0000000..df9ef89
--- /dev/null
+++ b/handdraw/settings.py
@@ -0,0 +1,193 @@
+from __future__ import annotations
+
+from copy import deepcopy
+from dataclasses import dataclass, field, fields
+import json
+import math
+
+from PIL import ImageColor
+
+from .v181d_hand import RIG_SETTINGS
+
+
+def control(default, label, group, low=None, high=None, step=1, choices=None):
+ return field(default=default, metadata=dict(label=label, group=group, low=low,
+ high=high, step=step, choices=choices))
+
+
+@dataclass(frozen=True)
+class Settings:
+ mode: str = control('d', 'Mode', 'Video', choices=[('Detailed', 'd'), ('Quick', 'e')])
+ duration: float = control(10., 'Duration (seconds)', 'Video', .1, 120, .1)
+ draw_percent: float = control(70., 'Drawing & coloring (%)', 'Video', 5, 100, 1)
+ ink_percent: float = control(45., 'Ink within drawing phase (%)', 'Video', 5, 95, 1)
+ width: int = control(1920, 'Maximum width (px)', 'Video', 64, 3840, 2)
+ height: int = control(1080, 'Maximum height (px)', 'Video', 64, 2160, 2)
+ fit: str = control('original', 'Image fit', 'Video', choices=[('Keep original aspect ratio', 'original'), ('Fill frame, crop center', 'cover'), ('Fit entire image, add padding', 'contain')])
+ fps: int = control(30, 'FPS', 'Video', 1, 60)
+ paper_color: str = control('#ffffff', 'Paper color', 'Video')
+ device: str = control('cuda', 'Rendering device', 'Video export', choices=[('GPU (CUDA)', 'cuda'), ('CPU', 'cpu')])
+ encoder: str = control('nvenc', 'Encoder', 'Video export', choices=[('NVIDIA NVENC', 'nvenc'), ('CPU H.264', 'cpu')])
+ quality: int = control(30, 'CQ / CRF', 'Video export', 1, 51)
+ encoder_preset: str = control('p4', 'NVENC preset', 'Video export', choices=[f'p{i}' for i in range(1, 8)])
+ cpu_preset: str = control('fast', 'CPU H.264 preset', 'Video export', choices=['ultrafast', 'fast', 'medium', 'slow'])
+ render_batch_size: int = control(2, 'Render batch size', 'Video export', 1, 8)
+ seed: int = control(42, 'Seed', 'Lines & colors', 0, 2147483647)
+ subject_first: bool = control(True, 'Color characters first', 'Lines & colors')
+ subject_resolution: int = control(1024, 'ISNet resolution', 'Lines & colors', 256, 1536, 128)
+ subject_threshold: float = control(.5, 'Subject mask threshold', 'Lines & colors', .05, .95, .01)
+ clean_ink: bool = control(True, 'Multiscale line cleanup', 'Lines & colors')
+ grid_edge: int = control(10, 'Line grid cell size (px)', 'Lines & colors', 2, 40)
+ adaptive_block: int = control(15, 'Line detection window (odd)', 'Lines & colors', 3, 51, 2)
+ adaptive_c: float = control(10., 'Line detection threshold C', 'Lines & colors', -10, 30, 1)
+ clahe_clip: float = control(2., 'CLAHE contrast', 'Lines & colors', .1, 8, .1)
+ palette_colors: int = control(16, 'Maximum palette colors', 'Lines & colors', 1, 32)
+ min_region_area: int = control(80, 'Minimum color region area (px)', 'Lines & colors', 1, 1000)
+ saturation: float = control(1., 'Color saturation', 'Lines & colors', 0, 2, .05)
+ brush_ratio: float = control(.12, 'Brush width / shorter image side', 'Coloring path', .01, .5, .01)
+ brush_min: float = control(24., 'Minimum brush width (px)', 'Coloring path', 1, 128, 1)
+ brush_max: float = control(92., 'Maximum brush width (px)', 'Coloring path', 1, 256, 1)
+ stroke_angle: float = control(12., 'Coloring stroke angle (degrees)', 'Coloring path', -80, 80, 1)
+ travel_speed_ratio: float = control(1.5, 'Travel speed / coloring speed', 'Coloring path', .1, 5, .1)
+ path_samples: int = control(4097, 'Hand path interpolation samples', 'Coloring path', 257, 16385, 256)
+ show_hand: bool = control(True, 'Show hand', 'Hand & pen')
+ hand_scale: float = control(1., 'Hand scale', 'Hand & pen', .1, 2, .05)
+ wrist_degrees: float = control(11., 'Wrist rotation amplitude (degrees)', 'Hand & pen', 0, 30, .5)
+ wrist_frequency: float = control(.55, 'Wrist motion frequency (Hz)', 'Hand & pen', 0, 3, .05)
+ finger_motion: float = control(1., 'Finger motion', 'Hand & pen', 0, 3, .1)
+ shadow_strength: float = control(1., 'Hand shadow strength', 'Hand & pen', 0, 2, .1)
+ draw_tip_x: int = control(0, 'Draw pen tip: X offset (native px)', 'Hand & pen', -100, 100)
+ draw_tip_y: int = control(0, 'Draw pen tip: Y offset (native px)', 'Hand & pen', -100, 100)
+ color_tip_x: int = control(0, 'Color pen tip: X offset (native px)', 'Hand & pen', -100, 100)
+ color_tip_y: int = control(0, 'Color pen tip: Y offset (native px)', 'Hand & pen', -100, 100)
+ rig_json: str = control('{}', 'Advanced hand rig (JSON)', 'Advanced')
+ ink_json: str = control('{}', 'Advanced line filter (JSON)', 'Advanced')
+
+ @property
+ def phase_seconds(self):
+ drawing = self.duration * self.draw_percent / 100
+ ink = drawing * self.ink_percent / 100
+ return ink, drawing - ink, self.duration - drawing
+
+ def validate(self):
+ for item in fields(self):
+ value, spec = getattr(self, item.name), item.metadata
+ if spec['choices']:
+ choices = [entry[1] if isinstance(entry, tuple) else entry for entry in spec['choices']]
+ if value not in choices:
+ raise ValueError(f'{item.name}: invalid choice')
+ elif isinstance(item.default, bool):
+ if not isinstance(value, bool):
+ raise ValueError(f'{item.name}: boolean required')
+ elif spec['low'] is not None:
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
+ raise ValueError(f'{item.name}: finite number required')
+ if not spec['low'] <= value <= spec['high']:
+ raise ValueError(f'{item.name}: must be {spec["low"]}..{spec["high"]}')
+ if isinstance(item.default, int) and int(value) != value:
+ raise ValueError(f'{item.name}: integer required')
+ if self.adaptive_block % 2 != 1 or self.brush_min > self.brush_max:
+ raise ValueError('Invalid adaptive window or brush width range')
+ if self.duration * self.fps < 1:
+ raise ValueError('Duration must cover at least one frame at the selected FPS')
+ if self.encoder == 'nvenc' and self.device != 'cuda':
+ raise ValueError('NVENC requires CUDA; select the CPU encoder for CPU rendering')
+ if not isinstance(self.paper_color, str) or len(ImageColor.getrgb(self.paper_color)) != 3:
+ raise ValueError('Paper color must be opaque RGB')
+ rig_settings(self)
+ ink_options(self)
+ return self
+
+
+INK_DEFAULTS = {'bilateral_first': [7, 12, 3], 'bilateral_second': [5, 12, 2],
+ 'clahe_tiles': 8, 'coarse_c': [5, 4], 'support_dilate': 3,
+ 'component_area': 4, 'component_span': 8, 'barrier_size': 3}
+
+
+def ink_options(settings):
+ if not isinstance(settings.ink_json, str) or len(settings.ink_json) > 20000:
+ raise ValueError('Ink settings must be a bounded JSON string')
+ extra = json.loads(settings.ink_json)
+ if not isinstance(extra, dict) or extra.keys() - INK_DEFAULTS.keys():
+ raise ValueError('Unknown ink setting')
+ result = {**deepcopy(INK_DEFAULTS), **extra}
+ for key, value in result.items():
+ values = value if isinstance(value, list) else [value]
+ if any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not 0 < v <= 100 for v in values):
+ raise ValueError(f'Invalid ink setting: {key}')
+ for key in ('bilateral_first', 'bilateral_second'):
+ if not isinstance(result[key], list) or len(result[key]) != 3 or result[key][0] % 2 != 1:
+ raise ValueError(f'Invalid bilateral parameters: {key}')
+ if not isinstance(result['coarse_c'], list) or len(result['coarse_c']) != 2:
+ raise ValueError('coarse_c must contain two numbers')
+ for key in ('clahe_tiles', 'support_dilate', 'barrier_size'):
+ if int(result[key]) != result[key]:
+ raise ValueError(f'{key} must be an integer')
+ return result
+
+
+def rig_settings(settings):
+ if not isinstance(settings.rig_json, str) or len(settings.rig_json) > 20000:
+ raise ValueError('Rig settings must be a bounded JSON string')
+ rig = deepcopy(RIG_SETTINGS)
+ extra = json.loads(settings.rig_json)
+ if not isinstance(extra, dict) or extra.keys() - rig.keys():
+ raise ValueError('Unknown rig setting')
+ protected = {'reference_height', 'native_scale', 'wrist_degrees', 'wrist_frequency'}
+ if extra.keys() & protected:
+ raise ValueError('Use the dedicated wrist/scale controls')
+ rig.update(extra)
+ # Validate against the native rig shape before any tensor allocation.
+ def check(value, template):
+ if isinstance(template, dict):
+ if not isinstance(value, dict) or value.keys() != template.keys():
+ raise ValueError('Rig keys must match the native schema')
+ for key in template:
+ check(value[key], template[key])
+ elif isinstance(template, list):
+ if not isinstance(value, list) or len(value) != len(template):
+ raise ValueError('Rig arrays must match the native schema')
+ for item, reference in zip(value, template):
+ check(item, reference)
+ elif isinstance(template, bool):
+ if value != template:
+ raise ValueError('The approved hand orientation is fixed')
+ elif isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or abs(value) > 4096:
+ raise ValueError('Rig values must be finite and bounded')
+ check(rig, RIG_SETTINGS)
+ if len(rig['oscillations']) != 4 or min(rig['contact_variance']) <= 0 or min(rig['contact_offset']) <= 0:
+ raise ValueError('Invalid contact shadow')
+ for key in ('marker_dilate', 'marker_falloff', 'nib_radius'):
+ if not 1 <= rig[key] <= 100 or int(rig[key]) != rig[key]:
+ raise ValueError(f'Invalid rig setting: {key}')
+ if any(not 0 <= opacity <= 1 or not 0 < sigma <= 100 for opacity, sigma in rig['shadow']):
+ raise ValueError('Invalid cast shadow')
+ if (any(value < 0 for key in ('shadow_offset', 'lift_shadow_offset') for value in rig[key])
+ or not 0 <= rig['lift_scale'] <= 1 or not 0 <= rig['lift_pixels'] <= 100
+ or not 0 <= rig['lift_shadow_fade'] <= 1 or not 0 <= rig['shadow_max'] <= 1
+ or not 0 <= rig['contact_opacity'] <= 1):
+ raise ValueError('Invalid lift or shadow settings')
+ rig['wrist_degrees'], rig['wrist_frequency'] = settings.wrist_degrees, settings.wrist_frequency
+ rig['shadow_max'] = min(1, max(0, rig['shadow_max'] * settings.shadow_strength))
+ rig['contact_opacity'] *= settings.shadow_strength
+ for shadow in rig['shadow']:
+ shadow[0] *= settings.shadow_strength
+ for mode in ('draw', 'color'):
+ pose = rig['poses'][mode]
+ if pose['native_size'] != RIG_SETTINGS['poses'][mode]['native_size'] or not .1 <= pose['native_scale'] <= 2:
+ raise ValueError('Hand dimensions are fixed; scale must be positive')
+ pose['native_scale'] *= settings.hand_scale
+ pose['tip'][0] += getattr(settings, mode + '_tip_x')
+ pose['tip'][1] += getattr(settings, mode + '_tip_y')
+ if any(int(value) != value for value in pose['tip']):
+ raise ValueError('Nib coordinates must be integers')
+ pose['tip'] = [int(value) for value in pose['tip']]
+ pose['native_size'] = list(RIG_SETTINGS['poses'][mode]['native_size'])
+ if any(not 0 <= p < size for p, size in zip(pose['tip'], pose['native_size'])):
+ raise ValueError('Nib anchor lies outside the hand image')
+ for center in pose['centers']:
+ if center[2] <= 0:
+ raise ValueError('Motion radius must be positive')
+ center[-2] *= settings.finger_motion
+ center[-1] *= settings.finger_motion
+ return rig
diff --git a/handdraw/subject.py b/handdraw/subject.py
new file mode 100644
index 0000000..890ce20
--- /dev/null
+++ b/handdraw/subject.py
@@ -0,0 +1,99 @@
+"""SkyTNT ISNet inference; see vendor_runtime/anime_segmentation/LICENSE."""
+from __future__ import annotations
+import importlib.util
+import threading
+import time
+from numbers import Integral, Real
+from pathlib import Path
+import cv2
+import numpy as np
+ROOT = Path(__file__).resolve().parents[1]
+MODEL_ROOT = ROOT / "assets" / "v181d"
+_MODEL_CACHE = None
+_MODEL_LOCK = threading.Lock()
+
+def _get_model(device):
+ global _MODEL_CACHE
+ with _MODEL_LOCK:
+ if _MODEL_CACHE is not None and _MODEL_CACHE[1] == device:
+ return _MODEL_CACHE
+
+ import torch
+ from safetensors.torch import load_file
+
+ source = ROOT / "vendor_runtime" / "anime_segmentation" / "isnet.py"
+ if not source.is_file():
+ raise RuntimeError(f"Missing official SkyTNT ISNet source: {source}")
+ spec = importlib.util.spec_from_file_location("_whiteboard_skytnt_isnet", source)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module) # Avoid upstream model/__init__, Lightning and training imports.
+ checkpoint = MODEL_ROOT / "model.safetensors"
+ if not checkpoint.is_file():
+ raise RuntimeError(f"Missing bundled Anime Segmentation checkpoint: {checkpoint}")
+ weights = load_file(str(checkpoint), device="cpu")
+ state = {key.removeprefix("net."): value for key, value in weights.items()
+ if key.startswith("net.")}
+ model = module.ISNetDIS()
+ model.load_state_dict(state, strict=True)
+ if device == 'cuda' and not torch.cuda.is_available():
+ raise RuntimeError('CUDA unavailable; select CPU explicitly.')
+ model = model.float().eval().to(device)
+ _MODEL_CACHE = model, device
+ return _MODEL_CACHE
+
+
+def release_subject_model():
+ global _MODEL_CACHE
+ with _MODEL_LOCK:
+ _MODEL_CACHE = None
+ import torch
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+
+
+def detect_subject_mask(image_rgb, resolution=1024, threshold=.5, *, device='cuda'):
+ """Return all semantic foreground as an HxW bool mask, including detached parts.
+
+ Foreground may contain multiple people; this model does not identify a main person.
+ """
+ if (not isinstance(image_rgb, np.ndarray) or image_rgb.ndim != 3
+ or image_rgb.shape[2] != 3 or image_rgb.dtype != np.uint8
+ or not image_rgb.shape[0] or not image_rgb.shape[1]):
+ raise ValueError("image_rgb must be a nonempty HxWx3 RGB uint8 array")
+ if (isinstance(resolution, (bool, np.bool_)) or not isinstance(resolution, Integral)
+ or resolution <= 0):
+ raise ValueError("resolution must be a positive integer")
+ if (isinstance(threshold, (bool, np.bool_)) or not isinstance(threshold, Real)
+ or not np.isfinite(threshold) or not 0 <= threshold <= 1):
+ raise ValueError("threshold must be finite and between 0 and 1")
+
+ import torch
+
+ started = time.perf_counter()
+ model, device = _get_model(device)
+ h0, w0 = image_rgb.shape[:2]
+ s = int(resolution)
+ h, w = (s, max(1, int(s * w0 / h0))) if h0 > w0 else (max(1, int(s * h0 / w0)), s)
+ top, left = (s - h) // 2, (s - w) // 2
+ image = (image_rgb / 255).astype(np.float32)
+ padded = np.zeros((s, s, 3), dtype=np.float32)
+ padded[top:top + h, left:left + w] = cv2.resize(image, (w, h))
+ tensor = torch.from_numpy(padded.transpose(2, 0, 1)[None]).to(device=device, dtype=torch.float32)
+ with torch.inference_mode():
+ prediction = model(tensor)[0][0]
+ if tuple(prediction.shape) != (1, 1, s, s) or not torch.isfinite(prediction).all().item():
+ raise RuntimeError("Invalid ISNet prediction shape or nonfinite values")
+ probabilities = prediction.sigmoid().float().cpu().numpy()[0, 0]
+ probabilities = cv2.resize(probabilities[top:top + h, left:left + w], (w0, h0))
+ if probabilities.shape != (h0, w0) or not np.isfinite(probabilities).all():
+ raise RuntimeError("Invalid restored ISNet prediction")
+ mask = probabilities >= threshold
+ return mask, {
+ "detector": "SkyTNT Anime Segmentation (ISNet)",
+ "device": device,
+ "elapsed": time.perf_counter() - started,
+ "coverage": float(mask.mean()),
+ "foreground_scope": "Semantic foreground may include multiple people; detached components are retained.",
+ }
+
+
diff --git a/handdraw/v181d_cluster.py b/handdraw/v181d_cluster.py
new file mode 100644
index 0000000..46e5a47
--- /dev/null
+++ b/handdraw/v181d_cluster.py
@@ -0,0 +1,209 @@
+"""Full-visible Lab kmeans++ for .d, with an OpenCV reference/fallback."""
+from __future__ import annotations
+
+import cv2
+import numpy as np
+
+
+def capped_color_count(pixels, cap=16):
+ seen = set()
+ for begin in range(0, len(pixels), 4096):
+ values = pixels[begin:begin + 4096].astype(np.uint32)
+ packed = (values[:, 0] << 16) | (values[:, 1] << 8) | values[:, 2]
+ for value in np.unique(packed):
+ seen.add(int(value))
+ if len(seen) >= cap:
+ return cap
+ return len(seen)
+
+
+def choose_backend(backend="auto"):
+ if backend not in {"auto", "cpu", "cuda"}:
+ raise ValueError("cluster backend must be auto, cpu, or cuda.")
+ if backend == "cpu":
+ return "cpu"
+ try:
+ import torch
+ if torch.cuda.is_available():
+ return "cuda"
+ except (ImportError, OSError, RuntimeError) as exc:
+ if backend == "cuda":
+ raise RuntimeError("Torch CUDA clustering is unavailable.") from exc
+ if backend == "cuda":
+ raise RuntimeError("Torch CUDA clustering is unavailable.")
+ return "cpu"
+
+
+def cluster_backend(backend="auto"):
+ return "torch-cuda" if choose_backend(backend) == "cuda" else "opencv-cpu"
+
+
+def _bounded_chunk_size(pixels, count, requested, budget):
+ available = min(budget, 6 * 1024 ** 3) - 48 * pixels - 64 * 1024 ** 2
+ chunk = min(requested, 262144, pixels, available // (16 * max(count, 3)))
+ if chunk < 1:
+ raise RuntimeError("Full-resolution .d clustering exceeds its CUDA memory budget.")
+ return int(chunk)
+
+
+def _squared_distances(values, centers):
+ # Direct FP32 channel arithmetic avoids TF32 and an N x K x 3 tensor.
+ distance = (values[:, 0, None] - centers[None, :, 0]).square()
+ for channel in (1, 2):
+ distance.add_((values[:, channel, None] - centers[None, :, channel]).square())
+ return distance
+
+
+def _assign(pixels, centers, chunk_size):
+ import torch
+ labels = torch.empty(len(pixels), dtype=torch.int64, device=pixels.device)
+ for begin in range(0, len(pixels), chunk_size):
+ values = pixels[begin:begin + chunk_size]
+ labels[begin:begin + len(values)] = _squared_distances(values, centers).argmin(dim=1)
+ return labels
+
+
+def _seed_centers(pixels, count, generator, chunk_size):
+ import torch
+ centers = torch.empty((count, 3), dtype=torch.float32, device=pixels.device)
+ first = torch.randint(len(pixels), (), generator=generator, device=pixels.device)
+ centers[0] = pixels[first]
+ nearest = torch.empty(len(pixels), dtype=torch.float32, device=pixels.device)
+ cumulative = torch.empty_like(nearest)
+ for color in range(1, count):
+ for begin in range(0, len(pixels), chunk_size):
+ values = pixels[begin:begin + chunk_size]
+ distances = _squared_distances(values, centers[color - 1:color]).flatten()
+ if color > 1:
+ distances = torch.minimum(nearest[begin:begin + len(values)], distances)
+ nearest[begin:begin + len(values)] = distances
+ torch.cumsum(nearest, dim=0, out=cumulative)
+ draws = torch.rand(3, generator=generator, device=pixels.device) * cumulative[-1]
+ candidates = torch.searchsorted(cumulative, draws, right=True).clamp_max(len(pixels) - 1)
+ potential = torch.zeros(3, dtype=torch.float32, device=pixels.device)
+ for begin in range(0, len(pixels), chunk_size):
+ values = pixels[begin:begin + chunk_size]
+ distances = _squared_distances(values, pixels[candidates])
+ potential.add_(torch.minimum(distances, nearest[begin:begin + len(values), None]).sum(dim=0))
+ centers[color] = pixels[candidates[potential.argmin()]]
+ return centers
+
+
+def _update_centers(pixels, labels, count, chunk_size):
+ import torch
+ sums = torch.zeros((count, 3), dtype=torch.float32, device=pixels.device)
+ counts = torch.zeros(count, dtype=torch.int64, device=pixels.device)
+ colors = torch.arange(count, device=pixels.device)
+ # Fixed-order reductions avoid floating-point scatter atomics.
+ for begin in range(0, len(pixels), chunk_size):
+ values = pixels[begin:begin + chunk_size]
+ membership = labels[begin:begin + len(values), None] == colors[None]
+ counts.add_(membership.sum(dim=0))
+ for channel in range(3):
+ sums[:, channel].add_(torch.where(membership, values[:, channel, None], 0.).sum(dim=0))
+ for empty in torch.nonzero(counts == 0).flatten().tolist():
+ largest = counts.argmax()
+ center = (sums[largest] / counts[largest]).reshape(1, 3)
+ best = torch.tensor(-1., device=pixels.device)
+ farthest = torch.tensor(0, dtype=torch.int64, device=pixels.device)
+ for begin in range(0, len(pixels), chunk_size):
+ values = pixels[begin:begin + chunk_size]
+ distance = _squared_distances(values, center).flatten()
+ distance.masked_fill_(labels[begin:begin + len(values)] != largest, -1.)
+ maximum, index = distance.flip(0).max(dim=0)
+ farthest = torch.where(maximum >= best, begin + len(values) - 1 - index, farthest)
+ best = torch.maximum(best, maximum)
+ point = pixels[farthest]
+ labels[farthest] = empty
+ counts[largest] -= 1
+ counts[empty] = 1
+ sums[largest] -= point
+ sums[empty] = point
+ return sums / counts[:, None]
+
+
+def _torch_kmeans(samples, count, seed, device, chunk_size):
+ import torch
+ device = torch.device(device)
+ budget = 6 * 1024 ** 3
+ if device.type == "cuda":
+ free, _ = torch.cuda.mem_get_info(device)
+ budget = min(budget, int(free * .8))
+ chunk_size = _bounded_chunk_size(len(samples), count, chunk_size, budget)
+ generator = torch.Generator(device=device).manual_seed(int(seed) & 0x7fffffff)
+ scores, iterations = [], []
+ best_score = float("inf")
+ with torch.inference_mode():
+ pixels = torch.as_tensor(samples, dtype=torch.float32, device=device)
+ for _ in range(3):
+ centers = _seed_centers(pixels, count, generator, chunk_size)
+ labels = _assign(pixels, centers, chunk_size)
+ for iteration in range(1, 10):
+ previous = centers
+ centers = _update_centers(pixels, labels, count, chunk_size)
+ if iteration == 9 or bool((centers - previous).square().sum(dim=1).max() <= 1.):
+ break
+ labels = _assign(pixels, centers, chunk_size)
+ # Keep the last mean-update labels, including repaired empty clusters.
+ objective = torch.zeros((), dtype=torch.float32, device=device)
+ for begin in range(0, len(pixels), chunk_size):
+ values = pixels[begin:begin + chunk_size]
+ objective.add_((values - centers[labels[begin:begin + len(values)]]).square().sum())
+ score = float(objective)
+ scores.append(score)
+ iterations.append(iteration + 1)
+ if score < best_score:
+ best_score = score
+ best_labels, best_centers = labels.clone(), centers.clone()
+ return (best_labels.to(device="cpu", dtype=torch.int32).numpy(), best_centers.cpu().numpy(),
+ {"compactness": best_score, "attempt_compactness": scores, "iterations": iterations,
+ "chunk_size": chunk_size, "memory_budget_bytes": budget,
+ "working_set_bound_bytes": 48 * len(samples) + 64 * 1024 ** 2 + 16 * chunk_size * max(count, 3),
+ "torch_version": torch.__version__})
+
+
+def cluster_lab(pixels, seed=42, *, backend="auto", chunk_size=262144, diagnostics=None, color_cap=16):
+ pixels = np.asarray(pixels)
+ if pixels.dtype != np.uint8 or pixels.ndim != 2 or pixels.shape[1] != 3 or not len(pixels):
+ raise ValueError(".d clustering requires nonempty uint8 Lab pixels with shape (N, 3).")
+ if not isinstance(chunk_size, (int, np.integer)) or chunk_size < 1:
+ raise ValueError("cluster chunk_size must be a positive integer.")
+ selected = choose_backend(backend)
+ selected_identity = "torch-cuda" if selected == "cuda" else "opencv-cpu"
+ seed = int(seed) & 0x7fffffff
+ count = capped_color_count(pixels, cap=color_cap)
+ fallback = "torch_cuda_unavailable" if backend == "auto" and selected == "cpu" else ""
+ details = {}
+ if count == 1:
+ labels, centers = np.zeros(len(pixels), np.int32), pixels[:1].astype(np.float32)
+ details["compactness"] = 0.
+ actual = selected_identity
+ else:
+ if selected == "cuda":
+ try:
+ labels, centers, details = _torch_kmeans(pixels, count, seed, "cuda", chunk_size)
+ except RuntimeError as exc:
+ if backend != "auto":
+ raise
+ fallback = f"{type(exc).__name__}: {exc}"
+ print(f".d CUDA clustering fallback: {fallback}", flush=True)
+ selected = "cpu"
+ if selected == "cpu":
+ # The .d plan holds its existing OpenCV RNG lock through palette routing.
+ cv2.setRNGSeed(seed)
+ objective, labels, centers = cv2.kmeans(
+ pixels.astype(np.float32), count, None,
+ (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.), 3, cv2.KMEANS_PP_CENTERS)
+ labels = labels[:, 0]
+ details["compactness"] = objective
+ actual = "torch-cuda" if selected == "cuda" else "opencv-cpu"
+ if diagnostics is not None:
+ diagnostics.update(cluster_backend=actual, cluster_requested_backend=backend, cluster_seed=seed,
+ cluster_selected_backend=selected_identity,
+ cluster_fast_path="single-color" if count == 1 else "",
+ cluster_dtype="float32", cluster_pixels=len(pixels), cluster_colors=count,
+ cluster_attempts=3, cluster_max_iter=10, cluster_epsilon=1.,
+ cluster_initialization="kmeans++ / 3 D2 trials", cluster_centers=centers.tolist(),
+ cluster_fallback_reason=fallback,
+ **{f"cluster_{key}": value for key, value in details.items()})
+ return labels, count
diff --git a/handdraw/v181d_hand.py b/handdraw/v181d_hand.py
new file mode 100644
index 0000000..020570e
--- /dev/null
+++ b/handdraw/v181d_hand.py
@@ -0,0 +1,284 @@
+"""Native photographic left-hand rigs with rigid markers and absolute-clock motion."""
+from __future__ import annotations
+
+from functools import lru_cache
+import hashlib
+import json
+import math
+from pathlib import Path
+from stat import S_ISREG
+
+import cv2
+import numpy as np
+
+
+HAND_RENDER_VERSION = "v181d-hand-long-turn-clock-v3"
+_REPO_ROOT = Path(__file__).resolve().parents[1]
+ASSETS = {mode: _REPO_ROOT / "assets" / "v181d" / f"{mode}-hand-long.png"
+ for mode in ("draw", "color")}
+RIG_SETTINGS = {
+ "reference_height": 1080, "native_scale": .76,
+ "wrist_degrees": 11, "wrist_frequency": .55,
+ "oscillations": [[1.3, 0], [1.05, 1.7], [1.45, 3.2], [.55, .4]],
+ "marker_dilate": 17, "marker_falloff": 25, "nib_radius": 12,
+ "shadow": [[.17, 18], [.07, 5]], "shadow_offset": [18, 22],
+ "contact_opacity": .18, "contact_variance": [80, 40],
+ "contact_offset": [6, 5.5], "shadow_max": .4,
+ "lift_scale": .025, "lift_pixels": 12,
+ "lift_shadow_offset": [8, 12], "lift_shadow_fade": .22,
+ "poses": {
+ "draw": {
+ "native_size": [768, 2048], "native_scale": 1.18, "mirror": True, "tip": [125, 70],
+ "marker": [[119, 62], [144, 66], [305, 205], [372, 287], [357, 309],
+ [335, 322], [316, 312], [276, 265], [145, 129]],
+ "centers": [[263, 104, 56, 5, -4], [368, 187, 66, -4, -3],
+ [180, 200, 56, -3, 5], [397, 423, 108, 4, -1]],
+ },
+ "color": {
+ "native_size": [735, 2140], "native_scale": 1.08, "mirror": False, "tip": [616, 102],
+ "marker": [[585, 53], [629, 100], [638, 291], [625, 463], [610, 502],
+ [564, 494], [566, 434], [591, 264], [605, 137]],
+ "centers": [[438, 168, 67, -4, 3], [533, 135, 74, 4, -3],
+ [633, 224, 70, -4, -4], [369, 572, 126, -4, -1]],
+ },
+ },
+}
+
+
+def _asset_stat(mode):
+ if mode not in RIG_SETTINGS["poses"] or mode not in ASSETS:
+ raise ValueError("Hand mode must be draw or color.")
+ path = ASSETS[mode].resolve()
+ if not path.is_relative_to(_REPO_ROOT):
+ raise ValueError("Hand asset must be inside this repo.")
+ stat = path.stat()
+ if not S_ISREG(stat.st_mode):
+ raise ValueError("Hand asset must be a regular PNG file.")
+ return path, stat
+
+
+def _asset_bytes(mode):
+ path, _ = _asset_stat(mode)
+ return path, path.read_bytes()
+
+
+@lru_cache(maxsize=4)
+def _asset_sha256(path, size, mtime_ns):
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def hand_asset_identity() -> dict:
+ """JSON-safe fingerprint of both persisted assets and all rig settings."""
+ assets = {}
+ for mode in ASSETS:
+ path, stat = _asset_stat(mode)
+ assets[mode] = {"path": path.relative_to(_REPO_ROOT).as_posix(),
+ "size": stat.st_size, "mtime_ns": stat.st_mtime_ns,
+ "sha256": _asset_sha256(path, stat.st_size, stat.st_mtime_ns)}
+ identity = {"version": HAND_RENDER_VERSION, "assets": assets,
+ "settings": json.loads(json.dumps(RIG_SETTINGS))}
+ payload = json.dumps(identity, sort_keys=True, separators=(",", ":"), allow_nan=False)
+ identity["fingerprint"] = hashlib.sha256(payload.encode("utf-8")).hexdigest()
+ return identity
+
+
+def prepare_asset(mode, settings=None):
+ _, encoded = _asset_bytes(mode)
+ config = RIG_SETTINGS if settings is None else settings
+ pose = config["poses"][mode]
+ width, height = pose["native_size"]
+ if not encoded.startswith(b"\x89PNG\r\n\x1a\n"):
+ raise ValueError("Hand asset must be a native uint8 RGBA PNG cutout.")
+ raw = cv2.imdecode(np.frombuffer(encoded, np.uint8), cv2.IMREAD_UNCHANGED)
+ if (raw is None or raw.dtype != np.uint8 or raw.shape != (height, width, 4)
+ or not np.any(raw[..., 3] == 0) or not np.any(raw[..., 3] >= 200)):
+ raise ValueError(f"Hand asset must be a transparent native uint8 RGBA {width}x{height} cutout.")
+ tx, ty = pose["tip"]
+ if raw[ty, tx, 3] < 128 or (settings is None and raw[ty, tx, :3].max() >= 128):
+ raise ValueError("Hand asset must have a visible dark marker nib at its anchor.")
+ polygon = np.array(pose["marker"], np.int32)
+ if pose["mirror"]:
+ raw = raw[:, ::-1]
+ tx = width - 1 - tx
+ polygon[:, 0] = width - 1 - polygon[:, 0]
+ image = cv2.cvtColor(raw, cv2.COLOR_BGRA2RGBA).astype(np.float32) / 255
+ image[..., :3] *= image[..., 3:4]
+ pen = np.zeros((height, width), np.uint8)
+ cv2.fillPoly(pen, [polygon], 1)
+ cv2.circle(pen, (tx, ty), int(config["nib_radius"]), 1, -1)
+ edge = int(config["marker_dilate"])
+ pen = cv2.dilate(pen, np.ones((edge, edge), np.uint8))
+ return image, (tx, ty), pen
+
+
+def motion_basis(mode, pen, settings=None):
+ if mode not in RIG_SETTINGS["poses"]:
+ raise ValueError("Hand mode must be draw or color.")
+ config = RIG_SETTINGS if settings is None else settings
+ pose = config["poses"][mode]
+ width, height = pose["native_size"]
+ if pen.shape != (height, width):
+ raise ValueError("Marker mask must match the native hand dimensions.")
+ y, x = np.indices(pen.shape, dtype=np.float32)
+ if pose["mirror"]:
+ x = width - 1 - x
+ # Include a zero-motion guard around the nib, barrel and cap before feathering.
+ distance = cv2.distanceTransform(1 - pen, cv2.DIST_L2, 3)
+ protect = np.clip(distance / config["marker_falloff"], 0, 1)
+ direction = -1 if pose["mirror"] else 1
+ fields = []
+ for cx, cy, radius, dx, dy in pose["centers"]:
+ weight = np.exp(-((x - cx) ** 2 + (y - cy) ** 2) / (2 * radius ** 2)) * protect
+ fields.append(np.stack((direction * dx * weight, dy * weight), axis=-1))
+ return np.stack(fields, axis=-2)
+
+
+def motion_at(seconds, settings=None):
+ if not math.isfinite(seconds):
+ raise ValueError("Hand motion seconds must be finite.")
+ config = RIG_SETTINGS if settings is None else settings
+ angle = math.radians(config["wrist_degrees"]) * math.sin(
+ seconds * math.tau * config["wrist_frequency"])
+ return (angle, *(math.sin(seconds * math.tau * frequency + phase)
+ for frequency, phase in config["oscillations"]))
+
+
+def scheduled_hands(state, block, indices, panel, minimum_index, fps):
+ """Return (batch slot, mode, page contact, absolute seconds, normalized lift)."""
+ if not math.isfinite(fps) or fps <= 0:
+ raise ValueError("Hand scheduling fps must be finite and positive.")
+ selected = [(slot, index) for slot, index in enumerate(indices)
+ if max(0, minimum_index) <= index < block.draw_frames - 1]
+ if not selected:
+ return []
+ path = np.asarray(state["pen_path"], dtype=np.float64)
+ if (path.ndim != 2 or path.shape[1] != 3 or not len(path)
+ or not np.isfinite(path).all() or np.any(np.diff(path[:, 0]) <= 0)
+ or np.any(path[:, 0] < 0) or np.any(path[:, 0] > 1)):
+ raise ValueError("pen_path must be finite Nx3 with strictly increasing normalized times.")
+ lift = np.asarray(state.get("pen_lift", np.zeros(len(path))), dtype=np.float64)
+ if (lift.shape != (len(path),) or not np.isfinite(lift).all()
+ or np.any(lift < 0) or np.any(lift > 1)):
+ raise ValueError("pen_lift must be a normalized finite 1-D array matching pen_path.")
+ ink_end = float(state["ink_end"])
+ if not math.isfinite(ink_end) or not 0 <= ink_end <= 1:
+ raise ValueError("ink_end must be finite and normalized.")
+ px, py = float(panel["x"]), float(panel["y"])
+ if not math.isfinite(px) or not math.isfinite(py):
+ raise ValueError("Panel offsets must be finite.")
+ events = []
+ for slot, index in selected:
+ progress = (index - max(0, minimum_index)) / max(1, block.draw_frames - max(0, minimum_index) - 1)
+ point = (float(np.interp(progress, path[:, 0], path[:, 1])) + px,
+ float(np.interp(progress, path[:, 0], path[:, 2])) + py)
+ events.append((slot, "draw" if progress < ink_end else "color", point,
+ (block.start_frame + index) / fps,
+ float(np.interp(progress, path[:, 0], lift))))
+ return events
+
+
+class MovingHand:
+ def __init__(self, mode, width, height, device, settings=None):
+ import torch
+ if any(not isinstance(value, (int, np.integer)) or value < 1 for value in (width, height)):
+ raise ValueError("Hand frame dimensions must be positive integers.")
+ self.settings = RIG_SETTINGS if settings is None else settings
+ image, self.tip, pen = prepare_asset(mode, self.settings)
+ basis = motion_basis(mode, pen, self.settings)
+ self.motion_margin = np.abs(basis).sum(axis=2).max(axis=(0, 1)) + 2
+ self.native_height, self.native_width = image.shape[:2]
+ self.width, self.height = width, height
+ alpha = image[..., 3]
+ shadow = sum(opacity * cv2.GaussianBlur(alpha, (0, 0), sigma)
+ for opacity, sigma in self.settings["shadow"])
+ texture = np.concatenate((image, shadow[..., None]), axis=-1)
+ self.texture = torch.from_numpy(texture).permute(2, 0, 1).unsqueeze(0).contiguous().to(device)
+ self.fields = torch.from_numpy(basis.reshape(self.native_height, self.native_width, -1))
+ self.fields = self.fields.permute(2, 0, 1).unsqueeze(0).contiguous().to(device)
+ self.yy, self.xx = torch.meshgrid(torch.arange(height, device=device, dtype=torch.float32),
+ torch.arange(width, device=device, dtype=torch.float32), indexing="ij")
+ self.size = self.settings["poses"][mode]["native_scale"] * height / self.settings["reference_height"]
+ ratio = height / self.settings["reference_height"]
+ self.shadow_dx, self.shadow_dy = (max(1, round(offset * ratio))
+ for offset in self.settings["shadow_offset"])
+ self.contact_scale = max(.1, ratio) ** 2
+
+ def stamp(self, frame, point, seconds, bounds, lift=0):
+ import torch
+ import torch.nn.functional as functional
+ if (not torch.is_tensor(frame) or frame.dtype != torch.uint8
+ or tuple(frame.shape) != (self.height, self.width, 3)
+ or frame.device != self.texture.device):
+ raise ValueError("Hand frame must be a matching HWC uint8 tensor on the rig device.")
+ if len(point) != 2 or not all(math.isfinite(value) for value in (*point, seconds)):
+ raise ValueError("Hand point and seconds must be finite.")
+ if not math.isfinite(lift) or not 0 <= lift <= 1:
+ raise ValueError("Hand lift must be finite and normalized.")
+ if len(bounds) != 4 or any(not isinstance(value, (int, np.integer)) for value in bounds):
+ raise ValueError("Hand bounds must be integer (left, top, right, bottom).")
+ left, top, right, bottom = bounds
+ if right < left or bottom < top:
+ raise ValueError("Hand bounds must be ordered.")
+ left, top = max(0, left), max(0, top)
+ right, bottom = min(self.width, right), min(self.height, bottom)
+ if left >= right or top >= bottom:
+ return frame
+ config = self.settings
+ ratio = self.height / config["reference_height"]
+ size = self.size * (1 + config["lift_scale"] * lift)
+ angle, *oscillations = motion_at(seconds, config)
+ cosine, sine = math.cos(angle), math.sin(angle)
+ extra_x, extra_y = config["lift_shadow_offset"]
+ ox = self.shadow_dx + round(extra_x * ratio * lift)
+ oy = self.shadow_dy + round(extra_y * ratio * lift)
+ vx, vy = config["contact_variance"]
+ cx, cy = config["contact_offset"]
+ # Include deformation, bilinear support and both shadows before clipping to the canvas.
+ mx, my = self.motion_margin
+ corners = np.array([[-mx, -my], [self.native_width + mx, -my],
+ [-mx, self.native_height + my],
+ [self.native_width + mx, self.native_height + my]]) - self.tip
+ bx = point[0] + size * (cosine * corners[:, 0] - sine * corners[:, 1])
+ by = point[1] - config["lift_pixels"] * ratio * lift + size * (
+ sine * corners[:, 0] + cosine * corners[:, 1])
+ contact_x = math.sqrt(vx * self.contact_scale * 24)
+ contact_y = math.sqrt(vy * self.contact_scale * 24)
+ x0 = max(0, math.floor(min(bx.min(), point[0] + ox / cx - contact_x)))
+ y0 = max(0, math.floor(min(by.min(), point[1] + oy / cy - contact_y)))
+ x1 = min(self.width, math.ceil(max(bx.max() + ox, point[0] + ox / cx + contact_x)))
+ y1 = min(self.height, math.ceil(max(by.max() + oy, point[1] + oy / cy + contact_y)))
+ left, top, right, bottom = max(left, x0), max(top, y0), min(right, x1), min(bottom, y1)
+ if x0 >= x1 or y0 >= y1:
+ self.last_delta = (torch.zeros_like(self.xx), torch.zeros_like(self.yy))
+ return frame
+ xx, yy = self.xx[y0:y1, x0:x1], self.yy[y0:y1, x0:x1]
+ dx = (xx - point[0]) / size
+ dy = (yy - point[1] + config["lift_pixels"] * ratio * lift) / size
+ sx = cosine * dx + sine * dy + self.tip[0]
+ sy = -sine * dx + cosine * dy + self.tip[1]
+ half_w, half_h = (self.native_width - 1) / 2, (self.native_height - 1) / 2
+ grid = torch.stack((sx / half_w - 1, sy / half_h - 1), dim=-1).unsqueeze(0)
+ local = functional.grid_sample(self.fields, grid, align_corners=True)[0]
+ delta_x = sum(local[2 * i] * value for i, value in enumerate(oscillations))
+ delta_y = sum(local[2 * i + 1] * value for i, value in enumerate(oscillations))
+ padding = (x0, self.width - x1, y0, self.height - y1)
+ self.last_delta = tuple(functional.pad(delta, padding) for delta in (delta_x, delta_y))
+ if left >= right or top >= bottom:
+ return frame
+ grid[..., 0] -= delta_x / half_w
+ grid[..., 1] -= delta_y / half_h
+ sampled = functional.grid_sample(self.texture, grid, align_corners=True)[0]
+ cast = torch.zeros_like(xx)
+ if ox < x1 - x0 and oy < y1 - y0:
+ cast[oy:, ox:] = sampled[4, :-oy, :-ox]
+ contact = config["contact_opacity"] * (1 - lift) * torch.exp(
+ -((xx - point[0] - ox / cx) ** 2 / (vx * self.contact_scale)
+ + (yy - point[1] - oy / cy) ** 2 / (vy * self.contact_scale)))
+ background = frame[y0:y1, x0:x1].permute(2, 0, 1).float() / 255
+ shadow = (cast * (1 - config["lift_shadow_fade"] * lift) + contact).clamp(
+ 0, config["shadow_max"])
+ background *= (1 - shadow).unsqueeze(0)
+ rgb = background * (1 - sampled[3:4]) + sampled[:3]
+ frame[top:bottom, left:right] = (rgb[:, top - y0:bottom - y0, left - x0:right - x0].permute(1, 2, 0)
+ .clamp(0, 1) * 255).round().to(torch.uint8)
+ return frame
diff --git a/handdraw/v181d_palette.py b/handdraw/v181d_palette.py
new file mode 100644
index 0000000..4125b1d
--- /dev/null
+++ b/handdraw/v181d_palette.py
@@ -0,0 +1,40 @@
+import cv2
+import numpy as np
+from scipy import ndimage
+from skimage.measure import label
+
+
+def _palette_regions(image, region_ids, *, visible_mask=None):
+ ids = np.asarray(region_ids, np.int32).copy()
+ if not np.any(ids > 0):
+ ids[:] = 1
+ elif np.any(ids == 0):
+ nearest = ndimage.distance_transform_edt(ids == 0, return_distances=False,
+ return_indices=True)
+ ids = ids[nearest[0], nearest[1]]
+ if visible_mask is not None:
+ ids[~visible_mask] = 0
+ count = int(ids.max()) + 1
+ areas = np.bincount(ids.ravel(), minlength=count)
+ active = np.flatnonzero(areas)
+ active = active[active > 0]
+ means = np.column_stack([
+ np.bincount(ids.ravel(), weights=image[:, :, channel].ravel(), minlength=count)[active]
+ / areas[active] for channel in range(3)])
+ lab = cv2.cvtColor(np.rint(means).astype(np.uint8)[None], cv2.COLOR_RGB2LAB)[0].astype(np.float32)
+ colors = min(8, len(np.unique(lab, axis=0)))
+ if colors == 1:
+ assignments = np.zeros(len(active), np.int32)
+ else:
+ # Weight the palette by image area, not the number of fragmented regions.
+ repeats = np.maximum(1, np.rint(areas[active] / areas[active].sum() * 2048).astype(int))
+ samples = np.repeat(lab, repeats, axis=0)
+ _, _, centers = cv2.kmeans(samples, colors, None,
+ (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, .5),
+ 3, cv2.KMEANS_PP_CENTERS)
+ assignments = np.argmin(((lab[:, None] - centers[None]) ** 2).sum(axis=2), axis=1)
+ lookup = np.zeros(count, np.int32)
+ lookup[active] = assignments + 1
+ palette = lookup[ids]
+ patches = label(palette, connectivity=2).astype(np.int32)
+ return palette, patches
diff --git a/handdraw/v181d_plan.py b/handdraw/v181d_plan.py
new file mode 100644
index 0000000..b548c56
--- /dev/null
+++ b/handdraw/v181d_plan.py
@@ -0,0 +1,117 @@
+"""V1.8.1.d source routing, normalized independently of narration duration."""
+from __future__ import annotations
+
+from contextlib import nullcontext
+import cv2
+import numpy as np
+from scipy import ndimage
+
+from .grid import _grid_ink, _KMEANS_LOCK
+from .v181d_cluster import cluster_backend, cluster_lab
+from .v181d_subject_fill import build_subject_fill_plan
+
+V181D_PLAN_VERSION = "v181d-subject-local-eased-torch-clean-v8-d-4"
+V181E_PLAN_VERSION = "v181e-subject-native-background-clusters-1"
+
+
+def build_v181d_ink_map(image_rgb, *, block_size=15, threshold_c=10, clahe_clip=2.,
+ bilateral_first=(7, 12, 3), bilateral_second=(5, 12, 2),
+ clahe_tiles=8, coarse_c=(5, 4), support_dilate=3,
+ component_area=4, component_span=8):
+ """Approved native D: edge-preserving contrast and multiscale speck cleanup."""
+ image_rgb = np.asarray(image_rgb, dtype=np.uint8)
+ if image_rgb.ndim != 3 or image_rgb.shape[2] != 3 or not image_rgb.size:
+ raise ValueError("A nonempty RGB image is required for D ink detection.")
+ gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)
+ gray = cv2.bilateralFilter(gray, int(bilateral_first[0]), *bilateral_first[1:])
+ gray = cv2.createCLAHE(clipLimit=clahe_clip, tileGridSize=(int(clahe_tiles), int(clahe_tiles))).apply(gray)
+ gray = cv2.bilateralFilter(gray, int(bilateral_second[0]), *bilateral_second[1:])
+ ink = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
+ cv2.THRESH_BINARY, block_size, threshold_c) == 0
+ h, w = gray.shape
+ support = np.zeros((h, w), bool)
+ for factor, offset in [(0.5, coarse_c[0]), (1 / 3, coarse_c[1])]:
+ reduced = cv2.resize(gray, (max(1, round(w * factor)), max(1, round(h * factor))),
+ interpolation=cv2.INTER_AREA)
+ coarse = cv2.adaptiveThreshold(reduced, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
+ cv2.THRESH_BINARY, block_size, offset) == 0
+ restored = cv2.resize(coarse.astype(np.uint8), (w, h), interpolation=cv2.INTER_NEAREST)
+ support |= cv2.dilate(restored, np.ones((int(support_dilate), int(support_dilate)), np.uint8)) > 0
+ _, labels, stats, _ = cv2.connectedComponentsWithStats((ink & support).astype(np.uint8),
+ connectivity=8)
+ scale = h / 720.0
+ keep = (stats[:, cv2.CC_STAT_AREA] >= max(2, round(component_area * scale * scale))) | (
+ np.maximum(stats[:, cv2.CC_STAT_WIDTH], stats[:, cv2.CC_STAT_HEIGHT]) >= max(3, round(component_span * scale))
+ )
+ keep[0] = False
+ return np.where(keep[labels], 0, 255).astype(np.uint8)
+
+
+def _region_ids(image, ink, visible, seed=42, *, backend="auto", diagnostics=None, benchmark=None,
+ palette_colors=16, min_region_area=80, barrier_size=3):
+ with benchmark.measure("palette_preprocess") if benchmark is not None else nullcontext():
+ lab = cv2.cvtColor(cv2.bilateralFilter(image, 9, 75, 75), cv2.COLOR_RGB2LAB)
+ with benchmark.measure("palette_cluster", cuda=cluster_backend(backend) == "torch-cuda") if benchmark else nullcontext():
+ labels, count = cluster_lab(lab[visible], seed, backend=backend, diagnostics=diagnostics, color_cap=palette_colors)
+ with benchmark.measure("palette_components") if benchmark is not None else nullcontext():
+ colors = np.full(ink.shape, -1, np.int32)
+ colors[visible] = labels
+ barrier = cv2.dilate(ink.astype(np.uint8), np.ones((int(barrier_size), int(barrier_size)), np.uint8)) > 0
+ ids = np.zeros(ink.shape, np.int32)
+ next_id = 1
+ for color in range(count):
+ components, total = ndimage.label((colors == color) & ~barrier)
+ areas = np.bincount(components.ravel())
+ kept = np.flatnonzero(areas >= min_region_area)
+ kept = kept[kept > 0]
+ lookup = np.zeros(total + 1, np.int32)
+ lookup[kept] = np.arange(next_id, next_id + len(kept))
+ selected = lookup[components]
+ ids[selected > 0] = selected[selected > 0]
+ next_id += len(kept)
+ return ids
+
+
+def build_v181d_plan(image_rgb, seed=42, *, subject_mask, visible_mask=None, cluster_backend="auto", benchmark=None,
+ background_clusters=False, grid_edge=10, clean_ink=True, ink_options=None,
+ palette_colors=16, min_region_area=80, barrier_size=3, fill_options=None, path_samples=4097):
+ image, subject = np.asarray(image_rgb), np.asarray(subject_mask)
+ if image.dtype != np.uint8 or image.ndim != 3 or image.shape[2] != 3 or min(image.shape[:2]) < 1:
+ raise ValueError("V1.8.1.d requires a nonempty uint8 RGB image.")
+ h, w = image.shape[:2]
+ visible = np.ones((h, w), bool) if visible_mask is None else np.asarray(visible_mask, dtype=bool)
+ if subject.shape != (h, w) or subject.dtype != np.bool_:
+ raise ValueError("subject_mask must be a bool mask matching the image.")
+ if visible.shape != (h, w) or not visible.any():
+ raise ValueError("visible_mask must match the image and contain pixels.")
+ with benchmark.measure("ink_grid") if benchmark else nullcontext():
+ options = ink_options or {}
+ ink, structure, ink_path = _grid_ink(image, visible, edge=grid_edge,
+ block_size=options.get('block_size', 15), threshold_c=options.get('threshold_c', 10),
+ ink_map=build_v181d_ink_map(image, **options) if clean_ink else None)
+ ink_end = .45 if ink_path else 0.
+ initial = np.asarray(ink_path[-1][1:] if ink_path else [(w - 1) / 2, (h - 1) / 2])
+ info = {}
+ with _KMEANS_LOCK:
+ cv2.setRNGSeed(int(seed) & 0x7fffffff)
+ ids = _region_ids(image, ink, visible, seed, backend=cluster_backend, diagnostics=info, benchmark=benchmark,
+ palette_colors=palette_colors, min_region_area=min_region_area, barrier_size=barrier_size)
+ timing, _, regions, _, tips, lift = build_subject_fill_plan(
+ image, ids, 0., 1., 30, initial, path_samples,
+ subject_mask=subject, visible_mask=visible, diagnostics=info, benchmark=benchmark,
+ **({"background_clusters": True} if background_clusters else {}), **(fill_options or {}))
+ path = np.column_stack((ink_end + np.linspace(0, 1, len(tips)) * (1 - ink_end), tips)).astype(np.float32)
+ if ink_path:
+ before = np.asarray(ink_path, np.float32)
+ before[:, 0] *= ink_end
+ before = before[:-1] if len(before) > 1 else before
+ path = np.vstack((before, path))
+ lift = np.concatenate((np.zeros(len(before)), lift))
+ color = np.full((h, w), 255, np.uint8)
+ color[visible] = np.clip(np.round(timing[visible] * 254), 0, 254).astype(np.uint8)
+ return {"structure_time": structure, "fill_time": np.full((h, w), 255, np.uint8),
+ "color_reveal_time": color, "color_contact_time": timing,
+ "pen_path": path, "pen_lift": lift.astype(np.float32), "ink_end": np.float32(ink_end),
+ "metadata": {"version": V181E_PLAN_VERSION if background_clusters else V181D_PLAN_VERSION,
+ "grid_cells": len(ink_path),
+ "palette_regions": regions, "subject_pixels": int((subject & visible).sum()), **info}}
diff --git a/handdraw/v181d_subject_fill.py b/handdraw/v181d_subject_fill.py
new file mode 100644
index 0000000..5e83437
--- /dev/null
+++ b/handdraw/v181d_subject_fill.py
@@ -0,0 +1,347 @@
+"""D-only local palette sweeps, with synchronized eased contact and pen-up lift."""
+import math
+from contextlib import nullcontext
+
+import numpy as np
+from skimage.measure import label
+
+from .v181d_palette import _palette_regions
+
+
+def _greedy_route(endpoints, initial_tip):
+ remaining = np.ones(len(endpoints), bool)
+ tip = initial_tip.copy()
+ route = []
+ while remaining.any():
+ score = np.linalg.norm(endpoints - tip, axis=2) + .08 * np.maximum(tip[1] - endpoints[:, :, 1], 0)
+ score[~remaining] = np.inf
+ index, reverse = np.unravel_index(np.argmin(score), score.shape)
+ remaining[index] = False
+ route.append((int(index), int(reverse)))
+ tip = endpoints[index, 1 - reverse]
+ return route
+
+
+def _route(endpoints, initial_tip, exit_points=None):
+ """Compare greedy and three-choice lookahead, then refine orientations/2-opt."""
+ n = len(endpoints)
+ if not n:
+ return []
+ distance = np.linalg.norm(endpoints[:, None, :, None] -
+ endpoints[None, :, None, :], axis=-1)
+ exit_cost = (np.linalg.norm(endpoints[:, :, None] - exit_points, axis=-1).min(axis=2)
+ if exit_points is not None and len(exit_points) else np.zeros((n, 2)))
+
+ def orient(order):
+ costs = np.linalg.norm(endpoints[order[0]] - initial_tip, axis=1)
+ parents = []
+ for previous, current in zip(order, order[1:]):
+ options = costs[:, None] + distance[previous, current, ::-1, :]
+ parents.append(options.argmin(axis=0))
+ costs = options.min(axis=0)
+ costs += exit_cost[order[-1], ::-1]
+ reverse = int(costs.argmin())
+ route = [(order[-1], reverse)]
+ for index, parent in zip(order[-2::-1], parents[::-1]):
+ reverse = int(parent[reverse])
+ route.append((index, reverse))
+ return route[::-1], float(costs.min())
+
+ orders = []
+ for lookahead in (False, True):
+ remaining = np.ones(n, bool)
+ tip = initial_tip.copy()
+ order = []
+ while remaining.any():
+ costs = np.linalg.norm(endpoints - tip, axis=2)
+ score = costs + .08 * np.maximum(tip[1] - endpoints[:, :, 1], 0)
+ score[~remaining] = np.inf
+ nearby = np.argsort(score.min(axis=1))[:min(3, int(remaining.sum()))]
+ candidates = (nearby[:, None] * 2 + np.arange(2)).ravel()
+ index, reverse = np.unravel_index(np.argmin(score), score.shape)
+ if lookahead and remaining.sum() > 1:
+ choices = []
+ for flat in candidates:
+ first, direction = np.unravel_index(flat, score.shape)
+ next_cost = distance[first, :, 1 - direction, :].copy()
+ next_cost[~remaining] = np.inf
+ next_cost[first] = np.inf
+ nearby_next = np.argsort(next_cost.min(axis=1))[:min(3, int(remaining.sum()) - 1)]
+ next_candidates = (nearby_next[:, None] * 2 + np.arange(2)).ravel()
+ best = np.inf
+ for next_flat in next_candidates:
+ second, second_direction = np.unravel_index(next_flat, next_cost.shape)
+ if remaining.sum() > 2:
+ final_cost = distance[second, :, 1 - second_direction, :].copy()
+ final_cost[~remaining] = np.inf
+ final_cost[[first, second]] = np.inf
+ tail = float(final_cost.min())
+ else:
+ tail = exit_cost[second, 1 - second_direction]
+ best = min(best, next_cost[second, second_direction] + tail)
+ choices.append((costs[first, direction] + best, score[first, direction],
+ int(first), int(direction)))
+ _, _, index, reverse = min(choices)
+ order.append(int(index))
+ remaining[index] = False
+ tip = endpoints[index, 1 - reverse]
+ orders.append(orient(order))
+ route, cost = min(orders, key=lambda item: item[1])
+ # Reversing a block and its stroke directions preserves internal transitions.
+ # Bound both the search window and improvement passes.
+ for _ in range(2):
+ best, change = 0., None
+ for left in range(n):
+ previous = initial_tip if left == 0 else endpoints[route[left - 1][0], 1 - route[left - 1][1]]
+ first, first_direction = route[left]
+ for right in range(left + 1, min(n, left + 13)):
+ last, last_direction = route[right]
+ old = np.linalg.norm(previous - endpoints[first, first_direction])
+ new = np.linalg.norm(previous - endpoints[last, 1 - last_direction])
+ if right + 1 < n:
+ after, after_direction = route[right + 1]
+ old += distance[last, after, 1 - last_direction, after_direction]
+ new += distance[first, after, first_direction, after_direction]
+ else:
+ old += exit_cost[last, 1 - last_direction]
+ new += exit_cost[first, first_direction]
+ if old - new > best + 1e-9:
+ best, change = float(old - new), (left, right)
+ if change is None:
+ break
+ left, right = change
+ route[left:right + 1] = [(index, 1 - reverse) for index, reverse in route[left:right + 1][::-1]]
+ route, cost = orient([index for index, _ in route])
+ return route
+
+
+def _compact_route(endpoints, order, initial_tip, boundaries):
+ """Orient across colors and reverse bounded blocks within each color only."""
+ n = len(order)
+ if not n:
+ return []
+ distance = np.linalg.norm(endpoints[:, None, :, None] -
+ endpoints[None, :, None, :], axis=-1)
+ entry = np.linalg.norm(endpoints - initial_tip, axis=2)
+
+ def orient(order):
+ costs = entry[order[0]].copy()
+ parents = []
+ for previous, current in zip(order, order[1:]):
+ options = costs[:, None] + distance[previous, current, ::-1, :]
+ parents.append(options.argmin(axis=0))
+ costs = options.min(axis=0)
+ reverse = int(costs.argmin())
+ route = [(order[-1], reverse)]
+ for index, parent in zip(order[-2::-1], parents[::-1]):
+ reverse = int(parent[reverse])
+ route.append((index, reverse))
+ return route[::-1]
+
+ route = orient(order)
+ for _ in range(12):
+ best, change = 0., None
+ for low, high in boundaries:
+ for left in range(low, high):
+ first, first_direction = route[left]
+ if left:
+ before, before_direction = route[left - 1]
+ entering = distance[before, :, 1 - before_direction, :]
+ else:
+ entering = entry
+ for right in range(left + 1, min(high, left + 25)):
+ last, last_direction = route[right]
+ old = entering[first, first_direction]
+ new = entering[last, 1 - last_direction]
+ if right + 1 < n:
+ after, after_direction = route[right + 1]
+ old += distance[last, after, 1 - last_direction, after_direction]
+ new += distance[first, after, first_direction, after_direction]
+ if old - new > best + 1e-9:
+ best, change = float(old - new), (left, right)
+ if change is None:
+ break
+ left, right = change
+ order = [index for index, _ in route]
+ order[left:right + 1] = order[left:right + 1][::-1]
+ route = orient(order)
+ return route
+
+
+def _merge_short(pending, u, v, brush_width, cosine, sine):
+ """Combine only short neighboring spans that fit the original brush corridor."""
+ active = list(pending)
+ for index in range(len(active)):
+ if active[index] is None:
+ continue
+ selected, begin, end, v0, v1 = active[index]
+ if v1 - v0 > brush_width * .65:
+ continue
+ for other in range(index + 1, len(active)):
+ item = active[other]
+ if item is None or item[4] - item[3] > brush_width * .65:
+ continue
+ low, high = min(v0, item[3]), max(v1, item[4])
+ gap = max(v0 - item[4], item[3] - v1, 0.)
+ endpoint_gap = np.linalg.norm(np.array([begin, end])[:, None] - np.array([item[1], item[2]]), axis=2).min()
+ if gap > brush_width * .75 or high - low > brush_width * 1.5 or endpoint_gap > brush_width:
+ continue
+ combined = np.concatenate((selected, item[0]))
+ low_u, high_u = float(u[combined].min()), float(u[combined].max())
+ if high_u - low_u > brush_width:
+ continue
+ lane_u = (low_u + high_u) * .5
+ begin = np.array([lane_u * cosine - low * sine, lane_u * sine + low * cosine])
+ end = np.array([lane_u * cosine - high * sine, lane_u * sine + high * cosine])
+ selected, v0, v1 = combined, low, high
+ active[index] = (selected, begin, end, v0, v1)
+ active[other] = None
+ if v1 - v0 > brush_width * .65:
+ break
+ return [item for item in active if item is not None]
+
+
+def build_subject_fill_plan(image, region_ids, start, duration, fps, initial_tip, frame_count,
+ *, subject_mask=None, visible_mask=None, diagnostics=None, benchmark=None,
+ background_clusters=False, brush_min=24., brush_max=92., brush_ratio=.12,
+ stroke_angle=12., travel_speed_ratio=1.5):
+ with benchmark.measure("stroke_groups") if benchmark is not None else nullcontext():
+ palette, patches = _palette_regions(image, region_ids, visible_mask=visible_mask)
+ h, w = palette.shape
+ visible = np.ones((h, w), bool) if visible_mask is None else np.asarray(visible_mask, dtype=bool)
+ if visible.shape != (h, w) or not visible.any():
+ raise ValueError("visible_mask must match the image and contain pixels.")
+ if subject_mask is not None:
+ subject_mask = np.asarray(subject_mask)
+ if subject_mask.shape != (h, w) or subject_mask.dtype != np.bool_:
+ raise ValueError("subject_mask must be a bool mask matching the image.")
+ patches = label(palette + (~subject_mask) * int(palette.max()),
+ connectivity=2).astype(np.int32)
+ patches[~visible] = 0
+ if duration <= 0 or frame_count < 1 or not np.isfinite([start, duration]).all():
+ raise ValueError("duration and frame_count must be positive and times finite.")
+ tip = np.asarray(initial_tip, float)
+ if tip.shape != (2,) or not np.isfinite(tip).all():
+ raise ValueError("initial_tip must be a finite pair.")
+ brush_width = max(brush_min, min(brush_max, min(h, w) * brush_ratio))
+ cosine, sine = math.cos(math.radians(stroke_angle)), math.sin(math.radians(stroke_angle))
+ groups = []
+ phases = [subject_mask & visible, ~subject_mask & visible] if subject_mask is not None else [visible]
+ for phase_index, phase in enumerate(phases):
+ ys, xs = np.where(phase)
+ if not len(ys):
+ continue
+ # Choose the first substantial occurrence of each color from the top.
+ colors = sorted(np.unique(palette[phase]), key=lambda color: (
+ np.percentile(ys[palette[ys, xs] == color], 5), int(color)))
+ for color in colors:
+ ys, xs = np.where(phase & (palette == color))
+ u, v = xs * cosine + ys * sine, -xs * sine + ys * cosine
+ lanes = np.floor((u - u.min()) / brush_width).astype(np.int32)
+ pending = []
+ # A shared lane grid merges nearby fragmented patches of this color.
+ # Only short empty gaps can be swept through; distant islands split.
+ for lane in np.unique(lanes):
+ indexes = np.flatnonzero(lanes == lane)
+ order = indexes[np.argsort(v[indexes])]
+ breaks = np.flatnonzero(np.diff(v[order]) > brush_width * .75) + 1
+ for selected in np.split(order, breaks):
+ lane_u = (u[selected].min() + u[selected].max()) * .5
+ v0, v1 = float(v[selected[0]]), float(v[selected[-1]])
+ begin = np.array([lane_u * cosine - v0 * sine,
+ lane_u * sine + v0 * cosine])
+ end = np.array([lane_u * cosine - v1 * sine,
+ lane_u * sine + v1 * cosine])
+ pending.append((selected, begin, end, v0, v1))
+ pending = _merge_short(pending, u, v, brush_width, cosine, sine)
+ groups.append((phase_index, ys, xs, v, pending))
+ with benchmark.measure("route_order") if benchmark is not None else nullcontext():
+ candidates = []
+ # Check actual complete travel: a nearest next-color endpoint is only a hint.
+ for mode in ("greedy", "local", "exit"):
+ tip = np.asarray(initial_tip, float).copy()
+ strokes = []
+ for group_index, (phase_index, ys, xs, v, pending) in enumerate(groups):
+ endpoints = np.array([[item[1], item[2]] for item in pending])
+ exit_points = (np.array([[item[1], item[2]] for item in groups[group_index + 1][4]]).reshape(-1, 2)
+ if mode == "exit" and group_index + 1 < len(groups) else None)
+ route = _greedy_route(endpoints, tip) if mode == "greedy" else _route(endpoints, tip, exit_points)
+ for index, reverse in route:
+ selected, begin, end, v0, v1 = pending[index]
+ if reverse:
+ begin, end, v0, v1 = end, begin, v1, v0
+ travel = float(np.linalg.norm(begin - tip))
+ length = max(abs(v1 - v0), brush_width * .35)
+ progress = ((v[selected] - v0) / (v1 - v0) if abs(v1 - v0) > 1e-6
+ else np.full(len(selected), .5))
+ strokes.append((ys[selected], xs[selected], progress, begin, end,
+ travel, length, tip.copy()))
+ tip = end
+ candidates.append(strokes)
+ boundaries, offset = [], 0
+ for group in groups:
+ count = len(group[4])
+ boundaries.append((offset, offset + count))
+ offset += count
+ for original in candidates[:]:
+ endpoints = np.array([[stroke[3], stroke[4]] for stroke in original])
+ route = _compact_route(endpoints, list(range(len(original))),
+ np.asarray(initial_tip, float), boundaries)
+ tip = np.asarray(initial_tip, float).copy()
+ refined = []
+ for index, reverse in route:
+ ys, xs, progress, begin, end, _, length, _ = original[index]
+ if reverse:
+ begin, end, progress = end, begin, 1 - progress
+ travel = float(np.linalg.norm(begin - tip))
+ refined.append((ys, xs, progress, begin, end, travel, length, tip.copy()))
+ tip = end
+ candidates.append(refined)
+ strokes = min(candidates, key=lambda candidate: sum(stroke[5] for stroke in candidate))
+ if diagnostics is not None:
+ diagnostics.update(brush_strokes=len(strokes),
+ travel_pixels=sum(stroke[5] for stroke in strokes),
+ greedy_travel_pixels=sum(stroke[5] for stroke in candidates[0]))
+
+ with benchmark.measure("contact_timeline") if benchmark is not None else nullcontext():
+ # Both nib position and opaque pixel contact use this one eased timeline.
+ weights = np.array([[max(stroke[5] / travel_speed_ratio, brush_width * .04), stroke[6]]
+ for stroke in strokes], float)
+ durations = duration * weights / weights.sum()
+ timing = np.full((h, w), np.inf, np.float32)
+ frame_times = np.linspace(start, start + duration, frame_count)
+ tips = np.broadcast_to(np.asarray(initial_tip, float), (frame_count, 2)).copy()
+ lift = np.zeros(frame_count, float)
+ current = start
+ for stroke, (travel_duration, paint_duration) in zip(strokes, durations):
+ ys, xs, progress, begin, end, travel, length, previous = stroke
+ paint_start = current + travel_duration
+ paint_end = paint_start + paint_duration
+ travel_frames = (frame_times >= current) & (frame_times < paint_start)
+ q = np.clip((frame_times[travel_frames] - current) / travel_duration, 0, 1)
+ ease = .5 - .5 * np.cos(np.pi * q)
+ tips[travel_frames] = previous + ease[:, None] * (begin - previous)
+ lift[travel_frames] = np.sin(np.pi * q)
+ paint_frames = (frame_times >= paint_start) & (frame_times <= paint_end + 1e-9)
+ q = np.clip((frame_times[paint_frames] - paint_start) / paint_duration, 0, 1)
+ ease = .5 - .5 * np.cos(np.pi * q)
+ tips[paint_frames] = begin + ease[:, None] * (end - begin)
+ # Invert position easing: contact occurs exactly when the nib reaches v.
+ contact = np.arccos(1 - 2 * np.clip(progress, 0, 1)) / np.pi
+ timing[ys, xs] = paint_start + contact * paint_duration
+ current = paint_end
+ end_time = np.float32(start + duration)
+ if float(end_time) > start + duration:
+ end_time = np.nextafter(end_time, np.float32(-np.inf))
+ np.minimum(timing, end_time, out=timing)
+ timing[~visible] = np.inf
+ tips[:, 0] = np.clip(tips[:, 0], 0, w - 1)
+ tips[:, 1] = np.clip(tips[:, 1], 0, h - 1)
+ plan = timing, patches, int(patches.max()), 0.0, tips, lift
+ if background_clusters:
+ from .v181e_background_fill import reschedule_background
+ with benchmark.measure("background_reschedule") if benchmark is not None else nullcontext():
+ plan = reschedule_background(plan, strokes, durations, region_ids, subject_mask,
+ start, duration, initial_tip, brush_width)
+ plan[0][~visible] = np.inf
+ return plan
diff --git a/handdraw/v181e_background_fill.py b/handdraw/v181e_background_fill.py
new file mode 100644
index 0000000..9349cc7
--- /dev/null
+++ b/handdraw/v181e_background_fill.py
@@ -0,0 +1,91 @@
+"""E-only background tail: finish edge-bounded clusters from left to right."""
+import numpy as np
+from scipy import ndimage
+from skimage.measure import label
+
+from .v181d_subject_fill import _greedy_route
+
+
+def _order_background(strokes, region_ids, foreground, initial_tip, brush_width):
+ # Keep raw edge IDs: palette IDs can merge neighboring regions of the same color.
+ ids = np.asarray(region_ids, np.int32).copy()
+ if not np.any(ids > 0):
+ ids[:] = 1
+ elif np.any(ids == 0):
+ nearest = ndimage.distance_transform_edt(ids == 0, return_distances=False, return_indices=True)
+ ids = ids[nearest[0], nearest[1]]
+ clusters = label(np.where(foreground, 0, ids), connectivity=2).astype(np.int32)
+ groups = {}
+ for ys, xs, progress, begin, end, _, _, _ in strokes:
+ labels = clusters[ys, xs]
+ for rid in np.unique(labels):
+ selected = labels == rid
+ p = progress[selected]
+ low, high = float(p.min()), float(p.max())
+ a = begin + low * (end - begin)
+ b = begin + high * (end - begin)
+ contact = (p - low) / (high - low) if high - low > 1e-12 else np.full(len(p), .5)
+ length = max(float(np.linalg.norm(b - a)), brush_width * .35)
+ groups.setdefault(int(rid), []).append((ys[selected], xs[selected], contact, a, b, 0., length, a))
+ centers = {rid: sum(float(s[1].sum()) for s in group) / sum(len(s[1]) for s in group)
+ for rid, group in groups.items()}
+ ordered = []
+ tip = np.asarray(initial_tip, float)
+ for rid in sorted(groups, key=lambda rid: (centers[rid], rid)):
+ group = groups[rid]
+ endpoints = np.array([[s[3], s[4]] for s in group])
+ for index, reverse in _greedy_route(endpoints, tip):
+ ys, xs, progress, begin, end, _, length, _ = group[index]
+ if reverse:
+ begin, end, progress = end, begin, 1 - progress
+ ordered.append((ys, xs, progress, begin, end,
+ float(np.linalg.norm(begin - tip)), length, tip.copy()))
+ tip = end
+ return ordered
+
+
+def reschedule_background(plan, strokes, native_durations, region_ids, subject_mask,
+ start, duration, initial_tip, brush_width):
+ foreground = subject_mask if subject_mask is not None else np.zeros(region_ids.shape, bool)
+ count = sum(bool(foreground[s[0][0], s[1][0]]) for s in strokes)
+ background_start = float(start + native_durations[:count].sum())
+ current_tip = strokes[count - 1][4].copy() if count else np.asarray(initial_tip, float)
+ background = _order_background(strokes[count:], region_ids, foreground, current_tip, brush_width)
+ if not background:
+ return plan
+
+ # The native subject timeline is already final. Only overwrite the background tail.
+ timing, patches, regions, fade, tips, lift = plan
+ ordered = []
+ for ys, xs, progress, begin, end, _, length, _ in background:
+ if np.linalg.norm(end - current_tip) < np.linalg.norm(begin - current_tip):
+ begin, end, progress = end, begin, 1 - progress
+ travel = float(np.linalg.norm(begin - current_tip))
+ ordered.append((ys, xs, progress, begin, end, travel, length, current_tip.copy()))
+ current_tip = end
+ weights = np.array([[max(s[5] / 1.5, brush_width * .04), s[6]] for s in ordered])
+ durations = (start + duration - background_start) * weights / weights.sum()
+ frame_times = np.linspace(start, start + duration, len(tips))
+ current = background_start
+ for stroke, (travel_duration, paint_duration) in zip(ordered, durations):
+ ys, xs, progress, begin, end, _, _, previous = stroke
+ paint_start = current + travel_duration
+ paint_end = paint_start + paint_duration
+ travelling = (frame_times >= current) & (frame_times < paint_start)
+ q = np.clip((frame_times[travelling] - current) / travel_duration, 0, 1)
+ tips[travelling] = previous + (.5 - .5 * np.cos(np.pi * q))[:, None] * (begin - previous)
+ lift[travelling] = np.sin(np.pi * q)
+ painting = (frame_times >= paint_start) & (frame_times <= paint_end + 1e-9)
+ q = np.clip((frame_times[painting] - paint_start) / paint_duration, 0, 1)
+ tips[painting] = begin + (.5 - .5 * np.cos(np.pi * q))[:, None] * (end - begin)
+ lift[painting] = 0
+ contact = np.arccos(1 - 2 * np.clip(progress, 0, 1)) / np.pi
+ timing[ys, xs] = paint_start + contact * paint_duration
+ current = paint_end
+ end_time = np.float32(start + duration)
+ if float(end_time) > start + duration:
+ end_time = np.nextafter(end_time, np.float32(-np.inf))
+ timing[~foreground] = np.minimum(timing[~foreground], end_time)
+ tips[:, 0] = np.clip(tips[:, 0], 0, timing.shape[1] - 1)
+ tips[:, 1] = np.clip(tips[:, 1], 0, timing.shape[0] - 1)
+ return timing, patches, regions, fade, tips, lift
diff --git a/requirements-dev.txt b/requirements-dev.txt
new file mode 100644
index 0000000..0765da3
--- /dev/null
+++ b/requirements-dev.txt
@@ -0,0 +1,2 @@
+-r requirements.txt
+pytest>=8,<10
diff --git a/requirements-gpu.txt b/requirements-gpu.txt
new file mode 100644
index 0000000..13c9cf5
--- /dev/null
+++ b/requirements-gpu.txt
@@ -0,0 +1,2 @@
+-r requirements.txt
+PyNvVideoCodec>=2.0
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..cf9f16a
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,9 @@
+gradio==6.29.1
+torch==2.8.0
+torchvision==0.23.0
+numpy>=2.4,<2.5
+opencv-python>=5.0,<6
+scipy>=1.17,<1.18
+scikit-image>=0.26,<0.27
+safetensors>=0.8,<0.9
+Pillow>=11,<13
diff --git a/scripts/download_model.py b/scripts/download_model.py
new file mode 100644
index 0000000..1426b63
--- /dev/null
+++ b/scripts/download_model.py
@@ -0,0 +1,72 @@
+"""Explicit, verified download of the pinned ISNet checkpoint (stdlib only)."""
+
+import argparse
+import hashlib
+from pathlib import Path
+import tempfile
+import time
+import urllib.request
+
+MODEL_URL = 'https://huggingface.co/skytnt/anime-seg/resolve/493cb60893f47441b26ec4fb9a306bce9e342982/model.safetensors'
+EXPECTED_SIZE = 203982056
+EXPECTED_SHA256 = '3351563ba8b61a01a66bacb79cf36aabce2da62d88b7606a719f573f23fe5d3e'
+DEFAULT_PATH = Path(__file__).resolve().parents[1] / 'assets' / 'v181d' / 'model.safetensors'
+CHUNK_SIZE = 1024 * 1024
+
+
+def verify_model(path):
+ if not path.is_file() or path.stat().st_size != EXPECTED_SIZE:
+ return False
+ digest = hashlib.sha256()
+ with path.open('rb') as source:
+ for chunk in iter(lambda: source.read(CHUNK_SIZE), b''):
+ digest.update(chunk)
+ return digest.hexdigest() == EXPECTED_SHA256
+
+
+def download_model(destination=DEFAULT_PATH):
+ destination = Path(destination)
+ if verify_model(destination):
+ return destination
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ temporary = None
+ deadline = time.monotonic() + 600
+ try:
+ with tempfile.NamedTemporaryFile(dir=destination.parent, prefix=destination.name + '.',
+ suffix='.part', delete=False) as target:
+ temporary = Path(target.name)
+ digest, size = hashlib.sha256(), 0
+ request = urllib.request.Request(MODEL_URL, headers={'User-Agent': 'Handdraw-model-downloader'})
+ with urllib.request.urlopen(request, timeout=30) as source:
+ while True:
+ if time.monotonic() >= deadline:
+ raise TimeoutError('Model download exceeded 10 minutes')
+ chunk = source.read(CHUNK_SIZE)
+ if not chunk:
+ break
+ size += len(chunk)
+ if size > EXPECTED_SIZE:
+ raise ValueError('Model exceeds the expected size')
+ digest.update(chunk)
+ target.write(chunk)
+ if size != EXPECTED_SIZE or digest.hexdigest() != EXPECTED_SHA256:
+ raise ValueError('Model size or SHA256 mismatch')
+ temporary.replace(destination)
+ return destination
+ finally:
+ if temporary is not None:
+ temporary.unlink(missing_ok=True)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--output', type=Path, default=DEFAULT_PATH)
+ args = parser.parse_args()
+ try:
+ print(download_model(args.output))
+ except (OSError, ValueError) as exc:
+ parser.exit(1, f'Model download failed: {exc}\n')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/render_readme_demos.py b/scripts/render_readme_demos.py
new file mode 100644
index 0000000..b82d544
--- /dev/null
+++ b/scripts/render_readme_demos.py
@@ -0,0 +1,55 @@
+"""Render three supplied images and create compact, looping README previews."""
+from pathlib import Path
+import argparse
+import subprocess
+import sys
+
+import numpy as np
+from PIL import Image
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from handdraw.render import ffmpeg_binary, render_video
+from handdraw.settings import Settings
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--mode', choices=('d', 'e'), default='e')
+ parser.add_argument('images', nargs=3, type=Path)
+ args = parser.parse_args()
+ sources = args.images
+ if len(sources) != 3 or not all(path.is_file() for path in sources):
+ raise SystemExit('Supply exactly three existing input images.')
+ root = Path(__file__).resolve().parents[1]
+ previews = root / 'docs' / 'media'
+ previews.mkdir(parents=True, exist_ok=True)
+ for index, source in enumerate(sources, 1):
+ print(f'Demo {index}: {source.name}', flush=True)
+ with Image.open(source) as image:
+ rgb = np.asarray(image.convert('RGB'))
+ image.convert('RGB').save(previews / f'source-{index:02d}.png')
+ video, report = render_video(
+ rgb, Settings(mode=args.mode, duration=8, width=1280, height=720, fps=50),
+ output_dir=root / 'outputs' / 'readme-demos')
+ suffix = '-d' if args.mode == 'd' else ''
+ gif = previews / f'demo-{index:02d}{suffix}.gif'
+ subprocess.run([
+ ffmpeg_binary(), '-hide_banner', '-loglevel', 'error', '-y', '-i', str(video),
+ '-filter_complex',
+ '[0:v]fps=50,scale=640:-2:flags=lanczos,split[a][b];'
+ '[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=sierra2_4a',
+ '-loop', '0', str(gif),
+ ], check=True)
+ with Image.open(gif) as animation:
+ assert animation.is_animated and animation.n_frames > 1
+ elapsed = 0
+ for frame in range(animation.n_frames):
+ animation.seek(frame)
+ elapsed += animation.info.get('duration', 0)
+ assert abs(elapsed - 8000) < 150, elapsed
+ print(f'OK: {video}\nGIF: {gif} ({gif.stat().st_size / 1048576:.2f} MiB)'
+ f'\nRender: {report["wall_seconds"]:.1f}s', flush=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/start.bat b/start.bat
new file mode 100644
index 0000000..4c75913
--- /dev/null
+++ b/start.bat
@@ -0,0 +1,8 @@
+@echo off
+setlocal
+if not exist "%~dp0.venv\Scripts\pythonw.exe" (
+ echo Missing .venv. Follow the installation steps in README.md.
+ exit /b 1
+)
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0start.ps1" %*
+exit /b %errorlevel%
diff --git a/start.ps1 b/start.ps1
new file mode 100644
index 0000000..0169616
--- /dev/null
+++ b/start.ps1
@@ -0,0 +1,9 @@
+param([ValidateRange(1, 65535)][int]$Port = 7860)
+$ErrorActionPreference = 'Stop'
+$python = Join-Path $PSScriptRoot '.venv\Scripts\pythonw.exe'
+$app = Join-Path $PSScriptRoot 'app.py'
+if (-not (Test-Path -LiteralPath $python -PathType Leaf)) {
+ throw 'Missing .venv. Follow the installation steps in README.md.'
+}
+$process = Start-Process -FilePath $python -ArgumentList @(('"' + $app + '"'), '--open', '--log', '--port', $Port) -WorkingDirectory $PSScriptRoot -WindowStyle Hidden -PassThru
+Write-Output "Handdraw PID $($process.Id): http://127.0.0.1:$Port"
diff --git a/tests/test_download.py b/tests/test_download.py
new file mode 100644
index 0000000..9371203
--- /dev/null
+++ b/tests/test_download.py
@@ -0,0 +1,54 @@
+import hashlib
+import importlib
+import io
+
+import pytest
+
+
+def download(monkeypatch):
+ module = importlib.import_module('scripts.download_model')
+ payload = b'verified model fixture'
+ monkeypatch.setattr(module, 'EXPECTED_SIZE', len(payload))
+ monkeypatch.setattr(module, 'EXPECTED_SHA256', hashlib.sha256(payload).hexdigest())
+ monkeypatch.setattr(module.urllib.request, 'urlopen',
+ lambda request, timeout: io.BytesIO(payload))
+ return module, payload
+
+
+def test_verified_download_and_existing_file_skip(download, tmp_path, monkeypatch):
+ module, payload = download
+ target = tmp_path / 'assets' / 'model.safetensors'
+ assert module.download_model(target) == target
+ assert target.read_bytes() == payload
+ assert list(target.parent.iterdir()) == [target]
+ monkeypatch.setattr(module.urllib.request, 'urlopen',
+ lambda *args, **kwargs: pytest.fail('Existing model must not download'))
+ assert module.download_model(target) == target
+
+
[email protected]('bad', [b'short', b'x' * len(b'verified model fixture'), b'x' * 100])
+def test_bad_download_preserves_previous_file_and_removes_temp(download, tmp_path, monkeypatch, bad):
+ module, _ = download
+ target = tmp_path / 'model.safetensors'
+ target.write_bytes(b'previous')
+ monkeypatch.setattr(module.urllib.request, 'urlopen',
+ lambda request, timeout: io.BytesIO(bad))
+ with pytest.raises(ValueError):
+ module.download_model(target)
+ assert target.read_bytes() == b'previous'
+ assert list(tmp_path.iterdir()) == [target]
+
+
+def test_network_failure_cleans_temp_and_uses_timeout(download, tmp_path, monkeypatch):
+ module, _ = download
+
+ def fail(request, timeout):
+ assert 0 < timeout <= 30
+ assert request.full_url == module.MODEL_URL
+ raise TimeoutError('network timeout')
+
+ monkeypatch.setattr(module.urllib.request, 'urlopen', fail)
+ with pytest.raises(TimeoutError):
+ module.download_model(tmp_path / 'model.safetensors')
+ assert not list(tmp_path.iterdir())
diff --git a/tests/test_tool.py b/tests/test_tool.py
new file mode 100644
index 0000000..fac5816
--- /dev/null
+++ b/tests/test_tool.py
@@ -0,0 +1,112 @@
+import importlib
+from dataclasses import replace
+
+import numpy as np
+import pytest
+
+
+def modules():
+ return importlib.import_module('handdraw.settings'), importlib.import_module('handdraw.render')
+
+
+def image():
+ rgb = np.full((64, 96, 3), 245, np.uint8)
+ rgb[8:55, 15:80] = (50, 130, 180)
+ rgb[20:44, 32:61] = (180, 50, 40)
+ rgb[30:33, 8:88] = 0
+ return rgb
+
+
+def test_two_ratios_drive_separate_phase_durations():
+ config, _ = modules()
+ settings = config.Settings(duration=10, draw_percent=70, ink_percent=45)
+ assert settings.phase_seconds == pytest.approx((3.15, 3.85, 3))
+ assert replace(settings, ink_percent=80).phase_seconds == pytest.approx((5.6, 1.4, 3))
+
+
[email protected]('changes', [dict(duration=float('nan')), dict(duration=-1),
+ dict(ink_percent=100), dict(draw_percent=0), dict(mode='c'), dict(width=10000),
+ dict(fps=0), dict(device='auto'), dict(adaptive_block=4), dict(palette_colors=0)])
+def test_invalid_settings_fail_before_render(changes):
+ config, _ = modules()
+ with pytest.raises(ValueError):
+ replace(config.Settings(), **changes).validate()
+
+
+def test_keep_aspect_has_no_crop_or_white_border():
+ config, core = modules()
+ rgb = image()
+ fitted = core.fit_image(rgb, config.Settings(width=96, height=96, fit='original'))
+ np.testing.assert_array_equal(fitted, rgb)
+
+
[email protected]('mode', ('d', 'e'))
+def test_plan_has_monotone_path_subject_priority_and_complete_color(mode):
+ config, core = modules()
+ subject = np.zeros((64, 96), bool)
+ subject[16:50, 26:72] = True
+ plan = core.build_plan(image(), config.Settings(mode=mode, device='cpu'), subject_mask=subject)
+ assert np.all(np.diff(plan['pen_path'][:, 0]) > 0)
+ assert np.isfinite(plan['color_contact_time']).all()
+ assert plan['color_contact_time'][subject].max() <= plan['color_contact_time'][~subject].min()
+ assert plan['color_contact_time'].max() <= 1
+
+
+def test_rig_settings_are_per_render_and_do_not_mutate_defaults():
+ config, _ = modules()
+ from handdraw.v181d_hand import RIG_SETTINGS
+ before = config.rig_settings(config.Settings())
+ changed = config.rig_settings(config.Settings(wrist_degrees=20, finger_motion=0, shadow_strength=0))
+ assert changed['wrist_degrees'] == 20
+ assert all(center[-2:] == [0, 0] for pose in changed['poses'].values() for center in pose['centers'])
+ assert changed['shadow_max'] == 0
+ assert RIG_SETTINGS == before
+
+
+def test_cache_does_not_confuse_different_shapes_with_identical_bytes():
+ config, core = modules()
+ settings = config.Settings(device='cpu', encoder='cpu', subject_first=False)
+ first = np.full((32, 64, 3), 175, np.uint8)
+ second = np.full((64, 32, 3), 175, np.uint8)
+ assert first.tobytes() == second.tobytes()
+ a, _ = core._cached_plan(first, settings)
+ b, reused = core._cached_plan(second, settings)
+ assert not reused
+ assert a['structure_time'].shape == (32, 64)
+ assert b['structure_time'].shape == (64, 32)
+
+
+def test_paper_requires_opaque_rgb_color():
+ config, _ = modules()
+ with pytest.raises(ValueError):
+ config.Settings(paper_color='#ffffffff').validate()
+
+
+def test_every_public_setting_has_a_ui_control():
+ from dataclasses import fields
+ config, _ = modules()
+ app = importlib.import_module('app')
+ demo = app.build_ui()
+ assert set(demo.setting_controls) == {field.name for field in fields(config.Settings)}
+ assert demo.setting_controls['mode'].choices == [('Detailed', 'd'), ('Quick', 'e')]
+
+
+def test_cpu_export_is_a_real_mp4(tmp_path):
+ import cv2
+ config, core = modules()
+ settings = config.Settings(width=96, height=64, duration=.5, fps=20, mode='e',
+ device='cpu', encoder='cpu', show_hand=False, subject_first=False)
+ output, report = core.render_video(image(), settings, output_dir=tmp_path)
+ assert output.is_file() and output.suffix == '.mp4'
+ capture = cv2.VideoCapture(str(output))
+ frames = []
+ while True:
+ ok, frame = capture.read()
+ if not ok:
+ break
+ frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
+ capture.release()
+ assert len(frames) == 10
+ assert np.abs(frames[-1].astype(float) - image()).mean() < 6
+ assert report['settings']['mode'] == 'e' and report['frames'] == 10
+ assert report['device'] == 'cpu'
diff --git a/tests/test_ui.py b/tests/test_ui.py
new file mode 100644
index 0000000..71a773b
--- /dev/null
+++ b/tests/test_ui.py
@@ -0,0 +1,80 @@
+from dataclasses import fields
+import importlib
+import json
+from pathlib import Path
+import sys
+from types import SimpleNamespace
+
+import numpy as np
+import pytest
+
+from handdraw.settings import INK_DEFAULTS, RIG_SETTINGS, Settings
+
+
+def test_controls_match_native_metadata_and_defaults():
+ app = importlib.import_module('app')
+ demo = app.build_ui()
+ try:
+ assert set(demo.setting_controls) == {item.name for item in fields(Settings)}
+ for item in fields(Settings):
+ component = demo.setting_controls[item.name]
+ assert component.label == item.metadata['label']
+ if item.name not in ('rig_json', 'ink_json'):
+ assert component.value == item.default
+ if item.metadata['low'] is not None:
+ assert component.minimum == item.metadata['low']
+ assert component.maximum == item.metadata['high']
+ assert component.step == item.metadata['step']
+ assert demo.setting_controls['mode'].choices == [
+ ('Detailed', 'd'), ('Quick', 'e')]
+ rig = json.loads(demo.setting_controls['rig_json'].value)
+ assert rig == {key: value for key, value in RIG_SETTINGS.items()
+ if key not in app.PROTECTED_RIG_KEYS}
+ assert json.loads(demo.setting_controls['ink_json'].value) == INK_DEFAULTS
+ Settings(rig_json=json.dumps(rig), ink_json=json.dumps(INK_DEFAULTS)).validate()
+ assert demo.analytics_enabled is False
+ assert demo._queue.max_size == 8
+ assert demo._queue.default_concurrency_limit == 1
+ finally:
+ demo.close()
+
+
+def test_render_adapter_returns_paths_and_forwards_progress(monkeypatch, tmp_path):
+ app = importlib.import_module('app')
+ monkeypatch.setattr(app, 'OUTPUT_DIR', tmp_path)
+ image = np.zeros((8, 8, 4), dtype=np.uint8)
+ output = tmp_path / 'video.mp4'
+ output.write_bytes(b'test')
+ updates = []
+
+ def render(image_numpy, settings, output_dir=None, progress=None):
+ assert image_numpy is image
+ assert settings == Settings()
+ assert Path(output_dir) == tmp_path
+ progress(.5, 'Rendering')
+ return output, {'frames': 1}
+
+ monkeypatch.setitem(sys.modules, 'handdraw.render', SimpleNamespace(render_video=render))
+ result = app.render_image(image, {item.name: item.default for item in fields(Settings)},
+ lambda fraction, desc: updates.append((fraction, desc)))
+ assert result == (str(output), str(output), {'frames': 1})
+ assert updates == [(.5, 'Rendering')]
+
+
+def test_invalid_settings_fail_before_renderer_import():
+ app = importlib.import_module('app')
+ with pytest.raises(app.gr.Error):
+ app.render_image(np.zeros((8, 8, 4), dtype=np.uint8), {'duration': -1})
+ with pytest.raises(app.gr.Error):
+ app.render_image(None, {})
+
+
+def test_render_adapter_rejects_output_outside_output_directory(monkeypatch, tmp_path):
+ app = importlib.import_module('app')
+ monkeypatch.setattr(app, 'OUTPUT_DIR', tmp_path / 'outputs')
+ output = tmp_path / 'outside.mp4'
+ output.write_bytes(b'test')
+ monkeypatch.setitem(sys.modules, 'handdraw.render', SimpleNamespace(
+ render_video=lambda *args, **kwargs: (output, {})))
+ with pytest.raises(app.gr.Error, match='invalid output file'):
+ app.render_image(np.zeros((8, 8, 4), dtype=np.uint8), {})
diff --git a/vendor_runtime/anime_segmentation/LICENSE b/vendor_runtime/anime_segmentation/LICENSE
new file mode 100644
index 0000000..b09cd78
--- /dev/null
+++ b/vendor_runtime/anime_segmentation/LICENSE
@@ -0,0 +1,201 @@
+Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor_runtime/anime_segmentation/isnet.py b/vendor_runtime/anime_segmentation/isnet.py
new file mode 100644
index 0000000..09d4fc3
--- /dev/null
+++ b/vendor_runtime/anime_segmentation/isnet.py
@@ -0,0 +1,619 @@
+# Codes are borrowed from
+# https://github.com/xuebinqin/DIS/blob/main/IS-Net/models/isnet.py
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torchvision import models
+
+bce_loss = nn.BCEWithLogitsLoss(reduction="mean")
+
+
+def muti_loss_fusion(preds, target):
+ loss0 = 0.0
+ loss = 0.0
+
+ for i in range(0, len(preds)):
+ if preds[i].shape[2] != target.shape[2] or preds[i].shape[3] != target.shape[3]:
+ tmp_target = F.interpolate(
+ target, size=preds[i].size()[2:], mode="bilinear", align_corners=True
+ )
+ loss = loss + bce_loss(preds[i], tmp_target)
+ else:
+ loss = loss + bce_loss(preds[i], target)
+ if i == 0:
+ loss0 = loss
+ return loss0, loss
+
+
+fea_loss = nn.MSELoss(reduction="mean")
+kl_loss = nn.KLDivLoss(reduction="mean")
+l1_loss = nn.L1Loss(reduction="mean")
+smooth_l1_loss = nn.SmoothL1Loss(reduction="mean")
+
+
+def muti_loss_fusion_kl(preds, target, dfs, fs, mode="MSE"):
+ loss0 = 0.0
+ loss = 0.0
+
+ for i in range(0, len(preds)):
+ if preds[i].shape[2] != target.shape[2] or preds[i].shape[3] != target.shape[3]:
+ tmp_target = F.interpolate(
+ target, size=preds[i].size()[2:], mode="bilinear", align_corners=True
+ )
+ loss = loss + bce_loss(preds[i], tmp_target)
+ else:
+ loss = loss + bce_loss(preds[i], target)
+ if i == 0:
+ loss0 = loss
+
+ for i in range(0, len(dfs)):
+ df = dfs[i]
+ fs_i = fs[i]
+ if mode == "MSE":
+ loss = loss + fea_loss(
+ df, fs_i
+ ) ### add the mse loss of features as additional constraints
+ elif mode == "KL":
+ loss = loss + kl_loss(F.log_softmax(df, dim=1), F.softmax(fs_i, dim=1))
+ elif mode == "MAE":
+ loss = loss + l1_loss(df, fs_i)
+ elif mode == "SmoothL1":
+ loss = loss + smooth_l1_loss(df, fs_i)
+
+ return loss0, loss
+
+
+class REBNCONV(nn.Module):
+ def __init__(self, in_ch=3, out_ch=3, dirate=1, stride=1):
+ super(REBNCONV, self).__init__()
+
+ self.conv_s1 = nn.Conv2d(
+ in_ch, out_ch, 3, padding=1 * dirate, dilation=1 * dirate, stride=stride
+ )
+ self.bn_s1 = nn.BatchNorm2d(out_ch)
+ self.relu_s1 = nn.ReLU(inplace=True)
+
+ def forward(self, x):
+ hx = x
+ xout = self.relu_s1(self.bn_s1(self.conv_s1(hx)))
+
+ return xout
+
+
+## upsample tensor 'src' to have the same spatial size with tensor 'tar'
+def _upsample_like(src, tar):
+ src = F.interpolate(src, size=tar.shape[2:], mode="bilinear", align_corners=False)
+
+ return src
+
+
+### RSU-7 ###
+class RSU7(nn.Module):
+ def __init__(self, in_ch=3, mid_ch=12, out_ch=3, img_size=512):
+ super(RSU7, self).__init__()
+
+ self.in_ch = in_ch
+ self.mid_ch = mid_ch
+ self.out_ch = out_ch
+
+ self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) ## 1 -> 1/2
+
+ self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)
+ self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)
+ self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)
+ self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1)
+ self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1)
+ self.pool5 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=1)
+
+ self.rebnconv7 = REBNCONV(mid_ch, mid_ch, dirate=2)
+
+ self.rebnconv6d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1)
+
+ def forward(self, x):
+ b, c, h, w = x.shape
+
+ hx = x
+ hxin = self.rebnconvin(hx)
+
+ hx1 = self.rebnconv1(hxin)
+ hx = self.pool1(hx1)
+
+ hx2 = self.rebnconv2(hx)
+ hx = self.pool2(hx2)
+
+ hx3 = self.rebnconv3(hx)
+ hx = self.pool3(hx3)
+
+ hx4 = self.rebnconv4(hx)
+ hx = self.pool4(hx4)
+
+ hx5 = self.rebnconv5(hx)
+ hx = self.pool5(hx5)
+
+ hx6 = self.rebnconv6(hx)
+
+ hx7 = self.rebnconv7(hx6)
+
+ hx6d = self.rebnconv6d(torch.cat((hx7, hx6), 1))
+ hx6dup = _upsample_like(hx6d, hx5)
+
+ hx5d = self.rebnconv5d(torch.cat((hx6dup, hx5), 1))
+ hx5dup = _upsample_like(hx5d, hx4)
+
+ hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1))
+ hx4dup = _upsample_like(hx4d, hx3)
+
+ hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1))
+ hx3dup = _upsample_like(hx3d, hx2)
+
+ hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))
+ hx2dup = _upsample_like(hx2d, hx1)
+
+ hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))
+
+ return hx1d + hxin
+
+
+### RSU-6 ###
+class RSU6(nn.Module):
+ def __init__(self, in_ch=3, mid_ch=12, out_ch=3):
+ super(RSU6, self).__init__()
+
+ self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)
+
+ self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)
+ self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)
+ self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)
+ self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1)
+ self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1)
+
+ self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=2)
+
+ self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1)
+
+ def forward(self, x):
+ hx = x
+
+ hxin = self.rebnconvin(hx)
+
+ hx1 = self.rebnconv1(hxin)
+ hx = self.pool1(hx1)
+
+ hx2 = self.rebnconv2(hx)
+ hx = self.pool2(hx2)
+
+ hx3 = self.rebnconv3(hx)
+ hx = self.pool3(hx3)
+
+ hx4 = self.rebnconv4(hx)
+ hx = self.pool4(hx4)
+
+ hx5 = self.rebnconv5(hx)
+
+ hx6 = self.rebnconv6(hx5)
+
+ hx5d = self.rebnconv5d(torch.cat((hx6, hx5), 1))
+ hx5dup = _upsample_like(hx5d, hx4)
+
+ hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1))
+ hx4dup = _upsample_like(hx4d, hx3)
+
+ hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1))
+ hx3dup = _upsample_like(hx3d, hx2)
+
+ hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))
+ hx2dup = _upsample_like(hx2d, hx1)
+
+ hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))
+
+ return hx1d + hxin
+
+
+### RSU-5 ###
+class RSU5(nn.Module):
+ def __init__(self, in_ch=3, mid_ch=12, out_ch=3):
+ super(RSU5, self).__init__()
+
+ self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)
+
+ self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)
+ self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)
+ self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)
+ self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1)
+
+ self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=2)
+
+ self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1)
+
+ def forward(self, x):
+ hx = x
+
+ hxin = self.rebnconvin(hx)
+
+ hx1 = self.rebnconv1(hxin)
+ hx = self.pool1(hx1)
+
+ hx2 = self.rebnconv2(hx)
+ hx = self.pool2(hx2)
+
+ hx3 = self.rebnconv3(hx)
+ hx = self.pool3(hx3)
+
+ hx4 = self.rebnconv4(hx)
+
+ hx5 = self.rebnconv5(hx4)
+
+ hx4d = self.rebnconv4d(torch.cat((hx5, hx4), 1))
+ hx4dup = _upsample_like(hx4d, hx3)
+
+ hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1))
+ hx3dup = _upsample_like(hx3d, hx2)
+
+ hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))
+ hx2dup = _upsample_like(hx2d, hx1)
+
+ hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))
+
+ return hx1d + hxin
+
+
+### RSU-4 ###
+class RSU4(nn.Module):
+ def __init__(self, in_ch=3, mid_ch=12, out_ch=3):
+ super(RSU4, self).__init__()
+
+ self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)
+
+ self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)
+ self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)
+ self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)
+
+ self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=2)
+
+ self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
+ self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1)
+
+ def forward(self, x):
+ hx = x
+
+ hxin = self.rebnconvin(hx)
+
+ hx1 = self.rebnconv1(hxin)
+ hx = self.pool1(hx1)
+
+ hx2 = self.rebnconv2(hx)
+ hx = self.pool2(hx2)
+
+ hx3 = self.rebnconv3(hx)
+
+ hx4 = self.rebnconv4(hx3)
+
+ hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1))
+ hx3dup = _upsample_like(hx3d, hx2)
+
+ hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))
+ hx2dup = _upsample_like(hx2d, hx1)
+
+ hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))
+
+ return hx1d + hxin
+
+
+### RSU-4F ###
+class RSU4F(nn.Module):
+ def __init__(self, in_ch=3, mid_ch=12, out_ch=3):
+ super(RSU4F, self).__init__()
+
+ self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)
+
+ self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)
+ self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=2)
+ self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=4)
+
+ self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=8)
+
+ self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=4)
+ self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=2)
+ self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1)
+
+ def forward(self, x):
+ hx = x
+
+ hxin = self.rebnconvin(hx)
+
+ hx1 = self.rebnconv1(hxin)
+ hx2 = self.rebnconv2(hx1)
+ hx3 = self.rebnconv3(hx2)
+
+ hx4 = self.rebnconv4(hx3)
+
+ hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1))
+ hx2d = self.rebnconv2d(torch.cat((hx3d, hx2), 1))
+ hx1d = self.rebnconv1d(torch.cat((hx2d, hx1), 1))
+
+ return hx1d + hxin
+
+
+class myrebnconv(nn.Module):
+ def __init__(
+ self,
+ in_ch=3,
+ out_ch=1,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ dilation=1,
+ groups=1,
+ ):
+ super(myrebnconv, self).__init__()
+
+ self.conv = nn.Conv2d(
+ in_ch,
+ out_ch,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ groups=groups,
+ )
+ self.bn = nn.BatchNorm2d(out_ch)
+ self.rl = nn.ReLU(inplace=True)
+
+ def forward(self, x):
+ return self.rl(self.bn(self.conv(x)))
+
+
+class ISNetGTEncoder(nn.Module):
+ def __init__(self, in_ch=1, out_ch=1):
+ super(ISNetGTEncoder, self).__init__()
+
+ self.conv_in = myrebnconv(
+ in_ch, 16, 3, stride=2, padding=1
+ ) # nn.Conv2d(in_ch,64,3,stride=2,padding=1)
+
+ self.stage1 = RSU7(16, 16, 64)
+ self.pool12 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.stage2 = RSU6(64, 16, 64)
+ self.pool23 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.stage3 = RSU5(64, 32, 128)
+ self.pool34 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.stage4 = RSU4(128, 32, 256)
+ self.pool45 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.stage5 = RSU4F(256, 64, 512)
+ self.pool56 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.stage6 = RSU4F(512, 64, 512)
+
+ self.side1 = nn.Conv2d(64, out_ch, 3, padding=1)
+ self.side2 = nn.Conv2d(64, out_ch, 3, padding=1)
+ self.side3 = nn.Conv2d(128, out_ch, 3, padding=1)
+ self.side4 = nn.Conv2d(256, out_ch, 3, padding=1)
+ self.side5 = nn.Conv2d(512, out_ch, 3, padding=1)
+ self.side6 = nn.Conv2d(512, out_ch, 3, padding=1)
+
+ @staticmethod
+ def compute_loss(args):
+ preds, targets = args
+ return muti_loss_fusion(preds, targets)
+
+ def forward(self, x):
+ hx = x
+
+ hxin = self.conv_in(hx)
+ # hx = self.pool_in(hxin)
+
+ # stage 1
+ hx1 = self.stage1(hxin)
+ hx = self.pool12(hx1)
+
+ # stage 2
+ hx2 = self.stage2(hx)
+ hx = self.pool23(hx2)
+
+ # stage 3
+ hx3 = self.stage3(hx)
+ hx = self.pool34(hx3)
+
+ # stage 4
+ hx4 = self.stage4(hx)
+ hx = self.pool45(hx4)
+
+ # stage 5
+ hx5 = self.stage5(hx)
+ hx = self.pool56(hx5)
+
+ # stage 6
+ hx6 = self.stage6(hx)
+
+ # side output
+ d1 = self.side1(hx1)
+ d1 = _upsample_like(d1, x)
+
+ d2 = self.side2(hx2)
+ d2 = _upsample_like(d2, x)
+
+ d3 = self.side3(hx3)
+ d3 = _upsample_like(d3, x)
+
+ d4 = self.side4(hx4)
+ d4 = _upsample_like(d4, x)
+
+ d5 = self.side5(hx5)
+ d5 = _upsample_like(d5, x)
+
+ d6 = self.side6(hx6)
+ d6 = _upsample_like(d6, x)
+
+ # d0 = self.outconv(torch.cat((d1,d2,d3,d4,d5,d6),1))
+
+ # return [torch.sigmoid(d1), torch.sigmoid(d2), torch.sigmoid(d3), torch.sigmoid(d4), torch.sigmoid(d5), torch.sigmoid(d6)], [hx1, hx2, hx3, hx4, hx5, hx6]
+ return [d1, d2, d3, d4, d5, d6], [hx1, hx2, hx3, hx4, hx5, hx6]
+
+
+class ISNetDIS(nn.Module):
+ def __init__(self, in_ch=3, out_ch=1):
+ super(ISNetDIS, self).__init__()
+
+ self.conv_in = nn.Conv2d(in_ch, 64, 3, stride=2, padding=1)
+ self.pool_in = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.stage1 = RSU7(64, 32, 64)
+ self.pool12 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.stage2 = RSU6(64, 32, 128)
+ self.pool23 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.stage3 = RSU5(128, 64, 256)
+ self.pool34 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.stage4 = RSU4(256, 128, 512)
+ self.pool45 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.stage5 = RSU4F(512, 256, 512)
+ self.pool56 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
+
+ self.stage6 = RSU4F(512, 256, 512)
+
+ # decoder
+ self.stage5d = RSU4F(1024, 256, 512)
+ self.stage4d = RSU4(1024, 128, 256)
+ self.stage3d = RSU5(512, 64, 128)
+ self.stage2d = RSU6(256, 32, 64)
+ self.stage1d = RSU7(128, 16, 64)
+
+ self.side1 = nn.Conv2d(64, out_ch, 3, padding=1)
+ self.side2 = nn.Conv2d(64, out_ch, 3, padding=1)
+ self.side3 = nn.Conv2d(128, out_ch, 3, padding=1)
+ self.side4 = nn.Conv2d(256, out_ch, 3, padding=1)
+ self.side5 = nn.Conv2d(512, out_ch, 3, padding=1)
+ self.side6 = nn.Conv2d(512, out_ch, 3, padding=1)
+
+ # self.outconv = nn.Conv2d(6*out_ch,out_ch,1)
+
+ @staticmethod
+ def compute_loss_kl(preds, targets, dfs, fs, mode="MSE"):
+ return muti_loss_fusion_kl(preds, targets, dfs, fs, mode=mode)
+
+ @staticmethod
+ def compute_loss(args):
+ if len(args) == 3:
+ ds, dfs, labels = args
+ return muti_loss_fusion(ds, labels)
+ else:
+ ds, dfs, labels, fs = args
+ return muti_loss_fusion_kl(ds, labels, dfs, fs, mode="MSE")
+
+ def forward(self, x):
+ hx = x
+
+ hxin = self.conv_in(hx)
+ hx = self.pool_in(hxin)
+
+ # stage 1
+ hx1 = self.stage1(hxin)
+ hx = self.pool12(hx1)
+
+ # stage 2
+ hx2 = self.stage2(hx)
+ hx = self.pool23(hx2)
+
+ # stage 3
+ hx3 = self.stage3(hx)
+ hx = self.pool34(hx3)
+
+ # stage 4
+ hx4 = self.stage4(hx)
+ hx = self.pool45(hx4)
+
+ # stage 5
+ hx5 = self.stage5(hx)
+ hx = self.pool56(hx5)
+
+ # stage 6
+ hx6 = self.stage6(hx)
+ hx6up = _upsample_like(hx6, hx5)
+
+ # -------------------- decoder --------------------
+ hx5d = self.stage5d(torch.cat((hx6up, hx5), 1))
+ hx5dup = _upsample_like(hx5d, hx4)
+
+ hx4d = self.stage4d(torch.cat((hx5dup, hx4), 1))
+ hx4dup = _upsample_like(hx4d, hx3)
+
+ hx3d = self.stage3d(torch.cat((hx4dup, hx3), 1))
+ hx3dup = _upsample_like(hx3d, hx2)
+
+ hx2d = self.stage2d(torch.cat((hx3dup, hx2), 1))
+ hx2dup = _upsample_like(hx2d, hx1)
+
+ hx1d = self.stage1d(torch.cat((hx2dup, hx1), 1))
+
+ # side output
+ d1 = self.side1(hx1d)
+ d1 = _upsample_like(d1, x)
+
+ d2 = self.side2(hx2d)
+ d2 = _upsample_like(d2, x)
+
+ d3 = self.side3(hx3d)
+ d3 = _upsample_like(d3, x)
+
+ d4 = self.side4(hx4d)
+ d4 = _upsample_like(d4, x)
+
+ d5 = self.side5(hx5d)
+ d5 = _upsample_like(d5, x)
+
+ d6 = self.side6(hx6)
+ d6 = _upsample_like(d6, x)
+
+ # d0 = self.outconv(torch.cat((d1,d2,d3,d4,d5,d6),1))
+
+ # return [torch.sigmoid(d1), torch.sigmoid(d2), torch.sigmoid(d3), torch.sigmoid(d4), torch.sigmoid(d5), torch.sigmoid(d6)], [hx1d, hx2d, hx3d, hx4d, hx5d, hx6]
+ return [d1, d2, d3, d4, d5, d6], [hx1d, hx2d, hx3d, hx4d, hx5d, hx6]
diff --git a/vendor_runtime/srt_whiteboard/LICENSE b/vendor_runtime/srt_whiteboard/LICENSE
new file mode 100644
index 0000000..f2a66ae
--- /dev/null
+++ b/vendor_runtime/srt_whiteboard/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 江哥是老登啊
+
+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.