{ "cells": [ { "cell_type": "code", "execution_count": 232, "id": "f000e485-ba7d-4d12-ad00-67cc7f2512be", "metadata": { "tags": [] }, "outputs": [], "source": [ "import os\n", "import zipfile\n", "import shutil\n", "import time\n", "from PIL import Image, ImageDraw, ImageFilter\n", "import io\n", "from rembg import remove\n", "import json\n", "from transformers import pipeline\n", "import numpy as np\n", "from concurrent.futures import ThreadPoolExecutor\n", "import gradio as gr\n", "\n", "\n", "def remove_background_rembg(input_path):\n", "\tprint(f\"Removing background using rembg for image: {input_path}\")\n", "\twith open(input_path, 'rb') as i:\n", "\t\tinput_image = i.read()\n", "\toutput_image = remove(input_image)\n", "\timg = Image.open(io.BytesIO(output_image)).convert(\"RGBA\")\n", "\treturn img\n", "\n", "def remove_background_bria(input_path):\n", "\tprint(f\"Removing background using bria for image: {input_path}\")\n", "\tpipe = pipeline(\"image-segmentation\", model=\"briaai/RMBG-1.4\", trust_remote_code=True)\n", "\tpillow_image = pipe(input_path)\n", "\treturn pillow_image\n", "\n", "###### PlACE TO PUT ANOTHER MODEL #######\n", "\n", "def get_bounding_box_with_threshold(image, threshold):\n", "\t# Convert image to numpy array\n", "\timg_array = np.array(image)\n", " \n", "\t# Get alpha channel\n", "\talpha = img_array[:,:,3]\n", " \n", "\t# Find rows and columns where alpha > threshold\n", "\trows = np.any(alpha > threshold, axis=1)\n", "\tcols = np.any(alpha > threshold, axis=0)\n", " \n", "\t# Find the bounding box\n", "\ttop, bottom = np.where(rows)[0][[0, -1]]\n", "\tleft, right = np.where(cols)[0][[0, -1]]\n", " \n", "\tif left < right and top < bottom:\n", "\t\treturn (left, top, right, bottom)\n", "\telse:\n", "\t\treturn None\n", "\n", "def position_logic(image_path, canvas_size, padding_top, padding_right, padding_bottom, padding_left, use_threshold=True):\n", " image = Image.open(image_path)\n", " image = image.convert(\"RGBA\")\n", "\n", " # Get the bounding box of the non-blank area with threshold\n", " if use_threshold:\n", " bbox = get_bounding_box_with_threshold(image, threshold=10)\n", " else:\n", " bbox = image.getbbox()\n", " log = []\n", "\n", " if bbox:\n", " # Check 1 pixel around the image for non-transparent pixels\n", " width, height = image.size\n", " cropped_sides = []\n", " \n", " # Define tolerance for transparency\n", " tolerance = 30 # Adjust this value as needed\n", " \n", " # Check top edge\n", " if any(image.getpixel((x, 0))[3] > tolerance for x in range(width)):\n", " cropped_sides.append(\"top\")\n", " \n", " # Check bottom edge\n", " if any(image.getpixel((x, height-1))[3] > tolerance for x in range(width)):\n", " cropped_sides.append(\"bottom\")\n", " \n", " # Check left edge\n", " if any(image.getpixel((0, y))[3] > tolerance for y in range(height)):\n", " cropped_sides.append(\"left\")\n", " \n", " # Check right edge\n", " if any(image.getpixel((width-1, y))[3] > tolerance for y in range(height)):\n", " cropped_sides.append(\"right\")\n", " \n", " if cropped_sides:\n", " info_message = f\"Info for {os.path.basename(image_path)}: The following sides of the image may contain cropped objects: {', '.join(cropped_sides)}\"\n", " print(info_message)\n", " log.append({\"info\": info_message})\n", " else:\n", " info_message = f\"Info for {os.path.basename(image_path)}: The image is not cropped.\"\n", " print(info_message)\n", " log.append({\"info\": info_message})\n", " \n", " # Crop the image to the bounding box\n", " image = image.crop(bbox)\n", " log.append({\"action\": \"crop\", \"bbox\": [str(bbox[0]), str(bbox[1]), str(bbox[2]), str(bbox[3])]})\n", " \n", " # Calculate the new size to expand the image\n", " target_width, target_height = canvas_size\n", " aspect_ratio = image.width / image.height\n", " \n", " if len(cropped_sides) == 4:\n", " # If the image is cropped on all sides, center crop it to fit the canvas\n", " if aspect_ratio > 1: # Landscape\n", " new_height = target_height\n", " new_width = int(new_height * aspect_ratio)\n", " left = (new_width - target_width) // 2\n", " image = image.resize((new_width, new_height), Image.LANCZOS)\n", " image = image.crop((left, 0, left + target_width, target_height))\n", " else: # Portrait or square\n", " new_width = target_width\n", " new_height = int(new_width / aspect_ratio)\n", " top = (new_height - target_height) // 2\n", " image = image.resize((new_width, new_height), Image.LANCZOS)\n", " image = image.crop((0, top, target_width, top + target_height))\n", " log.append({\"action\": \"center_crop_resize\", \"new_size\": f\"{target_width}x{target_height}\"})\n", " x, y = 0, 0\n", " elif not cropped_sides:\n", " # If the image is not cropped, expand it from center until it touches the padding\n", " new_height = target_height - padding_top - padding_bottom\n", " new_width = int(new_height * aspect_ratio)\n", " \n", " if new_width > target_width - padding_left - padding_right:\n", " # If width exceeds available space, adjust based on width\n", " new_width = target_width - padding_left - padding_right\n", " new_height = int(new_width / aspect_ratio)\n", " \n", " # Resize the image\n", " image = image.resize((new_width, new_height), Image.LANCZOS)\n", " log.append({\"action\": \"resize\", \"new_width\": str(new_width), \"new_height\": str(new_height)})\n", " \n", " x = (target_width - new_width) // 2\n", " y = target_height - new_height - padding_bottom\n", " else:\n", " # New logic for handling cropped top and left, or top and right\n", " if set(cropped_sides) == {\"top\", \"left\"} or set(cropped_sides) == {\"top\", \"right\"}:\n", " new_height = target_height - padding_bottom\n", " new_width = int(new_height * aspect_ratio)\n", " \n", " # If new width exceeds canvas width, adjust based on width\n", " if new_width > target_width:\n", " new_width = target_width\n", " new_height = int(new_width / aspect_ratio)\n", " \n", " # Resize the image\n", " image = image.resize((new_width, new_height), Image.LANCZOS)\n", " log.append({\"action\": \"resize\", \"new_width\": str(new_width), \"new_height\": str(new_height)})\n", " \n", " # Set position\n", " if \"left\" in cropped_sides:\n", " x = 0\n", " else: # right in cropped_sides\n", " x = target_width - new_width\n", " y = 0\n", " \n", " # If the resized image is taller than the canvas minus padding, crop from the bottom\n", " if new_height > target_height - padding_bottom:\n", " crop_bottom = new_height - (target_height - padding_bottom)\n", " image = image.crop((0, 0, new_width, new_height - crop_bottom))\n", " new_height = target_height - padding_bottom\n", " log.append({\"action\": \"crop_vertical\", \"bottom_pixels_removed\": str(crop_bottom)})\n", " \n", " log.append({\"action\": \"position\", \"x\": str(x), \"y\": str(y)})\n", " elif set(cropped_sides) == {\"bottom\", \"left\"} or set(cropped_sides) == {\"bottom\", \"right\"}:\n", " # Handle bottom & left or bottom & right cropped images\n", " new_height = target_height - padding_top\n", " new_width = int(new_height * aspect_ratio)\n", " \n", " # If new width exceeds canvas width, adjust based on width\n", " if new_width > target_width - padding_left - padding_right:\n", " new_width = target_width - padding_left - padding_right\n", " new_height = int(new_width / aspect_ratio)\n", " \n", " # Resize the image without cropping or stretching\n", " image = image.resize((new_width, new_height), Image.LANCZOS)\n", " log.append({\"action\": \"resize\", \"new_width\": str(new_width), \"new_height\": str(new_height)})\n", " \n", " # Set position\n", " if \"left\" in cropped_sides:\n", " x = 0\n", " else: # right in cropped_sides\n", " x = target_width - new_width\n", " y = target_height - new_height\n", " \n", " log.append({\"action\": \"position\", \"x\": str(x), \"y\": str(y)})\n", " elif set(cropped_sides) == {\"bottom\", \"left\", \"right\"}:\n", " # Expand the image from the center\n", " new_width = target_width\n", " new_height = int(new_width / aspect_ratio)\n", " \n", " if new_height < target_height:\n", " new_height = target_height\n", " new_width = int(new_height * aspect_ratio)\n", " \n", " image = image.resize((new_width, new_height), Image.LANCZOS)\n", " \n", " # Crop to fit the canvas\n", " left = (new_width - target_width) // 2\n", " top = 0\n", " image = image.crop((left, top, left + target_width, top + target_height))\n", " \n", " log.append({\"action\": \"expand_and_crop\", \"new_size\": f\"{target_width}x{target_height}\"})\n", " x, y = 0, 0\n", " elif cropped_sides == [\"top\"]:\n", " # New logic for handling only top-cropped images\n", " if image.width > image.height:\n", " new_width = target_width\n", " new_height = int(target_width / aspect_ratio)\n", " else:\n", " new_height = target_height - padding_bottom\n", " new_width = int(new_height * aspect_ratio)\n", " \n", " # Resize the image\n", " image = image.resize((new_width, new_height), Image.LANCZOS)\n", " log.append({\"action\": \"resize\", \"new_width\": str(new_width), \"new_height\": str(new_height)})\n", " \n", " x = (target_width - new_width) // 2\n", " y = 0 # Align to top\n", " \n", " # Apply padding only to non-cropped sides\n", " x = max(padding_left, min(x, target_width - new_width - padding_right))\n", " elif cropped_sides in [[\"right\"], [\"left\"]]:\n", " # New logic for handling only right-cropped or left-cropped images\n", " if image.width > image.height:\n", " new_width = target_width - max(padding_left, padding_right)\n", " new_height = int(new_width / aspect_ratio)\n", " else:\n", " new_height = target_height - padding_top - padding_bottom\n", " new_width = int(new_height * aspect_ratio)\n", " \n", " # Resize the image\n", " image = image.resize((new_width, new_height), Image.LANCZOS)\n", " log.append({\"action\": \"resize\", \"new_width\": str(new_width), \"new_height\": str(new_height)})\n", " \n", " if cropped_sides == [\"right\"]:\n", " x = target_width - new_width # Align to right\n", " else: # cropped_sides == [\"left\"]\n", " x = 0 # Align to left\n", " y = target_height - new_height - padding_bottom # Respect bottom padding\n", " \n", " # Ensure top padding is respected\n", " if y < padding_top:\n", " y = padding_top\n", " \n", " log.append({\"action\": \"position\", \"x\": str(x), \"y\": str(y)})\n", " elif set(cropped_sides) == {\"left\", \"right\"}:\n", " # Logic for handling images cropped on both left and right sides\n", " new_width = target_width # Expand to full width of canvas\n", " \n", " # Calculate the aspect ratio of the original image\n", " aspect_ratio = image.width / image.height\n", " \n", " # Calculate the new height while maintaining aspect ratio\n", " new_height = int(new_width / aspect_ratio)\n", " \n", " # Resize the image\n", " image = image.resize((new_width, new_height), Image.LANCZOS)\n", " log.append({\"action\": \"resize\", \"new_width\": str(new_width), \"new_height\": str(new_height)})\n", " \n", " # Set horizontal position (always 0 as it spans full width)\n", " x = 0\n", " \n", " # Calculate vertical position to respect bottom padding\n", " y = target_height - new_height - padding_bottom\n", " \n", " # If the resized image is taller than the canvas, crop from the top only\n", " if new_height > target_height - padding_bottom:\n", " crop_top = new_height - (target_height - padding_bottom)\n", " image = image.crop((0, crop_top, new_width, new_height))\n", " new_height = target_height - padding_bottom\n", " y = 0\n", " log.append({\"action\": \"crop_vertical\", \"top_pixels_removed\": str(crop_top)})\n", " else:\n", " # Align the image to the bottom with padding\n", " y = target_height - new_height - padding_bottom\n", " \n", " log.append({\"action\": \"position\", \"x\": str(x), \"y\": str(y)})\n", " elif cropped_sides == [\"bottom\"]:\n", " # Logic for handling images cropped on the bottom side\n", " # Calculate the aspect ratio of the original image\n", " aspect_ratio = image.width / image.height\n", " \n", " if aspect_ratio < 1: # Portrait orientation\n", " new_height = target_height - padding_top # Full height with top padding\n", " new_width = int(new_height * aspect_ratio)\n", " \n", " # If the new width exceeds the canvas width, adjust it\n", " if new_width > target_width:\n", " new_width = target_width\n", " new_height = int(new_width / aspect_ratio)\n", " else: # Landscape orientation\n", " new_width = target_width - padding_left - padding_right\n", " new_height = int(new_width / aspect_ratio)\n", " \n", " # If the new height exceeds the canvas height, adjust it\n", " if new_height > target_height:\n", " new_height = target_height\n", " new_width = int(new_height * aspect_ratio)\n", " \n", " # Resize the image\n", " image = image.resize((new_width, new_height), Image.LANCZOS)\n", " log.append({\"action\": \"resize\", \"new_width\": str(new_width), \"new_height\": str(new_height)})\n", " \n", " # Set horizontal position (centered)\n", " x = (target_width - new_width) // 2\n", " \n", " # Set vertical position (touching bottom edge for all cases)\n", " y = target_height - new_height\n", " \n", " log.append({\"action\": \"position\", \"x\": str(x), \"y\": str(y)})\n", " else:\n", " # Use the original resizing logic for other partially cropped images\n", " if image.width > image.height:\n", " new_width = target_width\n", " new_height = int(target_width / aspect_ratio)\n", " else:\n", " new_height = target_height\n", " new_width = int(target_height * aspect_ratio)\n", " \n", " # Resize the image\n", " image = image.resize((new_width, new_height), Image.LANCZOS)\n", " log.append({\"action\": \"resize\", \"new_width\": str(new_width), \"new_height\": str(new_height)})\n", " \n", " # Center horizontally for all images\n", " x = (target_width - new_width) // 2\n", " y = target_height - new_height - padding_bottom\n", " \n", " # Adjust positions for cropped sides\n", " if \"top\" in cropped_sides:\n", " y = 0\n", " elif \"bottom\" in cropped_sides:\n", " y = target_height - new_height\n", " if \"left\" in cropped_sides:\n", " x = 0\n", " elif \"right\" in cropped_sides:\n", " x = target_width - new_width\n", " \n", " # Apply padding only to non-cropped sides, but keep horizontal centering\n", " if \"left\" not in cropped_sides and \"right\" not in cropped_sides:\n", " x = (target_width - new_width) // 2 # Always center horizontally\n", " if \"top\" not in cropped_sides and \"bottom\" not in cropped_sides:\n", " y = max(padding_top, min(y, target_height - new_height - padding_bottom))\n", "\n", " return log, image, x, y\n", "\n" ] }, { "cell_type": "code", "execution_count": 233, "id": "76ca7d68-810c-4cac-a9a2-838f0a08e6fb", "metadata": {}, "outputs": [], "source": [ "def watermark_with_transparency(image, watermark_image_path): \n", " watermark = Image.open(watermark_image_path).convert(\"RGBA\")\n", " width, height = image.size\n", "\n", " # Resize watermark if it doesn't match the canvas size\n", " if watermark.size != image.size:\n", " watermark = watermark.resize(image.size, Image.LANCZOS)\n", " \n", " #Create new canvas and put the watermark on it \n", " transparent = Image.new('RGBA', (width, height), (0,0,0,0))\n", "\n", " # Paste the image to the watermark\n", " transparent.paste(watermark, ((transparent.width - watermark.width) // 2 , (transparent.width - watermark.height) // 2), watermark)\n", " # Paste the watermark to the image\n", " transparent.paste(image, ((transparent.width - width) // 2 , (transparent.width - height) // 2), image)\n", "\n", " \n", " return transparent\n", "\n" ] }, { "cell_type": "code", "execution_count": 234, "id": "5d368688-3579-4fa4-b129-e899fa42fbce", "metadata": { "tags": [] }, "outputs": [], "source": [ "def process_single_image(image_path, output_folder, bg_method, canvas_size_name, output_format, bg_choice, custom_color, watermark_path=None):\n", " add_padding_line = False\n", "\n", " if canvas_size_name == 'Rox':\n", " canvas_size = (1080, 1080)\n", " padding_top = 112\n", " padding_right = 125\n", " padding_bottom = 116\n", " padding_left = 125\n", " elif canvas_size_name == 'Columbia':\n", " canvas_size = (730, 610)\n", " padding_top = 30\n", " padding_right = 105\n", " padding_bottom = 35\n", " padding_left = 105\n", " elif canvas_size_name == 'Zalora':\n", " canvas_size = (763, 1100)\n", " padding_top = 50\n", " padding_right = 50\n", " padding_bottom = 200\n", " padding_left = 50\n", "\n", "\n", " filename = os.path.basename(image_path)\n", " try:\n", " print(f\"Processing image: {filename}\")\n", " if bg_method == 'rembg':\n", " image_with_no_bg = remove_background_rembg(image_path)\n", " elif bg_method == 'bria':\n", " image_with_no_bg = remove_background_bria(image_path)\n", " else:\n", " image_with_no_bg = Image.open(image_path).convert(\"RGBA\")\n", " \n", " temp_image_path = os.path.join(output_folder, f\"temp_{filename}\")\n", " image_with_no_bg.save(temp_image_path, format='PNG')\n", "\n", " log, new_image, x, y = position_logic(temp_image_path, canvas_size, padding_top, padding_right, padding_bottom, padding_left)\n", "\n", " # Create a new canvas with the appropriate background\n", " if bg_choice == 'white':\n", " canvas = Image.new(\"RGBA\", canvas_size, \"WHITE\")\n", " canvas.putalpha(120)\n", " canvas.paste(new_image, (x, y), new_image)\n", " \n", " elif bg_choice == 'custom':\n", " canvas = Image.new(\"RGBA\", canvas_size, custom_color)\n", " canvas.putalpha(120) \n", " canvas.paste(new_image, (x, y), new_image)\n", " \n", " elif bg_choice == \"blur\":\n", " # Create a blurred version of the entire image\n", " blurred = Image.open(image_path).convert(\"RGBA\")\n", " blurred = blurred.filter(ImageFilter.GaussianBlur(10))\n", " blurred = blurred.resize(new_image.size, Image.LANCZOS)\n", " # Resize the blurred image to fit the canvas\n", " canvas = blurred\n", " canvas.putalpha(90)\n", " canvas.paste(new_image, (0,0), new_image)\n", " \n", " else: # transparent\n", " canvas = Image.new(\"RGBA\", canvas_size, (0, 0, 0, 0))\n", " canvas.paste(new_image, (x, y), new_image)\n", " \n", " log.append({\"action\": \"paste\", \"position\": [str(x), str(y)]})\n", " \n", "\n", " # Add visible black line for padding when background is not transparent\n", " if add_padding_line:\n", " draw = ImageDraw.Draw(canvas)\n", " draw.rectangle([padding_left, padding_top, canvas_size[0] - padding_right, canvas_size[1] - padding_bottom], outline=\"black\", width=5)\n", " log.append({\"action\": \"add_padding_line\"})\n", "\n", " output_ext = 'jpg' if output_format == 'JPG' else 'png'\n", " output_filename = f\"{os.path.splitext(filename)[0]}.{output_ext}\"\n", " output_path = os.path.join(output_folder, output_filename)\n", " \n", " # Applying the watermark, if exist\n", " if watermark_path:\n", " try:\n", " canvas = watermark_with_transparency(canvas, watermark_path)\n", " log.append({\"action\": \"add_watermark\"})\n", " \n", " except Exception as e:\n", " print(f\"Error processing watermark: {e}\")\n", "\n", "\n", " output_ext = 'jpg' if output_format == 'JPG' else 'png'\n", " output_filename = f\"{os.path.splitext(filename)[0]}.{output_ext}\"\n", " output_path = os.path.join(output_folder, output_filename)\n", "\n", " if output_format == 'JPG':\n", " canvas.convert('RGB').save(output_path, format='JPEG')\n", " else:\n", " canvas.save(output_path, format='PNG')\n", " \n", " os.remove(temp_image_path)\n", "\n", " print(f\"Processed image path: {output_path}\")\n", " return [(output_path, image_path)], log\n", "\n", " except Exception as e:\n", " print(f\"Error processing {filename}: {e}\")\n", " return None, None\n", "\n", "######################################## WATERMARK PATH #############################################################\n", " \n", " \n", "def process_images(input_files, bg_method='rembg', watermark_path=None, canvas_size='Rox', output_format='PNG', bg_choice='transparent', custom_color=\"#ffffff\", num_workers=4, progress=gr.Progress()):\n", " start_time = time.time()\n", "\n", " output_folder = \"processed_images\"\n", " if os.path.exists(output_folder):\n", " shutil.rmtree(output_folder)\n", " os.makedirs(output_folder)\n", "\n", " processed_images = []\n", " original_images = []\n", " all_logs = []\n", "\n", " if isinstance(input_files, str) and input_files.lower().endswith(('.zip', '.rar')):\n", " # Handle zip file\n", " input_folder = \"temp_input\"\n", " if os.path.exists(input_folder):\n", " shutil.rmtree(input_folder)\n", " os.makedirs(input_folder)\n", " \n", " try:\n", " with zipfile.ZipFile(input_files, 'r') as zip_ref:\n", " zip_ref.extractall(input_folder)\n", " except zipfile.BadZipFile as e:\n", " print(f\"Error extracting zip file: {e}\")\n", " return [], None, 0\n", " \n", " image_files = [os.path.join(input_folder, f) for f in os.listdir(input_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp'))]\n", " elif isinstance(input_files, list):\n", " # Handle multiple files\n", " image_files = input_files\n", " else:\n", " # Handle single file\n", " image_files = [input_files]\n", "\n", " total_images = len(image_files)\n", " print(f\"Total images to process: {total_images}\")\n", "\n", " avg_processing_time = 0\n", " with ThreadPoolExecutor(max_workers=num_workers) as executor:\n", " future_to_image = {executor.submit(process_single_image, image_path, output_folder, bg_method, canvas_size, output_format, bg_choice, custom_color, watermark_path): image_path for image_path in image_files}\n", " for idx, future in enumerate(future_to_image):\n", " try:\n", " start_time_image = time.time()\n", " result, log = future.result()\n", " end_time_image = time.time()\n", " image_processing_time = end_time_image - start_time_image\n", " \n", " # Update average processing time\n", " avg_processing_time = (avg_processing_time * idx + image_processing_time) / (idx + 1)\n", " \n", " if result:\n", " processed_images.extend(result)\n", " original_images.append(future_to_image[future])\n", " \n", " all_logs.append({os.path.basename(future_to_image[future]): log})\n", " \n", " # Estimate remaining time\n", " remaining_images = total_images - (idx + 1)\n", " estimated_remaining_time = remaining_images * avg_processing_time\n", " \n", " progress((idx + 1) / total_images, f\"{idx + 1}/{total_images} images processed. Estimated time remaining: {estimated_remaining_time:.2f} seconds\")\n", " except Exception as e:\n", " print(f\"Error processing image {future_to_image[future]}: {e}\")\n", "\n", " output_zip_path = \"processed_images.zip\"\n", " with zipfile.ZipFile(output_zip_path, 'w') as zipf:\n", " for file, _ in processed_images:\n", " zipf.write(file, os.path.basename(file))\n", "\n", " # Write the comprehensive log for all images\n", " with open(os.path.join(output_folder, 'process_log.json'), 'w') as log_file:\n", " json.dump(all_logs, log_file, indent=4)\n", " print(\"Comprehensive log saved to\", os.path.join(output_folder, 'process_log.json'))\n", "\n", " end_time = time.time()\n", " processing_time = end_time - start_time\n", " print(f\"Processing time: {processing_time} seconds\")\n", "\n", "\n", " input_path = processed_images[0][1]\n", " output_path = processed_images[0][0]\n", " print(f\"{processed_images} | {input_path} | {output_path} | WATERMARK OBJECT: {watermark_path}\")\n", "\n", "\n", " return original_images, processed_images, output_zip_path, processing_time" ] }, { "cell_type": "code", "execution_count": 235, "id": "cd52ae59-8d8c-45ed-8bde-4e7ce2c4464f", "metadata": { "tags": [] }, "outputs": [], "source": [ "def gradio_interface(input_files, bg_method, watermark, canvas_size, output_format, bg_choice, custom_color, num_workers):\n", " progress = gr.Progress()\n", " watermark_path = watermark.name if watermark else None\n", " \n", " # Check input_files, is it single image, list image, or zip/rar\n", " if isinstance(input_files, str) and input_files.lower().endswith(('.zip', '.rar')):\n", " return process_images(input_files, bg_method, watermark_path, canvas_size, output_format, bg_choice, custom_color, num_workers, progress)\n", " elif isinstance(input_files, list):\n", " return process_images(input_files, bg_method, watermark_path, canvas_size, output_format, bg_choice, custom_color, num_workers, progress)\n", " else:\n", " return process_images(input_files.name, bg_method, watermark_path, canvas_size, output_format, bg_choice, custom_color, num_workers, progress)\n", "\n", "def show_color_picker(bg_choice):\n", " if bg_choice == 'custom':\n", " return gr.update(visible=True)\n", " return gr.update(visible=False)\n", "\n", "def update_compare(evt: gr.SelectData):\n", " print(f\"Selected value: {evt.value}\") # Debug print\n", " \n", " try:\n", " if isinstance(evt.value, list) and len(evt.value) == 2:\n", " _, combined_path = evt.value\n", " if '|' in combined_path:\n", " output_path, input_path = combined_path.split('|')\n", " else:\n", " raise ValueError(f\"Unexpected format in second element: {combined_path}\")\n", " elif isinstance(evt.value, str):\n", " if '|' in evt.value:\n", " output_path, input_path = evt.value.split('|')\n", " else:\n", " raise ValueError(f\"Unexpected string format: {evt.value}\")\n", " else:\n", " raise ValueError(f\"Unexpected input format: {evt.value}\")\n", " \n", " # Remove any URL prefix from the paths\n", " output_path = output_path.split('=')[-1] if '=' in output_path else output_path\n", " input_path = input_path.split('=')[-1] if '=' in input_path else input_path\n", " \n", " # Open the original and processed images\n", " original_img = Image.open(input_path)\n", " processed_img = Image.open(output_path)\n", " \n", " # Calculate the aspect ratios\n", " original_ratio = f\"{original_img.width}x{original_img.height}\"\n", " processed_ratio = f\"{processed_img.width}x{processed_img.height}\"\n", " \n", " print(f\"Successfully processed. Input: {input_path}, Output: {output_path}\")\n", " return gr.update(value=input_path), gr.update(value=output_path), gr.update(value=original_ratio), gr.update(value=processed_ratio)\n", " except Exception as e:\n", " print(f\"Error in update_compare: {e}\")\n", " return gr.update(value=None), gr.update(value=None), gr.update(value=None), gr.update(value=None)\n", " \n", "def process(input_files, bg_method, watermark, canvas_size, output_format, bg_choice, custom_color, num_workers):\n", " _, processed_images, zip_path, time_taken = gradio_interface(input_files, bg_method, watermark, canvas_size, output_format, bg_choice, custom_color, num_workers)\n", " processed_images_with_captions = [\n", " [f\"{img}\", f\"{img}|{caption}\"] # Format to match the observed structure\n", " for img, caption in processed_images\n", " ]\n", " return processed_images_with_captions, zip_path, f\"{time_taken:.2f} seconds\"" ] }, { "cell_type": "code", "execution_count": 236, "id": "21f056e3-95ed-44d2-82f9-3551beda4f97", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running on local URL: http://127.0.0.1:7924\n", "\n", "To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "