DecodeMarketing Claude Opus 4.6 commited on
Commit
2e95e07
·
1 Parent(s): 1988036

Fix syntax error in tab3.py — indent body inside try block

Browse files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Files changed (1) hide show
  1. tab3.py +93 -94
tab3.py CHANGED
@@ -38,105 +38,104 @@ def white_to_transparent_tool():
38
  try:
39
  processed_files = []
40
  failed_files = []
41
-
42
- # Save uploaded files to temp dir
43
- for uploaded_file in uploaded_files:
44
- file_path = os.path.join(temp_dir, uploaded_file.name)
45
- with open(file_path, 'wb') as f:
46
- f.write(uploaded_file.getbuffer())
47
-
48
- # Process images
49
- progress_bar = st.progress(0)
50
- status_text = st.empty()
51
-
52
- for i, uploaded_file in enumerate(uploaded_files):
53
- status_text.text(f"Processing {uploaded_file.name}... ({i+1}/{len(uploaded_files)})")
54
- progress_bar.progress((i + 1) / len(uploaded_files))
55
-
56
- try:
57
- img = PILImage.open(os.path.join(temp_dir, uploaded_file.name)).convert("RGBA")
58
-
59
- # Convert to numpy array for OpenCV processing
60
- img_array = np.array(img)
61
-
62
- if crop_image:
63
- # Crop image
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  gray = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
65
  th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
66
-
67
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
68
  morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
69
-
70
- cnts, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
71
- if cnts: # Only crop if contours are found
72
- cnt = sorted(cnts, key=cv2.contourArea)[-1]
73
- x,y,w,h = cv2.boundingRect(cnt)
74
- img_array = img_array[y:y+h, x:x+w]
75
-
76
- # Make white background transparent
77
- gray = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
78
- th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
79
-
80
- kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
81
- morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
82
-
83
- roi, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
84
-
85
- mask = np.zeros(img_array.shape, img_array.dtype)
86
- if roi: # Only proceed if contours are found
87
- cv2.fillPoly(mask, roi, (255,)*img_array.shape[2])
88
- masked_image = cv2.bitwise_and(img_array, mask)
89
-
90
- # Convert back to PIL Image
91
- result_img = PILImage.fromarray(masked_image, mode="RGBA")
92
-
93
- # Save the processed image
94
- new_filename = os.path.splitext(uploaded_file.name)[0] + ".png"
95
- processed_path = os.path.join(temp_dir,
96
- new_filename)
97
- result_img.save(processed_path)
98
- processed_files.append(processed_path)
99
- else:
100
  failed_files.append(uploaded_file.name)
101
- except Exception as e:
102
- failed_files.append(uploaded_file.name)
103
- st.warning(f"Failed to process {uploaded_file.name}: {str(e)}")
104
-
105
- status_text.empty()
106
- progress_bar.empty()
107
-
108
- if processed_files:
109
- st.success(f"✅ Successfully processed {len(processed_files)} images")
110
-
111
- # Create zip file with processed images
112
- zip_buffer = io.BytesIO()
113
- with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
114
- for file_path in processed_files:
115
- zip_file.write(file_path, os.path.basename(file_path))
116
-
117
- zip_buffer.seek(0)
118
-
119
- # Download button
120
- st.download_button(
121
- label="📥 Download Processed Images (ZIP)",
122
- data=zip_buffer.getvalue(),
123
- file_name="transparent_images.zip",
124
- mime="application/zip"
125
- )
126
-
127
- # Show preview
128
- with st.expander("🖼️ Preview Processed Images"):
129
- cols = st.columns(3)
130
- for i, file_path in enumerate(processed_files[:6]): # Show max 6 images
131
- with cols[i % 3]:
132
- img = PILImage.open(file_path)
133
- st.image(img, caption=os.path.basename(file_path), use_column_width=True)
134
-
135
- if len(processed_files) > 6:
136
- st.info(f"Showing first 6 images. Total processed: {len(processed_files)}")
137
-
138
- if failed_files:
139
- st.warning(f"⚠️ Failed to process {len(failed_files)} files: {', '.join(failed_files)}")
140
  finally:
141
  shutil.rmtree(temp_dir, ignore_errors=True)
142
 
 
38
  try:
39
  processed_files = []
40
  failed_files = []
41
+
42
+ # Save uploaded files to temp dir
43
+ for uploaded_file in uploaded_files:
44
+ file_path = os.path.join(temp_dir, uploaded_file.name)
45
+ with open(file_path, 'wb') as f:
46
+ f.write(uploaded_file.getbuffer())
47
+
48
+ # Process images
49
+ progress_bar = st.progress(0)
50
+ status_text = st.empty()
51
+
52
+ for i, uploaded_file in enumerate(uploaded_files):
53
+ status_text.text(f"Processing {uploaded_file.name}... ({i+1}/{len(uploaded_files)})")
54
+ progress_bar.progress((i + 1) / len(uploaded_files))
55
+
56
+ try:
57
+ img = PILImage.open(os.path.join(temp_dir, uploaded_file.name)).convert("RGBA")
58
+
59
+ # Convert to numpy array for OpenCV processing
60
+ img_array = np.array(img)
61
+
62
+ if crop_image:
63
+ # Crop image
64
+ gray = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
65
+ th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
66
+
67
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
68
+ morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
69
+
70
+ cnts, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
71
+ if cnts: # Only crop if contours are found
72
+ cnt = sorted(cnts, key=cv2.contourArea)[-1]
73
+ x,y,w,h = cv2.boundingRect(cnt)
74
+ img_array = img_array[y:y+h, x:x+w]
75
+
76
+ # Make white background transparent
77
  gray = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
78
  th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
79
+
80
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
81
  morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
82
+
83
+ roi, _ = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
84
+
85
+ mask = np.zeros(img_array.shape, img_array.dtype)
86
+ if roi: # Only proceed if contours are found
87
+ cv2.fillPoly(mask, roi, (255,)*img_array.shape[2])
88
+ masked_image = cv2.bitwise_and(img_array, mask)
89
+
90
+ # Convert back to PIL Image
91
+ result_img = PILImage.fromarray(masked_image, mode="RGBA")
92
+
93
+ # Save the processed image
94
+ new_filename = os.path.splitext(uploaded_file.name)[0] + ".png"
95
+ processed_path = os.path.join(temp_dir, new_filename)
96
+ result_img.save(processed_path)
97
+ processed_files.append(processed_path)
98
+ else:
99
+ failed_files.append(uploaded_file.name)
100
+ except Exception as e:
 
 
 
 
 
 
 
 
 
 
 
 
101
  failed_files.append(uploaded_file.name)
102
+ st.warning(f"Failed to process {uploaded_file.name}: {str(e)}")
103
+
104
+ status_text.empty()
105
+ progress_bar.empty()
106
+
107
+ if processed_files:
108
+ st.success(f"✅ Successfully processed {len(processed_files)} images")
109
+
110
+ # Create zip file with processed images
111
+ zip_buffer = io.BytesIO()
112
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
113
+ for file_path in processed_files:
114
+ zip_file.write(file_path, os.path.basename(file_path))
115
+
116
+ zip_buffer.seek(0)
117
+
118
+ # Download button
119
+ st.download_button(
120
+ label="📥 Download Processed Images (ZIP)",
121
+ data=zip_buffer.getvalue(),
122
+ file_name="transparent_images.zip",
123
+ mime="application/zip"
124
+ )
125
+
126
+ # Show preview
127
+ with st.expander("🖼️ Preview Processed Images"):
128
+ cols = st.columns(3)
129
+ for i, file_path in enumerate(processed_files[:6]): # Show max 6 images
130
+ with cols[i % 3]:
131
+ img = PILImage.open(file_path)
132
+ st.image(img, caption=os.path.basename(file_path), use_column_width=True)
133
+
134
+ if len(processed_files) > 6:
135
+ st.info(f"Showing first 6 images. Total processed: {len(processed_files)}")
136
+
137
+ if failed_files:
138
+ st.warning(f"⚠️ Failed to process {len(failed_files)} files: {', '.join(failed_files)}")
 
 
139
  finally:
140
  shutil.rmtree(temp_dir, ignore_errors=True)
141