Python API

June 24, 2026 ยท View on GitHub

The stable public Python API is exported from co_op_translator.api. Most integrations use one of these workflows:

ScenarioUse this whenMain APIs
Translate individual files or documentsYour application reads source content, calls Co-op Translator for translation, and decides where to save the result.translate_markdown_content, translate_notebook_content, translate_image_content, rewrite_markdown_paths, rewrite_notebook_paths
Prepare content for host-agent translationYour MCP host or application model will translate chunks, while Co-op Translator handles chunking and reconstruction.start_markdown_agent_translation, finish_markdown_agent_translation, start_notebook_agent_translation, finish_notebook_agent_translation
Translate an entire repositoryYou want the Python API to behave like the CLI and handle discovery, output paths, metadata, cleanup, and writes.run_translation

Most lower-level modules under core, config, review, and utils are implementation details used by these API entry points.

MCP clients use the same public API through the MCP Server. Use this page when calling Python directly, and the MCP guide when exposing Co-op Translator to an agent or editor. If you are deciding between CLI, Python API, and MCP, start with Choose Your Workflow.

First-Time API Flow

Start here if you are calling Co-op Translator from Python code:

  1. Configure an LLM provider as described in Configuration, unless you are only preparing Markdown or notebook chunks for host-agent translation.
  2. Decide whether your application owns file I/O.
  3. Use content APIs when your application reads and writes individual files.
  4. Use run_translation when Co-op Translator should process a repository like the CLI.
  5. Use run_review after translation if you need deterministic checks in automation.
GoalAPI to start with
Translate one Markdown string or filetranslate_markdown_content
Translate one notebook payloadtranslate_notebook_content
Translate one imagetranslate_image_content
Let a host agent translate Markdown or notebook chunksstart_markdown_agent_translation or start_notebook_agent_translation
Rewrite translated links after choosing an output pathrewrite_markdown_paths or rewrite_notebook_paths
Translate a full repositoryrun_translation
Review translated outputrun_review

Scenario 1: Translate Individual Files or Documents

Use this workflow when you already have a file, editor buffer, notebook payload, MCP request, or custom pipeline input. Your code owns file I/O:

  1. Read the source content.
  2. Call a content translation API.
  3. Optionally call a path rewriting API if the translated content will be written into a project translation folder.
  4. Save or return the result from your application.

The content translation APIs do not run project discovery, do not write metadata, do not append disclaimers, and do not rewrite links automatically.

Markdown File

import asyncio
from pathlib import Path

from co_op_translator.api import (
    rewrite_markdown_paths,
    translate_markdown_content,
)


async def main() -> None:
    source_path = Path("docs/guide.md")
    target_path = Path("translations/ko/docs/guide.md")

    translated = await translate_markdown_content(
        source_path.read_text(encoding="utf-8"),
        "ko",
        {"source_path": source_path},
    )

    rewritten = rewrite_markdown_paths(
        translated,
        source_path=source_path,
        target_path=target_path,
        policy={
            "language_code": "ko",
            "root_dir": ".",
            "translations_dir": "translations",
            "translated_images_dir": "translated_images",
            "translation_types": ["markdown", "images"],
        },
    )

    target_path.parent.mkdir(parents=True, exist_ok=True)
    target_path.write_text(rewritten, encoding="utf-8")


asyncio.run(main())

If the translated Markdown will not live in a Co-op Translator project layout, skip rewrite_markdown_paths and save the translated string directly.

Notebook File

import asyncio
from pathlib import Path

from co_op_translator.api import (
    rewrite_notebook_paths,
    translate_notebook_content,
)


async def main() -> None:
    source_path = Path("docs/tutorial.ipynb")
    target_path = Path("translations/ja/docs/tutorial.ipynb")

    translated_json = await translate_notebook_content(
        source_path.read_text(encoding="utf-8"),
        "ja",
        {"source_path": source_path},
    )

    rewritten_json = rewrite_notebook_paths(
        translated_json,
        source_path=source_path,
        target_path=target_path,
        policy={
            "language_code": "ja",
            "root_dir": ".",
            "translations_dir": "translations",
            "translated_images_dir": "translated_images",
            "translation_types": ["notebook", "images"],
        },
    )

    target_path.parent.mkdir(parents=True, exist_ok=True)
    target_path.write_text(rewritten_json, encoding="utf-8")


asyncio.run(main())

translate_notebook_content translates Markdown cells and preserves non-Markdown cells. Path rewriting is applied only to Markdown cells.

Image File

from pathlib import Path

from co_op_translator.api import translate_image_content

source_path = Path("docs/images/hero.png")
target_path = Path("translated_images/fr/hero.png")

translated_image = translate_image_content(
    source_path,
    "fr",
    {
        "root_dir": ".",
        "fast_mode": False,
    },
)

target_path.parent.mkdir(parents=True, exist_ok=True)
translated_image.save(target_path)

translate_image_content reads the source image and returns a rendered PIL.Image.Image. It does not write translated image metadata.

Scenario 2: Translate an Entire Repository

Use this workflow when you want the Python API to behave like the translate CLI. run_translation discovers supported files, translates selected content types, rewrites paths, writes output files, updates metadata, and performs translation maintenance tasks such as cleanup.

run_translation is the preferred project orchestration entry point. translate_project is exported as a compatibility alias with the same behavior.

Translate Markdown files in the current repository into Korean and Japanese:

from co_op_translator.api import run_translation

run_translation(
    language_codes="ko ja",
    markdown=True,
)

Translate only notebooks from a specific project root:

from co_op_translator.api import run_translation

run_translation(
    language_codes="fr",
    root_dir="./my-course",
    notebook=True,
)

Preview translation volume without writing files:

from co_op_translator.api import run_translation

run_translation(
    language_codes="es de",
    root_dir="./my-course",
    markdown=True,
    dry_run=True,
)

Translate multiple content roots in one call:

from co_op_translator.api import run_translation

run_translation(
    language_codes="ko",
    markdown=True,
    root_dirs=["./docs", "./labs"],
)

Write translations into explicit output groups:

from co_op_translator.api import run_translation

run_translation(
    language_codes="ja",
    markdown=True,
    groups=[
        ("./course-a", "./localized/course-a"),
        ("./course-b", "./localized/course-b"),
    ],
)

Use a per-language placeholder when each language should contain a nested subdirectory:

from co_op_translator.api import run_translation

run_translation(
    language_codes="ko",
    markdown=True,
    groups=[
        ("./course", "./translations/<lang>/course"),
    ],
)

If none of markdown, notebook, or images are set, the API translates all supported types: Markdown, notebooks, and images.

Review Translated Output

run_review runs deterministic translation checks without LLM or Vision credentials.

!!! note "Beta" run_review is a beta deterministic review API. It does not call model providers or write files, but checks and issue schemas may evolve.

from co_op_translator.api import run_review

run_review(
    language_codes="ko ja",
    root_dir="./my-course",
    markdown=True,
    notebook=True,
)

Review only files changed against a base ref and print GitHub-flavored output:

from co_op_translator.api import run_review

run_review(
    language_codes="ko",
    root_dir="./my-course",
    markdown=True,
    notebook=True,
    changed_from="origin/main",
    output_format="github",
)

Copy-Paste API Examples

Translate Markdown content without file writes:

import asyncio

from co_op_translator.api import translate_markdown_content


async def main() -> None:
    translated = await translate_markdown_content(
        "# Hello\n\nWelcome to the course.",
        "ko",
    )
    print(translated)


asyncio.run(main())

Translate and rewrite Markdown links:

import asyncio

from co_op_translator.api import rewrite_markdown_paths, translate_markdown_content


async def main() -> None:
    translated = await translate_markdown_content(
        "[Setup](../setup.md)\n\n![Hero](images/hero.png)",
        "ko",
        {"source_path": "docs/guide.md"},
    )
    rewritten = rewrite_markdown_paths(
        translated,
        source_path="docs/guide.md",
        target_path="translations/ko/docs/guide.md",
        policy={
            "language_code": "ko",
            "root_dir": ".",
            "translations_dir": "translations",
            "translated_images_dir": "translated_images",
            "translation_types": ["markdown", "images"],
        },
    )
    print(rewritten)


asyncio.run(main())

Translate a repository from Python:

from co_op_translator.api import run_translation

run_translation(
    language_codes="ko ja",
    root_dir="./course",
    markdown=True,
    yes=True,
)

Translate multiple roots:

from co_op_translator.api import run_translation

run_translation(
    language_codes="ko",
    markdown=True,
    root_dirs=[
        "./docs",
        "./labs",
    ],
)

Preserve glossary terms:

from co_op_translator.api import run_translation

run_translation(
    language_codes="fr",
    markdown=True,
    glossaries=[
        "Co-op Translator",
        "Azure AI Foundry",
        "GitHub Actions",
    ],
)

Public Entry Points

from co_op_translator.api import (
    ImageTranslationOptions,
    MarkdownTranslationOptions,
    NotebookTranslationOptions,
    finish_markdown_agent_translation,
    finish_notebook_agent_translation,
    run_review,
    run_translation,
    rewrite_markdown_paths,
    rewrite_notebook_paths,
    start_markdown_agent_translation,
    start_notebook_agent_translation,
    translate_image_content,
    translate_markdown_content,
    translate_notebook_content,
    translate_project,
)

::: co_op_translator.api.translate_markdown_content

::: co_op_translator.api.translate_notebook_content

::: co_op_translator.api.translate_image_content

::: co_op_translator.api.start_markdown_agent_translation

::: co_op_translator.api.finish_markdown_agent_translation

::: co_op_translator.api.start_notebook_agent_translation

::: co_op_translator.api.finish_notebook_agent_translation

::: co_op_translator.api.rewrite_markdown_paths

::: co_op_translator.api.rewrite_notebook_paths

::: co_op_translator.api.MarkdownTranslationOptions

::: co_op_translator.api.NotebookTranslationOptions

::: co_op_translator.api.ImageTranslationOptions

::: co_op_translator.api.run_translation

::: co_op_translator.api.translate_project

::: co_op_translator.api.run_review

Content Translation APIs

Content translation APIs are intended for integrations that already have content in memory, such as an editor extension, MCP tool, notebook processor, or custom pipeline.

FunctionInputOutputFile I/ONotes
translate_markdown_contentMarkdown strMarkdown strNoAsync. Translates Markdown content only. It does not rewrite links, write metadata, or append disclaimers.
translate_notebook_contentNotebook JSON str or dictNotebook JSON strNoAsync. Translates Markdown cells and preserves non-Markdown cells. It does not rewrite links, write metadata, or append disclaimers.
translate_image_contentImage pathPIL.Image.ImageReads source image onlySynchronous. Extracts and translates image text, then returns a rendered image. It does not save translated image metadata.

translate_markdown_content and translate_notebook_content accept an optional source_path through their options. The path is passed as context to the translator; callers remain responsible for any project-specific path rewriting after translation.

from co_op_translator.api import MarkdownTranslationOptions, translate_markdown_content

translated = await translate_markdown_content(
    document,
    "ko",
    MarkdownTranslationOptions(source_path="docs/guide.md"),
)

The same options can be passed as dictionaries:

translated = await translate_markdown_content(
    document,
    "ko",
    {"source_path": "docs/guide.md"},
)

Agent-Assisted Translation APIs

Agent-assisted APIs do not call Azure OpenAI or OpenAI from Co-op Translator. They prepare Markdown or notebook chunks for a host agent to translate, then reconstruct the final content from translated chunks.

FunctionPurpose
start_markdown_agent_translationReturn a self-contained Markdown job with chunks, prompts, and reconstruction state.
finish_markdown_agent_translationReconstruct Markdown from a job and host-agent translated chunks.
start_notebook_agent_translationReturn a notebook job with Markdown-cell chunks for host-agent translation.
finish_notebook_agent_translationReconstruct notebook JSON while preserving code cells, outputs, and metadata.

This workflow is mainly intended for MCP hosts. If you need production repository translation with Co-op Translator managing provider calls, use translate_markdown_content, translate_notebook_content, or run_translation.

Path Rewriting APIs

Path rewriting APIs perform no translation. They update links and frontmatter paths after callers know the source path, translated target path, and project layout.

FunctionScopeNotes
rewrite_markdown_pathsMarkdown body and frontmatterRewrites Markdown links and supported frontmatter path fields for a translated target.
rewrite_notebook_pathsMarkdown cells in notebook JSONApplies Markdown path rewriting to each Markdown cell and leaves non-Markdown cells unchanged.

The policy argument may be a dictionary with these fields:

FieldRequiredPurpose
language_codeYesTarget language code, such as "ko" or "pt-BR".
root_dirNoSource project root. Defaults to ".".
translations_dirNoText translation output directory. Defaults to translations under root_dir.
translated_images_dirNoTranslated image output directory. Defaults to translated_images under root_dir.
translation_typesNoEnabled translation types. Defaults to Markdown, notebooks, and images.
lang_subdirNoOptional subdirectory under each language folder.

Project Translation Parameters

ParameterTypeDefaultPurpose
language_codesstrRequiredSpace-separated target language codes, such as "ko ja fr", or "all". Alias codes are normalized to canonical BCP 47 values.
root_dirstr"."Project root for a single translation target. Ignored when root_dirs or groups are supplied.
updateboolFalseDelete and recreate existing translations for the selected languages.
imagesboolFalseInclude image translation. Requires Azure AI Vision configuration.
markdownboolFalseInclude Markdown translation.
notebookboolFalseInclude Jupyter notebook translation.
debugboolFalseEnable debug logging.
save_logsboolFalseSave DEBUG-level log files under the root logs/ directory.
yesboolTrueAuto-confirm prompts for programmatic and CI usage.
add_disclaimerboolFalseAdd machine translation disclaimers to translated Markdown and notebooks.
translations_dirstr | NoneNoneCustom text translation output directory. Relative paths resolve against each root.
image_dirstr | NoneNoneCustom translated image output directory. Relative paths resolve against each root.
root_dirsIterable[str] | NoneNoneMultiple roots that share the same output settings.
groupsIterable[tuple[str, str | None]] | NoneNoneExplicit (root_dir, translations_dir) pairs. Takes precedence over root_dirs.
repo_urlstr | NoneNoneRepository URL used when rendering README language table guidance.
glossariesIterable[str] | NoneNoneGlossary terms to preserve during translation. Duplicates and blank terms are normalized.
dry_runboolFalseEstimate translation volume and preview migration behavior without writing files.

Review Parameters

run_review intentionally mirrors the run_translation signature where possible so automation can switch between translation and review workflows with minimal branching.

ParameterTypeDefaultPurpose
language_codesstr | Iterable[str]"all"Target language folders to review. Space-separated strings and iterables are accepted. "all" reviews every discovered translation language.
root_dirstr"."Project root for a single review target. Ignored when root_dirs or groups are supplied.
markdownboolFalseInclude Markdown and MDX source files.
notebookboolFalseInclude Jupyter notebook source files.
imagesboolFalseReserved for parity with translation options. Link references to images are checked from Markdown.
translations_dirstr | NoneNoneCustom text translation output directory. Relative paths resolve against each root.
root_dirsIterable[str] | NoneNoneMultiple roots that share the same output settings.
groupsIterable[tuple[str, str | None]] | NoneNoneExplicit (root_dir, translations_dir) pairs. Takes precedence over root_dirs.
changed_fromstr | NoneNoneGit ref used to limit review to changed source files.
output_formatstr"text"Review output format. Supported values are "text" and "github".
fail_on_warningsboolFalseTreat warnings as failures in addition to errors.
debugboolFalseEnable debug logging.
save_logsboolFalseSave DEBUG-level log files under the root logs/ directory.

If none of markdown, notebook, or images are set, the API reviews Markdown, notebooks, and image link references where applicable. Review does not call an LLM provider and does not require API keys.

Configuration Requirements

Provider-backed translation APIs require provider configuration before translating:

  • Markdown and notebook translation require an LLM provider. Configure either Azure OpenAI or OpenAI.
  • Image translation requires Azure AI Vision in addition to the LLM provider.
  • run_translation runs lightweight connectivity checks before project translation begins.
  • Agent-assisted start_*_agent_translation and finish_*_agent_translation APIs do not call Co-op Translator LLM providers. The host application or MCP agent translates the prepared chunks.
  • rewrite_markdown_paths, rewrite_notebook_paths, and run_review are deterministic and do not require provider credentials.

Required Azure OpenAI variables:

AZURE_OPENAI_API_KEY="..."
AZURE_OPENAI_ENDPOINT="https://<resource>.openai.azure.com/"
AZURE_OPENAI_MODEL_NAME="gpt-4o"
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="<deployment>"
AZURE_OPENAI_API_VERSION="2024-12-01-preview"

Required OpenAI variables:

OPENAI_API_KEY="..."
OPENAI_CHAT_MODEL_ID="gpt-4o"

Required Azure AI Vision variables for image translation:

AZURE_AI_SERVICE_API_KEY="..."
AZURE_AI_SERVICE_ENDPOINT="https://<resource>.cognitiveservices.azure.com/"

run_review is deterministic and does not require Azure OpenAI, OpenAI, or Azure AI Vision configuration.

Behavior Notes

  • Content translation APIs keep translation separate from project path rewriting. Call rewrite_markdown_paths or rewrite_notebook_paths explicitly when translated content needs project-relative links adjusted for a target location.
  • Project orchestration APIs add project behavior around content translation, including file discovery, writes, path rewriting, metadata, cleanup, and optional disclaimers.
  • run_translation prints progress and estimate summaries through Click, matching the CLI user experience.
  • dry_run=True computes estimates using virtual README updates, but does not write the README or translation files.
  • groups are processed sequentially. A single aggregate estimate is printed before work begins.
  • When image translation is selected, missing Vision configuration raises an error before translation starts.
  • Existing alias-based language folders are detected and can be migrated to canonical language folder names as part of the run.
  • run_review fails on missing translated files, missing or stale translation metadata, malformed Markdown frontmatter/code fences, and invalid translated notebook JSON.
  • run_review reports missing local Markdown and image link targets as warnings by default.

Internal Call Path

The API delegates to the same core implementation used by the CLI:

Translation:

  1. co_op_translator.api.translation.translate_markdown_content, translate_notebook_content, or translate_image_content for in-memory translation.
  2. co_op_translator.api.translation.rewrite_markdown_paths or rewrite_notebook_paths for explicit path post-processing.
  3. co_op_translator.api.translation.run_translation for full project orchestration.
  4. co_op_translator.config.Config, LLMConfig, and VisionConfig.
  5. co_op_translator.core.project.ProjectTranslator.
  6. co_op_translator.core.project.TranslationManager.
  7. Focused project translation mixins for Markdown, notebooks, and images.
  8. Markdown, notebook, text, and image translators under co_op_translator.core.

Review:

  1. co_op_translator.api.review.run_review
  2. co_op_translator.review.targets.build_review_targets
  3. co_op_translator.review.runner.ReviewRunner
  4. Deterministic checks under co_op_translator.review.checks

The following classes are useful for maintainers, but are not exported as the package-level stable API.

ClassModuleResponsibility
ProjectTranslatorco_op_translator.core.project.project_translatorCoordinates project-level translation, directory management, per-language metadata normalization, and delegation to Markdown, notebook, and image translators.
TranslationManagerco_op_translator.core.project.translationPerforms the async file processing work for Markdown, notebooks, images, stale detection, and translation metadata updates.
ProjectMarkdownTranslationMixinco_op_translator.core.project.translation.project_markdown_translationOrchestrates Markdown file reads, content translation, path rewriting, metadata, disclaimers, and writes.
ProjectNotebookTranslationMixinco_op_translator.core.project.translation.project_notebook_translationOrchestrates notebook file reads, Markdown-cell translation, path rewriting, metadata, disclaimers, and writes.
ProjectImageTranslationMixinco_op_translator.core.project.translation.project_image_translationOrchestrates source image discovery, image translation, output paths, metadata, and writes.
ProjectEvaluatorco_op_translator.core.project.project_evaluatorFinds translated Markdown pairs, evaluates translation quality, and reads confidence metadata for low-confidence repair workflows.
ReviewRunnerco_op_translator.review.runnerCoordinates deterministic review checks across source files, target languages, and configured translation roots.
ReviewTargetco_op_translator.review.targetsDescribes a source root and the translation output directory reviewed for that root.
LanguageFolderMigratorco_op_translator.core.project.language_migratorDetects legacy alias language folders and prepares canonical BCP 47 folder migration plans.
Configco_op_translator.config.base_configLoads .env files and checks whether required LLM and optional Vision providers are configured.
LLMConfigco_op_translator.config.llm_config.configAuto-detects Azure OpenAI or OpenAI, validates required environment variables, and runs provider connectivity checks.
VisionConfigco_op_translator.config.vision_config.configDetects Azure AI Vision configuration and runs connectivity checks for image translation.