codelor-color 2.1.0__tar.gz
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.
- codelor_color-2.1.0/LICENSE +21 -0
- codelor_color-2.1.0/PKG-INFO +61 -0
- codelor_color-2.1.0/README.md +43 -0
- codelor_color-2.1.0/codelor_color/__init__.py +9 -0
- codelor_color-2.1.0/codelor_color/model.py +282 -0
- codelor_color-2.1.0/codelor_color.egg-info/PKG-INFO +61 -0
- codelor_color-2.1.0/codelor_color.egg-info/SOURCES.txt +10 -0
- codelor_color-2.1.0/codelor_color.egg-info/dependency_links.txt +1 -0
- codelor_color-2.1.0/codelor_color.egg-info/requires.txt +1 -0
- codelor_color-2.1.0/codelor_color.egg-info/top_level.txt +1 -0
- codelor_color-2.1.0/pyproject.toml +31 -0
- codelor_color-2.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Plimb-ai
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: codelor-color
|
|
3
|
+
Version: 2.1.0
|
|
4
|
+
Summary: A lightweight PyTorch Transformer architecture for Chroma Key (Green Screen).
|
|
5
|
+
Author-email: PlimbAi <plimb.ai.contact@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Plimb-ai/codelor-color
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/Plimb-ai/codelor-color/issues
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: torch>=2.0.0
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# Codelor Color Architecture πΏπ§
|
|
20
|
+
|
|
21
|
+
This repository contains the pure PyTorch architecture for Codelor Color, a lightweight Transformer designed for Chroma Key (green screen) segmentation.
|
|
22
|
+
|
|
23
|
+
Important note: The model weights (.safetensors), training scripts, and inference tools are available on the Hugging Face repository: plimb/codelor-color-1.2
|
|
24
|
+
|
|
25
|
+
## π¦ Installation
|
|
26
|
+
|
|
27
|
+
pip install codelor-color
|
|
28
|
+
|
|
29
|
+
## π Usage
|
|
30
|
+
|
|
31
|
+
You can instantiate the architecture directly and load your own weights.
|
|
32
|
+
|
|
33
|
+
import torch
|
|
34
|
+
from codelor_color import CodelorColor
|
|
35
|
+
|
|
36
|
+
# Initialize the architecture
|
|
37
|
+
model = CodelorColor(dim=128, depth=8, heads=8, tied_after=4)
|
|
38
|
+
|
|
39
|
+
# Load your weights
|
|
40
|
+
# state_dict = load_file("model.safetensors")
|
|
41
|
+
# model.load_state_dict(state_dict)
|
|
42
|
+
|
|
43
|
+
model.eval()
|
|
44
|
+
|
|
45
|
+
# Forward pass
|
|
46
|
+
img = torch.rand(1, 3, 160, 160)
|
|
47
|
+
ref = torch.tensor([[0.20, 0.85, 0.30]]) # Target color (Green)
|
|
48
|
+
|
|
49
|
+
with torch.no_grad():
|
|
50
|
+
prob_mask = torch.sigmoid(model(img, ref))
|
|
51
|
+
|
|
52
|
+
## ποΈ Architecture Details
|
|
53
|
+
|
|
54
|
+
- ConvNeXt-style Stem: Anti-aliased downsampling for crisp edges.
|
|
55
|
+
- Transformer Blocks: 8 blocks with 2D RoPE, QK-Norm, and weight sharing (tied_after).
|
|
56
|
+
- Color Cross-Attention: Injects the target RGB color at each block.
|
|
57
|
+
- Gated Decoder: FPN-like decoder with deep supervision and a Sobel edge head.
|
|
58
|
+
|
|
59
|
+
## π License
|
|
60
|
+
|
|
61
|
+
MIT License.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Codelor Color Architecture πΏπ§
|
|
2
|
+
|
|
3
|
+
This repository contains the pure PyTorch architecture for Codelor Color, a lightweight Transformer designed for Chroma Key (green screen) segmentation.
|
|
4
|
+
|
|
5
|
+
Important note: The model weights (.safetensors), training scripts, and inference tools are available on the Hugging Face repository: plimb/codelor-color-1.2
|
|
6
|
+
|
|
7
|
+
## π¦ Installation
|
|
8
|
+
|
|
9
|
+
pip install codelor-color
|
|
10
|
+
|
|
11
|
+
## π Usage
|
|
12
|
+
|
|
13
|
+
You can instantiate the architecture directly and load your own weights.
|
|
14
|
+
|
|
15
|
+
import torch
|
|
16
|
+
from codelor_color import CodelorColor
|
|
17
|
+
|
|
18
|
+
# Initialize the architecture
|
|
19
|
+
model = CodelorColor(dim=128, depth=8, heads=8, tied_after=4)
|
|
20
|
+
|
|
21
|
+
# Load your weights
|
|
22
|
+
# state_dict = load_file("model.safetensors")
|
|
23
|
+
# model.load_state_dict(state_dict)
|
|
24
|
+
|
|
25
|
+
model.eval()
|
|
26
|
+
|
|
27
|
+
# Forward pass
|
|
28
|
+
img = torch.rand(1, 3, 160, 160)
|
|
29
|
+
ref = torch.tensor([[0.20, 0.85, 0.30]]) # Target color (Green)
|
|
30
|
+
|
|
31
|
+
with torch.no_grad():
|
|
32
|
+
prob_mask = torch.sigmoid(model(img, ref))
|
|
33
|
+
|
|
34
|
+
## ποΈ Architecture Details
|
|
35
|
+
|
|
36
|
+
- ConvNeXt-style Stem: Anti-aliased downsampling for crisp edges.
|
|
37
|
+
- Transformer Blocks: 8 blocks with 2D RoPE, QK-Norm, and weight sharing (tied_after).
|
|
38
|
+
- Color Cross-Attention: Injects the target RGB color at each block.
|
|
39
|
+
- Gated Decoder: FPN-like decoder with deep supervision and a Sobel edge head.
|
|
40
|
+
|
|
41
|
+
## π License
|
|
42
|
+
|
|
43
|
+
MIT License.
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
import torch.nn.functional as F
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
# ============================================================
|
|
8
|
+
# ARCHITECTURE CODELOR COLOR
|
|
9
|
+
# ============================================================
|
|
10
|
+
|
|
11
|
+
class RMSNorm(nn.Module):
|
|
12
|
+
def __init__(self, dim, eps=1e-6):
|
|
13
|
+
super().__init__()
|
|
14
|
+
self.eps = eps
|
|
15
|
+
self.w = nn.Parameter(torch.ones(dim))
|
|
16
|
+
def forward(self, x):
|
|
17
|
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.w
|
|
18
|
+
|
|
19
|
+
class SwiGLU(nn.Module):
|
|
20
|
+
def __init__(self, dim, hidden):
|
|
21
|
+
super().__init__()
|
|
22
|
+
self.w12 = nn.Linear(dim, hidden * 2, bias=False)
|
|
23
|
+
self.w3 = nn.Linear(hidden, dim, bias=False)
|
|
24
|
+
def forward(self, x):
|
|
25
|
+
a, b = self.w12(x).chunk(2, dim=-1)
|
|
26
|
+
return self.w3(F.silu(a) * b)
|
|
27
|
+
|
|
28
|
+
class LayerScale(nn.Module):
|
|
29
|
+
def __init__(self, dim, init=1e-6):
|
|
30
|
+
super().__init__()
|
|
31
|
+
self.gamma = nn.Parameter(torch.ones(dim) * init)
|
|
32
|
+
def forward(self, x):
|
|
33
|
+
return x * self.gamma
|
|
34
|
+
|
|
35
|
+
class DropPath(nn.Module):
|
|
36
|
+
def __init__(self, p=0.0):
|
|
37
|
+
super().__init__()
|
|
38
|
+
self.p = p
|
|
39
|
+
def forward(self, x):
|
|
40
|
+
if self.p == 0.0 or not self.training:
|
|
41
|
+
return x
|
|
42
|
+
keep = 1 - self.p
|
|
43
|
+
mask = torch.rand(x.shape[0], 1, 1, device=x.device) < keep
|
|
44
|
+
return x * mask / keep
|
|
45
|
+
|
|
46
|
+
def rope_2d(q, k, h, w, base=100.0):
|
|
47
|
+
B, Hh, N, D = q.shape
|
|
48
|
+
d4 = D // 4
|
|
49
|
+
freqs = 1.0 / (base ** (torch.arange(0, d4, device=q.device).float() / d4))
|
|
50
|
+
xs = torch.arange(w, device=q.device).float()
|
|
51
|
+
ys = torch.arange(h, device=q.device).float()
|
|
52
|
+
ax = torch.outer(xs, freqs)[None, :, :].expand(h, w, d4).reshape(h * w, d4)
|
|
53
|
+
ay = torch.outer(ys, freqs)[:, None, :].expand(h, w, d4).reshape(h * w, d4)
|
|
54
|
+
ang = torch.cat([ax, ay], dim=-1)
|
|
55
|
+
cos, sin = ang.cos()[None, None], ang.sin()[None, None]
|
|
56
|
+
def rot(x):
|
|
57
|
+
x1, x2 = x[..., :D//2], x[..., D//2:]
|
|
58
|
+
return torch.cat([x1*cos - x2*sin, x1*sin + x2*cos], dim=-1)
|
|
59
|
+
return rot(q), rot(k)
|
|
60
|
+
|
|
61
|
+
class Attention(nn.Module):
|
|
62
|
+
def __init__(self, dim, heads):
|
|
63
|
+
super().__init__()
|
|
64
|
+
assert dim % heads == 0
|
|
65
|
+
self.heads = heads
|
|
66
|
+
self.dh = dim // heads
|
|
67
|
+
self.qkv = nn.Linear(dim, dim * 3, bias=False)
|
|
68
|
+
self.q_norm = RMSNorm(self.dh)
|
|
69
|
+
self.k_norm = RMSNorm(self.dh)
|
|
70
|
+
self.proj = nn.Linear(dim, dim, bias=False)
|
|
71
|
+
def forward(self, x, h, w):
|
|
72
|
+
B, N, C = x.shape
|
|
73
|
+
qkv = self.qkv(x).reshape(B, N, 3, self.heads, self.dh).permute(2, 0, 3, 1, 4)
|
|
74
|
+
q, k, v = qkv.unbind(0)
|
|
75
|
+
q, k = self.q_norm(q), self.k_norm(k)
|
|
76
|
+
q, k = rope_2d(q, k, h, w)
|
|
77
|
+
out = F.scaled_dot_product_attention(q, k, v)
|
|
78
|
+
return self.proj(out.transpose(1, 2).reshape(B, N, C))
|
|
79
|
+
|
|
80
|
+
class ColorCrossAttention(nn.Module):
|
|
81
|
+
def __init__(self, dim, heads):
|
|
82
|
+
super().__init__()
|
|
83
|
+
assert dim % heads == 0
|
|
84
|
+
self.heads = heads
|
|
85
|
+
self.dh = dim // heads
|
|
86
|
+
self.q = nn.Linear(dim, dim, bias=False)
|
|
87
|
+
self.kv = nn.Linear(dim, dim * 2, bias=False)
|
|
88
|
+
self.q_norm = RMSNorm(self.dh)
|
|
89
|
+
self.k_norm = RMSNorm(self.dh)
|
|
90
|
+
self.proj = nn.Linear(dim, dim, bias=False)
|
|
91
|
+
def forward(self, spatial, cond):
|
|
92
|
+
B, N, C = spatial.shape
|
|
93
|
+
M = cond.shape[1]
|
|
94
|
+
q = self.q(spatial).reshape(B, N, self.heads, self.dh).transpose(1, 2)
|
|
95
|
+
kv = self.kv(cond).reshape(B, M, 2, self.heads, self.dh).permute(2, 0, 3, 1, 4)
|
|
96
|
+
k, v = kv.unbind(0)
|
|
97
|
+
q, k = self.q_norm(q), self.k_norm(k)
|
|
98
|
+
out = F.scaled_dot_product_attention(q, k, v)
|
|
99
|
+
return self.proj(out.transpose(1, 2).reshape(B, N, C))
|
|
100
|
+
|
|
101
|
+
class Block(nn.Module):
|
|
102
|
+
def __init__(self, dim, heads, mlp_ratio=3.0, drop_path=0.0):
|
|
103
|
+
super().__init__()
|
|
104
|
+
self.norm1 = RMSNorm(dim)
|
|
105
|
+
self.attn = Attention(dim, heads)
|
|
106
|
+
self.ls1 = LayerScale(dim)
|
|
107
|
+
self.dp1 = DropPath(drop_path)
|
|
108
|
+
self.norm2 = RMSNorm(dim)
|
|
109
|
+
self.ffn = SwiGLU(dim, int(dim * mlp_ratio))
|
|
110
|
+
self.ls2 = LayerScale(dim)
|
|
111
|
+
self.dp2 = DropPath(drop_path)
|
|
112
|
+
def forward(self, x, h, w):
|
|
113
|
+
x = x + self.dp1(self.ls1(self.attn(self.norm1(x), h, w)))
|
|
114
|
+
return x + self.dp2(self.ls2(self.ffn(self.norm2(x))))
|
|
115
|
+
|
|
116
|
+
class AntiAliasDownsample(nn.Module):
|
|
117
|
+
def __init__(self, c_in, c_out):
|
|
118
|
+
super().__init__()
|
|
119
|
+
self.blur = nn.Conv2d(c_in, c_in, 3, padding=1, groups=c_in, bias=False)
|
|
120
|
+
kernel = torch.tensor([1., 2., 1.])
|
|
121
|
+
kernel = kernel / kernel.sum()
|
|
122
|
+
bk = kernel[:, None] * kernel[None, :]
|
|
123
|
+
with torch.no_grad():
|
|
124
|
+
self.blur.weight.copy_(bk.expand(c_in, 1, 3, 3))
|
|
125
|
+
self.blur.weight.requires_grad_(False)
|
|
126
|
+
self.conv = nn.Conv2d(c_in, c_out, 1, stride=2, bias=False)
|
|
127
|
+
self.bn = nn.BatchNorm2d(c_out)
|
|
128
|
+
self.act = nn.SiLU(inplace=True)
|
|
129
|
+
def forward(self, x):
|
|
130
|
+
return self.act(self.bn(self.conv(self.blur(x))))
|
|
131
|
+
|
|
132
|
+
class ConvNeXtStem(nn.Module):
|
|
133
|
+
def __init__(self, dim):
|
|
134
|
+
super().__init__()
|
|
135
|
+
self.patch = nn.Sequential(
|
|
136
|
+
nn.Conv2d(3, 32, kernel_size=4, stride=4, bias=False),
|
|
137
|
+
nn.BatchNorm2d(32), nn.SiLU(inplace=True))
|
|
138
|
+
self.block1 = nn.Sequential(
|
|
139
|
+
nn.Conv2d(32, 32, 7, padding=3, groups=32, bias=False),
|
|
140
|
+
nn.BatchNorm2d(32), nn.SiLU(inplace=True),
|
|
141
|
+
nn.Conv2d(32, 32, 1, bias=False),
|
|
142
|
+
nn.BatchNorm2d(32))
|
|
143
|
+
self.down8 = AntiAliasDownsample(32, 64)
|
|
144
|
+
self.down16 = AntiAliasDownsample(64, dim)
|
|
145
|
+
def forward(self, x):
|
|
146
|
+
x = self.patch(x)
|
|
147
|
+
x = x + self.block1(x)
|
|
148
|
+
f4 = x
|
|
149
|
+
f8 = self.down8(f4)
|
|
150
|
+
f16 = self.down16(f8)
|
|
151
|
+
return f4, f8, f16
|
|
152
|
+
|
|
153
|
+
class SobelEdge(nn.Module):
|
|
154
|
+
def __init__(self):
|
|
155
|
+
super().__init__()
|
|
156
|
+
sx = torch.tensor([[-1,0,1],[-2,0,2],[-1,0,1]]).float().view(1,1,3,3)
|
|
157
|
+
sy = torch.tensor([[-1,-2,-1],[0,0,0],[1,2,1]]).float().view(1,1,3,3)
|
|
158
|
+
self.register_buffer('sx', sx)
|
|
159
|
+
self.register_buffer('sy', sy)
|
|
160
|
+
def forward(self, gray):
|
|
161
|
+
ex = F.conv2d(gray, self.sx, padding=1)
|
|
162
|
+
ey = F.conv2d(gray, self.sy, padding=1)
|
|
163
|
+
return (ex**2 + ey**2 + 1e-6).sqrt()
|
|
164
|
+
|
|
165
|
+
class GatedDecoder(nn.Module):
|
|
166
|
+
def __init__(self, dim):
|
|
167
|
+
super().__init__()
|
|
168
|
+
self.proj16 = nn.Conv2d(dim, dim, 1, bias=False)
|
|
169
|
+
self.aux_head = nn.Conv2d(dim, 1, 1)
|
|
170
|
+
self.up8 = nn.Sequential(
|
|
171
|
+
nn.Conv2d(dim+64, dim, 3, padding=1, bias=False),
|
|
172
|
+
nn.BatchNorm2d(dim), nn.SiLU(inplace=True))
|
|
173
|
+
self.up4 = nn.Sequential(
|
|
174
|
+
nn.Conv2d(dim+32, 64, 3, padding=1, bias=False),
|
|
175
|
+
nn.BatchNorm2d(64), nn.SiLU(inplace=True))
|
|
176
|
+
self.up1 = nn.Sequential(
|
|
177
|
+
nn.Conv2d(64+3+1+1, 32, 3, padding=1, bias=False),
|
|
178
|
+
nn.BatchNorm2d(32), nn.SiLU(inplace=True),
|
|
179
|
+
nn.Conv2d(32, 32, 3, padding=1, bias=False),
|
|
180
|
+
nn.BatchNorm2d(32), nn.SiLU(inplace=True))
|
|
181
|
+
self.head = nn.Conv2d(32, 1, 1)
|
|
182
|
+
self.gate8 = nn.Parameter(torch.zeros(1))
|
|
183
|
+
self.gate4 = nn.Parameter(torch.zeros(1))
|
|
184
|
+
self.edge = SobelEdge()
|
|
185
|
+
def forward(self, latent, f4, f8, img, ref_rgb):
|
|
186
|
+
B, _, H, W = img.shape
|
|
187
|
+
x = self.proj16(latent)
|
|
188
|
+
aux = self.aux_head(x)
|
|
189
|
+
aux = F.interpolate(aux, size=f4.shape[-2:], mode='bilinear', align_corners=False)
|
|
190
|
+
x = F.interpolate(x, size=f8.shape[-2:], mode='bilinear', align_corners=False)
|
|
191
|
+
x = self.up8(torch.cat([x, torch.sigmoid(self.gate8) * f8], 1))
|
|
192
|
+
x = F.interpolate(x, size=f4.shape[-2:], mode='bilinear', align_corners=False)
|
|
193
|
+
x = self.up4(torch.cat([x, torch.sigmoid(self.gate4) * f4], 1))
|
|
194
|
+
x = F.interpolate(x, size=(H, W), mode='bilinear', align_corners=False)
|
|
195
|
+
ref_map = ref_rgb.view(B, 3, 1, 1).expand(B, 3, H, W)
|
|
196
|
+
cos = F.cosine_similarity(img, ref_map, dim=1, eps=1e-6).unsqueeze(1)
|
|
197
|
+
gray = img.mean(1, keepdim=True)
|
|
198
|
+
edge = self.edge(gray)
|
|
199
|
+
x = self.up1(torch.cat([x, img, cos, edge], 1))
|
|
200
|
+
return self.head(x), aux
|
|
201
|
+
|
|
202
|
+
class CodelorColor(nn.Module):
|
|
203
|
+
def __init__(self, dim=128, depth=8, heads=8, tied_after=4, mlp_ratio=3.0, max_tokens=1024, drop_path_rate=0.1):
|
|
204
|
+
super().__init__()
|
|
205
|
+
self.dim, self.depth, self.heads = dim, depth, heads
|
|
206
|
+
self.tied_after, self.mlp_ratio = tied_after, mlp_ratio
|
|
207
|
+
self.max_tokens = max_tokens
|
|
208
|
+
self.stem = ConvNeXtStem(dim)
|
|
209
|
+
self.color_mlp = nn.Sequential(
|
|
210
|
+
nn.Linear(3, dim), nn.SiLU(inplace=True), nn.Linear(dim, dim))
|
|
211
|
+
self.pos = nn.Parameter(torch.zeros(1, max_tokens, dim))
|
|
212
|
+
nn.init.trunc_normal_(self.pos, std=0.02)
|
|
213
|
+
n_unique = depth if tied_after <= 0 else min(depth, tied_after)
|
|
214
|
+
dp = [drop_path_rate * i / max(1, depth - 1) for i in range(depth)]
|
|
215
|
+
self.blocks = nn.ModuleList([
|
|
216
|
+
Block(dim, heads, mlp_ratio, drop_path=dp[i] if i < len(dp) else 0.0)
|
|
217
|
+
for i in range(n_unique)])
|
|
218
|
+
self.color_xattn = nn.ModuleList([
|
|
219
|
+
ColorCrossAttention(dim, heads) for _ in range(n_unique)])
|
|
220
|
+
self.norm_out = RMSNorm(dim)
|
|
221
|
+
self.decoder = GatedDecoder(dim)
|
|
222
|
+
|
|
223
|
+
def _get(self, i):
|
|
224
|
+
if self.tied_after > 0 and i >= self.tied_after:
|
|
225
|
+
return self.blocks[i - self.tied_after], self.color_xattn[i - self.tied_after]
|
|
226
|
+
return self.blocks[i], self.color_xattn[i]
|
|
227
|
+
|
|
228
|
+
def forward(self, img, ref_rgb, return_aux=False):
|
|
229
|
+
B = img.shape[0]
|
|
230
|
+
f4, f8, f16 = self.stem(img)
|
|
231
|
+
_, _, h, w = f16.shape
|
|
232
|
+
N = h * w
|
|
233
|
+
tokens = f16.flatten(2).transpose(1, 2)
|
|
234
|
+
if N <= self.pos.shape[1]:
|
|
235
|
+
tokens = tokens + self.pos[:, :N]
|
|
236
|
+
c_tok = self.color_mlp(ref_rgb).unsqueeze(1)
|
|
237
|
+
x = tokens
|
|
238
|
+
for i in range(self.depth):
|
|
239
|
+
blk, xa = self._get(i)
|
|
240
|
+
x = blk(x, h, w)
|
|
241
|
+
x = x + xa(x, c_tok)
|
|
242
|
+
x = self.norm_out(x)
|
|
243
|
+
latent = x.transpose(1, 2).reshape(B, -1, h, w)
|
|
244
|
+
main, aux = self.decoder(latent, f4, f8, img, ref_rgb)
|
|
245
|
+
return (main, aux) if return_aux else main
|
|
246
|
+
|
|
247
|
+
def config(self):
|
|
248
|
+
return dict(dim=self.dim, depth=self.depth, heads=self.heads,
|
|
249
|
+
tied_after=self.tied_after, mlp_ratio=self.mlp_ratio,
|
|
250
|
+
max_tokens=self.max_tokens)
|
|
251
|
+
|
|
252
|
+
# ============================================================
|
|
253
|
+
# FONCTIONS UTILITAIRES
|
|
254
|
+
# ============================================================
|
|
255
|
+
|
|
256
|
+
def load_from_pretrained(path_or_repo, device="cpu"):
|
|
257
|
+
p = Path(path_or_repo)
|
|
258
|
+
if not p.exists():
|
|
259
|
+
from huggingface_hub import snapshot_download
|
|
260
|
+
p = Path(snapshot_download(path_or_repo))
|
|
261
|
+
cfg = json.loads((p / "config.json").read_text())
|
|
262
|
+
model = CodelorColor(**cfg["hyperparameters"])
|
|
263
|
+
from safetensors.torch import load_file
|
|
264
|
+
model.load_state_dict(load_file(p / "model.safetensors"))
|
|
265
|
+
return model.eval().to(device)
|
|
266
|
+
|
|
267
|
+
def predict_mask(model, image_tensor, color_rgb=None, threshold=0.5, device="cpu"):
|
|
268
|
+
if color_rgb is None:
|
|
269
|
+
color_rgb = (0.20, 0.85, 0.30)
|
|
270
|
+
if image_tensor.ndim == 3:
|
|
271
|
+
image_tensor = image_tensor.unsqueeze(0)
|
|
272
|
+
image_tensor = image_tensor.to(device)
|
|
273
|
+
ref = torch.tensor(color_rgb, dtype=torch.float32, device=device).view(1, 3)
|
|
274
|
+
with torch.no_grad():
|
|
275
|
+
prob = torch.sigmoid(model(image_tensor, ref))[0, 0].cpu().numpy()
|
|
276
|
+
return prob > threshold, prob
|
|
277
|
+
|
|
278
|
+
def remove_green(image_tensor, model, color_rgb=None, threshold=0.5, device="cpu"):
|
|
279
|
+
import numpy as np
|
|
280
|
+
_, prob = predict_mask(model, image_tensor, color_rgb, threshold, device)
|
|
281
|
+
alpha = torch.from_numpy((1.0 - prob.astype("float32")).clip(0, 1)).unsqueeze(0)
|
|
282
|
+
return torch.cat([image_tensor.cpu(), alpha], dim=0)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: codelor-color
|
|
3
|
+
Version: 2.1.0
|
|
4
|
+
Summary: A lightweight PyTorch Transformer architecture for Chroma Key (Green Screen).
|
|
5
|
+
Author-email: PlimbAi <plimb.ai.contact@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Plimb-ai/codelor-color
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/Plimb-ai/codelor-color/issues
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: torch>=2.0.0
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# Codelor Color Architecture πΏπ§
|
|
20
|
+
|
|
21
|
+
This repository contains the pure PyTorch architecture for Codelor Color, a lightweight Transformer designed for Chroma Key (green screen) segmentation.
|
|
22
|
+
|
|
23
|
+
Important note: The model weights (.safetensors), training scripts, and inference tools are available on the Hugging Face repository: plimb/codelor-color-1.2
|
|
24
|
+
|
|
25
|
+
## π¦ Installation
|
|
26
|
+
|
|
27
|
+
pip install codelor-color
|
|
28
|
+
|
|
29
|
+
## π Usage
|
|
30
|
+
|
|
31
|
+
You can instantiate the architecture directly and load your own weights.
|
|
32
|
+
|
|
33
|
+
import torch
|
|
34
|
+
from codelor_color import CodelorColor
|
|
35
|
+
|
|
36
|
+
# Initialize the architecture
|
|
37
|
+
model = CodelorColor(dim=128, depth=8, heads=8, tied_after=4)
|
|
38
|
+
|
|
39
|
+
# Load your weights
|
|
40
|
+
# state_dict = load_file("model.safetensors")
|
|
41
|
+
# model.load_state_dict(state_dict)
|
|
42
|
+
|
|
43
|
+
model.eval()
|
|
44
|
+
|
|
45
|
+
# Forward pass
|
|
46
|
+
img = torch.rand(1, 3, 160, 160)
|
|
47
|
+
ref = torch.tensor([[0.20, 0.85, 0.30]]) # Target color (Green)
|
|
48
|
+
|
|
49
|
+
with torch.no_grad():
|
|
50
|
+
prob_mask = torch.sigmoid(model(img, ref))
|
|
51
|
+
|
|
52
|
+
## ποΈ Architecture Details
|
|
53
|
+
|
|
54
|
+
- ConvNeXt-style Stem: Anti-aliased downsampling for crisp edges.
|
|
55
|
+
- Transformer Blocks: 8 blocks with 2D RoPE, QK-Norm, and weight sharing (tied_after).
|
|
56
|
+
- Color Cross-Attention: Injects the target RGB color at each block.
|
|
57
|
+
- Gated Decoder: FPN-like decoder with deep supervision and a Sobel edge head.
|
|
58
|
+
|
|
59
|
+
## π License
|
|
60
|
+
|
|
61
|
+
MIT License.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
codelor_color/__init__.py
|
|
5
|
+
codelor_color/model.py
|
|
6
|
+
codelor_color.egg-info/PKG-INFO
|
|
7
|
+
codelor_color.egg-info/SOURCES.txt
|
|
8
|
+
codelor_color.egg-info/dependency_links.txt
|
|
9
|
+
codelor_color.egg-info/requires.txt
|
|
10
|
+
codelor_color.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
torch>=2.0.0
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
codelor_color
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "codelor-color"
|
|
7
|
+
version = "2.1.0"
|
|
8
|
+
description = "A lightweight PyTorch Transformer architecture for Chroma Key (Green Screen)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "PlimbAi", email = "plimb.ai.contact@gmail.com"}
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
20
|
+
]
|
|
21
|
+
dependencies = [
|
|
22
|
+
"torch>=2.0.0"
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://github.com/Plimb-ai/codelor-color"
|
|
27
|
+
"Bug Tracker" = "https://github.com/Plimb-ai/codelor-color/issues"
|
|
28
|
+
|
|
29
|
+
[tool.setuptools.packages.find]
|
|
30
|
+
where = ["."]
|
|
31
|
+
include = ["codelor_color*"]
|