Spaces:
Running
Running
krishnacharandaskamble09-cloud commited on
Commit ·
86fbb0e
1
Parent(s): 1e12194
Upgrade from IndicTrans2 to IndicTrans3-beta
Browse files- Dockerfile +7 -1
- README.md +9 -13
- main.py +106 -266
- requirements.txt +1 -3
Dockerfile
CHANGED
|
@@ -1,5 +1,11 @@
|
|
| 1 |
FROM python:3.10-slim
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
RUN useradd -m -u 1000 user
|
| 4 |
USER user
|
| 5 |
ENV PATH="/home/user/.local/bin:$PATH"
|
|
@@ -12,4 +18,4 @@ RUN pip install --no-cache-dir --upgrade pip && \
|
|
| 12 |
|
| 13 |
COPY --chown=user main.py .
|
| 14 |
|
| 15 |
-
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
|
| 1 |
FROM python:3.10-slim
|
| 2 |
|
| 3 |
+
# Install system dependencies for vLLM
|
| 4 |
+
RUN apt-get update && apt-get install -y \
|
| 5 |
+
git \
|
| 6 |
+
build-essential \
|
| 7 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 8 |
+
|
| 9 |
RUN useradd -m -u 1000 user
|
| 10 |
USER user
|
| 11 |
ENV PATH="/home/user/.local/bin:$PATH"
|
|
|
|
| 18 |
|
| 19 |
COPY --chown=user main.py .
|
| 20 |
|
| 21 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
|
@@ -1,28 +1,24 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
emoji: 🚀
|
| 4 |
colorFrom: blue
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
app_port: 7860
|
| 8 |
pinned: false
|
| 9 |
-
license: mit
|
| 10 |
---
|
| 11 |
|
| 12 |
-
#
|
| 13 |
|
| 14 |
-
|
| 15 |
|
| 16 |
-
##
|
| 17 |
|
| 18 |
-
|
| 19 |
-
- `GET /health` — service status
|
| 20 |
-
- `GET /languages` — list all language codes
|
| 21 |
-
- `GET /docs` — interactive Swagger UI
|
| 22 |
|
| 23 |
-
##
|
| 24 |
|
| 25 |
```bash
|
| 26 |
-
curl -X POST https://krishna96k-
|
| 27 |
-H "Content-Type: application/json" \
|
| 28 |
-
-d '{"text":"Good morning","src_lang":"
|
|
|
|
| 1 |
---
|
| 2 |
+
title: IndicTrans3 Translation API
|
| 3 |
emoji: 🚀
|
| 4 |
colorFrom: blue
|
| 5 |
+
colorTo: blue
|
| 6 |
sdk: docker
|
| 7 |
app_port: 7860
|
| 8 |
pinned: false
|
|
|
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# IndicTrans3 Translation API
|
| 12 |
|
| 13 |
+
Document-level translation for Indian languages.
|
| 14 |
|
| 15 |
+
## Supported Languages
|
| 16 |
|
| 17 |
+
15+ Indian languages including Hindi, Tamil, Telugu, Kannada, Bengali, Marathi, Gujarati, Malayalam, Punjabi, Odia, Assamese, Urdu, Sanskrit, Nepali, Maithili.
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
## Usage
|
| 20 |
|
| 21 |
```bash
|
| 22 |
+
curl -X POST https://krishna96k-indictrans3-api.hf.space/translate \
|
| 23 |
-H "Content-Type: application/json" \
|
| 24 |
+
-d '{"text": "Good morning", "src_lang": "English", "tgt_lang": "Hindi"}'
|
main.py
CHANGED
|
@@ -1,207 +1,117 @@
|
|
| 1 |
import os
|
| 2 |
-
import re
|
| 3 |
import logging
|
| 4 |
from contextlib import asynccontextmanager
|
| 5 |
|
| 6 |
import torch
|
| 7 |
from fastapi import FastAPI, HTTPException
|
| 8 |
-
from huggingface_hub import login
|
| 9 |
from pydantic import BaseModel, field_validator
|
| 10 |
-
from
|
| 11 |
-
|
| 12 |
-
try:
|
| 13 |
-
from IndicTransToolkit.processor import IndicProcessor
|
| 14 |
-
INDIC_AVAILABLE = True
|
| 15 |
-
except ImportError:
|
| 16 |
-
INDIC_AVAILABLE = False
|
| 17 |
-
logging.warning("IndicTransToolkit not installed")
|
| 18 |
|
| 19 |
logging.basicConfig(level=logging.INFO)
|
| 20 |
logger = logging.getLogger(__name__)
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
"
|
| 25 |
-
"
|
| 26 |
-
"
|
| 27 |
-
"
|
| 28 |
-
"
|
| 29 |
-
"
|
| 30 |
-
"
|
| 31 |
-
"
|
| 32 |
-
"
|
| 33 |
-
"
|
| 34 |
-
"
|
| 35 |
-
"
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
"
|
| 40 |
-
"indic_to_en": "ai4bharat/indictrans2-indic-en-1B",
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
# Script ranges for detection
|
| 44 |
-
SCRIPT_RANGES = {
|
| 45 |
-
"hin_Deva": (0x0900, 0x097F), # Devanagari
|
| 46 |
-
"kan_Knda": (0x0C80, 0x0CFF), # Kannada
|
| 47 |
-
"tam_Taml": (0x0B80, 0x0BFF), # Tamil
|
| 48 |
-
"tel_Telu": (0x0C00, 0x0C7F), # Telugu
|
| 49 |
-
"ben_Beng": (0x0980, 0x09FF), # Bengali
|
| 50 |
-
"guj_Gujr": (0x0A80, 0x0AFF), # Gujarati
|
| 51 |
-
"mal_Mlym": (0x0D00, 0x0D7F), # Malayalam
|
| 52 |
-
"pan_Guru": (0x0A00, 0x0A7F), # Gurmukhi
|
| 53 |
-
"ory_Orya": (0x0B00, 0x0B7F), # Odia
|
| 54 |
-
"asm_Beng": (0x0980, 0x09FF), # Assamese (same as Bengali)
|
| 55 |
-
"urd_Arab": (0x0600, 0x06FF), # Arabic
|
| 56 |
}
|
| 57 |
|
| 58 |
-
#
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
r'(?:[aeiouy]+[mn]?|[bcdfghjklmnpqrstvwxz]{2,})'
|
| 63 |
-
r'[\u0900-\u097F\u0C80-\u0CFF\u0B80-\u0BFF\u0C00-\u0C7F\u0980-\u09FF\u0A80-\u0AFF\u0D00-\u0D7F\u0A00-\u0A7F\u0B00-\u0B7F\u0600-\u06FF]*',
|
| 64 |
-
re.IGNORECASE
|
| 65 |
-
)
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
Detect if text contains transliterated English words.
|
| 73 |
-
Returns True if transliteration detected, False if proper translation.
|
| 74 |
-
"""
|
| 75 |
-
if not text or target_lang == "eng_Latn":
|
| 76 |
-
return False
|
| 77 |
-
|
| 78 |
-
# Get script range for target language
|
| 79 |
-
script_range = SCRIPT_RANGES.get(target_lang)
|
| 80 |
-
if not script_range:
|
| 81 |
-
return False
|
| 82 |
-
|
| 83 |
-
# Check if text contains characters from target script
|
| 84 |
-
has_target_script = any(script_range[0] <= ord(c) <= script_range[1] for c in text)
|
| 85 |
-
if not has_target_script:
|
| 86 |
-
return True # No target script characters? Definitely wrong
|
| 87 |
-
|
| 88 |
-
# Check for English consonant clusters (strong indicator of transliteration)
|
| 89 |
-
# English words have characteristic consonant patterns
|
| 90 |
-
english_consonant_clusters = re.compile(r'[bcdfghjklmnpqrstvwxz]{3,}', re.IGNORECASE)
|
| 91 |
-
if english_consonant_clusters.search(text):
|
| 92 |
-
return True
|
| 93 |
-
|
| 94 |
-
# Check for common English word endings in transliterated form
|
| 95 |
-
english_endings = re.compile(r'[aeiouy]?(?:ing|tion|ment|ness|ity|ive|ous|ance|ence|logy|graph)$', re.IGNORECASE)
|
| 96 |
-
words = text.split()
|
| 97 |
-
for word in words:
|
| 98 |
-
if english_endings.search(word):
|
| 99 |
-
return True
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
return
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
elif tgt_lang == "kan_Knda":
|
| 127 |
-
return "ಶುಭೋದಯ"
|
| 128 |
-
elif tgt_lang == "tam_Taml":
|
| 129 |
-
return "காலை வணக்கம்"
|
| 130 |
-
elif tgt_lang == "tel_Telu":
|
| 131 |
-
return "శుభోదయం"
|
| 132 |
-
elif tgt_lang == "ben_Beng":
|
| 133 |
-
return "সুপ্রভাত"
|
| 134 |
-
elif tgt_lang == "mar_Deva":
|
| 135 |
-
return "शुभ प्रभात"
|
| 136 |
-
elif tgt_lang == "guj_Gujr":
|
| 137 |
-
return "સુપ્રભાત"
|
| 138 |
-
elif tgt_lang == "mal_Mlym":
|
| 139 |
-
return "സുപ്രഭാതം"
|
| 140 |
|
| 141 |
-
#
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
|
|
|
|
|
|
| 149 |
|
| 150 |
-
#
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
return "ಧನ್ಯವಾದಗಳು"
|
| 156 |
-
elif tgt_lang == "tam_Taml":
|
| 157 |
-
return "நன்றி"
|
| 158 |
-
elif tgt_lang == "tel_Telu":
|
| 159 |
-
return "ధన్యవాదాలు"
|
| 160 |
-
|
| 161 |
-
return text # Return original if no fix found
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
return models[key], processors.get(key)
|
| 166 |
-
|
| 167 |
-
hf_token = os.environ.get("HF_TOKEN")
|
| 168 |
-
if hf_token:
|
| 169 |
-
login(token=hf_token)
|
| 170 |
-
|
| 171 |
-
checkpoint = MODEL_MAP[key]
|
| 172 |
-
logger.info(f"Loading {checkpoint}...")
|
| 173 |
-
|
| 174 |
-
tokenizer = AutoTokenizer.from_pretrained(checkpoint, trust_remote_code=True)
|
| 175 |
-
model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint, trust_remote_code=True)
|
| 176 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 177 |
-
model = model.to(device).eval()
|
| 178 |
-
|
| 179 |
-
if INDIC_AVAILABLE:
|
| 180 |
-
processor = IndicProcessor(inference=True)
|
| 181 |
-
processors[key] = processor
|
| 182 |
-
else:
|
| 183 |
-
processor = None
|
| 184 |
-
|
| 185 |
-
models[key] = {"tokenizer": tokenizer, "model": model, "device": device}
|
| 186 |
-
logger.info(f"Loaded {key} on {device}")
|
| 187 |
-
|
| 188 |
-
return models[key], processor
|
| 189 |
|
| 190 |
@asynccontextmanager
|
| 191 |
async def lifespan(app: FastAPI):
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
for key in ["en_to_indic", "indic_to_en"]:
|
| 196 |
-
try:
|
| 197 |
-
load_model_and_processor(key)
|
| 198 |
-
except Exception as e:
|
| 199 |
-
logger.warning(f"Could not preload {key}: {e}")
|
| 200 |
yield
|
| 201 |
-
|
| 202 |
-
processors.clear()
|
| 203 |
|
| 204 |
-
app = FastAPI(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
class TranslateRequest(BaseModel):
|
| 207 |
text: str
|
|
@@ -218,8 +128,8 @@ class TranslateRequest(BaseModel):
|
|
| 218 |
@field_validator("src_lang", "tgt_lang")
|
| 219 |
@classmethod
|
| 220 |
def lang_supported(cls, v):
|
| 221 |
-
if v not in SUPPORTED_LANGUAGES:
|
| 222 |
-
raise ValueError(f"Unsupported language: {v}")
|
| 223 |
return v
|
| 224 |
|
| 225 |
@app.post("/translate")
|
|
@@ -229,98 +139,28 @@ async def translate(request: TranslateRequest):
|
|
| 229 |
if request.src_lang == request.tgt_lang:
|
| 230 |
raise HTTPException(400, "Source and target must be different")
|
| 231 |
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
else:
|
| 238 |
-
raise HTTPException(400, f"Only English ↔ Indian language translation is supported.")
|
| 239 |
-
|
| 240 |
-
# Load model and processor
|
| 241 |
-
model_data, processor = load_model_and_processor(model_key)
|
| 242 |
-
tokenizer = model_data["tokenizer"]
|
| 243 |
-
model = model_data["model"]
|
| 244 |
-
device = model_data["device"]
|
| 245 |
-
|
| 246 |
-
# Preprocess using IndicProcessor
|
| 247 |
-
if processor is not None:
|
| 248 |
-
batch = processor.preprocess_batch(
|
| 249 |
-
[request.text],
|
| 250 |
-
src_lang=request.src_lang,
|
| 251 |
-
tgt_lang=request.tgt_lang,
|
| 252 |
)
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
return_tensors="pt",
|
| 263 |
-
return_attention_mask=True,
|
| 264 |
-
).to(device)
|
| 265 |
-
|
| 266 |
-
# Generate
|
| 267 |
-
with torch.no_grad():
|
| 268 |
-
generated_tokens = model.generate(
|
| 269 |
-
**inputs,
|
| 270 |
-
use_cache=True,
|
| 271 |
-
min_length=0,
|
| 272 |
-
max_length=256,
|
| 273 |
-
num_beams=5,
|
| 274 |
-
num_return_sequences=1,
|
| 275 |
-
)
|
| 276 |
-
|
| 277 |
-
# Decode
|
| 278 |
-
result = tokenizer.batch_decode(
|
| 279 |
-
generated_tokens,
|
| 280 |
-
skip_special_tokens=True,
|
| 281 |
-
clean_up_tokenization_spaces=True,
|
| 282 |
-
)[0]
|
| 283 |
-
|
| 284 |
-
# Postprocess
|
| 285 |
-
if processor is not None:
|
| 286 |
-
translations = processor.postprocess_batch([result], lang=request.tgt_lang)
|
| 287 |
-
result = translations[0]
|
| 288 |
-
|
| 289 |
-
# ============================================================
|
| 290 |
-
# TRANSLITERATION BLOCKADE
|
| 291 |
-
# ============================================================
|
| 292 |
-
if request.src_lang == "eng_Latn" and request.tgt_lang != "eng_Latn":
|
| 293 |
-
# Check if result contains transliteration
|
| 294 |
-
if is_transliteration(result, request.tgt_lang):
|
| 295 |
-
logger.warning(f"Transliteration detected in: {result}")
|
| 296 |
-
|
| 297 |
-
# Try to fix common cases
|
| 298 |
-
fixed = fix_common_transliterations(result, request.src_lang, request.tgt_lang)
|
| 299 |
-
|
| 300 |
-
if fixed != result:
|
| 301 |
-
result = fixed
|
| 302 |
-
logger.info(f"Fixed transliteration to: {result}")
|
| 303 |
-
else:
|
| 304 |
-
# If we can't fix, add a warning note
|
| 305 |
-
result = result + " [Note: This appears to be transliteration, not proper translation]"
|
| 306 |
-
|
| 307 |
-
logger.info(f"Result: {result}")
|
| 308 |
-
|
| 309 |
-
return {
|
| 310 |
-
"translated_text": result,
|
| 311 |
-
"source": request.src_lang,
|
| 312 |
-
"target": request.tgt_lang,
|
| 313 |
-
"transliteration_detected": is_transliteration(result, request.tgt_lang) if request.src_lang == "eng_Latn" else False
|
| 314 |
-
}
|
| 315 |
|
| 316 |
@app.get("/health")
|
| 317 |
async def health():
|
| 318 |
return {
|
| 319 |
"status": "ok",
|
| 320 |
-
"
|
| 321 |
-
"
|
| 322 |
-
"hf_authenticated": bool(os.environ.get("HF_TOKEN")),
|
| 323 |
-
"indic_processor_available": INDIC_AVAILABLE
|
| 324 |
}
|
| 325 |
|
| 326 |
@app.get("/languages")
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import logging
|
| 3 |
from contextlib import asynccontextmanager
|
| 4 |
|
| 5 |
import torch
|
| 6 |
from fastapi import FastAPI, HTTPException
|
|
|
|
| 7 |
from pydantic import BaseModel, field_validator
|
| 8 |
+
from vllm import LLM, SamplingParams
|
| 9 |
+
from transformers import AutoTokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
logging.basicConfig(level=logging.INFO)
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
+
# Language codes mapping (ISO codes)
|
| 15 |
+
CODE_TO_LANG = {
|
| 16 |
+
"en": "English",
|
| 17 |
+
"hi": "Hindi",
|
| 18 |
+
"ta": "Tamil",
|
| 19 |
+
"te": "Telugu",
|
| 20 |
+
"bn": "Bengali",
|
| 21 |
+
"mr": "Marathi",
|
| 22 |
+
"gu": "Gujarati",
|
| 23 |
+
"kn": "Kannada",
|
| 24 |
+
"ml": "Malayalam",
|
| 25 |
+
"pa": "Punjabi",
|
| 26 |
+
"or": "Odia",
|
| 27 |
+
"as": "Assamese",
|
| 28 |
+
"ur": "Urdu",
|
| 29 |
+
"sa": "Sanskrit",
|
| 30 |
+
"ne": "Nepali",
|
| 31 |
+
"mai": "Maithili",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
}
|
| 33 |
|
| 34 |
+
# Reverse mapping for API
|
| 35 |
+
LANG_TO_CODE = {v: k for k, v in CODE_TO_LANG.items()}
|
| 36 |
+
# Add display names
|
| 37 |
+
SUPPORTED_LANGUAGES = CODE_TO_LANG
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
# Model path
|
| 40 |
+
MODEL_NAME = "ai4bharat/IndicTrans3-beta"
|
| 41 |
|
| 42 |
+
class TranslationModel:
|
| 43 |
+
_instance = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
def __new__(cls):
|
| 46 |
+
if cls._instance is None:
|
| 47 |
+
cls._instance = super().__new__(cls)
|
| 48 |
+
cls._instance._initialize()
|
| 49 |
+
return cls._instance
|
| 50 |
|
| 51 |
+
def _initialize(self):
|
| 52 |
+
logger.info(f"Loading IndicTrans3 model from {MODEL_NAME}...")
|
| 53 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 54 |
+
"meta-llama/Llama-3.2-3B-Instruct",
|
| 55 |
+
padding_side="left"
|
| 56 |
+
)
|
| 57 |
+
self.llm = LLM(
|
| 58 |
+
model=MODEL_NAME,
|
| 59 |
+
trust_remote_code=True,
|
| 60 |
+
tensor_parallel_size=1, # Increase if multiple GPUs
|
| 61 |
+
)
|
| 62 |
+
self.sampling_params = SamplingParams(
|
| 63 |
+
temperature=0.7,
|
| 64 |
+
max_tokens=4096,
|
| 65 |
+
repetition_penalty=1.0,
|
| 66 |
+
)
|
| 67 |
+
logger.info("IndicTrans3 loaded successfully")
|
| 68 |
+
|
| 69 |
+
def translate(self, text: str, src_lang: str, tgt_lang: str) -> str:
|
| 70 |
+
# Convert language codes if needed
|
| 71 |
+
if src_lang in LANG_TO_CODE:
|
| 72 |
+
src_code = LANG_TO_CODE[src_lang]
|
| 73 |
+
else:
|
| 74 |
+
src_code = src_lang
|
| 75 |
|
| 76 |
+
if tgt_lang in LANG_TO_CODE:
|
| 77 |
+
tgt_code = LANG_TO_CODE[tgt_lang]
|
| 78 |
+
else:
|
| 79 |
+
tgt_code = tgt_lang
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
+
# Create prompt using chat template
|
| 82 |
+
prompt_dict = [{
|
| 83 |
+
"role": "user",
|
| 84 |
+
"content": f"Translate the following text to {CODE_TO_LANG[tgt_code]}: {text}"
|
| 85 |
+
}]
|
| 86 |
+
prompt = self.tokenizer.apply_chat_template(
|
| 87 |
+
prompt_dict,
|
| 88 |
+
tokenize=False,
|
| 89 |
+
add_generation_prompt=True
|
| 90 |
+
)
|
| 91 |
|
| 92 |
+
# Generate translation
|
| 93 |
+
outputs = self.llm.generate([prompt], self.sampling_params)
|
| 94 |
+
result = outputs[0].outputs[0].text.strip()
|
| 95 |
+
|
| 96 |
+
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
# Global model instance
|
| 99 |
+
model_instance = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
@asynccontextmanager
|
| 102 |
async def lifespan(app: FastAPI):
|
| 103 |
+
global model_instance
|
| 104 |
+
logger.info("Starting IndicTrans3 Translation API...")
|
| 105 |
+
model_instance = TranslationModel()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
yield
|
| 107 |
+
logger.info("Shutting down...")
|
|
|
|
| 108 |
|
| 109 |
+
app = FastAPI(
|
| 110 |
+
title="IndicTrans3 Translation API",
|
| 111 |
+
description="Document-level translation for Indian languages",
|
| 112 |
+
version="3.0.0",
|
| 113 |
+
lifespan=lifespan,
|
| 114 |
+
)
|
| 115 |
|
| 116 |
class TranslateRequest(BaseModel):
|
| 117 |
text: str
|
|
|
|
| 128 |
@field_validator("src_lang", "tgt_lang")
|
| 129 |
@classmethod
|
| 130 |
def lang_supported(cls, v):
|
| 131 |
+
if v not in SUPPORTED_LANGUAGES and v not in CODE_TO_LANG:
|
| 132 |
+
raise ValueError(f"Unsupported language: {v}. Supported: {list(SUPPORTED_LANGUAGES.keys())}")
|
| 133 |
return v
|
| 134 |
|
| 135 |
@app.post("/translate")
|
|
|
|
| 139 |
if request.src_lang == request.tgt_lang:
|
| 140 |
raise HTTPException(400, "Source and target must be different")
|
| 141 |
|
| 142 |
+
try:
|
| 143 |
+
result = model_instance.translate(
|
| 144 |
+
request.text,
|
| 145 |
+
request.src_lang,
|
| 146 |
+
request.tgt_lang
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
)
|
| 148 |
+
|
| 149 |
+
return {
|
| 150 |
+
"translated_text": result,
|
| 151 |
+
"source": request.src_lang,
|
| 152 |
+
"target": request.tgt_lang
|
| 153 |
+
}
|
| 154 |
+
except Exception as e:
|
| 155 |
+
logger.exception("Translation failed")
|
| 156 |
+
raise HTTPException(500, f"Translation error: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
@app.get("/health")
|
| 159 |
async def health():
|
| 160 |
return {
|
| 161 |
"status": "ok",
|
| 162 |
+
"model": "IndicTrans3-beta",
|
| 163 |
+
"supported_languages": SUPPORTED_LANGUAGES
|
|
|
|
|
|
|
| 164 |
}
|
| 165 |
|
| 166 |
@app.get("/languages")
|
requirements.txt
CHANGED
|
@@ -3,6 +3,4 @@ uvicorn[standard]==0.29.0
|
|
| 3 |
pydantic==2.7.1
|
| 4 |
torch==2.3.0
|
| 5 |
transformers==4.41.1
|
| 6 |
-
|
| 7 |
-
huggingface-hub==0.23.0
|
| 8 |
-
IndicTransToolkit
|
|
|
|
| 3 |
pydantic==2.7.1
|
| 4 |
torch==2.3.0
|
| 5 |
transformers==4.41.1
|
| 6 |
+
vllm
|
|
|
|
|
|