Gnanashri Kota Venkatesh commited on
Commit
ad25e7d
Β·
unverified Β·
1 Parent(s): 4296f34

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +399 -20
app.py CHANGED
@@ -1,13 +1,3 @@
1
- import sys
2
- import warnings
3
-
4
- try:
5
- import cv2
6
- CV2_AVAILABLE = True
7
- except ImportError as e:
8
- CV2_AVAILABLE = False
9
- warnings.warn(f"OpenCV not available: {str(e)} - some features disabled")
10
-
11
  import os
12
  import re
13
  import tempfile
@@ -17,21 +7,18 @@ from pathlib import Path
17
  from collections import defaultdict
18
  from reportlab.lib.pagesizes import A4
19
  from reportlab.platypus import (
20
- SimpleDocTemplate, Table, TableStyle, Image as RLImage,
21
- Paragraph, Spacer, PageBreak, KeepInFrame
22
  )
23
  from reportlab.lib.styles import getSampleStyleSheet
24
  from reportlab.lib import colors
25
- from PIL import Image as PILImage, ImageOps
26
  import io
27
  import shutil
28
- import numpy as np
29
  import pandas as pd
 
30
 
31
-
32
-
33
-
34
-
35
  st.set_page_config(
36
  page_title="Brand Assets Tools",
37
  page_icon="πŸ”§",
@@ -1372,17 +1359,407 @@ def center_on_canvas_tool():
1372
  - Original aspect ratio is maintained
1373
  """)
1374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1375
  def main():
1376
  st.title("πŸ”§ Brand Assets Tools")
1377
 
1378
- tab1, tab2, tab3, tab4, tab5, tab6, tab7 = st.tabs([
1379
  "PDF Report Generator",
1380
  "Excel Image Extractor",
1381
  "Brand File Renamer",
1382
  "White to Transparent",
1383
  "Find Smallest Dimensions",
1384
  "Resize with Transparent Canvas",
1385
- "Center on Canvas"
 
1386
  ])
1387
 
1388
  with tab1:
@@ -1399,6 +1776,8 @@ def main():
1399
  resize_with_transparent_canvas_tool()
1400
  with tab7:
1401
  center_on_canvas_tool()
 
 
1402
 
1403
  if __name__ == "__main__":
1404
  main()
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import re
3
  import tempfile
 
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(
23
  page_title="Brand Assets Tools",
24
  page_icon="πŸ”§",
 
1359
  - Original aspect ratio is maintained
1360
  """)
1361
 
1362
+ # ========== Shared Functions ==========
1363
+ def extract_zip_to_temp(uploaded_file):
1364
+ """Extract uploaded zip file to temporary directory"""
1365
+ temp_dir = tempfile.mkdtemp()
1366
+ with zipfile.ZipFile(uploaded_file, 'r') as zip_ref:
1367
+ zip_ref.extractall(temp_dir)
1368
+ return temp_dir
1369
+
1370
+ def extract_brand(file_stem):
1371
+ """Extract brand name from filename using pattern matching"""
1372
+ parts = re.split(r'[ _\-]', file_stem)
1373
+ return re.sub(r'[^a-z0-9]', '', parts[0].lower()) if parts else "unknown"
1374
+
1375
+ def clean_letters_only(text):
1376
+ return re.sub(r'[^A-Za-z]', '', text)
1377
+
1378
+ def get_cleaned_filename_without_brand(filename, brand):
1379
+ full_letters = clean_letters_only(Path(filename).stem.lower())
1380
+ return full_letters.replace(brand, '', 1)
1381
+
1382
+ def get_asset_cell(file_path, filename, col_count):
1383
+ """Create optimized asset cell for PDF with better image handling"""
1384
+ ext = Path(file_path).suffix.lower()
1385
+ styles = getSampleStyleSheet()
1386
+
1387
+ try:
1388
+ if ext in ALLOWED_IMAGE_EXTENSIONS:
1389
+ with PILImage.open(file_path) as img:
1390
+ orig_width, orig_height = img.size
1391
+ available_width = A4[0] - 40
1392
+ max_width = available_width / col_count
1393
+ max_height = 120
1394
+
1395
+ aspect_ratio = orig_width / orig_height
1396
+ width = max_width
1397
+ height = width / aspect_ratio
1398
+
1399
+ if height > max_height:
1400
+ height = max_height
1401
+ width = height * aspect_ratio
1402
+
1403
+ buffer = io.BytesIO()
1404
+ img.convert("RGB").save(buffer, format='PNG')
1405
+ buffer.seek(0)
1406
+ rl_img = RLImage(buffer, width=width, height=height)
1407
+
1408
+ frame = KeepInFrame(max_width, max_height + 30, content=[
1409
+ rl_img,
1410
+ Paragraph(filename, styles['Normal'])
1411
+ ], hAlign='CENTER')
1412
+
1413
+ return frame
1414
+ else:
1415
+ return Paragraph(f"{filename}", styles['Normal'])
1416
+ except Exception as e:
1417
+ return Paragraph(f"[Image Error]<br/>{filename}", styles['Normal'])
1418
+
1419
+ # ========== PDF Generator Functions ==========
1420
+ def analyze_files_by_filename(input_folder):
1421
+ """Analyze files by extracting brand names from filenames"""
1422
+ dateien = []
1423
+ marken_set = set()
1424
+ renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
1425
+
1426
+ for subfolder in sorted(Path(input_folder).iterdir()):
1427
+ if not subfolder.is_dir():
1428
+ continue
1429
+
1430
+ for file in sorted(subfolder.iterdir()):
1431
+ if file.suffix.lower() not in ALL_ALLOWED_EXTENSIONS:
1432
+ continue
1433
+ marke = extract_brand(file.stem)
1434
+ marken_set.add(marke)
1435
+ dateien.append({
1436
+ "original_file": file,
1437
+ "original_folder": subfolder.name,
1438
+ "marke": marke
1439
+ })
1440
+
1441
+ for eintrag in dateien:
1442
+ orig = eintrag["original_file"]
1443
+ marke = eintrag["marke"]
1444
+ folder_name = eintrag["original_folder"]
1445
+ renamed_files_by_folder_and_marke[folder_name][marke].append((orig, orig.name))
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:
1454
+ return None, "No brands found in filenames."
1455
+
1456
+ # Create brand index
1457
+ marken_index = {}
1458
+ if erste_marke and erste_marke in marken_set:
1459
+ marken_index[erste_marke] = "01"
1460
+ aktuelle_nummer = 2
1461
+ for marke in sorted(marken_set):
1462
+ if marke != erste_marke:
1463
+ marken_index[marke] = f"{aktuelle_nummer:02d}"
1464
+ aktuelle_nummer += 1
1465
+ else:
1466
+ for i, marke in enumerate(sorted(marken_set), 1):
1467
+ marken_index[marke] = f"{i:02d}"
1468
+
1469
+ # Generate PDF
1470
+ pdf_buffer = io.BytesIO()
1471
+ doc = SimpleDocTemplate(pdf_buffer, pagesize=A4, leftMargin=20, rightMargin=20, topMargin=40, bottomMargin=30)
1472
+ elements = []
1473
+ styles = getSampleStyleSheet()
1474
+
1475
+ nummer_zu_marke = {v: k for k, v in marken_index.items()}
1476
+ marken_spalten = sorted(nummer_zu_marke.items())
1477
+
1478
+ # Overview by folder
1479
+ for folder in sorted(renamed_files_by_folder_and_marke):
1480
+ elements.append(Paragraph(f"<b>Folder: {folder}</b>", styles['Heading2']))
1481
+
1482
+ abschnitt = renamed_files_by_folder_and_marke[folder]
1483
+ total = 0
1484
+ lines = []
1485
+ for nummer, marke in marken_spalten:
1486
+ count = len(abschnitt.get(marke, []))
1487
+ total += count
1488
+ lines.append(f"{nummer} ({marke}): {count}")
1489
+ lines.append(f"Total: {total}")
1490
+ elements.append(Paragraph("<br/>".join(lines), styles['Normal']))
1491
+ elements.append(Spacer(1, 10))
1492
+
1493
+ headers = [f"{nummer} ({marke})" for nummer, marke in marken_spalten]
1494
+ data = [headers]
1495
+ col_data = []
1496
+ max_rows = 0
1497
+ for _, marke in marken_spalten:
1498
+ eintraege = abschnitt.get(marke, [])
1499
+ zellen = [get_asset_cell(p, n, len(headers)) for p, n in eintraege]
1500
+ col_data.append(zellen)
1501
+ max_rows = max(max_rows, len(zellen))
1502
+
1503
+ for i in range(max_rows):
1504
+ row = []
1505
+ for col in col_data:
1506
+ row.append(col[i] if i < len(col) else "")
1507
+ data.append(row)
1508
+
1509
+ col_width = (A4[0] - 40) / len(headers)
1510
+ t = Table(data, colWidths=[col_width] * len(headers))
1511
+ t.setStyle(TableStyle([
1512
+ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
1513
+ ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
1514
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
1515
+ ]))
1516
+ elements.append(t)
1517
+ elements.append(PageBreak())
1518
+
1519
+ # Total overview
1520
+ elements.append(Paragraph("<b>Total Overview</b>", styles['Heading2']))
1521
+ global_counts = defaultdict(int)
1522
+ for folder_data in renamed_files_by_folder_and_marke.values():
1523
+ for marke, daten in folder_data.items():
1524
+ global_counts[marke] += len(daten)
1525
+
1526
+ gesamt = 0
1527
+ summary = []
1528
+ for nummer, marke in marken_spalten:
1529
+ count = global_counts[marke]
1530
+ summary.append(f"{marke}: {count} assets")
1531
+ gesamt += count
1532
+ summary.append(f"Total number of all assets: {gesamt}")
1533
+ elements.append(Paragraph("<br/>".join(summary), styles['Normal']))
1534
+
1535
+ try:
1536
+ doc.build(elements)
1537
+ pdf_buffer.seek(0)
1538
+ return pdf_buffer, None
1539
+ except Exception as e:
1540
+ return None, f"Error generating PDF: {str(e)}"
1541
+
1542
+ # ========== Excel Report Functions ==========
1543
+ def generate_excel_report(output_folder: Path, marken_index: dict, file_to_factorgroup: dict):
1544
+ final_excel_path = output_folder / "IcAt_Overview_Final.xlsx"
1545
+
1546
+ nummer_zu_marke = {v: k for k, v in marken_index.items()}
1547
+ data = []
1548
+ for file in sorted(output_folder.iterdir()):
1549
+ if file.is_file() and file.suffix.lower() in {'.png', '.txt', '.csv', '.md'}:
1550
+ name = file.stem
1551
+ match = re.match(r"(\d{2})B(\d{2})([a-z0-9]+)", name, re.IGNORECASE)
1552
+ if match:
1553
+ markennummer, blocknummer, marke = match.groups()
1554
+ factor = nummer_zu_marke.get(markennummer, marke)
1555
+ factorgroup = file_to_factorgroup.get(file.name, f"{blocknummer}Unknown")
1556
+ data.append({
1557
+ "factor": factor,
1558
+ "factorgroup": factorgroup,
1559
+ "ID": name
1560
+ })
1561
+
1562
+ df_assets = pd.DataFrame(data, columns=["factor", "factorgroup", "ID"])
1563
+
1564
+ reordered_data = []
1565
+ for _, row in df_assets.iterrows():
1566
+ raw_fg = str(row["factorgroup"])
1567
+ group_prefix = raw_fg[:2]
1568
+ try:
1569
+ group = str(int(group_prefix))
1570
+ except ValueError:
1571
+ group = group_prefix
1572
+
1573
+ reordered_data.append({
1574
+ "Group": group,
1575
+ "factor": row["factorgroup"],
1576
+ "factorgroup": row["factor"],
1577
+ "ID": row["ID"]
1578
+ })
1579
+
1580
+ df_reordered = pd.DataFrame(reordered_data, columns=["Group", "factor", "factorgroup", "ID"])
1581
+
1582
+ with pd.ExcelWriter(final_excel_path, engine='openpyxl') as writer:
1583
+ df_assets.to_excel(writer, index=False, sheet_name="Assets")
1584
+ df_reordered.to_excel(writer, index=False, sheet_name="Reordered")
1585
+
1586
+ return final_excel_path
1587
+
1588
+ # ========== File Processing Functions ==========
1589
+ def process_files(input_folder, marken_index, output_root):
1590
+ """Process and rename files according to brand numbering"""
1591
+ dateien = []
1592
+ renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
1593
+ file_to_factorgroup = {}
1594
+
1595
+ for subfolder in sorted(Path(input_folder).iterdir()):
1596
+ if not subfolder.is_dir():
1597
+ continue
1598
+ blocknummer = re.sub(r'\D', '', subfolder.name)[:2].zfill(2)
1599
+
1600
+ for file in sorted(subfolder.iterdir()):
1601
+ if file.suffix.lower() not in ALL_ALLOWED_EXTENSIONS:
1602
+ continue
1603
+ marke = extract_brand(file.stem)
1604
+
1605
+ markennummer = marken_index[marke]
1606
+ cleaned = get_cleaned_filename_without_brand(file.name, marke)
1607
+
1608
+ # Create new filename
1609
+ neuer_name = f"{markennummer}B{blocknummer}{marke}{cleaned}{file.suffix.lower()}"
1610
+ ziel = output_root / neuer_name
1611
+
1612
+ if file.suffix.lower() in ALLOWED_IMAGE_EXTENSIONS:
1613
+ with PILImage.open(file) as img:
1614
+ img.convert("RGB").save(ziel, format='PNG')
1615
+ else:
1616
+ shutil.copy2(file, ziel)
1617
+
1618
+ renamed_files_by_folder_and_marke[subfolder.name][marke].append((ziel, neuer_name))
1619
+ file_to_factorgroup[neuer_name] = subfolder.name
1620
+
1621
+ return renamed_files_by_folder_and_marke, file_to_factorgroup
1622
+
1623
+ # ========== Streamlit UI Components ==========
1624
+ def brand_renamer_tool():
1625
+ st.header("Advanced Brand File Processor")
1626
+ st.markdown("Automatically rename and organize brand assets with numbering and generate reports.")
1627
+
1628
+ uploaded_file = st.file_uploader(
1629
+ "Choose a ZIP file",
1630
+ type=['zip'],
1631
+ help="Upload a zip file containing your brand folders with assets."
1632
+ )
1633
+
1634
+ if uploaded_file:
1635
+ with st.spinner("Extracting and analyzing files..."):
1636
+ # Extract zip file
1637
+ temp_dir = extract_zip_to_temp(uploaded_file)
1638
+ input_folder = Path(temp_dir)
1639
+
1640
+ # Find the actual input folder (in case zip has a root folder)
1641
+ items = os.listdir(temp_dir)
1642
+ if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
1643
+ input_folder = Path(temp_dir) / items[0]
1644
+
1645
+ # Create output folder
1646
+ output_folder = Path(temp_dir) / "output"
1647
+ output_folder.mkdir(exist_ok=True)
1648
+
1649
+ # Analyze files to detect brands
1650
+ marken_set, _, _ = analyze_files_by_filename(input_folder)
1651
+
1652
+ if not marken_set:
1653
+ st.error("No brands found in the uploaded files.")
1654
+ return
1655
+
1656
+ st.success(f"Detected brands: {', '.join(sorted(marken_set))}")
1657
+
1658
+ # Brand numbering selection
1659
+ st.subheader("Brand Numbering")
1660
+ erste_marke = st.selectbox(
1661
+ "Which brand should be number 01?",
1662
+ options=sorted(marken_set),
1663
+ index=0
1664
+ )
1665
+
1666
+ # Create brand index
1667
+ marken_index = {erste_marke: "01"}
1668
+ aktuelle_nummer = 2
1669
+ for marke in sorted(marken_set):
1670
+ if marke != erste_marke:
1671
+ marken_index[marke] = f"{aktuelle_nummer:02d}"
1672
+ aktuelle_nummer += 1
1673
+
1674
+ if st.button("Process Files and Generate Reports", type="primary"):
1675
+ with st.spinner("Processing files..."):
1676
+ # Process and rename files
1677
+ renamed_files, file_to_factorgroup = process_files(
1678
+ input_folder,
1679
+ marken_index,
1680
+ output_folder
1681
+ )
1682
+
1683
+ # Generate PDF report
1684
+ pdf_buffer, error = generate_filename_based_pdf_report(input_folder, erste_marke)
1685
+ if error:
1686
+ st.error(f"PDF generation failed: {error}")
1687
+
1688
+ # Generate Excel report
1689
+ excel_path = generate_excel_report(output_folder, marken_index, file_to_factorgroup)
1690
+
1691
+ # Create zip of processed files
1692
+ zip_buffer = io.BytesIO()
1693
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
1694
+ for file in output_folder.iterdir():
1695
+ zip_file.write(file, file.name)
1696
+
1697
+ zip_buffer.seek(0)
1698
+
1699
+ # Display download options
1700
+ st.success("Processing complete!")
1701
+
1702
+ col1, col2, col3 = st.columns(3)
1703
+
1704
+ with col1:
1705
+ if pdf_buffer:
1706
+ st.download_button(
1707
+ label="πŸ“₯ Download PDF Report",
1708
+ data=pdf_buffer.getvalue(),
1709
+ file_name="Brand_Assets_Report.pdf",
1710
+ mime="application/pdf"
1711
+ )
1712
+
1713
+ with col2:
1714
+ st.download_button(
1715
+ label="πŸ“Š Download Excel Report",
1716
+ data=open(excel_path, 'rb').read(),
1717
+ file_name="Brand_Assets_Overview.xlsx",
1718
+ mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
1719
+ )
1720
+
1721
+ with col3:
1722
+ st.download_button(
1723
+ label="πŸ“¦ Download Processed Files",
1724
+ data=zip_buffer.getvalue(),
1725
+ file_name="Brand_Assets_Processed.zip",
1726
+ mime="application/zip"
1727
+ )
1728
+
1729
+ # Clean up
1730
+ shutil.rmtree(temp_dir)
1731
+ else:
1732
+ st.info("πŸ‘† Please upload a zip file to get started.")
1733
+
1734
+ with st.expander("πŸ“– Instructions"):
1735
+ st.markdown("""
1736
+ **How to use this tool:**
1737
+
1738
+ 1. Prepare a zip file with:
1739
+ - Subfolders for each brand (optional)
1740
+ - Files named with brand identifiers (e.g., "nike_shoe.jpg")
1741
+ 2. Upload the zip file
1742
+ 3. Select which brand should be numbered "01"
1743
+ 4. Click "Process Files" to:
1744
+ - Rename files with brand numbering
1745
+ - Generate PDF and Excel reports
1746
+ - Download processed files
1747
+
1748
+ **Output Format:**
1749
+ - `01B00nikefilename.png` (BrandNumber + Block + BrandName + OriginalName)
1750
+ """)
1751
  def main():
1752
  st.title("πŸ”§ Brand Assets Tools")
1753
 
1754
+ tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8 = st.tabs([
1755
  "PDF Report Generator",
1756
  "Excel Image Extractor",
1757
  "Brand File Renamer",
1758
  "White to Transparent",
1759
  "Find Smallest Dimensions",
1760
  "Resize with Transparent Canvas",
1761
+ "Center on Canvas",
1762
+ "Advanced Brand Processor"
1763
  ])
1764
 
1765
  with tab1:
 
1776
  resize_with_transparent_canvas_tool()
1777
  with tab7:
1778
  center_on_canvas_tool()
1779
+ with tab8:
1780
+ brand_renamer_tool()
1781
 
1782
  if __name__ == "__main__":
1783
  main()