EN2AR-Service / app.py
SarahAshraf70's picture
Create app.py
dff402e verified
Raw History Blame Contribute Delete
1.43 kB
from fastapi import FastAPI, HTTPException
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import torch
# Initialize FastAPI app
app = FastAPI()
# Load the Hugging Face model and tokenizer
MODEL_NAME = "Helsinki-NLP/opus-mt-en-ar"
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
@app.get("/")
def read_root():
"""
Root endpoint to check service health.
"""
return {"message": "EN2AR Translation Service is up and running!"}
@app.post("/translate/")
def translate(text: str):
"""
Translate English text to Arabic.
Args:
text (str): The English text to be translated.
Returns:
dict: The translated text.
"""
if not text:
raise HTTPException(status_code=400, detail="Input text is required for translation.")
try:
# Tokenize the input text
inputs = tokenizer.encode(text, return_tensors="pt", max_length=512, truncation=True)
# Generate translation
outputs = model.generate(inputs, max_length=512, num_beams=5, early_stopping=True)
# Decode the translated text
translated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
return {"translated_text": translated_text}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Translation failed: {str(e)}")