Spaces:
No application file
No application file
Download app.py from SarahAshraf70/EN2AR-Service: direct link, hf CLI and curl.
- Browser
- Download file 1.43 kB
-
https://huggingface.co/spaces/SarahAshraf70/EN2AR-Service/resolve/main/app.py
- Command line
-
hf download hf://spaces/SarahAshraf70/EN2AR-Service/app.py
-
curl -L -o app.py https://huggingface.co/spaces/SarahAshraf70/EN2AR-Service/resolve/main/app.py
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) | |
| def read_root(): | |
| """ | |
| Root endpoint to check service health. | |
| """ | |
| return {"message": "EN2AR Translation Service is up and running!"} | |
| 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)}") | |