File size: 1,974 Bytes
ecf6004
 
6f69b1d
ecf6004
6f69b1d
ecf6004
6f69b1d
 
 
ecf6004
 
6f69b1d
 
 
 
 
 
 
 
 
 
 
 
 
 
bc4b22c
6f69b1d
 
 
 
ecf6004
6f69b1d
 
 
 
 
 
 
 
 
 
 
ecf6004
 
 
 
 
6f69b1d
 
 
ecf6004
 
6f69b1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from transformers import pipeline
import os

# -------------------------------
# Initialize FastAPI app
# -------------------------------
app = FastAPI(title="Language Translator API")

# -------------------------------
# Enable CORS for your extension
# -------------------------------
# Replace with your Chrome extension ID for security, or use "*" for testing
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        #"*",  # ✅ recommended
        "*"  # ⚠️ uncomment for open access during testing
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# -------------------------------
# Model Loading
# -------------------------------
MODEL_PATH = "./model"

if not os.path.exists(MODEL_PATH):
    raise RuntimeError("Model folder not found! Make sure '/model' is uploaded to your Space.")

print("📁 Model files found:", os.listdir(MODEL_PATH))

# Load model from local folder (pre-downloaded)
translator = pipeline("translation", model=MODEL_PATH)

# -------------------------------
# Request/Response Models
# -------------------------------
class TranslationRequest(BaseModel):
    text: str
    src_lang: str
    tgt_lang: str

# -------------------------------
# API Route
# -------------------------------
@app.post("/translate")
def translate(req: TranslationRequest):
    """
    Translate text from source language to target language.
    """
    try:
        result = translator(
            req.text,
            src_lang=req.src_lang,
            tgt_lang=req.tgt_lang
        )
        return {"translated_text": result[0]['translation_text']}
    except Exception as e:
        return {"error": str(e)}

# -------------------------------
# Root route
# -------------------------------
@app.get("/")
def root():
    return {"message": "✅ Language Translator API is running successfully!"}