import os import tempfile import math import streamlit as st from pptx import Presentation from pptx.util import Inches, Pt from pptx.dml.color import RGBColor from pptx.enum.text import PP_ALIGN from PIL import Image, ImageOps from cropper import crop_with_yolo, predict_infection_score # ───────────────────────────── # Streamlit UI # ───────────────────────────── st.title("💊 Treatments → PowerPoint Generator with Infection Scores") main_option = st.selectbox("Select Main Option", ["O", "V"]) mode = "eye" if main_option == "O" else "vagina" st.write(f"🧠 YOLO mode: {mode}") num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1) num_days = st.number_input("Enter number of days", 1, 10, 3, 1) max_imgs_per_slide = st.number_input( "Enter number of images per slide", 1, 50, 9, 1 ) #Number of images upto 50 treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)] day_list = [f"Day {i+1}" for i in range(num_days)] uploaded_files = {} st.markdown("### 📁 Upload images for each Treatment and Day") for treatment in treatment_list: st.subheader(treatment) uploaded_files[treatment] = {} for day in day_list: uploaded_files[treatment][day] = st.file_uploader( f"Upload image(s) for {day}", type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"], accept_multiple_files=True, key=f"{treatment}_{day}", ) SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"} # ───────────────────────────── # Helpers # ───────────────────────────── def normalize_image_for_ppt(path: str) -> str | None: """Convert unsupported formats to PNG + fix EXIF rotation.""" try: with Image.open(path) as im: fmt = (im.format or "").upper() im = ImageOps.exif_transpose(im) if fmt not in SUPPORTED_BY_PPTX: im = im.convert("RGB") out_path = os.path.splitext(path)[0] + "_clean.png" im.save(out_path, "PNG") return out_path return path except Exception as e: st.error(f"❌ Could not normalize image '{path}': {e}") return None def crop_with_margin(image_path: str, mode: str) -> str: """Use YOLO model for cropping (no extra PPT-side padding).""" try: cropped = crop_with_yolo(image_path, mode) return cropped if cropped and os.path.exists(cropped) else image_path except Exception as e: st.error(f"❌ YOLO crop failed for {image_path}: {e}") return image_path def compute_grid(n: int) -> tuple[int, int]: """Decide columns/rows so n images fit nicely.""" cols = math.ceil(math.sqrt(n)) rows = math.ceil(n / cols) return cols, rows def add_centered_title(slide, title_text: str, slide_width_in: float): """Add a perfectly centered title using presentation width.""" title_box = slide.shapes.add_textbox( Inches(0), Inches(0.2), Inches(slide_width_in), Inches(0.8), ) tf = title_box.text_frame tf.word_wrap = True p = tf.paragraphs[0] p.text = title_text p.alignment = PP_ALIGN.CENTER p.font.bold = True p.font.size = Pt(24) p.font.color.rgb = RGBColor(0, 0, 0) def get_font_size(num_images: int) -> int: """Dynamic caption font size.""" if num_images <= 6: return 12 elif num_images <= 20: return 10 elif num_images <= 35: return 8 else: return 7 # ───────────────────────────── # PowerPoint Generation # ───────────────────────────── if st.button("📊 Generate PowerPoint"): prs = Presentation() EMU_PER_INCH = 914400 SLIDE_W_IN = prs.slide_width / EMU_PER_INCH SLIDE_H_IN = prs.slide_height / EMU_PER_INCH # Margins and layout constants LEFT_MARGIN_IN = 0.5 RIGHT_MARGIN_IN = 0.5 TOP_MARGIN_IN = 1.0 BOTTOM_MARGIN_IN = 0.5 usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN base_font_size = get_font_size(max_imgs_per_slide) for day in day_list: st.write(f"🖼️ Adding images for {day}...") # Gather all uploaded files for this day day_files = [] for treatment in treatment_list: files = uploaded_files[treatment][day] if files: for f in files: day_files.append((treatment, f)) total_imgs = len(day_files) if total_imgs == 0: continue # Compute a single, consistent grid for all slides in this day cols, rows = compute_grid(max_imgs_per_slide) cell_w = usable_w_in / cols cell_h = usable_h_in / rows image_h_ratio = 0.75 img_area_h = cell_h * image_h_ratio caption_h = cell_h * (1 - image_h_ratio) idx = 0 slide_index_for_day = 0 while idx < total_imgs: chunk = day_files[idx:idx + max_imgs_per_slide] n_chunk = len(chunk) slide = prs.slides.add_slide(prs.slide_layouts[6]) title_suffix = "" if slide_index_for_day == 0 else f" (contd.)" add_centered_title(slide, f"{day} — Treatment Images{title_suffix}", SLIDE_W_IN) slide_index_for_day += 1 for local_i, (treatment, file) in enumerate(chunk): row = local_i // cols col = local_i % cols cell_left = LEFT_MARGIN_IN + col * cell_w cell_top = TOP_MARGIN_IN + row * cell_h suffix = os.path.splitext(file.name)[1] with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp: tmp.write(file.read()) raw_path = tmp.name cropped_path = crop_with_margin(raw_path, mode) safe_path = normalize_image_for_ppt(cropped_path) if not safe_path: continue try: # Preserve aspect ratio and fit naturally with Image.open(safe_path) as im: w, h = im.size img_ratio = w / h box_ratio = cell_w / img_area_h if img_ratio > box_ratio: img_w = cell_w * 0.9 img_h = img_w / img_ratio else: img_h = img_area_h * 0.9 img_w = img_h * img_ratio img_left = cell_left + (cell_w - img_w) / 2 img_top = cell_top + (img_area_h - img_h) / 2 slide.shapes.add_picture( safe_path, left=Inches(img_left), top=Inches(img_top), width=Inches(img_w), height=Inches(img_h), ) # Caption (closer under image) score = predict_infection_score(safe_path, mode) img_name = file.name caption_text = f"{treatment} — {day} | Score: {score}" caption_top = cell_top + img_area_h + 0.003 # slightly closer gap tx = slide.shapes.add_textbox( Inches(cell_left), Inches(caption_top), Inches(cell_w), Inches(caption_h), ) tf = tx.text_frame tf.word_wrap = True p = tf.paragraphs[0] p.text = caption_text p.alignment = PP_ALIGN.CENTER p.font.size = Pt(base_font_size) p.font.bold = True p.font.color.rgb = RGBColor(0, 0, 0) except Exception as e: st.error(f"❌ Failed to add image '{safe_path}': {e}") idx += max_imgs_per_slide with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx: prs.save(tmp_pptx.name) st.success("✅ PowerPoint generated successfully") st.download_button( "⬇️ Download PowerPoint", data=open(tmp_pptx.name, "rb").read(), file_name="treatments_with_scores.pptx", ) # #First deployed # import os # import tempfile # import math # import streamlit as st # from pptx import Presentation # from pptx.util import Inches, Pt # from pptx.dml.color import RGBColor # from pptx.enum.text import PP_ALIGN # from PIL import Image, ImageOps # from cropper import crop_with_yolo, predict_infection_score # # ───────────────────────────── # # Streamlit UI # # ───────────────────────────── # st.title("💊 Treatments → PowerPoint Generator with Infection Scores") # main_option = st.selectbox("Select Main Option", ["O", "V"]) # mode = "eye" if main_option == "O" else "vagina" # st.write(f"🧠 YOLO mode: {mode}") # num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1) # num_days = st.number_input("Enter number of days", 1, 10, 3, 1) # max_imgs_per_slide = st.number_input( # "Enter number of images per slide", 1, 50, 9, 1 # ) # #Number of images upto 50 # treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)] # day_list = [f"Day {i+1}" for i in range(num_days)] # uploaded_files = {} # st.markdown("### 📁 Upload images for each Treatment and Day") # for treatment in treatment_list: # st.subheader(treatment) # uploaded_files[treatment] = {} # for day in day_list: # uploaded_files[treatment][day] = st.file_uploader( # f"Upload image(s) for {day}", # type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"], # accept_multiple_files=True, # key=f"{treatment}_{day}", # ) # SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"} # # ───────────────────────────── # # Helpers # # ───────────────────────────── # def normalize_image_for_ppt(path: str) -> str | None: # """Convert unsupported formats to PNG + fix EXIF rotation.""" # try: # with Image.open(path) as im: # fmt = (im.format or "").upper() # im = ImageOps.exif_transpose(im) # if fmt not in SUPPORTED_BY_PPTX: # im = im.convert("RGB") # out_path = os.path.splitext(path)[0] + "_clean.png" # im.save(out_path, "PNG") # return out_path # return path # except Exception as e: # st.error(f"❌ Could not normalize image '{path}': {e}") # return None # def crop_with_margin(image_path: str, mode: str) -> str: # """Use YOLO model for cropping (no extra PPT-side padding).""" # try: # cropped = crop_with_yolo(image_path, mode) # return cropped if cropped and os.path.exists(cropped) else image_path # except Exception as e: # st.error(f"❌ YOLO crop failed for {image_path}: {e}") # return image_path # def compute_grid(n: int) -> tuple[int, int]: # """Decide columns/rows so n images fit nicely.""" # cols = math.ceil(math.sqrt(n)) # rows = math.ceil(n / cols) # return cols, rows # def add_centered_title(slide, title_text: str, slide_width_in: float): # """Add a perfectly centered title using presentation width.""" # title_box = slide.shapes.add_textbox( # Inches(0), # Inches(0.2), # Inches(slide_width_in), # Inches(0.8), # ) # tf = title_box.text_frame # tf.word_wrap = True # p = tf.paragraphs[0] # p.text = title_text # p.alignment = PP_ALIGN.CENTER # p.font.bold = True # p.font.size = Pt(24) # p.font.color.rgb = RGBColor(0, 0, 0) # def get_font_size(num_images: int) -> int: # """Dynamic caption font size.""" # if num_images <= 6: # return 12 # elif num_images <= 20: # return 10 # elif num_images <= 35: # return 8 # else: # return 7 # # ───────────────────────────── # # PowerPoint Generation # # ───────────────────────────── # if st.button("📊 Generate PowerPoint"): # prs = Presentation() # EMU_PER_INCH = 914400 # SLIDE_W_IN = prs.slide_width / EMU_PER_INCH # SLIDE_H_IN = prs.slide_height / EMU_PER_INCH # # Margins and layout constants # LEFT_MARGIN_IN = 0.5 # RIGHT_MARGIN_IN = 0.5 # TOP_MARGIN_IN = 1.0 # BOTTOM_MARGIN_IN = 0.5 # usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN # usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN # base_font_size = get_font_size(max_imgs_per_slide) # for day in day_list: # st.write(f"🖼️ Adding images for {day}...") # # Gather all uploaded files for this day # day_files = [] # for treatment in treatment_list: # files = uploaded_files[treatment][day] # if files: # for f in files: # day_files.append((treatment, f)) # total_imgs = len(day_files) # if total_imgs == 0: # continue # # Compute a single, consistent grid for all slides in this day # cols, rows = compute_grid(max_imgs_per_slide) # cell_w = usable_w_in / cols # cell_h = usable_h_in / rows # image_h_ratio = 0.75 # img_area_h = cell_h * image_h_ratio # caption_h = cell_h * (1 - image_h_ratio) # idx = 0 # slide_index_for_day = 0 # while idx < total_imgs: # chunk = day_files[idx:idx + max_imgs_per_slide] # n_chunk = len(chunk) # slide = prs.slides.add_slide(prs.slide_layouts[6]) # title_suffix = "" if slide_index_for_day == 0 else f" (contd.)" # add_centered_title(slide, f"{day} — Treatment Images{title_suffix}", SLIDE_W_IN) # slide_index_for_day += 1 # for local_i, (treatment, file) in enumerate(chunk): # row = local_i // cols # col = local_i % cols # cell_left = LEFT_MARGIN_IN + col * cell_w # cell_top = TOP_MARGIN_IN + row * cell_h # suffix = os.path.splitext(file.name)[1] # with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp: # tmp.write(file.read()) # raw_path = tmp.name # cropped_path = crop_with_margin(raw_path, mode) # safe_path = normalize_image_for_ppt(cropped_path) # if not safe_path: # continue # try: # # Preserve aspect ratio and fit naturally # with Image.open(safe_path) as im: # w, h = im.size # img_ratio = w / h # box_ratio = cell_w / img_area_h # if img_ratio > box_ratio: # img_w = cell_w * 0.9 # img_h = img_w / img_ratio # else: # img_h = img_area_h * 0.9 # img_w = img_h * img_ratio # img_left = cell_left + (cell_w - img_w) / 2 # img_top = cell_top + (img_area_h - img_h) / 2 # slide.shapes.add_picture( # safe_path, # left=Inches(img_left), # top=Inches(img_top), # width=Inches(img_w), # height=Inches(img_h), # ) # # Caption (closer under image) # score = predict_infection_score(safe_path, mode) # caption_text = f"{treatment} — {day} | Score: {score}" # caption_top = cell_top + img_area_h + 0.003 # slightly closer gap # tx = slide.shapes.add_textbox( # Inches(cell_left), # Inches(caption_top), # Inches(cell_w), # Inches(caption_h), # ) # tf = tx.text_frame # tf.word_wrap = True # p = tf.paragraphs[0] # p.text = caption_text # p.alignment = PP_ALIGN.CENTER # p.font.size = Pt(base_font_size) # p.font.bold = True # p.font.color.rgb = RGBColor(0, 0, 0) # except Exception as e: # st.error(f"❌ Failed to add image '{safe_path}': {e}") # idx += max_imgs_per_slide # with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx: # prs.save(tmp_pptx.name) # st.success("✅ PowerPoint generated successfully") # st.download_button( # "⬇️ Download PowerPoint", # data=open(tmp_pptx.name, "rb").read(), # file_name="treatments_with_scores.pptx", # ) # st.success("✅ PowerPoint generated successfully — centered titles, perfect spacing, consistent sizing!") # import os # import tempfile # import math # import streamlit as st # from pptx import Presentation # from pptx.util import Inches, Pt # from pptx.dml.color import RGBColor # from pptx.enum.text import PP_ALIGN # from PIL import Image, ImageOps # from cropper import crop_with_yolo, predict_infection_score # # ───────────────────────────── # # Streamlit UI # # ───────────────────────────── # st.title("💊 Treatments → PowerPoint Generator with Infection Scores") # main_option = st.selectbox("Select Main Option", ["O", "V"]) # mode = "eye" if main_option == "O" else "vagina" # st.write(f"🧠 YOLO mode: {mode}") # num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1) # num_days = st.number_input("Enter number of days", 1, 10, 3, 1) # max_imgs_per_slide = st.number_input( # "Enter number of images per slide (up to 50)", 1, 50, 9, 1 # ) # treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)] # day_list = [f"Day {i+1}" for i in range(num_days)] # uploaded_files = {} # st.markdown("### 📁 Upload images for each Treatment and Day") # for treatment in treatment_list: # st.subheader(treatment) # uploaded_files[treatment] = {} # for day in day_list: # uploaded_files[treatment][day] = st.file_uploader( # f"Upload image(s) for {day}", # type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"], # accept_multiple_files=True, # key=f"{treatment}_{day}", # ) # SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"} # # ───────────────────────────── # # Helpers # # ───────────────────────────── # def normalize_image_for_ppt(path: str) -> str | None: # """Convert unsupported formats to PNG + fix EXIF rotation.""" # try: # with Image.open(path) as im: # fmt = (im.format or "").upper() # im = ImageOps.exif_transpose(im) # if fmt not in SUPPORTED_BY_PPTX: # im = im.convert("RGB") # out_path = os.path.splitext(path)[0] + "_clean.png" # im.save(out_path, "PNG") # return out_path # return path # except Exception as e: # st.error(f"❌ Could not normalize image '{path}': {e}") # return None # def crop_with_margin(image_path: str, mode: str) -> str: # """Use YOLO model for cropping (no extra PPT-side padding).""" # try: # cropped = crop_with_yolo(image_path, mode) # return cropped if cropped and os.path.exists(cropped) else image_path # except Exception as e: # st.error(f"❌ YOLO crop failed for {image_path}: {e}") # return image_path # def compute_grid(n: int) -> tuple[int, int]: # """Decide columns/rows so n images fit nicely.""" # cols = math.ceil(math.sqrt(n)) # rows = math.ceil(n / cols) # return cols, rows # def add_centered_title(slide, title_text: str): # """Add a perfectly centered title.""" # slide_width_in = slide.part.slide_layout.slide_master.part.slide_width / 914400 # title_box = slide.shapes.add_textbox( # Inches(0), # Inches(0.2), # Inches(slide_width_in), # Inches(0.8), # ) # tf = title_box.text_frame # tf.word_wrap = True # p = tf.paragraphs[0] # p.text = title_text # p.alignment = PP_ALIGN.CENTER # p.font.bold = True # p.font.size = Pt(24) # p.font.color.rgb = RGBColor(0, 0, 0) # def get_font_size(num_images: int) -> int: # """Dynamic caption font size.""" # if num_images <= 6: # return 12 # elif num_images <= 20: # return 10 # elif num_images <= 35: # return 8 # else: # return 7 # # ───────────────────────────── # # PowerPoint Generation # # ───────────────────────────── # if st.button("📊 Generate PowerPoint"): # prs = Presentation() # EMU_PER_INCH = 914400 # SLIDE_W_IN = prs.slide_width / EMU_PER_INCH # SLIDE_H_IN = prs.slide_height / EMU_PER_INCH # # Margins and layout constants # LEFT_MARGIN_IN = 0.5 # RIGHT_MARGIN_IN = 0.5 # TOP_MARGIN_IN = 1.0 # BOTTOM_MARGIN_IN = 0.5 # usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN # usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN # base_font_size = get_font_size(max_imgs_per_slide) # for day in day_list: # st.write(f"🖼️ Adding images for {day}...") # # Gather all uploaded files for this day # day_files = [] # for treatment in treatment_list: # files = uploaded_files[treatment][day] # if files: # for f in files: # day_files.append((treatment, f)) # total_imgs = len(day_files) # if total_imgs == 0: # continue # # Compute a single, consistent grid for all slides in this day # cols, rows = compute_grid(max_imgs_per_slide) # cell_w = usable_w_in / cols # cell_h = usable_h_in / rows # image_h_ratio = 0.75 # img_area_h = cell_h * image_h_ratio # caption_h = cell_h * (1 - image_h_ratio) # idx = 0 # slide_index_for_day = 0 # while idx < total_imgs: # chunk = day_files[idx:idx + max_imgs_per_slide] # n_chunk = len(chunk) # slide = prs.slides.add_slide(prs.slide_layouts[6]) # title_suffix = "" if slide_index_for_day == 0 else f" (contd.)" # add_centered_title(slide, f"{day} — Treatment Images{title_suffix}") # slide_index_for_day += 1 # for local_i, (treatment, file) in enumerate(chunk): # row = local_i // cols # col = local_i % cols # cell_left = LEFT_MARGIN_IN + col * cell_w # cell_top = TOP_MARGIN_IN + row * cell_h # suffix = os.path.splitext(file.name)[1] # with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp: # tmp.write(file.read()) # raw_path = tmp.name # cropped_path = crop_with_margin(raw_path, mode) # safe_path = normalize_image_for_ppt(cropped_path) # if not safe_path: # continue # try: # # Preserve aspect ratio # with Image.open(safe_path) as im: # w, h = im.size # img_ratio = w / h # box_ratio = cell_w / img_area_h # if img_ratio > box_ratio: # img_w = cell_w * 0.9 # img_h = img_w / img_ratio # else: # img_h = img_area_h * 0.9 # img_w = img_h * img_ratio # img_left = cell_left + (cell_w - img_w) / 2 # img_top = cell_top + (img_area_h - img_h) / 2 # slide.shapes.add_picture( # safe_path, # left=Inches(img_left), # top=Inches(img_top), # width=Inches(img_w), # height=Inches(img_h), # ) # # Caption (even closer) # score = predict_infection_score(safe_path, mode) # caption_text = f"{treatment} — {day} | Score: {score}" # caption_top = cell_top + img_area_h + 0.005 # closer spacing # tx = slide.shapes.add_textbox( # Inches(cell_left), # Inches(caption_top), # Inches(cell_w), # Inches(caption_h), # ) # tf = tx.text_frame # tf.word_wrap = True # p = tf.paragraphs[0] # p.text = caption_text # p.alignment = PP_ALIGN.CENTER # p.font.size = Pt(base_font_size) # p.font.bold = True # p.font.color.rgb = RGBColor(0, 0, 0) # except Exception as e: # st.error(f"❌ Failed to add image '{safe_path}': {e}") # idx += max_imgs_per_slide # with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx: # prs.save(tmp_pptx.name) # st.success("✅ PowerPoint generated successfully — centered titles and clean spacing!") # st.download_button( # "⬇️ Download PowerPoint", # data=open(tmp_pptx.name, "rb").read(), # file_name="treatments_with_scores.pptx", # ) # #no overlapping, all images in the PPT are of the same size # import os # import tempfile # import math # import streamlit as st # from pptx import Presentation # from pptx.util import Inches, Pt # from pptx.dml.color import RGBColor # from pptx.enum.text import PP_ALIGN # from PIL import Image, ImageOps # from cropper import crop_with_yolo, predict_infection_score # # ───────────────────────────── # # Streamlit UI # # ───────────────────────────── # st.title("💊 Treatments → PowerPoint Generator with Infection Scores") # main_option = st.selectbox("Select Main Option", ["O", "V"]) # mode = "eye" if main_option == "O" else "vagina" # st.write(f"🧠 YOLO mode: {mode}") # num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1) # num_days = st.number_input("Enter number of days", 1, 10, 3, 1) # max_imgs_per_slide = st.number_input( # "Enter number of images per slide (up to 50)", 1, 50, 9, 1 # ) # treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)] # day_list = [f"Day {i+1}" for i in range(num_days)] # uploaded_files = {} # st.markdown("### 📁 Upload images for each Treatment and Day") # for treatment in treatment_list: # st.subheader(treatment) # uploaded_files[treatment] = {} # for day in day_list: # uploaded_files[treatment][day] = st.file_uploader( # f"Upload image(s) for {day}", # type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"], # accept_multiple_files=True, # key=f"{treatment}_{day}", # ) # SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"} # # ───────────────────────────── # # Helpers # # ───────────────────────────── # def normalize_image_for_ppt(path: str) -> str | None: # """Convert unsupported formats to PNG + fix EXIF rotation.""" # try: # with Image.open(path) as im: # fmt = (im.format or "").upper() # im = ImageOps.exif_transpose(im) # if fmt not in SUPPORTED_BY_PPTX: # im = im.convert("RGB") # out_path = os.path.splitext(path)[0] + "_clean.png" # im.save(out_path, "PNG") # return out_path # return path # except Exception as e: # st.error(f"❌ Could not normalize image '{path}': {e}") # return None # def crop_with_margin(image_path: str, mode: str) -> str: # """Use YOLO model for cropping (no extra PPT-side padding).""" # try: # cropped = crop_with_yolo(image_path, mode) # return cropped if cropped and os.path.exists(cropped) else image_path # except Exception as e: # st.error(f"❌ YOLO crop failed for {image_path}: {e}") # return image_path # def compute_grid(n: int) -> tuple[int, int]: # """Decide columns/rows so n images fit nicely.""" # cols = math.ceil(math.sqrt(n)) # rows = math.ceil(n / cols) # return cols, rows # def add_centered_title(slide, title_text: str): # """Add a perfectly centered title.""" # title_box = slide.shapes.add_textbox(Inches(0), Inches(0.2), Inches(13.33), Inches(0.8)) # tf = title_box.text_frame # tf.word_wrap = True # p = tf.paragraphs[0] # p.text = title_text # p.alignment = PP_ALIGN.CENTER # p.font.bold = True # p.font.size = Pt(24) # p.font.color.rgb = RGBColor(0, 0, 0) # def get_font_size(num_images: int) -> int: # """Dynamic caption font size.""" # if num_images <= 6: # return 12 # elif num_images <= 20: # return 10 # elif num_images <= 35: # return 8 # else: # return 7 # # ───────────────────────────── # # PowerPoint Generation # # ───────────────────────────── # if st.button("📊 Generate PowerPoint"): # prs = Presentation() # EMU_PER_INCH = 914400 # SLIDE_W_IN = prs.slide_width / EMU_PER_INCH # SLIDE_H_IN = prs.slide_height / EMU_PER_INCH # # Margins and layout constants # LEFT_MARGIN_IN = 0.5 # RIGHT_MARGIN_IN = 0.5 # TOP_MARGIN_IN = 1.0 # BOTTOM_MARGIN_IN = 0.5 # usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN # usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN # base_font_size = get_font_size(max_imgs_per_slide) # for day in day_list: # st.write(f"🖼️ Adding images for {day}...") # # Gather all uploaded files for this day # day_files = [] # for treatment in treatment_list: # files = uploaded_files[treatment][day] # if files: # for f in files: # day_files.append((treatment, f)) # total_imgs = len(day_files) # if total_imgs == 0: # continue # # Compute a single, consistent grid for all slides in this day # cols, rows = compute_grid(max_imgs_per_slide) # cell_w = usable_w_in / cols # cell_h = usable_h_in / rows # image_h_ratio = 0.75 # img_area_h = cell_h * image_h_ratio # caption_h = cell_h * (1 - image_h_ratio) # idx = 0 # slide_index_for_day = 0 # while idx < total_imgs: # chunk = day_files[idx:idx + max_imgs_per_slide] # n_chunk = len(chunk) # slide = prs.slides.add_slide(prs.slide_layouts[6]) # title_suffix = "" if slide_index_for_day == 0 else f" (contd.)" # add_centered_title(slide, f"{day} — Treatment Images{title_suffix}") # slide_index_for_day += 1 # for local_i, (treatment, file) in enumerate(chunk): # row = local_i // cols # col = local_i % cols # cell_left = LEFT_MARGIN_IN + col * cell_w # cell_top = TOP_MARGIN_IN + row * cell_h # suffix = os.path.splitext(file.name)[1] # with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp: # tmp.write(file.read()) # raw_path = tmp.name # cropped_path = crop_with_margin(raw_path, mode) # safe_path = normalize_image_for_ppt(cropped_path) # if not safe_path: # continue # try: # # Preserve aspect ratio # with Image.open(safe_path) as im: # w, h = im.size # img_ratio = w / h # box_ratio = cell_w / img_area_h # if img_ratio > box_ratio: # img_w = cell_w * 0.9 # img_h = img_w / img_ratio # else: # img_h = img_area_h * 0.9 # img_w = img_h * img_ratio # img_left = cell_left + (cell_w - img_w) / 2 # img_top = cell_top + (img_area_h - img_h) / 2 # slide.shapes.add_picture( # safe_path, # left=Inches(img_left), # top=Inches(img_top), # width=Inches(img_w), # height=Inches(img_h), # ) # # Caption (separate zone) # score = predict_infection_score(safe_path, mode) # caption_text = f"{treatment} — {day} | Score: {score}" # caption_top = cell_top + img_area_h + 0.03 # tx = slide.shapes.add_textbox( # Inches(cell_left), # Inches(caption_top), # Inches(cell_w), # Inches(caption_h), # ) # tf = tx.text_frame # tf.word_wrap = True # p = tf.paragraphs[0] # p.text = caption_text # p.alignment = PP_ALIGN.CENTER # p.font.size = Pt(base_font_size) # p.font.bold = True # p.font.color.rgb = RGBColor(0, 0, 0) # except Exception as e: # st.error(f"❌ Failed to add image '{safe_path}': {e}") # idx += max_imgs_per_slide # with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx: # prs.save(tmp_pptx.name) # st.success("✅ PowerPoint generated successfully — consistent size & centered titles!") # st.download_button( # "⬇️ Download PowerPoint", # data=open(tmp_pptx.name, "rb").read(), # file_name="treatments_with_scores.pptx", # ) # #was trying # # #Works pretty good, no overlapping # import os # import tempfile # import math # import streamlit as st # from pptx import Presentation # from pptx.util import Inches, Pt # from pptx.dml.color import RGBColor # from pptx.enum.text import PP_ALIGN # from PIL import Image, ImageOps # from cropper import crop_with_yolo, predict_infection_score # # ───────────────────────────── # # Streamlit UI # # ───────────────────────────── # st.title("💊 Treatments → PowerPoint Generator with Infection Scores") # main_option = st.selectbox("Select Main Option", ["O", "V"]) # mode = "eye" if main_option == "O" else "vagina" # st.write(f"🧠 YOLO mode: {mode}") # num_treatments = st.number_input("Enter number of treatments", 1, 10, 3, 1) # num_days = st.number_input("Enter number of days", 1, 10, 3, 1) # max_imgs_per_slide = st.number_input( # "Enter number of images per slide (up to 50)", 1, 50, 6, 1 # ) # treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)] # day_list = [f"Day {i+1}" for i in range(num_days)] # uploaded_files = {} # st.markdown("### 📁 Upload images for each Treatment and Day") # for treatment in treatment_list: # st.subheader(treatment) # uploaded_files[treatment] = {} # for day in day_list: # uploaded_files[treatment][day] = st.file_uploader( # f"Upload image(s) for {day}", # type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"], # accept_multiple_files=True, # key=f"{treatment}_{day}", # ) # SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"} # # ───────────────────────────── # # Helpers # # ───────────────────────────── # def normalize_image_for_ppt(path: str) -> str | None: # """Convert unsupported formats to PNG + fix EXIF rotation.""" # try: # with Image.open(path) as im: # fmt = (im.format or "").upper() # im = ImageOps.exif_transpose(im) # if fmt not in SUPPORTED_BY_PPTX: # im = im.convert("RGB") # out_path = os.path.splitext(path)[0] + "_clean.png" # im.save(out_path, "PNG") # return out_path # return path # except Exception as e: # st.error(f"❌ Could not normalize image '{path}': {e}") # return None # def crop_with_margin(image_path: str, mode: str) -> str: # """Use YOLO model for cropping (no extra PPT-side padding).""" # try: # cropped = crop_with_yolo(image_path, mode) # return cropped if cropped and os.path.exists(cropped) else image_path # except Exception as e: # st.error(f"❌ YOLO crop failed for {image_path}: {e}") # return image_path # def compute_grid(n: int) -> tuple[int, int]: # """Decide columns/rows so n images fit nicely.""" # cols = math.ceil(math.sqrt(n)) # rows = math.ceil(n / cols) # return cols, rows # def add_slide_title(slide, title_text: str): # """Add a centered title at the top of the slide.""" # title_box = slide.shapes.add_textbox(Inches(0.3), Inches(0.1), Inches(12), Inches(0.6)) # tf = title_box.text_frame # tf.word_wrap = True # p = tf.paragraphs[0] # p.text = title_text # p.alignment = PP_ALIGN.CENTER # p.font.bold = True # p.font.size = Pt(20) # p.font.color.rgb = RGBColor(0, 0, 0) # def get_font_size(num_images: int) -> int: # if num_images <= 6: # return 12 # elif num_images <= 20: # return 10 # elif num_images <= 35: # return 8 # else: # return 7 # # ───────────────────────────── # # PowerPoint Generation # # ───────────────────────────── # if st.button("📊 Generate PowerPoint"): # prs = Presentation() # EMU_PER_INCH = 914400 # SLIDE_W_IN = prs.slide_width / EMU_PER_INCH # SLIDE_H_IN = prs.slide_height / EMU_PER_INCH # LEFT_MARGIN_IN = 0.5 # RIGHT_MARGIN_IN = 0.5 # TOP_MARGIN_IN = 1.0 # BOTTOM_MARGIN_IN = 0.5 # usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN # usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN # base_font_size = get_font_size(max_imgs_per_slide) # for day in day_list: # st.write(f"🖼️ Adding images for {day}...") # # Collect all images of this day # day_files = [] # for treatment in treatment_list: # files = uploaded_files[treatment][day] # if files: # for f in files: # day_files.append((treatment, f)) # total_imgs = len(day_files) # if total_imgs == 0: # continue # idx = 0 # slide_index_for_day = 0 # while idx < total_imgs: # chunk = day_files[idx:idx + max_imgs_per_slide] # n_chunk = len(chunk) # slide = prs.slides.add_slide(prs.slide_layouts[6]) # title_suffix = "" if slide_index_for_day == 0 else " (contd.)" # add_slide_title(slide, f"{day} — Treatment Images{title_suffix}") # slide_index_for_day += 1 # # Compute grid # cols, rows = compute_grid(n_chunk) # cell_w = usable_w_in / cols # cell_h = usable_h_in / rows # # Image and caption spacing constants # image_h_ratio = 0.75 # 75% image, 25% caption zone per cell # img_area_h = cell_h * image_h_ratio # caption_h = cell_h * (1 - image_h_ratio) # for local_i, (treatment, file) in enumerate(chunk): # row = local_i // cols # col = local_i % cols # cell_left = LEFT_MARGIN_IN + col * cell_w # cell_top = TOP_MARGIN_IN + row * cell_h # suffix = os.path.splitext(file.name)[1] # with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp: # tmp.write(file.read()) # raw_path = tmp.name # cropped_path = crop_with_margin(raw_path, mode) # safe_path = normalize_image_for_ppt(cropped_path) # if not safe_path: # continue # try: # # Preserve image ratio — scale to fit inside its image zone # with Image.open(safe_path) as im: # w, h = im.size # img_ratio = w / h # box_ratio = cell_w / img_area_h # if img_ratio > box_ratio: # img_w = cell_w * 0.9 # img_h = img_w / img_ratio # else: # img_h = img_area_h * 0.9 # img_w = img_h * img_ratio # img_left = cell_left + (cell_w - img_w) / 2 # img_top = cell_top + (img_area_h - img_h) / 2 # slide.shapes.add_picture( # safe_path, # left=Inches(img_left), # top=Inches(img_top), # width=Inches(img_w), # height=Inches(img_h), # ) # # Caption — completely separate vertical zone # score = predict_infection_score(safe_path, mode) # caption_text = f"{treatment} — {day} | Score: {score}" # caption_top = cell_top + img_area_h + 0.02 # tx = slide.shapes.add_textbox( # Inches(cell_left), # Inches(caption_top), # Inches(cell_w), # Inches(caption_h), # ) # tf = tx.text_frame # tf.word_wrap = True # p = tf.paragraphs[0] # p.text = caption_text # p.alignment = PP_ALIGN.CENTER # p.font.size = Pt(base_font_size) # p.font.bold = True # p.font.color.rgb = RGBColor(0, 0, 0) # except Exception as e: # st.error(f"❌ Failed to add image '{safe_path}': {e}") # idx += max_imgs_per_slide # with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx: # prs.save(tmp_pptx.name) # st.success("✅ PowerPoint generated successfully — no overlaps, consistent spacing!") # st.download_button( # "⬇️ Download PowerPoint", # data=open(tmp_pptx.name, "rb").read(), # file_name="treatments_with_scores.pptx", # )