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
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// 학습 전용 일꾼 (Web Worker): 화면과 다른 스레드에서 engine.js의 train을 돌려, 학습하는 동안 화면이 버벅이지 않게 한다.
|
|
2
|
+
// web.js의 trainInWorker가 부름. 끝나면 가중치(state)를 넘기고, 화면 쪽이 같은 모델을 다시 만들어 예측·미리보기·저장에 씀.
|
|
3
|
+
// 주고받는 것: init {tf: [주소, SRI], engine} → ready {backend} · train {id, plan, d, s, pretrained} → epoch {id, p} … done/error · cancel {id}
|
|
4
|
+
"use strict";
|
|
5
|
+
const cancelled = new Set();
|
|
6
|
+
|
|
7
|
+
async function init({ tf, engine }) {
|
|
8
|
+
const r = await fetch(tf[0], { integrity: tf[1], mode: "cors" }); // CDN 파일은 내용 해시가 맞을 때만
|
|
9
|
+
if (!r.ok) throw new Error("TensorFlow.js를 받지 못함 (" + r.status + ")");
|
|
10
|
+
const url = URL.createObjectURL(new Blob([await r.text()], { type: "text/javascript" }));
|
|
11
|
+
try { importScripts(url); } finally { URL.revokeObjectURL(url); }
|
|
12
|
+
importScripts(engine);
|
|
13
|
+
await self.tf.ready();
|
|
14
|
+
return self.tf.getBackend();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function train({ id, plan, d, s, pretrained }) {
|
|
18
|
+
const E = self.DLEngine;
|
|
19
|
+
await E.ensurePretrained(plan, pretrained);
|
|
20
|
+
const { net, result, out, outTr } = await E.train(plan, d, s,
|
|
21
|
+
(p) => { self.postMessage({ type: "epoch", id, p }); return cancelled.has(id); },
|
|
22
|
+
() => cancelled.has(id));
|
|
23
|
+
try {
|
|
24
|
+
const state = net.state(), moved = [];
|
|
25
|
+
for (const v of Object.values(state)) moved.push(v.data.buffer);
|
|
26
|
+
if (out) moved.push(out.buffer);
|
|
27
|
+
if (outTr) moved.push(outTr.buffer);
|
|
28
|
+
self.postMessage({ type: "done", id, result, out: out || null, outTr: outTr || null, state }, moved);
|
|
29
|
+
} finally { net.dispose(); }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
self.onmessage = async (e) => {
|
|
33
|
+
const m = e.data;
|
|
34
|
+
if (m.type === "cancel") { cancelled.add(m.id); return; }
|
|
35
|
+
try {
|
|
36
|
+
if (m.type === "init") self.postMessage({ type: "ready", backend: await init(m) });
|
|
37
|
+
else if (m.type === "train") await train(m);
|
|
38
|
+
} catch (err) {
|
|
39
|
+
self.postMessage({ type: "error", id: m.id, name: err.name || "Error", message: String(err.message || err) });
|
|
40
|
+
} finally { if (m.id) cancelled.delete(m.id); }
|
|
41
|
+
};
|
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
// BlockLearning 웹 버전(GitHub Pages)의 다리: 화면(app.js)의 api(path, body)를 서버 대신 브라우저 안에서 처리한다.
|
|
2
|
+
// - Python(blocklearning 패키지)은 Pyodide로 그대로 돌린다: 검사·데이터 읽기·과제·코드 생성·프로젝트 파일 (web.py)
|
|
3
|
+
// - 학습·샘플 따라가기는 TensorFlow.js 엔진(engine.js), 파일은 고르기(업로드 아님, 브라우저 안에만)·내려받기
|
|
4
|
+
// 데이터는 PC 밖으로 나가지 않는다. 로컬 실행(python -m blocklearning)에서는 이 파일을 쓰지 않는다.
|
|
5
|
+
(function () {
|
|
6
|
+
"use strict";
|
|
7
|
+
const PY_VERSION = "0.27.7";
|
|
8
|
+
const BASE = "src/blocklearning/";
|
|
9
|
+
const PY_FILES = ["__init__.py", "analysis.py", "anomaly.py", "blocks.py", "codegen.py", "core.py", "data.py", "detect.py", "forecast.py", "graph.py", "jobs.py", "layers.py", "losses.py", "nn_extra.py",
|
|
10
|
+
"labeling.py", "labeling_sources.py", "predict.py", "pretrained.py", "project.py", "multi.py", "segment.py", "tasks.py", "web.py", "weblabel.py"];
|
|
11
|
+
const PRETRAINED = BASE + "pretrained/"; // 사전학습 가중치 (그 블록을 쓸 때만 받음)
|
|
12
|
+
const gotData = new Set(); // 받아 둔 예시 데이터 파일 (예시를 누를 때만 받음)
|
|
13
|
+
const E = () => window.DLEngine;
|
|
14
|
+
|
|
15
|
+
const W = { py: null, mod: null, studio: null, data: null, trained: null, jobs: {}, running: null, n: 0 };
|
|
16
|
+
|
|
17
|
+
// ------------------------------------------------------------ 준비 (Pyodide + 우리 Python 코드)
|
|
18
|
+
function bootMessage(text) {
|
|
19
|
+
let el = document.getElementById("web-boot");
|
|
20
|
+
if (!el) {
|
|
21
|
+
el = document.createElement("div");
|
|
22
|
+
el.id = "web-boot";
|
|
23
|
+
el.className = "web-boot";
|
|
24
|
+
document.body.appendChild(el);
|
|
25
|
+
}
|
|
26
|
+
el.textContent = text;
|
|
27
|
+
el.hidden = !text;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function boot() {
|
|
31
|
+
bootMessage("BlockLearning을 준비하는 중… (처음 열 때는 10초쯤 걸립니다. 계산은 모두 이 브라우저 안에서 합니다)");
|
|
32
|
+
const py = await loadPyodide({ indexURL: `https://cdn.jsdelivr.net/pyodide/v${PY_VERSION}/full/` });
|
|
33
|
+
await py.loadPackage(["numpy", "pillow"]);
|
|
34
|
+
py.FS.mkdirTree("/app/blocklearning/data");
|
|
35
|
+
await Promise.all(PY_FILES.map(async (f) => py.FS.writeFile(`/app/blocklearning/${f}`, await (await fetch(BASE + f, { cache: "no-cache" })).text())));
|
|
36
|
+
py.FS.mkdirTree("/data");
|
|
37
|
+
py.runPython("import sys; sys.path.insert(0, '/app')");
|
|
38
|
+
W.mod = py.pyimport("blocklearning.web");
|
|
39
|
+
W.lab = py.pyimport("blocklearning.weblabel");
|
|
40
|
+
W.studio = W.mod.WebStudio();
|
|
41
|
+
W.py = py;
|
|
42
|
+
bootMessage("");
|
|
43
|
+
}
|
|
44
|
+
const ready = boot().catch((e) => { bootMessage("BlockLearning을 준비하지 못함: " + e.message + " (인터넷 연결을 확인하고 새로 고치세요)"); throw e; });
|
|
45
|
+
|
|
46
|
+
// ------------------------------------------------------------ 도움 함수
|
|
47
|
+
function pyError(e) { // Python 예외 → 화면 오류 모양
|
|
48
|
+
const msg = String((e && e.message) || e);
|
|
49
|
+
const m = msg.match(/UserError: (.*)/) || msg.match(/DataError: (.*)/) || msg.match(/(\w+Error: .*)\s*$/);
|
|
50
|
+
return { message: m ? m[1].trim() : "처리 중 오류", hint: "", detail: msg.slice(-3000) };
|
|
51
|
+
}
|
|
52
|
+
function wrapped(json) { // web.py의 _wrap 결과 {status, body}
|
|
53
|
+
const r = JSON.parse(json);
|
|
54
|
+
if (r.status !== 200) throw (r.body && r.body.error) || { message: "오류" };
|
|
55
|
+
return r.body;
|
|
56
|
+
}
|
|
57
|
+
function download(name, data, type = "application/octet-stream") {
|
|
58
|
+
const blob = data instanceof Blob ? data : new Blob([data], { type });
|
|
59
|
+
const a = document.createElement("a");
|
|
60
|
+
a.href = URL.createObjectURL(blob);
|
|
61
|
+
a.download = name;
|
|
62
|
+
document.body.appendChild(a);
|
|
63
|
+
a.click();
|
|
64
|
+
setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 2000);
|
|
65
|
+
}
|
|
66
|
+
const baseName = (p) => String(p || "").trim().replace(/^["']|["']$/g, "").split(/[\\/]/).pop();
|
|
67
|
+
function bytesOf(proxy) { // Python bytes → Uint8Array
|
|
68
|
+
const u8 = proxy.toJs();
|
|
69
|
+
if (proxy.destroy) proxy.destroy();
|
|
70
|
+
return u8;
|
|
71
|
+
}
|
|
72
|
+
function getData() {
|
|
73
|
+
if (W.data) return W.data;
|
|
74
|
+
const p = W.mod.data_payload(W.studio);
|
|
75
|
+
const f32 = (k) => { const u8 = bytesOf(p.get(k)); return new Float32Array(u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength)); };
|
|
76
|
+
const meta = JSON.parse(p.get("meta"));
|
|
77
|
+
W.data = Object.assign(meta, { X_train: f32("X_train"), X_test: f32("X_test"), y_train: f32("y_train"), y_test: f32("y_test") });
|
|
78
|
+
p.destroy();
|
|
79
|
+
return W.data;
|
|
80
|
+
}
|
|
81
|
+
function stateForPython(net) { // 엔진 가중치 → Python에 넘길 {이름: {shape, data(바이트), int}}
|
|
82
|
+
const out = {};
|
|
83
|
+
for (const [k, v] of Object.entries(net.state())) {
|
|
84
|
+
const isInt = v.data instanceof Int32Array;
|
|
85
|
+
out[k] = { shape: v.shape, data: new Uint8Array(v.data.buffer.slice(0)), int: isInt };
|
|
86
|
+
}
|
|
87
|
+
return W.py.toPy(out);
|
|
88
|
+
}
|
|
89
|
+
function clearTrained() {
|
|
90
|
+
if (W.running) W.running.cancelled = true;
|
|
91
|
+
if (W.trained) W.trained.net.dispose();
|
|
92
|
+
W.trained = null;
|
|
93
|
+
W.data = null;
|
|
94
|
+
}
|
|
95
|
+
const pyCall = (method, path, body) => {
|
|
96
|
+
const r = JSON.parse(W.mod.call_json(W.studio, method, path, body === undefined ? "" : JSON.stringify(body)));
|
|
97
|
+
if (r.status !== 200) throw (r.body && r.body.error) || { message: `오류 ${r.status}` };
|
|
98
|
+
return r.body;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
// ------------------------------------------------------------ 학습 일꾼 (train-worker.js): 화면과 다른 스레드에서 학습
|
|
102
|
+
// 일꾼이 GPU(WebGL)를 못 쓰는데 화면은 쓸 수 있으면 (OffscreenCanvas가 없는 브라우저 등) 화면 스레드에서 학습 (느린 CPU보다 나음)
|
|
103
|
+
let worker = null;
|
|
104
|
+
function trainWorker() {
|
|
105
|
+
if (!worker) worker = new Promise((ok, no) => {
|
|
106
|
+
const B = window.DL_BOOT || {};
|
|
107
|
+
if (typeof Worker === "undefined" || !B.TF) return no(new Error("일꾼 없음"));
|
|
108
|
+
const static_ = new URL(B.STATIC || "src/blocklearning/static/", location.href).href;
|
|
109
|
+
const w = new Worker(static_ + "train-worker.js?v=" + Date.now());
|
|
110
|
+
const runs = new Map();
|
|
111
|
+
w.onmessage = (e) => {
|
|
112
|
+
const m = e.data;
|
|
113
|
+
if (m.type === "ready") {
|
|
114
|
+
if (E().tf.getBackend() !== "cpu" && m.backend === "cpu") { w.terminate(); return no(new Error("일꾼 GPU 없음")); }
|
|
115
|
+
return ok({ w, runs });
|
|
116
|
+
}
|
|
117
|
+
if (m.type === "error" && !m.id) { w.terminate(); return no(new Error(m.message)); } // 준비 실패 (TF.js를 못 받음 등) → 화면 스레드로
|
|
118
|
+
const r = runs.get(m.id);
|
|
119
|
+
if (!r) return;
|
|
120
|
+
if (m.type === "epoch") { if (r.onEpoch(m.p)) w.postMessage({ type: "cancel", id: m.id }); }
|
|
121
|
+
else { runs.delete(m.id); m.type === "done" ? r.ok(m) : r.no(Object.assign(new Error(m.message), { name: m.name })); }
|
|
122
|
+
};
|
|
123
|
+
w.onerror = (e) => { // 일꾼이 죽음 (메모리 부족 등): 하던 학습은 오류로, 다음엔 새 일꾼
|
|
124
|
+
e.preventDefault();
|
|
125
|
+
const err = new Error(e.message || "학습 일꾼이 멈춤");
|
|
126
|
+
no(err); runs.forEach((r) => r.no(err)); runs.clear();
|
|
127
|
+
w.terminate(); worker = null;
|
|
128
|
+
};
|
|
129
|
+
w.postMessage({ type: "init", tf: B.TF, engine: static_ + "engine.js?v=" + Date.now() });
|
|
130
|
+
});
|
|
131
|
+
return worker;
|
|
132
|
+
}
|
|
133
|
+
async function trainOffMain(plan, d, s, onEpoch, isCancelled) { // E().train과 같은 결과 {net, result, out, outTr}
|
|
134
|
+
let W_;
|
|
135
|
+
try { W_ = await trainWorker(); }
|
|
136
|
+
catch (e) { // 일꾼을 못 쓰면 지금처럼 화면 스레드에서
|
|
137
|
+
await E().ensurePretrained(plan, PRETRAINED);
|
|
138
|
+
return E().train(plan, d, s, onEpoch, isCancelled);
|
|
139
|
+
}
|
|
140
|
+
const id = "t" + (++W.n), { w, runs } = W_;
|
|
141
|
+
const m = await new Promise((ok, no) => {
|
|
142
|
+
runs.set(id, { ok, no, onEpoch });
|
|
143
|
+
const poll = setInterval(() => { if (!runs.has(id)) clearInterval(poll); else if (isCancelled && isCancelled()) w.postMessage({ type: "cancel", id }); }, 100);
|
|
144
|
+
w.postMessage({ type: "train", id, plan, d, s, pretrained: new URL(PRETRAINED, location.href).href }); // 데이터는 복사 (화면 쪽도 계속 씀)
|
|
145
|
+
});
|
|
146
|
+
const net = new (E().Net)(plan, s.seed || 0); // 일꾼이 학습한 가중치를 화면 쪽 모델에 (예측·미리보기·저장은 여기서)
|
|
147
|
+
try { net.load(m.state); } catch (e) { net.dispose(); throw e; }
|
|
148
|
+
return { net, result: m.result, out: m.out || undefined, outTr: m.outTr || undefined };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ------------------------------------------------------------ 학습 (작업처럼: id → 진행 읽기)
|
|
152
|
+
function startTrain(body) {
|
|
153
|
+
const plan = wrapped(W.mod.plan(W.studio, JSON.stringify(body.graph)));
|
|
154
|
+
const data = getData();
|
|
155
|
+
if (W.running) W.running.cancelled = true;
|
|
156
|
+
const ls = wrapped(W.mod.loss_setup(W.studio, JSON.stringify(body.settings || {}))); // 조립한 손실 검사 (기본이면 spec 없음)
|
|
157
|
+
const s = Object.assign({ epochs: 30, lr: 1e-3, batch_size: 32, seed: 0 }, body.settings || {}, { loss: ls.spec, class_weights: ls.class_weights });
|
|
158
|
+
const job = { id: "w" + (++W.n), kind: "train", state: "running", progress: [], result: null, error: null, cancelled: false };
|
|
159
|
+
W.jobs[job.id] = job;
|
|
160
|
+
W.running = job;
|
|
161
|
+
const onEpoch = (p) => { job.progress.push(p); job.progress.splice(0, Math.max(0, job.progress.length - 100)); return job.cancelled; };
|
|
162
|
+
const dist = plan.steps.find((st) => st.type === "output" && st.cfg.head === "distance"); // 이상 탐지 '정상과의 거리'
|
|
163
|
+
(dist ? E().ensurePretrained(plan, PRETRAINED).then(() => E().fitDistance(plan, data, fitDistance(dist), onEpoch))
|
|
164
|
+
: trainOffMain(plan, data, s, onEpoch, () => job.cancelled)).then(({ net, result, out, outTr }) => {
|
|
165
|
+
if ((job.cancelled && !job.stopped) || W.data !== data) { net.dispose(); job.state = "cancelled"; return; } // 다시 시작·데이터 바뀜은 버림
|
|
166
|
+
result.stopped = !!job.stopped;
|
|
167
|
+
if (out) Object.assign(result, wrapped(W.mod.task_result(W.studio, new Uint8Array(out.buffer), new Uint8Array(outTr.buffer)))); // 예측·이상 탐지
|
|
168
|
+
if (W.trained) W.trained.net.dispose();
|
|
169
|
+
W.trained = { net, plan, graph: body.graph, settings: body.settings || {}, results: result };
|
|
170
|
+
const st = stateForPython(net);
|
|
171
|
+
try { W.mod.set_trained(W.studio, JSON.stringify(body.graph), JSON.stringify(body.settings || {}), JSON.stringify(result), st); }
|
|
172
|
+
finally { st.destroy(); }
|
|
173
|
+
job.result = result;
|
|
174
|
+
job.state = "done";
|
|
175
|
+
changed("train");
|
|
176
|
+
}).catch((e) => {
|
|
177
|
+
job.state = job.cancelled ? "cancelled" : "failed";
|
|
178
|
+
job.error = `${e.name || "Error"}: ${e.message || e}`;
|
|
179
|
+
}).finally(() => { if (W.running === job) W.running = null; });
|
|
180
|
+
return { id: job.id };
|
|
181
|
+
}
|
|
182
|
+
function fitDistance(head) { // 정상 특징 → 정상과의 거리 값 (Python anomaly.fit_distance)
|
|
183
|
+
const k = head.params.find((p) => p[0].endsWith(".basis"))[1][0];
|
|
184
|
+
return async (F, n, c) => {
|
|
185
|
+
const p = W.mod.fit_distance(W.studio, new Uint8Array(F.buffer, F.byteOffset, F.byteLength), n, c, k), out = {};
|
|
186
|
+
try {
|
|
187
|
+
for (const name of ["mean", "basis", "inv_var", "inv_rest"]) {
|
|
188
|
+
const u8 = bytesOf(p.get(name));
|
|
189
|
+
out[name] = new Float32Array(u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength));
|
|
190
|
+
}
|
|
191
|
+
} finally { p.destroy(); }
|
|
192
|
+
return out;
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
function jobView(path) {
|
|
196
|
+
const id = path.split("/")[3], job = W.jobs[id];
|
|
197
|
+
if (!job) throw { message: "작업을 찾을 수 없음" };
|
|
198
|
+
if (path.endsWith("/cancel")) { job.cancelled = job.stopped = true; return { ok: true }; } // [멈추기]: 거기까지 학습한 것은 남김
|
|
199
|
+
return { id: job.id, kind: job.kind, state: job.state, progress: job.progress.slice(), result: job.result, error: job.error };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ------------------------------------------------------------ 샘플 따라가기
|
|
203
|
+
function activations(body) {
|
|
204
|
+
if (!W.trained) throw { message: "학습된 모델이 없음", hint: "④ 학습 단계에서 먼저 학습하세요" };
|
|
205
|
+
const i = Number(body.sample_index || 0);
|
|
206
|
+
const s = wrapped(W.mod.sample(W.studio, i));
|
|
207
|
+
const d = getData(), net = W.trained.net;
|
|
208
|
+
const x = E().toInput(Float32Array.from(s.x), 1, net.kind, d.length, d.image, d.channels);
|
|
209
|
+
const attention = {};
|
|
210
|
+
const values = Object.fromEntries(Object.entries(net.trace(x, attention)).map(([k, v]) => [k, E().thin(v)])); // 층마다 줄이기
|
|
211
|
+
const out = net.predict(x);
|
|
212
|
+
x.dispose();
|
|
213
|
+
let pred;
|
|
214
|
+
if (d.task === "detection") pred = `상자 ${E().detDecode(out, 0, d.det, E().DET.show).length}개 찾음`;
|
|
215
|
+
else if (d.task === "forecast") pred = `다음 ${out.length}개 (첫 값 ${Number(out[0].toPrecision(4))})`;
|
|
216
|
+
else if (d.task === "segmentation") { // 시점마다 가장 큰 상태 → 구간 이름
|
|
217
|
+
const K = d.seg.n_cls, L = d.seg.length, names = [];
|
|
218
|
+
for (let t = 0; t < L; t++) {
|
|
219
|
+
let b = 0;
|
|
220
|
+
for (let k = 1; k < K; k++) if (out[k * L + t] > out[b * L + t]) b = k;
|
|
221
|
+
if (!names.length || names[names.length - 1] !== b) names.push(b);
|
|
222
|
+
}
|
|
223
|
+
pred = names.slice(0, 5).map((k) => s.classes[k]).join(" → ") + (names.length > 5 ? ` … (구간 ${names.length}개)` : "");
|
|
224
|
+
}
|
|
225
|
+
else if (d.task === "anomaly") {
|
|
226
|
+
let t = 0;
|
|
227
|
+
for (let j = 0; j < out.length; j++) t += (out[j] - s.x[j]) ** 2;
|
|
228
|
+
const sc = out.length === 1 && s.x.length > 1 ? out[0] : t / out.length, th = W.trained.results && W.trained.results.threshold; // '정상과의 거리'면 출력이 점수
|
|
229
|
+
pred = `이상 점수 ${Number(sc.toPrecision(3))}` + (th === undefined || th === null ? "" : sc > th ? " → 이상" : " → 정상");
|
|
230
|
+
}
|
|
231
|
+
else if (d.task === "classification") { let b = 0; for (let j = 1; j < out.length; j++) if (out[j] > out[b]) b = j; pred = s.classes[b]; }
|
|
232
|
+
else if (d.task === "multi") pred = d.multi.heads.map((h) => { // 정답마다: 분류는 가장 큰 클래스, 값은 그 칸
|
|
233
|
+
if (h.kind !== "class") return `${h.name} ${Number(out[h.start].toPrecision(4))}`;
|
|
234
|
+
let b = 0;
|
|
235
|
+
for (let k = 1; k < h.size; k++) if (out[h.start + k] > out[h.start + b]) b = k;
|
|
236
|
+
return `${h.name} ${h.classes[b]}`;
|
|
237
|
+
}).join(" · ");
|
|
238
|
+
else pred = out[0];
|
|
239
|
+
let sal = null;
|
|
240
|
+
try { sal = E().saliency(net, Float32Array.from(s.x), d); } catch (e) { sal = null; } // 기울기를 못 내는 블록이면 보이지 않음
|
|
241
|
+
return { index: i, label: s.label, prediction: pred, input: s.input, values, attention, order: s.order, saliency: sal };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// ------------------------------------------------------------ 코드·가중치·프로젝트 (내려받기)
|
|
245
|
+
function codeSave(body) {
|
|
246
|
+
let name = baseName(body.path);
|
|
247
|
+
if (!/\.py$/i.test(name)) throw { message: "파이썬 파일(.py) 이름을 넣으세요", hint: "예: model_pytorch.py" };
|
|
248
|
+
const stem = name.replace(/\.py$/i, ""), wname = stem + "_weights.npz";
|
|
249
|
+
const r = pyCall("POST", "/api/code", Object.assign({}, body, { weights_file: wname }));
|
|
250
|
+
download(name, r.code, "text/x-python");
|
|
251
|
+
const files = [name];
|
|
252
|
+
if (r.trained && r.framework === "pytorch" && W.trained) {
|
|
253
|
+
const st = stateForPython(W.trained.net);
|
|
254
|
+
try { download(wname, bytesOf(W.mod.weights_npz(W.studio, JSON.stringify(W.trained.graph), st))); } finally { st.destroy(); }
|
|
255
|
+
files.push(wname);
|
|
256
|
+
}
|
|
257
|
+
return { files, trained: r.trained };
|
|
258
|
+
}
|
|
259
|
+
function exportModel() {
|
|
260
|
+
if (!W.trained) throw { message: "학습된 모델이 없음", hint: "④ 학습 단계에서 먼저 학습하세요" };
|
|
261
|
+
return codeSave({ graph: W.trained.graph, framework: "pytorch", settings: W.trained.settings, path: "model_pytorch.py" });
|
|
262
|
+
}
|
|
263
|
+
function projectSave(body) {
|
|
264
|
+
let name = baseName(body.path) || "blocklearning-project.blocklearning";
|
|
265
|
+
if (!/\.(blocklearning|dlstudio)$/i.test(name)) name += ".blocklearning";
|
|
266
|
+
const st = W.trained ? stateForPython(W.trained.net) : null;
|
|
267
|
+
try { download(name, bytesOf(W.mod.project_bytes(W.studio, st))); }
|
|
268
|
+
catch (e) { throw pyError(e); }
|
|
269
|
+
finally { if (st) st.destroy(); }
|
|
270
|
+
return { ok: true, file: name };
|
|
271
|
+
}
|
|
272
|
+
async function loadTrained(r) { // {response, state, plan} → 엔진에 학습한 모델
|
|
273
|
+
if (W.trained) { W.trained.net.dispose(); W.trained = null; }
|
|
274
|
+
if (!r.state) return;
|
|
275
|
+
await E().ensurePretrained(r.plan, PRETRAINED); // 고정 가중치는 프로젝트에 없음 → 사전학습 파일에서
|
|
276
|
+
const net = new (E().Net)(r.plan, 0);
|
|
277
|
+
const st = {};
|
|
278
|
+
for (const [k, v] of Object.entries(r.state)) st[k] = { shape: v.shape, data: v.int ? Int32Array.from(v.data) : Float32Array.from(v.data) };
|
|
279
|
+
net.load(st);
|
|
280
|
+
W.trained = { net, plan: r.plan, graph: r.response.graph, settings: r.response.train_settings || {}, results: r.response.results || {} };
|
|
281
|
+
}
|
|
282
|
+
async function projectOpen(body) {
|
|
283
|
+
const r = wrapped(W.mod.record_open(W.studio, body.path, body.data_path || ""));
|
|
284
|
+
W.openedName = r.name || "";
|
|
285
|
+
W.data = null;
|
|
286
|
+
await loadTrained(r);
|
|
287
|
+
return r.response;
|
|
288
|
+
}
|
|
289
|
+
async function runRestore(body) { // 학습 기록의 모델로 돌아가기
|
|
290
|
+
const r = wrapped(W.mod.run_restore(W.studio, Number(body.n)));
|
|
291
|
+
await loadTrained(r);
|
|
292
|
+
changed("train");
|
|
293
|
+
return r.response;
|
|
294
|
+
}
|
|
295
|
+
async function predictNew(body) { // 새 데이터로 예측: Python이 읽고 정규화 → 엔진(CPU) → Python이 표로
|
|
296
|
+
if (!W.trained) throw { message: "학습된 모델이 없음", hint: "④ 학습 단계에서 먼저 학습하세요" };
|
|
297
|
+
const n = wrapped(W.mod.predict_prepare(W.studio, JSON.stringify(body))).n;
|
|
298
|
+
const u8 = bytesOf(W.mod.predict_x(W.studio));
|
|
299
|
+
const X = new Float32Array(u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength));
|
|
300
|
+
const d = getData(), net = W.trained.net;
|
|
301
|
+
const x = E().toInput(X, n, net.kind, d.length, d.image, d.channels);
|
|
302
|
+
let out;
|
|
303
|
+
try { out = (await E().checkedPredict(net, x, n)).out; } finally { x.dispose(); }
|
|
304
|
+
return wrapped(W.mod.predict_finish(W.studio, new Uint8Array(out.buffer)));
|
|
305
|
+
}
|
|
306
|
+
const VIEW = ["pos", "size", "brk", "shift"];
|
|
307
|
+
function bare(g) { // 화면용 값을 뺀 그래프 (같은 모델인지 비교)
|
|
308
|
+
return JSON.stringify(g, (k, v) => (VIEW.includes(k) ? undefined : v));
|
|
309
|
+
}
|
|
310
|
+
async function preview(body) { // ③ 블록 미리보기: 학습 샘플 하나가 그 블록을 지난 값
|
|
311
|
+
const plan = wrapped(W.mod.plan(W.studio, JSON.stringify(body.graph)));
|
|
312
|
+
await E().ensurePretrained(plan, PRETRAINED);
|
|
313
|
+
const d = getData();
|
|
314
|
+
const trained = !!W.trained && bare(W.trained.graph) === bare(body.graph);
|
|
315
|
+
const net = trained ? W.trained.net : new (E().Net)(plan, 0);
|
|
316
|
+
const x = E().toInput(d.X_train.slice(0, d.n_features), 1, net.kind, d.length, d.image, d.channels);
|
|
317
|
+
try {
|
|
318
|
+
const vals = net.trace(x);
|
|
319
|
+
if (!(body.node in vals)) throw { message: "이 블록의 값을 찾을 수 없음", hint: "블록을 다시 고르세요" };
|
|
320
|
+
const label = d.task === "detection" ? `상자 ${d.det.train[0].length}개` : d.task === "classification" ? d.classes[d.y_train[0]] : d.y_train[0];
|
|
321
|
+
return { node: body.node, value: E().thin(vals[body.node]), trained, label };
|
|
322
|
+
} finally { x.dispose(); if (!trained) net.dispose(); }
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ------------------------------------------------------------ 라벨링 (라벨링 페이지 · studio ② 라벨링한 데이터)
|
|
326
|
+
// 계산은 core.api_label 그대로 (numpy만 씀). 파일 경로가 필요한 동작만 여기서: 새로 만들기·합치기·내보내기(내려받기)·그림 보기
|
|
327
|
+
const LABEL_READ = new Set(["state", "items", "item", "rule_preview", "cluster", "normal_candidates", "columns"]);
|
|
328
|
+
const LABEL_OUT = new Set(["export", "export_yolo", "export_coco", "export_normals", "split", "bundle"]);
|
|
329
|
+
let labelUrls = {}; // 그림 이름 → blob URL (크게 보기)
|
|
330
|
+
function resetLabelUrls() { Object.values(labelUrls).forEach((u) => URL.revokeObjectURL(u)); labelUrls = {}; }
|
|
331
|
+
function labelCall(op, body) {
|
|
332
|
+
let r;
|
|
333
|
+
if (op === "new") { resetLabelUrls(); r = wrapped(W.lab.new_job(W.studio, JSON.stringify(body))); }
|
|
334
|
+
else if (op === "merge") r = wrapped(W.lab.merge_file(W.studio, body.file || ""));
|
|
335
|
+
else if (op === "use" || op === "open") throw { message: "웹 버전은 라벨링 페이지의 작업 목록으로 엽니다", hint: "" };
|
|
336
|
+
else if (op === "deep_suggest") return deepSuggest(body);
|
|
337
|
+
else if (LABEL_OUT.has(op)) { // 내보내기: Pyodide 안에 쓴 파일을 내려받기
|
|
338
|
+
r = wrapped(W.lab.export_file(W.studio, op, JSON.stringify(body)));
|
|
339
|
+
for (const [name, p] of r.files) download(name, W.py.FS.readFile(p));
|
|
340
|
+
return r;
|
|
341
|
+
} else r = pyCall("POST", "/api/label/" + op, body);
|
|
342
|
+
if (!LABEL_READ.has(op)) changed("label");
|
|
343
|
+
return r;
|
|
344
|
+
}
|
|
345
|
+
function loadScript(src, integrity) {
|
|
346
|
+
return new Promise((ok, no) => {
|
|
347
|
+
const s = document.createElement("script");
|
|
348
|
+
s.src = src;
|
|
349
|
+
if (integrity) { s.integrity = integrity; s.crossOrigin = "anonymous"; }
|
|
350
|
+
s.onload = ok;
|
|
351
|
+
s.onerror = () => no(new Error("불러오지 못함: " + src));
|
|
352
|
+
document.body.appendChild(s);
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
async function ensureEngine() { // 라벨링 페이지: 학습 엔진(TF.js + engine.js)은 처음 쓸 때 불러옴
|
|
356
|
+
if (window.tf && window.DLEngine) return;
|
|
357
|
+
const B = window.DL_BOOT || {};
|
|
358
|
+
if (!window.tf) await loadScript(B.TF[0], B.TF[1]);
|
|
359
|
+
if (!window.DLEngine) await loadScript((B.STATIC || "src/blocklearning/static/") + "engine.js?v=" + Date.now());
|
|
360
|
+
}
|
|
361
|
+
async function deepSuggest(body) { // 딥러닝 제안: 정답 붙은 샘플로 대표 모델 학습 → 정답 없는 샘플에 확률
|
|
362
|
+
const prep = wrapped(W.lab.deep_prepare(W.studio));
|
|
363
|
+
if (body.onProgress) body.onProgress(`${prep.model} 준비 중… (처음이면 학습 엔진을 받느라 몇 초 걸립니다)`);
|
|
364
|
+
await ensureEngine();
|
|
365
|
+
const p = W.lab.deep_payload();
|
|
366
|
+
const f32 = (k) => { const u8 = bytesOf(p.get(k)); return new Float32Array(u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength)); };
|
|
367
|
+
const meta = JSON.parse(p.get("meta"));
|
|
368
|
+
const d = Object.assign(meta, { X_train: f32("X_train"), X_test: f32("X_test"), y_train: f32("y_train"), y_test: f32("y_test") });
|
|
369
|
+
const Xp = f32("X_pred");
|
|
370
|
+
p.destroy();
|
|
371
|
+
const epochs = 40;
|
|
372
|
+
const { net, result } = await trainOffMain(prep.plan, d, { epochs, lr: 0.003, batch_size: 32, seed: 0 },
|
|
373
|
+
(pr) => { if (body.onProgress) body.onProgress(`${prep.model} 학습 중… ${pr.epoch}/${epochs}`); return false; });
|
|
374
|
+
let probs;
|
|
375
|
+
const x = E().toInput(Xp, meta.n_pred, net.kind, d.length, d.image, d.channels);
|
|
376
|
+
try {
|
|
377
|
+
const out = (await E().checkedPredict(net, x, meta.n_pred)).out;
|
|
378
|
+
const k = d.n_out;
|
|
379
|
+
probs = new Float32Array(out.length);
|
|
380
|
+
for (let i = 0; i < meta.n_pred; i++) { // softmax
|
|
381
|
+
let m = -Infinity, s = 0;
|
|
382
|
+
for (let j = 0; j < k; j++) m = Math.max(m, out[i * k + j]);
|
|
383
|
+
for (let j = 0; j < k; j++) { probs[i * k + j] = Math.exp(out[i * k + j] - m); s += probs[i * k + j]; }
|
|
384
|
+
for (let j = 0; j < k; j++) probs[i * k + j] /= s;
|
|
385
|
+
}
|
|
386
|
+
} finally { x.dispose(); net.dispose(); }
|
|
387
|
+
const acc = meta.n_test ? result.test_metric : null;
|
|
388
|
+
const r = wrapped(W.lab.deep_apply(W.studio, new Uint8Array(probs.buffer), acc));
|
|
389
|
+
changed("label");
|
|
390
|
+
return Object.assign(r, { model: prep.model });
|
|
391
|
+
}
|
|
392
|
+
async function labelFileUrl(name) { // 그림 원본 → blob URL
|
|
393
|
+
if (labelUrls[name]) return labelUrls[name];
|
|
394
|
+
const p = String(W.lab.file_path(W.studio, name));
|
|
395
|
+
const ext = (p.split(".").pop() || "").toLowerCase();
|
|
396
|
+
const type = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", bmp: "image/bmp" }[ext] || "application/octet-stream";
|
|
397
|
+
labelUrls[name] = URL.createObjectURL(new Blob([W.py.FS.readFile(p)], { type }));
|
|
398
|
+
return labelUrls[name];
|
|
399
|
+
}
|
|
400
|
+
function labelWork() { // 지금 작업 → {work: 정답 JSON 글자, meta: 목록 요약}
|
|
401
|
+
return { work: String(W.lab.work_text(W.studio)), meta: JSON.parse(String(W.lab.summary(W.studio))) };
|
|
402
|
+
}
|
|
403
|
+
const labelData = () => bytesOf(W.lab.data_bytes(W.studio));
|
|
404
|
+
async function labelOpen(work, data) { // 보관함의 작업 → 라벨링 페이지에서 엶
|
|
405
|
+
await ready;
|
|
406
|
+
resetLabelUrls();
|
|
407
|
+
W.py.FS.mkdirTree("/work");
|
|
408
|
+
const p = `/work/label_${++W.n}.zip`;
|
|
409
|
+
if (data && data.length) W.py.FS.writeFile(p, data);
|
|
410
|
+
return wrapped(W.lab.open_job(W.studio, data && data.length ? p : "", work));
|
|
411
|
+
}
|
|
412
|
+
async function labelOpenBundle(path) { // 작업 묶음(.dllabel.zip) 가져오기
|
|
413
|
+
await ready;
|
|
414
|
+
resetLabelUrls();
|
|
415
|
+
return wrapped(W.lab.open_bundle(W.studio, path));
|
|
416
|
+
}
|
|
417
|
+
async function useLabelJob(body) { // studio ②: 라벨링한 작업 → 학습 데이터
|
|
418
|
+
const rec = await window.DLStore.labels.load(body.label_job);
|
|
419
|
+
if (!rec || !rec.work) throw { message: "라벨링 작업을 찾을 수 없음", hint: "라벨링 페이지에서 작업을 다시 열어 저장하세요" };
|
|
420
|
+
clearTrained();
|
|
421
|
+
W.py.FS.mkdirTree("/work");
|
|
422
|
+
const p = `/work/label_${++W.n}.zip`;
|
|
423
|
+
if (rec.data && rec.data.length) W.py.FS.writeFile(p, rec.data);
|
|
424
|
+
const r = wrapped(W.lab.use_job(W.studio, rec.data && rec.data.length ? p : "", rec.work, !!body.confirmed_only));
|
|
425
|
+
const item = (await window.DLStore.labels.list()).find((x) => x.id === body.label_job);
|
|
426
|
+
r.label_name = item ? item.name : "";
|
|
427
|
+
changed("data");
|
|
428
|
+
return r;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// ------------------------------------------------------------ 바뀜 알림 (자동 저장이 듣는 곳)
|
|
432
|
+
const listeners = [];
|
|
433
|
+
function changed(kind) { for (const f of listeners) { try { f(kind); } catch (e) { console.error(e); } } }
|
|
434
|
+
|
|
435
|
+
// 지금 작업을 기록 바이트로 (store.js가 브라우저 보관함·구글 드라이브에 씀). 데이터가 없거나 모델이 없으면 null
|
|
436
|
+
// opts.withData: 데이터를 프로젝트 파일 안에 함께 (내보내기), opts.dataCopy: 데이터 사본(data.zip)도 따로 만듦 (데이터가 바뀐 때만)
|
|
437
|
+
function recordBytes(name, opts = {}) {
|
|
438
|
+
if (!W.studio || !W.studio.data) return null;
|
|
439
|
+
const st = W.trained ? stateForPython(W.trained.net) : null;
|
|
440
|
+
try {
|
|
441
|
+
const out = { project: bytesOf(W.mod.record_project(W.studio, st, name || "", !!opts.withData)) };
|
|
442
|
+
if (opts.dataCopy) out.data = bytesOf(W.mod.data_zip(W.studio));
|
|
443
|
+
return out;
|
|
444
|
+
} catch (e) {
|
|
445
|
+
const err = pyError(e);
|
|
446
|
+
if (/저장할 모델이 없음/.test(err.message)) return null;
|
|
447
|
+
throw err;
|
|
448
|
+
} finally { if (st) st.destroy(); }
|
|
449
|
+
}
|
|
450
|
+
// 예시 데이터 파일 받기: 예시 하나에 필요한 npz만 (처음 열 때 모두 받지 않게)
|
|
451
|
+
async function ensureExample(kind) {
|
|
452
|
+
if (!kind) return;
|
|
453
|
+
for (const f of JSON.parse(W.mod.example_files_json(kind))) {
|
|
454
|
+
if (gotData.has(f)) continue;
|
|
455
|
+
const res = await fetch(BASE + "data/" + f, { cache: "no-cache" });
|
|
456
|
+
if (!res.ok) throw { message: `예시 데이터를 받지 못함: ${f}`, hint: "인터넷 연결을 확인하고 다시 누르세요" };
|
|
457
|
+
W.py.FS.writeFile(`/app/blocklearning/data/${f}`, new Uint8Array(await res.arrayBuffer()));
|
|
458
|
+
gotData.add(f);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
// 기록 바이트 → 열기 (화면용 응답). data는 없어도 됨 (예시 데이터, 또는 프로젝트 zip 안에 데이터가 있음)
|
|
462
|
+
async function openRecord(project, data) {
|
|
463
|
+
await ready;
|
|
464
|
+
W.py.FS.mkdirTree("/work");
|
|
465
|
+
W.py.FS.writeFile("/work/open.blocklearning", project);
|
|
466
|
+
if (data && data.length) W.py.FS.writeFile("/work/open.zip", data);
|
|
467
|
+
await ensureExample(W.mod.project_example("/work/open.blocklearning"));
|
|
468
|
+
return api("/api/project/open", { path: "/work/open.blocklearning", data_path: data && data.length ? "/work/open.zip" : "" });
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// ------------------------------------------------------------ api: 화면이 부르는 곳
|
|
472
|
+
async function api(path, body) {
|
|
473
|
+
await ready;
|
|
474
|
+
const method = body === undefined ? "GET" : "POST";
|
|
475
|
+
try {
|
|
476
|
+
if (path === "/api/train" && method === "POST") return startTrain(body);
|
|
477
|
+
if (path.startsWith("/api/jobs/")) return jobView(path);
|
|
478
|
+
if (path === "/api/activations") return activations(body);
|
|
479
|
+
if (path === "/api/project/export") return exportModel();
|
|
480
|
+
if (path === "/api/code/save") return codeSave(body);
|
|
481
|
+
if (path === "/api/project/save") return projectSave(body);
|
|
482
|
+
if (path === "/api/project/open") return await projectOpen(body);
|
|
483
|
+
if (path === "/api/runs/restore") return await runRestore(body);
|
|
484
|
+
if (path === "/api/predict") return await predictNew(body);
|
|
485
|
+
if (path === "/api/preview") return await preview(body);
|
|
486
|
+
if (path === "/api/anomaly/threshold") { // 이상 탐지 기준값: Python 결과와 엔진 쪽 결과 둘 다
|
|
487
|
+
const r = pyCall(method, path, body);
|
|
488
|
+
if (W.trained && W.trained.results) W.trained.results.threshold = r.threshold;
|
|
489
|
+
return r;
|
|
490
|
+
}
|
|
491
|
+
if (path.startsWith("/api/label/")) return labelCall(path.slice("/api/label/".length), body || {});
|
|
492
|
+
if (path === "/api/data/load" && body && body.label_job) return await useLabelJob(body);
|
|
493
|
+
if (path === "/api/data/load") { clearTrained(); if (body && body.example) await ensureExample(body.example); }
|
|
494
|
+
const r = pyCall(method, path, body);
|
|
495
|
+
if (method === "POST") {
|
|
496
|
+
if (path === "/api/data/load") changed("data");
|
|
497
|
+
else if (path === "/api/model/check" || path === "/api/task/select") changed("model");
|
|
498
|
+
}
|
|
499
|
+
if (path === "/api/state" && W.trained) Object.assign(r, { trained: true, trained_graph: W.trained.graph, results: W.trained.results });
|
|
500
|
+
if (path === "/api/runs/delete") changed("train");
|
|
501
|
+
return r;
|
|
502
|
+
} catch (e) {
|
|
503
|
+
if (e && e.message !== undefined && !(e instanceof Error)) throw e; // 이미 화면 오류 모양
|
|
504
|
+
throw pyError(e);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// ------------------------------------------------------------ 파일 고르기 (Pyodide 파일 시스템 /data에 씀)
|
|
509
|
+
function pick(opts) {
|
|
510
|
+
return new Promise((resolve) => {
|
|
511
|
+
const inp = document.createElement("input");
|
|
512
|
+
inp.type = "file";
|
|
513
|
+
if (opts.accept) inp.accept = opts.accept;
|
|
514
|
+
if (opts.dir) { inp.webkitdirectory = true; inp.multiple = true; }
|
|
515
|
+
inp.onchange = () => resolve(Array.from(inp.files || []));
|
|
516
|
+
inp.click();
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
async function writeFiles(files) { // → Pyodide 안의 경로 (폴더면 폴더 경로)
|
|
520
|
+
await ready;
|
|
521
|
+
const root = `/data/u${++W.n}`;
|
|
522
|
+
let top = null;
|
|
523
|
+
for (const f of files) {
|
|
524
|
+
const rel = f.webkitRelativePath || f.name;
|
|
525
|
+
const p = `${root}/${rel}`;
|
|
526
|
+
W.py.FS.mkdirTree(p.slice(0, p.lastIndexOf("/")));
|
|
527
|
+
W.py.FS.writeFile(p, new Uint8Array(await f.arrayBuffer()));
|
|
528
|
+
if (f.webkitRelativePath) top = rel.split("/")[0];
|
|
529
|
+
}
|
|
530
|
+
return top ? `${root}/${top}` : `${root}/${files[0].name}`;
|
|
531
|
+
}
|
|
532
|
+
async function pickInto(inputId, opts) {
|
|
533
|
+
const files = await pick(opts);
|
|
534
|
+
if (!files.length) return false;
|
|
535
|
+
const p = await writeFiles(files);
|
|
536
|
+
const el = document.getElementById(inputId);
|
|
537
|
+
el.dataset.path = p; // app.js의 pathVal이 읽는 실제 위치
|
|
538
|
+
el.value = opts.dir ? files[0].webkitRelativePath.split("/")[0] + ` (파일 ${files.length}개)` : files[0].name;
|
|
539
|
+
return true;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// app.js를 불러온 뒤: 경로 칸을 '고르기'로, 열기는 파일 고르기로, 라벨링 단추는 안내로
|
|
543
|
+
function afterApp() {
|
|
544
|
+
const $ = (id) => document.getElementById(id);
|
|
545
|
+
for (const id of ["csv-path", "folder-path", "series-path", "series-label-file", "predict-path", "predict-folder", "predict-series"]) {
|
|
546
|
+
const el = $(id);
|
|
547
|
+
if (!el) continue;
|
|
548
|
+
el.readOnly = true;
|
|
549
|
+
el.placeholder = id === "series-label-file" ? "정답 표 (선택) — 단추로 고르기" : "단추로 고르세요 (브라우저 안에서만 읽음)";
|
|
550
|
+
}
|
|
551
|
+
const wrapBtn = (btnId, inputId, opts, label) => {
|
|
552
|
+
const b = $(btnId);
|
|
553
|
+
if (!b) return;
|
|
554
|
+
const orig = b.onclick;
|
|
555
|
+
if (label) b.textContent = label;
|
|
556
|
+
b.onclick = async (ev) => { if (await pickInto(inputId, opts)) orig && orig.call(b, ev); };
|
|
557
|
+
};
|
|
558
|
+
const csvLoad = $("btn-csv") && $("btn-csv").onclick;
|
|
559
|
+
wrapBtn("btn-csv", "csv-path", { accept: ".csv,.tsv,.txt" }, "CSV 파일 고르기");
|
|
560
|
+
const panel = $("step-data"), dz = $("dropzone"); // CSV를 ② 데이터 화면에 끌어 놓기
|
|
561
|
+
if (panel && dz && csvLoad) {
|
|
562
|
+
dz.hidden = false;
|
|
563
|
+
panel.addEventListener("dragover", (e) => { e.preventDefault(); panel.classList.add("drag"); });
|
|
564
|
+
panel.addEventListener("dragleave", (e) => { if (!panel.contains(e.relatedTarget)) panel.classList.remove("drag"); });
|
|
565
|
+
panel.addEventListener("drop", async (e) => {
|
|
566
|
+
e.preventDefault();
|
|
567
|
+
panel.classList.remove("drag");
|
|
568
|
+
const f = Array.from((e.dataTransfer && e.dataTransfer.files) || []).find((x) => /\.(csv|tsv|txt)$/i.test(x.name));
|
|
569
|
+
if (!f) return window.showMessage && window.showMessage("CSV 파일만 끌어 놓을 수 있습니다", "이미지 폴더는 [이미지 폴더 고르기]로 고르세요");
|
|
570
|
+
const el = $("csv-path");
|
|
571
|
+
el.dataset.path = await writeFiles([f]);
|
|
572
|
+
el.value = f.name;
|
|
573
|
+
csvLoad.call($("btn-csv"));
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
wrapBtn("btn-folder", "folder-path", { dir: true }, "이미지 폴더 고르기");
|
|
577
|
+
wrapBtn("btn-predict-csv", "predict-path", { accept: ".csv,.tsv,.txt" }, "CSV 파일 고르고 예측"); // ⑤ 예측
|
|
578
|
+
wrapBtn("btn-predict-folder", "predict-folder", { dir: true }, "그림 폴더 고르고 예측");
|
|
579
|
+
wrapBtn("btn-predict-series", "predict-series", { dir: true }, "폴더 고르고 예측");
|
|
580
|
+
wrapBtn("btn-series-scan", "series-path", { dir: true }, "폴더 고르기");
|
|
581
|
+
const lf = $("series-label-file");
|
|
582
|
+
if (lf) {
|
|
583
|
+
const b = document.createElement("button");
|
|
584
|
+
b.textContent = "정답 표 고르기";
|
|
585
|
+
b.onclick = async () => { if (await pickInto("series-label-file", { accept: ".csv,.tsv,.txt" })) lf.dispatchEvent(new Event("change")); };
|
|
586
|
+
lf.after(b);
|
|
587
|
+
}
|
|
588
|
+
const dev = $("device");
|
|
589
|
+
if (dev && dev.closest("label")) dev.closest("label").hidden = true; // 웹은 브라우저가 알아서 (GPU가 있으면 WebGL)
|
|
590
|
+
const ex = $("btn-export-pt");
|
|
591
|
+
if (ex) ex.textContent = "학습한 모델 내려받기 (PyTorch 코드 + 가중치)";
|
|
592
|
+
const be = $("btn-export");
|
|
593
|
+
if (be) { be.textContent = "내려받기"; be.title = "학습한 모델을 PyTorch 코드와 가중치(.npz)로 내려받기"; }
|
|
594
|
+
document.body.classList.add("web");
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
window.DLS_WEB = { api, afterApp, ready, writeFiles, recordBytes, openRecord, pick, pickInto,
|
|
598
|
+
labelFileUrl, labelWork, labelData, labelOpen, labelOpenBundle,
|
|
599
|
+
onChange: (f) => listeners.push(f), hasData: () => !!(W.studio && W.studio.data), openedName: () => W.openedName || "",
|
|
600
|
+
download,
|
|
601
|
+
pickProject: async () => { const f = await pick({ accept: ".blocklearning,.dlstudio,.zip" }); return f.length ? writeFiles(f) : null; } };
|
|
602
|
+
})();
|