Weblate Integration

Integrating Weblate into an image annotation system using Python can enhance the localization and translation processes of the application. Weblate is a web-based translation tool that supports various file formats and provides a collaborative environment for translators. By leveraging its API, developers can automate the translation of image annotations, ensuring that users from different linguistic backgrounds can access and understand the content effectively. This integration involves setting up a Weblate project, configuring the necessary translation files, and utilizing Python scripts to interact with the Weblate API for fetching and updating translations.

To begin the integration, developers need to create a Weblate project that corresponds to the image annotation system. This includes defining the source language and the target languages for translation. Once the project is set up, the next step is to prepare the translation files, which may include strings related to image descriptions, labels, and other relevant metadata. Python libraries such as requests can be used to interact with the Weblate API, allowing developers to programmatically push new strings for translation and pull completed translations back into the image annotation system.

After establishing the connection between the image annotation system and Weblate, it is essential to implement a workflow that handles the synchronization of translations. This may involve setting up a cron job or a background task that periodically checks for updates in Weblate and applies them to the annotation system. Additionally, error handling and logging mechanisms should be incorporated to manage any issues that arise during the translation process. By following these steps, developers can create a seamless integration that improves the accessibility of their image annotation system across different languages.

Step 1: Set Up Weblate

You can either use Weblate’s hosted version or self-host it on your server.

Option 1: Use Weblate’s Hosted Service

Option 2: Self-Host Weblate (Recommended for Full Control)

Install Weblate on your server using Docker:

docker run -d --name weblate -p 8080:8080 weblate/weblate
  • Access Weblate at http://localhost:8080 and create an admin account.

Step 2: Create a Weblate Project

  1. Log in to Weblate and create a new project.
  2. Name it something like “Image Annotation Translations”.
  3. If using Git, connect your repository where translation files are stored.
  4. Otherwise, Weblate can store translations internally.

Step 3: Add Translation Components

  1. Click “Add Component” (e.g., for UI text, annotations).
  2. Choose the file format your system uses (.po, .json, .yaml, .xliff).
  3. Set English (en) as the source language.
  4. Add French (fr), Arabic (ar), or other target languages.
  5. Upload an existing file or let Weblate generate one.

Step 4: Connect Weblate API with Python

To automate translation updates, use Weblate’s REST API.

4.1 Get API Credentials

  1. In Weblate, go to User Settings → API Access.
  2. Generate an API Token and save it securely.

4.2 Install Requests Library

If you haven’t already, install requests:

pip install requests

4.3 Fetch Existing Translations via API

Retrieve existing translations for a language:

import requests

API_URL = “https://your-weblate-instance/api/translations/”
API_KEY = “YOUR_API_KEY”

headers = {“Authorization”: f”Token {API_KEY}}

response = requests.get(f”{API_URL}your-project/your-component/fr/”, headers=headers)

if response.status_code == 200:
print(response.json()) # Displays the translation data
else:
print(“Error:”, response.text)

Step 5: Auto-Translate New Annotations

Whenever a new annotation is added, send it to Weblate for translation.

def send_annotation_to_weblate(annotation_text, language):
data = {
"text": annotation_text,
"language": language
}
response = requests.post(f”{API_URL}your-project/your-component/”, headers=headers, json=data)if response.status_code == 201:
print(“Annotation sent for translation”)
else:
print(“Error:”, response.text)# Example: Send new annotation for French translation
send_annotation_to_weblate(“New annotation text”, “fr”)

Step 6: Fetch Translated Annotations & Save to Database

To retrieve translated annotations and store them in your system:

def get_translated_annotation(annotation_id, language):
response = requests.get(f"{API_URL}your-project/your-component/{language}/{annotation_id}/", headers=headers)
if response.status_code == 200:
translation = response.json().get(“translated_text”)
return translation
else:
print(“Error fetching translation:”, response.text)
return None# Example: Get translated annotation
translated_text = get_translated_annotation(“12345”, “fr”)
print(“Translated Annotation:”, translated_text)

Step 7: Automate Translation Synchronization

Option 1: Weblate Manages Git Repository

  • Connect Weblate to your GitHub/GitLab repo.
  • Weblate will auto-commit translations and sync updates.

Option 2: Manual Export & Import via Python

To download translated .json or .po files:

def download_translations(language):
response = requests.get(f"{API_URL}your-project/your-component/{language}/file/", headers=headers)
if response.status_code == 200:
with open(f”translations_{language}.po”, “wb”) as file:
file.write(response.content)
print(f”Downloaded {language} translations.”)
else:
print(“Error:”, response.text)# Example: Download French translations
download_translations(“fr”)

Step 8: Use Translations in Your Application

Modify your Python app to dynamically load translations. Example using Flask & Babel:

Install Flask-Babel

pip install flask-babel

Set Up Flask-Babel in Your App

from flask import Flask, request
from flask_babel import Babel
app = Flask(__name__)
app.config[‘BABEL_DEFAULT_LOCALE’] = ‘en’
babel = Babel(app)@babel.localeselector
def get_locale():
return request.args.get(‘lang’, ‘en’) # Get language from URL query param@app.route(‘/’)
def index():
return {“message”: gettext(“Welcome to the image annotation system!”)}if __name__ == ‘__main__’:
app.run()
  • Replace "Welcome to the image annotation system!" with Weblate-managed translations.

Step 9: Add a Translation Review Feature in Admin Panel

If using Django, enable translation review in Django Admin:

from django.contrib import admin
from .models import Annotation
class AnnotationAdmin(admin.ModelAdmin):
list_display = (‘text’, ‘translated_text’, ‘language’, ‘review_status’)
search_fields = (‘text’, ‘translated_text’)admin.site.register(Annotation, AnnotationAdmin)

✅ Allows manual translation corrections in the admin panel.

Final Thoughts

Automates translation of image annotations via Weblate API.
Stores translations in the database for retrieval.
Synchronizes with Git or fetches translations via API.
Supports Flask & Django for frontend integration.

Post Disclaimer

Disclaimer/Publisher’s Note: The content provided on this website is for informational purposes only. The statements, opinions, and data expressed are those of the individual authors or contributors and do not necessarily reflect the views or opinions of Lexsense. The statements, opinions, and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of Lexsense and/or the editor(s). Lexsense and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.