Upload 3 files
Browse filesFiles changed (3)
- README.md+10
- app.py+43
- coverage.pyAdded+206
266 unmodified lines267268269266 unmodified linesrecords with the build script (a stand-in replaces only the embedding model) and checks the combined search.`tests/test_extras.py` writes small exports with the real column names, builds them with `build_khazna_extras.py` andchecks units, people counts, theses filters and counts, KU-affiliation filtering, Scopus-only cards and the year rules.266 unmodified lines267268269270271272273274275276277278279266 unmodified linesrecords with the build script (a stand-in replaces only the embedding model) and checks the combined search.`tests/test_extras.py` writes small exports with the real column names, builds them with `build_khazna_extras.py` andchecks units, people counts, theses filters and counts, KU-affiliation filtering, Scopus-only cards and the year rules.## Coverage dashboard (Khazna vs Scopus/SciVal)`libguides/khazna-coverage-dashboard.html` is a separate LibGuides HTML box (not the assistant). It reads`GET /coverage/summary?year=`, `GET /coverage/list?category=&year=&q=&page=` and `GET /coverage/export?category=&year=`(`.xlsx`; `category=all` gives a summary sheet plus one sheet per non-overlapping category). Categories: KU papers inScopus/SciVal; all Khazna outputs; Khazna with / without a KU unit (organisational or managing unit), each split intoKU-affiliated / not KU-affiliated / not checked yet; KU papers missing from Khazna. Built from the data the bot alreadyholds (no Pure or Scopus calls). Open to anyone with the link (no password), by decision of 30 Nov 2026.
439 unmodified lines440441442443444445439 unmodified linesreturn builder.status()@app.get("/stats/publications")def publication_stats():"""All KU publications by year for a dashboard: KU-affiliated records in Khazna (per Scopus/SciVal)439 unmodified lines440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488439 unmodified linesreturn builder.status()# ── Khazna vs Scopus/SciVal coverage dashboard (open to anyone with the link: Nikesh, 30 Nov 2026) ──def _coverage_year(year: str | None) -> int | None:if not year or year in ("all", "0"):return Noneif not year.isdigit() or not 1900 < int(year) < 2100:raise HTTPException(422, "year must be a 4-digit year or 'all'")return int(year)@app.get("/coverage/summary")def coverage_summary(year: str | None = None):import coveragetry:return coverage.summary(_coverage_year(year))except RuntimeError as e:raise HTTPException(503, str(e))@app.get("/coverage/list")def coverage_list(category: str, year: str | None = None, q: str = "", page: int = 1, size: int = 50):import coveragetry:return coverage.page(category, _coverage_year(year), q[:120], page, size)except KeyError:raise HTTPException(422, "unknown category")except RuntimeError as e:raise HTTPException(503, str(e))@app.get("/coverage/export")def coverage_export(category: str = "all", year: str | None = None):import coveragefrom fastapi.responses import Responsetry:data, name = coverage.excel(category, _coverage_year(year))except KeyError:raise HTTPException(422, "unknown category")except RuntimeError as e:raise HTTPException(503, str(e))return Response(data, media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",headers={"Content-Disposition": f'attachment; filename="{name}"'})@app.get("/stats/publications")def publication_stats():"""All KU publications by year for a dashboard: KU-affiliated records in Khazna (per Scopus/SciVal)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""Khazna vs Scopus/SciVal coverage: the figures of the "Khazna vs SciVal" workbook, live from the bot's data.
Categories (all can be limited to one publication year): scopus_ku all KU papers in Scopus/SciVal (stored list: SciVal uploads + Scopus updates) khazna_all all research outputs in Khazna unit_all Khazna records WITH a KU unit (organisational unit or managing unit filled) unit_ku ... with a unit, KU-affiliated per Scopus/SciVal unit_not_ku ... with a unit, NOT KU-affiliated per Scopus/SciVal unit_unchecked ... with a unit, not checked yet (current-year records SciVal/Scopus does not list yet, or no match data) nounit_all / nounit_ku / nounit_not_ku / nounit_unchecked the same WITHOUT a unit missing KU papers in Scopus/SciVal that are not in Khazna
"Not KU-affiliated" means: no match with a KU paper in Scopus/SciVal by Scopus ID or DOI. Records with neithercan land there wrongly; the Excel marks them ("No DOI or Scopus ID").Everything is read from data the bot already holds; nothing calls Pure or Scopus. Counts are as of the last refresh."""from __future__ import annotations
import ioimport threadingfrom pathlib import Path
import pandas as pd
import khazna_index
PORTAL = "https://khazna.ku.ac.ae"
LABELS = { "scopus_ku": "KU papers in Scopus/SciVal", "khazna_all": "All research outputs in Khazna", "unit_all": "In Khazna, with a KU unit", "unit_ku": "With a unit · KU-affiliated", "unit_not_ku": "With a unit · not KU-affiliated", "unit_unchecked": "With a unit · not checked yet", "nounit_all": "In Khazna, without a unit", "nounit_ku": "Without a unit · KU-affiliated", "nounit_not_ku": "Without a unit · not KU-affiliated", "nounit_unchecked": "Without a unit · not checked yet", "missing": "KU papers missing from Khazna",}ORDER = list(LABELS)SHEET = {"scopus_ku": "Scopus-SciVal KU", "khazna_all": "Khazna all", "unit_all": "With unit", "unit_ku": "Unit - KU", "unit_not_ku": "Unit - not KU", "unit_unchecked": "Unit - not checked", "nounit_all": "No unit", "nounit_ku": "No unit - KU", "nounit_not_ku": "No unit - not KU", "nounit_unchecked": "No unit - not checked", "missing": "Missing from Khazna"}
_lock = threading.Lock()_cache: dict = {"key": None}
def _s(df: pd.DataFrame, col: str) -> pd.Series: return df[col].fillna("").astype(str).str.strip() if col in df.columns else pd.Series("", index=df.index)
def _year(df: pd.DataFrame, col: str = "year") -> pd.Series: return pd.to_numeric(df[col], errors="coerce").fillna(0).astype(int) if col in df.columns else pd.Series(0, index=df.index)
def _tables() -> dict: """(khazna, scopus_list, missing) DataFrames in one shape, rebuilt only when the underlying data changes.""" idx, miss, d = khazna_index.INDEX, khazna_index.MISSING, khazna_index.DIRECTORY data = getattr(idx, "_data", None) mdata = getattr(miss, "_data", None) master_f = Path(idx.dir) / "scival" / "scival_ku.parquet" mtime = master_f.stat().st_mtime if master_f.exists() else 0 key = (id(data), id(mdata), id(d.ku_table), mtime) with _lock: if _cache["key"] == key: return _cache if not data: raise RuntimeError("The research-outputs index is not loaded yet.") rec = data[0] kt = d.ku_table if d.ku_table is not None else pd.DataFrame(columns=["uuid", "ku_status", "eid"]) flag = dict(zip(kt.uuid, kt.ku_status)) eid = dict(zip(kt.uuid, kt["eid"].fillna("").astype(str))) if "eid" in kt.columns else {} k = pd.DataFrame({ "uuid": _s(rec, "uuid"), "title": _s(rec, "title"), "year": _year(rec), "type": _s(rec, "type"), "org_units": _s(rec, "org_units"), "department": _s(rec, "department"), "journal": _s(rec, "journal"), "doi": _s(rec, "doi"), }) k["eid"] = k.uuid.map(eid).fillna("") st = k.uuid.map(flag).fillna("") k["ku"] = st.map({"ku": "ku", "not_ku": "not_ku"}).fillna("unchecked") k["has_unit"] = (k.org_units != "") | (k.department != "") k["link"] = PORTAL + "/en/publications/" + k.uuid k["note"] = "" k.loc[(k.doi == "") & (k.eid == ""), "note"] = "No DOI or Scopus ID: affiliation could not be matched"
if master_f.exists(): m = pd.read_parquet(master_f) else: m = pd.DataFrame(columns=["eid", "title", "doi", "year", "type", "journal", "authors", "scopus_url"]) in_k_eid = set(k.eid[k.eid != ""]) in_k_doi = set(k.doi[k.doi != ""]) s = pd.DataFrame({"eid": _s(m, "eid"), "title": _s(m, "title"), "year": _year(m), "type": _s(m, "type"), "journal": _s(m, "journal"), "doi": _s(m, "doi"), "authors": _s(m, "authors")}) s["in_khazna"] = s.eid.isin(in_k_eid) | ((s.doi != "") & s.doi.isin(in_k_doi)) s["link"] = _s(m, "scopus_url") s.loc[s.link == "", "link"] = "https://www.scopus.com/record/display.uri?eid=" + s.eid + "&origin=resultslist"
if mdata: mm = mdata[0] x = pd.DataFrame({"eid": _s(mm, "eid") if "eid" in mm.columns else _s(mm, "uuid"), "title": _s(mm, "title"), "year": _year(mm), "type": _s(mm, "type"), "journal": _s(mm, "journal"), "doi": _s(mm, "doi"), "authors": _s(mm, "authors"), "link": _s(mm, "scopus_url")}) else: x = pd.DataFrame(columns=["eid", "title", "year", "type", "journal", "doi", "authors", "link"]) built = (idx.info or {}).get("built_at", "") if hasattr(idx, "info") else "" _cache.update(key=key, khazna=k, scopus=s, missing=x, as_of={"khazna": built, "ku_flags": d.info.get("ku_affiliation", {}).get("built_at", "") if isinstance(d.info.get("ku_affiliation"), dict) else "", "missing": (miss.info or {}).get("built_at", "") if hasattr(miss, "info") else ""}) return _cache
def _select(category: str, year: int | None) -> tuple[pd.DataFrame, str]: """→ (rows, source) where source is 'khazna', 'scopus' or 'missing'.""" if category not in LABELS: raise KeyError(category) t = _tables() if category == "scopus_ku": df, src = t["scopus"], "scopus" elif category == "missing": df, src = t["missing"], "missing" else: df, src = t["khazna"], "khazna" if category != "khazna_all": part, flag = category.split("_", 1) df = df[df.has_unit] if part == "unit" else df[~df.has_unit] if flag != "all": df = df[df.ku == flag] if year: df = df[df.year == year] return df, src
def summary(year: int | None = None) -> dict: t = _tables() years = sorted(set(t["khazna"].year) | set(t["scopus"].year) | set(t["missing"].year) - {0}, reverse=True) years = [int(y) for y in years if y] counts = {c: int(len(_select(c, year)[0])) for c in ORDER} return {"year": year, "years": years, "counts": counts, "labels": LABELS, "as_of": t["as_of"], "notes": {"not_ku": "No match with a KU paper in Scopus/SciVal by Scopus ID or DOI.", "unchecked": "Mostly current-year records Scopus/SciVal does not list yet.", "unit": "Organisational unit or managing unit filled."}}
def _public(df: pd.DataFrame, src: str) -> pd.DataFrame: if src == "khazna": out = df.assign(units=df.org_units.where(df.org_units != "", df.department), ku_affiliation=df.ku.map({"ku": "KU-affiliated", "not_ku": "Not KU-affiliated", "unchecked": "Not checked yet"})) return out[["title", "year", "type", "units", "journal", "doi", "eid", "ku_affiliation", "note", "link", "uuid"]] if src == "scopus": out = df.assign(in_khazna=df.in_khazna.map({True: "Yes", False: "No"})) return out[["title", "year", "type", "journal", "doi", "eid", "authors", "in_khazna", "link"]] return df[["title", "year", "type", "journal", "doi", "eid", "authors", "link"]]
def page(category: str, year: int | None = None, q: str = "", page_no: int = 1, size: int = 50) -> dict: df, src = _select(category, year) if q.strip(): words = q.lower().split() blob = (df.title + " " + df.doi + " " + df.get("journal", "")).str.lower() for w in words: df = df[blob.loc[df.index].str.contains(w, regex=False)] df = df.sort_values(["year", "title"], ascending=[False, True]) size = max(10, min(int(size), 200)) total = len(df) pages = max(1, -(-total // size)) page_no = max(1, min(int(page_no), pages)) rows = _public(df.iloc[(page_no - 1) * size: page_no * size], src) return {"category": category, "label": LABELS[category], "year": year, "q": q, "total": total, "page": page_no, "pages": pages, "size": size, "source": src, "rows": rows.to_dict("records")}
HEAD = {"title": "Title", "year": "Year", "type": "Type", "units": "KU unit(s)", "journal": "Journal", "doi": "DOI", "eid": "Scopus EID", "ku_affiliation": "KU affiliation (Scopus/SciVal)", "note": "Note", "link": "Link", "uuid": "Khazna UUID", "authors": "Authors (Scopus)", "in_khazna": "In Khazna"}
def excel(category: str, year: int | None = None) -> tuple[bytes, str]: """One category, or category='all': a summary sheet plus one sheet per category.""" # "all": the summary plus the leaf categories only (the totals would repeat the same rows) cats = [c for c in ORDER if c not in ("khazna_all", "unit_all", "nounit_all")] if category == "all" else [category] for c in cats: if c not in LABELS: raise KeyError(c) buf = io.BytesIO() with pd.ExcelWriter(buf, engine="openpyxl") as xw: if category == "all": s = summary(year) pd.DataFrame([{"Category": LABELS[c], "Papers": s["counts"][c]} for c in ORDER]).to_excel( xw, sheet_name="Summary", index=False) for c in cats: df, src = _select(c, year) _public(df.sort_values(["year", "title"], ascending=[False, True]), src).rename(columns=HEAD).to_excel( xw, sheet_name=SHEET[c][:31], index=False) for ws in xw.book.worksheets: ws.freeze_panes = "A2" for col, width in zip("ABCDEFGHIJK", (70, 8, 22, 40, 40, 28, 22, 26, 40, 50, 38)): ws.column_dimensions[col].width = width name = f"khazna_coverage_{category}_{year or 'all-years'}.xlsx" return buf.getvalue(), nameREADME.md+10
app.py+43
coverage.pyAdded+206