Gnanashri Kota Venkatesh commited on
Commit
fb80b9e
Β·
unverified Β·
1 Parent(s): 3ed5aab

Update tab6.py

Browse files
Files changed (1) hide show
  1. tab6.py +266 -169
tab6.py CHANGED
@@ -1,190 +1,287 @@
1
  import io
2
  import os
3
- import zipfile
4
  import shutil
 
 
5
  import streamlit as st
6
- from PIL import Image as PILImage
7
-
8
- from helper import extract_zip_to_temp
9
 
10
- ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'}
11
- ALLOWED_TEXT_EXTENSIONS = {'.txt', '.md', '.csv'}
12
- ALLOWED_VIDEO_EXTENSIONS = {'.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', '.m4v', '.3gp', '.ogv'}
13
- ALLOWED_AUDIO_EXTENSIONS = {'.mp3', '.wav', '.aac', '.flac', '.ogg', '.m4a', '.wma'}
14
- ALL_ALLOWED_EXTENSIONS = ALLOWED_IMAGE_EXTENSIONS.union(ALLOWED_TEXT_EXTENSIONS).union(ALLOWED_VIDEO_EXTENSIONS).union(ALLOWED_AUDIO_EXTENSIONS)
15
 
16
 
17
- def resize_with_transparent_canvas_tool():
18
- st.header("Resize with Transparent Canvas")
19
- st.markdown("Resize images to 400px on the largest side while maintaining aspect ratio on transparent background.")
20
-
21
- # File upload with unique key
 
 
 
 
 
22
  uploaded_file = st.file_uploader(
23
- "Choose a ZIP file with images",
24
  type=['zip'],
25
- help="Upload a zip file containing images to resize.",
26
- key="resize_transparent_upload"
27
  )
28
-
 
 
 
 
 
 
29
  if uploaded_file:
30
- # Show the fixed resize setting
31
- st.info("Images will be resized to 400px on the largest side (width or height), maintaining aspect ratio.")
32
-
33
- # Process button with unique key
34
- if st.button("Process Images", type="primary", key="process_resize_transparent_images"):
35
- try:
36
- # Extract zip file
37
- with st.spinner("Extracting zip file..."):
38
- temp_dir = extract_zip_to_temp(uploaded_file)
39
- input_folder = temp_dir
40
- items = os.listdir(temp_dir)
41
- if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
42
- input_folder = os.path.join(temp_dir, items[0])
43
-
44
- # Create output folder
45
- output_folder = os.path.join(temp_dir, "resized_transparent_output")
46
- os.makedirs(output_folder, exist_ok=True)
47
-
48
- # Process images
49
- processed_count = 0
50
- error_count = 0
51
- progress_bar = st.progress(0)
52
- status_text = st.empty()
53
-
54
- all_files = []
55
- for root, dirs, files in os.walk(input_folder):
56
- for file in files:
57
- # Accept ALL file extensions, not just images
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
- ext = os.path.splitext(file_path)[1].lower()
69
-
70
- # Only process if it's an image, otherwise copy as-is
71
- if ext in ALLOWED_IMAGE_EXTENSIONS:
72
- new_path = os.path.join(output_folder, os.path.splitext(relative_path)[0] + ".png")
73
- os.makedirs(os.path.dirname(new_path), exist_ok=True)
74
-
75
- with PILImage.open(file_path) as img:
76
- img = img.convert("RGBA")
77
- orig_w, orig_h = img.size
78
-
79
- # Calculate scaling factor based on largest side
80
- max_dimension = 400
81
- if orig_w >= orig_h:
82
- # Width is larger or equal
83
- scale_factor = max_dimension / orig_w
84
- new_w = max_dimension
85
- new_h = int(orig_h * scale_factor)
86
- else:
87
- # Height is larger
88
- scale_factor = max_dimension / orig_h
89
- new_h = max_dimension
90
- new_w = int(orig_w * scale_factor)
91
-
92
- # Resize image while maintaining aspect ratio
93
- img_resized = img.resize((new_w, new_h), PILImage.LANCZOS)
94
-
95
- # Create transparent canvas with the exact resized dimensions
96
- canvas = PILImage.new("RGBA", (new_w, new_h), (0, 0, 0, 0))
97
-
98
- # The resized image fits perfectly on the canvas (no centering needed)
99
- canvas.paste(img_resized, (0, 0), mask=img_resized)
100
 
101
- canvas.save(new_path)
102
- else:
103
- # Not an image - copy as-is with original extension
104
- new_path = os.path.join(output_folder, relative_path)
105
- os.makedirs(os.path.dirname(new_path), exist_ok=True)
106
- shutil.copy2(file_path, new_path)
107
-
108
- processed_count += 1
109
- except Exception as e:
110
- error_count += 1
111
- st.warning(f"Error processing {os.path.basename(file_path)}: {str(e)}")
112
-
113
- status_text.empty()
114
- progress_bar.empty()
115
-
116
- # Results summary
117
- st.success(f"""
118
- Processing complete!
119
- - βœ… Processed: {processed_count} images
120
- - ❌ Errors: {error_count} images
121
- - All images resized to 400px on largest side
122
- """)
123
-
124
- if processed_count > 0:
125
- # Create zip file with processed images
126
- zip_buffer = io.BytesIO()
127
- with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
128
- for root, dirs, files in os.walk(output_folder):
129
- for file in files:
130
- file_path = os.path.join(root, file)
131
- rel_path = os.path.relpath(file_path, output_folder)
132
- zip_file.write(file_path, rel_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
- zip_buffer.seek(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- # Download button with unique key
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  st.download_button(
138
- label="πŸ“₯ Download Resized Images (ZIP)",
139
- data=zip_buffer.getvalue(),
140
- file_name="resized_400px_images.zip",
141
- mime="application/zip",
142
- key="download_resized_transparent"
143
  )
144
-
145
- # Show preview
146
- with st.expander("πŸ–ΌοΈ Preview Resized Images"):
147
- sample_files = []
148
- for root, dirs, files in os.walk(output_folder):
149
- for file in files[:3]: # Get first 3 files from each folder
150
- if len(sample_files) < 6: # Max 6 samples
151
- sample_files.append(os.path.join(root, file))
152
-
153
- if sample_files:
154
- cols = st.columns(3)
155
- for i, file_path in enumerate(sample_files):
156
- with cols[i % 3]:
157
- img = PILImage.open(file_path)
158
- st.image(img, caption=f"{os.path.basename(file_path)} ({img.size[0]}x{img.size[1]})", use_column_width=True)
159
-
160
- if processed_count > 6:
161
- st.info(f"Showing sample images. Total processed: {processed_count}")
162
-
163
- except Exception as e:
164
- st.error(f"An error occurred during processing: {str(e)}")
165
-
 
 
 
 
 
 
166
  else:
167
- st.info("πŸ‘† Please upload a zip file with images to resize.")
168
-
169
- # Instructions
 
 
 
 
170
  with st.expander("πŸ“– Instructions"):
171
  st.markdown("""
172
- **How to use this tool:**
173
-
174
- 1. Upload a zip file containing images
175
- 2. All images will be resized to 400px on their largest side (width or height)
176
- 3. Aspect ratio is maintained - smaller dimension will be scaled proportionally
177
- 4. Click "Process Images"
178
- 5. Download the resized images with transparent backgrounds
179
-
180
- **Examples:**
181
- - 1000x800 image β†’ 400x320 image (width was larger)
182
- - 600x1200 image β†’ 200x400 image (height was larger)
183
- - 400x400 image β†’ 400x400 image (already correct size)
184
 
185
- **Features:**
186
- - Maintains original aspect ratio
187
- - Outputs PNG files to preserve transparency
188
- - Preserves folder structure
189
- - Fixed 400px maximum on largest dimension
 
190
  """)
 
1
  import io
2
  import os
 
3
  import shutil
4
+ import zipfile
5
+ from pathlib import Path
6
  import streamlit as st
7
+ from reportlab.lib.pagesizes import A4
8
+ from reportlab.lib.styles import getSampleStyleSheet
9
+ from helper import extract_zip_to_temp, analyze_files_by_filename, generate_filename_based_pdf_report_with_extensions, process_files, generate_excel_report
10
 
 
 
 
 
 
11
 
12
 
13
+ def brand_renamer_tool():
14
+ st.header("Advanced Brand File Processor")
15
+ st.markdown("Automatically rename and organize brand assets with numbering and generate reports.")
16
+
17
+ # Initialize session state for persistent results
18
+ if 'processing_complete' not in st.session_state:
19
+ st.session_state.processing_complete = False
20
+ if 'processed_data' not in st.session_state:
21
+ st.session_state.processed_data = {}
22
+
23
  uploaded_file = st.file_uploader(
24
+ "Choose a ZIP file",
25
  type=['zip'],
 
 
26
  )
27
+
28
+ # Reset processing state when new file is uploaded
29
+ if uploaded_file and 'uploaded_file_name' in st.session_state:
30
+ if st.session_state.uploaded_file_name != uploaded_file.name:
31
+ st.session_state.processing_complete = False
32
+ st.session_state.processed_data = {}
33
+
34
  if uploaded_file:
35
+ # Store uploaded file name to detect changes
36
+ st.session_state.uploaded_file_name = uploaded_file.name
37
+
38
+ if not st.session_state.processing_complete:
39
+ with st.spinner("Extracting and analyzing files..."):
40
+ temp_dir = extract_zip_to_temp(uploaded_file)
41
+ input_folder = Path(temp_dir)
42
+
43
+ items = os.listdir(temp_dir)
44
+ if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
45
+ input_folder = Path(temp_dir) / items[0]
46
+
47
+ output_folder = Path(temp_dir) / "output"
48
+ output_folder.mkdir(exist_ok=True)
49
+
50
+ marken_set, _, _ = analyze_files_by_filename(input_folder)
51
+
52
+ if not marken_set:
53
+ st.error("No brands found in the uploaded files.")
54
+ return
55
+
56
+ st.success(f"Detected brands: {', '.join(sorted(marken_set))}")
57
+
58
+ # Brand numbering selection
59
+ st.subheader("Brand Numbering")
60
+ erste_marke = st.selectbox(
61
+ "Which brand should be number 01?",
62
+ options=sorted(marken_set),
63
+ index=0
64
+ )
65
+
66
+ marken_index = {erste_marke: "01"}
67
+ aktuelle_nummer = 2
68
+ for marke in sorted(marken_set):
69
+ if marke != erste_marke:
70
+ marken_index[marke] = f"{aktuelle_nummer:02d}"
71
+ aktuelle_nummer += 1
72
+
73
+ if st.button("Process Files and Generate Reports", type="primary"):
74
+ with st.spinner("Processing files..."):
75
+ # Process and rename files
76
+ renamed_files, file_to_factorgroup = process_files(
77
+ input_folder,
78
+ marken_index,
79
+ output_folder
80
+ )
81
+
82
+ # Rename files to preserve original extensions instead of forcing .png
83
+ for file_path in output_folder.iterdir():
84
+ if file_path.is_file():
85
+ # Get original extension (if it exists)
86
+ original_ext = file_path.suffix.lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
+ # If file has no extension, try to detect from content or keep as is
89
+ if not original_ext:
90
+ # Try to find original extension from renamed_files mapping
91
+ original_name = None
92
+ for folder_data in renamed_files.values():
93
+ for brand_data in folder_data.values():
94
+ for orig_path, new_name in brand_data:
95
+ if Path(new_name).name == file_path.name:
96
+ original_name = Path(orig_path).name
97
+ break
98
+
99
+ if original_name:
100
+ orig_ext = Path(original_name).suffix.lower()
101
+ if orig_ext:
102
+ new_file_path = file_path.with_suffix(orig_ext)
103
+ try:
104
+ file_path.rename(new_file_path)
105
+ except Exception as e:
106
+ print(f"Could not rename {file_path}: {e}")
107
+
108
+ # Generate PDF with extensions - supports all file types
109
+ pdf_buffer, error = generate_filename_based_pdf_report_with_extensions(
110
+ input_folder,
111
+ erste_marke,
112
+ marken_index # Pass marken_index for ID generation
113
+ )
114
+ if error:
115
+ st.error(f"PDF generation failed: {error}")
116
+
117
+ excel_path = generate_excel_report(output_folder, marken_index, file_to_factorgroup)
118
+
119
+ # Create individual file buffers
120
+ zip_buffer = io.BytesIO()
121
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
122
+ for file in output_folder.iterdir():
123
+ if file.is_file():
124
+ zip_file.write(file, file.name)
125
+ zip_buffer.seek(0)
126
+
127
+ # Create combined download with all files
128
+ combined_zip_buffer = io.BytesIO()
129
+ with zipfile.ZipFile(combined_zip_buffer, 'w', zipfile.ZIP_DEFLATED) as combined_zip:
130
+ # Add processed files
131
+ for file in output_folder.iterdir():
132
+ if file.is_file():
133
+ combined_zip.write(file, f"processed_files/{file.name}")
134
+
135
+ # Add PDF report if available
136
+ if pdf_buffer:
137
+ combined_zip.writestr("reports/Brand_Assets_Report.pdf", pdf_buffer.getvalue())
138
+
139
+ # Add Excel report
140
+ with open(excel_path, 'rb') as excel_file:
141
+ combined_zip.writestr("reports/Brand_Assets_Overview.xlsx", excel_file.read())
142
+
143
+ combined_zip_buffer.seek(0)
144
+
145
+ # Store processed data in session state
146
+ st.session_state.processed_data = {
147
+ 'pdf_buffer': pdf_buffer,
148
+ 'excel_path': excel_path,
149
+ 'zip_buffer': zip_buffer,
150
+ 'combined_zip_buffer': combined_zip_buffer,
151
+ 'temp_dir': temp_dir,
152
+ 'renamed_files': renamed_files
153
+ }
154
+ st.session_state.processing_complete = True
155
+
156
+ # Force rerun to show download buttons
157
+ st.rerun()
158
+
159
+ # Show download options if processing is complete
160
+ if st.session_state.processing_complete:
161
+ st.success("Processing complete!")
162
+
163
+ # Display a preview of processed names with original extensions
164
+ with st.expander("Preview Processed Names"):
165
+ if 'renamed_files' in st.session_state.processed_data:
166
+ st.write("Sample processed filenames (with original extensions preserved):")
167
+ # Handle the case where renamed_files might be a defaultdict
168
+ renamed_files_data = st.session_state.processed_data['renamed_files']
169
 
170
+ # Extract sample file names safely
171
+ sample_files = []
172
+ if hasattr(renamed_files_data, 'items'):
173
+ # It's a dictionary-like object
174
+ for folder_name, brand_data in list(renamed_files_data.items())[:3]: # First 3 folders
175
+ for brand_name, files in list(brand_data.items())[:2]: # First 2 brands per folder
176
+ for file_path, new_name in files[:2]: # First 2 files per brand
177
+ if isinstance(new_name, str):
178
+ # Preserve original extension
179
+ original_ext = Path(file_path).suffix
180
+ pdf_name = Path(new_name).stem + original_ext
181
+ sample_files.append((Path(file_path).name, pdf_name))
182
+ if len(sample_files) >= 10:
183
+ break
184
+ if len(sample_files) >= 10:
185
+ break
186
+ if len(sample_files) >= 10:
187
+ break
188
 
189
+ # Display the sample files
190
+ for old_name, pdf_name in sample_files:
191
+ st.write(f"{old_name} β†’ {pdf_name}")
192
+
193
+ # Option to start over
194
+ if st.button("πŸ”„ Process New File", help="Clear results and upload a new file"):
195
+ st.session_state.processing_complete = False
196
+ st.session_state.processed_data = {}
197
+ if 'temp_dir' in st.session_state.processed_data:
198
+ try:
199
+ shutil.rmtree(st.session_state.processed_data['temp_dir'])
200
+ except:
201
+ pass
202
+ st.rerun()
203
+
204
+ st.markdown("---")
205
+
206
+ # Combined download option (recommended)
207
+ st.subheader("πŸ“¦ Complete Package Download")
208
+ st.markdown("**Recommended:** Download everything in one convenient package")
209
+
210
+ if st.session_state.processed_data.get('combined_zip_buffer'):
211
+ st.download_button(
212
+ label="🎁 Download Complete Package (All Files + Reports)",
213
+ data=st.session_state.processed_data['combined_zip_buffer'].getvalue(),
214
+ file_name="Brand_Assets_Complete_Package.zip",
215
+ mime="application/zip",
216
+ type="primary"
217
+ )
218
+
219
+ st.markdown("---")
220
+
221
+ # Individual download options
222
+ st.subheader("πŸ“ Individual Downloads")
223
+ st.markdown("Or download items separately:")
224
+
225
+ col1, col2, col3 = st.columns(3)
226
+
227
+ with col1:
228
+ if st.session_state.processed_data.get('pdf_buffer'):
229
  st.download_button(
230
+ label="πŸ“„ PDF Report",
231
+ data=st.session_state.processed_data['pdf_buffer'].getvalue(),
232
+ file_name="Brand_Assets_Report.pdf",
233
+ mime="application/pdf"
 
234
  )
235
+ else:
236
+ st.info("PDF report not available")
237
+
238
+ with col2:
239
+ if st.session_state.processed_data.get('excel_path'):
240
+ try:
241
+ with open(st.session_state.processed_data['excel_path'], 'rb') as excel_file:
242
+ st.download_button(
243
+ label="πŸ“Š Excel Report",
244
+ data=excel_file.read(),
245
+ file_name="Brand_Assets_Overview.xlsx",
246
+ mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
247
+ )
248
+ except:
249
+ st.info("Excel report not available")
250
+
251
+ with col3:
252
+ if st.session_state.processed_data.get('zip_buffer'):
253
+ st.download_button(
254
+ label="πŸ“¦ Processed Files",
255
+ data=st.session_state.processed_data['zip_buffer'].getvalue(),
256
+ file_name="Brand_Assets_Processed.zip",
257
+ mime="application/zip"
258
+ )
259
+
260
+ st.markdown("---")
261
+ st.info("πŸ’‘ **Tip:** Downloads will remain available until you upload a new file or click 'Process New File'")
262
+
263
  else:
264
+ # Reset session state when no file is uploaded
265
+ if st.session_state.processing_complete:
266
+ st.session_state.processing_complete = False
267
+ st.session_state.processed_data = {}
268
+
269
+ st.info("πŸ‘† Please upload a zip file to get started.")
270
+
271
  with st.expander("πŸ“– Instructions"):
272
  st.markdown("""
273
+ Upload a ZIP file containing brand asset folders. The tool will:
274
+ 1. Detect all brands automatically
275
+ 2. Let you choose which brand gets number 01
276
+ 3. Process and rename all files with proper numbering (preserving all file extensions)
277
+ 4. Generate a PDF report showing all assets with original filenames and extensions
278
+ 5. Create an Excel overview of the processed files (all file types)
279
+ 6. Package everything for easy download
 
 
 
 
 
280
 
281
+ **Supported file types:** All extensions are supported including:
282
+ - Images: .png, .jpg, .jpeg, .gif, .bmp, .svg, .webp
283
+ - Videos: .mp4, .avi, .mov, .mkv, .webm
284
+ - Audio: .mp3, .wav, .ogg, .flac, .m4a
285
+ - Documents: .pdf, .doc, .docx, .txt, .xlsx
286
+ - And any other file type!
287
  """)