Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,20 +1,35 @@
|
|
| 1 |
-
from
|
|
|
|
|
|
|
|
|
|
| 2 |
import requests
|
| 3 |
import os
|
| 4 |
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 15 |
|
| 16 |
def query_hf(model_id, inputs, parameters=None):
|
| 17 |
-
"""Panggil Hugging Face Inference API"""
|
| 18 |
url = f"https://api-inference.huggingface.co/models/{model_id}"
|
| 19 |
payload = {"inputs": inputs}
|
| 20 |
if parameters:
|
|
@@ -25,38 +40,66 @@ def query_hf(model_id, inputs, parameters=None):
|
|
| 25 |
else:
|
| 26 |
return {"error": f"{response.status_code}: {response.text}"}
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
data = request.json
|
| 32 |
-
user_input = data.get("text", "").strip()
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
if not user_input:
|
| 35 |
-
return
|
| 36 |
|
| 37 |
-
# ---
|
| 38 |
if user_input.lower().startswith("terjemahkan:"):
|
| 39 |
-
# Hapus prefix "terjemahkan:" → ambil teks mentah
|
| 40 |
clean_text = user_input[len("terjemahkan:"):].strip()
|
| 41 |
if not clean_text:
|
| 42 |
-
return
|
| 43 |
|
| 44 |
-
#
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
else:
|
| 51 |
-
# Panggil Qwen sebagai chatbot interaktif
|
| 52 |
-
result = query_hf(QWEN_MODEL, user_input, parameters={"max_new_tokens": 200})
|
| 53 |
-
if isinstance(result, list) and "generated_text" in result[0]:
|
| 54 |
-
reply = result[0]["generated_text"]
|
| 55 |
-
else:
|
| 56 |
-
reply = result.get("error", "Terjadi kesalahan pada model interaktif.")
|
| 57 |
-
|
| 58 |
-
return jsonify({"reply": reply})
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
if __name__ == "__main__":
|
| 62 |
-
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
| 4 |
+
import torch
|
| 5 |
import requests
|
| 6 |
import os
|
| 7 |
|
| 8 |
+
# 🔹 Model Translator (lokal di Space)
|
| 9 |
+
MODELS = {
|
| 10 |
+
"in2bg": "rahmanansah/t5-id-bugis",
|
| 11 |
+
"bg2id": "rahmanansah/t5-bugis-id"
|
| 12 |
+
}
|
| 13 |
|
| 14 |
+
loaded_models = {}
|
| 15 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 16 |
|
| 17 |
+
def load_model(model_id):
|
| 18 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 19 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(model_id).to(device)
|
| 20 |
+
return tokenizer, model
|
| 21 |
|
| 22 |
+
for key, model_id in MODELS.items():
|
| 23 |
+
print(f"🔄 Loading {key} -> {model_id}")
|
| 24 |
+
loaded_models[key] = load_model(model_id)
|
| 25 |
+
print("✅ Semua model sudah diload")
|
| 26 |
+
|
| 27 |
+
# 🔹 Model Chat (panggil API Hugging Face)
|
| 28 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 29 |
+
QWEN_MODEL = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 30 |
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 31 |
|
| 32 |
def query_hf(model_id, inputs, parameters=None):
|
|
|
|
| 33 |
url = f"https://api-inference.huggingface.co/models/{model_id}"
|
| 34 |
payload = {"inputs": inputs}
|
| 35 |
if parameters:
|
|
|
|
| 40 |
else:
|
| 41 |
return {"error": f"{response.status_code}: {response.text}"}
|
| 42 |
|
| 43 |
+
# 🔹 FastAPI
|
| 44 |
+
app = FastAPI()
|
| 45 |
+
|
| 46 |
+
class TranslateInput(BaseModel):
|
| 47 |
+
text: str
|
| 48 |
+
model: str # "in2bg" atau "bg2id"
|
| 49 |
+
|
| 50 |
+
@app.post("/translate")
|
| 51 |
+
def translate(input: TranslateInput):
|
| 52 |
+
if input.model not in loaded_models:
|
| 53 |
+
return {"error": f"Model '{input.model}' tidak tersedia. Pilihan: {list(loaded_models.keys())}"}
|
| 54 |
+
|
| 55 |
+
tokenizer, model = loaded_models[input.model]
|
| 56 |
+
text = input.text.strip()
|
| 57 |
|
| 58 |
+
if not text:
|
| 59 |
+
return {"result": ""}
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
if input.model == "in2bg":
|
| 62 |
+
prefixed_text = f"translate id2bg: {text}"
|
| 63 |
+
else:
|
| 64 |
+
prefixed_text = f"translate bg2id: {text}"
|
| 65 |
+
|
| 66 |
+
inputs = tokenizer(prefixed_text, return_tensors="pt").to(device)
|
| 67 |
+
outputs = model.generate(**inputs, max_length=64)
|
| 68 |
+
decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 69 |
+
|
| 70 |
+
return {"result": decoded}
|
| 71 |
+
|
| 72 |
+
# 🔹 Chat endpoint
|
| 73 |
+
class ChatInput(BaseModel):
|
| 74 |
+
text: str
|
| 75 |
+
|
| 76 |
+
@app.post("/chat")
|
| 77 |
+
def chat(input: ChatInput):
|
| 78 |
+
user_input = input.text.strip()
|
| 79 |
if not user_input:
|
| 80 |
+
return {"reply": "Teks kosong, silakan masukkan sesuatu."}
|
| 81 |
|
| 82 |
+
# --- Jika prefiks "terjemahkan:", arahkan ke translator ---
|
| 83 |
if user_input.lower().startswith("terjemahkan:"):
|
|
|
|
| 84 |
clean_text = user_input[len("terjemahkan:"):].strip()
|
| 85 |
if not clean_text:
|
| 86 |
+
return {"reply": "Silakan masukkan teks setelah 'terjemahkan:'"}
|
| 87 |
|
| 88 |
+
# Default Indo -> Bugis
|
| 89 |
+
tokenizer, model = loaded_models["in2bg"]
|
| 90 |
+
inputs = tokenizer(f"translate id2bg: {clean_text}", return_tensors="pt").to(device)
|
| 91 |
+
outputs = model.generate(**inputs, max_length=64)
|
| 92 |
+
decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 93 |
+
return {"reply": decoded}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
+
# --- Jika bukan, pakai Qwen chatbot ---
|
| 96 |
+
result = query_hf(QWEN_MODEL, user_input, parameters={"max_new_tokens": 200})
|
| 97 |
+
if isinstance(result, list) and "generated_text" in result[0]:
|
| 98 |
+
reply = result[0]["generated_text"]
|
| 99 |
+
else:
|
| 100 |
+
reply = result.get("error", "Terjadi kesalahan pada model interaktif.")
|
| 101 |
+
return {"reply": reply}
|
| 102 |
|
| 103 |
if __name__ == "__main__":
|
| 104 |
+
import uvicorn
|
| 105 |
+
uvicorn.run("app:app", host="0.0.0.0", port=7860)
|