Migrating codebases between languages is painful. You spend hours translating syntax, idioms, and patterns manually. What if you could describe the translation and have AI do the heavy lifting?
In this tutorial, youβll build a code translator that converts code between languages using Ollama. No API keys, no cloud calls, everything runs on your machine.
How It Works
- You provide source code and specify the target language
- The AI reads the code, understands the logic, and translates it
- You get idiomatic code in the target language, not just syntax conversion
The key insight: most code translators do syntax conversion. They replace def with func, class with struct, and call it done. This tool does logic translation. It understands what the code does and produces equivalent code in the target language.
Prerequisites
- Ollama installed
- Python 3.10+
Step 1: Pull the model
ollama pull qwen2.5-coder:7b
Step 2: Create the translator
#!/usr/bin/env python3
"""Local AI code translator using Ollama."""
import subprocess
import sys
import json
import urllib.request
OLLAMA_URL = "http://localhost:11434/api/generate"
MODEL = "qwen2.5-coder:7b"
PROMPT_TEMPLATE = """Translate the following code from {source_lang} to {target_lang}.
Requirements:
1. Produce idiomatic code in the target language
2. Preserve all functionality
3. Add comments explaining non-obvious translations
4. Use standard libraries, avoid external dependencies unless necessary
5. Handle error patterns appropriate for the target language
Source code ({source_lang}):
```{source_lang}
{code}
Output ONLY the translated code in {target_lang}. No explanations."""
def translate_code(code, source_lang, target_lang): """Translate code between languages.""" payload = json.dumps({ βmodelβ: MODEL, βpromptβ: PROMPT_TEMPLATE.format( source_lang=source_lang, target_lang=target_lang, code=code ), βstreamβ: False, βoptionsβ: {βtemperatureβ: 0.3, βnum_predictβ: 2000} }).encode()
req = urllib.request.Request(
OLLAMA_URL,
data=payload,
headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=120) as resp:
response = json.loads(resp.read())["response"].strip()
# Remove code block markers
if response.startswith("```"):
response = response.split("\n", 1)[1]
if response.endswith("```"):
response = response[:-3]
return response.strip()
def translate_file(input_file, output_file, source_lang, target_lang): """Translate an entire file.""" with open(input_file, βrβ) as f: code = f.read()
print(f"Translating {input_file} from {source_lang} to {target_lang}...")
translated = translate_code(code, source_lang, target_lang)
with open(output_file, "w") as f:
f.write(translated)
print(f"Translated to {output_file}")
if name == βmainβ: if len(sys.argv) < 5: print(βUsage: python translate.py input.py output.go python goβ) sys.exit(1)
input_file, output_file, source_lang, target_lang = sys.argv[1:5]
translate_file(input_file, output_file, source_lang, target_lang)
## Step 3: Use it
```bash
# Translate a file
python translate.py app.py app.go python go
# Translate inline
python -c "
from translate import translate_code
code = '''
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
'''
print(translate_code(code, 'python', 'go'))
"
What Makes This Different
Most code translators do syntax conversion. This tool does logic translation:
- Python list comprehensions become Go
forloops with proper error handling - JavaScript async/await becomes Go goroutines where appropriate
- Python classes become Go structs with methods
- Type hints become Go type declarations
The AI understands the intent, not just the syntax.
Supported Language Pairs
The tool works with any language pair Ollama supports. Tested pairs:
- Python to Go, JavaScript, TypeScript, Rust
- JavaScript to TypeScript, Python, Go
- TypeScript to JavaScript, Python, Go
- Go to Python, JavaScript
- Java to Python, Go, Kotlin
Limitations
- Complex concurrent code may not translate correctly
- Language-specific libraries need manual replacement
- Very large files may need chunking
- Generated code needs testing before production use
Real-World Use Cases
Migrating a Python Flask app to Go. I translated 15 Python files to Go. The AI handled 80% correctly. The remaining 20% needed manual fixes for library-specific code.
Converting JavaScript to TypeScript. The AI added proper type annotations, interfaces, and generics. It understood TypeScript idioms that simple regex conversion would miss.
Porting utilities to Rust. For performance-critical code, translating Python utilities to Rust made sense. The AI generated safe Rust code with proper error handling.
Legacy code modernization. Converting old Java 8 code to modern Kotlin. The AI used coroutines, data classes, and other Kotlin features correctly.
Tips for Better Translations
- Translate small files first. Start with utilities and helpers before tackling complex modules.
- Provide context. If the code uses domain-specific patterns, mention them in the description.
- Review imports. The AI tries to use standard libraries, but some replacements need manual work.
- Test thoroughly. Even 90% correct translations need testing for the remaining 10%.
My Take
This tool is not a replacement for manual translation, but it is a massive time saver. For straightforward code (utilities, data processing, API clients), it produces 80-90% correct translations. For complex business logic, use it as a starting point and refine manually.
Rating: 7.5/10 β Great for boilerplate and straightforward code. Needs manual review for complex logic.
FAQ
How accurate is the translation?
For straightforward code (utilities, data processing), 80-90% accurate. For complex business logic, 60-70%. Always test the translated code.
Can I translate entire projects?
Not in this basic version. The tool works file by file. For entire projects, you would need to add directory traversal and dependency management.
Does it handle imports and dependencies?
The AI attempts to use standard libraries in the target language. External dependencies need manual replacement after translation.
Can I customize the translation style?
Yes. Modify the PROMPT_TEMPLATE to specify coding style preferences, naming conventions, or architectural patterns.
What if the translation is wrong?
Review the output and fix issues manually. The AI generates a starting point, not perfect code. For complex logic, use the translation as a reference and rewrite where needed.
Related: Best AI Coding Tools 2026 Β· Ollama Complete Guide Β· Python Complete Guide
This article is part of our βBuild It With AIβ series. See more practical AI tutorials: AI Commit Message Generator Β· AI Code Review Bot Β· Local RAG Pipeline