File size: 1,259 Bytes
e1e2e3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"""Canonical JSON representation for model-facing text units."""

from __future__ import annotations

import json


def load_text_units(encoded: str) -> list[str]:
    """Load a published text field and enforce a non-empty string list."""
    units = json.loads(encoded)
    if not isinstance(units, list) or not units:
        raise ValueError("text must encode a non-empty JSON list")
    if not all(isinstance(unit, str) and unit.strip() for unit in units):
        raise ValueError("every text unit must be a non-empty string")
    return units


def source_text_units(value: str) -> list[str]:
    """Accept either an internal atomic string or published JSON text units."""
    try:
        return load_text_units(value)
    except (json.JSONDecodeError, TypeError, ValueError):
        if not isinstance(value, str) or not value.strip():
            raise ValueError("source text must be a non-empty string")
        return [value]


def encode_text_units(units: list[str]) -> str:
    """Serialize text units without losing their original strings."""
    if not units or not all(isinstance(unit, str) and unit.strip() for unit in units):
        raise ValueError("text units must be non-empty strings")
    return json.dumps(units, ensure_ascii=False)