Spaces:
Running
Running
import os | |
from fastapi import FastAPI, HTTPException | |
from transformers import pipeline | |
import logging | |
# Atur direktori cache untuk Hugging Face | |
os.environ["HF_HOME"] = "/app/cache" | |
os.environ["TRANSFORMERS_CACHE"] = "/app/cache" | |
app = FastAPI() | |
logging.basicConfig(level=logging.INFO) | |
logger = logging.getLogger(__name__) | |
try: | |
logger.info("Loading translation model...") | |
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-id") | |
logger.info("Model loaded successfully") | |
except Exception as e: | |
logger.error(f"Failed to load model: {str(e)}") | |
raise Exception(f"Model initialization failed: {str(e)}") | |
async def translate(text: str): | |
if not text: | |
raise HTTPException(status_code=400, detail="Text input is required") | |
try: | |
result = translator(text) | |
return {"translated_text": result[0]["translation_text"]} | |
except Exception as e: | |
logger.error(f"Translation failed: {str(e)}") | |
raise HTTPException(status_code=500, detail=f"Translation failed: {str(e)}") |