Rahaf2001 commited on
Commit
c0b49be
ยท
verified ยท
1 Parent(s): b134dd2

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +24 -63
main.py CHANGED
@@ -1,12 +1,10 @@
1
  from fastapi import FastAPI, UploadFile, File
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from ultralytics import YOLO
4
- from PIL import Image
5
- import io, requests, os, tempfile
6
- import cv2
7
 
8
  app = FastAPI()
9
- #
10
  app.add_middleware(
11
  CORSMiddleware,
12
  allow_origins=["*"],
@@ -25,12 +23,10 @@ app.add_middleware(
25
  # f.write(r.content)
26
  # print(" Model ready")
27
 
28
- # download_model()
29
  print("Loading model...")
30
  model = YOLO("best.pt")
31
  print("Model ready")
32
 
33
-
34
  CLASS_NAMES = {
35
  0: 'crack',
36
  1: 'other',
@@ -52,62 +48,24 @@ def root():
52
  @app.post("/detect")
53
  async def detect(file: UploadFile = File(...)):
54
  contents = await file.read()
55
- filename = file.filename.lower()
56
-
57
- # โ”€โ”€ ููŠุฏูŠูˆ โ”€โ”€
58
- if any(filename.endswith(ext) for ext in ['.mp4', '.avi', '.mov', '.mkv']):
59
- with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as tmp:
60
- tmp.write(contents)
61
- tmp_path = tmp.name
62
-
63
- cap = cv2.VideoCapture(tmp_path)
64
- total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
65
-
66
- # ู†ุญู„ู„ 5 frames ู…ูˆุฒุนุฉ ุนู„ู‰ ุงู„ููŠุฏูŠูˆ
67
- sample_points = [int(total_frames * i / 5) for i in range(1, 6)]
68
- all_detections = []
69
-
70
- for frame_num in sample_points:
71
- cap.set(cv2.CAP_PROP_POS_FRAMES, frame_num)
72
- ret, frame = cap.read()
73
- if not ret:
74
- continue
75
 
76
- img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
77
- results = model(img)
 
 
78
 
79
- for box in results[0].boxes:
80
- cls = int(box.cls)
81
- conf = float(box.conf)
82
- xywhn = box.xywhn[0].tolist()
83
- area = xywhn[2] * xywhn[3]
84
- all_detections.append({
85
- "damage_type": CLASS_NAMES.get(cls, 'other'),
86
- "confidence" : round(conf, 3),
87
- "severity" : get_severity(conf, area),
88
- "bbox" : xywhn,
89
- "frame" : frame_num
90
- })
91
 
92
- cap.release()
93
- os.unlink(tmp_path)
94
 
95
- return {
96
- "total" : len(all_detections),
97
- "detections": all_detections
98
- }
99
-
100
- # โ”€โ”€ ุตูˆุฑุฉ โ”€โ”€
101
- else:
102
- try:
103
- img = Image.open(io.BytesIO(contents))
104
- except Exception as e:
105
- return {"error": str(e), "total": 0, "detections": []}
106
-
107
- results = model(img)
108
- all_detections = []
109
-
110
- for box in results[0].boxes:
111
  cls = int(box.cls)
112
  conf = float(box.conf)
113
  xywhn = box.xywhn[0].tolist()
@@ -117,10 +75,13 @@ async def detect(file: UploadFile = File(...)):
117
  "confidence" : round(conf, 3),
118
  "severity" : get_severity(conf, area),
119
  "bbox" : xywhn,
120
- "frame" : 0
121
  })
 
 
 
122
 
123
- return {
124
- "total" : len(all_detections),
125
- "detections": all_detections
126
- }
 
1
  from fastapi import FastAPI, UploadFile, File
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from ultralytics import YOLO
4
+ import os, tempfile
 
 
5
 
6
  app = FastAPI()
7
+
8
  app.add_middleware(
9
  CORSMiddleware,
10
  allow_origins=["*"],
 
23
  # f.write(r.content)
24
  # print(" Model ready")
25
 
 
26
  print("Loading model...")
27
  model = YOLO("best.pt")
28
  print("Model ready")
29
 
 
30
  CLASS_NAMES = {
31
  0: 'crack',
32
  1: 'other',
 
48
  @app.post("/detect")
49
  async def detect(file: UploadFile = File(...)):
50
  contents = await file.read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
+ suffix = '.' + file.filename.split('.')[-1]
53
+ with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
54
+ tmp.write(contents)
55
+ tmp_path = tmp.name
56
 
57
+ results = model.predict(
58
+ source = tmp_path,
59
+ conf = 0.25,
60
+ verbose = False,
61
+ stream = True
62
+ )
 
 
 
 
 
 
63
 
64
+ all_detections = []
65
+ frame_num = 0
66
 
67
+ for result in results:
68
+ for box in result.boxes:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  cls = int(box.cls)
70
  conf = float(box.conf)
71
  xywhn = box.xywhn[0].tolist()
 
75
  "confidence" : round(conf, 3),
76
  "severity" : get_severity(conf, area),
77
  "bbox" : xywhn,
78
+ "frame" : frame_num
79
  })
80
+ frame_num += 1
81
+
82
+ os.unlink(tmp_path)
83
 
84
+ return {
85
+ "total" : len(all_detections),
86
+ "detections": all_detections
87
+ }