Spaces:
Sleeping
Sleeping
File size: 6,861 Bytes
f2518c9 d5327ae 297eef6 f2518c9 297eef6 f2518c9 ae00b72 297eef6 0f27524 297eef6 f2518c9 297eef6 ae00b72 297eef6 d5327ae ae00b72 297eef6 9541352 ae00b72 9541352 d5327ae ae00b72 297eef6 b0f7e66 297eef6 ae00b72 297eef6 ae00b72 297eef6 d5327ae ae00b72 d5327ae ae00b72 297eef6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from ultralytics import YOLO
from typing import Dict
# from core.defect_detection import *
from core.defect_detection_image import *
from utils import *
import uvicorn, asyncio
# ============================================================
# APP SETUP
# ============================================================
app = FastAPI(
title="AI Engine Dummy",
version="1.0.0",
description="""
## ๐ง AI Engine Dummy API
API simulasi integrasi **AI Engine** untuk deteksi defect pada sistem monitoring.
---
### ๐น Endpoint Utama
- `/start-detection` โ Memulai simulasi deteksi untuk beberapa kamera.
### ๐น Webhook
- Gunakan https://webhook.site/ untuk menerima hasil deteksi.
- Pastikan mengisi `webhook_url` pada payload request.
### ๐น Simulasi
- Tiap kamera akan melakukan deteksi selama max 5 (Sesuai Waktu Timeout) detik.
- Jika ditemukan defect, hasil langsung dikirim ke webhook dan semua kamera berhenti.
- Jika semua kamera tidak menemukan defect setelah 5 (Sesuai Waktu Timeout) detik โ status "OK" dikirim satu kali.
""",
)
# ============================================================
# CORS CONFIG (Hanya port 8899)
# ============================================================
allowed_origins = [
"*",
# "http://localhost:8899",
# "http://127.0.0.1:8899",
# "http://0.0.0.0:8899",
]
app.add_middleware(
CORSMiddleware,
allow_origins=allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ============================================================
# ROUTES
# ============================================================
@app.get("/")
def read_root():
return {"message": "Defect Detection API is running."}
@app.post("/start-detection")
async def start_detection(data: Dict):
station_id = data.get("station_id")
parts = data.get("parts")
webhook_url = data.get("webhook_url")
cameras = data.get("cameras", [])
# -------------------------------
# BASIC VALIDATION
# -------------------------------
if not station_id or not parts or not webhook_url or not cameras:
return JSONResponse(
status_code=400,
content={
"status": "error",
"station_id": station_id,
"camera_count": len(cameras),
"message": "Missing required fields"
}
)
# -------------------------------
# VALIDATION BEFORE EXECUTION
# -------------------------------
required_parts_fields = ["id", "pin_api", "name", "sku"]
validation_errors = validate_input(required_parts_fields, station_id, cameras, parts, webhook_url)
if validation_errors:
logger.error("[VALIDATION FAILED] Input data is invalid.")
for err in validation_errors:
logger.error(f" - {err}")
return JSONResponse(
status_code=400,
content={
"status": "error",
"station_id": station_id,
"camera_count": len(cameras),
"message": " | ".join(validation_errors)
}
)
logger.info(f"[INFO] Get metadata parts")
model_path = model_by_id_metadata(parts['id'])
logger.info(f"[INFO] Checking model_path")
model = model_path
# =====================================================
# BASE64 IMAGE DETECTION (NOT VIDEO STREAM)
# =====================================================
logger.info(f"[START] Station {station_id} โ {len(cameras)} camera(s) with base64 images")
# Jalankan detection di background
asyncio.create_task(
run_detection_group(station_id, cameras, webhook_url, model, parts)
)
return JSONResponse(
status_code=200,
content={
"status": "started",
"station_id": station_id,
"camera_count": len(cameras),
"message": "Base64 image detection is running in background."
}
)
# @app.post("/start-detection") # live stream
# async def start_detection(data: Dict):
# station_id = data.get("station_id")
# parts = data.get("parts")
# webhook_url = data.get("webhook_url")
# cameras = data.get("cameras", [])
# if not station_id or not parts or not webhook_url or not cameras:
# return JSONResponse(
# status_code=400,
# content={
# "status": "error",
# "station_id": station_id,
# "camera_count": len(cameras),
# "message": "Missing required fields"
# }
# )
# # -------------------------------
# # VALIDATION BEFORE EXECUTION
# # -------------------------------
# required_parts_fields = [
# "id",
# "pin_api",
# "name",
# "sku"
# ]
# validation_errors = validate_input(required_parts_fields, station_id, cameras, parts, webhook_url)
# if validation_errors:
# logger.error("[VALIDATION FAILED] Input data is invalid.")
# for err in validation_errors:
# logger.error(f" - {err}")
# return JSONResponse(
# status_code=400,
# content={
# "status": "error",
# "station_id": station_id,
# "camera_count": len(cameras),
# "message": " | ".join(validation_errors)
# }
# )
# logger.info(f"[INFO] Get metadata parts")
# model_path = model_by_id_metadata(parts['id'])
# logger.info(f"[INFO] Checking model_path")
# if isinstance(model_path, str):
# if not os.path.exists(model_path):
# logger.info(f"[INFO] Model file not found")
# return {"status": "error", "message": f"Model file not found: {model_path}"}
# model = YOLO(model_path)
# else:
# model = model_path
# logger.info(f"[START] Station {station_id} โ {len(cameras)} kamera diproses")
# # running background
# asyncio.create_task(run_detection_group(station_id, cameras, webhook_url, model, parts))
# return JSONResponse(
# status_code=200,
# content={
# "status": "started",
# "station_id": station_id,
# "camera_count": len(cameras),
# "message": "Detection is running in background."
# }
# )
# ============================================================
# ENTRY POINT
# ============================================================
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)
|