Khelendramee commited on
Commit
40ddc07
·
verified ·
1 Parent(s): 7ca4a7e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -27
app.py CHANGED
@@ -1,33 +1,33 @@
1
- from fastapi import FastAPI, UploadFile, File
2
- from fastapi.responses import JSONResponse
3
- from fastapi.staticfiles import StaticFiles
4
- from ultralytics import YOLO
5
- import shutil
6
- import uuid
7
- import base64
8
- import cv2
9
 
10
  app = FastAPI()
11
 
12
- # Mount static frontend
13
- app.mount("/", StaticFiles(directory="static", html=True), name="static")
14
 
15
- # Load YOLOv8 model
16
- model = YOLO("yolov8n.pt") # Use your own trained model if needed
 
 
17
 
18
- @app.post("/detect")
19
- async def detect(file: UploadFile = File(...)):
20
- # Save image to disk
21
- file_name = f"uploads/{uuid.uuid4()}.jpg"
22
- with open(file_name, "wb") as buffer:
23
- shutil.copyfileobj(file.file, buffer)
 
 
 
 
24
 
25
- # Detect objects
26
- results = model(file_name)
27
- result_image = results[0].plot() # Get image with boxes
28
-
29
- # Encode image to base64 to send back
30
- _, buffer = cv2.imencode('.jpg', result_image)
31
- b64_encoded = base64.b64encode(buffer).decode('utf-8')
32
-
33
- return JSONResponse(content={"image": b64_encoded})
 
1
+ from fastapi import FastAPI, BackgroundTasks
2
+ import time
3
+ import threading
 
 
 
 
 
4
 
5
  app = FastAPI()
6
 
7
+ task_running = False
8
+ thread = None
9
 
10
+ def background_task():
11
+ while task_running:
12
+ print("Task running...")
13
+ time.sleep(2)
14
 
15
+ @app.get("/start")
16
+ def start_task():
17
+ global task_running, thread
18
+ if not task_running:
19
+ task_running = True
20
+ thread = threading.Thread(target=background_task)
21
+ thread.start()
22
+ return {"message": "Task started"}
23
+ else:
24
+ return {"message": "Task already running"}
25
 
26
+ @app.get("/stop")
27
+ def stop_task():
28
+ global task_running
29
+ if task_running:
30
+ task_running = False
31
+ return {"message": "Task stopped"}
32
+ else:
33
+ return {"message": "No task running"}