Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -21,14 +21,26 @@ async def root():
|
|
| 21 |
|
| 22 |
@app.post("/predict")
|
| 23 |
async def predict(request: ImageRequest):
|
| 24 |
-
#
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
np_arr = np.frombuffer(image_bytes, np.uint8)
|
| 27 |
image = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
|
| 28 |
if image is None:
|
| 29 |
return {"error": "Invalid image"}
|
| 30 |
|
| 31 |
-
|
| 32 |
results = model.predict(image)
|
| 33 |
result = results[0]
|
| 34 |
|
|
@@ -44,18 +56,21 @@ async def predict(request: ImageRequest):
|
|
| 44 |
'''
|
| 45 |
Create unique key for each detection
|
| 46 |
EX: if multiple "missing_hole", keys will be:
|
| 47 |
-
"missing_hole", "
|
| 48 |
'''
|
| 49 |
if class_name in class_counters:
|
| 50 |
class_counters[class_name] += 1
|
| 51 |
-
key = f"{class_name}
|
| 52 |
else:
|
| 53 |
class_counters[class_name] = 1
|
| 54 |
key = class_name
|
| 55 |
|
| 56 |
json_result[key] = [x1, y1, x2, y2]
|
| 57 |
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
if __name__ == "__main__":
|
| 61 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 21 |
|
| 22 |
@app.post("/predict")
|
| 23 |
async def predict(request: ImageRequest):
|
| 24 |
+
# Check if the image string is empty
|
| 25 |
+
if not request.image:
|
| 26 |
+
return {"error": "Empty image string"}
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
# Attempt to decode Base64 string to bytes
|
| 30 |
+
image_bytes = base64.b64decode(request.image, validate=True)
|
| 31 |
+
except Exception as e:
|
| 32 |
+
return {"error": "Invalid Base64 string", "details": str(e)}
|
| 33 |
+
|
| 34 |
+
# Ensure the decoded bytes are not empty
|
| 35 |
+
if not image_bytes:
|
| 36 |
+
return {"error": "Decoded data is empty"}
|
| 37 |
+
|
| 38 |
np_arr = np.frombuffer(image_bytes, np.uint8)
|
| 39 |
image = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
|
| 40 |
if image is None:
|
| 41 |
return {"error": "Invalid image"}
|
| 42 |
|
| 43 |
+
|
| 44 |
results = model.predict(image)
|
| 45 |
result = results[0]
|
| 46 |
|
|
|
|
| 56 |
'''
|
| 57 |
Create unique key for each detection
|
| 58 |
EX: if multiple "missing_hole", keys will be:
|
| 59 |
+
"missing_hole", "missing_hole2", ...
|
| 60 |
'''
|
| 61 |
if class_name in class_counters:
|
| 62 |
class_counters[class_name] += 1
|
| 63 |
+
key = f"{class_name}{class_counters[class_name]}"
|
| 64 |
else:
|
| 65 |
class_counters[class_name] = 1
|
| 66 |
key = class_name
|
| 67 |
|
| 68 |
json_result[key] = [x1, y1, x2, y2]
|
| 69 |
|
| 70 |
+
# Creating statistics summary
|
| 71 |
+
statistics_summary = {f"{count} {name}{'s' if count > 1 else ''}": count for name, count in class_counters.items()}
|
| 72 |
+
|
| 73 |
+
return {"statistics": statistics_summary, "detections": json_result}
|
| 74 |
|
| 75 |
if __name__ == "__main__":
|
| 76 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|