Spaces:
Sleeping
Sleeping
venkatesh commited on
Commit Β·
289f379
1
Parent(s): c9303e1
fix(tab6): preserve manual Excel folder changes, handle duplicate file formats, add flexible report detection and date stamping
Browse files- __pycache__/tab8.cpython-313.pyc +0 -0
- tab8.py +128 -115
__pycache__/tab8.cpython-313.pyc
CHANGED
|
Binary files a/__pycache__/tab8.cpython-313.pyc and b/__pycache__/tab8.cpython-313.pyc differ
|
|
|
tab8.py
CHANGED
|
@@ -5,6 +5,7 @@ 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,
|
|
@@ -26,7 +27,6 @@ def parse_filename(filename):
|
|
| 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:
|
|
@@ -58,21 +58,24 @@ def parse_filename(filename):
|
|
| 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 = []
|
|
@@ -91,7 +94,7 @@ def reconstruct_folder_structure(files_folder):
|
|
| 91 |
|
| 92 |
# Skip Excel and PDF files from previous runs
|
| 93 |
if file_path.suffix.lower() in ['.xlsx', '.pdf']:
|
| 94 |
-
if
|
| 95 |
skipped_files.append(f"{file_path.name} (report file)")
|
| 96 |
continue
|
| 97 |
|
|
@@ -117,40 +120,65 @@ def reconstruct_folder_structure(files_folder):
|
|
| 117 |
if marke not in marken_index:
|
| 118 |
marken_index[marke] = markennummer
|
| 119 |
|
| 120 |
-
# Create folder name
|
| 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
|
| 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 |
-
#
|
| 150 |
-
existing_excel =
|
| 151 |
-
|
| 152 |
-
if not existing_excel.exists():
|
| 153 |
-
return None, None, "Error:
|
| 154 |
|
| 155 |
# Read existing Excel to get the file_to_factorgroup mapping
|
| 156 |
try:
|
|
@@ -163,19 +191,14 @@ def regenerate_reports_from_folder(files_folder):
|
|
| 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('['):
|
| 172 |
filename = lang_val
|
| 173 |
file_to_factorgroup[filename] = factorgroup
|
| 174 |
|
| 175 |
-
if idx < 5:
|
| 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")
|
|
@@ -191,7 +214,7 @@ def regenerate_reports_from_folder(files_folder):
|
|
| 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]:
|
| 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"
|
|
@@ -204,7 +227,7 @@ def regenerate_reports_from_folder(files_folder):
|
|
| 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
|
| 208 |
continue
|
| 209 |
|
| 210 |
# Parse to get blocknummer for new files
|
|
@@ -249,27 +272,15 @@ def regenerate_reports_from_folder(files_folder):
|
|
| 249 |
return None, None, f"PDF generation failed: {pdf_error}"
|
| 250 |
|
| 251 |
# Backup the old Excel file before deleting
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 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,
|
|
@@ -277,26 +288,9 @@ def regenerate_reports_from_folder(files_folder):
|
|
| 277 |
)
|
| 278 |
|
| 279 |
# Debug: Check how many entries were added
|
| 280 |
-
import pandas as pd
|
| 281 |
try:
|
| 282 |
-
|
| 283 |
-
print(f"\nβ
Excel generated with {len(
|
| 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 |
|
|
@@ -309,9 +303,13 @@ def regenerate_reports_from_folder(files_folder):
|
|
| 309 |
|
| 310 |
|
| 311 |
def regenerate_reports_tool():
|
| 312 |
-
"""Tab
|
| 313 |
st.header("Re Run Matrix")
|
| 314 |
-
st.markdown("
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
|
| 316 |
# Initialize session state
|
| 317 |
if 'regeneration_complete' not in st.session_state:
|
|
@@ -320,18 +318,18 @@ def regenerate_reports_tool():
|
|
| 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 '
|
| 329 |
-
if st.session_state.
|
| 330 |
st.session_state.regeneration_complete = False
|
| 331 |
st.session_state.regenerated_data = {}
|
| 332 |
|
| 333 |
if uploaded_file:
|
| 334 |
-
st.session_state.
|
| 335 |
|
| 336 |
if not st.session_state.regeneration_complete:
|
| 337 |
if st.button("Regenerate Reports", type="primary"):
|
|
@@ -339,24 +337,21 @@ def regenerate_reports_tool():
|
|
| 339 |
# Extract ZIP
|
| 340 |
temp_dir = extract_zip_to_temp(uploaded_file)
|
| 341 |
|
| 342 |
-
# Find the actual files folder
|
| 343 |
root_folder = Path(temp_dir)
|
| 344 |
|
| 345 |
-
# Keep descending if there's only one subfolder
|
| 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
|
|
@@ -374,57 +369,58 @@ def regenerate_reports_tool():
|
|
| 374 |
try:
|
| 375 |
df_new = pd.read_excel(excel_path, sheet_name='Assets')
|
| 376 |
|
| 377 |
-
# Compare with
|
| 378 |
-
|
| 379 |
-
if
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
st.success(f"β
Excel generated with {
|
| 392 |
-
|
| 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 |
-
#
|
|
|
|
|
|
|
|
|
|
| 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
|
| 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
|
| 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
|
| 421 |
if pdf_buffer:
|
| 422 |
-
combined_zip.writestr("reports/
|
| 423 |
|
| 424 |
-
# Add Excel report
|
| 425 |
if excel_path and excel_path.exists():
|
| 426 |
with open(excel_path, 'rb') as excel_file:
|
| 427 |
-
combined_zip.writestr("reports/
|
| 428 |
|
| 429 |
combined_zip_buffer.seek(0)
|
| 430 |
|
|
@@ -434,7 +430,8 @@ def regenerate_reports_tool():
|
|
| 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 |
|
|
@@ -457,6 +454,8 @@ def regenerate_reports_tool():
|
|
| 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")
|
|
@@ -465,7 +464,7 @@ def regenerate_reports_tool():
|
|
| 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="
|
| 469 |
mime="application/zip",
|
| 470 |
type="primary"
|
| 471 |
)
|
|
@@ -483,7 +482,7 @@ def regenerate_reports_tool():
|
|
| 483 |
st.download_button(
|
| 484 |
label="π PDF Report",
|
| 485 |
data=st.session_state.regenerated_data['pdf_buffer'].getvalue(),
|
| 486 |
-
file_name="
|
| 487 |
mime="application/pdf"
|
| 488 |
)
|
| 489 |
else:
|
|
@@ -496,7 +495,7 @@ def regenerate_reports_tool():
|
|
| 496 |
st.download_button(
|
| 497 |
label="π Excel Report",
|
| 498 |
data=excel_file.read(),
|
| 499 |
-
file_name="
|
| 500 |
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
| 501 |
)
|
| 502 |
except:
|
|
@@ -507,7 +506,7 @@ def regenerate_reports_tool():
|
|
| 507 |
st.download_button(
|
| 508 |
label="π¦ Processed Files",
|
| 509 |
data=st.session_state.regenerated_data['zip_buffer'].getvalue(),
|
| 510 |
-
file_name="
|
| 511 |
mime="application/zip"
|
| 512 |
)
|
| 513 |
|
|
@@ -524,32 +523,46 @@ def regenerate_reports_tool():
|
|
| 524 |
|
| 525 |
with st.expander("π Instructions"):
|
| 526 |
st.markdown("""
|
| 527 |
-
**What is Tab
|
| 528 |
|
| 529 |
-
|
| 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
|
| 538 |
-
2.
|
| 539 |
-
3.
|
| 540 |
-
4.
|
| 541 |
-
5.
|
| 542 |
-
|
| 543 |
-
|
|
|
|
|
|
|
| 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 |
-
**
|
| 555 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import zipfile
|
| 6 |
from pathlib import Path
|
| 7 |
from collections import defaultdict
|
| 8 |
+
from datetime import datetime
|
| 9 |
import streamlit as st
|
| 10 |
from helper import (
|
| 11 |
extract_zip_to_temp,
|
|
|
|
| 27 |
ext = Path(filename).suffix.lower()
|
| 28 |
|
| 29 |
# Pattern: 2 digits + B + 2 digits + brand name (letters only) + 2 digits + rest
|
|
|
|
| 30 |
match = re.match(r'^(\d{2})B(\d{2})([a-zA-Z]+)(\d{2})(.*)$', stem)
|
| 31 |
|
| 32 |
if match:
|
|
|
|
| 58 |
return None
|
| 59 |
|
| 60 |
|
| 61 |
+
def get_base_filename_without_ext(filename):
|
| 62 |
+
"""Get base filename without extension for duplicate detection"""
|
| 63 |
+
return Path(filename).stem
|
| 64 |
+
|
| 65 |
+
|
| 66 |
def reconstruct_folder_structure(files_folder):
|
| 67 |
"""
|
| 68 |
Reconstruct the folder structure from parsed filenames.
|
| 69 |
Groups files by blocknummer (folder) and marke (brand).
|
| 70 |
+
Handles duplicate base filenames with different extensions.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Track unique base filenames for counting
|
| 78 |
+
unique_base_files = defaultdict(set) # folder -> set of base filenames
|
| 79 |
|
| 80 |
# Collect all valid files
|
| 81 |
parsed_files = []
|
|
|
|
| 94 |
|
| 95 |
# Skip Excel and PDF files from previous runs
|
| 96 |
if file_path.suffix.lower() in ['.xlsx', '.pdf']:
|
| 97 |
+
if any(keyword in file_path.name for keyword in ['Overview', 'Report', 'IcAt']):
|
| 98 |
skipped_files.append(f"{file_path.name} (report file)")
|
| 99 |
continue
|
| 100 |
|
|
|
|
| 120 |
if marke not in marken_index:
|
| 121 |
marken_index[marke] = markennummer
|
| 122 |
|
| 123 |
+
# Create folder name
|
|
|
|
| 124 |
folder_name = f"{blocknummer}Folder"
|
| 125 |
|
| 126 |
+
# Track unique base filename for this folder
|
| 127 |
+
base_filename = get_base_filename_without_ext(file_path.name)
|
| 128 |
+
unique_base_files[folder_name].add(base_filename)
|
| 129 |
+
|
| 130 |
# Add to structure
|
| 131 |
renamed_files_by_folder_and_marke[folder_name][marke].append(
|
| 132 |
(file_path, file_path.name)
|
| 133 |
)
|
| 134 |
|
| 135 |
+
# Map file to factorgroup
|
| 136 |
file_to_factorgroup[file_path.name] = folder_name
|
| 137 |
|
| 138 |
# Prepare debug info
|
| 139 |
debug_info = {
|
| 140 |
'total_files': total_files,
|
| 141 |
'parsed_files': len(parsed_files),
|
| 142 |
+
'skipped_files': skipped_files,
|
| 143 |
+
'unique_counts': {folder: len(bases) for folder, bases in unique_base_files.items()}
|
| 144 |
}
|
| 145 |
|
| 146 |
return marken_set, renamed_files_by_folder_and_marke, marken_index, file_to_factorgroup, debug_info
|
| 147 |
|
| 148 |
|
| 149 |
+
def find_existing_reports(files_folder):
|
| 150 |
+
"""Find existing PDF and Excel reports in the folder"""
|
| 151 |
+
pdf_file = None
|
| 152 |
+
excel_file = None
|
| 153 |
+
|
| 154 |
+
for file in Path(files_folder).iterdir():
|
| 155 |
+
if not file.is_file():
|
| 156 |
+
continue
|
| 157 |
+
|
| 158 |
+
# Look for Excel file
|
| 159 |
+
if file.suffix.lower() == '.xlsx' and 'IcAt' in file.name and 'Overview' in file.name:
|
| 160 |
+
excel_file = file
|
| 161 |
+
|
| 162 |
+
# Look for PDF file
|
| 163 |
+
if file.suffix.lower() == '.pdf' and ('Brand' in file.name or 'Report' in file.name or 'IcAt' in file.name):
|
| 164 |
+
pdf_file = file
|
| 165 |
+
|
| 166 |
+
return pdf_file, excel_file
|
| 167 |
+
|
| 168 |
+
|
| 169 |
def regenerate_reports_from_folder(files_folder):
|
| 170 |
"""
|
| 171 |
Regenerate PDF and Excel reports from a folder containing Tab 5 output files.
|
| 172 |
Uses the EXISTING Excel file to get the correct factorgroup mappings!
|
| 173 |
+
Preserves manual folder structure changes from the Excel file.
|
| 174 |
"""
|
| 175 |
import pandas as pd
|
| 176 |
|
| 177 |
+
# Find existing reports (flexible naming)
|
| 178 |
+
old_pdf_file, existing_excel = find_existing_reports(files_folder)
|
| 179 |
+
|
| 180 |
+
if not existing_excel or not existing_excel.exists():
|
| 181 |
+
return None, None, "Error: Excel overview file not found in the folder. Please ensure the Excel file from Tab 5 is included in the ZIP."
|
| 182 |
|
| 183 |
# Read existing Excel to get the file_to_factorgroup mapping
|
| 184 |
try:
|
|
|
|
| 191 |
lang_val = str(row['Language'])
|
| 192 |
factorgroup = str(row['factorgroup'])
|
| 193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
# Check if Language looks like a filename (has an extension)
|
| 195 |
+
if '.' in lang_val and not lang_val.startswith('['):
|
| 196 |
filename = lang_val
|
| 197 |
file_to_factorgroup[filename] = factorgroup
|
| 198 |
|
| 199 |
+
if idx < 5:
|
| 200 |
print(f" Row {idx}: '{filename}' -> {factorgroup}")
|
| 201 |
elif idx < 5:
|
|
|
|
| 202 |
print(f" Row {idx}: Skipping (text content): '{lang_val[:30]}...'")
|
| 203 |
|
| 204 |
print(f"β
Loaded {len(file_to_factorgroup)} file mappings from existing Excel")
|
|
|
|
| 214 |
error_msg += f"Successfully parsed: {debug_info['parsed_files']}\n"
|
| 215 |
if debug_info['skipped_files']:
|
| 216 |
error_msg += f"\nSkipped files:\n"
|
| 217 |
+
for skipped in debug_info['skipped_files'][:10]:
|
| 218 |
error_msg += f" - {skipped}\n"
|
| 219 |
if len(debug_info['skipped_files']) > 10:
|
| 220 |
error_msg += f" ... and {len(debug_info['skipped_files']) - 10} more\n"
|
|
|
|
| 227 |
if file_path.is_file() and file_path.name not in file_to_factorgroup:
|
| 228 |
# Skip Excel/PDF files
|
| 229 |
if file_path.suffix.lower() in ['.xlsx', '.pdf']:
|
| 230 |
+
if any(keyword in file_path.name for keyword in ['Overview', 'Report', 'IcAt']):
|
| 231 |
continue
|
| 232 |
|
| 233 |
# Parse to get blocknummer for new files
|
|
|
|
| 272 |
return None, None, f"PDF generation failed: {pdf_error}"
|
| 273 |
|
| 274 |
# Backup the old Excel file before deleting
|
| 275 |
+
backup_excel_path = Path(files_folder) / f"{existing_excel.stem}.backup"
|
| 276 |
+
if existing_excel.exists():
|
| 277 |
+
shutil.copy2(existing_excel, backup_excel_path)
|
| 278 |
+
existing_excel.unlink()
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
# Generate Excel using existing helper function
|
|
|
|
|
|
|
| 281 |
print(f"\nπ Generating Excel report...")
|
| 282 |
print(f" Passing {len(file_to_factorgroup)} file mappings to generate_excel_report")
|
| 283 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
excel_path = generate_excel_report(
|
| 285 |
Path(files_folder),
|
| 286 |
marken_index,
|
|
|
|
| 288 |
)
|
| 289 |
|
| 290 |
# Debug: Check how many entries were added
|
|
|
|
| 291 |
try:
|
| 292 |
+
df_new = pd.read_excel(excel_path, sheet_name='Assets')
|
| 293 |
+
print(f"\nβ
Excel generated with {len(df_new)} rows")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
except Exception as e:
|
| 295 |
print(f"Could not read Excel for debug: {e}")
|
| 296 |
|
|
|
|
| 303 |
|
| 304 |
|
| 305 |
def regenerate_reports_tool():
|
| 306 |
+
"""Tab 6: Regenerate PDF and Excel from Tab 5 output + manually added images"""
|
| 307 |
st.header("Re Run Matrix")
|
| 308 |
+
st.markdown("""
|
| 309 |
+
Upload a ZIP containing your Tab 5 output folder (with optional manually added images).
|
| 310 |
+
|
| 311 |
+
The tool will regenerate updated reports with the current date stamp.
|
| 312 |
+
""")
|
| 313 |
|
| 314 |
# Initialize session state
|
| 315 |
if 'regeneration_complete' not in st.session_state:
|
|
|
|
| 318 |
st.session_state.regenerated_data = {}
|
| 319 |
|
| 320 |
uploaded_file = st.file_uploader(
|
| 321 |
+
"Choose a ZIP file containing Tab 5 output (including both PDF and Excel reports)",
|
| 322 |
type=['zip'],
|
| 323 |
)
|
| 324 |
|
| 325 |
# Reset processing state when new file is uploaded
|
| 326 |
+
if uploaded_file and 'uploaded_file_name_tab6' in st.session_state:
|
| 327 |
+
if st.session_state.uploaded_file_name_tab6 != uploaded_file.name:
|
| 328 |
st.session_state.regeneration_complete = False
|
| 329 |
st.session_state.regenerated_data = {}
|
| 330 |
|
| 331 |
if uploaded_file:
|
| 332 |
+
st.session_state.uploaded_file_name_tab6 = uploaded_file.name
|
| 333 |
|
| 334 |
if not st.session_state.regeneration_complete:
|
| 335 |
if st.button("Regenerate Reports", type="primary"):
|
|
|
|
| 337 |
# Extract ZIP
|
| 338 |
temp_dir = extract_zip_to_temp(uploaded_file)
|
| 339 |
|
| 340 |
+
# Find the actual files folder
|
| 341 |
root_folder = Path(temp_dir)
|
| 342 |
|
| 343 |
+
# Keep descending if there's only one subfolder
|
| 344 |
while True:
|
| 345 |
items = [item for item in os.listdir(root_folder) if not item.startswith('.') and not item.startswith('_')]
|
| 346 |
|
|
|
|
| 347 |
if len(items) == 1 and os.path.isdir(os.path.join(root_folder, items[0])):
|
| 348 |
root_folder = root_folder / items[0]
|
| 349 |
else:
|
|
|
|
| 350 |
break
|
| 351 |
|
| 352 |
# Look for processed_files folder
|
| 353 |
processed_files_folder = root_folder / "processed_files"
|
| 354 |
if not processed_files_folder.exists():
|
|
|
|
| 355 |
processed_files_folder = root_folder
|
| 356 |
|
| 357 |
# Regenerate reports
|
|
|
|
| 369 |
try:
|
| 370 |
df_new = pd.read_excel(excel_path, sheet_name='Assets')
|
| 371 |
|
| 372 |
+
# Compare with backup
|
| 373 |
+
backup_files = list(processed_files_folder.glob("*.backup"))
|
| 374 |
+
if backup_files:
|
| 375 |
+
try:
|
| 376 |
+
df_old = pd.read_excel(backup_files[0], sheet_name='Assets')
|
| 377 |
+
old_count = len(df_old)
|
| 378 |
+
new_count = len(df_new)
|
| 379 |
+
added_count = new_count - old_count
|
| 380 |
+
|
| 381 |
+
if added_count > 0:
|
| 382 |
+
st.success(f"β
Excel generated with {new_count} entries ({added_count} NEW entries added!)")
|
| 383 |
+
else:
|
| 384 |
+
st.success(f"β
Excel generated with {new_count} entries (same as before)")
|
| 385 |
+
except:
|
| 386 |
+
st.success(f"β
Excel generated with {len(df_new)} entries")
|
| 387 |
+
else:
|
| 388 |
st.success(f"β
Excel generated with {len(df_new)} entries")
|
| 389 |
|
| 390 |
except Exception as e:
|
| 391 |
st.warning(f"Excel created but couldn't read for stats: {e}")
|
| 392 |
|
| 393 |
+
# Generate timestamp for filenames
|
| 394 |
+
timestamp = datetime.now().strftime("%Y%m%d")
|
| 395 |
+
|
| 396 |
+
# Create individual processed files ZIP
|
| 397 |
zip_buffer = io.BytesIO()
|
| 398 |
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
| 399 |
for file in processed_files_folder.iterdir():
|
| 400 |
if file.is_file():
|
|
|
|
| 401 |
if file.name.endswith('.backup'):
|
| 402 |
continue
|
| 403 |
zip_file.write(file, file.name)
|
| 404 |
zip_buffer.seek(0)
|
| 405 |
|
| 406 |
+
# Create combined ZIP with processed_files/ and reports/ folders
|
| 407 |
combined_zip_buffer = io.BytesIO()
|
| 408 |
with zipfile.ZipFile(combined_zip_buffer, 'w', zipfile.ZIP_DEFLATED) as combined_zip:
|
| 409 |
+
# Add all processed files
|
| 410 |
for file in processed_files_folder.iterdir():
|
| 411 |
if file.is_file():
|
|
|
|
| 412 |
if file.name.endswith('.backup'):
|
| 413 |
continue
|
| 414 |
combined_zip.write(file, f"processed_files/{file.name}")
|
| 415 |
|
| 416 |
+
# Add PDF report with timestamp
|
| 417 |
if pdf_buffer:
|
| 418 |
+
combined_zip.writestr(f"reports/Brand_Assets_Report_update_{timestamp}.pdf", pdf_buffer.getvalue())
|
| 419 |
|
| 420 |
+
# Add Excel report with timestamp
|
| 421 |
if excel_path and excel_path.exists():
|
| 422 |
with open(excel_path, 'rb') as excel_file:
|
| 423 |
+
combined_zip.writestr(f"reports/Brand_Assets_Overview_update_{timestamp}.xlsx", excel_file.read())
|
| 424 |
|
| 425 |
combined_zip_buffer.seek(0)
|
| 426 |
|
|
|
|
| 430 |
'excel_path': excel_path,
|
| 431 |
'zip_buffer': zip_buffer,
|
| 432 |
'combined_zip_buffer': combined_zip_buffer,
|
| 433 |
+
'temp_dir': temp_dir,
|
| 434 |
+
'timestamp': timestamp
|
| 435 |
}
|
| 436 |
st.session_state.regeneration_complete = True
|
| 437 |
|
|
|
|
| 454 |
|
| 455 |
st.markdown("---")
|
| 456 |
|
| 457 |
+
timestamp = st.session_state.regenerated_data.get('timestamp', datetime.now().strftime("%Y%m%d"))
|
| 458 |
+
|
| 459 |
# Combined download option (recommended)
|
| 460 |
st.subheader("π¦ Complete Package Download")
|
| 461 |
st.markdown("**Recommended:** Download everything in one convenient package")
|
|
|
|
| 464 |
st.download_button(
|
| 465 |
label="π Download Complete Package (All Files + Reports)",
|
| 466 |
data=st.session_state.regenerated_data['combined_zip_buffer'].getvalue(),
|
| 467 |
+
file_name=f"Brand_Assets_Complete_Package_{timestamp}.zip",
|
| 468 |
mime="application/zip",
|
| 469 |
type="primary"
|
| 470 |
)
|
|
|
|
| 482 |
st.download_button(
|
| 483 |
label="π PDF Report",
|
| 484 |
data=st.session_state.regenerated_data['pdf_buffer'].getvalue(),
|
| 485 |
+
file_name=f"Brand_Assets_Report_update_{timestamp}.pdf",
|
| 486 |
mime="application/pdf"
|
| 487 |
)
|
| 488 |
else:
|
|
|
|
| 495 |
st.download_button(
|
| 496 |
label="π Excel Report",
|
| 497 |
data=excel_file.read(),
|
| 498 |
+
file_name=f"Brand_Assets_Overview_update_{timestamp}.xlsx",
|
| 499 |
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
| 500 |
)
|
| 501 |
except:
|
|
|
|
| 506 |
st.download_button(
|
| 507 |
label="π¦ Processed Files",
|
| 508 |
data=st.session_state.regenerated_data['zip_buffer'].getvalue(),
|
| 509 |
+
file_name=f"Brand_Assets_Processed_{timestamp}.zip",
|
| 510 |
mime="application/zip"
|
| 511 |
)
|
| 512 |
|
|
|
|
| 523 |
|
| 524 |
with st.expander("π Instructions"):
|
| 525 |
st.markdown("""
|
| 526 |
+
**What is Tab 6 (Re Run Matrix)?**
|
| 527 |
|
| 528 |
+
This tool regenerates PDF and Excel reports from a Tab 5 output folder that may contain manually added images.
|
| 529 |
|
| 530 |
**Use Case:**
|
| 531 |
+
1. You ran Tab 5 and got an output folder with images, PDF, and Excel reports
|
| 532 |
2. You manually added new images to that folder (following the same naming convention)
|
| 533 |
3. You want to regenerate the reports to include the new images
|
| 534 |
|
| 535 |
**How to use:**
|
| 536 |
+
1. Take your Tab 5 output folder (the one with processed_files/ and reports/ folders)
|
| 537 |
+
2. **Important:** Make sure BOTH the PDF and Excel reports are included in the ZIP
|
| 538 |
+
3. Add any new images you want (following the naming convention)
|
| 539 |
+
4. ZIP the entire folder
|
| 540 |
+
5. Upload the ZIP here
|
| 541 |
+
6. Click "Regenerate Reports"
|
| 542 |
+
7. Download the updated reports (with today's date in the filename)
|
| 543 |
+
|
| 544 |
+
**Naming Convention for New Files:**
|
| 545 |
All files must follow this pattern: `{markennummer}B{blocknummer}{marke}{count_str}{cleaned}{ext}`
|
| 546 |
|
| 547 |
Example: `01B01brand01filename.png`
|
| 548 |
+
- `01` = brand number (markennummer)
|
| 549 |
- `B01` = block/folder number
|
| 550 |
- `brand` = brand name
|
| 551 |
- `01` = sequential counter
|
| 552 |
- `filename` = cleaned name
|
| 553 |
- `.png` = file extension
|
| 554 |
|
| 555 |
+
**Important Notes:**
|
| 556 |
+
- The tool preserves any manual folder structure changes you made in the Excel file
|
| 557 |
+
- Files with the same name but different extensions (e.g., .mp4 and .png) are counted only once
|
| 558 |
+
- Both formats will appear in the reports, but the count remains accurate
|
| 559 |
+
- Report files are automatically named with the current date (YYYYMMDD format)
|
| 560 |
+
- The tool will skip any existing report files when processing
|
| 561 |
+
|
| 562 |
+
**Multiple File Formats:**
|
| 563 |
+
If you have files like:
|
| 564 |
+
- `01B17nivea47appvideo.mp4`
|
| 565 |
+
- `01B17nivea47appvideo.png`
|
| 566 |
+
|
| 567 |
+
Both will be included in the reports, but counted as 1 asset (not 2) in the summary statistics.
|
| 568 |
+
""")
|