Download cropper.py from OpthLab/OGV: direct link, hf CLI and curl.
- Browser
- Download file 28.6 kB
-
https://huggingface.co/spaces/OpthLab/OGV/resolve/main/cropper.py
- Command line
-
hf download hf://spaces/OpthLab/OGV/cropper.py
-
curl -L -o cropper.py https://huggingface.co/spaces/OpthLab/OGV/resolve/main/cropper.py
28.6 kB
| from ultralytics import YOLO | |
| import cv2 | |
| import os | |
| import numpy as np | |
| import torch | |
| from torchvision import models, transforms | |
| from PIL import Image | |
| from pptx import Presentation | |
| from pptx.util import Inches, Emu, Pt | |
| # βββββββββββββββββββββββββββββ | |
| # 1οΈβ£ YOLO Model Loader | |
| # βββββββββββββββββββββββββββββ | |
| def load_model(mode="eye"): | |
| base_dir = os.path.dirname(os.path.abspath(__file__)) | |
| if mode == "eye": | |
| model_path = os.path.join(base_dir, "models/besteyegwinf.pt") | |
| elif mode == "vagina": | |
| model_path = os.path.join(base_dir, "models/bestvag3.pt") | |
| else: | |
| raise ValueError("Invalid mode! Use 'eye' or 'vagina'.") | |
| if not os.path.exists(model_path): | |
| raise FileNotFoundError(f"Model not found: {model_path}") | |
| return YOLO(model_path) | |
| # βββββββββββββββββββββββββββββ | |
| # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion) | |
| # βββββββββββββββββββββββββββββ | |
| def pad_to_fixed_rectangle(image, target_w=1000, target_h=700): | |
| """Fits cropped image into fixed rectangle without stretching.""" | |
| h, w = image.shape[:2] | |
| scale = min(target_w / w, target_h / h) | |
| new_w, new_h = int(w * scale), int(h * scale) | |
| resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) | |
| canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255 | |
| x_offset = (target_w - new_w) // 2 | |
| y_offset = (target_h - new_h) // 2 | |
| canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized | |
| return canvas | |
| # βββββββββββββββββββββββββββββ | |
| # 3οΈβ£ Crop Image with YOLO | |
| # βββββββββββββββββββββββββββββ | |
| def crop_with_yolo(img_path, mode="eye"): | |
| try: | |
| yolo_model = load_model(mode) | |
| conf_value = 0.55 if mode == "eye" else 0.05 | |
| results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False) | |
| img = cv2.imread(img_path) | |
| if img is None: | |
| print(f"[ERROR] Could not read {img_path}") | |
| return img_path | |
| if not results or not len(results[0].boxes): | |
| print(f"[WARN] No detection for {img_path} ({mode})") | |
| padded = pad_to_fixed_rectangle(img) | |
| out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg" | |
| cv2.imwrite(out_path, padded) | |
| return out_path | |
| boxes = results[0].boxes | |
| best = boxes[boxes.conf.argmax()] | |
| x1, y1, x2, y2 = map(int, best.xyxy[0]) | |
| h, w = img.shape[:2] | |
| x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2) | |
| crop = img[y1:y2, x1:x2].copy() | |
| padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700) | |
| out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg" | |
| cv2.imwrite(out_path, padded) | |
| print(f"[INFO] Saved {out_path}") | |
| return out_path | |
| except Exception as e: | |
| print(f"[ERROR] YOLO cropping failed: {e}") | |
| return img_path | |
| # βββββββββββββββββββββββββββββ | |
| # 4οΈβ£ Infection Score Classifier (EfficientNet for eye & vagina) | |
| # βββββββββββββββββββββββββββββ | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| _loaded_classifiers = {} | |
| cls_tfms = transforms.Compose([ | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor(), | |
| transforms.Normalize([0.485, 0.456, 0.406], | |
| [0.229, 0.224, 0.225]), | |
| ]) | |
| def load_classifier(mode="eye"): | |
| """Loads the correct classifier (eye/vagina) only once.""" | |
| global _loaded_classifiers | |
| if mode in _loaded_classifiers: | |
| return _loaded_classifiers[mode] | |
| base_dir = os.path.dirname(os.path.abspath(__file__)) | |
| model_file = ( | |
| os.path.join(base_dir, "models/grey_and_white_eye_infection_classifier.pth") | |
| if mode == "eye" | |
| else os.path.join(base_dir, "models/vagina_infection_classifier.pth") | |
| ) | |
| if not os.path.exists(model_file): | |
| raise FileNotFoundError(f"Classifier model not found: {model_file}") | |
| model = models.efficientnet_b0(weights=None) | |
| model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5) | |
| model.load_state_dict(torch.load(model_file, map_location=device)) | |
| model.eval().to(device) | |
| _loaded_classifiers[mode] = model | |
| print(f"[INFO] Loaded classifier for {mode}") | |
| return model | |
| def predict_infection_score(image_path: str, mode="eye") -> int: | |
| """Predicts infection score (1β5) for both eyes and vaginas.""" | |
| try: | |
| model = load_classifier(mode) | |
| img = Image.open(image_path).convert("RGB") | |
| x = cls_tfms(img).unsqueeze(0).to(device) | |
| with torch.no_grad(): | |
| logits = model(x) | |
| pred = logits.argmax(1).item() + 1 | |
| return pred | |
| except Exception as e: | |
| print(f"[ERROR] Score prediction failed: {e}") | |
| return None | |
| # #First deployed | |
| # from ultralytics import YOLO | |
| # import cv2 | |
| # import os | |
| # import numpy as np | |
| # import torch | |
| # from torchvision import models, transforms | |
| # from PIL import Image | |
| # from pptx import Presentation | |
| # from pptx.util import Inches, Emu, Pt | |
| # # βββββββββββββββββββββββββββββ | |
| # # 1οΈβ£ YOLO Model Loader | |
| # # βββββββββββββββββββββββββββββ | |
| # def load_model(mode="eye"): | |
| # base_dir = os.path.dirname(os.path.abspath(__file__)) | |
| # if mode == "eye": | |
| # model_path = os.path.join(base_dir, "models/besteyegwinf.pt") | |
| # elif mode == "vagina": | |
| # model_path = os.path.join(base_dir, "models/bestvag3.pt") | |
| # else: | |
| # raise ValueError("Invalid mode! Use 'eye' or 'vagina'.") | |
| # if not os.path.exists(model_path): | |
| # raise FileNotFoundError(f"Model not found: {model_path}") | |
| # return YOLO(model_path) | |
| # # βββββββββββββββββββββββββββββ | |
| # # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion) | |
| # # βββββββββββββββββββββββββββββ | |
| # def pad_to_fixed_rectangle(image, target_w=1000, target_h=700): | |
| # """Fits cropped image into fixed rectangle without stretching.""" | |
| # h, w = image.shape[:2] | |
| # scale = min(target_w / w, target_h / h) | |
| # new_w, new_h = int(w * scale), int(h * scale) | |
| # resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) | |
| # canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255 | |
| # x_offset = (target_w - new_w) // 2 | |
| # y_offset = (target_h - new_h) // 2 | |
| # canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized | |
| # return canvas | |
| # # βββββββββββββββββββββββββββββ | |
| # # 3οΈβ£ Crop Image with YOLO | |
| # # βββββββββββββββββββββββββββββ | |
| # def crop_with_yolo(img_path, mode="eye"): | |
| # try: | |
| # yolo_model = load_model(mode) | |
| # conf_value = 0.55 if mode == "eye" else 0.05 | |
| # results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False) | |
| # img = cv2.imread(img_path) | |
| # if img is None: | |
| # print(f"[ERROR] Could not read {img_path}") | |
| # return img_path | |
| # if not results or not len(results[0].boxes): | |
| # print(f"[WARN] No detection for {img_path} ({mode})") | |
| # padded = pad_to_fixed_rectangle(img) | |
| # out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg" | |
| # cv2.imwrite(out_path, padded) | |
| # return out_path | |
| # boxes = results[0].boxes | |
| # best = boxes[boxes.conf.argmax()] | |
| # x1, y1, x2, y2 = map(int, best.xyxy[0]) | |
| # h, w = img.shape[:2] | |
| # x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2) | |
| # crop = img[y1:y2, x1:x2].copy() | |
| # padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700) | |
| # out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg" | |
| # cv2.imwrite(out_path, padded) | |
| # print(f"[INFO] Saved {out_path}") | |
| # return out_path | |
| # except Exception as e: | |
| # print(f"[ERROR] YOLO cropping failed: {e}") | |
| # return img_path | |
| # # βββββββββββββββββββββββββββββ | |
| # # 4οΈβ£ Infection Score Classifier (EfficientNet for eye & vagina) | |
| # # βββββββββββββββββββββββββββββ | |
| # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| # _loaded_classifiers = {} | |
| # cls_tfms = transforms.Compose([ | |
| # transforms.Resize((224, 224)), | |
| # transforms.ToTensor(), | |
| # transforms.Normalize([0.485, 0.456, 0.406], | |
| # [0.229, 0.224, 0.225]), | |
| # ]) | |
| # def load_classifier(mode="eye"): | |
| # """Loads the correct classifier (eye/vagina) only once.""" | |
| # global _loaded_classifiers | |
| # if mode in _loaded_classifiers: | |
| # return _loaded_classifiers[mode] | |
| # base_dir = os.path.dirname(os.path.abspath(__file__)) | |
| # model_file = ( | |
| # os.path.join(base_dir, "models/grey_and_white_eye_infection_classifier.pth") | |
| # if mode == "eye" | |
| # else os.path.join(base_dir, "models/vagina_infection_classifier.pth") | |
| # ) | |
| # if not os.path.exists(model_file): | |
| # raise FileNotFoundError(f"Classifier model not found: {model_file}") | |
| # model = models.efficientnet_b0(weights=None) | |
| # model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5) | |
| # model.load_state_dict(torch.load(model_file, map_location=device)) | |
| # model.eval().to(device) | |
| # _loaded_classifiers[mode] = model | |
| # print(f"[INFO] Loaded classifier for {mode}") | |
| # return model | |
| # def predict_infection_score(image_path: str, mode="eye") -> int: | |
| # """Predicts infection score (1β5) for both eyes and vaginas.""" | |
| # try: | |
| # model = load_classifier(mode) | |
| # img = Image.open(image_path).convert("RGB") | |
| # x = cls_tfms(img).unsqueeze(0).to(device) | |
| # with torch.no_grad(): | |
| # logits = model(x) | |
| # pred = logits.argmax(1).item() + 1 | |
| # return pred | |
| # except Exception as e: | |
| # print(f"[ERROR] Score prediction failed: {e}") | |
| # return None | |
| # #PRESENTED IN LAB MEETING | |
| # from ultralytics import YOLO | |
| # import cv2 | |
| # import os | |
| # import numpy as np | |
| # from pptx import Presentation | |
| # from pptx.util import Inches, Emu, Pt | |
| # # βββββββββββββββββββββββββββββ | |
| # # 1οΈβ£ YOLO Model Loader | |
| # # βββββββββββββββββββββββββββββ | |
| # def load_model(mode="eye"): | |
| # base_dir = os.path.dirname(os.path.abspath(__file__)) | |
| # if mode == "eye": | |
| # model_path = os.path.join(base_dir, "besteyegwinf.pt") | |
| # elif mode == "vagina": | |
| # model_path = os.path.join(base_dir, "bestvag3.pt") | |
| # else: | |
| # raise ValueError("Invalid mode! Use 'eye' or 'vagina'.") | |
| # if not os.path.exists(model_path): | |
| # raise FileNotFoundError(f"Model not found: {model_path}") | |
| # return YOLO(model_path) | |
| # # βββββββββββββββββββββββββββββ | |
| # # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion) | |
| # # βββββββββββββββββββββββββββββ | |
| # def pad_to_fixed_rectangle(image, target_w=1000, target_h=700): | |
| # """Fits the cropped image into a fixed rectangular box (1000Γ700) | |
| # without stretching or distorting it. | |
| # Keeps original aspect ratio and adds white padding if needed.""" | |
| # h, w = image.shape[:2] | |
| # scale = min(target_w / w, target_h / h) | |
| # new_w, new_h = int(w * scale), int(h * scale) | |
| # resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) | |
| # canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255 | |
| # x_offset = (target_w - new_w) // 2 | |
| # y_offset = (target_h - new_h) // 2 | |
| # canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized | |
| # return canvas | |
| # # βββββββββββββββββββββββββββββ | |
| # # 3οΈβ£ Crop Image with YOLO | |
| # # βββββββββββββββββββββββββββββ | |
| # def crop_with_yolo(img_path, mode="eye"): | |
| # try: | |
| # yolo_model = load_model(mode) | |
| # conf_value = 0.55 if mode == "eye" else 0.1 | |
| # results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False) | |
| # img = cv2.imread(img_path) | |
| # if img is None: | |
| # print(f"[ERROR] Could not read {img_path}") | |
| # return img_path | |
| # if not results or not len(results[0].boxes): | |
| # print(f"[WARN] No detection for {img_path} ({mode})") | |
| # padded = pad_to_fixed_rectangle(img) | |
| # out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg" | |
| # cv2.imwrite(out_path, padded) | |
| # return out_path | |
| # boxes = results[0].boxes | |
| # best = boxes[boxes.conf.argmax()] | |
| # x1, y1, x2, y2 = map(int, best.xyxy[0]) | |
| # h, w = img.shape[:2] | |
| # x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2) | |
| # crop = img[y1:y2, x1:x2].copy() | |
| # padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700) | |
| # out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg" | |
| # cv2.imwrite(out_path, padded) | |
| # print(f"[INFO] Saved {out_path}") | |
| # return out_path | |
| # except Exception as e: | |
| # print(f"[ERROR] YOLO cropping failed: {e}") | |
| # return img_path | |
| # # βββββββββββββββββββββββββββββ | |
| # # 4οΈβ£ Generate PowerPoint (no distortion) | |
| # # βββββββββββββββββββββββββββββ | |
| # def generate_ppt(image_paths, output_ppt="output.pptx"): | |
| # prs = Presentation() | |
| # cols, rows = 3, 2 | |
| # margin_left, margin_top = Inches(0.5), Inches(0.5) | |
| # cell_w, cell_h = Inches(3.0), Inches(2.25) | |
| # slide = None | |
| # for i, img_path in enumerate([p for p in image_paths if p and os.path.exists(p)]): | |
| # if i % (cols * rows) == 0: | |
| # slide = prs.slides.add_slide(prs.slide_layouts[6]) | |
| # idx = i % (cols * rows) | |
| # r, c = divmod(idx, cols) | |
| # cell_left = margin_left + c * cell_w | |
| # cell_top = margin_top + r * cell_h | |
| # try: | |
| # slide.shapes.add_picture(img_path, cell_left, cell_top, width=cell_w, height=cell_h) | |
| # except Exception as e: | |
| # print(f"[WARN] Skipping {img_path}: {e}") | |
| # prs.save(output_ppt) | |
| # print(f"[β ] PowerPoint saved as {output_ppt}") | |
| # # βββββββββββββββββββββββββββββ | |
| # # 5οΈβ£ Infection Score Classifier (EfficientNet) | |
| # # βββββββββββββββββββββββββββββ | |
| # import torch | |
| # from torchvision import models, transforms | |
| # from PIL import Image | |
| # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| # _classifier_model = None | |
| # def load_classifier(): | |
| # """Loads the trained EfficientNet classifier model once.""" | |
| # global _classifier_model | |
| # if _classifier_model is None: | |
| # model = models.efficientnet_b0(pretrained=False) | |
| # model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5) | |
| # model.load_state_dict(torch.load("eye_infection_classifier.pth", map_location=device)) | |
| # model.eval().to(device) | |
| # _classifier_model = model | |
| # return _classifier_model | |
| # cls_tfms = transforms.Compose([ | |
| # transforms.Resize((224, 224)), | |
| # transforms.ToTensor(), | |
| # transforms.Normalize([0.485, 0.456, 0.406], | |
| # [0.229, 0.224, 0.225]), | |
| # ]) | |
| # def predict_infection_score(image_path: str) -> int: | |
| # """Predicts infection score (1β5) for eye images only.""" | |
| # model = load_classifier() | |
| # img = Image.open(image_path).convert("RGB") | |
| # x = cls_tfms(img).unsqueeze(0).to(device) | |
| # with torch.no_grad(): | |
| # logits = model(x) | |
| # pred = logits.argmax(1).item() + 1 | |
| # return pred | |
| # #GOOD WORKING FOR EYE INFECTION SCORES, ALSO DISPLAYS VAGINA SCORES WHICH ARE CURRENTLY NOT REQUIRED | |
| # from ultralytics import YOLO | |
| # import cv2 | |
| # import os | |
| # import numpy as np | |
| # from pptx import Presentation | |
| # from pptx.util import Inches, Emu, Pt | |
| # # βββββββββββββββββββββββββββββ | |
| # # 1οΈβ£ YOLO Model Loader | |
| # # βββββββββββββββββββββββββββββ | |
| # def load_model(mode="eye"): | |
| # base_dir = os.path.dirname(os.path.abspath(__file__)) | |
| # if mode == "eye": | |
| # model_path = os.path.join(base_dir, "besteyegwinf.pt") | |
| # elif mode == "vagina": | |
| # model_path = os.path.join(base_dir, "bestvag3.pt") | |
| # else: | |
| # raise ValueError("Invalid mode! Use 'eye' or 'vagina'.") | |
| # if not os.path.exists(model_path): | |
| # raise FileNotFoundError(f"Model not found: {model_path}") | |
| # return YOLO(model_path) | |
| # # βββββββββββββββββββββββββββββ | |
| # # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion) | |
| # # βββββββββββββββββββββββββββββ | |
| # def pad_to_fixed_rectangle(image, target_w=1000, target_h=700): | |
| # """ | |
| # Fits the cropped image into a fixed rectangular box (1000Γ700) | |
| # without stretching or distorting it. | |
| # Keeps original aspect ratio and adds white padding if needed. | |
| # """ | |
| # h, w = image.shape[:2] | |
| # scale = min(target_w / w, target_h / h) | |
| # new_w, new_h = int(w * scale), int(h * scale) | |
| # resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) | |
| # canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255 | |
| # x_offset = (target_w - new_w) // 2 | |
| # y_offset = (target_h - new_h) // 2 | |
| # canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized | |
| # return canvas | |
| # # βββββββββββββββββββββββββββββ | |
| # # 3οΈβ£ Crop Image with YOLO | |
| # # βββββββββββββββββββββββββββββ | |
| # def crop_with_yolo(img_path, mode="eye"): | |
| # try: | |
| # yolo_model = load_model(mode) | |
| # conf_value = 0.55 if mode == "eye" else 0.1 | |
| # results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False) | |
| # img = cv2.imread(img_path) | |
| # if img is None: | |
| # print(f"[ERROR] Could not read {img_path}") | |
| # return img_path | |
| # if not results or not len(results[0].boxes): | |
| # print(f"[WARN] No detection for {img_path} ({mode})") | |
| # padded = pad_to_fixed_rectangle(img) | |
| # out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg" | |
| # cv2.imwrite(out_path, padded) | |
| # return out_path | |
| # boxes = results[0].boxes | |
| # best = boxes[boxes.conf.argmax()] | |
| # x1, y1, x2, y2 = map(int, best.xyxy[0]) | |
| # h, w = img.shape[:2] | |
| # x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2) | |
| # crop = img[y1:y2, x1:x2].copy() | |
| # padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700) | |
| # out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg" | |
| # cv2.imwrite(out_path, padded) | |
| # print(f"[INFO] Saved {out_path}") | |
| # return out_path | |
| # except Exception as e: | |
| # print(f"[ERROR] YOLO cropping failed: {e}") | |
| # return img_path | |
| # # βββββββββββββββββββββββββββββ | |
| # # 4οΈβ£ Generate PowerPoint (no distortion) | |
| # # βββββββββββββββββββββββββββββ | |
| # def generate_ppt(image_paths, output_ppt="output.pptx"): | |
| # prs = Presentation() | |
| # cols, rows = 3, 2 | |
| # margin_left, margin_top = Inches(0.5), Inches(0.5) | |
| # cell_w, cell_h = Inches(3.0), Inches(2.25) | |
| # slide = None | |
| # for i, img_path in enumerate([p for p in image_paths if p and os.path.exists(p)]): | |
| # if i % (cols * rows) == 0: | |
| # slide = prs.slides.add_slide(prs.slide_layouts[6]) | |
| # idx = i % (cols * rows) | |
| # r, c = divmod(idx, cols) | |
| # cell_left = margin_left + c * cell_w | |
| # cell_top = margin_top + r * cell_h | |
| # try: | |
| # pic = slide.shapes.add_picture(img_path, cell_left, cell_top, | |
| # width=cell_w, height=cell_h) | |
| # cw, ch = cell_w._value, cell_h._value | |
| # new_left = Emu(cell_left._value + (cw - pic.width) // 2) | |
| # new_top = Emu(cell_top._value + (ch - pic.height) // 2) | |
| # pic.left, pic.top = new_left, new_top | |
| # except Exception as e: | |
| # print(f"[WARN] Skipping {img_path}: {e}") | |
| # prs.save(output_ppt) | |
| # print(f"[β ] PowerPoint saved as {output_ppt}") | |
| # # βββββββββββββββββββββββββββββ | |
| # # 5οΈβ£ Infection Score Classifier (EfficientNet) | |
| # # βββββββββββββββββββββββββββββ | |
| # import torch | |
| # from torchvision import models, transforms | |
| # from PIL import Image | |
| # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| # _classifier_model = None | |
| # def load_classifier(): | |
| # """Loads the trained EfficientNet classifier model once.""" | |
| # global _classifier_model | |
| # if _classifier_model is None: | |
| # model = models.efficientnet_b0(pretrained=False) | |
| # model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5) | |
| # model.load_state_dict(torch.load("eye_infection_classifier.pth", map_location=device)) | |
| # model.eval().to(device) | |
| # _classifier_model = model | |
| # return _classifier_model | |
| # cls_tfms = transforms.Compose([ | |
| # transforms.Resize((224, 224)), | |
| # transforms.ToTensor(), | |
| # transforms.Normalize([0.485, 0.456, 0.406], | |
| # [0.229, 0.224, 0.225]), | |
| # ]) | |
| # def predict_infection_score(image_path: str) -> int: | |
| # """Predicts infection score (1β5) for the given eye image.""" | |
| # model = load_classifier() | |
| # img = Image.open(image_path).convert("RGB") | |
| # x = cls_tfms(img).unsqueeze(0).to(device) | |
| # with torch.no_grad(): | |
| # logits = model(x) | |
| # pred = logits.argmax(1).item() + 1 | |
| # return pred | |
| # #FINAL WORKING HEALTHY INFECTED CROPPING CODE | |
| # from ultralytics import YOLO | |
| # import cv2 | |
| # import os | |
| # import numpy as np | |
| # from pptx import Presentation | |
| # from pptx.util import Inches, Emu, Pt | |
| # # βββββββββββββββββββββββββββββ | |
| # # 1οΈβ£ YOLO Model Loader | |
| # # βββββββββββββββββββββββββββββ | |
| # def load_model(mode="eye"): | |
| # base_dir = os.path.dirname(os.path.abspath(__file__)) | |
| # if mode == "eye": | |
| # model_path = os.path.join(base_dir, "besteyegwinf.pt") | |
| # elif mode == "vagina": | |
| # model_path = os.path.join(base_dir, "bestvag3.pt") | |
| # else: | |
| # raise ValueError("Invalid mode! Use 'eye' or 'vagina'.") | |
| # if not os.path.exists(model_path): | |
| # raise FileNotFoundError(f"Model not found: {model_path}") | |
| # return YOLO(model_path) | |
| # # βββββββββββββββββββββββββββββ | |
| # # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion) | |
| # # βββββββββββββββββββββββββββββ | |
| # def pad_to_fixed_rectangle(image, target_w=1000, target_h=700): | |
| # """ | |
| # Fits the cropped image into a fixed rectangular box (1000Γ700) | |
| # without stretching or distorting it. | |
| # Keeps original aspect ratio and adds white padding if needed. | |
| # """ | |
| # h, w = image.shape[:2] | |
| # scale = min(target_w / w, target_h / h) | |
| # new_w, new_h = int(w * scale), int(h * scale) | |
| # resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) | |
| # # Create white canvas and center the resized image | |
| # canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255 | |
| # x_offset = (target_w - new_w) // 2 | |
| # y_offset = (target_h - new_h) // 2 | |
| # canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized | |
| # return canvas | |
| # # βββββββββββββββββββββββββββββ | |
| # # 3οΈβ£ Crop Image with YOLO | |
| # # βββββββββββββββββββββββββββββ | |
| # def crop_with_yolo(img_path, mode="eye"): | |
| # try: | |
| # yolo_model = load_model(mode) | |
| # conf_value = 0.55 if mode == "eye" else 0.1 | |
| # results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False) | |
| # img = cv2.imread(img_path) | |
| # if img is None: | |
| # print(f"[ERROR] Could not read {img_path}") | |
| # return img_path | |
| # # No detections β use original image padded | |
| # if not results or not len(results[0].boxes): | |
| # print(f"[WARN] No detection for {img_path} ({mode})") | |
| # padded = pad_to_fixed_rectangle(img) | |
| # out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg" | |
| # cv2.imwrite(out_path, padded) | |
| # return out_path | |
| # # Use highest-confidence detection | |
| # boxes = results[0].boxes | |
| # best = boxes[boxes.conf.argmax()] | |
| # x1, y1, x2, y2 = map(int, best.xyxy[0]) | |
| # h, w = img.shape[:2] | |
| # x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2) | |
| # crop = img[y1:y2, x1:x2].copy() | |
| # # β Make all crops same rectangular size (no distortion) | |
| # padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700) | |
| # out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg" | |
| # cv2.imwrite(out_path, padded) | |
| # print(f"[INFO] Saved {out_path}") | |
| # return out_path | |
| # except Exception as e: | |
| # print(f"[ERROR] YOLO cropping failed: {e}") | |
| # return img_path | |
| # # βββββββββββββββββββββββββββββ | |
| # # 4οΈβ£ Generate PowerPoint (no distortion) | |
| # # βββββββββββββββββββββββββββββ | |
| # def generate_ppt(image_paths, output_ppt="output.pptx"): | |
| # """ | |
| # Adds up to 6 images per slide (3Γ2 grid). | |
| # Each image has uniform rectangular size (no stretching). | |
| # """ | |
| # prs = Presentation() | |
| # cols, rows = 3, 2 | |
| # margin_left, margin_top = Inches(0.5), Inches(0.5) | |
| # cell_w, cell_h = Inches(3.0), Inches(2.25) # rectangular frame | |
| # slide = None | |
| # for i, img_path in enumerate([p for p in image_paths if p and os.path.exists(p)]): | |
| # if i % (cols * rows) == 0: | |
| # slide = prs.slides.add_slide(prs.slide_layouts[6]) | |
| # idx = i % (cols * rows) | |
| # r, c = divmod(idx, cols) | |
| # cell_left = margin_left + c * cell_w | |
| # cell_top = margin_top + r * cell_h | |
| # try: | |
| # pic = slide.shapes.add_picture(img_path, cell_left, cell_top, | |
| # width=cell_w, height=cell_h) | |
| # cw, ch = cell_w._value, cell_h._value | |
| # new_left = Emu(cell_left._value + (cw - pic.width) // 2) | |
| # new_top = Emu(cell_top._value + (ch - pic.height) // 2) | |
| # pic.left, pic.top = new_left, new_top | |
| # try: | |
| # pic.line.fill.background() | |
| # pic.shadow.inherit = False | |
| # except Exception: | |
| # pass | |
| # except Exception as e: | |
| # print(f"[WARN] Skipping {img_path}: {e}") | |
| # prs.save(output_ppt) | |
| # print(f"[β ] PowerPoint saved as {output_ppt}") | |