TraductAL / docs /README_DETAILED.md
Norelad's picture
Upload folder using huggingface_hub
40bcd86 verified
|
Raw History Blame Contribute Delete
42.9 kB

A newer version of the Gradio SDK is available: 6.32.0

Upgrade

TraductAL - Multilingual, multimodal translation system

A neuro-symbolic approach combining neural MT with Prolog-based validation

A completely offline, privacy-focused multilingual translation system combining an open-source neural translation engine with Prolog-based symbolic validation. The system uses Apertus-8B (Apache-2.0) for 1811 languages, with a focus on low-resource and endangered languages including all Romansh variants, and Trealla Prolog DCG parsers providing symbolic validation and error correction to prevent hallucinations.

As of v1.1.0, NLLB-200 (CC-BY-NC-4.0) has been removed. Apertus-8B is the sole translation engine. See THIRD-PARTY-NOTICES.md for the licensing rationale.

πŸ—οΈ Architecture Overview

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   TraductAL Hybrid System                    β”‚
β”‚              65+ Languages Production Ready                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚                   β”‚
         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
         β”‚  Apertus-8B (Apache) β”‚   β”‚  Apertus-8B (HF)       β”‚
         β”‚  1811 languages      β”‚   β”‚  1811 languages        β”‚
         β”‚  50 mainstream in UI β”‚   β”‚  15+ low-resource      β”‚
         β”‚  Fast on GPU         β”‚   β”‚  Specialized dialects  β”‚
         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                    β”‚                   β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β–Ό
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚  Trealla Prolog   β”‚
                    β”‚  DCG Validation   β”‚
                    β”‚  - Grammar check  β”‚
                    β”‚  - Glossary parse β”‚
                    β”‚  - Error detect   β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

⚠️ Development Status & Disclaimer

USE AT YOUR OWN RISK - This system is currently in active development and not ready for production use.

Known Limitations:

  • Incomplete translations: Some words or text segments may be missing from output
  • Quality varies: Translation accuracy depends on language pair and text complexity
  • No quality guarantees: Results may not be suitable for professional or critical use
  • Model limitations: Base models may require fine-tuning for specific domains
  • Low-resource language support: Continuously being expanded and validated
  • UI Language Support: Web interfaces support 50+ mainstream languages plus 15+ low-resource/Swiss languages
    • Apertus-8B: 65+ languages in the UI, 1811 available via the Python API
    • All 6 Romansh variants included
    • Expanded from original 12 languages in December 2025

Recommended Use:

  • βœ… Development and testing purposes
  • βœ… Research on low-resource languages and dialects
  • βœ… Privacy-focused translation where perfect accuracy isn't critical
  • βœ… Linguistic analysis with Prolog validation
  • ❌ Production systems requiring reliable translations
  • ❌ Professional document translation without human review
  • ❌ Critical communications or legal documents

πŸ”’ Privacy & Security

  • 100% Offline: No internet connection required after setup
  • Zero Data Leakage: All processing happens locally
  • Professional Grade: Suitable for confidential document translation
  • No Logging: No translation history stored externally
  • Open Source: Apertus-8B is Apache-2.0 licensed, permitting commercial use

🌍 Language Support

TraductAL supports 65+ languages in its web interface, with all 1811 Apertus-8B languages available via the Python API.

Mainstream Languages - 50 in UI

Core European Languages (6): English, French, German, Italian, Spanish, Portuguese

Major World Languages (6): Russian, Chinese, Hindi, Arabic, Japanese, Korean

Additional European Languages (12): Dutch, Polish, Czech, Swedish, Danish, Norwegian, Finnish, Greek, Turkish, Hungarian, Romanian, Icelandic

Major Asian Languages (8): Vietnamese, Thai, Indonesian, Malay, Tamil, Bengali, Urdu, Persian, Hebrew (9 total)

African Languages (4): Swahili, Amharic, Hausa, Yoruba

Regional European Languages (3): Catalan, Galician, Basque

Slavic Languages (9): Ukrainian, Bulgarian, Serbian, Croatian, Slovak, Slovenian, Macedonian, Lithuanian, Latvian

Baltic & Other (3): Albanian, Estonian, Latvian

Plus 150+ more languages available via API/CLI

Apertus-8B (Low-Resource & Endangered Languages) - 15+ Languages in UI

Swiss-German Dialects (6): All major Romansh variants (Sursilvan, Vallader, Puter, Surmiran, Sutsilvan, Rumantsch Grischun)

Celtic & Regional Languages (9): Occitan, Breton, Welsh, Scottish Gaelic, Irish, Luxembourgish, Friulian, Ladin, Sardinian

Swiss French dialects: Vaud, Geneva, Fribourg, Valais, NeuchΓ’tel, Jura (in development)

Plus 1796+ more languages available via API/CLI for endangered and low-resource languages

Download: Apertus-8B on Hugging Face Dataset: Romansh Dataset on Hugging Face

Trealla Prolog (Symbolic Validation)

Provides linguistic validation and dependency parsing:

  • Swiss French glossaries: DCG parser for 1861 Glossaire Vaudois
  • Grammar validation: Rule-based error detection and correction
  • Hallucination detection: Symbolic verification of neural outputs

Related Projects

TraductAL focuses on Romansh and Swiss dialects. For Coptic language support, see these separate projects:

  • Coptic Dependency Parser: GitHub | Demo on HF
  • Coptic Translation Interface: HF Space
  • Note: Coptic requires specialized models trained on CopticScriptorium data, as Apertus-8B does not support the Coptic script or language

πŸš€ Quick Start

Prerequisites

  • Python: 3.8+ (3.10+ recommended)
  • RAM: 8GB minimum, 16GB+ recommended (32GB for Apertus-8B on CPU)
  • Storage: 10-25GB for models
  • OS: Linux (tested), macOS, Windows
  • Optional: NVIDIA GPU with 16GB+ VRAM for faster Apertus-8B inference

Installation

1. Clone and Install Python Dependencies

# Clone the repository
git clone <repository-url>
cd TraductAL

# Install core dependencies
pip install -r requirements.txt

# Optional: Install enhanced features (Whisper STT, TTS, training)
pip install -r requirements_enhanced.txt

2. Download Translation Models

For Apertus-8B (all languages):

# Download from Hugging Face
# Option 1: Using huggingface-cli
huggingface-cli download apertus-8b

# Option 2: Using Python
python -c "from transformers import AutoModel; AutoModel.from_pretrained('apertus-8b')"

# Download Romansh dataset
python download_romansh_dataset.py

3. Install Trealla Prolog (Optional, for validation)

# Install Trealla Prolog for DCG validation
cd glossary_parser
./setup_janus.sh

Basic Usage

Command-Line Interface

# Simple mainstream language translation
./translate_enhanced.sh en fr "Hello, how are you?"

# Apertus-8B: Romansh translation
python apertus_translator.py --src de --tgt rm-sursilv --text "Guten Tag"

# Hybrid with validation
python apertus_trealla_hybrid.py --text "Hello world" --src en --tgt rm-sursilv

# Interactive mode
./translate_enhanced.sh interactive en fr

# List available languages
./translate_enhanced.sh list-languages

# System health check
./translate_enhanced.sh check

Python API

Unified interface (recommended):

from unified_translator import UnifiedTranslator

translator = UnifiedTranslator()
result = translator.translate("Hello world", "en", "fr")
print(result["translation"])

Apertus-8B directly:

from apertus_translator import ApertusTranslator

# Initialize Apertus translator (auto-downloads from HuggingFace if not present)
translator = ApertusTranslator(model_path="apertus-8b")  # HuggingFace model ID
translator.load_model()

# Translate to Romansh Sursilvan
result = translator.translate(
    text="Good morning, how are you?",
    src_lang="en",
    tgt_lang="rm-sursilv"
)

print(f"Translation: {result['translation']}")
print(f"Model: {result['model']}")
print(f"Time: {result['time']}")

Hybrid translation with Prolog validation:

from apertus_trealla_hybrid import HybridTranslationValidator

# Initialize hybrid validator (uses HuggingFace model)
validator = HybridTranslationValidator(config={
    'apertus_model_id': 'apertus-8b',  # HuggingFace model ID
    'enable_validation': True
})

# Translate with automatic validation
result = validator.translate(
    text="Guten Tag",
    src_lang="de",
    tgt_lang="rm-sursilv",
    validate=True
)

print(f"Translation: {result['translation']}")
print(f"Validation: {result['validation']['status']}")
if result['corrected']:
    print(f"Original: {result['original_neural']}")

Web Interface (Gradio)

Gradio Interface

# Launch the interface
./start_gradio.sh

# Access at http://localhost:7860
# Includes: 50+ mainstream languages + 15+ Apertus low-resource languages
# Uses: Apertus-8B (Apache-2.0)
# Features: Text translation, STT, TTS, Batch translation
# Total: 65+ languages in UI

✨ What's New (December 2025):

  • Expanded from 12 to 50+ mainstream languages in the Gradio interface
  • Added 9+ additional low-resource languages (Celtic, regional European languages)
  • All 6 Romansh variants fully supported with TTS
  • Major world languages: Russian, Chinese, Hindi, Arabic, Japanese, Korean now in UI
  • Enhanced coverage: Slavic, Baltic, Asian, African language families

πŸ“ Text & Audio Length Handling:

  • Short texts/audio: βœ… Optimized for sentences and short paragraphs
  • Long texts: ⚠️ Limited by model context windows
    • Apertus-8B: Default max_tokens=512 (configurable in Python API)
    • Workaround: Use batch translation tab for multi-paragraph documents
  • Long audio files: βœ… Whisper handles long audio natively (tested with files up to several minutes)
    • Processes entire audio file in one pass
    • No chunking required
  • Audio-to-Audio pipeline: ⚠️ Inherits text translation length limits
    • STT works with long audio
    • Translation limited by model context window
    • TTS works with generated translation length

πŸ“Š Model Options & Performance

Apertus-8B (the translation engine)

  • Size: ~16GB (bfloat16)
  • Speed: 2-5 seconds per sentence (GPU), 10-25 seconds (CPU)
  • Memory: 16-24GB RAM (GPU), 32GB+ RAM (CPU)
  • License: Apache-2.0 β€” commercial use permitted
  • Quality: State-of-the-art for rare languages
  • Languages Available: 1811 (65+ shown in the production UI)
  • UI Coverage: Core European (6) + Major World (6) + Extended European (12) + Asian (9) + African (4) + Regional (3) + Slavic/Baltic (12) + 6 Romansh variants + Celtic and regional European languages (Occitan, Breton, Welsh, Scottish Gaelic, Irish, Luxembourgish, Friulian, Ladin, Sardinian)
  • Use cases: Swiss dialects (Romansh), Celtic languages, endangered languages, mainstream pairs, linguistic research
  • Interface: Used by ./start_gradio.sh and via the Python API for all 1811 languages

Model Selection

Apertus-8B handles every language pair:

# Mainstream pair
translate(text="Hello", src="en", tgt="fr")  # β†’ Apertus-8B

# Romansh β€” the specialist case
translate(text="Hello", src="en", tgt="rm-sursilv")  # β†’ Apertus-8B

πŸ› οΈ System Requirements

Minimum (CPU-only)

  • Python: 3.10+
  • RAM: 32GB (Apertus-8B in bfloat16 on CPU)
  • Storage: 20GB
  • OS: Linux, macOS, Windows
  • CPU: Modern multi-core processor

Recommended (GPU)

  • Python: 3.10+
  • RAM: 16GB (32GB for CPU-only Apertus)
  • Storage: 25GB (models + workspace)
  • OS: Linux (Ubuntu 20.04+)
  • GPU: NVIDIA GPU with 16GB+ VRAM (for Apertus-8B)
  • CPU: Modern multi-core processor (if no GPU)

For Development & Training

  • RAM: 32GB+
  • Storage: 50GB+
  • GPU: NVIDIA GPU with 24GB+ VRAM (A100, RTX 4090, etc.)
  • CUDA: 11.8+ for PyTorch

πŸ“ Project Structure

TraductAL/
β”œβ”€β”€ README.md                          # This file
β”œβ”€β”€ requirements.txt                   # Core Python dependencies
β”œβ”€β”€ requirements_enhanced.txt          # Enhanced features (STT/TTS)
β”œβ”€β”€ requirements_training.txt          # Training dependencies
β”‚
β”œβ”€β”€ Core Translation Engines
β”‚   β”œβ”€β”€ apertus_translator.py         # Apertus-8B translator (1811 languages)
β”‚   β”œβ”€β”€ apertus_trealla_hybrid.py     # Hybrid neural-symbolic system
β”‚   └── unified_translator.py         # Unified interface
β”‚
β”œβ”€β”€ Multimodal Components
β”‚   β”œβ”€β”€ whisper_stt.py                # Speech-to-text (Whisper)
β”‚   β”œβ”€β”€ tts_engine.py                 # Text-to-speech (MMS-TTS)
β”‚   └── multimodal_translator.py      # Audio-to-audio pipeline
β”‚
β”œβ”€β”€ Prolog/DCG Parsers
β”‚   └── glossary_parser/
β”‚       β”œβ”€β”€ grammar.pl                # DCG grammar rules
β”‚       β”œβ”€β”€ lexicon.pl                # Lexicon module
β”‚       β”œβ”€β”€ trealla_interface.py      # Trealla-Python bridge
β”‚       └── setup_janus.sh            # Prolog setup script
β”‚
β”œβ”€β”€ Web Interfaces
β”‚   β”œβ”€β”€ app.py                        # Basic Gradio UI
β”‚   β”œβ”€β”€ enhanced_app.py               # Multimodal Gradio UI
β”‚   └── gradio_app.py                 # Advanced Gradio interface
β”‚
β”œβ”€β”€ Command-Line Tools
β”‚   β”œβ”€β”€ translate_enhanced.sh         # Main CLI wrapper
β”‚   β”œβ”€β”€ translate_romansh.sh          # Romansh-specific CLI
β”‚   └── batch_news_translator.py      # Batch processing
β”‚
β”œβ”€β”€ Dataset & Training
β”‚   β”œβ”€β”€ swiss_french_dataset_builder.py     # Build training datasets
β”‚   β”œβ”€β”€ glossary_extractor.py               # Extract glossaries
β”‚   └── datasets/                            # Training data
β”‚
β”œβ”€β”€ Documentation
β”‚   β”œβ”€β”€ APERTUS_TREALLA_INTEGRATION.md      # Hybrid system docs
β”‚   β”œβ”€β”€ APERTUS_TREALLA_QUICKSTART.md       # Quick start guide
β”‚   β”œβ”€β”€ DCG_PARSER_SUMMARY.md               # Parser documentation
β”‚   β”œβ”€β”€ INTEGRATION_ARCHITECTURE.md         # System architecture
β”‚   β”œβ”€β”€ ROMANSH_GUIDE.md                    # Romansh translation guide
β”‚   β”œβ”€β”€ MULTIMODAL_GUIDE.md                 # Audio translation guide
β”‚   β”œβ”€β”€ WHISPER_INTEGRATION.md              # STT integration
β”‚   β”œβ”€β”€ SWISS_FRENCH_README.md              # Swiss French project
β”‚   └── PRODUCTION_READINESS.md            # Readiness & citation notes
β”‚
└── Models
    └── apertus-8b/                 # Downloaded from HuggingFace (Apache-2.0)

πŸ–₯️ User Interfaces Overview

TraductAL provides multiple interfaces for different use cases:

Web Interface Comparison

Feature ./start_gradio.sh Python API CLI
Model Support Apertus-8B Apertus-8B Apertus-8B
Languages Shown 65+ All 1811 All 1811
Romansh Support βœ… Yes (6 variants) βœ… Yes βœ… Yes
World Languages βœ… 50+ major βœ… 1811 βœ… 1811
Low-Resource βœ… 15+ languages βœ… 1811 βœ… 1811
STT/TTS βœ… Yes βœ… Yes Partial
Virtual Env Required Optional Optional
Best For Production use Integration Automation

Interface Details

1. Gradio Interface (./start_gradio.sh) - RECOMMENDED

./start_gradio.sh
  • Purpose: Complete production-ready multimodal translation system
  • Languages: 65+ total
    • 50 mainstream languages (via Apertus-8B)
      • Core European: English, French, German, Italian, Spanish, Portuguese
      • Major World: Russian, Chinese, Hindi, Arabic, Japanese, Korean
      • Extended European: Dutch, Polish, Czech, Swedish, Danish, Norwegian, Finnish, Greek, Turkish, Hungarian, Romanian, and more
      • Asian: Vietnamese, Thai, Indonesian, Malay, Tamil, Bengali, Urdu, Persian, Hebrew
      • African: Swahili, Amharic, Hausa, Yoruba
      • Slavic & Baltic: Ukrainian, Bulgarian, Serbian, Croatian, Slovak, Slovenian, and more
    • 15+ low-resource languages (via Apertus-8B)
      • 6 Romansh variants (Sursilvan, Vallader, Puter, Surmiran, Sutsilvan, Rumantsch Grischun)
      • 9+ Celtic & Regional: Occitan, Breton, Welsh, Scottish Gaelic, Irish, Luxembourgish, Friulian, Ladin, Sardinian
  • Model: Apertus-8B (Apache-2.0), the sole engine
  • Features: Text translation + Speech-to-Text + Text-to-Speech + Batch translation
  • Romansh: Full support for all 6 variants with TTS
  • Good for: Production use, development, testing, comprehensive language coverage

2. Python API (Full Access)

from unified_translator import UnifiedTranslator
  • Purpose: Programmatic integration
  • Languages: All 1811 Apertus-8B languages
  • Good for: Custom applications, batch processing, research

3. Command-Line Interface

./translate_enhanced.sh en fr "Hello world"
python apertus_translator.py --src de --tgt rm-sursilv --text "Guten Tag"
  • Purpose: Shell scripting and automation
  • Languages: All supported
  • Model Selection: Full control
  • Good for: Pipelines, automation, testing

Language List Status

βœ… Production Ready (December 2025):

  • Full Gradio interface (./start_gradio.sh) now includes 65+ languages
  • Apertus-8B: 50 mainstream languages in the UI (from original 12) plus 15+ low-resource languages
  • Covers all major world languages plus Swiss dialects and Celtic languages
  • All 1811 Apertus-8B languages available via the Python API and CLI

πŸ“‹ Further Expansion: To add more languages beyond the current 65+, see ADD_LANGUAGES_GUIDE.md:

  • Step-by-step instructions for adding any Apertus-8B language
  • TTS integration for new languages
  • Testing procedures

πŸ”§ Advanced Usage

Handling Long Texts & Documents

Length Capability Summary:

Modality Component Short Content Long Content Notes
Text Translation Apertus-8B βœ… Perfect ⚠️ Limited ~512 tokens default (configurable)
Audio β†’ Text Whisper STT βœ… Perfect βœ… Perfect No length limits, handles hours
Text β†’ Audio MMS-TTS βœ… Perfect βœ… Good Synthesizes any length text
Audio β†’ Audio Full Pipeline βœ… Perfect ⚠️ Limited Limited by translation step
Batch Files Gradio Tab βœ… Perfect βœ… Perfect Line-by-line translation

Current Limitations:

  • Translation models have context window limits (~512 tokens β‰ˆ 400-500 words)
  • Single-pass translation works best for sentences and short paragraphs
  • Long documents require chunking strategies
  • Workaround: Batch translation tab or Python chunking (see below)

Option 1: Batch Translation (Gradio Interface)

The Gradio interface includes a dedicated "Batch Translation" tab for handling multiple sentences or paragraphs.

Step-by-step Guide:

  1. Launch the full Gradio interface:
./start_gradio.sh
  1. Navigate to the "πŸ“„ Batch Translation" tab

  2. Prepare your text file (one sentence/paragraph per line):

# Example file: document.txt
Guten Morgen! Wie geht es Ihnen?
Ich freue mich, Sie kennenzulernen.
Die Schweiz ist ein schΓΆnes Land mit vier Sprachen.
Romansch ist eine der Landessprachen der Schweiz.
Es gibt sechs verschiedene Romansch-Dialekte.
  1. Upload the file or paste the text directly

  2. Select languages:

    • Source: German
    • Target: Romansh Sursilvan
  3. Click "🌍 Translate All"

  4. Results (one translation per line):

Bun di! Co vai a Vus?
Jau ma legrel da enconuscher Vus.
La Svizra Γ¨ in bel pajais cun quatter linguas.
Il rumantsch Γ¨ ina da las linguas naziunalas da la Svizra.
I ha ses differents dialects rumantschs.

Key Features:

  • βœ… Each line translated independently
  • βœ… No length limit per file (can have hundreds of lines)
  • βœ… Preserves line structure
  • βœ… Works with all 18 languages in the interface
  • βœ… Can paste directly or upload .txt files

Option 2: Python API with Chunking

from unified_translator import UnifiedTranslator

translator = UnifiedTranslator()

# Split long text into chunks
def chunk_text(text, max_words=400):
    """Split text into chunks by sentences."""
    sentences = text.split('. ')
    chunks = []
    current_chunk = []
    current_length = 0

    for sentence in sentences:
        sentence_length = len(sentence.split())
        if current_length + sentence_length > max_words:
            chunks.append('. '.join(current_chunk) + '.')
            current_chunk = [sentence]
            current_length = sentence_length
        else:
            current_chunk.append(sentence)
            current_length += sentence_length

    if current_chunk:
        chunks.append('. '.join(current_chunk) + '.')

    return chunks

# Translate long document
long_text = """[Your long document here...]"""
chunks = chunk_text(long_text)
translations = []

for chunk in chunks:
    result = translator.translate(chunk, "en", "fr")
    translations.append(result["translation"])

final_translation = " ".join(translations)

Option 3: Command-Line Batch Translation

Method A: Using the batch translator script

# Create an input file
cat > articles.txt << 'EOF'
Guten Morgen! Wie geht es Ihnen?
Ich freue mich, Sie kennenzulernen.
Die Schweiz ist ein schΓΆnes Land.
Romansch wird in GraubΓΌnden gesprochen.
EOF

# Translate with batch_news_translator.py
python batch_news_translator.py --src de --tgt rm-sursilv --input articles.txt --output translated.txt

# View results
cat translated.txt

Method B: Using shell loops

# Create input file
cat > input.txt << 'EOF'
Hello, how are you?
Goodbye, see you later.
Thank you very much.
Have a nice day!
EOF

# Translate line by line
while IFS= read -r line; do
    echo "Translating: $line"
    ./translate_enhanced.sh en fr "$line"
    echo "---"
done < input.txt > output.txt

# View results
cat output.txt

Method C: Using Python for batch processing

# batch_translate.py
from unified_translator import UnifiedTranslator

translator = UnifiedTranslator()

# Read input file
with open('input.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()

# Translate each line
translations = []
for i, line in enumerate(lines, 1):
    line = line.strip()
    if not line:
        translations.append("")
        continue

    print(f"Translating line {i}/{len(lines)}...")
    result = translator.translate(line, "en", "fr")
    translations.append(result["translation"])

# Write output
with open('output.txt', 'w', encoding='utf-8') as f:
    f.write('\n'.join(translations))

print(f"βœ… Translated {len(translations)} lines")

Real-World Example: Translating a Long Article

# Create a multi-paragraph article
cat > long_article.txt << 'EOF'
Die Schweizer Alpen sind weltberΓΌhmt.
Sie erstrecken sich ΓΌber mehrere Kantone.
Viele Touristen besuchen jedes Jahr die Bergregionen.
Im Winter ist Skifahren sehr beliebt.
Im Sommer kommen Wanderer aus aller Welt.
Die Landschaft ist atemberaubend schΓΆn.
Kleine DΓΆrfer liegen in den TΓ€lern.
Die Menschen sprechen verschiedene Sprachen.
Die lokale Kultur ist sehr reich.
Traditionelle Feste werden das ganze Jahr ΓΌber gefeiert.
EOF

# Batch translate German β†’ Romansh Sursilvan
python batch_news_translator.py \
    --src de \
    --tgt rm-sursilv \
    --input long_article.txt \
    --output article_romansh.txt

# View the Romansh translation
cat article_romansh.txt

Expected Output:

Las Alps svizras Γ¨n renumadas en tut il mund.
Ellas sa extendeschan sur plirs chantuns.
Bler turissens visitan mintga onn las regiuns da muntogna.
Tal enviern Γ¨ il skis fitg popular.
Tal stad vegnian randunadurs da tut il mund.
Il cuntegn Γ¨ maletg da mussair.
Pitschens vitgs sa chattan en las vals.
La glieud discurra differentas linguas.
La cultura locala Γ¨ fitg ritga.
Festas tradiziunalas vegnan festivadas tut onn.

Handling Long Audio Files

Good News: Audio processing handles long files well!

Speech-to-Text (No Length Limits):

from whisper_stt import WhisperSTT

stt = WhisperSTT(model_size="base")  # or "medium" for better quality
stt.load_model()

# Works with long audio files (tested up to 30+ minutes)
transcription = stt.transcribe("long_podcast.mp3", language="en")
print(transcription)

Audio-to-Audio Pipeline (With Text Limitation):

# Long audio β†’ Text works perfectly
# Text β†’ Translation has 512 token limit
# Translation β†’ Speech works perfectly

# For long audio:
# 1. Transcribe entire audio (works)
# 2. Chunk transcription for translation (required)
# 3. Translate chunks
# 4. Synthesize each chunk to audio
# 5. Concatenate audio chunks

from whisper_stt import WhisperSTT
from unified_translator import UnifiedTranslator
from tts_engine import TTSEngine
import numpy as np
import scipy.io.wavfile

stt = WhisperSTT()
translator = UnifiedTranslator()
tts = TTSEngine()

# Step 1: Transcribe long audio
transcription = stt.transcribe("long_speech.mp3", language="de")

# Step 2: Chunk and translate
chunks = chunk_text(transcription, max_words=400)
translated_chunks = []
for chunk in chunks:
    result = translator.translate(chunk, "de", "en")
    translated_chunks.append(result["translation"])

# Step 3: Synthesize each chunk
audio_chunks = []
for i, chunk in enumerate(translated_chunks):
    audio_path, sr = tts.text_to_speech(chunk, "English")
    audio_data, _ = scipy.io.wavfile.read(audio_path)
    audio_chunks.append(audio_data)

# Step 4: Concatenate audio
final_audio = np.concatenate(audio_chunks)
scipy.io.wavfile.write("output_long.wav", sr, final_audio)

Model Selection & Configuration

# Default engine
from unified_translator import UnifiedTranslator

translator = UnifiedTranslator()
result = translator.translate("Hello", "en", "fr")

# Or drive Apertus-8B directly
from apertus_translator import ApertusTranslator

translator = ApertusTranslator(model_path="apertus-8b")  # HuggingFace model ID
result = translator.translate(
    text="Hello",
    src_lang="en",
    tgt_lang="rm-sursilv",
    max_tokens=512
)

Trealla Prolog DCG Parsing

from glossary_parser.trealla_interface import TreallaGlossaryParser

# Initialize parser
parser = TreallaGlossaryParser()

# Parse Swiss French glossary entry
result = parser.parse_entry("""
ABANDONNER (S'), v.pr. Ce verbe ne peut s'employer
dans l'expression : cet enfant s'abandonne...
""")

print(f"Headword: {result['headword']}")
print(f"POS: {result['pos']}")
print(f"Definition: {result['definition']}")

Hybrid Translation with Validation

from apertus_trealla_hybrid import HybridTranslationValidator

# Initialize hybrid system
validator = HybridTranslationValidator(config={
    'apertus_model_id': 'apertus-8b',  # HuggingFace model ID
    'enable_validation': True,
    'max_length_ratio': 3.0
})

# Translate with automatic validation (Romansh example)
result = validator.translate(
    text="Bonjour le monde",
    src_lang="fr",
    tgt_lang="rm-sursilv",  # Romansh Sursilvan
    validate=True
)

# Check validation results
if result['validation']['valid']:
    print(f"βœ“ Translation validated: {result['translation']}")
else:
    print(f"⚠ Errors detected: {result['validation']['errors']}")

Multimodal Translation (Speech-to-Speech)

from whisper_stt import WhisperSTT
from unified_translator import UnifiedTranslator
from tts_engine import TTSEngine

# Initialize pipeline
stt = WhisperSTT()
translator = UnifiedTranslator()
tts = TTSEngine()

# Audio-to-audio translation
audio_input = "speech_german.mp3"

# Step 1: Speech to text
text_de = stt.transcribe(audio_input, language="de")

# Step 2: Translate
text_en = translator.translate(text_de, src_lang="de", tgt_lang="en")

# Step 3: Text to speech
tts.synthesize(text_en, language="en", output="speech_english.mp3")

Performance Monitoring

result = translator.translate("Hello world", "en", "fr")
print(f"Translation time: {result['time']:.2f}s")
print(f"Model used: {result['method']}")
print(f"Device: {result.get('device', 'CPU')}")

🌟 Key Features

Neural Translation Engine

  • Single permissive engine: Apertus-8B (Apache-2.0), 1811 languages
  • Production-ready language coverage: 65+ languages in web UI (50 mainstream + 15+ low-resource)
  • Fully commercial-friendly: no non-commercial model components in the translation path
    • Major world languages: Russian, Chinese, Hindi, Arabic, Japanese, Korean
    • European languages: All major European languages plus Slavic, Baltic, and regional languages
    • Asian languages: Vietnamese, Thai, Indonesian, Malay, Tamil, Bengali, Urdu, Persian, Hebrew
    • African languages: Swahili, Amharic, Hausa, Yoruba
  • Low-resource specialist: Apertus-8B for endangered, rare, and dialect languages
  • Swiss language focus: All 6 Romansh variants, Swiss French dialects (in development)
  • Celtic & regional languages: Occitan, Breton, Welsh, Scottish Gaelic, Irish, and more
  • HuggingFace integration: Direct download and deployment from HF hub

Symbolic Validation (Trealla Prolog)

  • DCG-based parsing: Linguistically-principled grammar analysis
  • Dependency parsing: Full syntactic structure analysis (Swiss French glossaries)
  • Error detection: Automatic hallucination and grammar error detection
  • Glossary extraction: Parse and structure historical linguistic resources (1861 Glossaire Vaudois)
  • Hybrid neural-symbolic: Combine LLM flexibility with logical validation

Multimodal Capabilities

  • Speech-to-text: Whisper integration (99 languages)
  • Text-to-speech: MMS-TTS synthesis
  • Audio-to-audio: Complete speech translation pipeline
  • Document processing: PDF, text, batch file translation

Privacy & Deployment

  • 100% offline: No internet required after model download
  • Zero telemetry: All processing local, no data leakage
  • Flexible deployment: CPU, GPU, or mixed configurations
  • Docker support: Containerized deployment available
  • API & CLI: Multiple interfaces for integration

Developer-Friendly

  • Python API: Clean, documented interfaces
  • Command-line tools: Shell scripts for automation
  • Gradio web UI: Interactive browser-based interface
  • Extensible architecture: Easy to add new languages/models
  • Training support: Fine-tuning scripts included

πŸ”¬ Research & Linguistic Applications

TraductAL is designed for linguistic research and low-resource language preservation:

  • Romansh preservation: Complete support for all 6 Romansh variants
  • Swiss French dialectology: Building datasets for 6 regional dialects (Vaud, Geneva, etc.)
  • Glossary digitization: Extract structured data from historical dictionaries (1861 Glossaire Vaudois)
  • DCG formalism: Linguistic parser based on proven grammatical frameworks
  • Endangered language documentation: Support for 1811+ languages via Apertus-8B

Related Ancient Language Projects

For Coptic (ancient Egyptian language), see separate specialized projects:

  • These use custom megalaa models trained on CopticScriptorium data
  • Apertus-8B does not support the Coptic script
  • Links provided in "Related Projects" section above

πŸ“– Documentation

Quick Start Guides

Architecture & Integration

Development & Training

Reference

πŸ§ͺ Example Usage Scenarios

Scenario 1: Translate German to Romansh Sursilvan

# Using Apertus-8B (automatically selected)
python apertus_translator.py \
    --src de \
    --tgt rm-sursilv \
    --text "Guten Morgen, wie geht es Ihnen heute?"

# Output:
# Translation: Bun di, co vai a Vus oz?
# Model: Apertus-8B
# Time: 2.3s

Scenario 2: Parse Swiss French Glossary

# Extract entries from 1861 Glossaire Vaudois
python glossary_extractor.py --input glossaire_vaud.txt --output vaud_dataset.csv

# Parse individual entry
python -c "
from glossary_parser.trealla_interface import TreallaGlossaryParser
parser = TreallaGlossaryParser()
result = parser.parse_entry('PANOSSE, s.f. Serpillière, torchon à laver')
print(result)
"

Scenario 3: Validate Romansh Translation

# Translate with validation
python apertus_trealla_hybrid.py \
    --text "Hello world" \
    --src en \
    --tgt rm-sursilv \
    --validate

# System validates output using Trealla Prolog DCG grammar

Scenario 4: Speech-to-Speech Translation

# German audio β†’ English audio
from whisper_stt import WhisperSTT
from unified_translator import UnifiedTranslator
from tts_engine import TTSEngine

# Pipeline
stt = WhisperSTT()
translator = UnifiedTranslator()
tts = TTSEngine()

# Process
german_text = stt.transcribe("speech_de.mp3", language="de")
english_text = translator.translate(german_text, "de", "en")
tts.synthesize(english_text, "en", "speech_en.mp3")

πŸ› οΈ Trealla Prolog DCG Parser

The TraductAL system includes a powerful DCG (Definite Clause Grammar) parser built on Trealla Prolog, adapted from the author's original French 2L error detection parser (1989-1991) and Coptic dependency parser.

Key Features

  • Pure DCG formalism: Linguistically-principled grammar rules
  • ISO Prolog compliant: Portable, standards-based
  • Fast & lightweight: 2MB binary, <100ms parse time
  • Python integration: Seamless via subprocess interface
  • Extensible: Easy to add new language grammars

Architecture

grammar.pl (DCG rules) + lexicon.pl (lexical data)
                 ↓
         Trealla Prolog Engine
                 ↓
     trealla_interface.py (Python bridge)
                 ↓
    Neural translation validation

Applications

  • Swiss French glossary parsing: Extract 1861+ entries from Glossaire Vaudois
  • Translation validation: Detect neural hallucinations and errors
  • Grammar error detection: Rule-based linguistic checks
  • Romansh dialect validation: Ensure authentic dialectal forms

πŸŽ“ Authorship & Attribution

Important for Academic & Research Use:

This system represents original work by the author:

  • Linguistic Core (DCG grammar, lexicon): Original research by the author, based on Master's thesis in Computational Linguistics (1989-1991)
  • System Integration (Python code, interfaces): Developed by the author
  • Translation Models: Third-party open-source components (Meta, OpenAI, etc.)

For complete transparency, see: THIRD-PARTY-NOTICES.md

This document provides:

  • Detailed component-by-component attribution
  • Citation guidelines for academic papers
  • Ethical disclosure statements for grant applications
  • Verification methodology for reproducibility
  • Teaching guidelines for educational contexts

Quick Summary:

  • βœ… Original Work: Prolog DCG grammars, lexicon, linguistic theory, Python integration
  • 🌐 Third-Party: Pre-trained ML models (Apertus-8B, Whisper, MMS-TTS)

This transparent attribution model supports academic integrity while acknowledging modern development practices.

🀝 Contributing

Contributions are welcome! Areas of particular interest:

  • New language support: Add support for additional low-resource languages
  • DCG grammars: Contribute linguistic rules for new languages
  • Dataset creation: Build training data for dialects
  • Model fine-tuning: Improve translation quality for specific domains
  • Documentation: Improve guides and examples

Note: Contributions will be attributed appropriately. Please indicate if AI tools were used in development.

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Model Licenses

The translation path is fully permissive. TTS remains non-commercial:

  • Apertus-8B: Apache 2.0 (commercial use permitted) β€” the sole translation engine
  • MMS-TTS: CC-BY-NC 4.0 (Meta AI, non-commercial) β€” text-to-speech only
  • Full per-model breakdown: see THIRD-PARTY-NOTICES.md
  • Trealla Prolog: MIT License
  • Whisper: MIT License (OpenAI)

πŸ™ Acknowledgments

Original Research Foundation

  • Author's Master's Thesis (1989-1991): French 2L Error Detection Parser using DCG formalism, providing the theoretical and methodological foundation for the Prolog-based linguistic components

Models & Frameworks

  • Meta AI for the MMS-TTS models
  • Apertus Team for the open-source 8B multilingual LLM
  • OpenAI for Whisper speech recognition
  • Trealla Prolog team (Andrew Davison) for the lightweight ISO Prolog implementation
  • Hugging Face for the Transformers library and model hosting
  • PyTorch team for the deep learning framework

Linguistic Resources

  • Lia Rumantscha for Romansh language resources and datasets
  • Canton de Vaud for Swiss French glossaries (1861 Glossaire Vaudois)
  • CopticScriptorium for Coptic text corpora (used in separate Coptic projects)
  • Swiss linguistic archives for dialectal documentation

Methodological Influences

  • DCG formalism from computational linguistics tradition
  • Swiss linguistic tradition of dialect preservation and documentation
  • Modern neural-symbolic integration approaches

πŸš€ Getting Started

Ready to translate?

# 1. Install dependencies
pip install -r requirements.txt

# 2. Download Apertus-8B
huggingface-cli download swiss-ai/Apertus-8B-2509

# 3. Test translation
python apertus_translator.py --list-languages

# 4. Start web interface (65+ languages)
./start_gradio.sh

πŸ“ Important Notes:

  • Production Ready: Full Gradio interface now supports 65+ languages (expanded December 2025)
  • Interface: 50 mainstream + 15+ low-resource languages
  • All 1811 Apertus-8B languages available via Python API and CLI

πŸ“š Additional Resources:


πŸŽ‰ Recent Updates (December 2025)

Major Language Expansion: 12 β†’ 65+ Languages

TraductAL has been significantly expanded to provide production-ready multilingual support:

Mainstream Languages: Expanded from 12 to 50 (served by Apertus-8B)

  • βœ… Original 6: English, French, German, Italian, Spanish, Portuguese
  • ✨ Added Major World (6): Russian, Chinese, Hindi, Arabic, Japanese, Korean
  • ✨ Added European (12): Dutch, Polish, Czech, Swedish, Danish, Norwegian, Finnish, Greek, Turkish, Hungarian, Romanian, Icelandic
  • ✨ Added Asian (9): Vietnamese, Thai, Indonesian, Malay, Tamil, Bengali, Urdu, Persian, Hebrew
  • ✨ Added African (4): Swahili, Amharic, Hausa, Yoruba
  • ✨ Added Regional (3): Catalan, Galician, Basque
  • ✨ Added Slavic/Baltic (12): Ukrainian, Bulgarian, Serbian, Croatian, Slovak, Slovenian, Macedonian, Albanian, Lithuanian, Latvian, Estonian, and more

Apertus-8B Low-Resource Languages: Expanded from 6 to 15+ languages

  • βœ… Original 6: All Romansh variants (Sursilvan, Vallader, Puter, Surmiran, Sutsilvan, Rumantsch Grischun)
  • ✨ Added Celtic & Regional (9+): Occitan, Breton, Welsh, Scottish Gaelic, Irish, Luxembourgish, Friulian, Ladin, Sardinian

Total Coverage: 65+ languages now available in the production web interface, covering:

  • 🌍 All major world languages
  • πŸ‡ͺπŸ‡Ί Comprehensive European coverage (including regional and minority languages)
  • 🌏 Major Asian languages
  • 🌍 Key African languages
  • πŸ‡¨πŸ‡­ All Swiss Romansh dialects
  • 🏴󠁧󠁒󠁷󠁬󠁳󠁿 Celtic and endangered European languages

System Capabilities:

  • Web UI: 65+ languages (production-ready)
  • Python API/CLI: all 1811 Apertus-8B languages
  • Full offline operation with zero data leakage
  • Speech-to-text and text-to-speech support
  • Batch translation for documents

TraductAL - Bridging mainstream and endangered languages through hybrid neural-symbolic translation 🌍

Now supporting 65+ languages with production-ready web interface