Pradnya99 commited on
Commit
106347f
Β·
verified Β·
1 Parent(s): 3d7c423

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -109
app.py CHANGED
@@ -21,22 +21,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
 
28
  treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)]
29
  day_list = [f"Day {i+1}" for i in range(num_days)]
30
 
31
  uploaded_files = {}
32
- st.markdown("### πŸ“ Upload images for each Treatment and Day")
33
 
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}",
@@ -48,177 +46,123 @@ SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"}
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
- """Crop using YOLO with your logic."""
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
  cols = math.ceil(math.sqrt(n))
80
  rows = math.ceil(n / cols)
81
  return cols, rows
82
 
83
 
84
- def add_centered_title(slide, title_text: str, slide_width_in: float):
85
- title_box = slide.shapes.add_textbox(
86
- Inches(0),
87
- Inches(0.2),
88
- Inches(slide_width_in),
89
- Inches(0.8),
90
- )
91
- tf = title_box.text_frame
92
- p = tf.paragraphs[0]
93
- p.text = title_text
94
- p.alignment = PP_ALIGN.CENTER
95
- p.font.bold = True
96
- p.font.size = Pt(24)
97
- p.font.color.rgb = RGBColor(0, 0, 0)
98
-
99
-
100
- def get_font_size(num_images: int) -> int:
101
- if num_images <= 6:
102
- return 12
103
- elif num_images <= 20:
104
- return 10
105
- elif num_images <= 35:
106
- return 8
107
- else:
108
- return 7
109
-
110
-
111
  # ─────────────────────────────
112
- # PowerPoint Generation
113
  # ─────────────────────────────
114
  if st.button("πŸ“Š Generate PowerPoint"):
115
  prs = Presentation()
116
- EMU_PER_INCH = 914400
117
- SLIDE_W_IN = prs.slide_width / EMU_PER_INCH
118
- SLIDE_H_IN = prs.slide_height / EMU_PER_INCH
119
 
120
- LEFT_MARGIN_IN = 0.5
121
- RIGHT_MARGIN_IN = 0.5
122
- TOP_MARGIN_IN = 1.0
123
- BOTTOM_MARGIN_IN = 0.5
124
 
125
- usable_w_in = SLIDE_W_IN - LEFT_MARGIN_IN - RIGHT_MARGIN_IN
126
- usable_h_in = SLIDE_H_IN - TOP_MARGIN_IN - BOTTOM_MARGIN_IN
 
 
127
 
128
- base_font_size = get_font_size(max_imgs_per_slide)
 
129
 
130
- for day in day_list:
131
- st.write(f"πŸ–ΌοΈ Adding images for {day}...")
132
 
 
133
  day_files = []
134
- for treatment in treatment_list:
135
- files = uploaded_files[treatment][day]
136
  if files:
137
  for f in files:
138
- day_files.append((treatment, f))
139
 
140
- total_imgs = len(day_files)
141
- if total_imgs == 0:
142
  continue
143
 
144
  cols, rows = compute_grid(max_imgs_per_slide)
145
- cell_w = usable_w_in / cols
146
- cell_h = usable_h_in / rows
147
 
148
- image_h_ratio = 0.75
149
- img_area_h = cell_h * image_h_ratio
150
- caption_h = cell_h * (1 - image_h_ratio)
 
 
151
 
152
  idx = 0
153
- slide_index_for_day = 0
154
 
155
- while idx < total_imgs:
156
  chunk = day_files[idx:idx + max_imgs_per_slide]
157
 
158
  slide = prs.slides.add_slide(prs.slide_layouts[6])
159
- title_suffix = "" if slide_index_for_day == 0 else " (contd.)"
160
- add_centered_title(slide, f"{day} β€” Treatment Images{title_suffix}", SLIDE_W_IN)
161
- slide_index_for_day += 1
162
 
163
  for local_i, (treatment, file) in enumerate(chunk):
164
  row = local_i // cols
165
  col = local_i % cols
166
 
167
- cell_left = LEFT_MARGIN_IN + col * cell_w
168
- cell_top = TOP_MARGIN_IN + row * cell_h
169
 
170
- suffix = os.path.splitext(file.name)[1]
171
- with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
172
  tmp.write(file.read())
173
  raw_path = tmp.name
174
 
175
- cropped_path = crop_with_margin(raw_path, mode)
176
- safe_path = normalize_image_for_ppt(cropped_path)
177
- if not safe_path:
178
- continue
179
 
180
- try:
181
- # ALWAYS preserve aspect ratio β†’ remove height
182
- img_w = cell_w * 0.9 # consistent WIDTH
183
- img_left = cell_left + (cell_w - img_w) / 2
184
- img_top = cell_top + (img_area_h - img_area_h * 0.9) / 2
185
 
 
186
  pic = slide.shapes.add_picture(
187
- safe_path,
188
  left=Inches(img_left),
189
- top=Inches(img_top),
190
- width=Inches(img_w) # Height auto-calculated = no stretching
191
  )
192
 
193
- # Caption
194
- score = predict_infection_score(safe_path, mode)
195
- caption_text = f"{treatment} β€” {day} | Score: {score}"
196
 
197
  tx = slide.shapes.add_textbox(
198
  Inches(cell_left),
199
- Inches(cell_top + img_area_h + 0.02),
200
  Inches(cell_w),
201
- Inches(caption_h),
202
  )
203
  p = tx.text_frame.paragraphs[0]
204
- p.text = caption_text
205
- p.alignment = PP_ALIGN.CENTER
206
- p.font.size = Pt(base_font_size)
207
  p.font.bold = True
 
 
208
 
209
  except Exception as e:
210
- st.error(f"❌ Failed to add image '{safe_path}': {e}")
211
 
212
  idx += max_imgs_per_slide
213
 
214
  with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx:
215
  prs.save(tmp_pptx.name)
216
- st.success("βœ… PowerPoint generated successfully")
217
- st.download_button(
218
- "⬇️ Download PowerPoint",
219
- data=open(tmp_pptx.name, "rb").read(),
220
- file_name="treatments_with_scores.pptx",
221
- )
222
 
223
 
224
 
 
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("Enter number of images per slide", 1, 50, 9, 1)
 
 
25
 
26
  treatment_list = [f"Treatment {i+1}" for i in range(num_treatments)]
27
  day_list = [f"Day {i+1}" for i in range(num_days)]
28
 
29
  uploaded_files = {}
30
+ st.markdown("### πŸ“ Upload images")
31
 
32
  for treatment in treatment_list:
33
  st.subheader(treatment)
34
  uploaded_files[treatment] = {}
35
  for day in day_list:
36
  uploaded_files[treatment][day] = st.file_uploader(
37
+ f"Upload for {day}",
38
  type=["jpg", "jpeg", "png", "tiff", "bmp", "gif", "mpo"],
39
  accept_multiple_files=True,
40
  key=f"{treatment}_{day}",
 
46
  # ─────────────────────────────
47
  # Helpers
48
  # ─────────────────────────────
49
+ def normalize_image_for_ppt(path):
 
50
  try:
51
  with Image.open(path) as im:
52
  fmt = (im.format or "").upper()
53
  im = ImageOps.exif_transpose(im)
54
  if fmt not in SUPPORTED_BY_PPTX:
 
55
  out_path = os.path.splitext(path)[0] + "_clean.png"
56
+ im.convert("RGB").save(out_path, "PNG")
57
  return out_path
58
  return path
59
+ except:
60
+ return path
 
61
 
62
 
63
+ def compute_grid(n):
 
 
 
 
 
 
 
 
 
 
64
  cols = math.ceil(math.sqrt(n))
65
  rows = math.ceil(n / cols)
66
  return cols, rows
67
 
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  # ─────────────────────────────
70
+ # PPT Generation
71
  # ─────────────────────────────
72
  if st.button("πŸ“Š Generate PowerPoint"):
73
  prs = Presentation()
 
 
 
74
 
75
+ EMU = 914400
76
+ SLIDE_W = prs.slide_width / EMU
77
+ SLIDE_H = prs.slide_height / EMU
 
78
 
79
+ LEFT = 0.5
80
+ RIGHT = 0.5
81
+ TOP = 1.0
82
+ BOTTOM = 0.5
83
 
84
+ usable_w = SLIDE_W - LEFT - RIGHT
85
+ usable_h = SLIDE_H - TOP - BOTTOM
86
 
87
+ base_font_size = 10
 
88
 
89
+ for day in day_list:
90
  day_files = []
91
+ for t in treatment_list:
92
+ files = uploaded_files[t][day]
93
  if files:
94
  for f in files:
95
+ day_files.append((t, f))
96
 
97
+ if not day_files:
 
98
  continue
99
 
100
  cols, rows = compute_grid(max_imgs_per_slide)
 
 
101
 
102
+ cell_w = usable_w / cols
103
+ cell_h = usable_h / rows
104
+
105
+ img_area_h = cell_h * 0.75
106
+ caption_h = cell_h * 0.25
107
 
108
  idx = 0
109
+ slide_no = 0
110
 
111
+ while idx < len(day_files):
112
  chunk = day_files[idx:idx + max_imgs_per_slide]
113
 
114
  slide = prs.slides.add_slide(prs.slide_layouts[6])
115
+ slide_no += 1
 
 
116
 
117
  for local_i, (treatment, file) in enumerate(chunk):
118
  row = local_i // cols
119
  col = local_i % cols
120
 
121
+ cell_left = LEFT + col * cell_w
122
+ cell_top = TOP + row * cell_h
123
 
124
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.name)[1]) as tmp:
 
125
  tmp.write(file.read())
126
  raw_path = tmp.name
127
 
128
+ cropped = crop_with_yolo(raw_path, mode)
129
+ safe = normalize_image_for_ppt(cropped)
 
 
130
 
131
+ # FIX: width only β†’ height auto-calculated β†’ NO stretching
132
+ img_w = cell_w * 0.9
133
+ img_left = cell_left + (cell_w - img_w) / 2
 
 
134
 
135
+ try:
136
  pic = slide.shapes.add_picture(
137
+ safe,
138
  left=Inches(img_left),
139
+ top=Inches(cell_top),
140
+ width=Inches(img_w)
141
  )
142
 
143
+ score = predict_infection_score(safe, mode)
 
 
144
 
145
  tx = slide.shapes.add_textbox(
146
  Inches(cell_left),
147
+ Inches(cell_top + img_area_h),
148
  Inches(cell_w),
149
+ Inches(caption_h)
150
  )
151
  p = tx.text_frame.paragraphs[0]
152
+ p.text = f"{treatment} β€” {day} | Score: {score}"
 
 
153
  p.font.bold = True
154
+ p.font.size = Pt(base_font_size)
155
+ p.alignment = PP_ALIGN.CENTER
156
 
157
  except Exception as e:
158
+ st.error(f"Error adding image: {e}")
159
 
160
  idx += max_imgs_per_slide
161
 
162
  with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as tmp_pptx:
163
  prs.save(tmp_pptx.name)
164
+ st.success("βœ” PPT ready")
165
+ st.download_button("⬇ Download", data=open(tmp_pptx.name, "rb").read(), file_name="treatments_with_scores.pptx")
 
 
 
 
166
 
167
 
168