Pradnya99 commited on
Commit
7b1ece5
Β·
verified Β·
1 Parent(s): 0923971

Added Caching, keep image size same

Browse files
Files changed (1) hide show
  1. app.py +1212 -962
app.py CHANGED
@@ -1,962 +1,1212 @@
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(
958
- # "⬇️ Download PowerPoint",
959
- # data=open(tmp_pptx.name, "rb").read(),
960
- # file_name="treatments_with_scores.pptx",
961
- # )
962
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 functools import lru_cache
11
+
12
+ from cropper import crop_with_yolo, predict_infection_score
13
+
14
+
15
+ # ─────────────────────────────
16
+ # Streamlit UI
17
+ # ─────────────────────────────
18
+ st.set_page_config(layout="wide")
19
+ st.title("πŸ’Š Treatments β†’ PowerPoint Generator with Infection Scores")
20
+
21
+ main_option = st.selectbox("Select Main Option", ["O", "V"])
22
+ mode = "eye" if main_option == "O" else "vagina"
23
+ st.write(f"🧠 YOLO mode: {mode}")
24
+
25
+ num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1)
26
+ num_days = st.number_input("Enter number of days", 1, 10, 3, 1)
27
+ max_imgs_per_slide = st.number_input(
28
+ "Enter number of images per slide", 1, 50, 9, 1
29
+ )
30
+
31
+ treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)]
32
+ day_list = [f"Day {i+1}" for i in range(num_days)]
33
+
34
+ uploaded_files = {}
35
+ st.markdown("### πŸ“ Upload images for each Treatment and Day")
36
+
37
+ for treatment in treatment_list:
38
+ st.subheader(treatment)
39
+ uploaded_files[treatment] = {}
40
+ for day in day_list:
41
+ uploaded_files[treatment][day] = st.file_uploader(
42
+ f"Upload image(s) for {day}",
43
+ type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"],
44
+ accept_multiple_files=True,
45
+ key=f"{treatment}_{day}",
46
+ )
47
+
48
+ SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"}
49
+
50
+
51
+
52
+ # ─────────────────────────────
53
+ # HELPERS β€” Quality preserved
54
+ # ─────────────────────────────
55
+
56
+ def normalize_image_for_ppt(path: str) -> str | None:
57
+ """
58
+ KEEP ORIGINAL RESOLUTION.
59
+ KEEP ORIGINAL FORMAT IF PPT-SUPPORTED.
60
+ ONLY fix EXIF rotation.
61
+ NEVER convert PNG/JPG, no re-encoding.
62
+ """
63
+ try:
64
+ with Image.open(path) as im:
65
+ fmt = (im.format or "").upper()
66
+ im = ImageOps.exif_transpose(im)
67
+
68
+ # if format not supported, convert ONCE to PNG (lossless)
69
+ if fmt not in SUPPORTED_BY_PPTX:
70
+ out_path = os.path.splitext(path)[0] + "_fixed.png"
71
+ im.save(out_path, "PNG")
72
+ return out_path
73
+
74
+ return path
75
+
76
+ except Exception as e:
77
+ st.error(f"❌ Could not normalize image '{path}': {e}")
78
+ return None
79
+
80
+
81
+
82
+ def compute_grid(n: int) -> tuple[int, int]:
83
+ """Decide columns/rows so n images fit nicely."""
84
+ cols = math.ceil(math.sqrt(n))
85
+ rows = math.ceil(n / cols)
86
+ return cols, rows
87
+
88
+
89
+ def add_centered_title(slide, title_text: str, slide_width_in: float):
90
+ title_box = slide.shapes.add_textbox(
91
+ Inches(0),
92
+ Inches(0.2),
93
+ Inches(slide_width_in),
94
+ Inches(0.8),
95
+ )
96
+ tf = title_box.text_frame
97
+ p = tf.paragraphs[0]
98
+ p.text = title_text
99
+ p.alignment = PP_ALIGN.CENTER
100
+ p.font.bold = True
101
+ p.font.size = Pt(24)
102
+ p.font.color.rgb = RGBColor(0, 0, 0)
103
+
104
+
105
+ def get_font_size(num_images: int) -> int:
106
+ if num_images <= 6:
107
+ return 12
108
+ elif num_images <= 20:
109
+ return 10
110
+ elif num_images <= 35:
111
+ return 8
112
+ else:
113
+ return 7
114
+
115
+
116
+
117
+ # ─────────────────────────────
118
+ # Fixed DISPLAY size for all images in PPT
119
+ # (Original image resolution is not changed)
120
+ # ─────────────────────────────
121
+
122
+ def get_fixed_display_size(cell_w, img_area_h):
123
+ """
124
+ All images appear SAME SIZE inside PPT.
125
+ Resolution preserved, only display size controlled.
126
+ """
127
+ img_w = cell_w * 0.90
128
+ img_h = img_area_h * 0.90
129
+ return img_w, img_h
130
+
131
+
132
+
133
+ # ─────────────────────────────
134
+ # MAIN PPT GENERATION
135
+ # ─────────────────────────────
136
+
137
+ if st.button("πŸ“Š Generate PowerPoint"):
138
+ prs = Presentation()
139
+ EMU_PER_INCH = 914400
140
+ SLIDE_W_IN = prs.slide_width / EMU_PER_INCH
141
+ SLIDE_H_IN = prs.slide_height / EMU_PER_INCH
142
+
143
+ LEFT_MARGIN_IN = 0.5
144
+ RIGHT_MARGIN_IN = 0.5
145
+ TOP_MARGIN_IN = 1.0
146
+ BOTTOM_MARGIN_IN = 0.5
147
+
148
+ usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN
149
+ usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN
150
+
151
+ base_font_size = get_font_size(max_imgs_per_slide)
152
+
153
+ for day in day_list:
154
+ st.write(f"πŸ–ΌοΈ Adding images for {day}...")
155
+
156
+ # collect files
157
+ day_files = []
158
+ for treatment in treatment_list:
159
+ files = uploaded_files[treatment][day]
160
+ if files:
161
+ for f in files:
162
+ day_files.append((treatment, f))
163
+
164
+ total_imgs = len(day_files)
165
+ if total_imgs == 0:
166
+ continue
167
+
168
+ # grid
169
+ cols, rows = compute_grid(max_imgs_per_slide)
170
+ cell_w = usable_w_in / cols
171
+ cell_h = usable_h_in / rows
172
+
173
+ img_area_h = cell_h * 0.75
174
+ caption_h = cell_h * 0.25
175
+
176
+ fixed_img_w, fixed_img_h = get_fixed_display_size(cell_w, img_area_h)
177
+
178
+ idx = 0
179
+ slide_index_for_day = 0
180
+
181
+ while idx < total_imgs:
182
+ chunk = day_files[idx:idx + max_imgs_per_slide]
183
+
184
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
185
+ title_suffix = "" if slide_index_for_day == 0 else " (contd.)"
186
+ add_centered_title(slide, f"{day} β€” Treatment Images{title_suffix}", SLIDE_W_IN)
187
+ slide_index_for_day += 1
188
+
189
+ for local_i, (treatment, file) in enumerate(chunk):
190
+ row = local_i // cols
191
+ col = local_i % cols
192
+
193
+ cell_left = LEFT_MARGIN_IN + col * cell_w
194
+ cell_top = TOP_MARGIN_IN + row * cell_h
195
+
196
+ suffix = os.path.splitext(file.name)[1]
197
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
198
+ tmp.write(file.read())
199
+ raw_path = tmp.name
200
+
201
+ cropped_path = crop_with_yolo(raw_path, mode)
202
+ safe_path = normalize_image_for_ppt(cropped_path)
203
+ if not safe_path:
204
+ continue
205
+
206
+ try:
207
+ # Insert image with FIXED display area
208
+ img_left = cell_left + (cell_w - fixed_img_w) / 2
209
+ img_top = cell_top + (img_area_h - fixed_img_h) / 2
210
+
211
+ slide.shapes.add_picture(
212
+ safe_path,
213
+ left=Inches(img_left),
214
+ top=Inches(img_top),
215
+ width=Inches(fixed_img_w),
216
+ height=Inches(fixed_img_h),
217
+ )
218
+
219
+ # Caption
220
+ score = predict_infection_score(safe_path, mode)
221
+ caption_text = f"{treatment} β€” {day} | Score: {score}"
222
+
223
+ tx = slide.shapes.add_textbox(
224
+ Inches(cell_left),
225
+ Inches(cell_top + img_area_h + 0.02),
226
+ Inches(cell_w),
227
+ Inches(caption_h),
228
+ )
229
+ p = tx.text_frame.paragraphs[0]
230
+ p.text = caption_text
231
+ p.font.size = Pt(base_font_size)
232
+ p.font.bold = True
233
+ p.alignment = PP_ALIGN.CENTER
234
+
235
+ except Exception as e:
236
+ st.error(f"❌ Failed to add image '{safe_path}': {e}")
237
+
238
+ idx += max_imgs_per_slide
239
+
240
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx:
241
+ prs.save(tmp_pptx.name)
242
+ st.success("βœ… PowerPoint generated successfully")
243
+ st.download_button(
244
+ "⬇️ Download PowerPoint",
245
+ data=open(tmp_pptx.name, "rb").read(),
246
+ file_name="treatments_with_scores.pptx",
247
+ )
248
+
249
+
250
+ # #First deployed
251
+ # import os
252
+ # import tempfile
253
+ # import math
254
+ # import streamlit as st
255
+ # from pptx import Presentation
256
+ # from pptx.util import Inches, Pt
257
+ # from pptx.dml.color import RGBColor
258
+ # from pptx.enum.text import PP_ALIGN
259
+ # from PIL import Image, ImageOps
260
+ # from cropper import crop_with_yolo, predict_infection_score
261
+
262
+
263
+ # # ─────────────────────────────
264
+ # # Streamlit UI
265
+ # # ─────────────────────────────
266
+ # st.title("πŸ’Š Treatments β†’ PowerPoint Generator with Infection Scores")
267
+
268
+ # main_option = st.selectbox("Select Main Option", ["O", "V"])
269
+ # mode = "eye" if main_option == "O" else "vagina"
270
+ # st.write(f"🧠 YOLO mode: {mode}")
271
+
272
+ # num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1)
273
+ # num_days = st.number_input("Enter number of days", 1, 10, 3, 1)
274
+ # max_imgs_per_slide = st.number_input(
275
+ # "Enter number of images per slide", 1, 50, 9, 1
276
+ # )
277
+ # #Number of images upto 50
278
+
279
+ # treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)]
280
+ # day_list = [f"Day {i+1}" for i in range(num_days)]
281
+
282
+ # uploaded_files = {}
283
+ # st.markdown("### πŸ“ Upload images for each Treatment and Day")
284
+ # for treatment in treatment_list:
285
+ # st.subheader(treatment)
286
+ # uploaded_files[treatment] = {}
287
+ # for day in day_list:
288
+ # uploaded_files[treatment][day] = st.file_uploader(
289
+ # f"Upload image(s) for {day}",
290
+ # type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"],
291
+ # accept_multiple_files=True,
292
+ # key=f"{treatment}_{day}",
293
+ # )
294
+
295
+ # SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"}
296
+
297
+
298
+ # # ─────────────────────────────
299
+ # # Helpers
300
+ # # ─────────────────────────────
301
+ # def normalize_image_for_ppt(path: str) -> str | None:
302
+ # """Convert unsupported formats to PNG + fix EXIF rotation."""
303
+ # try:
304
+ # with Image.open(path) as im:
305
+ # fmt = (im.format or "").upper()
306
+ # im = ImageOps.exif_transpose(im)
307
+ # if fmt not in SUPPORTED_BY_PPTX:
308
+ # im = im.convert("RGB")
309
+ # out_path = os.path.splitext(path)[0] + "_clean.png"
310
+ # im.save(out_path, "PNG")
311
+ # return out_path
312
+ # return path
313
+ # except Exception as e:
314
+ # st.error(f"❌ Could not normalize image '{path}': {e}")
315
+ # return None
316
+
317
+
318
+ # def crop_with_margin(image_path: str, mode: str) -> str:
319
+ # """Use YOLO model for cropping (no extra PPT-side padding)."""
320
+ # try:
321
+ # cropped = crop_with_yolo(image_path, mode)
322
+ # return cropped if cropped and os.path.exists(cropped) else image_path
323
+ # except Exception as e:
324
+ # st.error(f"❌ YOLO crop failed for {image_path}: {e}")
325
+ # return image_path
326
+
327
+
328
+ # def compute_grid(n: int) -> tuple[int, int]:
329
+ # """Decide columns/rows so n images fit nicely."""
330
+ # cols = math.ceil(math.sqrt(n))
331
+ # rows = math.ceil(n / cols)
332
+ # return cols, rows
333
+
334
+
335
+ # def add_centered_title(slide, title_text: str, slide_width_in: float):
336
+ # """Add a perfectly centered title using presentation width."""
337
+ # title_box = slide.shapes.add_textbox(
338
+ # Inches(0),
339
+ # Inches(0.2),
340
+ # Inches(slide_width_in),
341
+ # Inches(0.8),
342
+ # )
343
+ # tf = title_box.text_frame
344
+ # tf.word_wrap = True
345
+ # p = tf.paragraphs[0]
346
+ # p.text = title_text
347
+ # p.alignment = PP_ALIGN.CENTER
348
+ # p.font.bold = True
349
+ # p.font.size = Pt(24)
350
+ # p.font.color.rgb = RGBColor(0, 0, 0)
351
+
352
+
353
+ # def get_font_size(num_images: int) -> int:
354
+ # """Dynamic caption font size."""
355
+ # if num_images <= 6:
356
+ # return 12
357
+ # elif num_images <= 20:
358
+ # return 10
359
+ # elif num_images <= 35:
360
+ # return 8
361
+ # else:
362
+ # return 7
363
+
364
+
365
+ # # ─────────────────────────────
366
+ # # PowerPoint Generation
367
+ # # ─────────────────────────────
368
+ # if st.button("πŸ“Š Generate PowerPoint"):
369
+ # prs = Presentation()
370
+ # EMU_PER_INCH = 914400
371
+ # SLIDE_W_IN = prs.slide_width / EMU_PER_INCH
372
+ # SLIDE_H_IN = prs.slide_height / EMU_PER_INCH
373
+
374
+ # # Margins and layout constants
375
+ # LEFT_MARGIN_IN = 0.5
376
+ # RIGHT_MARGIN_IN = 0.5
377
+ # TOP_MARGIN_IN = 1.0
378
+ # BOTTOM_MARGIN_IN = 0.5
379
+ # usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN
380
+ # usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN
381
+
382
+ # base_font_size = get_font_size(max_imgs_per_slide)
383
+
384
+ # for day in day_list:
385
+ # st.write(f"πŸ–ΌοΈ Adding images for {day}...")
386
+
387
+ # # Gather all uploaded files for this day
388
+ # day_files = []
389
+ # for treatment in treatment_list:
390
+ # files = uploaded_files[treatment][day]
391
+ # if files:
392
+ # for f in files:
393
+ # day_files.append((treatment, f))
394
+
395
+ # total_imgs = len(day_files)
396
+ # if total_imgs == 0:
397
+ # continue
398
+
399
+ # # Compute a single, consistent grid for all slides in this day
400
+ # cols, rows = compute_grid(max_imgs_per_slide)
401
+ # cell_w = usable_w_in / cols
402
+ # cell_h = usable_h_in / rows
403
+ # image_h_ratio = 0.75
404
+ # img_area_h = cell_h * image_h_ratio
405
+ # caption_h = cell_h * (1 - image_h_ratio)
406
+
407
+ # idx = 0
408
+ # slide_index_for_day = 0
409
+
410
+ # while idx < total_imgs:
411
+ # chunk = day_files[idx:idx + max_imgs_per_slide]
412
+ # n_chunk = len(chunk)
413
+
414
+ # slide = prs.slides.add_slide(prs.slide_layouts[6])
415
+ # title_suffix = "" if slide_index_for_day == 0 else f" (contd.)"
416
+ # add_centered_title(slide, f"{day} β€” Treatment Images{title_suffix}", SLIDE_W_IN)
417
+ # slide_index_for_day += 1
418
+
419
+ # for local_i, (treatment, file) in enumerate(chunk):
420
+ # row = local_i // cols
421
+ # col = local_i % cols
422
+ # cell_left = LEFT_MARGIN_IN + col * cell_w
423
+ # cell_top = TOP_MARGIN_IN + row * cell_h
424
+
425
+ # suffix = os.path.splitext(file.name)[1]
426
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
427
+ # tmp.write(file.read())
428
+ # raw_path = tmp.name
429
+
430
+ # cropped_path = crop_with_margin(raw_path, mode)
431
+ # safe_path = normalize_image_for_ppt(cropped_path)
432
+ # if not safe_path:
433
+ # continue
434
+
435
+ # try:
436
+ # # Preserve aspect ratio and fit naturally
437
+ # with Image.open(safe_path) as im:
438
+ # w, h = im.size
439
+ # img_ratio = w / h
440
+ # box_ratio = cell_w / img_area_h
441
+ # if img_ratio > box_ratio:
442
+ # img_w = cell_w * 0.9
443
+ # img_h = img_w / img_ratio
444
+ # else:
445
+ # img_h = img_area_h * 0.9
446
+ # img_w = img_h * img_ratio
447
+
448
+ # img_left = cell_left + (cell_w - img_w) / 2
449
+ # img_top = cell_top + (img_area_h - img_h) / 2
450
+
451
+ # slide.shapes.add_picture(
452
+ # safe_path,
453
+ # left=Inches(img_left),
454
+ # top=Inches(img_top),
455
+ # width=Inches(img_w),
456
+ # height=Inches(img_h),
457
+ # )
458
+
459
+ # # Caption (closer under image)
460
+ # score = predict_infection_score(safe_path, mode)
461
+ # caption_text = f"{treatment} β€” {day} | Score: {score}"
462
+ # caption_top = cell_top + img_area_h + 0.003 # slightly closer gap
463
+
464
+ # tx = slide.shapes.add_textbox(
465
+ # Inches(cell_left),
466
+ # Inches(caption_top),
467
+ # Inches(cell_w),
468
+ # Inches(caption_h),
469
+ # )
470
+ # tf = tx.text_frame
471
+ # tf.word_wrap = True
472
+ # p = tf.paragraphs[0]
473
+ # p.text = caption_text
474
+ # p.alignment = PP_ALIGN.CENTER
475
+ # p.font.size = Pt(base_font_size)
476
+ # p.font.bold = True
477
+ # p.font.color.rgb = RGBColor(0, 0, 0)
478
+
479
+ # except Exception as e:
480
+ # st.error(f"❌ Failed to add image '{safe_path}': {e}")
481
+
482
+ # idx += max_imgs_per_slide
483
+
484
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx:
485
+ # prs.save(tmp_pptx.name)
486
+ # st.success("βœ… PowerPoint generated successfully")
487
+ # st.download_button(
488
+ # "⬇️ Download PowerPoint",
489
+ # data=open(tmp_pptx.name, "rb").read(),
490
+ # file_name="treatments_with_scores.pptx",
491
+ # )
492
+
493
+ # st.success("βœ… PowerPoint generated successfully β€” centered titles, perfect spacing, consistent sizing!")
494
+
495
+
496
+ # import os
497
+ # import tempfile
498
+ # import math
499
+ # import streamlit as st
500
+ # from pptx import Presentation
501
+ # from pptx.util import Inches, Pt
502
+ # from pptx.dml.color import RGBColor
503
+ # from pptx.enum.text import PP_ALIGN
504
+ # from PIL import Image, ImageOps
505
+ # from cropper import crop_with_yolo, predict_infection_score
506
+
507
+
508
+ # # ─────────────────────────────
509
+ # # Streamlit UI
510
+ # # ─────────────────────────────
511
+ # st.title("πŸ’Š Treatments β†’ PowerPoint Generator with Infection Scores")
512
+
513
+ # main_option = st.selectbox("Select Main Option", ["O", "V"])
514
+ # mode = "eye" if main_option == "O" else "vagina"
515
+ # st.write(f"🧠 YOLO mode: {mode}")
516
+
517
+ # num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1)
518
+ # num_days = st.number_input("Enter number of days", 1, 10, 3, 1)
519
+ # max_imgs_per_slide = st.number_input(
520
+ # "Enter number of images per slide (up to 50)", 1, 50, 9, 1
521
+ # )
522
+
523
+ # treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)]
524
+ # day_list = [f"Day {i+1}" for i in range(num_days)]
525
+
526
+ # uploaded_files = {}
527
+ # st.markdown("### πŸ“ Upload images for each Treatment and Day")
528
+ # for treatment in treatment_list:
529
+ # st.subheader(treatment)
530
+ # uploaded_files[treatment] = {}
531
+ # for day in day_list:
532
+ # uploaded_files[treatment][day] = st.file_uploader(
533
+ # f"Upload image(s) for {day}",
534
+ # type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"],
535
+ # accept_multiple_files=True,
536
+ # key=f"{treatment}_{day}",
537
+ # )
538
+
539
+ # SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"}
540
+
541
+
542
+ # # ─────────────────────────────
543
+ # # Helpers
544
+ # # ─────────────────────────────
545
+ # def normalize_image_for_ppt(path: str) -> str | None:
546
+ # """Convert unsupported formats to PNG + fix EXIF rotation."""
547
+ # try:
548
+ # with Image.open(path) as im:
549
+ # fmt = (im.format or "").upper()
550
+ # im = ImageOps.exif_transpose(im)
551
+ # if fmt not in SUPPORTED_BY_PPTX:
552
+ # im = im.convert("RGB")
553
+ # out_path = os.path.splitext(path)[0] + "_clean.png"
554
+ # im.save(out_path, "PNG")
555
+ # return out_path
556
+ # return path
557
+ # except Exception as e:
558
+ # st.error(f"❌ Could not normalize image '{path}': {e}")
559
+ # return None
560
+
561
+
562
+ # def crop_with_margin(image_path: str, mode: str) -> str:
563
+ # """Use YOLO model for cropping (no extra PPT-side padding)."""
564
+ # try:
565
+ # cropped = crop_with_yolo(image_path, mode)
566
+ # return cropped if cropped and os.path.exists(cropped) else image_path
567
+ # except Exception as e:
568
+ # st.error(f"❌ YOLO crop failed for {image_path}: {e}")
569
+ # return image_path
570
+
571
+
572
+ # def compute_grid(n: int) -> tuple[int, int]:
573
+ # """Decide columns/rows so n images fit nicely."""
574
+ # cols = math.ceil(math.sqrt(n))
575
+ # rows = math.ceil(n / cols)
576
+ # return cols, rows
577
+
578
+
579
+ # def add_centered_title(slide, title_text: str):
580
+ # """Add a perfectly centered title."""
581
+ # slide_width_in = slide.part.slide_layout.slide_master.part.slide_width / 914400
582
+ # title_box = slide.shapes.add_textbox(
583
+ # Inches(0),
584
+ # Inches(0.2),
585
+ # Inches(slide_width_in),
586
+ # Inches(0.8),
587
+ # )
588
+ # tf = title_box.text_frame
589
+ # tf.word_wrap = True
590
+ # p = tf.paragraphs[0]
591
+ # p.text = title_text
592
+ # p.alignment = PP_ALIGN.CENTER
593
+ # p.font.bold = True
594
+ # p.font.size = Pt(24)
595
+ # p.font.color.rgb = RGBColor(0, 0, 0)
596
+
597
+
598
+ # def get_font_size(num_images: int) -> int:
599
+ # """Dynamic caption font size."""
600
+ # if num_images <= 6:
601
+ # return 12
602
+ # elif num_images <= 20:
603
+ # return 10
604
+ # elif num_images <= 35:
605
+ # return 8
606
+ # else:
607
+ # return 7
608
+
609
+
610
+ # # ─────────────────────────────
611
+ # # PowerPoint Generation
612
+ # # ─────────────────────────────
613
+ # if st.button("πŸ“Š Generate PowerPoint"):
614
+ # prs = Presentation()
615
+ # EMU_PER_INCH = 914400
616
+ # SLIDE_W_IN = prs.slide_width / EMU_PER_INCH
617
+ # SLIDE_H_IN = prs.slide_height / EMU_PER_INCH
618
+
619
+ # # Margins and layout constants
620
+ # LEFT_MARGIN_IN = 0.5
621
+ # RIGHT_MARGIN_IN = 0.5
622
+ # TOP_MARGIN_IN = 1.0
623
+ # BOTTOM_MARGIN_IN = 0.5
624
+ # usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN
625
+ # usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN
626
+
627
+ # base_font_size = get_font_size(max_imgs_per_slide)
628
+
629
+ # for day in day_list:
630
+ # st.write(f"πŸ–ΌοΈ Adding images for {day}...")
631
+
632
+ # # Gather all uploaded files for this day
633
+ # day_files = []
634
+ # for treatment in treatment_list:
635
+ # files = uploaded_files[treatment][day]
636
+ # if files:
637
+ # for f in files:
638
+ # day_files.append((treatment, f))
639
+
640
+ # total_imgs = len(day_files)
641
+ # if total_imgs == 0:
642
+ # continue
643
+
644
+ # # Compute a single, consistent grid for all slides in this day
645
+ # cols, rows = compute_grid(max_imgs_per_slide)
646
+ # cell_w = usable_w_in / cols
647
+ # cell_h = usable_h_in / rows
648
+ # image_h_ratio = 0.75
649
+ # img_area_h = cell_h * image_h_ratio
650
+ # caption_h = cell_h * (1 - image_h_ratio)
651
+
652
+ # idx = 0
653
+ # slide_index_for_day = 0
654
+
655
+ # while idx < total_imgs:
656
+ # chunk = day_files[idx:idx + max_imgs_per_slide]
657
+ # n_chunk = len(chunk)
658
+
659
+ # slide = prs.slides.add_slide(prs.slide_layouts[6])
660
+ # title_suffix = "" if slide_index_for_day == 0 else f" (contd.)"
661
+ # add_centered_title(slide, f"{day} β€” Treatment Images{title_suffix}")
662
+ # slide_index_for_day += 1
663
+
664
+ # for local_i, (treatment, file) in enumerate(chunk):
665
+ # row = local_i // cols
666
+ # col = local_i % cols
667
+ # cell_left = LEFT_MARGIN_IN + col * cell_w
668
+ # cell_top = TOP_MARGIN_IN + row * cell_h
669
+
670
+ # suffix = os.path.splitext(file.name)[1]
671
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
672
+ # tmp.write(file.read())
673
+ # raw_path = tmp.name
674
+
675
+ # cropped_path = crop_with_margin(raw_path, mode)
676
+ # safe_path = normalize_image_for_ppt(cropped_path)
677
+ # if not safe_path:
678
+ # continue
679
+
680
+ # try:
681
+ # # Preserve aspect ratio
682
+ # with Image.open(safe_path) as im:
683
+ # w, h = im.size
684
+ # img_ratio = w / h
685
+ # box_ratio = cell_w / img_area_h
686
+ # if img_ratio > box_ratio:
687
+ # img_w = cell_w * 0.9
688
+ # img_h = img_w / img_ratio
689
+ # else:
690
+ # img_h = img_area_h * 0.9
691
+ # img_w = img_h * img_ratio
692
+
693
+ # img_left = cell_left + (cell_w - img_w) / 2
694
+ # img_top = cell_top + (img_area_h - img_h) / 2
695
+
696
+ # slide.shapes.add_picture(
697
+ # safe_path,
698
+ # left=Inches(img_left),
699
+ # top=Inches(img_top),
700
+ # width=Inches(img_w),
701
+ # height=Inches(img_h),
702
+ # )
703
+
704
+ # # Caption (even closer)
705
+ # score = predict_infection_score(safe_path, mode)
706
+ # caption_text = f"{treatment} β€” {day} | Score: {score}"
707
+ # caption_top = cell_top + img_area_h + 0.005 # closer spacing
708
+
709
+ # tx = slide.shapes.add_textbox(
710
+ # Inches(cell_left),
711
+ # Inches(caption_top),
712
+ # Inches(cell_w),
713
+ # Inches(caption_h),
714
+ # )
715
+ # tf = tx.text_frame
716
+ # tf.word_wrap = True
717
+ # p = tf.paragraphs[0]
718
+ # p.text = caption_text
719
+ # p.alignment = PP_ALIGN.CENTER
720
+ # p.font.size = Pt(base_font_size)
721
+ # p.font.bold = True
722
+ # p.font.color.rgb = RGBColor(0, 0, 0)
723
+
724
+ # except Exception as e:
725
+ # st.error(f"❌ Failed to add image '{safe_path}': {e}")
726
+
727
+ # idx += max_imgs_per_slide
728
+
729
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx:
730
+ # prs.save(tmp_pptx.name)
731
+ # st.success("βœ… PowerPoint generated successfully β€” centered titles and clean spacing!")
732
+ # st.download_button(
733
+ # "⬇️ Download PowerPoint",
734
+ # data=open(tmp_pptx.name, "rb").read(),
735
+ # file_name="treatments_with_scores.pptx",
736
+ # )
737
+
738
+ # #no overlapping, all images in the PPT are of the same size
739
+ # import os
740
+ # import tempfile
741
+ # import math
742
+ # import streamlit as st
743
+ # from pptx import Presentation
744
+ # from pptx.util import Inches, Pt
745
+ # from pptx.dml.color import RGBColor
746
+ # from pptx.enum.text import PP_ALIGN
747
+ # from PIL import Image, ImageOps
748
+ # from cropper import crop_with_yolo, predict_infection_score
749
+
750
+
751
+ # # ─────────────────────────────
752
+ # # Streamlit UI
753
+ # # ─────────────────────────────
754
+ # st.title("πŸ’Š Treatments β†’ PowerPoint Generator with Infection Scores")
755
+
756
+ # main_option = st.selectbox("Select Main Option", ["O", "V"])
757
+ # mode = "eye" if main_option == "O" else "vagina"
758
+ # st.write(f"🧠 YOLO mode: {mode}")
759
+
760
+ # num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1)
761
+ # num_days = st.number_input("Enter number of days", 1, 10, 3, 1)
762
+ # max_imgs_per_slide = st.number_input(
763
+ # "Enter number of images per slide (up to 50)", 1, 50, 9, 1
764
+ # )
765
+
766
+ # treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)]
767
+ # day_list = [f"Day {i+1}" for i in range(num_days)]
768
+
769
+ # uploaded_files = {}
770
+ # st.markdown("### πŸ“ Upload images for each Treatment and Day")
771
+ # for treatment in treatment_list:
772
+ # st.subheader(treatment)
773
+ # uploaded_files[treatment] = {}
774
+ # for day in day_list:
775
+ # uploaded_files[treatment][day] = st.file_uploader(
776
+ # f"Upload image(s) for {day}",
777
+ # type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"],
778
+ # accept_multiple_files=True,
779
+ # key=f"{treatment}_{day}",
780
+ # )
781
+
782
+ # SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"}
783
+
784
+
785
+ # # ─────────────────────────────
786
+ # # Helpers
787
+ # # ─────────────────────────────
788
+ # def normalize_image_for_ppt(path: str) -> str | None:
789
+ # """Convert unsupported formats to PNG + fix EXIF rotation."""
790
+ # try:
791
+ # with Image.open(path) as im:
792
+ # fmt = (im.format or "").upper()
793
+ # im = ImageOps.exif_transpose(im)
794
+ # if fmt not in SUPPORTED_BY_PPTX:
795
+ # im = im.convert("RGB")
796
+ # out_path = os.path.splitext(path)[0] + "_clean.png"
797
+ # im.save(out_path, "PNG")
798
+ # return out_path
799
+ # return path
800
+ # except Exception as e:
801
+ # st.error(f"❌ Could not normalize image '{path}': {e}")
802
+ # return None
803
+
804
+
805
+ # def crop_with_margin(image_path: str, mode: str) -> str:
806
+ # """Use YOLO model for cropping (no extra PPT-side padding)."""
807
+ # try:
808
+ # cropped = crop_with_yolo(image_path, mode)
809
+ # return cropped if cropped and os.path.exists(cropped) else image_path
810
+ # except Exception as e:
811
+ # st.error(f"❌ YOLO crop failed for {image_path}: {e}")
812
+ # return image_path
813
+
814
+
815
+ # def compute_grid(n: int) -> tuple[int, int]:
816
+ # """Decide columns/rows so n images fit nicely."""
817
+ # cols = math.ceil(math.sqrt(n))
818
+ # rows = math.ceil(n / cols)
819
+ # return cols, rows
820
+
821
+
822
+ # def add_centered_title(slide, title_text: str):
823
+ # """Add a perfectly centered title."""
824
+ # title_box = slide.shapes.add_textbox(Inches(0), Inches(0.2), Inches(13.33), Inches(0.8))
825
+ # tf = title_box.text_frame
826
+ # tf.word_wrap = True
827
+ # p = tf.paragraphs[0]
828
+ # p.text = title_text
829
+ # p.alignment = PP_ALIGN.CENTER
830
+ # p.font.bold = True
831
+ # p.font.size = Pt(24)
832
+ # p.font.color.rgb = RGBColor(0, 0, 0)
833
+
834
+
835
+ # def get_font_size(num_images: int) -> int:
836
+ # """Dynamic caption font size."""
837
+ # if num_images <= 6:
838
+ # return 12
839
+ # elif num_images <= 20:
840
+ # return 10
841
+ # elif num_images <= 35:
842
+ # return 8
843
+ # else:
844
+ # return 7
845
+
846
+
847
+ # # ─────────────────────────────
848
+ # # PowerPoint Generation
849
+ # # ─────────────────────────────
850
+ # if st.button("πŸ“Š Generate PowerPoint"):
851
+ # prs = Presentation()
852
+ # EMU_PER_INCH = 914400
853
+ # SLIDE_W_IN = prs.slide_width / EMU_PER_INCH
854
+ # SLIDE_H_IN = prs.slide_height / EMU_PER_INCH
855
+
856
+ # # Margins and layout constants
857
+ # LEFT_MARGIN_IN = 0.5
858
+ # RIGHT_MARGIN_IN = 0.5
859
+ # TOP_MARGIN_IN = 1.0
860
+ # BOTTOM_MARGIN_IN = 0.5
861
+ # usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN
862
+ # usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN
863
+
864
+ # base_font_size = get_font_size(max_imgs_per_slide)
865
+
866
+ # for day in day_list:
867
+ # st.write(f"πŸ–ΌοΈ Adding images for {day}...")
868
+
869
+ # # Gather all uploaded files for this day
870
+ # day_files = []
871
+ # for treatment in treatment_list:
872
+ # files = uploaded_files[treatment][day]
873
+ # if files:
874
+ # for f in files:
875
+ # day_files.append((treatment, f))
876
+
877
+ # total_imgs = len(day_files)
878
+ # if total_imgs == 0:
879
+ # continue
880
+
881
+ # # Compute a single, consistent grid for all slides in this day
882
+ # cols, rows = compute_grid(max_imgs_per_slide)
883
+ # cell_w = usable_w_in / cols
884
+ # cell_h = usable_h_in / rows
885
+ # image_h_ratio = 0.75
886
+ # img_area_h = cell_h * image_h_ratio
887
+ # caption_h = cell_h * (1 - image_h_ratio)
888
+
889
+ # idx = 0
890
+ # slide_index_for_day = 0
891
+
892
+ # while idx < total_imgs:
893
+ # chunk = day_files[idx:idx + max_imgs_per_slide]
894
+ # n_chunk = len(chunk)
895
+
896
+ # slide = prs.slides.add_slide(prs.slide_layouts[6])
897
+ # title_suffix = "" if slide_index_for_day == 0 else f" (contd.)"
898
+ # add_centered_title(slide, f"{day} β€” Treatment Images{title_suffix}")
899
+ # slide_index_for_day += 1
900
+
901
+ # for local_i, (treatment, file) in enumerate(chunk):
902
+ # row = local_i // cols
903
+ # col = local_i % cols
904
+ # cell_left = LEFT_MARGIN_IN + col * cell_w
905
+ # cell_top = TOP_MARGIN_IN + row * cell_h
906
+
907
+ # suffix = os.path.splitext(file.name)[1]
908
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
909
+ # tmp.write(file.read())
910
+ # raw_path = tmp.name
911
+
912
+ # cropped_path = crop_with_margin(raw_path, mode)
913
+ # safe_path = normalize_image_for_ppt(cropped_path)
914
+ # if not safe_path:
915
+ # continue
916
+
917
+ # try:
918
+ # # Preserve aspect ratio
919
+ # with Image.open(safe_path) as im:
920
+ # w, h = im.size
921
+ # img_ratio = w / h
922
+ # box_ratio = cell_w / img_area_h
923
+ # if img_ratio > box_ratio:
924
+ # img_w = cell_w * 0.9
925
+ # img_h = img_w / img_ratio
926
+ # else:
927
+ # img_h = img_area_h * 0.9
928
+ # img_w = img_h * img_ratio
929
+
930
+ # img_left = cell_left + (cell_w - img_w) / 2
931
+ # img_top = cell_top + (img_area_h - img_h) / 2
932
+
933
+ # slide.shapes.add_picture(
934
+ # safe_path,
935
+ # left=Inches(img_left),
936
+ # top=Inches(img_top),
937
+ # width=Inches(img_w),
938
+ # height=Inches(img_h),
939
+ # )
940
+
941
+ # # Caption (separate zone)
942
+ # score = predict_infection_score(safe_path, mode)
943
+ # caption_text = f"{treatment} β€” {day} | Score: {score}"
944
+ # caption_top = cell_top + img_area_h + 0.03
945
+
946
+ # tx = slide.shapes.add_textbox(
947
+ # Inches(cell_left),
948
+ # Inches(caption_top),
949
+ # Inches(cell_w),
950
+ # Inches(caption_h),
951
+ # )
952
+ # tf = tx.text_frame
953
+ # tf.word_wrap = True
954
+ # p = tf.paragraphs[0]
955
+ # p.text = caption_text
956
+ # p.alignment = PP_ALIGN.CENTER
957
+ # p.font.size = Pt(base_font_size)
958
+ # p.font.bold = True
959
+ # p.font.color.rgb = RGBColor(0, 0, 0)
960
+
961
+ # except Exception as e:
962
+ # st.error(f"❌ Failed to add image '{safe_path}': {e}")
963
+
964
+ # idx += max_imgs_per_slide
965
+
966
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx:
967
+ # prs.save(tmp_pptx.name)
968
+ # st.success("βœ… PowerPoint generated successfully β€” consistent size & centered titles!")
969
+ # st.download_button(
970
+ # "⬇️ Download PowerPoint",
971
+ # data=open(tmp_pptx.name, "rb").read(),
972
+ # file_name="treatments_with_scores.pptx",
973
+ # )
974
+
975
+ # #was trying
976
+ # # #Works pretty good, no overlapping
977
+ # import os
978
+ # import tempfile
979
+ # import math
980
+ # import streamlit as st
981
+ # from pptx import Presentation
982
+ # from pptx.util import Inches, Pt
983
+ # from pptx.dml.color import RGBColor
984
+ # from pptx.enum.text import PP_ALIGN
985
+ # from PIL import Image, ImageOps
986
+ # from cropper import crop_with_yolo, predict_infection_score
987
+
988
+
989
+ # # ─────────────────────────────
990
+ # # Streamlit UI
991
+ # # ─────────────────────────────
992
+ # st.title("πŸ’Š Treatments β†’ PowerPoint Generator with Infection Scores")
993
+
994
+ # main_option = st.selectbox("Select Main Option", ["O", "V"])
995
+ # mode = "eye" if main_option == "O" else "vagina"
996
+ # st.write(f"🧠 YOLO mode: {mode}")
997
+
998
+ # num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1)
999
+ # num_days = st.number_input("Enter number of days", 1, 10, 3, 1)
1000
+ # max_imgs_per_slide = st.number_input(
1001
+ # "Enter number of images per slide (up to 50)", 1, 50, 6, 1
1002
+ # )
1003
+
1004
+ # treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)]
1005
+ # day_list = [f"Day {i+1}" for i in range(num_days)]
1006
+
1007
+ # uploaded_files = {}
1008
+ # st.markdown("### πŸ“ Upload images for each Treatment and Day")
1009
+ # for treatment in treatment_list:
1010
+ # st.subheader(treatment)
1011
+ # uploaded_files[treatment] = {}
1012
+ # for day in day_list:
1013
+ # uploaded_files[treatment][day] = st.file_uploader(
1014
+ # f"Upload image(s) for {day}",
1015
+ # type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"],
1016
+ # accept_multiple_files=True,
1017
+ # key=f"{treatment}_{day}",
1018
+ # )
1019
+
1020
+ # SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"}
1021
+
1022
+
1023
+ # # ─────────────────────────────
1024
+ # # Helpers
1025
+ # # ─────────────────────────────
1026
+ # def normalize_image_for_ppt(path: str) -> str | None:
1027
+ # """Convert unsupported formats to PNG + fix EXIF rotation."""
1028
+ # try:
1029
+ # with Image.open(path) as im:
1030
+ # fmt = (im.format or "").upper()
1031
+ # im = ImageOps.exif_transpose(im)
1032
+ # if fmt not in SUPPORTED_BY_PPTX:
1033
+ # im = im.convert("RGB")
1034
+ # out_path = os.path.splitext(path)[0] + "_clean.png"
1035
+ # im.save(out_path, "PNG")
1036
+ # return out_path
1037
+ # return path
1038
+ # except Exception as e:
1039
+ # st.error(f"❌ Could not normalize image '{path}': {e}")
1040
+ # return None
1041
+
1042
+
1043
+ # def crop_with_margin(image_path: str, mode: str) -> str:
1044
+ # """Use YOLO model for cropping (no extra PPT-side padding)."""
1045
+ # try:
1046
+ # cropped = crop_with_yolo(image_path, mode)
1047
+ # return cropped if cropped and os.path.exists(cropped) else image_path
1048
+ # except Exception as e:
1049
+ # st.error(f"❌ YOLO crop failed for {image_path}: {e}")
1050
+ # return image_path
1051
+
1052
+
1053
+ # def compute_grid(n: int) -> tuple[int, int]:
1054
+ # """Decide columns/rows so n images fit nicely."""
1055
+ # cols = math.ceil(math.sqrt(n))
1056
+ # rows = math.ceil(n / cols)
1057
+ # return cols, rows
1058
+
1059
+
1060
+ # def add_slide_title(slide, title_text: str):
1061
+ # """Add a centered title at the top of the slide."""
1062
+ # title_box = slide.shapes.add_textbox(Inches(0.3), Inches(0.1), Inches(12), Inches(0.6))
1063
+ # tf = title_box.text_frame
1064
+ # tf.word_wrap = True
1065
+ # p = tf.paragraphs[0]
1066
+ # p.text = title_text
1067
+ # p.alignment = PP_ALIGN.CENTER
1068
+ # p.font.bold = True
1069
+ # p.font.size = Pt(20)
1070
+ # p.font.color.rgb = RGBColor(0, 0, 0)
1071
+
1072
+
1073
+ # def get_font_size(num_images: int) -> int:
1074
+ # if num_images <= 6:
1075
+ # return 12
1076
+ # elif num_images <= 20:
1077
+ # return 10
1078
+ # elif num_images <= 35:
1079
+ # return 8
1080
+ # else:
1081
+ # return 7
1082
+
1083
+
1084
+ # # ─────────────────────────────
1085
+ # # PowerPoint Generation
1086
+ # # ─────────────────────────────
1087
+ # if st.button("πŸ“Š Generate PowerPoint"):
1088
+ # prs = Presentation()
1089
+ # EMU_PER_INCH = 914400
1090
+ # SLIDE_W_IN = prs.slide_width / EMU_PER_INCH
1091
+ # SLIDE_H_IN = prs.slide_height / EMU_PER_INCH
1092
+
1093
+ # LEFT_MARGIN_IN = 0.5
1094
+ # RIGHT_MARGIN_IN = 0.5
1095
+ # TOP_MARGIN_IN = 1.0
1096
+ # BOTTOM_MARGIN_IN = 0.5
1097
+ # usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN
1098
+ # usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN
1099
+
1100
+ # base_font_size = get_font_size(max_imgs_per_slide)
1101
+
1102
+ # for day in day_list:
1103
+ # st.write(f"πŸ–ΌοΈ Adding images for {day}...")
1104
+
1105
+ # # Collect all images of this day
1106
+ # day_files = []
1107
+ # for treatment in treatment_list:
1108
+ # files = uploaded_files[treatment][day]
1109
+ # if files:
1110
+ # for f in files:
1111
+ # day_files.append((treatment, f))
1112
+
1113
+ # total_imgs = len(day_files)
1114
+ # if total_imgs == 0:
1115
+ # continue
1116
+
1117
+ # idx = 0
1118
+ # slide_index_for_day = 0
1119
+
1120
+ # while idx < total_imgs:
1121
+ # chunk = day_files[idx:idx + max_imgs_per_slide]
1122
+ # n_chunk = len(chunk)
1123
+
1124
+ # slide = prs.slides.add_slide(prs.slide_layouts[6])
1125
+ # title_suffix = "" if slide_index_for_day == 0 else " (contd.)"
1126
+ # add_slide_title(slide, f"{day} β€” Treatment Images{title_suffix}")
1127
+ # slide_index_for_day += 1
1128
+
1129
+ # # Compute grid
1130
+ # cols, rows = compute_grid(n_chunk)
1131
+ # cell_w = usable_w_in / cols
1132
+ # cell_h = usable_h_in / rows
1133
+
1134
+ # # Image and caption spacing constants
1135
+ # image_h_ratio = 0.75 # 75% image, 25% caption zone per cell
1136
+ # img_area_h = cell_h * image_h_ratio
1137
+ # caption_h = cell_h * (1 - image_h_ratio)
1138
+
1139
+ # for local_i, (treatment, file) in enumerate(chunk):
1140
+ # row = local_i // cols
1141
+ # col = local_i % cols
1142
+ # cell_left = LEFT_MARGIN_IN + col * cell_w
1143
+ # cell_top = TOP_MARGIN_IN + row * cell_h
1144
+
1145
+ # suffix = os.path.splitext(file.name)[1]
1146
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
1147
+ # tmp.write(file.read())
1148
+ # raw_path = tmp.name
1149
+
1150
+ # cropped_path = crop_with_margin(raw_path, mode)
1151
+ # safe_path = normalize_image_for_ppt(cropped_path)
1152
+ # if not safe_path:
1153
+ # continue
1154
+
1155
+ # try:
1156
+ # # Preserve image ratio β€” scale to fit inside its image zone
1157
+ # with Image.open(safe_path) as im:
1158
+ # w, h = im.size
1159
+ # img_ratio = w / h
1160
+ # box_ratio = cell_w / img_area_h
1161
+ # if img_ratio > box_ratio:
1162
+ # img_w = cell_w * 0.9
1163
+ # img_h = img_w / img_ratio
1164
+ # else:
1165
+ # img_h = img_area_h * 0.9
1166
+ # img_w = img_h * img_ratio
1167
+
1168
+ # img_left = cell_left + (cell_w - img_w) / 2
1169
+ # img_top = cell_top + (img_area_h - img_h) / 2
1170
+
1171
+ # slide.shapes.add_picture(
1172
+ # safe_path,
1173
+ # left=Inches(img_left),
1174
+ # top=Inches(img_top),
1175
+ # width=Inches(img_w),
1176
+ # height=Inches(img_h),
1177
+ # )
1178
+
1179
+ # # Caption β€” completely separate vertical zone
1180
+ # score = predict_infection_score(safe_path, mode)
1181
+ # caption_text = f"{treatment} β€” {day} | Score: {score}"
1182
+ # caption_top = cell_top + img_area_h + 0.02
1183
+
1184
+ # tx = slide.shapes.add_textbox(
1185
+ # Inches(cell_left),
1186
+ # Inches(caption_top),
1187
+ # Inches(cell_w),
1188
+ # Inches(caption_h),
1189
+ # )
1190
+ # tf = tx.text_frame
1191
+ # tf.word_wrap = True
1192
+ # p = tf.paragraphs[0]
1193
+ # p.text = caption_text
1194
+ # p.alignment = PP_ALIGN.CENTER
1195
+ # p.font.size = Pt(base_font_size)
1196
+ # p.font.bold = True
1197
+ # p.font.color.rgb = RGBColor(0, 0, 0)
1198
+
1199
+ # except Exception as e:
1200
+ # st.error(f"❌ Failed to add image '{safe_path}': {e}")
1201
+
1202
+ # idx += max_imgs_per_slide
1203
+
1204
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx:
1205
+ # prs.save(tmp_pptx.name)
1206
+ # st.success("βœ… PowerPoint generated successfully β€” no overlaps, consistent spacing!")
1207
+ # st.download_button(
1208
+ # "⬇️ Download PowerPoint",
1209
+ # data=open(tmp_pptx.name, "rb").read(),
1210
+ # file_name="treatments_with_scores.pptx",
1211
+ # )
1212
+