chryzxc commited on
Commit
0d7d4cd
·
verified ·
1 Parent(s): 0e2d401

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -28
app.py CHANGED
@@ -1,8 +1,8 @@
1
  from fastapi import FastAPI, HTTPException, Request
 
2
  from onnxruntime import InferenceSession
3
  from transformers import AutoTokenizer
4
  import numpy as np
5
- import os
6
  import uvicorn
7
 
8
  app = FastAPI()
@@ -15,21 +15,23 @@ tokenizer = AutoTokenizer.from_pretrained(
15
  )
16
 
17
  # Load ONNX model
18
- try:
19
- session = InferenceSession("model.onnx")
20
- print("Model loaded successfully")
21
- except Exception as e:
22
- print(f"Failed to load model: {str(e)}")
23
- raise
24
 
25
- @app.get("/")
26
- def health_check():
27
- return {"status": "OK", "model": "ONNX"}
 
 
 
 
 
 
 
 
28
 
29
  @app.post("/api/predict")
30
  async def predict(request: Request):
31
  try:
32
- # Get JSON input
33
  data = await request.json()
34
  text = data.get("text", "")
35
 
@@ -45,30 +47,22 @@ async def predict(request: Request):
45
  max_length=32
46
  )
47
 
48
- # Prepare ONNX inputs with correct shapes
49
- onnx_inputs = {
50
  "input_ids": inputs["input_ids"].astype(np.int64),
51
  "attention_mask": inputs["attention_mask"].astype(np.int64)
52
- }
53
-
54
- # Run inference
55
- outputs = session.run(None, onnx_inputs)
56
-
57
- # Convert outputs to list and handle numpy types
58
- embedding = outputs[0][0].astype(float).tolist() # First output, first batch
59
 
60
- return {
61
- "embedding": embedding,
 
62
  "tokens": tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
63
  }
64
 
 
 
65
  except Exception as e:
66
  raise HTTPException(status_code=500, detail=str(e))
67
 
68
  if __name__ == "__main__":
69
- uvicorn.run(
70
- "app:app",
71
- host="0.0.0.0",
72
- port=7860,
73
- reload=False
74
- )
 
1
  from fastapi import FastAPI, HTTPException, Request
2
+ from fastapi.encoders import jsonable_encoder
3
  from onnxruntime import InferenceSession
4
  from transformers import AutoTokenizer
5
  import numpy as np
 
6
  import uvicorn
7
 
8
  app = FastAPI()
 
15
  )
16
 
17
  # Load ONNX model
18
+ session = InferenceSession("model.onnx")
 
 
 
 
 
19
 
20
+ def convert_output(value):
21
+ """Recursively convert numpy types to native Python types"""
22
+ if isinstance(value, (np.generic, np.ndarray)):
23
+ if value.size == 1:
24
+ return float(value.item()) # Convert single values to float
25
+ return value.astype(float).tolist() # Convert arrays to list
26
+ elif isinstance(value, list):
27
+ return [convert_output(x) for x in value]
28
+ elif isinstance(value, dict):
29
+ return {k: convert_output(v) for k, v in value.items()}
30
+ return value
31
 
32
  @app.post("/api/predict")
33
  async def predict(request: Request):
34
  try:
 
35
  data = await request.json()
36
  text = data.get("text", "")
37
 
 
47
  max_length=32
48
  )
49
 
50
+ # Run model
51
+ outputs = session.run(None, {
52
  "input_ids": inputs["input_ids"].astype(np.int64),
53
  "attention_mask": inputs["attention_mask"].astype(np.int64)
54
+ })
 
 
 
 
 
 
55
 
56
+ # Prepare response with converted types
57
+ response = {
58
+ "embedding": convert_output(outputs[0]), # Process main output
59
  "tokens": tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
60
  }
61
 
62
+ return jsonable_encoder(response)
63
+
64
  except Exception as e:
65
  raise HTTPException(status_code=500, detail=str(e))
66
 
67
  if __name__ == "__main__":
68
+ uvicorn.run(app, host="0.0.0.0", port=7860)