Coverage for src/scixplorer/cli/interpret.py: 96%
594 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
1"""Read a search typed in plain words the way a person means it.
3:func:`interpret` turns ``Kewley 2008``, ``exoplanets 2026`` or ``ApJ 608 119``
4into conditions on :class:`~scixplorer.models.document.Document`. It makes no
5request: it reads the words against patterns (years, bibcodes, DOIs, arXiv and
6ORCID identifiers), the journal list and, once downloaded, the Unified Astronomy
7Thesaurus. Each piece of the search becomes one :class:`Reading`, so that the
8command can show how every word was understood.
10The rules, in the order they are tried on each word:
121. ``field:value`` is a condition on that field (``author:``, ``title:``,
13 ``year:``, any document field, and short forms such as ``a:`` and ``j:``);
14 ``citations:``, ``references:``, ``trending:``, ``useful:``, ``reviews:``
15 and ``similar:`` apply that operator to the interpreted value.
162. A quoted phrase is ``"Surname, Initials"``, a journal title, or else a
17 phrase to find in the title, abstract and keywords.
183. A bibcode, DOI, arXiv identifier, ORCID iD, or a link to one.
194. A year (``2005``), a range (``2005-2010``, ``2015-``), or ``since 2020``.
205. A journal, by abbreviation or title, and the volume and page after it.
216. ``Surname, Initials`` or ``Initials Surname``: an author.
227. The longest run of words that names a UAT concept.
238. A capitalised word: an author's surname.
249. Anything else: a word to find in the title, abstract and keywords. A word
25 in lower case that is not in the thesaurus may also be an author's surname,
26 so it matches either.
28A search that already looks like Solr syntax (``AND``, ``[2000 TO 2010]``) is
29sent as it is.
30"""
32from __future__ import annotations
34import re
35import warnings
36from collections.abc import Callable, Sequence
37from dataclasses import dataclass, replace
38from datetime import date
39from typing import Any
40from urllib.parse import unquote
42from ..exceptions import DataNotAvailable, QueryWarning, SciXError
43from ..expr import Expr
44from ..fields import FloatField, IntegerField
45from ..models.document import Document
46from ..models.journal import Journal
47from ..models.uat import UATConcept
48from ..utils import is_valid_orcid, parse_bibcode
50__all__ = ["Interpretation", "Reading", "interpret"]
52#: The earliest year a four-digit number is read as.
53FIRST_YEAR = 1500
55#: Words that say nothing about what to search for.
56STOPWORDS = frozenset(
57 "a an and by et for from in of on or the to with".split()
58)
60#: Lower-case words that begin a surname, as in "van der Marel".
61PARTICLES = frozenset("da das de del della den der di dos du la le ten ter van von".split())
63#: Names people use for journals that the journal list does not have.
64JOURNAL_ALIASES = {
65 "A+A": "A&A",
66 "AA": "A&A",
67 "AandA": "A&A",
68 "ApJL": "ApJL",
69 "ApJLett": "ApJL",
70 "Icarus": "Icar",
71 "Nature": "Natur",
72 "PRD": "PhRvD",
73 "PRL": "PhRvL",
74 "Science": "Sci",
75 "apjl": "ApJL",
76}
78#: Short forms of the fields a search names most.
79FIELD_ALIASES = {
80 "a": "author",
81 "au": "author",
82 "fa": "first_author",
83 "first": "first_author",
84 "t": "title",
85 "k": "keyword",
86 "kw": "keyword",
87 "j": "journal",
88 "pub": "journal",
89 "y": "year",
90 "yr": "year",
91 "v": "volume",
92 "vol": "volume",
93 "p": "page",
94 "pp": "page",
95 "concept": "uat",
96 "cites": "citations",
97 "refs": "references",
98}
100#: Prefixes that apply a second-order operator to the interpreted value.
101OPERATORS = ("citations", "references", "trending", "useful", "reviews", "similar")
103_KINDS = {"first_author": "first author", "uat": "concept", "abs": "text"}
105_SOLR_SYNTAX = re.compile(r"\b(?:AND|OR|NOT)\b|\[[^\]]*\bTO\b[^\]]*\]|\w\(|[*?]\w|\w[*?]")
106_TOKEN = re.compile(r'(?:(?P<prefix>[A-Za-z_]+):)?"(?P<quoted>[^"]*)"(?P<sep>[,;]?)|(?P<word>\S+)')
107_PREFIXED = re.compile(r"(?P<prefix>[A-Za-z_]+):(?P<value>.+)", re.DOTALL)
108_INITIALS = re.compile(r"(?:[A-Z]\.?-?){1,4}")
109_LEADING_INITIALS = re.compile(r"(?:[A-Z]\.-?){1,4}|[A-Z]")
110_AUTHOR_PHRASE = re.compile(r"[^\W\d_][\w'’ -]*,\s*[^\W\d_][\w.'’ -]*")
111_YEAR_RANGE = re.compile(r"(\d{4})(?:-|–|—|\.\.)(\d{4})")
112_YEAR_FROM = re.compile(r"(\d{4})(?:-|–|\+|\.\.)")
113_YEAR_TO = re.compile(r"(?:-|–|\.\.)(\d{4})")
114_PAGE = re.compile(r"[A-Za-z]?\d+[A-Za-z]?")
115_DOI = re.compile(r"10\.\d{4,9}/\S+")
116_ARXIV = re.compile(r"(?:arxiv:)?(\d{4}\.\d{4,5}|[a-z-]+(?:\.[A-Z]{2})?/\d{7})(?:v\d+)?", re.IGNORECASE)
117_ORCID = re.compile(r"\d{4}-\d{4}-\d{4}-\d{3}[\dXx]")
118_RECORD_URL = re.compile(r"https?://(?:ui\.adsabs\.harvard\.edu|(?:www\.)?scixplorer\.org)/abs/([^/?#]+)")
119_DOI_URL = re.compile(r"https?://(?:dx\.)?doi\.org/(10\..+)")
120_ARXIV_URL = re.compile(r"https?://(?:www\.)?arxiv\.org/(?:abs|pdf)/(.+?)(?:\.pdf)?")
121_ORCID_URL = re.compile(r"https?://orcid\.org/(.+)")
122_YEAR_WORDS = {"since": ">=", "from": ">=", "after": ">", "before": "<", "until": "<="}
125@dataclass(frozen=True)
126class Reading:
127 """How one piece of a search was understood.
129 ``kind`` says what it was read as (``"author"``, ``"year"``,
130 ``"journal"``, ``"concept"``, ``"text"``, ...), ``source`` is what was
131 typed, ``value`` is what it means in words, and ``expr`` is the condition.
132 ``loose``, if there is one, is a wider condition to fall back on when the
133 search finds nothing: a concept also as words, a surname also as a word.
134 """
136 kind: str
137 source: str
138 value: str
139 expr: Expr
140 loose: Expr | None = None
142 def __str__(self) -> str:
143 return f"{self.kind} {self.value}"
146@dataclass(frozen=True)
147class Interpretation:
148 """A search as it was understood: one :class:`Reading` per piece, all of which must hold.
150 ``notes`` say what could have been read better, for example that the
151 thesaurus has not been downloaded.
152 """
154 text: str
155 readings: tuple[Reading, ...]
156 notes: tuple[str, ...] = ()
158 @property
159 def expr(self) -> Expr | None:
160 """Every reading's condition, AND-ed; ``None`` if the search was empty."""
161 combined: Expr | None = None
162 for reading in self.readings:
163 combined = reading.expr if combined is None else combined & reading.expr
164 return combined
166 def relaxed(self) -> Interpretation | None:
167 """The same search with every reading that has a wider condition using it; ``None`` if none has."""
168 if not any(reading.loose is not None for reading in self.readings):
169 return None
170 return replace(self, readings=tuple(_loosened(reading) for reading in self.readings))
172 def __str__(self) -> str:
173 return " · ".join(str(reading) for reading in self.readings)
176def _loosened(reading: Reading) -> Reading:
177 if reading.loose is None:
178 return reading
179 return Reading(f"{reading.kind} or text", reading.source, reading.value, reading.loose)
182@dataclass(frozen=True)
183class _Token:
184 text: str
185 quoted: bool = False
186 comma: bool = False
187 prefix: str | None = None
188 first: bool = False
191def interpret(query: str | Sequence[str], *, today: date | None = None) -> Interpretation:
192 """Read a search typed in plain words; see the module documentation for the rules.
194 :param query: the search as one string, or as the words of a command line.
195 In a string, double quotes make a phrase. Of several command-line
196 words, one that holds spaces was quoted in the shell, and is a phrase.
197 :param today: the date that decides which numbers can be years (default: today).
198 """
199 text = query.strip() if isinstance(query, str) else " ".join(query).strip()
200 if _SOLR_SYNTAX.search(_unquoted(text)):
201 return Interpretation(text, (Reading("query", text, text, Document.raw(text)),))
202 parser = _Parser(_tokens(query), today or date.today())
203 parser.run()
204 return Interpretation(text, tuple(parser.readings), tuple(dict.fromkeys(parser.notes)))
207def _unquoted(text: str) -> str:
208 """``text`` without its double-quoted phrases."""
209 return re.sub(r'"[^"]*"', '""', text)
212# Tokens.
215def _known_prefix(prefix: str) -> str | None:
216 """The field or operator a ``prefix:`` names, or ``None`` if it names none."""
217 name = prefix.lower()
218 name = FIELD_ALIASES.get(name, name)
219 if name in OPERATORS or name in ("journal", "uat") or name in Document._fields:
220 return name
221 return None
224def _tokens(query: str | Sequence[str]) -> list[_Token]:
225 if isinstance(query, str):
226 return _split(query)
227 words = [word for word in query if word.strip()]
228 if len(words) == 1:
229 return _split(words[0])
230 tokens: list[_Token] = []
231 for word in words:
232 if not re.search(r"\s", word.strip()):
233 tokens.extend(_split(word))
234 continue
235 # A command-line word holding spaces was quoted in the shell.
236 prefix, value = None, word.strip()
237 match = _PREFIXED.fullmatch(value)
238 if match is not None and _known_prefix(match["prefix"]) is not None:
239 prefix, value = _known_prefix(match["prefix"]), match["value"].strip()
240 tokens.append(_Token(value.strip('"'), quoted=True, prefix=prefix))
241 return tokens
244def _split(text: str) -> list[_Token]:
245 tokens: list[_Token] = []
246 for match in _TOKEN.finditer(text):
247 if match["word"] is None:
248 prefix = _known_prefix(match["prefix"]) if match["prefix"] else None
249 if match["quoted"].strip(): 249 ↛ 251line 249 didn't jump to line 251 because the condition on line 249 was always true
250 tokens.append(_Token(match["quoted"].strip(), quoted=True, comma=bool(match["sep"]), prefix=prefix))
251 continue
252 token = _word_token(match["word"])
253 if token is not None: 253 ↛ 246line 253 didn't jump to line 246 because the condition on line 253 was always true
254 tokens.append(token)
255 return tokens
258def _word_token(word: str) -> _Token | None:
259 """One unquoted word, without the punctuation of the sentence or citation around it."""
260 comma = False
261 while word and word[-1] in ",;":
262 comma, word = True, word[:-1]
263 if word.startswith("(") and word.endswith(")"):
264 word = word[1:-1]
265 elif word.startswith(("(", "[")) and not any(c in word for c in ")]"): 265 ↛ 266line 265 didn't jump to line 266 because the condition on line 265 was never true
266 word = word[1:]
267 elif word.endswith((")", "]")) and not any(c in word for c in "(["): 267 ↛ 268line 267 didn't jump to line 268 because the condition on line 267 was never true
268 word = word[:-1]
269 first = word.startswith("^") and len(word) > 1
270 if first:
271 word = word[1:]
272 if word.endswith(".") and not _INITIALS.fullmatch(word) and not _DOI.fullmatch(word):
273 word = word.rstrip(".")
274 if not word: 274 ↛ 275line 274 didn't jump to line 275 because the condition on line 274 was never true
275 return None
276 prefix = None
277 match = _PREFIXED.fullmatch(word)
278 if match is not None and not match["value"].startswith("//"):
279 prefix = _known_prefix(match["prefix"])
280 if prefix is not None:
281 word = match["value"].strip('"')
282 return _Token(word, comma=comma, prefix=prefix, first=first) if word else None
285# Reference data.
288def _fold(text: str) -> str:
289 """Lower case, letters and digits only: ``ARA&A`` and ``araa`` fold to the same key."""
290 return "".join(c for c in text.lower() if c.isalnum())
293def _distinctive(abbreviation: str) -> bool:
294 """Whether an abbreviation is unlikely to be an ordinary word or name (``ApJ``, not ``Icar``)."""
295 return len(abbreviation) >= 3 and re.fullmatch(r"[A-Z]?[a-z]+", abbreviation) is None
298class _Journals:
299 """The journal list, indexed by abbreviation, by folded abbreviation and by title."""
301 def __init__(self, journals: Sequence[Journal]) -> None:
302 self.by_abbreviation: dict[str, Journal] = {}
303 self.by_title: dict[str, Journal] = {}
304 folded: dict[str, list[Journal]] = {}
305 for journal in journals:
306 abbreviation, title = journal.abbreviation, journal.title
307 if not abbreviation: 307 ↛ 308line 307 didn't jump to line 308 because the condition on line 307 was never true
308 continue
309 self.by_abbreviation.setdefault(abbreviation, journal)
310 if _distinctive(abbreviation):
311 folded.setdefault(_fold(abbreviation), []).append(journal)
312 if title: 312 ↛ 305line 312 didn't jump to line 305 because the condition on line 312 was always true
313 key = " ".join(title.lower().split())
314 self.by_title.setdefault(key, journal)
315 self.by_title.setdefault(key.removeprefix("the "), journal)
316 self.folded = {key: found[0] for key, found in folded.items() if len(found) == 1}
318 def named(self, text: str) -> tuple[str, str] | None:
319 """``(abbreviation, title)`` of the journal ``text`` names outright, in any spelling."""
320 text = text.strip()
321 alias = JOURNAL_ALIASES.get(text)
322 if alias is not None:
323 journal = self.by_abbreviation.get(alias)
324 return alias, (journal.title or "") if journal is not None else ""
325 journal = (
326 self.by_abbreviation.get(text)
327 or self.folded.get(_fold(text))
328 or self.by_title.get(" ".join(text.lower().split()))
329 )
330 return None if journal is None else (journal.abbreviation or text, journal.title or "")
333class _Thesaurus:
334 """UAT concepts by name, and the words their names are made of."""
336 def __init__(self, concepts: Sequence[UATConcept]) -> None:
337 self.exact: dict[str, UATConcept] = {}
338 self.singular: dict[str, UATConcept] = {}
339 self.words: set[str] = set()
340 ranked = sorted(concepts, key=lambda concept: bool(concept.deprecated))
341 # Preferred names first, so that a name one concept prefers is never taken by another's synonym.
342 for preferred in (True, False):
343 for concept in ranked:
344 for name in [concept.name] if preferred else list(concept.alt_names or ()):
345 if not name: 345 ↛ 346line 345 didn't jump to line 346 because the condition on line 345 was never true
346 continue
347 key = " ".join(name.lower().split())
348 self.exact.setdefault(key, concept)
349 self.singular.setdefault(_singular(key), concept)
350 for word in re.findall(r"[^\W\d_]+", key):
351 self.words.update((word, _singular(word)))
353 def named(self, text: str) -> UATConcept | None:
354 """The concept with this name, ignoring case and a plural ending."""
355 key = " ".join(text.lower().split())
356 return self.exact.get(key) or self.singular.get(_singular(key))
359def _singular(text: str) -> str:
360 """``text`` with a plural ending removed from its last word: enough to match ``black hole(s)``."""
361 if text.endswith("ies") and len(text) > 4:
362 return text[:-3] + "y"
363 if text.endswith("s") and not text.endswith(("ss", "us", "is")) and len(text) > 3:
364 return text[:-1]
365 return text
368_cache: dict[str, tuple[Any, Any]] = {}
371def _cached(name: str, rows: Any, build: Callable[[Any], Any]) -> Any:
372 """``build(rows)``, rebuilt only when the data behind ``rows`` has been reloaded."""
373 held = _cache.get(name)
374 if held is None or held[0] is not rows:
375 held = _cache[name] = (rows, build(rows))
376 return held[1]
379def _journals() -> _Journals:
380 # The rows come from the model's own backend, so they are the ones its queries see.
381 journals: _Journals = _cached("journals", Journal._backend._loader(), _Journals)
382 return journals
385def _thesaurus() -> _Thesaurus | None:
386 """The thesaurus, or ``None`` until it has been downloaded."""
387 try:
388 rows = UATConcept._backend._loader()
389 except DataNotAvailable:
390 return None
391 thesaurus: _Thesaurus = _cached("uat", rows, _Thesaurus)
392 return thesaurus
395# Small readers.
398def _is_name(text: str) -> bool:
399 """Whether ``text`` looks like a surname: capitalised, with lower-case letters, and nothing but letters."""
400 return (
401 text[:1].isupper()
402 and any(c.islower() for c in text)
403 and all(c.isalpha() or c in "-'’" for c in text)
404 and text[-1].isalpha()
405 )
408def _either(word: str) -> Expr:
409 return (Document.author == word) | (Document.abs == word)
412def _identifier(text: str) -> Reading | None:
413 """A bibcode, DOI, arXiv identifier or ORCID iD, or a link to one."""
414 for pattern, read in ((_DOI_URL, _doi), (_ARXIV_URL, _arxiv), (_ORCID_URL, _orcid)):
415 match = pattern.fullmatch(text)
416 if match is not None:
417 return read(text, unquote(match[1]).strip("/"))
418 match = _RECORD_URL.match(text)
419 if match is not None:
420 identifier = unquote(match[1])
421 return _bibcode(text, identifier) or Reading(
422 "identifier", text, identifier, Document.identifier == identifier
423 )
424 if _DOI.fullmatch(text):
425 return _doi(text, text)
426 if _ORCID.fullmatch(text):
427 return _orcid(text, text)
428 return _bibcode(text, text) or _arxiv(text, text)
431def _bibcode(source: str, text: str) -> Reading | None:
432 try:
433 year = int(parse_bibcode(text)["year"])
434 except ValueError:
435 return None
436 if year < FIRST_YEAR: 436 ↛ 437line 436 didn't jump to line 437 because the condition on line 436 was never true
437 return None
438 return Reading("bibcode", source, text, Document.bibcode == text)
441def _doi(source: str, text: str) -> Reading:
442 return Reading("doi", source, text, Document.doi == text)
445def _arxiv(source: str, text: str) -> Reading | None:
446 match = _ARXIV.fullmatch(text)
447 if match is None:
448 return None
449 return Reading("arxiv", source, match[1], Document.arxiv == match[1])
452def _orcid(source: str, text: str) -> Reading:
453 orcid = text.upper()
454 with warnings.catch_warnings():
455 warnings.simplefilter("ignore", QueryWarning)
456 expr = Document.orcid == orcid
457 return Reading("orcid", source, orcid, expr)
460class _Parser:
461 def __init__(self, tokens: list[_Token], today: date) -> None:
462 self.tokens = tokens
463 self.last_year = today.year + 2
464 self.readings: list[Reading] = []
465 self.notes: list[str] = []
466 self.journals = _journals()
467 self.thesaurus = _thesaurus()
469 def run(self) -> None:
470 rules = (
471 self._prefixed,
472 self._quoted,
473 self._identified,
474 self._et_al,
475 self._year_words,
476 self._year,
477 self._journal,
478 self._full_name,
479 self._concept,
480 self._surname_alone,
481 self._word,
482 )
483 position = 0
484 while position < len(self.tokens):
485 for rule in rules: 485 ↛ 484line 485 didn't jump to line 484 because the loop on line 485 didn't complete
486 following = rule(position)
487 if following is not None:
488 position = following
489 break
490 if not self.readings and self.tokens:
491 # Nothing but words like "the": search for them after all.
492 text = " ".join(token.text for token in self.tokens)
493 self._add("text", text, f'"{text}"', Document.abs == text)
494 if self.thesaurus is None and any(reading.kind in ("text", "author or text") for reading in self.readings):
495 self.notes.append(
496 "The Unified Astronomy Thesaurus is not downloaded, so topics are searched as words; "
497 "run `scix --refresh-data` once to have them recognised as concepts."
498 )
500 def _add(self, kind: str, source: str, value: str, expr: Expr, loose: Expr | None = None) -> None:
501 self.readings.append(Reading(kind, source, value, expr, loose))
503 def _plain(self, position: int) -> _Token | None:
504 """The token at ``position`` if it is an ordinary unquoted word."""
505 if position >= len(self.tokens):
506 return None
507 token = self.tokens[position]
508 return None if token.quoted or token.prefix is not None else token
510 def _year_of(self, text: str) -> int | None:
511 if len(text) == 4 and text.isdigit() and FIRST_YEAR <= int(text) <= self.last_year:
512 return int(text)
513 return None
515 def _source(self, start: int, end: int) -> str:
516 return " ".join(
517 ("^" if token.first else "") + token.text + ("," if token.comma and index < end - 1 else "")
518 for index, token in enumerate(self.tokens[start:end], start)
519 )
521 # Rule 1: field:value.
523 def _prefixed(self, position: int) -> int | None:
524 token = self.tokens[position]
525 name, value = token.prefix, token.text
526 if name is None:
527 return None
528 source = f"{name}:{value}"
529 if name in OPERATORS:
530 inner = interpret(value)
531 if inner.expr is None: 531 ↛ 532line 531 didn't jump to line 532 because the condition on line 531 was never true
532 return position + 1
533 operator: Callable[[Expr], Expr] = getattr(Document, name)
534 self._add(name, source, f"of {inner}", operator(inner.expr))
535 self.notes.extend(inner.notes)
536 elif name == "journal":
537 abbreviation, title = self.journals.named(value) or (value, "")
538 self._journal_reading(source, abbreviation, title)
539 elif name == "uat":
540 self._uat(source, value)
541 elif name == "year":
542 if not self._year_reading(source, value):
543 self._add("year", source, value, Document.raw(f"year:{value}"))
544 elif name == "orcid":
545 self.readings.append(_orcid(source, value))
546 else:
547 self._add(_KINDS.get(name, name.replace("_", " ")), source, value, self._field(name, value))
548 return position + 1
550 def _field(self, name: str, value: str) -> Expr:
551 """``Document.<name> == value``, or the same in Solr syntax if the value does not suit the field."""
552 field = Document._fields[name]
553 typed: Any = value
554 try:
555 if isinstance(field, IntegerField):
556 typed = int(value)
557 elif isinstance(field, FloatField): 557 ↛ 558line 557 didn't jump to line 558 because the condition on line 557 was never true
558 typed = float(value)
559 condition: Expr = getattr(Document, name) == typed
560 except (SciXError, TypeError, ValueError):
561 return Document.raw(f"{field.solr_name}:{value}")
562 return condition
564 def _uat(self, source: str, value: str) -> None:
565 if value.isdigit():
566 concept = UATConcept.lookup(value) if self.thesaurus is not None else None
567 name = f"{concept.name} (UAT {value})" if concept is not None else f"UAT {value}"
568 self._add("concept", source, name, Document.uat_concepts == int(value))
569 return
570 concept = self.thesaurus.named(value) if self.thesaurus is not None else None
571 if concept is None:
572 self._add("concept", source, value, Document.uat == value)
573 else:
574 self._concept_reading(source, concept, value)
576 def _concept_reading(self, source: str, concept: UATConcept, typed: str) -> None:
577 expr = Document.uat_concepts == concept
578 self._add("concept", source, f"{concept.name} (UAT {concept.id})", expr, expr | (Document.abs == typed))
580 # Rule 2: quoted phrases.
582 def _quoted(self, position: int) -> int | None:
583 token = self.tokens[position]
584 if not token.quoted:
585 return None
586 text = token.text
587 first = text.startswith("^") # "^Kewley, L": the first author
588 text = text.lstrip("^").strip()
589 if not text:
590 return position + 1
591 reading = _identifier(text)
592 journal = self.journals.named(text) if " " in text else None
593 if reading is not None:
594 self.readings.append(reading)
595 elif (_AUTHOR_PHRASE.fullmatch(text) or (first and _is_name(text))) and text[:1].isupper():
596 self._author(token.text, text, first=first)
597 elif journal is not None:
598 self._journal_reading(text, *journal)
599 else:
600 self._add("text", f'"{text}"', f'"{text}"', Document.abs == text)
601 return position + 1
603 # Rule 3: identifiers.
605 def _identified(self, position: int) -> int | None:
606 reading = _identifier(self.tokens[position].text)
607 if reading is None:
608 return None
609 self.readings.append(reading)
610 return position + 1
612 # "et al." makes the first author named the first author of the paper.
614 def _et_al(self, position: int) -> int | None:
615 token = self.tokens[position]
616 if token.text == "&":
617 return position + 1
618 following = self._plain(position + 1)
619 if token.text.lower() != "et" or following is None or following.text.lower().rstrip(".") != "al":
620 return None
621 for index, reading in enumerate(self.readings): 621 ↛ 628line 621 didn't jump to line 628 because the loop on line 621 didn't complete
622 if reading.kind == "author": 622 ↛ 621line 622 didn't jump to line 621 because the condition on line 622 was always true
623 name = reading.value
624 self.readings[index] = Reading(
625 "first author", f"{reading.source} et al.", name, Document.first_author == name
626 )
627 break
628 return position + 2
630 # Rule 4: years.
632 def _year_words(self, position: int) -> int | None:
633 following = self._plain(position + 1)
634 operator = _YEAR_WORDS.get(self.tokens[position].text.lower())
635 year = self._year_of(following.text) if following is not None else None
636 if operator is None or year is None or following is None:
637 return None
638 source = f"{self.tokens[position].text} {following.text}"
639 if operator == ">=":
640 self._add("year", source, f"{year} or later", Document.year >= year)
641 elif operator == ">":
642 self._add("year", source, f"after {year}", Document.year > year)
643 elif operator == "<":
644 self._add("year", source, f"before {year}", Document.year < year)
645 else:
646 self._add("year", source, f"{year} or earlier", Document.year <= year)
647 return position + 2
649 def _year(self, position: int) -> int | None:
650 text = self.tokens[position].text
651 return position + 1 if self._year_reading(text, text) else None
653 def _year_reading(self, source: str, text: str) -> bool:
654 year = self._year_of(text)
655 if year is not None:
656 self._add("year", source, text, Document.year == year)
657 return True
658 match = _YEAR_RANGE.fullmatch(text)
659 if match is not None:
660 first, last = self._year_of(match[1]), self._year_of(match[2])
661 if first is not None and last is not None and first <= last:
662 self._add("year", source, f"{first}–{last}", Document.year.between(first, last))
663 return True
664 return False
665 match = _YEAR_FROM.fullmatch(text)
666 if match is not None and self._year_of(match[1]) is not None:
667 self._add("year", source, f"{match[1]} or later", Document.year >= int(match[1]))
668 return True
669 match = _YEAR_TO.fullmatch(text)
670 if match is not None and self._year_of(match[1]) is not None:
671 self._add("year", source, f"{match[1]} or earlier", Document.year <= int(match[1]))
672 return True
673 return False
675 # Rule 5: journals, with volume and page.
677 def _is_number(self, position: int) -> bool:
678 token = self._plain(position)
679 return token is not None and token.text.isdigit()
681 def _journal(self, position: int) -> int | None:
682 found = self._journal_at(position)
683 if found is None:
684 return None
685 end, abbreviation, title = found
686 self._journal_reading(self._source(position, end), abbreviation, title)
687 return self._volume_and_page(end)
689 def _journal_at(self, position: int) -> tuple[int, str, str] | None:
690 """``(end, abbreviation, title)`` of the journal named by the words starting at ``position``."""
691 token = self._plain(position)
692 if token is None: 692 ↛ 693line 692 didn't jump to line 693 because the condition on line 692 was never true
693 return None
694 text = token.text
695 numbered = self._is_number(position + 1)
696 volume_follows = numbered and self._year_of(self.tokens[position + 1].text) is None
697 alias = JOURNAL_ALIASES.get(text)
698 if alias is not None:
699 journal = self.journals.by_abbreviation.get(alias)
700 return position + 1, alias, (journal.title or "") if journal is not None else ""
701 # A word that also names a concept ("MHD") is the journal only before a volume: "MHD 12 34".
702 is_concept = self.thesaurus is not None and self.thesaurus.named(text) is not None
703 journal = self.journals.by_abbreviation.get(text)
704 if journal is not None and (volume_follows or (not is_concept and (numbered or _distinctive(text)))):
705 return position + 1, text, journal.title or ""
706 journal = self.journals.folded.get(_fold(text)) if len(text) >= 3 else None
707 if journal is not None and journal.abbreviation and not is_concept and not self._is_topic_word(text):
708 return position + 1, journal.abbreviation, journal.title or ""
709 if not text[:1].isupper():
710 return None
711 # A title of two words or more, written with a capital: "Astrophysical Journal 900 12".
712 run = self._run(position, limit=10)
713 for length in range(len(run), 1, -1):
714 phrase = " ".join(run[:length])
715 journal = self.journals.by_title.get(phrase.lower())
716 if journal is None or not journal.abbreviation:
717 continue
718 is_concept = self.thesaurus is not None and self.thesaurus.named(phrase) is not None
719 following = self._plain(position + length)
720 before_volume = following is not None and following.text.isdigit() and self._year_of(following.text) is None
721 if not is_concept or before_volume:
722 return position + length, journal.abbreviation, journal.title or ""
723 return None
725 def _is_topic_word(self, text: str) -> bool:
726 return self.thesaurus is not None and text.lower() in self.thesaurus.words
728 def _journal_reading(self, source: str, abbreviation: str, title: str) -> None:
729 value = f"{title} ({abbreviation})" if title and title != abbreviation else abbreviation
730 self._add("journal", source, value, Document.journal == abbreviation)
732 def _volume_and_page(self, position: int) -> int:
733 """Read the numbers after a journal: a volume, then a page; a lone year stays a year."""
734 first = self._plain(position)
735 if first is None or not first.text.isdigit():
736 return position
737 second = self._plain(position + 1)
738 third = self._plain(position + 2)
739 has_page = second is not None and _PAGE.fullmatch(second.text) is not None
740 if self._year_of(first.text) is not None:
741 if not has_page:
742 return position # "ApJ 2020": the year rule reads it.
743 if third is not None and second is not None and second.text.isdigit() and _PAGE.fullmatch(third.text): 743 ↛ 747line 743 didn't jump to line 747 because the condition on line 743 was always true
744 # "ApJ 2004 608 119": year, volume, page.
745 self._add("year", first.text, first.text, Document.year == int(first.text))
746 return self._volume_and_page(position + 1)
747 self._add("volume", first.text, first.text, Document.volume == first.text)
748 if not has_page or second is None:
749 return position + 1
750 self._add("page", second.text, second.text, Document.page == second.text)
751 return position + 2
753 # Rules 6 and 8: authors.
755 def _surname(self, position: int) -> tuple[str, int] | None:
756 """``(surname, end)`` of the surname starting at ``position``, with any particles before it."""
757 parts: list[str] = []
758 index = position
759 while True:
760 token = self._plain(index)
761 if token is None: 761 ↛ 762line 761 didn't jump to line 762 because the condition on line 761 was never true
762 return None
763 if token.text.lower() in PARTICLES and not token.comma and self._plain(index + 1) is not None:
764 parts.append(token.text)
765 index += 1
766 continue
767 if not _is_name(token.text):
768 return None
769 parts.append(token.text)
770 return " ".join(parts), index + 1
772 def _given(self, position: int) -> tuple[list[str], int]:
773 """The initials at ``position`` and after it, stopping after one that ends in a comma."""
774 given: list[str] = []
775 while True:
776 token = self._plain(position)
777 if token is None or not _INITIALS.fullmatch(token.text) or self._is_journal_reference(position):
778 return given, position
779 given.append(token.text)
780 position += 1
781 if token.comma:
782 return given, position
784 def _is_journal_reference(self, position: int) -> bool:
785 """Whether the word at ``position`` is a journal with its volume: the ``AJ`` of "AJ 125 525"."""
786 return self._is_number(position + 1) and self._journal_at(position) is not None
788 def _full_name(self, position: int) -> int | None:
789 """``Surname, Initials``, ``Surname, Given`` or ``Initials Surname``."""
790 start = self.tokens[position]
791 if start.quoted or start.prefix is not None: 791 ↛ 792line 791 didn't jump to line 792 because the condition on line 791 was never true
792 return None
793 # Initials first: "L. J. Kewley".
794 if _LEADING_INITIALS.fullmatch(start.text):
795 initials, end = self._leading_initials(position)
796 surname = self._surname(end)
797 if initials and surname is not None: 797 ↛ 801line 797 didn't jump to line 801 because the condition on line 797 was always true
798 name, end = surname
799 self._author(self._source(position, end), f"{name}, {' '.join(initials)}", first=start.first)
800 return end
801 return None
802 surname = self._surname(position)
803 if surname is None:
804 return None
805 name, end = surname
806 if not self.tokens[end - 1].comma:
807 return None
808 given, after = self._given(end)
809 if not given:
810 token = self._plain(end)
811 if token is None or not _is_name(token.text) or self._begins_another_author(end):
812 return None
813 more, after = self._given(end + 1) if not token.comma else ([], end + 1)
814 given = [token.text, *more]
815 self._author(self._source(position, after), f"{name}, {' '.join(given)}", first=start.first)
816 return after
818 def _leading_initials(self, position: int) -> tuple[list[str], int]:
819 initials: list[str] = []
820 while True:
821 token = self._plain(position)
822 if token is None or token.comma or not _LEADING_INITIALS.fullmatch(token.text):
823 return initials, position
824 initials.append(token.text)
825 position += 1
827 def _begins_another_author(self, position: int) -> bool:
828 """Whether the name at ``position`` is the next surname of a list, not a given name."""
829 token, following = self.tokens[position], self._plain(position + 1)
830 if not token.comma or following is None:
831 return False
832 return bool(_INITIALS.fullmatch(following.text)) or _is_name(following.text)
834 def _surname_alone(self, position: int) -> int | None:
835 surname = self._surname(position)
836 if surname is None:
837 return None
838 name, end = surname
839 self._author(self._source(position, end), name, first=self.tokens[position].first, loose=_either(name))
840 return end
842 def _author(self, source: str, name: str, *, first: bool, loose: Expr | None = None) -> None:
843 if first:
844 self._add("first author", source, name, Document.first_author == name)
845 else:
846 self._add("author", source, name, Document.author == name, loose)
848 # Rule 7: UAT concepts.
850 def _run(self, position: int, limit: int) -> list[str]:
851 """The ordinary words from ``position`` on: up to ``limit``, ending at a comma, a year or a phrase."""
852 words: list[str] = []
853 while len(words) < limit: 853 ↛ 860line 853 didn't jump to line 860 because the condition on line 853 was always true
854 token = self._plain(position + len(words))
855 if token is None or token.first or self._year_of(token.text) is not None:
856 break
857 words.append(token.text)
858 if token.comma:
859 break
860 return words
862 def _concept(self, position: int) -> int | None:
863 if self.thesaurus is None:
864 return None
865 run = self._run(position, limit=9)
866 for length in range(len(run), 0, -1):
867 phrase = " ".join(run[:length])
868 if length == 1 and (len(phrase) < 3 or phrase.lower() in STOPWORDS or phrase.lower() in PARTICLES):
869 break
870 concept = self.thesaurus.named(phrase)
871 if concept is not None:
872 self._concept_reading(self._source(position, position + length), concept, phrase)
873 return position + length
874 return None
876 # Rule 9: words.
878 def _word(self, position: int) -> int:
879 text = self.tokens[position].text
880 if text.lower() in STOPWORDS:
881 return position + 1
882 if text.lower() == "refereed":
883 self._add("property", text, "refereed", Document.property == "refereed")
884 return position + 1
885 if text.isalpha() and text.islower() and len(text) > 1 and not self._is_topic_word(text):
886 self._add("author or text", text, text, _either(text))
887 else:
888 self._add("text", text, text, Document.abs == text)
889 return position + 1