epitran

repository·master·Indexed 21 days ago

https://github.com/dmort27/epitran

A library and tool for transliterating orthographic text into the International Phonetic Alphabet (IPA). It supports various languages and scripts using mapping tables, preprocessors, and postprocessors. Key features include the Epitran class for basic transliteration, the Backoff class for multi-script text, DictFirst for dictionary-based fallback, and the epitran.vector module for generating phonological feature vectors.

Tokens
13.8K
Snippets
46
Records
53
Agent score
71%

What's inside epitran

  1. Create Map files (mapping tables)

    master

    Map files are UTF8-encoded, comma-delimited CSV files used for direct G2P conversion.

    Format Requirements

    • Header: The first row must be a header (e.g., Orth,Phon) and is discarded during processing.
    • Columns: Two columns separated by a comma. Column 1 is the orthographic sequence; Column 2 is the phonetic sequence.
    • Uniqueness: An orthographic form may only occur once in the file. Multiple orthographic forms may map to the same phonetic form.
    • Greedy Matching: Matching is greedy. If one orthographic form is a prefix of another, the longer form has priority.
    • Fallback: If no prefix matches, the first character of the orthographic form is appended to the phonetic form as-is, and processing continues with the remainder of the string.
    Orth,Phon
    a,a
    b,b
    ch,tʃ
  2. Write Preprocessor and Postprocessor rules

    master

    Pre- and post-processors use a grammar of context-sensitive string rewrite rules. These files support symbol definitions, rewrite rules, comments, and blank lines.

    Symbol Definitions

    Define reusable substrings using the syntax ::symbol_name:: = regex_pattern. Symbols must be defined before they are used.

    ::vowels:: = a|e|i|o|u

    Rewrite Rule Syntax

    Rules follow the pattern: target -> replacement / context.

    • ->: "is rewritten as"
    • /: "in the context of"
    • _: Indicates the position of the rewrite within the context.
    • #: Represents a word boundary (beginning or end of string).
    • 0: Represents the empty string (used for insertions or deletions).

    Examples

    • Contextual rewrite: e -> ə / _ # (Rewrite /e/ to /ə/ at the end of a word).
    • Deletion: ə -> 0 / k _ l (Delete /ə/ between /k/ and /l/).
    • Context-free: ch -> x / _ (Rewrite ch to x regardless of context).
    • Regex integration: Since Epitran uses the regex package, you can use standard regular expression notation in rules: c -> s / _ [ie] or c -> s / _ (i|e).
    • Using Symbols: u -> w / _ (::vowels::) (Rewrite /u/ to /w/ before a defined vowel symbol).

    Metathesis (Swapping)

    To swap two characters (e.g., "AB" to "BA"), use named capture groups sw1 and sw2 with the ?P<name> syntax:

    (?P<sw1>[char_set])(?P<sw2>.) -> 0 / _

    Rule Execution

    Rules are applied in the order they appear in the file. Earlier rules can "feed" (provide input for) or "bleed" (remove input for) later rules.

    ::vowels:: = a|e|i|o|u
    u -> w / _ (::vowels::)
    
    e -> ə / _ #
    
    ə -> 0 / k _ l
  3. Install CMU Flite for English G2P support

    master

    English G2P (eng-Latn) requires the lex_lookup binary from the CMU Flite speech synthesis system.

    Warning: The t2p interface is deprecated; use lex_lookup instead.

    Step 1: Obtain Source

    git clone https://github.com/festvox/flite.git
    cd flite

    Step 2: Build and Install

    Option A: System-wide (requires sudo)

    ./configure && make
    sudo make install
    cd testsuite && make lex_lookup
    sudo cp lex_lookup /usr/local/bin

    Option B: Local/Conda (no sudo required)

    ./configure --prefix=$CONDA_PREFIX
    make && make install
    cd testsuite && make lex_lookup
    cp lex_lookup $CONDA_PREFIX/bin/

    Note for MacOS/BSD: If make install fails on cp commands, edit main/Makefile and change cp -pd to cp -pR.

    git clone https://github.com/festvox/flite.git
    cd flite
    ./configure && make
    sudo make install
    cd testsuite && make lex_lookup
    sudo cp lex_lookup /usr/local/bin
  4. Extend Epitran with map files, preprocessors, and postprocessors

    master

    Epitran supports language expansion through a three-tier system:

    1. Map files: CSV files defining direct mappings between orthographic and phonetic units.
    2. Preprocessors: Text files containing rewrite rules applied to the orthographic form before mapping.
    3. Postprocessors: Text files containing rewrite rules applied to the phonetic form after mapping.

    File Naming and Location

    Files must follow the naming convention <iso639>-<iso15924>:

    • <iso639>: Three-letter, lowercase ISO 639-3 language code.
    • <iso15924>: Four-letter, capitalized ISO 15924 script code.

    Extensions:

    • Map files: .csv
    • Pre/Post-processor files: .txt

    Directory Structure: Files must reside in the data directory of the Epitran installation under the following subdirectories:

    • map/
    • pre/
    • post/
  5. Use English G2P with Epitran

    master

    Once lex_lookup is installed, you can use English G2P by instantiating epitran.Epitran with the code 'eng-Latn'.

    import epitran
    epi = epitran.Epitran('eng-Latn')
    print(epi.transliterate(u'Berkeley'))
    # Output: bɹ̩kli
  6. Use the Backoff class for multi-script text

    master

    The Backoff class allows for graceful fallback between different language-script modes. It processes text on a token-by-token basis. If a token contains mixed scripts that cannot be handled by any provided mode, it returns an empty string.

    Constructor: Backoff(lang_script_codes, cedict_file=None)

    • lang_script_codes: A list of language-script codes (e.g., ['hin-Deva', 'eng-Latn']).
    • cedict_file: Path to CC-CEDict (if needed for Chinese modes).

    Limitations:

    • Does not support parameterized pre/post-processors.
    • Does not support non-standard ligatures.
    • Does not support punctuation normalization.

    Public Methods:

    • transliterate(text): Returns a Unicode string of IPA phonemes.
    • trans_list(text): Returns a list of IPA Unicode strings (one per phoneme).
    • xsampa_list(text): Returns a list of X-SAMPA (ASCII) strings (one per phoneme).
    from epitran.backoff import Backoff
    
    # Fallback order: Hindi -> English -> Mandarin
    backoff = Backoff(['hin-Deva', 'eng-Latn', 'cmn-Hans'], cedict_file='cedict_1_0_ts_utf-8_mdbg.txt')
    
    print(backoff.transliterate('हिन्दी'))  # 'ɦindiː'
    print(backoff.trans_list('हिन्दी'))     # ['ɦ', 'i', 'n', 'd', 'iː']
    print(backoff.xsampa_list('हिन्दी'))    # ['h\', 'i', 'n', 'd', 'i:']
  7. Use DictFirst for dictionary-based fallback

    master

    The DictFirst class provides an alternative to Backoff. It checks if an input token exists in a provided dictionary for 'Language A'. If it does, it uses Language A's transliteration; otherwise, it falls back to 'Language B'.

    Constructor: DictFirst(lang_a_code, lang_b_code, dictionary_file_path)

    • lang_a_code: The primary language-script code.
    • lang_b_code: The fallback language-script code.
    • dictionary_file_path: Path to a UTF-8 encoded text file containing one word per line.

    Public Method:

    • transliterate(token): Returns the transliteration for Language A if the token is in the dictionary, otherwise returns the Language B transliteration.
    import dictfirst
    # If word is in sample-dict.txt, use tpi-Latn; else use eng-Latn
    df = dictfirst.DictFirst('tpi-Latn', 'eng-Latn', '../sample-dict.txt')
    
    print(df.transliterate('pela')) # 'pela' (if in dict)
    print(df.transliterate('pelo')) # 'pɛlow' (fallback)
  8. Transliterate text to IPA with Epitran.transliterate()

    master

    Use the transliterate method to convert Unicode orthographic text into an IPA string.

    Method Signature: Epitran.transliterate(text, normpunc=False, ligatures=False)

    • text: The input Unicode string.
    • normpunc (bool): If True, enables punctuation normalization.
    • ligatures (bool): If True, enables non-standard IPA ligatures.
    import epitran
    epi = epitran.Epitran('tur-Latn')
    print(epi.transliterate('Düğün'))
    # Output: dyɰyn
  9. Use the epitran.vector module for phonological feature vectors

    master

    The epitran.vector module provides the VectorsWithIPASpace class, which converts words into a structured representation containing phonetic forms and phonological feature vectors. This is useful for tasks requiring machine-readable representations of IPA features.

    Constructor Arguments

    • code: The language-script code for the language being processed.
    • spaces: A list of codes for the punctuation/symbol/IPA spaces where characters/segments are expected to reside.

    The word_to_segs method

    VectorsWithIPASpace.word_to_segs(word, normpunc=False)

    • word: A Unicode string to process.
    • normpunc: If set to True, punctuation in the input word is normalized to its ASCII equivalents.

    Returns a list of tuples representing the segments of the word.

    import epitran.vector
    # Initialize with language-script code and the relevant IPA space
    vwis = epitran.vector.VectorsWithIPASpace('uzb-Latn', ['uzb-Latn'])
    # Convert word to segments
    segments = vwis.word_to_segs('darë')
  10. Get detailed phonetic segments with Epitran.word_to_tuples()

    master

    The word_to_tuples method returns a list of tuples providing a granular breakdown of a word's phonetic structure.

    Note: This method is not implemented for all language-script pairs. Also, if pre-processors are active, the orthographic_form returned may not match the original input string, as pre-processors may modify the text to facilitate mapping.

    Tuple Structure: Each tuple in the list follows this schema:

    • character_category (String): Unicode General Category (e.g., 'L' for letters).
    • is_upper (Integer): Case indicator.
    • orthographic_form (Unicode String): The processed orthographic character.
    • phonetic_form (Unicode String): The resulting IPA character.
    • segments (List of Tuples): A list of sub-segments, where each sub-segment is (segment_string, vector_of_integers).
    import epitran
    epi = epitran.Epitran('tur-Latn')
    # Returns a list of detailed phonetic tuples
    segments = epi.word_to_tuples('Düğün')
  11. Initialize the Epitran class

    master

    The Epitran class is the primary interface for transliterating orthographic text to IPA. To initialize it, you must provide an ISO 639-3 language code followed by a hyphen and a four-letter script code (e.g., 'uig-Arab' for Uyghur in Perso-Arabic).

    Constructor Arguments:

    • code (required): ISO 639-3 language code + hyphen + 4-letter script code.
    • preproc (bool): Enables pre-processors. Defaults to True.
    • postproc (bool): Enables post-processors. Defaults to True.
    • ligatures (bool): Enables non-standard IPA ligatures like "ʤ" and "ʨ". Defaults to False.
    • cedict_file (str): Path to a CC-CEDict dictionary file (required for Mandarin Chinese cmn-Hans or cmn-Hant).
    • tones (bool): Enables IPA tones (e.g., ˩˨˧˦˥). Defaults to False (removes tones).
    import epitran
    # Uyghur in Perso-Arabic script
    epi = epitran.Epitran('uig-Arab')
    
    # Mandarin Chinese with CC-CEDict
    epi = epitran.Epitran('cmn-Hans', cedict_file='cedict_1_0_ts_utf-8_mdbg.txt')
  12. Configure Epitran backend parameters

    master

    When initializing Epitran(code, **kwargs), you can pass several keyword arguments that are forwarded to the underlying backend. Common parameters include:

    • preproc (bool): Apply preprocessors. Default is True.
    • postproc (bool): Apply postprocessors. Default is True.
    • ligatures (bool): Use phonetic ligatures instead of standard IPA. Default is False.
    • rev (bool): Use reverse transliteration. Default is False.
    • rev_preproc (bool): Apply preprocessors when reverse transliterating. Default is True.
    • rev_postproc (bool): Apply postprocessors when reverse transliterating. Default is True.
    • tones (bool): Include tone information. Default is False.
    • cedict_file (str): Path to a dictionary file for Chinese/Japanese support. Default is None.