Pradnya99 commited on
Commit
096ba00
Β·
verified Β·
1 Parent(s): 106347f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -60
app.py CHANGED
@@ -21,20 +21,22 @@ 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("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,124 +48,197 @@ SUPPORTED_BY_PPTX = {"BMP", "GIF", "JPEG", "PNG", "TIFF", "WMF"}
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
 
169
  # #First deployed
 
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}",
 
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
 
244
  # #First deployed