Spaces:
Sleeping
Sleeping
api code changed
Browse files- src/serve.py +22 -36
src/serve.py
CHANGED
|
@@ -1,68 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from PIL import Image
|
| 2 |
-
from torchvision import transforms
|
| 3 |
import torch
|
|
|
|
| 4 |
import os
|
| 5 |
-
from
|
| 6 |
-
from fastapi.responses import JSONResponse
|
| 7 |
-
from io import BytesIO
|
| 8 |
-
|
| 9 |
-
# from dotenv import load_dotenv
|
| 10 |
-
from .model import MalwareNet, malware_classes # assuming malware_classes contains class names
|
| 11 |
-
|
| 12 |
-
# load_dotenv()
|
| 13 |
|
| 14 |
app = FastAPI()
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
image = Image.open(image_path).convert("RGB")
|
| 19 |
preprocess = transforms.Compose([
|
| 20 |
-
transforms.Resize((224, 224)),
|
| 21 |
-
transforms.ToTensor(),
|
| 22 |
-
transforms.Normalize(
|
| 23 |
-
mean=[0.485, 0.456, 0.406],
|
| 24 |
-
std=[0.229, 0.224, 0.225]
|
| 25 |
-
)
|
| 26 |
])
|
| 27 |
-
return preprocess(image).unsqueeze(0)
|
| 28 |
|
| 29 |
-
# Load model and its weights
|
| 30 |
def load_model():
|
| 31 |
model = MalwareNet()
|
| 32 |
base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 33 |
-
model_location = os.path.join(base_dir, '../model/malwareNet.pt')
|
| 34 |
state_dict = torch.load(model_location, map_location=torch.device('cpu'), weights_only=True)
|
| 35 |
model.load_state_dict(state_dict)
|
| 36 |
-
model.eval()
|
| 37 |
return model
|
| 38 |
|
| 39 |
-
@app.get("/")
|
| 40 |
-
def status():
|
| 41 |
-
return {"status": "ok"}
|
| 42 |
-
|
| 43 |
@app.post("/predict")
|
| 44 |
-
async def predict(
|
| 45 |
-
image_path = data.get("image_url")
|
| 46 |
-
if not os.path.exists(image_path):
|
| 47 |
-
raise HTTPException(status_code=400, detail="Image path does not exist.")
|
| 48 |
-
|
| 49 |
try:
|
| 50 |
-
#
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
# Load the model and make the prediction
|
| 54 |
model = load_model()
|
| 55 |
-
with torch.no_grad():
|
| 56 |
prediction = model(img_tensor)
|
| 57 |
|
| 58 |
# Get the predicted class
|
| 59 |
predicted_class = malware_classes[torch.argmax(prediction).item()]
|
| 60 |
|
| 61 |
-
return JSONResponse(content={"
|
| 62 |
-
|
| 63 |
except Exception as e:
|
| 64 |
raise HTTPException(status_code=500, detail=f"Error processing the image: {e}")
|
| 65 |
|
|
|
|
| 66 |
if __name__ == "__main__":
|
| 67 |
import uvicorn
|
| 68 |
uvicorn.run(
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, File, UploadFile
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
from io import BytesIO
|
| 4 |
from PIL import Image
|
|
|
|
| 5 |
import torch
|
| 6 |
+
from torchvision import transforms
|
| 7 |
import os
|
| 8 |
+
from .model import MalwareNet, malware_classes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
app = FastAPI()
|
| 11 |
|
| 12 |
+
def preprocess_image(image_data):
|
| 13 |
+
image = Image.open(BytesIO(image_data)).convert("RGB")
|
|
|
|
| 14 |
preprocess = transforms.Compose([
|
| 15 |
+
transforms.Resize((224, 224)),
|
| 16 |
+
transforms.ToTensor(),
|
| 17 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
|
|
|
|
|
|
|
|
|
| 18 |
])
|
| 19 |
+
return preprocess(image).unsqueeze(0)
|
| 20 |
|
|
|
|
| 21 |
def load_model():
|
| 22 |
model = MalwareNet()
|
| 23 |
base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 24 |
+
model_location = os.path.join(base_dir, '../model/malwareNet.pt')
|
| 25 |
state_dict = torch.load(model_location, map_location=torch.device('cpu'), weights_only=True)
|
| 26 |
model.load_state_dict(state_dict)
|
| 27 |
+
model.eval()
|
| 28 |
return model
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
@app.post("/predict")
|
| 31 |
+
async def predict(file: UploadFile = File(...)):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
try:
|
| 33 |
+
# Read file bytes
|
| 34 |
+
image_data = await file.read()
|
| 35 |
+
|
| 36 |
+
# Preprocess the image
|
| 37 |
+
img_tensor = preprocess_image(image_data)
|
| 38 |
|
| 39 |
# Load the model and make the prediction
|
| 40 |
model = load_model()
|
| 41 |
+
with torch.no_grad():
|
| 42 |
prediction = model(img_tensor)
|
| 43 |
|
| 44 |
# Get the predicted class
|
| 45 |
predicted_class = malware_classes[torch.argmax(prediction).item()]
|
| 46 |
|
| 47 |
+
return JSONResponse(content={"prediction": predicted_class})
|
|
|
|
| 48 |
except Exception as e:
|
| 49 |
raise HTTPException(status_code=500, detail=f"Error processing the image: {e}")
|
| 50 |
|
| 51 |
+
|
| 52 |
if __name__ == "__main__":
|
| 53 |
import uvicorn
|
| 54 |
uvicorn.run(
|