Maruf commited on
Commit
7b6b122
·
1 Parent(s): f863e99
Files changed (2) hide show
  1. app.py +51 -14
  2. requirements.txt +4 -0
app.py CHANGED
@@ -1,21 +1,58 @@
 
 
1
  import torch
 
 
2
  import json
3
- import gradio as gr
 
 
 
4
 
5
  # Load YOLOv5s pretrained on COCO
6
  model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
7
 
8
- def detect(image):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  results = model(image)
10
- df = results.pandas().xyxy[0] # xmin, ymin, xmax, ymax, confidence, class, name
11
- return json.loads(df.to_json(orient="records"))
12
-
13
- iface = gr.Interface(
14
- fn=detect,
15
- inputs=gr.Image(type="pil"),
16
- outputs="json",
17
- title="COCO Object Detection (YOLOv5)",
18
- description="Upload an image to detect objects (COCO classes). Output is JSON."
19
- )
20
-
21
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile
2
+ from fastapi.responses import JSONResponse
3
  import torch
4
+ import pandas as pd
5
+ import uvicorn
6
  import json
7
+ from PIL import Image, UnidentifiedImageError
8
+ import io
9
+ import os
10
+ from datetime import datetime
11
 
12
  # Load YOLOv5s pretrained on COCO
13
  model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
14
 
15
+ # Folder to store annotated images
16
+ SAVE_DIR = "detections"
17
+ os.makedirs(SAVE_DIR, exist_ok=True)
18
+
19
+ app = FastAPI(title="COCO Object Detection API")
20
+
21
+ @app.post("/predict")
22
+ async def predict(file: UploadFile = File(...)):
23
+ try:
24
+ # Read uploaded file into bytes
25
+ image_bytes = await file.read()
26
+
27
+ # Open with Pillow safely
28
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
29
+ except UnidentifiedImageError:
30
+ return JSONResponse(
31
+ content={"error": "Unrecognized or invalid image file format."},
32
+ status_code=400
33
+ )
34
+
35
+ # Run inference
36
  results = model(image)
37
+
38
+ # Save annotated image locally
39
+ plotted_image = results.render()[0] # numpy array with boxes
40
+ pil_image = Image.fromarray(plotted_image)
41
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
42
+ save_path = os.path.join(SAVE_DIR, f"detection_{timestamp}.jpg")
43
+ pil_image.save(save_path, format="JPEG")
44
+ print (f"Saved annotated image to {save_path}")
45
+
46
+ # Convert results to JSON
47
+ df: pd.DataFrame = results.pandas().xyxy[0]
48
+ json_data = json.loads(df.to_json(orient="records"))
49
+
50
+ return JSONResponse(content=json_data)
51
+
52
+ @app.get("/")
53
+ def root():
54
+ return {"message": "Send POST /predict with an image file to get detections."}
55
+
56
+
57
+ if __name__ == "__main__":
58
+ uvicorn.run(app, host="0.0.0.0", port=8080)
requirements.txt CHANGED
@@ -2,3 +2,7 @@ torch
2
  torchvision
3
  pillow
4
  gradio
 
 
 
 
 
2
  torchvision
3
  pillow
4
  gradio
5
+ ultralytics
6
+ seaborn
7
+ fastapi
8
+ uvicorn