muhammadsalmanalfaridzi commited on
Commit
235ace7
β€’
1 Parent(s): 5ba039a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -201
app.py CHANGED
@@ -32,7 +32,7 @@ def remove_background_rembg(input_path):
32
 
33
  def remove_background_bria(input_path):
34
  print(f"Removing background using bria for image: {input_path}")
35
- pipe = pipeline("image-segmentation", model="briaai/RMBG-1.4", trust_remote_code=True, device=1)
36
  pillow_image = pipe(input_path)
37
  return pillow_image
38
 
@@ -52,58 +52,26 @@ def text_image_to_image(image, prompt):
52
  modified_image.save(image_path)
53
  return modified_image, image_path
54
 
55
- def process_images(image_paths, remove_bg_method):
56
- with ThreadPoolExecutor() as executor:
57
- if remove_bg_method == 'rembg':
58
- results = list(executor.map(remove_background_rembg, image_paths))
59
- elif remove_bg_method == 'bria':
60
- results = list(executor.map(remove_background_bria, image_paths))
61
- else: # No background removal
62
- results = image_paths # Just return the original paths
63
- return results
64
-
65
  def get_bounding_box_with_threshold(image, threshold):
 
66
  img_array = np.array(image)
 
 
67
  alpha = img_array[:, :, 3]
68
 
 
69
  rows = np.any(alpha > threshold, axis=1)
70
  cols = np.any(alpha > threshold, axis=0)
71
 
72
- try:
73
- top, bottom = np.where(rows)[0][[0, -1]]
74
- left, right = np.where(cols)[0][[0, -1]]
75
- except IndexError:
76
- return None # No non-transparent pixels found
77
 
78
- return (left, top, right, bottom) if left < right and top < bottom else None
79
-
80
- def check_cropped_sides(image, tolerance):
81
- cropped_sides = []
82
- width, height = image.size
83
- edges = {
84
- "top": [(x, 0) for x in range(width)],
85
- "bottom": [(x, height - 1) for x in range(width)],
86
- "left": [(0, y) for y in range(height)],
87
- "right": [(width - 1, y) for y in range(height)]
88
- }
89
-
90
- for side, pixels in edges.items():
91
- if any(image.getpixel(pixel)[3] > tolerance for pixel in pixels):
92
- cropped_sides.append(side)
93
-
94
- return cropped_sides
95
-
96
- def resize_image(image, target_size, aspect_ratio):
97
- target_width, target_height = target_size
98
- if aspect_ratio > 1: # Landscape
99
- new_height = target_height
100
- new_width = int(new_height * aspect_ratio)
101
- else: # Portrait or square
102
- new_width = target_width
103
- new_height = int(new_width / aspect_ratio)
104
-
105
- return image.resize((new_width, new_height), Image.LANCZOS), new_width, new_height
106
-
107
  def position_logic(image_path, canvas_size, padding_top, padding_right, padding_bottom, padding_left, use_threshold=True):
108
  image = Image.open(image_path)
109
  image = image.convert("RGBA")
@@ -400,14 +368,6 @@ def position_logic(image_path, canvas_size, padding_top, padding_right, padding_
400
 
401
  return log, image, x, y
402
 
403
- def get_canvas_size(canvas_size_name):
404
- sizes = {
405
- 'Rox': ((1080, 1080), (112, 125, 116, 125)),
406
- 'Columbia': ((730, 610), (30, 105, 35, 105)),
407
- 'Zalora': ((763, 1100), (50, 50, 200, 50)),
408
- }
409
- return sizes.get(canvas_size_name, ((1080, 1080), (0, 0, 0, 0)))
410
-
411
  def process_single_image(image_path, output_folder, bg_method, canvas_size_name, output_format, bg_choice, custom_color, watermark_path=None):
412
  add_padding_line = False
413
 
@@ -484,59 +444,6 @@ def process_single_image(image_path, output_folder, bg_method, canvas_size_name,
484
  except Exception as e:
485
  print(f"Error processing {filename}: {e}")
486
  return None, None
487
-
488
- def create_canvas(canvas_size, bg_choice, custom_color):
489
- if bg_choice == 'white':
490
- return Image.new("RGBA", canvas_size, "WHITE")
491
- elif bg_choice == 'custom':
492
- return Image.new("RGBA", canvas_size, custom_color)
493
- else: # transparent
494
- return Image.new("RGBA", canvas_size, (0, 0, 0, 0))
495
-
496
- # Function to add watermark
497
- def generate_image(prompt):
498
- # Code to generate an image using Stable Diffusion
499
- # Placeholder: Replace with actual image generation code
500
- response = requests.get("URL_OF_GENERATED_IMAGE") # Replace with the actual URL or generation method
501
- img = Image.open(BytesIO(response.content))
502
- return img
503
-
504
- def add_watermark(image, watermark_path):
505
- watermark = Image.open(watermark_path).convert("RGBA")
506
-
507
- # Resize watermark if needed
508
- watermark = watermark.resize((image.width // 4, image.height // 4), Image.ANTIALIAS)
509
-
510
- # Position watermark in the center
511
- position = ((image.width - watermark.width) // 2, (image.height - watermark.height) // 2)
512
-
513
- # Composite the watermark onto the image
514
- transparent = Image.new('RGBA', image.size, (0, 0, 0, 0))
515
- transparent.paste(image, (0, 0))
516
- transparent.paste(watermark, position, watermark)
517
-
518
- return transparent
519
-
520
- def process_image(prompt, watermark_path, bg_removal_choice):
521
- image = generate_image(prompt)
522
-
523
- if bg_removal_choice == "none":
524
- final_image = image
525
- else:
526
- # Placeholder for actual background removal code
527
- final_image = image # Replace with background removal logic
528
-
529
- final_image_with_watermark = add_watermark(final_image, watermark_path)
530
- return final_image_with_watermark
531
-
532
- def save_image(canvas, output_folder, filename, output_format):
533
- output_ext = 'jpg' if output_format == 'JPG' else 'png'
534
- output_path = os.path.join(output_folder, f"{os.path.splitext(filename)[0]}.{output_ext}")
535
- if output_format == 'JPG':
536
- canvas.convert('RGB').save(output_path, format='JPEG')
537
- else:
538
- canvas.save(output_path, format='PNG')
539
- return output_path
540
 
541
  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()):
542
  start_time = time.time()
@@ -599,32 +506,7 @@ def process_images(input_files, bg_method='rembg', watermark_path=None, canvas_s
599
  print(f"Error processing image {future_to_image[future]}: {e}")
600
 
601
  output_zip_path = "processed_images.zip"
602
- # Handle uploaded files
603
- if isinstance(input_files, list):
604
- images = [Image.open(file.name) for file in input_files]
605
- else:
606
- with zipfile.ZipFile(input_files.name, 'r') as zip_ref:
607
- zip_ref.extractall("extracted_images")
608
- images = [Image.open(os.path.join("extracted_images", f)) for f in os.listdir("extracted_images")]
609
-
610
- # Background removal logic (placeholder)
611
- for img in images:
612
- # Implement background removal based on selected method
613
- if bg_method == "rembg":
614
- img = remove_background_with_rembg(img) # Placeholder function
615
- elif bg_method == "bria":
616
- img = remove_background_with_bria(img) # Placeholder function
617
-
618
- # Add watermark if provided
619
- if watermark:
620
- watermark_img = Image.open(watermark.name).convert("RGBA")
621
- img = add_watermark(img, watermark_img)
622
-
623
- # Save processed image
624
- output_path = f"processed_{len(processed_images)}.{output_format.lower()}"
625
- img.save(output_path, format=output_format)
626
- processed_images.append(output_path)
627
-
628
  # Create a zip file of processed images
629
  with zipfile.ZipFile(output_zip_path, 'w') as zipf:
630
  for processed_img in processed_images:
@@ -632,75 +514,6 @@ def process_images(input_files, bg_method='rembg', watermark_path=None, canvas_s
632
 
633
  return processed_images, output_zip_path
634
 
635
- def add_watermark(image, watermark):
636
- # Resize and position watermark
637
- watermark = watermark.resize((image.width // 4, image.height // 4), Image.ANTIALIAS)
638
- position = ((image.width - watermark.width) // 2, (image.height - watermark.height) // 2)
639
-
640
- transparent = Image.new('RGBA', image.size, (0, 0, 0, 0))
641
- transparent.paste(image.convert("RGBA"), (0, 0))
642
- transparent.paste(watermark, position, watermark)
643
-
644
- return transparent.convert("RGB")
645
-
646
- def remove_background_with_rembg(image):
647
- # Placeholder for actual background removal code
648
- return image # Replace with actual removal logic
649
-
650
- def remove_background_with_bria(image):
651
- # Placeholder for actual background removal code
652
- return image # Replace with actual removal logic
653
-
654
- def show_color_picker(bg_choice):
655
- return bg_choice == "custom"
656
-
657
- def update_compare(selected_image):
658
- # Logic to display original vs processed images
659
- return selected_image, selected_image # Replace with actual images
660
-
661
- with zipfile.ZipFile(output_zip_path, 'w') as zipf:
662
- for file, _ in processed_images:
663
- zipf.write(file, os.path.basename(file))
664
-
665
- # Write the comprehensive log for all images
666
- with open(os.path.join(output_folder, 'process_log.json'), 'w') as log_file:
667
- json.dump(all_logs, log_file, indent=4)
668
- print("Comprehensive log saved to", os.path.join(output_folder, 'process_log.json'))
669
-
670
- end_time = time.time()
671
- processing_time = end_time - start_time
672
- print(f"Processing time: {processing_time} seconds")
673
-
674
- return original_images, processed_images, output_zip_path, processing_time
675
-
676
- def extract_image_files(input_files):
677
- if isinstance(input_files, str) and input_files.lower().endswith(('.zip', '.rar')):
678
- input_folder = "temp_input"
679
- if os.path.exists(input_folder):
680
- shutil.rmtree(input_folder)
681
- os.makedirs(input_folder)
682
-
683
- with zipfile.ZipFile(input_files, 'r') as zip_ref:
684
- zip_ref.extractall(input_folder)
685
-
686
- return [os.path.join(input_folder, f) for f in os.listdir(input_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp'))]
687
- elif isinstance(input_files, list):
688
- return input_files
689
- else:
690
- return [input_files]
691
-
692
- def create_output_zip(processed_images):
693
- output_zip_path = "processed_images.zip"
694
- with zipfile.ZipFile(output_zip_path, 'w') as zipf:
695
- for file, _ in processed_images:
696
- zipf.write(file, os.path.basename(file))
697
- return output_zip_path
698
-
699
- def save_log(all_logs, output_folder):
700
- with open(os.path.join(output_folder, 'process_log.json'), 'w') as log_file:
701
- json.dump(all_logs, log_file, indent=4)
702
- print("Comprehensive log saved to", os.path.join(output_folder, 'process_log.json'))
703
-
704
  def gradio_interface(input_files, bg_method, watermark, canvas_size, output_format, bg_choice, custom_color, num_workers):
705
  progress = gr.Progress()
706
  watermark_path = watermark.name if watermark else None
 
32
 
33
  def remove_background_bria(input_path):
34
  print(f"Removing background using bria for image: {input_path}")
35
+ pipe = pipeline("image-segmentation", model="briaai/RMBG-1.4", trust_remote_code=True, device=0)
36
  pillow_image = pipe(input_path)
37
  return pillow_image
38
 
 
52
  modified_image.save(image_path)
53
  return modified_image, image_path
54
 
 
 
 
 
 
 
 
 
 
 
55
  def get_bounding_box_with_threshold(image, threshold):
56
+ # Convert image to numpy array
57
  img_array = np.array(image)
58
+
59
+ # Get alpha channel
60
  alpha = img_array[:, :, 3]
61
 
62
+ # Find rows and columns where alpha > threshold
63
  rows = np.any(alpha > threshold, axis=1)
64
  cols = np.any(alpha > threshold, axis=0)
65
 
66
+ # Find the bounding box
67
+ top, bottom = np.where(rows)[0][[0, -1]]
68
+ left, right = np.where(cols)[0][[0, -1]]
 
 
69
 
70
+ if left < right and top < bottom:
71
+ return (left, top, right, bottom)
72
+ else:
73
+ return None
74
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  def position_logic(image_path, canvas_size, padding_top, padding_right, padding_bottom, padding_left, use_threshold=True):
76
  image = Image.open(image_path)
77
  image = image.convert("RGBA")
 
368
 
369
  return log, image, x, y
370
 
 
 
 
 
 
 
 
 
371
  def process_single_image(image_path, output_folder, bg_method, canvas_size_name, output_format, bg_choice, custom_color, watermark_path=None):
372
  add_padding_line = False
373
 
 
444
  except Exception as e:
445
  print(f"Error processing {filename}: {e}")
446
  return None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
 
448
  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()):
449
  start_time = time.time()
 
506
  print(f"Error processing image {future_to_image[future]}: {e}")
507
 
508
  output_zip_path = "processed_images.zip"
509
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
  # Create a zip file of processed images
511
  with zipfile.ZipFile(output_zip_path, 'w') as zipf:
512
  for processed_img in processed_images:
 
514
 
515
  return processed_images, output_zip_path
516
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
  def gradio_interface(input_files, bg_method, watermark, canvas_size, output_format, bg_choice, custom_color, num_workers):
518
  progress = gr.Progress()
519
  watermark_path = watermark.name if watermark else None