Spaces:
Sleeping
Sleeping
venkatesh commited on
Commit Β·
c9303e1
1
Parent(s): d3aa4e9
added new tab8
Browse files- __pycache__/helper.cpython-313.pyc +0 -0
- __pycache__/tab8.cpython-313.pyc +0 -0
- app.py +11 -7
- helper.py +1 -1
- tab8.py +555 -0
__pycache__/helper.cpython-313.pyc
CHANGED
|
Binary files a/__pycache__/helper.cpython-313.pyc and b/__pycache__/helper.cpython-313.pyc differ
|
|
|
__pycache__/tab8.cpython-313.pyc
CHANGED
|
Binary files a/__pycache__/tab8.cpython-313.pyc and b/__pycache__/tab8.cpython-313.pyc differ
|
|
|
app.py
CHANGED
|
@@ -6,6 +6,7 @@ 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(
|
|
@@ -18,31 +19,34 @@ st.set_page_config(
|
|
| 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 |
-
|
| 44 |
with tab7:
|
| 45 |
center_on_canvas_tool()
|
|
|
|
|
|
|
| 46 |
|
| 47 |
if __name__ == "__main__":
|
| 48 |
main()
|
|
|
|
| 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 |
+
from tab8 import regenerate_reports_tool
|
| 10 |
|
| 11 |
# Configure Streamlit page
|
| 12 |
st.set_page_config(
|
|
|
|
| 19 |
def main():
|
| 20 |
st.title("π§ Brand Assets Tools")
|
| 21 |
|
| 22 |
+
tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8 = st.tabs([
|
| 23 |
"Extract Images from Excel",
|
| 24 |
"Name assets by brand",
|
| 25 |
"Canvas white to Transparent",
|
| 26 |
"Asset Overview",
|
| 27 |
"Name stims by block + create output filesβ",
|
| 28 |
+
"Re-run Matrix",
|
| 29 |
"Resize",
|
| 30 |
"Place on Canvas"
|
| 31 |
+
|
| 32 |
])
|
| 33 |
|
| 34 |
with tab1:
|
| 35 |
excel_extractor_tool()
|
| 36 |
with tab2:
|
| 37 |
+
file_renamer_tool()
|
| 38 |
with tab3:
|
| 39 |
+
white_to_transparent_tool()
|
| 40 |
with tab4:
|
| 41 |
+
pdf_generator_tool()
|
| 42 |
with tab5:
|
| 43 |
+
brand_renamer_tool()
|
| 44 |
with tab6:
|
| 45 |
+
regenerate_reports_tool()
|
| 46 |
with tab7:
|
| 47 |
center_on_canvas_tool()
|
| 48 |
+
with tab8:
|
| 49 |
+
resize_with_transparent_canvas_tool()
|
| 50 |
|
| 51 |
if __name__ == "__main__":
|
| 52 |
main()
|
helper.py
CHANGED
|
@@ -202,7 +202,7 @@ def generate_excel_report(output_folder: Path, marken_index: dict, file_to_facto
|
|
| 202 |
|
| 203 |
if "B20" in only_id.upper():
|
| 204 |
is_b20_id = True
|
| 205 |
-
language_value = only_id +
|
| 206 |
elif file_ext == '.txt':
|
| 207 |
is_text_file = True
|
| 208 |
try:
|
|
|
|
| 202 |
|
| 203 |
if "B20" in only_id.upper():
|
| 204 |
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import shutil
|
| 5 |
+
import zipfile
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
import streamlit as st
|
| 9 |
+
from helper import (
|
| 10 |
+
extract_zip_to_temp,
|
| 11 |
+
generate_excel_report,
|
| 12 |
+
generate_filename_based_pdf_report_with_extensions,
|
| 13 |
+
ALL_ALLOWED_EXTENSIONS,
|
| 14 |
+
is_valid_file
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def parse_filename(filename):
|
| 19 |
+
"""
|
| 20 |
+
Parse filename following Tab 5 naming convention:
|
| 21 |
+
{markennummer}B{blocknummer}{marke}{count_str}{cleaned}{original_ext}
|
| 22 |
+
|
| 23 |
+
Returns: (markennummer, blocknummer, marke, count_str, cleaned, ext) or None if invalid
|
| 24 |
+
"""
|
| 25 |
+
stem = Path(filename).stem
|
| 26 |
+
ext = Path(filename).suffix.lower()
|
| 27 |
+
|
| 28 |
+
# Pattern: 2 digits + B + 2 digits + brand name (letters only) + 2 digits + rest
|
| 29 |
+
# Try to match brand name as letters only first, then extract count_str
|
| 30 |
+
match = re.match(r'^(\d{2})B(\d{2})([a-zA-Z]+)(\d{2})(.*)$', stem)
|
| 31 |
+
|
| 32 |
+
if match:
|
| 33 |
+
markennummer, blocknummer, marke, count_str, cleaned = match.groups()
|
| 34 |
+
return {
|
| 35 |
+
'markennummer': markennummer,
|
| 36 |
+
'blocknummer': blocknummer,
|
| 37 |
+
'marke': marke.lower(),
|
| 38 |
+
'count_str': count_str,
|
| 39 |
+
'cleaned': cleaned,
|
| 40 |
+
'ext': ext,
|
| 41 |
+
'full_filename': filename
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
# Fallback: Try more flexible pattern if brand contains numbers
|
| 45 |
+
match = re.match(r'^(\d{2})B(\d{2})([a-z0-9]+?)(\d{2})(.*)$', stem, re.IGNORECASE)
|
| 46 |
+
if match:
|
| 47 |
+
markennummer, blocknummer, marke, count_str, cleaned = match.groups()
|
| 48 |
+
return {
|
| 49 |
+
'markennummer': markennummer,
|
| 50 |
+
'blocknummer': blocknummer,
|
| 51 |
+
'marke': marke.lower(),
|
| 52 |
+
'count_str': count_str,
|
| 53 |
+
'cleaned': cleaned,
|
| 54 |
+
'ext': ext,
|
| 55 |
+
'full_filename': filename
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
return None
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def reconstruct_folder_structure(files_folder):
|
| 62 |
+
"""
|
| 63 |
+
Reconstruct the folder structure from parsed filenames.
|
| 64 |
+
Groups files by blocknummer (folder) and marke (brand).
|
| 65 |
+
|
| 66 |
+
Returns:
|
| 67 |
+
- marken_set: set of all brands
|
| 68 |
+
- renamed_files_by_folder_and_marke: nested dict structure
|
| 69 |
+
- marken_index: mapping of brand to markennummer
|
| 70 |
+
- file_to_factorgroup: mapping of filename to folder name
|
| 71 |
+
"""
|
| 72 |
+
marken_set = set()
|
| 73 |
+
marken_index = {}
|
| 74 |
+
renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
|
| 75 |
+
file_to_factorgroup = {}
|
| 76 |
+
|
| 77 |
+
# Collect all valid files
|
| 78 |
+
parsed_files = []
|
| 79 |
+
skipped_files = []
|
| 80 |
+
total_files = 0
|
| 81 |
+
|
| 82 |
+
for file_path in sorted(Path(files_folder).iterdir()):
|
| 83 |
+
if not file_path.is_file():
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
total_files += 1
|
| 87 |
+
|
| 88 |
+
if not is_valid_file(file_path):
|
| 89 |
+
skipped_files.append(f"{file_path.name} (invalid/system file)")
|
| 90 |
+
continue
|
| 91 |
+
|
| 92 |
+
# Skip Excel and PDF files from previous runs
|
| 93 |
+
if file_path.suffix.lower() in ['.xlsx', '.pdf']:
|
| 94 |
+
if 'Overview' in file_path.name or 'Report' in file_path.name:
|
| 95 |
+
skipped_files.append(f"{file_path.name} (report file)")
|
| 96 |
+
continue
|
| 97 |
+
|
| 98 |
+
# Parse filename
|
| 99 |
+
parsed = parse_filename(file_path.name)
|
| 100 |
+
if parsed:
|
| 101 |
+
parsed['file_path'] = file_path
|
| 102 |
+
parsed_files.append(parsed)
|
| 103 |
+
else:
|
| 104 |
+
skipped_files.append(f"{file_path.name} (doesn't match naming convention)")
|
| 105 |
+
|
| 106 |
+
# Build structure
|
| 107 |
+
for parsed in parsed_files:
|
| 108 |
+
marke = parsed['marke']
|
| 109 |
+
markennummer = parsed['markennummer']
|
| 110 |
+
blocknummer = parsed['blocknummer']
|
| 111 |
+
file_path = parsed['file_path']
|
| 112 |
+
|
| 113 |
+
# Add to marken_set
|
| 114 |
+
marken_set.add(marke)
|
| 115 |
+
|
| 116 |
+
# Add to marken_index (use first occurrence)
|
| 117 |
+
if marke not in marken_index:
|
| 118 |
+
marken_index[marke] = markennummer
|
| 119 |
+
|
| 120 |
+
# Create folder name - use just blocknummer to match Tab 5 output format
|
| 121 |
+
# The folder_name will be like "00Folder", "01Folder", etc.
|
| 122 |
+
folder_name = f"{blocknummer}Folder"
|
| 123 |
+
|
| 124 |
+
# Add to structure
|
| 125 |
+
renamed_files_by_folder_and_marke[folder_name][marke].append(
|
| 126 |
+
(file_path, file_path.name)
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# Map file to factorgroup - this is what goes into Excel's factorgroup column
|
| 130 |
+
file_to_factorgroup[file_path.name] = folder_name
|
| 131 |
+
|
| 132 |
+
# Prepare debug info
|
| 133 |
+
debug_info = {
|
| 134 |
+
'total_files': total_files,
|
| 135 |
+
'parsed_files': len(parsed_files),
|
| 136 |
+
'skipped_files': skipped_files
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
return marken_set, renamed_files_by_folder_and_marke, marken_index, file_to_factorgroup, debug_info
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def regenerate_reports_from_folder(files_folder):
|
| 143 |
+
"""
|
| 144 |
+
Regenerate PDF and Excel reports from a folder containing Tab 5 output files.
|
| 145 |
+
Uses the EXISTING Excel file to get the correct factorgroup mappings!
|
| 146 |
+
"""
|
| 147 |
+
import pandas as pd
|
| 148 |
+
|
| 149 |
+
# CRITICAL: Read the existing Excel file to get factorgroup mappings
|
| 150 |
+
existing_excel = Path(files_folder) / "IcAt_Overview_Final.xlsx"
|
| 151 |
+
|
| 152 |
+
if not existing_excel.exists():
|
| 153 |
+
return None, None, "Error: IcAt_Overview_Final.xlsx not found in the folder. This file is required to regenerate reports."
|
| 154 |
+
|
| 155 |
+
# Read existing Excel to get the file_to_factorgroup mapping
|
| 156 |
+
try:
|
| 157 |
+
df = pd.read_excel(existing_excel, sheet_name='Assets')
|
| 158 |
+
print(f"β
Excel has {len(df)} rows")
|
| 159 |
+
|
| 160 |
+
# Build file_to_factorgroup from the Excel
|
| 161 |
+
file_to_factorgroup = {}
|
| 162 |
+
for idx, row in df.iterrows():
|
| 163 |
+
lang_val = str(row['Language'])
|
| 164 |
+
factorgroup = str(row['factorgroup'])
|
| 165 |
+
|
| 166 |
+
# For normal files, Language contains the full filename with extension
|
| 167 |
+
# For text files, Language contains the text content
|
| 168 |
+
# For B20 files, Language contains the full filename with extension
|
| 169 |
+
|
| 170 |
+
# Check if Language looks like a filename (has an extension)
|
| 171 |
+
if '.' in lang_val and not lang_val.startswith('['): # Not an error message
|
| 172 |
+
filename = lang_val
|
| 173 |
+
file_to_factorgroup[filename] = factorgroup
|
| 174 |
+
|
| 175 |
+
if idx < 5: # Debug: show first 5 mappings
|
| 176 |
+
print(f" Row {idx}: '{filename}' -> {factorgroup}")
|
| 177 |
+
elif idx < 5:
|
| 178 |
+
# This is likely a text file - skip it for now
|
| 179 |
+
print(f" Row {idx}: Skipping (text content): '{lang_val[:30]}...'")
|
| 180 |
+
|
| 181 |
+
print(f"β
Loaded {len(file_to_factorgroup)} file mappings from existing Excel")
|
| 182 |
+
except Exception as e:
|
| 183 |
+
return None, None, f"Error reading existing Excel file: {str(e)}"
|
| 184 |
+
|
| 185 |
+
# Reconstruct structure from filenames
|
| 186 |
+
marken_set, renamed_files_by_folder_and_marke, marken_index, _, debug_info = reconstruct_folder_structure(files_folder)
|
| 187 |
+
|
| 188 |
+
if not marken_set:
|
| 189 |
+
error_msg = f"No valid files found matching the naming convention.\n\n"
|
| 190 |
+
error_msg += f"Total files found: {debug_info['total_files']}\n"
|
| 191 |
+
error_msg += f"Successfully parsed: {debug_info['parsed_files']}\n"
|
| 192 |
+
if debug_info['skipped_files']:
|
| 193 |
+
error_msg += f"\nSkipped files:\n"
|
| 194 |
+
for skipped in debug_info['skipped_files'][:10]: # Show first 10
|
| 195 |
+
error_msg += f" - {skipped}\n"
|
| 196 |
+
if len(debug_info['skipped_files']) > 10:
|
| 197 |
+
error_msg += f" ... and {len(debug_info['skipped_files']) - 10} more\n"
|
| 198 |
+
return None, None, error_msg
|
| 199 |
+
|
| 200 |
+
# Add any NEW files to file_to_factorgroup
|
| 201 |
+
new_files_added = 0
|
| 202 |
+
print(f"\nπ Scanning folder for NEW files not in existing Excel...")
|
| 203 |
+
for file_path in Path(files_folder).iterdir():
|
| 204 |
+
if file_path.is_file() and file_path.name not in file_to_factorgroup:
|
| 205 |
+
# Skip Excel/PDF files
|
| 206 |
+
if file_path.suffix.lower() in ['.xlsx', '.pdf']:
|
| 207 |
+
if 'Overview' in file_path.name or 'Report' in file_path.name:
|
| 208 |
+
continue
|
| 209 |
+
|
| 210 |
+
# Parse to get blocknummer for new files
|
| 211 |
+
parsed = parse_filename(file_path.name)
|
| 212 |
+
if parsed:
|
| 213 |
+
folder_name = f"{parsed['blocknummer']}Folder"
|
| 214 |
+
file_to_factorgroup[file_path.name] = folder_name
|
| 215 |
+
new_files_added += 1
|
| 216 |
+
print(f" β¨ NEW: {file_path.name} -> {folder_name}")
|
| 217 |
+
|
| 218 |
+
if new_files_added == 0:
|
| 219 |
+
print(f" βΉοΈ No new files found - all files already in Excel")
|
| 220 |
+
|
| 221 |
+
print(f"\nπ Summary:")
|
| 222 |
+
print(f" - Files from existing Excel: {len(file_to_factorgroup) - new_files_added}")
|
| 223 |
+
print(f" - NEW files added: {new_files_added}")
|
| 224 |
+
print(f" - Total files to process: {len(file_to_factorgroup)}")
|
| 225 |
+
|
| 226 |
+
# Create a temporary input folder structure that matches Tab 5 expectations
|
| 227 |
+
temp_input = Path(files_folder) / "_temp_input_structure"
|
| 228 |
+
temp_input.mkdir(exist_ok=True)
|
| 229 |
+
|
| 230 |
+
try:
|
| 231 |
+
# Create subfolder structure for PDF generation
|
| 232 |
+
for folder_name in renamed_files_by_folder_and_marke:
|
| 233 |
+
folder_path = temp_input / folder_name
|
| 234 |
+
folder_path.mkdir(exist_ok=True)
|
| 235 |
+
|
| 236 |
+
# Copy files to appropriate subfolders
|
| 237 |
+
for marke, files in renamed_files_by_folder_and_marke[folder_name].items():
|
| 238 |
+
for file_path, _ in files:
|
| 239 |
+
shutil.copy2(file_path, folder_path / file_path.name)
|
| 240 |
+
|
| 241 |
+
# Generate PDF using existing helper function
|
| 242 |
+
pdf_buffer, pdf_error = generate_filename_based_pdf_report_with_extensions(
|
| 243 |
+
temp_input,
|
| 244 |
+
erste_marke=None,
|
| 245 |
+
marken_index=marken_index
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
if pdf_error:
|
| 249 |
+
return None, None, f"PDF generation failed: {pdf_error}"
|
| 250 |
+
|
| 251 |
+
# Backup the old Excel file before deleting
|
| 252 |
+
old_excel_path = Path(files_folder) / "IcAt_Overview_Final.xlsx"
|
| 253 |
+
backup_excel_path = Path(files_folder) / "IcAt_Overview_Final.xlsx.backup"
|
| 254 |
+
if old_excel_path.exists():
|
| 255 |
+
# Create backup for comparison
|
| 256 |
+
shutil.copy2(old_excel_path, backup_excel_path)
|
| 257 |
+
# Remove old file to generate fresh
|
| 258 |
+
old_excel_path.unlink()
|
| 259 |
+
|
| 260 |
+
# Generate Excel using existing helper function
|
| 261 |
+
# Note: generate_excel_report will scan ALL files in files_folder
|
| 262 |
+
# including any newly added images
|
| 263 |
+
print(f"\nπ Generating Excel report...")
|
| 264 |
+
print(f" Passing {len(file_to_factorgroup)} file mappings to generate_excel_report")
|
| 265 |
+
|
| 266 |
+
# Debug: Show a few sample mappings
|
| 267 |
+
sample_count = 0
|
| 268 |
+
for filename, factorgroup in file_to_factorgroup.items():
|
| 269 |
+
if sample_count < 3:
|
| 270 |
+
print(f" Sample: '{filename}' -> '{factorgroup}'")
|
| 271 |
+
sample_count += 1
|
| 272 |
+
|
| 273 |
+
excel_path = generate_excel_report(
|
| 274 |
+
Path(files_folder),
|
| 275 |
+
marken_index,
|
| 276 |
+
file_to_factorgroup
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
# Debug: Check how many entries were added
|
| 280 |
+
import pandas as pd
|
| 281 |
+
try:
|
| 282 |
+
df = pd.read_excel(excel_path, sheet_name='Assets')
|
| 283 |
+
print(f"\nβ
Excel generated with {len(df)} rows")
|
| 284 |
+
|
| 285 |
+
# Check specifically for the user's new file
|
| 286 |
+
user_file = '01B01hersheys06packing.png'
|
| 287 |
+
if user_file in df['Language'].values:
|
| 288 |
+
row = df[df['Language'] == user_file].iloc[0]
|
| 289 |
+
print(f" β
Found user's new file '{user_file}':")
|
| 290 |
+
print(f" factor: {row['factor']}")
|
| 291 |
+
print(f" factorgroup: {row['factorgroup']}")
|
| 292 |
+
else:
|
| 293 |
+
print(f" β User's new file '{user_file}' NOT FOUND in Excel!")
|
| 294 |
+
print(f" Checking if file exists in folder...")
|
| 295 |
+
file_path = Path(files_folder) / user_file
|
| 296 |
+
if file_path.exists():
|
| 297 |
+
print(f" β
File EXISTS in folder")
|
| 298 |
+
else:
|
| 299 |
+
print(f" β File DOES NOT EXIST in folder")
|
| 300 |
+
except Exception as e:
|
| 301 |
+
print(f"Could not read Excel for debug: {e}")
|
| 302 |
+
|
| 303 |
+
return pdf_buffer, excel_path, None
|
| 304 |
+
|
| 305 |
+
finally:
|
| 306 |
+
# Clean up temp folder
|
| 307 |
+
if temp_input.exists():
|
| 308 |
+
shutil.rmtree(temp_input)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def regenerate_reports_tool():
|
| 312 |
+
"""Tab 8: Regenerate PDF and Excel from Tab 5 output + manually added images"""
|
| 313 |
+
st.header("Re Run Matrix")
|
| 314 |
+
st.markdown("Upload a ZIP containing Tab 5 output folder with optionally added images. The tool will regenerate PDF and Excel reports.")
|
| 315 |
+
|
| 316 |
+
# Initialize session state
|
| 317 |
+
if 'regeneration_complete' not in st.session_state:
|
| 318 |
+
st.session_state.regeneration_complete = False
|
| 319 |
+
if 'regenerated_data' not in st.session_state:
|
| 320 |
+
st.session_state.regenerated_data = {}
|
| 321 |
+
|
| 322 |
+
uploaded_file = st.file_uploader(
|
| 323 |
+
"Choose a ZIP file containing Tab 5 output",
|
| 324 |
+
type=['zip'],
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# Reset processing state when new file is uploaded
|
| 328 |
+
if uploaded_file and 'uploaded_file_name_tab8' in st.session_state:
|
| 329 |
+
if st.session_state.uploaded_file_name_tab8 != uploaded_file.name:
|
| 330 |
+
st.session_state.regeneration_complete = False
|
| 331 |
+
st.session_state.regenerated_data = {}
|
| 332 |
+
|
| 333 |
+
if uploaded_file:
|
| 334 |
+
st.session_state.uploaded_file_name_tab8 = uploaded_file.name
|
| 335 |
+
|
| 336 |
+
if not st.session_state.regeneration_complete:
|
| 337 |
+
if st.button("Regenerate Reports", type="primary"):
|
| 338 |
+
with st.spinner("Extracting files and analyzing structure..."):
|
| 339 |
+
# Extract ZIP
|
| 340 |
+
temp_dir = extract_zip_to_temp(uploaded_file)
|
| 341 |
+
|
| 342 |
+
# Find the actual files folder - look for processed_files
|
| 343 |
+
root_folder = Path(temp_dir)
|
| 344 |
+
|
| 345 |
+
# Keep descending if there's only one subfolder (to handle extra nesting)
|
| 346 |
+
while True:
|
| 347 |
+
items = [item for item in os.listdir(root_folder) if not item.startswith('.') and not item.startswith('_')]
|
| 348 |
+
|
| 349 |
+
# If only one item and it's a directory, descend into it
|
| 350 |
+
if len(items) == 1 and os.path.isdir(os.path.join(root_folder, items[0])):
|
| 351 |
+
root_folder = root_folder / items[0]
|
| 352 |
+
else:
|
| 353 |
+
# Found the actual root level
|
| 354 |
+
break
|
| 355 |
+
|
| 356 |
+
# Look for processed_files folder
|
| 357 |
+
processed_files_folder = root_folder / "processed_files"
|
| 358 |
+
if not processed_files_folder.exists():
|
| 359 |
+
# Maybe files are directly in root
|
| 360 |
+
processed_files_folder = root_folder
|
| 361 |
+
|
| 362 |
+
# Regenerate reports
|
| 363 |
+
with st.spinner("Regenerating PDF and Excel reports..."):
|
| 364 |
+
pdf_buffer, excel_path, error = regenerate_reports_from_folder(processed_files_folder)
|
| 365 |
+
|
| 366 |
+
if error:
|
| 367 |
+
st.error(error)
|
| 368 |
+
shutil.rmtree(temp_dir)
|
| 369 |
+
return
|
| 370 |
+
|
| 371 |
+
# Show Excel statistics
|
| 372 |
+
if excel_path and excel_path.exists():
|
| 373 |
+
import pandas as pd
|
| 374 |
+
try:
|
| 375 |
+
df_new = pd.read_excel(excel_path, sheet_name='Assets')
|
| 376 |
+
|
| 377 |
+
# Compare with old Excel
|
| 378 |
+
old_excel = processed_files_folder / "IcAt_Overview_Final.xlsx.backup"
|
| 379 |
+
if not old_excel.exists():
|
| 380 |
+
old_excel = processed_files_folder / "IcAt_Overview_Final.xlsx"
|
| 381 |
+
|
| 382 |
+
try:
|
| 383 |
+
df_old = pd.read_excel(old_excel, sheet_name='Assets')
|
| 384 |
+
old_count = len(df_old)
|
| 385 |
+
new_count = len(df_new)
|
| 386 |
+
added_count = new_count - old_count
|
| 387 |
+
|
| 388 |
+
if added_count > 0:
|
| 389 |
+
st.success(f"β
Excel generated with {new_count} entries ({added_count} NEW entries added!)")
|
| 390 |
+
else:
|
| 391 |
+
st.success(f"β
Excel generated with {new_count} entries (same as before)")
|
| 392 |
+
except:
|
| 393 |
+
st.success(f"β
Excel generated with {len(df_new)} entries")
|
| 394 |
+
|
| 395 |
+
except Exception as e:
|
| 396 |
+
st.warning(f"Excel created but couldn't read for stats: {e}")
|
| 397 |
+
|
| 398 |
+
# Create individual processed files ZIP (just like tab5)
|
| 399 |
+
zip_buffer = io.BytesIO()
|
| 400 |
+
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
| 401 |
+
for file in processed_files_folder.iterdir():
|
| 402 |
+
if file.is_file():
|
| 403 |
+
# Skip old backups
|
| 404 |
+
if file.name.endswith('.backup'):
|
| 405 |
+
continue
|
| 406 |
+
zip_file.write(file, file.name)
|
| 407 |
+
zip_buffer.seek(0)
|
| 408 |
+
|
| 409 |
+
# Create combined ZIP with processed_files/ and reports/ folders (just like tab5)
|
| 410 |
+
combined_zip_buffer = io.BytesIO()
|
| 411 |
+
with zipfile.ZipFile(combined_zip_buffer, 'w', zipfile.ZIP_DEFLATED) as combined_zip:
|
| 412 |
+
# Add all processed files to processed_files/ folder
|
| 413 |
+
for file in processed_files_folder.iterdir():
|
| 414 |
+
if file.is_file():
|
| 415 |
+
# Skip old backups
|
| 416 |
+
if file.name.endswith('.backup'):
|
| 417 |
+
continue
|
| 418 |
+
combined_zip.write(file, f"processed_files/{file.name}")
|
| 419 |
+
|
| 420 |
+
# Add PDF report to reports/ folder
|
| 421 |
+
if pdf_buffer:
|
| 422 |
+
combined_zip.writestr("reports/Brand_Assets_Report.pdf", pdf_buffer.getvalue())
|
| 423 |
+
|
| 424 |
+
# Add Excel report to reports/ folder
|
| 425 |
+
if excel_path and excel_path.exists():
|
| 426 |
+
with open(excel_path, 'rb') as excel_file:
|
| 427 |
+
combined_zip.writestr("reports/Brand_Assets_Overview.xlsx", excel_file.read())
|
| 428 |
+
|
| 429 |
+
combined_zip_buffer.seek(0)
|
| 430 |
+
|
| 431 |
+
# Store in session state
|
| 432 |
+
st.session_state.regenerated_data = {
|
| 433 |
+
'pdf_buffer': pdf_buffer,
|
| 434 |
+
'excel_path': excel_path,
|
| 435 |
+
'zip_buffer': zip_buffer,
|
| 436 |
+
'combined_zip_buffer': combined_zip_buffer,
|
| 437 |
+
'temp_dir': temp_dir
|
| 438 |
+
}
|
| 439 |
+
st.session_state.regeneration_complete = True
|
| 440 |
+
|
| 441 |
+
st.rerun()
|
| 442 |
+
|
| 443 |
+
# Show download options if processing is complete
|
| 444 |
+
if st.session_state.regeneration_complete:
|
| 445 |
+
st.success("β
Reports regenerated successfully!")
|
| 446 |
+
|
| 447 |
+
# Option to start over
|
| 448 |
+
if st.button("π Process New File", help="Clear results and upload a new file"):
|
| 449 |
+
st.session_state.regeneration_complete = False
|
| 450 |
+
st.session_state.regenerated_data = {}
|
| 451 |
+
if 'temp_dir' in st.session_state.regenerated_data:
|
| 452 |
+
try:
|
| 453 |
+
shutil.rmtree(st.session_state.regenerated_data['temp_dir'])
|
| 454 |
+
except:
|
| 455 |
+
pass
|
| 456 |
+
st.rerun()
|
| 457 |
+
|
| 458 |
+
st.markdown("---")
|
| 459 |
+
|
| 460 |
+
# Combined download option (recommended)
|
| 461 |
+
st.subheader("π¦ Complete Package Download")
|
| 462 |
+
st.markdown("**Recommended:** Download everything in one convenient package")
|
| 463 |
+
|
| 464 |
+
if st.session_state.regenerated_data.get('combined_zip_buffer'):
|
| 465 |
+
st.download_button(
|
| 466 |
+
label="π Download Complete Package (All Files + Reports)",
|
| 467 |
+
data=st.session_state.regenerated_data['combined_zip_buffer'].getvalue(),
|
| 468 |
+
file_name="Brand_Assets_Complete_Package.zip",
|
| 469 |
+
mime="application/zip",
|
| 470 |
+
type="primary"
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
st.markdown("---")
|
| 474 |
+
|
| 475 |
+
# Individual download options
|
| 476 |
+
st.subheader("π Individual Downloads")
|
| 477 |
+
st.markdown("Or download items separately:")
|
| 478 |
+
|
| 479 |
+
col1, col2, col3 = st.columns(3)
|
| 480 |
+
|
| 481 |
+
with col1:
|
| 482 |
+
if st.session_state.regenerated_data.get('pdf_buffer'):
|
| 483 |
+
st.download_button(
|
| 484 |
+
label="π PDF Report",
|
| 485 |
+
data=st.session_state.regenerated_data['pdf_buffer'].getvalue(),
|
| 486 |
+
file_name="Brand_Assets_Report.pdf",
|
| 487 |
+
mime="application/pdf"
|
| 488 |
+
)
|
| 489 |
+
else:
|
| 490 |
+
st.info("PDF report not available")
|
| 491 |
+
|
| 492 |
+
with col2:
|
| 493 |
+
if st.session_state.regenerated_data.get('excel_path'):
|
| 494 |
+
try:
|
| 495 |
+
with open(st.session_state.regenerated_data['excel_path'], 'rb') as excel_file:
|
| 496 |
+
st.download_button(
|
| 497 |
+
label="π Excel Report",
|
| 498 |
+
data=excel_file.read(),
|
| 499 |
+
file_name="Brand_Assets_Overview.xlsx",
|
| 500 |
+
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
| 501 |
+
)
|
| 502 |
+
except:
|
| 503 |
+
st.info("Excel report not available")
|
| 504 |
+
|
| 505 |
+
with col3:
|
| 506 |
+
if st.session_state.regenerated_data.get('zip_buffer'):
|
| 507 |
+
st.download_button(
|
| 508 |
+
label="π¦ Processed Files",
|
| 509 |
+
data=st.session_state.regenerated_data['zip_buffer'].getvalue(),
|
| 510 |
+
file_name="Brand_Assets_Processed.zip",
|
| 511 |
+
mime="application/zip"
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
st.markdown("---")
|
| 515 |
+
st.info("π‘ **Tip:** Downloads will remain available until you upload a new file or click 'Process New File'")
|
| 516 |
+
|
| 517 |
+
else:
|
| 518 |
+
# Reset session state when no file is uploaded
|
| 519 |
+
if st.session_state.regeneration_complete:
|
| 520 |
+
st.session_state.regeneration_complete = False
|
| 521 |
+
st.session_state.regenerated_data = {}
|
| 522 |
+
|
| 523 |
+
st.info("π Please upload a zip file to get started.")
|
| 524 |
+
|
| 525 |
+
with st.expander("π Instructions"):
|
| 526 |
+
st.markdown("""
|
| 527 |
+
**What is Tab 8?**
|
| 528 |
+
|
| 529 |
+
Tab 8 regenerates PDF and Excel reports from a Tab 5 output folder that may contain manually added images.
|
| 530 |
+
|
| 531 |
+
**Use Case:**
|
| 532 |
+
1. You ran Tab 5 and got an output folder with images, PDF, and Excel
|
| 533 |
+
2. You manually added new images to that folder (following the same naming convention)
|
| 534 |
+
3. You want to regenerate the reports to include the new images
|
| 535 |
+
|
| 536 |
+
**How to use:**
|
| 537 |
+
1. Take your Tab 5 output folder (with any manually added images)
|
| 538 |
+
2. ZIP the entire folder
|
| 539 |
+
3. Upload the ZIP here
|
| 540 |
+
4. Click "Regenerate Reports"
|
| 541 |
+
5. Download the new PDF and Excel files
|
| 542 |
+
|
| 543 |
+
**Naming Convention:**
|
| 544 |
+
All files must follow this pattern: `{markennummer}B{blocknummer}{marke}{count_str}{cleaned}{ext}`
|
| 545 |
+
|
| 546 |
+
Example: `01B01brand01filename.png`
|
| 547 |
+
- `01` = brand number
|
| 548 |
+
- `B01` = block/folder number
|
| 549 |
+
- `brand` = brand name
|
| 550 |
+
- `01` = sequential counter
|
| 551 |
+
- `filename` = cleaned name
|
| 552 |
+
- `.png` = file extension
|
| 553 |
+
|
| 554 |
+
**Note:** The tool will skip any existing Excel/PDF reports in the folder and only regenerate new ones.
|
| 555 |
+
""")
|