Gnanashri Kota Venkatesh commited on
Commit
4cd2f37
Β·
unverified Β·
1 Parent(s): 775e362

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +410 -0
app.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
18
+ page_title="Brand Assets Tools",
19
+ page_icon="πŸ”§",
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):
38
+ """Extract images from Excel file to specified directory"""
39
+ count = 0
40
+ extracted_files = []
41
+
42
+ try:
43
+ with zipfile.ZipFile(xlsx_file, 'r') as z:
44
+ for file_info in z.infolist():
45
+ if file_info.filename.startswith("xl/media/"):
46
+ filename = Path(file_info.filename).name
47
+ target_path = Path(output_dir) / filename
48
+
49
+ with z.open(file_info) as source, open(target_path, 'wb') as target:
50
+ shutil.copyfileobj(source, target)
51
+
52
+ extracted_files.append(str(target_path))
53
+ count += 1
54
+
55
+ return count, extracted_files, None
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)
64
+ if os.path.isdir(os.path.join(input_folder, f)) and not f.startswith('.')
65
+ ])
66
+ except Exception as e:
67
+ st.error(f"Error reading folders: {str(e)}")
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:
75
+ folder_path = os.path.join(input_folder, marke)
76
+ if os.path.isdir(folder_path):
77
+ try:
78
+ dateien = [
79
+ os.path.join(folder_path, f)
80
+ for f in os.listdir(folder_path)
81
+ if not f.startswith(".") and os.path.splitext(f)[1].lower() in ALL_ALLOWED_EXTENSIONS
82
+ ]
83
+ spalteninhalte[marke] = dateien
84
+ except Exception as e:
85
+ st.warning(f"Error reading files from {marke}: {str(e)}")
86
+ spalteninhalte[marke] = []
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
+
95
+ for marke, dateien in alle_dateien_pro_marke.items():
96
+ elements.append(Paragraph(f"Brand Overview: {marke}", styles['Heading2']))
97
+ elements.append(Spacer(1, 12))
98
+ elements.append(Paragraph(f"<b>Total Assets:</b> {len(dateien)}", styles['Normal']))
99
+ elements.append(Spacer(1, 12))
100
+
101
+ if not dateien:
102
+ elements.append(Paragraph("No assets found in this brand folder.", styles['Normal']))
103
+ elements.append(PageBreak())
104
+ continue
105
+
106
+ table_data = []
107
+ row_data = []
108
+ spaltenbreite = gesamtbreite / 3
109
+
110
+ for i, file_path in enumerate(dateien):
111
+ ext = os.path.splitext(file_path)[1].lower()
112
+ filename = os.path.basename(file_path)
113
+
114
+ if ext in ALLOWED_IMAGE_EXTENSIONS:
115
+ try:
116
+ pil_img = PILImage.open(file_path)
117
+ width, height = pil_img.size
118
+ aspect = height / width
119
+ new_width = spaltenbreite * 0.9
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:
132
+ table_data.append(row_data)
133
+ row_data = []
134
+
135
+ if row_data:
136
+ while len(row_data) < 3:
137
+ row_data.append("")
138
+ table_data.append(row_data)
139
+
140
+ if table_data:
141
+ table = Table(table_data, colWidths=[spaltenbreite] * 3)
142
+ table.setStyle(TableStyle([
143
+ ("GRID", (0, 0), (-1, -1), 1, colors.grey),
144
+ ("ALIGN", (0, 0), (-1, -1), "CENTER"),
145
+ ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
146
+ ]))
147
+ elements.append(table)
148
+
149
+ elements.append(PageBreak())
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
+
158
+ marken = erkenne_marken_aus_ordnern(input_folder)
159
+ if not marken:
160
+ return None, "No brand folders found in the uploaded zip file."
161
+
162
+ # Reorder brands if specified
163
+ if erste_marke and erste_marke in marken:
164
+ marken = [erste_marke] + [m for m in marken if m != erste_marke]
165
+
166
+ dateien_pro_marke = get_files_by_marke(input_folder, marken)
167
+ total_all = sum(len(dateien_pro_marke[marke]) for marke in marken)
168
+
169
+ alle_elements = []
170
+
171
+ # Overview page
172
+ alle_elements.append(Paragraph("Brand Assets Overview", styles['Title']))
173
+ alle_elements.append(Spacer(1, 20))
174
+
175
+ ΓΌbersicht_text = ", ".join([f"{marke}: {len(dateien_pro_marke[marke])}" for marke in marken])
176
+ alle_elements.append(Paragraph(f"<b>Assets per brand:</b> {ΓΌbersicht_text}", styles['Normal']))
177
+ alle_elements.append(Spacer(1, 12))
178
+ alle_elements.append(Paragraph(f"<b>Total assets:</b> {total_all}", styles['Normal']))
179
+ alle_elements.append(PageBreak())
180
+
181
+ # Individual brand pages
182
+ markenseiten = build_marken_einzelseiten(dateien_pro_marke, styles, gesamtbreite)
183
+ alle_elements.extend(markenseiten)
184
+
185
+ # Generate PDF
186
+ pdf_buffer = io.BytesIO()
187
+ doc = SimpleDocTemplate(pdf_buffer, pagesize=A4)
188
+
189
+ try:
190
+ doc.build(alle_elements)
191
+ pdf_buffer.seek(0)
192
+ return pdf_buffer, 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
+
208
+ if uploaded_file is not None:
209
+ try:
210
+ # Extract zip file
211
+ with st.spinner("Extracting zip file..."):
212
+ temp_dir = extract_zip_to_temp(uploaded_file)
213
+
214
+ # Find the actual input folder (in case zip has a root folder)
215
+ input_folder = temp_dir
216
+ items = os.listdir(temp_dir)
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
289
+ uploaded_files = st.file_uploader(
290
+ "Choose Excel file(s)",
291
+ type=['xlsx'],
292
+ accept_multiple_files=True,
293
+ help="Upload one or more .xlsx files to extract embedded images.",
294
+ key="excel_upload"
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
302
+
303
+ progress_bar = st.progress(0)
304
+ status_text = st.empty()
305
+
306
+ for i, uploaded_file in enumerate(uploaded_files):
307
+ status_text.text(f"Processing {uploaded_file.name}...")
308
+ progress_bar.progress((i + 1) / len(uploaded_files))
309
+
310
+ # Save uploaded file temporarily
311
+ temp_xlsx_path = os.path.join(temp_dir, uploaded_file.name)
312
+ with open(temp_xlsx_path, 'wb') as f:
313
+ f.write(uploaded_file.getbuffer())
314
+
315
+ # Create output directory for this file
316
+ output_dir = os.path.join(temp_dir, f"{Path(uploaded_file.name).stem}_images")
317
+ os.makedirs(output_dir, exist_ok=True)
318
+
319
+ # Extract images
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()
339
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
340
+ for file_path in all_extracted_files:
341
+ # Get relative path for zip structure
342
+ rel_path = os.path.relpath(file_path, temp_dir)
343
+ zip_file.write(file_path, rel_path)
344
+
345
+ zip_buffer.seek(0)
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
+
360
+ for file_path in all_extracted_files[:12]: # Show max 12 images
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)}")
368
+
369
+ if len(all_extracted_files) > 12:
370
+ st.info(f"Showing first 12 images. Total extracted: {len(all_extracted_files)}")
371
+
372
+ else:
373
+ st.info("No images were found in the uploaded Excel file(s).")
374
+
375
+ else:
376
+ st.info("πŸ‘† Please upload Excel file(s) to get started.")
377
+
378
+ # Instructions for Excel extractor
379
+ with st.expander("πŸ“– How to use Excel Image Extractor"):
380
+ st.markdown("""
381
+ **How it works:**
382
+
383
+ 1. Upload one or more Excel files (.xlsx format)
384
+ 2. The tool will scan for embedded images in the Excel files
385
+ 3. All found images will be extracted and made available for download
386
+ 4. Images are packaged in a ZIP file for easy download
387
+
388
+ **Note:**
389
+ - Only .xlsx files are supported (not .xls)
390
+ - Images must be embedded in the Excel file (not linked)
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()