For AI agents: the complete documentation index is available at https://canary.gukhanmun.org/llms.txt, the full documentation bundle is available at https://canary.gukhanmun.org/llms-full.txt, and this page is available as Markdown at https://canary.gukhanmun.org/api/python.md.

Python API

Import public types from gukhanmun. The extension module gukhanmun._native is private. See Installation for PyPI installation and the quick start for a complete conversion example.

Converter

Converter(...) accepts keyword-only configuration and returns an immutable, reusable converter. Accepted sequences are copied into owned immutable snapshots. Dictionary bytes and files are loaded at construction time.

KeywordTypeDefault
presetPresetPreset.KO_KR
renderingRenderModeRenderMode.HANGUL_ONLY
annotation_granularityAnnotationGranularityAnnotationGranularity.WORD
ignore_dictionary_required_hanjaboolFalse
original_glossOriginalGlossOriginalGloss.PARENS
hanja_variant_setHanjaVariantSetHanjaVariantSet.AS_DICTIONARY
segmentationSegmentationSegmentation.LATTICE
source_policySourcePolicySourcePolicy.REFERENCE_AUTHORIZED
reference_onlyboolFalse
numeralsNumeralStrategyNumeralStrategy.HANGUL_PHONETIC
initial_sound_lawbool | NoneNone, inherit preset
homophone_windowContextWindow | NoneNone, inherit preset
homophone_detectionHomophoneDetectionHomophoneDetection.CONTEXT_LOCAL
first_occurrence_windowContextWindowContextWindow.OFF
collapse_redundant_parensboolTrue
recoveryRecoveryRecovery.STRICT
punctuationPunctuationPreset | CustomPunctuationProfilePunctuationPreset.PRESERVE
dictionariesSequence of file, URL or map sources()
directivesDirectives | NoneNone
htmlHtmlOptions | NoneNone

KO_KR resolves initial_sound_law=True and homophone_window=ContextWindow.PER_BLOCK. KO_KP resolves False and ContextWindow.OFF. Neither preset loads official dictionaries. Original gloss settings affect only RenderMode.ORIGINAL; variant selection occurs after dictionary recognition.

The read-only options property returns ResolvedOptions with all keywords above except original_gloss, dictionaries, directives and html. Values use their declared enum categories, and punctuation is a ResolvedPunctuationProfile with no remaining UNSET fields. The profile and nested records are frozen.

Conversion operations

convert(source: str, *, format: InputFormat | MarkdownOptions = InputFormat.TEXT) -> str

InputFormat.TEXT converts plain text, HTML converts an HTML fragment, and MARKDOWN converts CommonMark. MarkdownOptions(gfm=False) is equivalent to MARKDOWN; gfm=True enables GitHub Flavored Markdown. Ruby rendering falls back to parentheses where inline markup is unavailable.

stream(*, format: InputFormat | MarkdownOptions = InputFormat.TEXT) -> ConversionStream
convert_iter(chunks: Iterable[str], *, format: InputFormat | MarkdownOptions = InputFormat.TEXT) -> Iterator[str]

ConversionStream.push(source: str) -> str buffers the chunk and returns "". finish() -> str converts the concatenated input once. A stream retains its converter and is single-consumer. It becomes terminal after successful finish or any push/finish failure; later calls raise RuntimeError.

convert_iter() validates the format when called, then consumes chunks when its returned iterator advances. It skips empty outputs and finishes only after normal upstream exhaustion. An upstream error or early iterator close does not finalize a partial document. For every partition of an input, concatenated stream/iterator output equals convert() on the complete input.

A converter may be shared across threads; streams have independent document state. Native work releases the GIL. Pending Python signals are checked after native work returns, so a long call can delay KeyboardInterrupt.

Option enums

These are standard-library enum.Enum classes. Values equal the JavaScript contract strings. Member names are uppercase, replacing hyphens with underscores: RenderMode.HANGUL_ONLY.value == "hangul-only". Raw strings and members of the wrong enum class raise TypeError; explicitly construct an enum to parse strings, for example Preset("ko-kp").

EnumString values
Presetko-kr, ko-kp
RenderModehangul-only, hangul-hanja-parens, hanja-hangul-parens, ruby-on-hangul, ruby-on-hanja, original
OriginalGlossparens, ruby
HanjaVariantSetas-dictionary, shinjitai, kanxi, simplified, asahimoji
Segmentationlattice, eager
SourcePolicyreference-authorized, reference-first, loanword-first, ordered
SourceRoleoverride, reference, loanword
NumeralStrategyhangul-phonetic, positional-arabic, additive-arabic, smart
ContextWindowoff, per-block, per-section, per-document
HomophoneDetectioncontext-local, dictionary-wide
Recoverystrict, lenient
PunctuationPresetpreserve, modern, traditional, traditional-vertical
SpaceAfterpreserve, remove, single
DictionaryFormatfst, cdb
InputFormattext, html, markdown
ErrorCodedictionary-load, segmentation, invalid-reading, html-scan, html-malformed-attr, markdown, unsupported-content-type, invalid-input, io, internal, other

Dictionary sources and entries

DictionaryEntry(hanja, reading, suffix_reading=None, preference=0, require_hanja=False, require_hangul=False) is a frozen record. hanja and reading are required and nonempty. A supplied suffix_reading is also nonempty. preference is a non-boolean integer from 0 through 4294967295. Repeated hanja keys remain competing readings: higher preference wins by default, with reading spelling breaking ties. A following Korean particle can select a compatible candidate. suffix_reading provides the non-word-initial form. require_hanja and require_hangul request hanja or hangul annotations, respectively.

MapDictionarySource(entries, role=SourceRole.OVERRIDE) snapshots its sequence into a tuple. An empty source is valid. Authored overrides take precedence over cooperative reference and loanword sources.

FileDictionarySource(data, format, role=None) accepts bytes, bytearray, memoryview, a string path or os.PathLike[str]. Mutable buffers and logical memoryview contents are copied; unreadable/released buffers raise INVALID_INPUT. Paths remain Python filesystem values, including valid surrogateescape paths, and are read during converter construction.

UrlDictionarySource(url, format, role=None, timeout=30.0, max_bytes=67108864, total_timeout=30.0) explicitly requests an HTTP(S) download during converter construction. Redirects must keep the initial URL's scheme, hostname and effective port (80 for HTTP or 443 for HTTPS when omitted). DNS hostname case is ignored; IPv6 scope identifiers are compared exactly. A redirect to a different origin raises INVALID_INPUT before the target is requested. Relative and absolute redirects within the same origin are supported. For a dictionary hosted on another origin, configure its final URL directly. The initial URL remains caller-selected, including internal endpoints. Origin checks compare URL components without inspecting resolved IP addresses. Malformed URLs, invalid ports, forbidden schemes and forbidden redirect destinations raise INVALID_INPUT. timeout limits individual socket operations. max_bytes is a positive integer limiting the dictionary body to 64 MiB by default; total_timeout is a finite positive deadline in seconds, shared by HTTP response reads across redirects. Headers and chunk framing also obey this deadline. DNS resolution occurs before socket timeouts are set and can exceed both timeout and total_timeout. Connection attempts use socket timeouts, but retries across resolved addresses and TLS negotiation can delay cancellation beyond total_timeout. Exceeding either download bound raises DICTIONARY_LOAD with an IO cause. Redirect bodies are closed without being consumed. Proxy environment variables are not used.

Every binary source needs DictionaryFormat.FST or CDB. Role precedence is explicit role, embedded source-evidence role, then OVERRIDE. Binary source and phrase evidence remain attached to their dictionaries.

SourcePolicy.REFERENCE_AUTHORIZED uses reference evidence to authorize alternate forms. REFERENCE_FIRST and LOANWORD_FIRST choose their stated preference. ORDERED selects by source registration order and ignores roles and reference_only. Under cooperative policies, reference_only=True excludes independent loanword choices while retaining reference-authorized forms. Source roles alone do not create lexical identities or authorize forms.

Official dictionaries

gukhanmun.dictionaries loads the official dictionaries from their optional data distributions. Install them with the core extras; see Dictionaries.

stdict(*, format: DictionaryFormat = DictionaryFormat.FST) -> FileDictionarySource
opendict_general(*, format: DictionaryFormat = DictionaryFormat.FST) -> FileDictionarySource
opendict_north_korean(*, format: DictionaryFormat = DictionaryFormat.FST) -> FileDictionarySource
opendict_dialect(*, format: DictionaryFormat = DictionaryFormat.FST) -> FileDictionarySource
opendict_archaic(*, format: DictionaryFormat = DictionaryFormat.FST) -> FileDictionarySource
loanwords(*, format: DictionaryFormat = DictionaryFormat.FST) -> FileDictionarySource
FunctionDistribution (FST/CDB)Role
stdict()gukhanmun-stdict-fst, gukhanmun-stdict-cdbREFERENCE
opendict_general()gukhanmun-opendict-fst, gukhanmun-opendict-cdbREFERENCE
opendict_north_korean()gukhanmun-opendict-fst, gukhanmun-opendict-cdbREFERENCE
opendict_dialect()gukhanmun-opendict-fst, gukhanmun-opendict-cdbREFERENCE
opendict_archaic()gukhanmun-opendict-fst, gukhanmun-opendict-cdbREFERENCE
loanwords()gukhanmun-loanwords-fst, gukhanmun-loanwords-cdbLOANWORD

Each function returns a FileDictionarySource with owned bytes, the requested format and the role above. stdict_bytes(), opendict_general_bytes(), opendict_north_korean_bytes(), opendict_dialect_bytes(), opendict_archaic_bytes() and loanwords_bytes() take the same keyword and return the bytes alone. format is keyword-only; anything other than a DictionaryFormat raises TypeError.

The functions read the packaged files through importlib.resources when called; importing gukhanmun or gukhanmun.dictionaries imports no data package. Gzip-compressed files are decompressed, so the bytes are ready for the loader. Which files are compressed is fixed per distribution and never inferred from their contents.

Failures raise GukhanmunError with DICTIONARY_LOAD. When an exception caused the failure, such as an import, read or decompression error, it is both the __cause__ and the source of IO entries in chain; a plain module that shadows the data package has no underlying exception, so its chain is empty. A missing distribution's message names pip install 'gukhanmun[<extra>]'; an installed distribution that cannot be imported, whose file is missing or unreadable, whose file differs from the size and SHA-256 hash recorded in its provenance.json, whose provenance.json cannot be read, or whose gzip-compressed file is empty or corrupt suggests pip install --force-reinstall. Exceptions that are not Exception subclasses, such as KeyboardInterrupt, propagate. Content that matches its record but is not a valid dictionary is reported by Converter(...), like any other binary source.

Directives and HTML preservation

Directives(require_hanja=(), require_hangul=(), skip_annotation=()) stores three literal-hanja tuples. Rules are registered in that order and affect annotation rendering. Python callbacks are not accepted.

HtmlOptions(preserve_classes=(), preserve_attributes=()) preserves an element and its descendants whenever any rule matches. Classes are case-sensitive ASCII-whitespace-separated tokens. Each attribute rule is an AttributeMatcher(name, value=None): None checks presence, while a string checks the exact decoded value. Attribute names are compared without ASCII case distinctions; values remain case-sensitive. The first duplicate attribute determines the match. A rule matches only a complete attribute name, including non-ASCII names. Values decode numeric character references and the named references amp, lt, gt, quot and apos.

Punctuation profiles

StopStyle(mark, after) selects one Unicode scalar and a SpaceAfter policy for following U+0020 spaces. DelimiterStyle(open, close) selects opening and closing punctuation scalars. Native validation checks categories and collisions when constructing the converter; output styles do not expand the set of recognized input punctuation.

CustomPunctuationProfile(base=PunctuationPreset.PRESERVE, comma=UNSET, period=UNSET, single=UNSET, double=UNSET) has three override states:

ValueEffect
UNSETInherit the base profile for that role
NonePreserve the role's input punctuation
StopStyle/DelimiterStyleUse that explicit output style

UNSET is the sole member of UnsetType; copying or pickling it preserves its identity. Comma/period accept StopStyle, and single/double accept DelimiterStyle. The resolved profile has the same four role fields, each containing the appropriate style or None.

Errors

GukhanmunError(code, message, chain=()) exposes code: ErrorCode, message: str and an immutable tuple[ErrorCause, ...]. ErrorCause(code, message) is a frozen record. Causes are ordered from the deepest/root cause to the immediate cause.

FailurePython result
Wrong argument type, enum category or required fieldTypeError
Invalid option, entry, punctuation or URL valueGukhanmunError with INVALID_INPUT
File/URL operational failureDICTIONARY_LOAD, with root-first IO causes
Invalid binary dictionaryDICTIONARY_LOAD
Invalid Unicode in constructor text optionsINVALID_INPUT
File path the operating system cannot encodeDICTIONARY_LOAD
Lone surrogate in source text or stream inputUnicodeEncodeError
Unexpected native Rust panicINTERNAL
Python interruptionOriginal KeyboardInterrupt propagates

All eleven error code values are retained even when a particular code is not normally produced by this binding. Native conversion mappings match Node-API: core errors map to SEGMENTATION, HTML to HTML_SCAN, Markdown to MARKDOWN, FST/CDB to DICTIONARY_LOAD, I/O to IO, configuration to INVALID_INPUT, and unclassified native errors to INTERNAL.

JavaScript correspondence

packages/types/index.ts defines the behavior baseline. Python uses constructor keywords instead of the async load() factory, and explicit enums instead of implicit string options.

JavaScript contractPython equivalent
load(options)Converter(**options)
preset, rendering, segmentation, numerals, recovery, punctuation, dictionaries, directives, htmlSame keyword names
originalGloss, hanjaVariantSetoriginal_gloss, hanja_variant_set
sourcePolicy, referenceOnly, initialSoundLawsource_policy, reference_only, initial_sound_law
homophoneWindow, homophoneDetectionhomophone_window, homophone_detection
firstOccurrenceWindow, collapseRedundantParensfirst_occurrence_window, collapse_redundant_parens
convert(source, format)convert(source, format=...)
Format strings/Markdown objectInputFormat/MarkdownOptions
TransformStream returned by stream()ConversionStream with push()/finish()
optionsFrozen ResolvedOptions
DictionaryEntry.suffixReading, requireHanja, requireHangulsuffix_reading, require_hanja, require_hangul
File source data, format, roleFileDictionarySource; explicit URLs use UrlDictionarySource
Map source entries, roleMapDictionarySource
requireHanja, requireHangul, skipAnnotation directivesDirectives.require_hanja, require_hangul, skip_annotation
preserveClasses, preserveAttributesHtmlOptions.preserve_classes, preserve_attributes
Attribute string or {name, value}AttributeMatcher(name, value=None)
Custom punctuation omitted/null/styleUNSET/None/style record
GukhanmunError.code, message, chainTyped code, message and frozen root-first cause tuple

The Python convenience method convert_iter() adapts an iterable of string chunks to the buffered stream contract.