-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsandbox4OpenAlex.py
More file actions
2448 lines (1957 loc) · 85.1 KB
/
sandbox4OpenAlex.py
File metadata and controls
2448 lines (1957 loc) · 85.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This is _negroni . It's simply copied stSearchDashOpenAlex_martini_with_olive_deployed_Copilot.py
# ###continue with this verison; the next thing to do: sampling/randomization
# Ask copilot for my todos and bookmarks and my genius idea (instead of target journal, v.v.)
## I need to "explode" the 3 topics and add a possibility to commission based on them
## add possibility to generate keywords
### add "my" heatmaps
# I changed
# BATCH = 500 --> BATCH = 200
# I set specter max rows to embed to 6000 from 5000 while doing the Adv Sci test
# note about COUNTRIES
# Because OpenAlex only returns up to the first 100 authorships in the work object, the “all authors from selected countries” mode
# #is limited by what OpenAlex returns in authorships. The docs state that authorships is limited to the first 100 authors for API performance.
### I have now enabled SPECTER - in 4 lines around 1235 (numbering in _iceberg) - just flip i to TRUE again to lock it
# # SPECTER2 toggle (disabled for now)
# st.subheader("Embeddings (optional)")
# fetch_specter2 = st.checkbox("Fetch SPECTER2 embeddings (disabled for testing)", value=False, disabled=False)
# s2_api_key = st.text_input("Semantic Scholar API key (disabled)", value="", type="password", disabled=False)
# max_embed_rows = st.number_input("Max rows to embed (disabled)", min_value=10, max_value=5000, value=200, step=50, disabled=False)
# s2_sleep_s = st.slider("Sleep between S2 requests (s) (disabled)", 0.0, 2.0, 0.35, 0.05, disabled=False)
#I need to add slicing by journal and the “other topics” and best also by any column –> to be now able to go to commissioning tab and filter out “Nature Cell etc”
# copied _gin and renamed to _iceberg for including Primary Topic filtering manually as Copilot keeps screwing up
# _gin is renamed stSearchDashOpenAlex_fernet_journalsAccum_v4_nostop - Copy.py
# in _fernet I added proper multiselect for journals - even though it's not very intuitive. I shall improve it.
# Then the disappearing button was patched --> _gin
# I had a version mess. This version is _dornfelder_SPECTER2 from 5pm 13-May-26 "merged" into stSearchDashOpenAlex_espresso_patched_v2.py
# saved earlier that day but actually more "advanced" - by mistake the whole SPECTER2 code was chucked instead of just GUI disabled
# so now it was added back into "espresso". Also further missing parts were added back
#
# This version was "merged" by Copilot from the two version and was named stSearchDashOpenAlex_espresso_merged_with_SPECTER2_disabled_plus_TopicID.py
# I copied and renamed this to _espresso_macchiato.py
# # in the meantime I had given Copilot the _dornfelder_SPECTER2 version to start implementing chatGPT based on my old (2024) Jupyter notebooks working with NatComm
## so that branch is a "cul-de-sac" and I'm going to re-do this (better hopefully, becuase the implementaion in the _dornfelder_specter2 was anyways a bit dumb
# Goals (What Copilot remembers per Lucie):
# Known issue: some journals such as BBA series or Analytical Biochemistry retrieve dramatically fewer records than from WoS or the OpenAlex web interface; under investigation
# Known issue: sometimes Meeting Abstracts are wrongly classified as Articles --> here on the other hand results are blown up with "wrong" results; for now,
# I recommend checking the expected number of records and cleaning downloaded results in excel if necessary. The Meeting Abstracts all started with the word Abstract in the title,
# so for my dataset from J Biological Chemistry I was able to simply chuck them in Excel but filtering for the word Abstract in the title et voila the number of records matches WoS
# SPECTER2 toggle is present but DISABLED for now (deployment safety).
import time
import json
import re
import io
from typing import Optional, Dict, Any, List
import pandas as pd
import requests
import streamlit as st
import plotly.express as px
WORKS_URL = "https://api.openalex.org/works"
SOURCES_URL = "https://api.openalex.org/sources"
SUBFIELDS_URL = "https://api.openalex.org/subfields"
# Semantic Scholar (S2) Graph API (for SPECTER2 embeddings) — code retained but UI is disabled by default
S2_PAPER_BATCH_URL = "https://api.semanticscholar.org/graph/v1/paper/batch"
# ----------------------------
# Cached taxonomy: Subfields
# ----------------------------
@st.cache_data(show_spinner=False, ttl=24 * 3600)
def fetch_all_subfields(api_key: str = "", mailto: str = "") -> pd.DataFrame:
"""Fetch all OpenAlex subfields (3rd level taxonomy) into a DataFrame.
Cached for 24h to avoid repeated calls.
"""
session = requests.Session()
rows: List[Dict[str, Any]] = []
cursor = "*"
while True:
params: Dict[str, Any] = {
"per_page": 200,
"cursor": cursor,
"select": ",".join(["id", "display_name", "field", "domain"]),
}
if api_key:
params["api_key"] = api_key
if mailto:
params["mailto"] = mailto
r = session.get(SUBFIELDS_URL, params=params, timeout=60)
r.raise_for_status()
data = r.json()
results = data.get("results", [])
if not results:
break
for s in results:
sid_url = s.get("id") or ""
sid = sid_url.rsplit("/", 1)[-1] if sid_url else ""
field = s.get("field") or {}
domain = s.get("domain") or {}
rows.append({
"subfield_id": sid,
"subfield_id_url": sid_url,
"subfield": s.get("display_name") or "",
"field": field.get("display_name") or "",
"domain": domain.get("display_name") or "",
})
cursor = (data.get("meta") or {}).get("next_cursor")
if not cursor:
break
df = pd.DataFrame(rows)
if df.empty:
return df
df["label"] = df.apply(lambda r: f"{r['subfield']} — {r['field']} / {r['domain']}".strip(), axis=1)
df = df.sort_values(["domain", "field", "subfield"], kind="stable").reset_index(drop=True)
return df
# ----------------------------
# Helpers
# ----------------------------
def save_country_labels():
st.session_state.country_labels_saved = st.session_state._country_labels
TOPICS_URL = "https://api.openalex.org/topics"
def search_topics(query: str, api_key: str = "", mailto: str = "", max_results: int = 15) -> List[Dict[str, Any]]:
if not query.strip():
return []
params = {
"search": query,
"per-page": max_results
}
if mailto:
params["mailto"] = mailto
headers = {}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
try:
r = requests.get(TOPICS_URL, params=params, headers=headers, timeout=30)
r.raise_for_status()
data = r.json()
return data.get("results", [])
except Exception:
return []
def invert_index_to_text(inv: Optional[Dict[str, List[int]]]) -> str:
"""Reconstruct abstract text from OpenAlex abstract_inverted_index."""
if not inv or not isinstance(inv, dict):
return ""
positions = {}
for word, idxs in inv.items():
if not isinstance(idxs, list):
continue
for i in idxs:
positions[i] = word
if not positions:
return ""
return " ".join(positions[i] for i in sorted(positions.keys()))
def safe_get_journal_from_primary_location(work: Dict[str, Any]) -> str:
"""Return journal/venue name from work['primary_location']['source']['display_name'].
Always returns a string (never None).
"""
pl = work.get("primary_location") or {}
src = pl.get("source") or {}
name = src.get("display_name") or ""
return str(name) if name is not None else ""
def safe_get_source_id_from_primary_location(work: Dict[str, Any]) -> str:
"""Return OpenAlex source id (Sxxxx) from primary_location.source.id."""
pl = work.get("primary_location") or {}
src = pl.get("source") or {}
sid_url = src.get("id") or ""
return sid_url.rsplit("/", 1)[-1] if sid_url else ""
def topics_to_strings(work: Dict[str, Any], top_n: int = 5) -> Dict[str, Any]:
"""
Flatten work['topics'] list into CSV-friendly strings.
Keeps top N topics (by score if present).
"""
topics = work.get("topics") or []
if not isinstance(topics, list):
topics = []
# Some topics include "score". Sort if present, else keep order.
def score(t):
s = t.get("score")
return s if isinstance(s, (int, float)) else -1
topics_sorted = sorted(
[t for t in topics if isinstance(t, dict)],
key=score,
reverse=True
)
top = topics_sorted[:top_n]
names = [t.get("display_name", "") for t in top if t.get("display_name")]
ids = [(t.get("id", "") or "").rsplit("/", 1)[-1] for t in top if t.get("id")]
return {
"TopicsTopN": "; ".join(names),
"TopicIDsTopN": "; ".join(ids),
"TopicsCount": len(topics),
}
# ----------------------------
# Semantic Scholar: SPECTER2 embeddings (retained for future work)
# NOTE: The UI toggle is disabled (greyed out) to prevent accidental use.
# ----------------------------
def _doi_to_s2_id(doi_url_or_raw: str) -> str:
"""Convert DOI URL (https://doi.org/...) or raw DOI into S2 ID format DOI:..."""
if not doi_url_or_raw:
return ""
s = str(doi_url_or_raw).strip()
s = re.sub(r"^https?://doi\.org/", "", s, flags=re.IGNORECASE)
s = re.sub(r"^doi:", "", s, flags=re.IGNORECASE)
return f"DOI:{s}" if s else ""
def _extract_specter2_from_embedding_obj(emb_obj):
"""Robust extraction of a vector from various embedding payload shapes."""
if emb_obj is None:
return None
if isinstance(emb_obj, list):
return emb_obj
if isinstance(emb_obj, dict):
for k in ("specter_v2", "specter2", "specter_2", "vector"):
v = emb_obj.get(k)
if isinstance(v, list):
return v
return None
def s2_fetch_specter2_embeddings(s2_ids: list[str], s2_api_key: str = "", sleep_s: float = 0.35) -> dict:
"""Fetch SPECTER2 embeddings from Semantic Scholar Graph API /paper/batch.
Returns mapping: requested_id -> {paperId, corpusId, specter2}
"""
out: dict = {}
if not s2_ids:
return out
headers = {}
if s2_api_key:
headers["x-api-key"] = s2_api_key
# Request full embedding object and extract SPECTER2 vector robustly.
fields = "paperId,corpusId,embedding"
BATCH = 200
for i in range(0, len(s2_ids), BATCH):
chunk = s2_ids[i:i + BATCH]
r = requests.post(
S2_PAPER_BATCH_URL,
params={"fields": fields},
json={"ids": chunk},
headers=headers,
timeout=60,
)
r.raise_for_status()
data = r.json()
if isinstance(data, list):
for req_id, item in zip(chunk, data):
if not isinstance(item, dict) or item.get("error"):
continue
emb_obj = item.get("embedding")
vec = _extract_specter2_from_embedding_obj(emb_obj)
if vec is None:
continue
out[req_id] = {
"paperId": item.get("paperId"),
"corpusId": item.get("corpusId"),
"specter2": vec,
}
time.sleep(sleep_s)
return out
def attach_specter2_to_df(df: pd.DataFrame, s2_api_key: str = "", max_rows: int = 200, sleep_s: float = 0.35) -> pd.DataFrame:
"""Attach SPECTER2 embeddings to DataFrame (proof-of-principle).
Adds columns (always created):
- S2_paperId, S2_corpusId, SPECTER2, SPECTER2_dim
Only the first max_rows are queried to keep it fast.
"""
if df is None or df.empty:
return df
d = df.copy()
# Always create columns so they remain visible even if fetching fails.
for col in ("S2_paperId", "S2_corpusId", "SPECTER2", "SPECTER2_dim"):
if col not in d.columns:
d[col] = pd.NA
if "DOI" not in d.columns:
return d
n = min(int(max_rows), len(d))
s2_ids = [_doi_to_s2_id(x) for x in d.loc[: n - 1, "DOI"].tolist()]
s2_ids = [x for x in s2_ids if x]
if not s2_ids:
return d
emb_map = s2_fetch_specter2_embeddings(s2_ids, s2_api_key=s2_api_key, sleep_s=sleep_s)
for idx in range(n):
req_id = _doi_to_s2_id(d.at[idx, "DOI"])
item = emb_map.get(req_id)
if not item:
continue
vec = item.get("specter2")
d.at[idx, "S2_paperId"] = item.get("paperId")
d.at[idx, "S2_corpusId"] = item.get("corpusId")
d.at[idx, "SPECTER2"] = json.dumps(vec)
d.at[idx, "SPECTER2_dim"] = len(vec) if isinstance(vec, list) else pd.NA
return d
return src.get("display_name") or ""
def source_id_short(openalex_source_id_url: str) -> str:
if not openalex_source_id_url:
return ""
return openalex_source_id_url.rsplit("/", 1)[-1]
def find_sources_by_name(journal_query: str, api_key: str = "", mailto: str = "", max_results: int = 25) -> List[Dict[str, Any]]:
if not journal_query.strip():
return []
params: Dict[str, Any] = {
"search": journal_query.strip(),
"per_page": min(max_results, 200),
"select": ",".join([
"id",
"display_name",
"host_organization_name",
"issn",
"issn_l",
"type",
"works_count",
"cited_by_count",
])
}
if api_key:
params["api_key"] = api_key
if mailto:
params["mailto"] = mailto
r = requests.get(SOURCES_URL, params=params, timeout=60)
r.raise_for_status()
return r.json().get("results", [])
def add_citations_by_year_columns(df: pd.DataFrame, years: List[int], src_col: str = "CountsByYear", drop_src: bool = True) -> pd.DataFrame:
"""Expand CountsByYear list (list of dicts) into wide year columns."""
if df is None or df.empty or src_col not in df.columns:
return df
out = df.copy()
for y in years:
out[str(y)] = 0
for i, items in enumerate(out[src_col]):
if not isinstance(items, list):
continue
for item in items:
if not isinstance(item, dict):
continue
y = item.get("year")
c = item.get("cited_by_count", 0)
if y in years:
out.at[i, str(y)] = c
if drop_src:
out = out.drop(columns=[src_col])
return out
def compute_topic_growth_table(
df: pd.DataFrame,
topic_col: str = "PrimaryTopic",
year_col: str = "PublicationYear",
start_year: int = 2023,
end_year: int = 2025,
smoothing: float = 1.0,
min_total: int = 5,
) -> pd.DataFrame:
"""Aggregate paper counts per topic and compute growth metrics."""
if df is None or df.empty or topic_col not in df.columns or year_col not in df.columns:
return pd.DataFrame(columns=["Topic", "N_total", "N_start", "N_end", "Delta", "CAGR", "SlopePerYear"])
d = df[[topic_col, year_col]].copy()
d[year_col] = pd.to_numeric(d[year_col], errors="coerce").astype("Int64")
d = d.dropna(subset=[topic_col, year_col])
d[topic_col] = d[topic_col].astype(str)
totals = d.groupby(topic_col).size().rename("N_total")
c_start = d[d[year_col] == int(start_year)].groupby(topic_col).size().rename("N_start")
c_end = d[d[year_col] == int(end_year)].groupby(topic_col).size().rename("N_end")
out = pd.concat([totals, c_start, c_end], axis=1).fillna(0)
out["N_total"] = out["N_total"].astype(int)
out["N_start"] = out["N_start"].astype(int)
out["N_end"] = out["N_end"].astype(int)
out = out[out["N_total"] >= int(min_total)].copy()
years = max(int(end_year) - int(start_year), 1)
out["Delta"] = out["N_end"] - out["N_start"]
out["CAGR"] = ((out["N_end"] + float(smoothing)) / (out["N_start"] + float(smoothing))) ** (1 / years) - 1
out["SlopePerYear"] = out["Delta"] / years
out = out.reset_index().rename(columns={topic_col: "Topic"})
return out
def compute_topic_impact_table_alltime(df: pd.DataFrame, agg: str = "Mean", min_n: int = 5) -> pd.DataFrame:
"""Impact A: all-time citations per paper by topic (mean/median)."""
if df is None or df.empty or "PrimaryTopic" not in df.columns or "CitedByCount" not in df.columns:
return pd.DataFrame(columns=["Topic", "N", "Impact", "IsSmall"])
d = df[["PrimaryTopic", "CitedByCount"]].copy()
d["PrimaryTopic"] = d["PrimaryTopic"].fillna("(Unknown)").astype(str)
d["CitedByCount"] = pd.to_numeric(d["CitedByCount"], errors="coerce")
g = d.groupby("PrimaryTopic")
n = g.size().rename("N")
if agg == "Median":
imp = g["CitedByCount"].median()
else:
imp = g["CitedByCount"].mean()
out = pd.concat([n, imp.rename("Impact")], axis=1).reset_index().rename(columns={"PrimaryTopic": "Topic"})
out["IsSmall"] = out["N"] < int(min_n)
return out
def compute_topic_impact_table_ifwindow(df: pd.DataFrame, X: int, agg: str = "Mean", min_n: int = 5) -> pd.DataFrame:
"""Impact B: citations in year X to papers published in X-1 and X-2 (mean/median per paper), by topic.
Requires year columns as strings (e.g., '2025') OR CountsByYear already expanded.
"""
if df is None or df.empty:
return pd.DataFrame(columns=["Topic", "N", "Impact", "IsSmall"])
if "PrimaryTopic" not in df.columns or "PublicationYear" not in df.columns:
return pd.DataFrame(columns=["Topic", "N", "Impact", "IsSmall"])
colX = str(int(X))
if colX not in df.columns:
# cannot compute
return pd.DataFrame(columns=["Topic", "N", "Impact", "IsSmall"])
d = df[["PrimaryTopic", "PublicationYear", colX]].copy()
d["PrimaryTopic"] = d["PrimaryTopic"].fillna("(Unknown)").astype(str)
d["PublicationYear"] = pd.to_numeric(d["PublicationYear"], errors="coerce").astype("Int64")
d[colX] = pd.to_numeric(d[colX], errors="coerce").fillna(0)
d = d[d["PublicationYear"].isin([int(X) - 1, int(X) - 2])].copy()
if d.empty:
return pd.DataFrame(columns=["Topic", "N", "Impact", "IsSmall"])
g = d.groupby("PrimaryTopic")
n = g.size().rename("N")
if agg == "Median":
imp = g[colX].median()
else:
imp = g[colX].mean()
out = pd.concat([n, imp.rename("Impact")], axis=1).reset_index().rename(columns={"PrimaryTopic": "Topic"})
out["IsSmall"] = out["N"] < int(min_n)
return out
# ----------------------------
# OpenAlex fetch
# ----------------------------
def build_works_params(
cursor: str,
keyword_query: str,
year_from: Optional[int],
year_to: Optional[int],
api_key: str,
mailto: str,
per_page: int,
source_ids: Optional[List[str]] = None,
subfield_id: Optional[str] = None,
#primary_topic_id: Optional[str] = None, # ✅ NEW in _iceberg
primary_topic_ids: Optional[List[str]] = None,
work_types: Optional[List[str]] = None,
countries: Optional[List[str]] = None,
#country_mode: str = "Any author (default)",
require_abstract: bool = True,
require_doi: bool = True,
include_xpac: bool = True,
) -> Dict[str, Any]:
filters: List[str] = []
if require_doi:
filters.append("has_doi:true")
if require_abstract:
filters.append("has_abstract:true")
# publication_year filtering (GUI-consistent)
if year_from is not None and year_to is not None:
filters.append(f"publication_year:{int(year_from)}-{int(year_to)}")
elif year_from is not None:
filters.append(f"publication_year:{int(year_from)}-9999")
elif year_to is not None:
filters.append(f"publication_year:0-{int(year_to)}")
if source_ids:
sources_val = "|".join([sid for sid in source_ids if sid])
if sources_val:
filters.append(f"primary_location.source.id:{sources_val}")
# --- Work type ---
if work_types:
filters.append(f"type:{'|'.join(work_types)}")
# --- Country (first author / affiliation workaround) ---
# --- Country (API-level only for default mode) ---
#if countries and country_mode == "Any author (default)":
# filters.append(f"authorships.institutions.country_code:{'|'.join(countries)}")
if countries:
filters.append(f"authorships.institutions.country_code:{'|'.join(countries)}")
if subfield_id:
filters.append(f"primary_topic.subfield.id:{subfield_id}")
#if primary_topic_id:
# filters.append(f"primary_topic.id:{primary_topic_id}") # ✅ NEW in _iceberg
if primary_topic_ids:
joined = "|".join(primary_topic_ids)
filters.append(f"primary_topic.id:{joined}")
params: Dict[str, Any] = {
"filter": ",".join(filters),
"per_page": per_page,
"cursor": cursor,
"select": ",".join([
"id",
"doi",
"display_name",
"abstract_inverted_index",
"authorships",
"primary_topic",
"topics",
"publication_year",
"publication_date",
"primary_location",
"type",
"cited_by_count",
"counts_by_year",
"referenced_works_count",
]),
}
if include_xpac:
params["include_xpac"] = "true"
if keyword_query.strip():
params["search"] = keyword_query.strip()
if api_key:
params["api_key"] = api_key
if mailto:
params["mailto"] = mailto
return params
def fetch_works(
n_rows: int,
keyword_query: str,
year_from: Optional[int],
year_to: Optional[int],
api_key: str,
mailto: str,
sleep_s: float,
source_ids: Optional[List[str]] = None,
subfield_id: Optional[str] = None,
primary_topic_ids: Optional[List[str]] = None,
work_types: Optional[List[str]] = None,
countries: Optional[List[str]] = None,
#country_mode: str = "Any author (default)",
require_abstract: bool = True,
require_doi: bool = True,
include_xpac: bool = True,
fetch_specter2: bool = False,
s2_api_key: str = "",
max_embed_rows: int = 200,
s2_sleep_s: float = 0.35,
progress_cb=None,
status_cb=None,
) -> pd.DataFrame:
session = requests.Session()
headers = {"User-Agent": "streamlit-openalex-search/espresso-v2"}
cursor = "*"
collected = 0
page_count = 0
rows: List[Dict[str, Any]] = []
while collected < n_rows:
params = build_works_params(
cursor=cursor,
keyword_query=keyword_query,
year_from=year_from,
year_to=year_to,
api_key=api_key,
mailto=mailto,
per_page=200,
source_ids=source_ids,
subfield_id=subfield_id,
#primary_topic_id=primary_topic_id,
primary_topic_ids=primary_topic_ids,
work_types=work_types,
#country_mode=country_mode,
countries=countries,
require_abstract=require_abstract,
require_doi=require_doi,
include_xpac=include_xpac,
)
r = session.get(WORKS_URL, params=params, headers=headers, timeout=60)
r.raise_for_status()
data = r.json()
results = data.get("results", [])
cursor = (data.get("meta") or {}).get("next_cursor")
page_count += 1
if status_cb:
status_cb(f"Fetched page {page_count} | collected {collected}/{n_rows}")
if not results:
break
for w in results:
doi = w.get("doi") or ""
title = w.get("display_name") or ""
abstract = invert_index_to_text(w.get("abstract_inverted_index"))
if not title:
continue
if require_doi and not doi:
continue
if require_abstract and not abstract:
continue
country_codes = []
for auth in (w.get("authorships") or []):
for inst in (auth.get("institutions") or []):
cc = inst.get("country_code")
if cc:
country_codes.append(cc)
country_codes = sorted(set(country_codes))
country_str = "; ".join(country_codes)
selected_countries = set(countries or [])
corresponding_country_codes = []
all_author_country_codes = []
for auth in (w.get("authorships") or []):
auth_inst_codes = []
for inst in (auth.get("institutions") or []):
cc = inst.get("country_code")
if cc:
auth_inst_codes.append(cc)
all_author_country_codes.append(cc)
if auth.get("is_corresponding"):
corresponding_country_codes.extend(auth_inst_codes)
all_author_country_codes = sorted(set(all_author_country_codes))
corresponding_country_codes = sorted(set(corresponding_country_codes))
row = {
"DOI": doi,
"Title": title,
"Abstract": abstract or "",
"Country": country_str,
"CorrespondingAuthorCountry": "; ".join(corresponding_country_codes),
"PublicationYear": w.get("publication_year"),
"PublicationDate": w.get("publication_date"),
"JournalOrVenue": safe_get_journal_from_primary_location(w),
"JournalSourceID": safe_get_source_id_from_primary_location(w),
"WorkType": w.get("type"),
"CitedByCount": w.get("cited_by_count"),
"CountsByYear": w.get("counts_by_year") or [],
"ReferencedWorksCount": w.get("referenced_works_count"),
"OpenAlexID": w.get("id"),
"OpenAlexURL": w.get("id"),
}
pt = w.get("primary_topic") or {}
if isinstance(pt, dict):
row["PrimaryTopic"] = pt.get("display_name", "")
row["PrimaryTopicID"] = (pt.get("id", "") or "").rsplit("/", 1)[-1] # Txxxx
sf = pt.get("subfield") or {}
fld = pt.get("field") or {}
dom = pt.get("domain") or {}
row["Subfield"] = sf.get("display_name", "") if isinstance(sf, dict) else ""
row["Field"] = fld.get("display_name", "") if isinstance(fld, dict) else ""
row["Domain"] = dom.get("display_name", "") if isinstance(dom, dict) else ""
else:
row["PrimaryTopic"] = ""
row["Subfield"] = ""
row["Field"] = ""
row["Domain"] = ""
# Add Top-N topic tags (from OpenAlex work["topics"]) for CSV-friendly export
row.update(topics_to_strings(w, top_n=5))
rows.append(row)
collected += 1
if collected >= n_rows:
break
if progress_cb:
progress_cb(min(collected / n_rows, 1.0))
if not cursor:
break
time.sleep(sleep_s)
df_out = pd.DataFrame(rows)
# Optional: attach SPECTER2 embeddings (currently disabled in UI)
if fetch_specter2:
try:
if status_cb:
status_cb(f"Fetching SPECTER2 embeddings for up to {max_embed_rows} rows…")
df_out = attach_specter2_to_df(df_out, s2_api_key=s2_api_key, max_rows=max_embed_rows, sleep_s=s2_sleep_s)
except Exception as e:
if status_cb:
status_cb(f"SPECTER2 embedding fetch failed: {e}")
return df_out
# ----------------------------
# Streamlit UI
# ----------------------------
# ----------------------------
# OpenAI / ChatGPT enrichment (safe: only runs on loaded/uploaded data)
# ----------------------------
def openai_chat_completion(api_key: str, model: str, prompt: str, temperature: float = 0.8, timeout_s: int = 120) -> str:
"""Call OpenAI Chat Completions API via HTTPS (no openai package required)."""
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
payload = {
"model": model,
"temperature": temperature,
"messages": [{"role": "user", "content": prompt}],
}
r = requests.post(url, headers=headers, json=payload, timeout=timeout_s)
r.raise_for_status()
data = r.json()
return (data.get("choices") or [{}])[0].get("message", {}).get("content", "").strip()
def parse_key_challenge_review(output: str) -> tuple[str, str]:
"""Parse 2-line output into (challenge, title). Robust to extra blank lines and prefixes."""
if not output:
return "", ""
lines = [ln.strip() for ln in str(output).splitlines() if ln.strip()]
if not lines:
return "", ""
challenge = lines[0]
title = lines[1] if len(lines) > 1 else ""
for pref in ("Key challenge:", "Key Challenge:", "Challenge:"):
if challenge.lower().startswith(pref.lower()):
challenge = challenge[len(pref):].strip()
break
for pref in (
"Possible Review Title:",
"Possible review title:",
"Possible Review Article Title:",
"Review title:",
"Title:",
):
if title.lower().startswith(pref.lower()):
title = title[len(pref):].strip()
break
return challenge, title
def build_input_text_from_row(row: pd.Series, mode: str, custom_col: str = "") -> str:
"""Build the text sent to ChatGPT from a dataframe row based on mode."""
title = str(row.get("Title", "") or row.get("Article Title", "") or "")
abstract = str(row.get("Abstract", "") or "")
if mode == "Title":
return title.strip()
if mode == "Abstract":
return abstract.strip()
if mode == "Title + Abstract":
if title and abstract:
return f"{title}\n\n{abstract}".strip()
return (title or abstract).strip()
if mode == "Custom column" and custom_col:
return str(row.get(custom_col, "") or "").strip()
# fallback
return (title + "\n\n" + abstract).strip()
def enrich_df_with_chatgpt(
df: pd.DataFrame,
top_n: int,
api_key: str,
model: str,
temperature: float,
prompt_text: str,
preset_name: str,
input_mode: str,
custom_col: str = "",
progress_cb=None,
) -> pd.DataFrame:
"""Run ChatGPT on top N rows and add result columns to df."""
if df is None or df.empty:
return df
d = df.copy()
n = max(1, min(int(top_n), len(d)))
col_ch = "Key challenge identified by ChatGPT"
col_rt = "Possible Review Article Title suggested by ChatGPT"
col_other = f"ChatGPT output ({preset_name})"
if preset_name == "Key challenge / Review":
if col_ch not in d.columns:
d[col_ch] = pd.NA
if col_rt not in d.columns:
d[col_rt] = pd.NA
else:
if col_other not in d.columns:
d[col_other] = pd.NA
for i in range(n):
if progress_cb:
progress_cb((i + 1) / n)
row = d.iloc[i]
input_text = build_input_text_from_row(row, mode=input_mode, custom_col=custom_col)
if not input_text:
continue
prompt = prompt_text.replace("{input_text}", input_text)
try:
out = openai_chat_completion(api_key=api_key, model=model, prompt=prompt, temperature=temperature)
except Exception as e:
if preset_name == "Key challenge / Review":
d.at[d.index[i], col_ch] = f"[ERROR] {e}"
d.at[d.index[i], col_rt] = ""
else:
d.at[d.index[i], col_other] = f"[ERROR] {e}"
continue
if preset_name == "Key challenge / Review":
ch, rt = parse_key_challenge_review(out)
d.at[d.index[i], col_ch] = ch
d.at[d.index[i], col_rt] = rt
else:
d.at[d.index[i], col_other] = out
return d
# ----------------------------
# Commissioning / Review-topic synthesis (group-level)
# ----------------------------
def _paper_id_from_row(row: pd.Series) -> str:
"""Pick a stable paper ID for prompts/traceability."""
doi = str(row.get("DOI", "") or "").strip()
if doi and doi.lower() not in ("nan", "none"):
return doi
oa = str(row.get("OpenAlexID", "") or row.get("OpenAlexURL", "") or "").strip()
if oa and oa.lower() not in ("nan", "none"):
return oa
return str(row.name)
def _paper_title_from_row(row: pd.Series) -> str:
return str(row.get("Title", "") or row.get("Article Title", "") or "").strip()
def _paper_abstract_from_row(row: pd.Series) -> str:
return str(row.get("Abstract", "") or "").strip()
def build_commissioning_prompt(papers: List[Dict[str, str]], min_support: int = 2) -> str:
"""Build a strict prompt that asks for high-level review topics + search strategies."""
# We ask for JSON-only output to make parsing robust.
rules = (
"You are helping a journal editor commission review articles based on a set of research papers.\n\n"
"From the provided list of papers (titles + abstracts), you must:\n"
"1) Identify recurring scientific problems, challenges, or methodological gaps\n"
"2) Group related papers into coherent topic clusters\n"
"3) Propose high-level REVIEW ARTICLE topics (NOT paper-specific summaries)\n"
"4) For each topic, design a search strategy that can later be used to check novelty via web search\n\n"
"CRITICAL RULES:\n"
"- DO NOT propose topics centered on single tools (e.g. 'DeepRTAlign').\n"
"- ALWAYS generalize to the underlying problem (e.g. 'retention time alignment in large-scale LC-MS').\n"
f"- Each topic must be supported by MULTIPLE papers (minimum {min_support} if possible).\n"
"- Avoid trivial or overly broad topics ('proteomics advances', 'AI in biology').\n"
"- Focus on topics that could realistically support a full Review article.\n"
"- If a topic is widely known, refine it to a specific integrative synthesis angle.\n\n"
"OUTPUT FORMAT (JSON ONLY, no markdown, no commentary):\n"
"{\n"
" \"topics\": [\n"
" {\n"
" \"topic_title\": string,\n"
" \"problem_gap\": string,\n"
" \"synthesis_angle\": string,\n"
" \"supporting_paper_ids\": [string, ...],\n"
" \"search_strategy\": {\n"
" \"boolean_query\": string,\n"
" \"keywords\": [string, ...],\n"
" \"exclusions\": [string, ...]\n"
" }\n"
" }\n"
" ]\n"
"}\n"
)
lines = [rules, "PAPERS:"]
for p in papers:
pid = p.get("paper_id", "")
title = p.get("title", "")
abstract = p.get("abstract", "")
lines.append(f"\n[PaperID] {pid}\n[Title] {title}\n[Abstract] {abstract}")
return "\n".join(lines)
def parse_commissioning_json(output: str) -> Dict[str, Any]:
"""Parse JSON-only model output. Tries to recover if there's leading/trailing text."""
if not output:
return {}
s = output.strip()
# Attempt direct JSON parse
try:
return json.loads(s)