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.
Files changed (74) hide show
  1. blocklearning/__init__.py +1 -0
  2. blocklearning/__main__.py +6 -0
  3. blocklearning/analysis.py +133 -0
  4. blocklearning/anomaly.py +148 -0
  5. blocklearning/blocks.py +601 -0
  6. blocklearning/cli.py +46 -0
  7. blocklearning/codegen.py +1012 -0
  8. blocklearning/core.py +861 -0
  9. blocklearning/data/bearing_uottawa.SOURCE.txt +6 -0
  10. blocklearning/data/bearing_uottawa.npz +0 -0
  11. blocklearning/data/concrete.SOURCE.txt +4 -0
  12. blocklearning/data/concrete.npz +0 -0
  13. blocklearning/data/digits32.SOURCE.txt +4 -0
  14. blocklearning/data/digits32.npz +0 -0
  15. blocklearning/data/ecg_mitdb.SOURCE.txt +6 -0
  16. blocklearning/data/ecg_mitdb.npz +0 -0
  17. blocklearning/data/hydraulic.SOURCE.txt +6 -0
  18. blocklearning/data/hydraulic.npz +0 -0
  19. blocklearning/data/pcb_det.SOURCE.txt +6 -0
  20. blocklearning/data/pcb_det.npz +0 -0
  21. blocklearning/data/pneumatic_seg.SOURCE.txt +8 -0
  22. blocklearning/data/pneumatic_seg.npz +0 -0
  23. blocklearning/data/pneumonia28.SOURCE.txt +13 -0
  24. blocklearning/data/pneumonia28.npz +0 -0
  25. blocklearning/data/steel_plates.SOURCE.txt +5 -0
  26. blocklearning/data/steel_plates.npz +0 -0
  27. blocklearning/data/steel_power.SOURCE.txt +3 -0
  28. blocklearning/data/steel_power.npz +0 -0
  29. blocklearning/data/steelblast.SOURCE.txt +4 -0
  30. blocklearning/data/steelblast.npz +0 -0
  31. blocklearning/data.py +1158 -0
  32. blocklearning/detect.py +222 -0
  33. blocklearning/forecast.py +204 -0
  34. blocklearning/graph.py +602 -0
  35. blocklearning/jobs.py +501 -0
  36. blocklearning/labeling.py +1294 -0
  37. blocklearning/labeling_sources.py +217 -0
  38. blocklearning/layers.py +615 -0
  39. blocklearning/losses.py +199 -0
  40. blocklearning/multi.py +175 -0
  41. blocklearning/nn_extra.py +643 -0
  42. blocklearning/predict.py +344 -0
  43. blocklearning/pretrained/LICENSE-mnv3s.txt +202 -0
  44. blocklearning/pretrained/mnv3s.SOURCE.txt +6 -0
  45. blocklearning/pretrained/mnv3s.bin +0 -0
  46. blocklearning/pretrained/mnv3s.json +1 -0
  47. blocklearning/pretrained.py +56 -0
  48. blocklearning/project.py +120 -0
  49. blocklearning/segment.py +173 -0
  50. blocklearning/server.py +116 -0
  51. blocklearning/static/app.js +1986 -0
  52. blocklearning/static/boot.js +51 -0
  53. blocklearning/static/demo.jpg +0 -0
  54. blocklearning/static/demo.webm +0 -0
  55. blocklearning/static/engine.js +1326 -0
  56. blocklearning/static/graph.js +1902 -0
  57. blocklearning/static/index.html +301 -0
  58. blocklearning/static/label.html +158 -0
  59. blocklearning/static/label.js +1040 -0
  60. blocklearning/static/labels.js +227 -0
  61. blocklearning/static/projects.js +516 -0
  62. blocklearning/static/store.js +259 -0
  63. blocklearning/static/style.css +844 -0
  64. blocklearning/static/train-worker.js +41 -0
  65. blocklearning/static/web.js +602 -0
  66. blocklearning/tasks.py +351 -0
  67. blocklearning/web.py +412 -0
  68. blocklearning/weblabel.py +316 -0
  69. blocklearning-0.1.0.dist-info/METADATA +66 -0
  70. blocklearning-0.1.0.dist-info/RECORD +74 -0
  71. blocklearning-0.1.0.dist-info/WHEEL +4 -0
  72. blocklearning-0.1.0.dist-info/entry_points.txt +2 -0
  73. blocklearning-0.1.0.dist-info/licenses/LICENSE +25 -0
  74. blocklearning-0.1.0.dist-info/licenses/src/blocklearning/pretrained/LICENSE-mnv3s.txt +202 -0
@@ -0,0 +1,516 @@
1
+ // BlockLearning 웹 버전: 첫 화면 "내 프로젝트"와 자동 저장.
2
+ // 처음 열면 첫 화면에서 프로젝트를 고르거나 새로 시작한다. 작업이 바뀌면(데이터·모델·과제·학습) 잠시 뒤 지금 프로젝트에
3
+ // 저장하고, 프로젝트가 없으면 처음 바뀔 때 데이터·과제 이름으로 만든다.
4
+ // 저장 위치: 이 브라우저(로그인 없음) 또는 구글 드라이브(로그인 시, 내 드라이브/BlockLearning/<프로젝트>/). store.js 참고.
5
+ (function () {
6
+ "use strict";
7
+ const S = () => window.DLStore;
8
+ const WEBB = () => window.DLS_WEB;
9
+ const KEY = "dlstudio-current"; // 마지막으로 연 프로젝트 {kind, id, name} (첫 화면의 '이어서 하기')
10
+ const START = "dlstudio-start"; // 새로 고친 뒤 할 일 (새 프로젝트 → task, 예시로 → quick)
11
+ const SAVE_DELAY = 1500;
12
+
13
+ let cur = null, dirty = false, dataDirty = false, timer = null, saving = null, tab = "local", quietUntil = 0;
14
+
15
+ const $ = (id) => document.getElementById(id);
16
+ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
17
+ function remember() { try { if (cur) localStorage.setItem(KEY, JSON.stringify(cur)); } catch (e) { /* 기억 못 해도 됨 */ } }
18
+ function forget() { try { localStorage.removeItem(KEY); } catch (e) { /* 없음 */ } }
19
+ function recall() { try { return JSON.parse(localStorage.getItem(KEY) || "null"); } catch (e) { return null; } }
20
+ const store = (kind) => (kind === "drive" ? S().drive : S().local);
21
+ const when = (t) => { const d = new Date(t); return isNaN(d) ? "" : d.toLocaleString("ko-KR", { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" }); };
22
+ const defaultName = () => "제목 없는 프로젝트 " + new Date().toLocaleString("ko-KR", { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" });
23
+ function autoName() { // 데이터와 과제로 이름 짓기 (예: "심전도 정상·이상 · 시계열 분류 (11. 24.)")
24
+ try {
25
+ let data = "";
26
+ if (st.dataName) data = st.dataName;
27
+ else if (st.dataSrc && st.examples) {
28
+ const e = st.examples.find((x) => x[0] === st.dataSrc);
29
+ data = e ? e[1].split(" · ")[0].replace(/\s*\([^)]*\)\s*$/, "") : st.dataSrc; // "이름 (분야) · 과제" → 이름
30
+ } else {
31
+ const v = ["csv-path", "folder-path", "series-path"].map((id) => ($(id) || {}).value || "").find((x) => x);
32
+ data = (v || "").replace(/\s*\(파일 \d+개\)$/, "").replace(/\.(csv|tsv|txt)$/i, "");
33
+ }
34
+ const base = [data, st.sub ? st.sub.name : ""].filter(Boolean).join(" · ");
35
+ return base ? `${base} (${new Date().toLocaleDateString("ko-KR", { month: "numeric", day: "numeric" })})` : defaultName();
36
+ } catch (e) { return defaultName(); }
37
+ }
38
+ const AUTO_SUFFIX = / \(\d{1,2}\. \d{1,2}\.\)( \d+)?$/; // autoName·uniqueName이 붙이는 꼬리 "(11. 26.)", "(11. 26.) 2"
39
+ async function uniqueName(kind, name) { // 같은 이름이 있으면 뒤에 번호
40
+ try {
41
+ const names = new Set((await store(kind).list()).map((p) => p.name));
42
+ let n = name, k = 2;
43
+ while (names.has(n)) n = name + ' ' + k++;
44
+ return n;
45
+ } catch (e) { return name; }
46
+ }
47
+ function stepsText() { // 만들기 단계 진행: 과제·데이터·모델·학습(다시 해야 하면 stale)
48
+ const train = st.trained ? (st.trainedJson !== st.graphJson ? "stale" : true) : false;
49
+ return JSON.stringify({ task: !!st.tpl, data: !!st.summary, model: !!(st.checked && st.checked.ok), train });
50
+ }
51
+ function stepsOf(card) { // 카드에 적힌 진행 (예전 기록은 한 줄 요약에서 어림)
52
+ try { if (card.dataset.steps) return JSON.parse(card.dataset.steps); } catch (e) { /* 아래 */ }
53
+ const meta = card.dataset.meta || "";
54
+ return { task: !!meta, data: true, model: !!meta, train: /학습 \d+번/.test(meta) };
55
+ }
56
+ function paintSteps(p) { // 고른 (열지 않은) 프로젝트의 진행을 왼쪽 만들기 흐름에
57
+ const set = (name, done, stale, locked) => {
58
+ const b = document.querySelector(`.step[data-step="${name}"]`);
59
+ if (!b) return;
60
+ b.classList.toggle("done", !!done && !stale);
61
+ b.classList.toggle("stale", !!stale);
62
+ b.classList.toggle("locked", !!locked);
63
+ };
64
+ set("task", p.task);
65
+ set("data", p.data);
66
+ set("model", p.model, false, !p.data);
67
+ set("train", p.train === true, p.train === "stale", !p.data);
68
+ set("predict", false, false, !p.data || !p.train);
69
+ }
70
+ function metaText() { // 첫 화면 카드의 한 줄 요약: 과제 · 학습 횟수 · 최고 시험 성적
71
+ try {
72
+ const runs = (st.runs || []).filter((r) => r.data_ok);
73
+ const best = runs.reduce((a, r) => (r.results.test_metric !== null && r.results.test_metric !== undefined &&
74
+ (!a || r.results.test_metric > a.results.test_metric) ? r : a), null);
75
+ const name = best && best.results.metric_name;
76
+ const score = !best ? "아직 학습 안 함" : name === "r2" ? `최고 R² ${best.results.test_metric.toFixed(3)}`
77
+ : name === "mean" ? `최고 평균 ${best.results.test_metric.toFixed(3)}`
78
+ : name === "auc" ? `최고 AUC ${best.results.test_metric.toFixed(3)}` : name === "recon" ? "학습함 (정상만)"
79
+ : `최고 시험 ${name === "map50" ? "mAP@0.5" : "정확도"} ${(best.results.test_metric * 100).toFixed(1)}%`;
80
+ return [st.sub ? st.sub.name : "", runs.length ? `학습 ${runs.length}번` : "", score].filter(Boolean).join(" · ");
81
+ } catch (e) { return ""; }
82
+ }
83
+
84
+ // ------------------------------------------------------------ 머리의 프로젝트 단추와 저장 상태
85
+ function status(text, bad = false) {
86
+ const el = $("proj-status");
87
+ if (el) {
88
+ el.textContent = text;
89
+ el.classList.toggle("bad", bad);
90
+ el.title = cur ? `작업이 바뀌면 '${cur.name}'에 자동으로 저장합니다 (${store(cur.kind).label})` : "데이터를 불러오면 자동으로 저장을 시작합니다";
91
+ }
92
+ }
93
+ function showCurrent() {
94
+ const b = $("btn-projects");
95
+ const named = cur && st.step !== "home"; // 홈에서는 '열린 프로젝트'를 따로 보이지 않음
96
+ if (b) b.textContent = named ? cur.name : "내 프로젝트";
97
+ if (b) b.title = named ? `${cur.name} — ${store(cur.kind).label}에 저장 (누르면 첫 화면)` : "첫 화면: 프로젝트 목록";
98
+ }
99
+
100
+ // ------------------------------------------------------------ 자동 저장
101
+ function onChange(kind) {
102
+ if (kind === "model" && Date.now() < quietUntil) return; // 연 직후 화면이 다시 검사하는 것은 바뀜이 아님
103
+ dirty = true;
104
+ if (kind === "data") dataDirty = true;
105
+ clearTimeout(timer);
106
+ timer = setTimeout(saveNow, SAVE_DELAY);
107
+ status("저장 기다리는 중…");
108
+ }
109
+ async function saveNow() {
110
+ if (saving) { await saving; }
111
+ if (!dirty) return;
112
+ let wantData = false;
113
+ saving = (async () => {
114
+ try {
115
+ if (!WEBB().hasData()) { status(""); dirty = false; return; } // 데이터가 없으면 저장할 것이 없음
116
+ wantData = dataDirty || !cur;
117
+ dirty = false;
118
+ const kind = cur ? cur.kind : S().drive.available() && S().drive.signedIn() ? "drive" : "local";
119
+ if (cur && wantData && AUTO_SUFFIX.test(cur.name)) { // 지어 준 이름 그대로면 (사용자가 안 바꿨으면) 데이터가 바뀔 때 이름도 따라
120
+ const next = autoName();
121
+ if (next.replace(AUTO_SUFFIX, "") !== cur.name.replace(AUTO_SUFFIX, "")) {
122
+ const nn = await uniqueName(cur.kind, next);
123
+ await store(cur.kind).rename(cur.id, nn);
124
+ cur.name = nn;
125
+ remember(); showCurrent();
126
+ }
127
+ }
128
+ const name = cur ? cur.name : await uniqueName(kind, autoName());
129
+ const rec = WEBB().recordBytes(name, { dataCopy: wantData });
130
+ if (!rec) { status(""); return; } // 아직 모델이 없음: 데이터 사본은 다음 저장 때 (표시를 지우지 않음)
131
+ status("저장 중…");
132
+ if (!cur) { // 처음 저장할 수 있을 때 프로젝트를 만듦 (빈 프로젝트가 생기지 않게)
133
+ const p = await store(kind).create(name);
134
+ cur = { kind, id: p.id, name: p.name };
135
+ remember(); showCurrent();
136
+ }
137
+ await store(cur.kind).save(cur.id, Object.assign(wantData ? rec : { project: rec.project }, { meta: metaText(), steps: stepsText() }));
138
+ if (wantData) dataDirty = false;
139
+ status("자동 저장됨 " + new Date().toLocaleTimeString("ko-KR", { hour: "2-digit", minute: "2-digit" }));
140
+ } catch (e) {
141
+ dirty = true;
142
+ if (wantData) dataDirty = true;
143
+ if (e && /데이터/.test(String(e.message)) && !cur) { status(""); return; }
144
+ status(e.needLogin ? "저장 안 됨: 구글 로그인 필요" : "저장 안 됨: " + (e.message || e), true);
145
+ }
146
+ })();
147
+ await saving;
148
+ saving = null;
149
+ }
150
+
151
+ // ------------------------------------------------------------ 열기·새로 만들기·가져오기·내보내기
152
+ async function openProject(kind, p) {
153
+ if (cur && cur.id === p.id && WEBB().hasData()) return go(st.trained ? "train" : "model"); // 이미 연 프로젝트
154
+ await saveNow();
155
+ status("여는 중…");
156
+ try {
157
+ const rec = await store(kind).load(p.id);
158
+ if (!rec || !rec.project) {
159
+ cur = { kind, id: p.id, name: p.name };
160
+ remember(); showCurrent();
161
+ status("아직 저장된 내용이 없음");
162
+ return go("task");
163
+ }
164
+ const r = await WEBB().openRecord(rec.project, rec.data);
165
+ cur = { kind, id: p.id, name: p.name };
166
+ remember(); showCurrent();
167
+ quietUntil = Date.now() + 3000;
168
+ applyOpened(r); // app.js
169
+ dirty = false; dataDirty = false;
170
+ if (r.notice) onChange("train"); // 예시 데이터가 바뀌어 학습 결과를 비웠으면 그 상태를 저장 (카드 요약·진행도)
171
+ status("열었음");
172
+ showMessage(`'${p.name}'을(를) 열었음`, r.notice || "", "", true);
173
+ } catch (e) { status("열지 못함", true); showError(e.message !== undefined ? e : { message: String(e) }); }
174
+ }
175
+ async function startFresh(then) { // 새 프로젝트: 지금 작업이 있으면 저장하고 깨끗한 화면으로 (새로 고침)
176
+ await saveNow();
177
+ cur = null;
178
+ if (WEBB().hasData()) {
179
+ try { sessionStorage.setItem(START, then); } catch (e) { /* 없음 */ }
180
+ forget();
181
+ location.reload();
182
+ return;
183
+ }
184
+ showCurrent();
185
+ status("");
186
+ afterStart(then);
187
+ }
188
+ async function afterStart() {
189
+ go("task");
190
+ }
191
+ async function importFile() {
192
+ const path = await WEBB().pickProject();
193
+ if (!path) return;
194
+ try {
195
+ await saveNow();
196
+ const r = await WEBB().api("/api/project/open", { path });
197
+ const kind = tab === "drive" && S().drive.signedIn() ? "drive" : "local";
198
+ const name = WEBB().openedName() || path.split("/").pop().replace(/\.(blocklearning|dlstudio)$/i, "");
199
+ const p = await store(kind).create(name);
200
+ cur = { kind, id: p.id, name: p.name };
201
+ remember(); showCurrent();
202
+ applyOpened(r);
203
+ dirty = true; dataDirty = true;
204
+ await saveNow();
205
+ showMessage(`가져왔음: '${name}' (${store(kind).label}에 저장)`, "", "", true);
206
+ } catch (e) { showError(e.message !== undefined ? e : { message: String(e) }); }
207
+ }
208
+ function exportFile() {
209
+ try {
210
+ const rec = WEBB().recordBytes(cur ? cur.name : "", { withData: true });
211
+ if (!rec) return showMessage("내보낼 것이 없음", "프로젝트를 열거나 데이터와 모델을 먼저 만드세요");
212
+ const name = (cur ? cur.name : "blocklearning-project").replace(/[\\/:*?"<>|]/g, "_") + ".blocklearning";
213
+ WEBB().download(name, rec.project);
214
+ showMessage(`내려받았음: ${name}`, "데이터 사본·학습 기록까지 들어 있어, 다른 PC의 BlockLearning에서 [파일 가져오기]로 그대로 열 수 있습니다", "", true);
215
+ } catch (e) { showError(e); }
216
+ }
217
+
218
+ // ------------------------------------------------------------ 첫 화면 "내 프로젝트"
219
+ const svgI = (d) => `<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${d}</svg>`;
220
+ const ICON = {
221
+ blocks: svgI('<rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="8.5" y="14" width="7" height="7" rx="1.5"/><path d="M6.5 10v2h11v-2M12 12v2"/>'),
222
+ chip: svgI('<rect x="6" y="6" width="12" height="12" rx="2"/><path d="M9 2v4M15 2v4M9 18v4M15 18v4M2 9h4M2 15h4M18 9h4M18 15h4"/>'),
223
+ chart: svgI('<path d="M3 3v18h18"/><path d="m7 15 4-4 3 3 5-6"/>'),
224
+ code: svgI('<path d="m8 8-4 4 4 4M16 8l4 4-4 4M14 5l-4 14"/>'),
225
+ folder: svgI('<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>'),
226
+ pen: svgI('<path d="M4 20h4L19 9l-4-4L4 16z"/><path d="m13.5 6.5 4 4"/>'),
227
+ trash: svgI('<path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13"/>'),
228
+ };
229
+ // 첫 화면 그림: 데이터 → 이어 붙인 블록(모델) → 결과. 점이 흘러감 (움직임을 줄이는 설정이면 멈춤)
230
+ const HERO_ART = `<svg viewBox="0 0 360 260" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
231
+ <defs>
232
+ <linearGradient id="ha-bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#eef2ff"/><stop offset="1" stop-color="#f5f3ff"/></linearGradient>
233
+ <linearGradient id="ha-ring" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#4f46e5"/><stop offset="1" stop-color="#7c3aed"/></linearGradient>
234
+ <pattern id="ha-dots" width="14" height="14" patternUnits="userSpaceOnUse"><circle cx="1.5" cy="1.5" r="1" fill="#c7d2fe" opacity=".55"/></pattern>
235
+ <filter id="ha-sh" x="-20%" y="-20%" width="140%" height="150%"><feDropShadow dx="0" dy="3" stdDeviation="4" flood-color="#312e81" flood-opacity=".10"/></filter>
236
+ <path id="ha-flow" d="M98 130 C118 130 118 58 140 58 L180 58 L180 202 L220 202 C236 202 236 130 252 130"/>
237
+ </defs>
238
+ <rect width="360" height="260" rx="18" fill="url(#ha-bg)"/>
239
+ <rect width="360" height="260" rx="18" fill="url(#ha-dots)"/>
240
+
241
+ <!-- 이어 주는 선 -->
242
+ <path d="M98 130 C118 130 118 58 140 58" fill="none" stroke="#a5b4fc" stroke-width="2" stroke-dasharray="4 5"/>
243
+ <path d="M220 202 C236 202 236 130 252 130" fill="none" stroke="#a5b4fc" stroke-width="2" stroke-dasharray="4 5"/>
244
+
245
+ <!-- 데이터: 그림 조각 + 신호 -->
246
+ <g filter="url(#ha-sh)">
247
+ <rect x="18" y="66" width="80" height="128" rx="14" fill="#fff"/>
248
+ </g>
249
+ <g transform="translate(31 80)">
250
+ <rect width="11" height="11" rx="2" fill="#c7d2fe"/><rect x="13" width="11" height="11" rx="2" fill="#818cf8"/><rect x="26" width="11" height="11" rx="2" fill="#e0e7ff"/><rect x="39" width="11" height="11" rx="2" fill="#a5b4fc"/>
251
+ <rect y="13" width="11" height="11" rx="2" fill="#818cf8"/><rect x="13" y="13" width="11" height="11" rx="2" fill="#4f46e5"/><rect x="26" y="13" width="11" height="11" rx="2" fill="#a5b4fc"/><rect x="39" y="13" width="11" height="11" rx="2" fill="#e0e7ff"/>
252
+ <rect y="26" width="11" height="11" rx="2" fill="#e0e7ff"/><rect x="13" y="26" width="11" height="11" rx="2" fill="#a5b4fc"/><rect x="26" y="26" width="11" height="11" rx="2" fill="#6366f1"/><rect x="39" y="26" width="11" height="11" rx="2" fill="#c7d2fe"/>
253
+ </g>
254
+ <path d="M30 152 q6 -14 12 0 t12 0 t12 0 t12 -2" fill="none" stroke="#14b8a6" stroke-width="2.4" stroke-linecap="round"/>
255
+ <path d="M30 174 q6 -9 12 0 t12 0 t12 0 t12 0" fill="none" stroke="#f59e0b" stroke-width="2.4" stroke-linecap="round" opacity=".85"/>
256
+
257
+ <!-- 흐르는 데이터 (블록 뒤로 지나감) -->
258
+ <g fill="#4f46e5">
259
+ <circle r="3.5" opacity=".9"><animateMotion dur="3.6s" repeatCount="indefinite" calcMode="linear"><mpath href="#ha-flow"/></animateMotion></circle>
260
+ <circle r="3" fill="#14b8a6" opacity=".9"><animateMotion dur="3.6s" begin="-1.2s" repeatCount="indefinite" calcMode="linear"><mpath href="#ha-flow"/></animateMotion></circle>
261
+ <circle r="3" fill="#f97316" opacity=".9"><animateMotion dur="3.6s" begin="-2.4s" repeatCount="indefinite" calcMode="linear"><mpath href="#ha-flow"/></animateMotion></circle>
262
+ </g>
263
+
264
+ <!-- 모델: 이어 붙인 블록 -->
265
+ <g filter="url(#ha-sh)">
266
+ <rect x="140" y="40" width="80" height="36" rx="10" fill="#fff"/>
267
+ <rect x="140" y="88" width="80" height="36" rx="10" fill="#fff"/>
268
+ <rect x="140" y="136" width="80" height="36" rx="10" fill="#fff"/>
269
+ <rect x="140" y="184" width="80" height="36" rx="10" fill="#fff"/>
270
+ </g>
271
+ <g>
272
+ <rect x="140" y="40" width="80" height="36" rx="10" fill="#ccfbf1" stroke="#14b8a6" stroke-width="1.5"/>
273
+ <rect x="140" y="88" width="80" height="36" rx="10" fill="#dbeafe" stroke="#3b82f6" stroke-width="1.5"/>
274
+ <rect x="140" y="136" width="80" height="36" rx="10" fill="#ede9fe" stroke="#8b5cf6" stroke-width="1.5"/>
275
+ <rect x="140" y="184" width="80" height="36" rx="10" fill="#ffedd5" stroke="#f97316" stroke-width="1.5"/>
276
+ <g fill="#fff" opacity=".9">
277
+ <rect x="152" y="52" width="40" height="5" rx="2.5"/><rect x="152" y="61" width="26" height="5" rx="2.5"/>
278
+ <rect x="152" y="100" width="34" height="5" rx="2.5"/><rect x="152" y="109" width="44" height="5" rx="2.5"/>
279
+ <rect x="152" y="148" width="44" height="5" rx="2.5"/><rect x="152" y="157" width="22" height="5" rx="2.5"/>
280
+ <rect x="152" y="196" width="30" height="5" rx="2.5"/><rect x="152" y="205" width="40" height="5" rx="2.5"/>
281
+ </g>
282
+ <g stroke-width="2" fill="#fff">
283
+ <circle cx="180" cy="82" r="4" stroke="#3b82f6"/><circle cx="180" cy="130" r="4" stroke="#8b5cf6"/><circle cx="180" cy="178" r="4" stroke="#f97316"/>
284
+ </g>
285
+ </g>
286
+
287
+ <!-- 결과: 다 됨 + 오르는 곡선 -->
288
+ <g filter="url(#ha-sh)">
289
+ <rect x="252" y="66" width="90" height="128" rx="14" fill="#fff"/>
290
+ </g>
291
+ <circle cx="297" cy="112" r="26" fill="none" stroke="#eef2ff" stroke-width="7"/>
292
+ <circle cx="297" cy="112" r="26" fill="none" stroke="url(#ha-ring)" stroke-width="7" stroke-linecap="round"
293
+ stroke-dasharray="163.4" stroke-dashoffset="18" transform="rotate(-90 297 112)">
294
+ <animate attributeName="stroke-dashoffset" values="163.4;18;18" keyTimes="0;.45;1" dur="5s" repeatCount="indefinite"/>
295
+ </circle>
296
+ <path d="M286 112 l7 7 l13 -14" fill="none" stroke="#4f46e5" stroke-width="3.2" stroke-linecap="round" stroke-linejoin="round"/>
297
+ <path d="M266 178 C278 176 284 166 294 162 S314 152 328 150" fill="none" stroke="#4f46e5" stroke-width="2.4" stroke-linecap="round"/>
298
+ <path d="M266 178 C278 176 284 166 294 162 S314 152 328 150 L328 182 L266 182 Z" fill="#4f46e5" opacity=".08"/>
299
+
300
+ </svg>`;
301
+ function ensureHome() {
302
+ if ($("step-home")) return;
303
+ const sec = document.createElement("section");
304
+ sec.id = "step-home";
305
+ sec.className = "panel";
306
+ sec.hidden = true;
307
+ sec.innerHTML = `
308
+ <div class="hero">
309
+ <div class="hero-text">
310
+ <div class="eyebrow">설치 없이 · 브라우저 안에서 · 무료</div>
311
+ <h1>블록을 이어 붙여<br>딥러닝 모델을 만드세요</h1>
312
+ <p>데이터를 넣고, 블록으로 모델을 짜고, 바로 학습해 결과를 봅니다. 코드를 몰라도 되고, 데이터는 이 PC 밖으로 나가지 않습니다.</p>
313
+ <div class="hero-cta">
314
+ <button class="primary lg" id="home-new">+ 새 프로젝트</button>
315
+ <button class="lg" id="home-video">▶ 사용 영상</button>
316
+ </div>
317
+ </div>
318
+ <div class="hero-art" aria-hidden="true">${HERO_ART}</div>
319
+ </div>
320
+ <div class="features">
321
+ <div class="feature"><span class="fi">${ICON.blocks}</span><b>블록으로 모델</b><span>CNN·RNN·ResNet을 끌어다 놓고 선으로 이어 만듭니다</span></div>
322
+ <div class="feature"><span class="fi">${ICON.chip}</span><b>브라우저에서 학습</b><span>설치·서버 없이 이 브라우저 안에서 바로 학습합니다</span></div>
323
+ <div class="feature"><span class="fi">${ICON.chart}</span><b>결과를 쉬운 말로</b><span>정확도·틀린 샘플·학습 기록을 보고 다음 할 일을 알려 줍니다</span></div>
324
+ <div class="feature"><span class="fi">${ICON.code}</span><b>PyTorch 코드로</b><span>만든 모델을 PyTorch·TensorFlow 코드와 가중치로 받습니다</span></div>
325
+ </div>
326
+ <div class="home-projects">
327
+ <div class="sec-head">
328
+ <h2>내 프로젝트</h2>
329
+ <div class="tabs home-tabs"><button class="tab" data-kind="local">이 브라우저</button><button class="tab" data-kind="drive">구글 드라이브</button></div>
330
+ <span class="grow"></span>
331
+ <button id="home-import">파일 가져오기</button>
332
+ <button id="home-export" hidden>지금 프로젝트 내려받기</button>
333
+ </div>
334
+ <div id="home-where" class="proj-where"></div>
335
+ <div id="home-list" class="proj-cards"></div>
336
+ </div>
337
+ <p class="muted use-note">교육·실험용 도구입니다. 학습 결과를 의료 진단이나 제조 판정 같은 실제 결정에 그대로 쓰지 마세요. <a href="privacy.html" target="_blank" rel="noopener">개인정보처리방침</a></p>`;
338
+ document.querySelector("main").prepend(sec);
339
+ try { // 움직임을 줄이는 설정이면 그림을 멈춤
340
+ if (matchMedia("(prefers-reduced-motion: reduce)").matches) {
341
+ sec.querySelectorAll(".hero-art animate").forEach((a) => a.remove());
342
+ sec.querySelectorAll(".hero-art animateMotion").forEach((a) => a.parentNode.remove()); // 흐르는 점은 뺌
343
+ }
344
+ } catch (e) { /* 없음 */ }
345
+ sec.querySelectorAll(".tab").forEach((b) => (b.onclick = () => { tab = b.dataset.kind; render(); }));
346
+ $("home-new").onclick = () => startFresh("task");
347
+ $("home-video").onclick = openVideo;
348
+ $("home-import").onclick = importFile;
349
+ $("home-export").onclick = exportFile;
350
+ $("home-list").onclick = async (e) => {
351
+ const card = e.target.closest("[data-id]");
352
+ if (!card) return;
353
+ const b = e.target.closest("button[data-a]");
354
+ const kind = tab, item = { id: card.dataset.id, name: card.dataset.name };
355
+ try {
356
+ if (!b && selId !== item.id) return selectCard(item.id); // 처음 누르면 고르기만, 한 번 더 누르면 열기
357
+ if (!b || b.dataset.a === "open") return openProject(kind, item);
358
+ if (b.dataset.a === "rename") {
359
+ const name = prompt("새 이름", item.name);
360
+ if (!name || name.trim() === item.name) return;
361
+ await store(kind).rename(item.id, name.trim());
362
+ if (cur && cur.id === item.id) { cur.name = name.trim(); remember(); showCurrent(); onChange("model"); }
363
+ return render();
364
+ }
365
+ if (b.dataset.a === "remove") {
366
+ const where = kind === "drive" ? "구글 드라이브 휴지통으로 옮깁니다 (드라이브에서 되살릴 수 있음)" : "이 브라우저에서 지웁니다. 되살릴 수 없습니다";
367
+ if (!confirm(`'${item.name}'을(를) 지울까요? ${where}.`)) return;
368
+ await store(kind).remove(item.id);
369
+ const last = recall();
370
+ if (last && last.id === item.id) forget();
371
+ if (cur && cur.id === item.id) { cur = null; showCurrent(); status(""); }
372
+ return render();
373
+ }
374
+ } catch (err) { showError(err.message !== undefined ? err : { message: String(err) }); }
375
+ };
376
+ }
377
+ // 사용 영상 창: 누를 때만 받아 재생, 닫으면 멈춤
378
+ function openVideo() {
379
+ let d = $("video-dialog");
380
+ if (!d) {
381
+ d = document.createElement("div");
382
+ d.id = "video-dialog";
383
+ d.className = "dialog";
384
+ d.innerHTML = `<div class="dialog-box video-box" role="dialog" aria-label="사용 영상">
385
+ <div class="dialog-head"><b>사용 영상</b><button class="x" aria-label="닫기">×</button></div>
386
+ <video src="src/blocklearning/static/demo.webm" poster="src/blocklearning/static/demo.jpg" controls muted playsinline></video></div>`;
387
+ document.body.appendChild(d);
388
+ const close = () => { d.hidden = true; d.querySelector("video").pause(); };
389
+ d.querySelector(".x").onclick = close;
390
+ d.onclick = (e) => { if (e.target === d) close(); };
391
+ document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !d.hidden) close(); });
392
+ }
393
+ d.hidden = false;
394
+ d.querySelector("video").play().catch(() => {});
395
+ }
396
+ async function render() {
397
+ ensureHome();
398
+ document.querySelectorAll("#step-home .tab").forEach((b) => b.classList.toggle("active", b.dataset.kind === tab));
399
+ $("home-export").hidden = !WEBB().hasData();
400
+ const where = $("home-where"), list = $("home-list"), last = recall();
401
+ list.innerHTML = "";
402
+ if (tab === "drive") {
403
+ const dv = S().drive;
404
+ if (!dv.available()) {
405
+ where.innerHTML = `<p class="muted">구글 드라이브 저장은 준비 중입니다. 지금은 '이 브라우저'에 저장됩니다.</p>`;
406
+ return;
407
+ }
408
+ if (!dv.signedIn()) {
409
+ where.innerHTML = `<p>구글 계정으로 로그인하면 <b>내 드라이브/BlockLearning/</b> 아래 프로젝트마다 폴더를 만들어 저장합니다. 다른 PC에서도 같은 계정으로 이어서 할 수 있습니다.</p>
410
+ <p class="muted">권한은 "BlockLearning이 만든 파일만"(drive.file)입니다. 다른 드라이브 파일·메일·계정 정보는 볼 수 없습니다. 데이터 사본이 본인 드라이브에 올라가니, 회사·의료 데이터는 규정을 확인하세요.</p>
411
+ <button class="primary" id="proj-login">구글로 로그인</button> <a href="privacy.html" target="_blank" rel="noopener">개인정보처리방침</a>`;
412
+ $("proj-login").onclick = async () => {
413
+ try { await dv.signIn(""); render(); if (dirty) saveNow(); }
414
+ catch (e) { showError({ message: e.message }); }
415
+ };
416
+ return;
417
+ }
418
+ where.innerHTML = `<p class="muted">구글 드라이브에 연결됨 (내 드라이브/BlockLearning/). 1시간이 지나면 다시 로그인을 묻습니다. <button id="proj-logout">로그아웃</button></p>`;
419
+ $("proj-logout").onclick = () => { dv.signOut(); render(); };
420
+ } else {
421
+ where.innerHTML = `<p class="muted">이 브라우저에 저장됩니다. 사이트 데이터를 지우면 사라지니 [내려받기]나 구글 드라이브로 보관하세요.</p>`;
422
+ }
423
+ list.innerHTML = `<p class="muted">불러오는 중…</p>`;
424
+ try {
425
+ const items = await store(tab).list();
426
+ list.innerHTML = items.length ? items.map((p) => {
427
+ const recent = last && last.id === p.id;
428
+ return `<div class="proj-card${selId === p.id ? " sel" : ""}" data-id="${esc(p.id)}" data-name="${esc(p.name)}" data-meta="${esc(p.meta || "")}" data-steps="${esc(p.steps || "")}">
429
+ <div class="pc-top"><span class="pc-icon">${esc((p.name || "?").trim().charAt(0))}</span>
430
+ ${recent ? '<span class="badge">최근</span>' : ""}</div>
431
+ <div class="pn">${esc(p.name)}</div>
432
+ <div class="pm">${esc(p.meta || "아직 학습 안 함")}</div>
433
+ <div class="pc-foot"><span class="pt">${esc(when(p.updated))} 저장</span>
434
+ <span class="pa"><button data-a="rename" class="ghost icon" title="이름 바꾸기" aria-label="이름 바꾸기">${ICON.pen}</button><button data-a="remove" class="ghost danger icon" title="지우기" aria-label="지우기">${ICON.trash}</button></span></div></div>`;
435
+ }).join("") : `<div class="empty"><span class="fi">${ICON.folder}</span><b>아직 프로젝트가 없습니다</b>
436
+ <span>데이터를 넣으면 자동으로 저장됩니다.</span></div>`;
437
+ } catch (e) { list.innerHTML = `<p class="bad">${esc(e.message || e)}</p>`; }
438
+ }
439
+ // 프로젝트 카드 고르기: 처음 누르면 고르기만 (테두리), 같은 카드를 한 번 더 누르면 열기, 빈 곳을 누르면 고르기 풀기
440
+ let selId = null;
441
+ function selectCard(id) {
442
+ selId = id;
443
+ document.querySelectorAll("#home-list .proj-card").forEach((c) => c.classList.toggle("sel", c.dataset.id === id));
444
+ const card = id && document.querySelector(`#home-list .proj-card[data-id="${CSS.escape(id)}"]`);
445
+ if (card && !(cur && cur.id === id)) paintSteps(stepsOf(card)); // 열지 않은 프로젝트: 저장해 둔 진행
446
+ else markSteps(); // 지금 연 프로젝트 (또는 고르지 않음): 지금 상태
447
+ showSteps();
448
+ }
449
+ // 왼쪽 '만들기' 흐름(과제~예측): 내 프로젝트 화면에서는 프로젝트를 골랐을 때만, 다른 단계에서는 늘
450
+ function showSteps() {
451
+ showCurrent();
452
+ if (st.step !== "home") markSteps(); // 홈에서 고른 카드의 진행으로 칠한 것은 단계로 가면 지금 상태로 되돌림
453
+ const show = st.step !== "home" || !!selId;
454
+ document.querySelectorAll("#steps .nav-label, #steps .step:not(.home-step)").forEach((el) => (el.style.display = show ? "" : "none"));
455
+ }
456
+ // 고른 프로젝트가 지금 연 것과 다르면, 만들기 단계를 누를 때 그 프로젝트를 먼저 열고 그 단계로
457
+ document.addEventListener("click", async (e) => {
458
+ const b = e.target.closest("#steps .step:not(.home-step)");
459
+ if (!b || st.step !== "home" || !selId || (cur && cur.id === selId)) return;
460
+ const card = document.querySelector(`#home-list .proj-card[data-id="${CSS.escape(selId)}"]`);
461
+ if (!card) return;
462
+ e.stopImmediatePropagation();
463
+ e.preventDefault();
464
+ await openProject(tab, { id: card.dataset.id, name: card.dataset.name });
465
+ if (cur && cur.id === card.dataset.id) go(b.dataset.step);
466
+ }, true);
467
+ document.addEventListener("click", (e) => {
468
+ if (selId && !e.target.closest("#home-list .proj-card")) selectCard(null);
469
+ });
470
+ function home(fromHistory = false) {
471
+ ensureHome();
472
+ if (cur) tab = cur.kind;
473
+ selId = null; // 홈: 아무것도 고르지 않은 채 (작업하던 프로젝트는 메모리에 남아 다시 열면 바로)
474
+ go("home", fromHistory === true); // 단추로 부르면 이벤트가 들어오므로 true일 때만
475
+ render();
476
+ }
477
+
478
+ // ------------------------------------------------------------ 시작
479
+ async function init() {
480
+ for (const id of ["btn-open", "btn-save"]) if ($(id)) $(id).hidden = true; // 웹은 첫 화면 '내 프로젝트'로
481
+ const box = document.createElement("div"); // 사이드바 위: 지금 프로젝트 (누르면 첫 화면)
482
+ box.className = "proj-switch";
483
+ box.innerHTML = `<div class="ps-label">프로젝트</div><button id="btn-projects" class="proj-btn"></button><span id="proj-status" class="proj-status"></span>`;
484
+ document.querySelector(".brand").after(box);
485
+ const b = $("btn-projects");
486
+ b.onclick = home;
487
+ const nav = $("steps"), hb = document.createElement("button"); // 단계 줄 맨 앞: 첫 화면
488
+ hb.className = "step home-step";
489
+ hb.dataset.step = "home";
490
+ hb.innerHTML = `<span class="n"><svg viewBox="0 0 20 20" width="15" height="15" aria-hidden="true"><path d="M3 9.5 10 3.5l7 6V17H12.5v-4.5h-5V17H3z" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/></svg></span><span class="sl">내 프로젝트<small>열기·새로 만들기</small></span>`;
491
+ hb.onclick = home;
492
+ nav.prepend(hb);
493
+ document.querySelector(".brand").onclick = home;
494
+ ensureHome();
495
+ showCurrent();
496
+ WEBB().onChange(onChange);
497
+ window.addEventListener("beforeunload", (e) => { if (dirty) { saveNow(); e.preventDefault(); e.returnValue = ""; } });
498
+ let then = "";
499
+ try { then = sessionStorage.getItem(START) || ""; sessionStorage.removeItem(START); } catch (e) { /* 없음 */ }
500
+ if (then) { await WEBB().ready; afterStart(then); return; }
501
+ const job = new URLSearchParams(location.search).get("label"); // 라벨링 페이지 [studio에서 쓰기]: 새 프로젝트로 그 정답을 불러옴
502
+ if (job) {
503
+ history.replaceState(null, "", location.pathname);
504
+ await WEBB().ready;
505
+ for (let i = 0; i < 80 && !(st.catalog && st.catalog.length); i++) await new Promise((r) => setTimeout(r, 250));
506
+ go("data");
507
+ await loadData(Object.assign(dataOptions(), { label_job: job }));
508
+ return;
509
+ }
510
+ const last = recall();
511
+ tab = last ? last.kind : "local";
512
+ home();
513
+ }
514
+
515
+ window.DLProjects = { init, saveNow, current: () => cur, home, startNew: startFresh, showSteps };
516
+ })();