Skip to content
greek conversion

Python

API reference

Everything is imported from greek_conversion. Options are those of Conversion options, with their keys in snake_case.

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.

def convert(
text: str,
source: Format,
target: Format,
options: ConversionOptions | PreparedOptions | None = None,
/,
**keywords: Unpack[ConversionOptions],
) -> str

Converts 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: if text is not a string.
  • Raises ValueError: if a format is unknown; OptionError if a preset, an option key, or an option value is.
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: if texts is a string rather than strings.
def reencode(
text: str,
format: Format,
options: ConversionOptions | PreparedOptions | None = None,
/,
**keywords: Unpack[ConversionOptions],
) -> str

Parses and writes text again in the same format: normalizes it, or restyles it after other options.

>>> reencode("ϲοφίαϲ", "greek", greek={"sigma": "standard"})
'σοφίας'
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: if texts is a string rather than strings.
def convert_detailed(
text: str,
source: Format,
target: Format,
options: ConversionOptions | PreparedOptions | None = None,
/,
**keywords: Unpack[ConversionOptions],
) -> ConversionResult

Converts 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)
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: if texts is a string rather than strings.
def convert_greek_passages(
text: str,
target: Format,
options: ConversionOptions | PreparedOptions | None = None,
/,
**keywords: Unpack[ConversionOptions],
) -> str

Converts 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ũ’'
def convert_greek_passages_detailed(
text: str,
target: Format,
options: ConversionOptions | PreparedOptions | None = None,
/,
**keywords: Unpack[ConversionOptions],
) -> ConversionResult

convert_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'])
def prepare_options(
options: ConversionOptions | PreparedOptions | None = None,
/,
**keywords: Unpack[ConversionOptions],
) -> PreparedOptions

Checks 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: as convert() would, at once.
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().

def resolve_conversion_options(
options: ConversionOptions | PreparedOptions | None = None,
/,
**keywords: Unpack[ConversionOptions],
) -> ConversionOptions

The 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'
def get_preset_options(preset: Preset) -> ConversionOptions

The options a preset sets.

>>> get_preset_options("tlg-core")
{'beta_code': {'case': 'uppercase', 'yot': '#401'}}
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)'
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']
def create_converter(
configuration: ConverterConfiguration | None = None,
/,
**keywords: Unpack[ConverterConfiguration],
) -> Converter

Creates 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: or TypeError, for an invalid configuration, at once.
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().

def convert(
text: str,
source: Format,
target: Format,
options: ConversionOptions | PreparedOptions | None = None,
/,
**keywords: Unpack[ConversionOptions],
) -> str

Converts 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.
def reencode(
text: str,
format: Format,
options: ConversionOptions | PreparedOptions | None = None,
/,
**keywords: Unpack[ConversionOptions],
) -> str

Parses 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.
def convert_detailed(
text: str,
source: Format,
target: Format,
options: ConversionOptions | PreparedOptions | None = None,
/,
**keywords: Unpack[ConversionOptions],
) -> ConverterConversionResult

Converts 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.
def convert_greek_passages(
text: str,
target: Format,
options: ConversionOptions | PreparedOptions | None = None,
/,
**keywords: Unpack[ConversionOptions],
) -> str

Converts 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],
) -> ConverterConversionResult

convert_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)
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: if texts is a string rather than strings.
  • Raises CharacterScopeError: if the converter rejects characters outside its scope, in one of the strings: its index is the rank of that string, and its diagnostics locate them in it.
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: if texts is a string rather than strings.
  • Raises CharacterScopeError: as convert_many() does.
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: if texts is a string rather than strings.
  • Raises CharacterScopeError: as convert_many() does.

Frozen dataclasses. Positions are in characters of the strings, as Python indexes them.

class ConversionResult

The 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, ...]
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, ...]
class ConversionLoss

One 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
class ConversionSpan

Where 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
class CharacterScopeDiagnostic

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

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.

class JavaScriptError(RuntimeError)

An error of the library that has no Python counterpart: a bug, which should be reported.

def set_engine(name: str | None) -> None

Chooses 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)
def engine_name() -> str

The name of the engine in use, "v8" or "quickjs", starting it if needed.

>>> engine_name() in ("v8", "quickjs")
True
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.