huggingface-php / app.py
azaharizaman's picture
Update
6fda1a0
Raw History Blame Contribute Delete
977 Bytes
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import pipeline
app = FastAPI(title="English to French Translator")
# Load model once at startuprfff
translator = pipeline("translation_en_to_fr", model="Helsinki-NLP/opus-mt-en-fr")
class TranslateRequest(BaseModel):
text: str
class TranslateResponse(BaseModel):
translated_text: str
@app.get("/")
def root():
return {"message": "Welcome to the English–French Translation API!"}
@app.post("/translate", response_model=TranslateResponse)
def translate(req: TranslateRequest):
if not req.text.strip():
raise HTTPException(status_code=400, detail="Text input cannot be empty.")
try:
result = translator(req.text)
translated = result[0]["translation_text"]
return TranslateResponse(translated_text=translated)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Translation failed: {str(e)}")