Spaces:
Sleeping

Dimas2005 commited on
Commit
264ee86
·
1 Parent(s): 7ae6520

commit docker3

Browse files
Files changed (4) hide show
  1. Dockerfile +7 -1
  2. README.md +1 -0
  3. app.py +46 -55
  4. requirements.txt +6 -5
Dockerfile CHANGED
@@ -1,6 +1,12 @@
1
  FROM python:3.10-slim
 
2
  WORKDIR /app
 
3
  COPY requirements.txt .
4
  RUN pip install --no-cache-dir -r requirements.txt
5
- COPY . .
 
 
 
 
6
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
1
  FROM python:3.10-slim
2
+
3
  WORKDIR /app
4
+
5
  COPY requirements.txt .
6
  RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ COPY app.py .
9
+
10
+ EXPOSE 7860
11
+
12
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -6,6 +6,7 @@ colorTo: pink
6
  sdk: docker
7
  pinned: false
8
  license: apache-2.0
 
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
6
  sdk: docker
7
  pinned: false
8
  license: apache-2.0
9
+ app_port: 7860
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -1,68 +1,49 @@
1
- from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
- from fastapi.responses import RedirectResponse
4
  from pydantic import BaseModel
5
- import torch
6
  from transformers import AutoModelForCausalLM, AutoTokenizer
7
- import os
8
 
9
- # ================== INISIALISASI APP ==================
10
- app = FastAPI(title="Sijawa Translation API", version="1.0")
11
 
12
- # CORS – izinkan semua origin (bisa diperketat nanti)
13
  app.add_middleware(
14
  CORSMiddleware,
15
  allow_origins=["*"],
16
- allow_credentials=True,
17
  allow_methods=["*"],
18
  allow_headers=["*"],
19
  )
20
 
21
- # ================== ROOT ENDPOINT ==================
22
- @app.get("/")
23
- async def root():
24
- """Redirect ke dokumentasi interaktif FastAPI (/docs)"""
25
- return RedirectResponse(url="/docs")
26
-
27
- # ================== LOAD MODEL ==================
28
- model_name = "Dimas2005/sijawa-llama3-v2"
29
-
30
- # HF_TOKEN akan otomatis terbaca dari environment jika diset sebagai Secret
31
- # (token tidak wajib, tapi mempercepat download)
32
- try:
33
- tokenizer = AutoTokenizer.from_pretrained(model_name)
34
- model = AutoModelForCausalLM.from_pretrained(
35
- model_name,
36
- device_map="cpu",
37
- dtype=torch.bfloat16 # ganti dari torch_dtype (sudah deprecated)
38
- )
39
- except Exception as e:
40
- print(f"❌ Gagal memuat model: {e}")
41
- # Jika gagal, app tetap berjalan tapi endpoint /translate akan error.
42
- # Lebih baik matikan app agar tidak misleading.
43
- raise RuntimeError("Model tidak dapat dimuat, periksa koneksi dan token.") from e
44
-
45
- # ================== SCHEMA REQUEST ==================
46
- class TranslationRequest(BaseModel):
47
  text: str
48
- direction: str = "jawa_to_id" # pilihan: "jawa_to_id" atau "id_to_jawa"
49
 
50
- # ================== ENDPOINT TERJEMAHAN ==================
51
- @app.post("/translate")
52
- def translate_api(req: TranslationRequest):
53
- # Validasi direction
54
- if req.direction == "jawa_to_id":
55
  instruction = "Terjemahkan Bahasa Jawa ke Bahasa Indonesia."
56
- elif req.direction == "id_to_jawa":
57
- instruction = "Terjemahkan Bahasa Indonesia ke Bahasa Jawa."
58
  else:
59
- raise HTTPException(
60
- status_code=400,
61
- detail="direction harus 'jawa_to_id' atau 'id_to_jawa'"
62
- )
 
 
 
63
 
64
- # Bangun prompt sesuai format model
65
- prompt = f"### Instruksi:\n{instruction}\n\n### Input:\n{req.text}\n\n### Output:\n"
66
  inputs = tokenizer(prompt, return_tensors="pt")
67
 
68
  with torch.no_grad():
@@ -70,19 +51,29 @@ def translate_api(req: TranslationRequest):
70
  **inputs,
71
  max_new_tokens=64,
72
  do_sample=False,
 
 
73
  pad_token_id=tokenizer.eos_token_id,
74
  eos_token_id=tokenizer.eos_token_id,
75
  repetition_penalty=1.2,
76
  no_repeat_ngram_size=3,
77
  )
78
 
79
- # Ekstrak token baru (tanpa prompt)
80
  new_tokens = outputs[0][inputs["input_ids"].shape[1]:]
81
- result = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
 
82
 
83
- return {"status": "success", "result": result}
84
 
85
- # ================== HEALTH CHECK (opsional) ==================
86
- @app.get("/health")
87
- def health_check():
88
- return {"status": "ok", "model_loaded": True}
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
  from fastapi.middleware.cors import CORSMiddleware
 
3
  from pydantic import BaseModel
 
4
  from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ import torch
6
 
7
+ app = FastAPI()
 
8
 
9
+ # Izinkan semua origin supaya React kamu bisa akses
10
  app.add_middleware(
11
  CORSMiddleware,
12
  allow_origins=["*"],
 
13
  allow_methods=["*"],
14
  allow_headers=["*"],
15
  )
16
 
17
+ MODEL_NAME = "Dimas2005/sijawa-llama3-v2"
18
+
19
+ print("Loading model... (ini memakan waktu ~1-2 menit saat cold start)")
20
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
21
+ model = AutoModelForCausalLM.from_pretrained(
22
+ MODEL_NAME,
23
+ torch_dtype=torch.float32, # CPU harus float32
24
+ device_map="cpu",
25
+ )
26
+ model.eval()
27
+ print("Model siap!")
28
+
29
+
30
+ class TranslateRequest(BaseModel):
 
 
 
 
 
 
 
 
 
 
 
 
31
  text: str
32
+ direction: str = "jawa_to_id" # "jawa_to_id" atau "id_to_jawa"
33
 
34
+
35
+ def translate(text: str, direction: str) -> str:
36
+ if direction == "jawa_to_id":
 
 
37
  instruction = "Terjemahkan Bahasa Jawa ke Bahasa Indonesia."
 
 
38
  else:
39
+ instruction = "Terjemahkan Bahasa Indonesia ke Bahasa Jawa."
40
+
41
+ prompt = (
42
+ f"### Instruksi:\n{instruction}\n\n"
43
+ f"### Input:\n{text}\n\n"
44
+ f"### Output:\n"
45
+ )
46
 
 
 
47
  inputs = tokenizer(prompt, return_tensors="pt")
48
 
49
  with torch.no_grad():
 
51
  **inputs,
52
  max_new_tokens=64,
53
  do_sample=False,
54
+ temperature=1.0,
55
+ use_cache=True,
56
  pad_token_id=tokenizer.eos_token_id,
57
  eos_token_id=tokenizer.eos_token_id,
58
  repetition_penalty=1.2,
59
  no_repeat_ngram_size=3,
60
  )
61
 
 
62
  new_tokens = outputs[0][inputs["input_ids"].shape[1]:]
63
+ result = tokenizer.decode(new_tokens, skip_special_tokens=True)
64
+ return result.strip()
65
 
 
66
 
67
+ @app.get("/")
68
+ def root():
69
+ return {"status": "SiJawa API is running"}
70
+
71
+
72
+ @app.post("/translate")
73
+ def translate_endpoint(req: TranslateRequest):
74
+ result = translate(req.text, req.direction)
75
+ return {
76
+ "input": req.text,
77
+ "direction": req.direction,
78
+ "result": result,
79
+ }
requirements.txt CHANGED
@@ -1,6 +1,7 @@
 
1
  uvicorn
2
- pydantic
3
- fastapi==0.111.0
4
- uvicorn==0.30.1
5
- torch==2.3.0
6
- transformers==4.41.2
 
1
+ fastapi
2
  uvicorn
3
+ transformers>=4.40.0
4
+ torch
5
+ accelerate
6
+ sentencepiece
7
+ protobuf