nmwafiy commited on
Commit
553adbb
·
verified ·
1 Parent(s): 7da7a7b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -15
app.py CHANGED
@@ -1,34 +1,47 @@
1
  import malaya
2
- from fastapi import FastAPI
3
  from pydantic import BaseModel
4
  import uvicorn
 
5
 
6
- app = FastAPI()
7
 
8
- # Note: Loading the model can take a minute on the first run
9
- # as it downloads the pre-trained weights.
10
  try:
11
- # We specify the model='small' to save memory on free tier Spaces
12
- model = malaya.jawi.transformer(model = 'small')
13
- except AttributeError:
14
- # Fallback for certain versions if the attribute name differs
15
- model = malaya.jawi.deep_model()
 
16
 
17
  class RequestData(BaseModel):
18
  text: str
19
 
20
  @app.get("/")
21
- def read_root():
22
- return {"status": "API is running"}
23
 
24
  @app.post("/convert")
25
- async def convert(data: RequestData):
 
 
 
 
 
 
26
  try:
27
- # Malaya's transformer returns a list of results
28
  result = model.generate([data.text], to_lang='jawi')
29
- return {"jawi": result[0]}
 
 
 
30
  except Exception as e:
31
  return {"error": str(e)}
32
 
33
  if __name__ == "__main__":
34
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
1
  import malaya
2
+ from fastapi import FastAPI, HTTPException
3
  from pydantic import BaseModel
4
  import uvicorn
5
+ import os
6
 
7
+ app = FastAPI(title="Jawi Transliteration API")
8
 
9
+ # Load the modern Jawi model (T5-based)
10
+ # On first run, this downloads ~200MB of weights
11
  try:
12
+ print("Loading Jawi model... this may take a moment.")
13
+ model = malaya.jawi.huggingface()
14
+ print("Model loaded successfully!")
15
+ except Exception as e:
16
+ print(f"Failed to load model: {e}")
17
+ model = None
18
 
19
  class RequestData(BaseModel):
20
  text: str
21
 
22
  @app.get("/")
23
+ def health_check():
24
+ return {"status": "ready" if model else "loading/error"}
25
 
26
  @app.post("/convert")
27
+ async def convert_to_jawi(data: RequestData):
28
+ if not model:
29
+ raise HTTPException(status_code=503, detail="Model not loaded")
30
+
31
+ if not data.text.strip():
32
+ return {"jawi": ""}
33
+
34
  try:
35
+ # result is a list, we take the first item
36
  result = model.generate([data.text], to_lang='jawi')
37
+ return {
38
+ "rumi": data.text,
39
+ "jawi": result[0]
40
+ }
41
  except Exception as e:
42
  return {"error": str(e)}
43
 
44
  if __name__ == "__main__":
45
+ # HF Spaces uses port 7860 by default
46
+ port = int(os.environ.get("PORT", 7860))
47
+ uvicorn.run(app, host="0.0.0.0", port=port)