venkatesh commited on
Commit
672e740
Β·
1 Parent(s): cb77653

updates in the adv brand file renamer tab

Browse files
Files changed (2) hide show
  1. README.md +1 -1
  2. app.py +208 -18
README.md CHANGED
@@ -1,2 +1,2 @@
1
  # tools
2
- App used to ensure all the internal tools for Decode Marketing GmBH are in one place for internal team members to use.
 
1
  # tools
2
+ App used to ensure all the internal tools for Decode Marketing GmBH are in one place for internal team members to use.
app.py CHANGED
@@ -2088,13 +2088,13 @@ def file_renamer_tool():
2088
  # Show preview
2089
  with st.expander("πŸ“‹ Preview renamed files"):
2090
  preview_df = pd.DataFrame(
2091
- processed_files[:20], # Show first 20 files
2092
  columns=["Original Name", "New Name", "Brand"]
2093
  )
2094
  st.dataframe(preview_df)
2095
 
2096
  if total_files > 20:
2097
- st.info(f"Showing first 20 files. Total processed: {total_files}")
2098
 
2099
  # Create zip file with renamed files
2100
  zip_buffer = io.BytesIO()
@@ -2263,7 +2263,7 @@ def white_to_transparent_tool():
2263
  for i, file_path in enumerate(processed_files[:6]): # Show max 6 images
2264
  with cols[i % 3]:
2265
  img = PILImage.open(file_path)
2266
- st.image(img, caption=os.path.basename(file_path), use_container_width=True)
2267
 
2268
  if len(processed_files) > 6:
2269
  st.info(f"Showing first 6 images. Total processed: {len(processed_files)}")
@@ -2355,12 +2355,12 @@ def find_smallest_dimensions_tool():
2355
  with col1:
2356
  st.subheader("Smallest Width")
2357
  st.write(f"Dimensions: {min_width} Γ— {height_at_min_width} px")
2358
- st.image(file_min_width, caption=os.path.basename(file_min_width), use_container_width =True)
2359
 
2360
  with col2:
2361
  st.subheader("Smallest Height")
2362
  st.write(f"Dimensions: {width_at_min_height} Γ— {min_height} px")
2363
- st.image(file_min_height, caption=os.path.basename(file_min_height), use_container_width =True)
2364
  else:
2365
  st.warning("No valid image files found in the uploaded zip.")
2366
 
@@ -2548,7 +2548,7 @@ def resize_with_transparent_canvas_tool():
2548
  for i, file_path in enumerate(sample_files):
2549
  with cols[i % 3]:
2550
  img = PILImage.open(file_path)
2551
- st.image(img, caption=os.path.basename(file_path), use_container_width=True)
2552
 
2553
  if processed_count > 6:
2554
  st.info(f"Showing sample images. Total processed: {processed_count}")
@@ -2701,7 +2701,7 @@ def center_on_canvas_tool():
2701
  for i, file_path in enumerate(sample_files):
2702
  with cols[i % 3]:
2703
  img = PILImage.open(file_path)
2704
- st.image(img, caption=os.path.basename(file_path), use_container_width=True)
2705
 
2706
  if processed_count > 6:
2707
  st.info(f"Showing sample images. Total processed: {processed_count}")
@@ -2781,7 +2781,7 @@ def generate_excel_report(output_folder: Path, marken_index: dict, file_to_facto
2781
 
2782
  reordered_data = []
2783
  for _, row in df_assets.iterrows():
2784
- raw_fg = str(row["factorgroup"])
2785
  group_prefix = raw_fg[:2]
2786
  try:
2787
  group = str(int(group_prefix))
@@ -2800,7 +2800,7 @@ def generate_excel_report(output_folder: Path, marken_index: dict, file_to_facto
2800
  })
2801
 
2802
  df_reordered = pd.DataFrame(reordered_data, columns=["Group", "factor", "factorgroup", "ID"])
2803
-
2804
  with pd.ExcelWriter(final_excel_path, engine='openpyxl') as writer:
2805
  df_assets.to_excel(writer, index=False, sheet_name="Assets")
2806
  df_reordered.to_excel(writer, index=False, sheet_name="Reordered")
@@ -3088,7 +3088,6 @@ def brand_renamer_tool():
3088
  uploaded_file = st.file_uploader(
3089
  "Choose a ZIP file",
3090
  type=['zip'],
3091
- # help="Upload a zip file containing your brand folders with assets."
3092
  )
3093
 
3094
  # Reset processing state when new file is uploaded
@@ -3145,11 +3144,21 @@ def brand_renamer_tool():
3145
  output_folder
3146
  )
3147
 
3148
- # Generate PDF with corrected ID labels
3149
- pdf_buffer, error = generate_filename_based_pdf_report(
 
 
 
 
 
 
 
 
 
 
3150
  input_folder,
3151
  erste_marke,
3152
- renamed_files # Pass the renamed files mapping
3153
  )
3154
  if error:
3155
  st.error(f"PDF generation failed: {error}")
@@ -3187,7 +3196,7 @@ def brand_renamer_tool():
3187
  'zip_buffer': zip_buffer,
3188
  'combined_zip_buffer': combined_zip_buffer,
3189
  'temp_dir': temp_dir,
3190
- 'renamed_files': renamed_files # Store for potential reuse
3191
  }
3192
  st.session_state.processing_complete = True
3193
 
@@ -3198,12 +3207,33 @@ def brand_renamer_tool():
3198
  if st.session_state.processing_complete:
3199
  st.success("Processing complete!")
3200
 
3201
- # Display a preview of processed names
3202
  with st.expander("Preview Processed Names"):
3203
  if 'renamed_files' in st.session_state.processed_data:
3204
- st.write("First 10 processed filenames:")
3205
- for i, (old_name, new_name) in enumerate(list(st.session_state.processed_data['renamed_files'].items())[:10]):
3206
- st.write(f"{old_name} β†’ {new_name}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3207
 
3208
  # Option to start over
3209
  if st.button("πŸ”„ Process New File", help="Clear results and upload a new file"):
@@ -3285,8 +3315,168 @@ def brand_renamer_tool():
3285
 
3286
  with st.expander("πŸ“– Instructions"):
3287
  st.markdown("""
 
 
 
 
 
 
 
3288
  """)
3289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3290
  def main():
3291
  st.title("πŸ”§ Brand Assets Tools")
3292
 
 
2088
  # Show preview
2089
  with st.expander("πŸ“‹ Preview renamed files"):
2090
  preview_df = pd.DataFrame(
2091
+ processed_files,
2092
  columns=["Original Name", "New Name", "Brand"]
2093
  )
2094
  st.dataframe(preview_df)
2095
 
2096
  if total_files > 20:
2097
+ st.info(f"Total processed: {total_files}")
2098
 
2099
  # Create zip file with renamed files
2100
  zip_buffer = io.BytesIO()
 
2263
  for i, file_path in enumerate(processed_files[:6]): # Show max 6 images
2264
  with cols[i % 3]:
2265
  img = PILImage.open(file_path)
2266
+ st.image(img, caption=os.path.basename(file_path), use_column_width=True)
2267
 
2268
  if len(processed_files) > 6:
2269
  st.info(f"Showing first 6 images. Total processed: {len(processed_files)}")
 
2355
  with col1:
2356
  st.subheader("Smallest Width")
2357
  st.write(f"Dimensions: {min_width} Γ— {height_at_min_width} px")
2358
+ st.image(file_min_width, caption=os.path.basename(file_min_width), use_column_width =True)
2359
 
2360
  with col2:
2361
  st.subheader("Smallest Height")
2362
  st.write(f"Dimensions: {width_at_min_height} Γ— {min_height} px")
2363
+ st.image(file_min_height, caption=os.path.basename(file_min_height), use_column_width =True)
2364
  else:
2365
  st.warning("No valid image files found in the uploaded zip.")
2366
 
 
2548
  for i, file_path in enumerate(sample_files):
2549
  with cols[i % 3]:
2550
  img = PILImage.open(file_path)
2551
+ st.image(img, caption=os.path.basename(file_path), use_column_width=True)
2552
 
2553
  if processed_count > 6:
2554
  st.info(f"Showing sample images. Total processed: {processed_count}")
 
2701
  for i, file_path in enumerate(sample_files):
2702
  with cols[i % 3]:
2703
  img = PILImage.open(file_path)
2704
+ st.image(img, caption=os.path.basename(file_path), use_column_width=True)
2705
 
2706
  if processed_count > 6:
2707
  st.info(f"Showing sample images. Total processed: {processed_count}")
 
2781
 
2782
  reordered_data = []
2783
  for _, row in df_assets.iterrows():
2784
+ raw_fg = str(row["ID"])
2785
  group_prefix = raw_fg[:2]
2786
  try:
2787
  group = str(int(group_prefix))
 
2800
  })
2801
 
2802
  df_reordered = pd.DataFrame(reordered_data, columns=["Group", "factor", "factorgroup", "ID"])
2803
+ df_reordered = df_reordered.sort_values(by='Group', ascending=True).reset_index(drop=True)
2804
  with pd.ExcelWriter(final_excel_path, engine='openpyxl') as writer:
2805
  df_assets.to_excel(writer, index=False, sheet_name="Assets")
2806
  df_reordered.to_excel(writer, index=False, sheet_name="Reordered")
 
3088
  uploaded_file = st.file_uploader(
3089
  "Choose a ZIP file",
3090
  type=['zip'],
 
3091
  )
3092
 
3093
  # Reset processing state when new file is uploaded
 
3144
  output_folder
3145
  )
3146
 
3147
+ # Also rename actual files in output folder to have .png extensions
3148
+ for file_path in output_folder.iterdir():
3149
+ if file_path.is_file() and not file_path.suffix:
3150
+ # File has no extension, add .png
3151
+ new_file_path = file_path.with_suffix('.png')
3152
+ try:
3153
+ file_path.rename(new_file_path)
3154
+ except Exception as e:
3155
+ print(f"Could not rename {file_path}: {e}")
3156
+
3157
+ # Generate PDF with extensions - use the modified function
3158
+ pdf_buffer, error = generate_filename_based_pdf_report_with_extensions(
3159
  input_folder,
3160
  erste_marke,
3161
+ marken_index # Pass marken_index for ID generation
3162
  )
3163
  if error:
3164
  st.error(f"PDF generation failed: {error}")
 
3196
  'zip_buffer': zip_buffer,
3197
  'combined_zip_buffer': combined_zip_buffer,
3198
  'temp_dir': temp_dir,
3199
+ 'renamed_files': renamed_files
3200
  }
3201
  st.session_state.processing_complete = True
3202
 
 
3207
  if st.session_state.processing_complete:
3208
  st.success("Processing complete!")
3209
 
3210
+ # Display a preview of processed names with extensions
3211
  with st.expander("Preview Processed Names"):
3212
  if 'renamed_files' in st.session_state.processed_data:
3213
+ st.write("Sample processed filenames (with .png extensions in PDF):")
3214
+ # Handle the case where renamed_files might be a defaultdict
3215
+ renamed_files_data = st.session_state.processed_data['renamed_files']
3216
+
3217
+ # Extract sample file names safely
3218
+ sample_files = []
3219
+ if hasattr(renamed_files_data, 'items'):
3220
+ # It's a dictionary-like object
3221
+ for folder_name, brand_data in list(renamed_files_data.items())[:3]: # First 3 folders
3222
+ for brand_name, files in list(brand_data.items())[:2]: # First 2 brands per folder
3223
+ for file_path, new_name in files[:2]: # First 2 files per brand
3224
+ if isinstance(new_name, str):
3225
+ pdf_name = Path(new_name).stem + '.png'
3226
+ sample_files.append((Path(file_path).name, pdf_name))
3227
+ if len(sample_files) >= 10:
3228
+ break
3229
+ if len(sample_files) >= 10:
3230
+ break
3231
+ if len(sample_files) >= 10:
3232
+ break
3233
+
3234
+ # Display the sample files
3235
+ for old_name, pdf_name in sample_files:
3236
+ st.write(f"{old_name} β†’ {pdf_name}")
3237
 
3238
  # Option to start over
3239
  if st.button("πŸ”„ Process New File", help="Clear results and upload a new file"):
 
3315
 
3316
  with st.expander("πŸ“– Instructions"):
3317
  st.markdown("""
3318
+ Upload a ZIP file containing brand asset folders. The tool will:
3319
+ 1. Detect all brands automatically
3320
+ 2. Let you choose which brand gets number 01
3321
+ 3. Process and rename all files with proper numbering
3322
+ 4. Generate a PDF report showing all assets with filenames including .png extensions
3323
+ 5. Create an Excel overview of the processed files
3324
+ 6. Package everything for easy download
3325
  """)
3326
 
3327
+
3328
+ def generate_filename_based_pdf_report_with_extensions(input_folder, erste_marke=None, marken_index=None):
3329
+ """Generate PDF report with .png extensions in image labels"""
3330
+ marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
3331
+
3332
+ if not marken_set:
3333
+ return None, "No brands found in filenames."
3334
+
3335
+ # Use provided marken_index or create new one
3336
+ if not marken_index:
3337
+ marken_index = {}
3338
+ if erste_marke and erste_marke in marken_set:
3339
+ marken_index[erste_marke] = "01"
3340
+ aktuelle_nummer = 2
3341
+ for marke in sorted(marken_set):
3342
+ if marke != erste_marke:
3343
+ marken_index[marke] = f"{aktuelle_nummer:02d}"
3344
+ aktuelle_nummer += 1
3345
+ else:
3346
+ for i, marke in enumerate(sorted(marken_set), 1):
3347
+ marken_index[marke] = f"{i:02d}"
3348
+
3349
+ # Generate PDF
3350
+ pdf_buffer = io.BytesIO()
3351
+ doc = SimpleDocTemplate(pdf_buffer, pagesize=A4, leftMargin=20, rightMargin=20, topMargin=40, bottomMargin=30)
3352
+ elements = []
3353
+ styles = getSampleStyleSheet()
3354
+
3355
+ nummer_zu_marke = {v: k for k, v in marken_index.items()}
3356
+ marken_spalten = sorted(nummer_zu_marke.items())
3357
+
3358
+ for folder in sorted(renamed_files_by_folder_and_marke):
3359
+ elements.append(Paragraph(f"<b>Folder: {folder}</b>", styles['Heading2']))
3360
+
3361
+ abschnitt = renamed_files_by_folder_and_marke[folder]
3362
+ total = 0
3363
+ lines = []
3364
+ for nummer, marke in marken_spalten:
3365
+ count = len(abschnitt.get(marke, []))
3366
+ total += count
3367
+ lines.append(f"{nummer} ({marke}): {count}")
3368
+ lines.append(f"Total: {total}")
3369
+ elements.append(Paragraph("<br/>".join(lines), styles['Normal']))
3370
+ elements.append(Spacer(1, 10))
3371
+
3372
+ headers = [f"{nummer} ({marke})" for nummer, marke in marken_spalten]
3373
+ data = [headers]
3374
+ col_data = []
3375
+ max_rows = 0
3376
+ for _, marke in marken_spalten:
3377
+ eintraege = abschnitt.get(marke, [])
3378
+ zellen = []
3379
+ for p, original_name in eintraege:
3380
+ # Generate the ID name and add .png extension for display
3381
+ blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
3382
+ markennummer = marken_index[marke]
3383
+ cleaned = get_cleaned_filename_without_brand(original_name, marke)
3384
+ id_name = f"{markennummer}B{blocknummer}{marke}{cleaned}.png" # Add .png here
3385
+
3386
+ cell = get_asset_cell(p, id_name, len(headers))
3387
+ zellen.append(cell)
3388
+ col_data.append(zellen)
3389
+ max_rows = max(max_rows, len(zellen))
3390
+
3391
+ for i in range(max_rows):
3392
+ row = []
3393
+ for col in col_data:
3394
+ row.append(col[i] if i < len(col) else "")
3395
+ data.append(row)
3396
+
3397
+ col_width = (A4[0] - 40) / len(headers)
3398
+ t = Table(data, colWidths=[col_width] * len(headers))
3399
+ t.setStyle(TableStyle([
3400
+ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
3401
+ ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
3402
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
3403
+ ]))
3404
+ elements.append(t)
3405
+ elements.append(PageBreak())
3406
+
3407
+ # Total overview
3408
+ elements.append(Paragraph("<b>Total Overview</b>", styles['Heading2']))
3409
+ global_counts = defaultdict(int)
3410
+ for folder_data in renamed_files_by_folder_and_marke.values():
3411
+ for marke, daten in folder_data.items():
3412
+ global_counts[marke] += len(daten)
3413
+
3414
+ gesamt = 0
3415
+ summary = []
3416
+ for nummer, marke in marken_spalten:
3417
+ count = global_counts[marke]
3418
+ summary.append(f"{marke}: {count} assets")
3419
+ gesamt += count
3420
+ summary.append(f"Total number of all assets: {gesamt}")
3421
+ elements.append(Paragraph("<br/>".join(summary), styles['Normal']))
3422
+
3423
+ # Add brand pages with .png extensions
3424
+ add_brand_pages_with_png_extensions(elements, marken_spalten, renamed_files_by_folder_and_marke, marken_index)
3425
+
3426
+ try:
3427
+ doc.build(elements)
3428
+ pdf_buffer.seek(0)
3429
+ return pdf_buffer, None
3430
+ except Exception as e:
3431
+ return None, f"Error generating PDF: {str(e)}"
3432
+
3433
+ def add_brand_pages_with_png_extensions(elements, marken_spalten, renamed_files_by_folder_and_marke, marken_index):
3434
+ """Add brand overview pages with .png extensions in labels"""
3435
+ styles = getSampleStyleSheet()
3436
+ for nummer, marke in marken_spalten:
3437
+ assets = []
3438
+ for folder in renamed_files_by_folder_and_marke:
3439
+ folder_assets = renamed_files_by_folder_and_marke[folder].get(marke, [])
3440
+ for pfad, original_name in folder_assets:
3441
+ # Generate the ID name with .png extension for display
3442
+ blocknummer = re.sub(r'\D', '', folder)[:2].zfill(2)
3443
+ markennummer = marken_index[marke]
3444
+ cleaned = get_cleaned_filename_without_brand(original_name, marke)
3445
+ id_name = f"{markennummer}B{blocknummer}{marke}{cleaned}.png" # Add .png here
3446
+ assets.append((pfad, id_name))
3447
+
3448
+ if not assets:
3449
+ continue
3450
+
3451
+ elements.append(PageBreak())
3452
+ elements.append(Paragraph(f"<b>Brand Overview: {nummer} – {marke}</b>", styles['Heading2']))
3453
+ elements.append(Spacer(1, 6))
3454
+ elements.append(Paragraph(f"Number of assets: {len(assets)}", styles['Normal']))
3455
+ elements.append(Spacer(1, 10))
3456
+
3457
+ headers = ["Asset"] * 4
3458
+ data = [headers]
3459
+ row = []
3460
+ for i, (pfad, id_name) in enumerate(assets):
3461
+ # Use ID name with .png extension as the label
3462
+ cell = get_asset_cell(pfad, id_name, 4)
3463
+ row.append(cell)
3464
+ if len(row) == 4:
3465
+ data.append(row)
3466
+ row = []
3467
+ if row:
3468
+ row.extend([""] * (4 - len(row)))
3469
+ data.append(row)
3470
+
3471
+ table = Table(data, colWidths=(A4[0] - 40) / 4)
3472
+ table.setStyle(TableStyle([
3473
+ ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
3474
+ ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
3475
+ ('VALIGN', (0, 0), (-1, -1), 'TOP'),
3476
+ ]))
3477
+ elements.append(table)
3478
+
3479
+
3480
  def main():
3481
  st.title("πŸ”§ Brand Assets Tools")
3482