Spaces:
Sleeping
Sleeping
Add Mask R-CNN integration & with updated backend logic
Browse files- .gitignore +31 -3
- backend/api.py +122 -0
- backend/claude_coco.py +0 -168
- backend/cv_detector.py +42 -234
- backend/gemini_coco.py +0 -147
- backend/openai_coco.py +0 -124
- backend/test_llm.py +0 -175
- backend/yolo_v8/configs/dataset.yaml +0 -10
- backend/yolo_v8/requirements.txt +0 -6
- backend/yolo_v8/src/convert_dataset.py +0 -79
- backend/yolo_v8/src/evaluate.py +0 -13
- backend/yolo_v8/src/inference.py +0 -12
- backend/yolo_v8/src/preprocess.py +0 -18
- backend/yolo_v8/src/train.py +0 -44
- backend/yolo_v8/src/utils.py +0 -15
- frontend/src/App.js +2 -7
- frontend/src/App.jsx +0 -0
- frontend/src/api/claimApiCV.js +0 -0
- frontend/src/components/ResultsDisplay.js +49 -43
.gitignore
CHANGED
|
@@ -216,8 +216,36 @@ frontend/node_modules/
|
|
| 216 |
frontend/build/
|
| 217 |
.DS_Store
|
| 218 |
|
| 219 |
-
backend/yolo_v8/data/
|
| 220 |
-
backend/yolo_v8/outputs/
|
| 221 |
runs/
|
| 222 |
backend/test_*.py
|
| 223 |
-
backend/llm_eval_results.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
frontend/build/
|
| 217 |
.DS_Store
|
| 218 |
|
|
|
|
|
|
|
| 219 |
runs/
|
| 220 |
backend/test_*.py
|
| 221 |
+
backend/llm_eval_results.py
|
| 222 |
+
|
| 223 |
+
# Model weights (too large for git, share via Drive/scp)
|
| 224 |
+
models/*.pth
|
| 225 |
+
pycache/
|
| 226 |
+
*.py[cod]
|
| 227 |
+
*$py.class
|
| 228 |
+
.venv/
|
| 229 |
+
venv/
|
| 230 |
+
env/
|
| 231 |
+
bin/
|
| 232 |
+
lib/
|
| 233 |
+
include/
|
| 234 |
+
.env
|
| 235 |
+
.env.local
|
| 236 |
+
**/.pth
|
| 237 |
+
**/.pt
|
| 238 |
+
**/.h5
|
| 239 |
+
**/.weights
|
| 240 |
+
**/*.onnx
|
| 241 |
+
archive/
|
| 242 |
+
runs/
|
| 243 |
+
backend/temp/
|
| 244 |
+
results/
|
| 245 |
+
logs/
|
| 246 |
+
build_log.txt
|
| 247 |
+
node_modules/
|
| 248 |
+
dist/
|
| 249 |
+
build/
|
| 250 |
+
.DS_Store
|
| 251 |
+
Thumbs.db
|
backend/api.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Auto-Owners AI Claims API
|
| 3 |
+
CV Detection: Mask R-CNN (parts) + Mask R-CNN (damage types)
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 7 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
+
from fastapi.responses import HTMLResponse
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import shutil
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
from cv_detector import CVDetector
|
| 14 |
+
|
| 15 |
+
app = FastAPI(title="Auto-Owners AI Claims API")
|
| 16 |
+
|
| 17 |
+
app.add_middleware(
|
| 18 |
+
CORSMiddleware,
|
| 19 |
+
allow_origins=["*"],
|
| 20 |
+
allow_credentials=True,
|
| 21 |
+
allow_methods=["*"],
|
| 22 |
+
allow_headers=["*"],
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
print("\nLoading CV models...")
|
| 26 |
+
cv_detector = CVDetector()
|
| 27 |
+
print("Models ready.\n")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@app.post("/detect")
|
| 31 |
+
async def detect(image: UploadFile = File(...)):
|
| 32 |
+
"""
|
| 33 |
+
Upload a vehicle photo. Returns detected parts and damage types as JSON.
|
| 34 |
+
"""
|
| 35 |
+
if not image.filename:
|
| 36 |
+
raise HTTPException(status_code=400, detail="No image provided")
|
| 37 |
+
|
| 38 |
+
temp_path = Path(f"temp/temp_{image.filename}")
|
| 39 |
+
temp_path.parent.mkdir(exist_ok=True)
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
with open(temp_path, "wb") as f:
|
| 43 |
+
shutil.copyfileobj(image.file, f)
|
| 44 |
+
|
| 45 |
+
t0 = time.perf_counter()
|
| 46 |
+
detections = cv_detector.detect(str(temp_path))
|
| 47 |
+
elapsed_ms = round((time.perf_counter() - t0) * 1000, 1)
|
| 48 |
+
|
| 49 |
+
return {
|
| 50 |
+
"detections": detections,
|
| 51 |
+
"summary": {
|
| 52 |
+
"total_damaged_parts": len(detections),
|
| 53 |
+
"parts": list({d["part"] for d in detections}),
|
| 54 |
+
"damage_types": list({d["damage_type"] for d in detections}),
|
| 55 |
+
},
|
| 56 |
+
"inference_ms": elapsed_ms,
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
except Exception as e:
|
| 60 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 61 |
+
|
| 62 |
+
finally:
|
| 63 |
+
if temp_path.exists():
|
| 64 |
+
temp_path.unlink()
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@app.get("/health")
|
| 68 |
+
def health():
|
| 69 |
+
return {"status": "healthy", "models": "parts + damage Mask R-CNN"}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@app.get("/", response_class=HTMLResponse)
|
| 73 |
+
def home():
|
| 74 |
+
return """
|
| 75 |
+
<!DOCTYPE html>
|
| 76 |
+
<html>
|
| 77 |
+
<head>
|
| 78 |
+
<title>CV Damage Detection</title>
|
| 79 |
+
<style>
|
| 80 |
+
body { font-family: Arial, sans-serif; max-width: 700px; margin: 50px auto; padding: 20px; background: #f5f5f5; }
|
| 81 |
+
.container { background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
|
| 82 |
+
h1 { color: #003d7a; }
|
| 83 |
+
input[type=file], button { display: block; width: 100%; padding: 10px; margin: 10px 0; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
|
| 84 |
+
button { background: #003d7a; color: white; border: none; cursor: pointer; font-size: 16px; }
|
| 85 |
+
button:hover { background: #005ca8; }
|
| 86 |
+
pre { background: #f8f9fa; padding: 15px; border-radius: 4px; overflow-x: auto; font-size: 13px; }
|
| 87 |
+
</style>
|
| 88 |
+
</head>
|
| 89 |
+
<body>
|
| 90 |
+
<div class="container">
|
| 91 |
+
<h1>CV Damage Detection</h1>
|
| 92 |
+
<p>Mask R-CNN parts detection + damage type detection</p>
|
| 93 |
+
<form id="form">
|
| 94 |
+
<input type="file" name="image" accept="image/*" required>
|
| 95 |
+
<button type="submit">Detect Damage</button>
|
| 96 |
+
</form>
|
| 97 |
+
<div id="result"></div>
|
| 98 |
+
</div>
|
| 99 |
+
<script>
|
| 100 |
+
document.getElementById('form').onsubmit = async (e) => {
|
| 101 |
+
e.preventDefault();
|
| 102 |
+
const resultDiv = document.getElementById('result');
|
| 103 |
+
resultDiv.innerHTML = '<p>Running detection...</p>';
|
| 104 |
+
const formData = new FormData(e.target);
|
| 105 |
+
try {
|
| 106 |
+
const res = await fetch('/detect', { method: 'POST', body: formData });
|
| 107 |
+
const data = await res.json();
|
| 108 |
+
if (!res.ok) { resultDiv.innerHTML = `<p><b>Error:</b> ${data.detail}</p>`; return; }
|
| 109 |
+
resultDiv.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
|
| 110 |
+
} catch (err) {
|
| 111 |
+
resultDiv.innerHTML = `<p><b>Error:</b> ${err.message}</p>`;
|
| 112 |
+
}
|
| 113 |
+
};
|
| 114 |
+
</script>
|
| 115 |
+
</body>
|
| 116 |
+
</html>
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
import uvicorn
|
| 122 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
backend/claude_coco.py
DELETED
|
@@ -1,168 +0,0 @@
|
|
| 1 |
-
import json, base64
|
| 2 |
-
from pathlib import Path
|
| 3 |
-
import anthropic
|
| 4 |
-
import os
|
| 5 |
-
from dotenv import load_dotenv
|
| 6 |
-
|
| 7 |
-
# load env variables
|
| 8 |
-
load_dotenv()
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def analyze_damage(image_path):
|
| 12 |
-
"""
|
| 13 |
-
Inputs image and returns a damaged parts list.
|
| 14 |
-
"""
|
| 15 |
-
client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
|
| 16 |
-
|
| 17 |
-
with open(image_path, "rb") as f:
|
| 18 |
-
b64 = base64.b64encode(f.read()).decode("utf-8")
|
| 19 |
-
|
| 20 |
-
# Match OpenAI prompt exactly for fair comparison
|
| 21 |
-
system_prompt = "You are a professional car damage classifier. Return ONLY JSON: {'damaged_parts': [{'part': 'name'}]}"
|
| 22 |
-
user_prompt = "Identify damage to: headlamp, front_bumper, hood, door, rear_bumper. Return ONLY JSON."
|
| 23 |
-
|
| 24 |
-
# Define JSON schema for structured output
|
| 25 |
-
schema = {
|
| 26 |
-
"type": "object",
|
| 27 |
-
"properties": {
|
| 28 |
-
"damaged_parts": {
|
| 29 |
-
"type": "array",
|
| 30 |
-
"items": {
|
| 31 |
-
"type": "object",
|
| 32 |
-
"properties": {"part": {"type": "string"}},
|
| 33 |
-
"required": ["part"],
|
| 34 |
-
},
|
| 35 |
-
}
|
| 36 |
-
},
|
| 37 |
-
"required": ["damaged_parts"],
|
| 38 |
-
}
|
| 39 |
-
|
| 40 |
-
try:
|
| 41 |
-
response = client.messages.create(
|
| 42 |
-
model="claude-sonnet-4-5-20250929",
|
| 43 |
-
max_tokens = 300,
|
| 44 |
-
system = system_prompt, # Change model here to test different ones
|
| 45 |
-
messages=[
|
| 46 |
-
{
|
| 47 |
-
"role": "user",
|
| 48 |
-
"content": [
|
| 49 |
-
{"type": "text", "text": user_prompt},
|
| 50 |
-
{
|
| 51 |
-
"type": "image",
|
| 52 |
-
"source": {
|
| 53 |
-
"type": "base64",
|
| 54 |
-
"media_type": "image/jpeg",
|
| 55 |
-
"data": b64,
|
| 56 |
-
},
|
| 57 |
-
},
|
| 58 |
-
],
|
| 59 |
-
}
|
| 60 |
-
],
|
| 61 |
-
tools = [{"name": "damaged_parts", "description":"...", "input_schema": schema}],
|
| 62 |
-
tool_choice = {"type": "tool", "name": "damaged_parts"}
|
| 63 |
-
)
|
| 64 |
-
|
| 65 |
-
tool_block = next(
|
| 66 |
-
(b for b in response.content if getattr(b, "type", None) == "tool_use"),
|
| 67 |
-
None
|
| 68 |
-
)
|
| 69 |
-
if tool_block is None:
|
| 70 |
-
raise ValueError("No tool_use block in Claude response")
|
| 71 |
-
|
| 72 |
-
result = tool_block.input
|
| 73 |
-
parts_list = result.get("damaged_parts", [])
|
| 74 |
-
|
| 75 |
-
cleaned = []
|
| 76 |
-
for item in parts_list:
|
| 77 |
-
if isinstance(item, str): cleaned.append(item)
|
| 78 |
-
elif isinstance(item, dict) and "part" in item: cleaned.append(item["part"])
|
| 79 |
-
return set(cleaned)
|
| 80 |
-
except Exception as e:
|
| 81 |
-
print(f"[Claude error] {type(e).__name__}: {e}")
|
| 82 |
-
return set()
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def run_benchmark(image_folder, labels_file, split_name):
|
| 86 |
-
"""
|
| 87 |
-
Runs against JSON labels to calculate accuracy.
|
| 88 |
-
"""
|
| 89 |
-
image_dir = Path(image_folder)
|
| 90 |
-
labels_path = Path(labels_file)
|
| 91 |
-
|
| 92 |
-
with open(labels_path) as f:
|
| 93 |
-
data = json.load(f)
|
| 94 |
-
|
| 95 |
-
# normalize category names
|
| 96 |
-
cats = {c["id"]: c["name"].lower().replace(" ", "_") for c in data["categories"]}
|
| 97 |
-
|
| 98 |
-
# map image IDs to ground truths
|
| 99 |
-
ground_truth = {}
|
| 100 |
-
for a in data["annotations"]:
|
| 101 |
-
img_id = a["image_id"]
|
| 102 |
-
if img_id not in ground_truth:
|
| 103 |
-
ground_truth[img_id] = set()
|
| 104 |
-
ground_truth[img_id].add(cats.get(a["category_id"]))
|
| 105 |
-
|
| 106 |
-
tp, fp, fn = 0, 0, 0
|
| 107 |
-
hamming_scores = []
|
| 108 |
-
|
| 109 |
-
print(f"\nBenchmarking {split_name.upper()}...")
|
| 110 |
-
for img in data["images"]:
|
| 111 |
-
path = image_dir / img["file_name"]
|
| 112 |
-
if not path.exists():
|
| 113 |
-
continue
|
| 114 |
-
|
| 115 |
-
pred = analyze_damage(str(path))
|
| 116 |
-
real = ground_truth.get(img["id"], set())
|
| 117 |
-
|
| 118 |
-
# precision/recall
|
| 119 |
-
tp += len(pred & real)
|
| 120 |
-
fp += len(pred - real)
|
| 121 |
-
fn += len(real - pred)
|
| 122 |
-
|
| 123 |
-
# partial matches count for accuracy
|
| 124 |
-
union = len(pred | real)
|
| 125 |
-
if union == 0:
|
| 126 |
-
hamming_scores.append(1.0) # no damage
|
| 127 |
-
else:
|
| 128 |
-
hamming_scores.append(len(pred & real) / union)
|
| 129 |
-
|
| 130 |
-
print(f" {img['file_name']} | AI: {list(pred)} | Real: {list(real)}")
|
| 131 |
-
|
| 132 |
-
# metrics
|
| 133 |
-
total = len(data["images"])
|
| 134 |
-
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
|
| 135 |
-
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
|
| 136 |
-
accuracy = sum(hamming_scores) / total
|
| 137 |
-
|
| 138 |
-
return {"precision": precision, "recall": recall, "accuracy": accuracy}
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
if __name__ == "__main__":
|
| 142 |
-
script_dir = Path(__file__).parent.resolve()
|
| 143 |
-
root = script_dir.parent
|
| 144 |
-
|
| 145 |
-
splits = [
|
| 146 |
-
{
|
| 147 |
-
"name": "train",
|
| 148 |
-
"dir": root / "archive" / "train",
|
| 149 |
-
"json": root / "archive" / "train" / "COCO_mul_train_annos.json",
|
| 150 |
-
},
|
| 151 |
-
{
|
| 152 |
-
"name": "val",
|
| 153 |
-
"dir": root / "archive" / "val",
|
| 154 |
-
"json": root / "archive" / "val" / "COCO_mul_val_annos.json",
|
| 155 |
-
},
|
| 156 |
-
]
|
| 157 |
-
|
| 158 |
-
print("\n" + "=" * 65)
|
| 159 |
-
print(f"{'SPLIT':<8} | {'PRECISION':<12} | {'RECALL':<12} | {'ACCURACY'}")
|
| 160 |
-
print("-" * 65)
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
for s in splits:
|
| 164 |
-
res = run_benchmark(s["dir"], s["json"], s["name"])
|
| 165 |
-
print(
|
| 166 |
-
f"{s['name'].upper():<8} | {res['precision']:<12.1%} | {res['recall']:<12.1%} | {res['accuracy']:.1%}"
|
| 167 |
-
)
|
| 168 |
-
print("=" * 65)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/cv_detector.py
CHANGED
|
@@ -1,247 +1,55 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
-
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
-
import
|
| 9 |
-
|
| 10 |
-
from torchvision.models.detection import maskrcnn_resnet50_fpn
|
| 11 |
-
from PIL import Image
|
| 12 |
-
import torchvision.transforms as T
|
| 13 |
-
import numpy as np
|
| 14 |
|
| 15 |
class CVDetector:
|
| 16 |
-
def __init__(self
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
"""
|
| 20 |
-
Initialize two-model detection system
|
| 21 |
-
|
| 22 |
-
Args:
|
| 23 |
-
parts_model_path: Path to Mask R-CNN parts weights
|
| 24 |
-
damage_model_path: Path to Mask R-CNN damage weights
|
| 25 |
-
"""
|
| 26 |
-
|
| 27 |
print("Loading CV models...")
|
| 28 |
-
|
| 29 |
-
# Device
|
| 30 |
-
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 31 |
-
print(f"Using device: {self.device}")
|
| 32 |
-
|
| 33 |
-
# Load parts model
|
| 34 |
-
self.parts_model = self._load_model(parts_model_path, num_classes=21) # Adjust num_classes
|
| 35 |
print("✓ Mask R-CNN (parts) loaded")
|
| 36 |
-
|
| 37 |
-
# Load damage model
|
| 38 |
-
self.damage_model = self._load_model(damage_model_path, num_classes=6) # Adjust num_classes
|
| 39 |
print("✓ Mask R-CNN (damage types) loaded")
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
# IoU threshold
|
| 45 |
-
self.iou_threshold = 0.3
|
| 46 |
-
|
| 47 |
-
# Class names (update these based on your training)
|
| 48 |
-
self.part_names = {
|
| 49 |
-
1: 'Back-bumper',
|
| 50 |
-
2: 'Back-door',
|
| 51 |
-
3: 'Back-wheel',
|
| 52 |
-
4: 'Back-window',
|
| 53 |
-
5: 'Back-windshield',
|
| 54 |
-
6: 'Fender',
|
| 55 |
-
7: 'Front-bumper',
|
| 56 |
-
8: 'Front-door',
|
| 57 |
-
8: 'Front-wheel',
|
| 58 |
-
9: 'Front-window',
|
| 59 |
-
10: 'Grille',
|
| 60 |
-
11: 'Headlight',
|
| 61 |
-
12: 'Hood',
|
| 62 |
-
13: 'License-plate',
|
| 63 |
-
14: 'Quarter-panel',
|
| 64 |
-
15: 'Rocker-panel',
|
| 65 |
-
16: 'Roof',
|
| 66 |
-
17: 'Tail-light',
|
| 67 |
-
18: 'Trunk',
|
| 68 |
-
19: 'Windshield'
|
| 69 |
-
}
|
| 70 |
-
|
| 71 |
-
self.damage_names = {
|
| 72 |
-
1: 'dent',
|
| 73 |
-
2: 'scratch',
|
| 74 |
-
3: 'crack',
|
| 75 |
-
4: 'glass_shatter',
|
| 76 |
-
5: 'lamp_broken',
|
| 77 |
-
6: 'tire_flat',
|
| 78 |
-
}
|
| 79 |
-
|
| 80 |
-
def _load_model(self, model_path, num_classes):
|
| 81 |
-
"""Load Mask R-CNN model"""
|
| 82 |
-
|
| 83 |
-
# Create model
|
| 84 |
-
model = maskrcnn_resnet50_fpn(weights=None, num_classes=num_classes)
|
| 85 |
-
|
| 86 |
-
# Load weights
|
| 87 |
-
checkpoint = torch.load(model_path, map_location=self.device)
|
| 88 |
-
|
| 89 |
-
# Handle different checkpoint formats
|
| 90 |
-
if 'model_state_dict' in checkpoint:
|
| 91 |
-
model.load_state_dict(checkpoint['model_state_dict'])
|
| 92 |
-
elif 'state_dict' in checkpoint:
|
| 93 |
-
model.load_state_dict(checkpoint['state_dict'])
|
| 94 |
-
else:
|
| 95 |
-
model.load_state_dict(checkpoint)
|
| 96 |
-
|
| 97 |
-
model.to(self.device)
|
| 98 |
-
model.eval()
|
| 99 |
-
|
| 100 |
-
return model
|
| 101 |
-
|
| 102 |
-
def detect(self, image_path, conf_threshold=0.25):
|
| 103 |
"""
|
| 104 |
-
Run two-model
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
List of detections with part, damage_type, bbox, confidence
|
| 112 |
"""
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
# STEP 1: Detect parts
|
| 119 |
-
with torch.no_grad():
|
| 120 |
-
parts_pred = self.parts_model([image_tensor])[0]
|
| 121 |
-
|
| 122 |
-
parts = self._extract_detections(
|
| 123 |
-
parts_pred,
|
| 124 |
-
self.part_names,
|
| 125 |
-
conf_threshold
|
| 126 |
-
)
|
| 127 |
-
|
| 128 |
-
# STEP 2: Detect damage types
|
| 129 |
-
with torch.no_grad():
|
| 130 |
-
damage_pred = self.damage_model([image_tensor])[0]
|
| 131 |
-
|
| 132 |
-
damages = self._extract_detections(
|
| 133 |
-
damage_pred,
|
| 134 |
-
self.damage_names,
|
| 135 |
-
conf_threshold
|
| 136 |
)
|
| 137 |
-
|
| 138 |
-
# STEP 3: Merge based on IoU
|
| 139 |
-
merged = self._merge_detections(parts, damages)
|
| 140 |
-
|
| 141 |
-
return merged
|
| 142 |
-
|
| 143 |
-
def _extract_detections(self, prediction, class_names, conf_threshold):
|
| 144 |
-
"""Extract detections from Mask R-CNN output"""
|
| 145 |
-
|
| 146 |
-
detections = []
|
| 147 |
-
|
| 148 |
-
boxes = prediction['boxes'].cpu().numpy()
|
| 149 |
-
labels = prediction['labels'].cpu().numpy()
|
| 150 |
-
scores = prediction['scores'].cpu().numpy()
|
| 151 |
-
|
| 152 |
-
for i in range(len(boxes)):
|
| 153 |
-
if scores[i] >= conf_threshold:
|
| 154 |
-
detections.append({
|
| 155 |
-
'label': class_names.get(labels[i], f'class_{labels[i]}'),
|
| 156 |
-
'bbox': boxes[i].tolist(),
|
| 157 |
-
'confidence': float(scores[i])
|
| 158 |
-
})
|
| 159 |
-
|
| 160 |
-
return detections
|
| 161 |
-
|
| 162 |
-
def _merge_detections(self, parts, damages):
|
| 163 |
-
"""
|
| 164 |
-
Merge part and damage detections using IoU
|
| 165 |
-
|
| 166 |
-
For each damage detection, find best matching part
|
| 167 |
-
"""
|
| 168 |
-
|
| 169 |
-
merged = []
|
| 170 |
-
|
| 171 |
-
for damage in damages:
|
| 172 |
-
best_match = None
|
| 173 |
-
best_iou = 0
|
| 174 |
-
|
| 175 |
-
# Find best matching part
|
| 176 |
-
for part in parts:
|
| 177 |
-
iou = self._calculate_iou(damage['bbox'], part['bbox'])
|
| 178 |
-
if iou > best_iou and iou > self.iou_threshold:
|
| 179 |
-
best_iou = iou
|
| 180 |
-
best_match = part
|
| 181 |
-
|
| 182 |
-
# Create merged detection
|
| 183 |
-
if best_match:
|
| 184 |
-
merged.append({
|
| 185 |
-
'part': best_match['label'],
|
| 186 |
-
'damage_type': damage['label'],
|
| 187 |
-
'bbox': damage['bbox'],
|
| 188 |
-
'confidence': (damage['confidence'] + best_match['confidence']) / 2,
|
| 189 |
-
'part_confidence': best_match['confidence'],
|
| 190 |
-
'damage_confidence': damage['confidence'],
|
| 191 |
-
'iou': best_iou
|
| 192 |
-
})
|
| 193 |
-
else:
|
| 194 |
-
# No matching part
|
| 195 |
-
merged.append({
|
| 196 |
-
'part': 'unknown_part',
|
| 197 |
-
'damage_type': damage['label'],
|
| 198 |
-
'bbox': damage['bbox'],
|
| 199 |
-
'confidence': damage['confidence'],
|
| 200 |
-
'part_confidence': 0.0,
|
| 201 |
-
'damage_confidence': damage['confidence'],
|
| 202 |
-
'iou': 0.0
|
| 203 |
-
})
|
| 204 |
-
|
| 205 |
-
return merged
|
| 206 |
-
|
| 207 |
-
def _calculate_iou(self, bbox1, bbox2):
|
| 208 |
-
"""Calculate Intersection over Union"""
|
| 209 |
-
|
| 210 |
-
x1_1, y1_1, x2_1, y2_1 = bbox1
|
| 211 |
-
x1_2, y1_2, x2_2, y2_2 = bbox2
|
| 212 |
-
|
| 213 |
-
# Intersection
|
| 214 |
-
x1_i = max(x1_1, x1_2)
|
| 215 |
-
y1_i = max(y1_1, y1_2)
|
| 216 |
-
x2_i = min(x2_1, x2_2)
|
| 217 |
-
y2_i = min(y2_1, y2_2)
|
| 218 |
-
|
| 219 |
-
if x2_i < x1_i or y2_i < y1_i:
|
| 220 |
-
return 0.0
|
| 221 |
-
|
| 222 |
-
intersection = (x2_i - x1_i) * (y2_i - y1_i)
|
| 223 |
-
|
| 224 |
-
# Union
|
| 225 |
-
area1 = (x2_1 - x1_1) * (y2_1 - y1_1)
|
| 226 |
-
area2 = (x2_2 - x1_2) * (y2_2 - y1_2)
|
| 227 |
-
union = area1 + area2 - intersection
|
| 228 |
-
|
| 229 |
-
iou = intersection / union if union > 0 else 0.0
|
| 230 |
-
|
| 231 |
-
return iou
|
| 232 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
-
|
| 235 |
-
# Test
|
| 236 |
-
detector = CVDetector()
|
| 237 |
-
|
| 238 |
-
results = detector.detect('test_car.jpg')
|
| 239 |
-
|
| 240 |
-
print("\nDetection Results:")
|
| 241 |
-
print("="*60)
|
| 242 |
-
for det in results:
|
| 243 |
-
print(f"Part: {det['part']}")
|
| 244 |
-
print(f"Damage: {det['damage_type']}")
|
| 245 |
-
print(f"Confidence: {det['confidence']:.2f}")
|
| 246 |
-
print(f"IoU: {det['iou']:.2f}")
|
| 247 |
-
print("-"*60)
|
|
|
|
| 1 |
"""
|
| 2 |
+
CV Detection wrapper around the Mask R-CNN pipeline in backend/mask_rcnn/.
|
| 3 |
+
|
| 4 |
+
Model weights are loaded from paths defined in mask_rcnn/config.py:
|
| 5 |
+
- models/parts_model.pth (22-class car parts)
|
| 6 |
+
- models/damage_model.pth (9-class damage types)
|
| 7 |
"""
|
| 8 |
|
| 9 |
+
from mask_rcnn.inference import infer, get_device, _load_model
|
| 10 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
class CVDetector:
|
| 13 |
+
def __init__(self):
|
| 14 |
+
"""Load both Mask R-CNN models. Paths come from mask_rcnn/config.py."""
|
| 15 |
+
self.device = get_device()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
print("Loading CV models...")
|
| 17 |
+
self.parts_model = _load_model("parts", self.device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
print("✓ Mask R-CNN (parts) loaded")
|
| 19 |
+
self.damage_model = _load_model("damage", self.device)
|
|
|
|
|
|
|
| 20 |
print("✓ Mask R-CNN (damage types) loaded")
|
| 21 |
+
self.has_parts_model = True
|
| 22 |
+
|
| 23 |
+
def detect(self, image_path: str, conf_threshold: float = 0.25) -> list[dict]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
"""
|
| 25 |
+
Run the two-model Mask R-CNN pipeline on an image.
|
| 26 |
+
|
| 27 |
+
Returns a flat list of detections, one entry per (part, damage_type) pair:
|
| 28 |
+
{
|
| 29 |
+
part, damage_type, confidence, bbox,
|
| 30 |
+
part_confidence, damage_confidence, iou, severity
|
| 31 |
+
}
|
|
|
|
| 32 |
"""
|
| 33 |
+
result = infer(
|
| 34 |
+
image_path,
|
| 35 |
+
parts_model=self.parts_model,
|
| 36 |
+
damage_model=self.damage_model,
|
| 37 |
+
device=self.device,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
detections = []
|
| 41 |
+
for part_entry in result.get("damaged_parts", []):
|
| 42 |
+
for dmg in part_entry.get("damage_types", []):
|
| 43 |
+
if dmg["confidence"] >= conf_threshold:
|
| 44 |
+
detections.append({
|
| 45 |
+
"part": part_entry["part"],
|
| 46 |
+
"damage_type": dmg["type"],
|
| 47 |
+
"confidence": (part_entry["part_confidence"] + dmg["confidence"]) / 2,
|
| 48 |
+
"bbox": dmg["damage_bbox"],
|
| 49 |
+
"part_confidence": part_entry["part_confidence"],
|
| 50 |
+
"damage_confidence": dmg["confidence"],
|
| 51 |
+
"iou": dmg["overlap_ratio"],
|
| 52 |
+
"severity": dmg["severity_proxy"],
|
| 53 |
+
})
|
| 54 |
|
| 55 |
+
return detections
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/gemini_coco.py
DELETED
|
@@ -1,147 +0,0 @@
|
|
| 1 |
-
import json
|
| 2 |
-
from pathlib import Path
|
| 3 |
-
from google import genai
|
| 4 |
-
import os
|
| 5 |
-
from dotenv import load_dotenv
|
| 6 |
-
from PIL import Image
|
| 7 |
-
|
| 8 |
-
# load env variables
|
| 9 |
-
load_dotenv()
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
def analyze_damage(image_path):
|
| 13 |
-
"""
|
| 14 |
-
Inputs image and returns a damaged parts list.
|
| 15 |
-
"""
|
| 16 |
-
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
|
| 17 |
-
|
| 18 |
-
img = Image.open(image_path)
|
| 19 |
-
|
| 20 |
-
# Match OpenAI prompt exactly for fair comparison
|
| 21 |
-
system_prompt = "You are a professional car damage classifier. Return ONLY JSON: {'damaged_parts': [{'part': 'name'}]}"
|
| 22 |
-
user_prompt = "Identify damage to: headlamp, front_bumper, hood, door, rear_bumper. Return ONLY JSON."
|
| 23 |
-
|
| 24 |
-
# Define JSON schema for structured output
|
| 25 |
-
schema = {
|
| 26 |
-
"type": "object",
|
| 27 |
-
"properties": {
|
| 28 |
-
"damaged_parts": {
|
| 29 |
-
"type": "array",
|
| 30 |
-
"items": {
|
| 31 |
-
"type": "object",
|
| 32 |
-
"properties": {"part": {"type": "string"}},
|
| 33 |
-
"required": ["part"],
|
| 34 |
-
},
|
| 35 |
-
}
|
| 36 |
-
},
|
| 37 |
-
"required": ["damaged_parts"],
|
| 38 |
-
}
|
| 39 |
-
|
| 40 |
-
try:
|
| 41 |
-
response = client.models.generate_content(
|
| 42 |
-
model="models/gemini-2.5-flash", # Change model here to test different ones
|
| 43 |
-
contents=[img, system_prompt + "\n\n" + user_prompt],
|
| 44 |
-
config={
|
| 45 |
-
"response_mime_type": "application/json",
|
| 46 |
-
"response_schema": schema,
|
| 47 |
-
"max_output_tokens": 1000,
|
| 48 |
-
},
|
| 49 |
-
)
|
| 50 |
-
|
| 51 |
-
result = json.loads(response.text.strip())
|
| 52 |
-
parts_list = result.get("damaged_parts", [])
|
| 53 |
-
|
| 54 |
-
cleaned = []
|
| 55 |
-
for item in parts_list:
|
| 56 |
-
if isinstance(item, str):
|
| 57 |
-
cleaned.append(item)
|
| 58 |
-
elif isinstance(item, dict) and "part" in item:
|
| 59 |
-
cleaned.append(item["part"])
|
| 60 |
-
return set(cleaned)
|
| 61 |
-
except:
|
| 62 |
-
return set()
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def run_benchmark(image_folder, labels_file, split_name):
|
| 66 |
-
"""
|
| 67 |
-
Runs against JSON labels to calculate accuracy.
|
| 68 |
-
"""
|
| 69 |
-
image_dir = Path(image_folder)
|
| 70 |
-
labels_path = Path(labels_file)
|
| 71 |
-
|
| 72 |
-
with open(labels_path) as f:
|
| 73 |
-
data = json.load(f)
|
| 74 |
-
|
| 75 |
-
# normalize category names
|
| 76 |
-
cats = {c["id"]: c["name"].lower().replace(" ", "_") for c in data["categories"]}
|
| 77 |
-
|
| 78 |
-
# map image IDs to ground truths
|
| 79 |
-
ground_truth = {}
|
| 80 |
-
for a in data["annotations"]:
|
| 81 |
-
img_id = a["image_id"]
|
| 82 |
-
if img_id not in ground_truth:
|
| 83 |
-
ground_truth[img_id] = set()
|
| 84 |
-
ground_truth[img_id].add(cats.get(a["category_id"]))
|
| 85 |
-
|
| 86 |
-
tp, fp, fn = 0, 0, 0
|
| 87 |
-
hamming_scores = []
|
| 88 |
-
|
| 89 |
-
print(f"\nBenchmarking {split_name.upper()}...")
|
| 90 |
-
for img in data["images"]:
|
| 91 |
-
path = image_dir / img["file_name"]
|
| 92 |
-
if not path.exists():
|
| 93 |
-
continue
|
| 94 |
-
|
| 95 |
-
pred = analyze_damage(str(path))
|
| 96 |
-
real = ground_truth.get(img["id"], set())
|
| 97 |
-
|
| 98 |
-
# precision/recall
|
| 99 |
-
tp += len(pred & real)
|
| 100 |
-
fp += len(pred - real)
|
| 101 |
-
fn += len(real - pred)
|
| 102 |
-
|
| 103 |
-
# partial matches count for accuracy
|
| 104 |
-
union = len(pred | real)
|
| 105 |
-
if union == 0:
|
| 106 |
-
hamming_scores.append(1.0) # no damage
|
| 107 |
-
else:
|
| 108 |
-
hamming_scores.append(len(pred & real) / union)
|
| 109 |
-
|
| 110 |
-
print(f" {img['file_name']} | AI: {list(pred)} | Real: {list(real)}")
|
| 111 |
-
|
| 112 |
-
# metrics
|
| 113 |
-
total = len(data["images"])
|
| 114 |
-
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
|
| 115 |
-
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
|
| 116 |
-
accuracy = sum(hamming_scores) / total
|
| 117 |
-
|
| 118 |
-
return {"precision": precision, "recall": recall, "accuracy": accuracy}
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
if __name__ == "__main__":
|
| 122 |
-
script_dir = Path(__file__).parent.resolve()
|
| 123 |
-
root = script_dir.parent
|
| 124 |
-
|
| 125 |
-
splits = [
|
| 126 |
-
{
|
| 127 |
-
"name": "train",
|
| 128 |
-
"dir": root / "archive" / "train",
|
| 129 |
-
"json": root / "archive" / "train" / "COCO_mul_train_annos.json",
|
| 130 |
-
},
|
| 131 |
-
{
|
| 132 |
-
"name": "val",
|
| 133 |
-
"dir": root / "archive" / "val",
|
| 134 |
-
"json": root / "archive" / "val" / "COCO_mul_val_annos.json",
|
| 135 |
-
},
|
| 136 |
-
]
|
| 137 |
-
|
| 138 |
-
print("\n" + "=" * 65)
|
| 139 |
-
print(f"{'SPLIT':<8} | {'PRECISION':<12} | {'RECALL':<12} | {'ACCURACY'}")
|
| 140 |
-
print("-" * 65)
|
| 141 |
-
|
| 142 |
-
for s in splits:
|
| 143 |
-
res = run_benchmark(s["dir"], s["json"], s["name"])
|
| 144 |
-
print(
|
| 145 |
-
f"{s['name'].upper():<8} | {res['precision']:<12.1%} | {res['recall']:<12.1%} | {res['accuracy']:.1%}"
|
| 146 |
-
)
|
| 147 |
-
print("=" * 65)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/openai_coco.py
DELETED
|
@@ -1,124 +0,0 @@
|
|
| 1 |
-
import json
|
| 2 |
-
from pathlib import Path
|
| 3 |
-
import base64
|
| 4 |
-
from openai import OpenAI
|
| 5 |
-
import os
|
| 6 |
-
from dotenv import load_dotenv
|
| 7 |
-
|
| 8 |
-
# load env variables
|
| 9 |
-
load_dotenv()
|
| 10 |
-
|
| 11 |
-
def analyze_damage(image_path):
|
| 12 |
-
"""
|
| 13 |
-
Inputs image and returns a damaged parts list.
|
| 14 |
-
"""
|
| 15 |
-
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
|
| 16 |
-
with open(image_path, "rb") as image_file:
|
| 17 |
-
base64_image = base64.b64encode(image_file.read()).decode('utf-8')
|
| 18 |
-
|
| 19 |
-
messages = [
|
| 20 |
-
{
|
| 21 |
-
"role": "system",
|
| 22 |
-
"content": "You are a professional car damage classifier. Return ONLY JSON: {'damaged_parts': [{'part': 'name'}]}"
|
| 23 |
-
},
|
| 24 |
-
{
|
| 25 |
-
"role": "user",
|
| 26 |
-
"content": [
|
| 27 |
-
{"type": "text", "text": "Identify damage to: headlamp, front_bumper, hood, door, rear_bumper. Return ONLY JSON."},
|
| 28 |
-
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
|
| 29 |
-
]
|
| 30 |
-
}
|
| 31 |
-
]
|
| 32 |
-
|
| 33 |
-
try:
|
| 34 |
-
response = client.chat.completions.create(
|
| 35 |
-
model="gpt-4o",
|
| 36 |
-
messages=messages,
|
| 37 |
-
response_format={"type": "json_object"},
|
| 38 |
-
max_tokens=300
|
| 39 |
-
)
|
| 40 |
-
result = json.loads(response.choices[0].message.content.strip())
|
| 41 |
-
parts_list = result.get("damaged_parts", [])
|
| 42 |
-
|
| 43 |
-
cleaned = []
|
| 44 |
-
for item in parts_list:
|
| 45 |
-
if isinstance(item, str): cleaned.append(item)
|
| 46 |
-
elif isinstance(item, dict) and "part" in item: cleaned.append(item["part"])
|
| 47 |
-
return set(cleaned)
|
| 48 |
-
except:
|
| 49 |
-
return set()
|
| 50 |
-
|
| 51 |
-
def run_benchmark(image_folder, labels_file, split_name):
|
| 52 |
-
"""
|
| 53 |
-
Runs against JSON labels to calculate accuracy.
|
| 54 |
-
"""
|
| 55 |
-
image_dir = Path(image_folder)
|
| 56 |
-
labels_path = Path(labels_file)
|
| 57 |
-
|
| 58 |
-
with open(labels_path) as f:
|
| 59 |
-
data = json.load(f)
|
| 60 |
-
|
| 61 |
-
# normalize category names
|
| 62 |
-
cats = {c['id']: c['name'].lower().replace(" ", "_") for c in data['categories']}
|
| 63 |
-
|
| 64 |
-
# map image IDs to ground truths
|
| 65 |
-
ground_truth = {}
|
| 66 |
-
for a in data['annotations']:
|
| 67 |
-
img_id = a['image_id']
|
| 68 |
-
if img_id not in ground_truth: ground_truth[img_id] = set()
|
| 69 |
-
ground_truth[img_id].add(cats.get(a['category_id']))
|
| 70 |
-
|
| 71 |
-
tp, fp, fn = 0, 0, 0
|
| 72 |
-
hamming_scores = []
|
| 73 |
-
|
| 74 |
-
print(f"\nBenchmarking {split_name.upper()}...")
|
| 75 |
-
for img in data['images']:
|
| 76 |
-
path = image_dir / img['file_name']
|
| 77 |
-
if not path.exists(): continue
|
| 78 |
-
|
| 79 |
-
pred = analyze_damage(str(path))
|
| 80 |
-
real = ground_truth.get(img['id'], set())
|
| 81 |
-
|
| 82 |
-
# precision/recall
|
| 83 |
-
tp += len(pred & real)
|
| 84 |
-
fp += len(pred - real)
|
| 85 |
-
fn += len(real - pred)
|
| 86 |
-
|
| 87 |
-
# partial matches count for accuracy
|
| 88 |
-
union = len(pred | real)
|
| 89 |
-
if union == 0:
|
| 90 |
-
hamming_scores.append(1.0) # no damage
|
| 91 |
-
else:
|
| 92 |
-
hamming_scores.append(len(pred & real) / union)
|
| 93 |
-
|
| 94 |
-
print(f" {img['file_name']} | AI: {list(pred)} | Real: {list(real)}")
|
| 95 |
-
|
| 96 |
-
# metrics
|
| 97 |
-
total = len(data['images'])
|
| 98 |
-
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
|
| 99 |
-
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
|
| 100 |
-
accuracy = sum(hamming_scores) / total
|
| 101 |
-
|
| 102 |
-
return {
|
| 103 |
-
"precision": precision,
|
| 104 |
-
"recall": recall,
|
| 105 |
-
"accuracy": accuracy
|
| 106 |
-
}
|
| 107 |
-
|
| 108 |
-
if __name__ == "__main__":
|
| 109 |
-
script_dir = Path(__file__).parent.resolve()
|
| 110 |
-
root = script_dir.parent
|
| 111 |
-
|
| 112 |
-
splits = [
|
| 113 |
-
{"name": "train", "dir": root/"archive"/"train", "json": root/"archive"/"train"/"COCO_mul_train_annos.json"},
|
| 114 |
-
{"name": "val", "dir": root/"archive"/"val", "json": root/"archive"/"val"/"COCO_mul_val_annos.json"}
|
| 115 |
-
]
|
| 116 |
-
|
| 117 |
-
print("\n" + "="*65)
|
| 118 |
-
print(f"{'SPLIT':<8} | {'PRECISION':<12} | {'RECALL':<12} | {'ACCURACY'}")
|
| 119 |
-
print("-" * 65)
|
| 120 |
-
|
| 121 |
-
for s in splits:
|
| 122 |
-
res = run_benchmark(s['dir'], s['json'], s['name'])
|
| 123 |
-
print(f"{s['name'].upper():<8} | {res['precision']:<12.1%} | {res['recall']:<12.1%} | {res['accuracy']:.1%}")
|
| 124 |
-
print("="*65)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/test_llm.py
DELETED
|
@@ -1,175 +0,0 @@
|
|
| 1 |
-
import json
|
| 2 |
-
|
| 3 |
-
def load_coco_data():
|
| 4 |
-
"""Load and parse COCO dataset"""
|
| 5 |
-
with open('../archive/train/COCO_mul_train_annos.json') as f:
|
| 6 |
-
coco_data = json.load(f)
|
| 7 |
-
|
| 8 |
-
# parse COCO format
|
| 9 |
-
images_list = coco_data['images']
|
| 10 |
-
annotations_list = coco_data['annotations']
|
| 11 |
-
categories = {cat['id']: cat['name'] for cat in coco_data['categories']}
|
| 12 |
-
|
| 13 |
-
# group annotations by image
|
| 14 |
-
image_annotations = {}
|
| 15 |
-
for anno in annotations_list:
|
| 16 |
-
img_id = anno['image_id']
|
| 17 |
-
if img_id not in image_annotations:
|
| 18 |
-
image_annotations[img_id] = []
|
| 19 |
-
image_annotations[img_id].append(categories[anno['category_id']])
|
| 20 |
-
|
| 21 |
-
# create test cases
|
| 22 |
-
test_cases = []
|
| 23 |
-
for img in images_list:
|
| 24 |
-
parts = image_annotations.get(img['id'], [])
|
| 25 |
-
if parts:
|
| 26 |
-
test_cases.append({
|
| 27 |
-
'image_id': img['id'],
|
| 28 |
-
'filename': img['file_name'],
|
| 29 |
-
'damaged_parts': list(set(parts)) # Remove duplicates
|
| 30 |
-
})
|
| 31 |
-
|
| 32 |
-
return test_cases
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
def generate_prompt(damaged_parts_ground_truth):
|
| 36 |
-
"""
|
| 37 |
-
Arguments:
|
| 38 |
-
damaged_parts_ground_truth: list like ["front_bumper", "door"]
|
| 39 |
-
|
| 40 |
-
Returns:
|
| 41 |
-
prompt (str): The prompt to send to LLM
|
| 42 |
-
mock_data (dict): The mock data used (for validation later)
|
| 43 |
-
"""
|
| 44 |
-
|
| 45 |
-
# create mock data
|
| 46 |
-
mock_data = create_mock_data(damaged_parts_ground_truth)
|
| 47 |
-
|
| 48 |
-
# format damaged parts for prompt
|
| 49 |
-
parts_list = []
|
| 50 |
-
for part in mock_data["damaged_parts"]:
|
| 51 |
-
parts_list.append(
|
| 52 |
-
f"- {part['part']}: {part['severity']} {part['damage_type']} "
|
| 53 |
-
f"(recommended: {part['action']}, estimated cost: ${part['cost_range'][0]}-${part['cost_range'][1]})"
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
parts_formatted = "\n".join(parts_list)
|
| 57 |
-
|
| 58 |
-
# build prompt
|
| 59 |
-
prompt = f"""You are an insurance adjuster assistant analyzing vehicle damage.
|
| 60 |
-
|
| 61 |
-
Vehicle: {mock_data['vehicle']['year']} {mock_data['vehicle']['make']} {mock_data['vehicle']['model']}
|
| 62 |
-
Location: ZIP {mock_data['zip_code']}
|
| 63 |
-
|
| 64 |
-
Damage Assessment from CV and Cost Models:
|
| 65 |
-
|
| 66 |
-
{parts_formatted}
|
| 67 |
-
|
| 68 |
-
Total Estimated Cost: ${mock_data['total_cost_range'][0]}-${mock_data['total_cost_range'][1]}
|
| 69 |
-
|
| 70 |
-
Generate a professional insurance claim assessment.
|
| 71 |
-
|
| 72 |
-
Return your response in this exact JSON format:
|
| 73 |
-
{{
|
| 74 |
-
"damaged_parts": [
|
| 75 |
-
{{
|
| 76 |
-
"part": "part_name",
|
| 77 |
-
"damage_type": "type",
|
| 78 |
-
"severity": "severity_level",
|
| 79 |
-
"action": "repair_or_replace",
|
| 80 |
-
"cost_range": [low, high]
|
| 81 |
-
}}
|
| 82 |
-
],
|
| 83 |
-
"total_cost_range": [low, high],
|
| 84 |
-
"explanation": "Professional damage assessment (2-4 sentences)",
|
| 85 |
-
"confidence_score": 0.85,
|
| 86 |
-
"stp_eligible": true,
|
| 87 |
-
"stp_reasoning": "Reasoning for STP decision"
|
| 88 |
-
}}
|
| 89 |
-
|
| 90 |
-
Guidelines:
|
| 91 |
-
- explanation: Reference specific damage, justify repair decisions and costs
|
| 92 |
-
- confidence_score (0.0-1.0):
|
| 93 |
-
* 0.9-1.0 = Very confident, standard damage
|
| 94 |
-
* 0.7-0.9 = Confident, typical case
|
| 95 |
-
* 0.5-0.7 = Moderate confidence
|
| 96 |
-
* <0.5 = Low confidence
|
| 97 |
-
- stp_eligible: true if straightforward and cost <$1500, false otherwise
|
| 98 |
-
- stp_reasoning: One sentence explaining STP decision
|
| 99 |
-
|
| 100 |
-
Return ONLY valid JSON with no other text."""
|
| 101 |
-
|
| 102 |
-
return prompt, mock_data
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
def create_mock_data(damaged_parts_ground_truth):
|
| 106 |
-
"""Generate realistic mock CV + Cost model outputs"""
|
| 107 |
-
|
| 108 |
-
import random
|
| 109 |
-
|
| 110 |
-
# fixed vehicle for testing
|
| 111 |
-
mock_data = {
|
| 112 |
-
"vehicle": {
|
| 113 |
-
"year": 2019,
|
| 114 |
-
"make": "Honda",
|
| 115 |
-
"model": "Civic"
|
| 116 |
-
},
|
| 117 |
-
"zip_code": "48823",
|
| 118 |
-
"damaged_parts": []
|
| 119 |
-
}
|
| 120 |
-
|
| 121 |
-
# cost estimates
|
| 122 |
-
part_costs = {
|
| 123 |
-
"front_bumper": {"repair": 500, "replace": 850},
|
| 124 |
-
"rear_bumper": {"repair": 500, "replace": 850},
|
| 125 |
-
"door": {"repair": 450, "replace": 1200},
|
| 126 |
-
"hood": {"repair": 600, "replace": 1500},
|
| 127 |
-
"headlamp": {"repair": 200, "replace": 500}
|
| 128 |
-
}
|
| 129 |
-
|
| 130 |
-
# damage types
|
| 131 |
-
damage_types_map = {
|
| 132 |
-
"front_bumper": ["crack", "dent", "scratch"],
|
| 133 |
-
"rear_bumper": ["crack", "dent", "scratch"],
|
| 134 |
-
"door": ["dent", "scratch"],
|
| 135 |
-
"hood": ["dent", "scratch"],
|
| 136 |
-
"headlamp": ["crack", "broken"]
|
| 137 |
-
}
|
| 138 |
-
|
| 139 |
-
for part in damaged_parts_ground_truth:
|
| 140 |
-
# random severity
|
| 141 |
-
severity = random.choice(["minor", "moderate", "major"])
|
| 142 |
-
|
| 143 |
-
# damage type based on part
|
| 144 |
-
damage_type = random.choice(damage_types_map.get(part, ["damage"]))
|
| 145 |
-
|
| 146 |
-
# action based on severity
|
| 147 |
-
if severity == "major":
|
| 148 |
-
action = "replace"
|
| 149 |
-
elif severity == "moderate":
|
| 150 |
-
action = random.choice(["repair", "replace"])
|
| 151 |
-
else:
|
| 152 |
-
action = "repair"
|
| 153 |
-
|
| 154 |
-
# get base cost
|
| 155 |
-
base_cost = part_costs.get(part, {}).get(action, 500)
|
| 156 |
-
|
| 157 |
-
# cost range (±20%)
|
| 158 |
-
cost_low = int(base_cost * 0.8)
|
| 159 |
-
cost_high = int(base_cost * 1.2)
|
| 160 |
-
|
| 161 |
-
mock_data["damaged_parts"].append({
|
| 162 |
-
"part": part,
|
| 163 |
-
"damage_type": damage_type,
|
| 164 |
-
"severity": severity,
|
| 165 |
-
"action": action,
|
| 166 |
-
"cost_range": [cost_low, cost_high],
|
| 167 |
-
"estimated_cost": base_cost
|
| 168 |
-
})
|
| 169 |
-
|
| 170 |
-
# total cost range
|
| 171 |
-
total_low = sum(p["cost_range"][0] for p in mock_data["damaged_parts"])
|
| 172 |
-
total_high = sum(p["cost_range"][1] for p in mock_data["damaged_parts"])
|
| 173 |
-
mock_data["total_cost_range"] = [total_low, total_high]
|
| 174 |
-
|
| 175 |
-
return mock_data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/yolo_v8/configs/dataset.yaml
DELETED
|
@@ -1,10 +0,0 @@
|
|
| 1 |
-
path: ../data/car_damage # root dir
|
| 2 |
-
train: train/images
|
| 3 |
-
val: val/images
|
| 4 |
-
|
| 5 |
-
names:
|
| 6 |
-
0: scratch
|
| 7 |
-
1: dent
|
| 8 |
-
2: breakage
|
| 9 |
-
3: glass_shatter
|
| 10 |
-
4: tire_flat
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/yolo_v8/requirements.txt
DELETED
|
@@ -1,6 +0,0 @@
|
|
| 1 |
-
ultralytics
|
| 2 |
-
opencv-python
|
| 3 |
-
pandas
|
| 4 |
-
numpy
|
| 5 |
-
scikit-learn
|
| 6 |
-
kagglehub
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/yolo_v8/src/convert_dataset.py
DELETED
|
@@ -1,79 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
import cv2
|
| 4 |
-
import shutil
|
| 5 |
-
from sklearn.model_selection import train_test_split
|
| 6 |
-
|
| 7 |
-
DATA_PATH = "../data/car_damage_dataset/Car damages dataset/File1"
|
| 8 |
-
IMG_PATH = os.path.join(DATA_PATH, "img")
|
| 9 |
-
ANN_PATH = os.path.join(DATA_PATH, "ann")
|
| 10 |
-
|
| 11 |
-
OUTPUT_PATH = "../data/yolo_dataset"
|
| 12 |
-
|
| 13 |
-
os.makedirs(f"{OUTPUT_PATH}/images/train", exist_ok=True)
|
| 14 |
-
os.makedirs(f"{OUTPUT_PATH}/images/val", exist_ok=True)
|
| 15 |
-
os.makedirs(f"{OUTPUT_PATH}/labels/train", exist_ok=True)
|
| 16 |
-
os.makedirs(f"{OUTPUT_PATH}/labels/val", exist_ok=True)
|
| 17 |
-
|
| 18 |
-
images = [f for f in os.listdir(IMG_PATH) if f.endswith(".jpg")]
|
| 19 |
-
|
| 20 |
-
train_imgs, val_imgs = train_test_split(images, test_size=0.2, random_state=42)
|
| 21 |
-
|
| 22 |
-
def polygon_to_bbox(points):
|
| 23 |
-
xs = [p[0] for p in points]
|
| 24 |
-
ys = [p[1] for p in points]
|
| 25 |
-
|
| 26 |
-
x_min = min(xs)
|
| 27 |
-
x_max = max(xs)
|
| 28 |
-
y_min = min(ys)
|
| 29 |
-
y_max = max(ys)
|
| 30 |
-
|
| 31 |
-
return x_min, y_min, x_max - x_min, y_max - y_min
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def convert_bbox(size, bbox):
|
| 35 |
-
w, h = size
|
| 36 |
-
x, y, bw, bh = bbox
|
| 37 |
-
|
| 38 |
-
x_center = (x + bw / 2) / w
|
| 39 |
-
y_center = (y + bh / 2) / h
|
| 40 |
-
bw /= w
|
| 41 |
-
bh /= h
|
| 42 |
-
|
| 43 |
-
return x_center, y_center, bw, bh
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
for split, img_list in [("train", train_imgs), ("val", val_imgs)]:
|
| 47 |
-
|
| 48 |
-
for img_name in img_list:
|
| 49 |
-
|
| 50 |
-
img_path = os.path.join(IMG_PATH, img_name)
|
| 51 |
-
ann_path = os.path.join(ANN_PATH, img_name.replace(".jpg", ".json"))
|
| 52 |
-
|
| 53 |
-
img = cv2.imread(img_path)
|
| 54 |
-
h, w, _ = img.shape
|
| 55 |
-
|
| 56 |
-
shutil.copy(img_path, f"{OUTPUT_PATH}/images/{split}/{img_name}")
|
| 57 |
-
|
| 58 |
-
label_path = f"{OUTPUT_PATH}/labels/{split}/{img_name.replace('.jpg','.txt')}"
|
| 59 |
-
|
| 60 |
-
with open(label_path, "w") as label_file:
|
| 61 |
-
|
| 62 |
-
if os.path.exists(ann_path):
|
| 63 |
-
|
| 64 |
-
with open(ann_path) as f:
|
| 65 |
-
data = json.load(f)
|
| 66 |
-
|
| 67 |
-
for obj in data["objects"]:
|
| 68 |
-
|
| 69 |
-
polygon = obj["polygon"]
|
| 70 |
-
|
| 71 |
-
bbox = polygon_to_bbox(polygon)
|
| 72 |
-
|
| 73 |
-
x, y, bw, bh = convert_bbox((w, h), bbox)
|
| 74 |
-
|
| 75 |
-
class_id = 0
|
| 76 |
-
|
| 77 |
-
label_file.write(f"{class_id} {x} {y} {bw} {bh}\n")
|
| 78 |
-
|
| 79 |
-
print("Dataset conversion complete.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/yolo_v8/src/evaluate.py
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
from ultralytics import YOLO
|
| 2 |
-
|
| 3 |
-
def evaluate():
|
| 4 |
-
|
| 5 |
-
model = YOLO("../outputs/baseline_model/weights/best.pt")
|
| 6 |
-
|
| 7 |
-
metrics = model.val()
|
| 8 |
-
|
| 9 |
-
print("mAP50:", metrics.box.map50)
|
| 10 |
-
print("mAP50-95:", metrics.box.map)
|
| 11 |
-
|
| 12 |
-
if __name__ == "__main__":
|
| 13 |
-
evaluate()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/yolo_v8/src/inference.py
DELETED
|
@@ -1,12 +0,0 @@
|
|
| 1 |
-
from ultralytics import YOLO
|
| 2 |
-
import time
|
| 3 |
-
|
| 4 |
-
model = YOLO("../outputs/baseline_model/weights/best.pt")
|
| 5 |
-
|
| 6 |
-
start = time.time()
|
| 7 |
-
|
| 8 |
-
results = model.predict("../test_images/test.jpg")
|
| 9 |
-
|
| 10 |
-
latency = time.time() - start
|
| 11 |
-
|
| 12 |
-
print("Inference time:", latency)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/yolo_v8/src/preprocess.py
DELETED
|
@@ -1,18 +0,0 @@
|
|
| 1 |
-
import cv2
|
| 2 |
-
import os
|
| 3 |
-
|
| 4 |
-
def blur_score(image_path):
|
| 5 |
-
img = cv2.imread(image_path)
|
| 6 |
-
score = cv2.Laplacian(img, cv2.CV_64F).var()
|
| 7 |
-
return score
|
| 8 |
-
|
| 9 |
-
def filter_blurry_images(image_folder, threshold=100):
|
| 10 |
-
removed = []
|
| 11 |
-
|
| 12 |
-
for img in os.listdir(image_folder):
|
| 13 |
-
path = os.path.join(image_folder, img)
|
| 14 |
-
|
| 15 |
-
if blur_score(path) < threshold:
|
| 16 |
-
removed.append(path)
|
| 17 |
-
|
| 18 |
-
return removed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/yolo_v8/src/train.py
DELETED
|
@@ -1,44 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
from ultralytics import YOLO
|
| 3 |
-
import torch
|
| 4 |
-
|
| 5 |
-
# train
|
| 6 |
-
def train_model():
|
| 7 |
-
base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 8 |
-
config_path = os.path.abspath(os.path.join(base_dir, '..', 'configs', 'dataset.yaml'))
|
| 9 |
-
output_dir = os.path.abspath(os.path.join(base_dir, '..', 'outputs', 'models'))
|
| 10 |
-
|
| 11 |
-
if not os.path.exists(config_path):
|
| 12 |
-
print(f"Error: Could not find configuration file at {config_path}")
|
| 13 |
-
return
|
| 14 |
-
|
| 15 |
-
# GPU
|
| 16 |
-
if torch.cuda.is_available():
|
| 17 |
-
device = 0
|
| 18 |
-
elif torch.backends.mps.is_available():
|
| 19 |
-
device = "mps"
|
| 20 |
-
else:
|
| 21 |
-
device = "cpu"
|
| 22 |
-
|
| 23 |
-
print(f"Using device: {device}")
|
| 24 |
-
|
| 25 |
-
# load pre-trained model
|
| 26 |
-
model = YOLO('yolov8n.pt')
|
| 27 |
-
|
| 28 |
-
# train
|
| 29 |
-
model.train(
|
| 30 |
-
data=config_path,
|
| 31 |
-
epochs=50,
|
| 32 |
-
imgsz=640,
|
| 33 |
-
batch=16,
|
| 34 |
-
project=output_dir,
|
| 35 |
-
name='baseline_run',
|
| 36 |
-
device=device,
|
| 37 |
-
exist_ok=True
|
| 38 |
-
)
|
| 39 |
-
|
| 40 |
-
if __name__ == "__main__":
|
| 41 |
-
train_model()
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/yolo_v8/src/utils.py
DELETED
|
@@ -1,15 +0,0 @@
|
|
| 1 |
-
def convert_to_json(results, class_names):
|
| 2 |
-
|
| 3 |
-
output = {"damaged_parts": []}
|
| 4 |
-
|
| 5 |
-
for box in results[0].boxes:
|
| 6 |
-
|
| 7 |
-
cls = int(box.cls)
|
| 8 |
-
conf = float(box.conf)
|
| 9 |
-
|
| 10 |
-
output["damaged_parts"].append({
|
| 11 |
-
"damage_type": class_names[cls],
|
| 12 |
-
"confidence": conf
|
| 13 |
-
})
|
| 14 |
-
|
| 15 |
-
return output
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/src/App.js
CHANGED
|
@@ -18,7 +18,7 @@ function App() {
|
|
| 18 |
formData.append('image', file);
|
| 19 |
|
| 20 |
try {
|
| 21 |
-
const response = await fetch('http://localhost:8000/
|
| 22 |
method: 'POST',
|
| 23 |
body: formData,
|
| 24 |
});
|
|
@@ -29,12 +29,7 @@ function App() {
|
|
| 29 |
|
| 30 |
} catch (error) {
|
| 31 |
console.error('Error:', error);
|
| 32 |
-
setResults({
|
| 33 |
-
damageType: "Error",
|
| 34 |
-
severity: "N/A",
|
| 35 |
-
estimatedCost: "N/A",
|
| 36 |
-
recommendation: "Failed to connect to backend. Is it running?"
|
| 37 |
-
});
|
| 38 |
setAppState('complete');
|
| 39 |
}
|
| 40 |
};
|
|
|
|
| 18 |
formData.append('image', file);
|
| 19 |
|
| 20 |
try {
|
| 21 |
+
const response = await fetch('http://localhost:8000/detect', {
|
| 22 |
method: 'POST',
|
| 23 |
body: formData,
|
| 24 |
});
|
|
|
|
| 29 |
|
| 30 |
} catch (error) {
|
| 31 |
console.error('Error:', error);
|
| 32 |
+
setResults({ error: "Failed to connect to backend. Is it running?" });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
setAppState('complete');
|
| 34 |
}
|
| 35 |
};
|
frontend/src/App.jsx
ADDED
|
File without changes
|
frontend/src/api/claimApiCV.js
ADDED
|
File without changes
|
frontend/src/components/ResultsDisplay.js
CHANGED
|
@@ -1,17 +1,18 @@
|
|
| 1 |
import React from 'react';
|
| 2 |
import { motion } from 'framer-motion';
|
| 3 |
-
import { CheckCircle, AlertCircle, RefreshCw
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
const ResultsDisplay = ({ results, onReset }) => {
|
| 6 |
-
|
| 7 |
-
damageType: "Bumper Dent",
|
| 8 |
-
severity: "Moderate",
|
| 9 |
-
estimatedCost: "$450 - $800",
|
| 10 |
-
recommendation: "Replace bumper cover and repaint."
|
| 11 |
-
};
|
| 12 |
|
| 13 |
-
const
|
| 14 |
-
if (!data) return null;
|
| 15 |
|
| 16 |
return (
|
| 17 |
<motion.div
|
|
@@ -21,49 +22,54 @@ const ResultsDisplay = ({ results, onReset }) => {
|
|
| 21 |
>
|
| 22 |
<div className="p-8 border-b border-gray-700 bg-gradient-to-r from-blue-900/20 to-purple-900/20">
|
| 23 |
<div className="flex items-center gap-3 mb-2">
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
| 25 |
<h2 className="text-2xl font-bold text-white">Analysis Complete</h2>
|
| 26 |
</div>
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
</div>
|
| 29 |
|
| 30 |
-
<div className="p-8 space-y-
|
| 31 |
-
|
| 32 |
-
<
|
| 33 |
-
|
| 34 |
-
<div className="p-4 bg-gray-900/50 rounded-xl border border-gray-700">
|
| 35 |
-
<span className="text-lg text-white font-medium">{data.damageType}</span>
|
| 36 |
-
</div>
|
| 37 |
-
</div>
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
<div className="
|
| 42 |
-
<
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
</div>
|
| 48 |
</div>
|
| 49 |
</div>
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
<div className="space-y-2">
|
| 53 |
-
<label className="text-sm font-medium text-gray-400">Estimated Repair Cost</label>
|
| 54 |
-
<div className="p-4 bg-gray-900/50 rounded-xl border border-gray-700">
|
| 55 |
-
<span className="text-2xl text-green-400 font-bold">{data.estimatedCost}</span>
|
| 56 |
-
</div>
|
| 57 |
-
</div>
|
| 58 |
-
|
| 59 |
-
<div className="space-y-2">
|
| 60 |
-
<label className="text-sm font-medium text-gray-400">AI Recommendation</label>
|
| 61 |
-
<div className="p-4 bg-blue-900/20 border border-blue-500/30 rounded-xl">
|
| 62 |
-
<p className="text-blue-200">{data.recommendation}</p>
|
| 63 |
-
</div>
|
| 64 |
-
</div>
|
| 65 |
|
| 66 |
-
<div className="pt-
|
| 67 |
<button
|
| 68 |
onClick={onReset}
|
| 69 |
className="w-full py-4 bg-white text-gray-900 rounded-xl font-bold hover:bg-gray-200 transition-colors flex items-center justify-center gap-2"
|
|
|
|
| 1 |
import React from 'react';
|
| 2 |
import { motion } from 'framer-motion';
|
| 3 |
+
import { CheckCircle, AlertCircle, RefreshCw } from 'lucide-react';
|
| 4 |
+
|
| 5 |
+
const severityDots = (severity) => {
|
| 6 |
+
const level = { minor: 1, moderate: 2, severe: 3 }[severity?.toLowerCase()] ?? 0;
|
| 7 |
+
return [1, 2, 3].map(i => (
|
| 8 |
+
<div key={i} className={`w-2 h-2 rounded-full ${i <= level ? 'bg-yellow-500' : 'bg-gray-700'}`} />
|
| 9 |
+
));
|
| 10 |
+
};
|
| 11 |
|
| 12 |
const ResultsDisplay = ({ results, onReset }) => {
|
| 13 |
+
if (!results) return null;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
const { detections = [], summary = {}, error } = results;
|
|
|
|
| 16 |
|
| 17 |
return (
|
| 18 |
<motion.div
|
|
|
|
| 22 |
>
|
| 23 |
<div className="p-8 border-b border-gray-700 bg-gradient-to-r from-blue-900/20 to-purple-900/20">
|
| 24 |
<div className="flex items-center gap-3 mb-2">
|
| 25 |
+
{error
|
| 26 |
+
? <AlertCircle className="w-8 h-8 text-red-400" />
|
| 27 |
+
: <CheckCircle className="w-8 h-8 text-green-400" />
|
| 28 |
+
}
|
| 29 |
<h2 className="text-2xl font-bold text-white">Analysis Complete</h2>
|
| 30 |
</div>
|
| 31 |
+
{error
|
| 32 |
+
? <p className="text-red-400 ml-11">{error}</p>
|
| 33 |
+
: <p className="text-gray-400 ml-11">
|
| 34 |
+
{summary.total_damaged_parts ?? 0} damaged part{summary.total_damaged_parts !== 1 ? 's' : ''} detected
|
| 35 |
+
</p>
|
| 36 |
+
}
|
| 37 |
</div>
|
| 38 |
|
| 39 |
+
<div className="p-8 space-y-4">
|
| 40 |
+
{detections.length === 0 && !error && (
|
| 41 |
+
<p className="text-gray-400 text-center py-4">No damage detected in this image.</p>
|
| 42 |
+
)}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
{detections.map((det, i) => (
|
| 45 |
+
<div key={i} className="p-4 bg-gray-900/50 rounded-xl border border-gray-700 space-y-3">
|
| 46 |
+
<div className="grid grid-cols-2 gap-4">
|
| 47 |
+
<div className="space-y-1">
|
| 48 |
+
<label className="text-xs font-medium text-gray-400">Part</label>
|
| 49 |
+
<p className="text-white font-medium">{det.part}</p>
|
| 50 |
+
</div>
|
| 51 |
+
<div className="space-y-1">
|
| 52 |
+
<label className="text-xs font-medium text-gray-400">Damage Type</label>
|
| 53 |
+
<p className="text-white font-medium">{det.damage_type}</p>
|
| 54 |
+
</div>
|
| 55 |
+
</div>
|
| 56 |
+
<div className="grid grid-cols-2 gap-4">
|
| 57 |
+
<div className="space-y-1">
|
| 58 |
+
<label className="text-xs font-medium text-gray-400">Severity</label>
|
| 59 |
+
<div className="flex items-center gap-2">
|
| 60 |
+
<span className="text-white capitalize">{det.severity ?? '—'}</span>
|
| 61 |
+
<div className="flex gap-1">{severityDots(det.severity)}</div>
|
| 62 |
+
</div>
|
| 63 |
+
</div>
|
| 64 |
+
<div className="space-y-1">
|
| 65 |
+
<label className="text-xs font-medium text-gray-400">Confidence</label>
|
| 66 |
+
<p className="text-white">{det.confidence != null ? `${(det.confidence * 100).toFixed(0)}%` : '—'}</p>
|
| 67 |
</div>
|
| 68 |
</div>
|
| 69 |
</div>
|
| 70 |
+
))}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
<div className="pt-4 border-t border-gray-700">
|
| 73 |
<button
|
| 74 |
onClick={onReset}
|
| 75 |
className="w-full py-4 bg-white text-gray-900 rounded-xl font-bold hover:bg-gray-200 transition-colors flex items-center justify-center gap-2"
|