File size: 2,793 Bytes
8a325f1
 
9ee0d9e
8a325f1
51a8967
8a325f1
 
 
 
9a940c6
8a325f1
 
 
9ee0d9e
 
 
 
 
 
 
8a325f1
 
 
 
 
 
afbb598
8a325f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51a8967
 
 
 
 
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
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import gradio as gr
from deep_translator import GoogleTranslator
import uvicorn # uvicorn ကို import လုပ်ပါ

# --- 1. API အတွက် Input Model ကိုသတ်မှတ်ပါ ---
class TranslationRequest(BaseModel):
    text: str

# --- 2. ဘာသာပြန်တဲ့ အဓိက Logic ကို Function တစ်ခုအဖြစ်ခွဲထုတ်ပါ ---
def get_translation(text: str) -> str:
    """ဘာသာပြန်တဲ့ core logic"""
    if not text:
        return ""
    try:
        translator = GoogleTranslator(source='auto', target='en')
        result = translator.translate(text)
        return result
    except Exception as e:
        # API အတွက်ဆိုရင် ပိုပြီးတိကျတဲ့ error message ပြန်ပေးသင့်ပါတယ်
        raise HTTPException(status_code=500, detail=f"Translation error: {str(e)}")

# --- 3. FastAPI App ကိုတည်ဆောက်ပြီး API Endpoint ဖန်တီးပါ ---
api = FastAPI()

@api.post("/translate")
def handle_api_translation(request: TranslationRequest):
    """
    Standard REST API endpoint.
    JSON body: {"text": "your text here"}
    """
    translated_text = get_translation(request.text)
    return {
        "original_text": request.text,
        "translated_text": translated_text
    }

# --- 4. Gradio UI ကိုတည်ဆောက်ပါ ---
def gradio_translate_wrapper(text: str):
    """Gradio အတွက် error handling သီးသန့်လုပ်ထားတဲ့ wrapper"""
    try:
        return get_translation(text)
    except HTTPException as e:
        return f"Error: {e.detail}"

gradio_ui = gr.Interface(
    fn=gradio_translate_wrapper,
    inputs=gr.Textbox(label="Input Text", lines=4),
    outputs=gr.Textbox(label="Translated Text", lines=4),
    title="Text Translation API",
    description="Translate text using the UI or call the /api/translate endpoint."
)

# --- 5. FastAPI app ပေါ်မှာ Gradio UI ကို mount လုပ်ပါ ---
app = gr.mount_gradio_app(api, gradio_ui, path="/")

# --- 6. Server ကို တိုက်ရိုက် run ရန်အတွက် main block ထည့်သွင်းပါ ---
# Hugging Face Space runner က uvicorn ကို အလိုအလျောက် run ပေးပေမယ့်၊
# ဒီ block က startup ပြဿနာအချို့ကို ဖြေရှင်းပေးနိုင်ပြီး app ကို အမြဲတမ်း run နေစေဖို့ သေချာစေပါတယ်။
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)