blocklearning 0.1.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.
- blocklearning/__init__.py +1 -0
- blocklearning/__main__.py +6 -0
- blocklearning/analysis.py +133 -0
- blocklearning/anomaly.py +148 -0
- blocklearning/blocks.py +601 -0
- blocklearning/cli.py +46 -0
- blocklearning/codegen.py +1012 -0
- blocklearning/core.py +861 -0
- blocklearning/data/bearing_uottawa.SOURCE.txt +6 -0
- blocklearning/data/bearing_uottawa.npz +0 -0
- blocklearning/data/concrete.SOURCE.txt +4 -0
- blocklearning/data/concrete.npz +0 -0
- blocklearning/data/digits32.SOURCE.txt +4 -0
- blocklearning/data/digits32.npz +0 -0
- blocklearning/data/ecg_mitdb.SOURCE.txt +6 -0
- blocklearning/data/ecg_mitdb.npz +0 -0
- blocklearning/data/hydraulic.SOURCE.txt +6 -0
- blocklearning/data/hydraulic.npz +0 -0
- blocklearning/data/pcb_det.SOURCE.txt +6 -0
- blocklearning/data/pcb_det.npz +0 -0
- blocklearning/data/pneumatic_seg.SOURCE.txt +8 -0
- blocklearning/data/pneumatic_seg.npz +0 -0
- blocklearning/data/pneumonia28.SOURCE.txt +13 -0
- blocklearning/data/pneumonia28.npz +0 -0
- blocklearning/data/steel_plates.SOURCE.txt +5 -0
- blocklearning/data/steel_plates.npz +0 -0
- blocklearning/data/steel_power.SOURCE.txt +3 -0
- blocklearning/data/steel_power.npz +0 -0
- blocklearning/data/steelblast.SOURCE.txt +4 -0
- blocklearning/data/steelblast.npz +0 -0
- blocklearning/data.py +1158 -0
- blocklearning/detect.py +222 -0
- blocklearning/forecast.py +204 -0
- blocklearning/graph.py +602 -0
- blocklearning/jobs.py +501 -0
- blocklearning/labeling.py +1294 -0
- blocklearning/labeling_sources.py +217 -0
- blocklearning/layers.py +615 -0
- blocklearning/losses.py +199 -0
- blocklearning/multi.py +175 -0
- blocklearning/nn_extra.py +643 -0
- blocklearning/predict.py +344 -0
- blocklearning/pretrained/LICENSE-mnv3s.txt +202 -0
- blocklearning/pretrained/mnv3s.SOURCE.txt +6 -0
- blocklearning/pretrained/mnv3s.bin +0 -0
- blocklearning/pretrained/mnv3s.json +1 -0
- blocklearning/pretrained.py +56 -0
- blocklearning/project.py +120 -0
- blocklearning/segment.py +173 -0
- blocklearning/server.py +116 -0
- blocklearning/static/app.js +1986 -0
- blocklearning/static/boot.js +51 -0
- blocklearning/static/demo.jpg +0 -0
- blocklearning/static/demo.webm +0 -0
- blocklearning/static/engine.js +1326 -0
- blocklearning/static/graph.js +1902 -0
- blocklearning/static/index.html +301 -0
- blocklearning/static/label.html +158 -0
- blocklearning/static/label.js +1040 -0
- blocklearning/static/labels.js +227 -0
- blocklearning/static/projects.js +516 -0
- blocklearning/static/store.js +259 -0
- blocklearning/static/style.css +844 -0
- blocklearning/static/train-worker.js +41 -0
- blocklearning/static/web.js +602 -0
- blocklearning/tasks.py +351 -0
- blocklearning/web.py +412 -0
- blocklearning/weblabel.py +316 -0
- blocklearning-0.1.0.dist-info/METADATA +66 -0
- blocklearning-0.1.0.dist-info/RECORD +74 -0
- blocklearning-0.1.0.dist-info/WHEEL +4 -0
- blocklearning-0.1.0.dist-info/entry_points.txt +2 -0
- blocklearning-0.1.0.dist-info/licenses/LICENSE +25 -0
- blocklearning-0.1.0.dist-info/licenses/src/blocklearning/pretrained/LICENSE-mnv3s.txt +202 -0
blocklearning/blocks.py
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
"""블록: 화면에서 쌓은 블록 JSON을 검증하고, 블록마다 출력 모양을 계산하고, torch 모델로 만든다.
|
|
2
|
+
|
|
3
|
+
블록 JSON은 위에서 아래 순서의 목록. 감싸는 블록(residual·repeat)은 "body" 목록을 가진다.
|
|
4
|
+
블록 위치(Path)는 최상위 i → (i,), body 안 j → (i, j), 더 깊으면 계속.
|
|
5
|
+
검증을 통과한 조립은 모델 만들기(build_model)가 실패하지 않는다.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
from blocklearning import layers as X
|
|
12
|
+
|
|
13
|
+
BLOCK_TYPES = ("conv", "pool", "global_avg", "last_step", "bn", "act", "dropout", "flatten", "dense", "lstm", "gru",
|
|
14
|
+
"simple_rnn", "se", "branch", "residual", "repeat", "output", "conv2d", "pool2d", "global_avg2d") + X.EXTRA_TYPES
|
|
15
|
+
CNN_TYPES = ("conv", "pool", "global_avg", "last_step", "se", "branch") # 시간 축이 있어야 하는 층
|
|
16
|
+
ONE_D_TYPES = ("conv", "pool", "global_avg", "last_step", "se") # 시계열·표 전용 (이미지에서 못 씀)
|
|
17
|
+
IMAGE_TYPES = ("conv2d", "pool2d", "global_avg2d") # 이미지 전용
|
|
18
|
+
RNN_TYPES = ("lstm", "gru", "simple_rnn")
|
|
19
|
+
ACT_KINDS = ("relu", "leaky_relu", "gelu", "silu", "elu", "mish", "softplus", "sigmoid", "tanh",
|
|
20
|
+
"selu", "relu6", "hardswish", "hardsigmoid", "softmax")
|
|
21
|
+
# 한도: 실수로 PC가 멈출 만큼 큰 모델만 막는 안전선
|
|
22
|
+
MAX_WIDTH = 65536 # Dense 입력·출력 개수
|
|
23
|
+
MAX_CHANNEL_LEN = 1048576 # 채널 하나의 길이(이미지면 높이×너비)
|
|
24
|
+
|
|
25
|
+
NAMES = {"conv": "Conv1D", "pool": "AvgPool1D", "global_avg": "GlobalAvgPool1D", "last_step": "LastTimestep",
|
|
26
|
+
"bn": "BatchNorm", "act": "Activation", "dropout": "Dropout", "flatten": "Flatten", "dense": "Dense",
|
|
27
|
+
"lstm": "LSTM", "gru": "GRU", "simple_rnn": "SimpleRNN", "se": "SE block", "branch": "Concat branches", "residual": "Residual block",
|
|
28
|
+
"repeat": "Repeat", "conv2d": "Conv2D", "pool2d": "AvgPool2D", "global_avg2d": "GlobalAvgPool2D",
|
|
29
|
+
"output": "Output", **X.EXTRA_NAMES}
|
|
30
|
+
|
|
31
|
+
Path = tuple
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class BlockIssue:
|
|
36
|
+
path: tuple
|
|
37
|
+
message: str
|
|
38
|
+
hint: str
|
|
39
|
+
|
|
40
|
+
def to_dict(self) -> dict:
|
|
41
|
+
return {"path": list(self.path), "message": self.message, "hint": self.hint}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class Checked:
|
|
46
|
+
issues: list = field(default_factory=list)
|
|
47
|
+
shapes: dict = field(default_factory=dict) # Path → 블록 뒤 모양 (배치 제외): (C, L) 또는 (n,)
|
|
48
|
+
kind: str = "cnn"
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def ok(self) -> bool:
|
|
52
|
+
return not self.issues
|
|
53
|
+
|
|
54
|
+
def to_dict(self) -> dict:
|
|
55
|
+
return {"ok": self.ok, "kind": self.kind, "issues": [i.to_dict() for i in self.issues],
|
|
56
|
+
"shapes": [{"path": list(p), "shape": list(s)} for p, s in self.shapes.items()]}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _int(b: dict, key: str, lo: int, hi: int, default=None, choices=None):
|
|
60
|
+
v = b.get(key, default)
|
|
61
|
+
if isinstance(v, bool) or not isinstance(v, int):
|
|
62
|
+
return None
|
|
63
|
+
if choices is not None:
|
|
64
|
+
return v if v in choices else None
|
|
65
|
+
return v if lo <= v <= hi else None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# 값 규칙: (키, 최소, 최대, 기본값, 허용 값, 설명)
|
|
69
|
+
PARAMS = {
|
|
70
|
+
"conv": [("channels", 1, 256, None, None, "filters는 1–256"), ("kernel", 1, 31, None, tuple(range(1, 32, 2)),
|
|
71
|
+
"kernel size는 1–31의 홀수"), ("stride", 1, 2, 1, (1, 2), "stride는 1 또는 2"),
|
|
72
|
+
("dilation", 1, 64, 1, None, "dilation은 1–64"), ("groups", 1, 256, 1, None, "groups는 1–256")],
|
|
73
|
+
"pool": [("size", 2, 4, None, (2, 4), "pool size는 2 또는 4")],
|
|
74
|
+
"conv2d": [("channels", 1, 256, None, None, "filters는 1–256"), ("kernel", 1, 7, None, (1, 3, 5, 7), "kernel size는 1·3·5·7"),
|
|
75
|
+
("stride", 1, 2, 1, (1, 2), "stride는 1 또는 2"), ("dilation", 1, 8, 1, (1, 2, 4, 8), "dilation은 1·2·4·8"),
|
|
76
|
+
("groups", 1, 256, 1, None, "groups는 1–256")],
|
|
77
|
+
"pool2d": [("size", 2, 2, 2, (2,), "pool size는 2")],
|
|
78
|
+
"dense": [("units", 1, 1024, None, None, "units는 1–1024")],
|
|
79
|
+
"lstm": [("hidden", 1, 256, None, None, "units는 1–256"), ("layers", 1, 3, 1, None, "layers는 1–3")],
|
|
80
|
+
"gru": [("hidden", 1, 256, None, None, "units는 1–256"), ("layers", 1, 3, 1, None, "layers는 1–3")],
|
|
81
|
+
"simple_rnn": [("hidden", 1, 256, None, None, "units는 1–256"), ("layers", 1, 3, 1, None, "layers는 1–3")],
|
|
82
|
+
"repeat": [("times", 1, 10, None, None, "repeat count는 1–10")],
|
|
83
|
+
"se": [("ratio", 1, 64, 4, None, "ratio는 1–64")],
|
|
84
|
+
**X.EXTRA_PARAMS,
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class _Walker:
|
|
89
|
+
def __init__(self, n_out: int, image: bool = False):
|
|
90
|
+
self.n_out = n_out
|
|
91
|
+
self.image = image
|
|
92
|
+
self.max_width = MAX_WIDTH
|
|
93
|
+
self.max_len = MAX_CHANNEL_LEN
|
|
94
|
+
self.issues: list = []
|
|
95
|
+
self.shapes: dict = {}
|
|
96
|
+
|
|
97
|
+
def issue(self, path, message, hint):
|
|
98
|
+
self.issues.append(BlockIssue(tuple(path), message, hint))
|
|
99
|
+
|
|
100
|
+
def values_ok(self, b: dict, path) -> bool:
|
|
101
|
+
ok = True
|
|
102
|
+
for key, lo, hi, default, choices, desc in PARAMS.get(b["type"], []):
|
|
103
|
+
if _int(b, key, lo, hi, default, choices) is None:
|
|
104
|
+
self.issue(path, f"{NAMES[b['type']]}: {key} 값 {b.get(key)!r}이(가) 맞지 않음", desc)
|
|
105
|
+
ok = False
|
|
106
|
+
if b["type"] == "act" and b.get("kind") not in ACT_KINDS:
|
|
107
|
+
self.issue(path, f"Activation 종류 {b.get('kind')!r}을(를) 모름", "목록에 있는 함수 중에서 고르세요")
|
|
108
|
+
ok = False
|
|
109
|
+
if b["type"] == "se" and b.get("act", "relu") not in ACT_KINDS:
|
|
110
|
+
self.issue(path, f"SE block: 안쪽 activation {b.get('act')!r}을(를) 모름", "ReLU 등 목록에 있는 함수로")
|
|
111
|
+
ok = False
|
|
112
|
+
pads = ("same", "valid", "causal") if b["type"] == "conv" else ("same", "valid")
|
|
113
|
+
if b["type"] in ("conv", "conv2d") and b.get("padding", "same") not in pads:
|
|
114
|
+
self.issue(path, f"{NAMES[b['type']]}: padding {b.get('padding')!r}이(가) 맞지 않음", "padding은 " + "·".join(pads))
|
|
115
|
+
ok = False
|
|
116
|
+
if b["type"] in RNN_TYPES:
|
|
117
|
+
for key in ("bidirectional", "return_sequences"):
|
|
118
|
+
if not isinstance(b.get(key, False), bool):
|
|
119
|
+
self.issue(path, f"{NAMES[b['type']]}: {key} 값 {b.get(key)!r}이(가) 맞지 않음", "참·거짓으로")
|
|
120
|
+
ok = False
|
|
121
|
+
if b["type"] in X.EXTRA_TYPES and not X.values_ok(self, b, path):
|
|
122
|
+
ok = False
|
|
123
|
+
if b["type"] == "dropout":
|
|
124
|
+
r = b.get("rate", 0.5)
|
|
125
|
+
if isinstance(r, bool) or not isinstance(r, (int, float)) or not 0 <= r < 1:
|
|
126
|
+
self.issue(path, f"Dropout: rate {r!r}이(가) 맞지 않음", "rate는 0 이상 1 미만 (예: 0.2)")
|
|
127
|
+
ok = False
|
|
128
|
+
return ok
|
|
129
|
+
|
|
130
|
+
def walk(self, blocks: list, shape, prefix: tuple, ctx: str):
|
|
131
|
+
"""블록 목록을 따라 모양을 계산. shape: (C, L) 또는 (n,), 모르면 None. ctx: top | residual | repeat."""
|
|
132
|
+
for i, b in enumerate(blocks):
|
|
133
|
+
path = prefix + (i,)
|
|
134
|
+
if not isinstance(b, dict) or b.get("type") not in BLOCK_TYPES:
|
|
135
|
+
t = b.get("type") if isinstance(b, dict) else b
|
|
136
|
+
self.issue(path, f"알 수 없는 블록 {t!r}", "팔레트에 있는 블록만 쓸 수 있습니다")
|
|
137
|
+
shape = None
|
|
138
|
+
continue
|
|
139
|
+
shape = self.block(b, shape, path, ctx, first=(prefix == () and i == 0), last=(i == len(blocks) - 1))
|
|
140
|
+
if shape is not None:
|
|
141
|
+
self.shapes[path] = tuple(shape) # repeat 안은 마지막 반복 값이 남음
|
|
142
|
+
return shape
|
|
143
|
+
|
|
144
|
+
def block(self, b: dict, shape, path, ctx, first: bool, last: bool):
|
|
145
|
+
t = b["type"]
|
|
146
|
+
if not self.values_ok(b, path):
|
|
147
|
+
return None
|
|
148
|
+
if t == "output":
|
|
149
|
+
if ctx != "top" or not last:
|
|
150
|
+
self.issue(path, "출력 블록은 맨 아래에 하나만", "출력 블록을 맨 아래로 옮기세요")
|
|
151
|
+
if getattr(self.n_out, "grid", None):
|
|
152
|
+
return self.det_head(shape, path)
|
|
153
|
+
if b.get("head") == "distance":
|
|
154
|
+
return self.dist_head(shape, path)
|
|
155
|
+
if getattr(self.n_out, "seg", False):
|
|
156
|
+
return self.seg_head(shape, path)
|
|
157
|
+
return self.dense_like(shape, self.n_out, path)
|
|
158
|
+
if shape is None:
|
|
159
|
+
return None
|
|
160
|
+
if t in RNN_TYPES: # (채널, 길이)를 시점마다 채널 수만큼의 값으로 읽음
|
|
161
|
+
if len(shape) != 2:
|
|
162
|
+
self.issue(path, f"{NAMES[t]}은(는) (채널, 길이) 모양에만 쓸 수 있음 (지금 {tuple(shape)})",
|
|
163
|
+
"이미지는 ToSequence 뒤에, Dense·GlobalPool 뒤에는 쓸 수 없음 (앞 순환 층은 return_sequences를 켜세요)")
|
|
164
|
+
return None
|
|
165
|
+
h = b["hidden"] * (2 if b.get("bidirectional") else 1)
|
|
166
|
+
return (h, shape[1]) if b.get("return_sequences") else (h,)
|
|
167
|
+
if t in X.EXTRA_TYPES:
|
|
168
|
+
return X.shape(self, b, shape, path, ctx)
|
|
169
|
+
if t in IMAGE_TYPES and len(shape) != 3:
|
|
170
|
+
self.issue(path, f"{NAMES[t]}은(는) (채널, 높이, 너비) 모양에만 쓸 수 있음 (지금 {tuple(shape)})",
|
|
171
|
+
"시계열에는 Conv1D·AvgPool1D를 쓰세요 (Spectrogram 뒤에는 됨). GlobalAvgPool2D·Flatten·Dense 뒤에는 쓸 수 없습니다")
|
|
172
|
+
return None
|
|
173
|
+
if t == "se" and len(shape) not in (2, 3):
|
|
174
|
+
self.issue(path, f"SE block은 (채널, 길이)나 (채널, 높이, 너비) 모양에만 (지금 {tuple(shape)})", X.SPATIAL_HINT)
|
|
175
|
+
return None
|
|
176
|
+
if t in CNN_TYPES and t != "se" and len(shape) != 2 and not (t == "branch" and len(shape) == 3):
|
|
177
|
+
self.issue(path, f"{NAMES[t]}은(는) (채널, 길이) 모양에만 쓸 수 있음 (지금 {tuple(shape)})",
|
|
178
|
+
"이미지에는 Conv2D·AvgPool2D 등 2D 층을 쓰세요 (ToSequence 뒤에는 됨). LSTM·GlobalAvgPool·Dense 뒤에는 쓸 수 없습니다")
|
|
179
|
+
return None
|
|
180
|
+
C, L = shape if len(shape) == 2 else (shape[0], None) if len(shape) == 3 else (None, None)
|
|
181
|
+
if t == "conv2d":
|
|
182
|
+
stride, valid, k = b.get("stride", 1), b.get("padding", "same") == "valid", b["kernel"]
|
|
183
|
+
d, g = b.get("dilation", 1), b.get("groups", 1)
|
|
184
|
+
if ctx == "residual" and (stride != 1 or valid):
|
|
185
|
+
self.issue(path, "Residual block 안에서는 stride 2나 padding valid를 쓸 수 없음 (크기가 바뀜)",
|
|
186
|
+
"stride 1, padding same으로 하거나 Residual block 밖으로 옮기세요")
|
|
187
|
+
return None
|
|
188
|
+
if C % g or b["channels"] % g:
|
|
189
|
+
self.issue(path, f"groups {g}가 들어오는 채널 {C}과 filters {b['channels']}을(를) 나누지 못함",
|
|
190
|
+
"groups는 두 채널 수의 공약수로 (depthwise는 DepthwiseConv2D 블록)")
|
|
191
|
+
return None
|
|
192
|
+
size = (lambda n: (n - d * (k - 1) - 1) // stride + 1) if valid else (lambda n: -(-n // stride))
|
|
193
|
+
return self.grid(b["channels"], size(shape[1]), size(shape[2]), path)
|
|
194
|
+
if t == "pool2d":
|
|
195
|
+
if ctx == "residual":
|
|
196
|
+
self.issue(path, "Residual block 안에서는 AvgPool2D를 쓸 수 없음 (크기가 바뀜)", "AvgPool2D를 Residual block 밖으로 옮기세요")
|
|
197
|
+
return None
|
|
198
|
+
return self.grid(C, shape[1] // 2, shape[2] // 2, path)
|
|
199
|
+
if t == "global_avg2d":
|
|
200
|
+
if ctx == "residual":
|
|
201
|
+
self.issue(path, "Residual block 안에서는 GlobalAvgPool2D를 쓸 수 없음", "GlobalAvgPool2D를 Residual block 밖으로 옮기세요")
|
|
202
|
+
return None
|
|
203
|
+
return (C,)
|
|
204
|
+
if t == "conv":
|
|
205
|
+
stride, d, g = b.get("stride", 1), b.get("dilation", 1), b.get("groups", 1)
|
|
206
|
+
valid = b.get("padding", "same") == "valid"
|
|
207
|
+
if ctx == "residual" and (stride != 1 or valid):
|
|
208
|
+
self.issue(path, "Residual block 안에서는 stride 2나 padding valid를 쓸 수 없음 (길이가 바뀜)",
|
|
209
|
+
"stride 1, padding same으로 하거나 Residual block 밖으로 옮기세요")
|
|
210
|
+
return None
|
|
211
|
+
if C % g or b["channels"] % g:
|
|
212
|
+
self.issue(path, f"groups {g}가 들어오는 채널 {C}과 filters {b['channels']}을(를) 나누지 못함",
|
|
213
|
+
"groups는 두 채널 수의 공약수로 (depthwise는 groups = filters = 들어오는 채널)")
|
|
214
|
+
return None
|
|
215
|
+
out_len = (L - d * (b["kernel"] - 1) - 1) // stride + 1 if valid else -(-L // stride)
|
|
216
|
+
return self.seq(b["channels"], out_len, path)
|
|
217
|
+
if t == "pool":
|
|
218
|
+
if ctx == "residual":
|
|
219
|
+
self.issue(path, "Residual block 안에서는 AvgPool1D를 쓸 수 없음 (길이가 바뀜)", "AvgPool1D를 Residual block 밖으로 옮기세요")
|
|
220
|
+
return None
|
|
221
|
+
return self.seq(C, L // b["size"], path)
|
|
222
|
+
if t == "global_avg":
|
|
223
|
+
if ctx == "residual":
|
|
224
|
+
self.issue(path, "Residual block 안에서는 GlobalAvgPool1D를 쓸 수 없음", "GlobalAvgPool1D를 Residual block 밖으로 옮기세요")
|
|
225
|
+
return None
|
|
226
|
+
return (C,)
|
|
227
|
+
if t == "branch":
|
|
228
|
+
lanes = b.get("branches")
|
|
229
|
+
if not isinstance(lanes, list) or len(lanes) < 2 or not all(isinstance(x, list) for x in lanes):
|
|
230
|
+
self.issue(path, "Concat branches는 갈래가 2개 이상이어야 함", "갈래를 추가하세요")
|
|
231
|
+
return None
|
|
232
|
+
total = 0
|
|
233
|
+
for j, lane in enumerate(lanes): # 갈래는 크기를 바꾸면 안 됨 (Residual block과 같은 규칙)
|
|
234
|
+
out = self.walk(lane, shape, path + (j,), "residual") if lane else shape
|
|
235
|
+
if out is None or len(out) != len(shape) or tuple(out[1:]) != tuple(shape[1:]):
|
|
236
|
+
return None
|
|
237
|
+
total += out[0]
|
|
238
|
+
return (total,) + tuple(shape[1:])
|
|
239
|
+
if t == "se":
|
|
240
|
+
if C // b.get("ratio", 4) < 1:
|
|
241
|
+
self.issue(path, f"SE block: 채널 {C}개를 ratio {b.get('ratio', 4)}로 나누면 0", "ratio를 채널 수보다 작게 하세요")
|
|
242
|
+
return None
|
|
243
|
+
return shape
|
|
244
|
+
if t == "last_step":
|
|
245
|
+
if ctx == "residual":
|
|
246
|
+
self.issue(path, "Residual block 안에서는 LastTimestep을 쓸 수 없음", "LastTimestep을 Residual block 밖으로 옮기세요")
|
|
247
|
+
return None
|
|
248
|
+
return (C,)
|
|
249
|
+
if t in ("bn", "act", "dropout"):
|
|
250
|
+
return shape
|
|
251
|
+
if t == "flatten":
|
|
252
|
+
if ctx == "residual":
|
|
253
|
+
self.issue(path, "Residual block 안에서는 Flatten을 쓸 수 없음", "Flatten을 Residual block 밖으로 옮기세요")
|
|
254
|
+
return None
|
|
255
|
+
return (_prod(shape),)
|
|
256
|
+
if t == "dense":
|
|
257
|
+
if ctx == "residual":
|
|
258
|
+
self.issue(path, "Residual block 안에서는 Dense를 쓸 수 없음", "Dense를 Residual block 밖으로 옮기세요")
|
|
259
|
+
return None
|
|
260
|
+
return self.dense_like(shape, b["units"], path)
|
|
261
|
+
if t == "residual":
|
|
262
|
+
if not b.get("body"):
|
|
263
|
+
self.issue(path, "Residual block 안이 비어 있음", "안에 층을 넣으세요")
|
|
264
|
+
return None
|
|
265
|
+
if len(shape) not in (2, 3):
|
|
266
|
+
self.issue(path, "Residual block은 시간 축이나 (높이, 너비)가 있는 데이터에만",
|
|
267
|
+
"Residual block을 GlobalAvgPool·Flatten·Dense 앞으로 옮기세요")
|
|
268
|
+
return None
|
|
269
|
+
out = self.walk(b["body"], shape, path, "residual")
|
|
270
|
+
return out if out is None or len(out) == len(shape) and tuple(out[1:]) == tuple(shape[1:]) else None
|
|
271
|
+
if t == "repeat":
|
|
272
|
+
body = b.get("body")
|
|
273
|
+
if not body:
|
|
274
|
+
self.issue(path, "Repeat 안이 비어 있음", "안에 층을 넣으세요")
|
|
275
|
+
return None
|
|
276
|
+
if any(isinstance(x, dict) and x.get("type") in RNN_TYPES + ("output",) for x in body):
|
|
277
|
+
self.issue(path, "Repeat 안에는 LSTM·GRU·SimpleRNN·Output을 넣을 수 없음", "그 층을 Repeat 밖으로 옮기세요")
|
|
278
|
+
return None
|
|
279
|
+
n_issues = len(self.issues)
|
|
280
|
+
for _ in range(b["times"]): # 펼친 것과 같은 규칙. 모양은 마지막 반복 기준
|
|
281
|
+
del self.issues[n_issues:]
|
|
282
|
+
shape = self.walk(body, shape, path, "residual" if ctx == "residual" else "repeat")
|
|
283
|
+
if shape is None:
|
|
284
|
+
break
|
|
285
|
+
return shape
|
|
286
|
+
return shape
|
|
287
|
+
|
|
288
|
+
def seq(self, C, L, path):
|
|
289
|
+
if L < 1:
|
|
290
|
+
self.issue(path, "길이가 0이 됨 (너무 많이 줄였음)", "AvgPool1D·stride 2를 줄이세요")
|
|
291
|
+
return None
|
|
292
|
+
if L > self.max_len:
|
|
293
|
+
self.issue(path, f"길이 {L}이(가) 한도 {self.max_len:,}을(를) 넘음", "AvgPool1D로 길이를 줄이세요")
|
|
294
|
+
return None
|
|
295
|
+
return (C, L)
|
|
296
|
+
|
|
297
|
+
def grid(self, C, H, W, path):
|
|
298
|
+
if H < 1 or W < 1:
|
|
299
|
+
self.issue(path, "크기가 0이 됨 (너무 많이 줄였음)", "AvgPool2D·stride 2·padding valid를 줄이세요")
|
|
300
|
+
return None
|
|
301
|
+
if H * W > self.max_len:
|
|
302
|
+
self.issue(path, f"크기 {H}×{W}가 한도 {self.max_len:,}칸을 넘음", "AvgPool2D로 크기를 줄이세요")
|
|
303
|
+
return None
|
|
304
|
+
return (C, H, W)
|
|
305
|
+
|
|
306
|
+
def det_head(self, shape, path):
|
|
307
|
+
"""탐지 출력: 바로 앞이 격자 모양 (채널, G, G)이어야 함 → 칸마다 1×1 필터로 (값 수, G, G)를 펼쳐 냄."""
|
|
308
|
+
if shape is None:
|
|
309
|
+
return None
|
|
310
|
+
G = self.n_out.grid
|
|
311
|
+
if len(shape) != 3 or shape[1] != G or shape[2] != G:
|
|
312
|
+
now = "×".join(map(str, shape[1:])) if len(shape) == 3 else f"숫자 {_prod(shape)}개 (위치가 없음)"
|
|
313
|
+
self.issue(path, f"탐지 모델의 출력 블록 바로 앞은 {G}×{G} 격자여야 함 (지금 {now})",
|
|
314
|
+
f"그림 {G * 8}×{G * 8}을 AvgPool2D로 세 번 줄이면 {G}×{G}가 됩니다. "
|
|
315
|
+
"GlobalAvgPool2D·Flatten·Dense는 위치를 잃어 탐지에 쓸 수 없습니다")
|
|
316
|
+
return None
|
|
317
|
+
return (int(self.n_out),)
|
|
318
|
+
|
|
319
|
+
def seg_head(self, shape, path):
|
|
320
|
+
"""구간 분할 출력: 바로 앞이 길이를 그대로 둔 줄 (채널, L)이어야 함 → 시점마다 상태 점수 (K, L)을 펼쳐 냄."""
|
|
321
|
+
if shape is None:
|
|
322
|
+
return None
|
|
323
|
+
L = self.n_out.length
|
|
324
|
+
if len(shape) != 2 or shape[1] != L:
|
|
325
|
+
now = f"길이 {shape[1]}" if len(shape) == 2 else f"숫자 {_prod(shape)}개 (시점이 없음)"
|
|
326
|
+
self.issue(path, f"구간 분할의 출력 블록 바로 앞은 길이 {L}인 줄이어야 함 (지금 {now})",
|
|
327
|
+
"시점마다 맞혀야 해서 길이를 줄이는 Pool·stride 2·Flatten·Dense는 쓸 수 없습니다 "
|
|
328
|
+
"(줄였다면 Upsample로 되돌리세요. 순환 층은 return_sequences를 켜세요)")
|
|
329
|
+
return None
|
|
330
|
+
return (int(self.n_out),)
|
|
331
|
+
|
|
332
|
+
def dist_head(self, shape, path):
|
|
333
|
+
"""이상 탐지 출력 '정상과의 거리': 바로 앞이 숫자 묶음(특징)이어야 함 → 점수 하나."""
|
|
334
|
+
if shape is None:
|
|
335
|
+
return None
|
|
336
|
+
if len(shape) != 1:
|
|
337
|
+
self.issue(path, f"'정상과의 거리' 출력 바로 앞은 숫자 묶음(특징)이어야 함 (지금 {tuple(shape)})",
|
|
338
|
+
"사전학습 블록(MobileNetV3-Small) 바로 뒤에 두세요")
|
|
339
|
+
return None
|
|
340
|
+
return (1,)
|
|
341
|
+
|
|
342
|
+
def dense_like(self, shape, units, path):
|
|
343
|
+
if shape is None:
|
|
344
|
+
return None
|
|
345
|
+
width = _prod(shape)
|
|
346
|
+
if width > self.max_width or units > self.max_width:
|
|
347
|
+
pool = "GlobalAvgPool2D나 AvgPool2D" if self.image else "GlobalAvgPool1D나 AvgPool1D"
|
|
348
|
+
self.issue(path, f"입력 {width:,}개가 한 층 한도 {self.max_width:,}을(를) 넘음", f"앞에 {pool}를 넣어 크기를 줄이세요")
|
|
349
|
+
return None
|
|
350
|
+
return (units,)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _prod(shape) -> int:
|
|
354
|
+
n = 1
|
|
355
|
+
for v in shape:
|
|
356
|
+
n *= v
|
|
357
|
+
return n
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def check(blocks: list, length: int, n_out: int, image: tuple = None) -> Checked:
|
|
361
|
+
"""블록 검증과 블록마다 출력 모양. length: 데이터 길이(이미지면 H·W), n_out: 분류 클래스 수(회귀면 1).
|
|
362
|
+
image: 이미지면 (H, W) → kind "image", 시작 모양 (1, H, W)."""
|
|
363
|
+
w = _Walker(n_out, image=bool(image))
|
|
364
|
+
if not isinstance(blocks, list) or not blocks:
|
|
365
|
+
w.issue((), "블록이 없음", "예시 모델을 불러오거나 블록을 쌓으세요")
|
|
366
|
+
return Checked(w.issues, {}, "image" if image else "cnn")
|
|
367
|
+
if image:
|
|
368
|
+
kind = "image"
|
|
369
|
+
else:
|
|
370
|
+
kind = "rnn" if isinstance(blocks[0], dict) and blocks[0].get("type") in RNN_TYPES else "cnn"
|
|
371
|
+
w.walk(blocks, (1,) + tuple(image) if image else (channels_of(length), int(length)), (), "top")
|
|
372
|
+
for i, b in enumerate(blocks): # 증강은 맨 앞(증강끼리)에만
|
|
373
|
+
if isinstance(b, dict) and b.get("type") in X.AUG_TYPES and any(
|
|
374
|
+
not (isinstance(p, dict) and p.get("type") in X.AUG_TYPES) for p in blocks[:i]):
|
|
375
|
+
w.issue((i,), f"{NAMES[b['type']]}은(는) Input 바로 뒤(다른 증강 블록 뒤)에만", "증강 블록을 맨 위로 옮기세요")
|
|
376
|
+
outs = [i for i, b in enumerate(blocks) if isinstance(b, dict) and b.get("type") == "output"]
|
|
377
|
+
if not outs:
|
|
378
|
+
w.issue((), "출력 블록이 없음", "맨 아래에 출력 블록을 놓으세요")
|
|
379
|
+
elif len(outs) > 1:
|
|
380
|
+
for i in outs[:-1]:
|
|
381
|
+
if not any(x.path == (i,) for x in w.issues):
|
|
382
|
+
w.issue((i,), "출력 블록은 하나만", "출력 블록을 하나만 남기세요")
|
|
383
|
+
return Checked(w.issues, w.shapes, kind)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
# ---------------------------------------------------------------- torch 모델 만들기
|
|
387
|
+
|
|
388
|
+
def _torch():
|
|
389
|
+
import torch
|
|
390
|
+
from torch import nn
|
|
391
|
+
return torch, nn
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def channels_of(length) -> int:
|
|
395
|
+
return getattr(length, "channels", 1)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def to_model_input(kind: str, X, image: tuple = None, channels: int = 1):
|
|
399
|
+
"""(n, C·L) → CNN은 (n, C, L), RNN은 (n, L, C), 이미지는 (n, 1, H, W). 채널이 여럿이면 X는 채널이 먼저."""
|
|
400
|
+
import numpy as np
|
|
401
|
+
X = np.asarray(X)
|
|
402
|
+
if kind == "image":
|
|
403
|
+
return X.reshape(len(X), 1, image[0], image[1])
|
|
404
|
+
x = X.reshape(len(X), channels, -1)
|
|
405
|
+
return x if kind == "cnn" else x.transpose(0, 2, 1)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _modules():
|
|
409
|
+
torch, nn = _torch()
|
|
410
|
+
|
|
411
|
+
class GlobalAvg(nn.Module):
|
|
412
|
+
def forward(self, x):
|
|
413
|
+
return x.mean(-1)
|
|
414
|
+
|
|
415
|
+
class GlobalAvg2d(nn.Module):
|
|
416
|
+
def forward(self, x):
|
|
417
|
+
return x.mean(dim=(-1, -2))
|
|
418
|
+
|
|
419
|
+
class Flatten(nn.Module):
|
|
420
|
+
def forward(self, x):
|
|
421
|
+
return torch.flatten(x, 1)
|
|
422
|
+
|
|
423
|
+
class Residual(nn.Module):
|
|
424
|
+
def __init__(self, body, shortcut=None):
|
|
425
|
+
super().__init__()
|
|
426
|
+
self.body = body
|
|
427
|
+
self.shortcut = shortcut
|
|
428
|
+
|
|
429
|
+
def forward(self, x):
|
|
430
|
+
s = x if self.shortcut is None else self.shortcut(x)
|
|
431
|
+
return s + self.body(x)
|
|
432
|
+
|
|
433
|
+
class SE(nn.Module):
|
|
434
|
+
"""Squeeze-and-Excitation: 채널마다 평균 → Dense → act → Dense → sigmoid → 채널 가중치를 곱함."""
|
|
435
|
+
|
|
436
|
+
def __init__(self, c, ratio, act):
|
|
437
|
+
super().__init__()
|
|
438
|
+
h = max(1, c // ratio)
|
|
439
|
+
self.fc1, self.act, self.fc2 = nn.Linear(c, h), act, nn.Linear(h, c)
|
|
440
|
+
|
|
441
|
+
def forward(self, x):
|
|
442
|
+
s = torch.sigmoid(self.fc2(self.act(self.fc1(x.flatten(2).mean(-1)))))
|
|
443
|
+
return x * s.reshape(*s.shape, *([1] * (x.dim() - 2)))
|
|
444
|
+
|
|
445
|
+
class Branch(nn.Module):
|
|
446
|
+
"""갈래마다 계산해 채널 방향으로 이어 붙임 (Inception). 빈 갈래는 들어온 값 그대로."""
|
|
447
|
+
|
|
448
|
+
def __init__(self, lanes):
|
|
449
|
+
super().__init__()
|
|
450
|
+
self.lanes = nn.ModuleList(lanes)
|
|
451
|
+
|
|
452
|
+
def forward(self, x):
|
|
453
|
+
return torch.cat([lane(x) for lane in self.lanes], dim=1)
|
|
454
|
+
|
|
455
|
+
class LastTimestep(nn.Module):
|
|
456
|
+
def forward(self, x):
|
|
457
|
+
return x[:, :, -1]
|
|
458
|
+
|
|
459
|
+
class LastStep(nn.Module):
|
|
460
|
+
def __init__(self, rnn):
|
|
461
|
+
super().__init__()
|
|
462
|
+
self.rnn = rnn
|
|
463
|
+
|
|
464
|
+
def forward(self, x):
|
|
465
|
+
out, _ = self.rnn(x)
|
|
466
|
+
return out[:, -1]
|
|
467
|
+
|
|
468
|
+
class StudioNet(nn.Module):
|
|
469
|
+
"""블록으로 만든 모델. block_modules: 블록 위치 키("0", "2.0.1") → 그 블록 출력을 내는 모듈 (등록 안 한 dict)."""
|
|
470
|
+
|
|
471
|
+
def __init__(self, layers, kind: str, block_modules: dict):
|
|
472
|
+
super().__init__()
|
|
473
|
+
self.layers = nn.Sequential(*layers)
|
|
474
|
+
self.kind = kind
|
|
475
|
+
self.block_modules = block_modules
|
|
476
|
+
|
|
477
|
+
def forward(self, x):
|
|
478
|
+
return self.layers(x.transpose(1, 2) if self.kind == "rnn" else x)
|
|
479
|
+
|
|
480
|
+
return GlobalAvg, Flatten, Residual, LastStep, StudioNet, LastTimestep, SE, Branch, GlobalAvg2d
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def act_module(kind: str):
|
|
484
|
+
"""활성화 이름 → 모듈."""
|
|
485
|
+
torch, nn = _torch()
|
|
486
|
+
if kind == "softmax":
|
|
487
|
+
return nn.Softmax(dim=1)
|
|
488
|
+
return {"relu": nn.ReLU, "sigmoid": nn.Sigmoid, "tanh": nn.Tanh, "leaky_relu": nn.LeakyReLU, "gelu": nn.GELU,
|
|
489
|
+
"silu": nn.SiLU, "elu": nn.ELU, "mish": nn.Mish, "softplus": nn.Softplus, "selu": nn.SELU, "relu6": nn.ReLU6,
|
|
490
|
+
"hardswish": nn.Hardswish, "hardsigmoid": nn.Hardsigmoid}[kind]()
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def make_layer(b: dict, shape, n_out: int):
|
|
494
|
+
"""감싸지 않는 층 하나(b: 블록 설정, shape: 들어오는 모양) → torch 모듈. 블록 목록과 그래프가 함께 쓴다."""
|
|
495
|
+
torch, nn = _torch()
|
|
496
|
+
GlobalAvg, Flatten, Residual, LastStep, StudioNet, LastTimestep, SE, Branch, GlobalAvg2d = _modules()
|
|
497
|
+
t = b["type"]
|
|
498
|
+
if t == "conv":
|
|
499
|
+
k, d = b["kernel"], b.get("dilation", 1)
|
|
500
|
+
if b.get("padding") == "causal":
|
|
501
|
+
from blocklearning.nn_extra import CausalConv1d
|
|
502
|
+
return CausalConv1d(shape[0], b["channels"], k, stride=b.get("stride", 1), dilation=d, groups=b.get("groups", 1))
|
|
503
|
+
pad = 0 if b.get("padding", "same") == "valid" else d * (k - 1) // 2
|
|
504
|
+
return nn.Conv1d(shape[0], b["channels"], k, stride=b.get("stride", 1), padding=pad, dilation=d,
|
|
505
|
+
groups=b.get("groups", 1))
|
|
506
|
+
if t == "pool":
|
|
507
|
+
return nn.AvgPool1d(b["size"])
|
|
508
|
+
if t == "conv2d":
|
|
509
|
+
k, d = b["kernel"], b.get("dilation", 1)
|
|
510
|
+
return nn.Conv2d(shape[0], b["channels"], k, stride=b.get("stride", 1),
|
|
511
|
+
padding=0 if b.get("padding", "same") == "valid" else d * (k - 1) // 2, dilation=d,
|
|
512
|
+
groups=b.get("groups", 1))
|
|
513
|
+
if t == "pool2d":
|
|
514
|
+
return nn.AvgPool2d(2)
|
|
515
|
+
if t == "global_avg2d":
|
|
516
|
+
return GlobalAvg2d()
|
|
517
|
+
if t == "global_avg":
|
|
518
|
+
return GlobalAvg()
|
|
519
|
+
if t == "last_step":
|
|
520
|
+
return LastTimestep()
|
|
521
|
+
if t == "se":
|
|
522
|
+
return SE(shape[0], b.get("ratio", 4), act_module(b.get("act", "relu")))
|
|
523
|
+
if t == "dropout":
|
|
524
|
+
return nn.Dropout(float(b.get("rate", 0.5)))
|
|
525
|
+
if t == "flatten":
|
|
526
|
+
return Flatten()
|
|
527
|
+
if t == "bn":
|
|
528
|
+
return nn.BatchNorm2d(shape[0]) if len(shape) == 3 else nn.BatchNorm1d(shape[0])
|
|
529
|
+
if t == "act":
|
|
530
|
+
return act_module(b["kind"])
|
|
531
|
+
if t == "output" and b.get("head") == "distance": # 이상 탐지: 정상과의 거리 (점수 하나)
|
|
532
|
+
from blocklearning.nn_extra import NormalDistance
|
|
533
|
+
return NormalDistance(_prod(shape), X.dist_k(_prod(shape)))
|
|
534
|
+
if t == "output" and getattr(n_out, "seg", False): # 구간 분할: 시점마다 1×1 필터 → (상태 수, L)을 펼침
|
|
535
|
+
return nn.Sequential(nn.Conv1d(shape[0], n_out.n_cls, 1), Flatten())
|
|
536
|
+
if t == "output" and getattr(n_out, "grid", None): # 탐지: 격자 칸마다 1×1 필터 → (값 수, G, G)를 펼침
|
|
537
|
+
return nn.Sequential(nn.Conv2d(shape[0], n_out.per_cell, 1), Flatten())
|
|
538
|
+
if t in ("dense", "output"):
|
|
539
|
+
lin = nn.Linear(_prod(shape), n_out if t == "output" else b["units"])
|
|
540
|
+
return nn.Sequential(Flatten(), lin) if len(shape) >= 2 else lin
|
|
541
|
+
if t in RNN_TYPES:
|
|
542
|
+
from blocklearning.nn_extra import RNNBlock
|
|
543
|
+
return RNNBlock(t, shape[0], b["hidden"], b.get("layers", 1), bool(b.get("bidirectional")), bool(b.get("return_sequences")))
|
|
544
|
+
if t in X.EXTRA_TYPES:
|
|
545
|
+
return extra_layer(b, shape)
|
|
546
|
+
raise ValueError(f"알 수 없는 층 {t}")
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def extra_layer(b: dict, shape, shape2=None):
|
|
550
|
+
"""추가 블록 → PyTorch 모듈 (layers.torch_args의 이름·인자로)."""
|
|
551
|
+
torch, nn = _torch()
|
|
552
|
+
from blocklearning import nn_extra
|
|
553
|
+
name, kw = X.torch_args(b["type"], b, shape, shape2)
|
|
554
|
+
cls = getattr(nn, name[3:]) if name.startswith("nn.") else getattr(nn_extra, name)
|
|
555
|
+
m = cls(*kw.get("_", []), **{k: v for k, v in kw.items() if k != "_"})
|
|
556
|
+
if b["type"] in X.PRETRAINED_TYPES: # 미리 학습한 가중치 (고정)
|
|
557
|
+
from blocklearning.pretrained import fill
|
|
558
|
+
fill(m, b["type"])
|
|
559
|
+
return m
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def build_model(blocks: list, length: int, n_out: int, seed: int = 0, image: tuple = None):
|
|
563
|
+
"""블록 JSON → StudioNet (float32). 검증을 통과하지 못하면 ValueError(첫 문제). image: 이미지면 (H, W)."""
|
|
564
|
+
c = check(blocks, length, n_out, image=image)
|
|
565
|
+
if not c.ok:
|
|
566
|
+
raise ValueError(c.issues[0].message)
|
|
567
|
+
torch, nn = _torch()
|
|
568
|
+
GlobalAvg, Flatten, Residual, LastStep, StudioNet, LastTimestep, SE, Branch, GlobalAvg2d = _modules()
|
|
569
|
+
torch.manual_seed(seed)
|
|
570
|
+
paths: dict = {}
|
|
571
|
+
|
|
572
|
+
def build(seq: list, shape, prefix: tuple, shapes: dict):
|
|
573
|
+
"""shapes: 블록 위치 → 출력 모양. Repeat 몸체는 반복마다 모양이 달라 반복마다 따로 계산한 것을 씀."""
|
|
574
|
+
mods = []
|
|
575
|
+
for i, b in enumerate(seq):
|
|
576
|
+
path = prefix + (i,)
|
|
577
|
+
t = b["type"]
|
|
578
|
+
if t == "branch":
|
|
579
|
+
m = Branch([build(lane, shape, path + (j,), shapes)[0] if lane else nn.Identity()
|
|
580
|
+
for j, lane in enumerate(b["branches"])])
|
|
581
|
+
elif t == "residual":
|
|
582
|
+
body, out = build(b["body"], shape, path, shapes)
|
|
583
|
+
conv = nn.Conv2d if len(shape) == 3 else nn.Conv1d
|
|
584
|
+
m = Residual(body, None if out[0] == shape[0] else conv(shape[0], out[0], 1))
|
|
585
|
+
elif t == "repeat":
|
|
586
|
+
reps, s = [], shape
|
|
587
|
+
for _ in range(b["times"]): # 가중치는 반복마다 따로, 대응표는 마지막 반복
|
|
588
|
+
w = _Walker(n_out, image=bool(image)) # 이번 반복의 입력 모양에서 몸체 모양을 다시 계산
|
|
589
|
+
w.walk(b["body"], s, path, "repeat")
|
|
590
|
+
body, s = build(b["body"], s, path, w.shapes)
|
|
591
|
+
reps.append(body)
|
|
592
|
+
m = nn.Sequential(*reps)
|
|
593
|
+
else:
|
|
594
|
+
m = make_layer(b, shape, n_out)
|
|
595
|
+
paths[".".join(map(str, path))] = m
|
|
596
|
+
mods.append(m)
|
|
597
|
+
shape = shapes[path]
|
|
598
|
+
return nn.Sequential(*mods), shape
|
|
599
|
+
|
|
600
|
+
seq, _ = build(blocks, (1,) + tuple(image) if image else (channels_of(length), int(length)), (), c.shapes)
|
|
601
|
+
return StudioNet(list(seq), c.kind, paths).float()
|
blocklearning/cli.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""명령: `blocklearning [--port 8765] [--no-browser]` (또는 `python -m blocklearning`) → PC에 BlockLearning을 띄우고 브라우저를 연다."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import sys
|
|
6
|
+
import webbrowser
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
PORT_TRIES = 20
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv: Optional[list] = None) -> int:
|
|
13
|
+
ap = argparse.ArgumentParser(prog="blocklearning", description="BlockLearning: 블록으로 딥러닝 모델 만들기 (브라우저 화면)")
|
|
14
|
+
ap.add_argument("--port", type=int, default=8765)
|
|
15
|
+
ap.add_argument("--no-browser", action="store_true")
|
|
16
|
+
ap.add_argument("--dry-run", action="store_true", help=argparse.SUPPRESS)
|
|
17
|
+
args = ap.parse_args(argv)
|
|
18
|
+
from blocklearning.server import make_server
|
|
19
|
+
server, err = None, None
|
|
20
|
+
for k in range(PORT_TRIES if args.port else 1): # 포트가 쓰이고 있으면 다음 포트
|
|
21
|
+
try:
|
|
22
|
+
server = make_server(args.port + k if args.port else 0)
|
|
23
|
+
break
|
|
24
|
+
except OSError as e:
|
|
25
|
+
err = e
|
|
26
|
+
if server is None:
|
|
27
|
+
print(f"포트를 열 수 없음: {err}", file=sys.stderr)
|
|
28
|
+
return 1
|
|
29
|
+
url = f"http://127.0.0.1:{server.server_address[1]}/"
|
|
30
|
+
print(f"BlockLearning: {url} (끝내려면 Ctrl+C)", flush=True)
|
|
31
|
+
if args.dry_run:
|
|
32
|
+
server.server_close()
|
|
33
|
+
return 0
|
|
34
|
+
if not args.no_browser:
|
|
35
|
+
webbrowser.open(url)
|
|
36
|
+
try:
|
|
37
|
+
server.serve_forever()
|
|
38
|
+
except KeyboardInterrupt:
|
|
39
|
+
pass
|
|
40
|
+
finally:
|
|
41
|
+
server.server_close()
|
|
42
|
+
return 0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
sys.exit(main())
|