File size: 14,339 Bytes
6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f 2afab78 6a3bd1f f3a4ad9 6a3bd1f f3a4ad9 6a3bd1f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 |
import gradio as gr
import torch
from PIL import Image
import spaces
import os
import json
import tempfile
from typing import List, Optional
from pixcribe_pipeline import PixcribePipeline
from ui_manager import UIManager
# Initialize Pipeline and UI Manager
print("Initializing Pixcribe V5 with Batch Processing...")
print("β³ Loading models (this may take a while)...")
pipeline = PixcribePipeline(yolo_variant='l')
ui_manager = UIManager()
print("β
All models loaded successfully!")
# Global variable to store latest batch results and images for export
latest_batch_results = None
latest_batch_images = None
@spaces.GPU(duration=180)
def process_images_wrapper(files, yolo_variant, caption_language, progress=gr.Progress()):
"""
Process single or multiple images with progress tracking.
This function automatically detects whether to use single-image or batch processing
based on the number of files uploaded.
Args:
files: List of uploaded file objects (or single file)
yolo_variant: YOLO model variant ('m', 'l', 'x')
caption_language: Caption language ('zh', 'en')
progress: Gradio Progress object for progress updates
Returns:
Tuple of (visualized_image, caption_html, batch_results_html, export_panel_visibility)
"""
global latest_batch_results, latest_batch_images
# Validate input
if files is None or (isinstance(files, list) and len(files) == 0):
error_msg = "<div style='color: #E74C3C; padding: 24px; text-align: center;'>Please upload at least one image</div>"
return None, error_msg, "", gr.update(visible=False)
# Convert single file to list
if not isinstance(files, list):
files = [files]
# Check maximum limit
if len(files) > 10:
error_msg = "<div style='color: #E74C3C; padding: 24px; text-align: center;'>Maximum 10 images allowed. Please select fewer images.</div>"
return None, error_msg, "", gr.update(visible=False)
# Load images from files
images = []
for file in files:
try:
if hasattr(file, 'name'):
# File object from Gradio
img = Image.open(file.name)
else:
# Direct path
img = Image.open(file)
# Convert to RGB if needed
if img.mode != 'RGB':
img = img.convert('RGB')
images.append(img)
except Exception as e:
print(f"β οΈ Warning: Failed to load image {file}: {str(e)}")
continue
if len(images) == 0:
error_msg = "<div style='color: #E74C3C; padding: 24px; text-align: center;'>No valid images found. Please upload valid image files.</div>"
return None, error_msg, "", gr.update(visible=False)
platform = 'instagram' # Fixed platform
# Single image processing mode
if len(images) == 1:
try:
results = pipeline.process_image(
image=images[0],
platform=platform,
yolo_variant=yolo_variant,
language=caption_language
)
if results is None:
error_msg = "<div style='color: #E74C3C; padding: 24px; text-align: center;'>Processing failed. Check terminal logs for details.</div>"
return None, error_msg, "", gr.update(visible=False)
# Get visualized image with brand boxes
visualized_image = results.get('visualized_image', images[0])
# Format captions with copy functionality
captions_html = ui_manager.format_captions_with_copy(results['captions'])
# Clear batch results when in single mode
latest_batch_results = None
latest_batch_images = None
return visualized_image, captions_html, "", gr.update(visible=False)
except Exception as e:
import traceback
error_msg = traceback.format_exc()
print("="*60)
print("ERROR DETAILS:")
print(error_msg)
print("="*60)
error_html = f"""
<div style='background: #FADBD8; border: 2px solid #E74C3C; border-radius: 20px; padding: 28px; margin: 16px 0;'>
<h3 style='color: #C0392B; margin-top: 0; font-size: 22px;'>β Processing Error</h3>
<p style='color: #E74C3C; font-weight: bold; font-size: 17px; margin-bottom: 16px;'>{str(e)}</p>
<details style='margin-top: 12px;'>
<summary style='cursor: pointer; color: #C0392B; font-weight: bold; font-size: 16px;'>View Full Error Trace</summary>
<pre style='background: white; padding: 16px; border-radius: 12px; overflow-x: auto; font-size: 13px; color: #2C3E50; margin-top: 12px;'>{error_msg}</pre>
</details>
</div>
"""
return None, error_html, "", gr.update(visible=False)
# Batch processing mode (2+ images)
else:
try:
# Define progress callback
def update_progress(progress_info):
current = progress_info['current']
total = progress_info['total']
percent = progress_info['percent']
# Update Gradio progress
progress(percent / 100, desc=f"Processing image {current}/{total}")
# Process batch
batch_results = pipeline.process_batch(
images=images,
platform=platform,
yolo_variant=yolo_variant,
language=caption_language,
progress_callback=update_progress
)
# Store results globally for export
latest_batch_results = batch_results
latest_batch_images = images
# Format batch results as HTML
batch_html = ui_manager.format_batch_results_html(batch_results)
# Return None for single image display, batch results HTML, and show export panel
return None, "", batch_html, gr.update(visible=True)
except Exception as e:
import traceback
error_msg = traceback.format_exc()
print("="*60)
print("BATCH PROCESSING ERROR:")
print(error_msg)
print("="*60)
error_html = f"""
<div style='background: #FADBD8; border: 2px solid #E74C3C; border-radius: 20px; padding: 28px; margin: 16px 0;'>
<h3 style='color: #C0392B; margin-top: 0; font-size: 22px;'>β Batch Processing Error</h3>
<p style='color: #E74C3C; font-weight: bold; font-size: 17px; margin-bottom: 16px;'>{str(e)}</p>
<details style='margin-top: 12px;'>
<summary style='cursor: pointer; color: #C0392B; font-weight: bold; font-size: 16px;'>View Full Error Trace</summary>
<pre style='background: white; padding: 16px; border-radius: 12px; overflow-x: auto; font-size: 13px; color: #2C3E50; margin-top: 12px;'>{error_msg}</pre>
</details>
</div>
"""
return None, error_html, "", gr.update(visible=False)
def export_json_handler():
"""Export batch results to JSON file."""
global latest_batch_results
if latest_batch_results is None:
return None
try:
# Create temporary file
temp_dir = tempfile.gettempdir()
output_path = os.path.join(temp_dir, "pixcribe_batch_results.json")
# Export to JSON
pipeline.batch_processor.export_to_json(latest_batch_results, output_path)
return output_path
except Exception as e:
print(f"Export JSON error: {str(e)}")
return None
def export_csv_handler():
"""Export batch results to CSV file."""
global latest_batch_results
if latest_batch_results is None:
return None
try:
# Create temporary file
temp_dir = tempfile.gettempdir()
output_path = os.path.join(temp_dir, "pixcribe_batch_results.csv")
# Export to CSV
pipeline.batch_processor.export_to_csv(latest_batch_results, output_path)
return output_path
except Exception as e:
print(f"Export CSV error: {str(e)}")
return None
def export_zip_handler():
"""Export batch results to ZIP archive."""
global latest_batch_results, latest_batch_images
if latest_batch_results is None or latest_batch_images is None:
return None
try:
# Create temporary file
temp_dir = tempfile.gettempdir()
output_path = os.path.join(temp_dir, "pixcribe_batch_results.zip")
# Export to ZIP
pipeline.batch_processor.export_to_zip(
latest_batch_results,
latest_batch_images,
output_path
)
return output_path
except Exception as e:
print(f"Export ZIP error: {str(e)}")
return None
# Create Gradio Interface
with gr.Blocks(css=ui_manager.custom_css, title="Pixcribe V5 - AI Social Media Captions") as app:
# Header
ui_manager.create_header()
# Info Banner - Loading Time Notice
ui_manager.create_info_banner()
# Top Row - Upload Images & Detected Objects
with gr.Row(elem_classes="main-row"):
# Left - Upload Card
with gr.Column(scale=1):
with gr.Group(elem_classes="upload-card"):
image_input = gr.File(
file_count="multiple",
file_types=["image"],
label="Upload Images (Max 10)",
elem_classes="upload-area"
)
# Right - Detected Objects (Single Image Mode)
with gr.Column(scale=1):
with gr.Group(elem_classes="results-card"):
gr.Markdown("### Detected Objects", elem_classes="section-title")
visualized_image = gr.Image(
label="",
elem_classes="image-container"
)
# Bottom - Settings Section (Full Width)
with gr.Group(elem_classes="settings-container"):
gr.Markdown("### Settings", elem_classes="section-title-left")
with gr.Row(elem_classes="settings-row"):
caption_language = gr.Radio(
choices=[
('ηΉι«δΈζ', 'zh'),
('English', 'en')
],
value='en',
label="Caption Language",
elem_classes="radio-group-inline"
)
yolo_variant = gr.Radio(
choices=[
('Fast (m)', 'm'),
('Balanced (l)', 'l'),
('Accurate (x)', 'x')
],
value='l',
label="Detection Mode",
elem_classes="radio-group-inline"
)
# Generate Button (Centered)
with gr.Row(elem_classes="button-row"):
analyze_btn = gr.Button(
"Generate Captions",
variant="primary",
elem_classes="generate-button"
)
# Processing Time Notice
gr.HTML("""
<div style="text-align: center; margin-top: 16px; color: #7F8C8D; font-size: 14px;">
<span style="opacity: 0.8;">β‘ Please be patient - AI processing may take some time</span>
</div>
""")
# Single Image Caption Results (Full Width)
with gr.Group(elem_classes="caption-results-container"):
gr.Markdown("### π Generated Captions", elem_classes="section-title")
caption_output = gr.HTML(
label="",
elem_id="caption-results"
)
# Batch Results Display (Initially Hidden)
batch_results_output = gr.HTML(
label="",
visible=True
)
# Export Panel (Initially Hidden)
with gr.Group(elem_classes="export-panel", visible=False) as export_panel:
gr.Markdown("### π₯ Export Batch Results", elem_classes="section-title-left")
with gr.Row():
json_btn = gr.Button("π Download JSON", variant="secondary")
csv_btn = gr.Button("π Download CSV", variant="secondary")
zip_btn = gr.Button("π¦ Download ZIP", variant="secondary")
json_file = gr.File(label="JSON Export", visible=False)
csv_file = gr.File(label="CSV Export", visible=False)
zip_file = gr.File(label="ZIP Export", visible=False)
# Footer
ui_manager.create_footer()
gr.HTML('''
<div style="
display: flex;
align-items: center;
justify-content: center;
gap: 20px;
padding: 20px 0;
">
<p style="
font-family: 'Arial', sans-serif;
font-size: 14px;
font-weight: 500;
letter-spacing: 2px;
background: linear-gradient(90deg, #555, #007ACC);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin: 0;
text-transform: uppercase;
display: inline-block;
">EXPLORE THE CODE β</p>
<a href="https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/Pixcribe" style="text-decoration: none;">
<img src="https://img.shields.io/badge/GitHub-Pixcribe-007ACC?logo=github&style=for-the-badge">
</a>
</div>
''')
# Connect button to processing function
analyze_btn.click(
fn=process_images_wrapper,
inputs=[image_input, yolo_variant, caption_language],
outputs=[visualized_image, caption_output, batch_results_output, export_panel]
)
# Connect export buttons
json_btn.click(
fn=export_json_handler,
inputs=[],
outputs=[json_file]
).then(
lambda: gr.update(visible=True),
outputs=[json_file]
)
csv_btn.click(
fn=export_csv_handler,
inputs=[],
outputs=[csv_file]
).then(
lambda: gr.update(visible=True),
outputs=[csv_file]
)
zip_btn.click(
fn=export_zip_handler,
inputs=[],
outputs=[zip_file]
).then(
lambda: gr.update(visible=True),
outputs=[zip_file]
)
if __name__ == "__main__":
app.launch(share=True)
|