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,259 @@
1
+ // BlockLearning 웹 버전의 프로젝트 저장소. 두 가지가 같은 모양으로 쓰인다:
2
+ // local — 이 브라우저 안 보관함(IndexedDB). 로그인 없음, 이 PC·이 브라우저에만
3
+ // drive — 사용자 본인의 구글 드라이브 "BlockLearning" 폴더 아래 프로젝트마다 하위 폴더
4
+ // 프로젝트 = project.dlstudio(그래프·설정·결과·가중치, 자주 저장) + data.zip(고른 데이터 사본, 데이터를 바꿀 때만)
5
+ // 모양: list() → [{id, name, updated}] · create(name) → {id, name} · save(id, {project, data?}) · load(id) → {project, data}
6
+ // rename(id, name) · remove(id)
7
+ (function () {
8
+ "use strict";
9
+
10
+ // 구글 클라우드 콘솔에서 만든 OAuth 클라이언트 ID (공개돼도 되는 값, 비밀번호 아님). 비어 있으면 드라이브는 '준비 중'
11
+ const GOOGLE_CLIENT_ID = "159159621123-6hakqofb5e8o68dt3olbiucbl3q4qsq1.apps.googleusercontent.com";
12
+ // 이 앱이 만든 파일만 보는 권한. 사용자의 다른 드라이브 파일·Gmail·계정에는 닿지 않음 (넓히지 말 것)
13
+ const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive.file";
14
+ const ROOT_NAME = "BlockLearning";
15
+ const OLD_ROOT_NAME = "DL studio"; // 예전 이름: 처음 로그인할 때 이 폴더를 새 이름으로 바꿈 (안의 프로젝트는 그대로)
16
+ const FOLDER = "application/vnd.google-apps.folder";
17
+
18
+ // ------------------------------------------------------------ 이 브라우저 (IndexedDB)
19
+ function idb() {
20
+ return new Promise((ok, no) => {
21
+ const r = indexedDB.open("dlstudio", 2); // 2: 라벨링 작업(labels) 더함
22
+ r.onupgradeneeded = () => {
23
+ const db = r.result, has = (n) => db.objectStoreNames.contains(n);
24
+ if (!has("projects")) db.createObjectStore("projects", { keyPath: "id" });
25
+ if (!has("blobs")) db.createObjectStore("blobs");
26
+ if (!has("labels")) db.createObjectStore("labels", { keyPath: "id" });
27
+ };
28
+ r.onsuccess = () => ok(r.result);
29
+ r.onerror = () => no(r.error || new Error("브라우저 보관함을 열 수 없음"));
30
+ });
31
+ }
32
+ async function tx(stores, mode, fn) {
33
+ const db = await idb();
34
+ return new Promise((ok, no) => {
35
+ const t = db.transaction(stores, mode);
36
+ let out;
37
+ Promise.resolve(fn(t)).then((v) => { out = v; });
38
+ t.oncomplete = () => { db.close(); ok(out); };
39
+ t.onerror = () => { db.close(); no(t.error); };
40
+ t.onabort = () => { db.close(); no(t.error || new Error("저장이 취소됨 (보관함 용량이 모자랄 수 있음)")); };
41
+ });
42
+ }
43
+ const req = (r) => new Promise((ok, no) => { r.onsuccess = () => ok(r.result); r.onerror = () => no(r.error); });
44
+
45
+ const local = {
46
+ kind: "local",
47
+ label: "이 브라우저",
48
+ available: () => typeof indexedDB !== "undefined",
49
+ async list() {
50
+ const all = await tx(["projects"], "readonly", (t) => req(t.objectStore("projects").getAll()));
51
+ return all.sort((a, b) => b.updated - a.updated);
52
+ },
53
+ async create(name) {
54
+ const p = { id: "p" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), name, updated: Date.now() };
55
+ await tx(["projects"], "readwrite", (t) => t.objectStore("projects").put(p));
56
+ return p;
57
+ },
58
+ async save(id, { project, data, meta, steps }) {
59
+ await tx(["projects", "blobs"], "readwrite", async (t) => {
60
+ const ps = t.objectStore("projects");
61
+ const p = await req(ps.get(id));
62
+ if (!p) throw new Error("프로젝트가 없음");
63
+ p.updated = Date.now();
64
+ if (meta !== undefined) p.meta = meta;
65
+ if (steps !== undefined) p.steps = steps; // 만들기 단계 진행 (첫 화면에서 고른 카드의 진행 표시)
66
+ ps.put(p);
67
+ t.objectStore("blobs").put(project, id + "/project");
68
+ if (data !== undefined) t.objectStore("blobs").put(data, id + "/data");
69
+ });
70
+ },
71
+ async load(id) {
72
+ return tx(["blobs"], "readonly", async (t) => {
73
+ const b = t.objectStore("blobs");
74
+ return { project: await req(b.get(id + "/project")), data: await req(b.get(id + "/data")) };
75
+ });
76
+ },
77
+ async rename(id, name) {
78
+ await tx(["projects"], "readwrite", async (t) => {
79
+ const ps = t.objectStore("projects"), p = await req(ps.get(id));
80
+ if (p) { p.name = name; p.updated = Date.now(); ps.put(p); }
81
+ });
82
+ },
83
+ async remove(id) {
84
+ await tx(["projects", "blobs"], "readwrite", (t) => {
85
+ t.objectStore("projects").delete(id);
86
+ t.objectStore("blobs").delete(id + "/project");
87
+ t.objectStore("blobs").delete(id + "/data");
88
+ });
89
+ },
90
+ };
91
+
92
+ // ------------------------------------------------------------ 라벨링 작업 (이 브라우저): 목록(labels) + 정답 JSON·데이터 사본(blobs의 L<id>/work·data)
93
+ // 모양: list() → [{id, name, updated, meta}] · create(name) · save(id, {work, data?, meta}) · load(id) → {work, data} · rename · remove
94
+ const labels = {
95
+ kind: "local",
96
+ label: "이 브라우저",
97
+ async list() {
98
+ const all = await tx(["labels"], "readonly", (t) => req(t.objectStore("labels").getAll()));
99
+ return all.sort((a, b) => b.updated - a.updated);
100
+ },
101
+ async create(name) {
102
+ const p = { id: "l" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), name, updated: Date.now(), meta: null };
103
+ await tx(["labels"], "readwrite", (t) => t.objectStore("labels").put(p));
104
+ return p;
105
+ },
106
+ async save(id, { work, data, meta }) {
107
+ await tx(["labels", "blobs"], "readwrite", async (t) => {
108
+ const ls = t.objectStore("labels");
109
+ const p = await req(ls.get(id));
110
+ if (!p) throw new Error("라벨링 작업이 없음");
111
+ p.updated = Date.now();
112
+ if (meta !== undefined) p.meta = meta;
113
+ ls.put(p);
114
+ if (work !== undefined) t.objectStore("blobs").put(work, "L" + id + "/work");
115
+ if (data !== undefined) t.objectStore("blobs").put(data, "L" + id + "/data");
116
+ });
117
+ },
118
+ async load(id) {
119
+ return tx(["blobs"], "readonly", async (t) => {
120
+ const b = t.objectStore("blobs");
121
+ return { work: await req(b.get("L" + id + "/work")), data: await req(b.get("L" + id + "/data")) };
122
+ });
123
+ },
124
+ async rename(id, name) {
125
+ await tx(["labels"], "readwrite", async (t) => {
126
+ const ls = t.objectStore("labels"), p = await req(ls.get(id));
127
+ if (p) { p.name = name; p.updated = Date.now(); ls.put(p); }
128
+ });
129
+ },
130
+ async remove(id) {
131
+ await tx(["labels", "blobs"], "readwrite", (t) => {
132
+ t.objectStore("labels").delete(id);
133
+ t.objectStore("blobs").delete("L" + id + "/work");
134
+ t.objectStore("blobs").delete("L" + id + "/data");
135
+ });
136
+ },
137
+ };
138
+
139
+ // ------------------------------------------------------------ 구글 드라이브
140
+ // 로그인은 구글 창(accounts.google.com)에서 하고, 이 페이지는 1시간짜리 출입증만 메모리에 둔다 (브라우저 저장소에 남기지 않음).
141
+ let token = null, tokenUntil = 0, tokenClient = null, rootId = null, user = "";
142
+
143
+ function loadGis() {
144
+ if (window.google && google.accounts && google.accounts.oauth2) return Promise.resolve();
145
+ return new Promise((ok, no) => {
146
+ const s = document.createElement("script");
147
+ s.src = "https://accounts.google.com/gsi/client";
148
+ s.onload = ok;
149
+ s.onerror = () => no(new Error("구글 로그인 스크립트를 불러오지 못함"));
150
+ document.head.appendChild(s);
151
+ });
152
+ }
153
+ async function signIn(prompt = "") { // 단추를 누를 때 불러야 함 (팝업)
154
+ if (!GOOGLE_CLIENT_ID) throw new Error("구글 드라이브 연결은 준비 중입니다");
155
+ await loadGis();
156
+ return new Promise((ok, no) => {
157
+ tokenClient = google.accounts.oauth2.initTokenClient({
158
+ client_id: GOOGLE_CLIENT_ID, scope: DRIVE_SCOPE,
159
+ callback: (r) => {
160
+ if (r.error) return no(new Error("구글 로그인 실패: " + r.error));
161
+ if (!google.accounts.oauth2.hasGrantedAllScopes(r, DRIVE_SCOPE)) return no(new Error("드라이브 권한을 허용해야 저장할 수 있습니다"));
162
+ token = r.access_token;
163
+ tokenUntil = Date.now() + (Number(r.expires_in || 3600) - 60) * 1000;
164
+ ok();
165
+ },
166
+ error_callback: (e) => no(new Error(e && e.type === "popup_closed" ? "로그인 창을 닫았습니다" : "구글 로그인 창을 열 수 없음 (팝업 차단 확인)")),
167
+ });
168
+ tokenClient.requestAccessToken({ prompt });
169
+ });
170
+ }
171
+ function signOut() {
172
+ if (token && window.google && google.accounts) google.accounts.oauth2.revoke(token, () => {});
173
+ token = null; tokenUntil = 0; rootId = null; user = "";
174
+ }
175
+ const signedIn = () => !!token && Date.now() < tokenUntil;
176
+
177
+ async function gapi(path, opt = {}) {
178
+ if (!signedIn()) throw Object.assign(new Error("구글 로그인이 필요합니다 (1시간이 지나면 다시 로그인)"), { needLogin: true });
179
+ const r = await fetch(path.startsWith("http") ? path : "https://www.googleapis.com/drive/v3/" + path,
180
+ Object.assign({}, opt, { headers: Object.assign({ Authorization: "Bearer " + token }, opt.headers || {}) }));
181
+ if (r.status === 401) { token = null; throw Object.assign(new Error("구글 로그인이 끝났습니다. 다시 로그인하세요"), { needLogin: true }); }
182
+ if (!r.ok) throw new Error(`구글 드라이브 오류 ${r.status}: ${(await r.text()).slice(0, 200)}`);
183
+ return r;
184
+ }
185
+ const q = (s) => encodeURIComponent(s);
186
+ const esc = (s) => String(s).replace(/\\/g, "\\\\").replace(/'/g, "\\'");
187
+ async function findChildren(parent, extra = "") {
188
+ const r = await gapi(`files?q=${q(`'${parent}' in parents and trashed=false${extra}`)}&fields=${q("files(id,name,mimeType,modifiedTime,description,appProperties)")}&pageSize=1000&spaces=drive`);
189
+ return (await r.json()).files || [];
190
+ }
191
+ async function makeFolder(name, parent) {
192
+ const r = await gapi("files?fields=id,name,modifiedTime", { method: "POST", headers: { "Content-Type": "application/json" },
193
+ body: JSON.stringify({ name, mimeType: FOLDER, parents: [parent] }) });
194
+ return r.json();
195
+ }
196
+ async function root() { // 내 드라이브/BlockLearning (이 앱이 만든 것만 보임)
197
+ if (rootId) return rootId;
198
+ const find = (name) => findChildren("root", ` and mimeType='${FOLDER}' and name='${esc(name)}'`);
199
+ let found = await find(ROOT_NAME);
200
+ if (!found.length) {
201
+ found = await find(OLD_ROOT_NAME);
202
+ if (found.length) await gapi(`files/${found[0].id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: ROOT_NAME }) });
203
+ }
204
+ rootId = found.length ? found[0].id : (await makeFolder(ROOT_NAME, "root")).id;
205
+ return rootId;
206
+ }
207
+ async function putFile(folder, name, bytes) { // 같은 이름 파일이 있으면 내용만 바꿈
208
+ const ex = (await findChildren(folder, ` and name='${esc(name)}'`))[0];
209
+ const type = "application/octet-stream";
210
+ if (ex) {
211
+ await gapi(`https://www.googleapis.com/upload/drive/v3/files/${ex.id}?uploadType=media`, { method: "PATCH", headers: { "Content-Type": type }, body: bytes });
212
+ return;
213
+ }
214
+ const meta = new Blob([JSON.stringify({ name, parents: [folder] })], { type: "application/json" });
215
+ const form = new FormData();
216
+ form.append("metadata", meta);
217
+ form.append("file", new Blob([bytes], { type }));
218
+ await gapi("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id", { method: "POST", body: form });
219
+ }
220
+ async function getFile(folder, name) {
221
+ const f = (await findChildren(folder, ` and name='${esc(name)}'`))[0];
222
+ if (!f) return null;
223
+ return new Uint8Array(await (await gapi(`files/${f.id}?alt=media`)).arrayBuffer());
224
+ }
225
+
226
+ const metaSent = {}, stepsSent = {};
227
+ const drive = {
228
+ kind: "drive",
229
+ label: "구글 드라이브",
230
+ available: () => !!GOOGLE_CLIENT_ID,
231
+ signedIn, signIn, signOut, user: () => user,
232
+ async list() {
233
+ const items = await findChildren(await root(), ` and mimeType='${FOLDER}'`);
234
+ return items.map((f) => ({ id: f.id, name: f.name, updated: Date.parse(f.modifiedTime) || 0, meta: f.description || "", steps: (f.appProperties || {}).steps || "" })).sort((a, b) => b.updated - a.updated);
235
+ },
236
+ async create(name) { const f = await makeFolder(name, await root()); return { id: f.id, name: f.name, updated: Date.now() }; },
237
+ async save(id, { project, data, meta, steps }) {
238
+ await putFile(id, "project.dlstudio", project);
239
+ if (data !== undefined && data !== null) await putFile(id, "data.zip", data);
240
+ if (meta !== undefined && meta !== metaSent[id]) { // 폴더 설명에 한 줄 요약 (첫 화면 카드에 보임)
241
+ await gapi(`files/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ description: meta }) });
242
+ metaSent[id] = meta;
243
+ }
244
+ if (steps !== undefined && steps !== stepsSent[id]) { // 만들기 단계 진행 (폴더의 앱 속성)
245
+ await gapi(`files/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ appProperties: { steps } }) });
246
+ stepsSent[id] = steps;
247
+ }
248
+ },
249
+ async load(id) { return { project: await getFile(id, "project.dlstudio"), data: await getFile(id, "data.zip") }; },
250
+ async rename(id, name) {
251
+ await gapi(`files/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) });
252
+ },
253
+ async remove(id) { // 휴지통으로 (드라이브에서 되살릴 수 있음)
254
+ await gapi(`files/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ trashed: true }) });
255
+ },
256
+ };
257
+
258
+ window.DLStore = { local, drive, labels, GOOGLE_CLIENT_ID, DRIVE_SCOPE };
259
+ })();