diffusers-workflow 0.4.0a3__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.
- diffusers_workflow-0.4.0a3.dist-info/METADATA +310 -0
- diffusers_workflow-0.4.0a3.dist-info/RECORD +171 -0
- diffusers_workflow-0.4.0a3.dist-info/WHEEL +5 -0
- diffusers_workflow-0.4.0a3.dist-info/entry_points.txt +6 -0
- diffusers_workflow-0.4.0a3.dist-info/licenses/LICENSE +201 -0
- diffusers_workflow-0.4.0a3.dist-info/top_level.txt +1 -0
- dw/__init__.py +353 -0
- dw/arguments.py +906 -0
- dw/cache_blocks.json +16 -0
- dw/cache_blocks.py +145 -0
- dw/community_pipelines/pipeline_flux_rf_inversion.py +1184 -0
- dw/events.py +78 -0
- dw/hub_cache.py +289 -0
- dw/introspection.py +458 -0
- dw/log_setup.py +45 -0
- dw/pipeline_processors/chain.py +750 -0
- dw/pipeline_processors/config_objects.py +235 -0
- dw/pipeline_processors/pipeline.py +1687 -0
- dw/pipeline_processors/remote.py +18 -0
- dw/previous_results.py +259 -0
- dw/prompt_weighting.py +378 -0
- dw/repl.py +298 -0
- dw/repl_commands.py +808 -0
- dw/repl_worker.py +129 -0
- dw/result.py +850 -0
- dw/run.py +92 -0
- dw/schema.py +24 -0
- dw/security.py +379 -0
- dw/serve.py +70 -0
- dw/server/__init__.py +2 -0
- dw/server/app.py +588 -0
- dw/server/jobs.py +547 -0
- dw/server/ui/assets/abap-08VXUWAP.js +1 -0
- dw/server/ui/assets/apex-BWPQTe0t.js +1 -0
- dw/server/ui/assets/azcli-Bc_sGQ0U.js +1 -0
- dw/server/ui/assets/bat-i0X4ZdIN.js +1 -0
- dw/server/ui/assets/bicep-B5-_aFwp.js +2 -0
- dw/server/ui/assets/cameligo-DMUM7wLl.js +1 -0
- dw/server/ui/assets/clojure-Cm7r79vr.js +1 -0
- dw/server/ui/assets/codicon-Brq4_Ui5.ttf +0 -0
- dw/server/ui/assets/coffee-Ba7i2nA0.js +1 -0
- dw/server/ui/assets/cpp-C7h46wYY.js +1 -0
- dw/server/ui/assets/csharp-BKxtCVv1.js +1 -0
- dw/server/ui/assets/csp-bTuwJoIa.js +1 -0
- dw/server/ui/assets/css-DIMkf-bt.js +3 -0
- dw/server/ui/assets/css.worker-B3ciXF_0.js +93 -0
- dw/server/ui/assets/cssMode-CEh6hWi2.js +1 -0
- dw/server/ui/assets/cypher-CVaqCwHa.js +1 -0
- dw/server/ui/assets/dart-onAF5SnQ.js +1 -0
- dw/server/ui/assets/dockerfile-DZFCIeNp.js +1 -0
- dw/server/ui/assets/ecl-D05T4iGw.js +1 -0
- dw/server/ui/assets/editor-jjEx9u7D.css +1 -0
- dw/server/ui/assets/editor.api-CExg3_mM.js +847 -0
- dw/server/ui/assets/editor.worker-q-txB4vs.js +30 -0
- dw/server/ui/assets/elixir-6RTg0lbw.js +1 -0
- dw/server/ui/assets/flow9-C5_-GSwl.js +1 -0
- dw/server/ui/assets/freemarker2-DH6orYh2.js +3 -0
- dw/server/ui/assets/fsharp-C8Ef5oNN.js +1 -0
- dw/server/ui/assets/go-C-y9NEjX.js +1 -0
- dw/server/ui/assets/graphql-fmXr3nnJ.js +1 -0
- dw/server/ui/assets/handlebars-CbrMVW4Q.js +1 -0
- dw/server/ui/assets/hcl-CpzslTdj.js +1 -0
- dw/server/ui/assets/html-YDNPZw2M.js +1 -0
- dw/server/ui/assets/html.worker-C93Ht9o9.js +506 -0
- dw/server/ui/assets/htmlMode-B_zSGWO2.js +1 -0
- dw/server/ui/assets/index-B7-VcYS-.css +1 -0
- dw/server/ui/assets/index-D_EiPU3b.js +13 -0
- dw/server/ui/assets/ini-sBoK_t0W.js +1 -0
- dw/server/ui/assets/java-BEtHBSE6.js +1 -0
- dw/server/ui/assets/javascript-dYuBvioq.js +1 -0
- dw/server/ui/assets/json.worker-B2V3pomh.js +62 -0
- dw/server/ui/assets/jsonMode-CUqLM39V.js +7 -0
- dw/server/ui/assets/julia-Bri6UV-V.js +1 -0
- dw/server/ui/assets/kotlin-BOotOW0E.js +1 -0
- dw/server/ui/assets/less-B9JPFI3C.js +2 -0
- dw/server/ui/assets/lexon-CfSJPG6W.js +1 -0
- dw/server/ui/assets/liquid-D6vxBzMv.js +1 -0
- dw/server/ui/assets/lspLanguageFeatures-1WJ2palX.js +4 -0
- dw/server/ui/assets/lua-CsQS60Ue.js +1 -0
- dw/server/ui/assets/m3-D-oSqn_W.js +1 -0
- dw/server/ui/assets/markdown-Cimd5fb3.js +1 -0
- dw/server/ui/assets/mdx-SHQb6vmD.js +1 -0
- dw/server/ui/assets/mips-CIPQ_RoX.js +1 -0
- dw/server/ui/assets/monaco--ixms01u.css +1 -0
- dw/server/ui/assets/monaco-CP-s5rcP.js +56 -0
- dw/server/ui/assets/msdax-DauUninz.js +1 -0
- dw/server/ui/assets/mysql-SOo6toE5.js +1 -0
- dw/server/ui/assets/objective-c-FvmIjYaQ.js +1 -0
- dw/server/ui/assets/pascal-DrH0SRf2.js +1 -0
- dw/server/ui/assets/pascaligo-D-ptJ9y-.js +1 -0
- dw/server/ui/assets/perl-oz_6vUea.js +1 -0
- dw/server/ui/assets/pgsql-DTj74zXo.js +1 -0
- dw/server/ui/assets/php-nr791fC2.js +1 -0
- dw/server/ui/assets/pla-CopQ2nXW.js +1 -0
- dw/server/ui/assets/postiats-43DmfD33.js +1 -0
- dw/server/ui/assets/powerquery-D3hlyOfw.js +1 -0
- dw/server/ui/assets/powershell-DmHpPYUd.js +1 -0
- dw/server/ui/assets/protobuf-C531GsRP.js +2 -0
- dw/server/ui/assets/pug-Z5eAx3Zn.js +1 -0
- dw/server/ui/assets/python-x0_EGHq9.js +1 -0
- dw/server/ui/assets/qsharp-DkqhCAOL.js +1 -0
- dw/server/ui/assets/r-BwWrilGY.js +1 -0
- dw/server/ui/assets/razor-BZC4LQDP.js +1 -0
- dw/server/ui/assets/redis-ClamHrr6.js +1 -0
- dw/server/ui/assets/redshift-DT7zqm-g.js +1 -0
- dw/server/ui/assets/restructuredtext-BYgofb2h.js +1 -0
- dw/server/ui/assets/ruby-DezsRK8O.js +1 -0
- dw/server/ui/assets/rust-DdL9SqIa.js +1 -0
- dw/server/ui/assets/sb-CcwsVR0C.js +1 -0
- dw/server/ui/assets/scala-DHpiXF5c.js +1 -0
- dw/server/ui/assets/scheme-BeGwcela.js +1 -0
- dw/server/ui/assets/scss-gp-XZpBa.js +3 -0
- dw/server/ui/assets/shell-CC2rA5mh.js +1 -0
- dw/server/ui/assets/solidity-BEEn4gHE.js +1 -0
- dw/server/ui/assets/sophia-CRfGWb83.js +1 -0
- dw/server/ui/assets/sparql-D_Lu-MrJ.js +1 -0
- dw/server/ui/assets/sql-NEE52Syq.js +1 -0
- dw/server/ui/assets/st-DbInun42.js +1 -0
- dw/server/ui/assets/swift-Bxkupp3x.js +1 -0
- dw/server/ui/assets/systemverilog-Bz4Y3fRF.js +1 -0
- dw/server/ui/assets/tcl-DISqw1ZD.js +1 -0
- dw/server/ui/assets/ts.worker-D7T1-Ig5.js +67738 -0
- dw/server/ui/assets/tsMode-BTfA6SbD.js +11 -0
- dw/server/ui/assets/twig-De2hgUGE.js +1 -0
- dw/server/ui/assets/typescript-CWA4MsNk.js +1 -0
- dw/server/ui/assets/typespec-B8J7ngcE.js +1 -0
- dw/server/ui/assets/vb-DV3o63ZY.js +1 -0
- dw/server/ui/assets/wgsl-DpFanUEy.js +298 -0
- dw/server/ui/assets/workers-CWU0uvj5.js +1 -0
- dw/server/ui/assets/xml-KmfTm3rg.js +1 -0
- dw/server/ui/assets/yaml-nFO_dDS6.js +1 -0
- dw/server/ui/index.html +17 -0
- dw/settings.py +77 -0
- dw/step.py +132 -0
- dw/tasks/audio_utils.py +266 -0
- dw/tasks/background_remover.py +43 -0
- dw/tasks/borders.py +113 -0
- dw/tasks/concat_videos.py +80 -0
- dw/tasks/depth_estimator.py +54 -0
- dw/tasks/diffusion_upscale.py +109 -0
- dw/tasks/format_messages.py +24 -0
- dw/tasks/gather.py +139 -0
- dw/tasks/image_to_text.py +43 -0
- dw/tasks/image_utils.py +661 -0
- dw/tasks/interpolate_frames.py +227 -0
- dw/tasks/model_cache.py +39 -0
- dw/tasks/pair_audio.py +58 -0
- dw/tasks/qr_code.py +19 -0
- dw/tasks/restore_faces.py +175 -0
- dw/tasks/rife_model.py +192 -0
- dw/tasks/segment.py +121 -0
- dw/tasks/task.py +474 -0
- dw/tasks/tensor_image.py +57 -0
- dw/tasks/text_generation.py +168 -0
- dw/tasks/text_sections.py +80 -0
- dw/tasks/upscale.py +203 -0
- dw/tasks/video_utils.py +154 -0
- dw/tasks/zoe_depth.py +71 -0
- dw/teacache.py +376 -0
- dw/teacache_models.json +99 -0
- dw/test.py +29 -0
- dw/type_helpers.py +68 -0
- dw/validate.py +43 -0
- dw/variables.py +153 -0
- dw/worker.py +517 -0
- dw/workflow.py +553 -0
- dw/workflow_schema.json +1157 -0
- dw/workflows/augment_prompt.json +65 -0
- dw/workflows/describe_image.json +58 -0
- dw/workflows/h3_context_ir.json +57 -0
- dw/workflows/test.json +31 -0
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
|