Gnanashri Kota Venkatesh commited on
Commit
a2adcd6
ยท
unverified ยท
1 Parent(s): ec9f9ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1054 -73
app.py CHANGED
@@ -1,17 +1,22 @@
1
  import os
 
2
  import tempfile
3
  import zipfile
4
  import streamlit as st
 
 
5
  from reportlab.lib.pagesizes import A4
6
  from reportlab.platypus import (
7
- SimpleDocTemplate, Table, TableStyle, Image, Paragraph, Spacer, PageBreak
8
  )
9
  from reportlab.lib.styles import getSampleStyleSheet
10
  from reportlab.lib import colors
11
  from PIL import Image as PILImage
12
  import io
13
- from pathlib import Path
14
  import shutil
 
 
 
15
 
16
  # Configure Streamlit page
17
  st.set_page_config(
@@ -20,18 +25,17 @@ st.set_page_config(
20
  layout="wide"
21
  )
22
 
23
- # Definierte Dateitypen
24
  ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'}
25
  ALLOWED_TEXT_EXTENSIONS = {'.txt', '.md', '.csv'}
26
  ALL_ALLOWED_EXTENSIONS = ALLOWED_IMAGE_EXTENSIONS.union(ALLOWED_TEXT_EXTENSIONS)
27
 
 
28
  def extract_zip_to_temp(uploaded_file):
29
  """Extract uploaded zip file to temporary directory"""
30
  temp_dir = tempfile.mkdtemp()
31
-
32
  with zipfile.ZipFile(uploaded_file, 'r') as zip_ref:
33
  zip_ref.extractall(temp_dir)
34
-
35
  return temp_dir
36
 
37
  def extract_images_from_xlsx(xlsx_file, output_dir):
@@ -56,8 +60,13 @@ def extract_images_from_xlsx(xlsx_file, output_dir):
56
  except Exception as e:
57
  return 0, [], str(e)
58
 
 
 
 
 
 
59
  def erkenne_marken_aus_ordnern(input_folder):
60
- """Recognize brands from subfolders"""
61
  try:
62
  return sorted([
63
  f for f in os.listdir(input_folder)
@@ -68,7 +77,7 @@ def erkenne_marken_aus_ordnern(input_folder):
68
  return []
69
 
70
  def get_files_by_marke(input_folder, marken):
71
- """Get files per brand"""
72
  spalteninhalte = {marke: [] for marke in marken}
73
 
74
  for marke in marken:
@@ -87,8 +96,45 @@ def get_files_by_marke(input_folder, marken):
87
 
88
  return spalteninhalte
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  def build_marken_einzelseiten(alle_dateien_pro_marke, styles, gesamtbreite):
91
- """Build individual brand overview pages"""
92
  elements = []
93
  max_bildhoehe = 100
94
 
@@ -120,12 +166,12 @@ def build_marken_einzelseiten(alle_dateien_pro_marke, styles, gesamtbreite):
120
  new_height = min(new_width * aspect, max_bildhoehe)
121
  new_width = new_height / aspect
122
 
123
- img = Image(file_path, width=new_width, height=new_height)
124
  cell = [img, Spacer(1, 4), Paragraph(filename, styles['Normal'])]
125
  except Exception as e:
126
- cell = Paragraph(f"๐Ÿ“„ {filename} (Error loading image)", styles['Normal'])
127
  else:
128
- cell = Paragraph(f"๐Ÿ“„ {filename}", styles['Normal'])
129
 
130
  row_data.append(cell)
131
  if len(row_data) == 3:
@@ -150,8 +196,75 @@ def build_marken_einzelseiten(alle_dateien_pro_marke, styles, gesamtbreite):
150
 
151
  return elements
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  def generate_pdf_report(input_folder, erste_marke=None):
154
- """Generate the complete PDF report"""
155
  styles = getSampleStyleSheet()
156
  gesamtbreite = 480
157
 
@@ -193,15 +306,118 @@ def generate_pdf_report(input_folder, erste_marke=None):
193
  except Exception as e:
194
  return None, f"Error generating PDF: {str(e)}"
195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  def pdf_generator_tool():
197
- st.header("๐Ÿ“Š Brand Assets PDF Generator")
198
- st.markdown("Upload a zip file containing brand folders with assets to generate a comprehensive PDF report.")
 
 
 
 
 
 
 
199
 
200
  # File upload
201
  uploaded_file = st.file_uploader(
202
  "Choose a ZIP file",
203
  type=['zip'],
204
- help="Upload a zip file containing folders named after your brands, with assets inside each folder.",
205
  key="pdf_zip_upload"
206
  )
207
 
@@ -217,72 +433,119 @@ def pdf_generator_tool():
217
  if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
218
  input_folder = os.path.join(temp_dir, items[0])
219
 
220
- # Recognize brands
221
- marken = erkenne_marken_aus_ordnern(input_folder)
222
-
223
- if not marken:
224
- st.error("โŒ No brand folders found in the uploaded zip file.")
225
- st.info("Make sure your zip file contains folders named after your brands, with assets inside each folder.")
226
- return
227
-
228
- st.success(f"๐Ÿ” Found brands: {', '.join(marken)}")
229
-
230
- # Get file counts for processing
231
- dateien_pro_marke = get_files_by_marke(input_folder, marken)
232
-
233
- # Options
234
- erste_marke = st.selectbox(
235
- "Which brand should appear first in the overview?",
236
- options=["Alphabetical order"] + marken
237
- )
238
- erste_marke = erste_marke if erste_marke != "Alphabetical order" else None
239
-
240
- # Generate PDF button
241
- if st.button("๐ŸŽฏ Generate PDF Report", type="primary"):
242
- with st.spinner("Generating PDF report..."):
243
- pdf_buffer, error = generate_pdf_report(input_folder, erste_marke)
244
 
245
- if error:
246
- st.error(f"โŒ {error}")
247
- elif pdf_buffer:
248
- st.success("โœ… PDF report generated successfully!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
 
250
- # Download button
251
- st.download_button(
252
- label="๐Ÿ“ฅ Download PDF Report",
253
- data=pdf_buffer.getvalue(),
254
- file_name="Brand_Assets_Report.pdf",
255
- mime="application/pdf"
256
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
  except zipfile.BadZipFile:
259
- st.error("โŒ Invalid zip file. Please upload a valid zip file.")
260
  except Exception as e:
261
- st.error(f"โŒ An error occurred: {str(e)}")
262
 
263
  else:
264
  st.info("๐Ÿ‘† Please upload a zip file to get started.")
265
 
266
- # Instructions for PDF generator
267
- with st.expander("๐Ÿ“– Instructions for PDF Generator"):
268
  st.markdown("""
269
  **How to use this tool:**
270
 
271
- 1. **Prepare your zip file:**
272
- - Create folders named after your brands
273
- - Place brand assets (images, text files) inside each brand folder
274
- - Zip the entire structure
275
 
276
- 2. **Supported file types:**
277
- - **Images:** JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP
278
- - **Text files:** TXT, MD, CSV
279
-
280
 
281
- 3. **Upload and generate your PDF report!**
 
 
282
  """)
283
 
284
  def excel_extractor_tool():
285
- st.header("๐Ÿ–ผ๏ธ Excel Image Extractor")
286
  st.markdown("Upload Excel files (.xlsx) to extract embedded images from them.")
287
 
288
  # File upload for Excel files
@@ -295,7 +558,7 @@ def excel_extractor_tool():
295
  )
296
 
297
  if uploaded_files:
298
- if st.button("๐Ÿ” Extract Images", type="primary", key="extract_btn"):
299
  temp_dir = tempfile.mkdtemp()
300
  all_extracted_files = []
301
  total_images = 0
@@ -320,19 +583,19 @@ def excel_extractor_tool():
320
  count, extracted_files, error = extract_images_from_xlsx(temp_xlsx_path, output_dir)
321
 
322
  if error:
323
- st.error(f"โŒ Error processing {uploaded_file.name}: {error}")
324
  elif count > 0:
325
- st.success(f"โœ… Extracted {count} image(s) from {uploaded_file.name}")
326
  all_extracted_files.extend(extracted_files)
327
  total_images += count
328
  else:
329
- st.warning(f"โš ๏ธ No images found in {uploaded_file.name}")
330
 
331
  status_text.empty()
332
  progress_bar.empty()
333
 
334
  if total_images > 0:
335
- st.success(f"๐ŸŽ‰ Total: {total_images} images extracted from {len(uploaded_files)} file(s)")
336
 
337
  # Create zip file with all extracted images
338
  zip_buffer = io.BytesIO()
@@ -346,14 +609,14 @@ def excel_extractor_tool():
346
 
347
  # Download button for all extracted images
348
  st.download_button(
349
- label="๐Ÿ“ฅ Download All Extracted Images (ZIP)",
350
  data=zip_buffer.getvalue(),
351
  file_name="extracted_images.zip",
352
  mime="application/zip"
353
  )
354
 
355
  # Show preview of extracted images
356
- with st.expander("๐Ÿ–ผ๏ธ Preview Extracted Images"):
357
  cols = st.columns(3)
358
  col_idx = 0
359
 
@@ -361,7 +624,7 @@ def excel_extractor_tool():
361
  try:
362
  with cols[col_idx % 3]:
363
  img = PILImage.open(file_path)
364
- st.image(img, caption=os.path.basename(file_path), use_column_width=True)
365
  col_idx += 1
366
  except Exception as e:
367
  st.write(f"Could not preview {os.path.basename(file_path)}")
@@ -391,20 +654,738 @@ def excel_extractor_tool():
391
  - Common image formats (PNG, JPG, etc.) are extracted
392
  """)
393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394
  def main():
395
  st.title("๐Ÿ”ง Brand Assets Tools")
396
 
397
- tab1, tab2 = st.tabs(["๐Ÿ“Š PDF Report Generator", "๐Ÿ–ผ๏ธ Excel Image Extractor"])
398
 
399
  with tab1:
400
  pdf_generator_tool()
401
  with tab2:
402
  excel_extractor_tool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
 
 
 
406
 
 
 
 
 
 
 
 
 
 
407
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
408
 
409
  if __name__ == "__main__":
410
  main()
 
1
  import os
2
+ import re
3
  import tempfile
4
  import zipfile
5
  import streamlit as st
6
+ from pathlib import Path
7
+ from collections import defaultdict
8
  from reportlab.lib.pagesizes import A4
9
  from reportlab.platypus import (
10
+ SimpleDocTemplate, Table, TableStyle, Image as RLImage, Paragraph, Spacer, PageBreak, KeepInFrame
11
  )
12
  from reportlab.lib.styles import getSampleStyleSheet
13
  from reportlab.lib import colors
14
  from PIL import Image as PILImage
15
  import io
 
16
  import shutil
17
+ import cv2
18
+ import pandas as pd
19
+ import numpy as np
20
 
21
  # Configure Streamlit page
22
  st.set_page_config(
 
25
  layout="wide"
26
  )
27
 
28
+ # Defined file types
29
  ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'}
30
  ALLOWED_TEXT_EXTENSIONS = {'.txt', '.md', '.csv'}
31
  ALL_ALLOWED_EXTENSIONS = ALLOWED_IMAGE_EXTENSIONS.union(ALLOWED_TEXT_EXTENSIONS)
32
 
33
+ # Helper functions from both files
34
  def extract_zip_to_temp(uploaded_file):
35
  """Extract uploaded zip file to temporary directory"""
36
  temp_dir = tempfile.mkdtemp()
 
37
  with zipfile.ZipFile(uploaded_file, 'r') as zip_ref:
38
  zip_ref.extractall(temp_dir)
 
39
  return temp_dir
40
 
41
  def extract_images_from_xlsx(xlsx_file, output_dir):
 
60
  except Exception as e:
61
  return 0, [], str(e)
62
 
63
+ def extract_brand(file_stem):
64
+ """Extract brand name from filename using pattern matching"""
65
+ parts = re.split(r'[ _\-]', file_stem)
66
+ return re.sub(r'[^a-z0-9]', '', parts[0].lower()) if parts else "unknown"
67
+
68
  def erkenne_marken_aus_ordnern(input_folder):
69
+ """Recognize brands from subfolders (original method)"""
70
  try:
71
  return sorted([
72
  f for f in os.listdir(input_folder)
 
77
  return []
78
 
79
  def get_files_by_marke(input_folder, marken):
80
+ """Get files per brand from folders"""
81
  spalteninhalte = {marke: [] for marke in marken}
82
 
83
  for marke in marken:
 
96
 
97
  return spalteninhalte
98
 
99
+ def get_asset_cell(file_path, filename, col_count):
100
+ """Create optimized asset cell for PDF with better image handling"""
101
+ ext = Path(file_path).suffix.lower()
102
+ styles = getSampleStyleSheet()
103
+
104
+ try:
105
+ if ext in ALLOWED_IMAGE_EXTENSIONS:
106
+ with PILImage.open(file_path) as img:
107
+ orig_width, orig_height = img.size
108
+ available_width = A4[0] - 40
109
+ max_width = available_width / col_count
110
+ max_height = 120
111
+
112
+ aspect_ratio = orig_width / orig_height
113
+ width = max_width
114
+ height = width / aspect_ratio
115
+
116
+ if height > max_height:
117
+ height = max_height
118
+ width = height * aspect_ratio
119
+
120
+ buffer = io.BytesIO()
121
+ img.convert("RGB").save(buffer, format='PNG')
122
+ buffer.seek(0)
123
+ rl_img = RLImage(buffer, width=width, height=height)
124
+
125
+ frame = KeepInFrame(max_width, max_height + 30, content=[
126
+ rl_img,
127
+ Paragraph(filename, styles['Normal'])
128
+ ], hAlign='CENTER')
129
+
130
+ return frame
131
+ else:
132
+ return Paragraph(f"{filename}", styles['Normal'])
133
+ except Exception as e:
134
+ return Paragraph(f"[Image Error]<br/>{filename}", styles['Normal'])
135
+
136
  def build_marken_einzelseiten(alle_dateien_pro_marke, styles, gesamtbreite):
137
+ """Build individual brand overview pages (original method)"""
138
  elements = []
139
  max_bildhoehe = 100
140
 
 
166
  new_height = min(new_width * aspect, max_bildhoehe)
167
  new_width = new_height / aspect
168
 
169
+ img = RLImage(file_path, width=new_width, height=new_height)
170
  cell = [img, Spacer(1, 4), Paragraph(filename, styles['Normal'])]
171
  except Exception as e:
172
+ cell = Paragraph(f"{filename} (Error loading image)", styles['Normal'])
173
  else:
174
+ cell = Paragraph(f"{filename}", styles['Normal'])
175
 
176
  row_data.append(cell)
177
  if len(row_data) == 3:
 
196
 
197
  return elements
198
 
199
+ def add_brand_pages(elements, marken_spalten, renamed_files_by_folder_and_marke):
200
+ """Add brand overview pages with optimized layout"""
201
+ styles = getSampleStyleSheet()
202
+ for nummer, marke in marken_spalten:
203
+ assets = []
204
+ for folder in renamed_files_by_folder_and_marke:
205
+ assets.extend(renamed_files_by_folder_and_marke[folder].get(marke, []))
206
+
207
+ if not assets:
208
+ continue
209
+
210
+ elements.append(PageBreak())
211
+ elements.append(Paragraph(f"<b>Brand Overview: {nummer} โ€“ {marke}</b>", styles['Heading2']))
212
+ elements.append(Spacer(1, 6))
213
+ elements.append(Paragraph(f"Number of assets: {len(assets)}", styles['Normal']))
214
+ elements.append(Spacer(1, 10))
215
+
216
+ headers = ["Asset"] * 4
217
+ data = [headers]
218
+ row = []
219
+ for i, (pfad, name) in enumerate(assets):
220
+ cell = get_asset_cell(pfad, name, 4)
221
+ row.append(cell)
222
+ if len(row) == 4:
223
+ data.append(row)
224
+ row = []
225
+ if row:
226
+ row.extend([""] * (4 - len(row)))
227
+ data.append(row)
228
+
229
+ table = Table(data, colWidths=(A4[0] - 40) / 4)
230
+ table.setStyle(TableStyle([
231
+ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
232
+ ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
233
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
234
+ ]))
235
+ elements.append(table)
236
+
237
+ def analyze_files_by_filename(input_folder):
238
+ """Analyze files by extracting brand names from filenames"""
239
+ dateien = []
240
+ marken_set = set()
241
+ renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
242
+
243
+ for subfolder in sorted(Path(input_folder).iterdir()):
244
+ if not subfolder.is_dir():
245
+ continue
246
+
247
+ for file in sorted(subfolder.iterdir()):
248
+ if file.suffix.lower() not in ALL_ALLOWED_EXTENSIONS:
249
+ continue
250
+ marke = extract_brand(file.stem)
251
+ marken_set.add(marke)
252
+ dateien.append({
253
+ "original_file": file,
254
+ "original_folder": subfolder.name,
255
+ "marke": marke
256
+ })
257
+
258
+ for eintrag in dateien:
259
+ orig = eintrag["original_file"]
260
+ marke = eintrag["marke"]
261
+ folder_name = eintrag["original_folder"]
262
+ renamed_files_by_folder_and_marke[folder_name][marke].append((orig, orig.name))
263
+
264
+ return marken_set, renamed_files_by_folder_and_marke, dateien
265
+
266
  def generate_pdf_report(input_folder, erste_marke=None):
267
+ """Generate the complete PDF report (original method)"""
268
  styles = getSampleStyleSheet()
269
  gesamtbreite = 480
270
 
 
306
  except Exception as e:
307
  return None, f"Error generating PDF: {str(e)}"
308
 
309
+ def generate_filename_based_pdf_report(input_folder, erste_marke=None):
310
+ """Generate PDF report based on filename brand analysis"""
311
+ marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
312
+
313
+ if not marken_set:
314
+ return None, "No brands found in filenames."
315
+
316
+ # Create brand index
317
+ marken_index = {}
318
+ if erste_marke and erste_marke in marken_set:
319
+ marken_index[erste_marke] = "01"
320
+ aktuelle_nummer = 2
321
+ for marke in sorted(marken_set):
322
+ if marke != erste_marke:
323
+ marken_index[marke] = f"{aktuelle_nummer:02d}"
324
+ aktuelle_nummer += 1
325
+ else:
326
+ for i, marke in enumerate(sorted(marken_set), 1):
327
+ marken_index[marke] = f"{i:02d}"
328
+
329
+ # Generate PDF
330
+ pdf_buffer = io.BytesIO()
331
+ doc = SimpleDocTemplate(pdf_buffer, pagesize=A4, leftMargin=20, rightMargin=20, topMargin=40, bottomMargin=30)
332
+ elements = []
333
+ styles = getSampleStyleSheet()
334
+
335
+ nummer_zu_marke = {v: k for k, v in marken_index.items()}
336
+ marken_spalten = sorted(nummer_zu_marke.items())
337
+
338
+ # Overview by folder
339
+ for folder in sorted(renamed_files_by_folder_and_marke):
340
+ elements.append(Paragraph(f"<b>Folder: {folder}</b>", styles['Heading2']))
341
+
342
+ abschnitt = renamed_files_by_folder_and_marke[folder]
343
+ total = 0
344
+ lines = []
345
+ for nummer, marke in marken_spalten:
346
+ count = len(abschnitt.get(marke, []))
347
+ total += count
348
+ lines.append(f"{nummer} ({marke}): {count}")
349
+ lines.append(f"Total: {total}")
350
+ elements.append(Paragraph("<br/>".join(lines), styles['Normal']))
351
+ elements.append(Spacer(1, 10))
352
+
353
+ headers = [f"{nummer} ({marke})" for nummer, marke in marken_spalten]
354
+ data = [headers]
355
+ col_data = []
356
+ max_rows = 0
357
+ for _, marke in marken_spalten:
358
+ eintraege = abschnitt.get(marke, [])
359
+ zellen = [get_asset_cell(p, n, len(headers)) for p, n in eintraege]
360
+ col_data.append(zellen)
361
+ max_rows = max(max_rows, len(zellen))
362
+
363
+ for i in range(max_rows):
364
+ row = []
365
+ for col in col_data:
366
+ row.append(col[i] if i < len(col) else "")
367
+ data.append(row)
368
+
369
+ col_width = (A4[0] - 40) / len(headers)
370
+ t = Table(data, colWidths=[col_width] * len(headers))
371
+ t.setStyle(TableStyle([
372
+ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
373
+ ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
374
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
375
+ ]))
376
+ elements.append(t)
377
+ elements.append(PageBreak())
378
+
379
+ # Total overview
380
+ elements.append(Paragraph("<b>Total Overview</b>", styles['Heading2']))
381
+ global_counts = defaultdict(int)
382
+ for folder_data in renamed_files_by_folder_and_marke.values():
383
+ for marke, daten in folder_data.items():
384
+ global_counts[marke] += len(daten)
385
+
386
+ gesamt = 0
387
+ summary = []
388
+ for nummer, marke in marken_spalten:
389
+ count = global_counts[marke]
390
+ summary.append(f"{marke}: {count} assets")
391
+ gesamt += count
392
+ summary.append(f"Total number of all assets: {gesamt}")
393
+ elements.append(Paragraph("<br/>".join(summary), styles['Normal']))
394
+
395
+ # Add brand pages
396
+ add_brand_pages(elements, marken_spalten, renamed_files_by_folder_and_marke)
397
+
398
+ try:
399
+ doc.build(elements)
400
+ pdf_buffer.seek(0)
401
+ return pdf_buffer, None
402
+ except Exception as e:
403
+ return None, f"Error generating PDF: {str(e)}"
404
+
405
  def pdf_generator_tool():
406
+ st.header("Brand Assets PDF Generator")
407
+ st.markdown("Upload a zip file containing brand assets to generate a comprehensive PDF report.")
408
+
409
+ # Analysis method selection
410
+ analysis_method = st.radio(
411
+ "Choose analysis method:",
412
+ ["Folder-based analysis", "Filename-based analysis"],
413
+ help="Folder-based: analyzes brands based on folder structure. Filename-based: extracts brand names from filenames."
414
+ )
415
 
416
  # File upload
417
  uploaded_file = st.file_uploader(
418
  "Choose a ZIP file",
419
  type=['zip'],
420
+ help="Upload a zip file containing your brand assets.",
421
  key="pdf_zip_upload"
422
  )
423
 
 
433
  if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
434
  input_folder = os.path.join(temp_dir, items[0])
435
 
436
+ if analysis_method == "Folder-based analysis":
437
+ # Original folder-based analysis
438
+ marken = erkenne_marken_aus_ordnern(input_folder)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439
 
440
+ if not marken:
441
+ st.error("No brand folders found in the uploaded zip file.")
442
+ st.info("Make sure your zip file contains folders named after your brands, with assets inside each folder.")
443
+ return
444
+
445
+ st.success(f"Found brands: {', '.join(marken)}")
446
+
447
+ # Get file counts for processing
448
+ dateien_pro_marke = get_files_by_marke(input_folder, marken)
449
+
450
+ # Options
451
+ erste_marke = st.selectbox(
452
+ "Which brand should appear first in the overview?",
453
+ options=["Alphabetical order"] + marken
454
+ )
455
+ erste_marke = erste_marke if erste_marke != "Alphabetical order" else None
456
+
457
+ # Generate PDF button
458
+ if st.button("Generate PDF Report", type="primary"):
459
+ with st.spinner("Generating PDF report..."):
460
+ pdf_buffer, error = generate_pdf_report(input_folder, erste_marke)
461
 
462
+ if error:
463
+ st.error(f"{error}")
464
+ elif pdf_buffer:
465
+ st.success("PDF report generated successfully!")
466
+
467
+ # Download button
468
+ st.download_button(
469
+ label="๐Ÿ“ฅ Download PDF Report",
470
+ data=pdf_buffer.getvalue(),
471
+ file_name="Brand_Assets_Report.pdf",
472
+ mime="application/pdf"
473
+ )
474
+
475
+ else:
476
+ # Filename-based analysis
477
+ marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
478
+
479
+ if not marken_set:
480
+ st.error("No brands found in filenames.")
481
+ st.info("Make sure your files are named with brand identifiers at the beginning (e.g., 'Brand1_asset.jpg').")
482
+ return
483
+
484
+ st.success(f"Found brands from filenames: {', '.join(sorted(marken_set))}")
485
+
486
+ # Show analysis preview
487
+ with st.expander("Analysis Preview"):
488
+ total_files = len(all_files)
489
+ for folder, brands in renamed_files_by_folder_and_marke.items():
490
+ st.write(f"**{folder}:**")
491
+ for brand, files in brands.items():
492
+ st.write(f"- {brand}: {len(files)} files")
493
+
494
+ # Options
495
+ erste_marke = st.selectbox(
496
+ "Which brand should be numbered as 01?",
497
+ options=["Alphabetical order"] + sorted(list(marken_set))
498
+ )
499
+ erste_marke = erste_marke if erste_marke != "Alphabetical order" else None
500
+
501
+ # Generate PDF button
502
+ if st.button("Generate PDF Report", type="primary"):
503
+ with st.spinner("Generating PDF report..."):
504
+ pdf_buffer, error = generate_filename_based_pdf_report(input_folder, erste_marke)
505
+
506
+ if error:
507
+ st.error(f"{error}")
508
+ elif pdf_buffer:
509
+ st.success("PDF report generated successfully!")
510
+
511
+ # Download button
512
+ st.download_button(
513
+ label="๐Ÿ“ฅ Download PDF Report",
514
+ data=pdf_buffer.getvalue(),
515
+ file_name="IcAt_Overview_Branding.pdf",
516
+ mime="application/pdf"
517
+ )
518
 
519
  except zipfile.BadZipFile:
520
+ st.error("Invalid zip file. Please upload a valid zip file.")
521
  except Exception as e:
522
+ st.error(f"An error occurred: {str(e)}")
523
 
524
  else:
525
  st.info("๐Ÿ‘† Please upload a zip file to get started.")
526
 
527
+ # Instructions
528
+ with st.expander("๐Ÿ“– Instructions"):
529
  st.markdown("""
530
  **How to use this tool:**
531
 
532
+ **Folder-based analysis:**
533
+ - Create folders named after your brands
534
+ - Place brand assets inside each brand folder
535
+ - Zip the entire structure
536
 
537
+ **Filename-based analysis:**
538
+ - Name your files with brand identifiers at the beginning (e.g., 'Brand1_asset.jpg', 'Brand2_document.pdf')
539
+ - Organize files in any folder structure
540
+ - The tool will extract brand names from filenames automatically
541
 
542
+ **Supported file types:**
543
+ - **Images:** JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP
544
+ - **Text files:** TXT, MD, CSV
545
  """)
546
 
547
  def excel_extractor_tool():
548
+ st.header("Excel Image Extractor")
549
  st.markdown("Upload Excel files (.xlsx) to extract embedded images from them.")
550
 
551
  # File upload for Excel files
 
558
  )
559
 
560
  if uploaded_files:
561
+ if st.button("Extract Images", type="primary", key="extract_btn"):
562
  temp_dir = tempfile.mkdtemp()
563
  all_extracted_files = []
564
  total_images = 0
 
583
  count, extracted_files, error = extract_images_from_xlsx(temp_xlsx_path, output_dir)
584
 
585
  if error:
586
+ st.error(f"Error processing {uploaded_file.name}: {error}")
587
  elif count > 0:
588
+ st.success(f"Extracted {count} image(s) from {uploaded_file.name}")
589
  all_extracted_files.extend(extracted_files)
590
  total_images += count
591
  else:
592
+ st.warning(f"No images found in {uploaded_file.name}")
593
 
594
  status_text.empty()
595
  progress_bar.empty()
596
 
597
  if total_images > 0:
598
+ st.success(f"Total: {total_images} images extracted from {len(uploaded_files)} file(s)")
599
 
600
  # Create zip file with all extracted images
601
  zip_buffer = io.BytesIO()
 
609
 
610
  # Download button for all extracted images
611
  st.download_button(
612
+ label="Download All Extracted Images (ZIP)",
613
  data=zip_buffer.getvalue(),
614
  file_name="extracted_images.zip",
615
  mime="application/zip"
616
  )
617
 
618
  # Show preview of extracted images
619
+ with st.expander("Preview Extracted Images"):
620
  cols = st.columns(3)
621
  col_idx = 0
622
 
 
624
  try:
625
  with cols[col_idx % 3]:
626
  img = PILImage.open(file_path)
627
+ st.image(img, caption=os.path.basename(file_path), use_container_width =True)
628
  col_idx += 1
629
  except Exception as e:
630
  st.write(f"Could not preview {os.path.basename(file_path)}")
 
654
  - Common image formats (PNG, JPG, etc.) are extracted
655
  """)
656
 
657
+ def file_renamer_tool():
658
+ st.header("Brand File Renamer")
659
+ st.markdown("Upload a zip file containing brand folders to automatically rename files with brand prefixes.")
660
+
661
+ # File upload
662
+ uploaded_file = st.file_uploader(
663
+ "Choose a ZIP file",
664
+ type=['zip'],
665
+ help="Upload a zip file containing your brand folders with assets.",
666
+ key="renamer_zip_upload"
667
+ )
668
+
669
+ if uploaded_file is not None:
670
+ try:
671
+ # Extract zip file
672
+ with st.spinner("Extracting zip file..."):
673
+ temp_dir = extract_zip_to_temp(uploaded_file)
674
+
675
+ # Find the actual input folder (in case zip has a root folder)
676
+ input_folder = Path(temp_dir)
677
+ items = os.listdir(temp_dir)
678
+ if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
679
+ input_folder = Path(temp_dir) / items[0]
680
+
681
+ # Create output folder
682
+ output_folder = input_folder.parent / (input_folder.name + "_renamed")
683
+ output_folder.mkdir(exist_ok=True)
684
+
685
+ # Process files
686
+ total_files = 0
687
+ processed_files = []
688
+
689
+ for subfolder in input_folder.iterdir():
690
+ if subfolder.is_dir():
691
+ markenname = subfolder.name
692
+ new_subfolder = output_folder / markenname
693
+ new_subfolder.mkdir(parents=True, exist_ok=True)
694
+
695
+ for file in subfolder.iterdir():
696
+ if file.is_file() and file.suffix.lower() in ALL_ALLOWED_EXTENSIONS:
697
+ new_name = f"{markenname}_{file.name}"
698
+ target_path = new_subfolder / new_name
699
+ shutil.copy2(file, target_path)
700
+ processed_files.append((file.name, new_name, markenname))
701
+ total_files += 1
702
+
703
+ if total_files > 0:
704
+ st.success(f"Successfully renamed and copied {total_files} files")
705
+
706
+ # Show preview
707
+ with st.expander("๐Ÿ“‹ Preview renamed files"):
708
+ preview_df = pd.DataFrame(
709
+ processed_files[:20], # Show first 20 files
710
+ columns=["Original Name", "New Name", "Brand"]
711
+ )
712
+ st.dataframe(preview_df)
713
+
714
+ if total_files > 20:
715
+ st.info(f"Showing first 20 files. Total processed: {total_files}")
716
+
717
+ # Create zip file with renamed files
718
+ zip_buffer = io.BytesIO()
719
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
720
+ for root, dirs, files in os.walk(output_folder):
721
+ for file in files:
722
+ file_path = Path(root) / file
723
+ rel_path = os.path.relpath(file_path, output_folder)
724
+ zip_file.write(file_path, rel_path)
725
+
726
+ zip_buffer.seek(0)
727
+
728
+ # Download button
729
+ st.download_button(
730
+ label="๐Ÿ“ฅ Download Renamed Files (ZIP)",
731
+ data=zip_buffer.getvalue(),
732
+ file_name="brand_files_renamed.zip",
733
+ mime="application/zip"
734
+ )
735
+ else:
736
+ st.warning("No files were found to rename in the uploaded zip file.")
737
+
738
+ except Exception as e:
739
+ st.error(f"An error occurred: {str(e)}")
740
+
741
+ else:
742
+ st.info("๐Ÿ‘† Please upload a zip file to get started.")
743
+
744
+ # Instructions
745
+ with st.expander("๐Ÿ“– Instructions"):
746
+ st.markdown("""
747
+ **How to use this tool:**
748
+
749
+ 1. Create folders named after your brands
750
+ 2. Place brand assets inside each brand folder
751
+ 3. Zip the entire structure
752
+ 4. Upload the zip file
753
+
754
+ **The tool will:**
755
+ - Create a new folder structure matching the original
756
+ - Rename all files with the brand prefix (e.g., "Brand1_filename.jpg")
757
+ - Provide a zip file with all renamed files
758
+
759
+ **Supported file types:**
760
+ - Images: JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP
761
+ - Text files: TXT, MD, CSV
762
+ """)
763
+
764
  def main():
765
  st.title("๐Ÿ”ง Brand Assets Tools")
766
 
767
+ tab1, tab2, tab3 = st.tabs(["PDF Report Generator", "Excel Image Extractor", "Brand File Renamer"])
768
 
769
  with tab1:
770
  pdf_generator_tool()
771
  with tab2:
772
  excel_extractor_tool()
773
+ with tab3:
774
+ file_renamer_tool()
775
+
776
+ def white_to_transparent_tool():
777
+ st.header("White Background to Transparent")
778
+ st.markdown("Upload images to convert white backgrounds to transparent.")
779
+
780
+ # Options
781
+ col1, col2 = st.columns(2)
782
+ with col1:
783
+ crop_image = st.checkbox("Crop white background", value=False)
784
+ with col2:
785
+ overwrite = st.checkbox("Overwrite original files", value=False)
786
+
787
+ # File upload
788
+ uploaded_files = st.file_uploader(
789
+ "Choose image files",
790
+ type=list(ALLOWED_IMAGE_EXTENSIONS),
791
+ accept_multiple_files=True,
792
+ help="Upload images to convert white backgrounds to transparent.",
793
+ key="transparent_upload"
794
+ )
795
+
796
+ if uploaded_files:
797
+ if st.button("Process Images", type="primary"):
798
+ temp_dir = tempfile.mkdtemp()
799
+ processed_files = []
800
+ failed_files = []
801
+
802
+ # Save uploaded files to temp dir
803
+ for uploaded_file in uploaded_files:
804
+ file_path = os.path.join(temp_dir, uploaded_file.name)
805
+ with open(file_path, 'wb') as f:
806
+ f.write(uploaded_file.getbuffer())
807
+
808
+ # Process images
809
+ progress_bar = st.progress(0)
810
+ status_text = st.empty()
811
+
812
+ for i, uploaded_file in enumerate(uploaded_files):
813
+ status_text.text(f"Processing {uploaded_file.name}... ({i+1}/{len(uploaded_files)})")
814
+ progress_bar.progress((i + 1) / len(uploaded_files))
815
+
816
+ try:
817
+ img = PILImage.open(os.path.join(temp_dir, uploaded_file.name)).convert("RGBA")
818
+
819
+ # Convert to numpy array for OpenCV processing
820
+ img_array = np.array(img)
821
+
822
+ if crop_image:
823
+ # Crop image
824
+ gray = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
825
+ th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
826
+
827
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
828
+ morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
829
+
830
+ cnts, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
831
+ if cnts: # Only crop if contours are found
832
+ cnt = sorted(cnts, key=cv2.contourArea)[-1]
833
+ x,y,w,h = cv2.boundingRect(cnt)
834
+ img_array = img_array[y:y+h, x:x+w]
835
+
836
+ # Make white background transparent
837
+ gray = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
838
+ th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
839
+
840
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
841
+ morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
842
+
843
+ roi, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
844
+
845
+ mask = np.zeros(img_array.shape, img_array.dtype)
846
+ if roi: # Only proceed if contours are found
847
+ cv2.fillPoly(mask, roi, (255,)*img_array.shape[2])
848
+ masked_image = cv2.bitwise_and(img_array, mask)
849
+
850
+ # Convert back to PIL Image
851
+ result_img = PILImage.fromarray(masked_image, mode="RGBA")
852
+
853
+ # Save the processed image
854
+ new_filename = os.path.splitext(uploaded_file.name)[0] + ".png"
855
+ processed_path = os.path.join(temp_dir, "processed_" + new_filename)
856
+ result_img.save(processed_path)
857
+ processed_files.append(processed_path)
858
+ else:
859
+ failed_files.append(uploaded_file.name)
860
+ except Exception as e:
861
+ failed_files.append(uploaded_file.name)
862
+ st.warning(f"Failed to process {uploaded_file.name}: {str(e)}")
863
+
864
+ status_text.empty()
865
+ progress_bar.empty()
866
+
867
+ if processed_files:
868
+ st.success(f"โœ… Successfully processed {len(processed_files)} images")
869
+
870
+ # Create zip file with processed images
871
+ zip_buffer = io.BytesIO()
872
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
873
+ for file_path in processed_files:
874
+ zip_file.write(file_path, os.path.basename(file_path))
875
+
876
+ zip_buffer.seek(0)
877
+
878
+ # Download button
879
+ st.download_button(
880
+ label="๐Ÿ“ฅ Download Processed Images (ZIP)",
881
+ data=zip_buffer.getvalue(),
882
+ file_name="transparent_images.zip",
883
+ mime="application/zip"
884
+ )
885
+
886
+ # Show preview
887
+ with st.expander("๐Ÿ–ผ๏ธ Preview Processed Images"):
888
+ cols = st.columns(3)
889
+ for i, file_path in enumerate(processed_files[:6]): # Show max 6 images
890
+ with cols[i % 3]:
891
+ img = PILImage.open(file_path)
892
+ st.image(img, caption=os.path.basename(file_path), use_container_width=True)
893
+
894
+ if len(processed_files) > 6:
895
+ st.info(f"Showing first 6 images. Total processed: {len(processed_files)}")
896
+
897
+ if failed_files:
898
+ st.warning(f"โš ๏ธ Failed to process {len(failed_files)} files: {', '.join(failed_files)}")
899
+
900
+ else:
901
+ st.info("๐Ÿ‘† Please upload image files to get started.")
902
+
903
+ # Instructions
904
+ with st.expander("๐Ÿ“– Instructions"):
905
+ st.markdown("""
906
+ **How to use this tool:**
907
+
908
+ 1. Upload one or more image files
909
+ 2. Choose processing options:
910
+ - Crop white background: Removes excess white space around the image
911
+ - Overwrite original files: Not applicable in this web version (always creates new files)
912
+ 3. Click "Process Images"
913
+ 4. Download the processed images with transparent backgrounds
914
+
915
+ **Note:**
916
+ - Output images will always be in PNG format to support transparency
917
+ - Only white backgrounds will be made transparent (threshold of 240/255)
918
+ - Complex images may require manual adjustment for best results
919
+ """)
920
 
921
+ def find_smallest_dimensions_tool():
922
+ st.header("Find Smallest Image Dimensions")
923
+ st.markdown("Analyze a folder to find images with the smallest width and height.")
924
+
925
+ # File upload
926
+ uploaded_file = st.file_uploader(
927
+ "Choose a ZIP file with images",
928
+ type=['zip'],
929
+ help="Upload a zip file containing images to analyze.",
930
+ key="dimensions_zip_upload"
931
+ )
932
+
933
+ if uploaded_file:
934
+ try:
935
+ # Extract zip file
936
+ with st.spinner("Extracting zip file..."):
937
+ temp_dir = extract_zip_to_temp(uploaded_file)
938
+
939
+ # Find the actual input folder (in case zip has a root folder)
940
+ input_folder = temp_dir
941
+ items = os.listdir(temp_dir)
942
+ if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
943
+ input_folder = os.path.join(temp_dir, items[0])
944
+
945
+ # Analyze images
946
+ with st.spinner("Analyzing images..."):
947
+ min_width = None
948
+ min_height = None
949
+ file_min_width = ""
950
+ file_min_height = ""
951
+ height_at_min_width = None
952
+ width_at_min_height = None
953
+ total_images = 0
954
+
955
+ for root, dirs, files in os.walk(input_folder):
956
+ for file in files:
957
+ ext = os.path.splitext(file)[1].lower()
958
+ if ext in ALLOWED_IMAGE_EXTENSIONS:
959
+ path = os.path.join(root, file)
960
+ try:
961
+ with PILImage.open(path) as img:
962
+ width, height = img.size
963
+ total_images += 1
964
+
965
+ if (min_width is None) or (width < min_width):
966
+ min_width = width
967
+ height_at_min_width = height
968
+ file_min_width = path
969
+
970
+ if (min_height is None) or (height < min_height):
971
+ min_height = height
972
+ width_at_min_height = width
973
+ file_min_height = path
974
+ except Exception as e:
975
+ st.warning(f"Error processing {file}: {str(e)}")
976
+
977
+ if min_width is not None and min_height is not None:
978
+ st.success(f"Analyzed {total_images} images")
979
+
980
+ col1, col2 = st.columns(2)
981
+ with col1:
982
+ st.subheader("Smallest Width")
983
+ st.write(f"Dimensions: {min_width} ร— {height_at_min_width} px")
984
+ st.image(file_min_width, caption=os.path.basename(file_min_width), use_container_width =True)
985
+
986
+ with col2:
987
+ st.subheader("Smallest Height")
988
+ st.write(f"Dimensions: {width_at_min_height} ร— {min_height} px")
989
+ st.image(file_min_height, caption=os.path.basename(file_min_height), use_container_width =True)
990
+ else:
991
+ st.warning("No valid image files found in the uploaded zip.")
992
+
993
+ except Exception as e:
994
+ st.error(f"An error occurred: {str(e)}")
995
+
996
+ else:
997
+ st.info("๐Ÿ‘† Please upload a zip file with images to analyze.")
998
+
999
+ # Instructions
1000
+ with st.expander("๐Ÿ“– Instructions"):
1001
+ st.markdown("""
1002
+ **How to use this tool:**
1003
+
1004
+ 1. Upload a zip file containing images
1005
+ 2. The tool will analyze all images in the folder and subfolders
1006
+ 3. It will find and display:
1007
+ - The image with the smallest width
1008
+ - The image with the smallest height
1009
+
1010
+ **Supported image formats:**
1011
+ - JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP
1012
+ """)
1013
 
1014
+ def resize_with_transparent_canvas_tool():
1015
+ st.header("Resize with Transparent Canvas")
1016
+ st.markdown("Resize images to a target dimension while maintaining aspect ratio on transparent background.")
1017
+
1018
+ # File upload with unique key
1019
+ uploaded_file = st.file_uploader(
1020
+ "Choose a ZIP file with images",
1021
+ type=['zip'],
1022
+ help="Upload a zip file containing images to resize.",
1023
+ key="resize_transparent_upload"
1024
+ )
1025
+
1026
+ if uploaded_file:
1027
+ # Options
1028
+ col1, col2 = st.columns(2)
1029
+ with col1:
1030
+ mode = st.radio(
1031
+ "Resize mode:",
1032
+ ["By height", "By width"],
1033
+ help="Resize all images to match either height or width while maintaining aspect ratio",
1034
+ key="resize_mode_selector"
1035
+ )
1036
+ with col2:
1037
+ # Set different limits based on mode
1038
+ if mode == "By height":
1039
+ target_value = st.number_input(
1040
+ "Target height (pixels):",
1041
+ min_value=10, # Minimum 10px height
1042
+ max_value=4000, # Maximum 4000px height
1043
+ value=1000, # Default 1000px
1044
+ step=10,
1045
+ key="target_height_input"
1046
+ )
1047
+ else: # By width
1048
+ target_value = st.number_input(
1049
+ "Target width (pixels):",
1050
+ min_value=10, # Minimum 10px width
1051
+ max_value=4000, # Maximum 4000px width
1052
+ value=1000, # Default 1000px
1053
+ step=10,
1054
+ key="target_width_input"
1055
+ )
1056
+
1057
+ # Process button with unique key
1058
+ if st.button("Process Images", type="primary", key="process_resize_transparent_images"):
1059
+ try:
1060
+ # Extract zip file
1061
+ with st.spinner("Extracting zip file..."):
1062
+ temp_dir = extract_zip_to_temp(uploaded_file)
1063
+ input_folder = temp_dir
1064
+ items = os.listdir(temp_dir)
1065
+ if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
1066
+ input_folder = os.path.join(temp_dir, items[0])
1067
+
1068
+ # Create output folder
1069
+ output_folder = os.path.join(temp_dir, "resized_transparent_output")
1070
+ os.makedirs(output_folder, exist_ok=True)
1071
+
1072
+ # Process images
1073
+ processed_count = 0
1074
+ error_count = 0
1075
+ progress_bar = st.progress(0)
1076
+ status_text = st.empty()
1077
+
1078
+ all_files = []
1079
+ for root, dirs, files in os.walk(input_folder):
1080
+ for file in files:
1081
+ ext = os.path.splitext(file)[1].lower()
1082
+ if ext in ALLOWED_IMAGE_EXTENSIONS:
1083
+ all_files.append(os.path.join(root, file))
1084
+
1085
+ total_files = len(all_files)
1086
+
1087
+ for i, file_path in enumerate(all_files):
1088
+ status_text.text(f"Processing {i+1}/{total_files}: {os.path.basename(file_path)}...")
1089
+ progress_bar.progress((i + 1) / total_files)
1090
+
1091
+ try:
1092
+ relative_path = os.path.relpath(file_path, input_folder)
1093
+ new_path = os.path.join(output_folder, os.path.splitext(relative_path)[0] + ".png")
1094
+ os.makedirs(os.path.dirname(new_path), exist_ok=True)
1095
+
1096
+ with PILImage.open(file_path) as img:
1097
+ img = img.convert("RGBA")
1098
+ orig_w, orig_h = img.size
1099
+
1100
+ if mode == "By height":
1101
+ # Calculate new dimensions based on target height
1102
+ factor = target_value / orig_h
1103
+ new_h = target_value
1104
+ new_w = int(orig_w * factor)
1105
+ else: # By width
1106
+ # Calculate new dimensions based on target width
1107
+ factor = target_value / orig_w
1108
+ new_w = target_value
1109
+ new_h = int(orig_h * factor)
1110
+
1111
+ # Resize image while maintaining aspect ratio
1112
+ img_resized = img.resize((new_w, new_h), PILImage.LANCZOS)
1113
+
1114
+ # Create transparent canvas with target dimensions
1115
+ if mode == "By height":
1116
+ # For height mode, canvas matches the resized width and target height
1117
+ canvas = PILImage.new("RGBA", (new_w, new_h), (0, 0, 0, 0))
1118
+ else:
1119
+ # For width mode, canvas matches the target width and resized height
1120
+ canvas = PILImage.new("RGBA", (new_w, new_h), (0, 0, 0, 0))
1121
+
1122
+ # Center the resized image on the canvas
1123
+ x_offset = (canvas.width - img_resized.width) // 2
1124
+ y_offset = (canvas.height - img_resized.height) // 2
1125
+ canvas.paste(img_resized, (x_offset, y_offset), mask=img_resized)
1126
+
1127
+ canvas.save(new_path)
1128
+ processed_count += 1
1129
+ except Exception as e:
1130
+ error_count += 1
1131
+ st.warning(f"Error processing {os.path.basename(file_path)}: {str(e)}")
1132
+
1133
+ status_text.empty()
1134
+ progress_bar.empty()
1135
+
1136
+ # Results summary
1137
+ st.success(f"""
1138
+ Processing complete!
1139
+ - โœ… Processed: {processed_count} images
1140
+ - โŒ Errors: {error_count} images
1141
+ """)
1142
+
1143
+ if processed_count > 0:
1144
+ # Create zip file with processed images
1145
+ zip_buffer = io.BytesIO()
1146
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
1147
+ for root, dirs, files in os.walk(output_folder):
1148
+ for file in files:
1149
+ file_path = os.path.join(root, file)
1150
+ rel_path = os.path.relpath(file_path, output_folder)
1151
+ zip_file.write(file_path, rel_path)
1152
+
1153
+ zip_buffer.seek(0)
1154
+
1155
+ # Download button with unique key
1156
+ st.download_button(
1157
+ label="๐Ÿ“ฅ Download Resized Images (ZIP)",
1158
+ data=zip_buffer.getvalue(),
1159
+ file_name="resized_transparent_images.zip",
1160
+ mime="application/zip",
1161
+ key="download_resized_transparent"
1162
+ )
1163
+
1164
+ # Show preview (removed key from expander)
1165
+ with st.expander("๐Ÿ–ผ๏ธ Preview Resized Images"):
1166
+ sample_files = []
1167
+ for root, dirs, files in os.walk(output_folder):
1168
+ for file in files[:3]: # Get first 3 files from each folder
1169
+ if len(sample_files) < 6: # Max 6 samples
1170
+ sample_files.append(os.path.join(root, file))
1171
+
1172
+ if sample_files:
1173
+ cols = st.columns(3)
1174
+ for i, file_path in enumerate(sample_files):
1175
+ with cols[i % 3]:
1176
+ img = PILImage.open(file_path)
1177
+ st.image(img, caption=os.path.basename(file_path), use_container_width=True)
1178
+
1179
+ if processed_count > 6:
1180
+ st.info(f"Showing sample images. Total processed: {processed_count}")
1181
+
1182
+ except Exception as e:
1183
+ st.error(f"An error occurred during processing: {str(e)}")
1184
+
1185
+ else:
1186
+ st.info("๐Ÿ‘† Please upload a zip file with images to resize.")
1187
+
1188
+ # Instructions (removed key from expander)
1189
+ with st.expander("๐Ÿ“– Instructions"):
1190
+ st.markdown("""
1191
+ **How to use this tool:**
1192
+
1193
+ 1. Upload a zip file containing images
1194
+ 2. Choose resize mode:
1195
+ - By height: All images will be resized to match the target height
1196
+ - By width: All images will be resized to match the target width
1197
+ 3. Set the target dimension (10-4000 pixels)
1198
+ 4. Click "Process Images"
1199
+ 5. Download the resized images with transparent backgrounds
1200
+
1201
+ **Features:**
1202
+ - Maintains original aspect ratio
1203
+ - Centers images on transparent canvas
1204
+ - Outputs PNG files to preserve transparency
1205
+ - Preserves folder structure
1206
+
1207
+ **Limits:**
1208
+ - Minimum dimension: 10 pixels
1209
+ - Maximum dimension: 4000 pixels
1210
+ - For batch processing of many images, please be patient
1211
+ """)
1212
+ def center_on_canvas_tool():
1213
+ st.header("Center on Transparent Canvas")
1214
+ st.markdown("Center small images on a transparent 500x500 canvas.")
1215
+
1216
+ # File upload - add unique key
1217
+ uploaded_file = st.file_uploader(
1218
+ "Choose a ZIP file with images",
1219
+ type=['zip'],
1220
+ help="Upload a zip file containing images to process.",
1221
+ key="canvas_center_upload" # Added unique key
1222
+ )
1223
+
1224
+ if uploaded_file:
1225
+ # Options
1226
+ canvas_size = st.number_input(
1227
+ "Canvas size (pixels):",
1228
+ min_value=100,
1229
+ max_value=2000,
1230
+ value=500,
1231
+ step=10,
1232
+ key="canvas_size_input" # Added unique key
1233
+ )
1234
+
1235
+ # Add unique key to the button
1236
+ if st.button("Process Images", type="primary", key="process_canvas_images"):
1237
+ try:
1238
+ # Extract zip file
1239
+ with st.spinner("Extracting zip file..."):
1240
+ temp_dir = extract_zip_to_temp(uploaded_file)
1241
+ input_folder = temp_dir
1242
+ items = os.listdir(temp_dir)
1243
+ if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
1244
+ input_folder = os.path.join(temp_dir, items[0])
1245
+
1246
+ # Create output folder
1247
+ output_folder = os.path.join(temp_dir, "canvas_output")
1248
+ os.makedirs(output_folder, exist_ok=True)
1249
+
1250
+ # Process images
1251
+ processed_count = 0
1252
+ progress_bar = st.progress(0)
1253
+ status_text = st.empty()
1254
+
1255
+ all_files = []
1256
+ for root, dirs, files in os.walk(input_folder):
1257
+ for file in files:
1258
+ ext = os.path.splitext(file)[1].lower()
1259
+ if ext in ALLOWED_IMAGE_EXTENSIONS:
1260
+ all_files.append(os.path.join(root, file))
1261
+
1262
+ for i, file_path in enumerate(all_files):
1263
+ status_text.text(f"Processing {os.path.basename(file_path)}... ({i+1}/{len(all_files)})")
1264
+ progress_bar.progress((i + 1) / len(all_files))
1265
+
1266
+ try:
1267
+ with PILImage.open(file_path) as img:
1268
+ width, height = img.size
1269
+
1270
+ if width < canvas_size and height < canvas_size:
1271
+ # Create transparent canvas
1272
+ canvas = PILImage.new('RGBA', (canvas_size, canvas_size), (255, 255, 255, 0))
1273
+
1274
+ # Convert image to RGBA if needed
1275
+ if img.mode != 'RGBA':
1276
+ img = img.convert('RGBA')
1277
+
1278
+ # Center image on canvas
1279
+ paste_x = (canvas_size - width) // 2
1280
+ paste_y = (canvas_size - height) // 2
1281
+ canvas.paste(img, (paste_x, paste_y), img)
1282
+
1283
+ # Save processed image
1284
+ new_filename = os.path.splitext(os.path.basename(file_path))[0] + ".png"
1285
+ output_path = os.path.join(output_folder, new_filename)
1286
+ canvas.save(output_path)
1287
+ processed_count += 1
1288
+ except Exception as e:
1289
+ st.warning(f"Error processing {os.path.basename(file_path)}: {str(e)}")
1290
+
1291
+ status_text.empty()
1292
+ progress_bar.empty()
1293
+
1294
+ if processed_count > 0:
1295
+ st.success(f"โœ… Successfully processed {processed_count} images")
1296
+
1297
+ # Create zip file with processed images
1298
+ zip_buffer = io.BytesIO()
1299
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
1300
+ for root, dirs, files in os.walk(output_folder):
1301
+ for file in files:
1302
+ file_path = os.path.join(root, file)
1303
+ rel_path = os.path.relpath(file_path, output_folder)
1304
+ zip_file.write(file_path, rel_path)
1305
+
1306
+ zip_buffer.seek(0)
1307
+
1308
+ # Download button
1309
+ st.download_button(
1310
+ label="๐Ÿ“ฅ Download Processed Images (ZIP)",
1311
+ data=zip_buffer.getvalue(),
1312
+ file_name="centered_images.zip",
1313
+ mime="application/zip"
1314
+ )
1315
+
1316
+ # Show preview
1317
+ with st.expander("๐Ÿ–ผ๏ธ Preview Processed Images"):
1318
+ sample_files = []
1319
+ for root, dirs, files in os.walk(output_folder):
1320
+ for file in files[:3]: # Get first 3 files from each folder
1321
+ if len(sample_files) < 6: # Max 6 samples
1322
+ sample_files.append(os.path.join(root, file))
1323
+
1324
+ cols = st.columns(3)
1325
+ for i, file_path in enumerate(sample_files):
1326
+ with cols[i % 3]:
1327
+ img = PILImage.open(file_path)
1328
+ st.image(img, caption=os.path.basename(file_path), use_container_width=True)
1329
+
1330
+ if processed_count > 6:
1331
+ st.info(f"Showing sample images. Total processed: {processed_count}")
1332
+ else:
1333
+ st.warning("No images were processed (all images were already larger than the canvas size).")
1334
+
1335
+ except Exception as e:
1336
+ st.error(f"An error occurred: {str(e)}")
1337
+
1338
+ else:
1339
+ st.info("๐Ÿ‘† Please upload a zip file with images to process.")
1340
+
1341
+ # Instructions
1342
+ with st.expander("๐Ÿ“– Instructions"):
1343
+ st.markdown("""
1344
+ **How to use this tool:**
1345
+
1346
+ 1. Upload a zip file containing images
1347
+ 2. Set the canvas size (default is 500x500 pixels)
1348
+ 3. Click "Process Images"
1349
+ 4. Download the processed images
1350
+
1351
+ **Features:**
1352
+ - Centers images smaller than canvas size on transparent background
1353
+ - Images larger than canvas size are skipped
1354
+ - Outputs PNG files to preserve transparency
1355
+ - Preserves folder structure
1356
+
1357
+ **Note:**
1358
+ - Only images smaller than the specified canvas size will be processed
1359
+ - Original aspect ratio is maintained
1360
+ """)
1361
 
1362
+ def main():
1363
+ st.title("๐Ÿ”ง Brand Assets Tools")
1364
 
1365
+ tab1, tab2, tab3, tab4, tab5, tab6, tab7 = st.tabs([
1366
+ "PDF Report Generator",
1367
+ "Excel Image Extractor",
1368
+ "Brand File Renamer",
1369
+ "White to Transparent",
1370
+ "Find Smallest Dimensions",
1371
+ "Resize with Transparent Canvas",
1372
+ "Center on Canvas"
1373
+ ])
1374
 
1375
+ with tab1:
1376
+ pdf_generator_tool()
1377
+ with tab2:
1378
+ excel_extractor_tool()
1379
+ with tab3:
1380
+ file_renamer_tool()
1381
+ with tab4:
1382
+ white_to_transparent_tool()
1383
+ with tab5:
1384
+ find_smallest_dimensions_tool()
1385
+ with tab6:
1386
+ resize_with_transparent_canvas_tool()
1387
+ with tab7:
1388
+ center_on_canvas_tool()
1389
 
1390
  if __name__ == "__main__":
1391
  main()