venkatesh commited on
Commit
b8cf0cb
Β·
1 Parent(s): cd2aecf

RERUN MATRIX update

Browse files
Files changed (4) hide show
  1. app.py +7 -4
  2. helper.py +79 -47
  3. tab6.py +729 -162
  4. tab8.py +157 -602
app.py CHANGED
@@ -1,12 +1,15 @@
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
- from tab8 import regenerate_reports_tool
 
10
 
11
  # Configure Streamlit page
12
  st.set_page_config(
@@ -28,7 +31,7 @@ def main():
28
  "Re-run Matrix",
29
  "Resize",
30
  "Place on Canvas"
31
-
32
  ])
33
 
34
  with tab1:
@@ -42,7 +45,7 @@ def main():
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:
 
1
  import streamlit as st
2
+
3
+ # Import tools for each tab
4
  from tab1 import excel_extractor_tool
5
  from tab2 import file_renamer_tool
6
  from tab3 import white_to_transparent_tool
7
  from tab4 import pdf_generator_tool
8
  from tab5 import brand_renamer_tool
9
+ from tab6 import updated_file_processor_tab
10
  from tab7 import center_on_canvas_tool
11
+ from tab8 import resize_with_transparent_canvas_tool
12
+
13
 
14
  # Configure Streamlit page
15
  st.set_page_config(
 
31
  "Re-run Matrix",
32
  "Resize",
33
  "Place on Canvas"
34
+
35
  ])
36
 
37
  with tab1:
 
45
  with tab5:
46
  brand_renamer_tool()
47
  with tab6:
48
+ updated_file_processor_tab()
49
  with tab7:
50
  center_on_canvas_tool()
51
  with tab8:
helper.py CHANGED
@@ -180,55 +180,66 @@ def is_valid_file(file_path):
180
  return True
181
 
182
  def generate_excel_report(output_folder: Path, marken_index: dict, file_to_factorgroup: dict):
183
- """Generate Excel report - ACCEPT ALL FILE TYPES"""
 
 
 
 
184
  final_excel_path = output_folder / "IcAt_Overview_Final.xlsx"
185
 
186
  nummer_zu_marke = {v: k for k, v in marken_index.items()}
187
  data = []
188
 
189
- for file in sorted(output_folder.iterdir()):
190
- if file.is_file() and is_valid_file(file):
191
- name = file.stem
192
- file_ext = file.suffix.lower() if file.suffix else ''
193
-
194
- match = re.match(r"(\d{2})B(\d{2})([a-z0-9]+)", name, re.IGNORECASE)
195
- if match:
196
- markennummer, blocknummer, marke = match.groups()
197
- factor = nummer_zu_marke.get(markennummer, marke)
198
-
199
- factorgroup = file_to_factorgroup.get(file.name, f"{blocknummer}Unknown")
200
- factorgroup = factorgroup.replace('_', '') # Remove all underscores
201
-
202
- only_id = name
203
- is_b20_id = False
204
- is_non_image_file = False # INITIALIZE HERE
205
-
206
- if "B20" in only_id.upper():
207
- is_b20_id = True
208
- language_value = only_id + file_ext
209
- # Highlight ALL non-image formats (not just .txt)
210
- elif file_ext in NON_IMAGE_EXTENSIONS:
211
- is_non_image_file = True
212
- if file_ext == '.txt':
213
- try:
214
- with open(file, 'r', encoding='utf-8', errors='ignore') as txt_file:
215
- txt_content = txt_file.read().strip()
216
- language_value = txt_content if txt_content else "[Empty file]"
217
- except Exception as e:
218
- language_value = f"[Error reading file: {str(e)}]"
219
- else:
220
- # For non-image, non-txt files, show the full filename with extension
221
- language_value = name + file_ext
 
 
 
 
222
  else:
 
223
  language_value = name + file_ext
224
-
225
- data.append({
226
- "factor": factor,
227
- "factorgroup": factorgroup,
228
- "ID": only_id,
229
- "Language": language_value,
230
- "highlight_yellow": is_non_image_file or is_b20_id # Highlight non-images
231
- })
 
 
232
 
233
  df_assets = pd.DataFrame(data, columns=["factor", "factorgroup", "ID", "Language"])
234
 
@@ -354,7 +365,7 @@ def add_brand_pages_with_png_extensions(elements, marken_spalten, renamed_files_
354
  def generate_filename_based_pdf_report_with_extensions(input_folder, erste_marke=None, marken_index=None):
355
  """Generate PDF report with .png extensions in image labels"""
356
  marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
357
-
358
  if not marken_set:
359
  return None, "No brands found in filenames."
360
 
@@ -381,15 +392,36 @@ def generate_filename_based_pdf_report_with_extensions(input_folder, erste_marke
381
  nummer_zu_marke = {v: k for k, v in marken_index.items()}
382
  marken_spalten = sorted(nummer_zu_marke.items())
383
 
384
- for folder in sorted(renamed_files_by_folder_and_marke):
 
 
 
 
 
 
 
 
385
  elements.append(Paragraph(f"<b>Folder: {folder}</b>", styles['Heading2']))
386
 
387
  abschnitt = renamed_files_by_folder_and_marke[folder]
388
- total = 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
  lines = []
390
  for nummer, marke in marken_spalten:
391
- count = len(abschnitt.get(marke, []))
392
- total += count
393
  lines.append(f"{nummer} ({marke}): {count}")
394
  lines.append(f"Total: {total}")
395
  elements.append(Paragraph("<br/>".join(lines), styles['Normal']))
 
180
  return True
181
 
182
  def generate_excel_report(output_folder: Path, marken_index: dict, file_to_factorgroup: dict):
183
+ """Generate Excel report - ACCEPT ALL FILE TYPES
184
+
185
+ ⚠️ CRITICAL: Only processes files that are in file_to_factorgroup parameter.
186
+ This ensures we only generate Excel entries for files we want to include.
187
+ """
188
  final_excel_path = output_folder / "IcAt_Overview_Final.xlsx"
189
 
190
  nummer_zu_marke = {v: k for k, v in marken_index.items()}
191
  data = []
192
 
193
+ # ⚠️ CRITICAL FIX: Iterate over file_to_factorgroup keys instead of scanning folder
194
+ # This ensures we ONLY process the files we explicitly want to include
195
+ for filename in sorted(file_to_factorgroup.keys()):
196
+ file = output_folder / filename
197
+
198
+ # Skip if file doesn't exist or isn't valid
199
+ if not file.exists() or not file.is_file() or not is_valid_file(file):
200
+ continue
201
+
202
+ name = file.stem
203
+ file_ext = file.suffix.lower() if file.suffix else ''
204
+
205
+ match = re.match(r"(\d{2})B(\d{2})([a-z0-9]+)", name, re.IGNORECASE)
206
+ if match:
207
+ markennummer, blocknummer, marke = match.groups()
208
+ factor = nummer_zu_marke.get(markennummer, marke)
209
+
210
+ factorgroup = file_to_factorgroup.get(file.name, f"{blocknummer}Unknown")
211
+ factorgroup = factorgroup.replace('_', '') # Remove all underscores
212
+
213
+ only_id = name
214
+ is_b20_id = False
215
+ is_non_image_file = False # INITIALIZE HERE
216
+
217
+ if "B20" in only_id.upper():
218
+ is_b20_id = True
219
+ language_value = only_id + file_ext
220
+ # Highlight ALL non-image formats (not just .txt)
221
+ elif file_ext in NON_IMAGE_EXTENSIONS:
222
+ is_non_image_file = True
223
+ if file_ext == '.txt':
224
+ try:
225
+ with open(file, 'r', encoding='utf-8', errors='ignore') as txt_file:
226
+ txt_content = txt_file.read().strip()
227
+ language_value = txt_content if txt_content else "[Empty file]"
228
+ except Exception as e:
229
+ language_value = f"[Error reading file: {str(e)}]"
230
  else:
231
+ # For non-image, non-txt files, show the full filename with extension
232
  language_value = name + file_ext
233
+ else:
234
+ language_value = name + file_ext
235
+
236
+ data.append({
237
+ "factor": factor,
238
+ "factorgroup": factorgroup,
239
+ "ID": only_id,
240
+ "Language": language_value,
241
+ "highlight_yellow": is_non_image_file or is_b20_id # Highlight non-images
242
+ })
243
 
244
  df_assets = pd.DataFrame(data, columns=["factor", "factorgroup", "ID", "Language"])
245
 
 
365
  def generate_filename_based_pdf_report_with_extensions(input_folder, erste_marke=None, marken_index=None):
366
  """Generate PDF report with .png extensions in image labels"""
367
  marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
368
+
369
  if not marken_set:
370
  return None, "No brands found in filenames."
371
 
 
392
  nummer_zu_marke = {v: k for k, v in marken_index.items()}
393
  marken_spalten = sorted(nummer_zu_marke.items())
394
 
395
+ # Sort folders naturally by blocknummer
396
+ def get_folder_sort_key(folder_name):
397
+ # Extract leading digits for natural sorting
398
+ match = re.match(r'^(\d+)', folder_name)
399
+ return int(match.group(1)) if match else 999
400
+
401
+ sorted_folders = sorted(renamed_files_by_folder_and_marke.keys(), key=get_folder_sort_key)
402
+
403
+ for folder in sorted_folders:
404
  elements.append(Paragraph(f"<b>Folder: {folder}</b>", styles['Heading2']))
405
 
406
  abschnitt = renamed_files_by_folder_and_marke[folder]
407
+
408
+ # Count UNIQUE base files per brand (considering deduplication)
409
+ brand_counts = {}
410
+ for nummer, marke in marken_spalten:
411
+ files = abschnitt.get(marke, [])
412
+ # Group by base filename (without extension) to count unique files
413
+ unique_bases = {}
414
+ for pfad, original_name in files:
415
+ base_name = Path(original_name).stem
416
+ if base_name not in unique_bases:
417
+ unique_bases[base_name] = []
418
+ unique_bases[base_name].append(Path(original_name).suffix.lower())
419
+ brand_counts[marke] = len(unique_bases)
420
+
421
+ total = sum(brand_counts.values())
422
  lines = []
423
  for nummer, marke in marken_spalten:
424
+ count = brand_counts.get(marke, 0)
 
425
  lines.append(f"{nummer} ({marke}): {count}")
426
  lines.append(f"Total: {total}")
427
  elements.append(Paragraph("<br/>".join(lines), styles['Normal']))
tab6.py CHANGED
@@ -1,180 +1,747 @@
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
180
  """)
 
 
 
 
 
 
1
  import os
2
+ import re
3
+ import shutil
4
  import zipfile
5
+ from pathlib import Path
6
+ from collections import defaultdict
7
+ from typing import Dict, Set, List, Tuple
8
  import streamlit as st
9
+ import pandas as pd
10
+ import tempfile
11
 
12
+ # Import helper functions from helper.py to reuse exact same logic
13
+ from helper import (
14
+ ALLOWED_IMAGE_EXTENSIONS,
15
+ ALLOWED_VIDEO_EXTENSIONS,
16
+ ALLOWED_AUDIO_EXTENSIONS,
17
+ ALLOWED_TEXT_EXTENSIONS,
18
+ NON_IMAGE_EXTENSIONS,
19
+ get_cleaned_filename_without_brand,
20
+ extract_brand
21
+ )
22
 
 
 
 
 
 
23
 
24
+ def extract_uploaded_zip(uploaded_file):
25
+ """Extract uploaded zip file to temporary directory"""
26
+ temp_dir = tempfile.mkdtemp()
27
+ with zipfile.ZipFile(uploaded_file, 'r') as zip_ref:
28
+ zip_ref.extractall(temp_dir)
29
+ return temp_dir
30
+
31
+
32
+ def read_zip_structure(temp_dir):
33
+ """
34
+ Analyze the extracted zip structure and identify:
35
+ - processed_files folder
36
+ - reports folder (with Excel and PDF)
37
+ """
38
+ temp_path = Path(temp_dir)
39
+
40
+ structure = {
41
+ 'processed_files': [],
42
+ 'excel_report': None,
43
+ 'pdf_report': None,
44
+ 'excel_data': None,
45
+ 'excel_path': None,
46
+ 'processed_files_dir': None
47
+ }
48
+
49
+ # Look for processed_files folder
50
+ processed_files_dir = temp_path / "processed_files"
51
+ if processed_files_dir.exists() and processed_files_dir.is_dir():
52
+ all_files = [f for f in processed_files_dir.iterdir() if f.is_file()]
53
+ structure['processed_files'] = all_files
54
+ structure['processed_files_dir'] = processed_files_dir
55
+
56
+ # Look for reports folder
57
+ reports_dir = temp_path / "reports"
58
+ if reports_dir.exists() and reports_dir.is_dir():
59
+ # Find Excel report - search by prefix "Brand_Assets_Overview"
60
+ excel_report = None
61
+ for file in reports_dir.iterdir():
62
+ if file.is_file() and file.name.startswith("Brand_Assets_Overview") and file.suffix.lower() in ['.xlsx', '.xls']:
63
+ excel_report = file
64
+ break
65
+
66
+ if excel_report:
67
+ structure['excel_report'] = excel_report
68
+ structure['excel_path'] = excel_report
69
+ # Read Excel data
70
+ try:
71
+ df_assets = pd.read_excel(excel_report, sheet_name='Assets')
72
+ df_reordered = pd.read_excel(excel_report, sheet_name='Reordered')
73
+ structure['excel_data'] = {'Assets': df_assets, 'Reordered': df_reordered}
74
+ except Exception as e:
75
+ st.warning(f"Could not read Excel file: {e}")
76
+
77
+ # Find PDF report - search by prefix "Brand_Assets_Report"
78
+ pdf_report = None
79
+ for file in reports_dir.iterdir():
80
+ if file.is_file() and file.name.startswith("Brand_Assets_Report") and file.suffix.lower() == '.pdf':
81
+ pdf_report = file
82
+ break
83
+
84
+ if pdf_report:
85
+ structure['pdf_report'] = pdf_report
86
+
87
+ return structure
88
+
89
+
90
+ def extract_metadata_from_excel(excel_data: Dict) -> Dict:
91
+ """
92
+ Extract critical metadata from the existing Excel file:
93
+ - marken_index (brand number to brand name mapping)
94
+ - file_to_factorgroup (filename to folder name mapping)
95
+ - existing files
96
+ """
97
+ df_assets = excel_data['Assets']
98
+
99
+ metadata = {
100
+ 'marken_index': {},
101
+ 'file_to_factorgroup': {},
102
+ 'existing_files': set(),
103
+ 'folder_names': set()
104
+ }
105
+
106
+ # Extract existing files and their factorgroups
107
+ for _, row in df_assets.iterrows():
108
+ file_id = str(row['ID'])
109
+ factorgroup = str(row['factorgroup'])
110
+ factor = str(row['factor'])
111
+
112
+ metadata['existing_files'].add(file_id)
113
+ metadata['file_to_factorgroup'][file_id] = factorgroup
114
+ metadata['folder_names'].add(factorgroup)
115
+
116
+ # Extract brand number from ID (first 2 digits)
117
+ match = re.match(r'(\d{2})B\d{2}([a-zA-Z]+)', file_id)
118
+ if match:
119
+ brand_num, brand_name = match.groups()
120
+ metadata['marken_index'][brand_name.lower()] = brand_num
121
+
122
+ return metadata
123
+
124
+
125
+ def find_duplicate_pngs(processed_files: List[Path]) -> Set[str]:
126
+ """
127
+ Find PNG files that have the same base name as video/audio files.
128
+ These PNGs should be ignored as they're duplicates.
129
+ """
130
+ video_audio_exts = ALLOWED_VIDEO_EXTENSIONS | ALLOWED_AUDIO_EXTENSIONS
131
+ png_to_ignore = set()
132
+
133
+ # Group files by base name (without extension)
134
+ files_by_basename = defaultdict(list)
135
+ for file_path in processed_files:
136
+ basename = file_path.stem
137
+ ext = file_path.suffix.lower()
138
+ files_by_basename[basename].append((file_path.name, ext))
139
+
140
+ # Check for PNG files with same name as video/audio files
141
+ for basename, files in files_by_basename.items():
142
+ extensions = [ext for _, ext in files]
143
+ has_video_audio = any(ext in video_audio_exts for ext in extensions)
144
+ has_png = '.png' in extensions
145
+
146
+ if has_video_audio and has_png:
147
+ # Found a PNG with same name as video/audio - mark PNG for ignoring
148
+ png_files = [name for name, ext in files if ext == '.png']
149
+ png_to_ignore.update(png_files)
150
+
151
+ return png_to_ignore
152
+
153
+
154
+ def analyze_processed_files(processed_files: List[Path], metadata: Dict, png_to_ignore: Set[str]):
155
+ """
156
+ Analyze all processed files and organize them using the EXACT same structure as helper.py
157
+ Returns: renamed_files_by_folder_and_marke, file_to_factorgroup
158
+ """
159
+ from helper import extract_brand, get_cleaned_filename_without_brand
160
+
161
+ renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
162
+ file_to_factorgroup = {}
163
+ marken_index = metadata['marken_index']
164
+
165
+ # Reverse the marken_index to get brand_number -> brand_name
166
+ nummer_zu_marke = {v: k for k, v in marken_index.items()}
167
+
168
+ for file_path in processed_files:
169
+ if file_path.name in png_to_ignore:
170
+ continue
171
+
172
+ filename = file_path.name
173
+ name = file_path.stem
174
+ file_ext = file_path.suffix.lower()
175
+
176
+ # Parse filename to extract metadata: 01B11brandname01description.ext
177
+ match = re.match(r"(\d{2})B(\d{2})([a-z0-9]+)", name, re.IGNORECASE)
178
+ if not match:
179
+ continue
180
+
181
+ markennummer, blocknummer, marke_from_name = match.groups()
182
+
183
+ # CRITICAL FIX: Use the brand name from marken_index based on brand NUMBER
184
+ # This ensures consistency with helper.py
185
+ marke = nummer_zu_marke.get(markennummer, marke_from_name.lower())
186
+
187
+ # Try to get factorgroup from existing metadata first
188
+ if name in metadata['file_to_factorgroup']:
189
+ factorgroup = metadata['file_to_factorgroup'][name]
190
+ else:
191
+ # New file - try to infer folder from other files with same block number
192
+ # Look for existing files with same block number
193
+ inferred_folder = None
194
+ for existing_id, existing_folder in metadata['file_to_factorgroup'].items():
195
+ if f"B{blocknummer}" in existing_id:
196
+ inferred_folder = existing_folder
197
+ break
198
+
199
+ if inferred_folder:
200
+ factorgroup = inferred_folder
201
+ else:
202
+ # Default fallback
203
+ factorgroup = f"{blocknummer}{marke}"
204
+
205
+ # Store mapping
206
+ file_to_factorgroup[filename] = factorgroup
207
+
208
+ # Add to renamed_files structure (folder_name -> brand -> files)
209
+ renamed_files_by_folder_and_marke[factorgroup][marke].append((file_path, filename))
210
+
211
+ return renamed_files_by_folder_and_marke, file_to_factorgroup, marken_index
212
+
213
+
214
+ def generate_updated_pdf_using_helper(renamed_files_by_folder_and_marke: Dict, marken_index: Dict,
215
+ output_path: Path) -> Tuple[bool, str]:
216
+ """
217
+ Generate PDF using THE EXACT SAME logic as helper.py's generate_filename_based_pdf_report_with_extensions
218
+ """
219
+ try:
220
+ from reportlab.lib.pagesizes import A4
221
+ from reportlab.lib.styles import getSampleStyleSheet
222
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
223
+ from reportlab.lib import colors
224
+ from reportlab.platypus import Image as RLImage
225
+ from pathlib import Path
226
+
227
+ doc = SimpleDocTemplate(str(output_path), pagesize=A4, leftMargin=20, rightMargin=20,
228
+ topMargin=40, bottomMargin=30)
229
+ elements = []
230
+ styles = getSampleStyleSheet()
231
+
232
+ # Create brand columns - EXACT same as helper.py
233
+ nummer_zu_marke = {v: k for k, v in marken_index.items()}
234
+ marken_spalten = sorted(nummer_zu_marke.items())
235
+
236
+ # Sort folders naturally by blocknummer - EXACT same as helper.py
237
+ def get_folder_sort_key(folder_name):
238
+ match = re.match(r'^(\d+)', folder_name)
239
+ return int(match.group(1)) if match else 999
240
+
241
+ sorted_folders = sorted(renamed_files_by_folder_and_marke.keys(), key=get_folder_sort_key)
242
+
243
+ # Process each folder - EXACT same structure as helper.py
244
+ for folder in sorted_folders:
245
+ elements.append(Paragraph(f"<b>Folder: {folder}</b>", styles['Heading2']))
246
+
247
+ abschnitt = renamed_files_by_folder_and_marke[folder]
248
+
249
+ # Count UNIQUE base files per brand (considering deduplication) - EXACT same as helper.py
250
+ brand_counts = {}
251
+ for nummer, marke in marken_spalten:
252
+ files = abschnitt.get(marke, [])
253
+ # Group by base filename (without extension) to count unique files
254
+ unique_bases = {}
255
+ for pfad, original_name in files:
256
+ base_name = Path(original_name).stem
257
+ if base_name not in unique_bases:
258
+ unique_bases[base_name] = []
259
+ unique_bases[base_name].append(Path(original_name).suffix.lower())
260
+ brand_counts[marke] = len(unique_bases)
261
+
262
+ total = sum(brand_counts.values())
263
+ lines = []
264
+ for nummer, marke in marken_spalten:
265
+ count = brand_counts.get(marke, 0)
266
+ lines.append(f"{nummer} ({marke}): {count}")
267
+ lines.append(f"Total: {total}")
268
+ elements.append(Paragraph("<br/>".join(lines), styles['Normal']))
269
+ elements.append(Spacer(1, 10))
270
+
271
+ # Create table - EXACT same as helper.py
272
+ headers = [f"{nummer} ({marke})" for nummer, marke in marken_spalten]
273
+ data = [headers]
274
+ col_data = []
275
+ max_rows = 0
276
+
277
+ for _, marke in marken_spalten:
278
+ eintraege = abschnitt.get(marke, [])
279
+ zellen = []
280
+ for pfad, original_name in eintraege:
281
+ # Use helper function to create cell
282
+ from helper import get_asset_cell
283
+ cell = get_asset_cell(pfad, original_name, len(headers))
284
+ zellen.append(cell)
285
+ col_data.append(zellen)
286
+ max_rows = max(max_rows, len(zellen))
287
+
288
+ for i in range(max_rows):
289
+ row = []
290
+ for col in col_data:
291
+ row.append(col[i] if i < len(col) else "")
292
+ data.append(row)
293
+
294
+ col_width = (A4[0] - 40) / len(headers)
295
+ t = Table(data, colWidths=[col_width] * len(headers))
296
+ t.setStyle(TableStyle([
297
+ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
298
+ ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
299
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
300
+ ]))
301
+ elements.append(t)
302
+ elements.append(PageBreak())
303
+
304
+ # Total overview - EXACT same as helper.py
305
+ elements.append(Paragraph("<b>Total Overview</b>", styles['Heading2']))
306
+ global_counts = defaultdict(int)
307
+ for folder_data in renamed_files_by_folder_and_marke.values():
308
+ for marke, daten in folder_data.items():
309
+ global_counts[marke] += len(daten)
310
+
311
+ gesamt = 0
312
+ summary = []
313
+ for nummer, marke in marken_spalten:
314
+ count = global_counts[marke]
315
+ summary.append(f"{marke}: {count} assets")
316
+ gesamt += count
317
+ summary.append(f"Total number of all assets: {gesamt}")
318
+ elements.append(Paragraph("<br/>".join(summary), styles['Normal']))
319
+
320
+ # Add brand pages - EXACT same as helper.py
321
+ from helper import add_brand_pages_with_png_extensions
322
+ add_brand_pages_with_png_extensions(elements, marken_spalten, renamed_files_by_folder_and_marke, marken_index)
323
+
324
+ # Build PDF
325
+ doc.build(elements)
326
+
327
+ return True, "PDF generated successfully"
328
+
329
+ except Exception as e:
330
+ import traceback
331
+ return False, f"Error generating PDF: {str(e)}\n{traceback.format_exc()}"
332
+
333
+
334
+ def generate_updated_excel_using_helper(processed_files_dir: Path, marken_index: Dict,
335
+ file_to_factorgroup: Dict, png_to_ignore: Set[str],
336
+ output_path: Path) -> Tuple[bool, str]:
337
+ """
338
+ Generate Excel using THE EXACT SAME logic as helper.py's generate_excel_report
339
+ """
340
+ try:
341
+ from openpyxl.styles import PatternFill
342
+
343
+ nummer_zu_marke = {v: k for k, v in marken_index.items()}
344
+ data = []
345
+
346
+ # Process all files - EXACT same logic as helper.py
347
+ for file in sorted(processed_files_dir.iterdir()):
348
+ if not file.is_file():
349
+ continue
350
+
351
+ # Skip ignored PNGs
352
+ if file.name in png_to_ignore:
353
+ continue
354
+
355
+ name = file.stem
356
+ file_ext = file.suffix.lower() if file.suffix else ''
357
+
358
+ match = re.match(r"(\d{2})B(\d{2})([a-z0-9]+)", name, re.IGNORECASE)
359
+ if match:
360
+ markennummer, blocknummer, marke = match.groups()
361
+ factor = nummer_zu_marke.get(markennummer, marke)
362
+
363
+ factorgroup = file_to_factorgroup.get(file.name, f"{blocknummer}Unknown")
364
+ factorgroup = factorgroup.replace('_', '') # Remove all underscores - EXACT same as helper.py
365
+
366
+ only_id = name
367
+ is_b20_id = False
368
+ is_non_image_file = False
369
+
370
+ if "B20" in only_id.upper():
371
+ is_b20_id = True
372
+ language_value = only_id + file_ext
373
+ # Highlight ALL non-image formats - EXACT same as helper.py
374
+ elif file_ext in NON_IMAGE_EXTENSIONS:
375
+ is_non_image_file = True
376
+ if file_ext == '.txt':
377
+ try:
378
+ with open(file, 'r', encoding='utf-8', errors='ignore') as txt_file:
379
+ txt_content = txt_file.read().strip()
380
+ language_value = txt_content if txt_content else "[Empty file]"
381
+ except Exception as e:
382
+ language_value = f"[Error reading file: {str(e)}]"
383
+ else:
384
+ language_value = name + file_ext
385
+ else:
386
+ language_value = name + file_ext
387
+
388
+ data.append({
389
+ "factor": factor,
390
+ "factorgroup": factorgroup,
391
+ "ID": only_id,
392
+ "Language": language_value,
393
+ "highlight_yellow": is_non_image_file or is_b20_id
394
+ })
395
+
396
+ # Create Assets sheet - EXACT same as helper.py
397
+ df_assets = pd.DataFrame(data, columns=["factor", "factorgroup", "ID", "Language"])
398
+
399
+ # Create Reordered sheet - EXACT same logic as helper.py
400
+ reordered_data = []
401
+ for _, row in df_assets.iterrows():
402
+ raw_factor = str(row["factorgroup"])
403
+ group_prefix = raw_factor[:2]
404
+ try:
405
+ group = str(int(group_prefix))
406
+ except ValueError:
407
+ group = group_prefix
408
+
409
+ clean_factor = str(row["factorgroup"]).replace('_', '')
410
+ clean_factorgroup = str(row["factor"]).replace('_', '')
411
+
412
+ reordered_data.append({
413
+ "Group": group,
414
+ "factor": clean_factor,
415
+ "factorgroup": clean_factorgroup,
416
+ "ID": row["ID"],
417
+ "Language": row["Language"]
418
+ })
419
+
420
+ df_reordered = pd.DataFrame(reordered_data, columns=["Group", "factor", "factorgroup", "ID", "Language"])
421
+ df_reordered['factor'] = df_reordered['factor'].astype(str)
422
+
423
+ df_reordered['Group_num'] = pd.to_numeric(df_reordered['Group'], errors='coerce').fillna(999).astype(int)
424
+ df_reordered['factor_num'] = df_reordered['factor'].str.extract(r'^(\d+)')[0]
425
+ df_reordered['factor_num'] = pd.to_numeric(df_reordered['factor_num'], errors='coerce').fillna(999).astype(int)
426
+
427
+ df_reordered = df_reordered.sort_values(
428
+ by=['Group_num', 'factor_num', 'factor'],
429
+ ascending=[True, True, True]
430
+ ).reset_index(drop=True)
431
+
432
+ df_reordered = df_reordered.drop(['factor_num', 'Group_num'], axis=1)
433
+
434
+ # Write to Excel with highlighting - EXACT same as helper.py
435
+ with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
436
+ df_assets.to_excel(writer, index=False, sheet_name="Assets")
437
+ df_reordered.to_excel(writer, index=False, sheet_name="Reordered")
438
+
439
+ workbook = writer.book
440
+ yellow_fill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
441
+
442
+ # Highlight Assets sheet
443
+ assets_sheet = workbook['Assets']
444
+ language_col_idx = 4
445
+ for row_idx in range(2, len(df_assets) + 2):
446
+ cell = assets_sheet.cell(row=row_idx, column=language_col_idx)
447
+ if row_idx - 2 < len(data):
448
+ if data[row_idx - 2].get("highlight_yellow", False):
449
+ cell.fill = yellow_fill
450
+
451
+ # Highlight Reordered sheet
452
+ reordered_sheet = workbook['Reordered']
453
+ language_col_idx = 5
454
+ id_col_idx = 4
455
+
456
+ id_to_highlight = {item["ID"]: item.get("highlight_yellow", False) for item in data}
457
+
458
+ for row_idx in range(2, len(df_reordered) + 2):
459
+ cell = reordered_sheet.cell(row=row_idx, column=language_col_idx)
460
+ id_cell = reordered_sheet.cell(row=row_idx, column=id_col_idx)
461
+ id_value = id_cell.value
462
+ if id_value and id_to_highlight.get(id_value, False):
463
+ cell.fill = yellow_fill
464
+
465
+ return True, "Excel generated successfully"
466
+
467
+ except Exception as e:
468
+ import traceback
469
+ return False, f"Error generating Excel: {str(e)}\n{traceback.format_exc()}"
470
+
471
+
472
+ def updated_file_processor_tab():
473
+ """
474
+ Tab 6: Process updated zip files from Tab 5
475
+ Uses EXACT same logic as helper.py to maintain structure
476
+ """
477
+ st.header("Rerun Matrix")
478
+
479
+
480
+
481
+ # Initialize session state
482
+ if 'tab6_processing_complete' not in st.session_state:
483
+ st.session_state.tab6_processing_complete = False
484
+ if 'tab6_data' not in st.session_state:
485
+ st.session_state.tab6_data = {}
486
 
 
 
 
 
 
487
  uploaded_file = st.file_uploader(
488
+ "Upload Modified ZIP File (from Tab 5)",
489
  type=['zip'],
490
+ key='tab6_uploader'
 
491
  )
492
+
493
+ # Reset processing state when new file is uploaded
494
+ if uploaded_file and 'tab6_uploaded_file_name' in st.session_state:
495
+ if st.session_state.tab6_uploaded_file_name != uploaded_file.name:
496
+ st.session_state.tab6_processing_complete = False
497
+ st.session_state.tab6_data = {}
498
+
499
  if uploaded_file:
500
+ st.session_state.tab6_uploaded_file_name = uploaded_file.name
501
+
502
+ if not st.session_state.tab6_processing_complete:
503
+ with st.spinner("πŸ” Extracting and analyzing uploaded zip file..."):
504
+ try:
505
+ temp_dir = extract_uploaded_zip(uploaded_file)
506
+ structure = read_zip_structure(temp_dir)
507
+
508
+ st.session_state.tab6_data = {
509
+ 'temp_dir': temp_dir,
510
+ 'structure': structure
511
+ }
512
+ st.session_state.tab6_processing_complete = True
513
+ st.rerun()
514
+
515
+ except Exception as e:
516
+ st.error(f"❌ Error processing zip file: {e}")
517
+ import traceback
518
+ st.code(traceback.format_exc())
519
+ return
520
+
521
+ # Display extracted contents
522
+ if st.session_state.tab6_processing_complete:
523
+ structure = st.session_state.tab6_data['structure']
524
+
525
+ if not structure['excel_data']:
526
+ st.error("❌ Cannot proceed: Excel file is required to extract folder structure and metadata.")
527
+ st.info("πŸ’‘ Make sure your zip contains an Excel file starting with `Brand_Assets_Overview` in the `reports/` folder.")
528
+ else:
529
+ if st.button("🎯 Analyze Files & Generate Reports", type="primary"):
530
+ with st.spinner("Processing files and generating reports..."):
531
+ try:
532
+ # Step 1: Extract metadata from existing Excel
533
+ metadata = extract_metadata_from_excel(structure['excel_data'])
534
+
535
+ st.info(f"πŸ“Š Found {len(metadata['existing_files'])} existing files in {len(metadata['folder_names'])} folders")
536
+
537
+ # Step 2: Find PNG duplicates
538
+ png_to_ignore = find_duplicate_pngs(structure['processed_files'])
539
+
540
+ if png_to_ignore:
541
+ st.info(f"ℹ️ Ignoring {len(png_to_ignore)} PNG files that duplicate video/audio files")
542
+
543
+ # Step 3: Analyze all processed files using helper.py logic
544
+ renamed_files_by_folder, file_to_factorgroup, marken_index = analyze_processed_files(
545
+ structure['processed_files'],
546
+ metadata,
547
+ png_to_ignore
548
+ )
549
+
550
+ # Step 4: Generate updated PDF using EXACT helper.py logic
551
+ temp_dir_path = Path(st.session_state.tab6_data['temp_dir'])
552
+ pdf_output_path = temp_dir_path / "Brand_Assets_Report_Updated.pdf"
553
+
554
+ pdf_success, pdf_msg = generate_updated_pdf_using_helper(
555
+ renamed_files_by_folder,
556
+ marken_index,
557
+ pdf_output_path
558
+ )
559
+
560
+ if pdf_success:
561
+ st.success(f"βœ… PDF: {pdf_msg}")
562
  else:
563
+ st.error(f"❌ PDF: {pdf_msg}")
564
+
565
+ # Step 5: Generate updated Excel using EXACT helper.py logic
566
+ excel_output_path = temp_dir_path / "IcAt_Overview_Final_Updated.xlsx"
567
+
568
+ excel_success, excel_msg = generate_updated_excel_using_helper(
569
+ structure['processed_files_dir'],
570
+ marken_index,
571
+ file_to_factorgroup,
572
+ png_to_ignore,
573
+ excel_output_path
574
+ )
575
+
576
+ if excel_success:
577
+ st.success(f"βœ… Excel: {excel_msg}")
578
+ else:
579
+ st.error(f"❌ Excel: {excel_msg}")
580
+
581
+ # Store results
582
+ st.session_state.tab6_data['pdf_updated'] = pdf_output_path if pdf_success else None
583
+ st.session_state.tab6_data['excel_updated'] = excel_output_path if excel_success else None
584
+ st.session_state.tab6_data['png_ignored'] = png_to_ignore
585
+ st.session_state.tab6_data['reports_generated'] = True
586
+ st.session_state.tab6_data['metadata'] = metadata
587
+
588
+ st.rerun()
589
+
590
+ except Exception as e:
591
+ st.error(f"❌ Error during processing: {str(e)}")
592
+ import traceback
593
+ st.code(traceback.format_exc())
594
+
595
+ # Show download buttons if reports were generated
596
+ if st.session_state.tab6_data.get('reports_generated'):
597
+ st.success("Processing complete!")
598
+
599
+ # Show processing info
600
+ if st.session_state.tab6_data.get('metadata'):
601
+ metadata = st.session_state.tab6_data['metadata']
602
+ with st.expander("ℹ️ Processing Details"):
603
+ st.write(f"**Folder names detected:** {len(metadata['folder_names'])}")
604
+ for folder in sorted(metadata['folder_names']):
605
+ st.text(f" β€’ {folder}")
606
+
607
+ st.write(f"\n**Brand index:**")
608
+ for brand, num in sorted(metadata['marken_index'].items()):
609
+ st.text(f" β€’ {num}: {brand}")
610
+
611
+ # Show ignored files info
612
+ if st.session_state.tab6_data.get('png_ignored'):
613
+ with st.expander("⚠️ Ignored PNG Files (duplicates of video/audio)"):
614
+ for png_file in sorted(st.session_state.tab6_data['png_ignored']):
615
+ st.text(f" β€’ {png_file}")
616
+
617
+ # Option to start over
618
+ if st.button("πŸ”„ Process New File", help="Clear results and upload a new file"):
619
+ if 'temp_dir' in st.session_state.tab6_data:
620
+ try:
621
+ shutil.rmtree(st.session_state.tab6_data['temp_dir'])
622
+ except:
623
+ pass
624
+ st.session_state.tab6_processing_complete = False
625
+ st.session_state.tab6_data = {}
626
+ st.rerun()
627
+
628
+ st.markdown("---")
629
+
630
+ # Combined download option (recommended)
631
+ st.subheader("πŸ“¦ Complete Package Download")
632
+ st.markdown("**Recommended:** Download everything in one convenient package")
633
+
634
+ # Create combined zip with updated files
635
+ if st.session_state.tab6_data.get('pdf_updated') and st.session_state.tab6_data.get('excel_updated'):
636
+ import io
637
+ combined_zip_buffer = io.BytesIO()
638
+ with zipfile.ZipFile(combined_zip_buffer, 'w', zipfile.ZIP_DEFLATED) as combined_zip:
639
+ # Add processed files
640
+ for file in structure['processed_files']:
641
+ if file.is_file():
642
+ combined_zip.write(file, f"processed_files/{file.name}")
643
+
644
+ # Add updated PDF report
645
+ pdf_path = st.session_state.tab6_data['pdf_updated']
646
+ if pdf_path.exists():
647
+ with open(pdf_path, 'rb') as f:
648
+ combined_zip.writestr("reports/Brand_Assets_Report.pdf", f.read())
649
+
650
+ # Add updated Excel report
651
+ excel_path = st.session_state.tab6_data['excel_updated']
652
+ if excel_path.exists():
653
+ with open(excel_path, 'rb') as f:
654
+ combined_zip.writestr("reports/Brand_Assets_Overview.xlsx", f.read())
655
+
656
+ combined_zip_buffer.seek(0)
657
+
658
  st.download_button(
659
+ label="🎁 Download Complete Package (All Files + Reports)",
660
+ data=combined_zip_buffer.getvalue(),
661
+ file_name="Brand_Assets_Complete_Package_Updated.zip",
662
  mime="application/zip",
663
+ type="primary"
664
  )
665
+
666
+ st.markdown("---")
667
+
668
+ # Individual download options
669
+ st.subheader("πŸ“ Individual Downloads")
670
+ st.markdown("Or download items separately:")
671
+
672
+ col1, col2, col3 = st.columns(3)
673
+
674
+ with col1:
675
+ if st.session_state.tab6_data.get('pdf_updated'):
676
+ pdf_path = st.session_state.tab6_data['pdf_updated']
677
+ if pdf_path.exists():
678
+ with open(pdf_path, 'rb') as f:
679
+ st.download_button(
680
+ label="πŸ“„ PDF Report",
681
+ data=f.read(),
682
+ file_name="Brand_Assets_Report.pdf",
683
+ mime="application/pdf"
684
+ )
685
+ else:
686
+ st.info("PDF report not available")
687
+
688
+ with col2:
689
+ if st.session_state.tab6_data.get('excel_updated'):
690
+ excel_path = st.session_state.tab6_data['excel_updated']
691
+ if excel_path.exists():
692
+ with open(excel_path, 'rb') as f:
693
+ st.download_button(
694
+ label="πŸ“Š Excel Report",
695
+ data=f.read(),
696
+ file_name="Brand_Assets_Overview.xlsx",
697
+ mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
698
+ )
699
+ else:
700
+ st.info("Excel report not available")
701
+
702
+ with col3:
703
+ if structure['processed_files_dir']:
704
+ # Create zip of processed files
705
+ import io
706
+ zip_buffer = io.BytesIO()
707
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
708
+ for file in structure['processed_files']:
709
+ if file.is_file():
710
+ zip_file.write(file, file.name)
711
+ zip_buffer.seek(0)
712
+
713
+ st.download_button(
714
+ label="πŸ“¦ Processed Files",
715
+ data=zip_buffer.getvalue(),
716
+ file_name="Brand_Assets_Processed.zip",
717
+ mime="application/zip"
718
+ )
719
+ else:
720
+ st.info("Processed files not available")
721
+
722
+ st.markdown("---")
723
+ st.info("πŸ’‘ **Tip:** Downloads will remain available until you upload a new file or click 'Process New File'")
724
+
725
  else:
726
+ st.info("πŸ‘† Please upload a zip file to begin.")
727
+
728
+ with st.expander("πŸ“– How to Use This Tool"):
 
729
  st.markdown("""
730
+ ### Workflow:
731
+
732
+ 1. **Get zip from Tab 5**: Download "Complete Package" from Tab 5
733
+
734
+ 2. **Optional: Update files manually**:
735
+ - Extract the zip locally
736
+ - Add/remove/modify files in `processed_files/` folder
737
+ - Keep the filename structure: `01B11brandname01description.ext`
738
+ - Re-zip maintaining folder structure
739
+
740
+ 3. **Upload here**: Upload the zip file
741
+
742
+ 4. **Generate reports**: Click "Analyze Files & Generate Reports"
 
 
 
 
 
743
  """)
744
+
745
+
746
+ if __name__ == "__main__":
747
+ updated_file_processor_tab()
tab8.py CHANGED
@@ -1,625 +1,180 @@
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
- from datetime import datetime
9
  import streamlit as st
10
- from helper import (
11
- extract_zip_to_temp,
12
- generate_excel_report,
13
- generate_filename_based_pdf_report_with_extensions,
14
- ALL_ALLOWED_EXTENSIONS,
15
- is_valid_file,
16
- ALLOWED_IMAGE_EXTENSIONS
17
- )
18
 
 
19
 
20
- def parse_filename(filename):
21
- """
22
- Parse filename following Tab 5 naming convention:
23
- {markennummer}B{blocknummer}{marke}{count_str}{cleaned}{original_ext}
 
24
 
25
- Returns: (markennummer, blocknummer, marke, count_str, cleaned, ext) or None if invalid
26
- """
27
- stem = Path(filename).stem
28
- ext = Path(filename).suffix.lower()
29
 
30
- # Pattern: 2 digits + B + 2 digits + brand name (letters only) + 2 digits + rest
31
- match = re.match(r'^(\d{2})B(\d{2})([a-zA-Z]+)(\d{2})(.*)$', stem)
32
-
33
- if match:
34
- markennummer, blocknummer, marke, count_str, cleaned = match.groups()
35
- return {
36
- 'markennummer': markennummer,
37
- 'blocknummer': blocknummer,
38
- 'marke': marke.lower(),
39
- 'count_str': count_str,
40
- 'cleaned': cleaned,
41
- 'ext': ext,
42
- 'full_filename': filename
43
- }
44
-
45
- # Fallback: Try more flexible pattern if brand contains numbers
46
- match = re.match(r'^(\d{2})B(\d{2})([a-z0-9]+?)(\d{2})(.*)$', stem, re.IGNORECASE)
47
- if match:
48
- markennummer, blocknummer, marke, count_str, cleaned = match.groups()
49
- return {
50
- 'markennummer': markennummer,
51
- 'blocknummer': blocknummer,
52
- 'marke': marke.lower(),
53
- 'count_str': count_str,
54
- 'cleaned': cleaned,
55
- 'ext': ext,
56
- 'full_filename': filename
57
- }
58
-
59
- return None
60
-
61
-
62
- def get_base_filename_without_ext(filename):
63
- """Get base filename without extension for duplicate detection"""
64
- return Path(filename).stem
65
-
66
-
67
- def get_original_folder_name(blocknummer, processed_files_folder):
68
- """Try to find the original folder name from Excel or folder structure"""
69
- # Look for the Excel file to extract original folder names
70
- excel_files = list(Path(processed_files_folder).glob("*IcAt*Overview*.xlsx"))
71
-
72
- if excel_files:
73
- try:
74
- import pandas as pd
75
- df = pd.read_excel(excel_files[0], sheet_name='Reordered')
76
- # Find rows matching this blocknummer
77
- matching_rows = df[df['Group'].astype(str) == blocknummer.lstrip('0')]
78
- if not matching_rows.empty:
79
- # Get the factorgroup value which contains the original folder name
80
- factorgroup = str(matching_rows.iloc[0]['factor'])
81
- # Extract folder name (remove blocknummer prefix if present)
82
- folder_name = re.sub(r'^\d+', '', factorgroup)
83
- return folder_name if folder_name else f"{blocknummer}Folder"
84
- except Exception as e:
85
- print(f"Could not extract folder name from Excel: {e}")
86
-
87
- return f"{blocknummer}Folder"
88
-
89
-
90
- def reconstruct_folder_structure(files_folder):
91
- """
92
- Reconstruct the folder structure from parsed filenames.
93
- Groups files by blocknummer (folder) and marke (brand).
94
- Handles duplicate base filenames - keeps non-image format over image format.
95
- """
96
- marken_set = set()
97
- marken_index = {}
98
- renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
99
- file_to_factorgroup = {}
100
- original_folder_names = {} # Map blocknummer to original folder name
101
-
102
- # Track unique base filenames for counting and duplicate detection
103
- unique_base_files = defaultdict(lambda: defaultdict(dict)) # folder -> base_filename -> {ext: file_path}
104
-
105
- # Collect all valid files
106
- parsed_files = []
107
- skipped_files = []
108
- total_files = 0
109
-
110
- for file_path in sorted(Path(files_folder).iterdir()):
111
- if not file_path.is_file():
112
- continue
113
-
114
- total_files += 1
115
-
116
- if not is_valid_file(file_path):
117
- skipped_files.append(f"{file_path.name} (invalid/system file)")
118
- continue
119
-
120
- # Skip Excel and PDF files from previous runs
121
- if file_path.suffix.lower() in ['.xlsx', '.pdf']:
122
- if any(keyword in file_path.name for keyword in ['Overview', 'Report', 'IcAt']):
123
- skipped_files.append(f"{file_path.name} (report file)")
124
- continue
125
-
126
- # Parse filename
127
- parsed = parse_filename(file_path.name)
128
- if parsed:
129
- parsed['file_path'] = file_path
130
- parsed_files.append(parsed)
131
- else:
132
- skipped_files.append(f"{file_path.name} (doesn't match naming convention)")
133
-
134
- # Try to get original folder names
135
- for parsed in parsed_files:
136
- blocknummer = parsed['blocknummer']
137
- if blocknummer not in original_folder_names:
138
- original_folder_names[blocknummer] = get_original_folder_name(blocknummer, files_folder)
139
-
140
- # Build structure with duplicate handling
141
- for parsed in parsed_files:
142
- marke = parsed['marke']
143
- markennummer = parsed['markennummer']
144
- blocknummer = parsed['blocknummer']
145
- file_path = parsed['file_path']
146
- ext = parsed['ext']
147
-
148
- # Add to marken_set
149
- marken_set.add(marke)
150
-
151
- # Add to marken_index (use first occurrence)
152
- if marke not in marken_index:
153
- marken_index[marke] = markennummer
154
-
155
- # Use original folder name if found, otherwise use blocknummer
156
- folder_name = original_folder_names.get(blocknummer, f"{blocknummer}Folder")
157
-
158
- # Track files by base filename for duplicate detection
159
- base_filename = get_base_filename_without_ext(file_path.name)
160
-
161
- # Store file with its extension
162
- unique_base_files[folder_name][base_filename][ext] = file_path
163
-
164
- # Now process the deduplicated files
165
- for folder_name in unique_base_files:
166
- for base_filename, extensions_dict in unique_base_files[folder_name].items():
167
- # If multiple extensions exist for same base filename
168
- if len(extensions_dict) > 1:
169
- # Priority: non-image formats over image formats
170
- non_image_files = {ext: path for ext, path in extensions_dict.items()
171
- if ext not in ALLOWED_IMAGE_EXTENSIONS}
172
-
173
- if non_image_files:
174
- # Use non-image format(s)
175
- for ext, file_path in non_image_files.items():
176
- parsed = parse_filename(file_path.name)
177
- marke = parsed['marke']
178
- renamed_files_by_folder_and_marke[folder_name][marke].append(
179
- (file_path, file_path.name)
180
- )
181
- file_to_factorgroup[file_path.name] = folder_name
182
- else:
183
- # All are images, just pick one (first one)
184
- ext, file_path = list(extensions_dict.items())[0]
185
- parsed = parse_filename(file_path.name)
186
- marke = parsed['marke']
187
- renamed_files_by_folder_and_marke[folder_name][marke].append(
188
- (file_path, file_path.name)
189
- )
190
- file_to_factorgroup[file_path.name] = folder_name
191
- else:
192
- # Only one extension, add it
193
- ext, file_path = list(extensions_dict.items())[0]
194
- parsed = parse_filename(file_path.name)
195
- marke = parsed['marke']
196
- renamed_files_by_folder_and_marke[folder_name][marke].append(
197
- (file_path, file_path.name)
198
- )
199
- file_to_factorgroup[file_path.name] = folder_name
200
-
201
- # Calculate unique counts after deduplication
202
- unique_counts = {folder: len(unique_base_files[folder]) for folder in unique_base_files}
203
-
204
- # Prepare debug info
205
- debug_info = {
206
- 'total_files': total_files,
207
- 'parsed_files': len(parsed_files),
208
- 'skipped_files': skipped_files,
209
- 'unique_counts': unique_counts
210
- }
211
-
212
- return marken_set, renamed_files_by_folder_and_marke, marken_index, file_to_factorgroup, debug_info
213
-
214
-
215
- def find_existing_reports(files_folder):
216
- """Find existing PDF and Excel reports in the folder"""
217
- pdf_file = None
218
- excel_file = None
219
 
220
- for file in Path(files_folder).iterdir():
221
- if not file.is_file():
222
- continue
223
-
224
- # Look for Excel file
225
- if file.suffix.lower() == '.xlsx' and 'IcAt' in file.name and 'Overview' in file.name:
226
- excel_file = file
227
-
228
- # Look for PDF file
229
- if file.suffix.lower() == '.pdf' and ('Brand' in file.name or 'Report' in file.name or 'IcAt' in file.name):
230
- pdf_file = file
231
-
232
- return pdf_file, excel_file
233
-
234
-
235
- def regenerate_reports_from_folder(files_folder):
236
- """
237
- Regenerate PDF and Excel reports from a folder containing Tab 5 output files.
238
- Uses the EXISTING Excel file to get the correct factorgroup mappings!
239
- Preserves manual folder structure changes from the Excel file.
240
- """
241
- import pandas as pd
242
-
243
- # Find existing reports (flexible naming)
244
- old_pdf_file, existing_excel = find_existing_reports(files_folder)
245
-
246
- if not existing_excel or not existing_excel.exists():
247
- 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."
248
-
249
- # Read existing Excel to get the file_to_factorgroup mapping
250
- try:
251
- df = pd.read_excel(existing_excel, sheet_name='Assets')
252
- print(f"βœ… Excel has {len(df)} rows")
253
-
254
- # Build file_to_factorgroup from the Excel
255
- file_to_factorgroup = {}
256
- for idx, row in df.iterrows():
257
- lang_val = str(row['Language'])
258
- factorgroup = str(row['factorgroup'])
259
-
260
- # Check if Language looks like a filename (has an extension)
261
- if '.' in lang_val and not lang_val.startswith('['):
262
- filename = lang_val
263
- file_to_factorgroup[filename] = factorgroup
264
-
265
- if idx < 5:
266
- print(f" Row {idx}: '{filename}' -> {factorgroup}")
267
- elif idx < 5:
268
- print(f" Row {idx}: Skipping (text content): '{lang_val[:30]}...'")
269
-
270
- print(f"βœ… Loaded {len(file_to_factorgroup)} file mappings from existing Excel")
271
- except Exception as e:
272
- return None, None, f"Error reading existing Excel file: {str(e)}"
273
-
274
- # Reconstruct structure from filenames (with deduplication)
275
- marken_set, renamed_files_by_folder_and_marke, marken_index, _, debug_info = reconstruct_folder_structure(files_folder)
276
-
277
- if not marken_set:
278
- error_msg = f"No valid files found matching the naming convention.\n\n"
279
- error_msg += f"Total files found: {debug_info['total_files']}\n"
280
- error_msg += f"Successfully parsed: {debug_info['parsed_files']}\n"
281
- if debug_info['skipped_files']:
282
- error_msg += f"\nSkipped files:\n"
283
- for skipped in debug_info['skipped_files'][:10]:
284
- error_msg += f" - {skipped}\n"
285
- if len(debug_info['skipped_files']) > 10:
286
- error_msg += f" ... and {len(debug_info['skipped_files']) - 10} more\n"
287
- return None, None, error_msg
288
-
289
- # Add any NEW files to file_to_factorgroup
290
- new_files_added = 0
291
- print(f"\nπŸ” Scanning folder for NEW files not in existing Excel...")
292
- for file_path in Path(files_folder).iterdir():
293
- if file_path.is_file() and file_path.name not in file_to_factorgroup:
294
- # Skip Excel/PDF files
295
- if file_path.suffix.lower() in ['.xlsx', '.pdf']:
296
- if any(keyword in file_path.name for keyword in ['Overview', 'Report', 'IcAt']):
297
- continue
298
-
299
- # Parse to get blocknummer for new files
300
- parsed = parse_filename(file_path.name)
301
- if parsed:
302
- blocknummer = parsed['blocknummer']
303
- folder_name = get_original_folder_name(blocknummer, files_folder)
304
- file_to_factorgroup[file_path.name] = folder_name
305
- new_files_added += 1
306
- print(f" ✨ NEW: {file_path.name} -> {folder_name}")
307
-
308
- if new_files_added == 0:
309
- print(f" ℹ️ No new files found - all files already in Excel")
310
-
311
- print(f"\nπŸ“Š Summary:")
312
- print(f" - Files from existing Excel: {len(file_to_factorgroup) - new_files_added}")
313
- print(f" - NEW files added: {new_files_added}")
314
- print(f" - Total files to process: {len(file_to_factorgroup)}")
315
-
316
- # Create a temporary input folder structure that matches Tab 5 expectations
317
- temp_input = Path(files_folder) / "_temp_input_structure"
318
- temp_input.mkdir(exist_ok=True)
319
-
320
- try:
321
- # Create subfolder structure for PDF generation
322
- for folder_name in renamed_files_by_folder_and_marke:
323
- folder_path = temp_input / folder_name
324
- folder_path.mkdir(exist_ok=True)
325
-
326
- # Copy files to appropriate subfolders
327
- for marke, files in renamed_files_by_folder_and_marke[folder_name].items():
328
- for file_path, _ in files:
329
- shutil.copy2(file_path, folder_path / file_path.name)
330
-
331
- # Generate PDF using existing helper function
332
- pdf_buffer, pdf_error = generate_filename_based_pdf_report_with_extensions(
333
- temp_input,
334
- erste_marke=None,
335
- marken_index=marken_index
336
- )
337
-
338
- if pdf_error:
339
- return None, None, f"PDF generation failed: {pdf_error}"
340
-
341
- # Backup the old Excel file before deleting
342
- backup_excel_path = Path(files_folder) / f"{existing_excel.stem}.backup"
343
- if existing_excel.exists():
344
- shutil.copy2(existing_excel, backup_excel_path)
345
- existing_excel.unlink()
346
-
347
- # Generate Excel using existing helper function
348
- print(f"\nπŸ“ Generating Excel report...")
349
- print(f" Passing {len(file_to_factorgroup)} file mappings to generate_excel_report")
350
-
351
- excel_path = generate_excel_report(
352
- Path(files_folder),
353
- marken_index,
354
- file_to_factorgroup
355
- )
356
-
357
- # Debug: Check how many entries were added
358
- try:
359
- df_new = pd.read_excel(excel_path, sheet_name='Assets')
360
- print(f"\nβœ… Excel generated with {len(df_new)} rows")
361
- except Exception as e:
362
- print(f"Could not read Excel for debug: {e}")
363
-
364
- return pdf_buffer, excel_path, None
365
-
366
- finally:
367
- # Clean up temp folder
368
- if temp_input.exists():
369
- shutil.rmtree(temp_input)
370
-
371
-
372
- def regenerate_reports_tool():
373
- """Tab 6: Regenerate PDF and Excel from Tab 5 output + manually added images"""
374
- st.header("Re Run Matrix")
375
- st.markdown("""
376
- Upload a ZIP containing your Tab 5 output folder (with optional manually added images).
377
-
378
- The tool will regenerate updated reports with the current date stamp.
379
- """)
380
-
381
- # Initialize session state
382
- if 'regeneration_complete' not in st.session_state:
383
- st.session_state.regeneration_complete = False
384
- if 'regenerated_data' not in st.session_state:
385
- st.session_state.regenerated_data = {}
386
-
387
  uploaded_file = st.file_uploader(
388
- "Choose a ZIP file containing Tab 5 output (including both PDF and Excel reports)",
389
  type=['zip'],
 
 
390
  )
391
-
392
- # Reset processing state when new file is uploaded
393
- if uploaded_file and 'uploaded_file_name_tab6' in st.session_state:
394
- if st.session_state.uploaded_file_name_tab6 != uploaded_file.name:
395
- st.session_state.regeneration_complete = False
396
- st.session_state.regenerated_data = {}
397
-
398
  if uploaded_file:
399
- st.session_state.uploaded_file_name_tab6 = uploaded_file.name
400
-
401
- if not st.session_state.regeneration_complete:
402
- if st.button("Regenerate Reports", type="primary"):
403
- with st.spinner("Extracting files and analyzing structure..."):
404
- # Extract ZIP
 
 
405
  temp_dir = extract_zip_to_temp(uploaded_file)
406
-
407
- # Find the actual files folder
408
- root_folder = Path(temp_dir)
409
-
410
- # Keep descending if there's only one subfolder
411
- while True:
412
- items = [item for item in os.listdir(root_folder) if not item.startswith('.') and not item.startswith('_')]
413
-
414
- if len(items) == 1 and os.path.isdir(os.path.join(root_folder, items[0])):
415
- root_folder = root_folder / items[0]
416
- else:
417
- break
418
-
419
- # Look for processed_files folder
420
- processed_files_folder = root_folder / "processed_files"
421
- if not processed_files_folder.exists():
422
- processed_files_folder = root_folder
423
-
424
- # Regenerate reports
425
- with st.spinner("Regenerating PDF and Excel reports..."):
426
- pdf_buffer, excel_path, error = regenerate_reports_from_folder(processed_files_folder)
427
-
428
- if error:
429
- st.error(error)
430
- shutil.rmtree(temp_dir)
431
- return
432
-
433
- # Show Excel statistics
434
- if excel_path and excel_path.exists():
435
- import pandas as pd
436
- try:
437
- df_new = pd.read_excel(excel_path, sheet_name='Assets')
438
-
439
- # Compare with backup
440
- backup_files = list(processed_files_folder.glob("*.backup"))
441
- if backup_files:
442
- try:
443
- df_old = pd.read_excel(backup_files[0], sheet_name='Assets')
444
- old_count = len(df_old)
445
- new_count = len(df_new)
446
- added_count = new_count - old_count
447
-
448
- if added_count > 0:
449
- st.success(f"βœ… Excel generated with {new_count} entries ({added_count} NEW entries added!)")
450
- else:
451
- st.success(f"βœ… Excel generated with {new_count} entries (same as before)")
452
- except:
453
- st.success(f"βœ… Excel generated with {len(df_new)} entries")
454
  else:
455
- st.success(f"βœ… Excel generated with {len(df_new)} entries")
456
-
457
- except Exception as e:
458
- st.warning(f"Excel created but couldn't read for stats: {e}")
459
-
460
- # Generate timestamp for filenames
461
- timestamp = datetime.now().strftime("%Y%m%d")
462
-
463
- # Create individual processed files ZIP
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464
  zip_buffer = io.BytesIO()
465
  with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
466
- for file in processed_files_folder.iterdir():
467
- if file.is_file():
468
- if file.name.endswith('.backup'):
469
- continue
470
- zip_file.write(file, file.name)
 
471
  zip_buffer.seek(0)
472
-
473
- # Create combined ZIP with processed_files/ and reports/ folders
474
- combined_zip_buffer = io.BytesIO()
475
- with zipfile.ZipFile(combined_zip_buffer, 'w', zipfile.ZIP_DEFLATED) as combined_zip:
476
- # Add all processed files
477
- for file in processed_files_folder.iterdir():
478
- if file.is_file():
479
- if file.name.endswith('.backup'):
480
- continue
481
- combined_zip.write(file, f"processed_files/{file.name}")
482
-
483
- # Add PDF report with timestamp
484
- if pdf_buffer:
485
- combined_zip.writestr(f"reports/Brand_Assets_Report_update_{timestamp}.pdf", pdf_buffer.getvalue())
486
-
487
- # Add Excel report with timestamp
488
- if excel_path and excel_path.exists():
489
- with open(excel_path, 'rb') as excel_file:
490
- combined_zip.writestr(f"reports/Brand_Assets_Overview_update_{timestamp}.xlsx", excel_file.read())
491
-
492
- combined_zip_buffer.seek(0)
493
-
494
- # Store in session state
495
- st.session_state.regenerated_data = {
496
- 'pdf_buffer': pdf_buffer,
497
- 'excel_path': excel_path,
498
- 'zip_buffer': zip_buffer,
499
- 'combined_zip_buffer': combined_zip_buffer,
500
- 'temp_dir': temp_dir,
501
- 'timestamp': timestamp
502
- }
503
- st.session_state.regeneration_complete = True
504
-
505
- st.rerun()
506
-
507
- # Show download options if processing is complete
508
- if st.session_state.regeneration_complete:
509
- st.success("βœ… Reports regenerated successfully!")
510
-
511
- # Option to start over
512
- if st.button("πŸ”„ Process New File", help="Clear results and upload a new file"):
513
- st.session_state.regeneration_complete = False
514
- st.session_state.regenerated_data = {}
515
- if 'temp_dir' in st.session_state.regenerated_data:
516
- try:
517
- shutil.rmtree(st.session_state.regenerated_data['temp_dir'])
518
- except:
519
- pass
520
- st.rerun()
521
-
522
- st.markdown("---")
523
-
524
- timestamp = st.session_state.regenerated_data.get('timestamp', datetime.now().strftime("%Y%m%d"))
525
-
526
- # Combined download option (recommended)
527
- st.subheader("πŸ“¦ Complete Package Download")
528
- st.markdown("**Recommended:** Download everything in one convenient package")
529
-
530
- if st.session_state.regenerated_data.get('combined_zip_buffer'):
531
- st.download_button(
532
- label="🎁 Download Complete Package (All Files + Reports)",
533
- data=st.session_state.regenerated_data['combined_zip_buffer'].getvalue(),
534
- file_name=f"Brand_Assets_Complete_Package_{timestamp}.zip",
535
- mime="application/zip",
536
- type="primary"
537
- )
538
-
539
- st.markdown("---")
540
-
541
- # Individual download options
542
- st.subheader("πŸ“ Individual Downloads")
543
- st.markdown("Or download items separately:")
544
-
545
- col1, col2, col3 = st.columns(3)
546
-
547
- with col1:
548
- if st.session_state.regenerated_data.get('pdf_buffer'):
549
- st.download_button(
550
- label="πŸ“„ PDF Report",
551
- data=st.session_state.regenerated_data['pdf_buffer'].getvalue(),
552
- file_name=f"Brand_Assets_Report_update_{timestamp}.pdf",
553
- mime="application/pdf"
554
- )
555
- else:
556
- st.info("PDF report not available")
557
-
558
- with col2:
559
- if st.session_state.regenerated_data.get('excel_path'):
560
- try:
561
- with open(st.session_state.regenerated_data['excel_path'], 'rb') as excel_file:
562
- st.download_button(
563
- label="πŸ“Š Excel Report",
564
- data=excel_file.read(),
565
- file_name=f"Brand_Assets_Overview_update_{timestamp}.xlsx",
566
- mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
567
- )
568
- except:
569
- st.info("Excel report not available")
570
-
571
- with col3:
572
- if st.session_state.regenerated_data.get('zip_buffer'):
573
  st.download_button(
574
- label="πŸ“¦ Processed Files",
575
- data=st.session_state.regenerated_data['zip_buffer'].getvalue(),
576
- file_name=f"Brand_Assets_Processed_{timestamp}.zip",
577
- mime="application/zip"
 
578
  )
579
-
580
- st.markdown("---")
581
- st.info("πŸ’‘ **Tip:** Downloads will remain available until you upload a new file or click 'Process New File'")
582
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
583
  else:
584
- # Reset session state when no file is uploaded
585
- if st.session_state.regeneration_complete:
586
- st.session_state.regeneration_complete = False
587
- st.session_state.regenerated_data = {}
588
-
589
- st.info("πŸ‘† Please upload a zip file to get started.")
590
-
591
  with st.expander("πŸ“– Instructions"):
592
  st.markdown("""
593
- **What is Tab 6 (Re Run Matrix)?**
594
-
595
- Regenerates PDF and Excel reports from Tab 5 output after you've manually added new files.
596
-
597
- **When to use:**
598
- 1. You have Tab 5 output with reports
599
- 2. You manually added new files (following naming convention)
600
- 3. You want updated reports with today's date
601
-
602
- **How to use:**
603
- 1. Take your Tab 5 output folder (must include both PDF and Excel reports)
604
- 2. Add any new files following the naming convention
605
- 3. ZIP the entire folder
606
- 4. Upload and click "Regenerate Reports"
607
- 5. Download updated reports
608
-
609
- **Naming Convention:**
610
- `{markennummer}B{blocknummer}{marke}{count_str}{cleaned}{ext}`
611
-
612
- Example: `01B01dove01bodylotion.png`
613
- - `01` = brand number
614
- - `B01` = block/folder number
615
- - `dove` = brand name
616
- - `01` = sequential counter
617
- - `bodylotion` = cleaned name
618
- - `.png` = file extension
619
-
620
- **Key Features:**
621
- - **Deduplication**: Same filename with different extensions counted only once
622
- - **Priority**: Non-image formats (mp4, mov, gif, txt) prioritized over images
623
- - **Highlighting**: Non-image formats highlighted in yellow in Excel
624
- - **Preserves**: Manual folder structure changes from Excel file
625
- """)
 
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
180
+ """)