janis-r commited on
Commit
83e5ffb
·
verified ·
1 Parent(s): 4dfccf3

LabScout 0.5.0

Browse files
Dockerfile CHANGED
@@ -5,15 +5,18 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
5
  PYTHONUNBUFFERED=1 \
6
  PIP_NO_CACHE_DIR=1 \
7
  LABSCOUT_CACHE_DIR=/tmp/labscout-cache \
 
8
  LABSCOUT_ROR_INDEX=/home/user/app/ror_index.json.gz
9
 
10
  RUN useradd -m -u 1000 user
11
  WORKDIR /home/user/app
12
- COPY --chown=user pyproject.toml README.md LICENSE ./
13
  COPY --chown=user src ./src
14
- RUN pip install --no-cache-dir .
15
- # the ROR registry in memory: organisations are matched without one API request per paper
16
- RUN labscout ror-index /home/user/app/ror_index.json.gz && chown user /home/user/app/ror_index.json.gz
 
 
17
 
18
  USER user
19
  EXPOSE 7860
 
5
  PYTHONUNBUFFERED=1 \
6
  PIP_NO_CACHE_DIR=1 \
7
  LABSCOUT_CACHE_DIR=/tmp/labscout-cache \
8
+ LABSCOUT_WARM_EXAMPLES=1 \
9
  LABSCOUT_ROR_INDEX=/home/user/app/ror_index.json.gz
10
 
11
  RUN useradd -m -u 1000 user
12
  WORKDIR /home/user/app
13
+ COPY --chown=user pyproject.toml README.md LICENSE constraints.txt ./
14
  COPY --chown=user src ./src
15
+ RUN pip install --no-cache-dir -c constraints.txt .
16
+ # the ROR registry in memory: organisations are matched without one API request per paper (the dump comes from
17
+ # Zenodo; a second try after a pause covers a short outage there)
18
+ RUN (labscout ror-index /home/user/app/ror_index.json.gz || (sleep 30 && labscout ror-index /home/user/app/ror_index.json.gz)) \
19
+ && chown user /home/user/app/ror_index.json.gz
20
 
21
  USER user
22
  EXPOSE 7860
README.md CHANGED
@@ -17,7 +17,8 @@ tags:
17
  Find the labs, people and studies behind a research topic, on a map, from PubMed, Europe PMC, ROR, NIH RePORTER, UKRI
18
  Gateway to Research and ClinicalTrials.gov.
19
 
20
- - **Web page:** type a topic, get a map, a table with the reason each lab came up, and Excel, CSV or JSON.
 
21
  - **MCP server for AI assistants:** add `https://<this space>.hf.space/mcp` as a custom connector.
22
 
23
- Code and documentation: https://github.com/actogram/scholar-mcp. Part of [Actogram Open Science](https://actogram.org).
 
17
  Find the labs, people and studies behind a research topic, on a map, from PubMed, Europe PMC, ROR, NIH RePORTER, UKRI
18
  Gateway to Research and ClinicalTrials.gov.
19
 
20
+ - **Web page:** type a topic or a question, get a map, a table with the reason each lab came up and links to
21
+ check it, and Excel, CSV or JSON.
22
  - **MCP server for AI assistants:** add `https://<this space>.hf.space/mcp` as a custom connector.
23
 
24
+ Code and documentation: https://github.com/actogram/scholar-mcp. Made by [Actogram](https://actogram.ai).
constraints.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # The versions this release was tested with. The image installs these, so that a rebuild months later runs the
2
+ # same code; raise them together with a test run.
3
+ httpx==0.28.1
4
+ mcp==2.3.0
5
+ openpyxl==3.1.5
6
+ pycountry==26.2.16
7
+ starlette==1.10.0
8
+ uvicorn==0.54.0
9
+ anyio==4.16.0
10
+ pydantic==2.14.3
pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
 
5
  [project]
6
  name = "labscout"
7
- version = "0.4.1"
8
  description = "LabScout finds the labs, people, grants, trials and patents behind a research topic from public sources, as a web page, a command line tool and an MCP server."
9
  readme = "README.md"
10
  license = "MIT"
@@ -24,6 +24,7 @@ classifiers = [
24
  "Topic :: Scientific/Engineering :: Information Analysis",
25
  ]
26
  dependencies = [
 
27
  "httpx>=0.27",
28
  "mcp>=2.3,<3",
29
  "openpyxl>=3.1",
@@ -39,7 +40,7 @@ dev = ["pytest>=8", "ruff>=0.6"]
39
  labscout = "labscout.cli:run"
40
 
41
  [project.urls]
42
- Homepage = "https://actogram.org"
43
  Source = "https://github.com/actogram/scholar-mcp"
44
  Issues = "https://github.com/actogram/scholar-mcp/issues"
45
 
 
4
 
5
  [project]
6
  name = "labscout"
7
+ version = "0.5.0"
8
  description = "LabScout finds the labs, people, grants, trials and patents behind a research topic from public sources, as a web page, a command line tool and an MCP server."
9
  readme = "README.md"
10
  license = "MIT"
 
24
  "Topic :: Scientific/Engineering :: Information Analysis",
25
  ]
26
  dependencies = [
27
+ "anyio>=4.11",
28
  "httpx>=0.27",
29
  "mcp>=2.3,<3",
30
  "openpyxl>=3.1",
 
40
  labscout = "labscout.cli:run"
41
 
42
  [project.urls]
43
+ Homepage = "https://actogram-labscout.hf.space"
44
  Source = "https://github.com/actogram/scholar-mcp"
45
  Issues = "https://github.com/actogram/scholar-mcp/issues"
46
 
src/labscout/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
  """LabScout: find the labs, people and studies behind a research topic."""
2
 
3
- __version__ = "0.4.1"
 
1
  """LabScout: find the labs, people and studies behind a research topic."""
2
 
3
+ __version__ = "0.5.0"
src/labscout/export.py CHANGED
@@ -5,8 +5,10 @@ from __future__ import annotations
5
  import csv
6
  import html
7
  import json
 
8
  from collections import Counter
9
  from pathlib import Path
 
10
 
11
  from .pipeline import LABELS, Result, read_as
12
 
@@ -16,6 +18,11 @@ SOURCES_NOTE = (
16
  "as published; e-mail addresses are removed. Organisations are matched automatically and can be wrong: "
17
  "the column 'match' says how each was found."
18
  )
 
 
 
 
 
19
  LAB_COLUMNS = [
20
  "rank",
21
  "lead",
@@ -25,6 +32,7 @@ LAB_COLUMNS = [
25
  "country",
26
  "ror",
27
  "match",
 
28
  "papers_as_senior_author",
29
  "papers_as_coauthor",
30
  "first_year",
@@ -67,6 +75,7 @@ def lab_rows(result: Result) -> list[dict[str, object]]:
67
  "country": org.country_name or org.country,
68
  "ror": org.ror,
69
  "match": org.match,
 
70
  "papers_as_senior_author": lab.senior_papers,
71
  "papers_as_coauthor": lab.other_papers,
72
  "first_year": lab.first_year,
@@ -122,10 +131,34 @@ def to_csv(result: Result, path: str | Path) -> Path:
122
  with path.open("w", newline="", encoding="utf-8") as f:
123
  w = csv.DictWriter(f, fieldnames=LAB_COLUMNS)
124
  w.writeheader()
125
- w.writerows(lab_rows(result))
126
  return path
127
 
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  def to_xlsx(result: Result, path: str | Path) -> Path:
130
  from openpyxl import Workbook
131
  from openpyxl.styles import Alignment, Font
@@ -135,29 +168,29 @@ def to_xlsx(result: Result, path: str | Path) -> Path:
135
  wb = Workbook()
136
  wb.properties.creator = wb.properties.lastModifiedBy = "Actogram LabScout"
137
  wb.properties.title = f"Labs for: {result.query}"
 
 
138
  for name, columns, rows in (("Labs", LAB_COLUMNS, lab_rows(result)), ("Papers", PAPER_COLUMNS, paper_rows(result))):
139
  ws = wb.active if name == "Labs" else wb.create_sheet(name)
140
  ws.title = name
141
  ws.append(columns)
142
  for cell in ws[1]:
143
- cell.font = Font(bold=True)
144
  for r in rows:
145
- ws.append([r.get(c) for c in columns])
146
  ws.freeze_panes = "A2"
147
  ws.auto_filter.ref = ws.dimensions
148
  link_col = columns.index("top_paper_url" if name == "Labs" else "url") + 1
149
- for row in ws.iter_rows(min_row=2, min_col=link_col, max_col=link_col):
150
- for cell in row:
151
- if cell.value:
152
- cell.hyperlink = str(cell.value)
153
- cell.font = Font(color="006956", underline="single")
154
  for i, c in enumerate(columns, 1):
155
- wide = {"why": 70, "title": 70, "top_paper": 60, "organization": 40, "lead": 24}.get(c, 14)
156
  ws.column_dimensions[get_column_letter(i)].width = wide
157
  if wide >= 40:
158
- for row in ws.iter_rows(min_row=2, min_col=i, max_col=i):
159
- for cell in row:
160
- cell.alignment = Alignment(wrap_text=True, vertical="top")
161
  about = wb.create_sheet("About")
162
  for line in (
163
  ["Search", result.query],
@@ -167,16 +200,17 @@ def to_xlsx(result: Result, path: str | Path) -> Path:
167
  ["Found", ", ".join(f"{k}: {v}" for k, v in result.found.items())],
168
  ["Counts", ", ".join(f"{k}: {v}" for k, v in result.counts.items())],
169
  ["PubMed read the search as", result.translation],
 
170
  ["Created", result.created],
171
  ["Tool", f"Actogram LabScout {result.version}, https://github.com/actogram/scholar-mcp"],
 
172
  ["Notes", SOURCES_NOTE],
173
  ):
174
- about.append(line)
175
- about.column_dimensions["A"].width = 18
176
  about.column_dimensions["B"].width = 110
177
- for row in about.iter_rows(min_col=2, max_col=2):
178
- for cell in row:
179
- cell.alignment = Alignment(wrap_text=True, vertical="top")
180
  wb.save(path)
181
  return path
182
 
@@ -200,7 +234,11 @@ def overview(result: Result) -> list[str]:
200
  out = []
201
  if not result.papers:
202
  names = " and ".join(LABELS.get(s, s) for s in result.sources if s not in result.failed)
203
- return [f"{years_text(result)}: {names or 'The sources'} found no papers for this search."]
 
 
 
 
204
  have = [(LABELS.get(s, s), result.found[s]) for s in result.sources if s in result.found]
205
  if have:
206
  said = " and ".join(f"{name} has {n:,}" for name, n in have)
@@ -238,9 +276,13 @@ def hint(result: Result) -> str:
238
  return f"Only {_n(papers, 'paper')} match. For more, use fewer words, OR between similar words, or more years."
239
  broad = any(result.found.get(s, 0) > 5 * max(1, result.counts.get(s, 0)) for s in result.sources)
240
  if broad:
241
- which = "newest" if result.order == "newest" else "most relevant and most cited"
 
 
 
 
242
  return (
243
- f"This topic is broad, so the labs come from the {which} papers only. To focus, add a word, put a phrase "
244
  "in quotes or narrow the years."
245
  )
246
  return ""
@@ -258,7 +300,8 @@ def country_bars(result: Result, top: int = 8) -> str:
258
  rows.append(("Other", rest))
259
  most = max(n for _, n in rows)
260
  items = "".join(
261
- f'<li title="{html.escape(name)}: {n} lab{"s" if n != 1 else ""}"><span class="k">{html.escape(name)}</span>'
 
262
  f'<span class="b"><i style="width:{max(2.0, 100 * n / most):.1f}%"></i></span><span class="v">{n}</span></li>'
263
  for name, n in rows
264
  )
@@ -309,11 +352,31 @@ def year_columns(result: Result, bars: int = 15) -> str:
309
  return f'<figure class="chart"><figcaption>Papers by year</figcaption>{svg}</figure>'
310
 
311
 
312
- def render_html(result: Result, top: int = 200, toolbar: str = "", footer: str = "") -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
  """The report page as text; `toolbar` is HTML placed under the title and `footer` at the end (the web page puts its
314
- links there)."""
 
315
  data = result.summary(top=top, papers_per_lab=5)
316
- payload = json.dumps(data, ensure_ascii=False).replace("</", "<\\/")
 
 
 
317
  e = html.escape
318
  advice = hint(result)
319
  reading = (
@@ -328,7 +391,10 @@ def render_html(result: Result, top: int = 200, toolbar: str = "", footer: str =
328
  "{{DESC}}": e(f"Labs working on {result.query}, on a map and in a table, from Actogram LabScout."),
329
  "{{QUERY}}": e(result.query),
330
  "{{OVERVIEW}}": "".join(f"<p>{e(line)}</p>" for line in overview(result)),
331
- "{{HINT}}": f'<p class="hint">{e(advice)}</p>' if advice else "",
 
 
 
332
  "{{READING}}": reading,
333
  "{{CHARTS}}": f'<div class="charts">{charts}</div>' if charts else "",
334
  "{{CREATED}}": e(result.created),
@@ -336,11 +402,9 @@ def render_html(result: Result, top: int = 200, toolbar: str = "", footer: str =
336
  "{{VERSION}}": e(result.version),
337
  "{{TOOLBAR}}": toolbar,
338
  "{{FOOTER}}": footer,
 
339
  }
340
- page = TEMPLATE
341
- for k, v in values.items():
342
- page = page.replace(k, v)
343
- return page.replace("{{DATA}}", payload)
344
 
345
 
346
  def to_html(result: Result, path: str | Path, top: int = 200) -> Path:
@@ -364,7 +428,7 @@ def csv_text(result: Result) -> str:
364
  buf = io.StringIO()
365
  w = csv.DictWriter(buf, fieldnames=LAB_COLUMNS)
366
  w.writeheader()
367
- w.writerows(lab_rows(result))
368
  return buf.getvalue()
369
 
370
 
@@ -423,6 +487,15 @@ details summary { cursor:pointer; color:var(--green); }
423
  details ol { margin:6px 0 0 18px; padding:0; }
424
  a { color:var(--green); }
425
  .why { color:var(--soft); }
 
 
 
 
 
 
 
 
 
426
  footer { padding-top:18px; padding-bottom:28px; color:var(--soft); font-size:13.5px; }
427
  @media (max-width:760px) { .charts { grid-template-columns:1fr; } }
428
  @media (max-width:640px) {
@@ -451,7 +524,10 @@ footer { padding-top:18px; padding-bottom:28px; color:var(--soft); font-size:13.
451
  {{CHARTS}}
452
  <div id="map" role="img" aria-label="Map of the labs that have a known place"></div>
453
  <div class="bar"><input id="q" type="search" placeholder="Filter by name, place, species or data" aria-label="Filter the labs">
 
 
454
  <span id="shown" aria-live="polite"></span></div>
 
455
  <div class="wrap"><table id="labs">
456
  <thead><tr><th data-k="rank">#</th><th data-k="lead">Lead</th><th data-k="organization">Organisation</th>
457
  <th data-k="country">Country</th><th data-k="papers_as_senior_author">Papers led</th><th data-k="last">Last paper</th>
@@ -459,7 +535,7 @@ footer { padding-top:18px; padding-bottom:28px; color:var(--soft); font-size:13.
459
  <tbody></tbody>
460
  </table></div>
461
  </main>
462
- <footer>{{FOOTER}}<p>Created {{CREATED}}. {{NOTE}}</p><p>Map tiles: &copy; OpenStreetMap contributors. Made with Actogram LabScout
463
  {{VERSION}}, <a href="https://github.com/actogram/scholar-mcp">github.com/actogram/scholar-mcp</a>.</p></footer>
464
  <script type="application/json" id="data">{{DATA}}</script>
465
  <script>
@@ -468,29 +544,51 @@ footer { padding-top:18px; padding-bottom:28px; color:var(--soft); font-size:13.
468
  var labs = data.labs.map(function (l, i) { l.rank = i + 1; l.last = (l.years || [])[1] || ''; return l; });
469
  function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
470
  return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'}[c]; }); }
 
 
471
  function papers(l) {
472
  if (!l.top_papers.length) return '';
473
  var n = l.top_papers.length;
474
  return '<details><summary>' + n + (n === 1 ? ' paper' : ' papers') + '</summary><ol>' + l.top_papers.map(function (p) {
475
- return '<li>' + (p.url ? '<a href="' + esc(p.url) + '" target="_blank" rel="noopener">' + esc(p.title) + '</a>' : esc(p.title)) +
476
- ' (' + esc(p.year) + ')</li>'; }).join('') + '</ol></details>';
477
  }
478
  var body = document.querySelector('#labs tbody');
479
  function row(l) {
480
- var lead = esc(l.lead) + (l.orcid ? ' <a href="https://orcid.org/' + esc(l.orcid) + '" target="_blank" rel="noopener">ORCID</a>' : '');
481
- var org = l.ror ? '<a href="' + esc(l.ror) + '" target="_blank" rel="noopener">' + esc(l.organization) + '</a>' : esc(l.organization);
482
- return '<tr><td class="num rank">' + l.rank + '</td><td data-label="Lead">' + lead + '</td><td data-label="Organisation">' + org +
483
- (l.city ? '<br><span class="why">' + esc(l.city) + '</span>' : '') + '</td><td data-label="Country">' + esc(l.country) +
 
 
 
 
 
 
 
 
 
484
  '</td><td class="num" data-label="Papers led">' + l.papers_as_senior_author + '</td><td class="num" data-label="Last paper">' +
485
  esc(l.last) + '</td><td><span class="why">' + esc(l.why) + '</span>' + papers(l) + '</td></tr>';
486
  }
487
- var key = 'rank', dir = 1;
 
 
 
 
 
488
  function draw() {
489
- var q = document.getElementById('q').value.toLowerCase();
490
- var list = labs.filter(function (l) { return !q || [l.lead, l.organization, l.city, l.country, l.why].join(' ').toLowerCase().indexOf(q) >= 0; });
 
 
491
  list.sort(function (a, b) { var x = a[key], y = b[key]; return (x > y ? 1 : x < y ? -1 : 0) * dir; });
492
  body.innerHTML = list.map(row).join('');
493
- document.getElementById('shown').textContent = list.length + ' of ' + labs.length + ' labs';
 
 
 
 
 
494
  }
495
  document.querySelectorAll('#labs th').forEach(function (th) {
496
  th.addEventListener('click', function () {
@@ -499,7 +597,18 @@ footer { padding-top:18px; padding-bottom:28px; color:var(--soft); font-size:13.
499
  th.setAttribute('aria-sort', dir > 0 ? 'ascending' : 'descending'); draw();
500
  });
501
  });
502
- document.getElementById('q').addEventListener('input', draw);
 
 
 
 
 
 
 
 
 
 
 
503
  draw();
504
  window.labscoutMap = function () {
505
  if (!window.L) {
@@ -509,16 +618,23 @@ footer { padding-top:18px; padding-bottom:28px; color:var(--soft); font-size:13.
509
  var map = L.map('map', { scrollWheelZoom: false }).setView([30, 10], 2);
510
  L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18,
511
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);
512
- var pts = [];
513
- labs.forEach(function (l) {
514
- if (l.lat == null || l.lon == null) return;
515
- var r = 5 + Math.min(10, 2 * l.papers_as_senior_author);
516
- L.circleMarker([l.lat, l.lon], { radius: r, color: '#00473a', weight: 1.5, fillColor: '#006956', fillOpacity: 0.55 })
517
- .bindPopup('<b>' + esc(l.lead) + '</b><br>' + esc(l.organization) + '<br>' + esc(l.why)).addTo(map);
518
- pts.push([l.lat, l.lon]);
519
- });
520
- if (pts.length > 1) map.fitBounds(pts, { padding: [24, 24], maxZoom: 6 });
521
- else if (pts.length === 1) map.setView(pts[0], 5);
 
 
 
 
 
 
 
522
  };
523
  })();
524
  </script>
 
5
  import csv
6
  import html
7
  import json
8
+ import re
9
  from collections import Counter
10
  from pathlib import Path
11
+ from typing import Any
12
 
13
  from .pipeline import LABELS, Result, read_as
14
 
 
18
  "as published; e-mail addresses are removed. Organisations are matched automatically and can be wrong: "
19
  "the column 'match' says how each was found."
20
  )
21
+ HOW_TO_READ = (
22
+ "A lab is the senior (last) author of the papers and the organisation printed with the name. The order shows how "
23
+ "much of a lab's work is on the topic: papers it led count most, then papers its lead co-authored and recent "
24
+ "work. It says nothing about the quality of the research. Check the papers before you rely on an entry."
25
+ )
26
  LAB_COLUMNS = [
27
  "rank",
28
  "lead",
 
32
  "country",
33
  "ror",
34
  "match",
35
+ "also_at",
36
  "papers_as_senior_author",
37
  "papers_as_coauthor",
38
  "first_year",
 
75
  "country": org.country_name or org.country,
76
  "ror": org.ror,
77
  "match": org.match,
78
+ "also_at": "; ".join(lab.other_organizations),
79
  "papers_as_senior_author": lab.senior_papers,
80
  "papers_as_coauthor": lab.other_papers,
81
  "first_year": lab.first_year,
 
131
  with path.open("w", newline="", encoding="utf-8") as f:
132
  w = csv.DictWriter(f, fieldnames=LAB_COLUMNS)
133
  w.writeheader()
134
+ w.writerows({k: _csv_cell(v) for k, v in r.items()} for r in lab_rows(result))
135
  return path
136
 
137
 
138
+ _NOT_IN_SHEETS = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
139
+
140
+
141
+ def _text_cell(value: object) -> object:
142
+ """A value for a spreadsheet cell, without the control characters a sheet refuses."""
143
+ return _NOT_IN_SHEETS.sub(" ", value) if isinstance(value, str) else value
144
+
145
+
146
+ def _add_row(ws: Any, values: list[object]) -> None:
147
+ """A row of plain values. A title or a search that starts with "=" would become a formula in the reader's
148
+ Excel (a link with a false label, for one); it is written as the text it is."""
149
+ ws.append([_text_cell(v) for v in values])
150
+ for cell in ws[ws.max_row]:
151
+ if cell.data_type == "f":
152
+ cell.data_type = "s"
153
+
154
+
155
+ def _csv_cell(value: object) -> object:
156
+ """The same for CSV, which has no cell types: Excel reads a cell that starts with = + - or @ as a formula."""
157
+ if isinstance(value, str) and value[:1] in ("=", "+", "-", "@", "\t", "\r"):
158
+ return "'" + value
159
+ return value
160
+
161
+
162
  def to_xlsx(result: Result, path: str | Path) -> Path:
163
  from openpyxl import Workbook
164
  from openpyxl.styles import Alignment, Font
 
168
  wb = Workbook()
169
  wb.properties.creator = wb.properties.lastModifiedBy = "Actogram LabScout"
170
  wb.properties.title = f"Labs for: {result.query}"
171
+ bold, link = Font(bold=True), Font(color="006956", underline="single")
172
+ wrap = Alignment(wrap_text=True, vertical="top") # one style object for all cells: a big sheet has 100,000 of them
173
  for name, columns, rows in (("Labs", LAB_COLUMNS, lab_rows(result)), ("Papers", PAPER_COLUMNS, paper_rows(result))):
174
  ws = wb.active if name == "Labs" else wb.create_sheet(name)
175
  ws.title = name
176
  ws.append(columns)
177
  for cell in ws[1]:
178
+ cell.font = bold
179
  for r in rows:
180
+ _add_row(ws, [r.get(c) for c in columns])
181
  ws.freeze_panes = "A2"
182
  ws.auto_filter.ref = ws.dimensions
183
  link_col = columns.index("top_paper_url" if name == "Labs" else "url") + 1
184
+ for (cell,) in ws.iter_rows(min_row=2, min_col=link_col, max_col=link_col):
185
+ if cell.value:
186
+ cell.hyperlink = str(cell.value)
187
+ cell.font = link
 
188
  for i, c in enumerate(columns, 1):
189
+ wide = {"why": 70, "title": 70, "top_paper": 60, "organization": 40, "lead": 24, "also_at": 30}.get(c, 14)
190
  ws.column_dimensions[get_column_letter(i)].width = wide
191
  if wide >= 40:
192
+ for (cell,) in ws.iter_rows(min_row=2, min_col=i, max_col=i):
193
+ cell.alignment = wrap
 
194
  about = wb.create_sheet("About")
195
  for line in (
196
  ["Search", result.query],
 
200
  ["Found", ", ".join(f"{k}: {v}" for k, v in result.found.items())],
201
  ["Counts", ", ".join(f"{k}: {v}" for k, v in result.counts.items())],
202
  ["PubMed read the search as", result.translation],
203
+ ["Notes on the search", " ".join(result.notes)],
204
  ["Created", result.created],
205
  ["Tool", f"Actogram LabScout {result.version}, https://github.com/actogram/scholar-mcp"],
206
+ ["How to read it", HOW_TO_READ],
207
  ["Notes", SOURCES_NOTE],
208
  ):
209
+ _add_row(about, list(line))
210
+ about.column_dimensions["A"].width = 26
211
  about.column_dimensions["B"].width = 110
212
+ for (cell,) in about.iter_rows(min_col=2, max_col=2):
213
+ cell.alignment = wrap
 
214
  wb.save(path)
215
  return path
216
 
 
234
  out = []
235
  if not result.papers:
236
  names = " and ".join(LABELS.get(s, s) for s in result.sources if s not in result.failed)
237
+ down = " and ".join(LABELS.get(s, s) for s in result.failed)
238
+ if down and not names:
239
+ return [f"{down} did not answer, so there is nothing to show. Please try again in a few minutes."]
240
+ said = [f"{years_text(result)}: {names or 'The sources'} found no papers for this search."]
241
+ return said + [f"{down} did not answer. Please try again in a few minutes."] * bool(down)
242
  have = [(LABELS.get(s, s), result.found[s]) for s in result.sources if s in result.found]
243
  if have:
244
  said = " and ".join(f"{name} has {n:,}" for name, n in have)
 
276
  return f"Only {_n(papers, 'paper')} match. For more, use fewer words, OR between similar words, or more years."
277
  broad = any(result.found.get(s, 0) > 5 * max(1, result.counts.get(s, 0)) for s in result.sources)
278
  if broad:
279
+ which = (
280
+ "newest papers"
281
+ if result.order == "newest"
282
+ else "best matches on PubMed and the most cited papers of each year on Europe PMC"
283
+ )
284
  return (
285
+ f"This topic is broad, so the labs come from the {which} only. To focus, add a word, put a phrase "
286
  "in quotes or narrow the years."
287
  )
288
  return ""
 
300
  rows.append(("Other", rest))
301
  most = max(n for _, n in rows)
302
  items = "".join(
303
+ f'<li data-c="{html.escape(name)}" title="{html.escape(name)}: {n} lab{"s" if n != 1 else ""}">'
304
+ f'<span class="k">{html.escape(name)}</span>'
305
  f'<span class="b"><i style="width:{max(2.0, 100 * n / most):.1f}%"></i></span><span class="v">{n}</span></li>'
306
  for name, n in rows
307
  )
 
352
  return f'<figure class="chart"><figcaption>Papers by year</figcaption>{svg}</figure>'
353
 
354
 
355
+ _PLACE = re.compile(r"\{\{[A-Z_]+\}\}")
356
+
357
+
358
+ def fill(template: str, values: dict[str, str]) -> str:
359
+ """The template with its places filled in one pass. A value is never read again, so a search for the text
360
+ "{{DATA}}" stays that text instead of pulling the data into the page."""
361
+ return _PLACE.sub(lambda m: values.get(m.group(0), m.group(0)), template)
362
+
363
+
364
+ def render_html(
365
+ result: Result,
366
+ top: int = 200,
367
+ toolbar: str = "",
368
+ footer: str = "",
369
+ profiles: str = "",
370
+ notes: list[str] | None = None,
371
+ ) -> str:
372
  """The report page as text; `toolbar` is HTML placed under the title and `footer` at the end (the web page puts its
373
+ links there). `profiles` is the address of a page that shows one researcher ("profile" on the web page); with it
374
+ every lab links there. `notes` are sentences about this request, shown before the notes of the search itself."""
375
  data = result.summary(top=top, papers_per_lab=5)
376
+ data["profiles"] = profiles
377
+ data["labs_total"] = len(result.labs)
378
+ # inside the script element no "<" is left: neither a closing tag nor a comment can start in the data
379
+ payload = json.dumps(data, ensure_ascii=False).replace("<", "\\u003c")
380
  e = html.escape
381
  advice = hint(result)
382
  reading = (
 
391
  "{{DESC}}": e(f"Labs working on {result.query}, on a map and in a table, from Actogram LabScout."),
392
  "{{QUERY}}": e(result.query),
393
  "{{OVERVIEW}}": "".join(f"<p>{e(line)}</p>" for line in overview(result)),
394
+ "{{HINT}}": "".join(
395
+ f'<p class="hint">{e(line)}</p>' for line in [*(notes or []), *result.notes, advice] if line
396
+ ),
397
+ "{{HOW}}": e(HOW_TO_READ),
398
  "{{READING}}": reading,
399
  "{{CHARTS}}": f'<div class="charts">{charts}</div>' if charts else "",
400
  "{{CREATED}}": e(result.created),
 
402
  "{{VERSION}}": e(result.version),
403
  "{{TOOLBAR}}": toolbar,
404
  "{{FOOTER}}": footer,
405
+ "{{DATA}}": payload,
406
  }
407
+ return fill(TEMPLATE, values)
 
 
 
408
 
409
 
410
  def to_html(result: Result, path: str | Path, top: int = 200) -> Path:
 
428
  buf = io.StringIO()
429
  w = csv.DictWriter(buf, fieldnames=LAB_COLUMNS)
430
  w.writeheader()
431
+ w.writerows({k: _csv_cell(v) for k, v in r.items()} for r in lab_rows(result))
432
  return buf.getvalue()
433
 
434
 
 
487
  details ol { margin:6px 0 0 18px; padding:0; }
488
  a { color:var(--green); }
489
  .why { color:var(--soft); }
490
+ .also, .unsure { display:block; color:var(--soft); font-size:13.5px; }
491
+ .links { display:block; font-size:13.5px; }
492
+ .links a { margin-right:10px; white-space:nowrap; }
493
+ .bar select { padding:8px 10px; font:inherit; border:1px solid var(--line); border-radius:8px; background:#fff; max-width:15em; }
494
+ .bar label { display:inline-flex; align-items:center; gap:6px; font-size:15px; white-space:nowrap; }
495
+ .bar label input { width:18px; height:18px; accent-color:var(--green); }
496
+ .howto { max-width:880px; margin:0 0 10px; color:var(--soft); font-size:14.5px; }
497
+ .hbars li[data-c] { cursor:pointer; }
498
+ .hbars li.on .k { font-weight:600; color:var(--green); }
499
  footer { padding-top:18px; padding-bottom:28px; color:var(--soft); font-size:13.5px; }
500
  @media (max-width:760px) { .charts { grid-template-columns:1fr; } }
501
  @media (max-width:640px) {
 
524
  {{CHARTS}}
525
  <div id="map" role="img" aria-label="Map of the labs that have a known place"></div>
526
  <div class="bar"><input id="q" type="search" placeholder="Filter by name, place, species or data" aria-label="Filter the labs">
527
+ <select id="country" aria-label="Country"><option value="">All countries</option></select>
528
+ <label><input type="checkbox" id="core"> 2 or more papers</label>
529
  <span id="shown" aria-live="polite"></span></div>
530
+ <p class="howto">{{HOW}}</p>
531
  <div class="wrap"><table id="labs">
532
  <thead><tr><th data-k="rank">#</th><th data-k="lead">Lead</th><th data-k="organization">Organisation</th>
533
  <th data-k="country">Country</th><th data-k="papers_as_senior_author">Papers led</th><th data-k="last">Last paper</th>
 
535
  <tbody></tbody>
536
  </table></div>
537
  </main>
538
+ <footer>{{FOOTER}}<p id="wrong"></p><p>Created {{CREATED}}. {{NOTE}}</p><p>Map tiles: &copy; OpenStreetMap contributors. Made with Actogram LabScout
539
  {{VERSION}}, <a href="https://github.com/actogram/scholar-mcp">github.com/actogram/scholar-mcp</a>.</p></footer>
540
  <script type="application/json" id="data">{{DATA}}</script>
541
  <script>
 
544
  var labs = data.labs.map(function (l, i) { l.rank = i + 1; l.last = (l.years || [])[1] || ''; return l; });
545
  function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
546
  return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'}[c]; }); }
547
+ function enc(s) { return encodeURIComponent(String(s == null ? '' : s)); }
548
+ function out(url, text) { return '<a href="' + esc(url) + '" target="_blank" rel="noopener">' + text + '</a>'; }
549
  function papers(l) {
550
  if (!l.top_papers.length) return '';
551
  var n = l.top_papers.length;
552
  return '<details><summary>' + n + (n === 1 ? ' paper' : ' papers') + '</summary><ol>' + l.top_papers.map(function (p) {
553
+ return '<li>' + (p.url ? out(p.url, esc(p.title)) : esc(p.title)) + ' (' + esc(p.year) + ')</li>'; }).join('') + '</ol></details>';
 
554
  }
555
  var body = document.querySelector('#labs tbody');
556
  function row(l) {
557
+ var links = [];
558
+ if (l.orcid) links.push(out('https://orcid.org/' + l.orcid, 'ORCID'));
559
+ if (l.author_search) links.push(out('https://pubmed.ncbi.nlm.nih.gov/?term=' + enc(l.author_search + '[au] AND (' + data.query + ')'), 'on PubMed'));
560
+ if (data.profiles) links.push('<a href="' + esc(data.profiles) + '?name=' + enc(l.lead_sorted || l.lead) + '&amp;topic=' +
561
+ enc(data.query) + '&amp;org=' + enc(l.ror ? l.organization : '') + '&amp;back=' + enc(location.search) + '">profile</a>');
562
+ var org = l.ror ? out(l.ror, esc(l.organization)) : esc(l.organization);
563
+ var sure = String(l.organization_match || '').indexOf('ror') === 0;
564
+ return '<tr><td class="num rank">' + l.rank + '</td><td data-label="Lead">' + esc(l.lead) +
565
+ (links.length ? '<span class="links">' + links.join('') + '</span>' : '') + '</td><td data-label="Organisation">' + org +
566
+ (l.city ? '<br><span class="why">' + esc(l.city) + '</span>' : '') +
567
+ (sure ? '' : '<span class="unsure">place not confirmed</span>') +
568
+ ((l.also_at || []).length ? '<span class="also">also: ' + esc(l.also_at.join('; ')) + '</span>' : '') +
569
+ '</td><td data-label="Country">' + esc(l.country) +
570
  '</td><td class="num" data-label="Papers led">' + l.papers_as_senior_author + '</td><td class="num" data-label="Last paper">' +
571
  esc(l.last) + '</td><td><span class="why">' + esc(l.why) + '</span>' + papers(l) + '</td></tr>';
572
  }
573
+ var pick = document.getElementById('country'), core = document.getElementById('core'), box = document.getElementById('q');
574
+ var seen = {};
575
+ labs.forEach(function (l) { if (l.country) seen[l.country] = (seen[l.country] || 0) + 1; });
576
+ Object.keys(seen).sort().forEach(function (c) {
577
+ var o = document.createElement('option'); o.value = c; o.textContent = c + ' (' + seen[c] + ')'; pick.appendChild(o); });
578
+ var key = 'rank', dir = 1, shownLabs = labs;
579
  function draw() {
580
+ var q = box.value.toLowerCase(), c = pick.value, two = core.checked;
581
+ var list = labs.filter(function (l) {
582
+ return (!c || l.country === c) && (!two || l.papers_as_senior_author >= 2) &&
583
+ (!q || [l.lead, l.organization, l.city, l.country, l.why, (l.also_at || []).join(' ')].join(' ').toLowerCase().indexOf(q) >= 0); });
584
  list.sort(function (a, b) { var x = a[key], y = b[key]; return (x > y ? 1 : x < y ? -1 : 0) * dir; });
585
  body.innerHTML = list.map(row).join('');
586
+ var all = data.labs_total || labs.length;
587
+ document.getElementById('shown').textContent = list.length + ' of ' + labs.length + ' labs' +
588
+ (all > labs.length ? ' (the first ' + labs.length + ' of ' + all.toLocaleString('en') + '; all are in the Excel file)' : '');
589
+ document.querySelectorAll('.hbars li[data-c]').forEach(function (li) { li.classList.toggle('on', li.getAttribute('data-c') === c); });
590
+ shownLabs = list;
591
+ if (window.labscoutMarks) window.labscoutMarks();
592
  }
593
  document.querySelectorAll('#labs th').forEach(function (th) {
594
  th.addEventListener('click', function () {
 
597
  th.setAttribute('aria-sort', dir > 0 ? 'ascending' : 'descending'); draw();
598
  });
599
  });
600
+ box.addEventListener('input', draw); pick.addEventListener('change', draw); core.addEventListener('change', draw);
601
+ document.querySelectorAll('.hbars li[data-c]').forEach(function (li) {
602
+ li.addEventListener('click', function () {
603
+ var c = li.getAttribute('data-c');
604
+ if (!seen[c]) return; // "Other", or a country outside the labs shown
605
+ pick.value = pick.value === c ? '' : c; draw();
606
+ });
607
+ });
608
+ var mail = 'services@actogram.ai', where = location.protocol.indexOf('http') === 0 ? location.href : data.query;
609
+ document.getElementById('wrong').innerHTML = 'Something wrong with an entry (a wrong organisation, two people shown as one)? ' +
610
+ '<a href="mailto:' + mail + '?subject=' + enc('LabScout: a correction') + '&amp;body=' + enc('Search: ' + where + '\n\nWhat is wrong:\n') +
611
+ '">Tell us</a> and we will correct it.';
612
  draw();
613
  window.labscoutMap = function () {
614
  if (!window.L) {
 
618
  var map = L.map('map', { scrollWheelZoom: false }).setView([30, 10], 2);
619
  L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18,
620
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);
621
+ var layer = L.layerGroup().addTo(map), first = true;
622
+ window.labscoutMarks = function () {
623
+ layer.clearLayers();
624
+ var pts = [];
625
+ shownLabs.forEach(function (l) {
626
+ if (l.lat == null || l.lon == null) return;
627
+ var r = 5 + Math.min(10, 2 * l.papers_as_senior_author);
628
+ L.circleMarker([l.lat, l.lon], { radius: r, color: '#00473a', weight: 1.5, fillColor: '#006956', fillOpacity: 0.55 })
629
+ .bindPopup('<b>' + esc(l.lead) + '</b><br>' + esc(l.organization) + '<br>' + esc(l.why)).addTo(layer);
630
+ pts.push([l.lat, l.lon]);
631
+ });
632
+ if (pts.length > 1) map.fitBounds(pts, { padding: [24, 24], maxZoom: 6 });
633
+ else if (pts.length === 1) map.setView(pts[0], 5);
634
+ else if (!first) map.setView([30, 10], 2);
635
+ first = false;
636
+ };
637
+ window.labscoutMarks();
638
  };
639
  })();
640
  </script>
src/labscout/http.py CHANGED
@@ -5,8 +5,12 @@ from __future__ import annotations
5
  import hashlib
6
  import json
7
  import logging
 
 
 
8
  import threading
9
  import time
 
10
  from pathlib import Path
11
  from typing import Any
12
  from urllib.parse import urlsplit
@@ -36,23 +40,55 @@ _NEXT: dict[str, float] = {}
36
  _NEXT_LOCK = threading.Lock()
37
 
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  class Http:
40
  def __init__(
41
  self, settings: Settings | None = None, transport: httpx.BaseTransport | None = None, pace: bool = True
42
  ) -> None:
43
  self.settings = settings or Settings.from_env()
44
- self._client = httpx.Client(
45
- timeout=self.settings.timeout,
46
- transport=transport,
47
- follow_redirects=True,
48
- headers={"User-Agent": self.settings.user_agent},
49
- )
 
 
 
 
50
  self._pace = dict(PACE) if pace else {}
51
  if pace and self.settings.ncbi_api_key:
52
  self._pace["eutils.ncbi.nlm.nih.gov"] = 0.11
53
 
54
  def close(self) -> None:
55
- self._client.close()
 
56
 
57
  def __enter__(self) -> Http:
58
  return self
@@ -61,14 +97,53 @@ class Http:
61
  self.close()
62
 
63
  # ---- public helpers ---------------------------------------------------------------------------------------------
64
- def get_json(self, url: str, params: dict[str, Any] | None = None, headers: dict[str, str] | None = None) -> Any:
65
- return self._request("GET", url, params=params, headers=headers, kind="json")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  def get_text(self, url: str, params: dict[str, Any] | None = None) -> str:
68
  return self._request("GET", url, params=params, kind="text")
69
 
70
- def post_form_text(self, url: str, data: dict[str, Any]) -> str:
71
- return self._request("POST", url, data=data, kind="text")
72
 
73
  def post_json(self, url: str, payload: dict[str, Any]) -> Any:
74
  return self._request("POST", url, json_body=payload, kind="json")
@@ -84,10 +159,12 @@ class Http:
84
  json_body: dict[str, Any] | None = None,
85
  headers: dict[str, str] | None = None,
86
  kind: str,
 
 
87
  ) -> Any:
88
  key = self._key(method, url, params, data, json_body, headers)
89
  cached = self._cache_get(key)
90
- if cached is not None:
91
  return cached
92
  host = urlsplit(url).hostname or ""
93
  delay = 1.0
@@ -110,7 +187,15 @@ class Http:
110
  continue
111
  resp.raise_for_status()
112
  value = resp.json() if kind == "json" else resp.text
113
- self._cache_put(key, value)
 
 
 
 
 
 
 
 
114
  return value
115
  raise RuntimeError(f"no answer from {host}") # not reached: the last attempt returns or raises
116
 
@@ -137,11 +222,11 @@ class Http:
137
 
138
  def _cache_get(self, key: str) -> Any:
139
  path = self._cache_path(key)
140
- if not path or not path.exists():
141
- return None
142
- if time.time() - path.stat().st_mtime > CACHE_DAYS * 86400:
143
  return None
144
- try:
 
 
145
  return json.loads(path.read_text(encoding="utf-8"))["value"]
146
  except (OSError, ValueError, KeyError):
147
  return None
@@ -164,3 +249,40 @@ def _retry_after(resp: httpx.Response) -> float | None:
164
  if value and value.isdigit():
165
  return min(float(value), 30.0)
166
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  import hashlib
6
  import json
7
  import logging
8
+ import os
9
+ import queue
10
+ import re
11
  import threading
12
  import time
13
+ from collections.abc import Callable
14
  from pathlib import Path
15
  from typing import Any
16
  from urllib.parse import urlsplit
 
40
  _NEXT_LOCK = threading.Lock()
41
 
42
 
43
+ class BadAnswer(httpx.HTTPError):
44
+ """A source answered, but not with what was asked for (see `check` in `Http.get_json`)."""
45
+
46
+
47
+ # One set of open connections for the whole process: every search talks to the same few hosts, and a new TLS
48
+ # handshake with each of them for each search is time the user waits.
49
+ _SHARED: dict[tuple[float, str], httpx.Client] = {}
50
+ _SHARED_LOCK = threading.Lock()
51
+
52
+
53
+ def _shared_client(settings: Settings) -> httpx.Client:
54
+ key = (settings.timeout, settings.user_agent)
55
+ with _SHARED_LOCK:
56
+ client = _SHARED.get(key)
57
+ if client is None or client.is_closed:
58
+ client = _SHARED[key] = httpx.Client(
59
+ timeout=settings.timeout, follow_redirects=True, headers={"User-Agent": settings.user_agent}
60
+ )
61
+ return client
62
+
63
+
64
+ def plain_error(err: Exception) -> str:
65
+ """An error for the log without the address it came from: that holds the search words and can hold a key."""
66
+ text = re.sub(r"https?://([^/\s'\"?]+)[^\s'\"]*", r"\1", f"{type(err).__name__}: {err}")
67
+ return text.split("\n")[0][:300]
68
+
69
+
70
  class Http:
71
  def __init__(
72
  self, settings: Settings | None = None, transport: httpx.BaseTransport | None = None, pace: bool = True
73
  ) -> None:
74
  self.settings = settings or Settings.from_env()
75
+ self._own = transport is not None # a client of its own only when the caller brings a transport (tests)
76
+ if self._own:
77
+ self._client = httpx.Client(
78
+ timeout=self.settings.timeout,
79
+ transport=transport,
80
+ follow_redirects=True,
81
+ headers={"User-Agent": self.settings.user_agent},
82
+ )
83
+ else:
84
+ self._client = _shared_client(self.settings)
85
  self._pace = dict(PACE) if pace else {}
86
  if pace and self.settings.ncbi_api_key:
87
  self._pace["eutils.ncbi.nlm.nih.gov"] = 0.11
88
 
89
  def close(self) -> None:
90
+ if self._own:
91
+ self._client.close()
92
 
93
  def __enter__(self) -> Http:
94
  return self
 
97
  self.close()
98
 
99
  # ---- public helpers ---------------------------------------------------------------------------------------------
100
+ def get_json(
101
+ self,
102
+ url: str,
103
+ params: dict[str, Any] | None = None,
104
+ headers: dict[str, str] | None = None,
105
+ check: Callable[[Any], bool] | None = None,
106
+ hedge: float | None = None,
107
+ keep: Callable[[Any], bool] | None = None,
108
+ ) -> Any:
109
+ """`check` says whether an answer is a real one. A source can answer 200 with an empty shell; such an answer
110
+ is asked for again and never kept in the cache. `keep` says whether an answer may go into the cache at all:
111
+ an error a source reports inside a 200 answer is returned to the caller, and asked for anew the next time.
112
+ `hedge` is for small requests to a source that is sometimes slow for no reason of ours: after that many
113
+ seconds without an answer the request is sent a second time, and the first answer to arrive is taken."""
114
+
115
+ def ask() -> Any:
116
+ return self._request("GET", url, params=params, headers=headers, kind="json", check=check, keep=keep)
117
+
118
+ return self._first_of_two(ask, hedge) if hedge else ask()
119
+
120
+ @staticmethod
121
+ def _first_of_two(ask: Callable[[], Any], after: float) -> Any:
122
+ box: queue.SimpleQueue[tuple[bool, Any]] = queue.SimpleQueue()
123
+
124
+ def run() -> None:
125
+ try:
126
+ box.put((True, ask()))
127
+ except Exception as err: # handed to the caller below
128
+ box.put((False, err))
129
+
130
+ threading.Thread(target=run, daemon=True).start()
131
+ try:
132
+ ok, value = box.get(timeout=after)
133
+ except queue.Empty:
134
+ threading.Thread(target=run, daemon=True).start()
135
+ ok, value = box.get()
136
+ if not ok: # the first one back failed: the other may still answer
137
+ ok, value = box.get()
138
+ if ok:
139
+ return value
140
+ raise value
141
 
142
  def get_text(self, url: str, params: dict[str, Any] | None = None) -> str:
143
  return self._request("GET", url, params=params, kind="text")
144
 
145
+ def post_form_text(self, url: str, data: dict[str, Any], check: Callable[[Any], bool] | None = None) -> str:
146
+ return self._request("POST", url, data=data, kind="text", check=check)
147
 
148
  def post_json(self, url: str, payload: dict[str, Any]) -> Any:
149
  return self._request("POST", url, json_body=payload, kind="json")
 
159
  json_body: dict[str, Any] | None = None,
160
  headers: dict[str, str] | None = None,
161
  kind: str,
162
+ check: Callable[[Any], bool] | None = None,
163
+ keep: Callable[[Any], bool] | None = None,
164
  ) -> Any:
165
  key = self._key(method, url, params, data, json_body, headers)
166
  cached = self._cache_get(key)
167
+ if cached is not None and (check is None or check(cached)) and (keep is None or keep(cached)):
168
  return cached
169
  host = urlsplit(url).hostname or ""
170
  delay = 1.0
 
187
  continue
188
  resp.raise_for_status()
189
  value = resp.json() if kind == "json" else resp.text
190
+ if check is not None and not check(value):
191
+ if attempt == 3:
192
+ raise BadAnswer(f"{host} keeps sending an empty answer")
193
+ log.warning("%s sent an empty answer, asking again", host)
194
+ time.sleep(delay)
195
+ delay *= 2
196
+ continue
197
+ if keep is None or keep(value):
198
+ self._cache_put(key, value)
199
  return value
200
  raise RuntimeError(f"no answer from {host}") # not reached: the last attempt returns or raises
201
 
 
222
 
223
  def _cache_get(self, key: str) -> Any:
224
  path = self._cache_path(key)
225
+ if not path:
 
 
226
  return None
227
+ try: # the file can go at any moment: the cache is tidied while searches run
228
+ if time.time() - path.stat().st_mtime > CACHE_DAYS * 86400:
229
+ return None
230
  return json.loads(path.read_text(encoding="utf-8"))["value"]
231
  except (OSError, ValueError, KeyError):
232
  return None
 
249
  if value and value.isdigit():
250
  return min(float(value), 30.0)
251
  return None
252
+
253
+
254
+ def tidy_cache(cache_dir: Path | None, max_mb: int | None = None) -> tuple[int, int]:
255
+ """Removes cached answers that are too old to be used, then the oldest ones until the cache fits in `max_mb`
256
+ (LABSCOUT_CACHE_MAX_MB, 3,000 by default). Returns (files removed, megabytes left). Without this the cache only
257
+ grows: one large search leaves over a hundred megabytes."""
258
+ if not cache_dir or not cache_dir.is_dir():
259
+ return 0, 0
260
+ if max_mb is None:
261
+ max_mb = int(os.environ.get("LABSCOUT_CACHE_MAX_MB", "3000"))
262
+ now = time.time()
263
+ kept: list[tuple[float, int, Path]] = []
264
+ removed = 0
265
+ for path in cache_dir.glob("*/*"):
266
+ try:
267
+ st = path.stat()
268
+ except OSError:
269
+ continue
270
+ if now - st.st_mtime > CACHE_DAYS * 86400 or path.suffix == ".tmp" and now - st.st_mtime > 3600:
271
+ removed += _unlink(path)
272
+ else:
273
+ kept.append((st.st_mtime, st.st_size, path))
274
+ size = sum(n for _, n, _ in kept)
275
+ for _, n, path in sorted(kept):
276
+ if size <= max_mb * 1_000_000:
277
+ break
278
+ removed += _unlink(path)
279
+ size -= n
280
+ return removed, size // 1_000_000
281
+
282
+
283
+ def _unlink(path: Path) -> int:
284
+ try:
285
+ path.unlink()
286
+ return 1
287
+ except OSError:
288
+ return 0
src/labscout/labs.py CHANGED
@@ -2,12 +2,13 @@
2
 
3
  from __future__ import annotations
4
 
 
5
  from collections import Counter, defaultdict
6
  from collections.abc import Callable
7
  from datetime import date
8
 
9
  from .models import Author, Lab, Organization, Paper
10
- from .text import fold, query_terms, signals_of, species_of
11
 
12
  Resolve = Callable[[str], "Organization | None"]
13
 
@@ -28,18 +29,299 @@ def lead_affiliation(p: Paper) -> tuple[Author | None, str]:
28
  return last, first_aff
29
 
30
 
31
- def build(papers: list[Paper], resolve: Resolve, query: str = "", top: int | None = None) -> list[Lab]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  terms = query_terms(query)
33
- groups: dict[tuple[str, str], list[tuple[Paper, Author, Organization]]] = defaultdict(list)
 
34
  for p in papers:
35
  lead, aff = lead_affiliation(p)
36
  if lead is None:
37
  continue
38
  org = resolve(aff) if aff else None
39
  org = org or Organization(name=aff.split(",")[0].strip() if aff else "Unknown organisation", match="")
40
- place = org.ror or fold(org.name)
41
- groups[(lead.key, place)].append((p, lead, org))
42
- groups = _join_same_person(groups)
 
 
 
 
 
 
 
 
 
43
 
44
  # where each name appears on the papers in any position, for "also co-author of"
45
  appearances: dict[str, list[tuple[Paper, Author]]] = defaultdict(list)
@@ -52,19 +334,22 @@ def build(papers: list[Paper], resolve: Resolve, query: str = "", top: int | Non
52
 
53
  labs = []
54
  this_year = date.today().year
55
- for (key, _), items in groups.items():
 
56
  items.sort(key=lambda t: t[0].year or 0, reverse=True)
57
  lead = max((t[1] for t in items), key=lambda a: (bool(a.orcid), len(a.fore_name)))
58
- org = items[0][2]
59
  lab_papers = [t[0] for t in items]
60
  years = [p.year for p in lab_papers if p.year]
61
- text = " ".join(_paper_text(p) for p in lab_papers)
62
- species = sorted({s for p in lab_papers for s in species_of(p.mesh, _paper_text(p))})
63
- signals = signals_of(text)
64
- matched = [t for t in terms if t in fold(text)]
 
 
65
  funders = [f for f, _ in Counter(f for p in lab_papers for f in p.funders).most_common(8)]
66
  senior = len(lab_papers)
67
- other = _coauthored(appearances[key], items, org)
68
  recent = bool(years) and max(years) >= this_year - 2
69
  score = 3 * senior + other + (2 if recent else 0) + 0.5 * len(signals) + 0.5 * len(matched)
70
  if any(p.has_data_links for p in lab_papers):
@@ -87,6 +372,7 @@ def build(papers: list[Paper], resolve: Resolve, query: str = "", top: int | Non
87
  matched_terms=matched,
88
  funders=funders,
89
  score=score,
 
90
  )
91
  )
92
  labs.sort(key=lambda lab: (-lab.score, -(lab.last_year or 0), lab.lead))
@@ -95,14 +381,20 @@ def build(papers: list[Paper], resolve: Resolve, query: str = "", top: int | Non
95
  return labs[:top] if top else labs
96
 
97
 
98
- def _coauthored(appearances: list[tuple[Paper, Author]], items: list, org: Organization) -> int:
99
  """Papers the lab's lead co-authored, counted only where the co-author is clearly the same person: the same ORCID
100
- iD, or an affiliation naming the lab's city or organisation. A common name such as "Li J" is many people, so a bare
101
- name does not count."""
102
  led = {id(t[0]) for t in items}
103
  orcids = {t[1].orcid for t in items if t[1].orcid}
104
- own = {fold(t[1].affiliations[0]) for t in items if t[1].affiliations}
105
- marks = [fold(x) for x in (org.city, org.name) if x and len(x) >= 4]
 
 
 
 
 
 
106
  n = 0
107
  for p, a in appearances:
108
  if id(p) in led:
@@ -110,38 +402,18 @@ def _coauthored(appearances: list[tuple[Paper, Author]], items: list, org: Organ
110
  if a.orcid and a.orcid in orcids:
111
  n += 1
112
  continue
113
- text = fold(" ".join(a.affiliations))
114
- if text and (any(m in text for m in marks) or any(o and o == fold(x) for o in own for x in a.affiliations)):
 
 
 
 
 
 
115
  n += 1
116
  return n
117
 
118
 
119
- def _join_same_person(groups: dict[tuple[str, str], list]) -> dict[tuple[str, str], list]:
120
- """One person at two organisations is one lab when it is clearly the same person: the same city (a university and
121
- its hospital) or the same ORCID iD. The organisation of the most recent paper names the lab. The same name in
122
- different cities without a shared ORCID iD stays apart: it may be two people."""
123
- by_person: dict[str, list[tuple[str, str]]] = defaultdict(list)
124
- for key in groups:
125
- by_person[key[0]].append(key)
126
- for keys in by_person.values():
127
- if len(keys) < 2:
128
- continue
129
- keys.sort(key=lambda k: -len(groups[k]))
130
- for k in keys[1:]:
131
- org = groups[k][0][2]
132
- ids = {t[1].orcid for t in groups[k] if t[1].orcid}
133
- for main in keys:
134
- if main == k or main not in groups:
135
- continue
136
- morg = groups[main][0][2]
137
- same = org.city and morg.city and fold(org.city) == fold(morg.city) and org.country == morg.country
138
- same = same or bool(ids & {t[1].orcid for t in groups[main] if t[1].orcid})
139
- if same and len(groups[main]) >= len(groups[k]):
140
- groups[main] += groups.pop(k)
141
- break
142
- return groups
143
-
144
-
145
  def explain(lab: Lab) -> str:
146
  """One plain sentence on why the lab came up."""
147
  span = (
 
2
 
3
  from __future__ import annotations
4
 
5
+ import re
6
  from collections import Counter, defaultdict
7
  from collections.abc import Callable
8
  from datetime import date
9
 
10
  from .models import Author, Lab, Organization, Paper
11
+ from .text import SIGNALS, fold, query_terms, signals_of, species_of
12
 
13
  Resolve = Callable[[str], "Organization | None"]
14
 
 
29
  return last, first_aff
30
 
31
 
32
+ # one given name written in several ways, all read as the first
33
+ _SAME_NAME = {"md": "muhammad", "mohd": "muhammad", "mohammad": "muhammad", "mohammed": "muhammad"}
34
+ _SAME_NAME |= {"mohamed": "muhammad", "muhammed": "muhammad", "mohamad": "muhammad"}
35
+
36
+
37
+ def given_name(fore: str) -> tuple[str, ...]:
38
+ """The given names as printed, lower case and without accents, an initial as one letter: ("susan", "s") for
39
+ "Susan S.", ("chienchang",) for "Chien-Chang", ("seog", "ju") for "Seog Ju", ("h", "c") for "H-C" or "HC"."""
40
+ raw = (fore or "").strip()
41
+ if raw.isalpha() and raw.isupper() and len(raw) <= 4: # initials printed as one word
42
+ return tuple(raw.lower())
43
+ out: list[str] = []
44
+ for word in fold(raw).replace(".", " ").split():
45
+ parts = [re.sub(r"[^a-z]", "", x) for x in word.split("-")]
46
+ parts = [x for x in parts if x]
47
+ if parts and all(len(x) == 1 for x in parts):
48
+ out += parts
49
+ elif parts:
50
+ name = "".join(parts)
51
+ name = _SAME_NAME.get(name, name)
52
+ if len(name) <= 5 and not set(name) & set("aeiouy"): # "Rjbj": initials printed as a word
53
+ out += list(name)
54
+ else:
55
+ out.append(name)
56
+ return tuple(out)
57
+
58
+
59
+ def has_given(name: tuple[str, ...]) -> bool:
60
+ """Whether a printed name holds a full given name, not only initials."""
61
+ return any(len(x) >= 2 for x in name)
62
+
63
+
64
+ def same_given(a: tuple[str, ...], b: tuple[str, ...]) -> bool:
65
+ """Whether two printed given names can be one person: the same letters ("Seog Ju", "Seog-Ju", "Seogju"); or name
66
+ by name the same, where an initial stands for a name that starts with it ("M Brandon", "Michael Brandon"; "Orfeu",
67
+ "Orfeu M"), with at least one full name in common. "Chien-Chang" and "Chien-Nan" are two people; so are
68
+ "Xiaoming" and "Xiaoping", one letter apart, and "John A" and "John B"."""
69
+ if "".join(x for x in a if len(x) > 1) == "".join(x for x in b if len(x) > 1) != "":
70
+ initials = zip((x for x in a if len(x) == 1), (y for y in b if len(y) == 1), strict=False)
71
+ return all(x == y for x, y in initials)
72
+ common = False
73
+ for x, y in zip(a, b, strict=False):
74
+ if len(x) == 1 or len(y) == 1:
75
+ if x[0] != y[0]:
76
+ return False
77
+ elif x == y:
78
+ common = True
79
+ else:
80
+ return False
81
+ return common
82
+
83
+
84
+ def _short_form(x: str, y: str) -> bool:
85
+ """One name starts with the other ("matt", "matthew"). Alone this proves nothing: "Yan" and "Yanping" are two
86
+ people."""
87
+ short, long = (x, y) if len(x) <= len(y) else (y, x)
88
+ return len(short) >= 3 and short != long and long.startswith(short)
89
+
90
+
91
+ def _split_people(entries: list[tuple[Paper, Author, Organization, str]]) -> list[list[tuple]]:
92
+ """The papers of one "last name, first initial" as the different people behind it: records whose given names
93
+ cannot be one person are kept apart (two people in one hospital often share a last name and an initial), and
94
+ records with the same ORCID iD stay together whatever the spelling. A record that prints only initials goes with
95
+ the person of its ORCID iD, else with the person who has most papers at the same organisation."""
96
+ printed = [given_name(e[1].fore_name) for e in entries]
97
+ names = Counter(n for n in printed if has_given(n))
98
+ if len(names) <= 1 and not any(e[1].orcid for e in entries):
99
+ return [entries]
100
+ people: list[tuple[str, ...]] = [] # one printed name stands for each person, the most frequent first
101
+ person_of: dict[tuple[str, ...], int] = {}
102
+ for name, _ in sorted(names.items(), key=lambda kv: (-kv[1], -len("".join(kv[0])), kv[0])):
103
+ hit = next((i for i, known in enumerate(people) if same_given(name, known)), None)
104
+ if hit is None:
105
+ people.append(name)
106
+ hit = len(people) - 1
107
+ person_of[name] = hit
108
+ alias = list(range(len(people))) # two spellings with one ORCID iD are one person
109
+
110
+ def root(i: int) -> int:
111
+ while alias[i] != i:
112
+ i = alias[i]
113
+ return i
114
+
115
+ by_orcid: dict[str, int] = {}
116
+ for e, name in zip(entries, printed, strict=True):
117
+ if e[1].orcid and has_given(name):
118
+ i = root(person_of[name])
119
+ j = root(by_orcid.setdefault(e[1].orcid, i))
120
+ if i != j:
121
+ alias[max(i, j)] = min(i, j)
122
+ # a short form of a name ("Matt" for "Matthew") is the same person when the papers share two co-authors
123
+ short_forms = [
124
+ (i, j)
125
+ for i, x in enumerate(people)
126
+ for j, y in enumerate(people)
127
+ if i < j and root(i) != root(j) and _short_form(x[0], y[0])
128
+ ]
129
+ if short_forms:
130
+ mates: dict[int, set[tuple[str, str]]] = defaultdict(set)
131
+ for e, name in zip(entries, printed, strict=True):
132
+ if has_given(name):
133
+ mates[person_of[name]] |= _coauthors([e])
134
+ for i, j in short_forms:
135
+ if root(i) != root(j) and len(mates[i] & mates[j]) >= 2:
136
+ alias[max(root(i), root(j))] = min(root(i), root(j))
137
+ at_place: dict[str, Counter[int]] = defaultdict(Counter)
138
+ overall: Counter[int] = Counter()
139
+ for e, name in zip(entries, printed, strict=True):
140
+ if has_given(name):
141
+ i = root(person_of[name])
142
+ at_place[e[3]][i] += 1
143
+ overall[i] += 1
144
+
145
+ def fits(initials: tuple[str, ...], i: int) -> bool:
146
+ """The initials of a record agree with a person's name, as far as both go."""
147
+ return all(x[0] == y[0] for x, y in zip(initials, people[i], strict=False))
148
+
149
+ out: dict[int, list[tuple]] = defaultdict(list)
150
+ for e, name in zip(entries, printed, strict=True):
151
+ if has_given(name):
152
+ i = root(person_of[name])
153
+ elif e[1].orcid in by_orcid:
154
+ i = root(by_orcid[e[1].orcid])
155
+ else:
156
+ here = [k for k in at_place[e[3]] if fits(name, k)] or [k for k in overall if fits(name, k)]
157
+ pool = at_place[e[3]] if here and here[0] in at_place[e[3]] else overall
158
+ i = min(here, key=lambda k: (-pool[k], k)) if here else -1 # nobody it could be: a person of its own
159
+ out[i].append(e)
160
+ return [out[i] for i in sorted(out)]
161
+
162
+
163
+ def _coauthors(items: list[tuple]) -> set[tuple[str, str]]:
164
+ """The co-authors on a person's papers who are printed with a full given name, as (name key, given names)."""
165
+ found = set()
166
+ for p, lead, *_ in items:
167
+ for a in p.authors:
168
+ if a is not lead:
169
+ name = given_name(a.fore_name)
170
+ if has_given(name):
171
+ found.add((a.key, "".join(x for x in name if len(x) > 1)))
172
+ return found
173
+
174
+
175
+ def _join_places(places: dict[str, list[tuple]], named: bool, crowded: bool = False) -> list[list[tuple]]:
176
+ """One person at two organisations is one lab when it is clearly the same person: the same city (a university and
177
+ its hospital), the same ORCID iD, or, for a person printed with a full given name, the same co-authors (two of
178
+ them, or one in the same country). Under a last name and initial that many people share (`crowded`) one
179
+ co-author in common can be chance, so two are asked for. The same name in different cities with none of these
180
+ stays apart: it may be two people."""
181
+ keys = sorted(places, key=lambda k: (-len(places[k]), k))
182
+ if len(keys) < 2:
183
+ return list(places.values())
184
+ known: dict[str, set[tuple[str, str]]] = {} # co-authors by place, worked out when first needed
185
+
186
+ def coauthors(place: str) -> set[tuple[str, str]]:
187
+ if place not in known:
188
+ known[place] = _coauthors(places[place])
189
+ return known[place]
190
+
191
+ for k in keys[1:]:
192
+ org = places[k][0][2]
193
+ ids = {t[1].orcid for t in places[k] if t[1].orcid}
194
+ mates = coauthors(k) if named else set()
195
+ for main in keys:
196
+ if main == k or main not in places or len(places[main]) < len(places[k]):
197
+ continue
198
+ morg = places[main][0][2]
199
+ same = org.city and morg.city and fold(org.city) == fold(morg.city) and org.country == morg.country
200
+ same = same or bool(ids & {t[1].orcid for t in places[main] if t[1].orcid})
201
+ same = same or (bool(org.name) and fold(org.name) == fold(morg.name)) # one of them without its place
202
+ if not same and mates:
203
+ shared = len(mates & coauthors(main))
204
+ nowhere = not (org.ror or org.country) # the affiliation named no organisation and no country
205
+ near = not crowded and bool(org.country) and org.country == morg.country
206
+ same = shared >= 2 or (shared == 1 and (nowhere or near))
207
+ if same:
208
+ places[main] += places.pop(k)
209
+ if main in known:
210
+ known[main] |= known.pop(k, None) or _coauthors(places[main])
211
+ break
212
+ if named and len(places) == 2:
213
+ # papers that print no affiliation at all, of a person known at one place only: that place
214
+ (a, x), (b, y) = places.items()
215
+ for lost, kept in ((a, b), (b, a)):
216
+ if all(not (t[2].ror or t[2].country) for t in places[lost]) and any(t[2].ror for t in places[kept]):
217
+ places[kept] += places.pop(lost)
218
+ break
219
+ return list(places.values())
220
+
221
+
222
+ def _name_words(a: Author) -> tuple[str, ...]:
223
+ """Every word of a name in the order it is printed, whichever of them the source filed as the last name."""
224
+ return given_name(a.fore_name) + tuple(fold(a.last_name).replace("-", " ").split())
225
+
226
+
227
+ def _join_spellings(groups: list[tuple[str, list[tuple]]]) -> list[tuple[str, list[tuple]]]:
228
+ """One name filed in two ways has two keys: "de Mello, Marco Tulio" and "Mello, Marco Tulio de", "Driller,
229
+ Matthew W" and "W Driller, Matthew". Where the words of the whole name are the same, such labs are joined by the
230
+ rules for one person's places. A name of initials and one word is too little to go by and is left alone."""
231
+ by_words: dict[tuple[str, ...], list[int]] = defaultdict(list)
232
+ for i, (_, items) in enumerate(groups):
233
+ for words in {_name_words(t[1]) for t in items}:
234
+ if sum(len(w) > 1 for w in words) >= 2:
235
+ by_words[words].append(i)
236
+ gone: set[int] = set()
237
+ for found in by_words.values():
238
+ found = [i for i in found if i not in gone]
239
+ if len({groups[i][0] for i in found}) < 2:
240
+ continue
241
+ places = {str(i): groups[i][1] for i in found}
242
+ _join_places(places, True)
243
+ for i in found:
244
+ if str(i) in places:
245
+ groups[i] = (groups[i][0], places[str(i)])
246
+ else:
247
+ gone.add(i)
248
+ return [g for i, g in enumerate(groups) if i not in gone]
249
+
250
+
251
+ def _home(items: list[tuple]) -> tuple[Organization, list[str]]:
252
+ """The organisation that names a lab whose papers carry several: one with a known place before one without, then
253
+ the one with most papers in the last five years, then with most papers. The others are returned by name."""
254
+ newest = max((t[0].year or 0 for t in items), default=0)
255
+ seen: dict[str, list] = {}
256
+ for p, _, org, place in items:
257
+ row = seen.setdefault(place, [org, 0, 0, 0])
258
+ row[1] += 1
259
+ row[2] += (p.year or 0) >= newest - 4
260
+ row[3] = max(row[3], p.year or 0)
261
+ ranked = sorted(seen.values(), key=lambda r: (r[0].lat is None, not r[0].ror, -r[2], -r[1], -r[3], r[0].name))
262
+ others = [r[0].name for r in ranked[1:] if r[0].ror and r[0].name != ranked[0][0].name] # known places only
263
+ return ranked[0][0], list(dict.fromkeys(others))[:3]
264
+
265
+
266
+ class _Features:
267
+ """What a search needs from each paper's text, worked out once per paper: the text without accents and in lower
268
+ case, the kinds of data and the species it mentions, and which search words it holds. A lab's features are the
269
+ union over its papers."""
270
+
271
+ def __init__(self, terms: list[str]) -> None:
272
+ self.terms = terms
273
+ self._memo: dict[int, tuple[list[str], list[str], set[str]]] = {}
274
+ self._folded: dict[str, str] = {}
275
+
276
+ def of(self, p: Paper) -> tuple[list[str], list[str], set[str]]:
277
+ got = self._memo.get(id(p))
278
+ if got is None:
279
+ text = _paper_text(p)
280
+ t = fold(text)
281
+ got = (signals_of(text, t), species_of(p.mesh, text, t), {w for w in self.terms if w in t})
282
+ self._memo[id(p)] = got
283
+ return got
284
+
285
+ def fold(self, s: str) -> str:
286
+ """fold() with a memory: the same affiliation text comes back for every paper of an author."""
287
+ v = self._folded.get(s)
288
+ if v is None:
289
+ v = self._folded[s] = fold(s)
290
+ return v
291
+
292
+
293
+ def read_papers(papers: list[Paper], query: str = "") -> _Features:
294
+ """The per-paper part of `build`, done ahead: the caller can run it while it waits for something else."""
295
+ feats = _Features(query_terms(query))
296
+ for p in papers:
297
+ feats.of(p)
298
+ return feats
299
+
300
+
301
+ def build(
302
+ papers: list[Paper], resolve: Resolve, query: str = "", top: int | None = None, feats: _Features | None = None
303
+ ) -> list[Lab]:
304
  terms = query_terms(query)
305
+ feats = feats or _Features(terms)
306
+ by_name: dict[str, list[tuple[Paper, Author, Organization, str]]] = defaultdict(list)
307
  for p in papers:
308
  lead, aff = lead_affiliation(p)
309
  if lead is None:
310
  continue
311
  org = resolve(aff) if aff else None
312
  org = org or Organization(name=aff.split(",")[0].strip() if aff else "Unknown organisation", match="")
313
+ by_name[lead.key].append((p, lead, org, org.ror or feats.fold(org.name)))
314
+ # a lab is one person at one organisation: first the different people behind a name, then their places
315
+ groups: list[tuple[str, list[tuple[Paper, Author, Organization, str]]]] = []
316
+ for key, entries in by_name.items():
317
+ people = _split_people(entries)
318
+ for person in people:
319
+ places: dict[str, list[tuple]] = defaultdict(list)
320
+ for e in person:
321
+ places[e[3]].append(e)
322
+ named = any(has_given(given_name(e[1].fore_name)) for e in person)
323
+ groups += [(key, items) for items in _join_places(places, named, crowded=len(people) >= 3)]
324
+ groups = _join_spellings(groups)
325
 
326
  # where each name appears on the papers in any position, for "also co-author of"
327
  appearances: dict[str, list[tuple[Paper, Author]]] = defaultdict(list)
 
334
 
335
  labs = []
336
  this_year = date.today().year
337
+ signal_order = [label for label, _, _ in SIGNALS]
338
+ for key, items in groups:
339
  items.sort(key=lambda t: t[0].year or 0, reverse=True)
340
  lead = max((t[1] for t in items), key=lambda a: (bool(a.orcid), len(a.fore_name)))
341
+ org, also_at = _home(items)
342
  lab_papers = [t[0] for t in items]
343
  years = [p.year for p in lab_papers if p.year]
344
+ of = [feats.of(p) for p in lab_papers]
345
+ have = {s for f in of for s in f[0]}
346
+ signals = [s for s in signal_order if s in have]
347
+ species = sorted({s for f in of for s in f[1]})
348
+ found = set().union(*(f[2] for f in of))
349
+ matched = [t for t in terms if t in found]
350
  funders = [f for f, _ in Counter(f for p in lab_papers for f in p.funders).most_common(8)]
351
  senior = len(lab_papers)
352
+ other = _coauthored(appearances[key], items, org, feats)
353
  recent = bool(years) and max(years) >= this_year - 2
354
  score = 3 * senior + other + (2 if recent else 0) + 0.5 * len(signals) + 0.5 * len(matched)
355
  if any(p.has_data_links for p in lab_papers):
 
372
  matched_terms=matched,
373
  funders=funders,
374
  score=score,
375
+ other_organizations=also_at,
376
  )
377
  )
378
  labs.sort(key=lambda lab: (-lab.score, -(lab.last_year or 0), lab.lead))
 
381
  return labs[:top] if top else labs
382
 
383
 
384
+ def _coauthored(appearances: list[tuple[Paper, Author]], items: list, org: Organization, feats: _Features) -> int:
385
  """Papers the lab's lead co-authored, counted only where the co-author is clearly the same person: the same ORCID
386
+ iD, or an affiliation naming one of the lab's cities or organisations. A common name such as "Li J" is many
387
+ people, so a bare name does not count, and a co-author printed with another given name is another person."""
388
  led = {id(t[0]) for t in items}
389
  orcids = {t[1].orcid for t in items if t[1].orcid}
390
+ own = {feats.fold(t[1].affiliations[0]) for t in items if t[1].affiliations}
391
+ own.discard("")
392
+ names = {n for n in (given_name(t[1].fore_name) for t in items) if has_given(n)}
393
+ marks = []
394
+ for o in dict.fromkeys(id(t[2]) for t in items):
395
+ home = next(t[2] for t in items if id(t[2]) == o)
396
+ marks += [feats.fold(x) for x in (home.city, home.name) if x and len(x) >= 4]
397
+ marks = list(dict.fromkeys(marks)) or [feats.fold(x) for x in (org.city, org.name) if x and len(x) >= 4]
398
  n = 0
399
  for p, a in appearances:
400
  if id(p) in led:
 
402
  if a.orcid and a.orcid in orcids:
403
  n += 1
404
  continue
405
+ if not a.affiliations:
406
+ continue
407
+ printed = given_name(a.fore_name)
408
+ if has_given(printed) and names and not any(same_given(printed, known) for known in names):
409
+ continue
410
+ folded = [feats.fold(x) for x in a.affiliations]
411
+ text = " ".join(folded)
412
+ if text and (any(m in text for m in marks) or any(x in own for x in folded)):
413
  n += 1
414
  return n
415
 
416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417
  def explain(lab: Lab) -> str:
418
  """One plain sentence on why the lab came up."""
419
  span = (
src/labscout/models.py CHANGED
@@ -22,7 +22,11 @@ class Author:
22
 
23
  @property
24
  def key(self) -> str:
25
- return name_key(self.last_name, self.fore_name, self.initials)
 
 
 
 
26
 
27
 
28
  @dataclass
@@ -172,11 +176,20 @@ class Lab:
172
  grants: list[Grant] = field(default_factory=list)
173
  score: float = 0.0
174
  why: str = ""
 
 
 
 
 
 
 
175
 
176
  def summary(self, max_papers: int = 5) -> dict[str, Any]:
177
  org = self.organization
178
  return {
179
  "lead": self.lead,
 
 
180
  "orcid": self.orcid,
181
  "organization": org.name,
182
  "ror": org.ror,
@@ -185,6 +198,7 @@ class Lab:
185
  "lat": org.lat,
186
  "lon": org.lon,
187
  "organization_match": org.match,
 
188
  "papers_as_senior_author": self.senior_papers,
189
  "papers_as_coauthor": self.other_papers,
190
  "years": [self.first_year, self.last_year],
 
22
 
23
  @property
24
  def key(self) -> str:
25
+ """Last name and first initial; worked out once, because a search asks for it many times per author."""
26
+ k = self.__dict__.get("_key")
27
+ if k is None:
28
+ k = self.__dict__["_key"] = name_key(self.last_name, self.fore_name, self.initials)
29
+ return k
30
 
31
 
32
  @dataclass
 
176
  grants: list[Grant] = field(default_factory=list)
177
  score: float = 0.0
178
  why: str = ""
179
+ other_organizations: list[str] = field(default_factory=list) # where else the same person's papers were printed
180
+
181
+ @property
182
+ def author_search(self) -> str:
183
+ """The lead as PubMed's author search wants it: last name and initials ("Redline S")."""
184
+ initials = "".join(w[0] for w in self.fore_name.replace("-", " ").replace(".", " ").split() if w[:1].isalpha())
185
+ return f"{self.last_name} {initials.upper()[:2]}".strip()
186
 
187
  def summary(self, max_papers: int = 5) -> dict[str, Any]:
188
  org = self.organization
189
  return {
190
  "lead": self.lead,
191
+ "lead_sorted": ", ".join(x for x in (self.last_name, self.fore_name) if x), # "Van Someren, Eus J W"
192
+ "author_search": self.author_search,
193
  "orcid": self.orcid,
194
  "organization": org.name,
195
  "ror": org.ror,
 
198
  "lat": org.lat,
199
  "lon": org.lon,
200
  "organization_match": org.match,
201
+ "also_at": self.other_organizations,
202
  "papers_as_senior_author": self.senior_papers,
203
  "papers_as_coauthor": self.other_papers,
204
  "years": [self.first_year, self.last_year],
src/labscout/pipeline.py CHANGED
@@ -6,16 +6,17 @@ import logging
6
  import os
7
  import re
8
  import threading
 
9
  from collections.abc import Callable, Iterable
10
  from concurrent.futures import ThreadPoolExecutor
11
  from dataclasses import dataclass, field
12
- from datetime import datetime, timezone
13
  from typing import Any
14
 
15
  from . import __version__
16
  from .errors import SearchError
17
- from .http import Http
18
- from .labs import build, lead_affiliation
19
  from .models import Lab, Paper
20
  from .sources import PUBLICATION_SOURCES, europepmc, nih_reporter, pubmed
21
  from .sources.ror import Resolver
@@ -27,6 +28,12 @@ LABELS = {"pubmed": "PubMed", "europepmc": "Europe PMC"}
27
  ORDERS = ("relevance", "newest")
28
  # Long searches that may run at the same time, from the web page and from assistants together.
29
  SEARCH_SLOTS = threading.BoundedSemaphore(int(os.environ.get("LABSCOUT_PARALLEL_SEARCHES", "2")))
 
 
 
 
 
 
30
  # progress(step, text): step is a source name, "organisations" or "labs"; text says what is happening, for people
31
  Progress = Callable[[str, str], None]
32
 
@@ -43,6 +50,7 @@ class Result:
43
  found: dict[str, int] = field(default_factory=dict) # hits per source; `counts` says how many were read
44
  failed: list[str] = field(default_factory=list) # sources that did not answer
45
  translation: str = "" # how PubMed read the search
 
46
  order: str = "relevance"
47
  created: str = field(default_factory=lambda: datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"))
48
  version: str = __version__
@@ -57,11 +65,110 @@ class Result:
57
  "found": self.found,
58
  "sources_not_answering": self.failed,
59
  "pubmed_reading": self.translation,
 
60
  "created": self.created,
61
  "labs": [lab.summary(papers_per_lab) for lab in self.labs[:top]],
62
  }
63
 
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  def _title_key(p: Paper) -> str:
66
  return re.sub(r"[^a-z0-9]", "", fold(p.title))[:80] + str(p.year or "")
67
 
@@ -80,7 +187,13 @@ def merge(papers: Iterable[Paper]) -> list[Paper]:
80
  )
81
  if k
82
  ]
83
- hit = next((index[k] for k in keys if k in index), None)
 
 
 
 
 
 
84
  if hit is None:
85
  out.append(p)
86
  hit = p
@@ -127,12 +240,13 @@ def collect(
127
  if order not in ORDERS:
128
  raise SearchError(f"unknown order {order!r}; use relevance or newest")
129
  check_query(query)
 
130
  info = {} if info is None else info
131
  found_by: dict[str, int] = info.setdefault("found", {})
132
  failed: list[str] = info.setdefault("failed", [])
133
  papers: list[Paper] = []
134
  counts: dict[str, int] = {}
135
- srcs = list(sources)
136
  for src in srcs:
137
  if src not in ("pubmed", "europepmc"):
138
  raise SearchError(f"unknown source {src!r}; use one of {', '.join(PUBLICATION_SOURCES)}")
@@ -148,7 +262,7 @@ def collect(
148
  except SearchError:
149
  raise
150
  except Exception as err: # one source being down should not stop the others
151
- log.warning("%s failed: %s", src, err)
152
  return [], meta, True
153
 
154
  # the sources answer side by side: a big search takes as long as the slower source, not the sum of both
@@ -163,6 +277,8 @@ def collect(
163
  found_by[src] = int(meta["total"])
164
  if meta.get("translation"):
165
  info["translation"] = meta["translation"]
 
 
166
  if progress:
167
  if down:
168
  progress(src, f"{name} did not answer; going on without it")
@@ -185,9 +301,95 @@ def collect(
185
  return merged, counts
186
 
187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  def check_query(query: str) -> None:
189
  """Stop a search with an unclosed quote or bracket: the sources would read it another way without saying so (an
190
- open bracket can drop the years, for example)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  if query.count('"') % 2:
192
  raise SearchError('The search has a quote mark without its pair. Please check the quotes (").')
193
  depth = 0
@@ -199,6 +401,15 @@ def check_query(query: str) -> None:
199
  raise SearchError("The search has a bracket without its pair. Please check the brackets ( ).")
200
 
201
 
 
 
 
 
 
 
 
 
 
202
  def read_as(source: str, order: str) -> str:
203
  """Which papers a source gives first: "most relevant" (PubMed's Best Match), "most cited" (Europe PMC, whose own
204
  relevance order is mostly by date) or "newest"."""
@@ -238,12 +449,17 @@ def find_labs(
238
  own = http is None
239
  http = http or Http()
240
  try:
241
- srcs = list(sources)
242
  info: dict[str, Any] = {}
243
  papers, counts = collect(http, query, start, end, limit, srcs, order, info, progress)
244
  resolve = Resolver(http)
245
  if hasattr(resolve, "prefetch"):
246
  resolve.prefetch([a for a in (lead_affiliation(p)[1] for p in papers) if a])
 
 
 
 
 
247
  if progress:
248
  total = sum(1 for p in papers if lead_affiliation(p)[1])
249
  done = 0
@@ -256,7 +472,7 @@ def find_labs(
256
  return resolve(aff)
257
 
258
  progress("organisations", f"Matching organisations: 0 of {total} papers")
259
- labs = build(papers, counted if progress else resolve, query=query)
260
  if progress and hasattr(resolve, "memo"):
261
  kinds: dict[str, int] = {}
262
  for org in resolve.memo.values():
@@ -299,7 +515,12 @@ def find_labs(
299
  http, lab.last_name, first, lab.organization.name, since=start
300
  )
301
  except Exception as err:
302
- log.warning("NIH RePORTER failed for %s: %s", lab.lead, err)
 
 
 
 
 
303
  return Result(
304
  query=query,
305
  start=start,
@@ -311,6 +532,7 @@ def find_labs(
311
  found=info.get("found", {}),
312
  failed=info.get("failed", []),
313
  translation=info.get("translation", ""),
 
314
  order=order,
315
  )
316
  finally:
@@ -341,20 +563,47 @@ def profile(
341
  from .text import signals_of, species_of
342
 
343
  last, first = split_name(name)
344
- if name_key(last, first) in hidden_people()[1]:
345
- return {"name": name, "error": "This researcher asked not to be shown in LabScout."}
 
 
 
 
 
 
346
  own = http is None
347
  http = http or Http()
348
  try:
349
- query = f'"{last} {first[:1]}"[au]' if first else f"{last}[au]"
 
350
  if topic:
351
  query += f" AND ({topic})"
352
  papers = pubmed.search(http, query, limit=limit)
353
  key = name_key(last, first)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  resolve = Resolver(http)
 
 
 
 
355
  places: Counter[str] = Counter()
356
  orgs: dict[str, Any] = {}
357
  coauthors: Counter[str] = Counter()
 
358
  for p in papers:
359
  me = next((a for a in p.authors if a.key == key), None)
360
  if me and me.affiliations:
@@ -363,14 +612,21 @@ def profile(
363
  k = org.ror or org.name
364
  places[k] += 1
365
  orgs[k] = org
 
366
  for a in p.authors:
367
- if a.key != key:
368
  coauthors[a.display] += 1
 
369
  if organization:
370
  want = fold(organization)
371
- papers = [
372
- p for p in papers if any(want in fold(" ".join(a.affiliations)) for a in p.authors if a.key == key)
373
- ] or papers
 
 
 
 
 
374
  text = " ".join(" ".join([p.title, p.abstract, " ".join(p.mesh)]) for p in papers)
375
  topics = Counter(
376
  m
@@ -382,6 +638,7 @@ def profile(
382
  "name": name,
383
  "pubmed_query": query,
384
  "papers_found": len(papers),
 
385
  "years": [
386
  min((p.year for p in papers if p.year), default=None),
387
  max((p.year for p in papers if p.year), default=None),
@@ -420,7 +677,7 @@ def profile(
420
  for g in gs[:10]
421
  ]
422
  except Exception as err:
423
- log.warning("NIH RePORTER failed for %s: %s", name, err)
424
  return out
425
  finally:
426
  if own:
 
6
  import os
7
  import re
8
  import threading
9
+ import time
10
  from collections.abc import Callable, Iterable
11
  from concurrent.futures import ThreadPoolExecutor
12
  from dataclasses import dataclass, field
13
+ from datetime import date, datetime, timezone
14
  from typing import Any
15
 
16
  from . import __version__
17
  from .errors import SearchError
18
+ from .http import Http, plain_error
19
+ from .labs import build, given_name, has_given, lead_affiliation, read_papers, same_given
20
  from .models import Lab, Paper
21
  from .sources import PUBLICATION_SOURCES, europepmc, nih_reporter, pubmed
22
  from .sources.ror import Resolver
 
28
  ORDERS = ("relevance", "newest")
29
  # Long searches that may run at the same time, from the web page and from assistants together.
30
  SEARCH_SLOTS = threading.BoundedSemaphore(int(os.environ.get("LABSCOUT_PARALLEL_SEARCHES", "2")))
31
+ # Searches that read few records do not wait behind long ones: they have places of their own.
32
+ SMALL_SLOTS = threading.BoundedSemaphore(int(os.environ.get("LABSCOUT_PARALLEL_SMALL", "3")))
33
+ SMALL_SEARCH = int(os.environ.get("LABSCOUT_SMALL_SEARCH", "3000")) # records, both sources together
34
+ API_WAIT = 2.0 # seconds a search waits for the ROR API after its own reading is done
35
+ MAX_QUERY = 300 # characters of one search, on the page and for assistants alike
36
+ FAILED_KEPT = 120 # seconds a result is kept that was made while a source did not answer; then the search runs again
37
  # progress(step, text): step is a source name, "organisations" or "labs"; text says what is happening, for people
38
  Progress = Callable[[str, str], None]
39
 
 
50
  found: dict[str, int] = field(default_factory=dict) # hits per source; `counts` says how many were read
51
  failed: list[str] = field(default_factory=list) # sources that did not answer
52
  translation: str = "" # how PubMed read the search
53
+ notes: list[str] = field(default_factory=list) # plain sentences the reader should see with the results
54
  order: str = "relevance"
55
  created: str = field(default_factory=lambda: datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"))
56
  version: str = __version__
 
65
  "found": self.found,
66
  "sources_not_answering": self.failed,
67
  "pubmed_reading": self.translation,
68
+ "notes": self.notes,
69
  "created": self.created,
70
  "labs": [lab.summary(papers_per_lab) for lab in self.labs[:top]],
71
  }
72
 
73
 
74
+ def size_of(
75
+ query: str,
76
+ start: int | None,
77
+ end: int | None,
78
+ sources: Iterable[str],
79
+ http: Http | None = None,
80
+ limit: int = 0,
81
+ order: str = "relevance",
82
+ ) -> dict[str, int]:
83
+ """How many records each source has for a search, asked before the search starts: a small search gets a place
84
+ of its own instead of waiting behind long ones (see `place_for`). A search PubMed cannot read stops here. With
85
+ the `limit` and `order` of the search to come, the questions are the ones the search asks first, so their answers
86
+ wait for it in the cache."""
87
+ check_query(query)
88
+ check_years(start, end)
89
+ own = http is None
90
+ http = http or Http()
91
+ try:
92
+
93
+ def one(src: str) -> int:
94
+ try:
95
+ if src == "pubmed":
96
+ return pubmed.count(http, query, start, end, limit, order)
97
+ return europepmc.count(http, query, start, end)
98
+ except SearchError:
99
+ raise
100
+ except Exception as err: # a source that is down is found out again, and said, by the search itself
101
+ log.warning("%s did not give a count: %s", src, plain_error(err))
102
+ return 0
103
+
104
+ srcs = list(dict.fromkeys(sources)) # a source named twice is still one source
105
+ with ThreadPoolExecutor(max_workers=max(1, len(srcs))) as pool:
106
+ return dict(zip(srcs, pool.map(one, srcs), strict=True))
107
+ finally:
108
+ if own:
109
+ http.close()
110
+
111
+
112
+ def place_for(sizes: dict[str, int], limit: int) -> threading.BoundedSemaphore:
113
+ """The queue a search waits in: its own for the small ones, so that they start at once."""
114
+ reads = sum(min(n, limit) for n in sizes.values())
115
+ return SMALL_SLOTS if reads <= SMALL_SEARCH else SEARCH_SLOTS
116
+
117
+
118
+ def result_key(query: str, start: int | None, end: int | None, sources: Iterable[str], order: str, limit: int) -> str:
119
+ import hashlib
120
+ import json
121
+
122
+ return hashlib.sha256(json.dumps([query, start, end, list(sources), order, limit]).encode()).hexdigest()[:16]
123
+
124
+
125
+ class Results:
126
+ """Finished searches, kept in memory for the page, its downloads and the assistants: the same search asked again
127
+ within the life of the process is answered at once. The oldest go when there are too many results or too many
128
+ papers in them (a broad search holds twenty thousand)."""
129
+
130
+ def __init__(self, most: int = 50, most_papers: int = 150_000) -> None:
131
+ self.most, self.most_papers = most, most_papers
132
+ self._kept: dict[str, Result] = {}
133
+ self._made: dict[str, float] = {} # when a result with a source missing was made
134
+ self._lock = threading.Lock()
135
+
136
+ def get(self, key: str) -> Result | None:
137
+ with self._lock:
138
+ result = self._kept.pop(key, None)
139
+ if result is None:
140
+ return None
141
+ if result.failed and time.time() - self._made.get(key, 0.0) > FAILED_KEPT:
142
+ self._made.pop(key, None) # made while a source did not answer: the next request searches again
143
+ return None
144
+ self._kept[key] = result # used again: to the young end
145
+ return result
146
+
147
+ def put(self, key: str, result: Result) -> None:
148
+ for p in result.papers: # the abstracts have done their work and are most of the memory
149
+ p.abstract = ""
150
+ with self._lock:
151
+ self._kept.pop(key, None)
152
+ self._kept[key] = result
153
+ self._made.pop(key, None)
154
+ if result.failed:
155
+ self._made[key] = time.time()
156
+ while len(self._kept) > self.most or (
157
+ len(self._kept) > 1 and sum(len(r.papers) for r in self._kept.values()) > self.most_papers
158
+ ):
159
+ del self._kept[next(iter(self._kept))]
160
+
161
+ def clear(self) -> None:
162
+ with self._lock:
163
+ self._kept.clear()
164
+
165
+ def __len__(self) -> int:
166
+ return len(self._kept)
167
+
168
+
169
+ RESULTS = Results()
170
+
171
+
172
  def _title_key(p: Paper) -> str:
173
  return re.sub(r"[^a-z0-9]", "", fold(p.title))[:80] + str(p.year or "")
174
 
 
187
  )
188
  if k
189
  ]
190
+ hit = None
191
+ for k in keys:
192
+ other = index.get(k)
193
+ if other is None or (k.startswith("t:") and p.pmid and other.pmid and p.pmid != other.pmid):
194
+ continue # two PubMed records with one title ("Editorial") are two papers
195
+ hit = other
196
+ break
197
  if hit is None:
198
  out.append(p)
199
  hit = p
 
240
  if order not in ORDERS:
241
  raise SearchError(f"unknown order {order!r}; use relevance or newest")
242
  check_query(query)
243
+ check_years(start, end)
244
  info = {} if info is None else info
245
  found_by: dict[str, int] = info.setdefault("found", {})
246
  failed: list[str] = info.setdefault("failed", [])
247
  papers: list[Paper] = []
248
  counts: dict[str, int] = {}
249
+ srcs = list(dict.fromkeys(sources))
250
  for src in srcs:
251
  if src not in ("pubmed", "europepmc"):
252
  raise SearchError(f"unknown source {src!r}; use one of {', '.join(PUBLICATION_SOURCES)}")
 
262
  except SearchError:
263
  raise
264
  except Exception as err: # one source being down should not stop the others
265
+ log.warning("%s failed: %s", src, plain_error(err))
266
  return [], meta, True
267
 
268
  # the sources answer side by side: a big search takes as long as the slower source, not the sum of both
 
277
  found_by[src] = int(meta["total"])
278
  if meta.get("translation"):
279
  info["translation"] = meta["translation"]
280
+ if meta.get("not_found"):
281
+ info["not_found"] = meta["not_found"]
282
  if progress:
283
  if down:
284
  progress(src, f"{name} did not answer; going on without it")
 
301
  return merged, counts
302
 
303
 
304
+ _SYNTAX = re.compile(r'\[[^\]]*\]|"|\b(?:AND|OR|NOT)\b|[()*]')
305
+ _ASK = {"find", "show", "list", "give", "tell", "get"}
306
+ _WH = {"who", "which", "what", "where"}
307
+ _DETERMINERS = {"all", "the", "top", "best", "leading", "main", "major", "key", "some", "any"}
308
+ _WHO = {"lab", "labs", "laboratories", "group", "groups", "team", "teams", "researcher", "researchers", "scientist"}
309
+ _WHO |= {"scientists", "expert", "experts", "people", "investigators", "institutions", "universities", "centers"}
310
+ _WHO |= {"centres", "institutes"}
311
+ _DOING = {"work", "works", "working", "study", "studies", "studying", "research", "researches", "researching"}
312
+ _DOING |= {"publish", "publishes", "publishing", "investigate", "investigates", "investigating", "specialize"}
313
+ _DOING |= {"specializes", "specializing", "specialise", "specialises", "specialising", "focus", "focuses", "focusing"}
314
+ _FILLERS = {"using", "among", "regarding", "concerning"}
315
+
316
+
317
+ def plain_question(text: str) -> tuple[str, str]:
318
+ """A question in plain words as search words, with a sentence that says so: "Which labs study sleep regularity in
319
+ older adults?" becomes "sleep regularity in older adults". PubMed asks for every word of a search, so the
320
+ question words ("labs", "study") would leave almost nothing. Only a text that opens like a question about who
321
+ works on something is changed; a search in PubMed's own terms (quotes, AND, OR, NOT, brackets, field tags) and
322
+ plain key words stay as typed."""
323
+ typed = re.sub(r"\s+", " ", (text or "").strip())
324
+ t = typed.rstrip("?.! ")
325
+ if not t or _SYNTAX.search(t):
326
+ return typed, ""
327
+ words = t.split(" ")
328
+ low = [w.lower().strip(",;:") for w in words]
329
+ n, i = len(low), 0
330
+
331
+ def at(*options: str) -> bool:
332
+ return i < n and low[i] in options
333
+
334
+ if at("please"):
335
+ i += 1
336
+ if at("can", "could") and low[i + 1 : i + 2] == ["you"]:
337
+ i += 2
338
+ asked = False
339
+ if i < n and low[i] in _ASK:
340
+ i += 1
341
+ asked = True
342
+ if at("me"):
343
+ i += 1
344
+ elif at("search", "look", "looking") and low[i + 1 : i + 2] == ["for"]:
345
+ i += 2
346
+ asked = True
347
+ elif i < n and low[i] in _WH:
348
+ i += 1
349
+ asked = True
350
+ if at("are", "is", "do", "does"):
351
+ i += 1
352
+ while i < n and low[i] in _DETERMINERS:
353
+ i += 1
354
+ if at("research") and low[i + 1 : i + 2] and low[i + 1] in _WHO:
355
+ i += 1
356
+ who = i < n and low[i] in _WHO
357
+ i += who
358
+ if at("that", "who", "which"):
359
+ i += 1
360
+ if at("are", "is"):
361
+ i += 1
362
+ if at("currently"):
363
+ i += 1
364
+ doing = (asked or who) and i < n and low[i] in _DOING
365
+ i += doing
366
+ about = (who or doing) and at("on", "in", "about", "for")
367
+ i += about
368
+ if not ((asked or who) and (doing or about)) or i >= n:
369
+ return typed, ""
370
+ rest = [w for w, lw in zip(words[i:], low[i:], strict=True) if lw not in _FILLERS]
371
+ clean = " ".join(rest).strip(" ,;:")
372
+ if not clean or clean == typed:
373
+ return typed, ""
374
+ return clean, f"Read as: {clean}. The question words were left out, because PubMed looks for every word."
375
+
376
+
377
  def check_query(query: str) -> None:
378
  """Stop a search with an unclosed quote or bracket: the sources would read it another way without saying so (an
379
+ open bracket can drop the years, for example). An empty search would be every paper of the years, and a very
380
+ long text is no search."""
381
+ if not query.strip():
382
+ raise SearchError("Give a topic to search for: a few key words in English.")
383
+ if len(query) > MAX_QUERY:
384
+ raise SearchError(
385
+ f"The search is {len(query):,} characters long. Please give a few key words, "
386
+ f"{MAX_QUERY} characters at most."
387
+ )
388
+ if re.search(r"[^\W\d_]", query) and not re.search(r"[A-Za-z\u00c0-\u024f]", query):
389
+ raise SearchError(
390
+ "The sources read English words in Latin letters only. Please type the topic in English, "
391
+ "for example: actigraphy sleep."
392
+ )
393
  if query.count('"') % 2:
394
  raise SearchError('The search has a quote mark without its pair. Please check the quotes (").')
395
  depth = 0
 
401
  raise SearchError("The search has a bracket without its pair. Please check the brackets ( ).")
402
 
403
 
404
+ def check_years(start: int | None, end: int | None) -> None:
405
+ """Stop a search for years the sources do not hold. They accept any number, and a year far away costs them and
406
+ this tool work for nothing."""
407
+ last = date.today().year + 1
408
+ for year in (start, end):
409
+ if year is not None and not 1800 <= year <= last:
410
+ raise SearchError(f"Years run from 1800 to {last}; {year} is outside.")
411
+
412
+
413
  def read_as(source: str, order: str) -> str:
414
  """Which papers a source gives first: "most relevant" (PubMed's Best Match), "most cited" (Europe PMC, whose own
415
  relevance order is mostly by date) or "newest"."""
 
449
  own = http is None
450
  http = http or Http()
451
  try:
452
+ srcs = list(dict.fromkeys(sources))
453
  info: dict[str, Any] = {}
454
  papers, counts = collect(http, query, start, end, limit, srcs, order, info, progress)
455
  resolve = Resolver(http)
456
  if hasattr(resolve, "prefetch"):
457
  resolve.prefetch([a for a in (lead_affiliation(p)[1] for p in papers) if a])
458
+ if progress:
459
+ progress("organisations", "Reading the papers and matching their organisations")
460
+ feats = read_papers(papers, query) # the ROR API answers the few open affiliations meanwhile
461
+ if hasattr(resolve, "settle"):
462
+ resolve.settle(API_WAIT)
463
  if progress:
464
  total = sum(1 for p in papers if lead_affiliation(p)[1])
465
  done = 0
 
472
  return resolve(aff)
473
 
474
  progress("organisations", f"Matching organisations: 0 of {total} papers")
475
+ labs = build(papers, counted if progress else resolve, query=query, feats=feats)
476
  if progress and hasattr(resolve, "memo"):
477
  kinds: dict[str, int] = {}
478
  for org in resolve.memo.values():
 
515
  http, lab.last_name, first, lab.organization.name, since=start
516
  )
517
  except Exception as err:
518
+ log.warning("NIH RePORTER failed for a lab: %s", plain_error(err))
519
+ notes = []
520
+ lost = [str(w) for w in info.get("not_found", [])]
521
+ if lost:
522
+ words = ", ".join(f"\u201c{w}\u201d" for w in lost)
523
+ notes.append(f"PubMed does not know {words} and searched without {'it' if len(lost) == 1 else 'them'}.")
524
  return Result(
525
  query=query,
526
  start=start,
 
532
  found=info.get("found", {}),
533
  failed=info.get("failed", []),
534
  translation=info.get("translation", ""),
535
+ notes=notes,
536
  order=order,
537
  )
538
  finally:
 
563
  from .text import signals_of, species_of
564
 
565
  last, first = split_name(name)
566
+ no_orcids, no_names = hidden_people()
567
+ gone = {"name": name, "error": "This researcher asked not to be shown in LabScout."}
568
+ if name_key(last, first) in no_names:
569
+ return gone
570
+
571
+ def is_hidden(a: Any) -> bool:
572
+ return a.key in no_names or bool(a.orcid and a.orcid in no_orcids)
573
+
574
  own = http is None
575
  http = http or Http()
576
  try:
577
+ # without quotes PubMed also finds the name printed with more initials ("Zee P" finds "Zee PC")
578
+ query = f"{last} {first[:1]}[au]" if first else f"{last}[au]"
579
  if topic:
580
  query += f" AND ({topic})"
581
  papers = pubmed.search(http, query, limit=limit)
582
  key = name_key(last, first)
583
+ # a hidden person is not shown under another spelling of the request either (the last name alone, for one)
584
+ family = name_key(last, "")
585
+ shown = [p for p in papers if not any(is_hidden(a) and name_key(a.last_name, "") == family for a in p.authors)]
586
+ if papers and not shown:
587
+ return gone
588
+ papers = shown
589
+ asked = given_name(first)
590
+ if has_given(asked):
591
+ # PubMed's author search goes by last name and initial; a paper stays only when the author it found can be
592
+ # the person asked for ("Susan Redline" is not "Sara Redline")
593
+ def fits(p: Paper) -> bool:
594
+ printed = [given_name(a.fore_name) for a in p.authors if a.key == key]
595
+ return any(not has_given(g) or same_given(g, asked) for g in printed)
596
+
597
+ papers = [p for p in papers if fits(p)]
598
  resolve = Resolver(http)
599
+ if hasattr(resolve, "prefetch"): # all places at once; the ROR API gets a moment for what is left open
600
+ mine = [a.affiliations[0] for p in papers for a in p.authors if a.key == key and a.affiliations]
601
+ resolve.prefetch(mine)
602
+ resolve.settle(1.5)
603
  places: Counter[str] = Counter()
604
  orgs: dict[str, Any] = {}
605
  coauthors: Counter[str] = Counter()
606
+ placed: dict[int, str] = {} # the organisation found for the person on each paper
607
  for p in papers:
608
  me = next((a for a in p.authors if a.key == key), None)
609
  if me and me.affiliations:
 
612
  k = org.ror or org.name
613
  places[k] += 1
614
  orgs[k] = org
615
+ placed[id(p)] = fold(org.name)
616
  for a in p.authors:
617
+ if a.key != key and not is_hidden(a):
618
  coauthors[a.display] += 1
619
+ at_organization: bool | None = None
620
  if organization:
621
  want = fold(organization)
622
+ kept = [
623
+ p
624
+ for p in papers
625
+ if placed.get(id(p)) == want
626
+ or any(want in fold(" ".join(a.affiliations)) for a in p.authors if a.key == key)
627
+ ]
628
+ at_organization = bool(kept) # when no paper names it, every paper under the name stays
629
+ papers = kept or papers
630
  text = " ".join(" ".join([p.title, p.abstract, " ".join(p.mesh)]) for p in papers)
631
  topics = Counter(
632
  m
 
638
  "name": name,
639
  "pubmed_query": query,
640
  "papers_found": len(papers),
641
+ "organization_found": at_organization,
642
  "years": [
643
  min((p.year for p in papers if p.year), default=None),
644
  max((p.year for p in papers if p.year), default=None),
 
677
  for g in gs[:10]
678
  ]
679
  except Exception as err:
680
+ log.warning("NIH RePORTER failed for a profile: %s", plain_error(err))
681
  return out
682
  finally:
683
  if own:
src/labscout/server.py CHANGED
@@ -6,31 +6,62 @@ Run locally over stdio (`labscout mcp`), as a web service (`labscout mcp --http`
6
 
7
  from __future__ import annotations
8
 
 
 
 
 
 
 
9
  from typing import Any
 
10
 
11
  import anyio
12
  import httpx
13
- from mcp.server.mcpserver import MCPServer
 
14
  from mcp.types import ToolAnnotations
15
 
16
  from . import __version__
17
  from .config import REPO
18
  from .errors import SearchError
19
  from .http import Http
20
- from .pipeline import ORDERS, SEARCH_SLOTS, collect, profile, split_name
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  from .pipeline import find_labs as _find_labs
22
  from .sources import PUBLICATION_SOURCES, clinicaltrials, nih_reporter, patents, ukri
23
- from .text import signals_of, species_of
24
 
25
  INSTRUCTIONS = (
26
- "LabScout finds the labs, people and studies behind a research topic from public sources: PubMed, Europe PMC, the "
27
- "Research Organization Registry, NIH RePORTER, UKRI Gateway to Research, ClinicalTrials.gov and the patent records "
28
- "in Europe PMC. Start with find_labs for a topic, then use lab_profile for a person. Results show names and "
29
- "affiliations as published; e-mail addresses are never returned. Organisations are matched automatically: the "
30
- "field organization_match says how each one was found. Use the results to discover research and "
31
- "collaborators, not to judge people."
 
 
 
32
  )
33
  READ = ToolAnnotations(read_only_hint=True, destructive_hint=False, idempotent_hint=True, open_world_hint=True)
 
 
 
 
 
 
 
34
 
35
  mcp = MCPServer(
36
  name="labscout", title="Actogram LabScout", instructions=INSTRUCTIONS, website_url=REPO, version=__version__
@@ -38,7 +69,7 @@ mcp = MCPServer(
38
 
39
 
40
  def _sources(sources: list[str] | None) -> list[str]:
41
- chosen = [s for s in (sources or PUBLICATION_SOURCES) if s in PUBLICATION_SOURCES]
42
  return chosen or list(PUBLICATION_SOURCES)
43
 
44
 
@@ -50,72 +81,256 @@ def _order(order: str) -> str:
50
  return order if order in ORDERS else "relevance"
51
 
52
 
53
- def _down(err: Exception) -> dict[str, Any]:
54
- """A source that does not answer becomes a plain message for the assistant instead of a failed call."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  if isinstance(err, httpx.HTTPStatusError):
56
  host = err.request.url.host
57
- return {
58
- "error": f"{host} is not answering right now (HTTP {err.response.status_code}). Please try again later."
59
- }
60
- return {"error": f"A source is not reachable right now ({type(err).__name__}). Please try again later."}
61
 
62
 
63
- async def _safely(fn: Any, heavy: bool = False) -> dict[str, Any]:
64
- """Run a tool in a worker thread; a heavy one waits for a free search slot, shared with the web page."""
 
65
 
66
  def run() -> dict[str, Any]:
67
- if not heavy:
68
- return fn()
69
- with SEARCH_SLOTS:
70
- return fn()
 
 
 
 
 
71
 
72
  try:
73
  return await anyio.to_thread.run_sync(run)
74
  except httpx.HTTPError as err:
75
- return _down(err)
76
  except SearchError as err: # a search the source cannot read: the message says what to change
77
- return {"error": str(err)}
78
-
79
-
80
- @mcp.tool(annotations=READ)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  async def find_labs(
82
  topic: str,
83
  from_year: int | None = None,
84
  to_year: int | None = None,
85
- max_papers: int = 1000,
86
- top: int = 20,
87
  sources: list[str] | None = None,
88
  with_grants: bool = False,
89
  order: str = "relevance",
 
 
 
90
  ) -> dict[str, Any]:
91
- """Find the labs working on a topic: who leads them, where they are, and why each one came up.
92
-
93
- topic: search words, PubMed style ("actigraphy AND sleep regularity" works).
94
- from_year, to_year: limit the publication years; the last five years find the labs active now.
95
- max_papers: papers read per source (default 1000, up to 10000; more papers find smaller labs further down the
96
- list). order: "relevance" reads the most relevant papers (default), "newest" the newest.
97
- top: labs returned (up to 100). sources: "pubmed", "europepmc" or both (default both).
 
 
 
 
 
 
 
98
  with_grants: also look up NIH grants for the five top labs (slower).
99
- The answer says how many papers each source has for the search ("found") and how many were read ("counts").
100
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  def run() -> dict[str, Any]:
103
- res = _find_labs(
104
- topic,
105
- from_year,
106
- to_year,
107
- _clip(max_papers, 10, 10000),
108
- _sources(sources),
109
- top=_clip(top, 1, 100),
110
- grants=5 if with_grants else 0,
111
- order=_order(order),
112
- )
113
- return res.summary(top=_clip(top, 1, 100))
114
-
115
- return await _safely(run, heavy=True)
116
-
117
-
118
- @mcp.tool(annotations=READ)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  async def search_papers(
120
  topic: str,
121
  from_year: int | None = None,
@@ -124,74 +339,94 @@ async def search_papers(
124
  sources: list[str] | None = None,
125
  order: str = "relevance",
126
  ) -> dict[str, Any]:
127
- """Papers on a topic from PubMed and Europe PMC, merged across sources, with species and data hints. order:
128
- "relevance" picks the most relevant papers (default), "newest" the newest; either way they are listed newest
129
- first."""
 
 
 
130
 
131
  def run() -> dict[str, Any]:
132
  info: dict[str, Any] = {}
133
  with Http() as http:
134
  papers, counts = collect(
135
- http, topic, from_year, to_year, _clip(max_papers, 1, 200), _sources(sources), _order(order), info
136
  )
137
  papers.sort(key=lambda p: -(p.year or 0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  return {
139
- "topic": topic,
140
  "order": _order(order),
141
  "found": info["found"],
142
  "counts": counts,
143
- "papers": [
144
- p.brief()
145
- | {
146
- "first_author": p.authors[0].display if p.authors else "",
147
- "senior_author": p.authors[-1].display if p.authors else "",
148
- "species": species_of(p.mesh, p.title + " " + p.abstract),
149
- "data_signals": signals_of(" ".join([p.title, p.abstract, " ".join(p.keywords)])),
150
- "sources": p.sources,
151
- }
152
- for p in papers[: _clip(max_papers, 1, 200)]
153
- ],
154
  }
155
 
156
- return await _safely(run, heavy=True)
157
 
158
 
159
- @mcp.tool(annotations=READ)
160
  async def lab_profile(name: str, topic: str = "", organization: str = "", max_papers: int = 100) -> dict[str, Any]:
161
- """One researcher: organisations, years, frequent co-authors and topics, species, data hints, recent papers and NIH
162
- grants. name: "Susan Redline" or "Redline, Susan". topic and organization narrow the search when a name is
163
- common."""
164
- return await _safely(lambda: profile(name, topic, organization, _clip(max_papers, 5, 300)), heavy=True)
 
 
165
 
 
 
 
 
 
 
 
166
 
167
- @mcp.tool(annotations=READ)
 
168
  async def find_trials(topic: str, max_studies: int = 25) -> dict[str, Any]:
169
- """Registered studies on ClinicalTrials.gov for a topic, with their responsible investigators and their sites."""
 
 
 
170
 
171
  def run() -> dict[str, Any]:
172
  with Http() as http:
173
  trials = clinicaltrials.search(http, topic, _clip(max_studies, 1, 200))
174
- return {
175
- "topic": topic,
176
- "studies": [
177
- {
178
- "nct_id": t.nct_id,
179
- "title": t.title,
180
- "status": t.status,
181
- "start": t.start,
182
- "sponsor": t.sponsor,
183
- "investigators": t.officials,
184
- "sites": t.sites[:20],
185
- "url": t.url,
186
- }
187
- for t in trials
188
- ],
189
- }
190
 
191
  return await _safely(run)
192
 
193
 
194
- @mcp.tool(annotations=READ)
195
  async def find_grants(
196
  investigator: str = "",
197
  text: str = "",
@@ -199,14 +434,17 @@ async def find_grants(
199
  max_grants: int = 25,
200
  funders: list[str] | None = None,
201
  ) -> dict[str, Any]:
202
- """Funded projects by investigator name ("Susan Redline") or by words in their title and terms.
 
203
 
204
  funders: "nih" (NIH RePORTER, USA) and "ukri" (UKRI Gateway to Research, UK); both by default. A search by
205
- investigator name uses NIH RePORTER only.
206
  """
 
207
  if not investigator and not text:
208
- return {"error": "Give an investigator name, words to search for, or both."}
209
- chosen = [f for f in (funders or ["nih", "ukri"]) if f in ("nih", "ukri")] or ["nih", "ukri"]
 
210
 
211
  def run() -> dict[str, Any]:
212
  last, first = split_name(investigator) if investigator else ("", "")
@@ -223,22 +461,29 @@ async def find_grants(
223
  )
224
  if "ukri" in chosen and text and not investigator:
225
  found += ukri.search(http, text, limit=_clip(max_grants, 1, 100))
226
- return {"investigator": investigator, "text": text, "funders": chosen, "grants": [g.brief() for g in found]}
 
 
227
 
228
  return await _safely(run)
229
 
230
 
231
- @mcp.tool(annotations=READ)
232
  async def find_patents(
233
  topic: str, from_year: int | None = None, to_year: int | None = None, max_patents: int = 25
234
  ) -> dict[str, Any]:
235
- """Patents on a topic, as background to what is already known: inventors, country, CPC classes and an Espacenet
236
- link. Source: the patent records in Europe PMC, which end in 2014; newer patents need a patent office service."""
 
 
 
237
 
238
  def run() -> dict[str, Any]:
239
  with Http() as http:
240
  found = patents.search(http, topic, from_year, to_year, _clip(max_patents, 1, 100))
241
- return {"topic": topic, "covers_up_to": patents.LAST_YEAR, "patents": [p.brief() for p in found]}
 
 
242
 
243
  return await _safely(run)
244
 
 
6
 
7
  from __future__ import annotations
8
 
9
+ import contextlib
10
+ import json
11
+ import os
12
+ import threading
13
+ import time
14
+ from collections.abc import Callable
15
  from typing import Any
16
+ from urllib.parse import urlencode
17
 
18
  import anyio
19
  import httpx
20
+ from mcp.server.mcpserver import Context, MCPServer
21
+ from mcp.server.mcpserver.exceptions import ToolError
22
  from mcp.types import ToolAnnotations
23
 
24
  from . import __version__
25
  from .config import REPO
26
  from .errors import SearchError
27
  from .http import Http
28
+ from .pipeline import (
29
+ MAX_QUERY,
30
+ ORDERS,
31
+ RESULTS,
32
+ Result,
33
+ check_years,
34
+ collect,
35
+ place_for,
36
+ plain_question,
37
+ profile,
38
+ result_key,
39
+ size_of,
40
+ split_name,
41
+ )
42
  from .pipeline import find_labs as _find_labs
43
  from .sources import PUBLICATION_SOURCES, clinicaltrials, nih_reporter, patents, ukri
44
+ from .text import _countries, _place_key, signals_of, species_of
45
 
46
  INSTRUCTIONS = (
47
+ "LabScout finds who works on a research topic and where: the labs (a senior author at an organisation), their "
48
+ "papers, grants, registered trials and patents, from PubMed, Europe PMC, the Research Organization Registry, NIH "
49
+ "RePORTER, UKRI Gateway to Research and ClinicalTrials.gov. Start with find_labs for a topic, then lab_profile "
50
+ "for one person. Give topics as a few key words in English (PubMed syntax works: quotes, AND, OR, NOT). Every "
51
+ "lab comes with the papers it rests on, so check them before you state something as fact. Results show names and "
52
+ "affiliations as published; e-mail addresses are never returned. Organisations are matched automatically: "
53
+ "organization_match says how each was found, and a value other than a ror one means the place is not confirmed. "
54
+ "The order of labs shows how much of their work is on the topic, not quality. Use the results to discover "
55
+ "research and collaborators, not to judge people."
56
  )
57
  READ = ToolAnnotations(read_only_hint=True, destructive_hint=False, idempotent_hint=True, open_world_hint=True)
58
+ FULL_READ = 10000 # papers per source of a full search, the same as the web page reads
59
+ QUICK_READ = 3000 # papers per source when a topic is too broad for an assistant to wait for a full search
60
+ AUTO_FULL = 12000 # records up to which find_labs reads everything by itself
61
+ MAX_CHARS = 60000 # the largest answer of find_labs, in characters: assistants cut longer tool results
62
+ # tool calls that may run or wait at one time; the next one is told to come back, so that the web page stays usable
63
+ CALLS = threading.BoundedSemaphore(int(os.environ.get("LABSCOUT_MCP_CALLS", "16")))
64
+ BUSY = "LabScout is busy: many searches are running. Please try again in a minute."
65
 
66
  mcp = MCPServer(
67
  name="labscout", title="Actogram LabScout", instructions=INSTRUCTIONS, website_url=REPO, version=__version__
 
69
 
70
 
71
  def _sources(sources: list[str] | None) -> list[str]:
72
+ chosen = [s for s in dict.fromkeys(sources or PUBLICATION_SOURCES) if s in PUBLICATION_SOURCES]
73
  return chosen or list(PUBLICATION_SOURCES)
74
 
75
 
 
81
  return order if order in ORDERS else "relevance"
82
 
83
 
84
+ def _said(text: str, most: int, what: str, needed: bool = False) -> str:
85
+ """A text the caller gave, trimmed. One that is far too long is refused with a sentence, and so is a missing
86
+ one that the tool cannot do without."""
87
+ text = (text or "").strip()
88
+ if len(text) > most:
89
+ raise ToolError(f"The {what} is {len(text):,} characters long; give {most} at most.")
90
+ if needed and not text:
91
+ raise ToolError(f"Give a {what}.")
92
+ return text
93
+
94
+
95
+ def _years(first: int | None, last: int | None) -> tuple[int | None, int | None]:
96
+ """Years the sources hold, the earlier one first."""
97
+ try:
98
+ check_years(first, last)
99
+ except SearchError as err:
100
+ raise ToolError(str(err)) from err
101
+ return (last, first) if first and last and first > last else (first, last)
102
+
103
+
104
+ def _fitting(items: list[dict[str, Any]], notes: list[str], what: str) -> list[dict[str, Any]]:
105
+ """As many of the items as an assistant can take in one answer, at least one. The answer goes out as indented
106
+ text, so that is what is measured; what was left out is said in `notes`."""
107
+ out: list[dict[str, Any]] = []
108
+ size = 0
109
+ for item in items:
110
+ size += len(json.dumps(item, ensure_ascii=False, indent=2)) + 4
111
+ if out and size > MAX_CHARS:
112
+ notes.append(f"{len(out)} of {len(items):,} {what} are shown, as many as fit one answer; ask for fewer.")
113
+ break
114
+ out.append(item)
115
+ return out
116
+
117
+
118
+ def _country_code(country: str) -> str:
119
+ """The two letter code of a country given by name or code ("USA", "UK", "Netherlands", "de"); "" if unknown."""
120
+ text = country.strip()
121
+ code = _countries().get(_place_key(text), "") # also "UK", which is no ISO code
122
+ return code or (text.upper() if len(text) == 2 and text.isascii() and text.isalpha() else "")
123
+
124
+
125
+ def _down(err: Exception) -> str:
126
+ """A source that does not answer, as a plain sentence for the assistant."""
127
  if isinstance(err, httpx.HTTPStatusError):
128
  host = err.request.url.host
129
+ return f"{host} is not answering right now (HTTP {err.response.status_code}). Please try again later."
130
+ return f"A source is not reachable right now ({type(err).__name__}). Please try again later."
 
 
131
 
132
 
133
+ async def _safely(fn: Callable[[], dict[str, Any]], place: threading.BoundedSemaphore | None = None) -> dict[str, Any]:
134
+ """Run a tool in a worker thread, in its place in the queue when it has one. What goes wrong becomes a tool
135
+ error with a sentence that says what to change or when to try again."""
136
 
137
  def run() -> dict[str, Any]:
138
+ if not CALLS.acquire(blocking=False):
139
+ raise ToolError(BUSY)
140
+ try:
141
+ if place is None:
142
+ return fn()
143
+ with place:
144
+ return fn()
145
+ finally:
146
+ CALLS.release()
147
 
148
  try:
149
  return await anyio.to_thread.run_sync(run)
150
  except httpx.HTTPError as err:
151
+ raise ToolError(_down(err)) from err
152
  except SearchError as err: # a search the source cannot read: the message says what to change
153
+ raise ToolError(str(err)) from err
154
+
155
+
156
+ def public_url() -> str:
157
+ """The address of the web page next to this server, when there is one (LABSCOUT_PUBLIC_URL, or the Space)."""
158
+ url = os.environ.get("LABSCOUT_PUBLIC_URL", "").strip().rstrip("/")
159
+ if not url and os.environ.get("SPACE_HOST"):
160
+ url = f"https://{os.environ['SPACE_HOST']}"
161
+ return url
162
+
163
+
164
+ def _report_url(query: str, start: int | None, end: int | None, sources: list[str], order: str) -> str:
165
+ base = public_url()
166
+ if not base:
167
+ return ""
168
+ q: list[tuple[str, str]] = [("topic", query), ("exact", "1"), ("order", order)]
169
+ q += [("from", str(start))] if start else []
170
+ q += [("to", str(end))] if end else []
171
+ q += [("source", s) for s in sources]
172
+ return f"{base}/search?{urlencode(q)}"
173
+
174
+
175
+ def _lab(lab: dict[str, Any], full: bool) -> dict[str, Any]:
176
+ """One lab for an assistant: every field, or the ones that answer "who, where, how much, why"."""
177
+ if full:
178
+ return {k: v for k, v in lab.items() if k != "score"}
179
+ out = {
180
+ "lead": lab["lead"],
181
+ "organization": lab["organization"],
182
+ "city": lab["city"],
183
+ "country": lab["country"],
184
+ "papers_as_senior_author": lab["papers_as_senior_author"],
185
+ "papers_as_coauthor": lab["papers_as_coauthor"],
186
+ "years": lab["years"],
187
+ "why": lab["why"],
188
+ "papers": [{"title": p["title"], "year": p["year"], "url": p["url"]} for p in lab["top_papers"][:2]],
189
+ }
190
+ if lab.get("orcid"):
191
+ out["orcid"] = lab["orcid"]
192
+ if lab.get("also_at"):
193
+ out["also_at"] = lab["also_at"]
194
+ if not str(lab.get("organization_match") or "").startswith("ror"):
195
+ out["place_confirmed"] = False
196
+ if lab.get("grants"):
197
+ out["grants"] = lab["grants"]
198
+ return out
199
+
200
+
201
+ def _labs_answer(
202
+ res: Result, top: int, country: str, full: bool, asked: str, note: str, depth: str, url: str
203
+ ) -> dict[str, Any]:
204
+ labs = res.labs
205
+ unknown = ""
206
+ if country:
207
+ code, name = _country_code(country), country.strip().lower()
208
+ labs = [
209
+ lab
210
+ for lab in labs
211
+ if (code and lab.organization.country == code) or name == (lab.organization.country_name or "").lower()
212
+ ]
213
+ if not code and not labs:
214
+ unknown = (
215
+ f"LabScout does not know the country {country.strip()!r}; give its English name or two-letter code."
216
+ )
217
+ shown: list[dict[str, Any]] = []
218
+ size = 0
219
+ for lab in labs[:top]:
220
+ item = _lab(lab.summary(3 if full else 2), full)
221
+ size += len(json.dumps(item, ensure_ascii=False, indent=2)) + 4 # as it is sent: indented text
222
+ if shown and size > MAX_CHARS:
223
+ break
224
+ shown.append(item)
225
+ out: dict[str, Any] = {
226
+ "query": res.query,
227
+ "years": [res.start, res.end],
228
+ "order": res.order,
229
+ "papers_found": res.found,
230
+ "papers_read": res.counts,
231
+ "depth": depth,
232
+ "labs_total": len(labs),
233
+ "labs_shown": len(shown),
234
+ "labs": shown,
235
+ "notes": [note] * bool(note) + list(res.notes) + [unknown] * bool(unknown),
236
+ "sources_not_answering": res.failed,
237
+ }
238
+ if asked and asked != res.query:
239
+ out["asked"] = asked
240
+ if len(shown) < len(labs):
241
+ how = "ask for more with top (up to 100)" if len(shown) == top else "ask for fewer labs or detail='concise'"
242
+ out["notes"].append(f"{len(shown)} of {len(labs):,} labs are shown; {how}, or narrow them with country.")
243
+ if url:
244
+ out["report_url"] = url
245
+ same = "the same search" if depth == "full" else "the full search (up to 10,000 papers per source)"
246
+ out["notes"].append(f"report_url opens {same} as a web page with a map, a table and Excel.")
247
+ return out
248
+
249
+
250
+ @mcp.tool(title="Find labs working on a topic", annotations=READ)
251
  async def find_labs(
252
  topic: str,
253
  from_year: int | None = None,
254
  to_year: int | None = None,
255
+ max_papers: int = 0,
256
+ top: int = 15,
257
  sources: list[str] | None = None,
258
  with_grants: bool = False,
259
  order: str = "relevance",
260
+ country: str = "",
261
+ detail: str = "concise",
262
+ ctx: Context | None = None,
263
  ) -> dict[str, Any]:
264
+ """Use this when the user asks who works on a research topic, which labs or groups lead a field, where they
265
+ are, or wants collaborators, hosts for a PhD or postdoc, partners for a grant by country, or experts on a topic.
266
+ Returns labs (a senior author at an organisation) ranked by how much of their work is on the topic, each with
267
+ the reason it came up and papers to check. Do not use it to look up one named person (use lab_profile) or to
268
+ list papers (use search_papers).
269
+
270
+ topic: a few key words in English; PubMed syntax works ("sleep regularity" AND actigraphy). A question in plain
271
+ words is reduced to its key words.
272
+ from_year, to_year: publication years; the last five years find the labs that are active now.
273
+ max_papers: papers read per source. 0 (default) reads every paper, up to 10000 per source, unless the topic is
274
+ very broad; then the 3000 best per source are read and the answer says so. Give 10000 to force a full read.
275
+ top: labs returned (default 15, up to 100). country: only labs in this country (name or two-letter code).
276
+ detail: "concise" (default) or "full" (all fields: ORCID, ROR, coordinates, species, data kinds, funders).
277
+ sources: "pubmed", "europepmc" or both (default both). order: "relevance" (default) or "newest".
278
  with_grants: also look up NIH grants for the five top labs (slower).
279
+ A full search of a large topic can take up to a minute; progress is reported while it runs.
280
  """
281
+ asked = topic = _said(topic, MAX_QUERY, "topic", needed=True)
282
+ query, note = plain_question(topic)
283
+ srcs, how = _sources(sources), _order(order)
284
+ top = _clip(top, 1, 100)
285
+ from_year, to_year = _years(from_year, to_year)
286
+ last: list[Any] = [0.0, 0, ""] # when the last message went, how many went, and for which step
287
+ loop = anyio.lowlevel.current_token() # the sources are read in threads of their own, which report through it
288
+ turn = threading.Lock() # one message at a time, so that their numbers rise
289
+
290
+ def progress(step: str, text: str) -> None:
291
+ with turn:
292
+ now = time.monotonic()
293
+ if ctx is None or ((step == "note" or step == last[2]) and now - last[0] < 1.0):
294
+ return # a new step is said at once; lines within a step at most once a second
295
+ last[0], last[1], last[2] = now, last[1] + 1, step
296
+ with contextlib.suppress(Exception): # progress is a courtesy: a client that has gone must not stop it
297
+ anyio.from_thread.run(ctx.report_progress, last[1], None, text, token=loop)
298
 
299
  def run() -> dict[str, Any]:
300
+ limit, depth = _clip(max_papers, 10, FULL_READ) if max_papers else FULL_READ, "full"
301
+ progress("count", "Counting the papers on the topic") # a first sign of life within a second
302
+ sizes = size_of(query, from_year, to_year, srcs, limit=FULL_READ, order=how)
303
+ if not max_papers and sum(min(n, FULL_READ) for n in sizes.values()) > AUTO_FULL:
304
+ limit = QUICK_READ
305
+ depth = (
306
+ f"partial: the topic is broad, so the {QUICK_READ:,} best papers per source were read. Narrow the "
307
+ f"topic or the years, or pass max_papers={FULL_READ} for the full read (up to a minute)."
308
+ )
309
+ elif limit < FULL_READ and any(n > limit for n in sizes.values()):
310
+ depth = f"partial: the {limit:,} best papers per source were read, as asked with max_papers."
311
+ key = result_key(query, from_year, to_year, srcs, how, limit)
312
+ res = None if with_grants else RESULTS.get(key)
313
+ if res is None:
314
+ with place_for(sizes, limit):
315
+ res = _find_labs(
316
+ query,
317
+ from_year,
318
+ to_year,
319
+ limit,
320
+ srcs,
321
+ grants=5 if with_grants else 0,
322
+ order=how,
323
+ progress=progress,
324
+ )
325
+ if not with_grants:
326
+ RESULTS.put(key, res)
327
+ url = _report_url(query, from_year, to_year, srcs, how)
328
+ return _labs_answer(res, top, country, detail == "full", asked, note, depth, url)
329
+
330
+ return await _safely(run)
331
+
332
+
333
+ @mcp.tool(title="Search papers on a topic", annotations=READ)
334
  async def search_papers(
335
  topic: str,
336
  from_year: int | None = None,
 
339
  sources: list[str] | None = None,
340
  order: str = "relevance",
341
  ) -> dict[str, Any]:
342
+ """Use this when the user wants papers on a topic from PubMed and Europe PMC (merged, each paper once), with
343
+ the species and the kinds of data each one mentions. Do not use it to find people or labs (use find_labs).
344
+ order: "relevance" picks the most relevant papers (default), "newest" the newest; either way they are listed
345
+ newest first. max_papers: up to 200."""
346
+ query, note = plain_question(_said(topic, MAX_QUERY, "topic", needed=True))
347
+ from_year, to_year = _years(from_year, to_year)
348
 
349
  def run() -> dict[str, Any]:
350
  info: dict[str, Any] = {}
351
  with Http() as http:
352
  papers, counts = collect(
353
+ http, query, from_year, to_year, _clip(max_papers, 1, 200), _sources(sources), _order(order), info
354
  )
355
  papers.sort(key=lambda p: -(p.year or 0))
356
+ lost = [str(w) for w in info.get("not_found", [])]
357
+ notes = [note] * bool(note) + [f"PubMed does not know: {', '.join(lost)}."] * bool(lost)
358
+ rows = [
359
+ p.brief()
360
+ | {
361
+ "first_author": p.authors[0].display if p.authors else "",
362
+ "senior_author": p.authors[-1].display if p.authors else "",
363
+ "species": species_of(p.mesh, p.title + " " + p.abstract),
364
+ "data_signals": signals_of(" ".join([p.title, p.abstract, " ".join(p.keywords)])),
365
+ "sources": p.sources,
366
+ }
367
+ for p in papers[: _clip(max_papers, 1, 200)]
368
+ ]
369
+ rows = _fitting(rows, notes, "papers")
370
  return {
371
+ "topic": query,
372
  "order": _order(order),
373
  "found": info["found"],
374
  "counts": counts,
375
+ "notes": notes,
376
+ "papers": rows,
 
 
 
 
 
 
 
 
 
377
  }
378
 
379
+ return await _safely(run)
380
 
381
 
382
+ @mcp.tool(title="Profile of one researcher", annotations=READ)
383
  async def lab_profile(name: str, topic: str = "", organization: str = "", max_papers: int = 100) -> dict[str, Any]:
384
+ """Use this when the user names one researcher and wants to know where they work, since when, with whom, on what,
385
+ their recent papers and NIH grants. name: "Susan Redline" or "Redline, Susan". A name is not a person: papers of
386
+ people with the same last name and first initial come together, so give topic and organization (taken from
387
+ find_labs) to keep to one person, and check the organisations in the answer."""
388
+ name = _said(name, 120, "name", needed=True)
389
+ topic, organization = _said(topic, MAX_QUERY, "topic"), _said(organization, 200, "organization")
390
 
391
+ def run() -> dict[str, Any]:
392
+ out = profile(name, topic, organization, _clip(max_papers, 5, 300))
393
+ if "error" in out:
394
+ raise ToolError(out["error"])
395
+ return out
396
+
397
+ return await _safely(run)
398
 
399
+
400
+ @mcp.tool(title="Find registered clinical studies", annotations=READ)
401
  async def find_trials(topic: str, max_studies: int = 25) -> dict[str, Any]:
402
+ """Use this when the user asks which clinical studies are registered on a topic, who runs them and at which
403
+ sites. Source: ClinicalTrials.gov. Returns the status, the responsible investigators and up to 20 sites of each
404
+ study."""
405
+ topic = _said(topic, MAX_QUERY, "topic", needed=True)
406
 
407
  def run() -> dict[str, Any]:
408
  with Http() as http:
409
  trials = clinicaltrials.search(http, topic, _clip(max_studies, 1, 200))
410
+ notes: list[str] = []
411
+ studies = [
412
+ {
413
+ "nct_id": t.nct_id,
414
+ "title": t.title,
415
+ "status": t.status,
416
+ "start": t.start,
417
+ "sponsor": t.sponsor,
418
+ "investigators": t.officials,
419
+ "sites": t.sites[:20],
420
+ "url": t.url,
421
+ }
422
+ for t in trials
423
+ ]
424
+ return {"topic": topic, "studies": _fitting(studies, notes, "studies"), "notes": notes}
 
425
 
426
  return await _safely(run)
427
 
428
 
429
+ @mcp.tool(title="Find funded research projects", annotations=READ)
430
  async def find_grants(
431
  investigator: str = "",
432
  text: str = "",
 
434
  max_grants: int = 25,
435
  funders: list[str] | None = None,
436
  ) -> dict[str, Any]:
437
+ """Use this when the user asks who is funded to work on a topic, or which grants a researcher holds. Give an
438
+ investigator name ("Susan Redline"), words to find in project titles and terms, or both.
439
 
440
  funders: "nih" (NIH RePORTER, USA) and "ukri" (UKRI Gateway to Research, UK); both by default. A search by
441
+ investigator name uses NIH RePORTER only. Other funders are not covered.
442
  """
443
+ investigator, text = _said(investigator, 120, "investigator name"), _said(text, MAX_QUERY, "text")
444
  if not investigator and not text:
445
+ raise ToolError("Give an investigator name, words to search for, or both.")
446
+ since = _years(since, None)[0]
447
+ chosen = [f for f in dict.fromkeys(funders or ["nih", "ukri"]) if f in ("nih", "ukri")] or ["nih", "ukri"]
448
 
449
  def run() -> dict[str, Any]:
450
  last, first = split_name(investigator) if investigator else ("", "")
 
461
  )
462
  if "ukri" in chosen and text and not investigator:
463
  found += ukri.search(http, text, limit=_clip(max_grants, 1, 100))
464
+ notes: list[str] = []
465
+ grants = _fitting([g.brief() for g in found], notes, "grants")
466
+ return {"investigator": investigator, "text": text, "funders": chosen, "grants": grants, "notes": notes}
467
 
468
  return await _safely(run)
469
 
470
 
471
+ @mcp.tool(title="Find patents on a topic (up to 2014)", annotations=READ)
472
  async def find_patents(
473
  topic: str, from_year: int | None = None, to_year: int | None = None, max_patents: int = 25
474
  ) -> dict[str, Any]:
475
+ """Use this when the user wants older patents on a topic as background to what is already known: inventors,
476
+ country, CPC classes and an Espacenet link. Source: the patent records in Europe PMC, which end in 2014. Do not
477
+ use it for recent patents: say that they need a patent office service such as Espacenet."""
478
+ topic = _said(topic, MAX_QUERY, "topic", needed=True)
479
+ from_year, to_year = _years(from_year, to_year)
480
 
481
  def run() -> dict[str, Any]:
482
  with Http() as http:
483
  found = patents.search(http, topic, from_year, to_year, _clip(max_patents, 1, 100))
484
+ notes: list[str] = []
485
+ rows = _fitting([p.brief() for p in found], notes, "patents")
486
+ return {"topic": topic, "covers_up_to": patents.LAST_YEAR, "patents": rows, "notes": notes}
487
 
488
  return await _safely(run)
489
 
src/labscout/sources/europepmc.py CHANGED
@@ -5,15 +5,21 @@ https://europepmc.org/RestfulWebService
5
 
6
  from __future__ import annotations
7
 
 
 
8
  import re
9
  from collections.abc import Callable
10
  from concurrent.futures import ThreadPoolExecutor
11
  from datetime import date
12
  from typing import Any
13
 
 
 
14
  from ..http import Http
15
  from ..models import Author, Paper
16
- from ..text import clean_affiliation
 
 
17
 
18
  SEARCH = "https://www.ebi.ac.uk/europepmc/webservices/rest/search"
19
  # Europe PMC's own relevance order puts the newest papers first, so "most relevant" reads the most cited matches.
@@ -52,12 +58,28 @@ def _query(query: str, start: int | None, end: int | None, preprints: bool) -> s
52
 
53
 
54
  Progress = Callable[[str], None]
55
- CHUNK = 1500 # records per year range when a search is read in full, side by side
 
 
 
 
 
 
 
 
 
56
 
57
 
58
  def _count(http: Http, q: str) -> int:
59
- data = http.get_json(SEARCH, {"query": q, "format": "json", "resultType": "idlist", "pageSize": 1})
60
- return int(data.get("hitCount") or 0)
 
 
 
 
 
 
 
61
 
62
 
63
  def _read(http: Http, q: str, limit: int, sort: str, info: dict[str, object] | None = None) -> list[Paper]:
@@ -68,11 +90,11 @@ def _read(http: Http, q: str, limit: int, sort: str, info: dict[str, object] | N
68
  "query": q,
69
  "format": "json",
70
  "resultType": "core",
71
- "pageSize": min(1000, limit - len(papers)),
72
  "cursorMark": cursor,
73
  "sort": SORT[sort],
74
  }
75
- data = http.get_json(SEARCH, params)
76
  if info is not None and cursor == "*":
77
  info["total"] = int(data.get("hitCount") or 0)
78
  results = data.get("resultList", {}).get("result", [])
@@ -80,22 +102,24 @@ def _read(http: Http, q: str, limit: int, sort: str, info: dict[str, object] | N
80
  nxt = data.get("nextCursorMark")
81
  if not results or not nxt or nxt == cursor:
82
  break
 
 
83
  cursor = nxt
84
  return papers[:limit]
85
 
86
 
87
- def _ranges(http: Http, query: str, start: int, end: int, preprints: bool) -> list[tuple[int, int, int]]:
88
- """Year ranges of at most CHUNK records each (a single year may hold more), found by halving."""
89
  out: list[tuple[int, int, int]] = []
90
  todo = [(start, end)]
91
- with ThreadPoolExecutor(max_workers=4) as pool:
92
  while todo:
93
  counts = list(pool.map(lambda r: _count(http, _query(query, r[0], r[1], preprints)), todo))
94
  nxt = []
95
  for (a, b), n in zip(todo, counts, strict=True):
96
  if not n:
97
  continue
98
- if n <= CHUNK or a == b:
99
  out.append((a, b, n))
100
  else:
101
  mid = (a + b) // 2
@@ -104,6 +128,112 @@ def _ranges(http: Http, query: str, start: int, end: int, preprints: bool) -> li
104
  return sorted(out)
105
 
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  def search(
108
  http: Http,
109
  query: str,
@@ -115,36 +245,55 @@ def search(
115
  info: dict[str, object] | None = None,
116
  progress: Progress | None = None,
117
  ) -> list[Paper]:
118
- """Papers for the search, the most cited ("relevance") or the newest first; `info` receives the number of hits
119
- ("total"). When every hit fits in `limit`, the order does not change what is read, so the years are read as
120
- ranges side by side; otherwise the first `limit` in the chosen order are read one page after another."""
121
- total = _count(http, _query(query, start, end, preprints))
 
 
 
 
 
122
  if info is not None:
123
  info["total"] = total
124
- if total <= 1000 or total > limit:
 
 
125
  if progress and total > limit:
126
- progress(f"Europe PMC has {total:,} papers; reading the first {limit:,} in its order, page by page")
127
- return _read(http, _query(query, start, end, preprints), limit, sort)
128
- first, last = start or 1900, end or date.today().year
129
- ranges = _ranges(http, query, first, last, preprints)
 
 
 
 
 
 
130
  if progress:
131
- shown = ", ".join(f"{a}" if a == b else f"{a} to {b}" for a, b, _ in ranges[:6])
132
- more = f" and {len(ranges) - 6} more" if len(ranges) > 6 else ""
133
- progress(
134
- f"Europe PMC has {total:,} papers; reading all of them in {len(ranges)} year ranges side by side "
135
- f"({shown}{more})"
136
- )
 
137
  done = [0]
 
138
 
139
- def one(r: tuple[int, int, int]) -> list[Paper]:
140
- got = _read(http, _query(query, r[0], r[1], preprints), r[2] + 100, sort)
141
  done[0] += len(got)
142
  if progress:
143
- progress(f"Europe PMC: {done[0]:,} of {total:,} records read")
144
  return got
145
 
146
- with ThreadPoolExecutor(max_workers=6) as pool:
147
- papers = [p for part in pool.map(one, ranges) for p in part]
 
 
 
 
148
  return papers
149
 
150
 
@@ -159,7 +308,7 @@ def _author(a: dict[str, Any]) -> Author | None:
159
  orcid = ""
160
  aid = a.get("authorId") or {}
161
  if (aid.get("type") or "").upper() == "ORCID":
162
- orcid = aid.get("value", "")
163
  return Author(
164
  last_name=last,
165
  fore_name=(a.get("firstName") or "").strip(),
 
5
 
6
  from __future__ import annotations
7
 
8
+ import calendar
9
+ import logging
10
  import re
11
  from collections.abc import Callable
12
  from concurrent.futures import ThreadPoolExecutor
13
  from datetime import date
14
  from typing import Any
15
 
16
+ import httpx
17
+
18
  from ..http import Http
19
  from ..models import Author, Paper
20
+ from ..text import clean_affiliation, orcid_id
21
+
22
+ log = logging.getLogger(__name__)
23
 
24
  SEARCH = "https://www.ebi.ac.uk/europepmc/webservices/rest/search"
25
  # Europe PMC's own relevance order puts the newest papers first, so "most relevant" reads the most cited matches.
 
58
 
59
 
60
  Progress = Callable[[str], None]
61
+ PAGE = 1000 # the largest page Europe PMC gives
62
+ WORKERS = 6 # parts read side by side
63
+ PART = 850 # records a part should hold: one page each, with some room
64
+ HEDGE = 2.0 # seconds after which a small request is sent a second time (see `_count`)
65
+ GROWTH = 1.07 # papers published in a year, against the year before: used to cut the years into even parts
66
+
67
+
68
+ def _answered(data: Any) -> bool:
69
+ """Europe PMC has at times answered 200 with nothing but its version. That is a failed answer, not "no papers"."""
70
+ return isinstance(data, dict) and "hitCount" in data
71
 
72
 
73
  def _count(http: Http, q: str) -> int:
74
+ """How many records a search has. Europe PMC answers a part of its requests seven or eight seconds late, while
75
+ the same request sent again comes back at once; so this small request is repeated when it is slow."""
76
+ params = {"query": q, "format": "json", "resultType": "idlist", "pageSize": 1}
77
+ return int(http.get_json(SEARCH, params, check=_answered, hedge=HEDGE).get("hitCount") or 0)
78
+
79
+
80
+ def count(http: Http, query: str, start: int | None = None, end: int | None = None, preprints: bool = True) -> int:
81
+ """How many records the search has; the search itself asks the same and finds the answer in the cache."""
82
+ return _count(http, _query(query, start, end, preprints))
83
 
84
 
85
  def _read(http: Http, q: str, limit: int, sort: str, info: dict[str, object] | None = None) -> list[Paper]:
 
90
  "query": q,
91
  "format": "json",
92
  "resultType": "core",
93
+ "pageSize": min(PAGE, limit - len(papers)),
94
  "cursorMark": cursor,
95
  "sort": SORT[sort],
96
  }
97
+ data = http.get_json(SEARCH, params, check=_answered)
98
  if info is not None and cursor == "*":
99
  info["total"] = int(data.get("hitCount") or 0)
100
  results = data.get("resultList", {}).get("result", [])
 
102
  nxt = data.get("nextCursorMark")
103
  if not results or not nxt or nxt == cursor:
104
  break
105
+ if len(results) < params["pageSize"] or len(papers) >= int(data.get("hitCount") or 0):
106
+ break # a short page is the last one: no need to ask for an empty page after it
107
  cursor = nxt
108
  return papers[:limit]
109
 
110
 
111
+ def _ranges(http: Http, query: str, start: int, end: int, preprints: bool, chunk: int) -> list[tuple[int, int, int]]:
112
+ """Year ranges of at most `chunk` records each (a single year may hold more), found by halving."""
113
  out: list[tuple[int, int, int]] = []
114
  todo = [(start, end)]
115
+ with ThreadPoolExecutor(max_workers=WORKERS) as pool:
116
  while todo:
117
  counts = list(pool.map(lambda r: _count(http, _query(query, r[0], r[1], preprints)), todo))
118
  nxt = []
119
  for (a, b), n in zip(todo, counts, strict=True):
120
  if not n:
121
  continue
122
+ if n <= chunk or a == b:
123
  out.append((a, b, n))
124
  else:
125
  mid = (a + b) // 2
 
128
  return sorted(out)
129
 
130
 
131
+ def _year_groups(first: int, last: int, groups: int) -> list[tuple[int, int]]:
132
+ """The years cut into runs that should hold about the same number of papers. More is published every year, so
133
+ the later runs are shorter. Nothing is counted for this: a count per year would cost more than it saves."""
134
+ years = list(range(first, last + 1))
135
+ groups = max(1, min(groups, len(years)))
136
+ weight = [GROWTH ** min(i, 40) for i in range(len(years))]
137
+ total, out, at, acc = sum(weight), [], 0, 0.0
138
+ for i, w in enumerate(weight):
139
+ acc += w
140
+ left = len(years) - i - 1 # years after this one
141
+ want = groups - len(out) - 1 # runs still to open after the current one
142
+ if (acc >= total * (len(out) + 1) / groups and left >= want) or left == want:
143
+ out.append((years[at], years[i]))
144
+ at = i + 1
145
+ if len(out) == groups - 1:
146
+ break
147
+ if at < len(years):
148
+ out.append((years[at], years[-1]))
149
+ return out
150
+
151
+
152
+ def _year_parts(q: str, year: int, parts: int) -> list[tuple[str, int]]:
153
+ """One year's search as up to twelve searches that together give exactly the same records, each with the number
154
+ of months it spans. All but the last ask for a span of first publication dates; the last one asks for everything
155
+ outside those spans (the later months and records without a date), so no record can fall between two parts or
156
+ into two of them."""
157
+ parts = max(2, min(12, parts))
158
+ step = 12 / parts
159
+ out, month = [], 1
160
+ for i in range(1, parts):
161
+ upto = max(month, min(11, round(i * step)))
162
+ last_day = calendar.monthrange(year, upto)[1]
163
+ out.append(
164
+ (f"({q}) AND (FIRST_PDATE:[{year}-{month:02d}-01 TO {year}-{upto:02d}-{last_day:02d}])", upto - month + 1)
165
+ )
166
+ month = upto + 1
167
+ if month > 11:
168
+ break
169
+ last_day = calendar.monthrange(year, month - 1)[1]
170
+ out.append((f"({q}) NOT (FIRST_PDATE:[{year}-01-01 TO {year}-{month - 1:02d}-{last_day:02d}])", 13 - month))
171
+ return out
172
+
173
+
174
+ def _share(limit: int, sizes: list[float]) -> list[int]:
175
+ """`limit` records divided over groups in proportion to their sizes."""
176
+ total = sum(sizes)
177
+ if not total:
178
+ return [0 for _ in sizes]
179
+ exact = [limit * n / total for n in sizes]
180
+ take = [int(x) for x in exact]
181
+ for i in sorted(range(len(sizes)), key=lambda i: (-(exact[i] - take[i]), i))[: limit - sum(take)]:
182
+ take[i] += 1 # the largest remainders first
183
+ return take
184
+
185
+
186
+ def _first_year(http: Http, q: str) -> int | None:
187
+ """The year of the oldest record of a search, to know which years to go through."""
188
+ params = {"query": q, "format": "json", "resultType": "lite", "pageSize": 1, "sort": "FIRST_PDATE_D asc"}
189
+ answer = http.get_json(SEARCH, params, check=_answered, hedge=HEDGE)
190
+ result = (answer.get("resultList") or {}).get("result") or []
191
+ if not result:
192
+ return None
193
+ years = [str(result[0].get(k) or "")[:4] for k in ("pubYear", "firstPublicationDate")]
194
+ return min((int(y) for y in years if y.isdigit()), default=None)
195
+
196
+
197
+ def _plan_all(query: str, first: int, last: int, preprints: bool, total: int) -> list[tuple[str, int]]:
198
+ """Every record of the search, as parts that together hold each record once: (search text, records to take)."""
199
+ parts = max(2, min(2 * WORKERS, -(-total // PART)))
200
+ years = last - first + 1
201
+ if years >= parts:
202
+ return [(_query(query, a, b, preprints), total) for a, b in _year_groups(first, last, parts)]
203
+ plan = []
204
+ for y, per_year in zip(range(first, last + 1), _share(parts, [GROWTH**i for i in range(years)]), strict=True):
205
+ q = _query(query, y, y, preprints)
206
+ plan += [(part, total) for part, _ in _year_parts(q, y, per_year)] if per_year > 1 else [(q, total)]
207
+ return plan
208
+
209
+
210
+ def _plan_shares(
211
+ http: Http, query: str, first: int, last: int, preprints: bool, total: int, limit: int
212
+ ) -> list[tuple[str, int]]:
213
+ """The `limit` most cited papers of a search that has more: every year gives its share, in proportion to what
214
+ was published in it. Up to six years are counted one by one, side by side; a longer time in runs of years."""
215
+ if last - first < 6:
216
+ years = list(range(first, last + 1))
217
+ try:
218
+ with ThreadPoolExecutor(max_workers=len(years)) as pool:
219
+ sizes = list(pool.map(lambda y: float(_count(http, _query(query, y, y, preprints))), years))
220
+ except httpx.HTTPError: # no counts to be had: equal shares, as good a guess as any
221
+ sizes = [1.0] * len(years)
222
+ spans = [(y, y, n) for y, n in zip(years, sizes, strict=True) if n]
223
+ else:
224
+ chunk = max(PAGE, total // 12)
225
+ spans = [(a, b, float(n)) for a, b, n in _ranges(http, query, first, last, preprints, chunk)]
226
+ plan: list[tuple[str, int]] = []
227
+ for (a, b, _), k in zip(spans, _share(limit, [n for _, _, n in spans]), strict=True):
228
+ q = _query(query, a, b, preprints)
229
+ if a == b and k > 1.2 * PART: # a big share of one year: dated parts, each by the months it spans
230
+ parts = _year_parts(q, a, -(-k // PART))
231
+ plan += [(part, t) for (part, _), t in zip(parts, _share(k, [m for _, m in parts]), strict=True) if t]
232
+ elif k:
233
+ plan.append((q, k))
234
+ return plan
235
+
236
+
237
  def search(
238
  http: Http,
239
  query: str,
 
245
  info: dict[str, object] | None = None,
246
  progress: Progress | None = None,
247
  ) -> list[Paper]:
248
+ """Papers for the search; `info` receives the number of hits ("total").
249
+
250
+ Europe PMC builds full records slowly (about eight seconds for a thousand) but serves several requests at once.
251
+ One page is one request. Anything larger is read as a few parts side by side. When every hit fits in `limit`,
252
+ the parts are runs of years (big years are split by date) that together hold each record once. When there are
253
+ more hits than `limit`, the most cited papers of each year are read, every year giving its share ("relevance"),
254
+ or simply the newest ("newest")."""
255
+ whole = _query(query, start, end, preprints)
256
+ total = _count(http, whole)
257
  if info is not None:
258
  info["total"] = total
259
+ if not total:
260
+ return []
261
+ if total <= PAGE or (total > limit and (limit <= PAGE or sort == "newest")):
262
  if progress and total > limit:
263
+ progress(f"Europe PMC has {total:,} papers; reading the first {limit:,} in its order")
264
+ return _read(http, whole, limit, sort)
265
+ first = start or _first_year(http, whole) or 1900
266
+ last = end or date.today().year
267
+ if total <= limit:
268
+ plan = _plan_all(query, first, last, preprints, total)
269
+ if not start: # also what is dated before the oldest year found, or not dated at all
270
+ plan.append((f"({whole}) NOT (PUB_YEAR:[{first} TO {last}])", total))
271
+ else:
272
+ plan = _plan_shares(http, query, first, last, preprints, total, limit)
273
  if progress:
274
+ if total <= limit:
275
+ progress(f"Europe PMC has {total:,} papers; reading all of them in {len(plan)} parts side by side")
276
+ else:
277
+ progress(
278
+ f"Europe PMC has {total:,} papers; reading the {limit:,} most cited, every year giving its share, "
279
+ f"in {len(plan)} parts side by side"
280
+ )
281
  done = [0]
282
+ aim = min(total, limit)
283
 
284
+ def one(part: tuple[str, int]) -> list[Paper]:
285
+ got = _read(http, part[0], part[1], sort)
286
  done[0] += len(got)
287
  if progress:
288
+ progress(f"Europe PMC: {min(done[0], aim):,} of {aim:,} records read")
289
  return got
290
 
291
+ with ThreadPoolExecutor(max_workers=WORKERS) as pool:
292
+ papers = [p for part in pool.map(one, plan) for p in part]
293
+ if total <= limit and len(papers) < total - max(5, total // 100):
294
+ # the parts should hold every record; if they fall short, read the search plainly rather than lose papers
295
+ log.warning("Europe PMC: the parts gave %s of %s records; reading the search in one piece", len(papers), total)
296
+ return _read(http, whole, limit, sort)
297
  return papers
298
 
299
 
 
308
  orcid = ""
309
  aid = a.get("authorId") or {}
310
  if (aid.get("type") or "").upper() == "ORCID":
311
+ orcid = orcid_id(aid.get("value", ""))
312
  return Author(
313
  last_name=last,
314
  fore_name=(a.get("firstName") or "").strip(),
src/labscout/sources/pubmed.py CHANGED
@@ -1,31 +1,38 @@
1
- """PubMed through NCBI's official E-utilities: search, then fetch the records as XML.
2
 
3
  NCBI asks programs to use E-utilities rather than the PubMed website, to send a tool name and a contact e-mail, and to
4
  stay within 3 requests per second (10 with an API key): https://www.ncbi.nlm.nih.gov/books/NBK25497/
 
 
 
 
5
  """
6
 
7
  from __future__ import annotations
8
 
9
  import logging
 
10
  import re
11
  import time
12
  import xml.etree.ElementTree as ET
13
  from collections.abc import Callable
14
  from concurrent.futures import ThreadPoolExecutor
15
  from datetime import date
 
16
 
17
  import httpx
18
 
19
  from ..errors import SearchError
20
- from ..http import Http
21
  from ..models import Author, Paper
22
- from ..text import clean_affiliation
23
 
24
  log = logging.getLogger(__name__)
25
 
26
  BASE = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
27
  TOOL = "labscout"
28
  ESEARCH_CAP = 9999 # esearch cannot page past 10,000 records; larger searches are split by year
 
29
 
30
 
31
  def _params(http: Http, **extra: object) -> dict[str, object]:
@@ -48,19 +55,50 @@ def _term(query: str, start: int | None, end: int | None) -> str:
48
  SORT = {"relevance": "relevance", "newest": "pub_date"} # PubMed's "Best Match", or publication date
49
 
50
 
51
- def _esearch(http: Http, term: str, retmax: int, sort: str = "newest") -> tuple[int, list[str], str]:
52
- """The number of hits, the first ids, and how PubMed read the search (its query translation)."""
 
 
 
 
 
 
53
  data = http.get_json(
54
- f"{BASE}/esearch.fcgi", _params(http, term=term, retmode="json", retmax=retmax, sort=SORT[sort])
 
 
55
  )
56
  res = data.get("esearchresult", {})
57
  if "ERROR" in res:
58
  raise SearchError(f"PubMed did not accept the search: {res['ERROR']}")
 
 
 
 
 
59
  return int(res.get("count", 0)), list(res.get("idlist", [])), res.get("querytranslation", "")
60
 
61
 
62
- def count(http: Http, query: str, start: int | None = None, end: int | None = None) -> int:
63
- return _esearch(http, _term(query, start, end), 0)[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
 
66
  def search_ids(
@@ -73,24 +111,54 @@ def search_ids(
73
  info: dict[str, object] | None = None,
74
  ) -> list[str]:
75
  """PubMed ids for the search, most relevant or newest first, at most `limit`; `info` receives the number of hits
76
- ("total") and PubMed's reading of the search ("translation"). Over 9,999 ids are collected year by year."""
77
- total, ids, translation = _esearch(http, _term(query, start, end), min(limit, ESEARCH_CAP), sort)
 
 
 
78
  if info is not None:
79
- info.update(total=total, translation=translation)
80
- if total <= ESEARCH_CAP or len(ids) >= limit:
 
 
81
  return ids[:limit]
82
  ids = []
83
- year = end or date.today().year
84
- first = start or 1800
 
85
  while year >= first and len(ids) < limit:
86
- n, chunk, _ = _esearch(http, _term(query, year, year), min(limit - len(ids), ESEARCH_CAP), sort)
 
87
  if n > ESEARCH_CAP:
88
  log.warning("PubMed has %s records for %s alone; only the first %s are used", n, year, ESEARCH_CAP)
89
- ids += chunk
 
90
  year -= 1
91
  return ids[:limit]
92
 
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  def fetch(
95
  http: Http, ids: list[str], batch: int = 200, workers: int = 0, progress: Callable[[str], None] | None = None
96
  ) -> list[Paper]:
@@ -102,21 +170,34 @@ def fetch(
102
 
103
  done = [0]
104
 
105
- def get(chunk: list[str], tries: int = 3) -> list[Paper]:
106
- """One batch; a refused batch is tried again and then split, so one bad answer loses no records."""
 
 
107
  for attempt in range(tries):
108
  try:
109
- return parse(
110
- http.post_form_text(f"{BASE}/efetch.fcgi", _params(http, id=",".join(chunk), retmode="xml"))
111
- )
112
- except (httpx.HTTPStatusError, ET.ParseError) as err:
113
- log.warning("PubMed refused a batch of %s records (%s), trying again", len(chunk), err)
114
- time.sleep(1 + attempt)
 
 
 
 
 
 
 
 
 
 
 
115
  if len(chunk) == 1:
116
  log.warning("PubMed record %s could not be read; skipped", chunk[0])
117
  return []
118
  half = len(chunk) // 2
119
- return get(chunk[:half], 2) + get(chunk[half:], 2)
120
 
121
  def one(chunk: list[str]) -> list[Paper]:
122
  got = get(chunk)
@@ -155,8 +236,28 @@ def search(
155
 
156
 
157
  # ---- parsing --------------------------------------------------------------------------------------------------------
 
 
 
158
  def _text(el: ET.Element | None) -> str:
159
- return re.sub(r"\s+", " ", "".join(el.itertext())).strip() if el is not None else ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
 
162
  def _year(article: ET.Element) -> int | None:
@@ -175,8 +276,8 @@ def _author(el: ET.Element) -> Author | None:
175
  orcid = ""
176
  for ident in el.findall("Identifier"):
177
  if (ident.get("Source") or "").upper() == "ORCID":
178
- orcid = re.sub(r"^https?://orcid\.org/", "", (ident.text or "").strip())
179
- affs = [clean_affiliation(_text(a)) for a in el.findall("AffiliationInfo/Affiliation")]
180
  return Author(
181
  last_name=last,
182
  fore_name=_text(el.find("ForeName")),
@@ -186,10 +287,41 @@ def _author(el: ET.Element) -> Author | None:
186
  )
187
 
188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  def parse(xml: str) -> list[Paper]:
190
- root = ET.fromstring(xml)
191
  papers = []
192
- for art in root.findall("PubmedArticle"):
 
 
 
193
  cit = art.find("MedlineCitation")
194
  article = cit.find("Article") if cit is not None else None
195
  if cit is None or article is None:
@@ -223,3 +355,110 @@ def parse(xml: str) -> list[Paper]:
223
  )
224
  )
225
  return papers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PubMed through NCBI's official E-utilities: search, then fetch the records as XML or, on request, as MEDLINE text.
2
 
3
  NCBI asks programs to use E-utilities rather than the PubMed website, to send a tool name and a contact e-mail, and to
4
  stay within 3 requests per second (10 with an API key): https://www.ncbi.nlm.nih.gov/books/NBK25497/
5
+
6
+ MEDLINE text is four to five times smaller than XML and two to three times quicker to parse, but NCBI writes it in
7
+ ASCII: "Gaël Chételat" arrives as "Gael Chetelat", "β" as "beta", and sub- and superscripts stand in parentheses. XML
8
+ keeps every character, so it is the default; LABSCOUT_PUBMED_FORMAT=medline switches to the text format.
9
  """
10
 
11
  from __future__ import annotations
12
 
13
  import logging
14
+ import os
15
  import re
16
  import time
17
  import xml.etree.ElementTree as ET
18
  from collections.abc import Callable
19
  from concurrent.futures import ThreadPoolExecutor
20
  from datetime import date
21
+ from functools import lru_cache
22
 
23
  import httpx
24
 
25
  from ..errors import SearchError
26
+ from ..http import BadAnswer, Http, plain_error
27
  from ..models import Author, Paper
28
+ from ..text import clean_affiliation, orcid_id
29
 
30
  log = logging.getLogger(__name__)
31
 
32
  BASE = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
33
  TOOL = "labscout"
34
  ESEARCH_CAP = 9999 # esearch cannot page past 10,000 records; larger searches are split by year
35
+ DEFAULT_FORMAT = "xml" # "medline" is smaller and faster, but loses accents and other non-ASCII characters
36
 
37
 
38
  def _params(http: Http, **extra: object) -> dict[str, object]:
 
55
  SORT = {"relevance": "relevance", "newest": "pub_date"} # PubMed's "Best Match", or publication date
56
 
57
 
58
+ DATE_ONLY = re.compile(r"\(?\d{4}(/\d\d/\d\d)?:\d{4}(/\d\d/\d\d)?\[Date - Publication\]\)?")
59
+
60
+
61
+ def _esearch(
62
+ http: Http, term: str, retmax: int, sort: str = "newest", notes: dict[str, object] | None = None
63
+ ) -> tuple[int, list[str], str]:
64
+ """The number of hits, the first ids, and how PubMed read the search (its query translation). `notes` receives
65
+ the words PubMed did not know ("not_found")."""
66
  data = http.get_json(
67
+ f"{BASE}/esearch.fcgi",
68
+ _params(http, term=term, retmode="json", retmax=retmax, sort=SORT[sort]),
69
+ keep=lambda d: "ERROR" not in (d.get("esearchresult") or {"ERROR": ""}),
70
  )
71
  res = data.get("esearchresult", {})
72
  if "ERROR" in res:
73
  raise SearchError(f"PubMed did not accept the search: {res['ERROR']}")
74
+ if notes is not None:
75
+ lost = list((res.get("errorlist") or {}).get("phrasesnotfound") or [])
76
+ lost += list((res.get("warninglist") or {}).get("quotedphrasesnotfound") or [])
77
+ if lost:
78
+ notes["not_found"] = list(dict.fromkeys(str(x) for x in lost))
79
  return int(res.get("count", 0)), list(res.get("idlist", [])), res.get("querytranslation", "")
80
 
81
 
82
+ def check_reading(query: str, translation: str, total: int) -> None:
83
+ """Stop when PubMed could read none of the search words. It drops what it cannot read without saying so (words in
84
+ Cyrillic, Chinese or Arabic letters, for example), and what is left is every paper of the chosen years."""
85
+ if not query.strip() or not total:
86
+ return
87
+ if not translation.strip() or DATE_ONLY.fullmatch(translation.strip()):
88
+ raise SearchError(
89
+ "PubMed could not read any word of this search, so it would return every paper of these years. "
90
+ "Please type the topic in English, in Latin letters."
91
+ )
92
+
93
+
94
+ def count(
95
+ http: Http, query: str, start: int | None = None, end: int | None = None, limit: int = 0, sort: str = "newest"
96
+ ) -> int:
97
+ """How many papers PubMed has for the search. With `limit` and `sort` it asks exactly what `search_ids` will ask
98
+ next, so that the search finds the answer in the cache instead of asking PubMed twice."""
99
+ total, _, translation = _esearch(http, _term(query, start, end), min(limit, ESEARCH_CAP), sort)
100
+ check_reading(query, translation, total)
101
+ return total
102
 
103
 
104
  def search_ids(
 
111
  info: dict[str, object] | None = None,
112
  ) -> list[str]:
113
  """PubMed ids for the search, most relevant or newest first, at most `limit`; `info` receives the number of hits
114
+ ("total"), PubMed's reading of the search ("translation") and the words it did not know ("not_found"). The newest
115
+ order collects more than 9,999 ids year by year; the most relevant order ends at 9,999, PubMed's own limit."""
116
+ notes: dict[str, object] = {}
117
+ total, ids, translation = _esearch(http, _term(query, start, end), min(limit, ESEARCH_CAP), sort, notes)
118
+ check_reading(query, translation, total)
119
  if info is not None:
120
+ info.update(total=total, translation=translation, **notes)
121
+ # PubMed gives at most 9,999 ids for one search. Its best matches cannot be continued past that point, so the
122
+ # most relevant order stops there; only the newest order goes on year by year.
123
+ if total <= ESEARCH_CAP or len(ids) >= limit or sort == "relevance":
124
  return ids[:limit]
125
  ids = []
126
+ seen: set[str] = set()
127
+ year = min(end or date.today().year, date.today().year + 1)
128
+ first = max(start or 1800, 1800)
129
  while year >= first and len(ids) < limit:
130
+ # a paper printed in one year and online the year before is found under both: some more are asked for
131
+ n, chunk, _ = _esearch(http, _term(query, year, year), min(limit - len(ids) + 500, ESEARCH_CAP), sort)
132
  if n > ESEARCH_CAP:
133
  log.warning("PubMed has %s records for %s alone; only the first %s are used", n, year, ESEARCH_CAP)
134
+ ids += [i for i in chunk if i not in seen]
135
+ seen.update(chunk)
136
  year -= 1
137
  return ids[:limit]
138
 
139
 
140
+ def _format() -> str:
141
+ """The format records are fetched in: LABSCOUT_PUBMED_FORMAT, "xml" or "medline" (MEDLINE text)."""
142
+ value = os.environ.get("LABSCOUT_PUBMED_FORMAT", "").strip().lower()
143
+ return value if value in ("xml", "medline") else DEFAULT_FORMAT
144
+
145
+
146
+ def _whole(text: str, asked: int) -> bool:
147
+ """An XML answer of efetch worth keeping: it ends as a record set does and holds about as many records as were
148
+ asked for. An id PubMed no longer has may be missing; an error document or a cut-off answer is asked for again
149
+ instead of being kept as "no records"."""
150
+ got = text.count("<PubmedArticle>") + text.count("<PubmedBookArticle>")
151
+ return text.rstrip().endswith("</PubmedArticleSet>") and got >= asked - max(1, asked // 10)
152
+
153
+
154
+ def _efetch(http: Http, chunk: list[str], fmt: str) -> str:
155
+ params = _params(http, id=",".join(chunk))
156
+ if fmt == "medline":
157
+ return http.post_form_text(f"{BASE}/efetch.fcgi", params | {"rettype": "medline", "retmode": "text"})
158
+ asked = len(set(chunk))
159
+ return http.post_form_text(f"{BASE}/efetch.fcgi", params | {"retmode": "xml"}, check=lambda t: _whole(t, asked))
160
+
161
+
162
  def fetch(
163
  http: Http, ids: list[str], batch: int = 200, workers: int = 0, progress: Callable[[str], None] | None = None
164
  ) -> list[Paper]:
 
170
 
171
  done = [0]
172
 
173
+ def get(chunk: list[str], tries: int = 3, fmt: str = _format()) -> list[Paper]:
174
+ """One batch; a refused batch is tried again and then split, so one bad answer loses no records. MEDLINE text
175
+ that cannot be read, or that holds fewer records than were asked for, is tried again and then read as XML."""
176
+ short: list[Paper] | None = None # MEDLINE text only: what an answer held that was not complete
177
  for attempt in range(tries):
178
  try:
179
+ if fmt == "xml":
180
+ return parse(_efetch(http, chunk, fmt))
181
+ short = parse_medline(_efetch(http, chunk, fmt))
182
+ if len(short) >= len(set(chunk)):
183
+ return short
184
+ err: object = f"{len(short)} records came back"
185
+ except (httpx.HTTPStatusError, BadAnswer, ET.ParseError) as refused:
186
+ err, short = refused, None
187
+ except ValueError as unreadable: # from parse_medline
188
+ err, short = unreadable, []
189
+ said = plain_error(err) if isinstance(err, Exception) else err
190
+ log.warning("PubMed refused a batch of %s records (%s), trying again", len(chunk), said)
191
+ time.sleep(1 + attempt)
192
+ if fmt == "medline" and short is not None:
193
+ log.warning("PubMed's MEDLINE text for %s records stayed incomplete; reading them as XML", len(chunk))
194
+ full = get(chunk, tries, "xml")
195
+ return full if len(full) > len(short) else short
196
  if len(chunk) == 1:
197
  log.warning("PubMed record %s could not be read; skipped", chunk[0])
198
  return []
199
  half = len(chunk) // 2
200
+ return get(chunk[:half], 2, fmt) + get(chunk[half:], 2, fmt)
201
 
202
  def one(chunk: list[str]) -> list[Paper]:
203
  got = get(chunk)
 
236
 
237
 
238
  # ---- parsing --------------------------------------------------------------------------------------------------------
239
+ _clean = lru_cache(maxsize=4096)(clean_affiliation) # one search brings the same affiliation many times
240
+
241
+
242
  def _text(el: ET.Element | None) -> str:
243
+ return " ".join("".join(el.itertext()).split()) if el is not None else ""
244
+
245
+
246
+ def _without_references(xml: str) -> str:
247
+ """The answer without its lists of cited references: about two thirds of a recent record, and no field is read
248
+ from them. The lists are the last children of PubmedData (of BookDocument in a book record), so each run of them
249
+ ends where that parent closes."""
250
+ parts, at = [], 0
251
+ ends = {"</PubmedData>": -1, "</BookDocument>": -1} # the next closing tag of each kind
252
+ while (start := xml.find("<ReferenceList>", at)) >= 0:
253
+ for tag, pos in ends.items():
254
+ if pos < start:
255
+ found = xml.find(tag, start)
256
+ ends[tag] = found if found >= 0 else len(xml)
257
+ parts.append(xml[at:start])
258
+ at = min(ends.values())
259
+ parts.append(xml[at:])
260
+ return "".join(parts)
261
 
262
 
263
  def _year(article: ET.Element) -> int | None:
 
276
  orcid = ""
277
  for ident in el.findall("Identifier"):
278
  if (ident.get("Source") or "").upper() == "ORCID":
279
+ orcid = orcid_id(ident.text or "")
280
+ affs = [_clean(_text(a)) for a in el.findall("AffiliationInfo/Affiliation")]
281
  return Author(
282
  last_name=last,
283
  fore_name=_text(el.find("ForeName")),
 
287
  )
288
 
289
 
290
+ def _book(el: ET.Element) -> Paper:
291
+ """A book or a book chapter (PubmedBookArticle), read as MEDLINE text gives it: the chapter's own title and date,
292
+ the book in place of the journal, the chapter's authors and not the editors of the book."""
293
+ doc = el.find("BookDocument")
294
+ book = doc.find("Book")
295
+ chapter = doc.find("ArticleTitle")
296
+ year = _text(doc.find("ContributionDate/Year")) or _text(book.find("PubDate/Year"))
297
+ people = doc.findall("AuthorList[@Type='authors']/Author") or book.findall("AuthorList[@Type='authors']/Author")
298
+ ids = {i.get("IdType"): (i.text or "").strip() for i in doc.findall("ArticleIdList/ArticleId")}
299
+ return Paper(
300
+ title=_text(chapter if chapter is not None else book.find("BookTitle")),
301
+ year=int(year) if year.isdigit() else None,
302
+ journal=_text(book.find("BookTitle" if chapter is not None else "CollectionTitle")),
303
+ pmid=_text(doc.find("PMID")),
304
+ doi=ids.get("doi", "").lower(),
305
+ pmcid=ids.get("pmc", ""),
306
+ authors=[a for a in (_author(x) for x in people) if a],
307
+ keywords=[_text(k) for k in doc.findall("KeywordList/Keyword")],
308
+ publication_types=[
309
+ *(_text(t) for t in doc.findall("PublicationType")),
310
+ "Book Chapter" if chapter is not None else "Book", # the type MEDLINE text adds
311
+ ],
312
+ abstract=" ".join(_text(a) for a in doc.findall("Abstract/AbstractText")),
313
+ funders=sorted({_text(g.find("Agency")) for g in doc.findall("GrantList/Grant")}),
314
+ sources=["pubmed"],
315
+ )
316
+
317
+
318
  def parse(xml: str) -> list[Paper]:
319
+ root = ET.fromstring(_without_references(xml))
320
  papers = []
321
+ for art in root:
322
+ if art.tag == "PubmedBookArticle":
323
+ papers.append(_book(art))
324
+ continue
325
  cit = art.find("MedlineCitation")
326
  article = cit.find("Article") if cit is not None else None
327
  if cit is None or article is None:
 
355
  )
356
  )
357
  return papers
358
+
359
+
360
+ # ---- parsing MEDLINE text -------------------------------------------------------------------------------------------
361
+ # A field is a tag of two to four letters, "- " and its value; lines that start with six spaces carry the value on.
362
+ FIELD = re.compile(r"^([A-Z]{2,4}) *-(.*(?:\n {6}.*)*)$|^.*\S.*$", re.M)
363
+ # An issue date with a year of its own: "2025", "2025 Dec", "2025 Dec 5", "2014 Jan-Feb", "2013 Fall". Any other shape
364
+ # ("2025 Nov-Dec 01", "Winter 2023") is XML's free-form MedlineDate, which gives way to the electronic date.
365
+ ISSUE_YEAR = re.compile(r"\d{4}(?: [A-Z][a-z]{2} \d{1,2}|\D*)")
366
+ # Identifiers of an organisation, printed after its affiliation: "... Boston, MA, USA. RINGGOLD: 1867"
367
+ AFFILIATION_IDS = re.compile(r"(?:\.? (?:ROR|GRID|ISNI|RINGGOLD): [\w:/.]+(?: [\dX]{4})*)+$")
368
+
369
+
370
+ def _medline_year(issue: str, electronic: str) -> int | None:
371
+ """The year as `_year` reads it from XML: the issue's own year, then the electronic date, then the first year
372
+ in a free-form issue date."""
373
+ if ISSUE_YEAR.fullmatch(issue):
374
+ return int(issue[:4])
375
+ if electronic[:4].isdigit():
376
+ return int(electronic[:4])
377
+ m = re.search(r"(19|20)\d{2}", issue)
378
+ return int(m.group(0)) if m else None
379
+
380
+
381
+ def _medline_author(full: str, short: str) -> Author:
382
+ """An author from the full name ("Smith, John A Jr") and the short one ("Smith JA Jr"): last name, fore name and
383
+ initials as XML has them, without the suffix. A single name ("Suryanshu") is printed the same in both."""
384
+ if not full:
385
+ last, _, initials = short.rpartition(" ")
386
+ return Author(last_name=last, initials=initials) if last else Author(last_name=short)
387
+ cuts = [m.start() for m in re.finditer(", ", full)]
388
+ cut = next((c for c in cuts if short.startswith(full[:c] + " ")), len(full)) # a last name can hold a comma
389
+ fore, rest = full[cut + 2 :], short[cut + 1 :]
390
+ initials, _, suffix = rest.partition(" ")
391
+ if len(suffix) > 1 and fore.endswith(" " + suffix):
392
+ fore = fore[: -len(suffix) - 1]
393
+ else:
394
+ initials = rest
395
+ return Author(last_name=full[:cut], fore_name=fore, initials=initials)
396
+
397
+
398
+ def _agency(grant: str) -> str:
399
+ """The funder in "R01 HL142543/HL/NHLBI NIH HHS/United States": the part before the country. The country is empty
400
+ for grants that publishers report: "667696/European Union's Horizon 2020 Research and Innovation Program/"."""
401
+ return grant.rsplit("/", 2)[-2] if "/" in grant else grant
402
+
403
+
404
+ def _medline_paper(fields: list[tuple[str, str]]) -> Paper:
405
+ got: dict[str, list[str]] = {}
406
+ authors: list[Author] = []
407
+ full, person = "", None
408
+ for tag, value in fields:
409
+ if tag == "AU" and (full or value != "et al."): # "et al." closes an author list that MEDLINE cut short
410
+ person = _medline_author(full, value)
411
+ authors.append(person)
412
+ full = ""
413
+ elif tag == "AUID" and person:
414
+ if value.upper().startswith("ORCID:"):
415
+ person.orcid = orcid_id(value[6:])
416
+ elif tag == "AD" and person:
417
+ aff = _clean(AFFILIATION_IDS.sub("", value))
418
+ if aff:
419
+ person.affiliations.append(aff)
420
+ else: # any other line ends the author: the affiliations after a group author (CN) are the group's
421
+ person = None
422
+ if tag == "FAU":
423
+ full = value
424
+ else:
425
+ got.setdefault(tag, []).append(value)
426
+
427
+ def first(tag: str) -> str:
428
+ return got[tag][0] if tag in got else ""
429
+
430
+ types = got.get("PT", [])
431
+ dois = [v[:-5].strip() for tag in ("LID", "AID") for v in got.get(tag, []) if v.endswith("[doi]")]
432
+ own = first("CTDT") # the date of a book chapter itself, which PubMed searches as its publication date
433
+ return Paper(
434
+ title=first("TI") or first("BTI"),
435
+ year=int(own[:4]) if own[:4].isdigit() else _medline_year(first("DP"), first("DEP")),
436
+ journal=first("JT") or (first("BTI") if "TI" in got else first("CTI")),
437
+ pmid=first("PMID"),
438
+ doi=dois[-1].lower() if dois else "",
439
+ pmcid=first("PMC"),
440
+ authors=authors,
441
+ mesh=[v.replace("*", "").split("/")[0] for v in got.get("MH", [])],
442
+ keywords=[v.removeprefix("*") for v in got.get("OT", [])],
443
+ publication_types=types,
444
+ abstract=first("AB"),
445
+ funders=sorted({_agency(v) for v in got.get("GR", []) if v != "etc."}), # "etc." closes a cut grant list
446
+ is_preprint=any("preprint" in t.lower() for t in types),
447
+ sources=["pubmed"],
448
+ )
449
+
450
+
451
+ def parse_medline(text: str) -> list[Paper]:
452
+ """Papers from MEDLINE text (efetch with rettype=medline and retmode=text), built like the ones `parse` makes
453
+ from XML. The text itself differs from XML: it spells non-ASCII characters in ASCII, prints the section labels
454
+ of an abstract ("METHODS: ...") and lists publication types in alphabetical order. Text that is not in this format
455
+ raises ValueError."""
456
+ records: list[list[tuple[str, str]]] = []
457
+ for m in FIELD.finditer(text):
458
+ tag = m.group(1)
459
+ if tag == "PMID":
460
+ records.append([])
461
+ elif tag is None or not records:
462
+ raise ValueError(f"not MEDLINE text: {m.group(0)[:80]!r}")
463
+ records[-1].append((tag, " ".join(m.group(2).split())))
464
+ return [_medline_paper(fields) for fields in records]
src/labscout/sources/ror.py CHANGED
@@ -12,7 +12,9 @@ from __future__ import annotations
12
  import logging
13
  import os
14
  import re
15
- from concurrent.futures import ThreadPoolExecutor
 
 
16
  from typing import Any
17
 
18
  from ..http import Http
@@ -80,6 +82,12 @@ def _fits(org: dict[str, Any], affiliation: str, country: str) -> bool:
80
  return False
81
 
82
 
 
 
 
 
 
 
83
  class Resolver:
84
  """Affiliation text to Organization, with a memory so that each text is looked up once per run."""
85
 
@@ -90,6 +98,8 @@ class Resolver:
90
  self.local = ror_local.load()
91
  # with the local copy the API only gets the few affiliations it could not place, so a big search stays fast
92
  self.api_left = int(os.environ.get("LABSCOUT_ROR_API_BUDGET", "20")) if self.local else -1
 
 
93
 
94
  def __call__(self, affiliation: str) -> Organization | None:
95
  aff = clean_affiliation(affiliation)
@@ -111,39 +121,62 @@ class Resolver:
111
  return self.memo[key]
112
 
113
  def prefetch(self, affiliations: list[str]) -> None:
114
- """Places all affiliations of a search at once: the local copy first, then the misses that the API budget
115
- allows side by side (the shared pacing keeps them within ROR's limit), the rest by their country."""
 
116
  if not self.local:
117
  return
118
- misses = []
 
119
  for raw in affiliations:
120
  aff = clean_affiliation(raw)
121
  key = fold(aff)
122
- if not aff or key in self.memo:
 
 
 
123
  continue
124
  self.texts[key] = aff
125
  country = country_from_text(aff)
126
  org = self.local.match(aff, country)
127
- if org:
128
- self.memo[key] = org
129
- else:
130
- self.memo[key] = self._text_only(aff, country)
131
- misses.append((key, aff, country))
132
- ask = misses[: max(self.api_left, 0)]
 
133
  self.api_left = 0
134
  if ask:
135
-
136
- def one(item: tuple[str, str, str]) -> tuple[str, Organization | None]:
137
- key, aff, country = item
138
- try:
139
- return key, self._api(aff, country)
140
- except Exception as err:
141
- log.warning("ROR lookup failed (%s); using the text of the affiliation", err)
142
- return key, self._text_only(aff, country)
143
-
144
- with ThreadPoolExecutor(max_workers=6) as pool:
145
- for key, org in pool.map(one, ask):
146
- self.memo[key] = org
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  def _resolve(self, aff: str) -> Organization | None:
149
  country = country_from_text(aff)
 
12
  import logging
13
  import os
14
  import re
15
+ import threading
16
+ from collections import Counter
17
+ from concurrent.futures import Future, ThreadPoolExecutor, wait
18
  from typing import Any
19
 
20
  from ..http import Http
 
82
  return False
83
 
84
 
85
+ # What the ROR API said about an affiliation the local copy could not place, kept for the life of the process: the
86
+ # same affiliations come back in search after search, and the API should hear each of them once.
87
+ _API_SAID: dict[str, Organization | None] = {}
88
+ _API_LOCK = threading.Lock()
89
+
90
+
91
  class Resolver:
92
  """Affiliation text to Organization, with a memory so that each text is looked up once per run."""
93
 
 
98
  self.local = ror_local.load()
99
  # with the local copy the API only gets the few affiliations it could not place, so a big search stays fast
100
  self.api_left = int(os.environ.get("LABSCOUT_ROR_API_BUDGET", "20")) if self.local else -1
101
+ self._asked: list[Future[None]] = []
102
+ self._open = True # answers still go into this run's memory
103
 
104
  def __call__(self, affiliation: str) -> Organization | None:
105
  aff = clean_affiliation(affiliation)
 
121
  return self.memo[key]
122
 
123
  def prefetch(self, affiliations: list[str]) -> None:
124
+ """Places all affiliations of a search at once with the local copy. Those it cannot place keep their country
125
+ for now, and the ones that stand on most papers (as many as the API budget allows) are sent to the ROR API in
126
+ the background; `settle` takes in the answers that have arrived."""
127
  if not self.local:
128
  return
129
+ papers: Counter[str] = Counter()
130
+ misses: dict[str, tuple[str, str, str]] = {}
131
  for raw in affiliations:
132
  aff = clean_affiliation(raw)
133
  key = fold(aff)
134
+ if not aff:
135
+ continue
136
+ papers[key] += 1
137
+ if key in self.memo:
138
  continue
139
  self.texts[key] = aff
140
  country = country_from_text(aff)
141
  org = self.local.match(aff, country)
142
+ if org is None:
143
+ with _API_LOCK:
144
+ asked, org = key in _API_SAID, _API_SAID.get(key)
145
+ if not asked:
146
+ misses[key] = (key, aff, country)
147
+ self.memo[key] = org or self._text_only(aff, country)
148
+ ask = sorted(misses.values(), key=lambda m: (-papers[m[0]], m[0]))[: max(self.api_left, 0)]
149
  self.api_left = 0
150
  if ask:
151
+ pool = ThreadPoolExecutor(max_workers=6)
152
+ self._asked = [pool.submit(self._ask, item) for item in ask]
153
+ pool.shutdown(wait=False)
154
+
155
+ def _ask(self, item: tuple[str, str, str]) -> None:
156
+ key, aff, country = item
157
+ try:
158
+ org = self._api(aff, country)
159
+ except Exception as err:
160
+ log.warning("ROR lookup failed (%s); using the text of the affiliation", err)
161
+ return
162
+ found = org if org and org.ror else None
163
+ with _API_LOCK:
164
+ if len(_API_SAID) > 50_000:
165
+ _API_SAID.clear()
166
+ _API_SAID[key] = found
167
+ if found and self._open:
168
+ self.memo[key] = found
169
+
170
+ def settle(self, seconds: float) -> int:
171
+ """Waits up to `seconds` for the answers of the ROR API and returns how many came. After this the run's
172
+ memory does not change any more, so one search never sees two answers for one affiliation; answers that
173
+ come later are kept for the next search."""
174
+ if not self._asked:
175
+ return 0
176
+ done, _ = wait(self._asked, timeout=max(0.0, seconds))
177
+ with _API_LOCK:
178
+ self._open = False
179
+ return len(done)
180
 
181
  def _resolve(self, aff: str) -> Organization | None:
182
  country = country_from_text(aff)
src/labscout/sources/ror_local.py CHANGED
@@ -4,8 +4,22 @@ thousand papers take many minutes).
4
 
5
  The index is built from ROR's own data dump (CC0, published on Zenodo) with `labscout ror-index OUT`, once, for
6
  example when the Docker image is built. LABSCOUT_ROR_INDEX names the file; without it the API is used as before.
7
- A name matches an affiliation under the same rule as the API name search: every significant word of the name is in
8
- the affiliation and the country agrees. A one word name must be a whole part of the affiliation ("Inserm").
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  """
10
 
11
  from __future__ import annotations
@@ -16,24 +30,113 @@ import json
16
  import logging
17
  import os
18
  import re
 
19
  import urllib.request
20
  import zipfile
 
21
  from functools import lru_cache
22
- from typing import Any
23
 
24
  from ..models import Organization
25
- from ..text import _countries, fold, significant
26
 
27
  log = logging.getLogger(__name__)
28
 
29
  ZENODO = "https://zenodo.org/api/communities/ror-data/records?sort=newest&size=1"
30
  # names made only of these words ("Department of Public Health", "Faculty of Medicine") name no single organisation
31
  _GENERIC_WORDS = """department faculty school college university universite universidad universita universitat
32
- hospital clinic clinical centre center institute institut instituto istituto national public health medicine medical
33
- research science sciences general foundation unit laboratory laboratories group division service services city
34
- regional central state federal royal children women community care sleep"""
35
  GENERIC = set(_GENERIC_WORDS.split())
36
  TYPES = {"education": 0, "healthcare": 1, "facility": 2, "funder": 3, "government": 3, "nonprofit": 3, "company": 4}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
 
39
  def _row(org: dict[str, Any]) -> list[Any] | None:
@@ -42,26 +145,30 @@ def _row(org: dict[str, Any]) -> list[Any] | None:
42
  names = org.get("names", [])
43
  first = names[0]["value"] if names else ""
44
  display = next((n["value"] for n in names if "ror_display" in n.get("types", [])), first)
45
- labels = sorted({n["value"] for n in names if {"ror_display", "label", "alias"} & set(n.get("types", []))})
46
- acronyms = sorted({n["value"] for n in names if "acronym" in n.get("types", [])})
47
  loc = ((org.get("locations") or [{}])[0]).get("geonames_details") or {}
48
  kind = min((TYPES.get(t, 5) for t in org.get("types", [])), default=5)
49
  return [
50
  org["id"],
51
  display,
52
- labels,
53
- acronyms,
54
  loc.get("name", ""),
55
  loc.get("country_code", ""),
56
  loc.get("country_name", ""),
57
  loc.get("lat"),
58
  loc.get("lng"),
59
  kind,
 
 
 
 
60
  ]
61
 
62
 
63
  def build(out: str, source: str = "") -> int:
64
- """Writes the compact index (gzipped JSON rows) from a ROR dump zip, a file path or, by default, the newest dump."""
 
 
65
  if not source:
66
  meta = json.load(urllib.request.urlopen(ZENODO, timeout=60))
67
  files = meta["hits"]["hits"][0]["files"]
@@ -74,69 +181,499 @@ def build(out: str, source: str = "") -> int:
74
  with zipfile.ZipFile(io.BytesIO(blob)) as z:
75
  name = next(n for n in z.namelist() if n.endswith(".json"))
76
  data = json.loads(z.read(name))
77
- rows = [r for r in map(_row, data) if r]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  with gzip.open(out, "wt", encoding="utf-8") as f:
79
- json.dump(rows, f, ensure_ascii=False, separators=(",", ":"))
80
  return len(rows)
81
 
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  class LocalRor:
84
  def __init__(self, path: str) -> None:
85
  with gzip.open(path, "rt", encoding="utf-8") as f:
86
  self.rows = json.load(f)
87
- # each name is filed under its rarest significant word, so an affiliation only checks a few candidates
88
- freq: dict[str, int] = {}
89
- names: list[tuple[frozenset[str], int, str]] = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  for i, r in enumerate(self.rows):
 
 
 
 
 
 
 
 
 
91
  for label in r[2]:
92
- label = re.sub(r"\s*\([^)]*\)\s*$", "", label) # "CJ America (United States)": the country is a note
93
- need = frozenset(significant(label))
94
- if need:
95
- names.append((need, i, fold(label).strip()))
96
- for w in need:
97
- freq[w] = freq.get(w, 0) + 1
98
- self.index: dict[str, list[tuple[frozenset[str], int, str]]] = {}
99
- for need, i, label in names:
100
- self.index.setdefault(min(need, key=lambda w: (freq[w], w)), []).append((need, i, label))
101
- self.exact = {fold(a).strip(): i for i, r in enumerate(self.rows) for a in r[3] if len(a) >= 4}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  def match(self, affiliation: str, country: str) -> Organization | None:
104
- countries = _countries()
105
- parts = [p.strip(" .-") for p in affiliation.replace(";", ",").split(",") if p.strip(" .-")]
106
- # a part that only names a country ("United States of America") is a place, never an organisation
107
- parts = [p for p in parts if fold(p) not in countries]
108
- segs = [significant(p) for p in parts]
109
- folded = {fold(p) for p in parts}
110
- have = set().union(*segs) if segs else set()
111
- best: tuple[tuple[int, ...], int] | None = None
112
- for w in have:
113
- for need, i, label in self.index.get(w, ()):
114
- if need <= GENERIC:
115
- continue
116
- if len(need) == 1 and label not in folded:
117
- continue
118
- at = next((k for k, seg in enumerate(segs) if need <= seg), None)
119
- if at is None: # all words of the name must stand in one part of the affiliation
120
- continue
121
  r = self.rows[i]
122
- if country and r[5] and r[5] != country:
123
- continue
124
- score = (len(need), -r[9], -at)
125
- if best is None or score > best[0]:
126
- best = (score, i)
127
- if best is None:
128
- for p in folded: # a part that starts with an acronym such as "INSERM U1219" or "CNRS"
129
- i = self.exact.get(p.split(" ")[0]) if p else None
130
- if i is not None and (not country or self.rows[i][5] in ("", country)):
131
- best = ((0,), i)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  if best is None:
134
  return None
135
- r = self.rows[best[1]]
136
- return Organization(
137
- name=r[1], ror=r[0], city=r[4], country=r[5], country_name=r[6], lat=r[7], lon=r[8], match="ror-local"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  )
139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
  @lru_cache(maxsize=1)
142
  def load() -> LocalRor | None:
 
4
 
5
  The index is built from ROR's own data dump (CC0, published on Zenodo) with `labscout ror-index OUT`, once, for
6
  example when the Docker image is built. LABSCOUT_ROR_INDEX names the file; without it the API is used as before.
7
+
8
+ How an affiliation is matched:
9
+
10
+ - A name matches as a phrase: its words stand next to each other and in the same order in the text, so "Northwestern
11
+ University" is not "University of Northwestern". A name may run across a comma ("University of California, San
12
+ Francisco"), but a comma between two organisations separates them.
13
+ - The country must agree. The town and the region of the organisation are evidence: they decide between
14
+ organisations of one name, and a name that says little by itself ("Heart Institute", "Department of Public Health",
15
+ "Orange") is taken only when the town of that organisation is named as well.
16
+ - A name that is only the end or the beginning of a longer name in the text ("Smidt Heart Institute", "Yunnan
17
+ University of Chinese Medicine") is another organisation.
18
+ - The first institution of the text that can be placed is taken, and in it the first organisation named.
19
+ - When no name is found: the university of a school that ROR does not list ("Yale School of Nursing"), then an
20
+ acronym written in capitals ("INSERM U1219").
21
+
22
+ When no rule can decide, nothing is returned: a wrong organisation is worse than none.
23
  """
24
 
25
  from __future__ import annotations
 
30
  import logging
31
  import os
32
  import re
33
+ import unicodedata
34
  import urllib.request
35
  import zipfile
36
+ from collections import Counter
37
  from functools import lru_cache
38
+ from typing import Any, NamedTuple
39
 
40
  from ..models import Organization
41
+ from ..text import PART_OF, STOP, US_STATE_NAMES, US_STATES, _countries, _country_codes, country_from_text, institutions
42
 
43
  log = logging.getLogger(__name__)
44
 
45
  ZENODO = "https://zenodo.org/api/communities/ror-data/records?sort=newest&size=1"
46
  # names made only of these words ("Department of Public Health", "Faculty of Medicine") name no single organisation
47
  _GENERIC_WORDS = """department faculty school college university universite universidad universita universitat
48
+ hospital clinic clinical center institute institut instituto istituto national public health medicine medical
49
+ research science general foundation unit laboratory group division service city regional central state federal
50
+ royal children women community care sleep"""
51
  GENERIC = set(_GENERIC_WORDS.split())
52
  TYPES = {"education": 0, "healthcare": 1, "facility": 2, "funder": 3, "government": 3, "nonprofit": 3, "company": 4}
53
+ # a short name that begins with one of these is usually a unit inside an organisation
54
+ _UNIT_WORDS = """department departamento departement dipartimento division faculty facultad faculte faculdade school
55
+ college laboratory laboratoire laboratorio section unit service servicio program graduate"""
56
+ UNITS = set(_UNIT_WORDS.split())
57
+ # "Institute of Physics" is what many universities call a department
58
+ INSTITUTES = {"institute", "institut", "instituto", "istituto", "center", "centro", "zentrum"}
59
+ UNIVERSITY = {"university", "universite", "universidad", "universita", "universidade", "universitat", "universiteit"}
60
+ # words that make a name read as an organisation; a name without one ("Neurological Surgery") reads as a subject
61
+ _INSTITUTION_WORDS = """hospital hopital hospitalier clinic clinique klinik klinikum college institute institut
62
+ instituto istituto institutet academy academia school ecole escuela escola hochschule center centro zentrum
63
+ foundation fondation fundacion fundacao stiftung laboratory laboratoire laboratorio council ministry agency society
64
+ association trust universitet universitas polytechnic"""
65
+ INSTITUTION = UNIVERSITY | set(_INSTITUTION_WORDS.split())
66
+ # company forms: "Fitbit Inc" is the organisation "Fitbit"
67
+ _LEGAL_WORDS = """inc incorporated ltd limited llc llp plc corp corporation co company gmbh ag kg sa sas sarl srl spa
68
+ bv nv ab oy aps kk pty pte pvt"""
69
+ LEGAL = set(_LEGAL_WORDS.split())
70
+ SCHOOLS = {"school", "college", "faculty"}
71
+ LOWER_SCHOOLS = {"high", "secondary", "primary", "elementary", "middle"}
72
+ # what may follow a name written without its town: "University of Maryland School of Medicine, Baltimore"
73
+ AFTER_SHORT = SCHOOLS | {"campus", "department", "graduate"}
74
+ LINKS = {"of", "for", "de", "di", "do", "da", "du", "del", "della", "fur"} # between a unit and its subject or town
75
+ # "Frankfurt am Main" is written "Frankfurt", "Amherst Center" is written "Amherst", "Seongnam-si" is "Seongnam"
76
+ TOWN_LINKS = {"am", "an", "im", "upon", "on", "under", "ob"}
77
+ TOWN_TAILS = {"center", "si", "shi", "gun"}
78
+ COMMON = 100 # a word in this many names says little: "Heart Institute", "Mental Health Services"
79
+ CITY_SIZE = 20 # a town with this many organisations is a place first: "Boston Medical School" is not Boston University
80
+ TOWN_SIZE = 5 # and one with this many is known well enough to tell "Institut Pasteur de Lille" from the one in Paris
81
+
82
+ # how a name is filed, added to sixteen times the number of its row
83
+ ALIAS = 1 # an alias in ROR, or a form of the name made here
84
+ NEEDS_TOWN = 2 # the name of a campus, or a name written without its town: the town must be in the text
85
+ NEEDS_COUNTRY = 4 # a name written without its country: the country must be in the text
86
+ TURNED = 8 # "X University" made from "University of X" or the other way round
87
+
88
+ _LETTERS = str.maketrans(
89
+ {"ø": "o", "ł": "l", "ß": "ss", "æ": "ae", "œ": "oe", "đ": "d", "ð": "d", "þ": "th", "ı": "i", "ə": "e"}
90
+ | dict.fromkeys("'’‘ʻʼ`´", "")
91
+ | dict.fromkeys("\u2013\u2014\u2010\u2011\u2012", "-") # dashes
92
+ | dict.fromkeys("“”«»", '"')
93
+ )
94
+ _MARKS = re.compile(r"[\u0300-\u036f]+") # the accents that are left when a letter is taken apart
95
+ _NOT_ASCII = re.compile(r"[^\x00-\x7f]+")
96
+ _FOREIGN = re.compile(r"[^\W\d_\u0000-\u02af\u1e00-\u1eff]") # a letter that is not Latin
97
+ _INITIALS = re.compile(r"\b([a-z])\s?[.&]\s?(?=[a-z]\b)") # "T.H. Chan" and "T. H. Chan", "A&M" and "A & M"
98
+ _SPELLING = re.compile(r"\b(centre|programme|organisation|saint|mount)(?=s?\b)")
99
+ _SPELLED = {"centre": "center", "programme": "program", "organisation": "organization", "saint": "st", "mount": "mt"}
100
+ _PLURAL_Y = re.compile(r"(?<=[a-z]{3})ies\b") # "laboratories" as "laboratory"
101
+ _PLURAL = re.compile(r"(?<=[a-z]{3}[b-hj-np-rtv-z])s\b") # "sciences" as "science"; not "Paris", "Texas", "campus"
102
+ _DASH = re.compile(r"\s-+\s")
103
+ # words in brackets or quotes that interrupt a name: 'University "G. d'Annunzio" of Chieti-Pescara'
104
+ _ASIDE = re.compile(r"\(([^()]*)\)(?=\s*[a-z0-9])|\"([^\"]*)\"(?=\s*[a-z0-9])")
105
+ _TOKEN = re.compile(r"[a-z]+|[0-9]+|[,()\[\]/:|]")
106
+ _WORD = re.compile(r"[a-z]+|[0-9]+")
107
+ _NOTE = re.compile(r"\s*\(([^)]*)\)\s*$")
108
+ # a footnote mark before the first word: "4 Department ...", "a School ...", "7831University"
109
+ _MARK = re.compile(r"\s*(?:(?:\d\d?|[a-z])\s+|\d+(?=[A-Z][a-z]))")
110
+ _CAPITALS = re.compile(r"\b[A-Z]{2,6}\b")
111
+ _ACRONYM = re.compile(r"(?:^|[,;(/])\s*([A-Z][A-Z0-9]*(?:[&-][A-Z0-9]+)*)\b(?P<rest>[^,;()/]*)")
112
+ _CODE = re.compile(r"[A-Za-z]+|\d+")
113
+
114
+
115
+ def _plain(s: str) -> str:
116
+ """Text as names are compared: lower case, no accents, no apostrophes, initials written together, one spelling
117
+ for words such as "centre" and "center" or "Saint" and "St", and plurals as singulars."""
118
+ if s.isascii():
119
+ s = s.lower()
120
+ if "'" in s or "`" in s:
121
+ s = s.replace("'", "").replace("`", "")
122
+ else:
123
+ s = _MARKS.sub("", unicodedata.normalize("NFKD", s.lower().translate(_LETTERS)))
124
+ s = _NOT_ASCII.sub(" ", s)
125
+ if "." in s or "&" in s:
126
+ s = _INITIALS.sub(r"\1", s)
127
+ if "centre" in s or "programme" in s or "organisation" in s or "saint" in s or "mount" in s:
128
+ s = _SPELLING.sub(lambda m: _SPELLED[m.group(1)], s)
129
+ if "s" in s:
130
+ s = _PLURAL.sub("", _PLURAL_Y.sub("y", s))
131
+ return s
132
+
133
+
134
+ def _key(s: str) -> str:
135
+ return " ".join(_WORD.findall(_plain(s)))
136
+
137
+
138
+ def _names(org: dict[str, Any], *kinds: str) -> set[str]:
139
+ return {n["value"] for n in org.get("names", []) if set(kinds) & set(n.get("types", []))}
140
 
141
 
142
  def _row(org: dict[str, Any]) -> list[Any] | None:
 
145
  names = org.get("names", [])
146
  first = names[0]["value"] if names else ""
147
  display = next((n["value"] for n in names if "ror_display" in n.get("types", [])), first)
 
 
148
  loc = ((org.get("locations") or [{}])[0]).get("geonames_details") or {}
149
  kind = min((TYPES.get(t, 5) for t in org.get("types", [])), default=5)
150
  return [
151
  org["id"],
152
  display,
153
+ sorted(_names(org, "ror_display", "label", "alias")),
154
+ sorted(_names(org, "acronym")),
155
  loc.get("name", ""),
156
  loc.get("country_code", ""),
157
  loc.get("country_name", ""),
158
  loc.get("lat"),
159
  loc.get("lng"),
160
  kind,
161
+ loc.get("country_subdivision_name") or "",
162
+ loc.get("country_subdivision_code") or "",
163
+ sorted(_names(org, "alias") - _names(org, "ror_display", "label")),
164
+ sorted(r["id"] for r in org.get("relationships", []) if r.get("type") == "parent"),
165
  ]
166
 
167
 
168
  def build(out: str, source: str = "") -> int:
169
+ """Writes the compact index (gzipped JSON rows) from a ROR dump zip, a file path or, by default, the newest dump.
170
+ A row holds: id, name, all names, acronyms, town, country code, country, latitude, longitude, kind, region, region
171
+ code, the names that are aliases, the rows of the parent organisations."""
172
  if not source:
173
  meta = json.load(urllib.request.urlopen(ZENODO, timeout=60))
174
  files = meta["hits"]["hits"][0]["files"]
 
181
  with zipfile.ZipFile(io.BytesIO(blob)) as z:
182
  name = next(n for n in z.namelist() if n.endswith(".json"))
183
  data = json.loads(z.read(name))
184
+ rows = {org["id"]: r for org in data if (r := _row(org))}
185
+ # an organisation that was renamed or merged into another is found under its old names, as its successor
186
+ heir = {
187
+ org["id"]: [r["id"] for r in org.get("relationships", []) if r.get("type") == "successor"]
188
+ for org in data
189
+ if org["id"] not in rows
190
+ }
191
+ for org in data:
192
+ after = heir.get(org["id"], [])
193
+ for _ in range(5): # the successor may itself have been replaced
194
+ if len(after) != 1 or after[0] in rows:
195
+ break
196
+ after = heir.get(after[0], [])
197
+ if len(after) == 1 and after[0] in rows:
198
+ row, old = rows[after[0]], _names(org, "ror_display", "label", "alias")
199
+ row[12] = sorted(set(row[12]) | (old - set(row[2])))
200
+ row[2] = sorted(set(row[2]) | old)
201
+ number = {rid: i for i, rid in enumerate(rows)}
202
+ for r in rows.values():
203
+ r[13] = sorted(number[p] for p in r[13] if p in number)
204
  with gzip.open(out, "wt", encoding="utf-8") as f:
205
+ json.dump(list(rows.values()), f, ensure_ascii=False, separators=(",", ":"))
206
  return len(rows)
207
 
208
 
209
+ class _Text:
210
+ """One institution of an affiliation, cut into words and into the parts between commas."""
211
+
212
+ __slots__ = ("raw", "words", "part", "tokens", "at", "_caps", "_out")
213
+
214
+ def __init__(self, raw: str) -> None:
215
+ mark = _MARK.match(raw)
216
+ self.raw = raw = raw[mark.end() :] if mark else raw
217
+ self.words: list[str] = [] # every word
218
+ self.part: list[int] = [] # the number of the part each word is in
219
+ self.tokens: list[str] = [] # the words that count in a name
220
+ self.at: list[int] = [] # where each token is in words
221
+ self._caps: set[str] | None = None
222
+ self._out: tuple[int, int, str] | None = None
223
+ s = _plain(raw)
224
+ if "(" in s or '"' in s: # an aside inside a part does not break the name around it
225
+ asides = ["".join(m) for m in _ASIDE.findall(s)]
226
+ if asides:
227
+ s = " , ".join([_ASIDE.sub(" ", s), *asides])
228
+ part = 0
229
+ for w in _TOKEN.findall(_DASH.sub(" , ", s)):
230
+ if w in ",()[]/:|":
231
+ part += 1
232
+ continue
233
+ if w not in STOP:
234
+ self.tokens.append(w)
235
+ self.at.append(len(self.words))
236
+ self.words.append(w)
237
+ self.part.append(part)
238
+
239
+ def outside(self, a: int, b: int) -> str:
240
+ """The text without the words a..b, for finding a town that is named apart from the name itself."""
241
+ if self._out is None or self._out[:2] != (a, b):
242
+ w = self.words
243
+ self._out = (a, b, f" {' '.join(w[:a])} | {' '.join(w[b + 1 :])} ")
244
+ return self._out[2]
245
+
246
+ def capitals(self) -> set[str]:
247
+ """Short words written in capitals, such as the state in "Boston, MA" or the acronym in "AP-HP Hôpital"."""
248
+ if self._caps is None:
249
+ self._caps = set(_CAPITALS.findall(self.raw))
250
+ return self._caps
251
+
252
+
253
+ class _Hit(NamedTuple):
254
+ """A name found in the text and the organisation it stands for."""
255
+
256
+ rank: tuple # the best hit has the highest
257
+ row: int
258
+ i: int # the tokens i..j are the name
259
+ j: int
260
+ key: str
261
+ support: int
262
+ unit: bool
263
+ starts: bool
264
+ crossed: int = -1 # the first token after the comma that the name runs across
265
+
266
+
267
  class LocalRor:
268
  def __init__(self, path: str) -> None:
269
  with gzip.open(path, "rt", encoding="utf-8") as f:
270
  self.rows = json.load(f)
271
+ self.city: list[str] = []
272
+ self.region: list[str] = []
273
+ self.code: list[str] = []
274
+ self.wholes = {p for r in self.rows if len(r) > 13 for p in r[13]} # organisations with parts of their own
275
+ countries = {_key(k) for k in _countries()}
276
+ names: dict[str, list[int]] = {}
277
+ prefixes: set[str] = set()
278
+ count: dict[str, int] = {}
279
+ turned: list[tuple[list[str], int]] = []
280
+ heads: dict[str, set[int]] = {}
281
+ acronyms: dict[str, set[int]] = {}
282
+ places: dict[tuple[str, bool], list[str]] = {}
283
+
284
+ def place(name: str, town: bool = False) -> list[str]:
285
+ """The words of a town, region or country as they are compared."""
286
+ words = places.get((name, town))
287
+ if words is None:
288
+ words = _WORD.findall(_plain(name))
289
+ if town and len(words) > 1 and (words[1] in TOWN_LINKS or (len(words) == 2 and words[1] in TOWN_TAILS)):
290
+ del words[1:]
291
+ places[name, town] = words
292
+ return words
293
+
294
+ def add(tokens: list[str], entry: int) -> None:
295
+ if not tokens or (len(tokens) == 1 and (len(tokens[0]) < 3 or tokens[0].isdigit() or tokens[0] in GENERIC)):
296
+ return # "E-Da Hospital" would be the name "hospital"
297
+ key = tokens[0]
298
+ count[key] = count.get(key, 0) + 1
299
+ for w in tokens[1:]:
300
+ prefixes.add(key)
301
+ key = f"{key} {w}"
302
+ count[w] = count.get(w, 0) + 1
303
+ names.setdefault(key, []).append(entry)
304
+
305
  for i, r in enumerate(self.rows):
306
+ town = place(r[4], True)
307
+ city = " ".join(town)
308
+ town = [w for w in town if w not in STOP]
309
+ self.city.append(city)
310
+ self.region.append(" ".join(place(r[10])) if len(r) > 10 else "")
311
+ self.code.append(r[11] if len(r) > 11 and r[11].isalpha() else "")
312
+ land = place(r[6])[1:] if r[6][:4] == "The " else place(r[6])
313
+ aliases = set(r[12]) if len(r) > 12 else ()
314
+ main = [w for w in _WORD.findall(_plain(_NOTE.sub("", r[1]))) if w not in STOP] if aliases else []
315
  for label in r[2]:
316
+ if not label.isascii() and len(_FOREIGN.findall(label)) > 2:
317
+ continue # a name in another script, of which only stray Latin letters would be compared
318
+ flags = ALIAS if label in aliases else 0
319
+ note = _NOTE.search(label) if label.rstrip().endswith(")") else None
320
+ if note: # "CJ America (United States)": the country is a note, "... (Beijing)" is a campus
321
+ label, where = label[: note.start()], _key(note.group(1))
322
+ if where == city:
323
+ flags |= NEEDS_TOWN
324
+ elif where not in countries:
325
+ add(_WORD.findall(_plain(f"{label} {where}")), i * 16 + flags)
326
+ words = _WORD.findall(_plain(label))
327
+ tokens = [w for w in words if w not in STOP]
328
+ if flags & ALIAS and i not in self.wholes and len(tokens) < len(main) and main[: len(tokens)] == tokens:
329
+ # "Indian Institute of Technology" is an alias of the one in Varanasi ("... BHU") and the start of
330
+ # the names of the others: an alias that leaves out what tells the organisation apart needs its town
331
+ rest = main[len(tokens) :]
332
+ if rest != town and not GENERIC.issuperset(rest):
333
+ flags |= NEEDS_TOWN
334
+ forms = [(tokens, flags)]
335
+ cut = len(tokens)
336
+ while cut > 1 and tokens[cut - 1] in LEGAL:
337
+ cut -= 1
338
+ if cut < len(tokens): # "RAND Corporation" is also written "RAND"
339
+ forms.append((tokens[:cut], flags))
340
+ n = len(town)
341
+ if n and len(tokens) - n >= 2 and tokens[-n:] == town:
342
+ # "Kazimierz Wielki University in Bydgoszcz" is written without the town when the town is named
343
+ forms.append((tokens[:-n], flags | NEEDS_TOWN))
344
+ n = len(land)
345
+ if n and len(words) > n and words[-n:] == land and words[-n - 1] not in STOP:
346
+ # "University of Newcastle Australia" is written without the country when the country is named
347
+ short = tokens[: len(tokens) - sum(w not in STOP for w in land)]
348
+ if len(short) >= 2:
349
+ forms.append((short, flags | NEEDS_COUNTRY))
350
+ for form, f in forms:
351
+ if GENERIC.issuperset(form) and form is not tokens:
352
+ continue
353
+ add(form, i * 16 + f)
354
+ if not 2 <= len(form) <= 4 or form.count("university") != 1 or GENERIC.issuperset(form):
355
+ continue
356
+ if form[0] == "university":
357
+ head, other = form[1:], [*form[1:], "university"]
358
+ elif form[-1] == "university":
359
+ head, other = form[:-1], ["university", *form[:-1]]
360
+ else:
361
+ continue
362
+ turned.append((other, i * 16 + (f | ALIAS | TURNED)))
363
+ if r[9] == 0 and len(form) <= 3 and not f & (NEEDS_TOWN | NEEDS_COUNTRY):
364
+ heads.setdefault(" ".join(head), set()).add(i)
365
+ for a in r[3]:
366
+ if len(a) >= 3 and a.isascii():
367
+ acronyms.setdefault(a.upper(), set()).add(i)
368
+ # "University of Manouba" and "Manouba University" are one organisation unless ROR lists both names
369
+ listed = set(names)
370
+ for tokens, entry in turned:
371
+ if " ".join(tokens) not in listed:
372
+ add(tokens, entry)
373
+ self.names = {k: tuple(sorted(set(v))) for k, v in names.items()}
374
+ self.prefixes = prefixes
375
+ self.heads = {k: tuple(sorted(v)) for k, v in heads.items()}
376
+ self.acronyms = {k: tuple(sorted(v)) for k, v in acronyms.items()}
377
+ self.common = frozenset(w for w, n in count.items() if n >= COMMON)
378
+ sizes = Counter(self.city)
379
+ self.towns = {" ".join(w for w in c.split() if w not in STOP): n for c, n in sizes.items() if c}
380
+ self.regions = frozenset(self.region) | frozenset(_key(s) for s in US_STATE_NAMES)
381
+ self.countries = frozenset(countries)
382
 
383
  def match(self, affiliation: str, country: str) -> Organization | None:
384
+ parts = institutions(affiliation)
385
+ for inst in parts:
386
+ i = self._place(_Text(inst), country if len(parts) == 1 else country_from_text(inst) or country)
387
+ if i is not None:
 
 
 
 
 
 
 
 
 
 
 
 
 
388
  r = self.rows[i]
389
+ return Organization(
390
+ name=r[1],
391
+ ror=r[0],
392
+ city=r[4],
393
+ country=r[5],
394
+ country_name=r[6],
395
+ lat=r[7],
396
+ lon=r[8],
397
+ match="ror-local",
398
+ )
399
+ return None
400
+
401
+ def _place(self, t: _Text, country: str) -> int | None:
402
+ """The row of the organisation that one institution of an affiliation names."""
403
+ tokens, at, part = t.tokens, t.at, t.part
404
+ names, prefixes = self.names, self.prefixes
405
+ n = len(tokens)
406
+ found: list[_Hit] = []
407
+ for i in range(n):
408
+ key = tokens[i]
409
+ j = i
410
+ crossed = -1
411
+ commas = 0
412
+ while True:
413
+ entries = names.get(key)
414
+ if entries is not None:
415
+ hit = self._judge(t, i, j, key, entries, country)
416
+ if hit is not None:
417
+ found.append(hit._replace(crossed=crossed) if crossed >= 0 else hit)
418
+ if key not in prefixes:
419
  break
420
+ j += 1
421
+ if j == n:
422
+ break
423
+ if part[at[j]] != part[at[j - 1]]:
424
+ commas += 1
425
+ if commas > 4:
426
+ break
427
+ if crossed < 0:
428
+ crossed = j
429
+ key = f"{key} {tokens[j]}"
430
+ good = []
431
+ for f in found:
432
+ # a name runs across a comma from the start of a part ("University of California, San Francisco"), and a
433
+ # comma between two organisations separates them ("West China Hospital, Sichuan University")
434
+ if f.crossed >= 0 and (
435
+ not f.starts or any(g.i == f.crossed and g.crossed < 0 and g.row != f.row for g in found)
436
+ ):
437
+ continue
438
+ if f.support < 3 and any(
439
+ g.j == f.i - 1 and g.row != f.row and part[at[f.i]] == part[at[g.j]] for g in found
440
+ ):
441
+ continue # "Chitkara University Institute of Engineering and Technology" is a unit of the university
442
+ if f.unit: # a unit is taken only when no other institution is named after it, or its parent is
443
+ after = [g.row for g in found if g.i > f.j and g.row != f.row]
444
+ if any(p not in self._parents(f.row) for p in after):
445
+ continue
446
+ if not after and not INSTITUTION.isdisjoint(t.words[at[f.j] + 1 :]):
447
+ continue
448
+ good.append(f)
449
+ if good:
450
+ best = max(good, key=lambda f: f.rank)
451
+ # a longer name that holds the chosen name, or names a part of that organisation, says more
452
+ parts = [f for f in good if f.j - f.i > best.j - best.i and self._part_of(f, best)]
453
+ return max(parts, key=lambda f: (f.j - f.i, f.rank)).row if parts else best.row
454
+ row = self._school(t, country)
455
+ return row if row is not None else self._acronym(t, country)
456
+
457
+ def _judge(self, t: _Text, i: int, j: int, key: str, entries: tuple[int, ...], country: str) -> _Hit | None:
458
+ """The organisation that the name at tokens i..j stands for, or None when the name is not to be trusted
459
+ here."""
460
+ words, part, tokens = t.words, t.part, t.tokens
461
+ a, b = t.at[i], t.at[j]
462
+ best: tuple | None = None
463
+ tied: list[int] = []
464
+ for e in entries: # the organisations of this name: the place decides, then the kind of name
465
+ row = e >> 4
466
+ if not self._fits(row, country, t) or (e & NEEDS_COUNTRY and not country):
467
+ continue
468
+ support = self._support(row, t, a, b, country)
469
+ if e & NEEDS_TOWN and support < 3:
470
+ continue
471
+ rank = (
472
+ support,
473
+ self.rows[row][5] == country,
474
+ not e & (NEEDS_TOWN | NEEDS_COUNTRY),
475
+ not e & ALIAS,
476
+ -self.rows[row][9],
477
+ )
478
+ if best is None or rank > best[0]:
479
+ best, tied = (rank, row, e & 15), []
480
+ elif rank == best[0] and row != best[1]:
481
+ tied.append(row)
482
  if best is None:
483
  return None
484
+ support, row, flags = best[0][0], best[1], best[2]
485
+ if tied: # two organisations of one name and nothing to tell them apart, unless one is part of the other
486
+ tied.append(row)
487
+ heads = [r for r in tied if all(o == r or r in self._parents(o) for o in tied)]
488
+ if len(heads) != 1:
489
+ return None
490
+ row = heads[0]
491
+ name = tokens[i : j + 1]
492
+ starts = i == 0 or part[t.at[i - 1]] != part[a]
493
+ end = b + 1 # the first word after the name and the words that only say what kind of body it is
494
+ skip = LEGAL if i < j or flags & ALIAS or key in self.common else LEGAL | GENERIC # "Philips Research"
495
+ while end < len(words) and part[end] == part[b] and words[end] in skip:
496
+ end += 1
497
+ whole = starts and (end == len(words) or part[end] != part[b])
498
+ if whole and (key in self.regions or key in self.countries):
499
+ return None # a part that only names a country or a region is a place, never an organisation
500
+ need_town = unit = tail = False
501
+ if i == j: # a one word name ("Inserm", "Fitbit Inc") must be a whole part and not where a town stands
502
+ code = end
503
+ while code < len(words) and part[code] == part[b] and (words[code].isdigit() or len(words[code]) <= 3):
504
+ code += 1 # the number of a unit: "Inserm U1219"
505
+ if not starts or (code < len(words) and part[code] == part[b]):
506
+ return None
507
+ if flags & ALIAS or key in self.towns or key in self.common or part[a] != part[0]:
508
+ city = self.city[row] # its own town must follow: "Inserm, Paris", but not "..., Orange, Connecticut"
509
+ if not city or f" {city} " not in f" {' '.join(words[end:])} ":
510
+ return None
511
+ elif key in self.towns:
512
+ need_town = True
513
+ if GENERIC.issuperset(name):
514
+ if not whole:
515
+ return None
516
+ unit = True
517
+ need_town = len(name) < 4 or name[0] in UNITS # "National Health Research Institutes" is a name
518
+ elif name[0] in UNITS and len(GENERIC.intersection(name)) > len(name) - 3:
519
+ need_town = unit = True # "Department of Biotechnology"; "School of Oriental and African Studies" is a name
520
+ elif i < j and support < 2 and row not in self.wholes and self._plain_words(name):
521
+ # a name of common words is one of many when it is short ("Heart Institute"), a short alias ("Mental
522
+ # Health Services") or what universities call a department ("Institute of Physics"): its town or region
523
+ # must be named
524
+ short = len(name) <= (3 if flags & ALIAS else 2) and UNIVERSITY.isdisjoint(name)
525
+ if short or name[0] in INSTITUTES:
526
+ return None
527
+ if not starts:
528
+ if flags & (NEEDS_TOWN | NEEDS_COUNTRY | TURNED):
529
+ return None # a name written without its town or country, or with its words turned round, starts a part
530
+ before = words[a - 1]
531
+ bare = INSTITUTION.isdisjoint(name)
532
+ if bare and (flags & ALIAS or before in ("of", "for")):
533
+ return None # "Department of Neurological Surgery" names a subject, not the company of that name
534
+ if bare:
535
+ need_town = True
536
+ elif before not in STOP and before not in GENERIC and not before.isdigit():
537
+ # "Smidt Heart Institute" is not "Heart Institute"; after a unit, as in "Department of Pediatrics LSU
538
+ # Health Sciences Center", the name stands for itself
539
+ first = a
540
+ while first > 0 and part[first - 1] == part[a]:
541
+ first -= 1
542
+ head = words[first]
543
+ if not (head in UNITS or head in GENERIC) or LINKS.isdisjoint(words[first:a]):
544
+ need_town = True
545
+ tail = before.upper() not in t.capitals() # "AP-HP Hôpital Raymond-Poincaré" is a name of its own
546
+ if need_town and support < 3:
547
+ return None
548
+ if end < len(words) and part[end] == part[b]: # the part goes on after the name
549
+ after = words[end]
550
+ more = end + 1 < len(words) and part[end + 1] == part[b]
551
+ if flags & (NEEDS_TOWN | NEEDS_COUNTRY) and after not in AFTER_SHORT:
552
+ return None # "University of Texas" for the one in San Antonio, not in "University of Texas Health ..."
553
+ if more and words[end + 1] != "the":
554
+ if name[-1] in UNIVERSITY and after in ("of", "for"):
555
+ return None # "Yunnan University of Chinese Medicine" is not "Yunnan University"
556
+ own = f"{self.city[row] or '-'} "
557
+ if name[-1] == "hospital" and after == "of" and not f"{' '.join(words[end + 1 :])} ".startswith(own):
558
+ return None # nor is "Zhongshan Hospital of Traditional Chinese Medicine" Zhongshan Hospital
559
+ if after in LINKS and self._other_town(row, tokens[j + 1 : j + 4]):
560
+ return None # "Institut Pasteur de Lille" is not the Institut Pasteur of Paris
561
+ if more and after == "at" and not UNIVERSITY.isdisjoint(name):
562
+ return None # "State University of New York at Albany" is not the whole State University
563
+ # an organisation is placed when its town or region is named, also inside its own name
564
+ placed = support >= 2 or f" {self.city[row] or '-'} " in f" {' '.join(words[a : b + 1])} "
565
+ # the first organisation named is the home of the author, unless its name is weak: a unit, the end of a
566
+ # longer name or a short name of common words
567
+ strong = not unit and not tail and (j - i >= 3 or not self._plain_words(name))
568
+ rank = (placed, strong, -i, j - i + 1, support, -self.rows[row][9])
569
+ return _Hit(rank, row, i, j, key, support, unit, starts)
570
+
571
+ def _support(self, row: int, t: _Text, a: int, b: int, country: str) -> int:
572
+ """How well the place of an organisation fits the text around its name (words a..b): 3 its town is named,
573
+ 2 its region, 1 only the country is known to agree, 0 nothing is known."""
574
+ outside = t.outside(a, b)
575
+ if self.city[row] and f" {self.city[row]} " in outside:
576
+ return 3
577
+ if self.region[row] and f" {self.region[row]} " in outside:
578
+ return 2
579
+ if self.code[row] and self.code[row] in t.capitals():
580
+ return 2
581
+ return 1 if country else 0
582
+
583
+ def _fits(self, row: int, country: str, t: _Text) -> bool:
584
+ there = self.rows[row][5]
585
+ if not country or not there or there == country:
586
+ return True
587
+ # "The University of Hong Kong, China": a place with its own code, when the text names the place as well
588
+ return PART_OF.get(there) == country and f" {_key(self.rows[row][6])} " in f" {' '.join(t.words)} "
589
+
590
+ def _parents(self, row: int) -> list[int]:
591
+ r = self.rows[row]
592
+ return r[13] if len(r) > 13 else []
593
+
594
+ def _part_of(self, f: _Hit, whole: _Hit) -> bool:
595
+ if f" {whole.key} " in f" {f.key} ":
596
+ return True
597
+ parents = self._parents(f.row)
598
+ return whole.row in parents or any(whole.row in self._parents(p) for p in parents)
599
+
600
+ def _plain_words(self, name: list[str]) -> bool:
601
+ """Whether a name is made of common words only and holds no place name: "Neuroscience Institute"."""
602
+ if not self.common.issuperset(name):
603
+ return False
604
+ n = len(name)
605
+ return not any(
606
+ (p := " ".join(name[x:y])) in self.towns or p in self.regions or p in self.countries
607
+ for x in range(n)
608
+ for y in range(x + 1, n + 1)
609
  )
610
 
611
+ def _other_town(self, row: int, after: list[str]) -> bool:
612
+ """Whether the words after a name begin with a town of some size that is not the town of the organisation."""
613
+ own = [w for w in self.city[row].split() if w not in STOP]
614
+ if after[: len(own)] == own[: len(after)]:
615
+ return False
616
+ for n in (3, 2, 1):
617
+ p = " ".join(after[:n])
618
+ if self.towns.get(p, 0) >= TOWN_SIZE and (n > 1 or p not in self.common):
619
+ return True
620
+ return False
621
+
622
+ def _elsewhere(self, t: _Text) -> bool:
623
+ """Whether a part of the text is the name of a town or a region."""
624
+ parts: dict[int, list[str]] = {}
625
+ for w, k in zip(t.tokens, t.at, strict=True):
626
+ parts.setdefault(t.part[k], []).append(w)
627
+ keys = [" ".join(ws) for ws in parts.values()]
628
+ return any(p not in self.countries and (p in self.towns or p in self.regions) for p in keys)
629
+
630
+ def _school(self, t: _Text, country: str) -> int | None:
631
+ """The university of a school that ROR does not list ("Harvard Law School", "Yale School of Nursing"), when
632
+ the name before the school gives exactly one university and is not the name of a place."""
633
+ tokens, at, part = t.tokens, t.at, t.part
634
+ for i in range(len(tokens)):
635
+ if i and part[at[i - 1]] == part[at[i]]:
636
+ continue # only the first word of a part
637
+ j = i + 1
638
+ while j < len(tokens) and part[at[j]] == part[at[i]] and tokens[j] not in SCHOOLS:
639
+ j += 1
640
+ if j == len(tokens) or part[at[j]] != part[at[i]] or tokens[j - 1] in LOWER_SCHOOLS:
641
+ continue
642
+ for n in (3, 2, 1):
643
+ head = " ".join(tokens[i : i + n])
644
+ if i + n <= j and head in self.heads:
645
+ rows = [r for r in self.heads[head] if self._fits(r, country, t)]
646
+ if len(rows) != 1 or self.towns.get(head, 0) >= CITY_SIZE or head in self.regions:
647
+ break
648
+ # "Sri Venkateswara Dental College, Chennai" is not the Sri Venkateswara University of Tirupati
649
+ if self._support(rows[0], t, 0, -1, country) >= 2 or not self._elsewhere(t):
650
+ return rows[0]
651
+ break
652
+ return None
653
+
654
+ def _acronym(self, t: _Text, country: str) -> int | None:
655
+ """An acronym written in capitals at the start of a part, when one organisation of the country has it: as
656
+ a whole part of four letters or more ("CNRS", "INSERM U1219"), or with the town or region of the organisation
657
+ in the text and no other institution after it ("NYU School of Medicine, New York")."""
658
+ if not country or t.raw.isupper():
659
+ return None
660
+ for m in _ACRONYM.finditer(t.raw):
661
+ word = m.group(1)
662
+ if word in US_STATES or word in _country_codes() or word.lower() in self.countries:
663
+ continue # "USA" is not the United States Army
664
+ rows = [r for r in self.acronyms.get(word, ()) if self._fits(r, country, t)]
665
+ if not rows:
666
+ continue
667
+ alone = len(rows) == 1 and len(word) >= 4 and t.raw[max(m.start(1) - 1, 0)] != "(" # not in brackets
668
+ if alone and all(w.isdigit() or len(w) <= 3 for w in _CODE.findall(m.group("rest"))):
669
+ return rows[0]
670
+ support = [self._support(r, t, 0, -1, country) for r in rows]
671
+ top = max(support)
672
+ later = _WORD.findall(_plain(t.raw[m.end() :]))
673
+ if top >= 2 and support.count(top) == 1 and INSTITUTION.isdisjoint(later):
674
+ return rows[support.index(top)]
675
+ return None
676
+
677
 
678
  @lru_cache(maxsize=1)
679
  def load() -> LocalRor | None:
src/labscout/sources/ukri.py CHANGED
@@ -55,7 +55,7 @@ def search(http: Http, text: str, limit: int = 25) -> list[Grant]:
55
  (i.get("value", "") for i in (p.get("identifiers") or {}).get("identifier", []) if i.get("type") == "RCUK"),
56
  "",
57
  )
58
- pi = _person(http, _href(p, "PI_PER"))
59
  org = _organisation(http, _href(p, "LEAD_ORG"))
60
  dept = p.get("leadOrganisationDepartment") or ""
61
  grants.append(
 
55
  (i.get("value", "") for i in (p.get("identifiers") or {}).get("identifier", []) if i.get("type") == "RCUK"),
56
  "",
57
  )
58
+ pi = _person(http, _href(p, "PI_PER") or _href(p, "FELLOW_PER")) # a fellowship names its fellow instead
59
  org = _organisation(http, _href(p, "LEAD_ORG"))
60
  dept = p.get("leadOrganisationDepartment") or ""
61
  grants.append(
src/labscout/text.py CHANGED
@@ -2,6 +2,7 @@
2
 
3
  from __future__ import annotations
4
 
 
5
  import re
6
  import unicodedata
7
  from functools import lru_cache
@@ -43,29 +44,56 @@ STOP = {
43
  }
44
  QUERY_WORDS = {"and", "or", "not"}
45
 
46
- # MeSH descriptors and words that say which species a study works with
 
 
47
  SPECIES = [
48
- ("human", ("humans",), r"\b(participants?|volunteers?|adults?|children|adolescents?|older adults|men|women)\b"),
49
- ("mouse", ("mice", "mice, inbred c57bl", "mice, knockout", "mice, transgenic"), r"\b(mice|mouse|murine)\b"),
50
- ("rat", ("rats", "rats, sprague-dawley", "rats, wistar"), r"\b(rats?)\b"),
51
- ("fruit fly", ("drosophila", "drosophila melanogaster"), r"\bdrosophila\b"),
52
- ("zebrafish", ("zebrafish",), r"\bzebrafish\b"),
53
- ("non-human primate", ("macaca", "macaca mulatta", "primates"), r"\b(macaques?|monkeys?|primates?)\b"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  ]
55
 
56
- # what kind of data a study holds, from its title, abstract, keywords and MeSH
57
  SIGNALS = [
58
- ("actigraphy", r"\bactigraph\w*"),
59
- ("accelerometry", r"\baccelerometr\w*|\baccelerometer\w*"),
60
- ("wearables", r"\bwearables?\b|\bsmart ?watch\w*|\bfitbit\b|\boura\b|\bapple watch\b|\bgarmin\b|\bwhoop\b"),
61
- ("step counts", r"\bstep counts?\b|\bdaily steps\b|\bpedometer\w*"),
62
- ("longitudinal", r"\blongitudinal\b|\bfollow-up\b|\brepeated measures?\b|\bprospective\b"),
63
- ("cohort", r"\bcohorts?\b|\bbiobank\b"),
64
- ("polysomnography", r"\bpolysomnograph\w*"),
65
- ("light exposure", r"\blight exposure\b|\blight sensor\w*"),
66
- ("shift work", r"\bshift ?work\w*|\bnight shifts?\b"),
67
- ("diaries", r"\bsleep diar(y|ies)\b|\becological momentary\b"),
 
 
 
 
 
 
 
 
68
  ]
 
 
69
 
70
  COUNTRY_ALIASES = {
71
  "usa": "US",
@@ -102,6 +130,25 @@ COUNTRY_ALIASES = {
102
  "p.r. china": "CN",
103
  "pr china": "CN",
104
  "people's republic of china": "CN",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  }
106
  US_STATES = {
107
  "AL",
@@ -156,14 +203,60 @@ US_STATES = {
156
  "WY",
157
  "DC",
158
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
 
161
  def fold(s: str) -> str:
162
- """Lower case without accents, for comparisons."""
163
- s = unicodedata.normalize("NFKD", s or "")
 
 
 
164
  return "".join(c for c in s if not unicodedata.combining(c)).lower()
165
 
166
 
 
 
 
 
 
 
 
167
  def words(s: str) -> list[str]:
168
  return re.findall(r"[a-z0-9]+", fold(s))
169
 
@@ -197,21 +290,32 @@ def query_terms(query: str) -> list[str]:
197
  return out
198
 
199
 
200
- def species_of(mesh: list[str], text: str) -> list[str]:
 
201
  m = {fold(x) for x in mesh}
202
- t = fold(text)
203
  found = []
204
- for label, terms, pattern in SPECIES:
205
- if any(term in m for term in terms) or (label != "human" and re.search(pattern, t)):
206
  found.append(label)
207
- if "human" not in found and not found and re.search(SPECIES[0][2], t):
208
  found.append("human")
209
  return found
210
 
211
 
212
- def signals_of(text: str) -> list[str]:
213
- t = fold(text)
214
- return [label for label, pattern in SIGNALS if re.search(pattern, t)]
 
 
 
 
 
 
 
 
 
 
215
 
216
 
217
  @lru_cache(maxsize=1)
@@ -223,22 +327,73 @@ def _countries() -> dict[str, str]:
223
  for attr in ("name", "official_name", "common_name"):
224
  v = getattr(c, attr, None)
225
  if v:
226
- names[fold(v)] = c.alpha_2
227
- names.update({fold(k): v for k, v in COUNTRY_ALIASES.items()})
 
 
228
  return names
229
 
230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  def country_from_text(affiliation: str) -> str:
232
- """ISO code of the country named at the end of an affiliation, or '' when it is not clear."""
233
- parts = [p.strip(" .") for p in re.split(r"[,;]", affiliation or "") if p.strip(" .")]
234
  table = _countries()
235
- for part in reversed(parts[-3:]):
236
- code = table.get(fold(part))
237
- if code:
238
- return code
239
- tokens = part.split()
240
- if tokens and tokens[0] in US_STATES and (len(tokens) == 1 or tokens[1].isdigit()):
241
- return "US"
 
 
 
242
  return ""
243
 
244
 
 
2
 
3
  from __future__ import annotations
4
 
5
+ import html
6
  import re
7
  import unicodedata
8
  from functools import lru_cache
 
44
  }
45
  QUERY_WORDS = {"and", "or", "not"}
46
 
47
+ # MeSH descriptors and words that say which species a study works with. The last entry of each row lists text
48
+ # fragments of which one must be present for the pattern to match: a plain search for them is far cheaper than the
49
+ # pattern, and most papers mention none.
50
  SPECIES = [
51
+ (
52
+ "human",
53
+ ("humans",),
54
+ r"\b(participants?|volunteers?|adults?|children|adolescents?|older adults|men|women)\b",
55
+ ("participant", "volunteer", "adult", "children", "adolescent", "men"),
56
+ ),
57
+ (
58
+ "mouse",
59
+ ("mice", "mice, inbred c57bl", "mice, knockout", "mice, transgenic"),
60
+ r"\b(mice|mouse|murine)\b",
61
+ ("mice", "mouse", "murine"),
62
+ ),
63
+ ("rat", ("rats", "rats, sprague-dawley", "rats, wistar"), r"\b(rats?)\b", ("rat",)),
64
+ ("fruit fly", ("drosophila", "drosophila melanogaster"), r"\bdrosophila\b", ("drosophila",)),
65
+ ("zebrafish", ("zebrafish",), r"\bzebrafish\b", ("zebrafish",)),
66
+ (
67
+ "non-human primate",
68
+ ("macaca", "macaca mulatta", "primates"),
69
+ r"\b(macaques?|monkeys?|primates?)\b",
70
+ ("macaque", "monkey", "primate"),
71
+ ),
72
  ]
73
 
74
+ # what kind of data a study holds, from its title, abstract, keywords and MeSH (label, pattern, fragments as above)
75
  SIGNALS = [
76
+ ("actigraphy", r"\bactigraph\w*", ("actigraph",)),
77
+ ("accelerometry", r"\baccelerometr\w*|\baccelerometer\w*", ("acceleromet",)),
78
+ (
79
+ "wearables",
80
+ r"\bwearables?\b|\bsmart ?watch\w*|\bfitbit\b|\boura\b|\bapple watch\b|\bgarmin\b|\bwhoop\b",
81
+ ("wearable", "smartwatch", "smart watch", "fitbit", "oura", "apple watch", "garmin", "whoop"),
82
+ ),
83
+ ("step counts", r"\bstep counts?\b|\bdaily steps\b|\bpedometer\w*", ("step count", "daily steps", "pedometer")),
84
+ (
85
+ "longitudinal",
86
+ r"\blongitudinal\b|\bfollow-up\b|\brepeated measures?\b|\bprospective\b",
87
+ ("longitudinal", "follow-up", "repeated measure", "prospective"),
88
+ ),
89
+ ("cohort", r"\bcohorts?\b|\bbiobank\b", ("cohort", "biobank")),
90
+ ("polysomnography", r"\bpolysomnograph\w*", ("polysomnograph",)),
91
+ ("light exposure", r"\blight exposure\b|\blight sensor\w*", ("light exposure", "light sensor")),
92
+ ("shift work", r"\bshift ?work\w*|\bnight shifts?\b", ("shift work", "shiftwork", "night shift")),
93
+ ("diaries", r"\bsleep diar(y|ies)\b|\becological momentary\b", ("sleep diar", "ecological momentary")),
94
  ]
95
+ _SPECIES = [(label, terms, re.compile(pattern), hints) for label, terms, pattern, hints in SPECIES]
96
+ _SIGNALS = [(label, re.compile(pattern), hints) for label, pattern, hints in SIGNALS]
97
 
98
  COUNTRY_ALIASES = {
99
  "usa": "US",
 
130
  "p.r. china": "CN",
131
  "pr china": "CN",
132
  "people's republic of china": "CN",
133
+ "prc": "CN",
134
+ "mainland china": "CN",
135
+ "hong kong sar": "HK",
136
+ "hong kong special administrative region": "HK",
137
+ "macau": "MO",
138
+ "macau sar": "MO",
139
+ "macao sar": "MO",
140
+ "republic of china": "TW",
141
+ "roc": "TW",
142
+ "great britain": "GB",
143
+ "republic of ireland": "IE",
144
+ "uae": "AE",
145
+ "ksa": "SA",
146
+ "kingdom of saudi arabia": "SA",
147
+ "brunei": "BN",
148
+ "palestine": "PS",
149
+ "ivory coast": "CI",
150
+ "dr congo": "CD",
151
+ "drc": "CD",
152
  }
153
  US_STATES = {
154
  "AL",
 
203
  "WY",
204
  "DC",
205
  }
206
+ _STATE_NAMES = (
207
+ "alabama|alaska|arizona|arkansas|california|colorado|connecticut|delaware|florida|georgia|hawaii|idaho|"
208
+ "illinois|indiana|iowa|kansas|kentucky|louisiana|maine|maryland|massachusetts|michigan|minnesota|mississippi|"
209
+ "missouri|montana|nebraska|nevada|new hampshire|new jersey|new mexico|new york|north carolina|north dakota|"
210
+ "ohio|oklahoma|oregon|pennsylvania|rhode island|south carolina|south dakota|tennessee|texas|utah|vermont|"
211
+ "virginia|washington|west virginia|wisconsin|wyoming|district of columbia|washington dc"
212
+ )
213
+ US_STATE_NAMES = frozenset(_STATE_NAMES.split("|"))
214
+ # places with a code of their own that are often written with the name of a larger country after them
215
+ # ("Hong Kong SAR, China", "San Juan, Puerto Rico, USA")
216
+ PART_OF = {
217
+ "HK": "CN",
218
+ "MO": "CN",
219
+ "TW": "CN",
220
+ "PR": "US",
221
+ "GU": "US",
222
+ "VI": "US",
223
+ "GF": "FR",
224
+ "GP": "FR",
225
+ "MQ": "FR",
226
+ "RE": "FR",
227
+ "NC": "FR",
228
+ "PF": "FR",
229
+ "GL": "DK",
230
+ "FO": "DK",
231
+ }
232
+ # a country named after one of these words is part of a longer name ("University of Jordan", "New Mexico")
233
+ _NOT_A_COUNTRY_AFTER = STOP | {"new", "mount", "du", "st", "saint"}
234
+
235
+
236
+ # letters that are no accent on another letter, with the way they are written when the letter is not at hand
237
+ _PLAIN_LETTERS = str.maketrans(
238
+ {"ø": "o", "ł": "l", "ß": "ss", "æ": "ae", "œ": "oe", "đ": "d", "ð": "d", "ı": "i", "þ": "th"}
239
+ | {"Ø": "o", "Ł": "l", "Æ": "ae", "Œ": "oe", "Đ": "d", "Ð": "d", "Þ": "th", "ẞ": "ss"}
240
+ )
241
+ _ORCID = re.compile(r"\d{15}[\dX]")
242
 
243
 
244
  def fold(s: str) -> str:
245
+ """Lower case without accents, for comparisons: "Søren Møller" and "Soren Moller" are one name."""
246
+ s = s or ""
247
+ if s.isascii(): # most titles, abstracts and affiliations: nothing to take apart
248
+ return s.lower()
249
+ s = unicodedata.normalize("NFKD", s.translate(_PLAIN_LETTERS))
250
  return "".join(c for c in s if not unicodedata.combining(c)).lower()
251
 
252
 
253
+ def orcid_id(text: str) -> str:
254
+ """The ORCID iD in what a source gives ("https://orcid.org/0000-0002-1825-0097", or the 16 characters without
255
+ hyphens), or "" when it is no whole iD: a cut-off one would lead nowhere and look like another person."""
256
+ raw = re.sub(r"[^0-9X]", "", (text or "").strip().rsplit("/", 1)[-1].upper())
257
+ return "-".join(raw[i : i + 4] for i in range(0, 16, 4)) if _ORCID.fullmatch(raw) else ""
258
+
259
+
260
  def words(s: str) -> list[str]:
261
  return re.findall(r"[a-z0-9]+", fold(s))
262
 
 
290
  return out
291
 
292
 
293
+ def species_of(mesh: list[str], text: str, folded: str | None = None) -> list[str]:
294
+ """Species from the MeSH terms and the text; `folded` is the text already through fold(), when the caller has it."""
295
  m = {fold(x) for x in mesh}
296
+ t = fold(text) if folded is None else folded
297
  found = []
298
+ for label, terms, pattern, hints in _SPECIES:
299
+ if any(term in m for term in terms) or (label != "human" and any(h in t for h in hints) and pattern.search(t)):
300
  found.append(label)
301
+ if not found and any(h in t for h in _SPECIES[0][3]) and _SPECIES[0][2].search(t):
302
  found.append("human")
303
  return found
304
 
305
 
306
+ def signals_of(text: str, folded: str | None = None) -> list[str]:
307
+ """Kinds of data the text mentions; `folded` is the text already through fold(), when the caller has it."""
308
+ t = fold(text) if folded is None else folded
309
+ return [label for label, pattern, hints in _SIGNALS if any(h in t for h in hints) and pattern.search(t)]
310
+
311
+
312
+ def _place_key(s: str) -> str:
313
+ """A place as it is compared: lower case, without accents, brackets, digits, dots and a leading "the", so that
314
+ "P. R. China", "the United Kingdom", "China (mainland)" and "Japan 113-8655" are found as they are meant."""
315
+ s = re.sub(r"\([^)]*\)|\S*\d\S*", " ", fold(s)).replace("'", "").replace("\u2019", "")
316
+ s = re.sub(r"\.\s*(?=[a-z]\b)", "", s) # "p. r. china" -> "pr china", "u.s.a." -> "usa."
317
+ s = " ".join(re.sub(r"[^a-z ]+", " ", s).split())
318
+ return s[4:] if s.startswith("the ") else s
319
 
320
 
321
  @lru_cache(maxsize=1)
 
327
  for attr in ("name", "official_name", "common_name"):
328
  v = getattr(c, attr, None)
329
  if v:
330
+ names[_place_key(v)] = c.alpha_2
331
+ if ", " in v: # "Korea, Republic of" is written "Republic of Korea"
332
+ names.setdefault(_place_key(" ".join(reversed(v.split(", ", 1)))), c.alpha_2)
333
+ names.update({_place_key(k): v for k, v in COUNTRY_ALIASES.items()})
334
  return names
335
 
336
 
337
+ @lru_cache(maxsize=1)
338
+ def _country_codes() -> dict[str, str]:
339
+ """Three and two letter ISO codes written as a country ("Muscat, OMN", "Prague, CZ"). A two letter code that is
340
+ also a US state stays a state."""
341
+ import pycountry
342
+
343
+ codes = {c.alpha_3: c.alpha_2 for c in pycountry.countries}
344
+ codes.update({c.alpha_2: c.alpha_2 for c in pycountry.countries if c.alpha_2 not in US_STATES})
345
+ return codes
346
+
347
+
348
+ def institutions(affiliation: str) -> list[str]:
349
+ """The institutions of an affiliation in the order they are written. One string sometimes holds several, with
350
+ semicolons between them; the first is the home of the author."""
351
+ s = affiliation or ""
352
+ if "&" in s:
353
+ s = html.unescape(s) # "Biosciences &amp; Bioengineering" has no semicolon of its own
354
+ return [p for p in (q.strip() for q in s.split(";")) if p]
355
+
356
+
357
+ def _part_country(part: str, table: dict[str, str]) -> str:
358
+ key = _place_key(part)
359
+ if not key:
360
+ return ""
361
+ code = table.get(key, "")
362
+ state = key in US_STATE_NAMES
363
+ if code and not state:
364
+ return code
365
+ tokens = part.split()
366
+ if state: # "Georgia" alone is the state or the country; "Georgia 30322" is the state
367
+ return "" if code and not any(t[:1].isdigit() for t in tokens) else "US"
368
+ if len(tokens) > 1 and tokens[-1][:1].isdigit():
369
+ tokens.pop() # a postcode: "MA 02115", "Stanford CA 94305"
370
+ if tokens[-1] in US_STATES and (len(tokens) == 1 or tokens[-2][:1].isalpha()):
371
+ return "US"
372
+ if len(tokens) == 1 and tokens[0].isupper() and tokens[0].strip(".") in _country_codes():
373
+ return _country_codes()[tokens[0].strip(".")]
374
+ words = key.split() # the country as the last words of a part without commas: "Guildford UK", "Seoul 03016 Korea"
375
+ for n in (4, 3, 2, 1):
376
+ if len(words) > n and words[-n - 1] not in _NOT_A_COUNTRY_AFTER:
377
+ tail = " ".join(words[-n:])
378
+ if tail in table and tail not in US_STATE_NAMES:
379
+ return table[tail]
380
+ return ""
381
+
382
+
383
  def country_from_text(affiliation: str) -> str:
384
+ """ISO code of the country named at the end of an affiliation, or '' when it is not clear. When the text holds
385
+ several institutions the country of the first one that names a country is given."""
386
  table = _countries()
387
+ for inst in institutions(affiliation):
388
+ parts = [p for p in (q.strip(" .") for q in re.split(r",| - ", inst)) if p]
389
+ for k in range(len(parts) - 1, max(len(parts) - 4, -1), -1):
390
+ code = _part_country(parts[k], table)
391
+ if code:
392
+ for before in reversed(parts[max(k - 3, 0) : k]): # "Kowloon, Hong Kong, 999077, China" is Hong Kong
393
+ inner = table.get(_place_key(before), "")
394
+ if PART_OF.get(inner) == code:
395
+ return inner
396
+ return code
397
  return ""
398
 
399
 
src/labscout/web.py CHANGED
@@ -2,6 +2,8 @@
2
 
3
  / a search form, with how it works and search tips
4
  /search the report for a search: map, charts, table, downloads; while it runs, a page with the steps
 
 
5
  /download the last results as Excel, CSV or JSON
6
  /privacy what the page and the tools do with personal data
7
  /mcp the MCP server (Streamable HTTP) for AI assistants
@@ -10,8 +12,8 @@
10
 
11
  from __future__ import annotations
12
 
13
- import hashlib
14
  import html
 
15
  import json
16
  import logging
17
  import os
@@ -20,7 +22,7 @@ import time
20
  from collections import OrderedDict, defaultdict, deque
21
  from datetime import date
22
  from typing import Any
23
- from urllib.parse import urlencode
24
 
25
  import anyio
26
  from mcp.server.transport_security import TransportSecuritySettings
@@ -32,16 +34,25 @@ from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse, R
32
  from starlette.routing import Mount, Route
33
 
34
  from . import __version__, art
35
- from .config import REPO
36
  from .errors import SearchError
37
- from .export import csv_text, render_html, xlsx_bytes
38
- from .pipeline import ORDERS, SEARCH_SLOTS, Result, find_labs
 
39
  from .server import mcp
40
  from .sources import PUBLICATION_SOURCES
41
 
42
  MAX_PAPERS = int(os.environ.get("LABSCOUT_WEB_MAX_PAPERS", "10000")) # per source, for one search on the page
43
  PER_HOUR = int(os.environ.get("LABSCOUT_SEARCHES_PER_HOUR", "20")) # per visitor
44
- KEEP = 50 # recent results kept in memory for the download links
 
 
 
 
 
 
 
 
45
  log = logging.getLogger(__name__)
46
  FRAMES = "frame-ancestors 'self' https://huggingface.co https://*.hf.space" # the Space page shows the app in a frame
47
  SECURITY = {
@@ -49,7 +60,7 @@ SECURITY = {
49
  "Referrer-Policy": "strict-origin-when-cross-origin",
50
  "Strict-Transport-Security": "max-age=31536000",
51
  "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; "
52
- "img-src 'self' data:; form-action 'self'; base-uri 'none'; " + FRAMES,
53
  }
54
  # the report also loads the map library and the map tiles
55
  REPORT_SECURITY = SECURITY | {
@@ -72,26 +83,63 @@ STEPS = {
72
  "labs": "Rank the labs and draw the map",
73
  }
74
 
75
- _results: OrderedDict[str, Result] = OrderedDict()
76
  _jobs: dict[str, dict[str, Any]] = {} # searches still running, or failed
77
  _lock = threading.Lock()
78
  _visits: dict[str, deque[float]] = defaultdict(deque)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
 
81
  def _visitor(request: Request) -> str:
82
- forwarded = request.headers.get("x-forwarded-for", "")
83
- return forwarded.split(",")[0].strip() or (request.client.host if request.client else "unknown")
84
-
85
-
86
- def _allowed(who: str) -> bool:
 
 
 
 
 
 
 
 
 
 
 
87
  now = time.time()
88
- if len(_visits) > 5000: # forget the visitors who have not searched for an hour
89
- for k in [k for k, v in _visits.items() if not v or now - v[-1] > 3600]:
90
- del _visits[k]
91
- seen = _visits[who]
92
  while seen and now - seen[0] > 3600:
93
  seen.popleft()
94
- if len(seen) >= PER_HOUR:
95
  return False
96
  seen.append(now)
97
  return True
@@ -99,12 +147,20 @@ def _allowed(who: str) -> bool:
99
 
100
  def _year(value: str | None) -> int | None:
101
  value = (value or "").strip()
102
- return int(value) if value.isdigit() and 1800 <= int(value) <= 2100 else None
 
 
103
 
104
 
105
  def _page(body: str, title: str = "Actogram LabScout", status: int = 200) -> HTMLResponse:
106
- page = PAGE.replace("{{TITLE}}", html.escape(title)).replace("{{BODY}}", body).replace("{{VERSION}}", __version__)
107
- return HTMLResponse(page, status_code=status, headers=SECURITY)
 
 
 
 
 
 
108
 
109
 
110
  async def home(request: Request) -> HTMLResponse:
@@ -113,8 +169,7 @@ async def home(request: Request) -> HTMLResponse:
113
  examples = " ".join(
114
  f'<a href="search?{html.escape(urlencode({"topic": t, "from": since}))}">{html.escape(t)}</a>' for t in EXAMPLES
115
  )
116
- body = FORM
117
- for k, v in {
118
  "{{MCP}}": html.escape(f"{base}/mcp"),
119
  "{{REPO}}": REPO,
120
  "{{MAX}}": f"{MAX_PAPERS:,}",
@@ -125,9 +180,8 @@ async def home(request: Request) -> HTMLResponse:
125
  "{{STEP_PAPERS}}": art.STEP_PAPERS,
126
  "{{STEP_LAB}}": art.STEP_LAB,
127
  "{{STEP_MAP}}": art.STEP_MAP,
128
- }.items():
129
- body = body.replace(k, v)
130
- return _page(body)
131
 
132
 
133
  async def privacy(request: Request) -> HTMLResponse:
@@ -135,7 +189,7 @@ async def privacy(request: Request) -> HTMLResponse:
135
 
136
 
137
  def _work(key: str, topic: str, start: int | None, end: int | None, sources: list[str], order: str) -> None:
138
- """One search, in its own thread; the page polls until it is done and shows the steps meanwhile."""
139
 
140
  def progress(step: str, text: str) -> None:
141
  with _lock:
@@ -144,30 +198,35 @@ def _work(key: str, topic: str, start: int | None, end: int | None, sources: lis
144
  return
145
  if step != "note":
146
  job["steps"][step] = text
 
147
  last = job["log"][-1][1] if job["log"] else ""
148
- moving = (step == "organisations" and last.startswith("Matching")) or (
149
  text.endswith("records read")
150
  and last.endswith("records read")
151
  and last.split(":")[0] == text.split(":")[0]
152
  )
153
- if moving: # one moving line instead of hundreds
154
- job["log"][-1] = (job["log"][-1][0], text)
155
  else:
156
- job["log"].append((round(time.time() - job["started"], 1), text))
157
  del job["log"][:-60]
158
 
159
  try:
160
- if not SEARCH_SLOTS.acquire(blocking=False):
 
 
161
  progress("queue", "Waiting for a free place: other searches are running")
162
- SEARCH_SLOTS.acquire()
163
  try:
164
  result = find_labs(topic, start, end, MAX_PAPERS, sources, order=order, progress=progress)
165
  finally:
166
- SEARCH_SLOTS.release()
 
 
 
 
 
167
  with _lock:
168
- _results[key] = result
169
- while len(_results) > KEEP:
170
- _results.popitem(last=False)
171
  _jobs.pop(key, None)
172
  except SearchError as err:
173
  with _lock:
@@ -181,6 +240,38 @@ def _work(key: str, topic: str, start: int | None, end: int | None, sources: lis
181
  }
182
 
183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  def _steps(job: dict[str, Any]) -> str:
185
  """The steps of a running search: done, now, still to come."""
186
  told = dict(job.get("steps", {}))
@@ -195,38 +286,72 @@ def _steps(job: dict[str, Any]) -> str:
195
  items.append(f'<li class="{state}">{html.escape(told[s])}</li>')
196
  else:
197
  items.append(f'<li class="todo">{html.escape(STEPS.get(s, s))}</li>')
198
- return '<ol class="steps">' + "".join(items) + "</ol>"
199
 
200
 
201
- async def search(request: Request) -> Response:
 
 
 
 
 
 
 
 
202
  q = request.query_params
203
- topic = (q.get("topic") or "").strip()[:300]
204
- if not topic:
205
- return _page(FORM_ERROR.format(msg="Type a topic to search for."), status=400)
206
  start, end = _year(q.get("from")), _year(q.get("to"))
207
  if start and end and start > end:
208
  start, end = end, start
209
- sources = [s for s in q.getlist("source") if s in PUBLICATION_SOURCES] or list(PUBLICATION_SOURCES)
210
  order = q.get("order") if q.get("order") in ORDERS else "relevance"
211
- key = hashlib.sha256(json.dumps([topic, start, end, sources, order]).encode()).hexdigest()[:16]
 
 
 
 
 
 
212
  with _lock:
213
- result = _results.get(key)
214
  job = _jobs.get(key)
215
- if result is not None:
216
- _results.move_to_end(key)
217
  if result is not None:
218
- toolbar = (
219
- f'<p class="tools"><a href="./">New search</a><a href="download/{key}.xlsx">Excel</a>'
220
- f'<a href="download/{key}.csv">CSV</a><a href="download/{key}.json">JSON</a></p>'
221
- )
 
 
 
 
 
 
222
  footer = '<p><a href="./">New search</a>. <a href="privacy">Privacy</a>.</p>'
223
- page = render_html(result, top=200, toolbar=toolbar, footer=footer)
 
 
 
 
 
 
 
224
  return HTMLResponse(page, headers=REPORT_SECURITY)
225
  if job and "error" in job:
226
  with _lock:
227
  _jobs.pop(key, None)
228
- return _page(FORM_ERROR.format(msg=html.escape(job["error"])), status=400)
 
 
229
  if job is None:
 
 
 
 
 
 
 
 
230
  if not _allowed(_visitor(request)):
231
  return _page(
232
  FORM_ERROR.format(msg=f"You have run {PER_HOUR} searches this hour. Please try again later."),
@@ -234,42 +359,165 @@ async def search(request: Request) -> Response:
234
  )
235
  with _lock:
236
  job = _jobs.setdefault(key, {"started": time.time(), "steps": {}, "log": [], "sources": sources})
237
- threading.Thread(target=_work, args=(key, topic, start, end, sources, order), daemon=True).start()
 
 
 
 
 
 
 
 
238
  with _lock:
239
- steps = _steps(job)
240
- lines = list(job.get("log", []))
241
  waited = int(time.time() - job["started"])
242
- trail = "".join(f'<li><span class="t">{t:.0f} s</span>{html.escape(text)}</li>' for t, text in reversed(lines))
243
- body = WAIT.format(topic=html.escape(topic), steps=steps, waited=waited, trail=trail or "<li>Starting</li>")
244
- resp = _page(body, title="Searching | Actogram LabScout")
245
- resp.headers["Refresh"] = "2"
246
- return resp
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
 
248
 
249
  async def download(request: Request) -> Response:
250
  key, fmt = request.path_params["key"], request.path_params["fmt"]
 
 
251
  result = _results.get(key)
252
  if result is None:
253
  return PlainTextResponse("These results are no longer kept. Please run the search again.", status_code=404)
254
  name = f"labscout_{key}.{fmt}"
255
  disposition = {"Content-Disposition": f'attachment; filename="{name}"'}
256
  if fmt == "xlsx":
257
- data = await anyio.to_thread.run_sync(lambda: xlsx_bytes(result))
 
 
 
 
 
 
258
  mime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
259
  return Response(data, media_type=mime, headers=disposition)
260
  if fmt == "csv":
261
  return Response(csv_text(result), media_type="text/csv; charset=utf-8", headers=disposition)
262
- body = json.dumps(result.summary(top=len(result.labs)), ensure_ascii=False, indent=2)
263
  return Response(body, media_type="application/json", headers=disposition)
264
 
265
 
266
  async def health(request: Request) -> JSONResponse:
267
- return JSONResponse({"status": "ok", "version": __version__})
 
 
 
 
 
 
 
 
 
 
 
268
 
269
 
270
  async def robots(request: Request) -> PlainTextResponse:
271
  """Search engines may read the pages, but not start searches or downloads: each one costs the sources work."""
272
- return PlainTextResponse("User-agent: *\nAllow: /\nDisallow: /search\nDisallow: /download/\nDisallow: /mcp\n")
 
273
 
274
 
275
  async def mcp_get(request: Request) -> PlainTextResponse:
@@ -290,6 +538,18 @@ def mcp_security() -> TransportSecuritySettings:
290
  )
291
 
292
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  def create_app() -> Starlette:
294
  # stateless: every request stands alone, so a restart of the Space never strands an assistant's session
295
  mcp_app = mcp.streamable_http_app(stateless_http=True, transport_security=mcp_security())
@@ -297,6 +557,8 @@ def create_app() -> Starlette:
297
  routes=[
298
  Route("/", home),
299
  Route("/search", search),
 
 
300
  Route("/download/{key:str}.{fmt:str}", download),
301
  Route("/privacy", privacy),
302
  Route("/health", health),
@@ -305,12 +567,18 @@ def create_app() -> Starlette:
305
  middleware=[Middleware(GZipMiddleware, minimum_size=1000)], # pages only: the MCP answers stream
306
  )
307
  routes: list[Any] = [Route("/mcp", mcp_get, methods=["GET"]), *mcp_app.routes, Mount("/", app=pages)]
 
 
 
308
  return Starlette(routes=routes, lifespan=mcp_app.router.lifespan_context)
309
 
310
 
311
  def run(host: str = "127.0.0.1", port: int = 8000) -> None:
312
  import uvicorn
313
 
 
 
 
314
  uvicorn.run(create_app(), host=host, port=port, proxy_headers=True, forwarded_allow_ips="*")
315
 
316
 
@@ -358,6 +626,7 @@ code { font:14.5px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; bac
358
  .tips td:first-child { width:42%; }
359
  ul.plain { padding-left:20px; }
360
  ul.plain li { margin:0 0 8px; }
 
361
  .steps { list-style:none; margin:22px 0; padding:0; display:grid; gap:12px; font-size:17px; }
362
  .steps li { position:relative; padding-left:34px; min-height:22px; }
363
  .steps li::before { content:""; position:absolute; left:0; top:2px; width:18px; height:18px; border:2px solid var(--line); border-radius:50%; }
@@ -378,15 +647,15 @@ footer { color:var(--soft); font-size:14px; margin-top:40px; border-top:1px soli
378
  .wait { display:none; color:var(--soft); margin:0; }
379
  form.busy .wait { display:block; }
380
  @media (max-width:760px) { .hero { grid-template-columns:1fr; } .art-hero { max-width:300px; } .how { grid-template-columns:1fr 1fr; } }
381
- @media (max-width:600px) { h1 { font-size:28px; } .row { grid-template-columns:1fr; } }
382
  @media (max-width:460px) { .how { grid-template-columns:1fr; } .how svg { max-width:100px; } }
383
  </style>
384
  </head>
385
  <body>
386
  <main>
387
  {{BODY}}
388
- <footer>Actogram LabScout {{VERSION}}. Open source under the MIT licence, part of
389
- <a href="https://actogram.org">Actogram Open Science</a>. Data from PubMed, Europe PMC, ROR, NIH RePORTER, UKRI
390
  Gateway to Research and ClinicalTrials.gov, shown as published, without e-mail addresses.
391
  <a href="privacy">Privacy</a>.</footer>
392
  </main>
@@ -406,8 +675,8 @@ FORM = """<div class="hero">
406
  {{ART}}
407
  </div>
408
  <form action="search" method="get">
409
- <label>Topic<input type="text" name="topic" required maxlength="300"
410
- placeholder="for example: actigraphy sleep regularity"></label>
411
  <div class="row">
412
  <label>From year<input type="number" name="from" min="1900" max="2100" value="{{FROM}}"></label>
413
  <label>To year<input type="number" name="to" min="1900" max="2100" placeholder="now"></label>
@@ -447,6 +716,7 @@ FORM = """<div class="hero">
447
  <thead><tr><th scope="col">To find</th><th scope="col">Type</th></tr></thead>
448
  <tbody>
449
  <tr><td>Papers on a topic</td><td><code>actigraphy sleep regularity</code></td></tr>
 
450
  <tr><td>An exact phrase</td><td><code>"sleep regularity index"</code></td></tr>
451
  <tr><td>Either of two words</td><td><code>actigraphy OR accelerometry</code></td></tr>
452
  <tr><td>Without a word</td><td><code>circadian NOT mice</code></td></tr>
@@ -455,16 +725,20 @@ FORM = """<div class="hero">
455
  </tbody>
456
  </table>
457
  <p class="note">Too many papers? Add a word, use quotes or narrow the years. Too few? Use fewer words or OR. The report
458
- says which, and shows how PubMed read your search.</p>
 
459
 
460
  <h2>Reading the results</h2>
461
  <ul class="plain">
462
  <li>Each lab is named after the last author of its papers, who usually leads it. Older PubMed records give only the
463
  first author's affiliation; then the lab is placed there.</li>
464
- <li>Organisations are matched automatically. In Excel, the column <i>match</i> says how each one was found: check it
465
- before you write to anyone.</li>
466
- <li>One person at two places is one lab when it is clearly the same person: the same city, or the same ORCID iD.
467
- Otherwise the name shows twice, because it may be two people.</li>
 
 
 
468
  <li>LabScout shows what researchers have published. Use it to find research and collaborators, not to judge
469
  people.</li>
470
  </ul>
@@ -489,13 +763,43 @@ FORM = """<div class="hero">
489
  FORM_ERROR = '<p class="err">{msg}</p><p><a href="./">Back to the search</a></p>'
490
 
491
  WAIT = """<h1>Searching for <span>{topic}</span></h1>
492
- <p class="lead">Most topics take under a minute, a very broad one two or three. This page follows the search and
493
  shows the report when it is ready.</p>
494
- {steps}
495
- <p class="note">{waited} seconds so far.</p>
496
  <h2>What LabScout is doing</h2>
497
- <ol class="trail" aria-live="polite">{trail}</ol>
498
- <p><a href="./">Back to the search</a></p>"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
499
 
500
  PRIVACY = """<h1>Privacy</h1>
501
  <p class="lead">What LabScout does with personal data, on this page and in its tools for AI assistants.</p>
@@ -514,10 +818,13 @@ PRIVACY = """<h1>Privacy</h1>
514
  <a href="https://huggingface.co/privacy">Hugging Face privacy policy</a>.</li>
515
  <li>To keep the tool fair, the page counts the searches from each IP address for one hour. The count stays in the
516
  server's memory and is not stored.</li>
 
 
517
  <li>Your search words go to PubMed (US National Library of Medicine) and Europe PMC (EMBL-EBI), and the
518
  affiliations in the papers go to the Research Organization Registry, to find the papers and the organisations.
519
  The last 50 reports stay in memory for the download links, and the answers of the sources are kept for seven
520
  days so that a repeated search is fast.</li>
 
521
  <li>Requests from an AI assistant are handled the same way.</li>
522
  </ul>
523
 
@@ -529,7 +836,8 @@ PRIVACY = """<h1>Privacy</h1>
529
  other contact details.</p>
530
  <p>The legal basis is our legitimate interest, and that of the people who use LabScout, in finding research and
531
  collaborators. The information is professional, already public and shown in its original context.</p>
532
- <p>You can object at any time and ask us to hide your entry. Write to
 
533
  <a href="mailto:services@actogram.ai">services@actogram.ai</a> with your name and, if you have one, your ORCID iD.
534
  A hidden entry stays hidden in later searches.</p>
535
 
@@ -537,5 +845,5 @@ PRIVACY = """<h1>Privacy</h1>
537
  <p>You can ask to see the data we hold about you, to correct or delete it, to restrict its use, or object to it. We
538
  answer within one month. You can also complain to the UK Information Commissioner's Office (ico.org.uk) or, in the
539
  EU, to the data protection authority where you live or work.</p>
540
- <p class="note">Last updated 27 October 2026.</p>
541
  """
 
2
 
3
  / a search form, with how it works and search tips
4
  /search the report for a search: map, charts, table, downloads; while it runs, a page with the steps
5
+ /status the steps of a running search, for the waiting page
6
+ /profile one researcher: organisations, topics, co-authors, recent papers, grants
7
  /download the last results as Excel, CSV or JSON
8
  /privacy what the page and the tools do with personal data
9
  /mcp the MCP server (Streamable HTTP) for AI assistants
 
12
 
13
  from __future__ import annotations
14
 
 
15
  import html
16
+ import ipaddress
17
  import json
18
  import logging
19
  import os
 
22
  from collections import OrderedDict, defaultdict, deque
23
  from datetime import date
24
  from typing import Any
25
+ from urllib.parse import parse_qsl, urlencode
26
 
27
  import anyio
28
  from mcp.server.transport_security import TransportSecuritySettings
 
34
  from starlette.routing import Mount, Route
35
 
36
  from . import __version__, art
37
+ from .config import REPO, Settings
38
  from .errors import SearchError
39
+ from .export import csv_text, fill, render_html, xlsx_bytes
40
+ from .http import tidy_cache
41
+ from .pipeline import ORDERS, RESULTS, SMALL_SLOTS, find_labs, place_for, plain_question, profile, result_key, size_of
42
  from .server import mcp
43
  from .sources import PUBLICATION_SOURCES
44
 
45
  MAX_PAPERS = int(os.environ.get("LABSCOUT_WEB_MAX_PAPERS", "10000")) # per source, for one search on the page
46
  PER_HOUR = int(os.environ.get("LABSCOUT_SEARCHES_PER_HOUR", "20")) # per visitor
47
+ PROFILES_PER_HOUR = 60 # per visitor
48
+ FAILURE_KEPT = 600 # seconds a failed search keeps its message for the visitor who waits for it
49
+ WARM_AFTER = 45 # seconds after a start before the examples of the home page are read (LABSCOUT_WARM_EXAMPLES=1)
50
+ MAX_WAITING = int(os.environ.get("LABSCOUT_MAX_WAITING", "30")) # searches running or waiting, all visitors together
51
+ # proxies with a public address between the visitors and this app (none on Hugging Face Spaces)
52
+ PROXY_HOPS = int(os.environ.get("LABSCOUT_PROXY_HOPS", "0"))
53
+ # where "made by" at the foot of the pages leads; the address must be one that answers
54
+ SITE_URL = os.environ.get("LABSCOUT_SITE_URL", "https://actogram.ai").strip() or "https://actogram.ai"
55
+ SITE_NAME = os.environ.get("LABSCOUT_SITE_NAME", "Actogram").strip() or "Actogram"
56
  log = logging.getLogger(__name__)
57
  FRAMES = "frame-ancestors 'self' https://huggingface.co https://*.hf.space" # the Space page shows the app in a frame
58
  SECURITY = {
 
60
  "Referrer-Policy": "strict-origin-when-cross-origin",
61
  "Strict-Transport-Security": "max-age=31536000",
62
  "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; "
63
+ "img-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; " + FRAMES,
64
  }
65
  # the report also loads the map library and the map tiles
66
  REPORT_SECURITY = SECURITY | {
 
83
  "labs": "Rank the labs and draw the map",
84
  }
85
 
86
+ _results = RESULTS # finished searches, shared with the assistants' tools
87
  _jobs: dict[str, dict[str, Any]] = {} # searches still running, or failed
88
  _lock = threading.Lock()
89
  _visits: dict[str, deque[float]] = defaultdict(deque)
90
+ _looks: dict[str, deque[float]] = defaultdict(deque)
91
+ _files: OrderedDict[tuple[str, str], bytes] = OrderedDict() # Excel files already made, the last few
92
+ _people: OrderedDict[tuple[str, str, str], dict[str, Any]] = OrderedDict() # profiles already made
93
+ _took: deque[float] = deque(maxlen=500) # how long the last searches took, in seconds; nothing about their words
94
+ _started = time.time()
95
+
96
+
97
+ def _forwarded(request: Request) -> list[tuple[str, bool | None]]:
98
+ """The addresses in X-Forwarded-For in the order they were added, each with whether it is a public one; None for
99
+ an entry that is no address. A port is taken off, and an IPv6 address stands for its /64: that much belongs to
100
+ one visitor."""
101
+ hops: list[tuple[str, bool | None]] = []
102
+ for host in request.headers.get("x-forwarded-for", "").split(","):
103
+ host = host.strip()
104
+ if not host:
105
+ continue
106
+ bare = host[1:].split("]")[0] if host.startswith("[") else host.split(":")[0] if host.count(":") == 1 else host
107
+ try:
108
+ ip = ipaddress.ip_address(bare)
109
+ except ValueError:
110
+ hops.append((host, None))
111
+ continue
112
+ if ip.version == 6:
113
+ bare = str(ipaddress.ip_network(f"{bare}/64", strict=False).network_address)
114
+ hops.append((bare, ip.is_global))
115
+ return hops
116
 
117
 
118
  def _visitor(request: Request) -> str:
119
+ """The visitor's address, for the hourly limits. Every proxy on the way adds the address it was called from to
120
+ the end of X-Forwarded-For, and a visitor can write anything in front of that. So the list is read from the end:
121
+ inner addresses of the hosting network are passed over, and the first entry that is not one of them is taken.
122
+ Nothing in front of it can be trusted."""
123
+ hops = _forwarded(request)
124
+ if PROXY_HOPS:
125
+ hops = hops[:-PROXY_HOPS]
126
+ for host, public in reversed(hops):
127
+ if public is not False:
128
+ return host
129
+ return hops[-1][0] if hops else (request.client.host if request.client else "unknown")
130
+
131
+
132
+ def _allowed(who: str, book: dict[str, deque[float]] | None = None, most: int | None = None) -> bool:
133
+ book = _visits if book is None else book
134
+ most = PER_HOUR if most is None else most
135
  now = time.time()
136
+ if len(book) > 5000: # forget the visitors who have not searched for an hour
137
+ for k in [k for k, v in book.items() if not v or now - v[-1] > 3600]:
138
+ del book[k]
139
+ seen = book[who]
140
  while seen and now - seen[0] > 3600:
141
  seen.popleft()
142
+ if len(seen) >= most:
143
  return False
144
  seen.append(now)
145
  return True
 
147
 
148
  def _year(value: str | None) -> int | None:
149
  value = (value or "").strip()
150
+ if len(value) == 4 and value.isascii() and value.isdigit() and 1800 <= int(value) <= date.today().year + 1:
151
+ return int(value)
152
+ return None
153
 
154
 
155
  def _page(body: str, title: str = "Actogram LabScout", status: int = 200) -> HTMLResponse:
156
+ values = {
157
+ "{{TITLE}}": html.escape(title),
158
+ "{{BODY}}": body,
159
+ "{{VERSION}}": __version__,
160
+ "{{SITE_URL}}": html.escape(SITE_URL),
161
+ "{{SITE_NAME}}": html.escape(SITE_NAME),
162
+ }
163
+ return HTMLResponse(fill(PAGE, values), status_code=status, headers=SECURITY)
164
 
165
 
166
  async def home(request: Request) -> HTMLResponse:
 
169
  examples = " ".join(
170
  f'<a href="search?{html.escape(urlencode({"topic": t, "from": since}))}">{html.escape(t)}</a>' for t in EXAMPLES
171
  )
172
+ values = {
 
173
  "{{MCP}}": html.escape(f"{base}/mcp"),
174
  "{{REPO}}": REPO,
175
  "{{MAX}}": f"{MAX_PAPERS:,}",
 
180
  "{{STEP_PAPERS}}": art.STEP_PAPERS,
181
  "{{STEP_LAB}}": art.STEP_LAB,
182
  "{{STEP_MAP}}": art.STEP_MAP,
183
+ }
184
+ return _page(fill(FORM, values))
 
185
 
186
 
187
  async def privacy(request: Request) -> HTMLResponse:
 
189
 
190
 
191
  def _work(key: str, topic: str, start: int | None, end: int | None, sources: list[str], order: str) -> None:
192
+ """One search, in its own thread; the page asks for its steps until it is done."""
193
 
194
  def progress(step: str, text: str) -> None:
195
  with _lock:
 
198
  return
199
  if step != "note":
200
  job["steps"][step] = text
201
+ now = round(time.time() - job["started"], 1)
202
  last = job["log"][-1][1] if job["log"] else ""
203
+ moving = (step == "organisations" and last.startswith("Matching") and text.startswith("Matching")) or (
204
  text.endswith("records read")
205
  and last.endswith("records read")
206
  and last.split(":")[0] == text.split(":")[0]
207
  )
208
+ if moving: # one moving line instead of hundreds, with the time of its last change
209
+ job["log"][-1] = (now, text)
210
  else:
211
+ job["log"].append((now, text))
212
  del job["log"][:-60]
213
 
214
  try:
215
+ sizes = size_of(topic, start, end, sources, limit=MAX_PAPERS, order=order) # also stops unreadable searches
216
+ place = place_for(sizes, MAX_PAPERS)
217
+ if not place.acquire(blocking=False):
218
  progress("queue", "Waiting for a free place: other searches are running")
219
+ place.acquire()
220
  try:
221
  result = find_labs(topic, start, end, MAX_PAPERS, sources, order=order, progress=progress)
222
  finally:
223
+ place.release()
224
+ _results.put(key, result)
225
+ with _lock:
226
+ took = time.time() - _jobs.get(key, {}).get("started", time.time())
227
+ _took.append(took)
228
+ log.info("search done: %s papers, %s labs, %.1f s", len(result.papers), len(result.labs), took)
229
  with _lock:
 
 
 
230
  _jobs.pop(key, None)
231
  except SearchError as err:
232
  with _lock:
 
240
  }
241
 
242
 
243
+ def _example(topic: str) -> tuple[str, int, list[str], str]:
244
+ """An example of the home page as the page will ask for it: (topic, first year, sources, key)."""
245
+ since, sources = date.today().year - 5, list(PUBLICATION_SOURCES)
246
+ topic = plain_question(topic)[0]
247
+ return topic, since, sources, result_key(topic, since, None, sources, "relevance", MAX_PAPERS)
248
+
249
+
250
+ def _warm_examples() -> None:
251
+ """After a start, read the examples of the home page one by one, each while no visitor is searching, so that a
252
+ first click on an example shows its report at once. A failure here is nobody's message and is dropped."""
253
+ time.sleep(WARM_AFTER)
254
+ for example in EXAMPLES:
255
+ topic, since, sources, key = _example(example)
256
+ for _ in range(240): # visitors first: wait for a quiet moment, at most twenty minutes
257
+ with _lock:
258
+ if not any("error" not in j for j in _jobs.values()):
259
+ break
260
+ time.sleep(5)
261
+ else:
262
+ return
263
+ if _results.get(key) is not None:
264
+ continue
265
+ with _lock:
266
+ if key in _jobs:
267
+ continue
268
+ _jobs[key] = {"started": time.time(), "steps": {}, "log": [], "sources": sources}
269
+ _work(key, topic, since, None, sources, "relevance")
270
+ with _lock:
271
+ if "error" in _jobs.get(key, {}):
272
+ del _jobs[key]
273
+
274
+
275
  def _steps(job: dict[str, Any]) -> str:
276
  """The steps of a running search: done, now, still to come."""
277
  told = dict(job.get("steps", {}))
 
286
  items.append(f'<li class="{state}">{html.escape(told[s])}</li>')
287
  else:
288
  items.append(f'<li class="todo">{html.escape(STEPS.get(s, s))}</li>')
289
+ return "".join(items)
290
 
291
 
292
+ def _trail(job: dict[str, Any]) -> str:
293
+ lines = list(job.get("log", []))
294
+ return "".join(f'<li><span class="t">{t:.0f} s</span>{html.escape(text)}</li>' for t, text in reversed(lines)) or (
295
+ "<li>Starting</li>"
296
+ )
297
+
298
+
299
+ def _ask(request: Request) -> tuple[str, str, str, int | None, int | None, list[str], str, str]:
300
+ """What a search request asks for: (as typed, as searched, a note on the difference, years, sources, order, key)."""
301
  q = request.query_params
302
+ asked = (q.get("topic") or "").strip()[:300]
303
+ topic, note = (asked, "") if q.get("exact") == "1" else plain_question(asked)
 
304
  start, end = _year(q.get("from")), _year(q.get("to"))
305
  if start and end and start > end:
306
  start, end = end, start
307
+ sources = [s for s in dict.fromkeys(q.getlist("source")) if s in PUBLICATION_SOURCES] or list(PUBLICATION_SOURCES)
308
  order = q.get("order") if q.get("order") in ORDERS else "relevance"
309
+ return asked, topic, note, start, end, sources, order, result_key(topic, start, end, sources, order, MAX_PAPERS)
310
+
311
+
312
+ async def search(request: Request) -> Response:
313
+ asked, topic, note, start, end, sources, order, key = _ask(request)
314
+ if not topic:
315
+ return _page(FORM_ERROR.format(msg="Type a topic to search for."), status=400)
316
  with _lock:
 
317
  job = _jobs.get(key)
318
+ result = _results.get(key)
 
319
  if result is not None:
320
+ tools = [
321
+ '<a href="./">New search</a>',
322
+ f'<a href="download/{key}.xlsx">Excel</a>',
323
+ f'<a href="download/{key}.csv">CSV</a>',
324
+ f'<a href="download/{key}.json">JSON</a>',
325
+ ]
326
+ if note: # a question was read as key words: offer the search exactly as typed, with the same choices
327
+ literal = [(k, v) for k, v in request.query_params.multi_items() if k not in ("topic", "exact")]
328
+ literal += [("topic", asked), ("exact", "1")]
329
+ tools.append(f'<a href="search?{html.escape(urlencode(literal))}">Search exactly as typed</a>')
330
  footer = '<p><a href="./">New search</a>. <a href="privacy">Privacy</a>.</p>'
331
+ page = render_html(
332
+ result,
333
+ top=200,
334
+ toolbar=f'<p class="tools">{"".join(tools)}</p>',
335
+ footer=footer,
336
+ profiles="profile",
337
+ notes=[note] if note else [],
338
+ )
339
  return HTMLResponse(page, headers=REPORT_SECURITY)
340
  if job and "error" in job:
341
  with _lock:
342
  _jobs.pop(key, None)
343
+ if time.time() - job["started"] < FAILURE_KEPT:
344
+ return _page(FORM_ERROR.format(msg=html.escape(job["error"])), status=400)
345
+ job = None # an old failure that nobody came back for: search again
346
  if job is None:
347
+ with _lock:
348
+ now = time.time()
349
+ for k in [k for k, j in _jobs.items() if "error" in j and now - j["started"] > FAILURE_KEPT]:
350
+ del _jobs[k]
351
+ busy = sum(1 for j in _jobs.values() if "error" not in j)
352
+ if busy >= MAX_WAITING:
353
+ msg = "LabScout is busy: many searches are waiting. Please try again in a few minutes."
354
+ return _page(FORM_ERROR.format(msg=msg), status=503)
355
  if not _allowed(_visitor(request)):
356
  return _page(
357
  FORM_ERROR.format(msg=f"You have run {PER_HOUR} searches this hour. Please try again later."),
 
359
  )
360
  with _lock:
361
  job = _jobs.setdefault(key, {"started": time.time(), "steps": {}, "log": [], "sources": sources})
362
+ try:
363
+ threading.Thread(target=_work, args=(key, topic, start, end, sources, order), daemon=True).start()
364
+ except RuntimeError: # no thread to be had: a search that nobody runs must not stay in the table
365
+ with _lock:
366
+ _jobs.pop(key, None)
367
+ return _page(FORM_ERROR.format(msg="LabScout is busy. Please try again in a few minutes."), status=503)
368
+ kinds = {True: "public", False: "inner", None: "unreadable"}
369
+ seen = "/".join(kinds[public] for _, public in _forwarded(request)) or "none"
370
+ log.info("search started: %s running or waiting, forwarded-for addresses: %s", busy + 1, seen)
371
  with _lock:
372
+ steps, trail = _steps(job), _trail(job)
 
373
  waited = int(time.time() - job["started"])
374
+ body = WAIT.format(topic=html.escape(topic), steps=steps, waited=waited, trail=trail, key=key)
375
+ return _page(body, title="Searching | Actogram LabScout")
376
+
377
+
378
+ async def status(request: Request) -> JSONResponse:
379
+ """Where a running search is, for the waiting page: it asks every second and shows the steps without reloading."""
380
+ key = request.path_params["key"]
381
+ with _lock:
382
+ job = _jobs.get(key)
383
+ if job is not None and "error" not in job:
384
+ body = {
385
+ "state": "running",
386
+ "steps": _steps(job),
387
+ "trail": _trail(job),
388
+ "waited": int(time.time() - job["started"]),
389
+ }
390
+ return JSONResponse(body, headers={"Cache-Control": "no-store"})
391
+ return JSONResponse({"state": "done"}, headers={"Cache-Control": "no-store"}) # ready or failed: reload to see
392
+
393
+
394
+ def _rows(items: list[str]) -> str:
395
+ return "".join(f"<li>{x}</li>" for x in items) or "<li>None found.</li>"
396
+
397
+
398
+ async def profile_page(request: Request) -> HTMLResponse:
399
+ """One researcher, reached from a lab in a report: where the name appears, with whom, on what, and the grants."""
400
+ q = request.query_params
401
+ name, topic, org = (q.get("name") or "").strip()[:120], (q.get("topic") or "").strip()[:300], (q.get("org") or "")
402
+ org = org.strip()[:200]
403
+ if not name:
404
+ return _page(FORM_ERROR.format(msg="No researcher was named."), status=400)
405
+ who = (name, topic, org)
406
+ data = _people.get(who)
407
+ if data is None:
408
+ if not _allowed(_visitor(request), _looks, PROFILES_PER_HOUR):
409
+ return _page(FORM_ERROR.format(msg="Too many profiles this hour. Please try again later."), status=429)
410
+
411
+ def look() -> dict[str, Any]:
412
+ with SMALL_SLOTS:
413
+ return profile(name, topic, org, 200)
414
+
415
+ try:
416
+ data = await anyio.to_thread.run_sync(look)
417
+ except SearchError as err:
418
+ return _page(FORM_ERROR.format(msg=html.escape(str(err))), status=400)
419
+ except Exception as err:
420
+ log.warning("profile failed: %s", err)
421
+ return _page(FORM_ERROR.format(msg="The sources did not answer. Please try again in a minute."), status=502)
422
+ _people[who] = data
423
+ while len(_people) > 200:
424
+ _people.popitem(last=False)
425
+ e = html.escape
426
+ if "error" in data:
427
+ return _page(FORM_ERROR.format(msg=e(data["error"])), status=404)
428
+ # the report sends its own address along, so that "back" opens that very search again
429
+ choices = ("topic", "from", "to", "source", "order", "exact")
430
+ back = [(k, v[:300]) for k, v in parse_qsl((q.get("back") or "").lstrip("?")[:2000]) if k in choices]
431
+ if not any(k == "topic" for k, _ in back):
432
+ back = [("topic", topic), ("exact", "1")] if topic else []
433
+ shown = " ".join(x.strip() for x in reversed(name.split(",", 1))) if "," in name else name
434
+ at = f" at {e(org)}" if org else ""
435
+ if org and data.get("organization_found") is False:
436
+ at = f" (no paper prints \u201c{e(org)}\u201d, so all papers under the name are counted)"
437
+ orgs = [
438
+ (f'<a href="{e(o["ror"])}" target="_blank" rel="noopener">{e(o["name"])}</a>' if o["ror"] else e(o["name"]))
439
+ + (f", {e(o['city'])}" if o["city"] else "")
440
+ + (f", {e(o['country'])}" if o["country"] else "")
441
+ + f": {o['papers']} paper{'s' if o['papers'] != 1 else ''}"
442
+ for o in data["organizations"]
443
+ ]
444
+ recent = [
445
+ (f'<a href="{e(p["url"])}" target="_blank" rel="noopener">{e(p["title"])}</a>' if p["url"] else e(p["title"]))
446
+ + f" ({e(str(p['year'] or ''))}, {e(p['journal'])})"
447
+ for p in data["recent_papers"]
448
+ ]
449
+ grants = [
450
+ (f'<a href="{e(g["url"])}" target="_blank" rel="noopener">{e(g["title"])}</a>' if g["url"] else e(g["title"]))
451
+ + f" ({e(g['number'])}, {e(g['organization'])}"
452
+ + (f", until {e(g['end_date'])}" if g["end_date"] else "")
453
+ + ")"
454
+ for g in data["grants"]
455
+ ]
456
+ years = [y for y in data["years"] if y]
457
+ span = (str(years[0]) if len(set(years)) == 1 else f"{years[0]} to {years[-1]}") if years else "no years given"
458
+ pubmed = "https://pubmed.ncbi.nlm.nih.gov/?" + urlencode({"term": data["pubmed_query"]})
459
+ body = PROFILE.format(
460
+ name=e(shown),
461
+ scope=f" on <b>{e(topic)}</b>" if topic else "",
462
+ org=at,
463
+ found=data["papers_found"],
464
+ span=e(span),
465
+ pubmed=e(pubmed),
466
+ orgs=_rows(orgs),
467
+ topics=_rows([f"{e(t['mesh'])} ({t['papers']})" for t in data["frequent_topics"]]),
468
+ mates=_rows([f"{e(c['name'])} ({c['papers']})" for c in data["frequent_coauthors"]]),
469
+ data=e(", ".join(data["data_signals"] + data["species"]) or "none noted"),
470
+ recent=_rows(recent),
471
+ grants=_rows(grants),
472
+ back=e("search?" + urlencode(back)) if back else "./",
473
+ )
474
+ return _page(body, title=f"{shown} | Actogram LabScout")
475
 
476
 
477
  async def download(request: Request) -> Response:
478
  key, fmt = request.path_params["key"], request.path_params["fmt"]
479
+ if fmt not in ("xlsx", "csv", "json"):
480
+ return PlainTextResponse("No such file.", status_code=404)
481
  result = _results.get(key)
482
  if result is None:
483
  return PlainTextResponse("These results are no longer kept. Please run the search again.", status_code=404)
484
  name = f"labscout_{key}.{fmt}"
485
  disposition = {"Content-Disposition": f'attachment; filename="{name}"'}
486
  if fmt == "xlsx":
487
+ run = (key, result.created) # the same search run again later gets a file of its own
488
+ data = _files.get(run)
489
+ if data is None: # a big sheet takes seconds to make: once, not on every click
490
+ data = await anyio.to_thread.run_sync(lambda: xlsx_bytes(result))
491
+ _files[run] = data
492
+ while len(_files) > 8:
493
+ _files.popitem(last=False)
494
  mime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
495
  return Response(data, media_type=mime, headers=disposition)
496
  if fmt == "csv":
497
  return Response(csv_text(result), media_type="text/csv; charset=utf-8", headers=disposition)
498
+ body = json.dumps(result.summary(top=len(result.labs)), ensure_ascii=False, separators=(",", ":"))
499
  return Response(body, media_type="application/json", headers=disposition)
500
 
501
 
502
  async def health(request: Request) -> JSONResponse:
503
+ """A status answer, with how many searches ran since the start and how long they took (no search words)."""
504
+ took = sorted(_took)
505
+ body: dict[str, Any] = {
506
+ "status": "ok",
507
+ "version": __version__,
508
+ "hours_up": round((time.time() - _started) / 3600, 1),
509
+ }
510
+ body["searches"] = len(took)
511
+ if took:
512
+ body["seconds_median"] = round(took[len(took) // 2], 1)
513
+ body["seconds_slowest"] = round(took[-1], 1)
514
+ return JSONResponse(body)
515
 
516
 
517
  async def robots(request: Request) -> PlainTextResponse:
518
  """Search engines may read the pages, but not start searches or downloads: each one costs the sources work."""
519
+ lines = ["User-agent: *", "Allow: /", "Disallow: /search", "Disallow: /status/", "Disallow: /profile"]
520
+ return PlainTextResponse("\n".join([*lines, "Disallow: /download/", "Disallow: /mcp"]) + "\n")
521
 
522
 
523
  async def mcp_get(request: Request) -> PlainTextResponse:
 
538
  )
539
 
540
 
541
+ def _keep_house() -> None:
542
+ """Every hour: remove cached answers that are too old or too many (see `http.tidy_cache`)."""
543
+ while True:
544
+ try:
545
+ removed, left = tidy_cache(Settings.from_env().cache_dir)
546
+ if removed:
547
+ log.info("cache tidied: %s files removed, %s MB left", removed, left)
548
+ except Exception as err:
549
+ log.warning("cache not tidied: %s", err)
550
+ time.sleep(3600)
551
+
552
+
553
  def create_app() -> Starlette:
554
  # stateless: every request stands alone, so a restart of the Space never strands an assistant's session
555
  mcp_app = mcp.streamable_http_app(stateless_http=True, transport_security=mcp_security())
 
557
  routes=[
558
  Route("/", home),
559
  Route("/search", search),
560
+ Route("/status/{key:str}", status),
561
+ Route("/profile", profile_page),
562
  Route("/download/{key:str}.{fmt:str}", download),
563
  Route("/privacy", privacy),
564
  Route("/health", health),
 
567
  middleware=[Middleware(GZipMiddleware, minimum_size=1000)], # pages only: the MCP answers stream
568
  )
569
  routes: list[Any] = [Route("/mcp", mcp_get, methods=["GET"]), *mcp_app.routes, Mount("/", app=pages)]
570
+ threading.Thread(target=_keep_house, daemon=True).start()
571
+ if os.environ.get("LABSCOUT_WARM_EXAMPLES") == "1":
572
+ threading.Thread(target=_warm_examples, daemon=True).start()
573
  return Starlette(routes=routes, lifespan=mcp_app.router.lifespan_context)
574
 
575
 
576
  def run(host: str = "127.0.0.1", port: int = 8000) -> None:
577
  import uvicorn
578
 
579
+ logging.getLogger("labscout").setLevel(logging.INFO)
580
+ if not logging.getLogger().handlers:
581
+ logging.basicConfig(format="%(levelname)s %(name)s %(message)s")
582
  uvicorn.run(create_app(), host=host, port=port, proxy_headers=True, forwarded_allow_ips="*")
583
 
584
 
 
626
  .tips td:first-child { width:42%; }
627
  ul.plain { padding-left:20px; }
628
  ul.plain li { margin:0 0 8px; }
629
+ ul.cols { columns:2; column-gap:28px; }
630
  .steps { list-style:none; margin:22px 0; padding:0; display:grid; gap:12px; font-size:17px; }
631
  .steps li { position:relative; padding-left:34px; min-height:22px; }
632
  .steps li::before { content:""; position:absolute; left:0; top:2px; width:18px; height:18px; border:2px solid var(--line); border-radius:50%; }
 
647
  .wait { display:none; color:var(--soft); margin:0; }
648
  form.busy .wait { display:block; }
649
  @media (max-width:760px) { .hero { grid-template-columns:1fr; } .art-hero { max-width:300px; } .how { grid-template-columns:1fr 1fr; } }
650
+ @media (max-width:600px) { h1 { font-size:28px; } .row { grid-template-columns:1fr; } ul.cols { columns:1; } }
651
  @media (max-width:460px) { .how { grid-template-columns:1fr; } .how svg { max-width:100px; } }
652
  </style>
653
  </head>
654
  <body>
655
  <main>
656
  {{BODY}}
657
+ <footer>Actogram LabScout {{VERSION}}. Open source under the MIT licence, made by
658
+ <a href="{{SITE_URL}}">{{SITE_NAME}}</a>. Data from PubMed, Europe PMC, ROR, NIH RePORTER, UKRI
659
  Gateway to Research and ClinicalTrials.gov, shown as published, without e-mail addresses.
660
  <a href="privacy">Privacy</a>.</footer>
661
  </main>
 
675
  {{ART}}
676
  </div>
677
  <form action="search" method="get">
678
+ <label>Topic<input type="text" name="topic" required maxlength="300" autofocus
679
+ placeholder="key words, or a question: which labs study social jetlag?"></label>
680
  <div class="row">
681
  <label>From year<input type="number" name="from" min="1900" max="2100" value="{{FROM}}"></label>
682
  <label>To year<input type="number" name="to" min="1900" max="2100" placeholder="now"></label>
 
716
  <thead><tr><th scope="col">To find</th><th scope="col">Type</th></tr></thead>
717
  <tbody>
718
  <tr><td>Papers on a topic</td><td><code>actigraphy sleep regularity</code></td></tr>
719
+ <tr><td>The same as a question in English</td><td><code>which labs study sleep regularity in older adults?</code></td></tr>
720
  <tr><td>An exact phrase</td><td><code>"sleep regularity index"</code></td></tr>
721
  <tr><td>Either of two words</td><td><code>actigraphy OR accelerometry</code></td></tr>
722
  <tr><td>Without a word</td><td><code>circadian NOT mice</code></td></tr>
 
725
  </tbody>
726
  </table>
727
  <p class="note">Too many papers? Add a word, use quotes or narrow the years. Too few? Use fewer words or OR. The report
728
+ says which, shows how PubMed read your search, and names the words PubMed did not know. The sources read English
729
+ words in Latin letters.</p>
730
 
731
  <h2>Reading the results</h2>
732
  <ul class="plain">
733
  <li>Each lab is named after the last author of its papers, who usually leads it. Older PubMed records give only the
734
  first author's affiliation; then the lab is placed there.</li>
735
+ <li>The order shows how much of a lab's work is on your topic: papers it led count most. It says nothing about the
736
+ quality of the research. Open the papers behind a lab, its lead on PubMed or the profile to check it.</li>
737
+ <li>Organisations are matched automatically. A lab marked <i>place not confirmed</i> was placed by its country only;
738
+ in Excel, the column <i>match</i> says how each one was found. Check it before you write to anyone.</li>
739
+ <li>One person at two places is one lab when it is clearly the same person: the same city, the same ORCID iD or the
740
+ same co-authors; the other places are listed under <i>also</i>. Otherwise the name shows twice, because it may be
741
+ two people. Two people who share a last name and an initial are kept apart by their given names.</li>
742
  <li>LabScout shows what researchers have published. Use it to find research and collaborators, not to judge
743
  people.</li>
744
  </ul>
 
763
  FORM_ERROR = '<p class="err">{msg}</p><p><a href="./">Back to the search</a></p>'
764
 
765
  WAIT = """<h1>Searching for <span>{topic}</span></h1>
766
+ <p class="lead">Most topics take a few seconds, a very broad one up to a minute. This page follows the search and
767
  shows the report when it is ready.</p>
768
+ <ol class="steps" id="steps">{steps}</ol>
769
+ <p class="note"><span id="waited">{waited}</span> seconds so far.</p>
770
  <h2>What LabScout is doing</h2>
771
+ <ol class="trail" id="trail" aria-live="polite">{trail}</ol>
772
+ <p><a href="./">Back to the search</a></p>
773
+ <noscript><meta http-equiv="refresh" content="2"></noscript>
774
+ <script>
775
+ (function () {{
776
+ function again(ms) {{ setTimeout(ask, ms); }}
777
+ function ask() {{
778
+ fetch('status/{key}', {{ cache: 'no-store' }}).then(function (r) {{ return r.json(); }}).then(function (s) {{
779
+ if (s.state !== 'running') {{ location.replace(location.href); return; }}
780
+ document.getElementById('steps').innerHTML = s.steps;
781
+ document.getElementById('trail').innerHTML = s.trail;
782
+ document.getElementById('waited').textContent = s.waited;
783
+ again(1000);
784
+ }}).catch(function () {{ again(2500); }});
785
+ }}
786
+ again(700);
787
+ }})();
788
+ </script>"""
789
+
790
+ PROFILE = """<h1>{name}</h1>
791
+ <p class="lead">{found} papers{scope}{org} under this name on PubMed, {span}.
792
+ <a href="{pubmed}" target="_blank" rel="noopener">See them on PubMed</a>.</p>
793
+ <p class="note">A name is not a person: PubMed finds papers by last name and first initial, so papers of people with
794
+ the same name can be mixed in. The organisations below show whether this is one person.</p>
795
+ <h2>Organisations on the papers</h2><ul class="plain">{orgs}</ul>
796
+ <h2>Recent papers</h2><ul class="plain">{recent}</ul>
797
+ <h2>Topics of the papers (MeSH)</h2><ul class="plain cols">{topics}</ul>
798
+ <h2>Frequent co-authors</h2><ul class="plain cols">{mates}</ul>
799
+ <h2>Data and species mentioned</h2><p>{data}</p>
800
+ <h2>NIH grants</h2><ul class="plain">{grants}</ul>
801
+ <p class="note">Grants are those of the US National Institutes of Health only; other funders are not covered here.</p>
802
+ <p><a href="{back}">Back to the labs</a> &middot; <a href="./">New search</a></p>"""
803
 
804
  PRIVACY = """<h1>Privacy</h1>
805
  <p class="lead">What LabScout does with personal data, on this page and in its tools for AI assistants.</p>
 
818
  <a href="https://huggingface.co/privacy">Hugging Face privacy policy</a>.</li>
819
  <li>To keep the tool fair, the page counts the searches from each IP address for one hour. The count stays in the
820
  server's memory and is not stored.</li>
821
+ <li>To see whether the tool is fast enough, the server keeps how long the last searches took, without their
822
+ words.</li>
823
  <li>Your search words go to PubMed (US National Library of Medicine) and Europe PMC (EMBL-EBI), and the
824
  affiliations in the papers go to the Research Organization Registry, to find the papers and the organisations.
825
  The last 50 reports stay in memory for the download links, and the answers of the sources are kept for seven
826
  days so that a repeated search is fast.</li>
827
+ <li>A researcher's profile page sends the name to PubMed and to NIH RePORTER in the same way.</li>
828
  <li>Requests from an AI assistant are handled the same way.</li>
829
  </ul>
830
 
 
836
  other contact details.</p>
837
  <p>The legal basis is our legitimate interest, and that of the people who use LabScout, in finding research and
838
  collaborators. The information is professional, already public and shown in its original context.</p>
839
+ <p>You can object at any time and ask us to hide your entry, or tell us that an entry is wrong (a wrong
840
+ organisation, two people shown as one). Write to
841
  <a href="mailto:services@actogram.ai">services@actogram.ai</a> with your name and, if you have one, your ORCID iD.
842
  A hidden entry stays hidden in later searches.</p>
843
 
 
845
  <p>You can ask to see the data we hold about you, to correct or delete it, to restrict its use, or object to it. We
846
  answer within one month. You can also complain to the UK Information Commissioner's Office (ico.org.uk) or, in the
847
  EU, to the data protection authority where you live or work.</p>
848
+ <p class="note">Last updated 14 November 2026.</p>
849
  """