Skip to main content

Python library for manipulating, creating and editing tmx files

Project description

Hypomnema

PyPI version License: MIT Python 3.12+

The industrial-grade TMX framework for Python.

Hypomnema is a strictly typed, policy-driven parser and generator for the TMX 1.4b standard. It provides a robust infrastructure for building Localization and NLP tools, designed to handle messy translation memories without crashing.

🚀 Why this library?

Most TMX parsers are simple XML wrappers. Hypomnema is an infrastructure library offering:

  • 🛡️ Policy-Driven Recovery: Configure exactly how to handle errors (missing segments, extra text, invalid tags). Choose between raise, ignore, log, or repair.
  • 🔌 Backend Agnostic: Runs on lxml for speed or standard xml.etree for zero-dependency environments.
  • ✨ Type Safe: Fully annotated with modern Python 3.12+ types. Returns structured Dataclasses, not raw XML nodes.
  • 🏗️ Symmetrical: Deserialize XML to Objects, manipulate them, and Serialize back to XML with roundtrip integrity.

📦 Installation

pip install hypomnema
OR
uv add hypomnema

For maximum performance, install with lxml support and use the LxmlBackend:

pip install "hypomnema[lxml]"
OR
uv add hypomnema[lxml]

⚡ Usage (Low-Level API)

Note: v0.4.2 exposes the core architecture components. Better docs and high-level convenience facades (load/dump) are coming in v0.5.

1. Deserializing (Reading)

To parse a file, you compose a Backend (the parser) with a Deserializer (the logic).

import xml.etree.ElementTree as ET
import hypomnema as hm

# 1. Initialize the Backend
backend = hm.StandardBackend()

# 2. Initialize the Deserializer
deserializer = hm.Deserializer(backend=backend)

# 3. Parse content (using standard ET for I/O in this example)
tree = ET.parse("memory.tmx")
root_element = tree.getroot()

# 4. Deserialize to Python Objects
tmx: hm.Tmx = deserializer.deserialize(root_element)

print(f"Source Language: {tmx.header.srclang}")
for tu in tmx.body:
    print(f"TU: {tu.tuid}")

2. Handling Dirty Data (Policies)

Real-world TMX files are often broken. Configure a DeserializationPolicy to handle errors gracefully.

If not specified, the default policy is strict on purpose to fail fast and prevent silent data corruption.

You can configure also configure the logging level for each policy value independently of its behavior.

import hypomnema as hm
import logging

# Configure a permissive policy
policy = hm.DeserializationPolicy()

# If a <tuv> has no <seg>, don't crash -> ignore the error (returns empty content)
hm.policy.missing_seg = PolicyValue("ignore", logging.WARNING)

# If a <tu> has garbage text between tags, ignore it
policy.extra_text = hm.PolicyValue("ignore", logging.INFO)

deserializer = hm.Deserializer(backend=backend, policy=policy)
tmx = deserializer.deserialize(root_element)

3. Serializing (Writing)

from datetime import datetime, timezone
import hypomnema as hm

# 1. Build the object tree
tmx_obj = hm.Tmx(
    version="1.4",
    header=hm.Header(
        creationtool="MyScript",
        creationtoolversion="1.0",
        segtype=hm.Segtype.SENTENCE,
        o_tmf="JSON",
        adminlang="en-US",
        srclang="en-US",
        datatype="plaintext",
        creationdate=datetime.now(timezone.utc)
    ),
    body=[
        hm.Tu(
            tuid="1",
            srclang="en-US",
            variants=[
                hm.Tuv(lang="en-US", content=["Hello World"]),
                hm.Tuv(lang="fr-FR", content=["Bonjour le monde"])
            ]
        )
    ]
)

# 2. Serialize to XML Element
serializer = hm.Serializer(backend=backend)
xml_root = serializer.serialize(tmx_obj)

# 3. Write to file (using backend specifics)
ET.ElementTree(xml_root).write("output.tmx", encoding="utf-8", xml_declaration=True)

🧩 Architecture

The library is built on three decoupled layers:

  1. Backend Layer: Abstracts the XML parser. LxmlBackend (fast, features) vs StandardBackend (portable).
  2. Orchestration Layer: Serializer and Deserializer classes that manage recursion and dispatch.
  3. Handler Layer: Specialized classes (TuvDeserializer, NoteSerializer) that implement the business logic and policy checks for specific TMX elements.

🛠️ Advanced Usage

Working with Mixed Content (Tags)

TMX segments often contain inline markup like placeholders (<ph>) or formatting (<bpt>). hypomnema parses these into a mixed list of strings and objects.

import hypomnema as hm

# Content is a list of strings and Inline objects
# XML: Hello <ph x="1">Name</ph>
print(variant.content) 
# Output: ["Hello ", Ph(x=1, content=["Name"])]

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

hypomnema-0.4.3.tar.gz (26.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

hypomnema-0.4.3-py3-none-any.whl (32.1 kB view details)

Uploaded Python 3

File details

Details for the file hypomnema-0.4.3.tar.gz.

File metadata

  • Download URL: hypomnema-0.4.3.tar.gz
  • Upload date:
  • Size: 26.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.17 {"installer":{"name":"uv","version":"0.9.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for hypomnema-0.4.3.tar.gz
Algorithm Hash digest
SHA256 6c883b4c972558e9882f28426abdda090517232f073475a927597b58ec74fd5a
MD5 8a584749fad19408e6900887a7759446
BLAKE2b-256 1b64a65a4ef6e85fb64823e522f46cbb34855f0e8901ce915ef5383e60b37dc1

See more details on using hashes here.

File details

Details for the file hypomnema-0.4.3-py3-none-any.whl.

File metadata

  • Download URL: hypomnema-0.4.3-py3-none-any.whl
  • Upload date:
  • Size: 32.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.17 {"installer":{"name":"uv","version":"0.9.17","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for hypomnema-0.4.3-py3-none-any.whl
Algorithm Hash digest
SHA256 cf12cb33bfc4b941132aca77175d97c895010227e25779509903d11b9c9035b5
MD5 9f5ab2aafda1ac26c3bb50fa415cef33
BLAKE2b-256 43bfac230a6d0c4eb204e485f972c9c57afbbadb6e37358458d69cb05056e29b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page