cella110n commited on
Commit
29788a3
·
verified ·
1 Parent(s): fe88ff7

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +339 -44
app.py CHANGED
@@ -7,7 +7,7 @@ import os
7
  import io
8
  import requests
9
  # import matplotlib.pyplot as plt # No plotting yet
10
- # import matplotlib # No plotting yet
11
  from huggingface_hub import hf_hub_download
12
  from dataclasses import dataclass
13
  from typing import List, Dict, Optional, Tuple
@@ -103,6 +103,187 @@ def preprocess_image(image: Image.Image, target_size=(448, 448)):
103
  img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
104
  return image, img_array
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  # --- Constants ---
107
  REPO_ID = "cella110n/cl_tagger"
108
  # Use the specified ONNX model filename
@@ -142,66 +323,180 @@ def initialize_onnx_paths():
142
  # Raise Gradio error to make it visible in the UI
143
  raise gr.Error(f"Initialization failed: {e}. Check logs and HF_TOKEN.")
144
 
145
- # --- ONNX Loading Test Function ---
146
  @spaces.GPU()
147
- def test_onnx_load():
148
- print("--- test_onnx_load function started (GPU worker) ---")
149
- if g_onnx_model_path is None:
150
- message = "Error: ONNX model path not initialized. Check startup logs."
 
151
  print(message)
152
- return message
153
-
154
- if not os.path.exists(g_onnx_model_path):
155
- message = f"Error: ONNX file not found at {g_onnx_model_path}. Check download."
156
- print(message)
157
- return message
158
 
 
 
159
  try:
160
- print(f"Attempting to load ONNX session from: {g_onnx_model_path}")
161
- # Determine providers (GPU if available)
162
  available_providers = ort.get_available_providers()
163
- print(f"Available ORT providers: {available_providers}")
164
  providers = []
165
- # Prioritize GPU providers
166
  if 'CUDAExecutionProvider' in available_providers:
167
- print("CUDAExecutionProvider found.")
168
  providers.append('CUDAExecutionProvider')
169
- elif 'DmlExecutionProvider' in available_providers: # For Windows with DirectML
170
- print("DmlExecutionProvider found.")
171
- providers.append('DmlExecutionProvider')
172
- # Always include CPU as fallback
173
  providers.append('CPUExecutionProvider')
174
-
175
  print(f"Attempting to load session with providers: {providers}")
176
  session = ort.InferenceSession(g_onnx_model_path, providers=providers)
177
- active_provider = session.get_providers()[0]
178
- message = f"ONNX session loaded successfully on GPU worker using provider: {active_provider}"
 
179
  print(message)
180
- # Clean up session immediately after test?
181
- # del session # Optional, depends if we want to keep it loaded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
 
183
  except Exception as e:
184
- message = f"Error loading ONNX session: {e}"
185
  print(message)
186
  import traceback; traceback.print_exc()
 
 
 
 
187
 
188
- return message
189
-
190
- # --- Gradio Interface Definition (Minimal for ONNX Load Test) ---
191
- with gr.Blocks() as demo:
192
- gr.Markdown("""
193
- # ONNX Model Load Test
194
- Downloads ONNX model and tag mapping, then attempts to load the ONNX session on the GPU worker when the button is clicked.
195
- Check logs for download and loading messages.
196
- """)
197
- with gr.Column():
198
- test_button = gr.Button("Test ONNX Load on GPU")
199
- output_text = gr.Textbox(label="Output")
200
-
201
- test_button.click(
202
- fn=test_onnx_load,
203
- inputs=[],
204
- outputs=[output_text]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  )
206
 
207
  # --- Main Block ---
 
7
  import io
8
  import requests
9
  # import matplotlib.pyplot as plt # No plotting yet
10
+ import matplotlib # For backend setting
11
  from huggingface_hub import hf_hub_download
12
  from dataclasses import dataclass
13
  from typing import List, Dict, Optional, Tuple
 
103
  img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
104
  return image, img_array
105
 
106
+ # Add get_tags function (from onnx_predict.py)
107
+ def get_tags(probs, labels: LabelData, gen_threshold, char_threshold):
108
+ result = {
109
+ "rating": [],
110
+ "general": [],
111
+ "character": [],
112
+ "copyright": [],
113
+ "artist": [],
114
+ "meta": [],
115
+ "quality": []
116
+ }
117
+ # Rating (select max)
118
+ if len(labels.rating) > 0:
119
+ # Ensure indices are within bounds
120
+ valid_indices = labels.rating[labels.rating < len(probs)]
121
+ if len(valid_indices) > 0:
122
+ rating_probs = probs[valid_indices]
123
+ if len(rating_probs) > 0:
124
+ rating_idx_local = np.argmax(rating_probs)
125
+ rating_idx_global = valid_indices[rating_idx_local]
126
+ # Check if global index is valid for names list
127
+ if rating_idx_global < len(labels.names) and labels.names[rating_idx_global] is not None:
128
+ rating_name = labels.names[rating_idx_global]
129
+ rating_conf = float(rating_probs[rating_idx_local])
130
+ result["rating"].append((rating_name, rating_conf))
131
+ else:
132
+ print(f"Warning: Invalid global index {rating_idx_global} for rating tag.")
133
+ else:
134
+ print("Warning: rating_probs became empty after filtering.")
135
+ else:
136
+ print("Warning: No valid indices found for rating tags within probs length.")
137
+
138
+ # Quality (select max)
139
+ if len(labels.quality) > 0:
140
+ valid_indices = labels.quality[labels.quality < len(probs)]
141
+ if len(valid_indices) > 0:
142
+ quality_probs = probs[valid_indices]
143
+ if len(quality_probs) > 0:
144
+ quality_idx_local = np.argmax(quality_probs)
145
+ quality_idx_global = valid_indices[quality_idx_local]
146
+ if quality_idx_global < len(labels.names) and labels.names[quality_idx_global] is not None:
147
+ quality_name = labels.names[quality_idx_global]
148
+ quality_conf = float(quality_probs[quality_idx_local])
149
+ result["quality"].append((quality_name, quality_conf))
150
+ else:
151
+ print(f"Warning: Invalid global index {quality_idx_global} for quality tag.")
152
+ else:
153
+ print("Warning: quality_probs became empty after filtering.")
154
+ else:
155
+ print("Warning: No valid indices found for quality tags within probs length.")
156
+
157
+ # Threshold-based categories
158
+ category_map = {
159
+ "general": (labels.general, gen_threshold),
160
+ "character": (labels.character, char_threshold),
161
+ "copyright": (labels.copyright, char_threshold),
162
+ "artist": (labels.artist, char_threshold),
163
+ "meta": (labels.meta, gen_threshold) # Use gen_threshold for meta as per original code
164
+ }
165
+ for category, (indices, threshold) in category_map.items():
166
+ if len(indices) > 0:
167
+ valid_indices = indices[(indices < len(probs))] # Check index bounds first
168
+ if len(valid_indices) > 0:
169
+ category_probs = probs[valid_indices]
170
+ mask = category_probs >= threshold
171
+ selected_indices_local = np.where(mask)[0]
172
+ if len(selected_indices_local) > 0:
173
+ selected_indices_global = valid_indices[selected_indices_local]
174
+ selected_probs = category_probs[selected_indices_local]
175
+ for idx_global, prob_val in zip(selected_indices_global, selected_probs):
176
+ # Check if global index is valid for names list
177
+ if idx_global < len(labels.names) and labels.names[idx_global] is not None:
178
+ result[category].append((labels.names[idx_global], float(prob_val)))
179
+ else:
180
+ print(f"Warning: Invalid global index {idx_global} for {category} tag.")
181
+ # else: print(f"No tags found for category '{category}' above threshold {threshold}")
182
+ # else: print(f"No valid indices found for category '{category}' within probs length.")
183
+ # else: print(f"No indices defined for category '{category}'")
184
+
185
+ # Sort by probability (descending)
186
+ for k in result:
187
+ result[k] = sorted(result[k], key=lambda x: x[1], reverse=True)
188
+ return result
189
+
190
+ # Add visualize_predictions function (Adapted from onnx_predict.py and previous versions)
191
+ def visualize_predictions(image: Image.Image, predictions: Dict, threshold: float):
192
+ # Filter out unwanted meta tags (e.g., id, commentary, request, mismatch)
193
+ filtered_meta = []
194
+ excluded_meta_patterns = ['id', 'commentary', 'request', 'mismatch']
195
+ for tag, prob in predictions.get("meta", []):
196
+ if not any(pattern in tag.lower() for pattern in excluded_meta_patterns):
197
+ filtered_meta.append((tag, prob))
198
+ predictions["meta"] = filtered_meta # Use filtered list for visualization
199
+
200
+ # --- Plotting Setup ---
201
+ plt.rcParams['font.family'] = 'DejaVu Sans' # Ensure font compatibility
202
+ fig = plt.figure(figsize=(20, 12), dpi=100)
203
+ gs = fig.add_gridspec(1, 2, width_ratios=[1.2, 1])
204
+
205
+ # Left side: Image
206
+ ax_img = fig.add_subplot(gs[0, 0])
207
+ ax_img.imshow(image)
208
+ ax_img.set_title("Original Image")
209
+ ax_img.axis('off')
210
+
211
+ # Right side: Tags
212
+ ax_tags = fig.add_subplot(gs[0, 1])
213
+ all_tags, all_probs, all_colors = [], [], []
214
+ color_map = {
215
+ 'rating': 'red', 'character': 'blue', 'copyright': 'purple',
216
+ 'artist': 'orange', 'general': 'green', 'meta': 'gray', 'quality': 'yellow'
217
+ }
218
+
219
+ # Aggregate tags from predictions dictionary
220
+ for cat, prefix, color in [
221
+ ('rating', 'R', color_map['rating']), ('quality', 'Q', color_map['quality']),
222
+ ('character', 'C', color_map['character']), ('copyright', '©', color_map['copyright']),
223
+ ('artist', 'A', color_map['artist']), ('general', 'G', color_map['general']),
224
+ ('meta', 'M', color_map['meta'])
225
+ ]:
226
+ # Sort within category by probability before adding
227
+ sorted_tags = sorted(predictions.get(cat, []), key=lambda x: x[1], reverse=True)
228
+ for tag, prob in sorted_tags:
229
+ # Add prefix to tag name for display
230
+ all_tags.append(f"[{prefix}] {tag.replace('_', ' ')}") # Replace underscores for display
231
+ all_probs.append(prob)
232
+ all_colors.append(color)
233
+
234
+ if not all_tags:
235
+ ax_tags.text(0.5, 0.5, "No tags found above threshold", ha='center', va='center')
236
+ ax_tags.set_title(f"Tags (Thresholds: Gen/Meta={threshold:.2f}, Char/Art/Copy={threshold:.2f})") # Assuming same threshold for now
237
+ ax_tags.axis('off')
238
+ else:
239
+ # Sort all aggregated tags by probability (descending) for plotting order
240
+ # Plotting from bottom up, so we want highest probability at the top
241
+ sorted_indices = sorted(range(len(all_probs)), key=lambda i: all_probs[i]) # Sort ascending for barh
242
+ all_tags = [all_tags[i] for i in sorted_indices]
243
+ all_probs = [all_probs[i] for i in sorted_indices]
244
+ all_colors = [all_colors[i] for i in sorted_indices]
245
+
246
+ num_tags = len(all_tags)
247
+ bar_height = min(0.8, max(0.1, 0.8 * (30 / num_tags))) if num_tags > 30 else 0.8
248
+ y_positions = np.arange(num_tags)
249
+
250
+ bars = ax_tags.barh(y_positions, all_probs, height=bar_height, color=all_colors)
251
+ ax_tags.set_yticks(y_positions)
252
+ ax_tags.set_yticklabels(all_tags)
253
+
254
+ fontsize = 10 if num_tags <= 40 else 8 if num_tags <= 60 else 6
255
+ for label in ax_tags.get_yticklabels():
256
+ label.set_fontsize(fontsize)
257
+
258
+ # Add probability text next to bars
259
+ for i, (bar, prob) in enumerate(zip(bars, all_probs)):
260
+ # Position text slightly outside the bar, ensuring it stays within plot bounds
261
+ text_x = min(prob + 0.02, 0.98) # Adjust x position
262
+ ax_tags.text(text_x, y_positions[i], f"{prob:.3f}", va='center', fontsize=fontsize)
263
+
264
+ ax_tags.set_xlim(0, 1)
265
+ ax_tags.set_title(f"Tags (Thresholds approx: {threshold:.2f})") # Indicate threshold used
266
+
267
+ # Add legend
268
+ from matplotlib.patches import Patch
269
+ legend_elements = [
270
+ Patch(facecolor=color, label=cat.capitalize()) for cat, color in color_map.items()
271
+ if any(t.startswith(f"[{cat[0].upper() if cat != 'copyright' else '©'}]") for t in all_tags)
272
+ ]
273
+ if legend_elements:
274
+ ax_tags.legend(handles=legend_elements, loc='lower right', fontsize=8)
275
+
276
+ plt.tight_layout()
277
+ plt.subplots_adjust(bottom=0.05)
278
+
279
+ # Save plot to buffer
280
+ buf = io.BytesIO()
281
+ plt.savefig(buf, format='png', dpi=100)
282
+ plt.close(fig)
283
+ buf.seek(0)
284
+ viz_image = Image.open(buf)
285
+ return viz_image
286
+
287
  # --- Constants ---
288
  REPO_ID = "cella110n/cl_tagger"
289
  # Use the specified ONNX model filename
 
323
  # Raise Gradio error to make it visible in the UI
324
  raise gr.Error(f"Initialization failed: {e}. Check logs and HF_TOKEN.")
325
 
326
+ # --- Main Prediction Function (ONNX) ---
327
  @spaces.GPU()
328
+ def predict_onnx(image_input, gen_threshold, char_threshold, output_mode):
329
+ print("--- predict_onnx function started (GPU worker) ---")
330
+ # --- 1. Ensure paths and labels are loaded ---
331
+ if g_onnx_model_path is None or g_labels_data is None:
332
+ message = "Error: Paths or labels not initialized. Check startup logs."
333
  print(message)
334
+ # Return error message and None for the image output
335
+ return message, None
 
 
 
 
336
 
337
+ # --- 2. Load ONNX Session (inside worker) ---
338
+ session = None
339
  try:
340
+ print(f"Loading ONNX session from: {g_onnx_model_path}")
 
341
  available_providers = ort.get_available_providers()
 
342
  providers = []
 
343
  if 'CUDAExecutionProvider' in available_providers:
 
344
  providers.append('CUDAExecutionProvider')
 
 
 
 
345
  providers.append('CPUExecutionProvider')
 
346
  print(f"Attempting to load session with providers: {providers}")
347
  session = ort.InferenceSession(g_onnx_model_path, providers=providers)
348
+ print(f"ONNX session loaded using: {session.get_providers()[0]}")
349
+ except Exception as e:
350
+ message = f"Error loading ONNX session in worker: {e}"
351
  print(message)
352
+ import traceback; traceback.print_exc()
353
+ return message, None
354
+
355
+ # --- 3. Process Input Image ---
356
+ if image_input is None:
357
+ return "Please upload an image.", None
358
+
359
+ print(f"Processing image with thresholds: gen={gen_threshold}, char={char_threshold}")
360
+ try:
361
+ # Handle different input types (PIL, numpy, URL, file path)
362
+ if isinstance(image_input, str):
363
+ if image_input.startswith("http"): # URL
364
+ response = requests.get(image_input, timeout=10)
365
+ response.raise_for_status()
366
+ image = Image.open(io.BytesIO(response.content))
367
+ elif os.path.exists(image_input): # File path
368
+ image = Image.open(image_input)
369
+ else:
370
+ raise ValueError(f"Invalid image input string: {image_input}")
371
+ elif isinstance(image_input, np.ndarray):
372
+ image = Image.fromarray(image_input)
373
+ elif isinstance(image_input, Image.Image):
374
+ image = image_input # Already a PIL image
375
+ else:
376
+ raise TypeError(f"Unsupported image input type: {type(image_input)}")
377
+
378
+ # Preprocess the PIL image
379
+ original_pil_image, input_tensor = preprocess_image(image)
380
+
381
+ # Ensure input tensor is float32, as expected by most ONNX models
382
+ # (even if the model internally uses float16)
383
+ input_tensor = input_tensor.astype(np.float32)
384
+
385
+ except Exception as e:
386
+ message = f"Error processing input image: {e}"
387
+ print(message)
388
+ return message, None
389
+
390
+ # --- 4. Run Inference ---
391
+ try:
392
+ input_name = session.get_inputs()[0].name
393
+ output_name = session.get_outputs()[0].name
394
+ print(f"Running inference with input '{input_name}', output '{output_name}'")
395
+ start_time = time.time()
396
+ outputs = session.run([output_name], {input_name: input_tensor})[0]
397
+ inference_time = time.time() - start_time
398
+ print(f"Inference completed in {inference_time:.3f} seconds")
399
+
400
+ # Check for NaN/Inf in outputs
401
+ if np.isnan(outputs).any() or np.isinf(outputs).any():
402
+ print("Warning: NaN or Inf detected in model output. Clamping...")
403
+ outputs = np.nan_to_num(outputs, nan=0.0, posinf=1.0, neginf=0.0) # Clamp to 0-1 range
404
+
405
+ # Apply sigmoid (outputs are likely logits)
406
+ # Use a stable sigmoid implementation
407
+ def stable_sigmoid(x):
408
+ return 1 / (1 + np.exp(-np.clip(x, -30, 30))) # Clip to avoid overflow
409
+ probs = stable_sigmoid(outputs[0]) # Assuming batch size 1
410
 
411
  except Exception as e:
412
+ message = f"Error during ONNX inference: {e}"
413
  print(message)
414
  import traceback; traceback.print_exc()
415
+ return message, None
416
+ finally:
417
+ # Clean up session if needed (might reduce memory usage between clicks)
418
+ del session
419
 
420
+ # --- 5. Post-process and Format Output ---
421
+ try:
422
+ print("Post-processing results...")
423
+ # Use the correct global variable for labels
424
+ predictions = get_tags(probs, g_labels_data, gen_threshold, char_threshold)
425
+
426
+ # Format output text string
427
+ output_tags = []
428
+ if predictions.get("rating"): output_tags.append(predictions["rating"][0][0].replace("_", " "))
429
+ if predictions.get("quality"): output_tags.append(predictions["quality"][0][0].replace("_", " "))
430
+ # Add other categories, respecting order and filtering meta if needed
431
+ for category in ["artist", "character", "copyright", "general", "meta"]:
432
+ tags_in_category = predictions.get(category, [])
433
+ for tag, prob in tags_in_category:
434
+ # Basic meta tag filtering for text output
435
+ if category == "meta" and any(p in tag.lower() for p in ['id', 'commentary', 'request', 'mismatch']):
436
+ continue
437
+ output_tags.append(tag.replace("_", " "))
438
+ output_text = ", ".join(output_tags)
439
+
440
+ # Generate visualization if requested
441
+ viz_image = None
442
+ if output_mode == "Tags + Visualization":
443
+ print("Generating visualization...")
444
+ # Pass the correct threshold for display title (can pass both if needed)
445
+ # For simplicity, passing gen_threshold as a representative value
446
+ viz_image = visualize_predictions(original_pil_image, predictions, gen_threshold)
447
+ print("Visualization generated.")
448
+ else:
449
+ print("Visualization skipped.")
450
+
451
+ print("Prediction complete.")
452
+ return output_text, viz_image
453
+
454
+ except Exception as e:
455
+ message = f"Error during post-processing: {e}"
456
+ print(message)
457
+ import traceback; traceback.print_exc()
458
+ return message, None
459
+
460
+ # --- Gradio Interface Definition (Full ONNX Version) ---
461
+ css = """
462
+ .gradio-container { font-family: 'IBM Plex Sans', sans-serif; }
463
+ footer { display: none !important; }
464
+ .gr-prose { max-width: 100% !important; }
465
+ """
466
+ # js = """ /* Keep existing JS */ """ # No JS needed currently
467
+
468
+ with gr.Blocks(css=css) as demo:
469
+ gr.Markdown("# WD EVA02 ONNX Tagger")
470
+ gr.Markdown("Upload an image or paste an image URL to predict tags using the fine-tuned WD EVA02 Tagger model (ONNX).")
471
+ gr.Markdown(f"Model Repository: [{REPO_ID}](https://huggingface.co/{REPO_ID}) - Using ONNX file: `{ONNX_FILENAME}`")
472
+ with gr.Row():
473
+ with gr.Column(scale=1):
474
+ image_input = gr.Image(type="pil", label="Input Image", elem_id="input-image")
475
+ # Add back URL input capability if desired (needs JS or separate component)
476
+ # gr.HTML("<div id='url-input-container'></div>")
477
+ gen_threshold = gr.Slider(minimum=0.0, maximum=1.0, step=0.05, value=0.55, label="General/Meta Tag Threshold")
478
+ char_threshold = gr.Slider(minimum=0.0, maximum=1.0, step=0.05, value=0.60, label="Character/Copyright/Artist Tag Threshold")
479
+ output_mode = gr.Radio(choices=["Tags Only", "Tags + Visualization"], value="Tags + Visualization", label="Output Mode")
480
+ predict_button = gr.Button("Predict", variant="primary")
481
+ with gr.Column(scale=1):
482
+ output_tags = gr.Textbox(label="Predicted Tags", lines=10, interactive=False)
483
+ output_visualization = gr.Image(type="pil", label="Prediction Visualization", interactive=False)
484
+ gr.Examples(
485
+ examples=[
486
+ ["https://pbs.twimg.com/media/GXBXsRvbQAAg1kp.jpg", 0.55, 0.60, "Tags + Visualization"],
487
+ ["https://pbs.twimg.com/media/GjlX0gibcAA4EJ4.jpg", 0.50, 0.50, "Tags Only"],
488
+ ["https://pbs.twimg.com/media/Gj4nQbjbEAATeoH.jpg", 0.55, 0.60, "Tags + Visualization"],
489
+ ["https://pbs.twimg.com/media/GkbtX0GaoAMlUZt.jpg", 0.45, 0.45, "Tags + Visualization"]
490
+ ],
491
+ inputs=[image_input, gen_threshold, char_threshold, output_mode],
492
+ outputs=[output_tags, output_visualization],
493
+ fn=predict_onnx, # Use the ONNX prediction function
494
+ cache_examples=False # Disable caching for examples during testing
495
+ )
496
+ predict_button.click(
497
+ fn=predict_onnx, # Use the ONNX prediction function
498
+ inputs=[image_input, gen_threshold, char_threshold, output_mode],
499
+ outputs=[output_tags, output_visualization]
500
  )
501
 
502
  # --- Main Block ---