hasmar03 commited on
Commit
f9230a6
·
verified ·
1 Parent(s): e32b63b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from fastapi import FastAPI
4
+ from pydantic import BaseModel
5
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
6
+
7
+ # ====== KONFIG ======
8
+ MODEL_ID = os.getenv("MODEL_ID", "hasmar03/mt5_id2md") # ganti kalau perlu
9
+ MAX_LEN = int(os.getenv("MAX_LEN", "128"))
10
+
11
+ # ====== LOAD MODEL SEKALI SAJA (startup) ======
12
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
13
+ model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_ID)
14
+ pipe = pipeline(
15
+ "text2text-generation",
16
+ model=model,
17
+ tokenizer=tokenizer,
18
+ max_length=MAX_LEN,
19
+ )
20
+
21
+ # ====== LOGIKA TERJEMAH ======
22
+ def _build_prompt(text: str, direction: str):
23
+ # sesuaikan dengan cara Anda melatih prompt-nya
24
+ if direction == "id2md":
25
+ return f"translate Indonesian to Mandar: {text}"
26
+ elif direction == "md2id":
27
+ return f"translate Mandar to Indonesian: {text}"
28
+ else:
29
+ return text
30
+
31
+ def translate_fn(text: str, arah: str):
32
+ prompt = _build_prompt(text, "id2md" if "Indonesia" in arah else "md2id")
33
+ out = pipe(prompt)[0]["generated_text"]
34
+ return out
35
+
36
+ # ====== UI GRADIO (untuk testing manual di browser) ======
37
+ with gr.Blocks(title="Mandar ↔ Indonesia Translator") as demo:
38
+ gr.Markdown("### Mandar ↔ Indonesia Translator")
39
+ arah = gr.Radio(
40
+ ["Indonesia → Mandar", "Mandar → Indonesia"],
41
+ value="Indonesia → Mandar",
42
+ label="Arah"
43
+ )
44
+ src = gr.Textbox(label="Teks sumber", lines=3)
45
+ btn = gr.Button("Terjemahkan")
46
+ out = gr.Textbox(label="Hasil", lines=3)
47
+ btn.click(translate_fn, inputs=[src, arah], outputs=out)
48
+
49
+ # ====== API FASTAPI (untuk Android / cURL) ======
50
+ class TranslateReq(BaseModel):
51
+ text: str
52
+ direction: str = "id2md" # "id2md" atau "md2id"
53
+
54
+ class TranslateResp(BaseModel):
55
+ translation: str
56
+
57
+ fastapi_app = FastAPI()
58
+
59
+ @fastapi_app.get("/health")
60
+ def health():
61
+ return {"ok": True}
62
+
63
+ @fastapi_app.post("/translate", response_model=TranslateResp)
64
+ def translate_api(body: TranslateReq):
65
+ prompt = _build_prompt(body.text, body.direction)
66
+ out = pipe(prompt)[0]["generated_text"]
67
+ return {"translation": out}
68
+
69
+ # Mount: root (/) tetap UI Gradio, endpoint /translate adalah FastAPI
70
+ app = gr.mount_gradio_app(fastapi_app, demo, path="/")