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

SkipEntry

a format, from to_csl_json

Recognised, not a bibliographic record. Becomes SKIPPED

EntryError

a format, from parse or to_csl_json

This entry is bad. Becomes FAILED with its reason

ParseError

a format, from parse

The file cannot be read at all. Becomes a one-entry failed result

UnknownFormat

get_format

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: ABC

A plug-in for one bibliographic file syntax, such as BibTeX or RIS.

Named under name and reachable through get_format() once listed in the LITERATURE setting. A subclass supplies parse() and to_csl_json(), and optionally handle_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 is specs/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 CREATED result.

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 FAILED result.

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 SKIPPED result.

get_result(entries: list[EntryResult], *, dry_run: bool) → ImportResult[source]#

Build the ImportResult for a run.

The one place a subclass can filter, reorder or annotate entries without 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 None by 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 file into 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() returning str or bytes. 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.

label: ClassVar[str | Promise]#

The human-readable label, which may be a lazy translation.

name: ClassVar[str]#

The name a caller runs an import under, and the key the LITERATURE setting 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 SkipEntry for an element that is recognised but is not a bibliographic record, and EntryError for an entry that is bad. A ValidationError may also escape, whether raised here or by from_csl_json once import_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: BibFormat

Reads .bib files, 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 None for 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 LITERATURE setting resolves. Machine-facing, so never translated.

parse(file) → Iterator[dict[str, Any] | _NonRecord][source]#

Yield the file’s entries in source order, then its preambles and comments.

to_csl_json(raw: dict[str, Any] | _NonRecord) → dict[str, Any][source]#

Turn one parsed entry into CSL JSON, or skip a comment or preamble.

exception EntryError[source]#

Bases: ImporterError

An entry that cannot be imported, for the reason given.

Raised from a format’s parse or to_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: object

The 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. None when it does not.

  • item (object | None) – The stored Item, on a real run that created one. None for 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 for SKIPPED, and refused for CREATED.

Raises:

ValueError – If a failure carries no reason, or a created entry carries one.

handle: str | None = None#
index: int#
item: object | None = None#
outcome: Outcome#
reason: str | None = None#
class ImportResult(entries: list[EntryResult] = <factory>, dry_run: bool = False, format_name: str | None = None)[source]#

Bases: object

The 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.

dry_run: bool = False#
entries: list[EntryResult]#
property failed#

Entries that could not be stored, each carrying its reason.

format_name: str | None = None#
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: Exception

Root of every exception raised by the import contract.

SkipEntry, EntryError and ParseError are how a format signals one entry or one file to its own workflow, which turns each into an outcome. None reaches the caller of import_file(). UnknownFormat is programmer error, so it does. They sit on separate branches so a caller’s except around an import cannot swallow an entry-level signal.

class Outcome(*values)[source]#

Bases: TextChoices

What 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: ImporterError

The file cannot be read at all.

Raised from a format’s parse when 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: object

One RIS entry recovered from a file.

tags is a sequence of pairs rather than a dict, because a repeatable tag such as AU or KW appears more than once (RISParser.REPEATABLE_TAGS).

Variables:
  • tags (tuple[tuple[str, str], ...]) – The entry’s (tag, value) pairs, in source order.

  • index (int) – The entry’s position among those the parser yielded.

  • start_line (int) – The line the entry’s opening TY tag was found on.

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.

index: int#
start_line: int#
tags: tuple[tuple[str, str], ...]#
values(tag: str) → list[str][source]#

Return every value this entry carries under tag.

Parameters:

tag – A two-character RIS tag.

Returns:

The values, unstripped, in source order.

class RISFormat[source]#

Bases: BibFormat

Reads .ris files, 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 ID or 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 None for header material.

label: ClassVar[str | Promise] = 'RIS'#

The human-readable label, which may be a lazy translation.

name: ClassVar[str] = 'ris'#

The name a caller runs an import under, and the key the LITERATURE setting 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 TY is 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 – raw is header material, or the entry carries only TY.

  • EntryError – The entry has no TY tag, or its citation key is longer than the catalogue allows. Either fails this entry alone.

class RISParser[source]#

Bases: object

Reads one .ris file into RISEntry objects, 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 rispy silently 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 TY tag is yielded once, as a plain str, just before the first entry, and RISFormat.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 a str if 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: ImporterError

An element that is recognised but is not a bibliographic record.

Raised from a format’s to_csl_json for things like a BibTeX @comment or 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: ImporterError

No 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)