aiqtech commited on
Commit
6110eef
·
verified ·
1 Parent(s): 07b7498

Update app-backup.py

Browse files
Files changed (1) hide show
  1. app-backup.py +61 -24
app-backup.py CHANGED
@@ -524,17 +524,18 @@ def add_text_to_image(
524
  opacity,
525
  x_position,
526
  y_position,
527
- thickness
 
 
528
  ):
529
  """
530
  Add text to an image with customizable properties
531
  """
532
  try:
533
- # 입력 이미지 처리 수정
534
  if input_image is None:
535
  return None
536
 
537
- # PIL Image 객체로 변환 (이미 PIL Image인 경우 그대로 사용)
538
  if not isinstance(input_image, Image.Image):
539
  if isinstance(input_image, np.ndarray):
540
  image = Image.fromarray(input_image)
@@ -547,21 +548,34 @@ def add_text_to_image(
547
  if image.mode != 'RGBA':
548
  image = image.convert('RGBA')
549
 
550
- # Create a transparent overlay for the text
 
 
 
 
 
551
  txt_overlay = Image.new('RGBA', image.size, (255, 255, 255, 0))
552
  draw = ImageDraw.Draw(txt_overlay)
553
 
554
- # Create a font with specified size
 
 
 
 
 
 
555
  try:
556
- font = ImageFont.truetype("DejaVuSans.ttf", int(font_size))
557
- except:
 
 
558
  try:
559
  font = ImageFont.truetype("arial.ttf", int(font_size))
560
  except:
561
  print("Using default font")
562
  font = ImageFont.load_default()
563
 
564
- # Convert color name to RGB
565
  color_map = {
566
  'White': (255, 255, 255),
567
  'Black': (0, 0, 0),
@@ -573,19 +587,19 @@ def add_text_to_image(
573
  }
574
  rgb_color = color_map.get(color, (255, 255, 255))
575
 
576
- # Get text size for positioning
577
  text_bbox = draw.textbbox((0, 0), text, font=font)
578
  text_width = text_bbox[2] - text_bbox[0]
579
  text_height = text_bbox[3] - text_bbox[1]
580
 
581
- # Calculate actual positions
582
  actual_x = int((image.width - text_width) * (x_position / 100))
583
  actual_y = int((image.height - text_height) * (y_position / 100))
584
 
585
- # Create final color with opacity
586
  text_color = (*rgb_color, int(opacity))
587
 
588
- # Draw text with stroke
589
  add_text_with_stroke(
590
  draw,
591
  text,
@@ -596,23 +610,29 @@ def add_text_to_image(
596
  int(thickness)
597
  )
598
 
599
- # Combine the original image with the text overlay
600
- output_image = Image.alpha_composite(image, txt_overlay)
 
 
 
 
 
601
 
602
- # Convert back to RGB for display
603
  output_image = output_image.convert('RGB')
604
 
605
  return output_image
606
 
607
  except Exception as e:
608
  print(f"Error in add_text_to_image: {str(e)}")
609
- return input_image # 에러 발생 시 원본 이미지 반환
 
610
 
611
  with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
612
  gr.HTML("""
613
  <div class="main-title">
614
- <h1>🎨GiniGen Canvas</h1>
615
- <p>AI Integrated Image Creator: Extract objects, generate backgrounds, and adjust ratios and positions to create complete images with AI.</p>
616
  </div>
617
  """)
618
 
@@ -686,12 +706,27 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
686
  # 텍스트 삽입 컨트롤을 더 명확하게 구분
687
  with gr.Group():
688
  gr.Markdown("### Add Text to Image")
689
- text_input = gr.Textbox(
690
- label="Text Content",
691
- placeholder="Enter text to add to image..."
692
- )
 
 
 
 
 
 
 
 
693
  with gr.Row():
694
  with gr.Column(scale=1):
 
 
 
 
 
 
 
695
  font_size = gr.Slider(
696
  minimum=10,
697
  maximum=200,
@@ -801,7 +836,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
801
  queue=True
802
  )
803
 
804
- # 텍스트 추가 버튼 이벤트 연결
805
  add_text_btn.click(
806
  fn=add_text_to_image,
807
  inputs=[
@@ -812,7 +847,9 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
812
  opacity_slider,
813
  x_position,
814
  y_position,
815
- thickness
 
 
816
  ],
817
  outputs=combined_image
818
  )
 
524
  opacity,
525
  x_position,
526
  y_position,
527
+ thickness,
528
+ text_position_type,
529
+ font_choice # 새로운 파라미터 추가
530
  ):
531
  """
532
  Add text to an image with customizable properties
533
  """
534
  try:
 
535
  if input_image is None:
536
  return None
537
 
538
+ # PIL Image 객체로 변환
539
  if not isinstance(input_image, Image.Image):
540
  if isinstance(input_image, np.ndarray):
541
  image = Image.fromarray(input_image)
 
548
  if image.mode != 'RGBA':
549
  image = image.convert('RGBA')
550
 
551
+ # Text Behind Image 처리
552
+ if text_position_type == "Text Behind Image":
553
+ # 원본 이미지의 배경 제거
554
+ overlay_image = remove_background(image)
555
+
556
+ # 텍스트 오버레이 생성
557
  txt_overlay = Image.new('RGBA', image.size, (255, 255, 255, 0))
558
  draw = ImageDraw.Draw(txt_overlay)
559
 
560
+ # 폰트 설정
561
+ font_files = {
562
+ "Default": "DejaVuSans.ttf",
563
+ "Korean Regular": "ko-Regular.ttf",
564
+ "Korean Son": "ko-son.ttf"
565
+ }
566
+
567
  try:
568
+ font_file = font_files.get(font_choice, "DejaVuSans.ttf")
569
+ font = ImageFont.truetype(font_file, int(font_size))
570
+ except Exception as e:
571
+ print(f"Font loading error ({font_choice}): {str(e)}")
572
  try:
573
  font = ImageFont.truetype("arial.ttf", int(font_size))
574
  except:
575
  print("Using default font")
576
  font = ImageFont.load_default()
577
 
578
+ # 색상 설정
579
  color_map = {
580
  'White': (255, 255, 255),
581
  'Black': (0, 0, 0),
 
587
  }
588
  rgb_color = color_map.get(color, (255, 255, 255))
589
 
590
+ # 텍스트 크기 계산
591
  text_bbox = draw.textbbox((0, 0), text, font=font)
592
  text_width = text_bbox[2] - text_bbox[0]
593
  text_height = text_bbox[3] - text_bbox[1]
594
 
595
+ # 위치 계산
596
  actual_x = int((image.width - text_width) * (x_position / 100))
597
  actual_y = int((image.height - text_height) * (y_position / 100))
598
 
599
+ # 텍스트 색상 설정
600
  text_color = (*rgb_color, int(opacity))
601
 
602
+ # 텍스트 그리기
603
  add_text_with_stroke(
604
  draw,
605
  text,
 
610
  int(thickness)
611
  )
612
 
613
+ if text_position_type == "Text Behind Image":
614
+ # 텍스트를 먼저 그리고 그 위에 이미지 오버레이
615
+ output_image = Image.alpha_composite(image, txt_overlay)
616
+ output_image = superimpose(output_image, overlay_image)
617
+ else:
618
+ # 기존 방식대로 텍스트를 이미지 위에 그리기
619
+ output_image = Image.alpha_composite(image, txt_overlay)
620
 
621
+ # RGB 변환
622
  output_image = output_image.convert('RGB')
623
 
624
  return output_image
625
 
626
  except Exception as e:
627
  print(f"Error in add_text_to_image: {str(e)}")
628
+ return input_image
629
+
630
 
631
  with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
632
  gr.HTML("""
633
  <div class="main-title">
634
+ <h1>🎨GiniGen Canvas-o3</h1>
635
+ <p>Remove background of specified objects, generate new backgrounds, and insert text over or behind images with prompts.</p>
636
  </div>
637
  """)
638
 
 
706
  # 텍스트 삽입 컨트롤을 더 명확하게 구분
707
  with gr.Group():
708
  gr.Markdown("### Add Text to Image")
709
+ with gr.Row():
710
+ text_input = gr.Textbox(
711
+ label="Text Content",
712
+ placeholder="Enter text to add to image..."
713
+ )
714
+ text_position_type = gr.Radio(
715
+ choices=["Text Over Image", "Text Behind Image"],
716
+ value="Text Over Image",
717
+ label="Text Position Type",
718
+ interactive=True
719
+ )
720
+
721
  with gr.Row():
722
  with gr.Column(scale=1):
723
+ # 폰트 선택 Dropdown 추가
724
+ font_choice = gr.Dropdown(
725
+ choices=["Default", "Korean Regular", "Korean Son"],
726
+ value="Default",
727
+ label="Font Selection",
728
+ interactive=True
729
+ )
730
  font_size = gr.Slider(
731
  minimum=10,
732
  maximum=200,
 
836
  queue=True
837
  )
838
 
839
+ # 텍스트 추가 버튼 이벤트 연결 수정
840
  add_text_btn.click(
841
  fn=add_text_to_image,
842
  inputs=[
 
847
  opacity_slider,
848
  x_position,
849
  y_position,
850
+ thickness,
851
+ text_position_type,
852
+ font_choice # 새로운 입력 추가
853
  ],
854
  outputs=combined_image
855
  )