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/web.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
"""웹 버전(GitHub Pages)에서 Pyodide로 부르는 Python 쪽.
|
|
2
|
+
|
|
3
|
+
화면의 다리(static/web.js)가 이 모듈을 부른다. API는 core.Studio(web=True)를 그대로 쓰고, torch가 필요한 일
|
|
4
|
+
(학습·샘플 따라가기·모델 정보)은 화면의 TensorFlow.js 엔진이 맡는다. 여기서는 엔진에 넘길 계획·데이터와
|
|
5
|
+
가중치를 담은 파일(.npz, 프로젝트)을 만든다. 데이터는 브라우저 안에서만 쓰고 밖으로 보내지 않는다.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import io
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import zipfile
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from blocklearning import codegen
|
|
18
|
+
from blocklearning.core import Studio, UserError, _clean, _graph_from, _jsonable
|
|
19
|
+
from blocklearning.graph import check_graph
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class WebStudio(Studio):
|
|
23
|
+
def __init__(self):
|
|
24
|
+
super().__init__(web=True)
|
|
25
|
+
|
|
26
|
+
def api_model_check(self, b: dict) -> dict:
|
|
27
|
+
"""torch 없이: 모양·문제는 그대로, '모델 정보'는 codegen.plan_dict의 파라미터 수에서."""
|
|
28
|
+
d = self.need_data()
|
|
29
|
+
graph = _graph_from(b)
|
|
30
|
+
c = check_graph(graph, d.length, d.n_out, image=d.image)
|
|
31
|
+
out = dict(c.to_dict(), graph=graph, panel=None)
|
|
32
|
+
if isinstance(graph, dict):
|
|
33
|
+
self.graph = graph
|
|
34
|
+
if c.ok:
|
|
35
|
+
plan = codegen.plan_dict(graph, d.length, d.n_out, d.image)
|
|
36
|
+
out["panel"] = {"ok": True, "params": plan["params"], "frozen": plan["frozen"],
|
|
37
|
+
"mb": (plan["params"] + plan["frozen"]) * 4 / 1e6, "message": "", "warnings": []}
|
|
38
|
+
return out
|
|
39
|
+
|
|
40
|
+
def api_data_load(self, b: dict) -> dict:
|
|
41
|
+
out = super().api_data_load(b)
|
|
42
|
+
self.model_graph = None # 새 데이터: 화면의 학습 결과는 버림
|
|
43
|
+
return out
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def call_json(studio: Studio, method: str, path: str, body_json: str) -> str:
|
|
47
|
+
"""화면의 api(path, body) 한 번: JSON 글자로 받고 JSON 글자 {"status", "body"}로 돌려줌."""
|
|
48
|
+
code, obj = studio.call(method, path, json.loads(body_json) if body_json else None)
|
|
49
|
+
return json.dumps({"status": code, "body": _clean(obj)}, ensure_ascii=False, default=_jsonable)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _wrap(fn):
|
|
53
|
+
"""UserError·DataError를 화면 오류 모양 JSON으로 (다리가 status를 보고 throw)."""
|
|
54
|
+
def run(*a):
|
|
55
|
+
from blocklearning.data import DataError
|
|
56
|
+
try:
|
|
57
|
+
return json.dumps({"status": 200, "body": fn(*a)}, ensure_ascii=False, default=_jsonable)
|
|
58
|
+
except UserError as e:
|
|
59
|
+
return json.dumps({"status": 400, "body": {"error": {"message": e.message, "hint": e.hint, "issues": e.issues}}},
|
|
60
|
+
ensure_ascii=False, default=_jsonable)
|
|
61
|
+
except DataError as e:
|
|
62
|
+
i = e.issues[0]
|
|
63
|
+
return json.dumps({"status": 400, "body": {"error": {"message": i.message, "hint": i.hint,
|
|
64
|
+
"issues": [x.to_dict() for x in e.issues]}}}, ensure_ascii=False)
|
|
65
|
+
return run
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@_wrap
|
|
69
|
+
def plan(studio: Studio, graph_json: str) -> dict:
|
|
70
|
+
"""학습할 그래프 → 엔진용 계획 (문제가 있으면 오류)."""
|
|
71
|
+
d = studio.need_data()
|
|
72
|
+
graph = json.loads(graph_json)
|
|
73
|
+
c = check_graph(graph, d.length, d.n_out, image=d.image)
|
|
74
|
+
if not c.ok:
|
|
75
|
+
i = c.issues[0]
|
|
76
|
+
raise UserError(i.message, i.hint, [x.to_dict() for x in c.issues])
|
|
77
|
+
return codegen.plan_dict(graph, d.length, d.n_out, d.image)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def data_payload(studio: Studio) -> dict:
|
|
81
|
+
"""엔진에 넘길 데이터: 정규화한 X(float32 바이트), 정답, 모양·과제 정보."""
|
|
82
|
+
d = studio.need_data()
|
|
83
|
+
f32 = lambda a: np.ascontiguousarray(a, dtype=np.float32).tobytes()
|
|
84
|
+
return {"X_train": f32(d.X_train), "X_test": f32(d.X_test), "y_train": f32(d.y_train), "y_test": f32(d.y_test),
|
|
85
|
+
"meta": json.dumps({"n_train": int(len(d.y_train)), "n_test": int(len(d.y_test)), "n_features": int(d.X_train.shape[1]),
|
|
86
|
+
"task": d.task, "n_out": int(d.n_out), "length": int(d.length), "channels": getattr(d.length, "channels", 1),
|
|
87
|
+
"image": list(d.image) if d.image else None,
|
|
88
|
+
"classes": [str(c) for c in d.classes] if d.task in ("classification", "detection") else [],
|
|
89
|
+
"det": None if d.task != "detection" else
|
|
90
|
+
{"grid": d.n_out.grid, "per_cell": d.n_out.per_cell, "n_cls": d.n_out.n_cls,
|
|
91
|
+
"train": d.det["train"], "test": d.det["test"]},
|
|
92
|
+
"seg": None if d.task != "segmentation" else {"n_cls": d.n_out.n_cls, "length": d.n_out.length},
|
|
93
|
+
"multi": None if d.task != "multi" else {"heads": d.n_out.heads}})}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@_wrap
|
|
97
|
+
def task_result(studio: Studio, out_bytes, out_tr_bytes) -> dict:
|
|
98
|
+
"""예측·이상 탐지: 화면이 학습한 모델의 시험·학습 출력(float32) → 결과 화면 값 (로컬 학습과 같은 jobs.task_result)."""
|
|
99
|
+
from blocklearning.jobs import task_result as tr
|
|
100
|
+
d = studio.need_data()
|
|
101
|
+
raw = lambda b: b.to_bytes() if hasattr(b, "to_bytes") else bytes(b)
|
|
102
|
+
out = np.frombuffer(raw(out_bytes), dtype=np.float32).reshape(len(d.X_test), -1).astype(np.float64)
|
|
103
|
+
out_tr = np.frombuffer(raw(out_tr_bytes), dtype=np.float32).reshape(len(d.X_train), -1).astype(np.float64)
|
|
104
|
+
return _clean(tr(d, out, out_tr))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def set_trained(studio: Studio, graph_json: str, settings_json: str, results_json: str, state=None) -> None:
|
|
108
|
+
"""화면에서 학습이 끝났음을 기록 (코드·프로젝트 저장이 학습한 그래프를 알게). state가 있으면 학습 기록에도 더함."""
|
|
109
|
+
studio.model_graph = json.loads(graph_json)
|
|
110
|
+
studio.train_settings = json.loads(settings_json)
|
|
111
|
+
studio.results = json.loads(results_json)
|
|
112
|
+
if state is not None:
|
|
113
|
+
studio.add_run(studio.model_graph, studio.train_settings, studio.results, _arrays(state))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _state_lists(sd: dict) -> dict:
|
|
117
|
+
"""가중치 dict(이름 → 배열) → 화면 엔진이 읽는 {이름: {shape, data(list), int}}."""
|
|
118
|
+
return {k: {"shape": list(np.shape(v)), "data": np.asarray(v).ravel().tolist(),
|
|
119
|
+
"int": bool(np.issubdtype(np.asarray(v).dtype, np.integer))} for k, v in sd.items()}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _opened(studio: Studio, pr: dict) -> dict:
|
|
123
|
+
"""열린 프로젝트 → 상태에 반영하고 화면용 응답 + 가중치 + 엔진용 계획."""
|
|
124
|
+
d = studio.data
|
|
125
|
+
studio.graph = pr["graph"]
|
|
126
|
+
studio.train_settings, studio.results, studio.selection = pr["train_settings"], pr["results"], pr["selection"]
|
|
127
|
+
state, plan_, notice = None, None, ""
|
|
128
|
+
if pr["state_dict"] is not None:
|
|
129
|
+
try:
|
|
130
|
+
plan_ = codegen.plan_dict(pr["graph"], d.length, d.n_out, d.image)
|
|
131
|
+
want = {p[0]: p[1] for st in plan_["steps"] for p in st["params"] if p[2] != "frozen"} # 고정 가중치는 저장 안 함
|
|
132
|
+
fits = {k: list(v.shape) for k, v in pr["state_dict"].items()} == want
|
|
133
|
+
except Exception: # 그래프가 지금 데이터 모양에서 검사를 통과하지 못함
|
|
134
|
+
fits = False
|
|
135
|
+
if fits:
|
|
136
|
+
state = _state_lists(pr["state_dict"])
|
|
137
|
+
studio.model_graph = pr["graph"]
|
|
138
|
+
elif dict(pr.get("data_source") or {}).get("example"):
|
|
139
|
+
# 예시 데이터가 바뀜 (예전 합성 예시 → 실제 데이터): 모델 구조는 두고 학습 결과만 비움
|
|
140
|
+
plan_, studio.model_graph, studio.results = None, None, {}
|
|
141
|
+
pr = dict(pr, results={})
|
|
142
|
+
notice = "예시 데이터가 공개된 실제 데이터로 바뀌어 예전 학습 결과는 비웠습니다. ④에서 다시 학습하세요."
|
|
143
|
+
else:
|
|
144
|
+
raise UserError("프로젝트의 모델이 지금 데이터와 맞지 않음", "프로젝트를 저장할 때와 같은 데이터를 불러오세요")
|
|
145
|
+
else:
|
|
146
|
+
studio.model_graph = None
|
|
147
|
+
studio.set_runs(pr)
|
|
148
|
+
res = {"graph": pr["graph"], "summary": d.summary(), "train_settings": pr["train_settings"], "results": pr["results"],
|
|
149
|
+
"trained": state is not None, "selection": studio.selection, "runs": studio.runs_view(),
|
|
150
|
+
"predict_kinds": studio.predict_kinds(), "notice": notice}
|
|
151
|
+
return {"response": _clean(res), "state": state, "plan": plan_}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@_wrap
|
|
155
|
+
def run_restore(studio: Studio, n: int) -> dict:
|
|
156
|
+
"""학습 기록 n을 지금 모델로: 화면용 응답 + 가중치 + 엔진용 계획."""
|
|
157
|
+
run = studio.pick_run(n)
|
|
158
|
+
d = studio.data
|
|
159
|
+
plan_ = codegen.plan_dict(run["graph"], d.length, d.n_out, d.image)
|
|
160
|
+
return {"response": _clean(studio.restored()), "state": _state_lists(studio.run_weights[run["n"]]), "plan": plan_}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@_wrap
|
|
164
|
+
def predict_prepare(studio: Studio, body_json: str) -> dict:
|
|
165
|
+
"""새 데이터로 예측 1단계: 읽고 정규화해 둠 (엔진이 predict_x로 가져감)."""
|
|
166
|
+
from blocklearning.core import _paths
|
|
167
|
+
from blocklearning.predict import read_new
|
|
168
|
+
d = studio.need_data()
|
|
169
|
+
if studio.model_graph is None:
|
|
170
|
+
raise UserError("학습된 모델이 없음", "④ 학습 단계에서 먼저 학습하세요")
|
|
171
|
+
studio.pending = read_new(d, _paths(json.loads(body_json)))
|
|
172
|
+
return {"n": len(studio.pending["names"])}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def predict_x(studio: Studio) -> bytes:
|
|
176
|
+
return np.ascontiguousarray(studio.pending["X"], dtype=np.float32).tobytes()
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@_wrap
|
|
180
|
+
def predict_finish(studio: Studio, out_bytes) -> dict:
|
|
181
|
+
"""새 데이터로 예측 2단계: 엔진의 출력 → 표·요약·CSV."""
|
|
182
|
+
from blocklearning.predict import table
|
|
183
|
+
raw = out_bytes.to_bytes() if hasattr(out_bytes, "to_bytes") else bytes(out_bytes)
|
|
184
|
+
p, studio.pending = studio.pending, None
|
|
185
|
+
out = np.frombuffer(raw, dtype=np.float32).reshape(len(p["names"]), -1)
|
|
186
|
+
return _clean(table(studio.data, p["names"], out, p["labels"], p["X"], studio.results, p.get("truth")))
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@_wrap
|
|
190
|
+
def sample(studio: Studio, i: int) -> dict:
|
|
191
|
+
"""샘플 따라가기의 데이터 쪽: 시험 샘플 i의 정규화한 값, 원래 값, 정답, 노드 순서."""
|
|
192
|
+
d = studio.need_data()
|
|
193
|
+
if studio.model_graph is None:
|
|
194
|
+
raise UserError("학습된 모델이 없음", "④ 학습 단계에서 먼저 학습하세요")
|
|
195
|
+
if not 0 <= i < len(d.y_test):
|
|
196
|
+
raise UserError(f"시험 샘플 번호 {i}이(가) 없음", f"0–{len(d.y_test) - 1} 사이로 고르세요")
|
|
197
|
+
label = d.label_text("test", i)
|
|
198
|
+
order = check_graph(studio.model_graph, d.length, d.n_out, image=d.image).order
|
|
199
|
+
return {"x": d.X_test[i].astype(float).tolist(), "input": np.round(d.raw(d.X_test[i]), 5).tolist(),
|
|
200
|
+
"label": label, "order": order, "classes": [str(c) for c in d.classes]}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _arrays(state) -> dict:
|
|
204
|
+
"""화면에서 온 가중치 {이름: {shape, data(TypedArray), int}} → numpy."""
|
|
205
|
+
state = state.to_py() if hasattr(state, "to_py") else state
|
|
206
|
+
out = {}
|
|
207
|
+
for k, v in state.items():
|
|
208
|
+
raw = v["data"]
|
|
209
|
+
raw = raw.to_bytes() if hasattr(raw, "to_bytes") else bytes(raw) # Pyodide: Uint8Array → JsProxy 또는 memoryview
|
|
210
|
+
src = np.frombuffer(raw, dtype=np.int32 if v.get("int") else np.float32)
|
|
211
|
+
out[k] = src.astype(np.int64 if v.get("int") else np.float32).reshape(v["shape"])
|
|
212
|
+
return out
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def weights_npz(studio: Studio, graph_json: str, state) -> bytes:
|
|
216
|
+
"""학습한 가중치 → 생성한 PyTorch 코드의 이름으로 .npz 바이트."""
|
|
217
|
+
d = studio.need_data()
|
|
218
|
+
buf = io.BytesIO()
|
|
219
|
+
codegen.save_npz(codegen.code_state(_arrays(state), json.loads(graph_json), d.length, d.n_out, d.image), buf, data=d)
|
|
220
|
+
return buf.getvalue()
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def project_bytes(studio: Studio, state) -> bytes:
|
|
224
|
+
"""프로젝트(.blocklearning) 바이트: 그래프·데이터 출처·설정·결과 + 학습한 가중치(있으면)."""
|
|
225
|
+
from blocklearning.project import save_project
|
|
226
|
+
d = studio.need_data()
|
|
227
|
+
graph = studio.model_graph if state is not None and studio.model_graph else studio.graph
|
|
228
|
+
if not graph:
|
|
229
|
+
raise UserError("저장할 모델이 없음", "③ 모델 단계에서 층을 놓으세요")
|
|
230
|
+
buf = io.BytesIO()
|
|
231
|
+
save_project(buf, graph, d.source, studio.train_settings, studio.strip_frozen(graph, _arrays(state)) if state is not None else None,
|
|
232
|
+
studio.results, studio.selection, runs=studio.runs, run_weights=studio.run_weights,
|
|
233
|
+
current_run=studio.current_run)
|
|
234
|
+
return buf.getvalue()
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def example_files_json(kind: str) -> str:
|
|
238
|
+
"""예시 하나에 필요한 데이터 파일 (화면이 누를 때만 내려받아 /app/blocklearning/data/에 둠)."""
|
|
239
|
+
from blocklearning.data import example_files
|
|
240
|
+
return json.dumps(example_files(str(kind or "")))
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def project_example(path: str) -> str:
|
|
244
|
+
"""프로젝트 파일의 데이터가 예시면 그 이름 (열기 전에 예시 파일을 받아 두게). 아니면 빈 글자."""
|
|
245
|
+
from blocklearning.project import open_project as _open
|
|
246
|
+
try:
|
|
247
|
+
return str(dict(_open(path)["data_source"]).get("example") or "")
|
|
248
|
+
except Exception: # 못 읽으면 여는 단계가 알맞은 오류를 냄
|
|
249
|
+
return ""
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
@_wrap
|
|
253
|
+
def open_project(studio: Studio, path: str) -> dict:
|
|
254
|
+
"""프로젝트 파일 열기. 예시 데이터면 다시 불러오고, 아니면 지금 불러온 데이터를 씀 (웹은 파일 위치를 기억 못 함).
|
|
255
|
+
돌려줌: 화면용 응답 + 가중치 {이름: {shape, data(list), int}} + 엔진용 계획."""
|
|
256
|
+
from blocklearning.project import open_project as _open
|
|
257
|
+
try:
|
|
258
|
+
pr = _open(path)
|
|
259
|
+
except ValueError as e:
|
|
260
|
+
raise UserError(str(e), "BlockLearning에서 저장한 .blocklearning 파일을 고르세요") from None
|
|
261
|
+
src = dict(pr["data_source"])
|
|
262
|
+
if src.get("example"):
|
|
263
|
+
load = {k: src[k] for k in ("normalize", "test_ratio", "seed") if k in src}
|
|
264
|
+
studio.api_data_load(dict(load, example=src["example"]))
|
|
265
|
+
elif studio.data is None:
|
|
266
|
+
raise UserError("이 프로젝트의 데이터를 먼저 불러오세요",
|
|
267
|
+
"웹 버전은 PC의 파일 위치를 기억하지 못합니다. ② 데이터에서 같은 데이터를 고른 뒤 다시 여세요")
|
|
268
|
+
return _opened(studio, pr)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
# ------------------------------------------------------------ 프로젝트 기록 (브라우저 보관함·구글 드라이브)
|
|
272
|
+
# 기록 = 프로젝트 파일(project.dlstudio: 그래프·설정·결과·가중치, 자주 저장) + 데이터 사본(data.zip: 고른 파일들, 데이터를 바꿀 때만).
|
|
273
|
+
# 고른 파일은 Pyodide 안의 /data/u<번호>/...에 있다 → 데이터 출처의 경로는 "@data/u<번호>/..."로 적어 두고, 열 때 새 자리로 바꾼다.
|
|
274
|
+
DATA_DIR = "/data" # Pyodide 안에서 고른 파일을 두는 곳 (시험은 바꿔 씀)
|
|
275
|
+
_MARK = "@data/"
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _root_re():
|
|
279
|
+
return re.compile("^" + re.escape(DATA_DIR) + r"/([uL]\d+)(/|$)") # u: 고른 파일, L: 다시 푼 라벨링 작업
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _walk_strings(obj, fn):
|
|
283
|
+
if isinstance(obj, dict):
|
|
284
|
+
return {k: _walk_strings(v, fn) for k, v in obj.items()}
|
|
285
|
+
if isinstance(obj, list):
|
|
286
|
+
return [_walk_strings(v, fn) for v in obj]
|
|
287
|
+
return fn(obj) if isinstance(obj, str) else obj
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _data_roots(source: dict) -> list:
|
|
291
|
+
roots = set()
|
|
292
|
+
rx = _root_re()
|
|
293
|
+
_walk_strings(source, lambda v: roots.add(rx.match(v).group(1)) if rx.match(v) else v)
|
|
294
|
+
return sorted(roots)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _portable_source(source: dict) -> dict:
|
|
298
|
+
rx = _root_re()
|
|
299
|
+
return _walk_strings(source, lambda v: rx.sub(lambda m: _MARK + m.group(1) + m.group(2), v))
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def data_zip(studio: Studio) -> bytes:
|
|
303
|
+
"""지금 데이터의 파일들(고른 파일·폴더) → zip 바이트 (예시 데이터면 빈 바이트)."""
|
|
304
|
+
d = studio.need_data()
|
|
305
|
+
roots = _data_roots(d.source)
|
|
306
|
+
if not roots:
|
|
307
|
+
return b""
|
|
308
|
+
buf = io.BytesIO()
|
|
309
|
+
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_STORED) as z: # 그림·CSV는 대개 이미 압축이 잘 안 됨
|
|
310
|
+
for r in roots:
|
|
311
|
+
base = f"{DATA_DIR}/{r}"
|
|
312
|
+
for dirpath, _, files in os.walk(base):
|
|
313
|
+
for f in files:
|
|
314
|
+
full = os.path.join(dirpath, f)
|
|
315
|
+
z.write(full, f"{r}/{os.path.relpath(full, base)}".replace(os.sep, "/"))
|
|
316
|
+
return buf.getvalue()
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def record_project(studio: Studio, state, name: str = "", with_data: bool = False) -> bytes:
|
|
320
|
+
"""프로젝트 파일 바이트. 데이터 경로는 옮길 수 있게(@data/...). with_data면 데이터 사본도 zip 안 data/에 (내보내기용)."""
|
|
321
|
+
from blocklearning.project import save_project
|
|
322
|
+
d = studio.need_data()
|
|
323
|
+
graph = studio.model_graph if state is not None and studio.model_graph else studio.graph
|
|
324
|
+
if not graph:
|
|
325
|
+
raise UserError("저장할 모델이 없음", "③ 모델 단계에서 층을 놓으세요")
|
|
326
|
+
extra = {}
|
|
327
|
+
if with_data:
|
|
328
|
+
raw = data_zip(studio)
|
|
329
|
+
if raw:
|
|
330
|
+
with zipfile.ZipFile(io.BytesIO(raw)) as z:
|
|
331
|
+
extra = {f"data/{n}": z.read(n) for n in z.namelist()}
|
|
332
|
+
buf = io.BytesIO()
|
|
333
|
+
save_project(buf, graph, _portable_source(d.source), studio.train_settings,
|
|
334
|
+
studio.strip_frozen(graph, _arrays(state)) if state is not None else None, studio.results, studio.selection, extra, name,
|
|
335
|
+
runs=studio.runs, run_weights=studio.run_weights, current_run=studio.current_run)
|
|
336
|
+
return buf.getvalue()
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
_n_open = [0]
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
@_wrap
|
|
343
|
+
def record_open(studio: Studio, project_path: str, data_path: str = "") -> dict:
|
|
344
|
+
"""프로젝트 기록 열기: 데이터 사본(따로 받은 data.zip 또는 프로젝트 zip 안 data/)을 새 자리에 풀고, 출처를 그 자리로 바꿔 불러옴.
|
|
345
|
+
돌려줌: 화면용 응답 + 가중치 + 엔진용 계획 + 프로젝트 이름."""
|
|
346
|
+
from blocklearning.project import open_project as _open
|
|
347
|
+
try:
|
|
348
|
+
pr = _open(project_path)
|
|
349
|
+
except (ValueError, KeyError) as e:
|
|
350
|
+
raise UserError(f"프로젝트 파일을 읽을 수 없음: {e}", "BlockLearning에서 저장한 .blocklearning 파일을 고르세요") from None
|
|
351
|
+
_n_open[0] += 1
|
|
352
|
+
root = f"{DATA_DIR}/r{_n_open[0]}"
|
|
353
|
+
root_n = os.path.normpath(root)
|
|
354
|
+
files = 0
|
|
355
|
+
sources = []
|
|
356
|
+
if data_path:
|
|
357
|
+
sources.append(("", zipfile.ZipFile(data_path)))
|
|
358
|
+
with zipfile.ZipFile(project_path) as pz:
|
|
359
|
+
if any(n.startswith("data/") for n in pz.namelist()):
|
|
360
|
+
sources.append(("data/", zipfile.ZipFile(io.BytesIO(open(project_path, "rb").read()))))
|
|
361
|
+
for prefix, z in sources:
|
|
362
|
+
with z:
|
|
363
|
+
for n in z.namelist():
|
|
364
|
+
if not n.startswith(prefix) or n.endswith("/") or n == prefix:
|
|
365
|
+
continue
|
|
366
|
+
rel = n[len(prefix):]
|
|
367
|
+
target = os.path.normpath(os.path.join(root, rel))
|
|
368
|
+
if not target.startswith(root_n + os.sep):
|
|
369
|
+
continue # zip 안의 ../ 같은 경로는 무시
|
|
370
|
+
os.makedirs(os.path.dirname(target), exist_ok=True)
|
|
371
|
+
with open(target, "wb") as f:
|
|
372
|
+
f.write(z.read(n))
|
|
373
|
+
files += 1
|
|
374
|
+
uses_copy = [] # 출처가 데이터 사본(@data/...)을 가리키는지
|
|
375
|
+
src = _walk_strings(pr["data_source"], lambda v: (uses_copy.append(1), root + "/" + v[len(_MARK):])[1] if v.startswith(_MARK) else v)
|
|
376
|
+
if src.get("example"):
|
|
377
|
+
studio.load_source(src)
|
|
378
|
+
elif files or uses_copy:
|
|
379
|
+
if not files:
|
|
380
|
+
raise UserError("이 프로젝트의 데이터 사본이 없음", "② 데이터에서 같은 데이터를 고른 뒤 다시 저장하세요")
|
|
381
|
+
studio.load_source(src)
|
|
382
|
+
elif studio.data is None:
|
|
383
|
+
raise UserError("이 프로젝트의 데이터를 먼저 불러오세요", "② 데이터에서 같은 데이터를 고른 뒤 다시 여세요")
|
|
384
|
+
return dict(_opened(studio, pr), name=pr.get("name", ""))
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def fit_distance(studio: Studio, feats, n: int, c: int, k: int) -> dict:
|
|
388
|
+
"""이상 탐지 '정상과의 거리': 엔진이 뽑은 정상 특징(float32 바이트, n × c) → 넣을 값 {이름: float32 바이트}."""
|
|
389
|
+
from blocklearning.anomaly import fit_distance as fit
|
|
390
|
+
raw = feats.to_bytes() if hasattr(feats, "to_bytes") else bytes(feats)
|
|
391
|
+
F = np.frombuffer(raw, dtype=np.float32).reshape(int(n), int(c))
|
|
392
|
+
return {name: np.ascontiguousarray(v, dtype=np.float32).tobytes() for name, v in fit(F, int(k)).items()}
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
@_wrap
|
|
396
|
+
def loss_setup(studio: Studio, settings_json: str) -> dict:
|
|
397
|
+
"""학습 설정의 손실 → 엔진이 쓸 {spec (기본이면 None), class_weights}. 잘못이면 오류."""
|
|
398
|
+
from blocklearning import losses
|
|
399
|
+
d = studio.need_data()
|
|
400
|
+
heads = d.n_out.heads if d.task == "multi" else None
|
|
401
|
+
try:
|
|
402
|
+
spec = losses.normalize(json.loads(settings_json or "{}").get("loss"), d.task, heads)
|
|
403
|
+
except ValueError as e:
|
|
404
|
+
raise UserError(str(e), "④ 학습 → 더 보기의 손실을 고치세요") from None
|
|
405
|
+
if heads: # 정답 여러 개: 엔진에 기본 손실이 없으니 늘 항 목록으로
|
|
406
|
+
cw = {k: v.tolist() for k, v in losses.multi_class_weights(d.y_train, heads, spec).items()}
|
|
407
|
+
return {"spec": [dict(t, label=losses.label(t)) for t in spec], "class_weights": cw or None}
|
|
408
|
+
if losses.is_default(spec, d.task):
|
|
409
|
+
return {"spec": None, "class_weights": None}
|
|
410
|
+
K = len(d.classes) if d.task in ("classification", "segmentation") else 0
|
|
411
|
+
cw = losses.class_weights(d.y_train, K).tolist() if K and any(t.get("balance") for t in spec) else None
|
|
412
|
+
return {"spec": [dict(t, label=losses.label(t)) for t in spec], "class_weights": cw}
|