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/project.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""프로젝트 파일(.blocklearning, zip): 모델 그래프, 데이터 출처·설정, 학습 설정, 결과 요약, 학습된 가중치.
|
|
2
|
+
내보내기: torch만으로 읽는 모델 파일(TorchScript .pt)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import warnings
|
|
8
|
+
import zipfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
FORMAT, VERSION = "dlstudio", 1
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def save_project(path, graph: dict, data_source: dict, train_settings: dict, model, results: dict,
|
|
16
|
+
selection: dict = None, extra_files: Optional[dict] = None, name: str = "",
|
|
17
|
+
runs: Optional[list] = None, run_weights: Optional[dict] = None, current_run=None) -> None:
|
|
18
|
+
"""path: 파일 경로 또는 쓸 수 있는 파일(BytesIO). model: torch 모델, 또는 가중치 dict(이름 → 배열, 웹 버전).
|
|
19
|
+
extra_files: zip에 함께 넣을 {이름: 바이트} (웹 버전의 데이터 사본 data/...). name: 프로젝트 이름.
|
|
20
|
+
runs: 학습 기록 목록, run_weights: 기록 번호 → 가중치 dict (runs/<번호>.npz)."""
|
|
21
|
+
if isinstance(path, (str, Path)):
|
|
22
|
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
23
|
+
meta = {"format": FORMAT, "version": VERSION, "name": name, "graph": graph, "data_source": data_source,
|
|
24
|
+
"train_settings": train_settings, "results": results, "selection": selection,
|
|
25
|
+
"runs": runs or [], "current_run": current_run}
|
|
26
|
+
with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as z:
|
|
27
|
+
z.writestr("project.json", json.dumps(meta, ensure_ascii=False, indent=1))
|
|
28
|
+
for arc, raw in (extra_files or {}).items():
|
|
29
|
+
z.writestr(arc, raw)
|
|
30
|
+
if model is not None: # 가중치: PyTorch state_dict 이름 그대로 .npz (torch 없이도 읽음)
|
|
31
|
+
from blocklearning.codegen import save_npz
|
|
32
|
+
buf = io.BytesIO()
|
|
33
|
+
save_npz(model if isinstance(model, dict) else model.state_dict(), buf)
|
|
34
|
+
z.writestr("model.npz", buf.getvalue())
|
|
35
|
+
from blocklearning.codegen import save_npz
|
|
36
|
+
for n, w in (run_weights or {}).items():
|
|
37
|
+
if any(r.get("n") == n for r in runs or []):
|
|
38
|
+
buf = io.BytesIO()
|
|
39
|
+
save_npz(w, buf)
|
|
40
|
+
z.writestr(f"runs/{int(n)}.npz", buf.getvalue())
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def open_project(path: str) -> dict:
|
|
44
|
+
try:
|
|
45
|
+
with zipfile.ZipFile(Path(path)) as z:
|
|
46
|
+
names = set(z.namelist())
|
|
47
|
+
meta = json.loads(z.read("project.json")) if "project.json" in names else {}
|
|
48
|
+
if meta.get("format") != FORMAT or meta.get("version") != VERSION:
|
|
49
|
+
raise ValueError("BlockLearning 프로젝트 파일이 아님")
|
|
50
|
+
state: Optional[dict] = None
|
|
51
|
+
if "model.npz" in names:
|
|
52
|
+
import numpy as np
|
|
53
|
+
with np.load(io.BytesIO(z.read("model.npz"))) as npz:
|
|
54
|
+
state = {k: npz[k] for k in npz.files}
|
|
55
|
+
run_weights = {}
|
|
56
|
+
for nm in names:
|
|
57
|
+
if nm.startswith("runs/") and nm.endswith(".npz") and nm[5:-4].isdigit():
|
|
58
|
+
import numpy as np
|
|
59
|
+
with np.load(io.BytesIO(z.read(nm))) as npz:
|
|
60
|
+
run_weights[int(nm[5:-4])] = {k: npz[k] for k in npz.files}
|
|
61
|
+
except zipfile.BadZipFile:
|
|
62
|
+
raise ValueError("BlockLearning 프로젝트 파일이 아님 (zip이 아님)") from None
|
|
63
|
+
return {"graph": meta["graph"], "data_source": meta["data_source"], "train_settings": meta["train_settings"],
|
|
64
|
+
"name": meta.get("name", ""),
|
|
65
|
+
"results": meta.get("results", {}), "selection": meta.get("selection"), "state_dict": state,
|
|
66
|
+
"runs": meta.get("runs") or [], "run_weights": run_weights, "current_run": meta.get("current_run")}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _export_module(model, data):
|
|
70
|
+
"""원래 값 한 행(CSV 그대로) → 정규화 → 모델 입력 모양 → 모델. studio 없이 torch만으로 돌아가게 TorchScript로 굳힐 모듈."""
|
|
71
|
+
import numpy as np
|
|
72
|
+
import torch
|
|
73
|
+
from torch import nn
|
|
74
|
+
|
|
75
|
+
class StudioExport(nn.Module):
|
|
76
|
+
def __init__(self, net, mean, std, kind: str, image):
|
|
77
|
+
super().__init__()
|
|
78
|
+
self.net = net
|
|
79
|
+
self.register_buffer("mean", torch.as_tensor(np.asarray(mean), dtype=torch.float32))
|
|
80
|
+
self.register_buffer("std", torch.as_tensor(np.asarray(std), dtype=torch.float32))
|
|
81
|
+
self.kind, self.image = kind, image
|
|
82
|
+
|
|
83
|
+
def forward(self, x): # x: (샘플 수, 특징 수) 원래 값
|
|
84
|
+
z = (x - self.mean) / self.std
|
|
85
|
+
if self.kind == "image":
|
|
86
|
+
return self.net(z.reshape(-1, 1, self.image[0], self.image[1]))
|
|
87
|
+
return self.net(z.unsqueeze(1) if self.kind == "cnn" else z.unsqueeze(2))
|
|
88
|
+
|
|
89
|
+
return StudioExport(model, data.mean, data.std, model.kind, data.image).eval()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def export_torch(model, data, path: str) -> dict:
|
|
93
|
+
"""학습된 모델 → 평문 모델 파일(TorchScript .pt). 받는 쪽은 BlockLearning 없이 torch.jit.load로 읽어
|
|
94
|
+
원래 값 행(샘플 수, 특징 수)을 넣으면 (샘플 수, 클래스 수) 점수 또는 (샘플 수, 1) 예측값이 나온다.
|
|
95
|
+
과제·클래스 이름·입력 설명은 파일 안의 studio.json (torch.jit.load(..., _extra_files={"studio.json": ""}))."""
|
|
96
|
+
import torch
|
|
97
|
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
98
|
+
m = _export_module(model.eval(), data)
|
|
99
|
+
example = torch.as_tensor(data.raw(data.X_train[:2]), dtype=torch.float32)
|
|
100
|
+
with warnings.catch_warnings():
|
|
101
|
+
warnings.simplefilter("ignore")
|
|
102
|
+
traced = torch.jit.trace(m, example, check_trace=False)
|
|
103
|
+
cls, det = data.task == "classification", data.task == "detection"
|
|
104
|
+
info = {"format": "dlstudio-model", "task": data.task, "classes": [str(c) for c in data.classes] if cls or det else [],
|
|
105
|
+
"n_features": int(data.X_train.shape[1]), "features": list(data.features or []),
|
|
106
|
+
"image": list(data.image) if data.image else None,
|
|
107
|
+
"input": ("행 하나 = 그림 하나를 흑백 0–1 값으로 펼친 픽셀 (높이×너비)" if data.image
|
|
108
|
+
else "행 하나 = 샘플 하나. 학습 CSV와 같은 열 순서의 원래 값 (정답 열 빼고)"),
|
|
109
|
+
"output": "클래스마다 점수 (가장 큰 것이 예측, 순서는 classes)" if cls else
|
|
110
|
+
(f"격자 {data.n_out.grid}×{data.n_out.grid} 칸마다 값 {data.n_out.per_cell}개 (있음·가운데 x·y·너비·높이의 제곱근·클래스 점수)를 "
|
|
111
|
+
"(값, 세로, 가로) 순서로 펼친 것 — BlockLearning의 blocklearning.detect.decode로 상자를 풂") if det else "예측값 (원래 단위)"}
|
|
112
|
+
if det:
|
|
113
|
+
info["grid"], info["per_cell"] = data.n_out.grid, data.n_out.per_cell
|
|
114
|
+
if data.task == "multi":
|
|
115
|
+
info["heads"] = data.n_out.heads
|
|
116
|
+
info["output"] = "정답마다 머리를 이어 붙인 한 줄 (heads의 start·size): 분류 머리는 클래스 점수, 값 머리는 예측값 (원래 단위)"
|
|
117
|
+
with warnings.catch_warnings(): # 새 torch는 TorchScript를 낡았다고 알리지만 가장 널리 읽힘
|
|
118
|
+
warnings.simplefilter("ignore")
|
|
119
|
+
torch.jit.save(traced, str(path), _extra_files={"studio.json": json.dumps(info, ensure_ascii=False)})
|
|
120
|
+
return info
|
blocklearning/segment.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""구간 분할: 긴 신호의 시점마다 상태(공정 단계 등)를 맞힌다.
|
|
2
|
+
|
|
3
|
+
데이터: 신호를 길이 L의 창으로 자르고, 창 안 시점마다 상태 번호 (y: (창 수, L)).
|
|
4
|
+
모델: 길이를 줄이지 않는 층들 → 출력 블록이 시점마다 1×1 합성곱으로 상태 점수 K개 → (K, L)을 펼친 K·L개 (상태가 먼저).
|
|
5
|
+
손실: 시점마다 교차 엔트로피. 성적: 시점 정확도 (맞힌 시점 비율).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import io
|
|
10
|
+
import csv
|
|
11
|
+
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
MIN_TRAIN = 10 # 학습 창이 이보다 적으면 안 됨
|
|
17
|
+
N_SHOW = 4 # 결과 화면에 그릴 시험 창 (상태가 가장 많이 바뀌는 것부터)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SegOut(int):
|
|
21
|
+
"""구간 분할 과제의 모델 출력 크기 (상태 수 K × 길이 L). int처럼 쓰이고, K·L을 함께 지님 →
|
|
22
|
+
모델 검사·만들기·코드가 출력 블록을 '시점마다 1×1 합성곱'으로 만든다."""
|
|
23
|
+
|
|
24
|
+
def __new__(cls, n_cls: int, length: int):
|
|
25
|
+
o = super().__new__(cls, int(n_cls) * int(length))
|
|
26
|
+
o.n_cls, o.length, o.seg = int(n_cls), int(length), True
|
|
27
|
+
return o
|
|
28
|
+
|
|
29
|
+
def __getnewargs__(self):
|
|
30
|
+
return (self.n_cls, self.length)
|
|
31
|
+
|
|
32
|
+
def __reduce__(self):
|
|
33
|
+
return (SegOut, (self.n_cls, self.length))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def make_segment_dataset(X, Y, classes: list, test_ratio: float = 0.2, seed: int = 0, normalize: bool = True,
|
|
37
|
+
source: dict | None = None, channels: int = 1):
|
|
38
|
+
"""창들 (n, C·L, 채널이 먼저) · 시점마다 상태 (n, L) → 구간 분할 Dataset (X는 채널마다 학습 몫 전체 평균·표준편차로 정규화)."""
|
|
39
|
+
from blocklearning.data import DataError, Dataset, Issue, seq_length
|
|
40
|
+
X, Y = np.asarray(X, dtype=np.float64), np.asarray(Y, dtype=np.int64)
|
|
41
|
+
n, L = Y.shape
|
|
42
|
+
if X.shape != (n, channels * L):
|
|
43
|
+
raise DataError([Issue(None, None, "창마다 시점 수만큼 상태가 있어야 함", "신호와 상태의 길이를 맞추세요")])
|
|
44
|
+
order = np.random.default_rng(seed).permutation(n)
|
|
45
|
+
n_te = max(1, int(round(n * test_ratio)))
|
|
46
|
+
te, tr = order[:n_te], order[n_te:]
|
|
47
|
+
if len(tr) < MIN_TRAIN:
|
|
48
|
+
raise DataError([Issue(None, None, f"학습 창이 {len(tr)}개뿐임", f"창이 {MIN_TRAIN}개 이상 되게 신호를 늘리거나 창 길이를 줄이세요")])
|
|
49
|
+
mu, sd = np.zeros(channels * L), np.ones(channels * L)
|
|
50
|
+
if normalize:
|
|
51
|
+
for c in range(channels):
|
|
52
|
+
part = X[tr][:, c * L:(c + 1) * L]
|
|
53
|
+
mu[c * L:(c + 1) * L], sd[c * L:(c + 1) * L] = float(part.mean()), float(part.std()) or 1.0
|
|
54
|
+
src = dict(source or {}, task="segmentation")
|
|
55
|
+
src.setdefault("normalize", normalize)
|
|
56
|
+
src.setdefault("test_ratio", test_ratio)
|
|
57
|
+
return Dataset((X[tr] - mu) / sd, (X[te] - mu) / sd, Y[tr], Y[te], "segmentation", [str(c) for c in classes],
|
|
58
|
+
seq_length(L, channels), mu, sd, src, [], None, None, {"segment": True})
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def predicted(out: np.ndarray, n: int, K: int) -> np.ndarray:
|
|
62
|
+
"""출력 (n, K·L) → 시점마다 상태 번호 (n, L)."""
|
|
63
|
+
return np.asarray(out).reshape(n, K, -1).argmax(1)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def metric(out: np.ndarray, y: np.ndarray, K: int) -> float:
|
|
67
|
+
"""시점 정확도: 맞힌 시점의 비율."""
|
|
68
|
+
y = np.asarray(y)
|
|
69
|
+
return float((predicted(out, len(y), K) == y).mean())
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def torch_loss(out, target, K: int):
|
|
73
|
+
"""시점마다 교차 엔트로피 (평균)."""
|
|
74
|
+
import torch.nn.functional as F
|
|
75
|
+
return F.cross_entropy(out.reshape(len(target), K, -1), target)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def runs(labels) -> list:
|
|
79
|
+
"""상태 줄 → [[상태, 시작, 길이], …] (같은 상태가 이어지는 구간)."""
|
|
80
|
+
labels = np.asarray(labels).ravel()
|
|
81
|
+
out, s = [], 0
|
|
82
|
+
for i in range(1, len(labels) + 1):
|
|
83
|
+
if i == len(labels) or labels[i] != labels[s]:
|
|
84
|
+
out.append([int(labels[s]), s, i - s])
|
|
85
|
+
s = i
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def states_text(labels, classes: list, limit: int = 5) -> str:
|
|
90
|
+
"""'대기 → 동작 1–10 → 긴 단계' (구간이 많으면 줄임)."""
|
|
91
|
+
names = [classes[r[0]] for r in runs(labels)]
|
|
92
|
+
return " → ".join(names[:limit]) + (f" … (구간 {len(names)}개)" if len(names) > limit else "")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def result(out: np.ndarray, out_tr: np.ndarray, d) -> dict:
|
|
96
|
+
"""결과 화면: 시점 혼동 행렬·상태별 재현율, 상태가 많이 바뀌는 시험 창 몇 개의 신호·정답·예측."""
|
|
97
|
+
K = len(d.classes)
|
|
98
|
+
p = predicted(out, len(d.y_test), K)
|
|
99
|
+
y = np.asarray(d.y_test)
|
|
100
|
+
cm = np.zeros((K, K), dtype=int)
|
|
101
|
+
np.add.at(cm, (y.ravel(), p.ravel()), 1)
|
|
102
|
+
rec = [None if cm[k].sum() == 0 else float(cm[k, k] / cm[k].sum()) for k in range(K)]
|
|
103
|
+
order = np.argsort([-len(runs(r)) for r in y], kind="stable")[:N_SHOW]
|
|
104
|
+
raw = d.raw(d.X_test)
|
|
105
|
+
show = [{"index": int(i), "x": np.round(raw[i][:d.length], 4).tolist(), "truth": y[i].tolist(), "pred": p[i].tolist(),
|
|
106
|
+
"acc": float((p[i] == y[i]).mean())} for i in order]
|
|
107
|
+
return {"confusion": cm.tolist(), "recall": rec, "seg_samples": show,
|
|
108
|
+
"train_metric": metric(out_tr, d.y_train, K)}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def table(d, names: list, out: np.ndarray, truth=None) -> dict:
|
|
112
|
+
"""⑤ 예측: 창마다 예측한 상태 구간 (정답이 있으면 시점 정확도). CSV는 시점마다 한 줄."""
|
|
113
|
+
K = len(d.classes)
|
|
114
|
+
p = predicted(out, len(names), K)
|
|
115
|
+
t = None if truth is None else np.asarray(truth)
|
|
116
|
+
buf = io.StringIO()
|
|
117
|
+
w = csv.writer(buf)
|
|
118
|
+
w.writerow(["창", "시점", "예측 상태"] + (["정답 상태"] if t is not None else []))
|
|
119
|
+
rows = []
|
|
120
|
+
for i, nm in enumerate(names):
|
|
121
|
+
for j, k in enumerate(p[i]):
|
|
122
|
+
w.writerow([nm, j, d.classes[k]] + ([d.classes[int(t[i][j])]] if t is not None else []))
|
|
123
|
+
acc = None if t is None else float((p[i] == t[i]).mean())
|
|
124
|
+
rows.append({"name": nm, "pred": states_text(p[i], d.classes), "label": None if t is None else states_text(t[i], d.classes),
|
|
125
|
+
"ok": None if acc is None else acc >= 0.9, "acc": acc, "seg_pred": p[i].tolist(),
|
|
126
|
+
"seg_truth": None if t is None else t[i].tolist()})
|
|
127
|
+
acc = None if t is None else float((p == t).mean())
|
|
128
|
+
summary = {"n": len(names), "task": "segmentation", "accuracy": acc, "classes": list(d.classes)}
|
|
129
|
+
return {"summary": summary, "rows": rows, "shown": len(rows), "csv": "" + buf.getvalue(), "has_label": t is not None}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def load_segment_csv(path: str, state_col=None, skip=None, length=None, normalize: bool = True, test_ratio: float = 0.2,
|
|
133
|
+
seed: int = 0):
|
|
134
|
+
"""긴 시계열 CSV (한 행 = 한 시점, 시간 순서) → 구간 분할 Dataset. state_col: 상태 열 번호 (없으면 마지막 열),
|
|
135
|
+
값 열 = 나머지 숫자 열 (글자뿐인 열·skip은 안 씀, 여러 개면 채널). length: 창 길이 (없으면 시점 수에 맞춰), 겹치지 않게 자름."""
|
|
136
|
+
from blocklearning.data import DataError, Issue, _column_values, _numeric_columns, _num, _read_table
|
|
137
|
+
name = Path(path).name
|
|
138
|
+
names, rows = _read_table(path)
|
|
139
|
+
if not rows or len(names) < 2:
|
|
140
|
+
raise DataError([Issue(None, None, "열이 2개 이상 있어야 함 (값 열 + 상태 열)", "한 행 = 한 시점, 마지막 열 = 그 시점의 상태")])
|
|
141
|
+
sc = len(names) - 1 if state_col is None else int(state_col)
|
|
142
|
+
if not 0 <= sc < len(names):
|
|
143
|
+
raise DataError([Issue(None, None, f"상태 열 번호 {sc + 1}이(가) 없음", "역할 표에서 상태 열을 다시 고르세요")])
|
|
144
|
+
skips = {int(j) for j in skip or []}
|
|
145
|
+
numeric = set(_numeric_columns(names, rows))
|
|
146
|
+
cols = [j for j in range(len(names)) if j != sc and j not in skips and names[j] in numeric]
|
|
147
|
+
if not cols:
|
|
148
|
+
raise DataError([Issue(None, None, "값(숫자) 열이 없음", "측정값이 숫자로 든 열이 있어야 합니다")])
|
|
149
|
+
V = np.stack([_column_values(name, names, rows, names[j]) for j in cols])
|
|
150
|
+
states = [(r[sc] if sc < len(r) else "").strip() for _, r in rows]
|
|
151
|
+
bad = next((i for i, v in enumerate(states) if not v), None)
|
|
152
|
+
if bad is not None:
|
|
153
|
+
raise DataError([Issue(rows[bad][0], sc + 1, f"{rows[bad][0]}행의 상태 칸이 비어 있음", "상태를 채우거나 그 행을 지우세요")])
|
|
154
|
+
uniq = sorted(set(states), key=lambda v: (_num(v) is None, _num(v) if _num(v) is not None else 0, v))
|
|
155
|
+
if len(uniq) < 2:
|
|
156
|
+
raise DataError([Issue(None, None, "상태가 한 가지뿐임", "구간 분할에는 상태가 두 가지 이상 있어야 합니다")])
|
|
157
|
+
if len(uniq) > 50:
|
|
158
|
+
raise DataError([Issue(None, None, f"상태가 {len(uniq)}가지 (50가지 넘음)", "상태 열이 맞는지 확인하세요 (숫자 측정값 열이 아니어야 함)")])
|
|
159
|
+
idx = {v: k for k, v in enumerate(uniq)}
|
|
160
|
+
y = np.asarray([idx[v] for v in states], dtype=np.int64)
|
|
161
|
+
T = len(y)
|
|
162
|
+
L = int(length) if length else int(min(512, max(32, (T // 20) // 8 * 8)))
|
|
163
|
+
n = T // L
|
|
164
|
+
if L < 8 or n < MIN_TRAIN + 2:
|
|
165
|
+
raise DataError([Issue(None, None, f"시점 {T:,}개를 길이 {L} 창으로 자르면 {n}개 (최소 {MIN_TRAIN + 2}개)",
|
|
166
|
+
"창 길이를 줄이거나 더 긴 기록을 넣으세요")])
|
|
167
|
+
X = np.stack([np.concatenate([V[c, i * L:(i + 1) * L] for c in range(len(cols))]) for i in range(n)])
|
|
168
|
+
Y = np.stack([y[i * L:(i + 1) * L] for i in range(n)])
|
|
169
|
+
used = set(cols) | {sc}
|
|
170
|
+
src = {"path": str(path), "task": "segmentation", "label_col": sc, "targets": [sc],
|
|
171
|
+
"skip": [j for j in range(len(names)) if j not in used], "length": L, "columns": list(names),
|
|
172
|
+
"channel_names": [names[j] for j in cols], "seed": seed}
|
|
173
|
+
return make_segment_dataset(X, Y, uniq, test_ratio=test_ratio, seed=seed, normalize=normalize, source=src, channels=len(cols))
|
blocklearning/server.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""BlockLearning 로컬 HTTP 서버: 127.0.0.1에만 열고, 화면(static)과 JSON API(core.Studio)를 제공한다."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import mimetypes
|
|
6
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Optional
|
|
9
|
+
from urllib.parse import parse_qs, unquote, urlparse
|
|
10
|
+
|
|
11
|
+
from blocklearning.core import Studio, UserError, _clean, _jsonable, _path # noqa: F401 (UserError는 예전 import 자리)
|
|
12
|
+
from blocklearning.data import DataError
|
|
13
|
+
|
|
14
|
+
STATIC_DIR = Path(__file__).parent / "static"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class StudioServer(Studio, ThreadingHTTPServer):
|
|
18
|
+
daemon_threads = True
|
|
19
|
+
|
|
20
|
+
def __init__(self, port: int, static_dir: Path):
|
|
21
|
+
ThreadingHTTPServer.__init__(self, ("127.0.0.1", port), Handler)
|
|
22
|
+
Studio.__init__(self)
|
|
23
|
+
self.static_dir = Path(static_dir).resolve()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Handler(BaseHTTPRequestHandler):
|
|
27
|
+
server: StudioServer
|
|
28
|
+
|
|
29
|
+
def log_message(self, fmt, *args): # 터미널을 조용히
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
def _send(self, code: int, body: bytes, ctype: str) -> None:
|
|
33
|
+
self.send_response(code)
|
|
34
|
+
self.send_header("Content-Type", ctype)
|
|
35
|
+
self.send_header("Content-Length", str(len(body)))
|
|
36
|
+
self.send_header("Cache-Control", "no-store")
|
|
37
|
+
self.end_headers()
|
|
38
|
+
self.wfile.write(body)
|
|
39
|
+
|
|
40
|
+
def _json(self, code: int, obj) -> None:
|
|
41
|
+
body = json.dumps(_clean(obj), ensure_ascii=False, allow_nan=False, default=_jsonable)
|
|
42
|
+
self._send(code, body.encode(), "application/json; charset=utf-8")
|
|
43
|
+
|
|
44
|
+
def _same_origin(self) -> bool:
|
|
45
|
+
"""다른 웹사이트가 로컬 API를 부르지 못하게 (CSRF·DNS rebinding): Host와 Origin이 이 서버여야 함."""
|
|
46
|
+
port = self.server.server_address[1]
|
|
47
|
+
ok = {f"127.0.0.1:{port}", f"localhost:{port}"}
|
|
48
|
+
if self.headers.get("Host", "") not in ok:
|
|
49
|
+
return False
|
|
50
|
+
origin = self.headers.get("Origin")
|
|
51
|
+
return origin is None or origin in {f"http://{h}" for h in ok}
|
|
52
|
+
|
|
53
|
+
def _error(self, code: int, message: str, hint: str = "", detail: str = "", issues=None) -> None:
|
|
54
|
+
self._json(code, {"error": {"message": message, "hint": hint, "detail": detail, "issues": issues or []}})
|
|
55
|
+
|
|
56
|
+
def do_GET(self):
|
|
57
|
+
path = unquote(urlparse(self.path).path)
|
|
58
|
+
if not self._same_origin():
|
|
59
|
+
return self._error(403, "다른 사이트에서 온 요청은 받지 않음")
|
|
60
|
+
if path.startswith("/api/"):
|
|
61
|
+
if path == "/api/label/file":
|
|
62
|
+
return self._label_file(parse_qs(urlparse(self.path).query).get("name", [""])[0])
|
|
63
|
+
code, obj = self.server.call("GET", path)
|
|
64
|
+
return self._json(code, obj)
|
|
65
|
+
if path in ("/", "/index.html"):
|
|
66
|
+
return self._file("index.html")
|
|
67
|
+
if path in ("/label", "/label.html"):
|
|
68
|
+
return self._file("label.html")
|
|
69
|
+
if path.startswith("/static/"):
|
|
70
|
+
return self._file(path[len("/static/"):])
|
|
71
|
+
self._error(404, "없는 주소")
|
|
72
|
+
|
|
73
|
+
def _label_file(self, name: str) -> None:
|
|
74
|
+
"""라벨링 그림 원본 (크게 보기). 작업의 샘플 이름만, 데이터 폴더 안의 그림 파일만."""
|
|
75
|
+
from blocklearning.data import IMAGE_EXTS
|
|
76
|
+
from blocklearning.labeling import _inside
|
|
77
|
+
srv = self.server
|
|
78
|
+
with srv.label_lock:
|
|
79
|
+
p = srv.label
|
|
80
|
+
try:
|
|
81
|
+
f = p.file_path(name) if p is not None else None
|
|
82
|
+
except DataError:
|
|
83
|
+
f = None
|
|
84
|
+
root = p.source.guard_root() if p is not None else ""
|
|
85
|
+
if f is None or f.suffix.lower() not in IMAGE_EXTS or not _inside(str(f), root) or not f.is_file():
|
|
86
|
+
return self._error(404, "없는 그림")
|
|
87
|
+
ctype = mimetypes.guess_type(f.name)[0] or "application/octet-stream"
|
|
88
|
+
self._send(200, f.read_bytes(), ctype)
|
|
89
|
+
|
|
90
|
+
def _file(self, rel: str) -> None:
|
|
91
|
+
root = self.server.static_dir
|
|
92
|
+
p = (root / rel).resolve()
|
|
93
|
+
if root not in p.parents or not p.is_file(): # static 폴더 밖(..)은 거절
|
|
94
|
+
return self._error(404, "없는 파일")
|
|
95
|
+
ctype = mimetypes.guess_type(p.name)[0] or "application/octet-stream"
|
|
96
|
+
if ctype.startswith("text/") or ctype in ("application/javascript",):
|
|
97
|
+
ctype += "; charset=utf-8"
|
|
98
|
+
self._send(200, p.read_bytes(), ctype)
|
|
99
|
+
|
|
100
|
+
def do_POST(self):
|
|
101
|
+
path = unquote(urlparse(self.path).path)
|
|
102
|
+
if not self._same_origin():
|
|
103
|
+
return self._error(403, "다른 사이트에서 온 요청은 받지 않음")
|
|
104
|
+
if not (self.headers.get("Content-Type") or "").startswith("application/json"):
|
|
105
|
+
return self._error(415, "JSON 요청만 받음")
|
|
106
|
+
try:
|
|
107
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
108
|
+
body = json.loads(self.rfile.read(n) or b"{}") if n else {}
|
|
109
|
+
except ValueError:
|
|
110
|
+
return self._error(400, "요청을 읽을 수 없음 (JSON 아님)")
|
|
111
|
+
code, obj = self.server.call("POST", path, body)
|
|
112
|
+
self._json(code, obj)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def make_server(port: int = 0, static_dir: Optional[str] = None) -> StudioServer:
|
|
116
|
+
return StudioServer(port, Path(static_dir) if static_dir else STATIC_DIR)
|