Python
API reference
Everything is imported from greek_conversion. Options are those of Conversion options, with their keys in snake_case.
Conversion
Section titled “Conversion”Each function takes options as a dictionary, as keyword arguments, or both, or prepared options; each _many form takes a list of strings and gives back a list, in one call into the engine.
convert()
Section titled “convert()”def convert( text: str, source: Format, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> strConverts text between Greek, Beta Code, and transliteration.
Unknown characters are kept. The output is canonical; a reverse
conversion is not necessarily lossless: use convert_detailed() when
that matters.
>>> convert("ἄνδρα μοι ἔννεπε", "greek", "beta-code")'a)/ndra moi e)/nnepe'>>> convert("a)/ndra", "beta-code", "greek")'ἄνδρα'>>> convert("Θεσσαλονίκη", "greek", "transliteration",... preset="iso-843-type-2")'Thessaloníki'>>> convert("ψυχή", "greek", "transliteration",... transliteration={"chi": "kh", "upsilon": "u"})'psukhḗ'- Raises
TypeError: iftextis not a string. - Raises
ValueError: if a format is unknown;OptionErrorif a preset, an option key, or an option value is.
convert_many()
Section titled “convert_many()”def convert_many( texts: Iterable[str], source: Format, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> list[str]Converts many strings in one call into the engine, as convert()
converts each: the fixed cost of a call is paid once. The fastest way to
convert the lines of a corpus or the cells of a column.
>>> convert_many(["λόγος", "ψυχή"], "greek", "beta-code", preset="tlg-core")['LO/GOS', 'YUXH/']- Raises
TypeError: iftextsis a string rather than strings.
reencode()
Section titled “reencode()”def reencode( text: str, format: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> strParses and writes text again in the same format: normalizes it, or restyles it after other options.
>>> reencode("ϲοφίαϲ", "greek", greek={"sigma": "standard"})'σοφίας'reencode_many()
Section titled “reencode_many()”def reencode_many( texts: Iterable[str], format: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> list[str]Parses and writes many strings again, in one call into the engine, as
reencode() does each.
>>> reencode_many(["ϲοφίαϲ", "λόγοϲ"], "greek", greek={"sigma": "standard"})['σοφίας', 'λόγος']- Raises
TypeError: iftextsis a string rather than strings.
convert_detailed()
Section titled “convert_detailed()”def convert_detailed( text: str, source: Format, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> ConversionResultConverts text and reports what the target cannot retain, and where each source token was read and written.
>>> result = convert_detailed("Θεσσαλονίκη", "greek",... "transliteration", preset="iso-843-type-2")>>> result.output, result.lossy, result.losses[0].offset('Thessaloníki', True, 10)convert_detailed_many()
Section titled “convert_detailed_many()”def convert_detailed_many( texts: Iterable[str], source: Format, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> list[ConversionResult]Converts many strings in one call into the engine, and reports for each
what convert_detailed() reports: the losses, and where each token
went. The positions of each result are in its own string.
>>> results = convert_detailed_many(["Θεσσαλονίκη", "Αθήνα"],... "greek", "transliteration", preset="iso-843-type-2")>>> [(result.output, result.lossy) for result in results][('Thessaloníki', True), ('Athína', True)]- Raises
TypeError: iftextsis a string rather than strings.
convert_greek_passages()
Section titled “convert_greek_passages()”def convert_greek_passages( text: str, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> strConverts the Greek passages of a text in another language, and copies the rest as it is.
>>> convert_greek_passages("see λόγος; also ‘ἀπ᾽ αὐτοῦ’", "transliteration")'see lógos; also ‘ap’ autoũ’'convert_greek_passages_detailed()
Section titled “convert_greek_passages_detailed()”def convert_greek_passages_detailed( text: str, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> ConversionResultconvert_greek_passages(), with the losses and spans of
convert_detailed().
>>> result = convert_greek_passages_detailed("voir ϐίος", "beta-code")>>> result.output, [loss.code for loss in result.losses]('voir bi/os', ['removed-glyph-variant'])Options and presets
Section titled “Options and presets”prepare_options()
Section titled “prepare_options()”def prepare_options( options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> PreparedOptionsChecks and resolves options once, for many conversions. The defaults and the presets alone are already resolved once; this serves custom options in a loop. Prepared options are returned as they are.
>>> scheme = prepare_options(transliteration={"phi": "f", "chi": "kh"})>>> [convert(word, "greek", "transliteration", scheme)... for word in ["φύσις", "χάος"]]['fýsis', 'kháos']- Raises
OptionError: asconvert()would, at once.
PreparedOptions
Section titled “PreparedOptions”class PreparedOptions(Handle)Options checked and resolved once, for many conversions: see
prepare_options(). They can be pickled, copied, and used in
another process or after set_engine().
resolve_conversion_options()
Section titled “resolve_conversion_options()”def resolve_conversion_options( options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> ConversionOptionsThe complete options that the given ones resolve to, as a fresh mapping, which can be given back as options.
>>> options = resolve_conversion_options(preset="sbl-general")>>> options["transliteration"]["long_vowels"]'macron'get_preset_options()
Section titled “get_preset_options()”def get_preset_options(preset: Preset) -> ConversionOptionsThe options a preset sets.
>>> get_preset_options("tlg-core"){'beta_code': {'case': 'uppercase', 'yot': '#401'}}get_preset_metadata()
Section titled “get_preset_metadata()”def get_preset_metadata(preset: Preset) -> dict[str, Any]What a preset follows, its references, and its coverage.
>>> get_preset_metadata("iso-843-type-2")["name"]'ISO 843:1997 — Type 2 (transcription)'list_preset_metadata()
Section titled “list_preset_metadata()”def list_preset_metadata() -> list[dict[str, Any]]The metadata of every preset.
>>> [metadata["id"] for metadata in list_preset_metadata()][:3]['ala-lc-ancient', 'ala-lc-modern', 'bnf-ancient']Converters
Section titled “Converters”create_converter()
Section titled “create_converter()”def create_converter( configuration: ConverterConfiguration | None = None, /, **keywords: Unpack[ConverterConfiguration],) -> ConverterCreates a converter that binds a preset, adds characters or spellings, or restricts the repertoire.
>>> strict = create_converter(exclude=["digamma"],... out_of_scope_behavior="reject")>>> try:... strict.convert("ϝάναξ", "greek", "transliteration")... except CharacterScopeError as error:... print(error)Conversion rejected: 1 out-of-scope character.- Raises
OptionError: orTypeError, for an invalid configuration, at once.
Converter
Section titled “Converter”class Converter(Handle)A converter with its own preset, repertoire, and characters: see
create_converter(). It can be pickled, copied, and used in another
process or after set_engine().
Converter.convert()
Section titled “Converter.convert()”def convert( text: str, source: Format, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> strConverts text with this converter’s characters and scope. Options add to its preset. Prepared options are taken when they were prepared with that preset, or with any when the converter binds none: they are then checked and resolved once.
>>> sbl = create_converter(preset="sbl-general")>>> sbl.convert("ἐν ἀρχῇ", "greek", "transliteration")'en archē'- Raises
ValueError: for another preset named in the options, or for options prepared with another preset, or without one when the converter binds one. - Raises
CharacterScopeError: if the converter rejects characters outside its scope.
Converter.reencode()
Section titled “Converter.reencode()”def reencode( text: str, format: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> strParses and writes text again in the same format, with this
converter’s characters and scope: convert(text, format, format).
>>> thorn = create_converter(aliases=[{... "letter": "theta",... "format": "transliteration",... "spellings": ["þ"],... }])>>> thorn.reencode("þeós", "transliteration")'theós'- Raises
ValueError: for another preset named in the options, or for options prepared with another preset, or without one when the converter binds one. - Raises
CharacterScopeError: if the converter rejects characters outside its scope.
Converter.convert_detailed()
Section titled “Converter.convert_detailed()”def convert_detailed( text: str, source: Format, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> ConverterConversionResultConverts text and reports the losses and the repertoire’s
diagnostics. It takes options as convert() does.
>>> no_digamma = create_converter(exclude=["digamma"])>>> result = no_digamma.convert_detailed("ϝάναξ", "greek",... "transliteration")>>> result.output, result.diagnostics[0].character('ϝánax', 'digamma')- Raises
ValueError: for another preset named in the options, or for options prepared with another preset, or without one when the converter binds one. - Raises
CharacterScopeError: if the converter rejects characters outside its scope.
Converter.convert_greek_passages()
Section titled “Converter.convert_greek_passages()”def convert_greek_passages( text: str, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> strConverts the Greek passages of a text in another language with this
converter’s characters and scope, and copies the rest as it is: see
convert_greek_passages(). The converter’s own Greek spellings
belong to the passages, whatever characters they are made of.
>>> no_digamma = create_converter(exclude=["digamma"])>>> no_digamma.convert_greek_passages("voir ϝάναξ ;", "transliteration")'voir ϝánax ;'- Raises
ValueError: for options, or prepared options, of another preset. - Raises
CharacterScopeError: if the converter rejects characters outside its scope.
Converter.convert_greek_passages_detailed()
Section titled “Converter.convert_greek_passages_detailed()”def convert_greek_passages_detailed( text: str, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> ConverterConversionResultconvert_greek_passages(), with the losses, the spans, and the
diagnostics of convert_detailed().
>>> no_digamma = create_converter(exclude=["digamma"])>>> result = no_digamma.convert_greek_passages_detailed(... "voir ϝάναξ ;", "transliteration")>>> result.output, result.diagnostics[0].offset('voir ϝánax ;', 5)Converter.convert_many()
Section titled “Converter.convert_many()”def convert_many( texts: Iterable[str], source: Format, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> list[str]Converts many strings in one call into the engine, as
convert() converts each: see convert_many().
>>> sbl = create_converter(preset="sbl-general")>>> sbl.convert_many(["λόγος", "ψυχή"], "greek", "transliteration")['logos', 'psychē']- Raises
TypeError: iftextsis a string rather than strings. - Raises
CharacterScopeError: if the converter rejects characters outside its scope, in one of the strings: itsindexis the rank of that string, and its diagnostics locate them in it.
Converter.reencode_many()
Section titled “Converter.reencode_many()”def reencode_many( texts: Iterable[str], format: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> list[str]Parses and writes many strings again, in one call into the engine,
as reencode() does each.
>>> thorn = create_converter(aliases=[{... "letter": "theta",... "format": "transliteration",... "spellings": ["þ"],... }])>>> thorn.reencode_many(["þeós", "þálassa"], "transliteration")['theós', 'thálassa']- Raises
TypeError: iftextsis a string rather than strings. - Raises
CharacterScopeError: asconvert_many()does.
Converter.convert_detailed_many()
Section titled “Converter.convert_detailed_many()”def convert_detailed_many( texts: Iterable[str], source: Format, target: Format, options: ConversionOptions | PreparedOptions | None = None, /, **keywords: Unpack[ConversionOptions],) -> list[ConverterConversionResult]Converts many strings in one call into the engine, and reports for
each what convert_detailed() reports. The positions of each
result are in its own string.
>>> no_digamma = create_converter(exclude=["digamma"])>>> results = no_digamma.convert_detailed_many(... ["ϝάναξ", "ἄναξ"], "greek", "transliteration")>>> [len(result.diagnostics) for result in results][1, 0]- Raises
TypeError: iftextsis a string rather than strings. - Raises
CharacterScopeError: asconvert_many()does.
Results
Section titled “Results”Frozen dataclasses. Positions are in characters of the strings, as Python indexes them.
ConversionResult
Section titled “ConversionResult”class ConversionResultThe output of a conversion, whether it lost information, what it lost, and where each source token went.
| Field | Type |
|---|---|
output |
str |
lossy |
bool |
losses |
tuple[ConversionLoss, ...] |
spans |
tuple[ConversionSpan, ...] |
ConverterConversionResult
Section titled “ConverterConversionResult”class ConverterConversionResult(ConversionResult)A detailed conversion by a Converter, with the diagnostics of
its repertoire kept apart from the losses.
| Field | Type |
|---|---|
output |
str |
lossy |
bool |
losses |
tuple[ConversionLoss, ...] |
spans |
tuple[ConversionSpan, ...] |
diagnostics |
tuple[CharacterScopeDiagnostic, ...] |
ConversionLoss
Section titled “ConversionLoss”class ConversionLossOne distinction of a source token that the target does not retain.
offset and length locate the token in the input, in code points.
diacritic is set for the codes about a mark, and glyph_variant
for those about a letter form.
| Field | Type |
|---|---|
code |
str |
index |
int |
offset |
int |
length |
int |
message |
str |
diacritic |
`str |
glyph_variant |
`str |
ConversionSpan
Section titled “ConversionSpan”class ConversionSpanWhere one source token was read in the input and written in the output, in code points.
| Field | Type |
|---|---|
input_start |
int |
input_end |
int |
output_start |
int |
output_end |
int |
CharacterScopeDiagnostic
Section titled “CharacterScopeDiagnostic”class CharacterScopeDiagnosticOne recognized character excluded by a converter, or lacking a
mapping in its preset. offset and length are in code points of the
input, as Python indexes strings.
| Field | Type |
|---|---|
code |
str |
index |
int |
offset |
int |
length |
int |
character |
str |
message |
str |
Errors
Section titled “Errors”OptionError
Section titled “OptionError”class OptionError(ValueError)An option that cannot be resolved: an unknown key or preset, a value outside the accepted ones, or two values that cannot be combined.
path names the option ("transliteration.long_vowels",
"preset"),
received is the value given (None for an unknown key),
accepted the accepted values or keys, and replacement the current
name of a key or value that a release candidate knew, if there is one.
CharacterScopeError
Section titled “CharacterScopeError”class CharacterScopeError(ValueError)Raised when a converter created with out_of_scope_behavior="reject"
meets recognized characters outside its scope. diagnostics locates
them in the string rejected; index is that string’s rank in the list
that a _many method was given, and None for a single string.
JavaScriptError
Section titled “JavaScriptError”class JavaScriptError(RuntimeError)An error of the library that has no Python counterpart: a bug, which should be reported.
Engines
Section titled “Engines”set_engine()
Section titled “set_engine()”def set_engine(name: str | None) -> NoneChooses the engine, "v8" or "quickjs", or None for the
default. The current engine, if any, is closed; prepared options and
converters are made again in the next one when they are next used.
>>> set_engine("quickjs")>>> engine_name()'quickjs'>>> set_engine(None)engine_name()
Section titled “engine_name()”def engine_name() -> strThe name of the engine in use, "v8" or "quickjs", starting it
if needed.
>>> engine_name() in ("v8", "quickjs")TrueConstants
Section titled “Constants”| Name | Value |
|---|---|
FORMATS |
The formats: ('greek', 'beta-code', 'transliteration'). |
DEFAULT_CONVERSION_OPTIONS |
The options that apply when none is given, as a dictionary. |
CONVERSION_OPTION_VALUES |
The values that each option accepts, by group and key. |
Generated from the library’s options and values, to annotate code and let a type checker check options: Format, Preset, ConversionOptions, SourceOptions, TransliterationOptions, GreekOptions, BetaCodeOptions, TextOptions, DiacriticsOptions, ConverterConfiguration, CharacterAlias, CustomCharacter. ConversionOptions and its groups are TypedDicts whose values are Literals; Format and Preset are Literals.