literature.importers#
The plug-in contract for importing bibliographic files. Every BibFormat runs through the same
fixed workflow and returns one outcome per entry the file contained. How to run an import is in
Import a bibliography file in code,
and how to add a format is in Add an import format.
Which formats an installation can read is the BIB_FORMATS key of the
LITERATURE setting.
Discovering the configured formats#
from literature.importers import available_formats, get_format
from literature.importers.exceptions import UnknownFormat
for name, format_class in available_formats().items():
print(name, "—", format_class.label)
try:
get_format("bibtex")
except UnknownFormat as exc:
print(exc) # "No import format named 'bibtex'. No import formats are configured."
Exceptions#
Exception |
Raised by |
Meaning |
|---|---|---|
|
a format, from |
Recognised, not a bibliographic record. Becomes |
|
a format, from |
This entry is bad. Becomes |
|
a format, from |
The file cannot be read at all. Becomes a one-entry failed result |
|
|
The name is not configured. Message lists the names that are. Reaches the caller |
SkipEntry, EntryError and ParseError are the format’s vocabulary for talking to the workflow
and never reach the caller. UnknownFormat is the caller’s problem and does.
Reference#
Reading bibliographic files into the catalogue: the import contract’s public names (FS-003).
- class BibFormat[source]#
Bases:
ABCA plug-in for one bibliographic file syntax, such as BibTeX or RIS.
Named under
nameand reachable throughget_format()once listed in theLITERATUREsetting. A subclass suppliesparse()andto_csl_json(), and optionallyhandle_for(). Every other method drives the workflow those stages plug into and may be overridden; the base class does not police what a subclass does with them. The full contract isspecs/003-import-contract/contracts/importers.md.- entry_created(*, index: int, handle: str | None, item: Any, dry_run: bool) EntryResult[source]#
Report one entry as stored.
- Parameters:
index – The entry’s zero-based position in the file.
handle – The entry’s handle, if it has one.
item – The stored
Item. Dropped from the report on a dry run, since its rows are about to be rolled back.dry_run – Whether this is a dry run.
- Returns:
A
CREATEDresult.
- entry_failed(*, index: int, handle: str | None, reason: str) EntryResult[source]#
Report one entry as unable to be stored, with the reason why.
- Parameters:
index – The entry’s zero-based position in the file.
handle – The entry’s handle, if it has one.
reason – Why the entry failed, for whoever fixes the source file.
- Returns:
A
FAILEDresult.
- entry_skipped(*, index: int, handle: str | None, reason: str | None = None) EntryResult[source]#
Report one entry as recognised but not a bibliographic record.
- Parameters:
index – The entry’s zero-based position in the file.
handle – The entry’s handle, if it has one.
reason – What was skipped, when the format knows. Optional, so a format is never required to invent one.
- Returns:
A
SKIPPEDresult.
- get_result(entries: list[EntryResult], *, dry_run: bool) ImportResult[source]#
Build the
ImportResultfor a run.The one place a subclass can filter, reorder or annotate
entrieswithout touching how any single entry was imported.- Parameters:
entries – Every entry’s result, in source order.
dry_run – Whether this is a dry run.
- Returns:
The run’s report.
- handle_for(raw: Any) str | None[source]#
Return the source’s own name for this entry, where the syntax has one.
A BibTeX cite key, an RIS record number. Not every syntax has one, and requiring it would push formats into inventing identifiers.
- Parameters:
raw – One entry
parse()yielded.- Returns:
The handle, or
Noneby default.
- import_entries(entries: Iterator[Any], *, dry_run: bool) list[EntryResult][source]#
Import each raw entry, consuming the iterator one entry at a time.
Assigns each entry its zero-based index and delegates the rest to
import_entry(). A failure raised by the iterator itself ends the file: the entries already recovered are kept, and the failure is recorded against the index the iterator stopped at.- Parameters:
entries – The raw entries, as
parse()yields them.dry_run – Whether this is a dry run.
- Returns:
One result per entry, in source order.
- import_entry(raw: Any, index: int, *, dry_run: bool) EntryResult[source]#
Import one raw entry inside its own savepoint.
Never raises. Anything
handle_for(),to_csl_json()or the storing stage raises becomes this entry’s outcome, never a whole-file failure and never an exception the caller has to catch.- Parameters:
raw – One entry
parse()yielded.index – The entry’s zero-based position in the file.
dry_run – Whether this is a dry run.
- Returns:
The entry’s result.
- import_file(file: Any, *, dry_run: bool = False) ImportResult[source]#
Import every entry this format finds in
fileinto the catalogue.The one documented way to run an import, identical for every format unless a subclass overrides a step. Never raises for bad file content: a file that cannot be parsed at all comes back as a result whose single entry failed, with the parser’s reason.
- Parameters:
file – An open file object in text or binary mode, or anything with a
read()returningstrorbytes. Never opened as a path and never decoded here, since decoding is the format’s job (docs/adr/0012-a-format-owns-its-own-decoding.md).dry_run – Run every stage and report every outcome, then roll the catalogue back to exactly how it was.
- Returns:
The run’s report, with one entry result per entry this format found, in source order.
- name: ClassVar[str]#
The name a caller runs an import under, and the key the
LITERATUREsetting resolves. Machine-facing, so never translated.
- abstractmethod parse(file) Iterator[Any][source]#
Yield the raw entries in
file, one at a time, in source order.An iterator, not a list, so a caller can consume entries without the whole file being converted first. Each entry is in whatever shape
to_csl_json()accepts.- Parameters:
file – The handle passed to
import_file().- Yields:
One raw entry at a time.
- Raises:
ParseError – The file cannot be read at all.
- abstractmethod to_csl_json(raw: Any) dict[str, Any][source]#
Turn one raw entry into a CSL JSON dict.
An implementation raises
SkipEntryfor an element that is recognised but is not a bibliographic record, andEntryErrorfor an entry that is bad. AValidationErrormay also escape, whether raised here or byfrom_csl_jsononceimport_entry()stores the returned dict.- Parameters:
raw – One entry
parse()yielded.- Returns:
The entry as CSL JSON.
- Raises:
NotImplementedError – The format does not implement this stage.
- class BibTeXFormat[source]#
Bases:
BibFormatReads
.bibfiles, in either the classic or the BibLaTeX dialect.- handle_for(raw: dict[str, Any] | _NonRecord) str | None[source]#
Return the cite key, which is what a reader will search for.
- Parameters:
raw – A parsed entry dict, or a
_NonRecord.- Returns:
The cite key, or
Nonefor a comment or preamble.
- label: ClassVar[str | Promise] = 'BibTeX'#
The human-readable label, which may be a lazy translation.
- name: ClassVar[str] = 'bibtex'#
The name a caller runs an import under, and the key the
LITERATUREsetting resolves. Machine-facing, so never translated.
- exception EntryError[source]#
Bases:
ImporterErrorAn entry that cannot be imported, for the reason given.
Raised from a format’s
parseorto_csl_json. The message becomes the entry result’s reason, so it is read by whoever has to fix the source file and should say what is wrong with the entry.
- class EntryResult(outcome: Outcome, index: int, handle: str | None = None, item: object | None = None, reason: str | None = None)[source]#
Bases:
objectThe fate of a single entry.
- Variables:
outcome (literature.importers.results.Outcome) – What became of the entry.
index (int) – Zero-based position among the entries the format found. Always present, and assigned by the runner rather than the format.
handle (str | None) – The source’s own name for this entry — a BibTeX cite key, an RIS record number — where the syntax has one.
Nonewhen it does not.item (object | None) – The stored
Item, on a real run that created one.Nonefor skipped and failed entries, and for every entry of a dry run, whose rows do not survive the transaction that made them.reason (str | None) – Why the entry failed, or what was recognised but not stored for a skipped entry. Required for
FAILED, optional forSKIPPED, and refused forCREATED.
- Raises:
ValueError – If a failure carries no reason, or a created entry carries one.
- class ImportResult(entries: list[EntryResult] = <factory>, dry_run: bool = False, format_name: str | None = None)[source]#
Bases:
objectThe report from one import run.
A caller learns what happened to every entry by reading this object, never by comparing input counts with stored items or reading the log.
- Variables:
entries (list[literature.importers.results.EntryResult]) – One result per entry the format found, in the order they occur in the source file, each appearing exactly once.
dry_run (bool) – Whether this run was a rehearsal that wrote nothing.
format_name (str | None) – The registered name used, when the import was run by name.
- property created#
Entries that became items.
- entries: list[EntryResult]#
- property failed#
Entries that could not be stored, each carrying its reason.
- property ok#
True when nothing failed. An import of an empty file is ok.
- property skipped#
Elements the format recognised but that are not bibliographic records.
- exception ImporterError[source]#
Bases:
ExceptionRoot of every exception raised by the import contract.
SkipEntry,EntryErrorandParseErrorare how a format signals one entry or one file to its own workflow, which turns each into an outcome. None reaches the caller ofimport_file().UnknownFormatis programmer error, so it does. They sit on separate branches so a caller’sexceptaround an import cannot swallow an entry-level signal.
- class Outcome(*values)[source]#
Bases:
TextChoicesWhat became of one entry.
There is deliberately no “updated”: matching an entry to a record already stored is a separate problem, and a value nothing can produce is speculation. A later feature that makes that judgement reports it as
SKIPPED.- CREATED = 'created'#
- FAILED = 'failed'#
- SKIPPED = 'skipped'#
- exception ParseError[source]#
Bases:
ImporterErrorThe file cannot be read at all.
Raised from a format’s
parsewhen nothing useful can be recovered — the file is not in this format, is truncated beyond recovery, or is in an unreadable encoding. The runner reports it as a single failed entry rather than letting it escape.
- class RISEntry(tags: tuple[tuple[str, str], ...], index: int, start_line: int)[source]#
Bases:
objectOne RIS entry recovered from a file.
tagsis a sequence of pairs rather than a dict, because a repeatable tag such asAUorKWappears more than once (RISParser.REPEATABLE_TAGS).- Variables:
- first(tag: str) str[source]#
Return this entry’s first value under
tag, stripped.A tag with a blank value reads the same as an absent one, since whitespace is nothing to store. Use
values()for the unstripped text or every value.- Parameters:
tag – A two-character RIS tag.
- Returns:
The first value, or
""where the entry carries none.
- class RISFormat[source]#
Bases:
BibFormatReads
.risfiles, from EndNote, Web of Science and Scopus alike.Every tag is read by the tag itself, never by which tool wrote the file, so there is no producer detection.
- entry_created(*, index: int, handle: str | None, item: Any, dry_run: bool) EntryResult[source]#
Report the key as stored, read off the item, which arrives on a dry run too.
- handle_for(raw: RISEntry | str) str | None[source]#
Return the citation key this entry will carry, stated in
IDor minted.entry_created()reports a stored entry under its key as stored, so this is the handle only a failed or skipped entry keeps.- Parameters:
raw – An entry, or header text.
- Returns:
The citation key, or
Nonefor header material.
- name: ClassVar[str] = 'ris'#
The name a caller runs an import under, and the key the
LITERATUREsetting resolves. Machine-facing, so never translated.
- parse(file) Iterator[RISEntry | str][source]#
Yield this file’s raw entries, delegating to
RISParser.parse().
- to_csl_json(raw: RISEntry | str) dict[str, Any][source]#
Turn one raw entry into CSL JSON.
An entry carrying only
TYis skipped rather than stored as a near-empty item. The check is on which tags are present, so a second tag with an empty value still counts.- Parameters:
raw – An entry, or the header text
RISParser.parse()yields.- Returns:
The entry as CSL JSON.
- Raises:
SkipEntry –
rawis header material, or the entry carries onlyTY.EntryError – The entry has no
TYtag, or its citation key is longer than the catalogue allows. Either fails this entry alone.
- class RISParser[source]#
Bases:
objectReads one
.risfile intoRISEntryobjects, one at a time.A generator, so a caller can consume one entry from a large file and leave the rest unread. Accepts a binary or a text handle. Bytes are decoded here as
utf-8-sig, so a byte-order mark is absorbed rather than becoming part of the first tag’s value, and a decoding failure can name the encoding and byte offset. A text handle passes through unchanged.The parser is hand-rolled because
rispysilently resynchronises past a malformed entry, where the import contract reports what happened to every entry (docs/adr/0011-the-ris-parser-is-hand-rolled.md).- REPEATABLE_TAGS: ClassVar[frozenset[str]] = frozenset({'A1', 'A2', 'A3', 'A4', 'AU', 'ED', 'KW', 'N1', 'SN', 'UR'})#
After one of these tags an untagged line is another value. After any other tag it continues the previous value, joined with a space. Repeatability is RIS syntax, so it lives on the parser rather than the mapping tables.
- parse(file) Iterator[RISEntry | str][source]#
Yield this file’s entries, one at a time, in source order.
Header material before the first
TYtag is yielded once, as a plainstr, just before the first entry, andRISFormat.to_csl_json()skips it. A file with no header yields no such string.An empty or whitespace-only file yields nothing.
- Parameters:
file – A binary or text handle.
- Yields:
Each
RISEntry, preceded once by the header text as astrif the file has one.- Raises:
ParseError – The file cannot be decoded, carries RIS tag lines but no
TY, or carries no tag lines at all.
- exception SkipEntry[source]#
Bases:
ImporterErrorAn element that is recognised but is not a bibliographic record.
Raised from a format’s
to_csl_jsonfor things like a BibTeX@commentor an RIS header line. Nothing is stored and nothing is wrong, so the entry is reported as skipped rather than failed. The message is optional, since skipping is not an error that needs explaining.
- exception UnknownFormat(name, available=())[source]#
Bases:
ImporterErrorNo format is configured under the requested name.
The message names the formats that are configured, because the useful reply to “bibtex is not a format” is the list of things that are.
- Parameters:
name – The requested format name.
available – The configured format names.
- available_formats() MappingProxyType[source]#
Return every configured format, keyed by name.
LITERATURE = {"BIB_FORMATS": [...]}lists dotted import paths. They are resolved on first read and cached, so nothing runs before the app registry is ready and enumerating twice does not re-import every module. The mapping is read-only: nothing but a setting change can alter it.- Returns:
A read-only mapping of name to format class.
- get_format(name: str) type[BibFormat][source]#
Return the format configured under
name.- Parameters:
name – The format’s registered name, such as
"bibtex".- Returns:
The format class.
- Raises:
UnknownFormat – Nothing is configured under
name. The message names the formats that are.
Example
from literature.importers import get_format with open("library.bib") as handle: result = get_format("bibtex")().import_file(handle) for entry in result.failed: print(entry.index, entry.handle, entry.reason)