Gnanashri Kota Venkatesh commited on
Commit
b161457
Β·
unverified Β·
1 Parent(s): 675eba7

Update app.py v2 chnages tab4

Browse files
Files changed (1) hide show
  1. app.py +772 -155
app.py CHANGED
@@ -306,8 +306,8 @@ def generate_pdf_report(input_folder, erste_marke=None):
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:
@@ -335,7 +335,7 @@ def generate_filename_based_pdf_report(input_folder, erste_marke=None):
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
 
@@ -354,9 +354,21 @@ def generate_filename_based_pdf_report(input_folder, erste_marke=None):
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
 
@@ -392,8 +404,8 @@ def generate_filename_based_pdf_report(input_folder, erste_marke=None):
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)
@@ -402,6 +414,431 @@ def generate_filename_based_pdf_report(input_folder, erste_marke=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.")
@@ -1380,6 +1817,60 @@ def get_cleaned_filename_without_brand(filename, brand):
1380
  full_letters = clean_letters_only(Path(filename).stem.lower())
1381
  return full_letters.replace(brand, '', 1)
1382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1383
  def get_asset_cell(file_path, filename, col_count):
1384
  """Create optimized asset cell for PDF with better image handling"""
1385
  ext = Path(file_path).suffix.lower()
@@ -1446,8 +1937,8 @@ def analyze_files_by_filename(input_folder):
1446
 
1447
  return marken_set, renamed_files_by_folder_and_marke, dateien
1448
 
1449
- def generate_filename_based_pdf_report(input_folder, erste_marke=None):
1450
- """Generate PDF report based on filename brand analysis"""
1451
  marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
1452
 
1453
  if not marken_set:
@@ -1495,7 +1986,18 @@ def generate_filename_based_pdf_report(input_folder, erste_marke=None):
1495
  max_rows = 0
1496
  for _, marke in marken_spalten:
1497
  eintraege = abschnitt.get(marke, [])
1498
- zellen = [get_asset_cell(p, n, len(headers)) for p, n in eintraege]
 
 
 
 
 
 
 
 
 
 
 
1499
  col_data.append(zellen)
1500
  max_rows = max(max_rows, len(zellen))
1501
 
@@ -1531,6 +2033,9 @@ def generate_filename_based_pdf_report(input_folder, erste_marke=None):
1531
  summary.append(f"Total number of all assets: {gesamt}")
1532
  elements.append(Paragraph("<br/>".join(summary), styles['Normal']))
1533
 
 
 
 
1534
  try:
1535
  doc.build(elements)
1536
  pdf_buffer.seek(0)
@@ -1538,53 +2043,54 @@ def generate_filename_based_pdf_report(input_folder, erste_marke=None):
1538
  except Exception as e:
1539
  return None, f"Error generating PDF: {str(e)}"
1540
 
1541
- def generate_excel_report(output_folder: Path, marken_index: dict, file_to_factorgroup: dict):
1542
- final_excel_path = output_folder / "IcAt_Overview_Final.xlsx"
1543
-
1544
- nummer_zu_marke = {v: k for k, v in marken_index.items()}
1545
- data = []
1546
- for file in sorted(output_folder.iterdir()):
1547
- if file.is_file() and file.suffix.lower() in {'.png', '.txt', '.csv', '.md'}:
1548
- name = file.stem
1549
- match = re.match(r"(\d{2})B(\d{2})([a-z0-9]+)", name, re.IGNORECASE)
1550
- if match:
1551
- markennummer, blocknummer, marke = match.groups()
1552
- factor = nummer_zu_marke.get(markennummer, marke)
1553
- factorgroup = file_to_factorgroup.get(file.name, f"{blocknummer}Unknown")
1554
- data.append({
1555
- "factor": factor,
1556
- "factorgroup": factorgroup,
1557
- "ID": name
1558
- })
1559
-
1560
- df_assets = pd.DataFrame(data, columns=["factor", "factorgroup", "ID"])
1561
-
1562
- reordered_data = []
1563
- for _, row in df_assets.iterrows():
1564
- raw_fg = str(row["factorgroup"])
1565
- group_prefix = raw_fg[:2]
1566
- try:
1567
- group = str(int(group_prefix))
1568
- except ValueError:
1569
- group = group_prefix
1570
 
1571
- reordered_data.append({
1572
- "Group": group,
1573
- "factor": row["factorgroup"],
1574
- "factorgroup": row["factor"],
1575
- "ID": row["ID"]
1576
- })
1577
 
1578
- df_reordered = pd.DataFrame(reordered_data, columns=["Group", "factor", "factorgroup", "ID"])
 
 
 
 
1579
 
1580
- with pd.ExcelWriter(final_excel_path, engine='openpyxl') as writer:
1581
- df_assets.to_excel(writer, index=False, sheet_name="Assets")
1582
- df_reordered.to_excel(writer, index=False, sheet_name="Reordered")
 
 
 
 
 
 
 
 
 
 
1583
 
1584
- return final_excel_path
 
 
 
 
 
 
1585
 
1586
  def process_files(input_folder, marken_index, output_root):
1587
- """Process and rename files according to brand numbering"""
1588
  dateien = []
1589
  renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
1590
  file_to_factorgroup = {}
@@ -1594,15 +2100,31 @@ def process_files(input_folder, marken_index, output_root):
1594
  continue
1595
  blocknummer = re.sub(r'\D', '', subfolder.name)[:2].zfill(2)
1596
 
 
 
 
 
 
1597
  for file in sorted(subfolder.iterdir()):
1598
  if file.suffix.lower() not in ALL_ALLOWED_EXTENSIONS:
1599
  continue
1600
  marke = extract_brand(file.stem)
 
 
 
 
 
 
 
 
 
 
1601
 
1602
  markennummer = marken_index[marke]
1603
  cleaned = get_cleaned_filename_without_brand(file.name, marke)
1604
 
1605
- neuer_name = f"{markennummer}B{blocknummer}{marke}{cleaned}{file.suffix.lower()}"
 
1606
  ziel = output_root / neuer_name
1607
 
1608
  if file.suffix.lower() in ALLOWED_IMAGE_EXTENSIONS:
@@ -1619,142 +2141,237 @@ def process_files(input_folder, marken_index, output_root):
1619
  def brand_renamer_tool():
1620
  st.header("Advanced Brand File Processor")
1621
  st.markdown("Automatically rename and organize brand assets with numbering and generate reports.")
1622
-
 
 
 
 
 
 
1623
  uploaded_file = st.file_uploader(
1624
  "Choose a ZIP file",
1625
  type=['zip'],
1626
  help="Upload a zip file containing your brand folders with assets."
1627
  )
1628
-
 
 
 
 
 
 
1629
  if uploaded_file:
1630
- with st.spinner("Extracting and analyzing files..."):
1631
- temp_dir = extract_zip_to_temp(uploaded_file)
1632
- input_folder = Path(temp_dir)
1633
-
1634
- items = os.listdir(temp_dir)
1635
- if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
1636
- input_folder = Path(temp_dir) / items[0]
1637
-
1638
- output_folder = Path(temp_dir) / "output"
1639
- output_folder.mkdir(exist_ok=True)
1640
-
1641
- marken_set, _, _ = analyze_files_by_filename(input_folder)
1642
-
1643
- if not marken_set:
1644
- st.error("No brands found in the uploaded files.")
1645
- return
1646
-
1647
- st.success(f"Detected brands: {', '.join(sorted(marken_set))}")
1648
-
1649
- # Brand numbering selection
1650
- st.subheader("Brand Numbering")
1651
- erste_marke = st.selectbox(
1652
- "Which brand should be number 01?",
1653
- options=sorted(marken_set),
1654
- index=0
1655
- )
1656
-
1657
- marken_index = {erste_marke: "01"}
1658
- aktuelle_nummer = 2
1659
- for marke in sorted(marken_set):
1660
- if marke != erste_marke:
1661
- marken_index[marke] = f"{aktuelle_nummer:02d}"
1662
- aktuelle_nummer += 1
1663
-
1664
- if st.button("Process Files and Generate Reports", type="primary"):
1665
- with st.spinner("Processing files..."):
1666
- # Process and rename files
1667
- renamed_files, file_to_factorgroup = process_files(
1668
- input_folder,
1669
- marken_index,
1670
- output_folder
1671
- )
1672
-
1673
- pdf_buffer, error = generate_filename_based_pdf_report(input_folder, erste_marke)
1674
- if error:
1675
- st.error(f"PDF generation failed: {error}")
1676
-
1677
- excel_path = generate_excel_report(output_folder, marken_index, file_to_factorgroup)
1678
-
1679
- zip_buffer = io.BytesIO()
1680
- with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
1681
- for file in output_folder.iterdir():
1682
- zip_file.write(file, file.name)
1683
-
1684
- zip_buffer.seek(0)
1685
-
1686
- st.success("Processing complete!")
1687
-
1688
- col1, col2, col3 = st.columns(3)
1689
-
1690
- with col1:
1691
- if pdf_buffer:
1692
- st.download_button(
1693
- label="πŸ“₯ Download PDF Report",
1694
- data=pdf_buffer.getvalue(),
1695
- file_name="Brand_Assets_Report.pdf",
1696
- mime="application/pdf"
1697
  )
1698
-
1699
- with col2:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1700
  st.download_button(
1701
- label="πŸ“Š Download Excel Report",
1702
- data=open(excel_path, 'rb').read(),
1703
- file_name="Brand_Assets_Overview.xlsx",
1704
- mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
1705
  )
1706
-
1707
- with col3:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1708
  st.download_button(
1709
- label="πŸ“¦ Download Processed Files",
1710
- data=zip_buffer.getvalue(),
1711
  file_name="Brand_Assets_Processed.zip",
1712
  mime="application/zip"
1713
  )
1714
-
1715
- shutil.rmtree(temp_dir)
 
 
1716
  else:
 
 
 
 
 
1717
  st.info("πŸ‘† Please upload a zip file to get started.")
1718
-
1719
  with st.expander("πŸ“– Instructions"):
1720
  st.markdown("""
1721
- **How to use this tool:**
1722
-
1723
- 1. Prepare a zip file with:
1724
- - Subfolders for each brand (optional)
1725
- - Files named with brand identifiers (e.g., "nike_shoe.jpg")
1726
- 2. Upload the zip file
1727
- 3. Select which brand should be numbered "01"
1728
- 4. Click "Process Files" to:
1729
- - Rename files with brand numbering
1730
- - Generate PDF and Excel reports
1731
- - Download processed files
1732
-
1733
- **Output Format:**
1734
- - `01B00nikefilename.png` (BrandNumber + Block + BrandName + OriginalName)
1735
  """)
 
1736
  def main():
1737
  st.title("πŸ”§ Brand Assets Tools")
1738
 
1739
  tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8 = st.tabs([
1740
- "PDF Report Generator",
1741
  "Excel Image Extractor",
1742
  "Brand File Renamer",
1743
- "White to Transparent",
 
1744
  "Find Smallest Dimensions",
1745
  "Resize with Transparent Canvas",
1746
  "Center on Canvas",
1747
- "Advanced Brand Processor"
1748
  ])
1749
 
1750
  with tab1:
1751
- pdf_generator_tool()
1752
  with tab2:
1753
- excel_extractor_tool()
1754
  with tab3:
1755
- file_renamer_tool()
1756
  with tab4:
1757
- white_to_transparent_tool()
1758
  with tab5:
1759
  find_smallest_dimensions_tool()
1760
  with tab6:
@@ -1762,7 +2379,7 @@ def main():
1762
  with tab7:
1763
  center_on_canvas_tool()
1764
  with tab8:
1765
- brand_renamer_tool()
1766
 
1767
  if __name__ == "__main__":
1768
  main()
 
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, processed_files_mapping=None):
310
+ """Generate PDF report based on filename brand analysis with final processed labels"""
311
  marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
312
 
313
  if not marken_set:
 
335
  nummer_zu_marke = {v: k for k, v in marken_index.items()}
336
  marken_spalten = sorted(nummer_zu_marke.items())
337
 
338
+ # Process each folder with final processed names
339
  for folder in sorted(renamed_files_by_folder_and_marke):
340
  elements.append(Paragraph(f"<b>Folder: {folder}</b>", styles['Heading2']))
341
 
 
354
  data = [headers]
355
  col_data = []
356
  max_rows = 0
357
+
358
  for _, marke in marken_spalten:
359
  eintraege = abschnitt.get(marke, [])
360
+ zellen = []
361
+ for original_path, original_name in eintraege:
362
+ # Generate the final processed ID name
363
+ blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
364
+ markennummer = marken_index[marke]
365
+ cleaned = get_cleaned_filename_without_brand(original_name, marke)
366
+ # Create the final ID without file extension for display
367
+ final_id = f"{markennummer}B{blocknummer}{marke}{cleaned}"
368
+
369
+ # Create cell with original path but final ID label
370
+ cell = get_asset_cell(original_path, final_id, len(headers))
371
+ zellen.append(cell)
372
  col_data.append(zellen)
373
  max_rows = max(max_rows, len(zellen))
374
 
 
404
  summary.append(f"Total number of all assets: {gesamt}")
405
  elements.append(Paragraph("<br/>".join(summary), styles['Normal']))
406
 
407
+ # Add brand pages with final processed labels
408
+ add_brand_pages_with_final_labels(elements, marken_spalten, renamed_files_by_folder_and_marke, marken_index)
409
 
410
  try:
411
  doc.build(elements)
 
414
  except Exception as e:
415
  return None, f"Error generating PDF: {str(e)}"
416
 
417
+ def add_brand_pages_with_final_labels(elements, marken_spalten, renamed_files_by_folder_and_marke, marken_index):
418
+ """Add brand overview pages with final processed ID labels"""
419
+ styles = getSampleStyleSheet()
420
+ for nummer, marke in marken_spalten:
421
+ assets = []
422
+ for folder in renamed_files_by_folder_and_marke:
423
+ folder_assets = renamed_files_by_folder_and_marke[folder].get(marke, [])
424
+ for original_path, original_name in folder_assets:
425
+ # Generate the final processed ID name (same logic as in Excel generation)
426
+ blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
427
+ markennummer = marken_index[marke]
428
+ cleaned = get_cleaned_filename_without_brand(original_name, marke)
429
+ final_id = f"{markennummer}B{blocknummer}{marke}{cleaned}"
430
+ assets.append((original_path, final_id))
431
+
432
+ if not assets:
433
+ continue
434
+
435
+ elements.append(PageBreak())
436
+ elements.append(Paragraph(f"<b>Brand Overview: {nummer} – {marke}</b>", styles['Heading2']))
437
+ elements.append(Spacer(1, 6))
438
+ elements.append(Paragraph(f"Number of assets: {len(assets)}", styles['Normal']))
439
+ elements.append(Spacer(1, 10))
440
+
441
+ headers = ["Asset"] * 4
442
+ data = [headers]
443
+ row = []
444
+ for i, (original_path, final_id) in enumerate(assets):
445
+ # Use final processed ID as the label
446
+ cell = get_asset_cell(original_path, final_id, 4)
447
+ row.append(cell)
448
+ if len(row) == 4:
449
+ data.append(row)
450
+ row = []
451
+ if row:
452
+ row.extend([""] * (4 - len(row)))
453
+ data.append(row)
454
+
455
+ table = Table(data, colWidths=(A4[0] - 40) / 4)
456
+ table.setStyle(TableStyle([
457
+ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
458
+ ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
459
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
460
+ ]))
461
+ elements.append(table)
462
+
463
+ def generate_two_section_pdf_report(input_folder, erste_marke=None):
464
+ """Generate PDF report with two sections: by block and by brand"""
465
+ marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
466
+
467
+ if not marken_set:
468
+ return None, "No brands found in filenames."
469
+
470
+ # Create brand index
471
+ marken_index = {}
472
+ if erste_marke and erste_marke in marken_set:
473
+ marken_index[erste_marke] = "01"
474
+ aktuelle_nummer = 2
475
+ for marke in sorted(marken_set):
476
+ if marke != erste_marke:
477
+ marken_index[marke] = f"{aktuelle_nummer:02d}"
478
+ aktuelle_nummer += 1
479
+ else:
480
+ for i, marke in enumerate(sorted(marken_set), 1):
481
+ marken_index[marke] = f"{i:02d}"
482
+
483
+ # Generate PDF
484
+ pdf_buffer = io.BytesIO()
485
+ doc = SimpleDocTemplate(pdf_buffer, pagesize=A4, leftMargin=20, rightMargin=20, topMargin=40, bottomMargin=30)
486
+ elements = []
487
+ styles = getSampleStyleSheet()
488
+
489
+ nummer_zu_marke = {v: k for k, v in marken_index.items()}
490
+ marken_spalten = sorted(nummer_zu_marke.items())
491
+
492
+ # SECTION 1: BY BLOCK/FOLDER
493
+ elements.append(Paragraph("<b>Section 1: Assets by Block</b>", styles['Title']))
494
+ elements.append(Spacer(1, 20))
495
+
496
+ for folder in sorted(renamed_files_by_folder_and_marke):
497
+ elements.append(Paragraph(f"<b>Folder: {folder}</b>", styles['Heading2']))
498
+
499
+ abschnitt = renamed_files_by_folder_and_marke[folder]
500
+ total = 0
501
+ lines = []
502
+ for nummer, marke in marken_spalten:
503
+ count = len(abschnitt.get(marke, []))
504
+ total += count
505
+ lines.append(f"{nummer} ({marke}): {count}")
506
+ lines.append(f"Total: {total}")
507
+ elements.append(Paragraph("<br/>".join(lines), styles['Normal']))
508
+ elements.append(Spacer(1, 10))
509
+
510
+ headers = [f"{nummer} ({marke})" for nummer, marke in marken_spalten]
511
+ data = [headers]
512
+ col_data = []
513
+ max_rows = 0
514
+
515
+ for _, marke in marken_spalten:
516
+ eintraege = abschnitt.get(marke, [])
517
+ zellen = []
518
+ for p, original_name in eintraege:
519
+ # Generate the ID name
520
+ blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
521
+ markennummer = marken_index[marke]
522
+ cleaned = get_cleaned_filename_without_brand(original_name, marke)
523
+ id_name = f"{markennummer}B{blocknummer}{marke}{cleaned}"
524
+
525
+ cell = get_asset_cell(p, id_name, len(headers))
526
+ zellen.append(cell)
527
+ col_data.append(zellen)
528
+ max_rows = max(max_rows, len(zellen))
529
+
530
+ for i in range(max_rows):
531
+ row = []
532
+ for col in col_data:
533
+ row.append(col[i] if i < len(col) else "")
534
+ data.append(row)
535
+
536
+ col_width = (A4[0] - 40) / len(headers)
537
+ t = Table(data, colWidths=[col_width] * len(headers))
538
+ t.setStyle(TableStyle([
539
+ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
540
+ ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
541
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
542
+ ]))
543
+ elements.append(t)
544
+ elements.append(PageBreak())
545
+
546
+ # SECTION 2: BY BRAND
547
+ elements.append(Paragraph("<b>Section 2: Assets by Brand</b>", styles['Title']))
548
+ elements.append(Spacer(1, 20))
549
+
550
+ # Total overview first
551
+ elements.append(Paragraph("<b>Total Overview</b>", styles['Heading2']))
552
+ global_counts = defaultdict(int)
553
+ for folder_data in renamed_files_by_folder_and_marke.values():
554
+ for marke, daten in folder_data.items():
555
+ global_counts[marke] += len(daten)
556
+
557
+ gesamt = 0
558
+ summary = []
559
+ for nummer, marke in marken_spalten:
560
+ count = global_counts[marke]
561
+ summary.append(f"{marke}: {count} assets")
562
+ gesamt += count
563
+ summary.append(f"Total number of all assets: {gesamt}")
564
+ elements.append(Paragraph("<br/>".join(summary), styles['Normal']))
565
+ elements.append(PageBreak())
566
+
567
+ # Individual brand pages
568
+ for nummer, marke in marken_spalten:
569
+ assets = []
570
+ for folder in renamed_files_by_folder_and_marke:
571
+ folder_assets = renamed_files_by_folder_and_marke[folder].get(marke, [])
572
+ brand_counter = 1 # Start counting from 1 for each brand in each folder
573
+ for pfad, original_name in folder_assets:
574
+ # Generate the ID name with sequential count
575
+ blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
576
+ markennummer = marken_index[marke]
577
+ count_str = f"{brand_counter:02d}"
578
+ cleaned = get_cleaned_filename_without_brand(original_name, marke)
579
+ id_name = f"{markennummer}B{blocknummer}{marke}{count_str}{cleaned}"
580
+ assets.append((pfad, id_name))
581
+ brand_counter += 1
582
+
583
+ if not assets:
584
+ continue
585
+
586
+ elements.append(PageBreak())
587
+ elements.append(Paragraph(f"<b>Brand Overview: {nummer} – {marke}</b>", styles['Heading2']))
588
+ elements.append(Spacer(1, 6))
589
+ elements.append(Paragraph(f"Assets per Brand: {', '.join([f'{k}: {len([a for a in assets if extract_brand(Path(a[1]).stem) == k])}' for k in [marke]])}", styles['Normal']))
590
+ elements.append(Paragraph(f"Total assets: {len(assets)}", styles['Normal']))
591
+ elements.append(Spacer(1, 10))
592
+
593
+ headers = ["Asset"] * 4
594
+ data = [headers]
595
+ row = []
596
+ for i, (pfad, id_name) in enumerate(assets):
597
+ cell = get_asset_cell(pfad, id_name, 4)
598
+ row.append(cell)
599
+ if len(row) == 4:
600
+ data.append(row)
601
+ row = []
602
+ if row:
603
+ row.extend([""] * (4 - len(row)))
604
+ data.append(row)
605
+
606
+ table = Table(data, colWidths=(A4[0] - 40) / 4)
607
+ table.setStyle(TableStyle([
608
+ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
609
+ ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
610
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
611
+ ]))
612
+ elements.append(table)
613
+
614
+ try:
615
+ doc.build(elements)
616
+ pdf_buffer.seek(0)
617
+ return pdf_buffer, None
618
+ except Exception as e:
619
+ return None, f"Error generating PDF: {str(e)}"
620
+
621
+
622
+ def brand_renamer_tool():
623
+ st.header("Advanced Brand File Processor")
624
+ st.markdown("Automatically rename and organize brand assets with numbering and generate reports.")
625
+
626
+ # Initialize session state for persistent results
627
+ if 'processing_complete' not in st.session_state:
628
+ st.session_state.processing_complete = False
629
+ if 'processed_data' not in st.session_state:
630
+ st.session_state.processed_data = {}
631
+
632
+ uploaded_file = st.file_uploader(
633
+ "Choose a ZIP file",
634
+ type=['zip'],
635
+ help="Upload a zip file containing your brand folders with assets."
636
+ )
637
+
638
+ # Reset processing state when new file is uploaded
639
+ if uploaded_file and 'uploaded_file_name' in st.session_state:
640
+ if st.session_state.uploaded_file_name != uploaded_file.name:
641
+ st.session_state.processing_complete = False
642
+ st.session_state.processed_data = {}
643
+
644
+ if uploaded_file:
645
+ # Store uploaded file name to detect changes
646
+ st.session_state.uploaded_file_name = uploaded_file.name
647
+
648
+ if not st.session_state.processing_complete:
649
+ with st.spinner("Extracting and analyzing files..."):
650
+ temp_dir = extract_zip_to_temp(uploaded_file)
651
+ input_folder = Path(temp_dir)
652
+
653
+ items = os.listdir(temp_dir)
654
+ if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
655
+ input_folder = Path(temp_dir) / items[0]
656
+
657
+ output_folder = Path(temp_dir) / "output"
658
+ output_folder.mkdir(exist_ok=True)
659
+
660
+ marken_set, _, _ = analyze_files_by_filename(input_folder)
661
+
662
+ if not marken_set:
663
+ st.error("No brands found in the uploaded files.")
664
+ return
665
+
666
+ st.success(f"Detected brands: {', '.join(sorted(marken_set))}")
667
+
668
+ # Brand numbering selection
669
+ st.subheader("Brand Numbering")
670
+ erste_marke = st.selectbox(
671
+ "Which brand should be number 01?",
672
+ options=sorted(marken_set),
673
+ index=0
674
+ )
675
+
676
+ marken_index = {erste_marke: "01"}
677
+ aktuelle_nummer = 2
678
+ for marke in sorted(marken_set):
679
+ if marke != erste_marke:
680
+ marken_index[marke] = f"{aktuelle_nummer:02d}"
681
+ aktuelle_nummer += 1
682
+
683
+ if st.button("Process Files and Generate Reports", type="primary"):
684
+ with st.spinner("Processing files..."):
685
+ # Process and rename files
686
+ renamed_files, file_to_factorgroup = process_files(
687
+ input_folder,
688
+ marken_index,
689
+ output_folder
690
+ )
691
+
692
+ # Generate PDF with TWO SECTIONS (by block and by brand)
693
+ pdf_buffer, error = generate_two_section_pdf_report(
694
+ input_folder,
695
+ erste_marke
696
+ )
697
+ if error:
698
+ st.error(f"PDF generation failed: {error}")
699
+
700
+ excel_path = generate_excel_report(output_folder, marken_index, file_to_factorgroup)
701
+
702
+ # Create individual file buffers
703
+ zip_buffer = io.BytesIO()
704
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
705
+ for file in output_folder.iterdir():
706
+ zip_file.write(file, file.name)
707
+ zip_buffer.seek(0)
708
+
709
+ # Create combined download with all files
710
+ combined_zip_buffer = io.BytesIO()
711
+ with zipfile.ZipFile(combined_zip_buffer, 'w', zipfile.ZIP_DEFLATED) as combined_zip:
712
+ # Add processed files
713
+ for file in output_folder.iterdir():
714
+ combined_zip.write(file, f"processed_files/{file.name}")
715
+
716
+ # Add PDF report if available
717
+ if pdf_buffer:
718
+ combined_zip.writestr("reports/Brand_Assets_Report_Two_Sections.pdf", pdf_buffer.getvalue())
719
+
720
+ # Add Excel report
721
+ with open(excel_path, 'rb') as excel_file:
722
+ combined_zip.writestr("reports/Brand_Assets_Overview.xlsx", excel_file.read())
723
+
724
+ combined_zip_buffer.seek(0)
725
+
726
+ # Store processed data in session state
727
+ st.session_state.processed_data = {
728
+ 'pdf_buffer': pdf_buffer,
729
+ 'excel_path': excel_path,
730
+ 'zip_buffer': zip_buffer,
731
+ 'combined_zip_buffer': combined_zip_buffer,
732
+ 'temp_dir': temp_dir,
733
+ 'renamed_files': renamed_files
734
+ }
735
+ st.session_state.processing_complete = True
736
+
737
+ # Force rerun to show download buttons
738
+ st.rerun()
739
+
740
+ # Show download options if processing is complete
741
+ if st.session_state.processing_complete:
742
+ st.success("βœ… Processing complete! PDF now includes both sections: by block and by brand.")
743
+
744
+ # Display a preview of processed names
745
+ with st.expander("Preview Final Processed Labels"):
746
+ if 'renamed_files' in st.session_state.processed_data:
747
+ st.write("Sample of final processed labels (as used in both PDF sections and Excel):")
748
+ count = 0
749
+ for folder_data in st.session_state.processed_data['renamed_files'].values():
750
+ for brand_data in folder_data.values():
751
+ for _, processed_name in brand_data:
752
+ if count < 10: # Show first 10
753
+ # Remove file extension for display
754
+ label_without_ext = Path(processed_name).stem
755
+ st.write(f"πŸ“„ {label_without_ext}")
756
+ count += 1
757
+ if count >= 10:
758
+ st.info("Showing first 10 labels...")
759
+
760
+ # Option to start over
761
+ if st.button("πŸ”„ Process New File", help="Clear results and upload a new file"):
762
+ st.session_state.processing_complete = False
763
+ st.session_state.processed_data = {}
764
+ if 'temp_dir' in st.session_state.processed_data:
765
+ try:
766
+ shutil.rmtree(st.session_state.processed_data['temp_dir'])
767
+ except:
768
+ pass
769
+ st.rerun()
770
+
771
+ st.markdown("---")
772
+
773
+ # Combined download option (recommended)
774
+ st.subheader("πŸ“¦ Complete Package Download")
775
+ st.markdown("**Recommended:** Download everything in one convenient package")
776
+
777
+ if st.session_state.processed_data.get('combined_zip_buffer'):
778
+ st.download_button(
779
+ label="🎁 Download Complete Package (All Files + Reports)",
780
+ data=st.session_state.processed_data['combined_zip_buffer'].getvalue(),
781
+ file_name="Brand_Assets_Complete_Package.zip",
782
+ mime="application/zip",
783
+ type="primary"
784
+ )
785
+
786
+ st.markdown("---")
787
+
788
+ # Individual download options
789
+ st.subheader("πŸ“ Individual Downloads")
790
+ st.markdown("Or download items separately:")
791
+
792
+ col1, col2, col3 = st.columns(3)
793
+
794
+ with col1:
795
+ if st.session_state.processed_data.get('pdf_buffer'):
796
+ st.download_button(
797
+ label="πŸ“„ PDF Report (Two Sections)",
798
+ data=st.session_state.processed_data['pdf_buffer'].getvalue(),
799
+ file_name="Brand_Assets_Report_Two_Sections.pdf",
800
+ mime="application/pdf"
801
+ )
802
+ else:
803
+ st.info("PDF report not available")
804
+
805
+ with col2:
806
+ if st.session_state.processed_data.get('excel_path'):
807
+ try:
808
+ with open(st.session_state.processed_data['excel_path'], 'rb') as excel_file:
809
+ st.download_button(
810
+ label="πŸ“Š Excel Report (Final Labels)",
811
+ data=excel_file.read(),
812
+ file_name="Brand_Assets_Overview.xlsx",
813
+ mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
814
+ )
815
+ except:
816
+ st.info("Excel report not available")
817
+
818
+ with col3:
819
+ if st.session_state.processed_data.get('zip_buffer'):
820
+ st.download_button(
821
+ label="πŸ“¦ Processed Files",
822
+ data=st.session_state.processed_data['zip_buffer'].getvalue(),
823
+ file_name="Brand_Assets_Processed.zip",
824
+ mime="application/zip"
825
+ )
826
+
827
+ st.markdown("---")
828
+ st.success("πŸ’‘ **Updated:** PDF now contains two distinct sections matching your requirements!")
829
+
830
+ else:
831
+ # Reset session state when no file is uploaded
832
+ if st.session_state.processing_complete:
833
+ st.session_state.processing_complete = False
834
+ st.session_state.processed_data = {}
835
+
836
+ st.info("πŸ‘† Please upload a zip file to get started.")
837
+
838
+ with st.expander("πŸ“– Instructions"):
839
+ st.markdown("""
840
+ """)
841
+
842
  def pdf_generator_tool():
843
  st.header("Brand Assets PDF Generator")
844
  st.markdown("Upload a zip file containing brand assets to generate a comprehensive PDF report.")
 
1817
  full_letters = clean_letters_only(Path(filename).stem.lower())
1818
  return full_letters.replace(brand, '', 1)
1819
 
1820
+ def generate_excel_report(output_folder: Path, marken_index: dict, file_to_factorgroup: dict):
1821
+ final_excel_path = output_folder / "IcAt_Overview_Final.xlsx"
1822
+
1823
+ nummer_zu_marke = {v: k for k, v in marken_index.items()}
1824
+ data = []
1825
+ for file in sorted(output_folder.iterdir()):
1826
+ if file.is_file() and file.suffix.lower() in {'.png', '.txt', '.csv', '.md'}:
1827
+ name = file.stem
1828
+ match = re.match(r"(\d{2})B(\d{2})([a-z0-9]+)", name, re.IGNORECASE)
1829
+ if match:
1830
+ markennummer, blocknummer, marke = match.groups()
1831
+ factor = nummer_zu_marke.get(markennummer, marke)
1832
+
1833
+ # Get factorgroup and remove underscores
1834
+ factorgroup = file_to_factorgroup.get(file.name, f"{blocknummer}Unknown")
1835
+ factorgroup = factorgroup.replace('_', '') # Remove all underscores
1836
+
1837
+ data.append({
1838
+ "factor": factor,
1839
+ "factorgroup": factorgroup,
1840
+ "ID": name
1841
+ })
1842
+
1843
+ df_assets = pd.DataFrame(data, columns=["factor", "factorgroup", "ID"])
1844
+
1845
+ reordered_data = []
1846
+ for _, row in df_assets.iterrows():
1847
+ raw_fg = str(row["factorgroup"])
1848
+ group_prefix = raw_fg[:2]
1849
+ try:
1850
+ group = str(int(group_prefix))
1851
+ except ValueError:
1852
+ group = group_prefix
1853
+
1854
+ # Also remove underscores from the reordered data
1855
+ clean_factor = str(row["factorgroup"]).replace('_', '')
1856
+ clean_factorgroup = str(row["factor"]).replace('_', '')
1857
+
1858
+ reordered_data.append({
1859
+ "Group": group,
1860
+ "factor": clean_factor,
1861
+ "factorgroup": clean_factorgroup,
1862
+ "ID": row["ID"]
1863
+ })
1864
+
1865
+ df_reordered = pd.DataFrame(reordered_data, columns=["Group", "factor", "factorgroup", "ID"])
1866
+
1867
+ with pd.ExcelWriter(final_excel_path, engine='openpyxl') as writer:
1868
+ df_assets.to_excel(writer, index=False, sheet_name="Assets")
1869
+ df_reordered.to_excel(writer, index=False, sheet_name="Reordered")
1870
+
1871
+ return final_excel_path
1872
+
1873
+
1874
  def get_asset_cell(file_path, filename, col_count):
1875
  """Create optimized asset cell for PDF with better image handling"""
1876
  ext = Path(file_path).suffix.lower()
 
1937
 
1938
  return marken_set, renamed_files_by_folder_and_marke, dateien
1939
 
1940
+ def generate_filename_based_pdf_report(input_folder, erste_marke=None, renamed_files_mapping=None):
1941
+ """Generate PDF report based on filename brand analysis with correct ID labels"""
1942
  marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
1943
 
1944
  if not marken_set:
 
1986
  max_rows = 0
1987
  for _, marke in marken_spalten:
1988
  eintraege = abschnitt.get(marke, [])
1989
+ zellen = []
1990
+ for p, original_name in eintraege:
1991
+ # Generate the ID name in the same format as used in Excel
1992
+ blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
1993
+ markennummer = marken_index[marke]
1994
+ cleaned = get_cleaned_filename_without_brand(original_name, marke)
1995
+ # Remove file extension for the ID
1996
+ id_name = f"{markennummer}B{blocknummer}{marke}{cleaned}"
1997
+
1998
+ # Use the ID name as the label instead of original filename
1999
+ cell = get_asset_cell(p, id_name, len(headers))
2000
+ zellen.append(cell)
2001
  col_data.append(zellen)
2002
  max_rows = max(max_rows, len(zellen))
2003
 
 
2033
  summary.append(f"Total number of all assets: {gesamt}")
2034
  elements.append(Paragraph("<br/>".join(summary), styles['Normal']))
2035
 
2036
+ # Add brand pages with corrected ID labels
2037
+ add_brand_pages_with_id_labels(elements, marken_spalten, renamed_files_by_folder_and_marke, marken_index)
2038
+
2039
  try:
2040
  doc.build(elements)
2041
  pdf_buffer.seek(0)
 
2043
  except Exception as e:
2044
  return None, f"Error generating PDF: {str(e)}"
2045
 
2046
+ def add_brand_pages_with_id_labels(elements, marken_spalten, renamed_files_by_folder_and_marke, marken_index):
2047
+ """Add brand overview pages with ID labels instead of filenames"""
2048
+ styles = getSampleStyleSheet()
2049
+ for nummer, marke in marken_spalten:
2050
+ assets = []
2051
+ for folder in renamed_files_by_folder_and_marke:
2052
+ folder_assets = renamed_files_by_folder_and_marke[folder].get(marke, [])
2053
+ for pfad, original_name in folder_assets:
2054
+ # Generate the ID name in the same format as used in Excel
2055
+ blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
2056
+ markennummer = marken_index[marke]
2057
+ cleaned = get_cleaned_filename_without_brand(original_name, marke)
2058
+ id_name = f"{markennummer}B{blocknummer}{marke}{cleaned}"
2059
+ assets.append((pfad, id_name))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2060
 
2061
+ if not assets:
2062
+ continue
 
 
 
 
2063
 
2064
+ elements.append(PageBreak())
2065
+ elements.append(Paragraph(f"<b>Brand Overview: {nummer} – {marke}</b>", styles['Heading2']))
2066
+ elements.append(Spacer(1, 6))
2067
+ elements.append(Paragraph(f"Number of assets: {len(assets)}", styles['Normal']))
2068
+ elements.append(Spacer(1, 10))
2069
 
2070
+ headers = ["Asset"] * 4
2071
+ data = [headers]
2072
+ row = []
2073
+ for i, (pfad, id_name) in enumerate(assets):
2074
+ # Use ID name as the label
2075
+ cell = get_asset_cell(pfad, id_name, 4)
2076
+ row.append(cell)
2077
+ if len(row) == 4:
2078
+ data.append(row)
2079
+ row = []
2080
+ if row:
2081
+ row.extend([""] * (4 - len(row)))
2082
+ data.append(row)
2083
 
2084
+ table = Table(data, colWidths=(A4[0] - 40) / 4)
2085
+ table.setStyle(TableStyle([
2086
+ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
2087
+ ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
2088
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
2089
+ ]))
2090
+ elements.append(table)
2091
 
2092
  def process_files(input_folder, marken_index, output_root):
2093
+ """Process and rename files according to brand numbering with sequential counting per brand/block"""
2094
  dateien = []
2095
  renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
2096
  file_to_factorgroup = {}
 
2100
  continue
2101
  blocknummer = re.sub(r'\D', '', subfolder.name)[:2].zfill(2)
2102
 
2103
+ # Count files per brand in this folder for sequential numbering
2104
+ brand_counters = defaultdict(int)
2105
+
2106
+ # First pass: count files per brand to establish proper numbering
2107
+ files_to_process = []
2108
  for file in sorted(subfolder.iterdir()):
2109
  if file.suffix.lower() not in ALL_ALLOWED_EXTENSIONS:
2110
  continue
2111
  marke = extract_brand(file.stem)
2112
+ brand_counters[marke] += 1
2113
+ files_to_process.append((file, marke))
2114
+
2115
+ # Reset counters for actual processing
2116
+ brand_counters = defaultdict(int)
2117
+
2118
+ # Second pass: process files with sequential numbering
2119
+ for file, marke in files_to_process:
2120
+ brand_counters[marke] += 1 # Increment counter for this brand
2121
+ count_str = f"{brand_counters[marke]:02d}" # Format as 01, 02, 03, etc.
2122
 
2123
  markennummer = marken_index[marke]
2124
  cleaned = get_cleaned_filename_without_brand(file.name, marke)
2125
 
2126
+ # New format: markennummer + B + blocknummer + marke + count + cleaned + extension
2127
+ neuer_name = f"{markennummer}B{blocknummer}{marke}{count_str}{cleaned}{file.suffix.lower()}"
2128
  ziel = output_root / neuer_name
2129
 
2130
  if file.suffix.lower() in ALLOWED_IMAGE_EXTENSIONS:
 
2141
  def brand_renamer_tool():
2142
  st.header("Advanced Brand File Processor")
2143
  st.markdown("Automatically rename and organize brand assets with numbering and generate reports.")
2144
+
2145
+ # Initialize session state for persistent results
2146
+ if 'processing_complete' not in st.session_state:
2147
+ st.session_state.processing_complete = False
2148
+ if 'processed_data' not in st.session_state:
2149
+ st.session_state.processed_data = {}
2150
+
2151
  uploaded_file = st.file_uploader(
2152
  "Choose a ZIP file",
2153
  type=['zip'],
2154
  help="Upload a zip file containing your brand folders with assets."
2155
  )
2156
+
2157
+ # Reset processing state when new file is uploaded
2158
+ if uploaded_file and 'uploaded_file_name' in st.session_state:
2159
+ if st.session_state.uploaded_file_name != uploaded_file.name:
2160
+ st.session_state.processing_complete = False
2161
+ st.session_state.processed_data = {}
2162
+
2163
  if uploaded_file:
2164
+ # Store uploaded file name to detect changes
2165
+ st.session_state.uploaded_file_name = uploaded_file.name
2166
+
2167
+ if not st.session_state.processing_complete:
2168
+ with st.spinner("Extracting and analyzing files..."):
2169
+ temp_dir = extract_zip_to_temp(uploaded_file)
2170
+ input_folder = Path(temp_dir)
2171
+
2172
+ items = os.listdir(temp_dir)
2173
+ if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
2174
+ input_folder = Path(temp_dir) / items[0]
2175
+
2176
+ output_folder = Path(temp_dir) / "output"
2177
+ output_folder.mkdir(exist_ok=True)
2178
+
2179
+ marken_set, _, _ = analyze_files_by_filename(input_folder)
2180
+
2181
+ if not marken_set:
2182
+ st.error("No brands found in the uploaded files.")
2183
+ return
2184
+
2185
+ st.success(f"Detected brands: {', '.join(sorted(marken_set))}")
2186
+
2187
+ # Brand numbering selection
2188
+ st.subheader("Brand Numbering")
2189
+ erste_marke = st.selectbox(
2190
+ "Which brand should be number 01?",
2191
+ options=sorted(marken_set),
2192
+ index=0
2193
+ )
2194
+
2195
+ marken_index = {erste_marke: "01"}
2196
+ aktuelle_nummer = 2
2197
+ for marke in sorted(marken_set):
2198
+ if marke != erste_marke:
2199
+ marken_index[marke] = f"{aktuelle_nummer:02d}"
2200
+ aktuelle_nummer += 1
2201
+
2202
+ if st.button("Process Files and Generate Reports", type="primary"):
2203
+ with st.spinner("Processing files..."):
2204
+ # Process and rename files
2205
+ renamed_files, file_to_factorgroup = process_files(
2206
+ input_folder,
2207
+ marken_index,
2208
+ output_folder
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2209
  )
2210
+
2211
+ # Generate PDF with corrected ID labels
2212
+ pdf_buffer, error = generate_filename_based_pdf_report(
2213
+ input_folder,
2214
+ erste_marke,
2215
+ renamed_files # Pass the renamed files mapping
2216
+ )
2217
+ if error:
2218
+ st.error(f"PDF generation failed: {error}")
2219
+
2220
+ excel_path = generate_excel_report(output_folder, marken_index, file_to_factorgroup)
2221
+
2222
+ # Create individual file buffers
2223
+ zip_buffer = io.BytesIO()
2224
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
2225
+ for file in output_folder.iterdir():
2226
+ zip_file.write(file, file.name)
2227
+ zip_buffer.seek(0)
2228
+
2229
+ # Create combined download with all files
2230
+ combined_zip_buffer = io.BytesIO()
2231
+ with zipfile.ZipFile(combined_zip_buffer, 'w', zipfile.ZIP_DEFLATED) as combined_zip:
2232
+ # Add processed files
2233
+ for file in output_folder.iterdir():
2234
+ combined_zip.write(file, f"processed_files/{file.name}")
2235
+
2236
+ # Add PDF report if available
2237
+ if pdf_buffer:
2238
+ combined_zip.writestr("reports/Brand_Assets_Report.pdf", pdf_buffer.getvalue())
2239
+
2240
+ # Add Excel report
2241
+ with open(excel_path, 'rb') as excel_file:
2242
+ combined_zip.writestr("reports/Brand_Assets_Overview.xlsx", excel_file.read())
2243
+
2244
+ combined_zip_buffer.seek(0)
2245
+
2246
+ # Store processed data in session state
2247
+ st.session_state.processed_data = {
2248
+ 'pdf_buffer': pdf_buffer,
2249
+ 'excel_path': excel_path,
2250
+ 'zip_buffer': zip_buffer,
2251
+ 'combined_zip_buffer': combined_zip_buffer,
2252
+ 'temp_dir': temp_dir,
2253
+ 'renamed_files': renamed_files # Store for potential reuse
2254
+ }
2255
+ st.session_state.processing_complete = True
2256
+
2257
+ # Force rerun to show download buttons
2258
+ st.rerun()
2259
+
2260
+ # Show download options if processing is complete
2261
+ if st.session_state.processing_complete:
2262
+ st.success("Processing complete!")
2263
+
2264
+ # Display a preview of processed names
2265
+ with st.expander("Preview Processed Names"):
2266
+ if 'renamed_files' in st.session_state.processed_data:
2267
+ st.write("First 10 processed filenames:")
2268
+ for i, (old_name, new_name) in enumerate(list(st.session_state.processed_data['renamed_files'].items())[:10]):
2269
+ st.write(f"{old_name} β†’ {new_name}")
2270
+
2271
+ # Option to start over
2272
+ if st.button("πŸ”„ Process New File", help="Clear results and upload a new file"):
2273
+ st.session_state.processing_complete = False
2274
+ st.session_state.processed_data = {}
2275
+ if 'temp_dir' in st.session_state.processed_data:
2276
+ try:
2277
+ shutil.rmtree(st.session_state.processed_data['temp_dir'])
2278
+ except:
2279
+ pass
2280
+ st.rerun()
2281
+
2282
+ st.markdown("---")
2283
+
2284
+ # Combined download option (recommended)
2285
+ st.subheader("πŸ“¦ Complete Package Download")
2286
+ st.markdown("**Recommended:** Download everything in one convenient package")
2287
+
2288
+ if st.session_state.processed_data.get('combined_zip_buffer'):
2289
+ st.download_button(
2290
+ label="🎁 Download Complete Package (All Files + Reports)",
2291
+ data=st.session_state.processed_data['combined_zip_buffer'].getvalue(),
2292
+ file_name="Brand_Assets_Complete_Package.zip",
2293
+ mime="application/zip",
2294
+ type="primary"
2295
+ )
2296
+
2297
+ st.markdown("---")
2298
+
2299
+ # Individual download options
2300
+ st.subheader("πŸ“ Individual Downloads")
2301
+ st.markdown("Or download items separately:")
2302
+
2303
+ col1, col2, col3 = st.columns(3)
2304
+
2305
+ with col1:
2306
+ if st.session_state.processed_data.get('pdf_buffer'):
2307
  st.download_button(
2308
+ label="πŸ“„ PDF Report",
2309
+ data=st.session_state.processed_data['pdf_buffer'].getvalue(),
2310
+ file_name="Brand_Assets_Report.pdf",
2311
+ mime="application/pdf"
2312
  )
2313
+ else:
2314
+ st.info("PDF report not available")
2315
+
2316
+ with col2:
2317
+ if st.session_state.processed_data.get('excel_path'):
2318
+ try:
2319
+ with open(st.session_state.processed_data['excel_path'], 'rb') as excel_file:
2320
+ st.download_button(
2321
+ label="πŸ“Š Excel Report",
2322
+ data=excel_file.read(),
2323
+ file_name="Brand_Assets_Overview.xlsx",
2324
+ mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
2325
+ )
2326
+ except:
2327
+ st.info("Excel report not available")
2328
+
2329
+ with col3:
2330
+ if st.session_state.processed_data.get('zip_buffer'):
2331
  st.download_button(
2332
+ label="πŸ“¦ Processed Files",
2333
+ data=st.session_state.processed_data['zip_buffer'].getvalue(),
2334
  file_name="Brand_Assets_Processed.zip",
2335
  mime="application/zip"
2336
  )
2337
+
2338
+ st.markdown("---")
2339
+ st.info("πŸ’‘ **Tip:** Downloads will remain available until you upload a new file or click 'Process New File'")
2340
+
2341
  else:
2342
+ # Reset session state when no file is uploaded
2343
+ if st.session_state.processing_complete:
2344
+ st.session_state.processing_complete = False
2345
+ st.session_state.processed_data = {}
2346
+
2347
  st.info("πŸ‘† Please upload a zip file to get started.")
2348
+
2349
  with st.expander("πŸ“– Instructions"):
2350
  st.markdown("""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2351
  """)
2352
+
2353
  def main():
2354
  st.title("πŸ”§ Brand Assets Tools")
2355
 
2356
  tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8 = st.tabs([
 
2357
  "Excel Image Extractor",
2358
  "Brand File Renamer",
2359
+ "PDF Report Generator",
2360
+ "Advanced Brand Processor",
2361
  "Find Smallest Dimensions",
2362
  "Resize with Transparent Canvas",
2363
  "Center on Canvas",
2364
+ "White to Transparent",
2365
  ])
2366
 
2367
  with tab1:
2368
+ excel_extractor_tool()
2369
  with tab2:
2370
+ file_renamer_tool()
2371
  with tab3:
2372
+ pdf_generator_tool()
2373
  with tab4:
2374
+ brand_renamer_tool()
2375
  with tab5:
2376
  find_smallest_dimensions_tool()
2377
  with tab6:
 
2379
  with tab7:
2380
  center_on_canvas_tool()
2381
  with tab8:
2382
+ white_to_transparent_tool()
2383
 
2384
  if __name__ == "__main__":
2385
  main()