Datasets:
Download scoring/structured.py from Sci-Index/Science-Index-Video: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/datasets/Sci-Index/Science-Index-Video/resolve/main/scoring/structured.py
- Command line
-
hf download hf://datasets/Sci-Index/Science-Index-Video/scoring/structured.py
-
curl -L -o structured.py https://huggingface.co/datasets/Sci-Index/Science-Index-Video/resolve/main/scoring/structured.py
10.3 kB
| import csv | |
| import json | |
| import math | |
| import os | |
| import numpy as np | |
| STRUCT_TYPES = {"trajectory", "polyline", "mask", "timeseries", "edges"} | |
| def s_of_e(e): | |
| if e is None or (isinstance(e, float) and math.isnan(e)): | |
| return 0.0 | |
| if e <= 1: | |
| return 1.0 | |
| if os.environ.get("SCI_SCORE_MODE", "binary") == "binary": | |
| return 0.0 | |
| return max(0.0, 1 - (e - 1) / 2) | |
| def is_file_ref(x): | |
| return isinstance(x, dict) and set(x) == {"file"} and isinstance(x["file"], str) | |
| def resolve(x, base): | |
| if not is_file_ref(x): | |
| return x | |
| if base is None: | |
| raise FileNotFoundError("no directory to resolve " + x["file"]) | |
| p = os.path.realpath(os.path.join(base, x["file"])) | |
| if not p.startswith(os.path.realpath(base) + os.sep): | |
| raise FileNotFoundError("file reference escapes its directory") | |
| return load_file(p) | |
| def load_file(p): | |
| ext = os.path.splitext(p)[1].lower() | |
| if ext == ".json": | |
| return json.load(open(p)) | |
| if ext == ".npy": | |
| return np.load(p, allow_pickle=False) | |
| if ext in (".png", ".tif", ".tiff", ".bmp"): | |
| from PIL import Image | |
| Image.MAX_IMAGE_PIXELS = None | |
| if ext in (".tif", ".tiff"): | |
| import tifffile | |
| return tifffile.imread(p) | |
| return np.array(Image.open(p)) | |
| if ext in (".csv", ".tsv", ".txt"): | |
| rows = list(csv.reader(open(p), delimiter="\t" if ext == ".tsv" else ",")) | |
| rows = [r for r in rows if r and any(c.strip() for c in r)] | |
| head = [c.strip().lower() for c in rows[0]] | |
| try: | |
| [float(c) for c in rows[0]] | |
| head = None | |
| except ValueError: | |
| rows = rows[1:] | |
| return {"header": head, "rows": [[c.strip() for c in r] for r in rows]} | |
| raise ValueError("unsupported answer file type " + ext) | |
| def table_cols(tab, want): | |
| head = tab["header"] | |
| rows = tab["rows"] | |
| if head is None: | |
| return None | |
| idx = {w: head.index(w) for w in want if w in head} | |
| return idx, rows | |
| def to_tracks(x): | |
| if isinstance(x, dict) and "rows" in x: | |
| cols = table_cols(x, ["id", "t", "frame", "x", "y", "z"]) | |
| if cols is None: | |
| arr = [[float(c) for c in r] for r in x["rows"]] | |
| return {"0": arr} | |
| idx, rows = cols | |
| tk = "t" if "t" in idx else "frame" | |
| dims = [d for d in ("x", "y", "z") if d in idx] | |
| out = {} | |
| for r in rows: | |
| k = r[idx["id"]] if "id" in idx else "0" | |
| out.setdefault(str(k), []).append([float(r[idx[tk]])] + [float(r[idx[d]]) for d in dims]) | |
| return out | |
| if isinstance(x, dict): | |
| return {str(k): to_points(v) for k, v in x.items()} | |
| if isinstance(x, (list, np.ndarray)): | |
| return {"0": to_points(x)} | |
| return {} | |
| def to_points(v): | |
| out = [] | |
| for p in v if v is not None else []: | |
| if isinstance(p, dict): | |
| keys = [k for k in ("t", "frame", "x", "y", "z") if k in p] | |
| out.append([float(p[k]) for k in keys]) | |
| else: | |
| out.append([float(c) for c in p]) | |
| return out | |
| def track_score(gt, pr, tau): | |
| if not gt: | |
| return 0.0 | |
| if not pr: | |
| return 0.0 | |
| pr = sorted(pr, key=lambda r: r[0]) | |
| pt = np.array([r[0] for r in pr]) | |
| pv = np.array([r[1:] for r in pr]) | |
| tot = 0.0 | |
| for r in gt: | |
| t, g = r[0], np.array(r[1:]) | |
| if t < pt[0] - 1e-9 or t > pt[-1] + 1e-9: | |
| continue | |
| p = np.array([np.interp(t, pt, pv[:, j]) for j in range(pv.shape[1])]) | |
| if len(p) < len(g): | |
| continue | |
| tot += s_of_e(float(np.linalg.norm(p[:len(g)] - g)) / tau) | |
| return tot / len(gt) | |
| def score_trajectory(pred, gt, tol): | |
| from scipy.optimize import linear_sum_assignment | |
| tau = float(tol["value"]) | |
| G, P = to_tracks(gt), to_tracks(pred) | |
| if not G: | |
| return 0.0, {} | |
| gk, pk = list(G), list(P) | |
| if not pk: | |
| return 0.0, {"matched": 0} | |
| if len(gk) == 1 and len(pk) == 1: | |
| s = track_score(G[gk[0]], P[pk[0]], tau) | |
| return s, {"track": round(s, 3)} | |
| S = np.array([[track_score(G[g], P[p], tau) for p in pk] for g in gk]) | |
| r, c = linear_sum_assignment(-S) | |
| matched = float(S[r, c].sum()) | |
| denom = max(len(gk), len(pk)) if tol.get("penalize_extra", True) else len(gk) | |
| return matched / denom, {"per_track": {gk[i]: round(float(S[i, j]), 3) for i, j in zip(r, c)}, "n_gt": len(gk), "n_pred": len(pk)} | |
| def to_lines(x): | |
| if isinstance(x, dict) and "rows" in x: | |
| cols = table_cols(x, ["id", "x", "y", "z"]) | |
| if cols is None: | |
| return [[[float(c) for c in r] for r in x["rows"]]] | |
| idx, rows = cols | |
| dims = [d for d in ("x", "y", "z") if d in idx] | |
| out = {} | |
| for r in rows: | |
| out.setdefault(r[idx["id"]] if "id" in idx else "0", []).append([float(r[idx[d]]) for d in dims]) | |
| return list(out.values()) | |
| if isinstance(x, dict): | |
| return [to_points(v) for v in x.values()] | |
| if isinstance(x, np.ndarray): | |
| x = x.tolist() | |
| if isinstance(x, list) and x and isinstance(x[0], (list, tuple)) and x[0] and isinstance(x[0][0], (list, tuple, dict)): | |
| return [to_points(v) for v in x] | |
| return [to_points(x)] | |
| def densify(lines, step): | |
| pts = [] | |
| for L in lines: | |
| L = np.array(L, float) | |
| if len(L) == 1: | |
| pts.append(L) | |
| continue | |
| for a, b in zip(L[:-1], L[1:]): | |
| n = max(1, int(math.ceil(np.linalg.norm(b - a) / step))) | |
| pts.append(a + (b - a) * np.linspace(0, 1, n, endpoint=False)[:, None]) | |
| pts.append(L[-1:]) | |
| return np.vstack(pts) if pts else np.zeros((0, 2)) | |
| def score_polyline(pred, gt, tol): | |
| from scipy.spatial import cKDTree | |
| tau = float(tol["value"]) | |
| G, P = to_lines(gt), to_lines(pred) | |
| G, P = [L for L in G if L], [L for L in P if L] | |
| if not G or not P: | |
| return 0.0, {} | |
| dim = min(len(G[0][0]), len(P[0][0])) | |
| g = densify([[p[:dim] for p in L] for L in G], tau / 4) | |
| p = densify([[q[:dim] for q in L] for L in P], tau / 4) | |
| dg, _ = cKDTree(p).query(g) | |
| dp, _ = cKDTree(g).query(p) | |
| recall = float(np.mean([s_of_e(d / tau) for d in dg])) | |
| precision = float(np.mean([s_of_e(d / tau) for d in dp])) | |
| f = 0.0 if recall + precision == 0 else 2 * recall * precision / (recall + precision) | |
| return f, {"recall": round(recall, 3), "precision": round(precision, 3), | |
| "mean_dist_gt_to_pred": round(float(dg.mean()), 2)} | |
| def as_mask(x): | |
| if isinstance(x, dict) and "rows" in x: | |
| x = [[float(c) for c in r] for r in x["rows"]] | |
| a = np.asarray(x) | |
| if a.ndim == 3 and a.shape[-1] in (3, 4): | |
| a = a[..., 0] | |
| return a | |
| def score_mask(pred, gt, tol): | |
| thr = float(tol.get("value", 0.5)) | |
| metric = tol.get("metric", "iou") | |
| G, P = as_mask(gt), as_mask(pred) | |
| if G.shape != P.shape: | |
| return 0.0, {"error": f"shape {P.shape} != {G.shape}"} | |
| classes = tol.get("classes") | |
| if classes is None: | |
| classes = [None] | |
| vals = {} | |
| for c in classes: | |
| g = (G > 0) if c is None else (G == c) | |
| p = (P > 0) if c is None else (P == c) | |
| inter, union, tot = np.logical_and(g, p).sum(), np.logical_or(g, p).sum(), g.sum() + p.sum() | |
| if union == 0: | |
| m = 1.0 | |
| elif metric == "dice": | |
| m = 2 * inter / tot | |
| else: | |
| m = inter / union | |
| vals["all" if c is None else str(c)] = float(m) | |
| s = float(np.mean([min(1.0, v / thr) for v in vals.values()])) | |
| return s, {metric: {k: round(v, 3) for k, v in vals.items()}} | |
| def to_series(x): | |
| if isinstance(x, dict) and "rows" in x: | |
| cols = table_cols(x, ["t", "y", "value"]) | |
| if cols is None: | |
| arr = [[float(c) for c in r] for r in x["rows"]] | |
| else: | |
| idx, rows = cols | |
| yk = "y" if "y" in idx else "value" | |
| arr = [[float(r[idx["t"]]), float(r[idx[yk]])] for r in rows] | |
| elif isinstance(x, dict) and "t" in x: | |
| arr = list(zip(map(float, x["t"]), map(float, x.get("y", x.get("value"))))) | |
| else: | |
| arr = [[float(a), float(b)] for a, b in x] | |
| arr = sorted(arr) | |
| return np.array([a for a, _ in arr]), np.array([b for _, b in arr]) | |
| def score_timeseries(pred, gt, tol): | |
| gt_t, gt_y = to_series(gt) | |
| try: | |
| pt, py = to_series(pred) | |
| except Exception: | |
| return 0.0, {} | |
| if len(pt) == 0: | |
| return 0.0, {} | |
| v, mode = float(tol["value"]), tol.get("mode", "abs") | |
| floor = float(tol.get("floor", 0.0)) | |
| tot = 0.0 | |
| for t, y in zip(gt_t, gt_y): | |
| if t < pt[0] - 1e-9 or t > pt[-1] + 1e-9: | |
| continue | |
| p = float(np.interp(t, pt, py)) | |
| tau = v if mode == "abs" else max(abs(y) * v, floor, 1e-12) | |
| tot += s_of_e(abs(p - y) / tau) | |
| return tot / len(gt_t), {} | |
| def score_edges(pred, gt, tol): | |
| directed = bool(tol.get("directed", False)) | |
| def norm(es): | |
| out = set() | |
| for e in es or []: | |
| if not isinstance(e, (list, tuple)) or len(e) != 2: | |
| continue | |
| a, b = str(e[0]).strip().lower(), str(e[1]).strip().lower() | |
| out.add((a, b) if directed else tuple(sorted((a, b)))) | |
| return out | |
| if isinstance(pred, dict) and "rows" in pred: | |
| pred = [r[:2] for r in pred["rows"]] | |
| G, P = norm(gt), norm(pred) | |
| if not G and not P: | |
| return 1.0, {} | |
| tp = len(G & P) | |
| if tp == 0: | |
| return 0.0, {"tp": 0, "n_gt": len(G), "n_pred": len(P)} | |
| pr, rc = tp / len(P), tp / len(G) | |
| return 2 * pr * rc / (pr + rc), {"tp": tp, "n_gt": len(G), "n_pred": len(P)} | |
| def score_struct(pred, gt, tol, pred_dir=None, gt_dir=None): | |
| try: | |
| gt = resolve(gt, gt_dir) | |
| except Exception as e: | |
| return 0.0, {"error": "gt: " + str(e)[:200]} | |
| try: | |
| pred = resolve(pred, pred_dir) | |
| except Exception as e: | |
| return 0.0, {"error": "pred: " + str(e)[:200]} | |
| if pred is None: | |
| return 0.0, {} | |
| f = {"trajectory": score_trajectory, "polyline": score_polyline, "mask": score_mask, | |
| "timeseries": score_timeseries, "edges": score_edges}[tol["type"]] | |
| try: | |
| return f(pred, gt, tol) | |
| except Exception as e: | |
| return 0.0, {"error": type(e).__name__ + ": " + str(e)[:200]} | |