File size: 42,931 Bytes
40bcd86 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 | # 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](https://huggingface.co/apertus-8b)
**Dataset**: [Romansh Dataset on Hugging Face](https://huggingface.co/datasets/romansh-dialects)
### 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](https://github.com/Rogation/coptic-dependency-parser) | [Demo on HF](https://huggingface.co/spaces/Norelad/coptic-dependency-parser)
- **Coptic Translation Interface**: [HF Space](https://huggingface.co/spaces/Norelad/coptic-translation-interface)
- **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
```bash
# 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):**
```bash
# 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)
```bash
# Install Trealla Prolog for DCG validation
cd glossary_parser
./setup_janus.sh
```
### Basic Usage
#### Command-Line Interface
```bash
# 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):**
```python
from unified_translator import UnifiedTranslator
translator = UnifiedTranslator()
result = translator.translate("Hello world", "en", "fr")
print(result["translation"])
```
**Apertus-8B directly:**
```python
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:**
```python
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**
```bash
# 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:
```python
# 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**
```bash
./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)
```python
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
```bash
./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:**
```bash
./start_gradio.sh
```
2. **Navigate to the "📄 Batch Translation" tab**
3. **Prepare your text file** (one sentence/paragraph per line):
```text
# 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.
```
4. **Upload the file or paste the text directly**
5. **Select languages:**
- Source: German
- Target: Romansh Sursilvan
6. **Click "🌍 Translate All"**
7. **Results** (one translation per line):
```text
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**
```python
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**
```bash
# 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**
```bash
# 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**
```python
# 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**
```bash
# 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:**
```text
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):**
```python
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):**
```python
# 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
```python
# 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
```python
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
```python
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)
```python
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
```python
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
- **[APERTUS_TREALLA_QUICKSTART.md](APERTUS_TREALLA_QUICKSTART.md)**: Get started with hybrid system
- **[QUICKSTART.md](QUICKSTART.md)**: General quick start
- **[ROMANSH_GUIDE.md](ROMANSH_GUIDE.md)**: Romansh translation guide
- **[MULTIMODAL_GUIDE.md](MULTIMODAL_GUIDE.md)**: Audio translation guide
- **[BATCH_TRANSLATION_EXAMPLES.md](BATCH_TRANSLATION_EXAMPLES.md)**: Complete guide to batch translation
### Architecture & Integration
- **[INTEGRATION_ARCHITECTURE.md](INTEGRATION_ARCHITECTURE.md)**: Complete system architecture
- **[APERTUS_TREALLA_INTEGRATION.md](APERTUS_TREALLA_INTEGRATION.md)**: Hybrid system details
- **[DCG_PARSER_SUMMARY.md](DCG_PARSER_SUMMARY.md)**: Prolog parser documentation
- **[WHISPER_INTEGRATION.md](WHISPER_INTEGRATION.md)**: STT integration guide
### Development & Training
- **[ADD_LANGUAGES_GUIDE.md](ADD_LANGUAGES_GUIDE.md)**: Add new languages
- **[SWISS_FRENCH_README.md](SWISS_FRENCH_README.md)**: Swiss French project
### Reference
- **[QUICK_REFERENCE.md](QUICK_REFERENCE.md)**: Command reference
- **[EVALUATION_SUMMARY.md](EVALUATION_SUMMARY.md)**: Quality metrics
- **[PROJECT_COMPLETION_SUMMARY.md](PROJECT_COMPLETION_SUMMARY.md)**: Project status
- **[LICENSE_INFO.md](LICENSE_INFO.md)**: Licensing information
## 🧪 Example Usage Scenarios
### Scenario 1: Translate German to Romansh Sursilvan
```bash
# 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
```bash
# 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
```bash
# 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
```python
# 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](../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](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?**
```bash
# 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:**
- Low-resource languages and dialects: [APERTUS_TREALLA_QUICKSTART.md](APERTUS_TREALLA_QUICKSTART.md)
- Linguistic research and DCG parsing: [DCG_PARSER_SUMMARY.md](DCG_PARSER_SUMMARY.md)
- Interface comparison: See "User Interfaces Overview" section above
- Adding more languages: [ADD_LANGUAGES_GUIDE.md](ADD_LANGUAGES_GUIDE.md)
---
## 🎉 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*
|