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)