Multilingual Translator - Developer Documentation

Introduction

This documentation explains how to use the Multilingual Translator project in real-world applications. The tool is designed for developers who want to add instant translation capabilities to their static or dynamic websites. It combines a FastAPI backend with a JavaScript frontend that leverages Web Workers, caching, and asynchronous requests for optimal performance. With this approach, developers can internationalize applications without rewriting their frontend logic.

Getting Started

  1. Clone the repository from GitHub.
  2. Install dependencies with pip.
  3. Add your Google API key to the .env file.
  4. Run uvicorn main:app --reload to start the server.

Architecture Overview

The architecture is composed of two main layers: the backend API built with FastAPI, and the frontend JavaScript code. The backend exposes a single endpoint /translate, which proxies requests to the Google Translate API, applies caching, and returns translated text. The frontend scans the DOM for elements with data-translate attributes, batches them, and dispatches translation requests through a Web Worker. This ensures that translations do not block the main UI thread and that long texts are processed in parallel.

Code Example

      
      from fastapi import FastAPI
      import httpx, os

      app = FastAPI()

      @app.post("/translate")
      async def translate_text(req: dict):
          text = req["text"]
          target = req["target"]
          async with httpx.AsyncClient() as client:
              res = await client.post(
                  "https://translation.googleapis.com/language/translate/v2",
                  params={"key": os.getenv("GOOGLE_API_KEY")},
                  json={"q": text, "target": target}
              )
              return res.json()
      
    

Supported Attributes

Attribute Description
data-translate="true" Marks short text for immediate translation.
lazy-translate="true" Marks long text to be translated in chunks.

Best Practices

Extended Example

Imagine a large knowledge base platform where thousands of articles need to be accessible in multiple languages. Instead of pre-translating all content manually, you can apply this tool to automatically translate articles on demand. This reduces storage costs and ensures that translations are always up to date with the original content. Furthermore, since the system caches previous translations, frequently accessed articles are instantly served from cache. This approach scales effectively and supports real-time user-driven translation requests, which is a major advantage for community-driven platforms, e-learning portals, and technical documentation sites.