sipena / services /artifacts.py
NabilHzs's picture
Deploy backend: FastAPI supervisor recommender
15d943c
Raw History Blame Contribute Delete
20.5 kB
from __future__ import annotations
import logging
import os
import re
from dataclasses import dataclass
from typing import TYPE_CHECKING
import numpy as np
import pandas as pd
if TYPE_CHECKING:
from sentence_transformers import SentenceTransformer
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class ArtifactStore:
sbert: "SentenceTransformer"
embeddings: np.ndarray
doc_embeddings: np.ndarray
doc_embeddings_norms: np.ndarray
metadata: pd.DataFrame
bt_en: object | None
bt_id: object | None
tfidf_matrix: object | None
tfidf_feature_names: np.ndarray | None
tfidf_unique_clusters: list[int] | None
embeddings_shape: tuple[int, int]
lecturer_col: str
year_col: str | None
topic_col: str | None
topic_ids: np.ndarray | None
topic_centroids: np.ndarray | None
topic_centroids_norms: np.ndarray | None
lecturer_topic_avg: dict[int, dict[str, np.ndarray]] | None
topic_lecturer_indices: dict[int, dict[str, list[int]]] | None
topic_pub_indices: dict[int, list[int]] | None
sbert_id: object | None = None
id_topic_offset: int = 0
lang_col: str | None = None
publications_df: pd.DataFrame | None = None
lecturer_profiles: pd.DataFrame | None = None
publication_ids: np.ndarray | None = None
def _as_1d_float32(vec: object, *, name: str) -> np.ndarray:
arr = np.asarray(vec, dtype=np.float32)
if arr.ndim != 1:
raise ValueError(f"{name} harus 1D vector. Dapat shape={arr.shape}")
return arr
def _load_tfidf_artifacts(artifacts_dir: str) -> tuple[object | None, np.ndarray | None, list[int] | None]:
tfidf_matrix_path = os.path.join(artifacts_dir, "tfidf_matrix.npz")
feature_names_path = os.path.join(artifacts_dir, "feature_names.npy")
unique_clusters_path = os.path.join(artifacts_dir, "unique_clusters.json")
if not (os.path.exists(tfidf_matrix_path) and os.path.exists(feature_names_path) and os.path.exists(unique_clusters_path)):
return None, None, None
import json
import scipy.sparse # type: ignore
tfidf_matrix = scipy.sparse.load_npz(tfidf_matrix_path)
feature_names = np.load(feature_names_path, allow_pickle=True)
with open(unique_clusters_path, "r", encoding="utf-8") as f:
unique_clusters = json.load(f)
clusters_int = [int(x) for x in unique_clusters]
return tfidf_matrix, np.asarray(feature_names, dtype=object), clusters_int
def _load_bertopic_models(artifacts_dir: str) -> tuple[object | None, object | None]:
bt_en = None
bt_id = None
try:
from bertopic import BERTopic # type: ignore
except ImportError:
return None, None
bt_en_path = os.path.join(artifacts_dir, "bt_en")
bt_id_path = os.path.join(artifacts_dir, "bt_id")
if os.path.exists(bt_en_path):
try:
bt_en = BERTopic.load(bt_en_path)
logger.info("Loaded BERTopic EN model from %s", bt_en_path)
except Exception as e:
logger.warning("Failed to load BERTopic EN: %s", e)
if os.path.exists(bt_id_path):
try:
bt_id = BERTopic.load(bt_id_path)
logger.info("Loaded BERTopic ID model from %s", bt_id_path)
except Exception as e:
logger.warning("Failed to load BERTopic ID: %s", e)
return bt_en, bt_id
def _load_notebook_export_artifacts(artifacts_dir: str) -> ArtifactStore:
from sentence_transformers import SentenceTransformer
model_dir = os.getenv("SBERT_MODEL_DIR", "").strip()
if not model_dir:
raise ValueError("SBERT_MODEL_DIR wajib di-set untuk mode NOTEBOOK_EXPORT")
sbert = SentenceTransformer(model_dir)
lecturer_topic_grouped_path = os.path.join(artifacts_dir, "lecturer_topic_grouped.pkl")
lecturer_embedding_data_path = os.path.join(artifacts_dir, "lecturer_embedding_data.pkl")
if not os.path.exists(lecturer_topic_grouped_path):
raise FileNotFoundError(f"lecturer_topic_grouped.pkl tidak ditemukan di: {lecturer_topic_grouped_path}")
if not os.path.exists(lecturer_embedding_data_path):
raise FileNotFoundError(f"lecturer_embedding_data.pkl tidak ditemukan di: {lecturer_embedding_data_path}")
lecturer_topic_grouped = pd.read_pickle(lecturer_topic_grouped_path)
lecturer_embedding_data = pd.read_pickle(lecturer_embedding_data_path)
required_ltg = {"cluster_label", "nama_dosen", "average_embedding"}
missing_ltg = required_ltg - set(lecturer_topic_grouped.columns)
if missing_ltg:
raise ValueError(f"Kolom wajib hilang di lecturer_topic_grouped.pkl: {sorted(missing_ltg)}")
required_led = {"cluster_label", "nama_dosen", "embedding"}
missing_led = required_led - set(lecturer_embedding_data.columns)
if missing_led:
raise ValueError(f"Kolom wajib hilang di lecturer_embedding_data.pkl: {sorted(missing_led)}")
lecturer_topic_grouped = lecturer_topic_grouped.copy()
lecturer_topic_grouped["cluster_label"] = pd.to_numeric(lecturer_topic_grouped["cluster_label"], errors="coerce")
lecturer_topic_grouped = lecturer_topic_grouped.dropna(subset=["cluster_label"])
lecturer_topic_grouped["cluster_label"] = lecturer_topic_grouped["cluster_label"].astype(int)
lecturer_embedding_data = lecturer_embedding_data.copy()
lecturer_embedding_data["cluster_label"] = pd.to_numeric(lecturer_embedding_data["cluster_label"], errors="coerce")
lecturer_embedding_data = lecturer_embedding_data.dropna(subset=["cluster_label"])
lecturer_embedding_data["cluster_label"] = lecturer_embedding_data["cluster_label"].astype(int)
topic_ids_list = sorted({int(x) for x in lecturer_topic_grouped["cluster_label"].unique().tolist()})
topic_ids = np.asarray(topic_ids_list, dtype=np.int32)
# lecturer_topic_avg from lecturer_topic_grouped
lecturer_topic_avg: dict[int, dict[str, np.ndarray]] = {}
for tid in topic_ids_list:
sub = lecturer_topic_grouped[lecturer_topic_grouped["cluster_label"] == int(tid)]
if sub.empty:
continue
# Accumulate per-individual-lecturer embeddings, splitting combined names
acc: dict[str, list[np.ndarray]] = {}
for raw_name, raw_vec in zip(
sub["nama_dosen"].astype(str).tolist(),
sub["average_embedding"].tolist(),
):
vec = _as_1d_float32(raw_vec, name=f"average_embedding topic={tid}")
for ind_name in (_split_lecturers(raw_name) or [raw_name.strip()]):
acc.setdefault(ind_name, []).append(vec)
lecturer_names_split = list(acc.keys())
avg_vecs_split = np.stack(
[np.stack(vecs, axis=0).mean(axis=0) for vecs in acc.values()],
axis=0,
).astype(np.float32, copy=False)
avg_norms_split = np.linalg.norm(avg_vecs_split, axis=1)
avg_norms_split = np.maximum(avg_norms_split, 1e-12).astype(np.float32, copy=False)
lecturer_topic_avg[int(tid)] = {
"lecturers": np.asarray(lecturer_names_split, dtype=object),
"avg_vecs": avg_vecs_split,
"avg_norms": avg_norms_split,
}
# topic centroids = mean of lecturer average embeddings (matches notebook centroid-from-avg approximation)
dim = int(next(iter(lecturer_topic_avg.values()))["avg_vecs"].shape[1]) if lecturer_topic_avg else 0
centroids = np.zeros((int(topic_ids.shape[0]), dim), dtype=np.float32)
topic_pub_indices: dict[int, list[int]] = {}
for i, tid in enumerate(topic_ids_list):
if int(tid) not in lecturer_topic_avg:
continue
centroids[i] = lecturer_topic_avg[int(tid)]["avg_vecs"].mean(axis=0)
topic_pub_indices[int(tid)] = []
topic_centroids = centroids
topic_centroids_norms = np.linalg.norm(topic_centroids, axis=1)
topic_centroids_norms = np.maximum(topic_centroids_norms, 1e-12).astype(np.float32, copy=False)
# Build doc_embeddings from lecturer_embedding_data (publication-level)
doc_embeddings_list = [_as_1d_float32(v, name="embedding") for v in lecturer_embedding_data["embedding"].tolist()]
doc_embeddings = np.stack(doc_embeddings_list, axis=0).astype(np.float32, copy=False)
doc_norms = np.linalg.norm(doc_embeddings, axis=1)
doc_norms = np.maximum(doc_norms, 1e-12).astype(np.float32, copy=False)
# Build indices for score2: topic -> lecturer -> pub indices
topic_lecturer_indices: dict[int, dict[str, list[int]]] = {}
for tid in topic_ids_list:
sub = lecturer_embedding_data[lecturer_embedding_data["cluster_label"] == int(tid)]
if sub.empty:
continue
idx_map: dict[str, list[int]] = {}
for pub_idx, name in zip(sub.index.to_numpy().tolist(), sub["nama_dosen"].astype(str).tolist()):
for lecturer_name in (_split_lecturers(name) or [name.strip()]):
idx_map.setdefault(lecturer_name, []).append(int(pub_idx))
topic_lecturer_indices[int(tid)] = idx_map
# Remap publication indices to 0..n-1 (since sub.index may not be contiguous)
# Create a stable order and rebuild maps
old_indices = lecturer_embedding_data.index.to_numpy(dtype=np.int64)
reindex = {int(old): int(new) for new, old in enumerate(old_indices.tolist())}
lecturer_embedding_data = lecturer_embedding_data.reset_index(drop=True)
topic_lecturer_indices_normed: dict[int, dict[str, list[int]]] = {}
topic_pub_indices_normed: dict[int, list[int]] = {}
for tid, m in topic_lecturer_indices.items():
nm: dict[str, list[int]] = {}
pubs: list[int] = []
for name, idxs in m.items():
new_idxs = [reindex[int(i)] for i in idxs]
nm[name] = new_idxs
pubs.extend(new_idxs)
topic_lecturer_indices_normed[int(tid)] = nm
topic_pub_indices_normed[int(tid)] = sorted(set(pubs))
tfidf_matrix, feature_names, unique_clusters = _load_tfidf_artifacts(artifacts_dir)
# Minimal metadata to keep interface consistent
metadata = lecturer_embedding_data[["nama_dosen", "cluster_label"]].copy()
lecturer_col = "nama_dosen"
topic_col = "cluster_label"
bt_en, bt_id = _load_bertopic_models(artifacts_dir)
return ArtifactStore(
sbert=sbert,
embeddings=doc_embeddings,
doc_embeddings=doc_embeddings,
doc_embeddings_norms=doc_norms,
metadata=metadata,
bt_en=bt_en,
bt_id=bt_id,
tfidf_matrix=tfidf_matrix,
tfidf_feature_names=feature_names,
tfidf_unique_clusters=unique_clusters,
embeddings_shape=(int(doc_embeddings.shape[0]), int(doc_embeddings.shape[1])),
lecturer_col=lecturer_col,
year_col=None,
topic_col=topic_col,
topic_ids=topic_ids,
topic_centroids=topic_centroids,
topic_centroids_norms=topic_centroids_norms,
lecturer_topic_avg=lecturer_topic_avg,
topic_lecturer_indices=topic_lecturer_indices_normed,
topic_pub_indices=topic_pub_indices_normed,
)
def _first_existing_col(df: pd.DataFrame, candidates: list[str]) -> str | None:
lower = {c.lower(): c for c in df.columns}
for cand in candidates:
if cand.lower() in lower:
return lower[cand.lower()]
return None
def _split_lecturers(value: object) -> list[str]:
if value is None:
return []
s = str(value).strip()
if not s or s.lower() in {"nan", "none"}:
return []
s = s.replace("[", " ").replace("]", " ").replace("(", " ").replace(")", " ")
s = s.replace("\"", " ").replace("'", " ")
splitter = r"\s*(?:;|\||,|&|\band\b|\bdan\b)\s*"
parts = [p.strip() for p in re.split(splitter, s) if p.strip()]
if not parts:
parts = [s]
cleaned: list[str] = []
seen: set[str] = set()
for p in parts:
name = " ".join(p.split()).strip()
key = name.lower()
if not name or key in {"nan", "none"}:
continue
if key in seen:
continue
seen.add(key)
cleaned.append(name)
return cleaned
def load_artifacts(artifacts_dir: str, data_dir: str) -> ArtifactStore:
mode = os.getenv("ARTIFACTS_MODE", "DEFAULT").strip().upper()
if mode in {"NOTEBOOK", "NOTEBOOK_EXPORT", "PKL"}:
return _load_notebook_export_artifacts(artifacts_dir=artifacts_dir)
from sentence_transformers import SentenceTransformer
# Load topic_info.json for model names and offset
sbert_id = None
id_topic_offset = 0
topic_info_path = os.path.join(artifacts_dir, "topic_info.json")
en_model_name = os.getenv("SBERT_MODEL", "all-mpnet-base-v2")
id_model_name = ""
if os.path.exists(topic_info_path):
import json as _json
with open(topic_info_path, "r", encoding="utf-8") as f:
topic_info = _json.load(f)
en_model_name = topic_info.get("en", {}).get("model_name", en_model_name)
id_model_name = topic_info.get("id", {}).get("model_name", "")
id_topic_offset = topic_info.get("id", {}).get("id_topic_offset", 0)
model_dir = os.getenv("SBERT_MODEL_DIR", "").strip()
if model_dir:
sbert = SentenceTransformer(model_dir)
else:
sbert = SentenceTransformer(en_model_name)
if id_model_name:
try:
sbert_id = SentenceTransformer(id_model_name)
logger.info("Loaded split-lang ID model: %s (offset=%d)", id_model_name, id_topic_offset)
except Exception as e:
logger.warning("Failed to load ID SBERT model %s: %s", id_model_name, e)
embeddings_path = os.path.join(artifacts_dir, "embeddings.npy")
if not os.path.exists(embeddings_path):
raise FileNotFoundError(
f"embeddings.npy tidak ditemukan di: {embeddings_path}. "
"Taruh file embeddings.npy di backend/models/ atau set ARTIFACTS_DIR."
)
embeddings = np.load(embeddings_path, mmap_mode="r")
if embeddings.ndim not in (2, 3):
raise ValueError(
"embeddings.npy harus 2D (n_docs, dim) atau 3D (n_docs, seq_len, dim). "
f"Dapat shape={embeddings.shape}"
)
if embeddings.ndim == 2:
doc_embeddings = embeddings.astype(np.float32, copy=False)
else:
doc_embeddings = embeddings.astype(np.float32, copy=False).mean(axis=1)
doc_norms = np.linalg.norm(doc_embeddings, axis=1)
doc_norms = np.maximum(doc_norms, 1e-12).astype(np.float32, copy=False)
# Prefer publications.csv (new structure), fall back to metadata.csv (legacy)
publications_path = os.path.join(data_dir, "publications.csv")
metadata_path = os.path.join(data_dir, "metadata.csv")
data_path = publications_path if os.path.exists(publications_path) else metadata_path
if not os.path.exists(data_path):
raise FileNotFoundError(
f"publications.csv atau metadata.csv tidak ditemukan di: {data_dir}. "
"Taruh file di backend/data/ atau set DATA_DIR."
)
metadata = pd.read_csv(data_path)
if len(metadata) != embeddings.shape[0]:
raise ValueError(
"Panjang data harus sama dengan jumlah baris embeddings.npy. "
f"data_rows={len(metadata)} embeddings_rows={embeddings.shape[0]}"
)
lecturer_col = _first_existing_col(metadata, ["dosen", "lecturer", "supervisor", "name"]) or ""
if not lecturer_col:
raise ValueError(
"Kolom dosen tidak ditemukan di metadata.csv. "
"Coba pakai salah satu nama kolom: dosen/lecturer/supervisor/name"
)
year_col = _first_existing_col(metadata, ["tahun", "year", "pub_year", "publication_year"])
lang_col = _first_existing_col(metadata, ["lang", "lang_group", "language"])
topic_col = _first_existing_col(metadata, [
"s3_topic_reduced", "s3_topic", "topic_id", "topic", "topicid",
])
topic_ids = None
topic_centroids = None
topic_centroids_norms = None
lecturer_topic_avg: dict[int, dict[str, np.ndarray]] | None = None
topic_lecturer_indices: dict[int, dict[str, list[int]]] | None = None
topic_pub_indices: dict[int, list[int]] | None = None
if topic_col is not None:
topic_series = pd.to_numeric(metadata[topic_col], errors="coerce").astype("Int64")
# Exclude noise topic (-1)
valid_mask = topic_series.notna().to_numpy() & (topic_series >= 0).to_numpy()
if valid_mask.any():
valid_topics = topic_series[valid_mask].astype(int).to_numpy()
unique_topics = np.unique(valid_topics)
topic_ids = unique_topics.astype(np.int32, copy=False)
lecturer_topic_avg = {}
topic_lecturer_indices = {}
topic_pub_indices = {}
centroids = np.zeros((topic_ids.shape[0], int(doc_embeddings.shape[1])), dtype=np.float32)
for i, tid in enumerate(topic_ids.tolist()):
topic_mask = (topic_series == int(tid)).to_numpy()
idxs = np.flatnonzero(topic_mask)
if idxs.size == 0:
continue
topic_pub_indices[int(tid)] = idxs.astype(np.int64, copy=False).tolist()
topic_emb = doc_embeddings[idxs].astype(np.float32, copy=False)
centroids[i] = topic_emb.mean(axis=0)
sub_meta = metadata.iloc[idxs]
idx_map: dict[str, list[int]] = {}
for pub_idx, cell in zip(idxs.tolist(), sub_meta[lecturer_col].tolist()):
for lecturer_name in _split_lecturers(cell):
idx_map.setdefault(lecturer_name, []).append(int(pub_idx))
lecturer_names = []
avg_vecs = []
for lecturer_name, pub_indices in idx_map.items():
vec = doc_embeddings[np.asarray(pub_indices, dtype=np.int64)].astype(np.float32, copy=False).mean(axis=0)
lecturer_names.append(str(lecturer_name))
avg_vecs.append(vec)
if lecturer_names:
avg_arr = np.stack(avg_vecs, axis=0).astype(np.float32, copy=False)
avg_norms = np.linalg.norm(avg_arr, axis=1)
avg_norms = np.maximum(avg_norms, 1e-12).astype(np.float32, copy=False)
lecturer_topic_avg[int(tid)] = {
"lecturers": np.asarray(lecturer_names, dtype=object),
"avg_vecs": avg_arr,
"avg_norms": avg_norms,
}
topic_lecturer_indices[int(tid)] = idx_map
topic_centroids = centroids
topic_centroids_norms = np.linalg.norm(topic_centroids, axis=1)
topic_centroids_norms = np.maximum(topic_centroids_norms, 1e-12).astype(np.float32, copy=False)
tfidf_matrix, tfidf_feature_names, tfidf_unique_clusters = _load_tfidf_artifacts(artifacts_dir)
bt_en, bt_id = _load_bertopic_models(artifacts_dir)
# Load new-structure files when available
publications_df = pd.read_csv(publications_path) if os.path.exists(publications_path) else metadata.copy()
lecturer_profiles_path = os.path.join(data_dir, "lecturer_profiles.csv")
lecturer_profiles = pd.read_csv(lecturer_profiles_path) if os.path.exists(lecturer_profiles_path) else None
publication_ids_path = os.path.join(artifacts_dir, "publication_ids.npy")
publication_ids = np.load(publication_ids_path, allow_pickle=True) if os.path.exists(publication_ids_path) else None
return ArtifactStore(
sbert=sbert,
embeddings=embeddings,
doc_embeddings=doc_embeddings,
doc_embeddings_norms=doc_norms,
metadata=metadata,
bt_en=bt_en,
bt_id=bt_id,
tfidf_matrix=tfidf_matrix,
tfidf_feature_names=tfidf_feature_names,
tfidf_unique_clusters=tfidf_unique_clusters,
embeddings_shape=(int(doc_embeddings.shape[0]), int(doc_embeddings.shape[1])),
lecturer_col=lecturer_col,
year_col=year_col,
topic_col=topic_col,
topic_ids=topic_ids,
topic_centroids=topic_centroids,
topic_centroids_norms=topic_centroids_norms,
lecturer_topic_avg=lecturer_topic_avg,
topic_lecturer_indices=topic_lecturer_indices,
topic_pub_indices=topic_pub_indices,
sbert_id=sbert_id,
id_topic_offset=id_topic_offset,
lang_col=lang_col,
publications_df=publications_df,
lecturer_profiles=lecturer_profiles,
publication_ids=publication_ids,
)