Source code for literature.converters

"""CSL JSON serialization and deserialization between ``Item`` instances and CSL JSON 1.0.2 dicts."""

from __future__ import annotations

import logging
from typing import Any

from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
from partial_dates import PartialDate

from literature.choices import DateType, IdentifierType, ItemType, NameRole
from literature.utils import parse_date_parts
from literature.validators import normalize_doi, normalize_issn

logger = logging.getLogger(__name__)

# Django field name → CSL JSON key, for fields that don't follow the default
# snake_case → hyphen-case pattern.
_DJANGO_TO_CSL: dict[str, str] = {
    "citation_key": "citation-key",  # exported as both "citation-key" and "id"
    "title_short": "title-short",
    "original_title": "original-title",
    "container_title": "container-title",
    "container_title_short": "container-title-short",
    "collection_title": "collection-title",
    "volume_title": "volume-title",
    "volume_title_short": "volume-title-short",
    "part_title": "part-title",
    "reviewed_title": "reviewed-title",
    "reviewed_genre": "reviewed-genre",
    "publisher_place": "publisher-place",
    "original_publisher": "original-publisher",
    "original_publisher_place": "original-publisher-place",
    "event_title": "event-title",
    "event_place": "event-place",
    "page_first": "page-first",
    "number_of_pages": "number-of-pages",
    "number_of_volumes": "number-of-volumes",
    "chapter_number": "chapter-number",
    "collection_number": "collection-number",
    "call_number": "call-number",
    "archive_place": "archive-place",
    # CSL JSON uses underscores for these two
    "archive_collection": "archive_collection",
    "archive_location": "archive_location",
    "journal_abbreviation": "journalAbbreviation",
}

_CSL_TO_DJANGO: dict[str, str] = {v: k for k, v in _DJANGO_TO_CSL.items()}
_CSL_TO_DJANGO.update(
    {
        "id": "citation_key",
        "shortTitle": "title_short",  # deprecated CSL key
        "event": "event_title",  # deprecated CSL key
    }
)

_SKIP_FIELDS = frozenset(
    {
        "id",
        "citation_key",
        "type",
        "categories",
        "custom",
        "created",
        "modified",
        *[r.value for r in NameRole],
        *[d.value for d in DateType],
        *[i.value for i in IdentifierType],
    }
)

_KNOWN_IDENTIFIER_TYPES = frozenset(i.value for i in IdentifierType)
_NAME_VARIABLE_KEYS = frozenset(r.value for r in NameRole)
_DATE_VARIABLE_KEYS = frozenset(d.value for d in DateType)


def _csl_key_to_django_field(csl_key: str) -> str | None:
    """Convert a CSL JSON field name to the corresponding Django model field name.

    Args:
        csl_key: The CSL JSON field name to convert.

    Returns:
        The Django field name, or None if the key should not be mapped to a
        scalar Item field.
    """
    if csl_key in _CSL_TO_DJANGO:
        return _CSL_TO_DJANGO[csl_key]
    candidate = csl_key.replace("-", "_")
    return candidate


def _django_field_to_csl_key(field_name: str) -> str:
    """Convert a Django model field name to its CSL JSON key.

    Args:
        field_name: The Django model field name to convert.

    Returns:
        The corresponding CSL JSON key.
    """
    if field_name in _DJANGO_TO_CSL:
        return _DJANGO_TO_CSL[field_name]
    return field_name.replace("_", "-")


def _partial_date_to_parts(pd: PartialDate) -> list[int]:
    """Convert a PartialDate to a CSL JSON date-parts single array.

    Args:
        pd: The PartialDate to convert.

    Returns:
        1-3 integers based on the PartialDate's precision: ``[year]``,
        ``[year, month]``, or ``[year, month, day]``.
    """
    return [part for part in (pd.year, pd.month, pd.day) if part is not None]


def _name_to_dict(name: Any) -> dict[str, Any]:
    """Convert a Name instance to a CSL JSON name object (omitting empty fields).

    Args:
        name: The Name instance to convert.

    Returns:
        The CSL JSON name object.
    """
    result: dict[str, Any] = {}
    if name.family:
        result["family"] = name.family
    if name.given:
        result["given"] = name.given
    if name.dropping_particle:
        result["dropping-particle"] = name.dropping_particle
    if name.non_dropping_particle:
        result["non-dropping-particle"] = name.non_dropping_particle
    if name.suffix:
        result["suffix"] = name.suffix
    if name.literal:
        result["literal"] = name.literal
    if name.comma_suffix:
        result["comma-suffix"] = name.comma_suffix
    if name.static_ordering:
        result["static-ordering"] = name.static_ordering
    if name.parse_names:
        result["parse-names"] = name.parse_names
    return result


[docs] def to_csl_json(item: Any) -> dict[str, Any]: """Serialize a saved Item instance to a CSL JSON 1.0.2 compatible dict. Args: item: A saved ``Item`` model instance (must have a primary key). Returns: A dict conforming to the CSL JSON 1.0.2 schema. Always contains ``"id"`` (= ``item.citation_key``) and ``"type"``, omits blank/null optional fields, orders name arrays by ``ItemName.order`` within each role, places known identifier types (DOI, ISBN, ISSN, PMID, PMCID, URL) as top-level keys and unknown types under ``custom``, and exports string-or-number CSL fields always as strings. """ from literature.models import ItemName result: dict[str, Any] = { "id": item.citation_key, "type": item.type, } scalar_skip = { "id", "pk", "citation_key", "type", "categories", "custom", "created", "modified", } for field in item._meta.get_fields(): if not hasattr(field, "attname"): continue fname = field.name if fname in scalar_skip: continue value = getattr(item, fname, None) if value is None or value == "" or value is False: continue csl_key = _django_field_to_csl_key(fname) result[csl_key] = value if item.categories: result["categories"] = item.categories _custom: dict[str, Any] = {} if item.custom: _custom.update(item.custom) for ident in item.item_identifiers.all(): if ident.type in _KNOWN_IDENTIFIER_TYPES: result[ident.type] = ident.value else: _custom[ident.type] = ident.value if _custom: result["custom"] = _custom from literature.models import ItemName # noqa: F811 roles_present: dict[str, list[dict]] = {} for item_name in ItemName.objects.filter(item=item).order_by("role", "order"): role = item_name.role name_dict = _name_to_dict(item_name.name) if name_dict: roles_present.setdefault(role, []).append(name_dict) result.update(roles_present) for item_date in item.item_dates.all(): date_obj: dict[str, Any] = {} if item_date.begin is not None: parts = [_partial_date_to_parts(item_date.begin)] if item_date.end is not None: parts.append(_partial_date_to_parts(item_date.end)) date_obj["date-parts"] = parts elif item_date.raw_date_parts: date_obj["date-parts"] = item_date.raw_date_parts if item_date.literal: date_obj["literal"] = item_date.literal if item_date.season: date_obj["season"] = item_date.season if item_date.circa: date_obj["circa"] = item_date.circa if date_obj: result[item_date.date_type] = date_obj return result
def _citation_key(data: dict) -> str: """Return the citation key a CSL JSON dict carries: ``citation-key``, falling back to ``id``. Stored exactly as given, whether or not the store already holds it (docs/adr/0023-citation-key-uniqueness-is-the-readers-concern.md). Args: data: The CSL JSON item dict to read a citation key from. Returns: The citation key. Raises: ValidationError: Both ``citation-key`` and ``id`` are absent or empty. """ raw_key = data.get("citation-key") or str(data.get("id", "")) if not raw_key: raise ValidationError( _("CSL JSON item missing both 'citation-key' and 'id' fields") ) return raw_key def _import_name_variable(data: dict, item: Any, role: str, order: int) -> bool: """Create or get a Name and link it to item with the given role and order. Args: data: A CSL JSON name object, or a plain string stored as ``literal``. item: The Item to link the name to. role: The CSL name-variable role (e.g. ``author``, ``editor``). order: The name's position within its role. Returns: ``True`` if the name was linked, ``False`` if the item already lists this name under this role and nothing was added. """ from literature.models import ItemName, Name name_data = {"literal": data} if isinstance(data, str) else data family = name_data.get("family", "") given = name_data.get("given", "") literal = name_data.get("literal", "") dropping_particle = name_data.get("dropping-particle", "") non_dropping_particle = name_data.get("non-dropping-particle", "") suffix = name_data.get("suffix", "") name, _ = Name.objects.get_or_create( family=family, given=given, literal=literal, dropping_particle=dropping_particle, non_dropping_particle=non_dropping_particle, suffix=suffix, defaults={ "comma_suffix": name_data.get("comma-suffix", False), "static_ordering": name_data.get("static-ordering", False), "parse_names": name_data.get("parse-names", False), }, ) name.full_clean() if ItemName.objects.filter(item=item, role=role, name=name).exists(): return False item_name = ItemName(item=item, name=name, role=role, order=order) item_name.full_clean() item_name.save() return True def _import_date_variable(data: dict, item: Any, date_type: str) -> None: """Create an ItemDate record from a CSL JSON date-variable object. Args: data: A CSL JSON date-variable object (e.g. the value of ``issued``). item: The Item to attach the date to. date_type: The CSL date-variable slot (e.g. ``issued``, ``accessed``). """ from literature.models import ItemDate date_parts = data.get("date-parts", []) begin = None end = None raw_date_parts_fallback = None if date_parts: begin_parts = date_parts[0] if len(date_parts) >= 1 else [] end_parts = date_parts[1] if len(date_parts) >= 2 else [] begin = parse_date_parts(begin_parts) if begin is None and begin_parts: raw_date_parts_fallback = date_parts if end_parts: end = parse_date_parts(end_parts) item_date = ItemDate( item=item, date_type=date_type, begin=begin, end=end, season=data.get("season", ""), circa=bool(data.get("circa", False)), literal=data.get("literal", "") or "", raw=data.get("raw", "") or "", raw_date_parts=raw_date_parts_fallback, ) item_date.full_clean() item_date.save()
[docs] def from_csl_json(data: dict, *, pk: int | None = None) -> Any: """Deserialize a CSL JSON dict into a new saved Item with all related records. Validates ``type``, reads the citation key (``citation-key`` falling back to ``id``, stored exactly as given; a key the store already holds is not rewritten, per docs/adr/0023-citation-key-uniqueness-is-the-readers-concern.md), maps scalar fields, and creates the related Name/ItemName, ItemDate and ItemIdentifier records. Every model instance is validated with ``full_clean()`` before saving. Args: data: A Python dict containing CSL JSON data for a single bibliographic item. pk: The primary key to give the new ``Item``, when it has to keep one it already had elsewhere, as ``upgrade_literature`` does. Left out, the database assigns one. Returns: A saved ``Item`` instance with all related ``ItemName``, ``ItemDate``, and ``ItemIdentifier`` records created. Raises: ValidationError: ``data["type"]`` is missing or not a recognized CSL type, or both ``data["citation-key"]`` and ``data["id"]`` are absent. """ from literature.models import Item, ItemIdentifier csl_type = data.get("type") if not csl_type: raise ValidationError(_("CSL JSON item missing required 'type' field")) if csl_type not in ItemType.values: raise ValidationError( _("Unknown CSL JSON item type: '{type}'").format(type=csl_type) ) citation_key = _citation_key(data) item_fields: dict[str, Any] = { "citation_key": citation_key, "type": csl_type, } non_scalar = ( _NAME_VARIABLE_KEYS | _DATE_VARIABLE_KEYS | _KNOWN_IDENTIFIER_TYPES | {"type", "citation-key", "id", "shortTitle", "event"} ) from literature.models import Item # noqa: F811 valid_item_fields = { f.name for f in Item._meta.get_fields() if hasattr(f, "attname") } for csl_key, value in data.items(): if csl_key in non_scalar: continue if csl_key in ("categories", "custom"): item_fields[csl_key] = value continue django_field = _csl_key_to_django_field(csl_key) if django_field and django_field in valid_item_fields: if isinstance(value, (int, float)) and django_field not in ( "categories", "custom", ): value = str(value) item_fields[django_field] = value if "shortTitle" in data and "title_short" not in item_fields: item_fields["title_short"] = data["shortTitle"] if "event" in data and "event_title" not in item_fields: item_fields["event_title"] = data["event"] item = Item(pk=pk, **item_fields) item.full_clean() item.save() for role_key in _NAME_VARIABLE_KEYS: names_data = data.get(role_key, []) order = 0 for name_data in names_data: if _import_name_variable(name_data, item, role_key, order): order += 1 for date_key in _DATE_VARIABLE_KEYS: date_data = data.get(date_key) if date_data is not None: _import_date_variable(date_data, item, date_key) for id_type in _KNOWN_IDENTIFIER_TYPES: value = data.get(id_type) if value: text = str(value) if id_type == IdentifierType.DOI: text = normalize_doi(text) elif id_type == IdentifierType.ISSN: text = normalize_issn(text) ident = ItemIdentifier(item=item, type=id_type, value=text) ident.full_clean() ident.save() custom_data = data.get("custom") or {} if isinstance(custom_data, dict): for key, value in custom_data.items(): if key not in _KNOWN_IDENTIFIER_TYPES and isinstance(value, str): logger.warning( "Unknown identifier type '%s' for item '%s'", key, citation_key ) ident = ItemIdentifier(item=item, type=key, value=value) ident.full_clean() ident.save() return item
[docs] def from_csl_json_list(data: list[dict]) -> list[Any]: """Import a list of CSL JSON dicts, skipping invalid items with warnings. Calls :func:`from_csl_json` for each item in the list. Items that fail validation are skipped and their errors are logged via ``logger.warning()`` rather than raised. Args: data: A Python list of CSL JSON dicts (one per bibliographic item). Returns: The saved ``Item`` instances for all successfully imported items, in input order. """ results = [] for item_data in data: try: item = from_csl_json(item_data) results.append(item) except ValidationError as exc: logger.warning("Skipping invalid CSL JSON item: %s", exc) return results