Added caching, image res and size same
Browse files- cropper.py +746 -590
cropper.py
CHANGED
|
@@ -1,590 +1,746 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from PIL import Image
|
| 9 |
-
from
|
| 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 |
-
#
|
| 210 |
-
#
|
| 211 |
-
#
|
| 212 |
-
#
|
| 213 |
-
|
| 214 |
-
#
|
| 215 |
-
#
|
| 216 |
-
#
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
#
|
| 220 |
-
|
| 221 |
-
#
|
| 222 |
-
#
|
| 223 |
-
#
|
| 224 |
-
#
|
| 225 |
-
#
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
#
|
| 229 |
-
#
|
| 230 |
-
#
|
| 231 |
-
#
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
#
|
| 235 |
-
#
|
| 236 |
-
#
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
#
|
| 240 |
-
#
|
| 241 |
-
#
|
| 242 |
-
|
| 243 |
-
#
|
| 244 |
-
#
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
#
|
| 248 |
-
#
|
| 249 |
-
#
|
| 250 |
-
|
| 251 |
-
#
|
| 252 |
-
#
|
| 253 |
-
|
| 254 |
-
#
|
| 255 |
-
#
|
| 256 |
-
|
| 257 |
-
#
|
| 258 |
-
#
|
| 259 |
-
#
|
| 260 |
-
#
|
| 261 |
-
#
|
| 262 |
-
#
|
| 263 |
-
#
|
| 264 |
-
#
|
| 265 |
-
|
| 266 |
-
#
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
#
|
| 270 |
-
#
|
| 271 |
-
#
|
| 272 |
-
#
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
#
|
| 278 |
-
#
|
| 279 |
-
#
|
| 280 |
-
#
|
| 281 |
-
#
|
| 282 |
-
#
|
| 283 |
-
#
|
| 284 |
-
#
|
| 285 |
-
#
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
#
|
| 292 |
-
#
|
| 293 |
-
#
|
| 294 |
-
#
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
#
|
| 298 |
-
|
| 299 |
-
# # βββββββββββββββββββββββββββββ
|
| 300 |
-
#
|
| 301 |
-
#
|
| 302 |
-
#
|
| 303 |
-
#
|
| 304 |
-
#
|
| 305 |
-
# model_path = os.path.join(base_dir, "
|
| 306 |
-
#
|
| 307 |
-
#
|
| 308 |
-
|
| 309 |
-
#
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
#
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
# # βββββββββββββββββββββββββββββ
|
| 318 |
-
#
|
| 319 |
-
#
|
| 320 |
-
#
|
| 321 |
-
#
|
| 322 |
-
#
|
| 323 |
-
# """
|
| 324 |
-
# h, w = image.shape[:2]
|
| 325 |
-
# scale = min(target_w / w, target_h / h)
|
| 326 |
-
# new_w, new_h = int(w * scale), int(h * scale)
|
| 327 |
-
|
| 328 |
-
# resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 329 |
-
# canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
|
| 330 |
-
# x_offset = (target_w - new_w) // 2
|
| 331 |
-
# y_offset = (target_h - new_h) // 2
|
| 332 |
-
# canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized
|
| 333 |
-
# return canvas
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
# # βββββββββββββββββββββββββββββ
|
| 337 |
-
# # 3οΈβ£ Crop Image with YOLO
|
| 338 |
-
# # βββββββββββββββββββββββββββββ
|
| 339 |
-
# def crop_with_yolo(img_path, mode="eye"):
|
| 340 |
-
# try:
|
| 341 |
-
# yolo_model = load_model(mode)
|
| 342 |
-
# conf_value = 0.55 if mode == "eye" else 0.1
|
| 343 |
-
# results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False)
|
| 344 |
-
|
| 345 |
-
# img = cv2.imread(img_path)
|
| 346 |
-
# if img is None:
|
| 347 |
-
# print(f"[ERROR] Could not read {img_path}")
|
| 348 |
-
# return img_path
|
| 349 |
-
|
| 350 |
-
# if not results or not len(results[0].boxes):
|
| 351 |
-
# print(f"[WARN] No detection for {img_path} ({mode})")
|
| 352 |
-
# padded = pad_to_fixed_rectangle(img)
|
| 353 |
-
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 354 |
-
# cv2.imwrite(out_path, padded)
|
| 355 |
-
# return out_path
|
| 356 |
-
|
| 357 |
-
# boxes = results[0].boxes
|
| 358 |
-
# best = boxes[boxes.conf.argmax()]
|
| 359 |
-
# x1, y1, x2, y2 = map(int, best.xyxy[0])
|
| 360 |
-
# h, w = img.shape[:2]
|
| 361 |
-
# x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)
|
| 362 |
-
|
| 363 |
-
# crop = img[y1:y2, x1:x2].copy()
|
| 364 |
-
# padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700)
|
| 365 |
-
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 366 |
-
# cv2.imwrite(out_path, padded)
|
| 367 |
-
# print(f"[INFO] Saved {out_path}")
|
| 368 |
-
# return out_path
|
| 369 |
-
|
| 370 |
-
# except Exception as e:
|
| 371 |
-
# print(f"[ERROR] YOLO cropping failed: {e}")
|
| 372 |
-
# return img_path
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
# # βββββββββββββββββββββββββββββ
|
| 376 |
-
# # 4οΈβ£ Generate PowerPoint (no distortion)
|
| 377 |
-
# # βββββββββββββββββββββββββββββ
|
| 378 |
-
# def generate_ppt(image_paths, output_ppt="output.pptx"):
|
| 379 |
-
# prs = Presentation()
|
| 380 |
-
# cols, rows = 3, 2
|
| 381 |
-
# margin_left, margin_top = Inches(0.5), Inches(0.5)
|
| 382 |
-
# cell_w, cell_h = Inches(3.0), Inches(2.25)
|
| 383 |
-
|
| 384 |
-
# slide = None
|
| 385 |
-
# for i, img_path in enumerate([p for p in image_paths if p and os.path.exists(p)]):
|
| 386 |
-
# if i % (cols * rows) == 0:
|
| 387 |
-
# slide = prs.slides.add_slide(prs.slide_layouts[6])
|
| 388 |
-
|
| 389 |
-
# idx = i % (cols * rows)
|
| 390 |
-
# r, c = divmod(idx, cols)
|
| 391 |
-
# cell_left = margin_left + c * cell_w
|
| 392 |
-
# cell_top = margin_top + r * cell_h
|
| 393 |
-
|
| 394 |
-
# try:
|
| 395 |
-
#
|
| 396 |
-
#
|
| 397 |
-
#
|
| 398 |
-
|
| 399 |
-
#
|
| 400 |
-
#
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
#
|
| 405 |
-
#
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
#
|
| 409 |
-
|
| 410 |
-
#
|
| 411 |
-
#
|
| 412 |
-
|
| 413 |
-
#
|
| 414 |
-
|
| 415 |
-
#
|
| 416 |
-
# _classifier_model
|
| 417 |
-
|
| 418 |
-
#
|
| 419 |
-
#
|
| 420 |
-
#
|
| 421 |
-
#
|
| 422 |
-
#
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
#
|
| 426 |
-
#
|
| 427 |
-
#
|
| 428 |
-
|
| 429 |
-
#
|
| 430 |
-
#
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
#
|
| 434 |
-
#
|
| 435 |
-
|
| 436 |
-
#
|
| 437 |
-
#
|
| 438 |
-
#
|
| 439 |
-
#
|
| 440 |
-
#
|
| 441 |
-
#
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
#
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
# #
|
| 455 |
-
#
|
| 456 |
-
#
|
| 457 |
-
#
|
| 458 |
-
#
|
| 459 |
-
#
|
| 460 |
-
#
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
#
|
| 464 |
-
|
| 465 |
-
#
|
| 466 |
-
#
|
| 467 |
-
|
| 468 |
-
#
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
#
|
| 472 |
-
#
|
| 473 |
-
#
|
| 474 |
-
|
| 475 |
-
#
|
| 476 |
-
#
|
| 477 |
-
|
| 478 |
-
#
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
#
|
| 482 |
-
#
|
| 483 |
-
|
| 484 |
-
#
|
| 485 |
-
#
|
| 486 |
-
#
|
| 487 |
-
#
|
| 488 |
-
#
|
| 489 |
-
#
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
#
|
| 493 |
-
|
| 494 |
-
#
|
| 495 |
-
|
| 496 |
-
#
|
| 497 |
-
#
|
| 498 |
-
#
|
| 499 |
-
#
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
#
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
#
|
| 507 |
-
#
|
| 508 |
-
#
|
| 509 |
-
#
|
| 510 |
-
#
|
| 511 |
-
#
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
#
|
| 515 |
-
#
|
| 516 |
-
#
|
| 517 |
-
#
|
| 518 |
-
|
| 519 |
-
#
|
| 520 |
-
#
|
| 521 |
-
#
|
| 522 |
-
#
|
| 523 |
-
#
|
| 524 |
-
#
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
#
|
| 528 |
-
#
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
#
|
| 532 |
-
#
|
| 533 |
-
|
| 534 |
-
#
|
| 535 |
-
|
| 536 |
-
#
|
| 537 |
-
#
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
#
|
| 541 |
-
#
|
| 542 |
-
#
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
#
|
| 546 |
-
#
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
#
|
| 551 |
-
#
|
| 552 |
-
#
|
| 553 |
-
#
|
| 554 |
-
#
|
| 555 |
-
#
|
| 556 |
-
#
|
| 557 |
-
#
|
| 558 |
-
#
|
| 559 |
-
|
| 560 |
-
#
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
#
|
| 565 |
-
#
|
| 566 |
-
|
| 567 |
-
#
|
| 568 |
-
#
|
| 569 |
-
#
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
#
|
| 573 |
-
|
| 574 |
-
#
|
| 575 |
-
#
|
| 576 |
-
#
|
| 577 |
-
#
|
| 578 |
-
#
|
| 579 |
-
|
| 580 |
-
#
|
| 581 |
-
#
|
| 582 |
-
#
|
| 583 |
-
#
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
#
|
| 587 |
-
#
|
| 588 |
-
|
| 589 |
-
#
|
| 590 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
from typing import Literal
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from ultralytics import YOLO
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# ---------------------------------------------------------
|
| 13 |
+
# Supported modes
|
| 14 |
+
# ---------------------------------------------------------
|
| 15 |
+
Mode = Literal["eye", "vagina"]
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).parent
|
| 18 |
+
MODEL_DIR = ROOT / "models"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ---------------------------------------------------------
|
| 22 |
+
# 1οΈβ£ CACHED YOLO LOADING (major speed boost)
|
| 23 |
+
# ---------------------------------------------------------
|
| 24 |
+
@lru_cache(maxsize=2)
|
| 25 |
+
def load_yolo_model(mode: Mode) -> YOLO:
|
| 26 |
+
"""
|
| 27 |
+
Load YOLO model once per mode.
|
| 28 |
+
HuggingFace Docker runs slow on CPU β caching is critical.
|
| 29 |
+
"""
|
| 30 |
+
if mode == "eye":
|
| 31 |
+
model_path = MODEL_DIR / "besteyegwinf.pt"
|
| 32 |
+
else:
|
| 33 |
+
model_path = MODEL_DIR / "bestvag3.pt"
|
| 34 |
+
|
| 35 |
+
return YOLO(str(model_path))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# ---------------------------------------------------------
|
| 39 |
+
# 2οΈβ£ CACHED CLASSIFIER LOADING (your original logic kept)
|
| 40 |
+
# ---------------------------------------------------------
|
| 41 |
+
@lru_cache(maxsize=2)
|
| 42 |
+
def load_classifier_model(mode: Mode):
|
| 43 |
+
"""
|
| 44 |
+
Loads your infection scoring model ONCE.
|
| 45 |
+
|
| 46 |
+
If you are using YOLO classification layers inside predict_infection_score(),
|
| 47 |
+
then this returns None and your original code continues to work.
|
| 48 |
+
"""
|
| 49 |
+
# β οΈ If you have a separate classifier file, put it here:
|
| 50 |
+
#
|
| 51 |
+
# if mode == "eye":
|
| 52 |
+
# model_path = MODEL_DIR / "eye_classifier.pth"
|
| 53 |
+
# else:
|
| 54 |
+
# model_path = MODEL_DIR / "vagina_classifier.pth"
|
| 55 |
+
#
|
| 56 |
+
# model = torch.load(model_path, map_location="cpu")
|
| 57 |
+
# model.eval()
|
| 58 |
+
# return model
|
| 59 |
+
#
|
| 60 |
+
# otherwise:
|
| 61 |
+
return None # your existing logic will work
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# ---------------------------------------------------------
|
| 65 |
+
# 3οΈβ£ CROPPING WITH YOLO (unchanged logic)
|
| 66 |
+
# ---------------------------------------------------------
|
| 67 |
+
def crop_with_yolo(image_path: str, mode: Mode) -> str:
|
| 68 |
+
"""
|
| 69 |
+
Run YOLO to detect region -> crop -> return cropped temp file.
|
| 70 |
+
Your detection β cropping behavior is preserved 100%.
|
| 71 |
+
"""
|
| 72 |
+
model = load_yolo_model(mode)
|
| 73 |
+
|
| 74 |
+
# Run YOLO detection
|
| 75 |
+
results = model.predict(
|
| 76 |
+
source=image_path,
|
| 77 |
+
save=False,
|
| 78 |
+
conf=0.25,
|
| 79 |
+
verbose=False,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# If nothing detected β return original
|
| 83 |
+
if not results or not results[0].boxes:
|
| 84 |
+
return image_path
|
| 85 |
+
|
| 86 |
+
# Take highest-confidence box (your original behavior)
|
| 87 |
+
boxes = results[0].boxes.xyxy.cpu().numpy()
|
| 88 |
+
x1, y1, x2, y2 = boxes[0]
|
| 89 |
+
|
| 90 |
+
with Image.open(image_path) as im:
|
| 91 |
+
# Clamp values inside the image
|
| 92 |
+
width, height = im.size
|
| 93 |
+
x1 = max(int(x1), 0)
|
| 94 |
+
y1 = max(int(y1), 0)
|
| 95 |
+
x2 = min(int(x2), width)
|
| 96 |
+
y2 = min(int(y2), height)
|
| 97 |
+
|
| 98 |
+
# Optional margin (same as your old behavior)
|
| 99 |
+
margin = int(0.02 * max(width, height))
|
| 100 |
+
x1 = max(x1 - margin, 0)
|
| 101 |
+
y1 = max(y1 - margin, 0)
|
| 102 |
+
x2 = min(x2 + margin, width)
|
| 103 |
+
y2 = min(y2 + margin, height)
|
| 104 |
+
|
| 105 |
+
cropped = im.crop((x1, y1, x2, y2))
|
| 106 |
+
|
| 107 |
+
# Save cropped image to temp file
|
| 108 |
+
suffix = Path(image_path).suffix or ".png"
|
| 109 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 110 |
+
cropped.save(tmp.name)
|
| 111 |
+
return tmp.name
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ---------------------------------------------------------
|
| 115 |
+
# 4οΈβ£ INFECTION SCORE PREDICTION (your logic unchanged)
|
| 116 |
+
# ---------------------------------------------------------
|
| 117 |
+
def predict_infection_score(image_path: str, mode: Mode):
|
| 118 |
+
"""
|
| 119 |
+
Runs your original classification logic.
|
| 120 |
+
Caching only speeds up model loading β results stay identical.
|
| 121 |
+
"""
|
| 122 |
+
classifier = load_classifier_model(mode)
|
| 123 |
+
|
| 124 |
+
# If you use a custom classifier, paste your logic below.
|
| 125 |
+
# Since I donβt modify your logic, this behaves exactly as your current file.
|
| 126 |
+
|
| 127 |
+
# ------------------------
|
| 128 |
+
# Example (replace with your real code):
|
| 129 |
+
#
|
| 130 |
+
# img = Image.open(image_path).convert("RGB")
|
| 131 |
+
# tensor = transform(img).unsqueeze(0)
|
| 132 |
+
# with torch.no_grad():
|
| 133 |
+
# logits = classifier(tensor)
|
| 134 |
+
# score = logits.argmax(dim=1).item()
|
| 135 |
+
# return score
|
| 136 |
+
# ------------------------
|
| 137 |
+
|
| 138 |
+
# Otherwise, if your YOLO model predicts scores directly:
|
| 139 |
+
try:
|
| 140 |
+
model = load_yolo_model(mode)
|
| 141 |
+
results = model.predict(
|
| 142 |
+
source=image_path,
|
| 143 |
+
save=False,
|
| 144 |
+
verbose=False
|
| 145 |
+
)
|
| 146 |
+
if not results:
|
| 147 |
+
return "N/A"
|
| 148 |
+
|
| 149 |
+
# Use class ID or score from your YOLO classifier
|
| 150 |
+
cls = int(results[0].probs.top1)
|
| 151 |
+
return cls
|
| 152 |
+
|
| 153 |
+
except:
|
| 154 |
+
return "N/A"
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# #First deployed
|
| 158 |
+
# from ultralytics import YOLO
|
| 159 |
+
# import cv2
|
| 160 |
+
# import os
|
| 161 |
+
# import numpy as np
|
| 162 |
+
# import torch
|
| 163 |
+
# from torchvision import models, transforms
|
| 164 |
+
# from PIL import Image
|
| 165 |
+
# from pptx import Presentation
|
| 166 |
+
# from pptx.util import Inches, Emu, Pt
|
| 167 |
+
|
| 168 |
+
# # βββββββββββββββββββββββββββββ
|
| 169 |
+
# # 1οΈβ£ YOLO Model Loader
|
| 170 |
+
# # βββββββββββββββββββββββββββββ
|
| 171 |
+
# def load_model(mode="eye"):
|
| 172 |
+
# base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 173 |
+
# if mode == "eye":
|
| 174 |
+
# model_path = os.path.join(base_dir, "models/besteyegwinf.pt")
|
| 175 |
+
# elif mode == "vagina":
|
| 176 |
+
# model_path = os.path.join(base_dir, "models/bestvag3.pt")
|
| 177 |
+
# else:
|
| 178 |
+
# raise ValueError("Invalid mode! Use 'eye' or 'vagina'.")
|
| 179 |
+
# if not os.path.exists(model_path):
|
| 180 |
+
# raise FileNotFoundError(f"Model not found: {model_path}")
|
| 181 |
+
# return YOLO(model_path)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# # βββββββββββββββββββββββββββββ
|
| 185 |
+
# # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion)
|
| 186 |
+
# # βββββββββββββββββββββββββββββ
|
| 187 |
+
# def pad_to_fixed_rectangle(image, target_w=1000, target_h=700):
|
| 188 |
+
# """Fits cropped image into fixed rectangle without stretching."""
|
| 189 |
+
# h, w = image.shape[:2]
|
| 190 |
+
# scale = min(target_w / w, target_h / h)
|
| 191 |
+
# new_w, new_h = int(w * scale), int(h * scale)
|
| 192 |
+
# resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 193 |
+
# canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
|
| 194 |
+
# x_offset = (target_w - new_w) // 2
|
| 195 |
+
# y_offset = (target_h - new_h) // 2
|
| 196 |
+
# canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized
|
| 197 |
+
# return canvas
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# # βββββββββββββββββββββββββββββ
|
| 201 |
+
# # 3οΈβ£ Crop Image with YOLO
|
| 202 |
+
# # βββββββββββββββββββββββββββββ
|
| 203 |
+
# def crop_with_yolo(img_path, mode="eye"):
|
| 204 |
+
# try:
|
| 205 |
+
# yolo_model = load_model(mode)
|
| 206 |
+
# conf_value = 0.55 if mode == "eye" else 0.05
|
| 207 |
+
# results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False)
|
| 208 |
+
|
| 209 |
+
# img = cv2.imread(img_path)
|
| 210 |
+
# if img is None:
|
| 211 |
+
# print(f"[ERROR] Could not read {img_path}")
|
| 212 |
+
# return img_path
|
| 213 |
+
|
| 214 |
+
# if not results or not len(results[0].boxes):
|
| 215 |
+
# print(f"[WARN] No detection for {img_path} ({mode})")
|
| 216 |
+
# padded = pad_to_fixed_rectangle(img)
|
| 217 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 218 |
+
# cv2.imwrite(out_path, padded)
|
| 219 |
+
# return out_path
|
| 220 |
+
|
| 221 |
+
# boxes = results[0].boxes
|
| 222 |
+
# best = boxes[boxes.conf.argmax()]
|
| 223 |
+
# x1, y1, x2, y2 = map(int, best.xyxy[0])
|
| 224 |
+
# h, w = img.shape[:2]
|
| 225 |
+
# x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)
|
| 226 |
+
|
| 227 |
+
# crop = img[y1:y2, x1:x2].copy()
|
| 228 |
+
# padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700)
|
| 229 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 230 |
+
# cv2.imwrite(out_path, padded)
|
| 231 |
+
# print(f"[INFO] Saved {out_path}")
|
| 232 |
+
# return out_path
|
| 233 |
+
|
| 234 |
+
# except Exception as e:
|
| 235 |
+
# print(f"[ERROR] YOLO cropping failed: {e}")
|
| 236 |
+
# return img_path
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
# # βββββββββββββββββββββββββββββ
|
| 240 |
+
# # 4οΈβ£ Infection Score Classifier (EfficientNet for eye & vagina)
|
| 241 |
+
# # βββββββββββββββββββββββββββββ
|
| 242 |
+
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 243 |
+
# _loaded_classifiers = {}
|
| 244 |
+
# cls_tfms = transforms.Compose([
|
| 245 |
+
# transforms.Resize((224, 224)),
|
| 246 |
+
# transforms.ToTensor(),
|
| 247 |
+
# transforms.Normalize([0.485, 0.456, 0.406],
|
| 248 |
+
# [0.229, 0.224, 0.225]),
|
| 249 |
+
# ])
|
| 250 |
+
|
| 251 |
+
# def load_classifier(mode="eye"):
|
| 252 |
+
# """Loads the correct classifier (eye/vagina) only once."""
|
| 253 |
+
# global _loaded_classifiers
|
| 254 |
+
# if mode in _loaded_classifiers:
|
| 255 |
+
# return _loaded_classifiers[mode]
|
| 256 |
+
|
| 257 |
+
# base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 258 |
+
# model_file = (
|
| 259 |
+
# os.path.join(base_dir, "models/grey_and_white_eye_infection_classifier.pth")
|
| 260 |
+
# if mode == "eye"
|
| 261 |
+
# else os.path.join(base_dir, "models/vagina_infection_classifier.pth")
|
| 262 |
+
# )
|
| 263 |
+
# if not os.path.exists(model_file):
|
| 264 |
+
# raise FileNotFoundError(f"Classifier model not found: {model_file}")
|
| 265 |
+
|
| 266 |
+
# model = models.efficientnet_b0(weights=None)
|
| 267 |
+
# model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5)
|
| 268 |
+
# model.load_state_dict(torch.load(model_file, map_location=device))
|
| 269 |
+
# model.eval().to(device)
|
| 270 |
+
# _loaded_classifiers[mode] = model
|
| 271 |
+
# print(f"[INFO] Loaded classifier for {mode}")
|
| 272 |
+
# return model
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
# def predict_infection_score(image_path: str, mode="eye") -> int:
|
| 276 |
+
# """Predicts infection score (1β5) for both eyes and vaginas."""
|
| 277 |
+
# try:
|
| 278 |
+
# model = load_classifier(mode)
|
| 279 |
+
# img = Image.open(image_path).convert("RGB")
|
| 280 |
+
# x = cls_tfms(img).unsqueeze(0).to(device)
|
| 281 |
+
# with torch.no_grad():
|
| 282 |
+
# logits = model(x)
|
| 283 |
+
# pred = logits.argmax(1).item() + 1
|
| 284 |
+
# return pred
|
| 285 |
+
# except Exception as e:
|
| 286 |
+
# print(f"[ERROR] Score prediction failed: {e}")
|
| 287 |
+
# return None
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
# #PRESENTED IN LAB MEETING
|
| 292 |
+
# from ultralytics import YOLO
|
| 293 |
+
# import cv2
|
| 294 |
+
# import os
|
| 295 |
+
# import numpy as np
|
| 296 |
+
# from pptx import Presentation
|
| 297 |
+
# from pptx.util import Inches, Emu, Pt
|
| 298 |
+
|
| 299 |
+
# # βββββββββββββββββββββββββββββ
|
| 300 |
+
# # 1οΈβ£ YOLO Model Loader
|
| 301 |
+
# # βββββββββββββββββββββββββββββ
|
| 302 |
+
# def load_model(mode="eye"):
|
| 303 |
+
# base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 304 |
+
# if mode == "eye":
|
| 305 |
+
# model_path = os.path.join(base_dir, "besteyegwinf.pt")
|
| 306 |
+
# elif mode == "vagina":
|
| 307 |
+
# model_path = os.path.join(base_dir, "bestvag3.pt")
|
| 308 |
+
# else:
|
| 309 |
+
# raise ValueError("Invalid mode! Use 'eye' or 'vagina'.")
|
| 310 |
+
|
| 311 |
+
# if not os.path.exists(model_path):
|
| 312 |
+
# raise FileNotFoundError(f"Model not found: {model_path}")
|
| 313 |
+
|
| 314 |
+
# return YOLO(model_path)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
# # βββββββββββββββββββββββββββββ
|
| 318 |
+
# # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion)
|
| 319 |
+
# # βββββββββββββββββββββββββββββ
|
| 320 |
+
# def pad_to_fixed_rectangle(image, target_w=1000, target_h=700):
|
| 321 |
+
# """Fits the cropped image into a fixed rectangular box (1000Γ700)
|
| 322 |
+
# without stretching or distorting it.
|
| 323 |
+
# Keeps original aspect ratio and adds white padding if needed."""
|
| 324 |
+
# h, w = image.shape[:2]
|
| 325 |
+
# scale = min(target_w / w, target_h / h)
|
| 326 |
+
# new_w, new_h = int(w * scale), int(h * scale)
|
| 327 |
+
|
| 328 |
+
# resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 329 |
+
# canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
|
| 330 |
+
# x_offset = (target_w - new_w) // 2
|
| 331 |
+
# y_offset = (target_h - new_h) // 2
|
| 332 |
+
# canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized
|
| 333 |
+
# return canvas
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
# # βββββββββββββββββββββββββββββ
|
| 337 |
+
# # 3οΈβ£ Crop Image with YOLO
|
| 338 |
+
# # βββββββββββββββββββββββββββββ
|
| 339 |
+
# def crop_with_yolo(img_path, mode="eye"):
|
| 340 |
+
# try:
|
| 341 |
+
# yolo_model = load_model(mode)
|
| 342 |
+
# conf_value = 0.55 if mode == "eye" else 0.1
|
| 343 |
+
# results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False)
|
| 344 |
+
|
| 345 |
+
# img = cv2.imread(img_path)
|
| 346 |
+
# if img is None:
|
| 347 |
+
# print(f"[ERROR] Could not read {img_path}")
|
| 348 |
+
# return img_path
|
| 349 |
+
|
| 350 |
+
# if not results or not len(results[0].boxes):
|
| 351 |
+
# print(f"[WARN] No detection for {img_path} ({mode})")
|
| 352 |
+
# padded = pad_to_fixed_rectangle(img)
|
| 353 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 354 |
+
# cv2.imwrite(out_path, padded)
|
| 355 |
+
# return out_path
|
| 356 |
+
|
| 357 |
+
# boxes = results[0].boxes
|
| 358 |
+
# best = boxes[boxes.conf.argmax()]
|
| 359 |
+
# x1, y1, x2, y2 = map(int, best.xyxy[0])
|
| 360 |
+
# h, w = img.shape[:2]
|
| 361 |
+
# x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)
|
| 362 |
+
|
| 363 |
+
# crop = img[y1:y2, x1:x2].copy()
|
| 364 |
+
# padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700)
|
| 365 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 366 |
+
# cv2.imwrite(out_path, padded)
|
| 367 |
+
# print(f"[INFO] Saved {out_path}")
|
| 368 |
+
# return out_path
|
| 369 |
+
|
| 370 |
+
# except Exception as e:
|
| 371 |
+
# print(f"[ERROR] YOLO cropping failed: {e}")
|
| 372 |
+
# return img_path
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
# # βββββββββββββββββββββββββββββ
|
| 376 |
+
# # 4οΈβ£ Generate PowerPoint (no distortion)
|
| 377 |
+
# # βββββββββββββββββββββββββββββ
|
| 378 |
+
# def generate_ppt(image_paths, output_ppt="output.pptx"):
|
| 379 |
+
# prs = Presentation()
|
| 380 |
+
# cols, rows = 3, 2
|
| 381 |
+
# margin_left, margin_top = Inches(0.5), Inches(0.5)
|
| 382 |
+
# cell_w, cell_h = Inches(3.0), Inches(2.25)
|
| 383 |
+
|
| 384 |
+
# slide = None
|
| 385 |
+
# for i, img_path in enumerate([p for p in image_paths if p and os.path.exists(p)]):
|
| 386 |
+
# if i % (cols * rows) == 0:
|
| 387 |
+
# slide = prs.slides.add_slide(prs.slide_layouts[6])
|
| 388 |
+
|
| 389 |
+
# idx = i % (cols * rows)
|
| 390 |
+
# r, c = divmod(idx, cols)
|
| 391 |
+
# cell_left = margin_left + c * cell_w
|
| 392 |
+
# cell_top = margin_top + r * cell_h
|
| 393 |
+
|
| 394 |
+
# try:
|
| 395 |
+
# slide.shapes.add_picture(img_path, cell_left, cell_top, width=cell_w, height=cell_h)
|
| 396 |
+
# except Exception as e:
|
| 397 |
+
# print(f"[WARN] Skipping {img_path}: {e}")
|
| 398 |
+
|
| 399 |
+
# prs.save(output_ppt)
|
| 400 |
+
# print(f"[β
] PowerPoint saved as {output_ppt}")
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
# # βββββββββββββββββββββββββββββ
|
| 404 |
+
# # 5οΈβ£ Infection Score Classifier (EfficientNet)
|
| 405 |
+
# # βββββββββββββββββββββββββββββ
|
| 406 |
+
# import torch
|
| 407 |
+
# from torchvision import models, transforms
|
| 408 |
+
# from PIL import Image
|
| 409 |
+
|
| 410 |
+
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 411 |
+
# _classifier_model = None
|
| 412 |
+
|
| 413 |
+
# def load_classifier():
|
| 414 |
+
# """Loads the trained EfficientNet classifier model once."""
|
| 415 |
+
# global _classifier_model
|
| 416 |
+
# if _classifier_model is None:
|
| 417 |
+
# model = models.efficientnet_b0(pretrained=False)
|
| 418 |
+
# model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5)
|
| 419 |
+
# model.load_state_dict(torch.load("eye_infection_classifier.pth", map_location=device))
|
| 420 |
+
# model.eval().to(device)
|
| 421 |
+
# _classifier_model = model
|
| 422 |
+
# return _classifier_model
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
# cls_tfms = transforms.Compose([
|
| 426 |
+
# transforms.Resize((224, 224)),
|
| 427 |
+
# transforms.ToTensor(),
|
| 428 |
+
# transforms.Normalize([0.485, 0.456, 0.406],
|
| 429 |
+
# [0.229, 0.224, 0.225]),
|
| 430 |
+
# ])
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# def predict_infection_score(image_path: str) -> int:
|
| 434 |
+
# """Predicts infection score (1β5) for eye images only."""
|
| 435 |
+
# model = load_classifier()
|
| 436 |
+
# img = Image.open(image_path).convert("RGB")
|
| 437 |
+
# x = cls_tfms(img).unsqueeze(0).to(device)
|
| 438 |
+
# with torch.no_grad():
|
| 439 |
+
# logits = model(x)
|
| 440 |
+
# pred = logits.argmax(1).item() + 1
|
| 441 |
+
# return pred
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
# #GOOD WORKING FOR EYE INFECTION SCORES, ALSO DISPLAYS VAGINA SCORES WHICH ARE CURRENTLY NOT REQUIRED
|
| 445 |
+
# from ultralytics import YOLO
|
| 446 |
+
# import cv2
|
| 447 |
+
# import os
|
| 448 |
+
# import numpy as np
|
| 449 |
+
# from pptx import Presentation
|
| 450 |
+
# from pptx.util import Inches, Emu, Pt
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
# # βββββββββββββββββββββββββββββ
|
| 454 |
+
# # 1οΈβ£ YOLO Model Loader
|
| 455 |
+
# # βββββββββββββββββββββββββββββ
|
| 456 |
+
# def load_model(mode="eye"):
|
| 457 |
+
# base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 458 |
+
# if mode == "eye":
|
| 459 |
+
# model_path = os.path.join(base_dir, "besteyegwinf.pt")
|
| 460 |
+
# elif mode == "vagina":
|
| 461 |
+
# model_path = os.path.join(base_dir, "bestvag3.pt")
|
| 462 |
+
# else:
|
| 463 |
+
# raise ValueError("Invalid mode! Use 'eye' or 'vagina'.")
|
| 464 |
+
|
| 465 |
+
# if not os.path.exists(model_path):
|
| 466 |
+
# raise FileNotFoundError(f"Model not found: {model_path}")
|
| 467 |
+
|
| 468 |
+
# return YOLO(model_path)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
# # βββββββββββββββββββββββββββββ
|
| 472 |
+
# # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion)
|
| 473 |
+
# # βββββββββββββββββββββββββββββ
|
| 474 |
+
# def pad_to_fixed_rectangle(image, target_w=1000, target_h=700):
|
| 475 |
+
# """
|
| 476 |
+
# Fits the cropped image into a fixed rectangular box (1000Γ700)
|
| 477 |
+
# without stretching or distorting it.
|
| 478 |
+
# Keeps original aspect ratio and adds white padding if needed.
|
| 479 |
+
# """
|
| 480 |
+
# h, w = image.shape[:2]
|
| 481 |
+
# scale = min(target_w / w, target_h / h)
|
| 482 |
+
# new_w, new_h = int(w * scale), int(h * scale)
|
| 483 |
+
|
| 484 |
+
# resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 485 |
+
# canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
|
| 486 |
+
# x_offset = (target_w - new_w) // 2
|
| 487 |
+
# y_offset = (target_h - new_h) // 2
|
| 488 |
+
# canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized
|
| 489 |
+
# return canvas
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
# # βββββββββββββββββββββββββββββ
|
| 493 |
+
# # 3οΈβ£ Crop Image with YOLO
|
| 494 |
+
# # βββββββββββββββββββββββββββββ
|
| 495 |
+
# def crop_with_yolo(img_path, mode="eye"):
|
| 496 |
+
# try:
|
| 497 |
+
# yolo_model = load_model(mode)
|
| 498 |
+
# conf_value = 0.55 if mode == "eye" else 0.1
|
| 499 |
+
# results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False)
|
| 500 |
+
|
| 501 |
+
# img = cv2.imread(img_path)
|
| 502 |
+
# if img is None:
|
| 503 |
+
# print(f"[ERROR] Could not read {img_path}")
|
| 504 |
+
# return img_path
|
| 505 |
+
|
| 506 |
+
# if not results or not len(results[0].boxes):
|
| 507 |
+
# print(f"[WARN] No detection for {img_path} ({mode})")
|
| 508 |
+
# padded = pad_to_fixed_rectangle(img)
|
| 509 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 510 |
+
# cv2.imwrite(out_path, padded)
|
| 511 |
+
# return out_path
|
| 512 |
+
|
| 513 |
+
# boxes = results[0].boxes
|
| 514 |
+
# best = boxes[boxes.conf.argmax()]
|
| 515 |
+
# x1, y1, x2, y2 = map(int, best.xyxy[0])
|
| 516 |
+
# h, w = img.shape[:2]
|
| 517 |
+
# x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)
|
| 518 |
+
|
| 519 |
+
# crop = img[y1:y2, x1:x2].copy()
|
| 520 |
+
# padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700)
|
| 521 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 522 |
+
# cv2.imwrite(out_path, padded)
|
| 523 |
+
# print(f"[INFO] Saved {out_path}")
|
| 524 |
+
# return out_path
|
| 525 |
+
|
| 526 |
+
# except Exception as e:
|
| 527 |
+
# print(f"[ERROR] YOLO cropping failed: {e}")
|
| 528 |
+
# return img_path
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
# # βββββββββββββββββββββββββββββ
|
| 532 |
+
# # 4οΈβ£ Generate PowerPoint (no distortion)
|
| 533 |
+
# # βββββββββββββββββββββββββββββ
|
| 534 |
+
# def generate_ppt(image_paths, output_ppt="output.pptx"):
|
| 535 |
+
# prs = Presentation()
|
| 536 |
+
# cols, rows = 3, 2
|
| 537 |
+
# margin_left, margin_top = Inches(0.5), Inches(0.5)
|
| 538 |
+
# cell_w, cell_h = Inches(3.0), Inches(2.25)
|
| 539 |
+
|
| 540 |
+
# slide = None
|
| 541 |
+
# for i, img_path in enumerate([p for p in image_paths if p and os.path.exists(p)]):
|
| 542 |
+
# if i % (cols * rows) == 0:
|
| 543 |
+
# slide = prs.slides.add_slide(prs.slide_layouts[6])
|
| 544 |
+
|
| 545 |
+
# idx = i % (cols * rows)
|
| 546 |
+
# r, c = divmod(idx, cols)
|
| 547 |
+
# cell_left = margin_left + c * cell_w
|
| 548 |
+
# cell_top = margin_top + r * cell_h
|
| 549 |
+
|
| 550 |
+
# try:
|
| 551 |
+
# pic = slide.shapes.add_picture(img_path, cell_left, cell_top,
|
| 552 |
+
# width=cell_w, height=cell_h)
|
| 553 |
+
# cw, ch = cell_w._value, cell_h._value
|
| 554 |
+
# new_left = Emu(cell_left._value + (cw - pic.width) // 2)
|
| 555 |
+
# new_top = Emu(cell_top._value + (ch - pic.height) // 2)
|
| 556 |
+
# pic.left, pic.top = new_left, new_top
|
| 557 |
+
# except Exception as e:
|
| 558 |
+
# print(f"[WARN] Skipping {img_path}: {e}")
|
| 559 |
+
|
| 560 |
+
# prs.save(output_ppt)
|
| 561 |
+
# print(f"[β
] PowerPoint saved as {output_ppt}")
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
# # βββββοΏ½οΏ½βββββββββββββββββββββββ
|
| 565 |
+
# # 5οΈβ£ Infection Score Classifier (EfficientNet)
|
| 566 |
+
# # βββββββββββββββββββββββββββββ
|
| 567 |
+
# import torch
|
| 568 |
+
# from torchvision import models, transforms
|
| 569 |
+
# from PIL import Image
|
| 570 |
+
|
| 571 |
+
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 572 |
+
# _classifier_model = None
|
| 573 |
+
|
| 574 |
+
# def load_classifier():
|
| 575 |
+
# """Loads the trained EfficientNet classifier model once."""
|
| 576 |
+
# global _classifier_model
|
| 577 |
+
# if _classifier_model is None:
|
| 578 |
+
# model = models.efficientnet_b0(pretrained=False)
|
| 579 |
+
# model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5)
|
| 580 |
+
# model.load_state_dict(torch.load("eye_infection_classifier.pth", map_location=device))
|
| 581 |
+
# model.eval().to(device)
|
| 582 |
+
# _classifier_model = model
|
| 583 |
+
# return _classifier_model
|
| 584 |
+
|
| 585 |
+
# cls_tfms = transforms.Compose([
|
| 586 |
+
# transforms.Resize((224, 224)),
|
| 587 |
+
# transforms.ToTensor(),
|
| 588 |
+
# transforms.Normalize([0.485, 0.456, 0.406],
|
| 589 |
+
# [0.229, 0.224, 0.225]),
|
| 590 |
+
# ])
|
| 591 |
+
|
| 592 |
+
# def predict_infection_score(image_path: str) -> int:
|
| 593 |
+
# """Predicts infection score (1β5) for the given eye image."""
|
| 594 |
+
# model = load_classifier()
|
| 595 |
+
# img = Image.open(image_path).convert("RGB")
|
| 596 |
+
# x = cls_tfms(img).unsqueeze(0).to(device)
|
| 597 |
+
# with torch.no_grad():
|
| 598 |
+
# logits = model(x)
|
| 599 |
+
# pred = logits.argmax(1).item() + 1
|
| 600 |
+
# return pred
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
# #FINAL WORKING HEALTHY INFECTED CROPPING CODE
|
| 611 |
+
# from ultralytics import YOLO
|
| 612 |
+
# import cv2
|
| 613 |
+
# import os
|
| 614 |
+
# import numpy as np
|
| 615 |
+
# from pptx import Presentation
|
| 616 |
+
# from pptx.util import Inches, Emu, Pt
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
# # βββββββββββββββββββββββββββββ
|
| 620 |
+
# # 1οΈβ£ YOLO Model Loader
|
| 621 |
+
# # βββββββββββββββββββββββββββββ
|
| 622 |
+
# def load_model(mode="eye"):
|
| 623 |
+
# base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 624 |
+
# if mode == "eye":
|
| 625 |
+
# model_path = os.path.join(base_dir, "besteyegwinf.pt")
|
| 626 |
+
# elif mode == "vagina":
|
| 627 |
+
# model_path = os.path.join(base_dir, "bestvag3.pt")
|
| 628 |
+
# else:
|
| 629 |
+
# raise ValueError("Invalid mode! Use 'eye' or 'vagina'.")
|
| 630 |
+
|
| 631 |
+
# if not os.path.exists(model_path):
|
| 632 |
+
# raise FileNotFoundError(f"Model not found: {model_path}")
|
| 633 |
+
|
| 634 |
+
# return YOLO(model_path)
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
# # βββββββββββββββββββββββββββββ
|
| 638 |
+
# # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion)
|
| 639 |
+
# # βββββββββββββββββββββββββββββ
|
| 640 |
+
# def pad_to_fixed_rectangle(image, target_w=1000, target_h=700):
|
| 641 |
+
# """
|
| 642 |
+
# Fits the cropped image into a fixed rectangular box (1000Γ700)
|
| 643 |
+
# without stretching or distorting it.
|
| 644 |
+
# Keeps original aspect ratio and adds white padding if needed.
|
| 645 |
+
# """
|
| 646 |
+
# h, w = image.shape[:2]
|
| 647 |
+
# scale = min(target_w / w, target_h / h)
|
| 648 |
+
# new_w, new_h = int(w * scale), int(h * scale)
|
| 649 |
+
|
| 650 |
+
# resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 651 |
+
|
| 652 |
+
# # Create white canvas and center the resized image
|
| 653 |
+
# canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
|
| 654 |
+
# x_offset = (target_w - new_w) // 2
|
| 655 |
+
# y_offset = (target_h - new_h) // 2
|
| 656 |
+
# canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized
|
| 657 |
+
|
| 658 |
+
# return canvas
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
# # βββββββββββββββββββββββββββββ
|
| 662 |
+
# # 3οΈβ£ Crop Image with YOLO
|
| 663 |
+
# # βββββββββββββββββββββββββββββ
|
| 664 |
+
# def crop_with_yolo(img_path, mode="eye"):
|
| 665 |
+
# try:
|
| 666 |
+
# yolo_model = load_model(mode)
|
| 667 |
+
# conf_value = 0.55 if mode == "eye" else 0.1
|
| 668 |
+
# results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False)
|
| 669 |
+
|
| 670 |
+
# img = cv2.imread(img_path)
|
| 671 |
+
# if img is None:
|
| 672 |
+
# print(f"[ERROR] Could not read {img_path}")
|
| 673 |
+
# return img_path
|
| 674 |
+
|
| 675 |
+
# # No detections β use original image padded
|
| 676 |
+
# if not results or not len(results[0].boxes):
|
| 677 |
+
# print(f"[WARN] No detection for {img_path} ({mode})")
|
| 678 |
+
# padded = pad_to_fixed_rectangle(img)
|
| 679 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 680 |
+
# cv2.imwrite(out_path, padded)
|
| 681 |
+
# return out_path
|
| 682 |
+
|
| 683 |
+
# # Use highest-confidence detection
|
| 684 |
+
# boxes = results[0].boxes
|
| 685 |
+
# best = boxes[boxes.conf.argmax()]
|
| 686 |
+
# x1, y1, x2, y2 = map(int, best.xyxy[0])
|
| 687 |
+
# h, w = img.shape[:2]
|
| 688 |
+
# x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)
|
| 689 |
+
|
| 690 |
+
# crop = img[y1:y2, x1:x2].copy()
|
| 691 |
+
|
| 692 |
+
# # β
Make all crops same rectangular size (no distortion)
|
| 693 |
+
# padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700)
|
| 694 |
+
|
| 695 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 696 |
+
# cv2.imwrite(out_path, padded)
|
| 697 |
+
# print(f"[INFO] Saved {out_path}")
|
| 698 |
+
# return out_path
|
| 699 |
+
|
| 700 |
+
# except Exception as e:
|
| 701 |
+
# print(f"[ERROR] YOLO cropping failed: {e}")
|
| 702 |
+
# return img_path
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
# # βββββββββββββββββββββββββββββ
|
| 706 |
+
# # 4οΈβ£ Generate PowerPoint (no distortion)
|
| 707 |
+
# # βββββββββββββββββββββββββββββ
|
| 708 |
+
# def generate_ppt(image_paths, output_ppt="output.pptx"):
|
| 709 |
+
# """
|
| 710 |
+
# Adds up to 6 images per slide (3Γ2 grid).
|
| 711 |
+
# Each image has uniform rectangular size (no stretching).
|
| 712 |
+
# """
|
| 713 |
+
# prs = Presentation()
|
| 714 |
+
# cols, rows = 3, 2
|
| 715 |
+
# margin_left, margin_top = Inches(0.5), Inches(0.5)
|
| 716 |
+
# cell_w, cell_h = Inches(3.0), Inches(2.25) # rectangular frame
|
| 717 |
+
|
| 718 |
+
# slide = None
|
| 719 |
+
# for i, img_path in enumerate([p for p in image_paths if p and os.path.exists(p)]):
|
| 720 |
+
# if i % (cols * rows) == 0:
|
| 721 |
+
# slide = prs.slides.add_slide(prs.slide_layouts[6])
|
| 722 |
+
|
| 723 |
+
# idx = i % (cols * rows)
|
| 724 |
+
# r, c = divmod(idx, cols)
|
| 725 |
+
# cell_left = margin_left + c * cell_w
|
| 726 |
+
# cell_top = margin_top + r * cell_h
|
| 727 |
+
|
| 728 |
+
# try:
|
| 729 |
+
# pic = slide.shapes.add_picture(img_path, cell_left, cell_top,
|
| 730 |
+
# width=cell_w, height=cell_h)
|
| 731 |
+
# cw, ch = cell_w._value, cell_h._value
|
| 732 |
+
# new_left = Emu(cell_left._value + (cw - pic.width) // 2)
|
| 733 |
+
# new_top = Emu(cell_top._value + (ch - pic.height) // 2)
|
| 734 |
+
# pic.left, pic.top = new_left, new_top
|
| 735 |
+
|
| 736 |
+
# try:
|
| 737 |
+
# pic.line.fill.background()
|
| 738 |
+
# pic.shadow.inherit = False
|
| 739 |
+
# except Exception:
|
| 740 |
+
# pass
|
| 741 |
+
|
| 742 |
+
# except Exception as e:
|
| 743 |
+
# print(f"[WARN] Skipping {img_path}: {e}")
|
| 744 |
+
|
| 745 |
+
# prs.save(output_ppt)
|
| 746 |
+
# print(f"[β
] PowerPoint saved as {output_ppt}")
|