| from __future__ import annotations |
|
|
| import json |
| from pathlib import Path |
| from typing import Iterable, List, Tuple |
|
|
| import numpy as np |
|
|
|
|
| def load_smiles(path: str | Path) -> List[str]: |
| path = Path(path) |
| if path.suffix.lower() in {".tsv", ".csv"}: |
| import pandas as pd |
|
|
| sep = "\t" if path.suffix.lower() == ".tsv" else "," |
| df = pd.read_csv(path, sep=sep) |
| if "smiles" not in df.columns: |
| raise ValueError(f"{path} does not have a 'smiles' column") |
| return df["smiles"].dropna().astype(str).tolist() |
| if path.suffix.lower() == ".parquet": |
| import pandas as pd |
|
|
| df = pd.read_parquet(path) |
| if "smiles" not in df.columns: |
| raise ValueError(f"{path} does not have a 'smiles' column") |
| return df["smiles"].dropna().astype(str).tolist() |
| with path.open("r", encoding="utf-8") as f: |
| return [line.strip() for line in f if line.strip()] |
|
|
|
|
| def save_smiles(path: str | Path, smiles: Iterable[str]) -> None: |
| path = Path(path) |
| with path.open("w", encoding="utf-8") as f: |
| for smi in smiles: |
| f.write(f"{smi}\n") |
|
|
|
|
| def load_embeddings(path: str | Path) -> np.ndarray: |
| path = Path(path) |
| if path.suffix == ".npz": |
| data = np.load(path) |
| if "embeddings" not in data: |
| raise ValueError(f"Missing 'embeddings' in {path}") |
| return data["embeddings"] |
| return np.load(path) |
|
|
|
|
| def save_embeddings(path: str | Path, embeddings: np.ndarray) -> None: |
| path = Path(path) |
| np.save(path, embeddings.astype(np.float32)) |
|
|
|
|
| def load_jsonl(path: str | Path) -> List[dict]: |
| path = Path(path) |
| rows: List[dict] = [] |
| with path.open("r", encoding="utf-8") as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| rows.append(json.loads(line)) |
| return rows |
|
|
|
|
| def save_jsonl(path: str | Path, rows: Iterable[dict]) -> None: |
| path = Path(path) |
| with path.open("w", encoding="utf-8") as f: |
| for row in rows: |
| f.write(json.dumps(row, ensure_ascii=True) + "\n") |
|
|
|
|
| def ensure_dir(path: str | Path) -> Path: |
| path = Path(path) |
| path.mkdir(parents=True, exist_ok=True) |
| return path |
|
|
|
|
| def to_numpy(x) -> np.ndarray: |
| if isinstance(x, np.ndarray): |
| return x |
| return np.asarray(x) |
|
|
|
|
| def chunked(items: List[str], batch_size: int) -> Iterable[Tuple[int, List[str]]]: |
| for i in range(0, len(items), batch_size): |
| yield i, items[i : i + batch_size] |
|
|