File size: 1,064 Bytes
5dc46ff
acf8bfe
fc58506
acf8bfe
fc58506
5dc46ff
 
 
 
fc58506
acf8bfe
 
 
 
 
 
 
 
 
 
 
fc58506
 
 
acf8bfe
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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)}")

@app.post("/translate")
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)}")