diffusers-workflow 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. diffusers_workflow-0.4.0.dist-info/METADATA +318 -0
  2. diffusers_workflow-0.4.0.dist-info/RECORD +260 -0
  3. diffusers_workflow-0.4.0.dist-info/WHEEL +5 -0
  4. diffusers_workflow-0.4.0.dist-info/entry_points.txt +7 -0
  5. diffusers_workflow-0.4.0.dist-info/licenses/LICENSE +201 -0
  6. diffusers_workflow-0.4.0.dist-info/top_level.txt +2 -0
  7. dw/__init__.py +440 -0
  8. dw/adapter_compatibility.py +226 -0
  9. dw/arguments.py +1231 -0
  10. dw/assessment_rules.py +159 -0
  11. dw/assets.py +130 -0
  12. dw/cache_blocks.json +16 -0
  13. dw/cache_blocks.py +146 -0
  14. dw/community_pipelines/pipeline_flux_rf_inversion.py +1184 -0
  15. dw/content_types.py +150 -0
  16. dw/dissolve_frame_errors.py +121 -0
  17. dw/docs/ACCELERATION.md +352 -0
  18. dw/docs/AGENT_LOOP.md +95 -0
  19. dw/docs/DEPENDENCIES.md +91 -0
  20. dw/docs/IP_ADAPTER.md +109 -0
  21. dw/docs/LORAS.md +131 -0
  22. dw/docs/MCP.md +517 -0
  23. dw/docs/PROMPT_WEIGHTING.md +78 -0
  24. dw/docs/QUANTIZATION.md +230 -0
  25. dw/docs/RECIPES_24GB.md +201 -0
  26. dw/docs/RELEASING.md +195 -0
  27. dw/docs/REMOTE.md +140 -0
  28. dw/docs/REPL_COMMANDS.md +121 -0
  29. dw/docs/REPL_WORKER_GUIDE.md +51 -0
  30. dw/docs/SECURITY.md +272 -0
  31. dw/docs/SECURITY_QUICKREF.md +112 -0
  32. dw/docs/SERVER.md +679 -0
  33. dw/docs/TASKS.md +1741 -0
  34. dw/docs/TESTING.md +71 -0
  35. dw/docs/WORKFLOW_GUIDE.md +2038 -0
  36. dw/docs/WORKSPACES.md +316 -0
  37. dw/download_watch.py +335 -0
  38. dw/elision.py +306 -0
  39. dw/events.py +275 -0
  40. dw/for_each.py +409 -0
  41. dw/host_memory.py +258 -0
  42. dw/host_memory_projection.py +230 -0
  43. dw/hub_cache.py +432 -0
  44. dw/introspection.py +1228 -0
  45. dw/kernel_availability.py +208 -0
  46. dw/locations.py +599 -0
  47. dw/log_setup.py +45 -0
  48. dw/loudness.py +82 -0
  49. dw/media_audio.py +217 -0
  50. dw/media_frames.py +367 -0
  51. dw/media_info.py +297 -0
  52. dw/pipeline_processors/chain.py +821 -0
  53. dw/pipeline_processors/config_objects.py +237 -0
  54. dw/pipeline_processors/pipeline.py +2297 -0
  55. dw/pipeline_processors/remote.py +46 -0
  56. dw/plan.py +920 -0
  57. dw/previous_results.py +411 -0
  58. dw/probe_paths.py +59 -0
  59. dw/prompt_schema.json +48 -0
  60. dw/prompt_weighting.py +378 -0
  61. dw/prompts.py +159 -0
  62. dw/realize.py +250 -0
  63. dw/reference_limits.py +215 -0
  64. dw/reference_names.py +125 -0
  65. dw/repl.py +338 -0
  66. dw/repl_commands.py +836 -0
  67. dw/repl_worker.py +159 -0
  68. dw/result.py +1720 -0
  69. dw/result_fps.py +82 -0
  70. dw/run.py +162 -0
  71. dw/runs.py +768 -0
  72. dw/scalar_result_validation.py +97 -0
  73. dw/schema.py +283 -0
  74. dw/security.py +1038 -0
  75. dw/select_validation.py +115 -0
  76. dw/serve.py +277 -0
  77. dw/server/__init__.py +2 -0
  78. dw/server/app.py +4586 -0
  79. dw/server/assess.py +132 -0
  80. dw/server/catalog_shape.py +487 -0
  81. dw/server/enhancers.py +129 -0
  82. dw/server/exports.py +480 -0
  83. dw/server/guides.py +257 -0
  84. dw/server/jobs.py +1561 -0
  85. dw/server/mcp_mount.py +95 -0
  86. dw/server/netinfo.py +124 -0
  87. dw/server/observed_cost.py +379 -0
  88. dw/server/sysinfo.py +71 -0
  89. dw/server/ui/assets/abap-08VXUWAP.js +1 -0
  90. dw/server/ui/assets/apex-BWPQTe0t.js +1 -0
  91. dw/server/ui/assets/azcli-Bc_sGQ0U.js +1 -0
  92. dw/server/ui/assets/bat-i0X4ZdIN.js +1 -0
  93. dw/server/ui/assets/bicep-B5-_aFwp.js +2 -0
  94. dw/server/ui/assets/cameligo-DMUM7wLl.js +1 -0
  95. dw/server/ui/assets/clojure-Cm7r79vr.js +1 -0
  96. dw/server/ui/assets/codicon-Brq4_Ui5.ttf +0 -0
  97. dw/server/ui/assets/coffee-Ba7i2nA0.js +1 -0
  98. dw/server/ui/assets/cpp-C7h46wYY.js +1 -0
  99. dw/server/ui/assets/csharp-BKxtCVv1.js +1 -0
  100. dw/server/ui/assets/csp-bTuwJoIa.js +1 -0
  101. dw/server/ui/assets/css-DIMkf-bt.js +3 -0
  102. dw/server/ui/assets/css.worker-B3ciXF_0.js +93 -0
  103. dw/server/ui/assets/cssMode-CPznxfY8.js +1 -0
  104. dw/server/ui/assets/cypher-CVaqCwHa.js +1 -0
  105. dw/server/ui/assets/dart-onAF5SnQ.js +1 -0
  106. dw/server/ui/assets/dockerfile-DZFCIeNp.js +1 -0
  107. dw/server/ui/assets/ecl-D05T4iGw.js +1 -0
  108. dw/server/ui/assets/editor-jjEx9u7D.css +1 -0
  109. dw/server/ui/assets/editor.api-CpWcotrd.js +847 -0
  110. dw/server/ui/assets/editor.worker-q-txB4vs.js +30 -0
  111. dw/server/ui/assets/elixir-6RTg0lbw.js +1 -0
  112. dw/server/ui/assets/flow9-C5_-GSwl.js +1 -0
  113. dw/server/ui/assets/freemarker2-CXtRM8N4.js +3 -0
  114. dw/server/ui/assets/fsharp-C8Ef5oNN.js +1 -0
  115. dw/server/ui/assets/go-C-y9NEjX.js +1 -0
  116. dw/server/ui/assets/graphql-fmXr3nnJ.js +1 -0
  117. dw/server/ui/assets/handlebars-N7x-6NMY.js +1 -0
  118. dw/server/ui/assets/hcl-CpzslTdj.js +1 -0
  119. dw/server/ui/assets/html-PhsdjHSr.js +1 -0
  120. dw/server/ui/assets/html.worker-C93Ht9o9.js +506 -0
  121. dw/server/ui/assets/htmlMode-Dgj0SEok.js +1 -0
  122. dw/server/ui/assets/index-3Vw6WAPW.css +1 -0
  123. dw/server/ui/assets/index-DgrYhQd9.js +43 -0
  124. dw/server/ui/assets/ini-sBoK_t0W.js +1 -0
  125. dw/server/ui/assets/java-BEtHBSE6.js +1 -0
  126. dw/server/ui/assets/javascript-BJqN9Qhv.js +1 -0
  127. dw/server/ui/assets/json.worker-B2V3pomh.js +62 -0
  128. dw/server/ui/assets/jsonMode-DbM4SWSv.js +7 -0
  129. dw/server/ui/assets/julia-Bri6UV-V.js +1 -0
  130. dw/server/ui/assets/kotlin-BOotOW0E.js +1 -0
  131. dw/server/ui/assets/less-B9JPFI3C.js +2 -0
  132. dw/server/ui/assets/lexon-CfSJPG6W.js +1 -0
  133. dw/server/ui/assets/liquid-BWr8lEc4.js +1 -0
  134. dw/server/ui/assets/lspLanguageFeatures-C1iGuDyZ.js +4 -0
  135. dw/server/ui/assets/lua-CsQS60Ue.js +1 -0
  136. dw/server/ui/assets/m3-D-oSqn_W.js +1 -0
  137. dw/server/ui/assets/markdown-Cimd5fb3.js +1 -0
  138. dw/server/ui/assets/mdx-DAdMi_0p.js +1 -0
  139. dw/server/ui/assets/mips-CIPQ_RoX.js +1 -0
  140. dw/server/ui/assets/monaco--ixms01u.css +1 -0
  141. dw/server/ui/assets/monaco-BGCeEqaw.js +56 -0
  142. dw/server/ui/assets/msdax-DauUninz.js +1 -0
  143. dw/server/ui/assets/mysql-SOo6toE5.js +1 -0
  144. dw/server/ui/assets/objective-c-FvmIjYaQ.js +1 -0
  145. dw/server/ui/assets/pascal-DrH0SRf2.js +1 -0
  146. dw/server/ui/assets/pascaligo-D-ptJ9y-.js +1 -0
  147. dw/server/ui/assets/perl-oz_6vUea.js +1 -0
  148. dw/server/ui/assets/pgsql-DTj74zXo.js +1 -0
  149. dw/server/ui/assets/php-nr791fC2.js +1 -0
  150. dw/server/ui/assets/pla-CopQ2nXW.js +1 -0
  151. dw/server/ui/assets/postiats-43DmfD33.js +1 -0
  152. dw/server/ui/assets/powerquery-D3hlyOfw.js +1 -0
  153. dw/server/ui/assets/powershell-DmHpPYUd.js +1 -0
  154. dw/server/ui/assets/protobuf-C531GsRP.js +2 -0
  155. dw/server/ui/assets/pug-Z5eAx3Zn.js +1 -0
  156. dw/server/ui/assets/python-Bcn70HdC.js +1 -0
  157. dw/server/ui/assets/qsharp-DkqhCAOL.js +1 -0
  158. dw/server/ui/assets/r-BwWrilGY.js +1 -0
  159. dw/server/ui/assets/razor-D1HmNnby.js +1 -0
  160. dw/server/ui/assets/redis-ClamHrr6.js +1 -0
  161. dw/server/ui/assets/redshift-DT7zqm-g.js +1 -0
  162. dw/server/ui/assets/restructuredtext-BYgofb2h.js +1 -0
  163. dw/server/ui/assets/ruby-DezsRK8O.js +1 -0
  164. dw/server/ui/assets/rust-DdL9SqIa.js +1 -0
  165. dw/server/ui/assets/sb-CcwsVR0C.js +1 -0
  166. dw/server/ui/assets/scala-DHpiXF5c.js +1 -0
  167. dw/server/ui/assets/scheme-BeGwcela.js +1 -0
  168. dw/server/ui/assets/scss-gp-XZpBa.js +3 -0
  169. dw/server/ui/assets/shell-CC2rA5mh.js +1 -0
  170. dw/server/ui/assets/solidity-BEEn4gHE.js +1 -0
  171. dw/server/ui/assets/sophia-CRfGWb83.js +1 -0
  172. dw/server/ui/assets/sparql-D_Lu-MrJ.js +1 -0
  173. dw/server/ui/assets/sql-NEE52Syq.js +1 -0
  174. dw/server/ui/assets/st-DbInun42.js +1 -0
  175. dw/server/ui/assets/swift-Bxkupp3x.js +1 -0
  176. dw/server/ui/assets/systemverilog-Bz4Y3fRF.js +1 -0
  177. dw/server/ui/assets/tcl-DISqw1ZD.js +1 -0
  178. dw/server/ui/assets/ts.worker-D7T1-Ig5.js +67738 -0
  179. dw/server/ui/assets/tsMode-D6u0XmOW.js +11 -0
  180. dw/server/ui/assets/twig-De2hgUGE.js +1 -0
  181. dw/server/ui/assets/typescript-BU6v-LMV.js +1 -0
  182. dw/server/ui/assets/typespec-B8J7ngcE.js +1 -0
  183. dw/server/ui/assets/vb-DV3o63ZY.js +1 -0
  184. dw/server/ui/assets/wgsl-DpFanUEy.js +298 -0
  185. dw/server/ui/assets/workers-Cn7cTUKr.js +1 -0
  186. dw/server/ui/assets/xml--0LP2Lwk.js +1 -0
  187. dw/server/ui/assets/yaml-mpBg9jnt.js +1 -0
  188. dw/server/ui/index.html +17 -0
  189. dw/server/updater.py +192 -0
  190. dw/settings.py +98 -0
  191. dw/shot_span_preflight.py +116 -0
  192. dw/shots.py +359 -0
  193. dw/slice_preflight.py +148 -0
  194. dw/step.py +187 -0
  195. dw/step_cache.py +442 -0
  196. dw/subfolders.py +107 -0
  197. dw/task_domains.py +307 -0
  198. dw/tasks/assess.py +826 -0
  199. dw/tasks/audio_transcription.py +88 -0
  200. dw/tasks/audio_utils.py +1862 -0
  201. dw/tasks/background_remover.py +43 -0
  202. dw/tasks/borders.py +113 -0
  203. dw/tasks/compose_text.py +74 -0
  204. dw/tasks/concat_videos.py +300 -0
  205. dw/tasks/depth_estimator.py +54 -0
  206. dw/tasks/diffusion_upscale.py +109 -0
  207. dw/tasks/dissolve_videos.py +342 -0
  208. dw/tasks/format_messages.py +24 -0
  209. dw/tasks/gather.py +173 -0
  210. dw/tasks/grade.py +97 -0
  211. dw/tasks/image_to_text.py +43 -0
  212. dw/tasks/image_utils.py +764 -0
  213. dw/tasks/interpolate_frames.py +252 -0
  214. dw/tasks/judge.py +68 -0
  215. dw/tasks/model_cache.py +55 -0
  216. dw/tasks/pair_audio.py +268 -0
  217. dw/tasks/qr_code.py +19 -0
  218. dw/tasks/restore_faces.py +175 -0
  219. dw/tasks/rife_model.py +192 -0
  220. dw/tasks/segment.py +121 -0
  221. dw/tasks/select.py +111 -0
  222. dw/tasks/speech_generation.py +228 -0
  223. dw/tasks/stabilize.py +129 -0
  224. dw/tasks/task.py +920 -0
  225. dw/tasks/tensor_image.py +57 -0
  226. dw/tasks/text_generation.py +169 -0
  227. dw/tasks/text_sections.py +80 -0
  228. dw/tasks/upscale.py +203 -0
  229. dw/tasks/video_utils.py +624 -0
  230. dw/tasks/zoe_depth.py +71 -0
  231. dw/teacache.py +381 -0
  232. dw/teacache_models.json +99 -0
  233. dw/test.py +29 -0
  234. dw/type_helpers.py +231 -0
  235. dw/validate.py +68 -0
  236. dw/variable_constraints.py +444 -0
  237. dw/variables.py +443 -0
  238. dw/video_extensions.py +141 -0
  239. dw/vram_estimate.py +116 -0
  240. dw/worker.py +764 -0
  241. dw/workflow.py +2007 -0
  242. dw/workflow_schema.json +1346 -0
  243. dw/workflow_sources.py +383 -0
  244. dw/workflows/h3_context_ir.json +57 -0
  245. dw/workflows/test.json +31 -0
  246. dw/workspace.py +730 -0
  247. dw_mcp/__init__.py +6 -0
  248. dw_mcp/__main__.py +133 -0
  249. dw_mcp/assets.py +336 -0
  250. dw_mcp/authoring.py +114 -0
  251. dw_mcp/catalog.py +360 -0
  252. dw_mcp/client.py +486 -0
  253. dw_mcp/diagnose.py +371 -0
  254. dw_mcp/exports.py +84 -0
  255. dw_mcp/guides.py +35 -0
  256. dw_mcp/media.py +638 -0
  257. dw_mcp/models.py +97 -0
  258. dw_mcp/prompts.py +104 -0
  259. dw_mcp/server.py +1343 -0
  260. dw_mcp/workspaces.py +212 -0
@@ -0,0 +1,175 @@
1
+ """
2
+ Face restoration via spandrel + facexlib.
3
+
4
+ Uses facexlib for face detection/alignment/pasting and spandrel for
5
+ neural network inference on cropped faces. Supports GFPGAN, RestoreFormer,
6
+ and CodeFormer (via spandrel-extra-arches) model weights.
7
+ """
8
+
9
+ import logging
10
+ import numpy as np
11
+ import torch
12
+ from PIL import Image
13
+
14
+ from .model_cache import cached_model
15
+
16
+ logger = logging.getLogger("dw")
17
+
18
+
19
+ def restore_faces(image, model_name, device="cpu", **kwargs):
20
+ """Restore faces in an image using a spandrel-compatible face restoration model.
21
+
22
+ Args:
23
+ image: PIL Image containing faces to restore
24
+ model_name: HuggingFace repo ID or local path to model weights
25
+ device: Target device ("cuda", "mps", "cpu")
26
+ **kwargs:
27
+ filename: Weight file name within a HF repo (default: auto-detect)
28
+ upscale_factor: Background upscale factor (default: 1, no upscaling)
29
+ face_size: Cropped face size in pixels (default: 512)
30
+ use_parse: Use face parsing for better blending (default: True)
31
+ only_center_face: Only restore the largest/center face (default: False)
32
+ detection_resize: Resize shorter side for detection speed (default: 640)
33
+ eye_dist_threshold: Skip faces with eye distance below this (default: 5)
34
+ upsample_img: Pre-upscaled background PIL Image (default: None)
35
+
36
+ Returns:
37
+ PIL Image with restored faces
38
+ """
39
+ try:
40
+ from facexlib.utils.face_restoration_helper import FaceRestoreHelper
41
+ except ImportError:
42
+ raise ImportError(
43
+ "facexlib is required for face restoration. Install with: pip install facexlib"
44
+ )
45
+
46
+ from .upscale import _resolve_model_path
47
+
48
+ filename = kwargs.get("filename", None)
49
+ upscale_factor = kwargs.get("upscale_factor", 1)
50
+ face_size = kwargs.get("face_size", 512)
51
+ use_parse = kwargs.get("use_parse", True)
52
+ only_center_face = kwargs.get("only_center_face", False)
53
+ detection_resize = kwargs.get("detection_resize", 640)
54
+ eye_dist_threshold = kwargs.get("eye_dist_threshold", 5)
55
+ upsample_img = kwargs.get("upsample_img", None)
56
+
57
+ # Load the face restoration model via spandrel
58
+ def load_descriptor():
59
+ model_path = _resolve_model_path(model_name, filename)
60
+ result = _load_face_model(model_path, device)
61
+ if device != "cpu" and result.supports_half:
62
+ result.model.half()
63
+ return result
64
+
65
+ descriptor = cached_model(
66
+ ("restore_faces", model_name, filename, str(device)), load_descriptor
67
+ )
68
+
69
+ # Set up facexlib helper
70
+ face_helper = FaceRestoreHelper(
71
+ upscale_factor=upscale_factor,
72
+ face_size=face_size,
73
+ crop_ratio=(1, 1),
74
+ det_model="retinaface_resnet50",
75
+ use_parse=use_parse,
76
+ device=torch.device(device),
77
+ )
78
+
79
+ # Convert PIL to BGR numpy (facexlib format)
80
+ input_bgr = np.array(image.convert("RGB"))[:, :, ::-1].copy()
81
+ face_helper.read_image(input_bgr)
82
+
83
+ # Detect faces
84
+ num_faces = face_helper.get_face_landmarks_5(
85
+ only_center_face=only_center_face,
86
+ resize=detection_resize,
87
+ eye_dist_threshold=eye_dist_threshold,
88
+ )
89
+ logger.info(f"Detected {num_faces} face(s)")
90
+
91
+ if num_faces == 0:
92
+ logger.warning("No faces detected, returning original image")
93
+ return image
94
+
95
+ # Align and warp faces to face_size x face_size
96
+ face_helper.align_warp_face()
97
+
98
+ # Half precision was applied at load time (see load_descriptor above) if supported
99
+ use_half = device != "cpu" and descriptor.supports_half
100
+ model_dtype = torch.float16 if use_half else torch.float32
101
+
102
+ # Restore each face
103
+ for i, cropped_face in enumerate(face_helper.cropped_faces):
104
+ logger.debug(f"Restoring face {i + 1}/{num_faces}")
105
+
106
+ # BGR uint8 numpy -> float32 tensor [1, 3, H, W]
107
+ face_tensor = (
108
+ torch.from_numpy(cropped_face.astype(np.float32) / 255.0)
109
+ .permute(2, 0, 1)
110
+ .unsqueeze(0)
111
+ )
112
+ face_tensor = face_tensor.to(device=device, dtype=model_dtype)
113
+
114
+ with torch.inference_mode():
115
+ restored_tensor = descriptor(face_tensor)
116
+
117
+ # Tensor -> BGR uint8 numpy. Rounds rather than truncates when
118
+ # quantizing (matches diffusers' VaeImageProcessor.numpy_to_pil
119
+ # behavior) so exact 8-bit values don't drift down a level; this
120
+ # stays local rather than using tensor_image's shared helpers
121
+ # because the data here is BGR numpy (facexlib's format), not PIL/RGB.
122
+ restored = restored_tensor.squeeze(0).permute(1, 2, 0)
123
+ restored = restored.mul(255).round().clamp(0, 255).byte().cpu().numpy()
124
+
125
+ # Resize to expected face_size if model output differs
126
+ if restored.shape[:2] != (face_size, face_size):
127
+ import cv2
128
+
129
+ restored = cv2.resize(
130
+ restored, (face_size, face_size), interpolation=cv2.INTER_LANCZOS4
131
+ )
132
+
133
+ face_helper.add_restored_face(restored)
134
+
135
+ # Prepare inverse affine transforms
136
+ face_helper.get_inverse_affine()
137
+
138
+ # Paste faces back onto the image
139
+ upsample_bgr = None
140
+ if upsample_img is not None:
141
+ upsample_bgr = np.array(upsample_img.convert("RGB"))[:, :, ::-1].copy()
142
+
143
+ result_bgr = face_helper.paste_faces_to_input_image(upsample_img=upsample_bgr)
144
+
145
+ # BGR numpy -> PIL RGB
146
+ result = Image.fromarray(result_bgr[:, :, ::-1])
147
+ logger.info(
148
+ f"Face restoration complete ({num_faces} face(s), {result.width}x{result.height})"
149
+ )
150
+
151
+ face_helper.clean_all()
152
+ return result
153
+
154
+
155
+ def _load_face_model(model_path, device):
156
+ """Load a face restoration model via spandrel."""
157
+ try:
158
+ from spandrel import ModelLoader, ImageModelDescriptor
159
+ except ImportError:
160
+ raise ImportError(
161
+ "spandrel is required for face restoration. Install with: pip install spandrel"
162
+ )
163
+
164
+ logger.info(f"Loading face restoration model from {model_path}")
165
+ loader = ModelLoader(device=torch.device(device))
166
+ descriptor = loader.load_from_file(model_path)
167
+
168
+ if not isinstance(descriptor, ImageModelDescriptor):
169
+ raise ValueError(
170
+ f"Model is not an image model (got {type(descriptor).__name__}). "
171
+ f"Expected a face restoration model (GFPGAN, CodeFormer, RestoreFormer)."
172
+ )
173
+
174
+ logger.info(f"Loaded {descriptor.architecture.name}")
175
+ return descriptor
dw/tasks/rife_model.py ADDED
@@ -0,0 +1,192 @@
1
+ """
2
+ RIFE IFNet v4.13 — Real-Time Intermediate Flow Estimation.
3
+
4
+ Vendored from https://github.com/hzwer/Practical-RIFE
5
+ Original architecture by Zhewei Huang et al.
6
+ Matches the v4.13.2 checkpoint layout (feature-encode Head + four IFBlocks).
7
+
8
+ MIT License — Copyright (c) Megvii Inc.
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ """
28
+
29
+ import torch
30
+ import torch.nn as nn
31
+ import torch.nn.functional as F
32
+
33
+
34
+ def warp(tenInput, tenFlow, tenFlow_div, backwarp_tenGrid):
35
+ """Backward warp tenInput according to optical flow tenFlow."""
36
+ tenFlow = torch.cat(
37
+ [
38
+ tenFlow[:, 0:1] / tenFlow_div[0],
39
+ tenFlow[:, 1:2] / tenFlow_div[1],
40
+ ],
41
+ 1,
42
+ )
43
+ g = (backwarp_tenGrid + tenFlow).permute(0, 2, 3, 1)
44
+ return F.grid_sample(
45
+ input=tenInput,
46
+ grid=g,
47
+ mode="bilinear",
48
+ padding_mode="border",
49
+ align_corners=True,
50
+ )
51
+
52
+
53
+ def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
54
+ return nn.Sequential(
55
+ nn.Conv2d(
56
+ in_planes,
57
+ out_planes,
58
+ kernel_size=kernel_size,
59
+ stride=stride,
60
+ padding=padding,
61
+ dilation=dilation,
62
+ bias=True,
63
+ ),
64
+ nn.LeakyReLU(0.2, True),
65
+ )
66
+
67
+
68
+ class ResConv(nn.Module):
69
+ def __init__(self, c, dilation=1):
70
+ super().__init__()
71
+ self.conv = nn.Conv2d(
72
+ c, c, 3, 1, dilation, dilation=dilation, groups=1, bias=True
73
+ )
74
+ self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True)
75
+ self.relu = nn.LeakyReLU(0.2, True)
76
+
77
+ def forward(self, x):
78
+ return self.relu(self.conv(x) * self.beta + x)
79
+
80
+
81
+ class Head(nn.Module):
82
+ """Feature encoder — 8-channel per-image features consumed by the IFBlocks."""
83
+
84
+ def __init__(self):
85
+ super().__init__()
86
+ self.cnn0 = nn.Conv2d(3, 32, 3, 2, 1)
87
+ self.cnn1 = nn.Conv2d(32, 32, 3, 1, 1)
88
+ self.cnn2 = nn.Conv2d(32, 32, 3, 1, 1)
89
+ self.cnn3 = nn.ConvTranspose2d(32, 8, 4, 2, 1)
90
+ self.relu = nn.LeakyReLU(0.2, True)
91
+
92
+ def forward(self, x):
93
+ x = self.relu(self.cnn0(x))
94
+ x = self.relu(self.cnn1(x))
95
+ x = self.relu(self.cnn2(x))
96
+ return self.cnn3(x)
97
+
98
+
99
+ class IFBlock(nn.Module):
100
+ def __init__(self, in_planes, c=64):
101
+ super().__init__()
102
+ self.conv0 = nn.Sequential(
103
+ conv(in_planes, c // 2, 3, 2, 1),
104
+ conv(c // 2, c, 3, 2, 1),
105
+ )
106
+ self.convblock = nn.Sequential(
107
+ ResConv(c),
108
+ ResConv(c),
109
+ ResConv(c),
110
+ ResConv(c),
111
+ ResConv(c),
112
+ ResConv(c),
113
+ ResConv(c),
114
+ ResConv(c),
115
+ )
116
+ self.lastconv = nn.Sequential(
117
+ nn.ConvTranspose2d(c, 4 * 6, 4, 2, 1),
118
+ nn.PixelShuffle(2),
119
+ )
120
+
121
+ def forward(self, x, flow=None, scale=1):
122
+ x = F.interpolate(
123
+ x, scale_factor=1.0 / scale, mode="bilinear", align_corners=False
124
+ )
125
+ if flow is not None:
126
+ flow = F.interpolate(
127
+ flow, scale_factor=1.0 / scale, mode="bilinear", align_corners=False
128
+ ) * (1.0 / scale)
129
+ x = torch.cat((x, flow), 1)
130
+ feat = self.conv0(x)
131
+ feat = self.convblock(feat)
132
+ tmp = self.lastconv(feat)
133
+ tmp = F.interpolate(
134
+ tmp, scale_factor=scale, mode="bilinear", align_corners=False
135
+ )
136
+ flow = tmp[:, :4] * scale
137
+ mask = tmp[:, 4:5]
138
+ return flow, mask
139
+
140
+
141
+ class IFNet(nn.Module):
142
+ def __init__(self):
143
+ super().__init__()
144
+ self.block0 = IFBlock(7 + 16, c=192)
145
+ self.block1 = IFBlock(8 + 4 + 16, c=128)
146
+ self.block2 = IFBlock(8 + 4 + 16, c=96)
147
+ self.block3 = IFBlock(8 + 4 + 16, c=64)
148
+ self.encode = Head()
149
+
150
+ def forward(self, img0, img1, timestep, scale_list, tenFlow_div, backwarp_tenGrid):
151
+ f0 = self.encode(img0[:, :3])
152
+ f1 = self.encode(img1[:, :3])
153
+ flow_list = []
154
+ merged = []
155
+ mask_list = []
156
+ warped_img0 = img0
157
+ warped_img1 = img1
158
+
159
+ flow = None
160
+ for i, (block, scale) in enumerate(
161
+ zip(
162
+ [self.block0, self.block1, self.block2, self.block3],
163
+ scale_list,
164
+ )
165
+ ):
166
+ if flow is None:
167
+ flow, mask = block(
168
+ torch.cat((img0[:, :3], img1[:, :3], f0, f1, timestep), 1),
169
+ None,
170
+ scale=scale,
171
+ )
172
+ else:
173
+ wf0 = warp(f0, flow[:, :2], tenFlow_div, backwarp_tenGrid)
174
+ wf1 = warp(f1, flow[:, 2:4], tenFlow_div, backwarp_tenGrid)
175
+ fd, m = block(
176
+ torch.cat((warped_img0, warped_img1, wf0, wf1, timestep, mask), 1),
177
+ flow,
178
+ scale=scale,
179
+ )
180
+ flow = flow + fd
181
+ mask = mask + m
182
+
183
+ mask_list.append(mask)
184
+ flow_list.append(flow)
185
+ warped_img0 = warp(img0[:, :3], flow[:, :2], tenFlow_div, backwarp_tenGrid)
186
+ warped_img1 = warp(img1[:, :3], flow[:, 2:4], tenFlow_div, backwarp_tenGrid)
187
+ merged.append(
188
+ warped_img0 * torch.sigmoid(mask)
189
+ + warped_img1 * (1 - torch.sigmoid(mask))
190
+ )
191
+
192
+ return flow_list, mask_list, merged
dw/tasks/segment.py ADDED
@@ -0,0 +1,121 @@
1
+ """
2
+ Image segmentation via GroundingDINO + SAM2.
3
+
4
+ Takes an image and a text prompt, detects objects matching the prompt,
5
+ and returns a binary mask image (white = detected object).
6
+ """
7
+
8
+ import logging
9
+ import torch
10
+ import numpy as np
11
+ from PIL import Image, ImageOps
12
+ from transformers import (
13
+ AutoProcessor,
14
+ AutoModelForZeroShotObjectDetection,
15
+ Sam2Model,
16
+ Sam2Processor,
17
+ )
18
+ from .model_cache import cached_model
19
+
20
+ logger = logging.getLogger("dw")
21
+
22
+ _DEFAULT_DINO_MODEL = "IDEA-Research/grounding-dino-base"
23
+ _DEFAULT_SAM_MODEL = "facebook/sam2-hiera-large"
24
+
25
+
26
+ def segment_image(image, prompt, device="cpu", **kwargs):
27
+ """Segment objects matching a text prompt, returning a binary mask.
28
+
29
+ Args:
30
+ image: PIL Image to segment
31
+ prompt: Text description of object(s) to detect (e.g., "dog")
32
+ device: Target device ("cuda", "mps", "cpu")
33
+ **kwargs:
34
+ model_name: GroundingDINO model ID
35
+ sam_model_name: SAM2 model ID
36
+ threshold: Detection confidence threshold (default: 0.3)
37
+ invert: Invert the output mask (default: False)
38
+
39
+ Returns:
40
+ PIL Image in mode "L" — white (255) for detected objects, black (0) for background.
41
+ """
42
+ model_name = kwargs.get("model_name", _DEFAULT_DINO_MODEL)
43
+ sam_model_name = kwargs.get("sam_model_name", _DEFAULT_SAM_MODEL)
44
+ threshold = kwargs.get("threshold", 0.3)
45
+ invert = kwargs.get("invert", False)
46
+
47
+ width, height = image.size
48
+
49
+ def load_dino():
50
+ logger.info(f"Loading GroundingDINO from {model_name}")
51
+ processor = AutoProcessor.from_pretrained(model_name)
52
+ model = AutoModelForZeroShotObjectDetection.from_pretrained(model_name).to(
53
+ device
54
+ )
55
+ return processor, model
56
+
57
+ dino_processor, dino_model = cached_model(
58
+ ("segment_dino", model_name, str(device)), load_dino
59
+ )
60
+
61
+ inputs = dino_processor(images=image, text=prompt, return_tensors="pt").to(device)
62
+
63
+ with torch.inference_mode():
64
+ outputs = dino_model(**inputs)
65
+
66
+ results = dino_processor.post_process_grounded_object_detection(
67
+ outputs,
68
+ inputs["input_ids"],
69
+ threshold=threshold,
70
+ target_sizes=[(height, width)],
71
+ )
72
+
73
+ boxes = results[0]["boxes"]
74
+ scores = results[0]["scores"]
75
+ labels = results[0]["labels"]
76
+
77
+ logger.info(f"Detected {len(boxes)} objects: {labels} (scores: {scores.tolist()})")
78
+
79
+ if len(boxes) == 0:
80
+ mask_image = Image.new("L", (width, height), 0)
81
+ if invert:
82
+ mask_image = ImageOps.invert(mask_image)
83
+ return mask_image
84
+
85
+ def load_sam():
86
+ logger.info(f"Loading SAM2 from {sam_model_name}")
87
+ processor = Sam2Processor.from_pretrained(sam_model_name)
88
+ model = Sam2Model.from_pretrained(sam_model_name).to(device)
89
+ return processor, model
90
+
91
+ sam_processor, sam_model = cached_model(
92
+ ("segment_sam", sam_model_name, str(device)), load_sam
93
+ )
94
+
95
+ input_boxes = [boxes.cpu().tolist()]
96
+
97
+ sam_inputs = sam_processor(
98
+ images=image,
99
+ input_boxes=input_boxes,
100
+ return_tensors="pt",
101
+ ).to(device)
102
+
103
+ with torch.inference_mode():
104
+ sam_outputs = sam_model(**sam_inputs)
105
+
106
+ masks = sam_processor.post_process_masks(
107
+ sam_outputs.pred_masks,
108
+ sam_inputs["original_sizes"],
109
+ sam_inputs["reshaped_input_sizes"],
110
+ )
111
+
112
+ combined = masks[0][:, 0].sum(dim=0).clamp(0, 1)
113
+ mask_array = (combined.cpu().numpy() * 255).astype(np.uint8)
114
+
115
+ mask_image = Image.fromarray(mask_array, mode="L")
116
+
117
+ if invert:
118
+ mask_image = ImageOps.invert(mask_image)
119
+
120
+ logger.info(f"Generated segmentation mask {width}x{height}")
121
+ return mask_image
dw/tasks/select.py ADDED
@@ -0,0 +1,111 @@
1
+ """Reduce a list of candidates to one by a deterministic rule.
2
+
3
+ The README's headline shape is N candidates -> choose one -> spend an
4
+ expensive stage on the winner. Today that choice lives at the agent
5
+ boundary (keep_output + asset:); this task is the version of it that needs
6
+ no judgment - argmax, a threshold, or a fixed index - so the recipe stays
7
+ inside the workflow and replays. See docs/proposals/score-and-select.md.
8
+ """
9
+
10
+ import logging
11
+
12
+ logger = logging.getLogger("dw")
13
+
14
+
15
+ class Selected:
16
+ """The winning candidate, plus the metadata that makes the choice
17
+ replayable (position, score). Compares equal to its own value so a
18
+ caller that only wants the winner can treat it as one."""
19
+
20
+ def __init__(self, value, position, score):
21
+ self.value = value
22
+ self.position = position
23
+ self.score = score
24
+
25
+ def __eq__(self, other):
26
+ if isinstance(other, Selected):
27
+ return (
28
+ self.value == other.value
29
+ and self.position == other.position
30
+ and self.score == other.score
31
+ )
32
+ return self.value == other
33
+
34
+ def __hash__(self):
35
+ return hash(self.value)
36
+
37
+ def __repr__(self):
38
+ return f"Selected(value={self.value!r}, position={self.position}, score={self.score!r})"
39
+
40
+
41
+ _THRESHOLD_RULES = {
42
+ "first_above": lambda score, threshold: score >= threshold,
43
+ "first_below": lambda score, threshold: score <= threshold,
44
+ }
45
+
46
+
47
+ def _parse_score(index, score):
48
+ if isinstance(score, bool) or not isinstance(score, (str, int, float)):
49
+ raise ValueError(f"select: score {index} is not a number: {score!r}")
50
+ try:
51
+ return float(score)
52
+ except (TypeError, ValueError):
53
+ raise ValueError(f"select: score {index} is not a number: {score!r}")
54
+
55
+
56
+ def select(candidates, scores, rule, threshold=None, index=None):
57
+ """Task command: pick one candidate out of many by a fixed rule.
58
+
59
+ Args:
60
+ candidates: The values to choose among, in order.
61
+ scores: One number (or numeric string) per candidate, same length.
62
+ rule: "argmax" | "argmin" | "first_above" | "first_below" | "index"
63
+ threshold: Required by first_above/first_below.
64
+ index: Required by rule "index" - a position into candidates.
65
+
66
+ Returns:
67
+ A Selected wrapping the winning value, its position and its score.
68
+
69
+ Raises:
70
+ ValueError: length mismatch, a non-numeric score, an unknown rule,
71
+ a missing threshold/index, an out-of-range index, or (for
72
+ first_above/first_below) no candidate meeting the threshold.
73
+ """
74
+ if len(candidates) != len(scores):
75
+ raise ValueError(
76
+ f"select got {len(candidates)} candidates and {len(scores)} scores "
77
+ "- candidates and scores must be the same length"
78
+ )
79
+
80
+ parsed_scores = [_parse_score(i, s) for i, s in enumerate(scores)]
81
+
82
+ if rule in ("argmax", "argmin"):
83
+ positions = range(len(parsed_scores))
84
+ picker = max if rule == "argmax" else min
85
+ position = picker(positions, key=lambda i: parsed_scores[i])
86
+ elif rule in _THRESHOLD_RULES:
87
+ if threshold is None:
88
+ raise ValueError(f"select rule '{rule}' requires a threshold")
89
+ passes = _THRESHOLD_RULES[rule]
90
+ position = next(
91
+ (i for i, s in enumerate(parsed_scores) if passes(s, threshold)), None
92
+ )
93
+ if position is None:
94
+ raise ValueError(
95
+ f"select: no candidate passes rule '{rule}' at threshold {threshold}"
96
+ )
97
+ elif rule == "index":
98
+ if index is None:
99
+ raise ValueError("select rule 'index' requires an index")
100
+ if index < 0 or index >= len(candidates):
101
+ raise ValueError(
102
+ f"select: index {index} is out of range for {len(candidates)} candidates"
103
+ )
104
+ position = index
105
+ else:
106
+ raise ValueError(f"select: unknown rule: {rule!r}")
107
+
108
+ logger.debug(f"select: rule={rule} chose position {position}")
109
+ return Selected(
110
+ value=candidates[position], position=position, score=parsed_scores[position]
111
+ )