Spaces:
Sleeping
Sleeping
metadata
title: Translator-API
emoji: 💻
colorFrom: purple
colorTo: gray
sdk: docker
pinned: true
🌐 Translator API
Alternative gratuite à Google Translate — API REST sans clé, auto-hébergée, avec dashboard admin temps réel.
✨ Fonctionnalités
| Fonctionnalité | Description |
|---|---|
| 🆓 Gratuit & Sans clé API | Pas d'inscription, pas de quota mensuel |
| ⚡ Rate limiting | 30 requêtes/minute par IP |
| 🌍 100+ langues | Support complet ISO 639-1 + détection auto |
| 📊 Dashboard Admin | Métriques CPU/RAM temps réel, logs, graphiques 120s |
| ⚖️ Architecture distribuée | Central (API + 1 core) + Workers (1 core) |
| 🔐 Auth admin sécurisée | Code d'accès via variables d'environnement |
| 🐳 Docker ready | Déploiement 1-click sur HuggingFace Spaces |
| 📚 Wiki intégré | Exemples JS, Python, Java, cURL |
🚀 Démarrage rapide
Option 1 : Docker Compose (Recommandé)
# 1. Cloner le repo
git clone https://github.com/NathMen12/Translator-API.git
cd Translator-API
# 2. Configurer les secrets
cp .env.example .env
# Éditer .env avec votre ADMIN_ACCESS_CODE
# 3. Lancer
docker-compose up -d
# 4. Accéder à l'API
curl -X POST http://localhost:7820/translate \
-H "Content-Type: application/json" \
-d '{"text": "Bonjour le monde", "source": "fr", "target": "en"}'
Option 2 : Développement local
# Installer les dépendances
npm install
# Lancer le central (terminal 1)
npm run dev:central
# Lancer le worker (terminal 2)
npm run dev:worker
# Test
curl -X POST http://localhost:7820/translate \
-H "Content-Type: application/json" \
-d '{"text": "Hello", "target": "fr"}'
🌐 Déploiement sur HuggingFace Spaces
- Fork ce repo sur votre GitHub
- Créez un Space sur huggingface.co/new-space
- SDK: Docker
- Hardware: CPU Basic (2 vCPU, 16 GB RAM) ✅
- Visibility: Public ou Private
- Ajoutez les Secrets dans Settings → Repository secrets :
ADMIN_ACCESS_CODE= votre mot de passe admin fortTAILSCALE_API_KEY= (optionnel) pour découverte workers
- Push → Le Space build et déploie automatiquement !
⚠️ Le port 7820 est exposé. HuggingFace Spaces mappe automatiquement sur le port 7860 en externe.
📖 Utilisation de l'API
Endpoint principal
POST /translate
Content-Type: application/json
{
"text": "Bonjour le monde",
"source": "fr", // optionnel, défaut: "auto"
"target": "en" // optionnel, défaut: "fr"
}
Réponse
{
"translatedText": "Hello world",
"source": "fr",
"target": "en",
"duration": 245
}
Codes d'erreur
| Code | Signification |
|---|---|
| 200 | Succès |
| 400 | Requête invalide (texte manquant, trop long >5000 chars) |
| 429 | Rate limit dépassé (30 req/min/IP) |
| 500 | Erreur serveur |
💻 Exemples d'intégration
JavaScript / TypeScript
// Fetch API (navigateur / Node 18+)
async function translate(text, source = 'auto', target = 'fr') {
const res = await fetch('https://VOTRE_SPACE.hf.space/translate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, source, target })
});
if (!res.ok) throw new Error((await res.json()).error);
return res.json();
}
// Utilisation
translate('Bonjour', 'fr', 'es').then(r => console.log(r.translatedText)); // "Hola"
Python
import requests
def translate(text, source='auto', target='fr', base_url='https://VOTRE_SPACE.hf.space'):
resp = requests.post(f'{base_url}/translate',
json={'text': text, 'source': source, 'target': target}, timeout=30)
resp.raise_for_status()
return resp.json()
# Usage
print(translate('Hello world', 'en', 'fr')['translatedText']) # "Bonjour le monde"
Java (HttpClient 11+)
var client = HttpClient.newHttpClient();
var body = "{\"text\":\"Bonjour\",\"source\":\"fr\",\"target\":\"en\"}";
var request = HttpRequest.newBuilder()
.uri(URI.create("https://VOTRE_SPACE.hf.space/translate"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Parse JSON pour obtenir translatedText
cURL
curl -X POST https://VOTRE_SPACE.hf.space/translate \
-H "Content-Type: application/json" \
-d '{"text": "Bonjour", "source": "fr", "target": "en"}'
📖 Plus d'exemples : Visitez
/wikisur votre instance déployée !
🔐 Panel Admin
Accédez à https://VOTRE_SPACE.hf.space/admin et entrez votre ADMIN_ACCESS_CODE.
Onglets disponibles :
| Onglet | Contenu |
|---|---|
| 🖥️ Machines | CPU/RAM temps réel (central + workers), jobs actifs |
| 📈 Requêtes (120s) | Graphique requêtes/minute, stats, taux actuel |
| 📋 Logs | Dernières traductions : IP, durée, langues, entrée/sortie |
⚙️ Configuration
Central (central/settings.json)
{
"port": 7820,
"rateLimit": { "maxRequestsPerMinutePerIP": 30, "windowMs": 60000 },
"scanLocalWorkers": true,
"metricsWindowSeconds": 120,
"maxLocalJobs": 4
}
Worker (worker/settings.json)
{
"maxConcurrentJobs": 2,
"centralHost": "localhost",
"centralPort": 7820
}
Variables d'environnement (Secrets)
| Variable | Requis | Description |
|---|---|---|
ADMIN_ACCESS_CODE |
✅ | Mot de passe admin (fort !) |
TAILSCALE_API_KEY |
❌ | Clé API Tailscale pour auto-découverte workers |
PORT |
❌ | Port d'écoute (défaut: 7820) |
🏗️ Architecture
┌─────────────────────────────────────────────────────┐
│ HUGGINGFACE SPACE │
│ ┌─────────────────────┐ ┌────────────────────┐ │
│ │ CENTRAL │ │ WORKER │ │
│ │ (1.5 CPU / 12GB) │◄───│ (0.5 CPU / 4GB) │ │
│ │ • Express API │ WS │ • Translation │ │
│ │ • Rate Limiting │ │ • Job Queue │ │
│ │ • Job Dispatch │ │ • Metrics Push │ │
│ │ • Admin Dashboard │ │ │ │
│ │ • Metrics Storage │ │ │ │
│ └─────────────────────┘ └────────────────────┘ │
└─────────────────────────────────────────────────────┘
- Central : Gère l'API HTTP, rate limiting, dispatch vers workers, dashboard
- Worker : Se connecte en WebSocket, exécute les traductions, pousse métriques
- Communication : WebSocket natif (ws) pour faible latence
📦 Structure du projet
Translator-API/
├── central/ # Machine centrale
│ ├── src/index.js # Serveur Express + WS + Admin
│ ├── settings.json # Config centrale
│ ├── public/ # Frontend statique
│ │ ├── index.html # Page d'accueil + test
│ │ ├── admin.html # Dashboard admin (Chart.js)
│ │ └── wiki.html # Documentation intégrée
│ └── secrets/ # .env (ignoré par git)
├── worker/ # Worker de traduction
│ ├── src/index.js # Client WS + file d'attente
│ └── settings.json # Config worker
├── shared/ # Code partagé (futur)
├── wiki/ # Docs markdown (source)
├── Dockerfile # Multi-stage build
├── docker-compose.yml # Orchestration locale
├── .env.example # Template secrets
└── package.json # Dépendances root
🛠️ Développement
# Installer tout
npm run install:all
# Central en mode watch
npm run dev:central
# Worker en mode watch
npm run dev:worker
# Tests
npm test
Logs
- Central :
central/logs/central.log - Worker :
worker/logs/worker.log
🔒 Sécurité
- Pas de clé API publique — Protection par rate limiting IP
- Admin protégé — Code fort dans variable d'environnement (pas dans le code)
- Secrets HF Spaces — Stockés chiffrés, injectés au runtime
- Non-root Docker — User
nodejs(UID 1001) - Helmet/CORS — Configurables selon besoins
📝 Licence
MIT License — Voir LICENSE
🤝 Contribution
- Fork le projet
- Créez une branche (
git checkout -b feature/amazing) - Committez (
git commit -m 'Add amazing feature') - Push (
git push origin feature/amazing) - Ouvrez une Pull Request
🙏 Remerciements
- @vitalets/google-translate-api — Moteur de traduction
- Chart.js — Graphiques admin
- HuggingFace Spaces — Hébergement gratuit