Upload 4 files
Browse filesFiles changed (4)
- app.py+22
- builder.py+47
- coverage.py+45
- scopus_sync.py+26-7
494 unmodified lines495496497498499500494 unmodified linesheaders={"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)494 unmodified lines495496497498499500501502503504505506507508509510511512513514515516517518519520521522494 unmodified linesheaders={"Content-Disposition": f'attachment; filename="{name}"'})@app.post("/admin/repair-scival")def repair_scival(x_admin_password: str | None = Header(default=None)):"""One-off (30 Nov): restore SciVal's full author lists and years that a Scopus run had overwritten."""_require_admin(x_admin_password)import builderif not builder.start_repair():raise HTTPException(409, "A build is already running.")return {"started": True, "status": "/admin/build/status"}@app.get("/admin/coverage/probe")async def coverage_probe(n: int = 300, x_admin_password: str | None = Header(default=None)):"""Opens a random sample of records on the Khazna portal (n, max 600) and reports which ones load, per feature.Admin only: it sends n x 2 requests to the portal. Takes about a minute for 300."""_require_admin(x_admin_password)import coveragetry:return await coverage.probe(max(20, min(int(n), 600)))except RuntimeError as e:raise HTTPException(503, str(e))@app.get("/stats/publications")def publication_stats():"""All KU publications by year for a dashboard: KU-affiliated records in Khazna (per Scopus/SciVal)
16 unmodified lines17181920212267 unmodified lines90919293949516 unmodified linesimport contextlibimport ioimport shutilimport sysimport threading67 unmodified linesreturn scopus_sync.make_client()def client_factory():"""Pure client for the sync thread (its own event loop needs its own HTTP client; tests replace this)."""import khazna_sync16 unmodified lines1718192021222367 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114216 unmodified linesimport contextlibimport ioimport osimport shutilimport sysimport threading67 unmodified linesreturn scopus_sync.make_client()REPAIR_BEFORE = os.environ.get("SCIVAL_REPAIR_BEFORE", "2026-11-30T03:30:00+00:00")def start_repair(before: str = REPAIR_BEFORE) -> bool:"""One-off: take the KU paper list as it was in the dataset BEFORE `before` (the first Scopus run) and feed itback as a SciVal update. With the keep-richer merge, full author lists and SciVal years come back; papers addedsince stay."""with _lock:if STATE["status"] == "running":return FalseSTATE.update(status="running", started=time.time(), finished=None, log=[], report={}, uploaded="")threading.Thread(target=_repair_then_build, args=(before,), daemon=True).start()return Truedef _repair_then_build(before: str) -> None:from datetime import datetimetry:import pandas as pdfrom huggingface_hub import HfApi, hf_hub_downloadrepo = khazna_index.INDEX.repoif not repo:raise RuntimeError("KHAZNA_INDEX_REPO is not set")cut = datetime.fromisoformat(before)commits = [c for c in HfApi().list_repo_commits(repo, repo_type="dataset") if c.created_at < cut]if not commits:raise RuntimeError(f"no dataset version before {before}")c = max(commits, key=lambda c: c.created_at)_log(f"repair: KU paper list from the dataset version of {c.created_at:%Y-%m-%d %H:%M} UTC ({c.commit_id[:8]})")f = hf_hub_download(repo, "scival/scival_ku.parquet", repo_type="dataset", revision=c.commit_id)old = pd.read_parquet(f)folder = UPLOAD_ROOT / f"repair-{int(time.time())}"folder.mkdir(parents=True, exist_ok=True)pd.DataFrame({"Title": old.get("title", ""), "Authors": old.get("authors", ""), "Year": old.get("year", ""),"Scopus Source title": old.get("journal", ""), "DOI": old.get("doi", ""),"Publication-type": old.get("type", ""), "EID": old.eid, "Institutions": ""}).to_csv(folder / "scival_update.csv", index=False)_log(f"repair: {len(old):,} papers, {int((old.get('authors', pd.Series(dtype=str)).fillna('') != '').sum()):,} ""with author lists; feeding them back (only empty fields, shorter author lists and years are restored)")except Exception as e:_log(f"repair FAILED before building ({type(e).__name__}: {str(e)[:200]}); nothing was changed")STATE["status"], STATE["finished"] = "failed", time.time()return_run(folder, upload=True)def client_factory():"""Pure client for the sync thread (its own event loop needs its own HTTP client; tests replace this)."""import khazna_sync
263 unmodified lines264265266263 unmodified linestag = "".join(f"_{k}-{v}" for k, v in (("portal", portal), ("staff", staff)) if v in FILTERS[k])name = f"khazna_coverage_{category}_{year or 'all-years'}{tag}.xlsx"return buf.getvalue(), name263 unmodified lines264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311263 unmodified linestag = "".join(f"_{k}-{v}" for k, v in (("portal", portal), ("staff", staff)) if v in FILTERS[k])name = f"khazna_coverage_{category}_{year or 'all-years'}{tag}.xlsx"return buf.getvalue(), name# ───────────────────────────── which records does the Khazna portal really show? ─────────────────────────────# The portal hides some records ("not found") for reasons the data does not state directly. probe() opens a random# sample of records on the portal and reports, per feature, how many loaded: the real rule shows up in the table.async def probe(n: int = 300, seed: int = 7, transport=None, concurrency: int = 6) -> dict:import asyncioimport httpxt = _tables()k = t["khazna"]sample = k.sample(min(n, len(k)), random_state=seed)sem = asyncio.Semaphore(concurrency)async def check(client, url):async with sem:try:r = await client.get(url)return "shown" if r.status_code == 200 else ("not_found" if r.status_code == 404 else f"http_{r.status_code}")except Exception as e:return "error"async with httpx.AsyncClient(timeout=30, follow_redirects=True, transport=transport,headers={"User-Agent": "KU-Library-Khazna-coverage-check"}) as client:uuid_urls = (PORTAL + "/en/publications/" + sample.uuid).tolist()res_uuid = await asyncio.gather(*(check(client, u) for u in uuid_urls))pretty = [u if u else "" for u in sample.portal_url.tolist()]res_pretty = await asyncio.gather(*(check(client, u) if u else asyncio.sleep(0, "no_url") for u in pretty))s = sample.assign(by_uuid=res_uuid, by_portal_url=res_pretty)s["shown"] = (s.by_uuid == "shown") | (s.by_portal_url == "shown")d = khazna_index.DIRECTORYany_person = s.uuid.map(dict(zip(k.uuid, k.get("staff", "unknown")))).fillna("unknown")def table(col):g = s.groupby(col).shown.agg(["count", "sum"])return {str(i): {"sampled": int(r["count"]), "shown": int(r["sum"])} for i, r in g.iterrows()}s["has_ku_author_link"] = s.uuid.map(dict(zip(k.uuid, (_s(khazna_index.INDEX._data[0], "person_uuids") != "")if "person_uuids" in khazna_index.INDEX._data[0].columnselse [False] * len(k)))).fillna(False)s["staff_now"] = any_persons["decade"] = (s.year // 5 * 5).astype(str) + "s"return {"sampled": len(s), "shown_total": int(s.shown.sum()),"by_uuid_link": dict(pd.Series(res_uuid).value_counts()), "by_portal_url": dict(pd.Series(res_pretty).value_counts()),"active_staff_in_directory": int(d.persons.active.map(lambda a: a is True).sum()) if d.persons is not None else None,"by": {c: table(c) for c in ("ku", "workflow", "staff_now", "has_ku_author_link", "type", "decade")},"examples_not_shown": s[~s.shown].head(5)[["uuid", "pure_id", "ku", "workflow", "staff_now"]].to_dict("records")}
1 unmodified line23456788 unmodified lines17181920212223152 unmodified lines1761771781791801819 unmodified lines19119219319419519619718 unmodified lines21621721821922022122222322421 unmodified lines2462472482491 unmodified lineNew KU papers straight from the Scopus Search API, instead of a monthly SciVal export.The SciVal upload stays: use it for the first full load, or whenever you prefer. This module only ADDS papers:1. asks Scopus for KU papers of the current and previous year (SCOPUS_YEARS, default 2);2. writes them as a SciVal-style table, so the existing, tested SciVal update code (update_scival inscripts/build_khazna_extras.py) merges them into scival/scival_ku.parquet and re-matches Khazna:- a Khazna record that matches a Scopus paper (EID, else DOI) becomes 'ku';8 unmodified linesSCOPUS_INSTTOKEN optional; needed when Elsevier only accepts the key from KU's networkSCOPUS_QUERY optional; default: AF-ID(...) of the KU units that have a Scopus affiliation ID in theorg-unit data, else SCOPUS_AF_IDS (default 60104134). Never a loose AFFIL() name search.SCOPUS_YEARS how many years back to refresh (default 2: this year and last)Quota: Scopus Search allows about 20,000 requests a week. KU's key allows 25 papers per page (a larger pagegives "Exceeds the maximum number allowed for the service level"), so ~2,500 papers a year take ~100 requests152 unmodified linesreturn pd.DataFrame(rows, columns=COLUMNS).drop_duplicates("EID")def stored_counts() -> dict[int, int]:"""Papers per year already in the stored KU list (from SciVal uploads and earlier Scopus runs)."""f = Path(khazna_index.INDEX.dir) / "scival" / "scival_ku.parquet"9 unmodified lineslog("scopus: skipped (no SCOPUS_API_KEY set)")return Nonethis_year = (today or date.today()).yearyears = [this_year - i for i in range(max(1, int(os.environ.get("SCOPUS_YEARS", "2"))))]query, have = ku_query(), stored_counts()log(f"scopus: query {query[:120]}{'…' if len(query) > 120 else ''}; years {', '.join(map(str, years))}")own = client is None18 unmodified lineslog(f"scopus {y}: KEPT the existing data: Scopus returned {len(df):,} papers but the list has {prev:,} "f"(above {MAX_SHARE:.0%}): the query probably catches other institutions; check SCOPUS_QUERY")else:new = len(df) if not prev else max(0, len(df) - prev)log(f"scopus {y}: using {len(df):,} papers (list has {prev:,} now, about {new:,} new)")keep.append(df)finally:if own:await client.aclose()21 unmodified linesreturn {"ok": False, "error": f"{type(e).__name__}: {str(e)[:200]}"}finally:if own:await client.aclose()1 unmodified line23456788 unmodified lines17181920212223152 unmodified lines1761771781791801811821831841851861871881891901911921931941951961979 unmodified lines20720820921021121221318 unmodified lines23223323423523623723823924024124224321 unmodified lines2652662672681 unmodified lineNew KU papers straight from the Scopus Search API, instead of a monthly SciVal export.The SciVal upload stays: use it for the first full load, or whenever you prefer. This module only ADDS papers:1. asks Scopus for KU papers of this year and next year (+ last year in January-March; SCOPUS_YEARS overrides);2. writes them as a SciVal-style table, so the existing, tested SciVal update code (update_scival inscripts/build_khazna_extras.py) merges them into scival/scival_ku.parquet and re-matches Khazna:- a Khazna record that matches a Scopus paper (EID, else DOI) becomes 'ku';8 unmodified linesSCOPUS_INSTTOKEN optional; needed when Elsevier only accepts the key from KU's networkSCOPUS_QUERY optional; default: AF-ID(...) of the KU units that have a Scopus affiliation ID in theorg-unit data, else SCOPUS_AF_IDS (default 60104134). Never a loose AFFIL() name search.SCOPUS_YEARS year offsets to refresh, e.g. "-1,0,1" (default: 0,1; plus -1 in January-March)Quota: Scopus Search allows about 20,000 requests a week. KU's key allows 25 papers per page (a larger pagegives "Exceeds the maximum number allowed for the service level"), so ~2,500 papers a year take ~100 requests152 unmodified linesreturn pd.DataFrame(rows, columns=COLUMNS).drop_duplicates("EID")def refresh_years(today: date) -> list[int]:"""This year and next year (papers online now with next year's issue date), plus last year in January-Marchwhile Scopus is still adding it. SCOPUS_YEARS overrides: comma-separated offsets from this year, e.g. "-1,0,1"."""raw = os.environ.get("SCOPUS_YEARS", "").strip()if raw and all(p.strip().lstrip("+-").isdigit() for p in raw.split(",")):offs = [int(p) for p in raw.split(",")]else:offs = ([-1] if today.month <= 3 else []) + [0, 1]return sorted({today.year + o for o in offs}, reverse=True)def stored_eids() -> set[str]:f = Path(khazna_index.INDEX.dir) / "scival" / "scival_ku.parquet"return set(pd.read_parquet(f, columns=["eid"]).eid) if f.exists() else set()def stored_counts() -> dict[int, int]:"""Papers per year already in the stored KU list (from SciVal uploads and earlier Scopus runs)."""f = Path(khazna_index.INDEX.dir) / "scival" / "scival_ku.parquet"9 unmodified lineslog("scopus: skipped (no SCOPUS_API_KEY set)")return Nonethis_year = (today or date.today()).yearyears = refresh_years(today or date.today())query, have = ku_query(), stored_counts()log(f"scopus: query {query[:120]}{'…' if len(query) > 120 else ''}; years {', '.join(map(str, years))}")own = client is None18 unmodified lineslog(f"scopus {y}: KEPT the existing data: Scopus returned {len(df):,} papers but the list has {prev:,} "f"(above {MAX_SHARE:.0%}): the query probably catches other institutions; check SCOPUS_QUERY")else:listed = stored_eids()fresh = df[~df.EID.isin(listed)]log(f"scopus {y}: {len(df):,} papers in Scopus, list has {prev:,}; adding {len(fresh):,} new "f"(papers already listed are left as they are: SciVal has full author lists)")if not fresh.empty:keep.append(fresh)finally:if own:await client.aclose()21 unmodified linesreturn {"ok": False, "error": f"{type(e).__name__}: {str(e)[:200]}"}finally:if own:await client.aclose()
app.py+22
builder.py+47
coverage.py+45
scopus_sync.py+26-7