|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from urllib.parse import parse_qs, quote, urljoin, urlparse |
| 4 | + |
| 5 | +import pandas as pd |
| 6 | +import requests |
| 7 | +from tqdm.auto import tqdm |
| 8 | + |
| 9 | + |
| 10 | +def get_roi_name_from_api_url(api_url: str) -> str: |
| 11 | + """Extract ROI name from the ROI API URL query parameter ``name``.""" |
| 12 | + p = urlparse(api_url) |
| 13 | + qs = parse_qs(p.query) |
| 14 | + roi_name = (qs.get("name") or [None])[0] |
| 15 | + if not roi_name: |
| 16 | + raise ValueError("Could not find 'name' parameter in the ROI API URL.") |
| 17 | + return roi_name |
| 18 | + |
| 19 | + |
| 20 | +def load_roi_api(api_url: str) -> pd.DataFrame: |
| 21 | + """Load ROI selections from the surface-viewer ROI API into a DataFrame.""" |
| 22 | + r = requests.get(api_url, timeout=60) |
| 23 | + r.raise_for_status() |
| 24 | + data = r.json() |
| 25 | + selections = data.get("selections", []) |
| 26 | + df = pd.DataFrame(selections) |
| 27 | + |
| 28 | + if df.empty: |
| 29 | + return df |
| 30 | + |
| 31 | + for c in ["row", "col"]: |
| 32 | + if c in df.columns: |
| 33 | + df[c] = df[c].astype("int64") |
| 34 | + |
| 35 | + for c in ["srcJson", "basename", "foldername"]: |
| 36 | + if c in df.columns: |
| 37 | + df[c] = df[c].astype("string") |
| 38 | + |
| 39 | + return df |
| 40 | + |
| 41 | + |
| 42 | +def infer_dataset_base_from_api(api_url: str) -> str: |
| 43 | + """Infer the dataset base URL ending in ``/`` from an ROI API URL.""" |
| 44 | + p = urlparse(api_url) |
| 45 | + qs = parse_qs(p.query) |
| 46 | + dataset = (qs.get("dataset") or [None])[0] |
| 47 | + if not dataset: |
| 48 | + raise ValueError("Could not find 'dataset' parameter in the API URL.") |
| 49 | + |
| 50 | + root = f"{p.scheme}://{p.netloc}/surface-viewer/data/" |
| 51 | + dataset_encoded = quote(dataset, safe="") |
| 52 | + return urljoin(root, dataset_encoded + "/") |
| 53 | + |
| 54 | + |
| 55 | +def add_json_urls(df: pd.DataFrame, api_url: str) -> pd.DataFrame: |
| 56 | + """Add a ``json_url`` column by resolving ``srcJson`` against the dataset base.""" |
| 57 | + if df.empty: |
| 58 | + df = df.copy() |
| 59 | + df["json_url"] = pd.Series(dtype="string") |
| 60 | + return df |
| 61 | + |
| 62 | + dataset_base = infer_dataset_base_from_api(api_url) |
| 63 | + df = df.copy() |
| 64 | + df["json_url"] = df["srcJson"].apply(lambda p: urljoin(dataset_base, str(p))) |
| 65 | + return df |
| 66 | + |
| 67 | + |
| 68 | +def _new_session() -> requests.Session: |
| 69 | + s = requests.Session() |
| 70 | + s.headers.update({"User-Agent": "eds-demo-notebook/0.1"}) |
| 71 | + return s |
| 72 | + |
| 73 | + |
| 74 | +def fetch_json_items(url: str, session: requests.Session | None = None) -> list: |
| 75 | + """GET a JSON file and return a list of records from either a list or ``{'items': ...}``.""" |
| 76 | + session = session or _new_session() |
| 77 | + try: |
| 78 | + r = session.get(url, timeout=60) |
| 79 | + r.raise_for_status() |
| 80 | + data = r.json() |
| 81 | + if isinstance(data, dict) and isinstance(data.get("items"), list): |
| 82 | + return data["items"] |
| 83 | + if isinstance(data, list): |
| 84 | + return data |
| 85 | + return [] |
| 86 | + except Exception: |
| 87 | + return [] |
| 88 | + |
| 89 | + |
| 90 | +def build_spectrum_index( |
| 91 | + urls: list[str], |
| 92 | + *, |
| 93 | + progress: bool = True, |
| 94 | + session: requests.Session | None = None, |
| 95 | +) -> dict[tuple[str, int, int], list[int]]: |
| 96 | + """Build a lookup ``(json_url, row, col) -> spectrum`` by reading each JSON file once.""" |
| 97 | + session = session or _new_session() |
| 98 | + index: dict[tuple[str, int, int], list[int]] = {} |
| 99 | + |
| 100 | + for url in tqdm(urls, desc="Downloading JSON files", disable=not progress): |
| 101 | + items = fetch_json_items(url, session) |
| 102 | + for rec in items: |
| 103 | + r = rec.get("rownum", rec.get("row")) |
| 104 | + c = rec.get("colnum", rec.get("col")) |
| 105 | + spec = rec.get("aggregatedspectrum") or rec.get("aggregatedSpectrum") or rec.get("spectrum") |
| 106 | + if r is None or c is None or spec is None: |
| 107 | + continue |
| 108 | + try: |
| 109 | + key = (url, int(r), int(c)) |
| 110 | + index[key] = [int(x) for x in spec] |
| 111 | + except Exception: |
| 112 | + pass |
| 113 | + |
| 114 | + return index |
| 115 | + |
| 116 | + |
| 117 | +def attach_spectra( |
| 118 | + df: pd.DataFrame, |
| 119 | + index: dict[tuple[str, int, int], list[int]], |
| 120 | + *, |
| 121 | + progress: bool = True, |
| 122 | +) -> pd.DataFrame: |
| 123 | + """Add a ``spectrum`` column to a DataFrame using the pre-built spectrum index.""" |
| 124 | + |
| 125 | + def pick(row): |
| 126 | + return index.get((row["json_url"], int(row["row"]), int(row["col"])), None) |
| 127 | + |
| 128 | + df = df.copy() |
| 129 | + if progress: |
| 130 | + tqdm.pandas(desc="Indexing spectra") |
| 131 | + df["spectrum"] = df.progress_apply(pick, axis=1) |
| 132 | + else: |
| 133 | + df["spectrum"] = df.apply(pick, axis=1) |
| 134 | + return df |
| 135 | + |
| 136 | + |
| 137 | +def get_selection_grid_url(api_url: str) -> str: |
| 138 | + """Return the first matching selection-grid JSON URL from the dataset overlays folder.""" |
| 139 | + dataset_base = infer_dataset_base_from_api(api_url) |
| 140 | + candidates = [ |
| 141 | + "overlays/selection-grid.json", |
| 142 | + "overlays/selection_grid.json", |
| 143 | + "selection-grid.json", |
| 144 | + "selection_grid.json", |
| 145 | + ] |
| 146 | + session = _new_session() |
| 147 | + for rel in candidates: |
| 148 | + url = urljoin(dataset_base, rel) |
| 149 | + try: |
| 150 | + r = session.get(url, timeout=30) |
| 151 | + if r.ok: |
| 152 | + return url |
| 153 | + except Exception: |
| 154 | + pass |
| 155 | + raise FileNotFoundError("Could not find selection-grid.json in the dataset overlays folder.") |
| 156 | + |
| 157 | + |
| 158 | +def load_all_cells_from_selection_grid(api_url: str) -> pd.DataFrame: |
| 159 | + """Load the full cell grid from ``overlays/selection-grid.json`` into a DataFrame.""" |
| 160 | + grid_url = get_selection_grid_url(api_url) |
| 161 | + session = _new_session() |
| 162 | + items = fetch_json_items(grid_url, session) |
| 163 | + |
| 164 | + rows = [] |
| 165 | + for rec in items: |
| 166 | + if rec.get("type") != "rect": |
| 167 | + continue |
| 168 | + r = rec.get("rownum", rec.get("row")) |
| 169 | + c = rec.get("colnum", rec.get("col")) |
| 170 | + src = rec.get("srcJson") |
| 171 | + if r is None or c is None or src is None: |
| 172 | + continue |
| 173 | + rows.append({ |
| 174 | + "row": int(r), |
| 175 | + "col": int(c), |
| 176 | + "srcJson": str(src), |
| 177 | + "basename": rec.get("basename"), |
| 178 | + "label": rec.get("label"), |
| 179 | + "x": rec.get("x"), |
| 180 | + "y": rec.get("y"), |
| 181 | + "width": rec.get("width"), |
| 182 | + "height": rec.get("height"), |
| 183 | + }) |
| 184 | + |
| 185 | + df = pd.DataFrame(rows) |
| 186 | + if df.empty: |
| 187 | + return df |
| 188 | + for c in ["srcJson", "basename", "label"]: |
| 189 | + if c in df.columns: |
| 190 | + df[c] = df[c].astype("string") |
| 191 | + df = add_json_urls(df, api_url) |
| 192 | + df = df.drop_duplicates(subset=["json_url", "row", "col"]).reset_index(drop=True) |
| 193 | + return df |
0 commit comments