Spaces:
Sleeping
Sleeping
venkatesh commited on
Commit ·
6aa31ae
1
Parent(s): da93e5f
added defined python file tabs instead of one app.py file
Browse files- __pycache__/helper.cpython-312.pyc +0 -0
- __pycache__/tab1.cpython-312.pyc +0 -0
- __pycache__/tab2.cpython-312.pyc +0 -0
- __pycache__/tab3.cpython-312.pyc +0 -0
- __pycache__/tab4.cpython-312.pyc +0 -0
- __pycache__/tab5.cpython-312.pyc +0 -0
- __pycache__/tab6.cpython-312.pyc +0 -0
- __pycache__/tab7.cpython-312.pyc +0 -0
- app.py +1 -0
- helper.py +1129 -0
- main.py +48 -0
- tab1.py +176 -0
- tab2.py +134 -0
- tab3.py +162 -0
- tab4.py +152 -0
- tab5.py +260 -0
- tab6.py +180 -0
- tab7.py +164 -0
__pycache__/helper.cpython-312.pyc
ADDED
|
Binary file (52.8 kB). View file
|
|
|
__pycache__/tab1.cpython-312.pyc
ADDED
|
Binary file (8.03 kB). View file
|
|
|
__pycache__/tab2.cpython-312.pyc
ADDED
|
Binary file (6.96 kB). View file
|
|
|
__pycache__/tab3.cpython-312.pyc
ADDED
|
Binary file (9.64 kB). View file
|
|
|
__pycache__/tab4.cpython-312.pyc
ADDED
|
Binary file (7.58 kB). View file
|
|
|
__pycache__/tab5.cpython-312.pyc
ADDED
|
Binary file (12.6 kB). View file
|
|
|
__pycache__/tab6.cpython-312.pyc
ADDED
|
Binary file (9.8 kB). View file
|
|
|
__pycache__/tab7.cpython-312.pyc
ADDED
|
Binary file (8.95 kB). View file
|
|
|
app.py
CHANGED
|
@@ -3099,6 +3099,7 @@ def process_files(input_folder, marken_index, output_root):
|
|
| 3099 |
file_to_factorgroup[neuer_name] = subfolder.name
|
| 3100 |
|
| 3101 |
return renamed_files_by_folder_and_marke, file_to_factorgroup
|
|
|
|
| 3102 |
def brand_renamer_tool():
|
| 3103 |
st.header("Advanced Brand File Processor")
|
| 3104 |
st.markdown("Automatically rename and organize brand assets with numbering and generate reports.")
|
|
|
|
| 3099 |
file_to_factorgroup[neuer_name] = subfolder.name
|
| 3100 |
|
| 3101 |
return renamed_files_by_folder_and_marke, file_to_factorgroup
|
| 3102 |
+
|
| 3103 |
def brand_renamer_tool():
|
| 3104 |
st.header("Advanced Brand File Processor")
|
| 3105 |
st.markdown("Automatically rename and organize brand assets with numbering and generate reports.")
|
helper.py
ADDED
|
@@ -0,0 +1,1129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import shutil
|
| 5 |
+
import tempfile
|
| 6 |
+
import zipfile
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import streamlit as st
|
| 11 |
+
from PIL import Image as PILImage
|
| 12 |
+
from reportlab.lib import colors
|
| 13 |
+
from reportlab.lib.pagesizes import A4
|
| 14 |
+
from reportlab.lib.styles import getSampleStyleSheet
|
| 15 |
+
from reportlab.platypus import (
|
| 16 |
+
SimpleDocTemplate, Table, TableStyle, Image as RLImage,
|
| 17 |
+
Paragraph, Spacer, PageBreak, KeepInFrame
|
| 18 |
+
)
|
| 19 |
+
import openpyxl
|
| 20 |
+
|
| 21 |
+
# Defined file types
|
| 22 |
+
ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'}
|
| 23 |
+
ALLOWED_TEXT_EXTENSIONS = {'.txt', '.md', '.csv'}
|
| 24 |
+
ALLOWED_VIDEO_EXTENSIONS = {'.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', '.m4v', '.3gp', '.ogv'}
|
| 25 |
+
ALLOWED_AUDIO_EXTENSIONS = {'.mp3', '.wav', '.aac', '.flac', '.ogg', '.m4a', '.wma'}
|
| 26 |
+
ALL_ALLOWED_EXTENSIONS = ALLOWED_IMAGE_EXTENSIONS.union(ALLOWED_TEXT_EXTENSIONS).union(ALLOWED_VIDEO_EXTENSIONS).union(ALLOWED_AUDIO_EXTENSIONS)
|
| 27 |
+
|
| 28 |
+
# Helper functions from both files
|
| 29 |
+
def extract_zip_to_temp(uploaded_file):
|
| 30 |
+
"""Extract uploaded zip file to temporary directory"""
|
| 31 |
+
temp_dir = tempfile.mkdtemp()
|
| 32 |
+
with zipfile.ZipFile(uploaded_file, 'r') as zip_ref:
|
| 33 |
+
zip_ref.extractall(temp_dir)
|
| 34 |
+
return temp_dir
|
| 35 |
+
|
| 36 |
+
def extract_images_from_xlsx_zip_method(xlsx_path, output_dir, target_sheet=None):
|
| 37 |
+
"""
|
| 38 |
+
Fallback method: Extract all images from xlsx using zip method
|
| 39 |
+
"""
|
| 40 |
+
try:
|
| 41 |
+
extracted_files = []
|
| 42 |
+
image_count = 0
|
| 43 |
+
|
| 44 |
+
with zipfile.ZipFile(xlsx_path, 'r') as zip_ref:
|
| 45 |
+
# Get available sheets
|
| 46 |
+
available_sheets = []
|
| 47 |
+
try:
|
| 48 |
+
with zip_ref.open('xl/workbook.xml') as f:
|
| 49 |
+
content = f.read().decode('utf-8')
|
| 50 |
+
sheet_matches = re.findall(r'<sheet name="([^"]+)"', content)
|
| 51 |
+
available_sheets = [match for match in sheet_matches]
|
| 52 |
+
except:
|
| 53 |
+
available_sheets = ["Sheet1"]
|
| 54 |
+
|
| 55 |
+
# Find all media files
|
| 56 |
+
media_files = [f for f in zip_ref.namelist() if f.startswith('xl/media/')]
|
| 57 |
+
|
| 58 |
+
if not media_files:
|
| 59 |
+
return 0, [], "No images found in Excel file", available_sheets
|
| 60 |
+
|
| 61 |
+
# Extract all images (since precise sheet mapping is complex)
|
| 62 |
+
for media_file in media_files:
|
| 63 |
+
try:
|
| 64 |
+
image_data = zip_ref.read(media_file)
|
| 65 |
+
original_filename = os.path.basename(media_file)
|
| 66 |
+
|
| 67 |
+
# Create output filename
|
| 68 |
+
if target_sheet and target_sheet != "All worksheets":
|
| 69 |
+
output_filename = f"{target_sheet}_{original_filename}"
|
| 70 |
+
else:
|
| 71 |
+
output_filename = original_filename
|
| 72 |
+
|
| 73 |
+
output_path = os.path.join(output_dir, output_filename)
|
| 74 |
+
|
| 75 |
+
with open(output_path, 'wb') as f:
|
| 76 |
+
f.write(image_data)
|
| 77 |
+
|
| 78 |
+
extracted_files.append(output_path)
|
| 79 |
+
image_count += 1
|
| 80 |
+
|
| 81 |
+
except Exception as e:
|
| 82 |
+
print(f"Error extracting {media_file}: {e}")
|
| 83 |
+
continue
|
| 84 |
+
|
| 85 |
+
warning_msg = None
|
| 86 |
+
if target_sheet and target_sheet != "All worksheets":
|
| 87 |
+
warning_msg = f"Note: Extracted all images from file. Sheet-specific extraction not fully supported with this method."
|
| 88 |
+
|
| 89 |
+
return image_count, extracted_files, warning_msg, available_sheets
|
| 90 |
+
|
| 91 |
+
except Exception as e:
|
| 92 |
+
return 0, [], f"Error processing Excel file: {str(e)}", []
|
| 93 |
+
|
| 94 |
+
def process_files(input_folder, marken_index, output_root):
|
| 95 |
+
"""Process and rename files according to brand numbering with sequential counting per brand/block"""
|
| 96 |
+
dateien = []
|
| 97 |
+
renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
|
| 98 |
+
file_to_factorgroup = {}
|
| 99 |
+
|
| 100 |
+
for subfolder in sorted(Path(input_folder).iterdir()):
|
| 101 |
+
if not subfolder.is_dir():
|
| 102 |
+
continue
|
| 103 |
+
blocknummer = re.sub(r'\D', '', subfolder.name)[:2].zfill(2)
|
| 104 |
+
|
| 105 |
+
# Count files per brand in this folder for sequential numbering
|
| 106 |
+
brand_counters = defaultdict(int)
|
| 107 |
+
|
| 108 |
+
# First pass: count files per brand to establish proper numbering
|
| 109 |
+
files_to_process = []
|
| 110 |
+
for file in sorted(subfolder.iterdir()):
|
| 111 |
+
if file.suffix.lower() not in ALL_ALLOWED_EXTENSIONS:
|
| 112 |
+
continue
|
| 113 |
+
marke = extract_brand(file.stem)
|
| 114 |
+
brand_counters[marke] += 1
|
| 115 |
+
files_to_process.append((file, marke))
|
| 116 |
+
|
| 117 |
+
# Reset counters for actual processing
|
| 118 |
+
brand_counters = defaultdict(int)
|
| 119 |
+
|
| 120 |
+
# Second pass: process files with sequential numbering
|
| 121 |
+
for file, marke in files_to_process:
|
| 122 |
+
brand_counters[marke] += 1 # Increment counter for this brand
|
| 123 |
+
count_str = f"{brand_counters[marke]:02d}" # Format as 01, 02, 03, etc.
|
| 124 |
+
|
| 125 |
+
markennummer = marken_index[marke]
|
| 126 |
+
cleaned = get_cleaned_filename_without_brand(file.name, marke)
|
| 127 |
+
|
| 128 |
+
# New format: markennummer + B + blocknummer + marke + count + cleaned + extension
|
| 129 |
+
neuer_name = f"{markennummer}B{blocknummer}{marke}{count_str}{cleaned}{file.suffix.lower()}"
|
| 130 |
+
ziel = output_root / neuer_name
|
| 131 |
+
|
| 132 |
+
if file.suffix.lower() in ALLOWED_IMAGE_EXTENSIONS:
|
| 133 |
+
with PILImage.open(file) as img:
|
| 134 |
+
# Preserve transparency instead of converting to RGB
|
| 135 |
+
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
|
| 136 |
+
# If image already has transparency, preserve it
|
| 137 |
+
img.save(ziel, format='PNG')
|
| 138 |
+
else:
|
| 139 |
+
# For images without transparency, convert to RGBA to allow transparency
|
| 140 |
+
img.convert("RGBA").save(ziel, format='PNG')
|
| 141 |
+
else:
|
| 142 |
+
shutil.copy2(file, ziel)
|
| 143 |
+
|
| 144 |
+
renamed_files_by_folder_and_marke[subfolder.name][marke].append((ziel, neuer_name))
|
| 145 |
+
file_to_factorgroup[neuer_name] = subfolder.name
|
| 146 |
+
|
| 147 |
+
return renamed_files_by_folder_and_marke, file_to_factorgroup
|
| 148 |
+
|
| 149 |
+
def generate_excel_report(output_folder: Path, marken_index: dict, file_to_factorgroup: dict):
|
| 150 |
+
final_excel_path = output_folder / "IcAt_Overview_Final.xlsx"
|
| 151 |
+
|
| 152 |
+
nummer_zu_marke = {v: k for k, v in marken_index.items()}
|
| 153 |
+
data = []
|
| 154 |
+
for file in sorted(output_folder.iterdir()):
|
| 155 |
+
if file.is_file() and file.suffix.lower() in {'.png', '.txt', '.csv', '.md'}:
|
| 156 |
+
name = file.stem
|
| 157 |
+
match = re.match(r"(\d{2})B(\d{2})([a-z0-9]+)", name, re.IGNORECASE)
|
| 158 |
+
if match:
|
| 159 |
+
markennummer, blocknummer, marke = match.groups()
|
| 160 |
+
factor = nummer_zu_marke.get(markennummer, marke)
|
| 161 |
+
|
| 162 |
+
# Get factorgroup and remove underscores
|
| 163 |
+
factorgroup = file_to_factorgroup.get(file.name, f"{blocknummer}Unknown")
|
| 164 |
+
factorgroup = factorgroup.replace('_', '') # Remove all underscores
|
| 165 |
+
|
| 166 |
+
data.append({
|
| 167 |
+
"factor": factor,
|
| 168 |
+
"factorgroup": factorgroup,
|
| 169 |
+
"ID": name
|
| 170 |
+
})
|
| 171 |
+
|
| 172 |
+
df_assets = pd.DataFrame(data, columns=["factor", "factorgroup", "ID"])
|
| 173 |
+
|
| 174 |
+
reordered_data = []
|
| 175 |
+
for _, row in df_assets.iterrows():
|
| 176 |
+
raw_fg = str(row["ID"])
|
| 177 |
+
group_prefix = raw_fg[:2]
|
| 178 |
+
try:
|
| 179 |
+
group = str(int(group_prefix))
|
| 180 |
+
except ValueError:
|
| 181 |
+
group = group_prefix
|
| 182 |
+
|
| 183 |
+
# Also remove underscores from the reordered data
|
| 184 |
+
clean_factor = str(row["factorgroup"]).replace('_', '')
|
| 185 |
+
clean_factorgroup = str(row["factor"]).replace('_', '')
|
| 186 |
+
|
| 187 |
+
reordered_data.append({
|
| 188 |
+
"Group": group,
|
| 189 |
+
"factor": clean_factor,
|
| 190 |
+
"factorgroup": clean_factorgroup,
|
| 191 |
+
"ID": row["ID"]
|
| 192 |
+
})
|
| 193 |
+
|
| 194 |
+
df_reordered = pd.DataFrame(reordered_data, columns=["Group", "factor", "factorgroup", "ID"])
|
| 195 |
+
df_reordered = df_reordered.sort_values(by='Group', ascending=True).reset_index(drop=True)
|
| 196 |
+
with pd.ExcelWriter(final_excel_path, engine='openpyxl') as writer:
|
| 197 |
+
df_assets.to_excel(writer, index=False, sheet_name="Assets")
|
| 198 |
+
df_reordered.to_excel(writer, index=False, sheet_name="Reordered")
|
| 199 |
+
|
| 200 |
+
return final_excel_path
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def add_brand_pages_with_png_extensions(elements, marken_spalten, renamed_files_by_folder_and_marke, marken_index):
|
| 204 |
+
"""Add brand overview pages with .png extensions in labels"""
|
| 205 |
+
styles = getSampleStyleSheet()
|
| 206 |
+
for nummer, marke in marken_spalten:
|
| 207 |
+
assets = []
|
| 208 |
+
for folder in renamed_files_by_folder_and_marke:
|
| 209 |
+
folder_assets = renamed_files_by_folder_and_marke[folder].get(marke, [])
|
| 210 |
+
for pfad, original_name in folder_assets:
|
| 211 |
+
# Generate the ID name with .png extension for display
|
| 212 |
+
blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
|
| 213 |
+
markennummer = marken_index[marke]
|
| 214 |
+
cleaned = get_cleaned_filename_without_brand(original_name, marke)
|
| 215 |
+
original_ext = Path(original_name).suffix.lower() # Get actual extension
|
| 216 |
+
id_name = f"{markennummer}B{blocknummer}{marke}{cleaned}{original_ext}" # Add .png here
|
| 217 |
+
assets.append((pfad, id_name))
|
| 218 |
+
|
| 219 |
+
if not assets:
|
| 220 |
+
continue
|
| 221 |
+
|
| 222 |
+
elements.append(PageBreak())
|
| 223 |
+
elements.append(Paragraph(f"<b>Brand Overview: {nummer} – {marke}</b>", styles['Heading2']))
|
| 224 |
+
elements.append(Spacer(1, 6))
|
| 225 |
+
elements.append(Paragraph(f"Number of assets: {len(assets)}", styles['Normal']))
|
| 226 |
+
elements.append(Spacer(1, 10))
|
| 227 |
+
|
| 228 |
+
headers = ["Asset"] * 4
|
| 229 |
+
data = [headers]
|
| 230 |
+
row = []
|
| 231 |
+
for i, (pfad, id_name) in enumerate(assets):
|
| 232 |
+
# Use ID name with .png extension as the label
|
| 233 |
+
cell = get_asset_cell(pfad, id_name, 4)
|
| 234 |
+
row.append(cell)
|
| 235 |
+
if len(row) == 4:
|
| 236 |
+
data.append(row)
|
| 237 |
+
row = []
|
| 238 |
+
if row:
|
| 239 |
+
row.extend([""] * (4 - len(row)))
|
| 240 |
+
data.append(row)
|
| 241 |
+
|
| 242 |
+
table = Table(data, colWidths=(A4[0] - 40) / 4)
|
| 243 |
+
table.setStyle(TableStyle([
|
| 244 |
+
('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
|
| 245 |
+
('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
|
| 246 |
+
('VALIGN', (0, 0), (-1, -1), 'TOP'),
|
| 247 |
+
]))
|
| 248 |
+
elements.append(table)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def generate_filename_based_pdf_report_with_extensions(input_folder, erste_marke=None, marken_index=None):
|
| 252 |
+
"""Generate PDF report with .png extensions in image labels"""
|
| 253 |
+
marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
|
| 254 |
+
|
| 255 |
+
if not marken_set:
|
| 256 |
+
return None, "No brands found in filenames."
|
| 257 |
+
|
| 258 |
+
# Use provided marken_index or create new one
|
| 259 |
+
if not marken_index:
|
| 260 |
+
marken_index = {}
|
| 261 |
+
if erste_marke and erste_marke in marken_set:
|
| 262 |
+
marken_index[erste_marke] = "01"
|
| 263 |
+
aktuelle_nummer = 2
|
| 264 |
+
for marke in sorted(marken_set):
|
| 265 |
+
if marke != erste_marke:
|
| 266 |
+
marken_index[marke] = f"{aktuelle_nummer:02d}"
|
| 267 |
+
aktuelle_nummer += 1
|
| 268 |
+
else:
|
| 269 |
+
for i, marke in enumerate(sorted(marken_set), 1):
|
| 270 |
+
marken_index[marke] = f"{i:02d}"
|
| 271 |
+
|
| 272 |
+
# Generate PDF
|
| 273 |
+
pdf_buffer = io.BytesIO()
|
| 274 |
+
doc = SimpleDocTemplate(pdf_buffer, pagesize=A4, leftMargin=20, rightMargin=20, topMargin=40, bottomMargin=30)
|
| 275 |
+
elements = []
|
| 276 |
+
styles = getSampleStyleSheet()
|
| 277 |
+
|
| 278 |
+
nummer_zu_marke = {v: k for k, v in marken_index.items()}
|
| 279 |
+
marken_spalten = sorted(nummer_zu_marke.items())
|
| 280 |
+
|
| 281 |
+
for folder in sorted(renamed_files_by_folder_and_marke):
|
| 282 |
+
elements.append(Paragraph(f"<b>Folder: {folder}</b>", styles['Heading2']))
|
| 283 |
+
|
| 284 |
+
abschnitt = renamed_files_by_folder_and_marke[folder]
|
| 285 |
+
total = 0
|
| 286 |
+
lines = []
|
| 287 |
+
for nummer, marke in marken_spalten:
|
| 288 |
+
count = len(abschnitt.get(marke, []))
|
| 289 |
+
total += count
|
| 290 |
+
lines.append(f"{nummer} ({marke}): {count}")
|
| 291 |
+
lines.append(f"Total: {total}")
|
| 292 |
+
elements.append(Paragraph("<br/>".join(lines), styles['Normal']))
|
| 293 |
+
elements.append(Spacer(1, 10))
|
| 294 |
+
|
| 295 |
+
headers = [f"{nummer} ({marke})" for nummer, marke in marken_spalten]
|
| 296 |
+
data = [headers]
|
| 297 |
+
col_data = []
|
| 298 |
+
max_rows = 0
|
| 299 |
+
for _, marke in marken_spalten:
|
| 300 |
+
eintraege = abschnitt.get(marke, [])
|
| 301 |
+
zellen = []
|
| 302 |
+
for p, original_name in eintraege:
|
| 303 |
+
# Generate the ID name and add .png extension for display
|
| 304 |
+
blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
|
| 305 |
+
markennummer = marken_index[marke]
|
| 306 |
+
cleaned = get_cleaned_filename_without_brand(original_name, marke)
|
| 307 |
+
original_ext = Path(original_name).suffix.lower() # Get actual extension
|
| 308 |
+
id_name = f"{markennummer}B{blocknummer}{marke}{cleaned}{original_ext}" # Add .png here
|
| 309 |
+
|
| 310 |
+
cell = get_asset_cell(p, id_name, len(headers))
|
| 311 |
+
zellen.append(cell)
|
| 312 |
+
col_data.append(zellen)
|
| 313 |
+
max_rows = max(max_rows, len(zellen))
|
| 314 |
+
|
| 315 |
+
for i in range(max_rows):
|
| 316 |
+
row = []
|
| 317 |
+
for col in col_data:
|
| 318 |
+
row.append(col[i] if i < len(col) else "")
|
| 319 |
+
data.append(row)
|
| 320 |
+
|
| 321 |
+
col_width = (A4[0] - 40) / len(headers)
|
| 322 |
+
t = Table(data, colWidths=[col_width] * len(headers))
|
| 323 |
+
t.setStyle(TableStyle([
|
| 324 |
+
('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
|
| 325 |
+
('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
|
| 326 |
+
('VALIGN', (0, 0), (-1, -1), 'TOP'),
|
| 327 |
+
]))
|
| 328 |
+
elements.append(t)
|
| 329 |
+
elements.append(PageBreak())
|
| 330 |
+
|
| 331 |
+
# Total overview
|
| 332 |
+
elements.append(Paragraph("<b>Total Overview</b>", styles['Heading2']))
|
| 333 |
+
global_counts = defaultdict(int)
|
| 334 |
+
for folder_data in renamed_files_by_folder_and_marke.values():
|
| 335 |
+
for marke, daten in folder_data.items():
|
| 336 |
+
global_counts[marke] += len(daten)
|
| 337 |
+
|
| 338 |
+
gesamt = 0
|
| 339 |
+
summary = []
|
| 340 |
+
for nummer, marke in marken_spalten:
|
| 341 |
+
count = global_counts[marke]
|
| 342 |
+
summary.append(f"{marke}: {count} assets")
|
| 343 |
+
gesamt += count
|
| 344 |
+
summary.append(f"Total number of all assets: {gesamt}")
|
| 345 |
+
elements.append(Paragraph("<br/>".join(summary), styles['Normal']))
|
| 346 |
+
|
| 347 |
+
# Add brand pages with .png extensions
|
| 348 |
+
add_brand_pages_with_png_extensions(elements, marken_spalten, renamed_files_by_folder_and_marke, marken_index)
|
| 349 |
+
|
| 350 |
+
try:
|
| 351 |
+
doc.build(elements)
|
| 352 |
+
pdf_buffer.seek(0)
|
| 353 |
+
return pdf_buffer, None
|
| 354 |
+
except Exception as e:
|
| 355 |
+
return None, f"Error generating PDF: {str(e)}"
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def extract_images_from_xlsx_by_sheet(xlsx_path, output_dir, target_sheet=None):
|
| 359 |
+
"""
|
| 360 |
+
Extract images from .xlsx files with reliable sheet-specific extraction
|
| 361 |
+
Uses openpyxl to directly access worksheet images
|
| 362 |
+
"""
|
| 363 |
+
try:
|
| 364 |
+
extracted_files = []
|
| 365 |
+
image_count = 0
|
| 366 |
+
|
| 367 |
+
# Load workbook with openpyxl
|
| 368 |
+
workbook = openpyxl.load_workbook(xlsx_path, data_only=True)
|
| 369 |
+
available_sheets = workbook.sheetnames
|
| 370 |
+
|
| 371 |
+
# Determine which sheets to process
|
| 372 |
+
if target_sheet is None or target_sheet == "All worksheets":
|
| 373 |
+
sheets_to_process = available_sheets
|
| 374 |
+
else:
|
| 375 |
+
sheets_to_process = [target_sheet] if target_sheet in available_sheets else []
|
| 376 |
+
|
| 377 |
+
if not sheets_to_process:
|
| 378 |
+
workbook.close()
|
| 379 |
+
return 0, [], "No valid sheets found to extract from", available_sheets
|
| 380 |
+
|
| 381 |
+
# Process each sheet
|
| 382 |
+
for sheet_name in sheets_to_process:
|
| 383 |
+
try:
|
| 384 |
+
worksheet = workbook[sheet_name]
|
| 385 |
+
|
| 386 |
+
# Check if worksheet has any images
|
| 387 |
+
if hasattr(worksheet, '_images') and worksheet._images:
|
| 388 |
+
sheet_image_count = 0
|
| 389 |
+
for image in worksheet._images:
|
| 390 |
+
try:
|
| 391 |
+
# Get image data
|
| 392 |
+
if hasattr(image, '_data'):
|
| 393 |
+
image_data = image._data()
|
| 394 |
+
else:
|
| 395 |
+
# Try alternative method
|
| 396 |
+
continue
|
| 397 |
+
|
| 398 |
+
# Determine file extension from image format
|
| 399 |
+
image_format = 'png' # default
|
| 400 |
+
if hasattr(image, 'format') and image.format:
|
| 401 |
+
image_format = image.format.lower()
|
| 402 |
+
elif len(image_data) > 4:
|
| 403 |
+
# Try to detect format from data
|
| 404 |
+
if image_data[:4] == b'\x89PNG':
|
| 405 |
+
image_format = 'png'
|
| 406 |
+
elif image_data[:3] == b'\xFF\xD8\xFF':
|
| 407 |
+
image_format = 'jpg'
|
| 408 |
+
elif image_data[:6] == b'GIF87a' or image_data[:6] == b'GIF89a':
|
| 409 |
+
image_format = 'gif'
|
| 410 |
+
|
| 411 |
+
# Create filename
|
| 412 |
+
if len(sheets_to_process) > 1:
|
| 413 |
+
filename = f"{sheet_name}_image_{sheet_image_count + 1:03d}.{image_format}"
|
| 414 |
+
else:
|
| 415 |
+
filename = f"image_{sheet_image_count + 1:03d}.{image_format}"
|
| 416 |
+
|
| 417 |
+
# Save image
|
| 418 |
+
output_path = os.path.join(output_dir, filename)
|
| 419 |
+
with open(output_path, 'wb') as f:
|
| 420 |
+
f.write(image_data)
|
| 421 |
+
|
| 422 |
+
extracted_files.append(output_path)
|
| 423 |
+
sheet_image_count += 1
|
| 424 |
+
image_count += 1
|
| 425 |
+
|
| 426 |
+
except Exception as e:
|
| 427 |
+
print(f"Error extracting image from {sheet_name}: {e}")
|
| 428 |
+
continue
|
| 429 |
+
|
| 430 |
+
print(f"Extracted {sheet_image_count} images from sheet: {sheet_name}")
|
| 431 |
+
|
| 432 |
+
# Also check for drawing objects (alternative method)
|
| 433 |
+
if hasattr(worksheet, 'drawing') and worksheet.drawing:
|
| 434 |
+
for drawing in worksheet.drawing:
|
| 435 |
+
if hasattr(drawing, '_images'):
|
| 436 |
+
for img in drawing._images:
|
| 437 |
+
try:
|
| 438 |
+
# Similar extraction logic for drawing images
|
| 439 |
+
if hasattr(img, '_data'):
|
| 440 |
+
image_data = img._data()
|
| 441 |
+
image_format = 'png'
|
| 442 |
+
|
| 443 |
+
if len(sheets_to_process) > 1:
|
| 444 |
+
filename = f"{sheet_name}_drawing_{image_count + 1:03d}.{image_format}"
|
| 445 |
+
else:
|
| 446 |
+
filename = f"drawing_{image_count + 1:03d}.{image_format}"
|
| 447 |
+
|
| 448 |
+
output_path = os.path.join(output_dir, filename)
|
| 449 |
+
with open(output_path, 'wb') as f:
|
| 450 |
+
f.write(image_data)
|
| 451 |
+
|
| 452 |
+
extracted_files.append(output_path)
|
| 453 |
+
image_count += 1
|
| 454 |
+
|
| 455 |
+
except Exception:
|
| 456 |
+
continue
|
| 457 |
+
|
| 458 |
+
except Exception as e:
|
| 459 |
+
print(f"Error processing sheet {sheet_name}: {e}")
|
| 460 |
+
continue
|
| 461 |
+
|
| 462 |
+
workbook.close()
|
| 463 |
+
|
| 464 |
+
# If openpyxl method didn't find images, fall back to zip extraction
|
| 465 |
+
if image_count == 0:
|
| 466 |
+
return extract_images_from_xlsx_zip_method(xlsx_path, output_dir, target_sheet)
|
| 467 |
+
|
| 468 |
+
return image_count, extracted_files, None, available_sheets
|
| 469 |
+
|
| 470 |
+
except Exception as e:
|
| 471 |
+
return extract_images_from_xlsx_zip_method(xlsx_path, output_dir, target_sheet)
|
| 472 |
+
|
| 473 |
+
def extract_images_from_xlsx(xlsx_file, output_dir):
|
| 474 |
+
"""Extract images from Excel file to specified directory"""
|
| 475 |
+
count = 0
|
| 476 |
+
extracted_files = []
|
| 477 |
+
|
| 478 |
+
try:
|
| 479 |
+
with zipfile.ZipFile(xlsx_file, 'r') as z:
|
| 480 |
+
for file_info in z.infolist():
|
| 481 |
+
if file_info.filename.startswith("xl/media/"):
|
| 482 |
+
filename = Path(file_info.filename).name
|
| 483 |
+
target_path = Path(output_dir) / filename
|
| 484 |
+
|
| 485 |
+
with z.open(file_info) as source, open(target_path, 'wb') as target:
|
| 486 |
+
shutil.copyfileobj(source, target)
|
| 487 |
+
|
| 488 |
+
extracted_files.append(str(target_path))
|
| 489 |
+
count += 1
|
| 490 |
+
|
| 491 |
+
return count, extracted_files, None
|
| 492 |
+
except Exception as e:
|
| 493 |
+
return 0, [], str(e)
|
| 494 |
+
|
| 495 |
+
def extract_brand(file_stem):
|
| 496 |
+
"""Extract brand name from filename using pattern matching"""
|
| 497 |
+
parts = re.split(r'[ _\-]', file_stem)
|
| 498 |
+
return re.sub(r'[^a-z0-9]', '', parts[0].lower()) if parts else "unknown"
|
| 499 |
+
|
| 500 |
+
def erkenne_marken_aus_ordnern(input_folder):
|
| 501 |
+
"""Recognize brands from subfolders (original method)"""
|
| 502 |
+
try:
|
| 503 |
+
return sorted([
|
| 504 |
+
f for f in os.listdir(input_folder)
|
| 505 |
+
if os.path.isdir(os.path.join(input_folder, f)) and not f.startswith('.')
|
| 506 |
+
])
|
| 507 |
+
except Exception as e:
|
| 508 |
+
st.error(f"Error reading folders: {str(e)}")
|
| 509 |
+
return []
|
| 510 |
+
|
| 511 |
+
def get_files_by_marke(input_folder, marken):
|
| 512 |
+
"""Get files per brand from folders"""
|
| 513 |
+
spalteninhalte = {marke: [] for marke in marken}
|
| 514 |
+
|
| 515 |
+
for marke in marken:
|
| 516 |
+
folder_path = os.path.join(input_folder, marke)
|
| 517 |
+
if os.path.isdir(folder_path):
|
| 518 |
+
try:
|
| 519 |
+
dateien = [
|
| 520 |
+
os.path.join(folder_path, f)
|
| 521 |
+
for f in os.listdir(folder_path)
|
| 522 |
+
if not f.startswith(".") and os.path.splitext(f)[1].lower() in ALL_ALLOWED_EXTENSIONS
|
| 523 |
+
]
|
| 524 |
+
spalteninhalte[marke] = dateien
|
| 525 |
+
except Exception as e:
|
| 526 |
+
st.warning(f"Error reading files from {marke}: {str(e)}")
|
| 527 |
+
spalteninhalte[marke] = []
|
| 528 |
+
|
| 529 |
+
return spalteninhalte
|
| 530 |
+
|
| 531 |
+
def get_asset_cell(file_path, filename, col_count):
|
| 532 |
+
"""Create optimized asset cell for PDF with proper transparency handling"""
|
| 533 |
+
ext = Path(file_path).suffix.lower()
|
| 534 |
+
styles = getSampleStyleSheet()
|
| 535 |
+
|
| 536 |
+
try:
|
| 537 |
+
if ext in ALLOWED_IMAGE_EXTENSIONS:
|
| 538 |
+
with PILImage.open(file_path) as img:
|
| 539 |
+
# Preserve transparency if available
|
| 540 |
+
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
|
| 541 |
+
# Create a white background for the PDF (transparency doesn't work well in PDF)
|
| 542 |
+
background = PILImage.new('RGB', img.size, (255, 255, 255))
|
| 543 |
+
if img.mode == 'RGBA':
|
| 544 |
+
# Paste the image onto the white background using the alpha channel as mask
|
| 545 |
+
background.paste(img, mask=img.split()[-1])
|
| 546 |
+
else:
|
| 547 |
+
# For other transparent modes, convert to RGBA first
|
| 548 |
+
img_rgba = img.convert('RGBA')
|
| 549 |
+
background.paste(img_rgba, mask=img_rgba.split()[-1])
|
| 550 |
+
img = background.convert('RGB')
|
| 551 |
+
else:
|
| 552 |
+
# Convert non-transparent images to RGB
|
| 553 |
+
img = img.convert('RGB')
|
| 554 |
+
|
| 555 |
+
orig_width, orig_height = img.size
|
| 556 |
+
available_width = A4[0] - 40
|
| 557 |
+
max_width = available_width / col_count
|
| 558 |
+
max_height = 120
|
| 559 |
+
|
| 560 |
+
aspect_ratio = orig_width / orig_height
|
| 561 |
+
width = max_width
|
| 562 |
+
height = width / aspect_ratio
|
| 563 |
+
|
| 564 |
+
if height > max_height:
|
| 565 |
+
height = max_height
|
| 566 |
+
width = height * aspect_ratio
|
| 567 |
+
|
| 568 |
+
buffer = io.BytesIO()
|
| 569 |
+
img.save(buffer, format='PNG')
|
| 570 |
+
buffer.seek(0)
|
| 571 |
+
|
| 572 |
+
rl_img = RLImage(buffer, width=width, height=height)
|
| 573 |
+
|
| 574 |
+
frame = KeepInFrame(max_width, max_height + 30, content=[
|
| 575 |
+
rl_img,
|
| 576 |
+
Paragraph(filename, styles['Normal'])
|
| 577 |
+
], hAlign='CENTER')
|
| 578 |
+
|
| 579 |
+
return frame
|
| 580 |
+
else:
|
| 581 |
+
return Paragraph(f"{filename}", styles['Normal'])
|
| 582 |
+
except Exception as e:
|
| 583 |
+
return Paragraph(f"[Image Error]<br/>{filename}", styles['Normal'])
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def build_marken_einzelseiten(alle_dateien_pro_marke, styles, gesamtbreite):
|
| 587 |
+
"""Build individual brand overview pages (original method)"""
|
| 588 |
+
elements = []
|
| 589 |
+
max_bildhoehe = 100
|
| 590 |
+
|
| 591 |
+
for marke, dateien in alle_dateien_pro_marke.items():
|
| 592 |
+
elements.append(Paragraph(f"Brand Overview: {marke}", styles['Heading2']))
|
| 593 |
+
elements.append(Spacer(1, 12))
|
| 594 |
+
elements.append(Paragraph(f"<b>Total Assets:</b> {len(dateien)}", styles['Normal']))
|
| 595 |
+
elements.append(Spacer(1, 12))
|
| 596 |
+
|
| 597 |
+
if not dateien:
|
| 598 |
+
elements.append(Paragraph("No assets found in this brand folder.", styles['Normal']))
|
| 599 |
+
# elements.append(PageBreak())
|
| 600 |
+
continue
|
| 601 |
+
|
| 602 |
+
table_data = []
|
| 603 |
+
row_data = []
|
| 604 |
+
spaltenbreite = gesamtbreite / 3
|
| 605 |
+
|
| 606 |
+
for i, file_path in enumerate(dateien):
|
| 607 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 608 |
+
filename = os.path.basename(file_path)
|
| 609 |
+
|
| 610 |
+
if ext in ALLOWED_IMAGE_EXTENSIONS:
|
| 611 |
+
try:
|
| 612 |
+
pil_img = PILImage.open(file_path)
|
| 613 |
+
width, height = pil_img.size
|
| 614 |
+
aspect = height / width
|
| 615 |
+
new_width = spaltenbreite * 0.9
|
| 616 |
+
new_height = min(new_width * aspect, max_bildhoehe)
|
| 617 |
+
new_width = new_height / aspect
|
| 618 |
+
|
| 619 |
+
img = RLImage(file_path, width=new_width, height=new_height)
|
| 620 |
+
cell = [img, Spacer(1, 4), Paragraph(filename, styles['Normal'])]
|
| 621 |
+
except Exception as e:
|
| 622 |
+
cell = Paragraph(f"{filename} (Error loading image)", styles['Normal'])
|
| 623 |
+
else:
|
| 624 |
+
cell = Paragraph(f"{filename}", styles['Normal'])
|
| 625 |
+
|
| 626 |
+
row_data.append(cell)
|
| 627 |
+
if len(row_data) == 3:
|
| 628 |
+
table_data.append(row_data)
|
| 629 |
+
row_data = []
|
| 630 |
+
|
| 631 |
+
if row_data:
|
| 632 |
+
while len(row_data) < 3:
|
| 633 |
+
row_data.append("")
|
| 634 |
+
table_data.append(row_data)
|
| 635 |
+
|
| 636 |
+
if table_data:
|
| 637 |
+
table = Table(table_data, colWidths=[spaltenbreite] * 3)
|
| 638 |
+
table.setStyle(TableStyle([
|
| 639 |
+
("GRID", (0, 0), (-1, -1), 1, colors.grey),
|
| 640 |
+
("ALIGN", (0, 0), (-1, -1), "CENTER"),
|
| 641 |
+
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
|
| 642 |
+
]))
|
| 643 |
+
elements.append(table)
|
| 644 |
+
|
| 645 |
+
elements.append(PageBreak())
|
| 646 |
+
|
| 647 |
+
return elements
|
| 648 |
+
|
| 649 |
+
def get_excel_worksheets_simple(excel_file_path):
|
| 650 |
+
"""Get list of worksheet names from Excel file - simplified version"""
|
| 651 |
+
try:
|
| 652 |
+
file_ext = Path(excel_file_path).suffix.lower()
|
| 653 |
+
|
| 654 |
+
if file_ext == '.xlsx':
|
| 655 |
+
try:
|
| 656 |
+
workbook = openpyxl.load_workbook(excel_file_path, read_only=True)
|
| 657 |
+
worksheets = workbook.sheetnames
|
| 658 |
+
workbook.close()
|
| 659 |
+
return worksheets
|
| 660 |
+
except Exception:
|
| 661 |
+
return ["Sheet1"] # Fallback
|
| 662 |
+
|
| 663 |
+
elif file_ext == '.xls':
|
| 664 |
+
try:
|
| 665 |
+
import xlrd
|
| 666 |
+
workbook = xlrd.open_workbook(excel_file_path)
|
| 667 |
+
return workbook.sheet_names()
|
| 668 |
+
except ImportError:
|
| 669 |
+
return ["Sheet1"] # Fallback instead of "All worksheets"
|
| 670 |
+
except Exception:
|
| 671 |
+
return ["Sheet1"]
|
| 672 |
+
|
| 673 |
+
return []
|
| 674 |
+
|
| 675 |
+
except Exception:
|
| 676 |
+
return []
|
| 677 |
+
|
| 678 |
+
def add_brand_pages(elements, marken_spalten, renamed_files_by_folder_and_marke):
|
| 679 |
+
"""Add brand overview pages with optimized layout"""
|
| 680 |
+
styles = getSampleStyleSheet()
|
| 681 |
+
for nummer, marke in marken_spalten:
|
| 682 |
+
assets = []
|
| 683 |
+
for folder in renamed_files_by_folder_and_marke:
|
| 684 |
+
assets.extend(renamed_files_by_folder_and_marke[folder].get(marke, []))
|
| 685 |
+
|
| 686 |
+
if not assets:
|
| 687 |
+
continue
|
| 688 |
+
|
| 689 |
+
elements.append(PageBreak())
|
| 690 |
+
elements.append(Paragraph(f"<b>Brand Overview: {nummer} – {marke}</b>", styles['Heading2']))
|
| 691 |
+
elements.append(Spacer(1, 6))
|
| 692 |
+
elements.append(Paragraph(f"Number of assets: {len(assets)}", styles['Normal']))
|
| 693 |
+
elements.append(Spacer(1, 10))
|
| 694 |
+
|
| 695 |
+
headers = ["Asset"] * 4
|
| 696 |
+
data = [headers]
|
| 697 |
+
row = []
|
| 698 |
+
for i, (pfad, name) in enumerate(assets):
|
| 699 |
+
cell = get_asset_cell(pfad, name, 4)
|
| 700 |
+
row.append(cell)
|
| 701 |
+
if len(row) == 4:
|
| 702 |
+
data.append(row)
|
| 703 |
+
row = []
|
| 704 |
+
if row:
|
| 705 |
+
row.extend([""] * (4 - len(row)))
|
| 706 |
+
data.append(row)
|
| 707 |
+
|
| 708 |
+
table = Table(data, colWidths=(A4[0] - 40) / 4)
|
| 709 |
+
table.setStyle(TableStyle([
|
| 710 |
+
('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
|
| 711 |
+
('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
|
| 712 |
+
('VALIGN', (0, 0), (-1, -1), 'TOP'),
|
| 713 |
+
]))
|
| 714 |
+
elements.append(table)
|
| 715 |
+
|
| 716 |
+
def analyze_files_by_filename(input_folder):
|
| 717 |
+
"""Analyze files by extracting brand names from filenames"""
|
| 718 |
+
dateien = []
|
| 719 |
+
marken_set = set()
|
| 720 |
+
renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
|
| 721 |
+
|
| 722 |
+
for subfolder in sorted(Path(input_folder).iterdir()):
|
| 723 |
+
if not subfolder.is_dir():
|
| 724 |
+
continue
|
| 725 |
+
|
| 726 |
+
for file in sorted(subfolder.iterdir()):
|
| 727 |
+
if file.suffix.lower() not in ALL_ALLOWED_EXTENSIONS:
|
| 728 |
+
continue
|
| 729 |
+
marke = extract_brand(file.stem)
|
| 730 |
+
marken_set.add(marke)
|
| 731 |
+
dateien.append({
|
| 732 |
+
"original_file": file,
|
| 733 |
+
"original_folder": subfolder.name,
|
| 734 |
+
"marke": marke
|
| 735 |
+
})
|
| 736 |
+
|
| 737 |
+
for eintrag in dateien:
|
| 738 |
+
orig = eintrag["original_file"]
|
| 739 |
+
marke = eintrag["marke"]
|
| 740 |
+
folder_name = eintrag["original_folder"]
|
| 741 |
+
renamed_files_by_folder_and_marke[folder_name][marke].append((orig, orig.name))
|
| 742 |
+
|
| 743 |
+
return marken_set, renamed_files_by_folder_and_marke, dateien
|
| 744 |
+
|
| 745 |
+
def generate_pdf_report(input_folder, erste_marke=None):
|
| 746 |
+
"""Generate the complete PDF report (original method)"""
|
| 747 |
+
styles = getSampleStyleSheet()
|
| 748 |
+
gesamtbreite = 480
|
| 749 |
+
|
| 750 |
+
marken = erkenne_marken_aus_ordnern(input_folder)
|
| 751 |
+
if not marken:
|
| 752 |
+
return None, "No brand folders found in the uploaded zip file."
|
| 753 |
+
|
| 754 |
+
# Reorder brands if specified
|
| 755 |
+
if erste_marke and erste_marke in marken:
|
| 756 |
+
marken = [erste_marke] + [m for m in marken if m != erste_marke]
|
| 757 |
+
|
| 758 |
+
dateien_pro_marke = get_files_by_marke(input_folder, marken)
|
| 759 |
+
total_all = sum(len(dateien_pro_marke[marke]) for marke in marken)
|
| 760 |
+
|
| 761 |
+
alle_elements = []
|
| 762 |
+
|
| 763 |
+
# Overview page
|
| 764 |
+
alle_elements.append(Paragraph("Brand Assets Overview", styles['Title']))
|
| 765 |
+
alle_elements.append(Spacer(1, 20))
|
| 766 |
+
|
| 767 |
+
übersicht_text = ", ".join([f"{marke}: {len(dateien_pro_marke[marke])}" for marke in marken])
|
| 768 |
+
alle_elements.append(Paragraph(f"<b>Assets per brand:</b> {übersicht_text}", styles['Normal']))
|
| 769 |
+
alle_elements.append(Spacer(1, 12))
|
| 770 |
+
alle_elements.append(Paragraph(f"<b>Total assets:</b> {total_all}", styles['Normal']))
|
| 771 |
+
alle_elements.append(PageBreak())
|
| 772 |
+
|
| 773 |
+
# Individual brand pages
|
| 774 |
+
markenseiten = build_marken_einzelseiten(dateien_pro_marke, styles, gesamtbreite)
|
| 775 |
+
alle_elements.extend(markenseiten)
|
| 776 |
+
|
| 777 |
+
# Generate PDF
|
| 778 |
+
pdf_buffer = io.BytesIO()
|
| 779 |
+
doc = SimpleDocTemplate(pdf_buffer, pagesize=A4)
|
| 780 |
+
|
| 781 |
+
try:
|
| 782 |
+
doc.build(alle_elements)
|
| 783 |
+
pdf_buffer.seek(0)
|
| 784 |
+
return pdf_buffer, None
|
| 785 |
+
except Exception as e:
|
| 786 |
+
return None, f"Error generating PDF: {str(e)}"
|
| 787 |
+
def extract_zip_to_temp(uploaded_file):
|
| 788 |
+
"""Extract uploaded zip file to temporary directory"""
|
| 789 |
+
temp_dir = tempfile.mkdtemp()
|
| 790 |
+
with zipfile.ZipFile(uploaded_file, 'r') as zip_ref:
|
| 791 |
+
zip_ref.extractall(temp_dir)
|
| 792 |
+
return temp_dir
|
| 793 |
+
|
| 794 |
+
def extract_brand(file_stem):
|
| 795 |
+
"""Extract brand name from filename using pattern matching"""
|
| 796 |
+
parts = re.split(r'[ _\-]', file_stem)
|
| 797 |
+
return re.sub(r'[^a-z0-9]', '', parts[0].lower()) if parts else "unknown"
|
| 798 |
+
|
| 799 |
+
def clean_letters_only(text):
|
| 800 |
+
return re.sub(r'[^A-Za-z]', '', text)
|
| 801 |
+
|
| 802 |
+
def get_cleaned_filename_without_brand(filename, brand):
|
| 803 |
+
full_letters = clean_letters_only(Path(filename).stem.lower())
|
| 804 |
+
return full_letters.replace(brand, '', 1)
|
| 805 |
+
|
| 806 |
+
def generate_filename_based_pdf_report(input_folder, erste_marke=None, processed_files_mapping=None):
|
| 807 |
+
"""Generate PDF report based on filename brand analysis with final processed labels"""
|
| 808 |
+
marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
|
| 809 |
+
|
| 810 |
+
if not marken_set:
|
| 811 |
+
return None, "No brands found in filenames."
|
| 812 |
+
|
| 813 |
+
# Create brand index
|
| 814 |
+
marken_index = {}
|
| 815 |
+
if erste_marke and erste_marke in marken_set:
|
| 816 |
+
marken_index[erste_marke] = "01"
|
| 817 |
+
aktuelle_nummer = 2
|
| 818 |
+
for marke in sorted(marken_set):
|
| 819 |
+
if marke != erste_marke:
|
| 820 |
+
marken_index[marke] = f"{aktuelle_nummer:02d}"
|
| 821 |
+
aktuelle_nummer += 1
|
| 822 |
+
else:
|
| 823 |
+
for i, marke in enumerate(sorted(marken_set), 1):
|
| 824 |
+
marken_index[marke] = f"{i:02d}"
|
| 825 |
+
|
| 826 |
+
# Generate PDF
|
| 827 |
+
pdf_buffer = io.BytesIO()
|
| 828 |
+
doc = SimpleDocTemplate(pdf_buffer, pagesize=A4, leftMargin=20, rightMargin=20, topMargin=40, bottomMargin=30)
|
| 829 |
+
elements = []
|
| 830 |
+
styles = getSampleStyleSheet()
|
| 831 |
+
|
| 832 |
+
nummer_zu_marke = {v: k for k, v in marken_index.items()}
|
| 833 |
+
marken_spalten = sorted(nummer_zu_marke.items())
|
| 834 |
+
|
| 835 |
+
# Process each folder with final processed names
|
| 836 |
+
for folder in sorted(renamed_files_by_folder_and_marke):
|
| 837 |
+
elements.append(Paragraph(f"<b>Folder: {folder}</b>", styles['Heading2']))
|
| 838 |
+
|
| 839 |
+
abschnitt = renamed_files_by_folder_and_marke[folder]
|
| 840 |
+
total = 0
|
| 841 |
+
lines = []
|
| 842 |
+
for nummer, marke in marken_spalten:
|
| 843 |
+
count = len(abschnitt.get(marke, []))
|
| 844 |
+
total += count
|
| 845 |
+
lines.append(f"{nummer} ({marke}): {count}")
|
| 846 |
+
lines.append(f"Total: {total}")
|
| 847 |
+
elements.append(Paragraph("<br/>".join(lines), styles['Normal']))
|
| 848 |
+
elements.append(Spacer(1, 10))
|
| 849 |
+
|
| 850 |
+
headers = [f"{nummer} ({marke})" for nummer, marke in marken_spalten]
|
| 851 |
+
data = [headers]
|
| 852 |
+
col_data = []
|
| 853 |
+
max_rows = 0
|
| 854 |
+
|
| 855 |
+
for _, marke in marken_spalten:
|
| 856 |
+
eintraege = abschnitt.get(marke, [])
|
| 857 |
+
zellen = []
|
| 858 |
+
for original_path, original_name in eintraege:
|
| 859 |
+
# Generate the final processed ID name
|
| 860 |
+
blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
|
| 861 |
+
markennummer = marken_index[marke]
|
| 862 |
+
cleaned = get_cleaned_filename_without_brand(original_name, marke)
|
| 863 |
+
# Create the final ID without file extension for display
|
| 864 |
+
final_id = f"{markennummer}B{blocknummer}{marke}{cleaned}"
|
| 865 |
+
|
| 866 |
+
# Create cell with original path but final ID label
|
| 867 |
+
cell = get_asset_cell(original_path, final_id, len(headers))
|
| 868 |
+
zellen.append(cell)
|
| 869 |
+
col_data.append(zellen)
|
| 870 |
+
max_rows = max(max_rows, len(zellen))
|
| 871 |
+
|
| 872 |
+
for i in range(max_rows):
|
| 873 |
+
row = []
|
| 874 |
+
for col in col_data:
|
| 875 |
+
row.append(col[i] if i < len(col) else "")
|
| 876 |
+
data.append(row)
|
| 877 |
+
|
| 878 |
+
col_width = (A4[0] - 40) / len(headers)
|
| 879 |
+
t = Table(data, colWidths=[col_width] * len(headers))
|
| 880 |
+
t.setStyle(TableStyle([
|
| 881 |
+
('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
|
| 882 |
+
('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
|
| 883 |
+
('VALIGN', (0, 0), (-1, -1), 'TOP'),
|
| 884 |
+
]))
|
| 885 |
+
elements.append(t)
|
| 886 |
+
elements.append(PageBreak())
|
| 887 |
+
|
| 888 |
+
# Total overview
|
| 889 |
+
elements.append(Paragraph("<b>Total Overview</b>", styles['Heading2']))
|
| 890 |
+
global_counts = defaultdict(int)
|
| 891 |
+
for folder_data in renamed_files_by_folder_and_marke.values():
|
| 892 |
+
for marke, daten in folder_data.items():
|
| 893 |
+
global_counts[marke] += len(daten)
|
| 894 |
+
|
| 895 |
+
gesamt = 0
|
| 896 |
+
summary = []
|
| 897 |
+
for nummer, marke in marken_spalten:
|
| 898 |
+
count = global_counts[marke]
|
| 899 |
+
summary.append(f"{marke}: {count} assets")
|
| 900 |
+
gesamt += count
|
| 901 |
+
summary.append(f"Total number of all assets: {gesamt}")
|
| 902 |
+
elements.append(Paragraph("<br/>".join(summary), styles['Normal']))
|
| 903 |
+
|
| 904 |
+
# Add brand pages with final processed labels
|
| 905 |
+
add_brand_pages_with_final_labels(elements, marken_spalten, renamed_files_by_folder_and_marke, marken_index)
|
| 906 |
+
|
| 907 |
+
try:
|
| 908 |
+
doc.build(elements)
|
| 909 |
+
pdf_buffer.seek(0)
|
| 910 |
+
return pdf_buffer, None
|
| 911 |
+
except Exception as e:
|
| 912 |
+
return None, f"Error generating PDF: {str(e)}"
|
| 913 |
+
|
| 914 |
+
def add_brand_pages_with_final_labels(elements, marken_spalten, renamed_files_by_folder_and_marke, marken_index):
|
| 915 |
+
"""Add brand overview pages with final processed ID labels"""
|
| 916 |
+
styles = getSampleStyleSheet()
|
| 917 |
+
for nummer, marke in marken_spalten:
|
| 918 |
+
assets = []
|
| 919 |
+
for folder in renamed_files_by_folder_and_marke:
|
| 920 |
+
folder_assets = renamed_files_by_folder_and_marke[folder].get(marke, [])
|
| 921 |
+
for original_path, original_name in folder_assets:
|
| 922 |
+
# Generate the final processed ID name (same logic as in Excel generation)
|
| 923 |
+
blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
|
| 924 |
+
markennummer = marken_index[marke]
|
| 925 |
+
cleaned = get_cleaned_filename_without_brand(original_name, marke)
|
| 926 |
+
final_id = f"{markennummer}B{blocknummer}{marke}{cleaned}"
|
| 927 |
+
assets.append((original_path, final_id))
|
| 928 |
+
|
| 929 |
+
if not assets:
|
| 930 |
+
continue
|
| 931 |
+
|
| 932 |
+
elements.append(PageBreak())
|
| 933 |
+
elements.append(Paragraph(f"<b>Brand Overview: {nummer} – {marke}</b>", styles['Heading2']))
|
| 934 |
+
elements.append(Spacer(1, 6))
|
| 935 |
+
elements.append(Paragraph(f"Number of assets: {len(assets)}", styles['Normal']))
|
| 936 |
+
elements.append(Spacer(1, 10))
|
| 937 |
+
|
| 938 |
+
headers = ["Asset"] * 4
|
| 939 |
+
data = [headers]
|
| 940 |
+
row = []
|
| 941 |
+
for i, (original_path, final_id) in enumerate(assets):
|
| 942 |
+
# Use final processed ID as the label
|
| 943 |
+
cell = get_asset_cell(original_path, final_id, 4)
|
| 944 |
+
row.append(cell)
|
| 945 |
+
if len(row) == 4:
|
| 946 |
+
data.append(row)
|
| 947 |
+
row = []
|
| 948 |
+
if row:
|
| 949 |
+
row.extend([""] * (4 - len(row)))
|
| 950 |
+
data.append(row)
|
| 951 |
+
|
| 952 |
+
table = Table(data, colWidths=(A4[0] - 40) / 4)
|
| 953 |
+
table.setStyle(TableStyle([
|
| 954 |
+
('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
|
| 955 |
+
('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
|
| 956 |
+
('VALIGN', (0, 0), (-1, -1), 'TOP'),
|
| 957 |
+
]))
|
| 958 |
+
elements.append(table)
|
| 959 |
+
|
| 960 |
+
def generate_two_section_pdf_report(input_folder, erste_marke=None):
|
| 961 |
+
"""Generate PDF report with two sections: by block and by brand - WITH EXTENSIONS"""
|
| 962 |
+
marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
|
| 963 |
+
|
| 964 |
+
if not marken_set:
|
| 965 |
+
return None, "No brands found in filenames."
|
| 966 |
+
|
| 967 |
+
# Create brand index
|
| 968 |
+
marken_index = {}
|
| 969 |
+
if erste_marke and erste_marke in marken_set:
|
| 970 |
+
marken_index[erste_marke] = "01"
|
| 971 |
+
aktuelle_nummer = 2
|
| 972 |
+
for marke in sorted(marken_set):
|
| 973 |
+
if marke != erste_marke:
|
| 974 |
+
marken_index[marke] = f"{aktuelle_nummer:02d}"
|
| 975 |
+
aktuelle_nummer += 1
|
| 976 |
+
else:
|
| 977 |
+
for i, marke in enumerate(sorted(marken_set), 1):
|
| 978 |
+
marken_index[marke] = f"{i:02d}"
|
| 979 |
+
|
| 980 |
+
# Generate PDF
|
| 981 |
+
pdf_buffer = io.BytesIO()
|
| 982 |
+
doc = SimpleDocTemplate(pdf_buffer, pagesize=A4, leftMargin=20, rightMargin=20, topMargin=40, bottomMargin=30)
|
| 983 |
+
elements = []
|
| 984 |
+
styles = getSampleStyleSheet()
|
| 985 |
+
|
| 986 |
+
nummer_zu_marke = {v: k for k, v in marken_index.items()}
|
| 987 |
+
marken_spalten = sorted(nummer_zu_marke.items())
|
| 988 |
+
|
| 989 |
+
# SECTION 1: BY BLOCK/FOLDER
|
| 990 |
+
elements.append(Paragraph("<b>Section 1: Assets by Block</b>", styles['Title']))
|
| 991 |
+
elements.append(Spacer(1, 20))
|
| 992 |
+
|
| 993 |
+
for folder in sorted(renamed_files_by_folder_and_marke):
|
| 994 |
+
elements.append(Paragraph(f"<b>Folder: {folder}</b>", styles['Heading2']))
|
| 995 |
+
|
| 996 |
+
abschnitt = renamed_files_by_folder_and_marke[folder]
|
| 997 |
+
total = 0
|
| 998 |
+
lines = []
|
| 999 |
+
for nummer, marke in marken_spalten:
|
| 1000 |
+
count = len(abschnitt.get(marke, []))
|
| 1001 |
+
total += count
|
| 1002 |
+
lines.append(f"{nummer} ({marke}): {count}")
|
| 1003 |
+
lines.append(f"Total: {total}")
|
| 1004 |
+
elements.append(Paragraph("<br/>".join(lines), styles['Normal']))
|
| 1005 |
+
elements.append(Spacer(1, 10))
|
| 1006 |
+
|
| 1007 |
+
headers = [f"{nummer} ({marke})" for nummer, marke in marken_spalten]
|
| 1008 |
+
data = [headers]
|
| 1009 |
+
col_data = []
|
| 1010 |
+
max_rows = 0
|
| 1011 |
+
|
| 1012 |
+
for _, marke in marken_spalten:
|
| 1013 |
+
eintraege = abschnitt.get(marke, [])
|
| 1014 |
+
zellen = []
|
| 1015 |
+
for p, original_name in eintraege:
|
| 1016 |
+
# Generate the ID name - KEEP THE FILE EXTENSION
|
| 1017 |
+
blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
|
| 1018 |
+
markennummer = marken_index[marke]
|
| 1019 |
+
cleaned = get_cleaned_filename_without_brand(original_name, marke)
|
| 1020 |
+
# Keep the original file extension
|
| 1021 |
+
file_extension = Path(original_name).suffix.lower()
|
| 1022 |
+
id_name = f"{markennummer}B{blocknummer}{marke}{cleaned}{file_extension}"
|
| 1023 |
+
|
| 1024 |
+
# Pass the full filename with extension to get_asset_cell
|
| 1025 |
+
cell = get_asset_cell(p, id_name, len(headers))
|
| 1026 |
+
zellen.append(cell)
|
| 1027 |
+
col_data.append(zellen)
|
| 1028 |
+
max_rows = max(max_rows, len(zellen))
|
| 1029 |
+
|
| 1030 |
+
for i in range(max_rows):
|
| 1031 |
+
row = []
|
| 1032 |
+
for col in col_data:
|
| 1033 |
+
row.append(col[i] if i < len(col) else "")
|
| 1034 |
+
data.append(row)
|
| 1035 |
+
|
| 1036 |
+
col_width = (A4[0] - 40) / len(headers)
|
| 1037 |
+
t = Table(data, colWidths=[col_width] * len(headers))
|
| 1038 |
+
t.setStyle(TableStyle([
|
| 1039 |
+
('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
|
| 1040 |
+
('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
|
| 1041 |
+
('VALIGN', (0, 0), (-1, -1), 'TOP'),
|
| 1042 |
+
]))
|
| 1043 |
+
elements.append(t)
|
| 1044 |
+
elements.append(PageBreak())
|
| 1045 |
+
|
| 1046 |
+
# SECTION 2: BY BRAND
|
| 1047 |
+
elements.append(Paragraph("<b>Section 2: Assets by Brand</b>", styles['Title']))
|
| 1048 |
+
elements.append(Spacer(1, 20))
|
| 1049 |
+
|
| 1050 |
+
# Total overview first
|
| 1051 |
+
elements.append(Paragraph("<b>Total Overview</b>", styles['Heading2']))
|
| 1052 |
+
global_counts = defaultdict(int)
|
| 1053 |
+
for folder_data in renamed_files_by_folder_and_marke.values():
|
| 1054 |
+
for marke, daten in folder_data.items():
|
| 1055 |
+
global_counts[marke] += len(daten)
|
| 1056 |
+
|
| 1057 |
+
gesamt = 0
|
| 1058 |
+
summary = []
|
| 1059 |
+
for nummer, marke in marken_spalten:
|
| 1060 |
+
count = global_counts[marke]
|
| 1061 |
+
summary.append(f"{marke}: {count} assets")
|
| 1062 |
+
gesamt += count
|
| 1063 |
+
summary.append(f"Total number of all assets: {gesamt}")
|
| 1064 |
+
elements.append(Paragraph("<br/>".join(summary), styles['Normal']))
|
| 1065 |
+
elements.append(PageBreak())
|
| 1066 |
+
first_brand = True
|
| 1067 |
+
# Individual brand pages
|
| 1068 |
+
for nummer, marke in marken_spalten:
|
| 1069 |
+
assets = []
|
| 1070 |
+
for folder in renamed_files_by_folder_and_marke:
|
| 1071 |
+
folder_assets = renamed_files_by_folder_and_marke[folder].get(marke, [])
|
| 1072 |
+
brand_counter = 1 # Start counting from 1 for each brand in each folder
|
| 1073 |
+
for pfad, original_name in folder_assets:
|
| 1074 |
+
# Generate the ID name with sequential count - KEEP THE FILE EXTENSION
|
| 1075 |
+
blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
|
| 1076 |
+
markennummer = marken_index[marke]
|
| 1077 |
+
count_str = f"{brand_counter:02d}"
|
| 1078 |
+
cleaned = get_cleaned_filename_without_brand(original_name, marke)
|
| 1079 |
+
# Keep the original file extension
|
| 1080 |
+
file_extension = Path(original_name).suffix.lower()
|
| 1081 |
+
id_name = f"{markennummer}B{blocknummer}{marke}{count_str}{cleaned}{file_extension}"
|
| 1082 |
+
assets.append((pfad, id_name))
|
| 1083 |
+
brand_counter += 1
|
| 1084 |
+
|
| 1085 |
+
if not assets:
|
| 1086 |
+
continue
|
| 1087 |
+
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
# Inside the loop for each brand
|
| 1091 |
+
if not first_brand:
|
| 1092 |
+
elements.append(PageBreak())
|
| 1093 |
+
else:
|
| 1094 |
+
first_brand = False
|
| 1095 |
+
elements.append(Paragraph(f"<b>Brand Overview: {nummer} – {marke}</b>", styles['Heading2']))
|
| 1096 |
+
elements.append(Spacer(1, 6))
|
| 1097 |
+
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']))
|
| 1098 |
+
elements.append(Paragraph(f"Total assets: {len(assets)}", styles['Normal']))
|
| 1099 |
+
elements.append(Spacer(1, 10))
|
| 1100 |
+
|
| 1101 |
+
|
| 1102 |
+
headers = ["Asset"] * 4
|
| 1103 |
+
data = [headers]
|
| 1104 |
+
row = []
|
| 1105 |
+
for i, (pfad, id_name) in enumerate(assets):
|
| 1106 |
+
# Pass the full filename with extension to get_asset_cell
|
| 1107 |
+
cell = get_asset_cell(pfad, id_name, 4)
|
| 1108 |
+
row.append(cell)
|
| 1109 |
+
if len(row) == 4:
|
| 1110 |
+
data.append(row)
|
| 1111 |
+
row = []
|
| 1112 |
+
if row:
|
| 1113 |
+
row.extend([""] * (4 - len(row)))
|
| 1114 |
+
data.append(row)
|
| 1115 |
+
|
| 1116 |
+
table = Table(data, colWidths=(A4[0] - 40) / 4)
|
| 1117 |
+
table.setStyle(TableStyle([
|
| 1118 |
+
('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
|
| 1119 |
+
('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
|
| 1120 |
+
('VALIGN', (0, 0), (-1, -1), 'TOP'),
|
| 1121 |
+
]))
|
| 1122 |
+
elements.append(table)
|
| 1123 |
+
|
| 1124 |
+
try:
|
| 1125 |
+
doc.build(elements)
|
| 1126 |
+
pdf_buffer.seek(0)
|
| 1127 |
+
return pdf_buffer, None
|
| 1128 |
+
except Exception as e:
|
| 1129 |
+
return None, f"Error generating PDF: {str(e)}"
|
main.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from tab1 import excel_extractor_tool
|
| 3 |
+
from tab2 import file_renamer_tool
|
| 4 |
+
from tab3 import white_to_transparent_tool
|
| 5 |
+
from tab4 import pdf_generator_tool
|
| 6 |
+
from tab5 import brand_renamer_tool
|
| 7 |
+
from tab6 import resize_with_transparent_canvas_tool
|
| 8 |
+
from tab7 import center_on_canvas_tool
|
| 9 |
+
|
| 10 |
+
# Configure Streamlit page
|
| 11 |
+
st.set_page_config(
|
| 12 |
+
page_title="Brand Asset Management Tools",
|
| 13 |
+
page_icon="🔧",
|
| 14 |
+
layout="wide"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
st.title("🔧 Brand Assets Tools")
|
| 20 |
+
|
| 21 |
+
tab1, tab2, tab3, tab4, tab5, tab6, tab7 = st.tabs([
|
| 22 |
+
"Extract Images from Excel",
|
| 23 |
+
"Name assets by brand",
|
| 24 |
+
"Canvas white to Transparent",
|
| 25 |
+
"Asset Overview",
|
| 26 |
+
"Name stims by block + create output files",
|
| 27 |
+
"Resize",
|
| 28 |
+
"Place on Canvas"
|
| 29 |
+
|
| 30 |
+
])
|
| 31 |
+
|
| 32 |
+
with tab1:
|
| 33 |
+
excel_extractor_tool()
|
| 34 |
+
with tab2:
|
| 35 |
+
file_renamer_tool()
|
| 36 |
+
with tab3:
|
| 37 |
+
white_to_transparent_tool()
|
| 38 |
+
with tab4:
|
| 39 |
+
pdf_generator_tool()
|
| 40 |
+
with tab5:
|
| 41 |
+
brand_renamer_tool()
|
| 42 |
+
with tab6:
|
| 43 |
+
resize_with_transparent_canvas_tool()
|
| 44 |
+
with tab7:
|
| 45 |
+
center_on_canvas_tool()
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
main()
|
tab1.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
import zipfile
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import streamlit as st
|
| 7 |
+
from reportlab.lib.pagesizes import A4
|
| 8 |
+
|
| 9 |
+
from helper import get_excel_worksheets_simple, extract_images_from_xlsx_by_sheet
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def excel_extractor_tool():
|
| 13 |
+
st.header("Excel Image Extractor")
|
| 14 |
+
st.markdown("Upload Excel files (.xlsx) to extract embedded images from specific sheets.")
|
| 15 |
+
|
| 16 |
+
# File upload for Excel files
|
| 17 |
+
uploaded_files = st.file_uploader(
|
| 18 |
+
"Choose Excel file(s)",
|
| 19 |
+
type=['xlsx'],
|
| 20 |
+
accept_multiple_files=True,
|
| 21 |
+
help="Upload one or more .xlsx files to extract embedded images.",
|
| 22 |
+
key="excel_upload_fixed"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
if uploaded_files:
|
| 26 |
+
# For each file, let user select sheets
|
| 27 |
+
sheet_selections = {}
|
| 28 |
+
|
| 29 |
+
for uploaded_file in uploaded_files:
|
| 30 |
+
# Temporarily save file to read sheet names
|
| 31 |
+
temp_dir = tempfile.mkdtemp()
|
| 32 |
+
temp_path = os.path.join(temp_dir, uploaded_file.name)
|
| 33 |
+
|
| 34 |
+
with open(temp_path, 'wb') as f:
|
| 35 |
+
f.write(uploaded_file.getbuffer())
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
# Get available sheets using the simple function
|
| 39 |
+
available_sheets = get_excel_worksheets_simple(temp_path)
|
| 40 |
+
|
| 41 |
+
if available_sheets:
|
| 42 |
+
st.subheader(f"Select sheets from: {uploaded_file.name}")
|
| 43 |
+
|
| 44 |
+
# Add "All sheets" option
|
| 45 |
+
all_options = ["All worksheets"] + available_sheets
|
| 46 |
+
|
| 47 |
+
selected = st.multiselect(
|
| 48 |
+
f"Choose sheets to extract images from:",
|
| 49 |
+
all_options,
|
| 50 |
+
default=["All worksheets"],
|
| 51 |
+
help="Select specific sheets or 'All worksheets' to extract from all sheets",
|
| 52 |
+
key=f"sheets_fixed_{uploaded_file.name}"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
if "All worksheets" in selected:
|
| 56 |
+
sheet_selections[uploaded_file.name] = available_sheets
|
| 57 |
+
else:
|
| 58 |
+
sheet_selections[uploaded_file.name] = [s for s in selected if s != "All worksheets"]
|
| 59 |
+
else:
|
| 60 |
+
st.warning(f"Could not read sheets from {uploaded_file.name}")
|
| 61 |
+
sheet_selections[uploaded_file.name] = []
|
| 62 |
+
|
| 63 |
+
except Exception as e:
|
| 64 |
+
st.error(f"Error reading {uploaded_file.name}: {str(e)}")
|
| 65 |
+
sheet_selections[uploaded_file.name] = []
|
| 66 |
+
|
| 67 |
+
# Clean up
|
| 68 |
+
try:
|
| 69 |
+
os.remove(temp_path)
|
| 70 |
+
os.rmdir(temp_dir)
|
| 71 |
+
except:
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
if st.button("Extract Images", type="primary", key="extract_btn_fixed"):
|
| 75 |
+
temp_dir = tempfile.mkdtemp()
|
| 76 |
+
all_extracted_files = []
|
| 77 |
+
total_images = 0
|
| 78 |
+
extraction_results = []
|
| 79 |
+
|
| 80 |
+
progress_bar = st.progress(0)
|
| 81 |
+
status_text = st.empty()
|
| 82 |
+
|
| 83 |
+
for i, uploaded_file in enumerate(uploaded_files):
|
| 84 |
+
file_name = uploaded_file.name
|
| 85 |
+
selected_sheets = sheet_selections.get(file_name, [])
|
| 86 |
+
|
| 87 |
+
if not selected_sheets:
|
| 88 |
+
st.warning(f"No sheets selected for {file_name}, skipping...")
|
| 89 |
+
continue
|
| 90 |
+
|
| 91 |
+
status_text.text(f"Processing {file_name}...")
|
| 92 |
+
progress_bar.progress((i + 1) / len(uploaded_files))
|
| 93 |
+
|
| 94 |
+
# Save uploaded file temporarily
|
| 95 |
+
temp_xlsx_path = os.path.join(temp_dir, file_name)
|
| 96 |
+
with open(temp_xlsx_path, 'wb') as f:
|
| 97 |
+
f.write(uploaded_file.getbuffer())
|
| 98 |
+
|
| 99 |
+
# Create output directory for this file
|
| 100 |
+
output_dir = os.path.join(temp_dir, f"{Path(file_name).stem}_images")
|
| 101 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 102 |
+
|
| 103 |
+
# Extract images for each selected sheet individually
|
| 104 |
+
file_total = 0
|
| 105 |
+
for sheet_name in selected_sheets:
|
| 106 |
+
sheet_output_dir = os.path.join(output_dir, sheet_name.replace('/', '_').replace('\\', '_'))
|
| 107 |
+
os.makedirs(sheet_output_dir, exist_ok=True)
|
| 108 |
+
|
| 109 |
+
count, extracted_files, error, _ = extract_images_from_xlsx_by_sheet(
|
| 110 |
+
temp_xlsx_path,
|
| 111 |
+
sheet_output_dir,
|
| 112 |
+
sheet_name
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
if error:
|
| 116 |
+
st.warning(f"Issue with {file_name} - {sheet_name}: {error}")
|
| 117 |
+
|
| 118 |
+
if count > 0:
|
| 119 |
+
extraction_results.append(f"✅ {file_name} - {sheet_name}: {count} images")
|
| 120 |
+
all_extracted_files.extend(extracted_files)
|
| 121 |
+
file_total += count
|
| 122 |
+
else:
|
| 123 |
+
extraction_results.append(f"⚪ {file_name} - {sheet_name}: No images found")
|
| 124 |
+
|
| 125 |
+
total_images += file_total
|
| 126 |
+
if file_total > 0:
|
| 127 |
+
st.success(f"Extracted {file_total} images from {file_name}")
|
| 128 |
+
else:
|
| 129 |
+
st.info(f"No images found in {file_name}")
|
| 130 |
+
|
| 131 |
+
status_text.empty()
|
| 132 |
+
progress_bar.empty()
|
| 133 |
+
|
| 134 |
+
# Show detailed extraction results
|
| 135 |
+
with st.expander("Detailed Extraction Results"):
|
| 136 |
+
for result in extraction_results:
|
| 137 |
+
st.write(result)
|
| 138 |
+
|
| 139 |
+
if total_images > 0:
|
| 140 |
+
st.success(f"Total: {total_images} images extracted from {len(uploaded_files)} file(s)")
|
| 141 |
+
|
| 142 |
+
# Show extracted files summary
|
| 143 |
+
with st.expander("Extracted Files Summary"):
|
| 144 |
+
for file_path in all_extracted_files[:20]: # Show first 20
|
| 145 |
+
st.write(f"📄 {os.path.relpath(file_path, temp_dir)}")
|
| 146 |
+
if len(all_extracted_files) > 20:
|
| 147 |
+
st.info(f"Showing first 20 files. Total extracted: {len(all_extracted_files)}")
|
| 148 |
+
|
| 149 |
+
# Create zip file with all extracted images
|
| 150 |
+
zip_buffer = io.BytesIO()
|
| 151 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
| 152 |
+
for file_path in all_extracted_files:
|
| 153 |
+
# Get relative path for zip structure
|
| 154 |
+
rel_path = os.path.relpath(file_path, temp_dir)
|
| 155 |
+
zip_file.write(file_path, rel_path)
|
| 156 |
+
|
| 157 |
+
zip_buffer.seek(0)
|
| 158 |
+
|
| 159 |
+
# Download button for all extracted images
|
| 160 |
+
st.download_button(
|
| 161 |
+
label="Download All Extracted Images (ZIP)",
|
| 162 |
+
data=zip_buffer.getvalue(),
|
| 163 |
+
file_name="extracted_images_by_sheet.zip",
|
| 164 |
+
mime="application/zip"
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
else:
|
| 168 |
+
st.info("No images were found in the selected sheets of the uploaded Excel file(s).")
|
| 169 |
+
|
| 170 |
+
else:
|
| 171 |
+
st.info("Please upload Excel file(s) to get started.")
|
| 172 |
+
|
| 173 |
+
with st.expander("Instructions"):
|
| 174 |
+
st.markdown("""
|
| 175 |
+
|
| 176 |
+
""")
|
tab2.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
import shutil
|
| 4 |
+
import zipfile
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import streamlit as st
|
| 8 |
+
from helper import extract_zip_to_temp
|
| 9 |
+
|
| 10 |
+
ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'}
|
| 11 |
+
ALLOWED_TEXT_EXTENSIONS = {'.txt', '.md', '.csv'}
|
| 12 |
+
ALLOWED_VIDEO_EXTENSIONS = {'.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', '.m4v', '.3gp', '.ogv'}
|
| 13 |
+
ALLOWED_AUDIO_EXTENSIONS = {'.mp3', '.wav', '.aac', '.flac', '.ogg', '.m4a', '.wma'}
|
| 14 |
+
ALL_ALLOWED_EXTENSIONS = ALLOWED_IMAGE_EXTENSIONS.union(ALLOWED_TEXT_EXTENSIONS).union(ALLOWED_VIDEO_EXTENSIONS).union(ALLOWED_AUDIO_EXTENSIONS)
|
| 15 |
+
|
| 16 |
+
def file_renamer_tool():
|
| 17 |
+
st.header("Brand File Renamer")
|
| 18 |
+
st.markdown("Upload a zip file containing brand folders to automatically rename files with brand prefixes.")
|
| 19 |
+
|
| 20 |
+
# File upload
|
| 21 |
+
uploaded_file = st.file_uploader(
|
| 22 |
+
"Choose a ZIP file",
|
| 23 |
+
type=['zip'],
|
| 24 |
+
# help="Upload a zip file containing your brand folders with assets.",
|
| 25 |
+
key="renamer_zip_upload"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
if uploaded_file is not None:
|
| 29 |
+
try:
|
| 30 |
+
# Extract zip file
|
| 31 |
+
with st.spinner("Extracting zip file..."):
|
| 32 |
+
temp_dir = extract_zip_to_temp(uploaded_file)
|
| 33 |
+
|
| 34 |
+
# Find the actual input folder (in case zip has a root folder)
|
| 35 |
+
input_folder = Path(temp_dir)
|
| 36 |
+
items = os.listdir(temp_dir)
|
| 37 |
+
if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
|
| 38 |
+
input_folder = Path(temp_dir) / items[0]
|
| 39 |
+
|
| 40 |
+
# Create output folder
|
| 41 |
+
output_folder = input_folder.parent / (input_folder.name + "_renamed")
|
| 42 |
+
output_folder.mkdir(exist_ok=True)
|
| 43 |
+
|
| 44 |
+
# Process files
|
| 45 |
+
total_files = 0
|
| 46 |
+
processed_files = []
|
| 47 |
+
file_type_counts = {"images": 0, "text": 0, "videos": 0}
|
| 48 |
+
|
| 49 |
+
for subfolder in input_folder.iterdir():
|
| 50 |
+
if subfolder.is_dir():
|
| 51 |
+
markenname = subfolder.name
|
| 52 |
+
new_subfolder = output_folder / markenname
|
| 53 |
+
new_subfolder.mkdir(parents=True, exist_ok=True)
|
| 54 |
+
|
| 55 |
+
for file in subfolder.iterdir():
|
| 56 |
+
if file.is_file() and file.suffix.lower() in ALL_ALLOWED_EXTENSIONS:
|
| 57 |
+
new_name = f"{markenname}_{file.name}"
|
| 58 |
+
target_path = new_subfolder / new_name
|
| 59 |
+
shutil.copy2(file, target_path)
|
| 60 |
+
processed_files.append((file.name, new_name, markenname))
|
| 61 |
+
total_files += 1
|
| 62 |
+
|
| 63 |
+
# Count file types
|
| 64 |
+
if file.suffix.lower() in ALLOWED_IMAGE_EXTENSIONS:
|
| 65 |
+
file_type_counts["images"] += 1
|
| 66 |
+
elif file.suffix.lower() in ALLOWED_TEXT_EXTENSIONS:
|
| 67 |
+
file_type_counts["text"] += 1
|
| 68 |
+
elif file.suffix.lower() in ALLOWED_VIDEO_EXTENSIONS:
|
| 69 |
+
file_type_counts["videos"] += 1
|
| 70 |
+
|
| 71 |
+
if total_files > 0:
|
| 72 |
+
st.success(f"Successfully renamed and copied {total_files} files")
|
| 73 |
+
|
| 74 |
+
# Show file type breakdown
|
| 75 |
+
st.info(f"File types processed: {file_type_counts['images']} images, {file_type_counts['text']} text files, {file_type_counts['videos']} videos")
|
| 76 |
+
|
| 77 |
+
# Show preview
|
| 78 |
+
with st.expander("📋 Preview renamed files"):
|
| 79 |
+
preview_df = pd.DataFrame(
|
| 80 |
+
processed_files,
|
| 81 |
+
columns=["Original Name", "New Name", "Brand"]
|
| 82 |
+
)
|
| 83 |
+
st.dataframe(preview_df)
|
| 84 |
+
|
| 85 |
+
if total_files > 20:
|
| 86 |
+
st.info(f"Total processed: {total_files}")
|
| 87 |
+
|
| 88 |
+
# Create zip file with renamed files
|
| 89 |
+
zip_buffer = io.BytesIO()
|
| 90 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
| 91 |
+
for root, dirs, files in os.walk(output_folder):
|
| 92 |
+
for file in files:
|
| 93 |
+
file_path = Path(root) / file
|
| 94 |
+
rel_path = os.path.relpath(file_path, output_folder)
|
| 95 |
+
zip_file.write(file_path, rel_path)
|
| 96 |
+
|
| 97 |
+
zip_buffer.seek(0)
|
| 98 |
+
|
| 99 |
+
# Download button
|
| 100 |
+
st.download_button(
|
| 101 |
+
label="📥 Download Renamed Files (ZIP)",
|
| 102 |
+
data=zip_buffer.getvalue(),
|
| 103 |
+
file_name="brand_files_renamed.zip",
|
| 104 |
+
mime="application/zip"
|
| 105 |
+
)
|
| 106 |
+
else:
|
| 107 |
+
st.warning("No files were found to rename in the uploaded zip file.")
|
| 108 |
+
|
| 109 |
+
except Exception as e:
|
| 110 |
+
st.error(f"An error occurred: {str(e)}")
|
| 111 |
+
|
| 112 |
+
else:
|
| 113 |
+
st.info("👆 Please upload a zip file to get started.")
|
| 114 |
+
|
| 115 |
+
# Instructions
|
| 116 |
+
with st.expander("📖 Instructions"):
|
| 117 |
+
st.markdown("""
|
| 118 |
+
**How to use this tool:**
|
| 119 |
+
|
| 120 |
+
1. Create folders named after your brands
|
| 121 |
+
2. Place brand assets inside each brand folder
|
| 122 |
+
3. Zip the entire structure
|
| 123 |
+
4. Upload the zip file
|
| 124 |
+
|
| 125 |
+
**The tool will:**
|
| 126 |
+
- Create a new folder structure matching the original
|
| 127 |
+
- Rename all files with the brand prefix (e.g., "Brand1_filename.jpg")
|
| 128 |
+
- Provide a zip file with all renamed files
|
| 129 |
+
|
| 130 |
+
**Supported file types:**
|
| 131 |
+
- **Images:** JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP
|
| 132 |
+
- **Text files:** TXT, MD, CSV
|
| 133 |
+
- **Videos:** MP4, AVI, MOV, WMV, FLV, MKV, WEBM, M4V, 3GP, OGV
|
| 134 |
+
""")
|
tab3.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
from reportlab.lib.pagesizes import A4
|
| 10 |
+
from reportlab.lib.styles import getSampleStyleSheet
|
| 11 |
+
|
| 12 |
+
ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'}
|
| 13 |
+
ALLOWED_TEXT_EXTENSIONS = {'.txt', '.md', '.csv'}
|
| 14 |
+
ALLOWED_VIDEO_EXTENSIONS = {'.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', '.m4v', '.3gp', '.ogv'}
|
| 15 |
+
ALLOWED_AUDIO_EXTENSIONS = {'.mp3', '.wav', '.aac', '.flac', '.ogg', '.m4a', '.wma'}
|
| 16 |
+
ALL_ALLOWED_EXTENSIONS = ALLOWED_IMAGE_EXTENSIONS.union(ALLOWED_TEXT_EXTENSIONS).union(ALLOWED_VIDEO_EXTENSIONS).union(ALLOWED_AUDIO_EXTENSIONS)
|
| 17 |
+
|
| 18 |
+
def white_to_transparent_tool():
|
| 19 |
+
st.header("White Background to Transparent")
|
| 20 |
+
st.markdown("Upload images to convert white backgrounds to transparent.")
|
| 21 |
+
|
| 22 |
+
# Options
|
| 23 |
+
col1, col2 = st.columns(2)
|
| 24 |
+
with col1:
|
| 25 |
+
crop_image = st.checkbox("Crop white background", value=False)
|
| 26 |
+
with col2:
|
| 27 |
+
overwrite = st.checkbox("Overwrite original files", value=False)
|
| 28 |
+
|
| 29 |
+
# File upload
|
| 30 |
+
uploaded_files = st.file_uploader(
|
| 31 |
+
"Choose image files",
|
| 32 |
+
type=list(ALLOWED_IMAGE_EXTENSIONS),
|
| 33 |
+
accept_multiple_files=True,
|
| 34 |
+
help="Upload images to convert white backgrounds to transparent.",
|
| 35 |
+
key="transparent_upload"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
if uploaded_files:
|
| 39 |
+
if st.button("Process Images", type="primary"):
|
| 40 |
+
temp_dir = tempfile.mkdtemp()
|
| 41 |
+
processed_files = []
|
| 42 |
+
failed_files = []
|
| 43 |
+
|
| 44 |
+
# Save uploaded files to temp dir
|
| 45 |
+
for uploaded_file in uploaded_files:
|
| 46 |
+
file_path = os.path.join(temp_dir, uploaded_file.name)
|
| 47 |
+
with open(file_path, 'wb') as f:
|
| 48 |
+
f.write(uploaded_file.getbuffer())
|
| 49 |
+
|
| 50 |
+
# Process images
|
| 51 |
+
progress_bar = st.progress(0)
|
| 52 |
+
status_text = st.empty()
|
| 53 |
+
|
| 54 |
+
for i, uploaded_file in enumerate(uploaded_files):
|
| 55 |
+
status_text.text(f"Processing {uploaded_file.name}... ({i+1}/{len(uploaded_files)})")
|
| 56 |
+
progress_bar.progress((i + 1) / len(uploaded_files))
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
img = PILImage.open(os.path.join(temp_dir, uploaded_file.name)).convert("RGBA")
|
| 60 |
+
|
| 61 |
+
# Convert to numpy array for OpenCV processing
|
| 62 |
+
img_array = np.array(img)
|
| 63 |
+
|
| 64 |
+
if crop_image:
|
| 65 |
+
# Crop image
|
| 66 |
+
gray = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
|
| 67 |
+
th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
|
| 68 |
+
|
| 69 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
|
| 70 |
+
morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
|
| 71 |
+
|
| 72 |
+
cnts, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 73 |
+
if cnts: # Only crop if contours are found
|
| 74 |
+
cnt = sorted(cnts, key=cv2.contourArea)[-1]
|
| 75 |
+
x,y,w,h = cv2.boundingRect(cnt)
|
| 76 |
+
img_array = img_array[y:y+h, x:x+w]
|
| 77 |
+
|
| 78 |
+
# Make white background transparent
|
| 79 |
+
gray = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
|
| 80 |
+
th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
|
| 81 |
+
|
| 82 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
|
| 83 |
+
morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
|
| 84 |
+
|
| 85 |
+
roi, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 86 |
+
|
| 87 |
+
mask = np.zeros(img_array.shape, img_array.dtype)
|
| 88 |
+
if roi: # Only proceed if contours are found
|
| 89 |
+
cv2.fillPoly(mask, roi, (255,)*img_array.shape[2])
|
| 90 |
+
masked_image = cv2.bitwise_and(img_array, mask)
|
| 91 |
+
|
| 92 |
+
# Convert back to PIL Image
|
| 93 |
+
result_img = PILImage.fromarray(masked_image, mode="RGBA")
|
| 94 |
+
|
| 95 |
+
# Save the processed image
|
| 96 |
+
new_filename = os.path.splitext(uploaded_file.name)[0] + ".png"
|
| 97 |
+
processed_path = os.path.join(temp_dir,
|
| 98 |
+
new_filename)
|
| 99 |
+
result_img.save(processed_path)
|
| 100 |
+
processed_files.append(processed_path)
|
| 101 |
+
else:
|
| 102 |
+
failed_files.append(uploaded_file.name)
|
| 103 |
+
except Exception as e:
|
| 104 |
+
failed_files.append(uploaded_file.name)
|
| 105 |
+
st.warning(f"Failed to process {uploaded_file.name}: {str(e)}")
|
| 106 |
+
|
| 107 |
+
status_text.empty()
|
| 108 |
+
progress_bar.empty()
|
| 109 |
+
|
| 110 |
+
if processed_files:
|
| 111 |
+
st.success(f"✅ Successfully processed {len(processed_files)} images")
|
| 112 |
+
|
| 113 |
+
# Create zip file with processed images
|
| 114 |
+
zip_buffer = io.BytesIO()
|
| 115 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
| 116 |
+
for file_path in processed_files:
|
| 117 |
+
zip_file.write(file_path, os.path.basename(file_path))
|
| 118 |
+
|
| 119 |
+
zip_buffer.seek(0)
|
| 120 |
+
|
| 121 |
+
# Download button
|
| 122 |
+
st.download_button(
|
| 123 |
+
label="📥 Download Processed Images (ZIP)",
|
| 124 |
+
data=zip_buffer.getvalue(),
|
| 125 |
+
file_name="transparent_images.zip",
|
| 126 |
+
mime="application/zip"
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# Show preview
|
| 130 |
+
with st.expander("🖼️ Preview Processed Images"):
|
| 131 |
+
cols = st.columns(3)
|
| 132 |
+
for i, file_path in enumerate(processed_files[:6]): # Show max 6 images
|
| 133 |
+
with cols[i % 3]:
|
| 134 |
+
img = PILImage.open(file_path)
|
| 135 |
+
st.image(img, caption=os.path.basename(file_path), use_column_width=True)
|
| 136 |
+
|
| 137 |
+
if len(processed_files) > 6:
|
| 138 |
+
st.info(f"Showing first 6 images. Total processed: {len(processed_files)}")
|
| 139 |
+
|
| 140 |
+
if failed_files:
|
| 141 |
+
st.warning(f"⚠️ Failed to process {len(failed_files)} files: {', '.join(failed_files)}")
|
| 142 |
+
|
| 143 |
+
else:
|
| 144 |
+
st.info("👆 Please upload image files to get started.")
|
| 145 |
+
|
| 146 |
+
# Instructions
|
| 147 |
+
with st.expander("📖 Instructions"):
|
| 148 |
+
st.markdown("""
|
| 149 |
+
**How to use this tool:**
|
| 150 |
+
|
| 151 |
+
1. Upload one or more image files
|
| 152 |
+
2. Choose processing options:
|
| 153 |
+
- Crop white background: Removes excess white space around the image
|
| 154 |
+
- Overwrite original files: Not applicable in this web version (always creates new files)
|
| 155 |
+
3. Click "Process Images"
|
| 156 |
+
4. Download the processed images with transparent backgrounds
|
| 157 |
+
|
| 158 |
+
**Note:**
|
| 159 |
+
- Output images will always be in PNG format to support transparency
|
| 160 |
+
- Only white backgrounds will be made transparent (threshold of 240/255)
|
| 161 |
+
- Complex images may require manual adjustment for best results
|
| 162 |
+
""")
|
tab4.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import zipfile
|
| 3 |
+
import streamlit as st
|
| 4 |
+
from reportlab.lib.pagesizes import A4
|
| 5 |
+
from reportlab.lib.styles import getSampleStyleSheet
|
| 6 |
+
|
| 7 |
+
from helper import extract_zip_to_temp, erkenne_marken_aus_ordnern, generate_pdf_report, get_files_by_marke, analyze_files_by_filename, generate_two_section_pdf_report
|
| 8 |
+
|
| 9 |
+
def pdf_generator_tool():
|
| 10 |
+
st.header("Asset Overview")
|
| 11 |
+
st.markdown("Upload a zip file containing brand assets to generate asset overview by brand")
|
| 12 |
+
|
| 13 |
+
# Analysis method selection
|
| 14 |
+
analysis_method = st.radio(
|
| 15 |
+
"Choose:",
|
| 16 |
+
["Overview by Brand", "Overview by Asset Type"],
|
| 17 |
+
help="Overview by Brand: assets are organized by brand folders (they do NOT include brandname_ (underscore \"_\") in filename) . Overview by Asset Type: assets are organized by blocks AND include brandname_ (underscore \"_\") in filename)"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
# File upload
|
| 21 |
+
uploaded_file = st.file_uploader(
|
| 22 |
+
"Choose a ZIP file",
|
| 23 |
+
type=['zip'],
|
| 24 |
+
key="pdf_zip_upload"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
if uploaded_file is not None:
|
| 28 |
+
try:
|
| 29 |
+
# Extract zip file
|
| 30 |
+
with st.spinner("Extracting zip file..."):
|
| 31 |
+
temp_dir = extract_zip_to_temp(uploaded_file)
|
| 32 |
+
|
| 33 |
+
# Find the actual input folder (in case zip has a root folder)
|
| 34 |
+
input_folder = temp_dir
|
| 35 |
+
items = os.listdir(temp_dir)
|
| 36 |
+
if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
|
| 37 |
+
input_folder = os.path.join(temp_dir, items[0])
|
| 38 |
+
|
| 39 |
+
if analysis_method == "Overview by Brand":
|
| 40 |
+
# Original folder-based analysis
|
| 41 |
+
marken = erkenne_marken_aus_ordnern(input_folder)
|
| 42 |
+
|
| 43 |
+
if not marken:
|
| 44 |
+
st.error("No brand folders found in the uploaded zip file.")
|
| 45 |
+
st.info("Make sure your zip file contains folders named after your brands, with assets inside each folder.")
|
| 46 |
+
return
|
| 47 |
+
|
| 48 |
+
st.success(f"Found brands: {', '.join(marken)}")
|
| 49 |
+
|
| 50 |
+
# Get file counts for processing
|
| 51 |
+
dateien_pro_marke = get_files_by_marke(input_folder, marken)
|
| 52 |
+
|
| 53 |
+
# Options
|
| 54 |
+
erste_marke = st.selectbox(
|
| 55 |
+
"Which brand should appear first in the overview?",
|
| 56 |
+
options=["Alphabetical order"] + marken
|
| 57 |
+
)
|
| 58 |
+
erste_marke = erste_marke if erste_marke != "Alphabetical order" else None
|
| 59 |
+
|
| 60 |
+
# Generate PDF button
|
| 61 |
+
if st.button("Generate PDF Report", type="primary"):
|
| 62 |
+
with st.spinner("Generating PDF report..."):
|
| 63 |
+
pdf_buffer, error = generate_pdf_report(input_folder, erste_marke)
|
| 64 |
+
|
| 65 |
+
if error:
|
| 66 |
+
st.error(f"{error}")
|
| 67 |
+
elif pdf_buffer:
|
| 68 |
+
st.success("PDF report generated successfully!")
|
| 69 |
+
|
| 70 |
+
# Download button
|
| 71 |
+
st.download_button(
|
| 72 |
+
label="📥 Download PDF Report",
|
| 73 |
+
data=pdf_buffer.getvalue(),
|
| 74 |
+
file_name="Brand_Assets_Report.pdf",
|
| 75 |
+
mime="application/pdf"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
else:
|
| 79 |
+
# Filename-based analysis (Overview by Asset Type)
|
| 80 |
+
marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
|
| 81 |
+
|
| 82 |
+
if not marken_set:
|
| 83 |
+
st.error("No brands found in filenames.")
|
| 84 |
+
st.info("Make sure your files are named with brand identifiers at the beginning (e.g., 'Brand1_asset.jpg').")
|
| 85 |
+
return
|
| 86 |
+
|
| 87 |
+
st.success(f"Found brands from filenames: {', '.join(sorted(marken_set))}")
|
| 88 |
+
|
| 89 |
+
# Show analysis preview
|
| 90 |
+
with st.expander("Analysis Preview"):
|
| 91 |
+
total_files = len(all_files)
|
| 92 |
+
for folder, brands in renamed_files_by_folder_and_marke.items():
|
| 93 |
+
st.write(f"**{folder}:**")
|
| 94 |
+
for brand, files in brands.items():
|
| 95 |
+
st.write(f"- {brand}: {len(files)} files")
|
| 96 |
+
|
| 97 |
+
# Options
|
| 98 |
+
erste_marke = st.selectbox(
|
| 99 |
+
"Which brand should be numbered as 01?",
|
| 100 |
+
options=["Alphabetical order"] + sorted(list(marken_set))
|
| 101 |
+
)
|
| 102 |
+
erste_marke = erste_marke if erste_marke != "Alphabetical order" else None
|
| 103 |
+
|
| 104 |
+
# Generate PDF button
|
| 105 |
+
if st.button("Generate PDF Report", type="primary"):
|
| 106 |
+
with st.spinner("Generating PDF report..."):
|
| 107 |
+
# Use the two-section report function for filename-based analysis
|
| 108 |
+
pdf_buffer, error = generate_two_section_pdf_report(input_folder, erste_marke)
|
| 109 |
+
|
| 110 |
+
if error:
|
| 111 |
+
st.error(f"{error}")
|
| 112 |
+
elif pdf_buffer:
|
| 113 |
+
st.success("PDF report generated successfully! (Contains two sections: by Brand and by Asset Type)")
|
| 114 |
+
|
| 115 |
+
# Download button
|
| 116 |
+
st.download_button(
|
| 117 |
+
label="📥 Download PDF Report (Two Sections)",
|
| 118 |
+
data=pdf_buffer.getvalue(),
|
| 119 |
+
file_name="IcAt_Overview by Brand and Asset Type.pdf",
|
| 120 |
+
mime="application/pdf"
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
except zipfile.BadZipFile:
|
| 124 |
+
st.error("Invalid zip file. Please upload a valid zip file.")
|
| 125 |
+
except Exception as e:
|
| 126 |
+
st.error(f"An error occurred: {str(e)}")
|
| 127 |
+
|
| 128 |
+
else:
|
| 129 |
+
st.info("👆 Please upload a zip file to get started.")
|
| 130 |
+
|
| 131 |
+
# Instructions
|
| 132 |
+
with st.expander("📖 Instructions"):
|
| 133 |
+
st.markdown("""
|
| 134 |
+
**How to use this tool:**
|
| 135 |
+
|
| 136 |
+
**Overview by Brand:**
|
| 137 |
+
- Create folders named after your brands
|
| 138 |
+
- Place brand assets inside each brand folder
|
| 139 |
+
- Assets do NOT need brand names in their filenames
|
| 140 |
+
- Zip the entire structure
|
| 141 |
+
- Generates single-section PDF report organized by brand
|
| 142 |
+
|
| 143 |
+
**Overview by Asset Type:**
|
| 144 |
+
- Name your files with brand identifiers at the beginning followed by an underscore (e.g., 'Brand1_asset.jpg', 'Brand2_document.pdf')
|
| 145 |
+
- Organize files in any folder structure (blocks/categories)
|
| 146 |
+
- The tool will extract brand names from filenames automatically
|
| 147 |
+
- Generates two-section PDF report: Section 1 (by Asset Type/Block) and Section 2 (by Brand)
|
| 148 |
+
|
| 149 |
+
**Supported file types:**
|
| 150 |
+
- **Images:** JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP
|
| 151 |
+
- **Text files:** TXT, MD, CSV
|
| 152 |
+
""")
|
tab5.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
import streamlit as st
|
| 7 |
+
from reportlab.lib.pagesizes import A4
|
| 8 |
+
from reportlab.lib.styles import getSampleStyleSheet
|
| 9 |
+
from helper import extract_zip_to_temp, analyze_files_by_filename, generate_filename_based_pdf_report_with_extensions, process_files, generate_excel_report
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def brand_renamer_tool():
|
| 14 |
+
st.header("Advanced Brand File Processor")
|
| 15 |
+
st.markdown("Automatically rename and organize brand assets with numbering and generate reports.")
|
| 16 |
+
|
| 17 |
+
# Initialize session state for persistent results
|
| 18 |
+
if 'processing_complete' not in st.session_state:
|
| 19 |
+
st.session_state.processing_complete = False
|
| 20 |
+
if 'processed_data' not in st.session_state:
|
| 21 |
+
st.session_state.processed_data = {}
|
| 22 |
+
|
| 23 |
+
uploaded_file = st.file_uploader(
|
| 24 |
+
"Choose a ZIP file",
|
| 25 |
+
type=['zip'],
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Reset processing state when new file is uploaded
|
| 29 |
+
if uploaded_file and 'uploaded_file_name' in st.session_state:
|
| 30 |
+
if st.session_state.uploaded_file_name != uploaded_file.name:
|
| 31 |
+
st.session_state.processing_complete = False
|
| 32 |
+
st.session_state.processed_data = {}
|
| 33 |
+
|
| 34 |
+
if uploaded_file:
|
| 35 |
+
# Store uploaded file name to detect changes
|
| 36 |
+
st.session_state.uploaded_file_name = uploaded_file.name
|
| 37 |
+
|
| 38 |
+
if not st.session_state.processing_complete:
|
| 39 |
+
with st.spinner("Extracting and analyzing files..."):
|
| 40 |
+
temp_dir = extract_zip_to_temp(uploaded_file)
|
| 41 |
+
input_folder = Path(temp_dir)
|
| 42 |
+
|
| 43 |
+
items = os.listdir(temp_dir)
|
| 44 |
+
if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
|
| 45 |
+
input_folder = Path(temp_dir) / items[0]
|
| 46 |
+
|
| 47 |
+
output_folder = Path(temp_dir) / "output"
|
| 48 |
+
output_folder.mkdir(exist_ok=True)
|
| 49 |
+
|
| 50 |
+
marken_set, _, _ = analyze_files_by_filename(input_folder)
|
| 51 |
+
|
| 52 |
+
if not marken_set:
|
| 53 |
+
st.error("No brands found in the uploaded files.")
|
| 54 |
+
return
|
| 55 |
+
|
| 56 |
+
st.success(f"Detected brands: {', '.join(sorted(marken_set))}")
|
| 57 |
+
|
| 58 |
+
# Brand numbering selection
|
| 59 |
+
st.subheader("Brand Numbering")
|
| 60 |
+
erste_marke = st.selectbox(
|
| 61 |
+
"Which brand should be number 01?",
|
| 62 |
+
options=sorted(marken_set),
|
| 63 |
+
index=0
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
marken_index = {erste_marke: "01"}
|
| 67 |
+
aktuelle_nummer = 2
|
| 68 |
+
for marke in sorted(marken_set):
|
| 69 |
+
if marke != erste_marke:
|
| 70 |
+
marken_index[marke] = f"{aktuelle_nummer:02d}"
|
| 71 |
+
aktuelle_nummer += 1
|
| 72 |
+
|
| 73 |
+
if st.button("Process Files and Generate Reports", type="primary"):
|
| 74 |
+
with st.spinner("Processing files..."):
|
| 75 |
+
# Process and rename files
|
| 76 |
+
renamed_files, file_to_factorgroup = process_files(
|
| 77 |
+
input_folder,
|
| 78 |
+
marken_index,
|
| 79 |
+
output_folder
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# Also rename actual files in output folder to have .png extensions
|
| 83 |
+
for file_path in output_folder.iterdir():
|
| 84 |
+
if file_path.is_file() and not file_path.suffix:
|
| 85 |
+
# File has no extension, add .png
|
| 86 |
+
new_file_path = file_path.with_suffix('.png')
|
| 87 |
+
try:
|
| 88 |
+
file_path.rename(new_file_path)
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print(f"Could not rename {file_path}: {e}")
|
| 91 |
+
|
| 92 |
+
# Generate PDF with extensions - use the modified function
|
| 93 |
+
pdf_buffer, error = generate_filename_based_pdf_report_with_extensions(
|
| 94 |
+
input_folder,
|
| 95 |
+
erste_marke,
|
| 96 |
+
marken_index # Pass marken_index for ID generation
|
| 97 |
+
)
|
| 98 |
+
if error:
|
| 99 |
+
st.error(f"PDF generation failed: {error}")
|
| 100 |
+
|
| 101 |
+
excel_path = generate_excel_report(output_folder, marken_index, file_to_factorgroup)
|
| 102 |
+
|
| 103 |
+
# Create individual file buffers
|
| 104 |
+
zip_buffer = io.BytesIO()
|
| 105 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
| 106 |
+
for file in output_folder.iterdir():
|
| 107 |
+
zip_file.write(file, file.name)
|
| 108 |
+
zip_buffer.seek(0)
|
| 109 |
+
|
| 110 |
+
# Create combined download with all files
|
| 111 |
+
combined_zip_buffer = io.BytesIO()
|
| 112 |
+
with zipfile.ZipFile(combined_zip_buffer, 'w', zipfile.ZIP_DEFLATED) as combined_zip:
|
| 113 |
+
# Add processed files
|
| 114 |
+
for file in output_folder.iterdir():
|
| 115 |
+
combined_zip.write(file, f"processed_files/{file.name}")
|
| 116 |
+
|
| 117 |
+
# Add PDF report if available
|
| 118 |
+
if pdf_buffer:
|
| 119 |
+
combined_zip.writestr("reports/Brand_Assets_Report.pdf", pdf_buffer.getvalue())
|
| 120 |
+
|
| 121 |
+
# Add Excel report
|
| 122 |
+
with open(excel_path, 'rb') as excel_file:
|
| 123 |
+
combined_zip.writestr("reports/Brand_Assets_Overview.xlsx", excel_file.read())
|
| 124 |
+
|
| 125 |
+
combined_zip_buffer.seek(0)
|
| 126 |
+
|
| 127 |
+
# Store processed data in session state
|
| 128 |
+
st.session_state.processed_data = {
|
| 129 |
+
'pdf_buffer': pdf_buffer,
|
| 130 |
+
'excel_path': excel_path,
|
| 131 |
+
'zip_buffer': zip_buffer,
|
| 132 |
+
'combined_zip_buffer': combined_zip_buffer,
|
| 133 |
+
'temp_dir': temp_dir,
|
| 134 |
+
'renamed_files': renamed_files
|
| 135 |
+
}
|
| 136 |
+
st.session_state.processing_complete = True
|
| 137 |
+
|
| 138 |
+
# Force rerun to show download buttons
|
| 139 |
+
st.rerun()
|
| 140 |
+
|
| 141 |
+
# Show download options if processing is complete
|
| 142 |
+
if st.session_state.processing_complete:
|
| 143 |
+
st.success("Processing complete!")
|
| 144 |
+
|
| 145 |
+
# Display a preview of processed names with extensions
|
| 146 |
+
with st.expander("Preview Processed Names"):
|
| 147 |
+
if 'renamed_files' in st.session_state.processed_data:
|
| 148 |
+
st.write("Sample processed filenames (with .png extensions in PDF):")
|
| 149 |
+
# Handle the case where renamed_files might be a defaultdict
|
| 150 |
+
renamed_files_data = st.session_state.processed_data['renamed_files']
|
| 151 |
+
|
| 152 |
+
# Extract sample file names safely
|
| 153 |
+
sample_files = []
|
| 154 |
+
if hasattr(renamed_files_data, 'items'):
|
| 155 |
+
# It's a dictionary-like object
|
| 156 |
+
for folder_name, brand_data in list(renamed_files_data.items())[:3]: # First 3 folders
|
| 157 |
+
for brand_name, files in list(brand_data.items())[:2]: # First 2 brands per folder
|
| 158 |
+
for file_path, new_name in files[:2]: # First 2 files per brand
|
| 159 |
+
if isinstance(new_name, str):
|
| 160 |
+
pdf_name = Path(new_name).stem + '.png'
|
| 161 |
+
sample_files.append((Path(file_path).name, pdf_name))
|
| 162 |
+
if len(sample_files) >= 10:
|
| 163 |
+
break
|
| 164 |
+
if len(sample_files) >= 10:
|
| 165 |
+
break
|
| 166 |
+
if len(sample_files) >= 10:
|
| 167 |
+
break
|
| 168 |
+
|
| 169 |
+
# Display the sample files
|
| 170 |
+
for old_name, pdf_name in sample_files:
|
| 171 |
+
st.write(f"{old_name} → {pdf_name}")
|
| 172 |
+
|
| 173 |
+
# Option to start over
|
| 174 |
+
if st.button("🔄 Process New File", help="Clear results and upload a new file"):
|
| 175 |
+
st.session_state.processing_complete = False
|
| 176 |
+
st.session_state.processed_data = {}
|
| 177 |
+
if 'temp_dir' in st.session_state.processed_data:
|
| 178 |
+
try:
|
| 179 |
+
shutil.rmtree(st.session_state.processed_data['temp_dir'])
|
| 180 |
+
except:
|
| 181 |
+
pass
|
| 182 |
+
st.rerun()
|
| 183 |
+
|
| 184 |
+
st.markdown("---")
|
| 185 |
+
|
| 186 |
+
# Combined download option (recommended)
|
| 187 |
+
st.subheader("📦 Complete Package Download")
|
| 188 |
+
st.markdown("**Recommended:** Download everything in one convenient package")
|
| 189 |
+
|
| 190 |
+
if st.session_state.processed_data.get('combined_zip_buffer'):
|
| 191 |
+
st.download_button(
|
| 192 |
+
label="🎁 Download Complete Package (All Files + Reports)",
|
| 193 |
+
data=st.session_state.processed_data['combined_zip_buffer'].getvalue(),
|
| 194 |
+
file_name="Brand_Assets_Complete_Package.zip",
|
| 195 |
+
mime="application/zip",
|
| 196 |
+
type="primary"
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
st.markdown("---")
|
| 200 |
+
|
| 201 |
+
# Individual download options
|
| 202 |
+
st.subheader("📁 Individual Downloads")
|
| 203 |
+
st.markdown("Or download items separately:")
|
| 204 |
+
|
| 205 |
+
col1, col2, col3 = st.columns(3)
|
| 206 |
+
|
| 207 |
+
with col1:
|
| 208 |
+
if st.session_state.processed_data.get('pdf_buffer'):
|
| 209 |
+
st.download_button(
|
| 210 |
+
label="📄 PDF Report",
|
| 211 |
+
data=st.session_state.processed_data['pdf_buffer'].getvalue(),
|
| 212 |
+
file_name="Brand_Assets_Report.pdf",
|
| 213 |
+
mime="application/pdf"
|
| 214 |
+
)
|
| 215 |
+
else:
|
| 216 |
+
st.info("PDF report not available")
|
| 217 |
+
|
| 218 |
+
with col2:
|
| 219 |
+
if st.session_state.processed_data.get('excel_path'):
|
| 220 |
+
try:
|
| 221 |
+
with open(st.session_state.processed_data['excel_path'], 'rb') as excel_file:
|
| 222 |
+
st.download_button(
|
| 223 |
+
label="📊 Excel Report",
|
| 224 |
+
data=excel_file.read(),
|
| 225 |
+
file_name="Brand_Assets_Overview.xlsx",
|
| 226 |
+
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
| 227 |
+
)
|
| 228 |
+
except:
|
| 229 |
+
st.info("Excel report not available")
|
| 230 |
+
|
| 231 |
+
with col3:
|
| 232 |
+
if st.session_state.processed_data.get('zip_buffer'):
|
| 233 |
+
st.download_button(
|
| 234 |
+
label="📦 Processed Files",
|
| 235 |
+
data=st.session_state.processed_data['zip_buffer'].getvalue(),
|
| 236 |
+
file_name="Brand_Assets_Processed.zip",
|
| 237 |
+
mime="application/zip"
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
st.markdown("---")
|
| 241 |
+
st.info("💡 **Tip:** Downloads will remain available until you upload a new file or click 'Process New File'")
|
| 242 |
+
|
| 243 |
+
else:
|
| 244 |
+
# Reset session state when no file is uploaded
|
| 245 |
+
if st.session_state.processing_complete:
|
| 246 |
+
st.session_state.processing_complete = False
|
| 247 |
+
st.session_state.processed_data = {}
|
| 248 |
+
|
| 249 |
+
st.info("👆 Please upload a zip file to get started.")
|
| 250 |
+
|
| 251 |
+
with st.expander("📖 Instructions"):
|
| 252 |
+
st.markdown("""
|
| 253 |
+
Upload a ZIP file containing brand asset folders. The tool will:
|
| 254 |
+
1. Detect all brands automatically
|
| 255 |
+
2. Let you choose which brand gets number 01
|
| 256 |
+
3. Process and rename all files with proper numbering
|
| 257 |
+
4. Generate a PDF report showing all assets with filenames including .png extensions
|
| 258 |
+
5. Create an Excel overview of the processed files
|
| 259 |
+
6. Package everything for easy download
|
| 260 |
+
""")
|
tab6.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
import zipfile
|
| 4 |
+
import streamlit as st
|
| 5 |
+
from PIL import Image as PILImage
|
| 6 |
+
|
| 7 |
+
from helper import extract_zip_to_temp
|
| 8 |
+
|
| 9 |
+
ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'}
|
| 10 |
+
ALLOWED_TEXT_EXTENSIONS = {'.txt', '.md', '.csv'}
|
| 11 |
+
ALLOWED_VIDEO_EXTENSIONS = {'.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', '.m4v', '.3gp', '.ogv'}
|
| 12 |
+
ALLOWED_AUDIO_EXTENSIONS = {'.mp3', '.wav', '.aac', '.flac', '.ogg', '.m4a', '.wma'}
|
| 13 |
+
ALL_ALLOWED_EXTENSIONS = ALLOWED_IMAGE_EXTENSIONS.union(ALLOWED_TEXT_EXTENSIONS).union(ALLOWED_VIDEO_EXTENSIONS).union(ALLOWED_AUDIO_EXTENSIONS)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def resize_with_transparent_canvas_tool():
|
| 17 |
+
st.header("Resize with Transparent Canvas")
|
| 18 |
+
st.markdown("Resize images to 400px on the largest side while maintaining aspect ratio on transparent background.")
|
| 19 |
+
|
| 20 |
+
# File upload with unique key
|
| 21 |
+
uploaded_file = st.file_uploader(
|
| 22 |
+
"Choose a ZIP file with images",
|
| 23 |
+
type=['zip'],
|
| 24 |
+
help="Upload a zip file containing images to resize.",
|
| 25 |
+
key="resize_transparent_upload"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
if uploaded_file:
|
| 29 |
+
# Show the fixed resize setting
|
| 30 |
+
st.info("Images will be resized to 400px on the largest side (width or height), maintaining aspect ratio.")
|
| 31 |
+
|
| 32 |
+
# Process button with unique key
|
| 33 |
+
if st.button("Process Images", type="primary", key="process_resize_transparent_images"):
|
| 34 |
+
try:
|
| 35 |
+
# Extract zip file
|
| 36 |
+
with st.spinner("Extracting zip file..."):
|
| 37 |
+
temp_dir = extract_zip_to_temp(uploaded_file)
|
| 38 |
+
input_folder = temp_dir
|
| 39 |
+
items = os.listdir(temp_dir)
|
| 40 |
+
if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
|
| 41 |
+
input_folder = os.path.join(temp_dir, items[0])
|
| 42 |
+
|
| 43 |
+
# Create output folder
|
| 44 |
+
output_folder = os.path.join(temp_dir, "resized_transparent_output")
|
| 45 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 46 |
+
|
| 47 |
+
# Process images
|
| 48 |
+
processed_count = 0
|
| 49 |
+
error_count = 0
|
| 50 |
+
progress_bar = st.progress(0)
|
| 51 |
+
status_text = st.empty()
|
| 52 |
+
|
| 53 |
+
all_files = []
|
| 54 |
+
for root, dirs, files in os.walk(input_folder):
|
| 55 |
+
for file in files:
|
| 56 |
+
ext = os.path.splitext(file)[1].lower()
|
| 57 |
+
if ext in ALLOWED_IMAGE_EXTENSIONS:
|
| 58 |
+
all_files.append(os.path.join(root, file))
|
| 59 |
+
|
| 60 |
+
total_files = len(all_files)
|
| 61 |
+
|
| 62 |
+
for i, file_path in enumerate(all_files):
|
| 63 |
+
status_text.text(f"Processing {i+1}/{total_files}: {os.path.basename(file_path)}...")
|
| 64 |
+
progress_bar.progress((i + 1) / total_files)
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
relative_path = os.path.relpath(file_path, input_folder)
|
| 68 |
+
new_path = os.path.join(output_folder, os.path.splitext(relative_path)[0] + ".png")
|
| 69 |
+
os.makedirs(os.path.dirname(new_path), exist_ok=True)
|
| 70 |
+
|
| 71 |
+
with PILImage.open(file_path) as img:
|
| 72 |
+
img = img.convert("RGBA")
|
| 73 |
+
orig_w, orig_h = img.size
|
| 74 |
+
|
| 75 |
+
# Calculate scaling factor based on largest side
|
| 76 |
+
max_dimension = 400
|
| 77 |
+
if orig_w >= orig_h:
|
| 78 |
+
# Width is larger or equal
|
| 79 |
+
scale_factor = max_dimension / orig_w
|
| 80 |
+
new_w = max_dimension
|
| 81 |
+
new_h = int(orig_h * scale_factor)
|
| 82 |
+
else:
|
| 83 |
+
# Height is larger
|
| 84 |
+
scale_factor = max_dimension / orig_h
|
| 85 |
+
new_h = max_dimension
|
| 86 |
+
new_w = int(orig_w * scale_factor)
|
| 87 |
+
|
| 88 |
+
# Resize image while maintaining aspect ratio
|
| 89 |
+
img_resized = img.resize((new_w, new_h), PILImage.LANCZOS)
|
| 90 |
+
|
| 91 |
+
# Create transparent canvas with the exact resized dimensions
|
| 92 |
+
canvas = PILImage.new("RGBA", (new_w, new_h), (0, 0, 0, 0))
|
| 93 |
+
|
| 94 |
+
# The resized image fits perfectly on the canvas (no centering needed)
|
| 95 |
+
canvas.paste(img_resized, (0, 0), mask=img_resized)
|
| 96 |
+
|
| 97 |
+
canvas.save(new_path)
|
| 98 |
+
processed_count += 1
|
| 99 |
+
except Exception as e:
|
| 100 |
+
error_count += 1
|
| 101 |
+
st.warning(f"Error processing {os.path.basename(file_path)}: {str(e)}")
|
| 102 |
+
|
| 103 |
+
status_text.empty()
|
| 104 |
+
progress_bar.empty()
|
| 105 |
+
|
| 106 |
+
# Results summary
|
| 107 |
+
st.success(f"""
|
| 108 |
+
Processing complete!
|
| 109 |
+
- ✅ Processed: {processed_count} images
|
| 110 |
+
- ❌ Errors: {error_count} images
|
| 111 |
+
- All images resized to 400px on largest side
|
| 112 |
+
""")
|
| 113 |
+
|
| 114 |
+
if processed_count > 0:
|
| 115 |
+
# Create zip file with processed images
|
| 116 |
+
zip_buffer = io.BytesIO()
|
| 117 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
| 118 |
+
for root, dirs, files in os.walk(output_folder):
|
| 119 |
+
for file in files:
|
| 120 |
+
file_path = os.path.join(root, file)
|
| 121 |
+
rel_path = os.path.relpath(file_path, output_folder)
|
| 122 |
+
zip_file.write(file_path, rel_path)
|
| 123 |
+
|
| 124 |
+
zip_buffer.seek(0)
|
| 125 |
+
|
| 126 |
+
# Download button with unique key
|
| 127 |
+
st.download_button(
|
| 128 |
+
label="📥 Download Resized Images (ZIP)",
|
| 129 |
+
data=zip_buffer.getvalue(),
|
| 130 |
+
file_name="resized_400px_images.zip",
|
| 131 |
+
mime="application/zip",
|
| 132 |
+
key="download_resized_transparent"
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# Show preview
|
| 136 |
+
with st.expander("🖼️ Preview Resized Images"):
|
| 137 |
+
sample_files = []
|
| 138 |
+
for root, dirs, files in os.walk(output_folder):
|
| 139 |
+
for file in files[:3]: # Get first 3 files from each folder
|
| 140 |
+
if len(sample_files) < 6: # Max 6 samples
|
| 141 |
+
sample_files.append(os.path.join(root, file))
|
| 142 |
+
|
| 143 |
+
if sample_files:
|
| 144 |
+
cols = st.columns(3)
|
| 145 |
+
for i, file_path in enumerate(sample_files):
|
| 146 |
+
with cols[i % 3]:
|
| 147 |
+
img = PILImage.open(file_path)
|
| 148 |
+
st.image(img, caption=f"{os.path.basename(file_path)} ({img.size[0]}x{img.size[1]})", use_column_width=True)
|
| 149 |
+
|
| 150 |
+
if processed_count > 6:
|
| 151 |
+
st.info(f"Showing sample images. Total processed: {processed_count}")
|
| 152 |
+
|
| 153 |
+
except Exception as e:
|
| 154 |
+
st.error(f"An error occurred during processing: {str(e)}")
|
| 155 |
+
|
| 156 |
+
else:
|
| 157 |
+
st.info("👆 Please upload a zip file with images to resize.")
|
| 158 |
+
|
| 159 |
+
# Instructions
|
| 160 |
+
with st.expander("📖 Instructions"):
|
| 161 |
+
st.markdown("""
|
| 162 |
+
**How to use this tool:**
|
| 163 |
+
|
| 164 |
+
1. Upload a zip file containing images
|
| 165 |
+
2. All images will be resized to 400px on their largest side (width or height)
|
| 166 |
+
3. Aspect ratio is maintained - smaller dimension will be scaled proportionally
|
| 167 |
+
4. Click "Process Images"
|
| 168 |
+
5. Download the resized images with transparent backgrounds
|
| 169 |
+
|
| 170 |
+
**Examples:**
|
| 171 |
+
- 1000x800 image → 400x320 image (width was larger)
|
| 172 |
+
- 600x1200 image → 200x400 image (height was larger)
|
| 173 |
+
- 400x400 image → 400x400 image (already correct size)
|
| 174 |
+
|
| 175 |
+
**Features:**
|
| 176 |
+
- Maintains original aspect ratio
|
| 177 |
+
- Outputs PNG files to preserve transparency
|
| 178 |
+
- Preserves folder structure
|
| 179 |
+
- Fixed 400px maximum on largest dimension
|
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|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
import zipfile
|
| 4 |
+
import streamlit as st
|
| 5 |
+
from PIL import Image as PILImage
|
| 6 |
+
|
| 7 |
+
from helper import extract_zip_to_temp
|
| 8 |
+
|
| 9 |
+
ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'}
|
| 10 |
+
ALLOWED_TEXT_EXTENSIONS = {'.txt', '.md', '.csv'}
|
| 11 |
+
ALLOWED_VIDEO_EXTENSIONS = {'.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', '.m4v', '.3gp', '.ogv'}
|
| 12 |
+
ALLOWED_AUDIO_EXTENSIONS = {'.mp3', '.wav', '.aac', '.flac', '.ogg', '.m4a', '.wma'}
|
| 13 |
+
ALL_ALLOWED_EXTENSIONS = ALLOWED_IMAGE_EXTENSIONS.union(ALLOWED_TEXT_EXTENSIONS).union(ALLOWED_VIDEO_EXTENSIONS).union(ALLOWED_AUDIO_EXTENSIONS)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def center_on_canvas_tool():
|
| 17 |
+
st.header("Center on Transparent Canvas")
|
| 18 |
+
st.markdown("Center small images on a transparent 500x500 canvas.")
|
| 19 |
+
|
| 20 |
+
# File upload - add unique key
|
| 21 |
+
uploaded_file = st.file_uploader(
|
| 22 |
+
"Choose a ZIP file with images",
|
| 23 |
+
type=['zip'],
|
| 24 |
+
help="Upload a zip file containing images to process.",
|
| 25 |
+
key="canvas_center_upload" # Added unique key
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
if uploaded_file:
|
| 29 |
+
# Options
|
| 30 |
+
canvas_size = st.number_input(
|
| 31 |
+
"Canvas size (pixels):",
|
| 32 |
+
min_value=100,
|
| 33 |
+
max_value=5000,
|
| 34 |
+
value=500,
|
| 35 |
+
step=10,
|
| 36 |
+
key="canvas_size_input" # Added unique key
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# Add unique key to the button
|
| 40 |
+
if st.button("Process Images", type="primary", key="process_canvas_images"):
|
| 41 |
+
try:
|
| 42 |
+
# Extract zip file
|
| 43 |
+
with st.spinner("Extracting zip file..."):
|
| 44 |
+
temp_dir = extract_zip_to_temp(uploaded_file)
|
| 45 |
+
input_folder = temp_dir
|
| 46 |
+
items = os.listdir(temp_dir)
|
| 47 |
+
if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
|
| 48 |
+
input_folder = os.path.join(temp_dir, items[0])
|
| 49 |
+
|
| 50 |
+
# Create output folder
|
| 51 |
+
output_folder = os.path.join(temp_dir, "canvas_output")
|
| 52 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 53 |
+
|
| 54 |
+
# Process images
|
| 55 |
+
processed_count = 0
|
| 56 |
+
progress_bar = st.progress(0)
|
| 57 |
+
status_text = st.empty()
|
| 58 |
+
|
| 59 |
+
all_files = []
|
| 60 |
+
for root, dirs, files in os.walk(input_folder):
|
| 61 |
+
for file in files:
|
| 62 |
+
ext = os.path.splitext(file)[1].lower()
|
| 63 |
+
if ext in ALLOWED_IMAGE_EXTENSIONS:
|
| 64 |
+
all_files.append(os.path.join(root, file))
|
| 65 |
+
|
| 66 |
+
for i, file_path in enumerate(all_files):
|
| 67 |
+
status_text.text(f"Processing {os.path.basename(file_path)}... ({i+1}/{len(all_files)})")
|
| 68 |
+
progress_bar.progress((i + 1) / len(all_files))
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
with PILImage.open(file_path) as img:
|
| 72 |
+
width, height = img.size
|
| 73 |
+
|
| 74 |
+
if width < canvas_size and height < canvas_size:
|
| 75 |
+
# Create transparent canvas
|
| 76 |
+
canvas = PILImage.new('RGBA', (canvas_size, canvas_size), (255, 255, 255, 0))
|
| 77 |
+
|
| 78 |
+
# Convert image to RGBA if needed
|
| 79 |
+
if img.mode != 'RGBA':
|
| 80 |
+
img = img.convert('RGBA')
|
| 81 |
+
|
| 82 |
+
# Center image on canvas
|
| 83 |
+
paste_x = (canvas_size - width) // 2
|
| 84 |
+
paste_y = (canvas_size - height) // 2
|
| 85 |
+
canvas.paste(img, (paste_x, paste_y), img)
|
| 86 |
+
|
| 87 |
+
# Save processed image
|
| 88 |
+
new_filename = os.path.splitext(os.path.basename(file_path))[0] + ".png"
|
| 89 |
+
output_path = os.path.join(output_folder, new_filename)
|
| 90 |
+
canvas.save(output_path)
|
| 91 |
+
processed_count += 1
|
| 92 |
+
except Exception as e:
|
| 93 |
+
st.warning(f"Error processing {os.path.basename(file_path)}: {str(e)}")
|
| 94 |
+
|
| 95 |
+
status_text.empty()
|
| 96 |
+
progress_bar.empty()
|
| 97 |
+
|
| 98 |
+
if processed_count > 0:
|
| 99 |
+
st.success(f"✅ Successfully processed {processed_count} images")
|
| 100 |
+
|
| 101 |
+
# Create zip file with processed images
|
| 102 |
+
zip_buffer = io.BytesIO()
|
| 103 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
| 104 |
+
for root, dirs, files in os.walk(output_folder):
|
| 105 |
+
for file in files:
|
| 106 |
+
file_path = os.path.join(root, file)
|
| 107 |
+
rel_path = os.path.relpath(file_path, output_folder)
|
| 108 |
+
zip_file.write(file_path, rel_path)
|
| 109 |
+
|
| 110 |
+
zip_buffer.seek(0)
|
| 111 |
+
|
| 112 |
+
# Download button
|
| 113 |
+
st.download_button(
|
| 114 |
+
label="📥 Download Processed Images (ZIP)",
|
| 115 |
+
data=zip_buffer.getvalue(),
|
| 116 |
+
file_name="centered_images.zip",
|
| 117 |
+
mime="application/zip"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
# Show preview
|
| 121 |
+
with st.expander("🖼️ Preview Processed Images"):
|
| 122 |
+
sample_files = []
|
| 123 |
+
for root, dirs, files in os.walk(output_folder):
|
| 124 |
+
for file in files[:3]: # Get first 3 files from each folder
|
| 125 |
+
if len(sample_files) < 6: # Max 6 samples
|
| 126 |
+
sample_files.append(os.path.join(root, file))
|
| 127 |
+
|
| 128 |
+
cols = st.columns(3)
|
| 129 |
+
for i, file_path in enumerate(sample_files):
|
| 130 |
+
with cols[i % 3]:
|
| 131 |
+
img = PILImage.open(file_path)
|
| 132 |
+
st.image(img, caption=os.path.basename(file_path), use_column_width=True)
|
| 133 |
+
|
| 134 |
+
if processed_count > 6:
|
| 135 |
+
st.info(f"Showing sample images. Total processed: {processed_count}")
|
| 136 |
+
else:
|
| 137 |
+
st.warning("No images were processed (all images were already larger than the canvas size).")
|
| 138 |
+
|
| 139 |
+
except Exception as e:
|
| 140 |
+
st.error(f"An error occurred: {str(e)}")
|
| 141 |
+
|
| 142 |
+
else:
|
| 143 |
+
st.info("👆 Please upload a zip file with images to process.")
|
| 144 |
+
|
| 145 |
+
# Instructions
|
| 146 |
+
with st.expander("📖 Instructions"):
|
| 147 |
+
st.markdown("""
|
| 148 |
+
**How to use this tool:**
|
| 149 |
+
|
| 150 |
+
1. Upload a zip file containing images
|
| 151 |
+
2. Set the canvas size (default is 500x500 pixels)
|
| 152 |
+
3. Click "Process Images"
|
| 153 |
+
4. Download the processed images
|
| 154 |
+
|
| 155 |
+
**Features:**
|
| 156 |
+
- Centers images smaller than canvas size on transparent background
|
| 157 |
+
- Images larger than canvas size are skipped
|
| 158 |
+
- Outputs PNG files to preserve transparency
|
| 159 |
+
- Preserves folder structure
|
| 160 |
+
|
| 161 |
+
**Note:**
|
| 162 |
+
- Only images smaller than the specified canvas size will be processed
|
| 163 |
+
- Original aspect ratio is maintained
|
| 164 |
+
""")
|