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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import math
|
| 4 |
+
import streamlit as st
|
| 5 |
+
from pptx import Presentation
|
| 6 |
+
from pptx.util import Inches, Pt
|
| 7 |
+
from pptx.dml.color import RGBColor
|
| 8 |
+
from pptx.enum.text import PP_ALIGN
|
| 9 |
+
from PIL import Image, ImageOps
|
| 10 |
+
from cropper import crop_with_yolo, predict_infection_score
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# βββββββββββββββββββββββββββββ
|
| 14 |
+
# Streamlit UI
|
| 15 |
+
# βββββββββββββββββββββββββββββ
|
| 16 |
+
st.title("π Treatments β PowerPoint Generator with Infection Scores")
|
| 17 |
+
|
| 18 |
+
main_option = st.selectbox("Select Main Option", ["O", "V"])
|
| 19 |
+
mode = "eye" if main_option == "O" else "vagina"
|
| 20 |
+
st.write(f"π§ YOLO mode: {mode}")
|
| 21 |
+
|
| 22 |
+
num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1)
|
| 23 |
+
num_days = st.number_input("Enter number of days", 1, 10, 3, 1)
|
| 24 |
+
max_imgs_per_slide = st.number_input(
|
| 25 |
+
"Enter number of images per slide", 1, 50, 9, 1
|
| 26 |
+
)
|
| 27 |
+
#Number of images upto 50
|
| 28 |
+
|
| 29 |
+
treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)]
|
| 30 |
+
day_list = [f"Day {i+1}" for i in range(num_days)]
|
| 31 |
+
|
| 32 |
+
uploaded_files = {}
|
| 33 |
+
st.markdown("### π Upload images for each Treatment and Day")
|
| 34 |
+
for treatment in treatment_list:
|
| 35 |
+
st.subheader(treatment)
|
| 36 |
+
uploaded_files[treatment] = {}
|
| 37 |
+
for day in day_list:
|
| 38 |
+
uploaded_files[treatment][day] = st.file_uploader(
|
| 39 |
+
f"Upload image(s) for {day}",
|
| 40 |
+
type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"],
|
| 41 |
+
accept_multiple_files=True,
|
| 42 |
+
key=f"{treatment}_{day}",
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# βββββββββββββββββββββββββββββ
|
| 49 |
+
# Helpers
|
| 50 |
+
# βββββββββββββββββββββββββββββ
|
| 51 |
+
def normalize_image_for_ppt(path: str) -> str | None:
|
| 52 |
+
"""Convert unsupported formats to PNG + fix EXIF rotation."""
|
| 53 |
+
try:
|
| 54 |
+
with Image.open(path) as im:
|
| 55 |
+
fmt = (im.format or "").upper()
|
| 56 |
+
im = ImageOps.exif_transpose(im)
|
| 57 |
+
if fmt not in SUPPORTED_BY_PPTX:
|
| 58 |
+
im = im.convert("RGB")
|
| 59 |
+
out_path = os.path.splitext(path)[0] + "_clean.png"
|
| 60 |
+
im.save(out_path, "PNG")
|
| 61 |
+
return out_path
|
| 62 |
+
return path
|
| 63 |
+
except Exception as e:
|
| 64 |
+
st.error(f"β Could not normalize image '{path}': {e}")
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def crop_with_margin(image_path: str, mode: str) -> str:
|
| 69 |
+
"""Use YOLO model for cropping (no extra PPT-side padding)."""
|
| 70 |
+
try:
|
| 71 |
+
cropped = crop_with_yolo(image_path, mode)
|
| 72 |
+
return cropped if cropped and os.path.exists(cropped) else image_path
|
| 73 |
+
except Exception as e:
|
| 74 |
+
st.error(f"β YOLO crop failed for {image_path}: {e}")
|
| 75 |
+
return image_path
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def compute_grid(n: int) -> tuple[int, int]:
|
| 79 |
+
"""Decide columns/rows so n images fit nicely."""
|
| 80 |
+
cols = math.ceil(math.sqrt(n))
|
| 81 |
+
rows = math.ceil(n / cols)
|
| 82 |
+
return cols, rows
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def add_centered_title(slide, title_text: str, slide_width_in: float):
|
| 86 |
+
"""Add a perfectly centered title using presentation width."""
|
| 87 |
+
title_box = slide.shapes.add_textbox(
|
| 88 |
+
Inches(0),
|
| 89 |
+
Inches(0.2),
|
| 90 |
+
Inches(slide_width_in),
|
| 91 |
+
Inches(0.8),
|
| 92 |
+
)
|
| 93 |
+
tf = title_box.text_frame
|
| 94 |
+
tf.word_wrap = True
|
| 95 |
+
p = tf.paragraphs[0]
|
| 96 |
+
p.text = title_text
|
| 97 |
+
p.alignment = PP_ALIGN.CENTER
|
| 98 |
+
p.font.bold = True
|
| 99 |
+
p.font.size = Pt(24)
|
| 100 |
+
p.font.color.rgb = RGBColor(0, 0, 0)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def get_font_size(num_images: int) -> int:
|
| 104 |
+
"""Dynamic caption font size."""
|
| 105 |
+
if num_images <= 6:
|
| 106 |
+
return 12
|
| 107 |
+
elif num_images <= 20:
|
| 108 |
+
return 10
|
| 109 |
+
elif num_images <= 35:
|
| 110 |
+
return 8
|
| 111 |
+
else:
|
| 112 |
+
return 7
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# βββββββββββββββββββββββββββββ
|
| 116 |
+
# PowerPoint Generation
|
| 117 |
+
# βββββββββββββββββββββββββββββ
|
| 118 |
+
if st.button("π Generate PowerPoint"):
|
| 119 |
+
prs = Presentation()
|
| 120 |
+
EMU_PER_INCH = 914400
|
| 121 |
+
SLIDE_W_IN = prs.slide_width / EMU_PER_INCH
|
| 122 |
+
SLIDE_H_IN = prs.slide_height / EMU_PER_INCH
|
| 123 |
+
|
| 124 |
+
# Margins and layout constants
|
| 125 |
+
LEFT_MARGIN_IN = 0.5
|
| 126 |
+
RIGHT_MARGIN_IN = 0.5
|
| 127 |
+
TOP_MARGIN_IN = 1.0
|
| 128 |
+
BOTTOM_MARGIN_IN = 0.5
|
| 129 |
+
usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN
|
| 130 |
+
usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN
|
| 131 |
+
|
| 132 |
+
base_font_size = get_font_size(max_imgs_per_slide)
|
| 133 |
+
|
| 134 |
+
for day in day_list:
|
| 135 |
+
st.write(f"πΌοΈ Adding images for {day}...")
|
| 136 |
+
|
| 137 |
+
# Gather all uploaded files for this day
|
| 138 |
+
day_files = []
|
| 139 |
+
for treatment in treatment_list:
|
| 140 |
+
files = uploaded_files[treatment][day]
|
| 141 |
+
if files:
|
| 142 |
+
for f in files:
|
| 143 |
+
day_files.append((treatment, f))
|
| 144 |
+
|
| 145 |
+
total_imgs = len(day_files)
|
| 146 |
+
if total_imgs == 0:
|
| 147 |
+
continue
|
| 148 |
+
|
| 149 |
+
# Compute a single, consistent grid for all slides in this day
|
| 150 |
+
cols, rows = compute_grid(max_imgs_per_slide)
|
| 151 |
+
cell_w = usable_w_in / cols
|
| 152 |
+
cell_h = usable_h_in / rows
|
| 153 |
+
image_h_ratio = 0.75
|
| 154 |
+
img_area_h = cell_h * image_h_ratio
|
| 155 |
+
caption_h = cell_h * (1 - image_h_ratio)
|
| 156 |
+
|
| 157 |
+
idx = 0
|
| 158 |
+
slide_index_for_day = 0
|
| 159 |
+
|
| 160 |
+
while idx < total_imgs:
|
| 161 |
+
chunk = day_files[idx:idx + max_imgs_per_slide]
|
| 162 |
+
n_chunk = len(chunk)
|
| 163 |
+
|
| 164 |
+
slide = prs.slides.add_slide(prs.slide_layouts[6])
|
| 165 |
+
title_suffix = "" if slide_index_for_day == 0 else f" (contd.)"
|
| 166 |
+
add_centered_title(slide, f"{day} β Treatment Images{title_suffix}", SLIDE_W_IN)
|
| 167 |
+
slide_index_for_day += 1
|
| 168 |
+
|
| 169 |
+
for local_i, (treatment, file) in enumerate(chunk):
|
| 170 |
+
row = local_i // cols
|
| 171 |
+
col = local_i % cols
|
| 172 |
+
cell_left = LEFT_MARGIN_IN + col * cell_w
|
| 173 |
+
cell_top = TOP_MARGIN_IN + row * cell_h
|
| 174 |
+
|
| 175 |
+
suffix = os.path.splitext(file.name)[1]
|
| 176 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 177 |
+
tmp.write(file.read())
|
| 178 |
+
raw_path = tmp.name
|
| 179 |
+
|
| 180 |
+
cropped_path = crop_with_margin(raw_path, mode)
|
| 181 |
+
safe_path = normalize_image_for_ppt(cropped_path)
|
| 182 |
+
if not safe_path:
|
| 183 |
+
continue
|
| 184 |
+
|
| 185 |
+
try:
|
| 186 |
+
# Preserve aspect ratio and fit naturally
|
| 187 |
+
with Image.open(safe_path) as im:
|
| 188 |
+
w, h = im.size
|
| 189 |
+
img_ratio = w / h
|
| 190 |
+
box_ratio = cell_w / img_area_h
|
| 191 |
+
if img_ratio > box_ratio:
|
| 192 |
+
img_w = cell_w * 0.9
|
| 193 |
+
img_h = img_w / img_ratio
|
| 194 |
+
else:
|
| 195 |
+
img_h = img_area_h * 0.9
|
| 196 |
+
img_w = img_h * img_ratio
|
| 197 |
+
|
| 198 |
+
img_left = cell_left + (cell_w - img_w) / 2
|
| 199 |
+
img_top = cell_top + (img_area_h - img_h) / 2
|
| 200 |
+
|
| 201 |
+
slide.shapes.add_picture(
|
| 202 |
+
safe_path,
|
| 203 |
+
left=Inches(img_left),
|
| 204 |
+
top=Inches(img_top),
|
| 205 |
+
width=Inches(img_w),
|
| 206 |
+
height=Inches(img_h),
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# Caption (closer under image)
|
| 210 |
+
score = predict_infection_score(safe_path, mode)
|
| 211 |
+
caption_text = f"{treatment} β {day} | Score: {score}"
|
| 212 |
+
caption_top = cell_top + img_area_h + 0.003 # slightly closer gap
|
| 213 |
+
|
| 214 |
+
tx = slide.shapes.add_textbox(
|
| 215 |
+
Inches(cell_left),
|
| 216 |
+
Inches(caption_top),
|
| 217 |
+
Inches(cell_w),
|
| 218 |
+
Inches(caption_h),
|
| 219 |
+
)
|
| 220 |
+
tf = tx.text_frame
|
| 221 |
+
tf.word_wrap = True
|
| 222 |
+
p = tf.paragraphs[0]
|
| 223 |
+
p.text = caption_text
|
| 224 |
+
p.alignment = PP_ALIGN.CENTER
|
| 225 |
+
p.font.size = Pt(base_font_size)
|
| 226 |
+
p.font.bold = True
|
| 227 |
+
p.font.color.rgb = RGBColor(0, 0, 0)
|
| 228 |
+
|
| 229 |
+
except Exception as e:
|
| 230 |
+
st.error(f"β Failed to add image '{safe_path}': {e}")
|
| 231 |
+
|
| 232 |
+
idx += max_imgs_per_slide
|
| 233 |
+
|
| 234 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx:
|
| 235 |
+
prs.save(tmp_pptx.name)
|
| 236 |
+
st.success("β
PowerPoint generated successfully")
|
| 237 |
+
st.download_button(
|
| 238 |
+
"β¬οΈ Download PowerPoint",
|
| 239 |
+
data=open(tmp_pptx.name, "rb").read(),
|
| 240 |
+
file_name="treatments_with_scores.pptx",
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
# st.success("β
PowerPoint generated successfully β centered titles, perfect spacing, consistent sizing!")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# import os
|
| 247 |
+
# import tempfile
|
| 248 |
+
# import math
|
| 249 |
+
# import streamlit as st
|
| 250 |
+
# from pptx import Presentation
|
| 251 |
+
# from pptx.util import Inches, Pt
|
| 252 |
+
# from pptx.dml.color import RGBColor
|
| 253 |
+
# from pptx.enum.text import PP_ALIGN
|
| 254 |
+
# from PIL import Image, ImageOps
|
| 255 |
+
# from cropper import crop_with_yolo, predict_infection_score
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
# # βββββββββββββββββββββββββββββ
|
| 259 |
+
# # Streamlit UI
|
| 260 |
+
# # βββββββββββββββββββββββββββββ
|
| 261 |
+
# st.title("π Treatments β PowerPoint Generator with Infection Scores")
|
| 262 |
+
|
| 263 |
+
# main_option = st.selectbox("Select Main Option", ["O", "V"])
|
| 264 |
+
# mode = "eye" if main_option == "O" else "vagina"
|
| 265 |
+
# st.write(f"π§ YOLO mode: {mode}")
|
| 266 |
+
|
| 267 |
+
# num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1)
|
| 268 |
+
# num_days = st.number_input("Enter number of days", 1, 10, 3, 1)
|
| 269 |
+
# max_imgs_per_slide = st.number_input(
|
| 270 |
+
# "Enter number of images per slide (up to 50)", 1, 50, 9, 1
|
| 271 |
+
# )
|
| 272 |
+
|
| 273 |
+
# treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)]
|
| 274 |
+
# day_list = [f"Day {i+1}" for i in range(num_days)]
|
| 275 |
+
|
| 276 |
+
# uploaded_files = {}
|
| 277 |
+
# st.markdown("### π Upload images for each Treatment and Day")
|
| 278 |
+
# for treatment in treatment_list:
|
| 279 |
+
# st.subheader(treatment)
|
| 280 |
+
# uploaded_files[treatment] = {}
|
| 281 |
+
# for day in day_list:
|
| 282 |
+
# uploaded_files[treatment][day] = st.file_uploader(
|
| 283 |
+
# f"Upload image(s) for {day}",
|
| 284 |
+
# type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"],
|
| 285 |
+
# accept_multiple_files=True,
|
| 286 |
+
# key=f"{treatment}_{day}",
|
| 287 |
+
# )
|
| 288 |
+
|
| 289 |
+
# SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"}
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# # βββββββββββββββββββββββββββββ
|
| 293 |
+
# # Helpers
|
| 294 |
+
# # βββββββββββββββββββββββββββββ
|
| 295 |
+
# def normalize_image_for_ppt(path: str) -> str | None:
|
| 296 |
+
# """Convert unsupported formats to PNG + fix EXIF rotation."""
|
| 297 |
+
# try:
|
| 298 |
+
# with Image.open(path) as im:
|
| 299 |
+
# fmt = (im.format or "").upper()
|
| 300 |
+
# im = ImageOps.exif_transpose(im)
|
| 301 |
+
# if fmt not in SUPPORTED_BY_PPTX:
|
| 302 |
+
# im = im.convert("RGB")
|
| 303 |
+
# out_path = os.path.splitext(path)[0] + "_clean.png"
|
| 304 |
+
# im.save(out_path, "PNG")
|
| 305 |
+
# return out_path
|
| 306 |
+
# return path
|
| 307 |
+
# except Exception as e:
|
| 308 |
+
# st.error(f"β Could not normalize image '{path}': {e}")
|
| 309 |
+
# return None
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
# def crop_with_margin(image_path: str, mode: str) -> str:
|
| 313 |
+
# """Use YOLO model for cropping (no extra PPT-side padding)."""
|
| 314 |
+
# try:
|
| 315 |
+
# cropped = crop_with_yolo(image_path, mode)
|
| 316 |
+
# return cropped if cropped and os.path.exists(cropped) else image_path
|
| 317 |
+
# except Exception as e:
|
| 318 |
+
# st.error(f"β YOLO crop failed for {image_path}: {e}")
|
| 319 |
+
# return image_path
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
# def compute_grid(n: int) -> tuple[int, int]:
|
| 323 |
+
# """Decide columns/rows so n images fit nicely."""
|
| 324 |
+
# cols = math.ceil(math.sqrt(n))
|
| 325 |
+
# rows = math.ceil(n / cols)
|
| 326 |
+
# return cols, rows
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
# def add_centered_title(slide, title_text: str):
|
| 330 |
+
# """Add a perfectly centered title."""
|
| 331 |
+
# slide_width_in = slide.part.slide_layout.slide_master.part.slide_width / 914400
|
| 332 |
+
# title_box = slide.shapes.add_textbox(
|
| 333 |
+
# Inches(0),
|
| 334 |
+
# Inches(0.2),
|
| 335 |
+
# Inches(slide_width_in),
|
| 336 |
+
# Inches(0.8),
|
| 337 |
+
# )
|
| 338 |
+
# tf = title_box.text_frame
|
| 339 |
+
# tf.word_wrap = True
|
| 340 |
+
# p = tf.paragraphs[0]
|
| 341 |
+
# p.text = title_text
|
| 342 |
+
# p.alignment = PP_ALIGN.CENTER
|
| 343 |
+
# p.font.bold = True
|
| 344 |
+
# p.font.size = Pt(24)
|
| 345 |
+
# p.font.color.rgb = RGBColor(0, 0, 0)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# def get_font_size(num_images: int) -> int:
|
| 349 |
+
# """Dynamic caption font size."""
|
| 350 |
+
# if num_images <= 6:
|
| 351 |
+
# return 12
|
| 352 |
+
# elif num_images <= 20:
|
| 353 |
+
# return 10
|
| 354 |
+
# elif num_images <= 35:
|
| 355 |
+
# return 8
|
| 356 |
+
# else:
|
| 357 |
+
# return 7
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
# # βββββββββββββββββββββββββββββ
|
| 361 |
+
# # PowerPoint Generation
|
| 362 |
+
# # βββββββββββββββββββββββββββββ
|
| 363 |
+
# if st.button("π Generate PowerPoint"):
|
| 364 |
+
# prs = Presentation()
|
| 365 |
+
# EMU_PER_INCH = 914400
|
| 366 |
+
# SLIDE_W_IN = prs.slide_width / EMU_PER_INCH
|
| 367 |
+
# SLIDE_H_IN = prs.slide_height / EMU_PER_INCH
|
| 368 |
+
|
| 369 |
+
# # Margins and layout constants
|
| 370 |
+
# LEFT_MARGIN_IN = 0.5
|
| 371 |
+
# RIGHT_MARGIN_IN = 0.5
|
| 372 |
+
# TOP_MARGIN_IN = 1.0
|
| 373 |
+
# BOTTOM_MARGIN_IN = 0.5
|
| 374 |
+
# usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN
|
| 375 |
+
# usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN
|
| 376 |
+
|
| 377 |
+
# base_font_size = get_font_size(max_imgs_per_slide)
|
| 378 |
+
|
| 379 |
+
# for day in day_list:
|
| 380 |
+
# st.write(f"πΌοΈ Adding images for {day}...")
|
| 381 |
+
|
| 382 |
+
# # Gather all uploaded files for this day
|
| 383 |
+
# day_files = []
|
| 384 |
+
# for treatment in treatment_list:
|
| 385 |
+
# files = uploaded_files[treatment][day]
|
| 386 |
+
# if files:
|
| 387 |
+
# for f in files:
|
| 388 |
+
# day_files.append((treatment, f))
|
| 389 |
+
|
| 390 |
+
# total_imgs = len(day_files)
|
| 391 |
+
# if total_imgs == 0:
|
| 392 |
+
# continue
|
| 393 |
+
|
| 394 |
+
# # Compute a single, consistent grid for all slides in this day
|
| 395 |
+
# cols, rows = compute_grid(max_imgs_per_slide)
|
| 396 |
+
# cell_w = usable_w_in / cols
|
| 397 |
+
# cell_h = usable_h_in / rows
|
| 398 |
+
# image_h_ratio = 0.75
|
| 399 |
+
# img_area_h = cell_h * image_h_ratio
|
| 400 |
+
# caption_h = cell_h * (1 - image_h_ratio)
|
| 401 |
+
|
| 402 |
+
# idx = 0
|
| 403 |
+
# slide_index_for_day = 0
|
| 404 |
+
|
| 405 |
+
# while idx < total_imgs:
|
| 406 |
+
# chunk = day_files[idx:idx + max_imgs_per_slide]
|
| 407 |
+
# n_chunk = len(chunk)
|
| 408 |
+
|
| 409 |
+
# slide = prs.slides.add_slide(prs.slide_layouts[6])
|
| 410 |
+
# title_suffix = "" if slide_index_for_day == 0 else f" (contd.)"
|
| 411 |
+
# add_centered_title(slide, f"{day} β Treatment Images{title_suffix}")
|
| 412 |
+
# slide_index_for_day += 1
|
| 413 |
+
|
| 414 |
+
# for local_i, (treatment, file) in enumerate(chunk):
|
| 415 |
+
# row = local_i // cols
|
| 416 |
+
# col = local_i % cols
|
| 417 |
+
# cell_left = LEFT_MARGIN_IN + col * cell_w
|
| 418 |
+
# cell_top = TOP_MARGIN_IN + row * cell_h
|
| 419 |
+
|
| 420 |
+
# suffix = os.path.splitext(file.name)[1]
|
| 421 |
+
# with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 422 |
+
# tmp.write(file.read())
|
| 423 |
+
# raw_path = tmp.name
|
| 424 |
+
|
| 425 |
+
# cropped_path = crop_with_margin(raw_path, mode)
|
| 426 |
+
# safe_path = normalize_image_for_ppt(cropped_path)
|
| 427 |
+
# if not safe_path:
|
| 428 |
+
# continue
|
| 429 |
+
|
| 430 |
+
# try:
|
| 431 |
+
# # Preserve aspect ratio
|
| 432 |
+
# with Image.open(safe_path) as im:
|
| 433 |
+
# w, h = im.size
|
| 434 |
+
# img_ratio = w / h
|
| 435 |
+
# box_ratio = cell_w / img_area_h
|
| 436 |
+
# if img_ratio > box_ratio:
|
| 437 |
+
# img_w = cell_w * 0.9
|
| 438 |
+
# img_h = img_w / img_ratio
|
| 439 |
+
# else:
|
| 440 |
+
# img_h = img_area_h * 0.9
|
| 441 |
+
# img_w = img_h * img_ratio
|
| 442 |
+
|
| 443 |
+
# img_left = cell_left + (cell_w - img_w) / 2
|
| 444 |
+
# img_top = cell_top + (img_area_h - img_h) / 2
|
| 445 |
+
|
| 446 |
+
# slide.shapes.add_picture(
|
| 447 |
+
# safe_path,
|
| 448 |
+
# left=Inches(img_left),
|
| 449 |
+
# top=Inches(img_top),
|
| 450 |
+
# width=Inches(img_w),
|
| 451 |
+
# height=Inches(img_h),
|
| 452 |
+
# )
|
| 453 |
+
|
| 454 |
+
# # Caption (even closer)
|
| 455 |
+
# score = predict_infection_score(safe_path, mode)
|
| 456 |
+
# caption_text = f"{treatment} β {day} | Score: {score}"
|
| 457 |
+
# caption_top = cell_top + img_area_h + 0.005 # closer spacing
|
| 458 |
+
|
| 459 |
+
# tx = slide.shapes.add_textbox(
|
| 460 |
+
# Inches(cell_left),
|
| 461 |
+
# Inches(caption_top),
|
| 462 |
+
# Inches(cell_w),
|
| 463 |
+
# Inches(caption_h),
|
| 464 |
+
# )
|
| 465 |
+
# tf = tx.text_frame
|
| 466 |
+
# tf.word_wrap = True
|
| 467 |
+
# p = tf.paragraphs[0]
|
| 468 |
+
# p.text = caption_text
|
| 469 |
+
# p.alignment = PP_ALIGN.CENTER
|
| 470 |
+
# p.font.size = Pt(base_font_size)
|
| 471 |
+
# p.font.bold = True
|
| 472 |
+
# p.font.color.rgb = RGBColor(0, 0, 0)
|
| 473 |
+
|
| 474 |
+
# except Exception as e:
|
| 475 |
+
# st.error(f"β Failed to add image '{safe_path}': {e}")
|
| 476 |
+
|
| 477 |
+
# idx += max_imgs_per_slide
|
| 478 |
+
|
| 479 |
+
# with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx:
|
| 480 |
+
# prs.save(tmp_pptx.name)
|
| 481 |
+
# st.success("β
PowerPoint generated successfully β centered titles and clean spacing!")
|
| 482 |
+
# st.download_button(
|
| 483 |
+
# "β¬οΈ Download PowerPoint",
|
| 484 |
+
# data=open(tmp_pptx.name, "rb").read(),
|
| 485 |
+
# file_name="treatments_with_scores.pptx",
|
| 486 |
+
# )
|
| 487 |
+
|
| 488 |
+
# #no overlapping, all images in the PPT are of the same size
|
| 489 |
+
# import os
|
| 490 |
+
# import tempfile
|
| 491 |
+
# import math
|
| 492 |
+
# import streamlit as st
|
| 493 |
+
# from pptx import Presentation
|
| 494 |
+
# from pptx.util import Inches, Pt
|
| 495 |
+
# from pptx.dml.color import RGBColor
|
| 496 |
+
# from pptx.enum.text import PP_ALIGN
|
| 497 |
+
# from PIL import Image, ImageOps
|
| 498 |
+
# from cropper import crop_with_yolo, predict_infection_score
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
# # βββββββββββββββββββββββββββββ
|
| 502 |
+
# # Streamlit UI
|
| 503 |
+
# # βββββββββββββββββββββββββββββ
|
| 504 |
+
# st.title("π Treatments β PowerPoint Generator with Infection Scores")
|
| 505 |
+
|
| 506 |
+
# main_option = st.selectbox("Select Main Option", ["O", "V"])
|
| 507 |
+
# mode = "eye" if main_option == "O" else "vagina"
|
| 508 |
+
# st.write(f"π§ YOLO mode: {mode}")
|
| 509 |
+
|
| 510 |
+
# num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1)
|
| 511 |
+
# num_days = st.number_input("Enter number of days", 1, 10, 3, 1)
|
| 512 |
+
# max_imgs_per_slide = st.number_input(
|
| 513 |
+
# "Enter number of images per slide (up to 50)", 1, 50, 9, 1
|
| 514 |
+
# )
|
| 515 |
+
|
| 516 |
+
# treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)]
|
| 517 |
+
# day_list = [f"Day {i+1}" for i in range(num_days)]
|
| 518 |
+
|
| 519 |
+
# uploaded_files = {}
|
| 520 |
+
# st.markdown("### π Upload images for each Treatment and Day")
|
| 521 |
+
# for treatment in treatment_list:
|
| 522 |
+
# st.subheader(treatment)
|
| 523 |
+
# uploaded_files[treatment] = {}
|
| 524 |
+
# for day in day_list:
|
| 525 |
+
# uploaded_files[treatment][day] = st.file_uploader(
|
| 526 |
+
# f"Upload image(s) for {day}",
|
| 527 |
+
# type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"],
|
| 528 |
+
# accept_multiple_files=True,
|
| 529 |
+
# key=f"{treatment}_{day}",
|
| 530 |
+
# )
|
| 531 |
+
|
| 532 |
+
# SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"}
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
# # βββββββββββββββββββββββββββββ
|
| 536 |
+
# # Helpers
|
| 537 |
+
# # βββββββββββββββββββββββββββββ
|
| 538 |
+
# def normalize_image_for_ppt(path: str) -> str | None:
|
| 539 |
+
# """Convert unsupported formats to PNG + fix EXIF rotation."""
|
| 540 |
+
# try:
|
| 541 |
+
# with Image.open(path) as im:
|
| 542 |
+
# fmt = (im.format or "").upper()
|
| 543 |
+
# im = ImageOps.exif_transpose(im)
|
| 544 |
+
# if fmt not in SUPPORTED_BY_PPTX:
|
| 545 |
+
# im = im.convert("RGB")
|
| 546 |
+
# out_path = os.path.splitext(path)[0] + "_clean.png"
|
| 547 |
+
# im.save(out_path, "PNG")
|
| 548 |
+
# return out_path
|
| 549 |
+
# return path
|
| 550 |
+
# except Exception as e:
|
| 551 |
+
# st.error(f"β Could not normalize image '{path}': {e}")
|
| 552 |
+
# return None
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
# def crop_with_margin(image_path: str, mode: str) -> str:
|
| 556 |
+
# """Use YOLO model for cropping (no extra PPT-side padding)."""
|
| 557 |
+
# try:
|
| 558 |
+
# cropped = crop_with_yolo(image_path, mode)
|
| 559 |
+
# return cropped if cropped and os.path.exists(cropped) else image_path
|
| 560 |
+
# except Exception as e:
|
| 561 |
+
# st.error(f"β YOLO crop failed for {image_path}: {e}")
|
| 562 |
+
# return image_path
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
# def compute_grid(n: int) -> tuple[int, int]:
|
| 566 |
+
# """Decide columns/rows so n images fit nicely."""
|
| 567 |
+
# cols = math.ceil(math.sqrt(n))
|
| 568 |
+
# rows = math.ceil(n / cols)
|
| 569 |
+
# return cols, rows
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
# def add_centered_title(slide, title_text: str):
|
| 573 |
+
# """Add a perfectly centered title."""
|
| 574 |
+
# title_box = slide.shapes.add_textbox(Inches(0), Inches(0.2), Inches(13.33), Inches(0.8))
|
| 575 |
+
# tf = title_box.text_frame
|
| 576 |
+
# tf.word_wrap = True
|
| 577 |
+
# p = tf.paragraphs[0]
|
| 578 |
+
# p.text = title_text
|
| 579 |
+
# p.alignment = PP_ALIGN.CENTER
|
| 580 |
+
# p.font.bold = True
|
| 581 |
+
# p.font.size = Pt(24)
|
| 582 |
+
# p.font.color.rgb = RGBColor(0, 0, 0)
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
# def get_font_size(num_images: int) -> int:
|
| 586 |
+
# """Dynamic caption font size."""
|
| 587 |
+
# if num_images <= 6:
|
| 588 |
+
# return 12
|
| 589 |
+
# elif num_images <= 20:
|
| 590 |
+
# return 10
|
| 591 |
+
# elif num_images <= 35:
|
| 592 |
+
# return 8
|
| 593 |
+
# else:
|
| 594 |
+
# return 7
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
# # βββββββββββββββββββββββββββββ
|
| 598 |
+
# # PowerPoint Generation
|
| 599 |
+
# # βββββββββββββββββββββββββββββ
|
| 600 |
+
# if st.button("π Generate PowerPoint"):
|
| 601 |
+
# prs = Presentation()
|
| 602 |
+
# EMU_PER_INCH = 914400
|
| 603 |
+
# SLIDE_W_IN = prs.slide_width / EMU_PER_INCH
|
| 604 |
+
# SLIDE_H_IN = prs.slide_height / EMU_PER_INCH
|
| 605 |
+
|
| 606 |
+
# # Margins and layout constants
|
| 607 |
+
# LEFT_MARGIN_IN = 0.5
|
| 608 |
+
# RIGHT_MARGIN_IN = 0.5
|
| 609 |
+
# TOP_MARGIN_IN = 1.0
|
| 610 |
+
# BOTTOM_MARGIN_IN = 0.5
|
| 611 |
+
# usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN
|
| 612 |
+
# usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN
|
| 613 |
+
|
| 614 |
+
# base_font_size = get_font_size(max_imgs_per_slide)
|
| 615 |
+
|
| 616 |
+
# for day in day_list:
|
| 617 |
+
# st.write(f"πΌοΈ Adding images for {day}...")
|
| 618 |
+
|
| 619 |
+
# # Gather all uploaded files for this day
|
| 620 |
+
# day_files = []
|
| 621 |
+
# for treatment in treatment_list:
|
| 622 |
+
# files = uploaded_files[treatment][day]
|
| 623 |
+
# if files:
|
| 624 |
+
# for f in files:
|
| 625 |
+
# day_files.append((treatment, f))
|
| 626 |
+
|
| 627 |
+
# total_imgs = len(day_files)
|
| 628 |
+
# if total_imgs == 0:
|
| 629 |
+
# continue
|
| 630 |
+
|
| 631 |
+
# # Compute a single, consistent grid for all slides in this day
|
| 632 |
+
# cols, rows = compute_grid(max_imgs_per_slide)
|
| 633 |
+
# cell_w = usable_w_in / cols
|
| 634 |
+
# cell_h = usable_h_in / rows
|
| 635 |
+
# image_h_ratio = 0.75
|
| 636 |
+
# img_area_h = cell_h * image_h_ratio
|
| 637 |
+
# caption_h = cell_h * (1 - image_h_ratio)
|
| 638 |
+
|
| 639 |
+
# idx = 0
|
| 640 |
+
# slide_index_for_day = 0
|
| 641 |
+
|
| 642 |
+
# while idx < total_imgs:
|
| 643 |
+
# chunk = day_files[idx:idx + max_imgs_per_slide]
|
| 644 |
+
# n_chunk = len(chunk)
|
| 645 |
+
|
| 646 |
+
# slide = prs.slides.add_slide(prs.slide_layouts[6])
|
| 647 |
+
# title_suffix = "" if slide_index_for_day == 0 else f" (contd.)"
|
| 648 |
+
# add_centered_title(slide, f"{day} β Treatment Images{title_suffix}")
|
| 649 |
+
# slide_index_for_day += 1
|
| 650 |
+
|
| 651 |
+
# for local_i, (treatment, file) in enumerate(chunk):
|
| 652 |
+
# row = local_i // cols
|
| 653 |
+
# col = local_i % cols
|
| 654 |
+
# cell_left = LEFT_MARGIN_IN + col * cell_w
|
| 655 |
+
# cell_top = TOP_MARGIN_IN + row * cell_h
|
| 656 |
+
|
| 657 |
+
# suffix = os.path.splitext(file.name)[1]
|
| 658 |
+
# with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 659 |
+
# tmp.write(file.read())
|
| 660 |
+
# raw_path = tmp.name
|
| 661 |
+
|
| 662 |
+
# cropped_path = crop_with_margin(raw_path, mode)
|
| 663 |
+
# safe_path = normalize_image_for_ppt(cropped_path)
|
| 664 |
+
# if not safe_path:
|
| 665 |
+
# continue
|
| 666 |
+
|
| 667 |
+
# try:
|
| 668 |
+
# # Preserve aspect ratio
|
| 669 |
+
# with Image.open(safe_path) as im:
|
| 670 |
+
# w, h = im.size
|
| 671 |
+
# img_ratio = w / h
|
| 672 |
+
# box_ratio = cell_w / img_area_h
|
| 673 |
+
# if img_ratio > box_ratio:
|
| 674 |
+
# img_w = cell_w * 0.9
|
| 675 |
+
# img_h = img_w / img_ratio
|
| 676 |
+
# else:
|
| 677 |
+
# img_h = img_area_h * 0.9
|
| 678 |
+
# img_w = img_h * img_ratio
|
| 679 |
+
|
| 680 |
+
# img_left = cell_left + (cell_w - img_w) / 2
|
| 681 |
+
# img_top = cell_top + (img_area_h - img_h) / 2
|
| 682 |
+
|
| 683 |
+
# slide.shapes.add_picture(
|
| 684 |
+
# safe_path,
|
| 685 |
+
# left=Inches(img_left),
|
| 686 |
+
# top=Inches(img_top),
|
| 687 |
+
# width=Inches(img_w),
|
| 688 |
+
# height=Inches(img_h),
|
| 689 |
+
# )
|
| 690 |
+
|
| 691 |
+
# # Caption (separate zone)
|
| 692 |
+
# score = predict_infection_score(safe_path, mode)
|
| 693 |
+
# caption_text = f"{treatment} β {day} | Score: {score}"
|
| 694 |
+
# caption_top = cell_top + img_area_h + 0.03
|
| 695 |
+
|
| 696 |
+
# tx = slide.shapes.add_textbox(
|
| 697 |
+
# Inches(cell_left),
|
| 698 |
+
# Inches(caption_top),
|
| 699 |
+
# Inches(cell_w),
|
| 700 |
+
# Inches(caption_h),
|
| 701 |
+
# )
|
| 702 |
+
# tf = tx.text_frame
|
| 703 |
+
# tf.word_wrap = True
|
| 704 |
+
# p = tf.paragraphs[0]
|
| 705 |
+
# p.text = caption_text
|
| 706 |
+
# p.alignment = PP_ALIGN.CENTER
|
| 707 |
+
# p.font.size = Pt(base_font_size)
|
| 708 |
+
# p.font.bold = True
|
| 709 |
+
# p.font.color.rgb = RGBColor(0, 0, 0)
|
| 710 |
+
|
| 711 |
+
# except Exception as e:
|
| 712 |
+
# st.error(f"β Failed to add image '{safe_path}': {e}")
|
| 713 |
+
|
| 714 |
+
# idx += max_imgs_per_slide
|
| 715 |
+
|
| 716 |
+
# with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx:
|
| 717 |
+
# prs.save(tmp_pptx.name)
|
| 718 |
+
# st.success("β
PowerPoint generated successfully β consistent size & centered titles!")
|
| 719 |
+
# st.download_button(
|
| 720 |
+
# "β¬οΈ Download PowerPoint",
|
| 721 |
+
# data=open(tmp_pptx.name, "rb").read(),
|
| 722 |
+
# file_name="treatments_with_scores.pptx",
|
| 723 |
+
# )
|
| 724 |
+
|
| 725 |
+
# #was trying
|
| 726 |
+
# # #Works pretty good, no overlapping
|
| 727 |
+
# import os
|
| 728 |
+
# import tempfile
|
| 729 |
+
# import math
|
| 730 |
+
# import streamlit as st
|
| 731 |
+
# from pptx import Presentation
|
| 732 |
+
# from pptx.util import Inches, Pt
|
| 733 |
+
# from pptx.dml.color import RGBColor
|
| 734 |
+
# from pptx.enum.text import PP_ALIGN
|
| 735 |
+
# from PIL import Image, ImageOps
|
| 736 |
+
# from cropper import crop_with_yolo, predict_infection_score
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
# # βββββββββββββββββββββββββββββ
|
| 740 |
+
# # Streamlit UI
|
| 741 |
+
# # βββββββββββββββββββββββββββββ
|
| 742 |
+
# st.title("π Treatments β PowerPoint Generator with Infection Scores")
|
| 743 |
+
|
| 744 |
+
# main_option = st.selectbox("Select Main Option", ["O", "V"])
|
| 745 |
+
# mode = "eye" if main_option == "O" else "vagina"
|
| 746 |
+
# st.write(f"π§ YOLO mode: {mode}")
|
| 747 |
+
|
| 748 |
+
# num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1)
|
| 749 |
+
# num_days = st.number_input("Enter number of days", 1, 10, 3, 1)
|
| 750 |
+
# max_imgs_per_slide = st.number_input(
|
| 751 |
+
# "Enter number of images per slide (up to 50)", 1, 50, 6, 1
|
| 752 |
+
# )
|
| 753 |
+
|
| 754 |
+
# treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)]
|
| 755 |
+
# day_list = [f"Day {i+1}" for i in range(num_days)]
|
| 756 |
+
|
| 757 |
+
# uploaded_files = {}
|
| 758 |
+
# st.markdown("### π Upload images for each Treatment and Day")
|
| 759 |
+
# for treatment in treatment_list:
|
| 760 |
+
# st.subheader(treatment)
|
| 761 |
+
# uploaded_files[treatment] = {}
|
| 762 |
+
# for day in day_list:
|
| 763 |
+
# uploaded_files[treatment][day] = st.file_uploader(
|
| 764 |
+
# f"Upload image(s) for {day}",
|
| 765 |
+
# type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"],
|
| 766 |
+
# accept_multiple_files=True,
|
| 767 |
+
# key=f"{treatment}_{day}",
|
| 768 |
+
# )
|
| 769 |
+
|
| 770 |
+
# SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"}
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
# # βββββββββββββββββββββββββββββ
|
| 774 |
+
# # Helpers
|
| 775 |
+
# # βββββββββββββββββββββββββββββ
|
| 776 |
+
# def normalize_image_for_ppt(path: str) -> str | None:
|
| 777 |
+
# """Convert unsupported formats to PNG + fix EXIF rotation."""
|
| 778 |
+
# try:
|
| 779 |
+
# with Image.open(path) as im:
|
| 780 |
+
# fmt = (im.format or "").upper()
|
| 781 |
+
# im = ImageOps.exif_transpose(im)
|
| 782 |
+
# if fmt not in SUPPORTED_BY_PPTX:
|
| 783 |
+
# im = im.convert("RGB")
|
| 784 |
+
# out_path = os.path.splitext(path)[0] + "_clean.png"
|
| 785 |
+
# im.save(out_path, "PNG")
|
| 786 |
+
# return out_path
|
| 787 |
+
# return path
|
| 788 |
+
# except Exception as e:
|
| 789 |
+
# st.error(f"β Could not normalize image '{path}': {e}")
|
| 790 |
+
# return None
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
# def crop_with_margin(image_path: str, mode: str) -> str:
|
| 794 |
+
# """Use YOLO model for cropping (no extra PPT-side padding)."""
|
| 795 |
+
# try:
|
| 796 |
+
# cropped = crop_with_yolo(image_path, mode)
|
| 797 |
+
# return cropped if cropped and os.path.exists(cropped) else image_path
|
| 798 |
+
# except Exception as e:
|
| 799 |
+
# st.error(f"β YOLO crop failed for {image_path}: {e}")
|
| 800 |
+
# return image_path
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
# def compute_grid(n: int) -> tuple[int, int]:
|
| 804 |
+
# """Decide columns/rows so n images fit nicely."""
|
| 805 |
+
# cols = math.ceil(math.sqrt(n))
|
| 806 |
+
# rows = math.ceil(n / cols)
|
| 807 |
+
# return cols, rows
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
# def add_slide_title(slide, title_text: str):
|
| 811 |
+
# """Add a centered title at the top of the slide."""
|
| 812 |
+
# title_box = slide.shapes.add_textbox(Inches(0.3), Inches(0.1), Inches(12), Inches(0.6))
|
| 813 |
+
# tf = title_box.text_frame
|
| 814 |
+
# tf.word_wrap = True
|
| 815 |
+
# p = tf.paragraphs[0]
|
| 816 |
+
# p.text = title_text
|
| 817 |
+
# p.alignment = PP_ALIGN.CENTER
|
| 818 |
+
# p.font.bold = True
|
| 819 |
+
# p.font.size = Pt(20)
|
| 820 |
+
# p.font.color.rgb = RGBColor(0, 0, 0)
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
# def get_font_size(num_images: int) -> int:
|
| 824 |
+
# if num_images <= 6:
|
| 825 |
+
# return 12
|
| 826 |
+
# elif num_images <= 20:
|
| 827 |
+
# return 10
|
| 828 |
+
# elif num_images <= 35:
|
| 829 |
+
# return 8
|
| 830 |
+
# else:
|
| 831 |
+
# return 7
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
# # βββββββββββββββββββββββββββββ
|
| 835 |
+
# # PowerPoint Generation
|
| 836 |
+
# # βββββββββββββββββββββββββββββ
|
| 837 |
+
# if st.button("π Generate PowerPoint"):
|
| 838 |
+
# prs = Presentation()
|
| 839 |
+
# EMU_PER_INCH = 914400
|
| 840 |
+
# SLIDE_W_IN = prs.slide_width / EMU_PER_INCH
|
| 841 |
+
# SLIDE_H_IN = prs.slide_height / EMU_PER_INCH
|
| 842 |
+
|
| 843 |
+
# LEFT_MARGIN_IN = 0.5
|
| 844 |
+
# RIGHT_MARGIN_IN = 0.5
|
| 845 |
+
# TOP_MARGIN_IN = 1.0
|
| 846 |
+
# BOTTOM_MARGIN_IN = 0.5
|
| 847 |
+
# usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN
|
| 848 |
+
# usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN
|
| 849 |
+
|
| 850 |
+
# base_font_size = get_font_size(max_imgs_per_slide)
|
| 851 |
+
|
| 852 |
+
# for day in day_list:
|
| 853 |
+
# st.write(f"πΌοΈ Adding images for {day}...")
|
| 854 |
+
|
| 855 |
+
# # Collect all images of this day
|
| 856 |
+
# day_files = []
|
| 857 |
+
# for treatment in treatment_list:
|
| 858 |
+
# files = uploaded_files[treatment][day]
|
| 859 |
+
# if files:
|
| 860 |
+
# for f in files:
|
| 861 |
+
# day_files.append((treatment, f))
|
| 862 |
+
|
| 863 |
+
# total_imgs = len(day_files)
|
| 864 |
+
# if total_imgs == 0:
|
| 865 |
+
# continue
|
| 866 |
+
|
| 867 |
+
# idx = 0
|
| 868 |
+
# slide_index_for_day = 0
|
| 869 |
+
|
| 870 |
+
# while idx < total_imgs:
|
| 871 |
+
# chunk = day_files[idx:idx + max_imgs_per_slide]
|
| 872 |
+
# n_chunk = len(chunk)
|
| 873 |
+
|
| 874 |
+
# slide = prs.slides.add_slide(prs.slide_layouts[6])
|
| 875 |
+
# title_suffix = "" if slide_index_for_day == 0 else " (contd.)"
|
| 876 |
+
# add_slide_title(slide, f"{day} β Treatment Images{title_suffix}")
|
| 877 |
+
# slide_index_for_day += 1
|
| 878 |
+
|
| 879 |
+
# # Compute grid
|
| 880 |
+
# cols, rows = compute_grid(n_chunk)
|
| 881 |
+
# cell_w = usable_w_in / cols
|
| 882 |
+
# cell_h = usable_h_in / rows
|
| 883 |
+
|
| 884 |
+
# # Image and caption spacing constants
|
| 885 |
+
# image_h_ratio = 0.75 # 75% image, 25% caption zone per cell
|
| 886 |
+
# img_area_h = cell_h * image_h_ratio
|
| 887 |
+
# caption_h = cell_h * (1 - image_h_ratio)
|
| 888 |
+
|
| 889 |
+
# for local_i, (treatment, file) in enumerate(chunk):
|
| 890 |
+
# row = local_i // cols
|
| 891 |
+
# col = local_i % cols
|
| 892 |
+
# cell_left = LEFT_MARGIN_IN + col * cell_w
|
| 893 |
+
# cell_top = TOP_MARGIN_IN + row * cell_h
|
| 894 |
+
|
| 895 |
+
# suffix = os.path.splitext(file.name)[1]
|
| 896 |
+
# with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 897 |
+
# tmp.write(file.read())
|
| 898 |
+
# raw_path = tmp.name
|
| 899 |
+
|
| 900 |
+
# cropped_path = crop_with_margin(raw_path, mode)
|
| 901 |
+
# safe_path = normalize_image_for_ppt(cropped_path)
|
| 902 |
+
# if not safe_path:
|
| 903 |
+
# continue
|
| 904 |
+
|
| 905 |
+
# try:
|
| 906 |
+
# # Preserve image ratio β scale to fit inside its image zone
|
| 907 |
+
# with Image.open(safe_path) as im:
|
| 908 |
+
# w, h = im.size
|
| 909 |
+
# img_ratio = w / h
|
| 910 |
+
# box_ratio = cell_w / img_area_h
|
| 911 |
+
# if img_ratio > box_ratio:
|
| 912 |
+
# img_w = cell_w * 0.9
|
| 913 |
+
# img_h = img_w / img_ratio
|
| 914 |
+
# else:
|
| 915 |
+
# img_h = img_area_h * 0.9
|
| 916 |
+
# img_w = img_h * img_ratio
|
| 917 |
+
|
| 918 |
+
# img_left = cell_left + (cell_w - img_w) / 2
|
| 919 |
+
# img_top = cell_top + (img_area_h - img_h) / 2
|
| 920 |
+
|
| 921 |
+
# slide.shapes.add_picture(
|
| 922 |
+
# safe_path,
|
| 923 |
+
# left=Inches(img_left),
|
| 924 |
+
# top=Inches(img_top),
|
| 925 |
+
# width=Inches(img_w),
|
| 926 |
+
# height=Inches(img_h),
|
| 927 |
+
# )
|
| 928 |
+
|
| 929 |
+
# # Caption β completely separate vertical zone
|
| 930 |
+
# score = predict_infection_score(safe_path, mode)
|
| 931 |
+
# caption_text = f"{treatment} β {day} | Score: {score}"
|
| 932 |
+
# caption_top = cell_top + img_area_h + 0.02
|
| 933 |
+
|
| 934 |
+
# tx = slide.shapes.add_textbox(
|
| 935 |
+
# Inches(cell_left),
|
| 936 |
+
# Inches(caption_top),
|
| 937 |
+
# Inches(cell_w),
|
| 938 |
+
# Inches(caption_h),
|
| 939 |
+
# )
|
| 940 |
+
# tf = tx.text_frame
|
| 941 |
+
# tf.word_wrap = True
|
| 942 |
+
# p = tf.paragraphs[0]
|
| 943 |
+
# p.text = caption_text
|
| 944 |
+
# p.alignment = PP_ALIGN.CENTER
|
| 945 |
+
# p.font.size = Pt(base_font_size)
|
| 946 |
+
# p.font.bold = True
|
| 947 |
+
# p.font.color.rgb = RGBColor(0, 0, 0)
|
| 948 |
+
|
| 949 |
+
# except Exception as e:
|
| 950 |
+
# st.error(f"β Failed to add image '{safe_path}': {e}")
|
| 951 |
+
|
| 952 |
+
# idx += max_imgs_per_slide
|
| 953 |
+
|
| 954 |
+
# with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx:
|
| 955 |
+
# prs.save(tmp_pptx.name)
|
| 956 |
+
# st.success("β
PowerPoint generated successfully β no overlaps, consistent spacing!")
|
| 957 |
+
# st.download_button(
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from ultralytics import YOLO
|
| 3 |
+
import cv2
|
| 4 |
+
import os
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from torchvision import models, transforms
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from pptx import Presentation
|
| 10 |
+
from pptx.util import Inches, Emu, Pt
|
| 11 |
+
|
| 12 |
+
# βββββββββββββββββββββββββββββ
|
| 13 |
+
# 1οΈβ£ YOLO Model Loader
|
| 14 |
+
# βββββββββββββββββββββββββββββ
|
| 15 |
+
def load_model(mode="eye"):
|
| 16 |
+
base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 17 |
+
if mode == "eye":
|
| 18 |
+
model_path = os.path.join(base_dir, "models/besteyegwinf.pt")
|
| 19 |
+
elif mode == "vagina":
|
| 20 |
+
model_path = os.path.join(base_dir, "models/bestvag3.pt")
|
| 21 |
+
else:
|
| 22 |
+
raise ValueError("Invalid mode! Use 'eye' or 'vagina'.")
|
| 23 |
+
if not os.path.exists(model_path):
|
| 24 |
+
raise FileNotFoundError(f"Model not found: {model_path}")
|
| 25 |
+
return YOLO(model_path)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# βββββββββββββββββββββββββββββ
|
| 29 |
+
# 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion)
|
| 30 |
+
# βββββββββββββββββββββββββββββ
|
| 31 |
+
def pad_to_fixed_rectangle(image, target_w=1000, target_h=700):
|
| 32 |
+
"""Fits cropped image into fixed rectangle without stretching."""
|
| 33 |
+
h, w = image.shape[:2]
|
| 34 |
+
scale = min(target_w / w, target_h / h)
|
| 35 |
+
new_w, new_h = int(w * scale), int(h * scale)
|
| 36 |
+
resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 37 |
+
canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
|
| 38 |
+
x_offset = (target_w - new_w) // 2
|
| 39 |
+
y_offset = (target_h - new_h) // 2
|
| 40 |
+
canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized
|
| 41 |
+
return canvas
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# βββββββββββββββββββββββββββββ
|
| 45 |
+
# 3οΈβ£ Crop Image with YOLO
|
| 46 |
+
# βββββββββββββββββββββββββββββ
|
| 47 |
+
def crop_with_yolo(img_path, mode="eye"):
|
| 48 |
+
try:
|
| 49 |
+
yolo_model = load_model(mode)
|
| 50 |
+
conf_value = 0.55 if mode == "eye" else 0.05
|
| 51 |
+
results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False)
|
| 52 |
+
|
| 53 |
+
img = cv2.imread(img_path)
|
| 54 |
+
if img is None:
|
| 55 |
+
print(f"[ERROR] Could not read {img_path}")
|
| 56 |
+
return img_path
|
| 57 |
+
|
| 58 |
+
if not results or not len(results[0].boxes):
|
| 59 |
+
print(f"[WARN] No detection for {img_path} ({mode})")
|
| 60 |
+
padded = pad_to_fixed_rectangle(img)
|
| 61 |
+
out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 62 |
+
cv2.imwrite(out_path, padded)
|
| 63 |
+
return out_path
|
| 64 |
+
|
| 65 |
+
boxes = results[0].boxes
|
| 66 |
+
best = boxes[boxes.conf.argmax()]
|
| 67 |
+
x1, y1, x2, y2 = map(int, best.xyxy[0])
|
| 68 |
+
h, w = img.shape[:2]
|
| 69 |
+
x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)
|
| 70 |
+
|
| 71 |
+
crop = img[y1:y2, x1:x2].copy()
|
| 72 |
+
padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700)
|
| 73 |
+
out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 74 |
+
cv2.imwrite(out_path, padded)
|
| 75 |
+
print(f"[INFO] Saved {out_path}")
|
| 76 |
+
return out_path
|
| 77 |
+
|
| 78 |
+
except Exception as e:
|
| 79 |
+
print(f"[ERROR] YOLO cropping failed: {e}")
|
| 80 |
+
return img_path
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# βββββββββββββββββββββββββββββ
|
| 84 |
+
# 4οΈβ£ Infection Score Classifier (EfficientNet for eye & vagina)
|
| 85 |
+
# βββββββββββββββββββββββββββββ
|
| 86 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 87 |
+
_loaded_classifiers = {}
|
| 88 |
+
cls_tfms = transforms.Compose([
|
| 89 |
+
transforms.Resize((224, 224)),
|
| 90 |
+
transforms.ToTensor(),
|
| 91 |
+
transforms.Normalize([0.485, 0.456, 0.406],
|
| 92 |
+
[0.229, 0.224, 0.225]),
|
| 93 |
+
])
|
| 94 |
+
|
| 95 |
+
def load_classifier(mode="eye"):
|
| 96 |
+
"""Loads the correct classifier (eye/vagina) only once."""
|
| 97 |
+
global _loaded_classifiers
|
| 98 |
+
if mode in _loaded_classifiers:
|
| 99 |
+
return _loaded_classifiers[mode]
|
| 100 |
+
|
| 101 |
+
base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 102 |
+
model_file = (
|
| 103 |
+
os.path.join(base_dir, "models/grey_and_white_eye_infection_classifier.pth")
|
| 104 |
+
if mode == "eye"
|
| 105 |
+
else os.path.join(base_dir, "models/vagina_infection_classifier.pth")
|
| 106 |
+
)
|
| 107 |
+
if not os.path.exists(model_file):
|
| 108 |
+
raise FileNotFoundError(f"Classifier model not found: {model_file}")
|
| 109 |
+
|
| 110 |
+
model = models.efficientnet_b0(weights=None)
|
| 111 |
+
model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5)
|
| 112 |
+
model.load_state_dict(torch.load(model_file, map_location=device))
|
| 113 |
+
model.eval().to(device)
|
| 114 |
+
_loaded_classifiers[mode] = model
|
| 115 |
+
print(f"[INFO] Loaded classifier for {mode}")
|
| 116 |
+
return model
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def predict_infection_score(image_path: str, mode="eye") -> int:
|
| 120 |
+
"""Predicts infection score (1β5) for both eyes and vaginas."""
|
| 121 |
+
try:
|
| 122 |
+
model = load_classifier(mode)
|
| 123 |
+
img = Image.open(image_path).convert("RGB")
|
| 124 |
+
x = cls_tfms(img).unsqueeze(0).to(device)
|
| 125 |
+
with torch.no_grad():
|
| 126 |
+
logits = model(x)
|
| 127 |
+
pred = logits.argmax(1).item() + 1
|
| 128 |
+
return pred
|
| 129 |
+
except Exception as e:
|
| 130 |
+
print(f"[ERROR] Score prediction failed: {e}")
|
| 131 |
+
return None
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# #PRESENTED IN LAB MEETING
|
| 136 |
+
# from ultralytics import YOLO
|
| 137 |
+
# import cv2
|
| 138 |
+
# import os
|
| 139 |
+
# import numpy as np
|
| 140 |
+
# from pptx import Presentation
|
| 141 |
+
# from pptx.util import Inches, Emu, Pt
|
| 142 |
+
|
| 143 |
+
# # βββββββββββββββββββββββββββββ
|
| 144 |
+
# # 1οΈβ£ YOLO Model Loader
|
| 145 |
+
# # βββββββββββββββββββββββββββββ
|
| 146 |
+
# def load_model(mode="eye"):
|
| 147 |
+
# base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 148 |
+
# if mode == "eye":
|
| 149 |
+
# model_path = os.path.join(base_dir, "besteyegwinf.pt")
|
| 150 |
+
# elif mode == "vagina":
|
| 151 |
+
# model_path = os.path.join(base_dir, "bestvag3.pt")
|
| 152 |
+
# else:
|
| 153 |
+
# raise ValueError("Invalid mode! Use 'eye' or 'vagina'.")
|
| 154 |
+
|
| 155 |
+
# if not os.path.exists(model_path):
|
| 156 |
+
# raise FileNotFoundError(f"Model not found: {model_path}")
|
| 157 |
+
|
| 158 |
+
# return YOLO(model_path)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# # βββββββββββββββββββββββββββββ
|
| 162 |
+
# # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion)
|
| 163 |
+
# # βββββββββββββββββββββββββββββ
|
| 164 |
+
# def pad_to_fixed_rectangle(image, target_w=1000, target_h=700):
|
| 165 |
+
# """Fits the cropped image into a fixed rectangular box (1000Γ700)
|
| 166 |
+
# without stretching or distorting it.
|
| 167 |
+
# Keeps original aspect ratio and adds white padding if needed."""
|
| 168 |
+
# h, w = image.shape[:2]
|
| 169 |
+
# scale = min(target_w / w, target_h / h)
|
| 170 |
+
# new_w, new_h = int(w * scale), int(h * scale)
|
| 171 |
+
|
| 172 |
+
# resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 173 |
+
# canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
|
| 174 |
+
# x_offset = (target_w - new_w) // 2
|
| 175 |
+
# y_offset = (target_h - new_h) // 2
|
| 176 |
+
# canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized
|
| 177 |
+
# return canvas
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# # βββββββββββββββββββββββββββββ
|
| 181 |
+
# # 3οΈβ£ Crop Image with YOLO
|
| 182 |
+
# # βββββββββββββββββββββββββββββ
|
| 183 |
+
# def crop_with_yolo(img_path, mode="eye"):
|
| 184 |
+
# try:
|
| 185 |
+
# yolo_model = load_model(mode)
|
| 186 |
+
# conf_value = 0.55 if mode == "eye" else 0.1
|
| 187 |
+
# results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False)
|
| 188 |
+
|
| 189 |
+
# img = cv2.imread(img_path)
|
| 190 |
+
# if img is None:
|
| 191 |
+
# print(f"[ERROR] Could not read {img_path}")
|
| 192 |
+
# return img_path
|
| 193 |
+
|
| 194 |
+
# if not results or not len(results[0].boxes):
|
| 195 |
+
# print(f"[WARN] No detection for {img_path} ({mode})")
|
| 196 |
+
# padded = pad_to_fixed_rectangle(img)
|
| 197 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 198 |
+
# cv2.imwrite(out_path, padded)
|
| 199 |
+
# return out_path
|
| 200 |
+
|
| 201 |
+
# boxes = results[0].boxes
|
| 202 |
+
# best = boxes[boxes.conf.argmax()]
|
| 203 |
+
# x1, y1, x2, y2 = map(int, best.xyxy[0])
|
| 204 |
+
# h, w = img.shape[:2]
|
| 205 |
+
# x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)
|
| 206 |
+
|
| 207 |
+
# crop = img[y1:y2, x1:x2].copy()
|
| 208 |
+
# padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700)
|
| 209 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 210 |
+
# cv2.imwrite(out_path, padded)
|
| 211 |
+
# print(f"[INFO] Saved {out_path}")
|
| 212 |
+
# return out_path
|
| 213 |
+
|
| 214 |
+
# except Exception as e:
|
| 215 |
+
# print(f"[ERROR] YOLO cropping failed: {e}")
|
| 216 |
+
# return img_path
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# # βββββββββββββββββββββββββββββ
|
| 220 |
+
# # 4οΈβ£ Generate PowerPoint (no distortion)
|
| 221 |
+
# # βββββββββββββββββββββββββββββ
|
| 222 |
+
# def generate_ppt(image_paths, output_ppt="output.pptx"):
|
| 223 |
+
# prs = Presentation()
|
| 224 |
+
# cols, rows = 3, 2
|
| 225 |
+
# margin_left, margin_top = Inches(0.5), Inches(0.5)
|
| 226 |
+
# cell_w, cell_h = Inches(3.0), Inches(2.25)
|
| 227 |
+
|
| 228 |
+
# slide = None
|
| 229 |
+
# for i, img_path in enumerate([p for p in image_paths if p and os.path.exists(p)]):
|
| 230 |
+
# if i % (cols * rows) == 0:
|
| 231 |
+
# slide = prs.slides.add_slide(prs.slide_layouts[6])
|
| 232 |
+
|
| 233 |
+
# idx = i % (cols * rows)
|
| 234 |
+
# r, c = divmod(idx, cols)
|
| 235 |
+
# cell_left = margin_left + c * cell_w
|
| 236 |
+
# cell_top = margin_top + r * cell_h
|
| 237 |
+
|
| 238 |
+
# try:
|
| 239 |
+
# slide.shapes.add_picture(img_path, cell_left, cell_top, width=cell_w, height=cell_h)
|
| 240 |
+
# except Exception as e:
|
| 241 |
+
# print(f"[WARN] Skipping {img_path}: {e}")
|
| 242 |
+
|
| 243 |
+
# prs.save(output_ppt)
|
| 244 |
+
# print(f"[β
] PowerPoint saved as {output_ppt}")
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
# # βββββββββββββββββββββββββββββ
|
| 248 |
+
# # 5οΈβ£ Infection Score Classifier (EfficientNet)
|
| 249 |
+
# # βββββββββββββββββββββββββββββ
|
| 250 |
+
# import torch
|
| 251 |
+
# from torchvision import models, transforms
|
| 252 |
+
# from PIL import Image
|
| 253 |
+
|
| 254 |
+
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 255 |
+
# _classifier_model = None
|
| 256 |
+
|
| 257 |
+
# def load_classifier():
|
| 258 |
+
# """Loads the trained EfficientNet classifier model once."""
|
| 259 |
+
# global _classifier_model
|
| 260 |
+
# if _classifier_model is None:
|
| 261 |
+
# model = models.efficientnet_b0(pretrained=False)
|
| 262 |
+
# model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5)
|
| 263 |
+
# model.load_state_dict(torch.load("eye_infection_classifier.pth", map_location=device))
|
| 264 |
+
# model.eval().to(device)
|
| 265 |
+
# _classifier_model = model
|
| 266 |
+
# return _classifier_model
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
# cls_tfms = transforms.Compose([
|
| 270 |
+
# transforms.Resize((224, 224)),
|
| 271 |
+
# transforms.ToTensor(),
|
| 272 |
+
# transforms.Normalize([0.485, 0.456, 0.406],
|
| 273 |
+
# [0.229, 0.224, 0.225]),
|
| 274 |
+
# ])
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
# def predict_infection_score(image_path: str) -> int:
|
| 278 |
+
# """Predicts infection score (1β5) for eye images only."""
|
| 279 |
+
# model = load_classifier()
|
| 280 |
+
# img = Image.open(image_path).convert("RGB")
|
| 281 |
+
# x = cls_tfms(img).unsqueeze(0).to(device)
|
| 282 |
+
# with torch.no_grad():
|
| 283 |
+
# logits = model(x)
|
| 284 |
+
# pred = logits.argmax(1).item() + 1
|
| 285 |
+
# return pred
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# #GOOD WORKING FOR EYE INFECTION SCORES, ALSO DISPLAYS VAGINA SCORES WHICH ARE CURRENTLY NOT REQUIRED
|
| 289 |
+
# from ultralytics import YOLO
|
| 290 |
+
# import cv2
|
| 291 |
+
# import os
|
| 292 |
+
# import numpy as np
|
| 293 |
+
# from pptx import Presentation
|
| 294 |
+
# from pptx.util import Inches, Emu, Pt
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
# # βββββββββββββββββββββββββββββ
|
| 298 |
+
# # 1οΈβ£ YOLO Model Loader
|
| 299 |
+
# # βββββββββββββββββββββββββββββ
|
| 300 |
+
# def load_model(mode="eye"):
|
| 301 |
+
# base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 302 |
+
# if mode == "eye":
|
| 303 |
+
# model_path = os.path.join(base_dir, "besteyegwinf.pt")
|
| 304 |
+
# elif mode == "vagina":
|
| 305 |
+
# model_path = os.path.join(base_dir, "bestvag3.pt")
|
| 306 |
+
# else:
|
| 307 |
+
# raise ValueError("Invalid mode! Use 'eye' or 'vagina'.")
|
| 308 |
+
|
| 309 |
+
# if not os.path.exists(model_path):
|
| 310 |
+
# raise FileNotFoundError(f"Model not found: {model_path}")
|
| 311 |
+
|
| 312 |
+
# return YOLO(model_path)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
# # βββββββββββββββββββββββββββββ
|
| 316 |
+
# # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion)
|
| 317 |
+
# # βββββββββββββββββββββββββββββ
|
| 318 |
+
# def pad_to_fixed_rectangle(image, target_w=1000, target_h=700):
|
| 319 |
+
# """
|
| 320 |
+
# Fits the cropped image into a fixed rectangular box (1000Γ700)
|
| 321 |
+
# without stretching or distorting it.
|
| 322 |
+
# Keeps original aspect ratio and adds white padding if needed.
|
| 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 |
+
# pic = slide.shapes.add_picture(img_path, cell_left, cell_top,
|
| 396 |
+
# width=cell_w, height=cell_h)
|
| 397 |
+
# cw, ch = cell_w._value, cell_h._value
|
| 398 |
+
# new_left = Emu(cell_left._value + (cw - pic.width) // 2)
|
| 399 |
+
# new_top = Emu(cell_top._value + (ch - pic.height) // 2)
|
| 400 |
+
# pic.left, pic.top = new_left, new_top
|
| 401 |
+
# except Exception as e:
|
| 402 |
+
# print(f"[WARN] Skipping {img_path}: {e}")
|
| 403 |
+
|
| 404 |
+
# prs.save(output_ppt)
|
| 405 |
+
# print(f"[β
] PowerPoint saved as {output_ppt}")
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
# # βββββββββββββββββββββββββββββ
|
| 409 |
+
# # 5οΈβ£ Infection Score Classifier (EfficientNet)
|
| 410 |
+
# # βββββββββββββββββββββββββββββ
|
| 411 |
+
# import torch
|
| 412 |
+
# from torchvision import models, transforms
|
| 413 |
+
# from PIL import Image
|
| 414 |
+
|
| 415 |
+
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 416 |
+
# _classifier_model = None
|
| 417 |
+
|
| 418 |
+
# def load_classifier():
|
| 419 |
+
# """Loads the trained EfficientNet classifier model once."""
|
| 420 |
+
# global _classifier_model
|
| 421 |
+
# if _classifier_model is None:
|
| 422 |
+
# model = models.efficientnet_b0(pretrained=False)
|
| 423 |
+
# model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5)
|
| 424 |
+
# model.load_state_dict(torch.load("eye_infection_classifier.pth", map_location=device))
|
| 425 |
+
# model.eval().to(device)
|
| 426 |
+
# _classifier_model = model
|
| 427 |
+
# return _classifier_model
|
| 428 |
+
|
| 429 |
+
# cls_tfms = transforms.Compose([
|
| 430 |
+
# transforms.Resize((224, 224)),
|
| 431 |
+
# transforms.ToTensor(),
|
| 432 |
+
# transforms.Normalize([0.485, 0.456, 0.406],
|
| 433 |
+
# [0.229, 0.224, 0.225]),
|
| 434 |
+
# ])
|
| 435 |
+
|
| 436 |
+
# def predict_infection_score(image_path: str) -> int:
|
| 437 |
+
# """Predicts infection score (1β5) for the given eye image."""
|
| 438 |
+
# model = load_classifier()
|
| 439 |
+
# img = Image.open(image_path).convert("RGB")
|
| 440 |
+
# x = cls_tfms(img).unsqueeze(0).to(device)
|
| 441 |
+
# with torch.no_grad():
|
| 442 |
+
# logits = model(x)
|
| 443 |
+
# pred = logits.argmax(1).item() + 1
|
| 444 |
+
# return pred
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
# #FINAL WORKING HEALTHY INFECTED CROPPING CODE
|
| 455 |
+
# from ultralytics import YOLO
|
| 456 |
+
# import cv2
|
| 457 |
+
# import os
|
| 458 |
+
# import numpy as np
|
| 459 |
+
# from pptx import Presentation
|
| 460 |
+
# from pptx.util import Inches, Emu, Pt
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
# # βββββββββββββββββββββββββββββ
|
| 464 |
+
# # 1οΈβ£ YOLO Model Loader
|
| 465 |
+
# # βββββββββββββββββββββββββββββ
|
| 466 |
+
# def load_model(mode="eye"):
|
| 467 |
+
# base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 468 |
+
# if mode == "eye":
|
| 469 |
+
# model_path = os.path.join(base_dir, "besteyegwinf.pt")
|
| 470 |
+
# elif mode == "vagina":
|
| 471 |
+
# model_path = os.path.join(base_dir, "bestvag3.pt")
|
| 472 |
+
# else:
|
| 473 |
+
# raise ValueError("Invalid mode! Use 'eye' or 'vagina'.")
|
| 474 |
+
|
| 475 |
+
# if not os.path.exists(model_path):
|
| 476 |
+
# raise FileNotFoundError(f"Model not found: {model_path}")
|
| 477 |
+
|
| 478 |
+
# return YOLO(model_path)
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
# # βββββββββββββββββββββββββββββ
|
| 482 |
+
# # 2οΈβ£ Pad All Crops to Same Rectangular Size (no distortion)
|
| 483 |
+
# # βββββββββββββββββββββββββββββ
|
| 484 |
+
# def pad_to_fixed_rectangle(image, target_w=1000, target_h=700):
|
| 485 |
+
# """
|
| 486 |
+
# Fits the cropped image into a fixed rectangular box (1000Γ700)
|
| 487 |
+
# without stretching or distorting it.
|
| 488 |
+
# Keeps original aspect ratio and adds white padding if needed.
|
| 489 |
+
# """
|
| 490 |
+
# h, w = image.shape[:2]
|
| 491 |
+
# scale = min(target_w / w, target_h / h)
|
| 492 |
+
# new_w, new_h = int(w * scale), int(h * scale)
|
| 493 |
+
|
| 494 |
+
# resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 495 |
+
|
| 496 |
+
# # Create white canvas and center the resized image
|
| 497 |
+
# canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
|
| 498 |
+
# x_offset = (target_w - new_w) // 2
|
| 499 |
+
# y_offset = (target_h - new_h) // 2
|
| 500 |
+
# canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized
|
| 501 |
+
|
| 502 |
+
# return canvas
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
# # βββββββββββββββββββββββββββββ
|
| 506 |
+
# # 3οΈβ£ Crop Image with YOLO
|
| 507 |
+
# # βββββββββββββββββββββββββββββ
|
| 508 |
+
# def crop_with_yolo(img_path, mode="eye"):
|
| 509 |
+
# try:
|
| 510 |
+
# yolo_model = load_model(mode)
|
| 511 |
+
# conf_value = 0.55 if mode == "eye" else 0.1
|
| 512 |
+
# results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False)
|
| 513 |
+
|
| 514 |
+
# img = cv2.imread(img_path)
|
| 515 |
+
# if img is None:
|
| 516 |
+
# print(f"[ERROR] Could not read {img_path}")
|
| 517 |
+
# return img_path
|
| 518 |
+
|
| 519 |
+
# # No detections β use original image padded
|
| 520 |
+
# if not results or not len(results[0].boxes):
|
| 521 |
+
# print(f"[WARN] No detection for {img_path} ({mode})")
|
| 522 |
+
# padded = pad_to_fixed_rectangle(img)
|
| 523 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 524 |
+
# cv2.imwrite(out_path, padded)
|
| 525 |
+
# return out_path
|
| 526 |
+
|
| 527 |
+
# # Use highest-confidence detection
|
| 528 |
+
# boxes = results[0].boxes
|
| 529 |
+
# best = boxes[boxes.conf.argmax()]
|
| 530 |
+
# x1, y1, x2, y2 = map(int, best.xyxy[0])
|
| 531 |
+
# h, w = img.shape[:2]
|
| 532 |
+
# x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)
|
| 533 |
+
|
| 534 |
+
# crop = img[y1:y2, x1:x2].copy()
|
| 535 |
+
|
| 536 |
+
# # β
Make all crops same rectangular size (no distortion)
|
| 537 |
+
# padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700)
|
| 538 |
+
|
| 539 |
+
# out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
|
| 540 |
+
# cv2.imwrite(out_path, padded)
|
| 541 |
+
# print(f"[INFO] Saved {out_path}")
|
| 542 |
+
# return out_path
|
| 543 |
+
|
| 544 |
+
# except Exception as e:
|
| 545 |
+
# print(f"[ERROR] YOLO cropping failed: {e}")
|
| 546 |
+
# return img_path
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
# # βββββββββββββββββββββββββββββ
|
| 550 |
+
# # 4οΈβ£ Generate PowerPoint (no distortion)
|
| 551 |
+
# # βββββββββββββββββββββββββββββ
|
| 552 |
+
# def generate_ppt(image_paths, output_ppt="output.pptx"):
|
| 553 |
+
# """
|
| 554 |
+
# Adds up to 6 images per slide (3Γ2 grid).
|
| 555 |
+
# Each image has uniform rectangular size (no stretching).
|
| 556 |
+
# """
|
| 557 |
+
# prs = Presentation()
|
| 558 |
+
# cols, rows = 3, 2
|
| 559 |
+
# margin_left, margin_top = Inches(0.5), Inches(0.5)
|
| 560 |
+
# cell_w, cell_h = Inches(3.0), Inches(2.25) # rectangular frame
|
| 561 |
+
|
| 562 |
+
# slide = None
|
| 563 |
+
# for i, img_path in enumerate([p for p in image_paths if p and os.path.exists(p)]):
|
| 564 |
+
# if i % (cols * rows) == 0:
|
| 565 |
+
# slide = prs.slides.add_slide(prs.slide_layouts[6])
|
| 566 |
+
|
| 567 |
+
# idx = i % (cols * rows)
|
| 568 |
+
# r, c = divmod(idx, cols)
|
| 569 |
+
# cell_left = margin_left + c * cell_w
|
| 570 |
+
# cell_top = margin_top + r * cell_h
|
| 571 |
+
|
| 572 |
+
# try:
|
| 573 |
+
# pic = slide.shapes.add_picture(img_path, cell_left, cell_top,
|
| 574 |
+
# width=cell_w, height=cell_h)
|
| 575 |
+
# cw, ch = cell_w._value, cell_h._value
|
| 576 |
+
# new_left = Emu(cell_left._value + (cw - pic.width) // 2)
|
| 577 |
+
# new_top = Emu(cell_top._value + (ch - pic.height) // 2)
|
| 578 |
+
# pic.left, pic.top = new_left, new_top
|
| 579 |
+
|
| 580 |
+
# try:
|
| 581 |
+
# pic.line.fill.background()
|
| 582 |
+
# pic.shadow.inherit = False
|
| 583 |
+
# except Exception:
|
| 584 |
+
# pass
|
| 585 |
+
|
| 586 |
+
# except Exception as e:
|
| 587 |
+
# print(f"[WARN] Skipping {img_path}: {e}")
|
| 588 |
+
|
| 589 |
+
# prs.save(output_ppt)
|
| 590 |
+
# print(f"[β
] PowerPoint saved as {output_ppt}")
|