rdjarbeng commited on
Commit
68894fa
·
1 Parent(s): 45a4752

Add debug options. Check for empty file in logs before accessing

Browse files
Files changed (1) hide show
  1. app.py +87 -26
app.py CHANGED
@@ -26,13 +26,28 @@ def log_user_interaction():
26
  init_counter()
27
  # Generate a unique user ID (hashed timestamp as proxy for session)
28
  user_id = md5(str(time.time()).encode()).hexdigest()
29
- with open(counter_file, "r") as f:
30
- data = json.load(f)
 
 
 
 
 
 
 
 
 
 
31
  data["total_requests"] += 1
32
  if user_id not in data["unique_sessions"]:
33
  data["unique_sessions"].append(user_id)
34
- with open(counter_file, "w") as f:
35
- json.dump(data, f)
 
 
 
 
 
36
  # Log only the request number and timestamp
37
  logging.info(f"Request #{data['total_requests']} at {time.strftime('%Y%m%d-%H%M%S')}")
38
  return data["total_requests"], len(data["unique_sessions"])
@@ -59,31 +74,51 @@ def hex_to_rgba(hex_color):
59
  return tuple(int(hex_color[i:i + 2], 16) for i in (0, 2, 4, 6))
60
 
61
  def remove_background(input_path, bg_color=None, transparent_bg=True, model_choice="", alpha_matting=False, post_process_mask=False, only_mask=False):
 
 
 
62
  try:
63
- # Log user interaction (minimal)
64
- log_user_interaction()
 
 
 
 
 
 
 
 
 
 
 
65
 
66
  # Open the input image
67
  input_image = Image.open(input_path)
 
68
 
69
  # Extract the original filename without extension
70
  original_filename = os.path.splitext(os.path.basename(input_path))[0]
71
  # Create the desired output filename
72
- output_filename = f"{original_filename}_hf_removebg.png"
 
73
 
74
  # Extract the model name from the choice
75
- model_name = model_choice.split(' | ')[0] if model_choice else ""
 
76
 
77
  # Set up the session with the chosen model, or None if no model is selected
78
  session = new_session(model_name) if model_name else None
79
 
80
  # Use transparent background if selected, otherwise use color
81
  bg_color_rgba = None if transparent_bg else hex_to_rgba(bg_color)
 
82
 
83
  # Prepare additional options
84
- remove_kwargs = {
85
- "session": session,
86
- }
 
 
87
 
88
  # Only add bgcolor if we have one
89
  if bg_color_rgba is not None:
@@ -104,46 +139,64 @@ def remove_background(input_path, bg_color=None, transparent_bg=True, model_choi
104
  if only_mask:
105
  remove_kwargs["only_mask"] = True
106
 
 
 
107
  # Convert PIL Image to numpy array
108
  input_array = np.array(input_image)
 
109
 
110
  # Use the remove function
 
111
  output_array = remove(input_array, **remove_kwargs)
 
112
 
113
  # Convert numpy array back to PIL Image
114
  output_image = Image.fromarray(output_array)
 
115
 
116
  # Preserve transparency for transparent background or only_mask
117
  if transparent_bg or only_mask:
118
  if output_image.mode != 'RGBA':
119
  output_image = output_image.convert('RGBA')
 
120
  elif output_image.mode != 'RGB':
121
  output_image = output_image.convert('RGB')
 
122
 
123
  # Create a temporary directory and save the image with the desired filename
124
  temp_dir = tempfile.mkdtemp()
125
  output_path = os.path.join(temp_dir, output_filename)
126
  output_image.save(output_path, format="PNG")
 
127
 
128
- return output_path
 
 
 
 
 
 
 
129
 
130
  except Exception as e:
 
 
 
131
  logging.error(f"An error occurred: {e}")
132
  return None
133
 
134
  # Fixed examples with proper values for all inputs
135
- # examples = [
136
- # [
137
- # 'scifi_man1.jpg', # input_path
138
- # "#FFFFFF", # bg_color (white)
139
- # True, # transparent_bg
140
- # "", # model_choice (empty string, which is in the choices)
141
- # False, # alpha_matting
142
- # False, # post_process_mask
143
- # False # only_mask
144
- # ]
145
- # ]
146
- examples = [['scifi_man1.jpg']]
147
 
148
  # Gradio interface
149
  iface = gr.Interface(
@@ -151,7 +204,7 @@ iface = gr.Interface(
151
  inputs=[
152
  gr.Image(type="filepath", label="Input Image"),
153
  gr.ColorPicker(label="Background Color (ignored if transparent is selected)", value="#FFFFFF"),
154
- gr.Checkbox(label="Transparent Background", value=True),
155
  gr.Dropdown(
156
  choices=[""] + [f"{k} | {v}" for k, v in MODEL_OPTIONS.items() if k != ""],
157
  label="Model Selection",
@@ -172,4 +225,12 @@ iface = gr.Interface(
172
  )
173
 
174
  if __name__ == "__main__":
175
- iface.launch()
 
 
 
 
 
 
 
 
 
26
  init_counter()
27
  # Generate a unique user ID (hashed timestamp as proxy for session)
28
  user_id = md5(str(time.time()).encode()).hexdigest()
29
+
30
+ try:
31
+ with open(counter_file, "r") as f:
32
+ content = f.read().strip()
33
+ if not content: # File is empty
34
+ data = {"total_requests": 0, "unique_sessions": []}
35
+ else:
36
+ data = json.loads(content)
37
+ except (json.JSONDecodeError, FileNotFoundError):
38
+ # Handle corrupted or missing file
39
+ data = {"total_requests": 0, "unique_sessions": []}
40
+
41
  data["total_requests"] += 1
42
  if user_id not in data["unique_sessions"]:
43
  data["unique_sessions"].append(user_id)
44
+
45
+ try:
46
+ with open(counter_file, "w") as f:
47
+ json.dump(data, f)
48
+ except Exception as e:
49
+ logging.error(f"Failed to write counter file: {e}")
50
+
51
  # Log only the request number and timestamp
52
  logging.info(f"Request #{data['total_requests']} at {time.strftime('%Y%m%d-%H%M%S')}")
53
  return data["total_requests"], len(data["unique_sessions"])
 
74
  return tuple(int(hex_color[i:i + 2], 16) for i in (0, 2, 4, 6))
75
 
76
  def remove_background(input_path, bg_color=None, transparent_bg=True, model_choice="", alpha_matting=False, post_process_mask=False, only_mask=False):
77
+ print(f"DEBUG: Function called with input_path: {input_path}")
78
+ print(f"DEBUG: Parameters - bg_color: {bg_color}, transparent_bg: {transparent_bg}, model_choice: {model_choice}")
79
+
80
  try:
81
+ # Check if input path is valid
82
+ if not input_path or not os.path.exists(input_path):
83
+ print(f"ERROR: Invalid input path: {input_path}")
84
+ return None
85
+
86
+ print("DEBUG: Starting background removal...")
87
+
88
+ # Log user interaction (minimal) - with error handling
89
+ try:
90
+ log_user_interaction()
91
+ except Exception as e:
92
+ print(f"WARNING: Failed to log user interaction: {e}")
93
+ # Continue with background removal even if logging fails
94
 
95
  # Open the input image
96
  input_image = Image.open(input_path)
97
+ print(f"DEBUG: Opened image with size: {input_image.size}, mode: {input_image.mode}")
98
 
99
  # Extract the original filename without extension
100
  original_filename = os.path.splitext(os.path.basename(input_path))[0]
101
  # Create the desired output filename
102
+ output_filename = f"{original_filename}_removebg.png"
103
+ print(f"DEBUG: Output filename will be: {output_filename}")
104
 
105
  # Extract the model name from the choice
106
+ model_name = model_choice.split(' | ')[0] if model_choice and ' | ' in model_choice else model_choice
107
+ print(f"DEBUG: Using model: {model_name if model_name else 'default'}")
108
 
109
  # Set up the session with the chosen model, or None if no model is selected
110
  session = new_session(model_name) if model_name else None
111
 
112
  # Use transparent background if selected, otherwise use color
113
  bg_color_rgba = None if transparent_bg else hex_to_rgba(bg_color)
114
+ print(f"DEBUG: Background color RGBA: {bg_color_rgba}")
115
 
116
  # Prepare additional options
117
+ remove_kwargs = {}
118
+
119
+ # Only add session if we have one
120
+ if session is not None:
121
+ remove_kwargs["session"] = session
122
 
123
  # Only add bgcolor if we have one
124
  if bg_color_rgba is not None:
 
139
  if only_mask:
140
  remove_kwargs["only_mask"] = True
141
 
142
+ print(f"DEBUG: Remove kwargs: {remove_kwargs}")
143
+
144
  # Convert PIL Image to numpy array
145
  input_array = np.array(input_image)
146
+ print(f"DEBUG: Input array shape: {input_array.shape}")
147
 
148
  # Use the remove function
149
+ print("DEBUG: Calling rembg.remove()...")
150
  output_array = remove(input_array, **remove_kwargs)
151
+ print(f"DEBUG: Output array shape: {output_array.shape}")
152
 
153
  # Convert numpy array back to PIL Image
154
  output_image = Image.fromarray(output_array)
155
+ print(f"DEBUG: Output image size: {output_image.size}, mode: {output_image.mode}")
156
 
157
  # Preserve transparency for transparent background or only_mask
158
  if transparent_bg or only_mask:
159
  if output_image.mode != 'RGBA':
160
  output_image = output_image.convert('RGBA')
161
+ print("DEBUG: Converted to RGBA mode")
162
  elif output_image.mode != 'RGB':
163
  output_image = output_image.convert('RGB')
164
+ print("DEBUG: Converted to RGB mode")
165
 
166
  # Create a temporary directory and save the image with the desired filename
167
  temp_dir = tempfile.mkdtemp()
168
  output_path = os.path.join(temp_dir, output_filename)
169
  output_image.save(output_path, format="PNG")
170
+ print(f"DEBUG: Saved output to: {output_path}")
171
 
172
+ # Verify the file was created
173
+ if os.path.exists(output_path):
174
+ file_size = os.path.getsize(output_path)
175
+ print(f"DEBUG: Output file created successfully, size: {file_size} bytes")
176
+ return output_path
177
+ else:
178
+ print("ERROR: Output file was not created")
179
+ return None
180
 
181
  except Exception as e:
182
+ print(f"ERROR: Exception occurred: {str(e)}")
183
+ import traceback
184
+ traceback.print_exc()
185
  logging.error(f"An error occurred: {e}")
186
  return None
187
 
188
  # Fixed examples with proper values for all inputs
189
+ examples = [
190
+ [
191
+ 'scifi_man1.jpg', # input_path
192
+ "#FFFFFF", # bg_color (white)
193
+ True, # transparent_bg
194
+ "", # model_choice (empty string, which is in the choices)
195
+ False, # alpha_matting
196
+ False, # post_process_mask
197
+ False # only_mask
198
+ ]
199
+ ]
 
200
 
201
  # Gradio interface
202
  iface = gr.Interface(
 
204
  inputs=[
205
  gr.Image(type="filepath", label="Input Image"),
206
  gr.ColorPicker(label="Background Color (ignored if transparent is selected)", value="#FFFFFF"),
207
+ gr.Checkbox(label="Transparent Background", value=False),
208
  gr.Dropdown(
209
  choices=[""] + [f"{k} | {v}" for k, v in MODEL_OPTIONS.items() if k != ""],
210
  label="Model Selection",
 
225
  )
226
 
227
  if __name__ == "__main__":
228
+ print("Starting Background Remover app...")
229
+ print("Open your browser and go to: http://127.0.0.1:7860")
230
+ iface.launch(
231
+ server_name="127.0.0.1",
232
+ server_port=7860,
233
+ share=False,
234
+ debug=True,
235
+ quiet=False
236
+ )