Surn commited on
Commit
80b040e
·
1 Parent(s): 6dd859c

Rearrainge Blocks

Browse files
Files changed (2) hide show
  1. app.py +542 -430
  2. src/condition.py +1 -2
app.py CHANGED
@@ -2,9 +2,12 @@ import os
2
  # Import constants
3
  import numpy as np
4
  import torch
 
 
 
5
  import utils.constants as constants
6
  import gradio as gr
7
- from PIL import Image
8
  from haishoku.haishoku import Haishoku
9
 
10
  from tempfile import NamedTemporaryFile
@@ -12,7 +15,7 @@ from tempfile import NamedTemporaryFile
12
  import atexit
13
  import random
14
  import logging
15
- import accelerate
16
  from transformers import AutoTokenizer
17
  import gc
18
 
@@ -26,8 +29,8 @@ from utils.color_utils import (
26
  detect_color_format,
27
  update_color_opacity,
28
  )
29
- from utils.misc import (get_filename, pause, convert_ratio_to_dimensions, install_cuda_toolkit,install_torch, _get_output, setup_runtime_env)
30
- from utils.depth_estimation import estimate_depth, create_3d_model, generate_depth_and_3d, generate_depth_button_click
31
 
32
  from utils.image_utils import (
33
  change_color,
@@ -40,7 +43,8 @@ from utils.image_utils import (
40
  apply_lut_to_image_path,
41
  multiply_and_blend_images,
42
  alpha_composite_with_control,
43
- crop_and_resize_image
 
44
  )
45
 
46
  from utils.hex_grid import (
@@ -64,7 +68,7 @@ from utils.version_info import (
64
  versions_html,
65
  #initialize_cuda,
66
  #release_torch_resources,
67
- get_torch_info
68
  )
69
  from utils.lora_details import (
70
  upd_prompt_notes,
@@ -179,6 +183,117 @@ def get_model_and_lora(model_textbox):
179
  default_model = model_textbox
180
  return default_model, []
181
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  @spaces.GPU(progress=gr.Progress(track_tqdm=True))
183
  def generate_image_lowmem(
184
  text,
@@ -206,7 +321,7 @@ def generate_image_lowmem(
206
 
207
  #initialize_cuda()
208
  device = "cuda" if torch.cuda.is_available() else "cpu"
209
- from src.condition import Condition
210
 
211
  print(f"device:{device}\nmodel_name:{model_name}\nlora_weights:{lora_weights}\n")
212
  #print(f"\n {get_torch_info()}\n")
@@ -481,7 +596,7 @@ def generate_ai_image_local (
481
  gc.collect()
482
  return None
483
 
484
- @spaces.GPU(duration=140,progress=gr.Progress(track_tqdm=True))
485
  def generate_input_image_click(map_option, prompt_textbox_value, negative_prompt_textbox_value, model_textbox_value, randomize_seed=True, seed=None, use_conditioned_image=False, strength=0.5, image_format="16:9", scale_factor=(8/3), progress=gr.Progress(track_tqdm=True)):
486
  if randomize_seed:
487
  seed = random.randint(0, constants.MAX_SEED)
@@ -566,465 +681,459 @@ def combine_images_with_lerp(input_image, output_image, alpha):
566
  return lerp_imagemath(in_image, out_image, alpha)
567
 
568
  def add_border(image, mask_width, mask_height, blank_color):
569
- #install_torch()
570
  bordered_image_output = Image.open(image).convert("RGBA")
571
  margin_color = detect_color_format(blank_color)
572
  print(f"Adding border to image with width: {mask_width}, height: {mask_height}, color: {margin_color}")
573
  return shrink_and_paste_on_blank(bordered_image_output, mask_width, mask_height, margin_color)
574
 
575
- @spaces.GPU()
576
  def getVersions():
577
  return versions_html()
 
578
  generate_input_image_click.zerogpu = True
579
- def main(debug=False):
580
- title = "HexaGrid Creator"
581
- #description = "Customizable Hexagon Grid Image Generator"
582
- examples = [["assets//examples//hex_map_p1.png", 32, 1, 0, 0, 0, 0, 0, "#ede9ac44","#12165380", True]]
583
 
584
- gr.set_static_paths(paths=["images/","images/images","images/prerendered","LUT/","fonts/"])
585
 
586
- # Gradio Blocks Interface
587
- with gr.Blocks(css_paths="style_20250128.css", title=title, theme='Surn/beeuty') as beeuty:
588
- with gr.Row():
589
- gr.Markdown("""
590
- # HexaGrid Creator
591
- ## Transform Your Images into Mesmerizing Hexagon Grid Masterpieces! ⬢""", elem_classes="intro")
592
- with gr.Row():
593
- with gr.Accordion("Welcome to HexaGrid Creator, the ultimate tool for transforming your images into stunning hexagon grid artworks. Whether you're a tabletop game enthusiast, a digital artist, or someone who loves unique patterns, HexaGrid Creator has something for you.", open=False, elem_classes="intro"):
594
- gr.Markdown ("""
595
 
596
- ## Drop an image into the Input Image and get started!
597
 
598
 
599
 
600
- ## What is HexaGrid Creator?
601
- HexaGrid Creator is a web-based application that allows you to apply a hexagon grid overlay to any image. You can customize the size, color, and opacity of the hexagons, as well as the background and border colors. The result is a visually striking image that looks like it was made from hexagonal tiles!
602
-
603
- ### What Can You Do?
604
- - **Generate Hexagon Grids:** Create beautiful hexagon grid overlays on any image with fully customizable parameters.
605
- - **AI-Powered Image Generation:** Use advanced AI models to generate images based on your prompts and apply hexagon grids to them.
606
- - **Color Exclusion:** Select and exclude specific colors from your hexagon grid for a cleaner and more refined look.
607
- - **Interactive Customization:** Adjust hexagon size, border size, rotation, background color, and more in real-time.
608
- - **Depth and 3D Model Generation:** Generate depth maps and 3D models from your images for enhanced visualization.
609
- - **Image Filter [Look-Up Table (LUT)] Application:** Apply filters (LUTs) to your images for color grading and enhancement.
610
- - **Pre-rendered Maps:** Access a library of pre-rendered hexagon maps for quick and easy customization.
611
- - **Add Margins:** Add customizable margins around your images for a polished finish.
612
-
613
- ### Why You'll Love It
614
- - **Fun and Easy to Use:** With an intuitive interface and real-time previews, creating hexagon grids has never been this fun!
615
- - **Endless Creativity:** Unleash your creativity with endless customization options and see your images transform in unique ways.
616
- - **Hexagon-Inspired Theme:** Enjoy a delightful yellow and purple theme inspired by hexagons! ⬢
617
- - **Advanced AI Models:** Leverage advanced AI models and LoRA weights for high-quality image generation and customization.
618
-
619
- ### Get Started
620
- 1. **Upload or Generate an Image:** Start by uploading your own image or generate one using our AI-powered tool.
621
- 2. **Customize Your Grid:** Play around with the settings to create the perfect hexagon grid overlay.
622
- 3. **Download and Share:** Once you're happy with your creation, download it and share it with the world!
623
-
624
- ### Advanced Features
625
- - **Generative AI Integration:** Utilize models like `black-forest-labs/FLUX.1-dev` and various LoRA weights for generating unique images.
626
- - **Pre-rendered Maps:** Access a library of pre-rendered hexagon maps for quick and easy customization.
627
- - **Image Filter [Look-Up Table (LUT)] Application:** Apply filters (LUTs) to your images for color grading and enhancement.
628
- - **Depth and 3D Model Generation:** Create depth maps and 3D models from your images for enhanced visualization.
629
- - **Add Margins:** Customize margins around your images for a polished finish.
630
-
631
- Join the hive and start creating with HexaGrid Creator today!
632
 
633
- """, elem_classes="intro")
634
- with gr.Row():
635
- from utils.image_utils import convert_to_rgba_png
636
-
637
- # Existing code
638
- with gr.Column(scale=2):
639
- input_image = gr.Image(
640
- label="Input Image",
641
- type="filepath",
642
- interactive=True,
643
- elem_classes="centered solid imgcontainer",
644
- key="imgInput",
645
- image_mode=None,
646
- format="PNG",
647
- show_download_button=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
648
  )
649
 
650
- # New code to convert input image to RGBA PNG
651
- def on_input_image_change(image_path):
652
- if image_path is None:
653
- gr.Warning("Please upload an Input Image to get started.")
654
- return None
655
- img, img_path = convert_to_rgba_png(image_path)
656
- return img_path
657
-
658
- input_image.change(
659
- fn=on_input_image_change,
660
- inputs=[input_image],
661
- outputs=[input_image], scroll_to_output=True,
662
- )
663
- with gr.Column():
664
- with gr.Accordion("Hex Coloring and Exclusion", open = False):
665
- with gr.Row():
666
- with gr.Column():
667
- color_picker = gr.ColorPicker(label="Pick a color to exclude",value="#505050")
668
- with gr.Column():
669
- filter_color = gr.Checkbox(label="Filter Excluded Colors from Sampling", value=False,)
670
- exclude_color_button = gr.Button("Exclude Color", elem_id="exlude_color_button", elem_classes="solid")
671
- color_display = gr.DataFrame(label="List of Excluded RGBA Colors", headers=["R", "G", "B", "A"], elem_id="excluded_colors", type="array", value=build_dataframe(excluded_color_list), interactive=True, elem_classes="solid centered")
672
- selected_row = gr.Number(0, label="Selected Row", visible=False)
673
- delete_button = gr.Button("Delete Row", elem_id="delete_exclusion_button", elem_classes="solid")
674
- fill_hex = gr.Checkbox(label="Fill Hex with color from Image", value=True)
675
- with gr.Accordion("Image Filters", open = False):
676
- with gr.Row():
677
- with gr.Column():
678
- composite_color = gr.ColorPicker(label="Color", value="#ede9ac44")
679
- with gr.Column():
680
- composite_opacity = gr.Slider(label="Opacity %", minimum=0, maximum=100, value=50, interactive=True)
681
- with gr.Row():
682
- composite_button = gr.Button("Composite", elem_classes="solid")
683
  with gr.Row():
684
  with gr.Column():
685
- lut_filename = gr.Textbox(
686
- value="",
687
- label="Look Up Table (LUT) File Name",
688
- elem_id="lutFileName")
689
- with gr.Column():
690
- lut_file = gr.File(
691
- value=None,
692
- file_count="single",
693
- file_types=[".cube"],
694
- type="filepath",
695
- label="LUT cube File")
696
- with gr.Row():
697
- lut_example_image = gr.Image(type="pil", label="Filter (LUT) Example Image", value=constants.default_lut_example_img)
698
- with gr.Row():
699
  with gr.Column():
700
- gr.Markdown("""
701
- ### Included Filters (LUTs)
702
- There are several included Filters:
703
-
704
- Try them on the example image before applying to your Input Image.
705
- """, elem_id="lut_markdown")
706
  with gr.Column():
707
- gr.Examples(elem_id="lut_examples",
708
- examples=[[f] for f in constants.lut_files],
709
- inputs=[lut_filename],
710
- outputs=[lut_filename],
711
- label="Select a Filter (LUT) file. Populate the LUT File Name field"
 
 
712
  )
713
-
714
- with gr.Row():
715
- apply_lut_button = gr.Button("Apply Filter (LUT)", elem_classes="solid", elem_id="apply_lut_button")
716
-
717
- lut_file.change(get_filename, inputs=[lut_file], outputs=[lut_filename])
718
- lut_filename.change(show_lut, inputs=[lut_filename, lut_example_image], outputs=[lut_example_image])
719
- apply_lut_button.click(
720
- lambda lut_filename, input_image: gr.Warning("Please upload an Input Image to get started.") if input_image is None else apply_lut_to_image_path(lut_filename, input_image)[0],
721
- inputs=[lut_filename, input_image],
722
- outputs=[input_image],
723
- scroll_to_output=True
724
  )
725
-
726
- with gr.Row():
727
- with gr.Accordion("Generative AI", open = False):
728
- with gr.Row():
729
- with gr.Column():
730
- model_options = gr.Dropdown(
731
- label="Model Options",
732
- choices=constants.MODELS + constants.LORA_WEIGHTS + ["Manual Entry"],
733
- value="Cossale/Frames2-Flex.1",
 
 
 
 
 
 
 
 
 
 
 
 
 
734
  elem_classes="solid"
735
- )
736
- model_textbox = gr.Textbox(
737
- label="LORA/Model",
738
- value="Cossale/Frames2-Flex.1",
739
- elem_classes="solid",
740
- elem_id="inference_model",
741
- visible=False
742
- )
743
- # Update map_options to a Dropdown with choices from constants.PROMPTS keys
744
- with gr.Row():
745
- with gr.Column():
746
- map_options = gr.Dropdown(
747
- label="Map Options",
748
- choices=list(constants.PROMPTS.keys()),
749
- value="Alien Landscape",
750
- elem_classes="solid",
751
- scale=0
752
- )
753
- with gr.Column():
754
- # Add Dropdown for sizing of Images, height and width based on selection. Options are 16x9, 16x10, 4x5, 1x1
755
- # The values of height and width are based on common resolutions for each aspect ratio
756
- # Default to 16x9, 912x512
757
- image_size_ratio = gr.Dropdown(label="Image Size", choices=["16:9", "16:10", "4:5", "4:3", "2:1","3:2","1:1", "9:16", "10:16", "5:4", "3:4","1:2", "2:3"], value="16:9", elem_classes="solid", type="value", scale=0, interactive=True)
758
- with gr.Column():
759
- seed_slider = gr.Slider(
760
- label="Seed",
761
- minimum=0,
762
- maximum=constants.MAX_SEED,
763
- step=1,
764
- value=0,
765
- scale=0
766
- )
767
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True, scale=0, interactive=True)
768
- prompt_textbox = gr.Textbox(
769
- label="Prompt",
770
- visible=False,
771
- elem_classes="solid",
772
- value="top-down, (rectangular tabletop_map) alien planet map, Battletech_boardgame scifi world with forests, lakes, oceans, continents and snow at the top and bottom, (middle is dark, no_reflections, no_shadows), from directly above. From 100,000 feet looking straight down",
773
- lines=4
774
- )
775
- negative_prompt_textbox = gr.Textbox(
776
- label="Negative Prompt",
777
- visible=False,
778
- elem_classes="solid",
779
- value="Earth, low quality, bad anatomy, blurry, cropped, worst quality, shadows, people, humans, reflections, shadows, realistic map of the Earth, isometric, text"
780
- )
781
- prompt_notes_label = gr.Label(
782
- "You should use FRM$ as trigger words. @1.5 minutes",
783
- elem_classes="solid centered small",
784
- show_label=False,
785
- visible=False
786
- )
787
- # Keep the change event to maintain functionality
788
- map_options.change(
789
- fn=update_prompt_visibility,
790
- inputs=[map_options],
791
- outputs=[prompt_textbox, negative_prompt_textbox, prompt_notes_label]
792
- )
793
- with gr.Row():
794
- generate_input_image = gr.Button(
795
- "Generate AI Image",
796
- elem_id="generate_input_image",
797
- elem_classes="solid"
798
- )
799
- with gr.Column(scale=2):
800
- with gr.Accordion("Template Image Styles", open = False):
801
- with gr.Row():
802
  # Gallery from PRE_RENDERED_IMAGES GOES HERE
803
  prerendered_image_gallery = gr.Gallery(label="Image Gallery", show_label=True, value=build_prerendered_images(constants.pre_rendered_maps_paths), elem_id="gallery", elem_classes="solid", type="filepath", columns=[3], rows=[3], preview=False ,object_fit="contain", height="auto", format="png",allow_preview=False)
804
- with gr.Row():
805
- image_guidance_stength = gr.Slider(label="Image Guidance Strength (prompt <-> image)", minimum=0, maximum=1.0, value=0.5, step=0.01, interactive=True)
806
- with gr.Column():
807
- replace_input_image_button = gr.Button(
808
- "Replace Input Image",
809
- elem_id="prerendered_replace_input_image_button",
810
- elem_classes="solid"
811
- )
812
- with gr.Column():
813
- generate_input_image_from_gallery = gr.Button(
814
- "Generate AI Image from Gallery",
815
- elem_id="generate_input_image_from_gallery",
816
- elem_classes="solid"
817
- )
818
-
819
- with gr.Accordion("Advanced Hexagon Settings", open = False):
820
- with gr.Row():
821
- start_x = gr.Number(label="Start X", value=0, minimum=-512, maximum= 512, precision=0)
822
- start_y = gr.Number(label="Start Y", value=0, minimum=-512, maximum= 512, precision=0)
823
- end_x = gr.Number(label="End X", value=0, minimum=-512, maximum= 512, precision=0)
824
- end_y = gr.Number(label="End Y", value=0, minimum=-512, maximum= 512, precision=0)
825
- with gr.Row():
826
- x_spacing = gr.Number(label="Adjust Horizontal spacing", value=-1, minimum=-200, maximum=200, precision=1)
827
- y_spacing = gr.Number(label="Adjust Vertical spacing", value=1, minimum=-200, maximum=200, precision=1)
828
- with gr.Row():
829
- rotation = gr.Slider(-90, 180, 0.0, 0.1, label="Hexagon Rotation (degree)")
830
- add_hex_text = gr.Dropdown(label="Add Text to Hexagons", choices=[None, "Row-Column Coordinates", "Sequential Numbers", "Playing Cards Sequential", "Playing Cards Alternate Red and Black", "Custom List"], value=None)
831
- with gr.Row():
832
- custom_text_list = gr.TextArea(label="Custom Text List", value=constants.cards_alternating, visible=False,)
833
- custom_text_color_list = gr.TextArea(label="Custom Text Color List", value=constants.card_colors_alternating, visible=False)
834
- with gr.Row():
835
- hex_text_info = gr.Markdown("""
836
- ### Text Color uses the Border Color and Border Opacity, unless you use a custom list.
837
- ### The Custom Text List and Custom Text Color List are comma separated lists.
838
- ### The custom color list is a comma separated list of hex colors.
839
- #### Example: "A,2,3,4,5,6,7,8,9,10,J,Q,K", "red,#0000FF,#00FF00,red,#FFFF00,#00FFFF,#FF8000,#FF00FF,#FF0080,#FF8000,#FF0080,lightblue"
840
- """, elem_id="hex_text_info", visible=False)
841
- add_hex_text.change(
842
- fn=lambda x: (
843
- gr.update(visible=(x == "Custom List")),
844
- gr.update(visible=(x == "Custom List")),
845
- gr.update(visible=(x != None))
846
- ),
847
- inputs=add_hex_text,
848
- outputs=[custom_text_list, custom_text_color_list, hex_text_info]
849
- )
850
  with gr.Row():
851
- hex_size = gr.Number(label="Hexagon Size", value=32, minimum=1, maximum=768)
852
- border_size = gr.Slider(-5,25,value=0,step=1,label="Border Size")
853
- with gr.Row():
854
- background_color = gr.ColorPicker(label="Background Color", value="#000000", interactive=True)
855
- background_opacity = gr.Slider(0,100,0,1,label="Background Opacity %")
856
- border_color = gr.ColorPicker(label="Border Color", value="#7b7b7b", interactive=True)
857
- border_opacity = gr.Slider(0,100,0,1,label="Border Opacity %")
858
  with gr.Row():
859
- hex_button = gr.Button("Generate Hex Grid!", elem_classes="solid", elem_id="btn-generate")
 
860
  with gr.Row():
861
- output_image = gr.Image(label="Hexagon Grid Image", image_mode = "RGBA", show_download_button=True, show_share_button=True,elem_classes="centered solid imgcontainer", format="PNG", type="filepath", key="ImgOutput")
862
- overlay_image = gr.Image(label="Hexagon Overlay Image", image_mode = "RGBA", show_share_button=True, elem_classes="centered solid imgcontainer", format="PNG", type="filepath", key="ImgOverlay")
863
  with gr.Row():
864
- output_overlay_composite = gr.Slider(0,100,50,0.5, label="Interpolate Intensity")
865
- output_blend_multiply_composite = gr.Slider(0,100,50,0.5, label="Overlay Intensity")
866
- output_alpha_composite = gr.Slider(0,100,50,0.5, label="Alpha Composite Intensity")
867
- with gr.Accordion("Add Margins (bleed)", open=False):
868
- with gr.Row():
869
- border_image_source = gr.Radio(label="Add Margins around which Image", choices=["Input Image", "Overlay Image"], value="Overlay Image")
870
- with gr.Row():
871
- mask_width = gr.Number(label="Margins Width", value=10, minimum=0, maximum=100, precision=0)
872
- mask_height = gr.Number(label="Margins Height", value=10, minimum=0, maximum=100, precision=0)
873
- with gr.Row():
874
- margin_color = gr.ColorPicker(label="Margin Color", value="#333333FF", interactive=True)
875
- margin_opacity = gr.Slider(0,100,95,0.5,label="Margin Opacity %")
876
- with gr.Row():
877
- add_border_button = gr.Button("Add Margins", elem_classes="solid", variant="secondary")
878
- with gr.Row():
879
- bordered_image_output = gr.Image(label="Image with Margins", image_mode="RGBA", show_download_button=True, show_share_button=True, elem_classes="centered solid imgcontainer", format="PNG", type="filepath", key="ImgBordered")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
880
 
881
- with gr.Accordion("Height Maps and 3D", open = False):
882
- with gr.Row():
883
- with gr.Column():
884
- voxel_size_factor = gr.Slider(label="Voxel Size Factor", value=1.00, minimum=0.01, maximum=40.00, step=0.01)
885
- with gr.Column():
886
- depth_image_source = gr.Radio(label="Depth Image Source", choices=["Input Image", "Output Image", "Overlay Image","Image with Margins"], value="Input Image")
887
- with gr.Row():
888
- generate_depth_button = gr.Button("Generate Depth Map and 3D Model From Selected Image", elem_classes="solid", variant="secondary")
889
- with gr.Row():
890
- depth_map_output = gr.Image(label="Depth Map", image_mode="L", elem_classes="centered solid imgcontainer", format="PNG", type="filepath", key="ImgDepth")
891
- model_output = gr.Model3D(label="3D Model", clear_color=[1.0, 1.0, 1.0, 0.25], key="Img3D", elem_classes="centered solid imgcontainer")
892
  with gr.Row():
893
- gr.Examples(examples=[
894
- ["assets//examples//hex_map_p1.png", False, True, -32,-31,80,80,-1.8,0,35,0,1,"#FFD0D0", 15],
895
- ["assets//examples//hex_map_p1_overlayed.png", False, False, -32,-31,80,80,-1.8,0,35,0,1,"#FFD0D0", 75],
896
- ["assets//examples//hex_flower_logo.png", False, True, -95,-95,100,100,-24,-2,190,30,2,"#FF8951", 50],
897
- ["assets//examples//hexed_fract_1.png", False, True, 0,0,0,0,0,0,10,0,0,"#000000", 5],
898
- ["assets//examples//tmpzt3mblvk.png", False, True, -20,10,0,0,-6,-2,35,30,1,"#ffffff", 0],
899
- ],
900
- inputs=[input_image, filter_color, fill_hex, start_x, start_y, end_x, end_y, x_spacing, y_spacing, hex_size, rotation, border_size, border_color, border_opacity],
901
- elem_id="examples")
902
  with gr.Row():
903
- gr.HTML(value=getVersions(), visible=True, elem_id="versions")
904
- # with gr.Row():
905
- # reinstall_torch = gr.Button("Reinstall Torch", elem_classes="solid small", variant="secondary")
906
- # reinstall_cuda_toolkit = gr.Button("Install CUDA Toolkit", elem_classes="solid small", variant="secondary")
907
- # reinitialize_cuda = gr.Button("Reinitialize CUDA", elem_classes="solid small", variant="secondary")
908
- # torch_release = gr.Button("Release Torch Resources", elem_classes="solid small", variant="secondary")
909
-
910
- # reinitialize_cuda.click(
911
- # fn=initialize_cuda,
912
- # inputs=[],
913
- # outputs=[]
914
- # )
915
- # torch_release.click(
916
- # fn=release_torch_resources,
917
- # inputs=[],
918
- # outputs=[]
919
- # )
920
- # reinstall_torch.click(
921
- # fn=install_torch,
922
- # inputs=[],
923
- # outputs=[]
924
- # )
925
-
926
- # reinstall_cuda_toolkit.click(
927
- # fn=install_cuda_toolkit,
928
- # inputs=[],
929
- # outputs=[]
930
- # )
931
-
932
- color_display.select(on_color_display_select,inputs=[color_display], outputs=[selected_row])
933
- color_display.input(on_input,inputs=[color_display], outputs=[color_display, gr.State(excluded_color_list)])
934
-
935
- delete_button.click(fn=delete_color, inputs=[selected_row, color_display], outputs=[color_display])
936
- exclude_color_button.click(fn=add_color, inputs=[color_picker, gr.State(excluded_color_list)], outputs=[color_display, gr.State(excluded_color_list)])
937
- hex_button.click(
938
- fn=lambda hex_size, border_size, input_image, start_x, start_y, end_x, end_y, rotation, background_color, background_opacity, border_color, border_opacity, fill_hex, color_display, filter_color, x_spacing, y_spacing, add_hex_text, custom_text_list, custom_text_color_list:
939
- gr.Warning("Please upload an Input Image to get started.") if input_image is None else hex_create(hex_size, border_size, input_image, start_x, start_y, end_x, end_y, rotation, background_color, background_opacity, border_color, border_opacity, fill_hex, color_display, filter_color, x_spacing, y_spacing, add_hex_text, custom_text_list, custom_text_color_list),
940
- inputs=[hex_size, border_size, input_image, start_x, start_y, end_x, end_y, rotation, background_color, background_opacity, border_color, border_opacity, fill_hex, color_display, filter_color, x_spacing, y_spacing, add_hex_text, custom_text_list, custom_text_color_list],
941
- outputs=[output_image, overlay_image],
942
- scroll_to_output=True
943
- )
944
- generate_input_image.click(
945
- fn=generate_input_image_click,
946
- inputs=[map_options, prompt_textbox, negative_prompt_textbox, model_textbox, randomize_seed, seed_slider, gr.State(False), gr.State(0.5), image_size_ratio],
947
- outputs=[input_image], scroll_to_output=True
948
- )
949
- generate_depth_button.click(
950
- fn=generate_depth_button_click,
951
- inputs=[depth_image_source, voxel_size_factor, input_image, output_image, overlay_image, bordered_image_output],
952
- outputs=[depth_map_output, model_output], scroll_to_output=True
953
- )
954
- model_textbox.change(
955
- fn=update_prompt_notes,
956
- inputs=model_textbox,
957
- outputs=prompt_notes_label,preprocess=False
958
- )
959
- model_options.change(
960
- fn=lambda x: (gr.update(visible=(x == "Manual Entry")), gr.update(value=x) if x != "Manual Entry" else gr.update()),
961
- inputs=model_options,
962
- outputs=[model_textbox, model_textbox]
963
- )
964
- model_options.change(
965
- fn=update_prompt_notes,
966
- inputs=model_options,
967
- outputs=prompt_notes_label
968
- )
969
- composite_button.click(
970
- fn=lambda input_image, composite_color, composite_opacity: gr.Warning("Please upload an Input Image to get started.") if input_image is None else change_color(input_image, composite_color, composite_opacity),
971
- inputs=[input_image, composite_color, composite_opacity],
972
- outputs=[input_image]
973
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
974
 
975
- #use conditioned_image as the input_image for generate_input_image_click
976
- generate_input_image_from_gallery.click(
977
- fn=generate_input_image_click,
978
- inputs=[map_options, prompt_textbox, negative_prompt_textbox, model_textbox,randomize_seed, seed_slider, gr.State(True), image_guidance_stength, image_size_ratio],
979
- outputs=[input_image], scroll_to_output=True
980
- )
981
 
982
- # Update the state variable with the prerendered image filepath when an image is selected
983
- prerendered_image_gallery.select(
984
- fn=on_prerendered_gallery_selection,
985
- inputs=None,
986
- outputs=[gr.State(current_prerendered_image)], # Update the state with the selected image
987
- show_api=False
988
- )
989
- # replace input image with selected gallery image
990
- replace_input_image_button.click(
991
- lambda: current_prerendered_image.value,
992
- inputs=None,
993
- outputs=[input_image], scroll_to_output=True
994
- )
995
- output_overlay_composite.change(
996
- fn=combine_images_with_lerp,
997
- inputs=[input_image, output_image, output_overlay_composite],
998
- outputs=[overlay_image], scroll_to_output=True
999
- )
1000
- output_blend_multiply_composite.change(
1001
- fn=multiply_and_blend_images,
1002
- inputs=[input_image, output_image, output_blend_multiply_composite],
1003
- outputs=[overlay_image],
1004
- scroll_to_output=True
1005
- )
1006
- output_alpha_composite.change(
1007
- fn=alpha_composite_with_control,
1008
- inputs=[input_image, output_image, output_alpha_composite],
1009
- outputs=[overlay_image],
1010
- scroll_to_output=True
1011
- )
1012
- add_border_button.click(
1013
- fn=lambda image_source, mask_w, mask_h, color, opacity, input_img, overlay_img: add_border(input_img if image_source == "Input Image" else overlay_img, mask_w, mask_h, update_color_opacity(detect_color_format(color), opacity * 2.55)),
1014
- inputs=[border_image_source, mask_width, mask_height, margin_color, margin_opacity, input_image, overlay_image],
1015
- outputs=[bordered_image_output],
1016
- scroll_to_output=True
1017
- )
1018
 
1019
- beeuty.queue(default_concurrency_limit=2,max_size=12,api_open=False)
1020
- beeuty.launch(allowed_paths=["assets","/","./assets","images","./images", "./images/prerendered"], favicon_path="./assets/favicon.ico", max_file_size="10mb")
1021
 
1022
 
1023
- if __name__ == "__main__":
1024
- logging.basicConfig(
1025
- format="[%(levelname)s] %(asctime)s %(message)s", level=logging.INFO
1026
- )
1027
- logging.info("Environment Variables: %s" % os.environ)
1028
  # if _get_output(["nvcc", "--version"]) is None:
1029
  # logging.info("Installing CUDA toolkit...")
1030
  # install_cuda_toolkit()
@@ -1034,4 +1143,7 @@ if __name__ == "__main__":
1034
  # logging.info("Installing CUDA extensions...")
1035
  # setup_runtime_env()
1036
  #main(os.getenv("DEBUG") == "1")
1037
- main()
 
 
 
 
2
  # Import constants
3
  import numpy as np
4
  import torch
5
+ from typing import Optional, Union, List, Tuple
6
+ from PIL import Image, ImageFilter
7
+ import cv2
8
  import utils.constants as constants
9
  import gradio as gr
10
+
11
  from haishoku.haishoku import Haishoku
12
 
13
  from tempfile import NamedTemporaryFile
 
15
  import atexit
16
  import random
17
  import logging
18
+ #import accelerate
19
  from transformers import AutoTokenizer
20
  import gc
21
 
 
29
  detect_color_format,
30
  update_color_opacity,
31
  )
32
+ from utils.misc import (get_filename, pause, convert_ratio_to_dimensions) #install_cuda_toolkit,install_torch, _get_output, setup_runtime_env)
33
+ #from utils.depth_estimation import generate_depth_button_click
34
 
35
  from utils.image_utils import (
36
  change_color,
 
43
  apply_lut_to_image_path,
44
  multiply_and_blend_images,
45
  alpha_composite_with_control,
46
+ crop_and_resize_image,
47
+ convert_to_rgba_png
48
  )
49
 
50
  from utils.hex_grid import (
 
68
  versions_html,
69
  #initialize_cuda,
70
  #release_torch_resources,
71
+ #get_torch_info
72
  )
73
  from utils.lora_details import (
74
  upd_prompt_notes,
 
183
  default_model = model_textbox
184
  return default_model, []
185
 
186
+ condition_dict = {
187
+ "depth": 0,
188
+ "canny": 1,
189
+ "subject": 4,
190
+ "coloring": 6,
191
+ "deblurring": 7,
192
+ "fill": 9,
193
+ }
194
+
195
+ class Condition(object):
196
+ def __init__(
197
+ self,
198
+ condition_type: str,
199
+ raw_img: Union[Image.Image, torch.Tensor] = None,
200
+ condition: Union[Image.Image,torch.Tensor] = None,
201
+ mask=None,
202
+ ) -> None:
203
+ self.condition_type = condition_type
204
+ assert raw_img is not None or condition is not None
205
+ if raw_img is not None:
206
+ self.condition = self.get_condition(condition_type, raw_img)
207
+ else:
208
+ self.condition = condition
209
+ # TODO: Add mask support
210
+ assert mask is None, "Mask not supported yet"
211
+ def get_condition(
212
+ self, condition_type: str, raw_img: Union[Image.Image, torch.Tensor]
213
+ ) -> Union[Image.Image, torch.Tensor]:
214
+ """
215
+ Returns the condition image.
216
+ """
217
+ if condition_type == "depth":
218
+ from transformers import pipeline
219
+ depth_pipe = pipeline(
220
+ task="depth-estimation",
221
+ model="LiheYoung/depth-anything-small-hf",
222
+ device="cuda",
223
+ )
224
+ source_image = raw_img.convert("RGB")
225
+ condition_img = depth_pipe(source_image)["depth"].convert("RGB")
226
+ return condition_img
227
+ elif condition_type == "canny":
228
+ img = np.array(raw_img)
229
+ edges = cv2.Canny(img, 100, 200)
230
+ edges = Image.fromarray(edges).convert("RGB")
231
+ return edges
232
+ elif condition_type == "subject":
233
+ return raw_img
234
+ elif condition_type == "coloring":
235
+ return raw_img.convert("L").convert("RGB")
236
+ elif condition_type == "deblurring":
237
+ condition_image = (
238
+ raw_img.convert("RGB")
239
+ .filter(ImageFilter.GaussianBlur(10))
240
+ .convert("RGB")
241
+ )
242
+ return condition_image
243
+ elif condition_type == "fill":
244
+ return raw_img.convert("RGB")
245
+ return self.condition
246
+ @property
247
+ def type_id(self) -> int:
248
+ """
249
+ Returns the type id of the condition.
250
+ """
251
+ return condition_dict[self.condition_type]
252
+ @classmethod
253
+ def get_type_id(cls, condition_type: str) -> int:
254
+ """
255
+ Returns the type id of the condition.
256
+ """
257
+ return condition_dict[condition_type]
258
+ def _encode_image(self, pipe: FluxPipeline, cond_img: Image.Image) -> torch.Tensor:
259
+ """
260
+ Encodes an image condition into tokens using the pipeline.
261
+ """
262
+ cond_img = pipe.image_processor.preprocess(cond_img)
263
+ cond_img = cond_img.to(pipe.device).to(pipe.dtype)
264
+ cond_img = pipe.vae.encode(cond_img).latent_dist.sample()
265
+ cond_img = (
266
+ cond_img - pipe.vae.config.shift_factor
267
+ ) * pipe.vae.config.scaling_factor
268
+ cond_tokens = pipe._pack_latents(cond_img, *cond_img.shape)
269
+ cond_ids = pipe._prepare_latent_image_ids(
270
+ cond_img.shape[0],
271
+ cond_img.shape[2]//2,
272
+ cond_img.shape[3]//2,
273
+ pipe.device,
274
+ pipe.dtype,
275
+ )
276
+ return cond_tokens, cond_ids
277
+ def encode(self, pipe: FluxPipeline) -> Tuple[torch.Tensor, torch.Tensor, int]:
278
+ """
279
+ Encodes the condition into tokens, ids and type_id.
280
+ """
281
+ if self.condition_type in [
282
+ "depth",
283
+ "canny",
284
+ "subject",
285
+ "coloring",
286
+ "deblurring",
287
+ "fill",
288
+ ]:
289
+ tokens, ids = self._encode_image(pipe, self.condition)
290
+ else:
291
+ raise NotImplementedError(
292
+ f"Condition type {self.condition_type} not implemented"
293
+ )
294
+ type_id = torch.ones_like(ids[:, :1]) * self.type_id
295
+ return tokens, ids, type_id
296
+
297
  @spaces.GPU(progress=gr.Progress(track_tqdm=True))
298
  def generate_image_lowmem(
299
  text,
 
321
 
322
  #initialize_cuda()
323
  device = "cuda" if torch.cuda.is_available() else "cpu"
324
+ #from src.condition import Condition
325
 
326
  print(f"device:{device}\nmodel_name:{model_name}\nlora_weights:{lora_weights}\n")
327
  #print(f"\n {get_torch_info()}\n")
 
596
  gc.collect()
597
  return None
598
 
599
+ @spaces.GPU(duration=140)
600
  def generate_input_image_click(map_option, prompt_textbox_value, negative_prompt_textbox_value, model_textbox_value, randomize_seed=True, seed=None, use_conditioned_image=False, strength=0.5, image_format="16:9", scale_factor=(8/3), progress=gr.Progress(track_tqdm=True)):
601
  if randomize_seed:
602
  seed = random.randint(0, constants.MAX_SEED)
 
681
  return lerp_imagemath(in_image, out_image, alpha)
682
 
683
  def add_border(image, mask_width, mask_height, blank_color):
 
684
  bordered_image_output = Image.open(image).convert("RGBA")
685
  margin_color = detect_color_format(blank_color)
686
  print(f"Adding border to image with width: {mask_width}, height: {mask_height}, color: {margin_color}")
687
  return shrink_and_paste_on_blank(bordered_image_output, mask_width, mask_height, margin_color)
688
 
 
689
  def getVersions():
690
  return versions_html()
691
+
692
  generate_input_image_click.zerogpu = True
693
+ #def main(debug=False):
694
+ title = "HexaGrid Creator"
695
+ #description = "Customizable Hexagon Grid Image Generator"
696
+ examples = [["assets//examples//hex_map_p1.png", 32, 1, 0, 0, 0, 0, 0, "#ede9ac44","#12165380", True]]
697
 
698
+ gr.set_static_paths(paths=["images/","images/images","images/prerendered","LUT/","fonts/"])
699
 
700
+ # Gradio Blocks Interface
701
+ with gr.Blocks(css_paths="style_20250128.css", title=title, theme='Surn/beeuty') as hexaGrid:
702
+ with gr.Row():
703
+ gr.Markdown("""
704
+ # HexaGrid Creator
705
+ ## Transform Your Images into Mesmerizing Hexagon Grid Masterpieces! ⬢""", elem_classes="intro")
706
+ with gr.Row():
707
+ with gr.Accordion("Welcome to HexaGrid Creator, the ultimate tool for transforming your images into stunning hexagon grid artworks. Whether you're a tabletop game enthusiast, a digital artist, or someone who loves unique patterns, HexaGrid Creator has something for you.", open=False, elem_classes="intro"):
708
+ gr.Markdown ("""
709
 
710
+ ## Drop an image into the Input Image and get started!
711
 
712
 
713
 
714
+ ## What is HexaGrid Creator?
715
+ HexaGrid Creator is a web-based application that allows you to apply a hexagon grid overlay to any image. You can customize the size, color, and opacity of the hexagons, as well as the background and border colors. The result is a visually striking image that looks like it was made from hexagonal tiles!
716
+
717
+ ### What Can You Do?
718
+ - **Generate Hexagon Grids:** Create beautiful hexagon grid overlays on any image with fully customizable parameters.
719
+ - **AI-Powered Image Generation:** Use advanced AI models to generate images based on your prompts and apply hexagon grids to them.
720
+ - **Color Exclusion:** Select and exclude specific colors from your hexagon grid for a cleaner and more refined look.
721
+ - **Interactive Customization:** Adjust hexagon size, border size, rotation, background color, and more in real-time.
722
+ - **Depth and 3D Model Generation:** Generate depth maps and 3D models from your images for enhanced visualization.
723
+ - **Image Filter [Look-Up Table (LUT)] Application:** Apply filters (LUTs) to your images for color grading and enhancement.
724
+ - **Pre-rendered Maps:** Access a library of pre-rendered hexagon maps for quick and easy customization.
725
+ - **Add Margins:** Add customizable margins around your images for a polished finish.
726
+
727
+ ### Why You'll Love It
728
+ - **Fun and Easy to Use:** With an intuitive interface and real-time previews, creating hexagon grids has never been this fun!
729
+ - **Endless Creativity:** Unleash your creativity with endless customization options and see your images transform in unique ways.
730
+ - **Hexagon-Inspired Theme:** Enjoy a delightful yellow and purple theme inspired by hexagons! ⬢
731
+ - **Advanced AI Models:** Leverage advanced AI models and LoRA weights for high-quality image generation and customization.
732
+
733
+ ### Get Started
734
+ 1. **Upload or Generate an Image:** Start by uploading your own image or generate one using our AI-powered tool.
735
+ 2. **Customize Your Grid:** Play around with the settings to create the perfect hexagon grid overlay.
736
+ 3. **Download and Share:** Once you're happy with your creation, download it and share it with the world!
737
+
738
+ ### Advanced Features
739
+ - **Generative AI Integration:** Utilize models like `black-forest-labs/FLUX.1-dev` and various LoRA weights for generating unique images.
740
+ - **Pre-rendered Maps:** Access a library of pre-rendered hexagon maps for quick and easy customization.
741
+ - **Image Filter [Look-Up Table (LUT)] Application:** Apply filters (LUTs) to your images for color grading and enhancement.
742
+ - **Depth and 3D Model Generation:** Create depth maps and 3D models from your images for enhanced visualization.
743
+ - **Add Margins:** Customize margins around your images for a polished finish.
744
+
745
+ Join the hive and start creating with HexaGrid Creator today!
746
 
747
+ """, elem_classes="intro")
748
+ with gr.Row():
749
+ with gr.Column(scale=2):
750
+ input_image = gr.Image(
751
+ label="Input Image",
752
+ type="filepath",
753
+ interactive=True,
754
+ elem_classes="centered solid imgcontainer",
755
+ key="imgInput",
756
+ image_mode=None,
757
+ format="PNG",
758
+ show_download_button=True,
759
+ )
760
+
761
+ # New code to convert input image to RGBA PNG
762
+ def on_input_image_change(image_path):
763
+ if image_path is None:
764
+ gr.Warning("Please upload an Input Image to get started.")
765
+ return None
766
+ img, img_path = convert_to_rgba_png(image_path)
767
+ return img_path
768
+
769
+ input_image.change(
770
+ fn=on_input_image_change,
771
+ inputs=[input_image],
772
+ outputs=[input_image], scroll_to_output=True,
773
+ )
774
+ with gr.Column():
775
+ with gr.Accordion("Hex Coloring and Exclusion", open = False):
776
+ with gr.Row():
777
+ with gr.Column():
778
+ color_picker = gr.ColorPicker(label="Pick a color to exclude",value="#505050")
779
+ with gr.Column():
780
+ filter_color = gr.Checkbox(label="Filter Excluded Colors from Sampling", value=False,)
781
+ exclude_color_button = gr.Button("Exclude Color", elem_id="exlude_color_button", elem_classes="solid")
782
+ color_display = gr.DataFrame(label="List of Excluded RGBA Colors", headers=["R", "G", "B", "A"], elem_id="excluded_colors", type="array", value=build_dataframe(excluded_color_list), interactive=True, elem_classes="solid centered")
783
+ selected_row = gr.Number(0, label="Selected Row", visible=False)
784
+ delete_button = gr.Button("Delete Row", elem_id="delete_exclusion_button", elem_classes="solid")
785
+ fill_hex = gr.Checkbox(label="Fill Hex with color from Image", value=True)
786
+ with gr.Accordion("Image Filters", open = False):
787
+ with gr.Row():
788
+ with gr.Column():
789
+ composite_color = gr.ColorPicker(label="Color", value="#ede9ac44")
790
+ with gr.Column():
791
+ composite_opacity = gr.Slider(label="Opacity %", minimum=0, maximum=100, value=50, interactive=True)
792
+ with gr.Row():
793
+ composite_button = gr.Button("Composite", elem_classes="solid")
794
+ with gr.Row():
795
+ with gr.Column():
796
+ lut_filename = gr.Textbox(
797
+ value="",
798
+ label="Look Up Table (LUT) File Name",
799
+ elem_id="lutFileName")
800
+ with gr.Column():
801
+ lut_file = gr.File(
802
+ value=None,
803
+ file_count="single",
804
+ file_types=[".cube"],
805
+ type="filepath",
806
+ label="LUT cube File")
807
+ with gr.Row():
808
+ lut_example_image = gr.Image(type="pil", label="Filter (LUT) Example Image", value=constants.default_lut_example_img)
809
+ with gr.Row():
810
+ with gr.Column():
811
+ gr.Markdown("""
812
+ ### Included Filters (LUTs)
813
+ There are several included Filters:
814
+
815
+ Try them on the example image before applying to your Input Image.
816
+ """, elem_id="lut_markdown")
817
+ with gr.Column():
818
+ gr.Examples(elem_id="lut_examples",
819
+ examples=[[f] for f in constants.lut_files],
820
+ inputs=[lut_filename],
821
+ outputs=[lut_filename],
822
+ label="Select a Filter (LUT) file. Populate the LUT File Name field"
823
+ )
824
+
825
+ with gr.Row():
826
+ apply_lut_button = gr.Button("Apply Filter (LUT)", elem_classes="solid", elem_id="apply_lut_button")
827
+
828
+ lut_file.change(get_filename, inputs=[lut_file], outputs=[lut_filename])
829
+ lut_filename.change(show_lut, inputs=[lut_filename, lut_example_image], outputs=[lut_example_image])
830
+ apply_lut_button.click(
831
+ lambda lut_filename, input_image: gr.Warning("Please upload an Input Image to get started.") if input_image is None else apply_lut_to_image_path(lut_filename, input_image)[0],
832
+ inputs=[lut_filename, input_image],
833
+ outputs=[input_image],
834
+ scroll_to_output=True
835
  )
836
 
837
+ with gr.Row():
838
+ with gr.Accordion("Generative AI", open = False):
839
+ with gr.Row():
840
+ with gr.Column():
841
+ model_options = gr.Dropdown(
842
+ label="Model Options",
843
+ choices=constants.MODELS + constants.LORA_WEIGHTS + ["Manual Entry"],
844
+ value="Cossale/Frames2-Flex.1",
845
+ elem_classes="solid"
846
+ )
847
+ model_textbox = gr.Textbox(
848
+ label="LORA/Model",
849
+ value="Cossale/Frames2-Flex.1",
850
+ elem_classes="solid",
851
+ elem_id="inference_model",
852
+ visible=False
853
+ )
854
+ # Update map_options to a Dropdown with choices from constants.PROMPTS keys
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
855
  with gr.Row():
856
  with gr.Column():
857
+ map_options = gr.Dropdown(
858
+ label="Map Options",
859
+ choices=list(constants.PROMPTS.keys()),
860
+ value="Alien Landscape",
861
+ elem_classes="solid",
862
+ scale=0
863
+ )
 
 
 
 
 
 
 
864
  with gr.Column():
865
+ # Add Dropdown for sizing of Images, height and width based on selection. Options are 16x9, 16x10, 4x5, 1x1
866
+ # The values of height and width are based on common resolutions for each aspect ratio
867
+ # Default to 16x9, 912x512
868
+ image_size_ratio = gr.Dropdown(label="Image Size", choices=["16:9", "16:10", "4:5", "4:3", "2:1","3:2","1:1", "9:16", "10:16", "5:4", "3:4","1:2", "2:3"], value="16:9", elem_classes="solid", type="value", scale=0, interactive=True)
 
 
869
  with gr.Column():
870
+ seed_slider = gr.Slider(
871
+ label="Seed",
872
+ minimum=0,
873
+ maximum=constants.MAX_SEED,
874
+ step=1,
875
+ value=0,
876
+ scale=0
877
  )
878
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True, scale=0, interactive=True)
879
+ prompt_textbox = gr.Textbox(
880
+ label="Prompt",
881
+ visible=False,
882
+ elem_classes="solid",
883
+ value="top-down, (rectangular tabletop_map) alien planet map, Battletech_boardgame scifi world with forests, lakes, oceans, continents and snow at the top and bottom, (middle is dark, no_reflections, no_shadows), from directly above. From 100,000 feet looking straight down",
884
+ lines=4
 
 
 
 
885
  )
886
+ negative_prompt_textbox = gr.Textbox(
887
+ label="Negative Prompt",
888
+ visible=False,
889
+ elem_classes="solid",
890
+ value="Earth, low quality, bad anatomy, blurry, cropped, worst quality, shadows, people, humans, reflections, shadows, realistic map of the Earth, isometric, text"
891
+ )
892
+ prompt_notes_label = gr.Label(
893
+ "You should use FRM$ as trigger words. @1.5 minutes",
894
+ elem_classes="solid centered small",
895
+ show_label=False,
896
+ visible=False
897
+ )
898
+ # Keep the change event to maintain functionality
899
+ map_options.change(
900
+ fn=update_prompt_visibility,
901
+ inputs=[map_options],
902
+ outputs=[prompt_textbox, negative_prompt_textbox, prompt_notes_label]
903
+ )
904
+ with gr.Row():
905
+ generate_input_image = gr.Button(
906
+ "Generate AI Image",
907
+ elem_id="generate_input_image",
908
  elem_classes="solid"
909
+ )
910
+ with gr.Column(scale=2):
911
+ with gr.Accordion("Template Image Styles", open = False):
912
+ with gr.Row():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
913
  # Gallery from PRE_RENDERED_IMAGES GOES HERE
914
  prerendered_image_gallery = gr.Gallery(label="Image Gallery", show_label=True, value=build_prerendered_images(constants.pre_rendered_maps_paths), elem_id="gallery", elem_classes="solid", type="filepath", columns=[3], rows=[3], preview=False ,object_fit="contain", height="auto", format="png",allow_preview=False)
915
+ with gr.Row():
916
+ image_guidance_stength = gr.Slider(label="Image Guidance Strength (prompt percentage)", minimum=0, maximum=1.0, value=0.8, step=0.01, interactive=True)
917
+ with gr.Column():
918
+ replace_input_image_button = gr.Button(
919
+ "Replace Input Image",
920
+ elem_id="prerendered_replace_input_image_button",
921
+ elem_classes="solid"
922
+ )
923
+ with gr.Column():
924
+ generate_input_image_from_gallery = gr.Button(
925
+ "Generate AI Image from Gallery",
926
+ elem_id="generate_input_image_from_gallery",
927
+ elem_classes="solid"
928
+ )
929
+
930
+ with gr.Accordion("Advanced Hexagon Settings", open = False):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
931
  with gr.Row():
932
+ start_x = gr.Number(label="Start X", value=0, minimum=-512, maximum= 512, precision=0)
933
+ start_y = gr.Number(label="Start Y", value=0, minimum=-512, maximum= 512, precision=0)
934
+ end_x = gr.Number(label="End X", value=0, minimum=-512, maximum= 512, precision=0)
935
+ end_y = gr.Number(label="End Y", value=0, minimum=-512, maximum= 512, precision=0)
 
 
 
936
  with gr.Row():
937
+ x_spacing = gr.Number(label="Adjust Horizontal spacing", value=-1, minimum=-200, maximum=200, precision=1)
938
+ y_spacing = gr.Number(label="Adjust Vertical spacing", value=1, minimum=-200, maximum=200, precision=1)
939
  with gr.Row():
940
+ rotation = gr.Slider(-90, 180, 0.0, 0.1, label="Hexagon Rotation (degree)")
941
+ add_hex_text = gr.Dropdown(label="Add Text to Hexagons", choices=[None, "Row-Column Coordinates", "Sequential Numbers", "Playing Cards Sequential", "Playing Cards Alternate Red and Black", "Custom List"], value=None)
942
  with gr.Row():
943
+ custom_text_list = gr.TextArea(label="Custom Text List", value=constants.cards_alternating, visible=False,)
944
+ custom_text_color_list = gr.TextArea(label="Custom Text Color List", value=constants.card_colors_alternating, visible=False)
945
+ with gr.Row():
946
+ hex_text_info = gr.Markdown("""
947
+ ### Text Color uses the Border Color and Border Opacity, unless you use a custom list.
948
+ ### The Custom Text List and Custom Text Color List are comma separated lists.
949
+ ### The custom color list is a comma separated list of hex colors.
950
+ #### Example: "A,2,3,4,5,6,7,8,9,10,J,Q,K", "red,#0000FF,#00FF00,red,#FFFF00,#00FFFF,#FF8000,#FF00FF,#FF0080,#FF8000,#FF0080,lightblue"
951
+ """, elem_id="hex_text_info", visible=False)
952
+ add_hex_text.change(
953
+ fn=lambda x: (
954
+ gr.update(visible=(x == "Custom List")),
955
+ gr.update(visible=(x == "Custom List")),
956
+ gr.update(visible=(x != None))
957
+ ),
958
+ inputs=add_hex_text,
959
+ outputs=[custom_text_list, custom_text_color_list, hex_text_info]
960
+ )
961
+ with gr.Row():
962
+ hex_size = gr.Number(label="Hexagon Size", value=32, minimum=1, maximum=768)
963
+ border_size = gr.Slider(-5,25,value=0,step=1,label="Border Size")
964
+ with gr.Row():
965
+ background_color = gr.ColorPicker(label="Background Color", value="#000000", interactive=True)
966
+ background_opacity = gr.Slider(0,100,0,1,label="Background Opacity %")
967
+ border_color = gr.ColorPicker(label="Border Color", value="#7b7b7b", interactive=True)
968
+ border_opacity = gr.Slider(0,100,0,1,label="Border Opacity %")
969
+ with gr.Row():
970
+ hex_button = gr.Button("Generate Hex Grid!", elem_classes="solid", elem_id="btn-generate")
971
+ with gr.Row():
972
+ output_image = gr.Image(label="Hexagon Grid Image", image_mode = "RGBA", show_download_button=True, show_share_button=True,elem_classes="centered solid imgcontainer", format="PNG", type="filepath", key="ImgOutput")
973
+ overlay_image = gr.Image(label="Hexagon Overlay Image", image_mode = "RGBA", show_share_button=True, elem_classes="centered solid imgcontainer", format="PNG", type="filepath", key="ImgOverlay")
974
+ with gr.Row():
975
+ output_overlay_composite = gr.Slider(0,100,50,0.5, label="Interpolate Intensity")
976
+ output_blend_multiply_composite = gr.Slider(0,100,50,0.5, label="Overlay Intensity")
977
+ output_alpha_composite = gr.Slider(0,100,50,0.5, label="Alpha Composite Intensity")
978
+ with gr.Accordion("Add Margins (bleed)", open=False):
979
+ with gr.Row():
980
+ border_image_source = gr.Radio(label="Add Margins around which Image", choices=["Input Image", "Overlay Image"], value="Overlay Image")
981
+ with gr.Row():
982
+ mask_width = gr.Number(label="Margins Width", value=10, minimum=0, maximum=100, precision=0)
983
+ mask_height = gr.Number(label="Margins Height", value=10, minimum=0, maximum=100, precision=0)
984
+ with gr.Row():
985
+ margin_color = gr.ColorPicker(label="Margin Color", value="#333333FF", interactive=True)
986
+ margin_opacity = gr.Slider(0,100,95,0.5,label="Margin Opacity %")
987
+ with gr.Row():
988
+ add_border_button = gr.Button("Add Margins", elem_classes="solid", variant="secondary")
989
+ with gr.Row():
990
+ bordered_image_output = gr.Image(label="Image with Margins", image_mode="RGBA", show_download_button=True, show_share_button=True, elem_classes="centered solid imgcontainer", format="PNG", type="filepath", key="ImgBordered")
991
 
992
+ with gr.Accordion("Height Maps and 3D", open = False):
 
 
 
 
 
 
 
 
 
 
993
  with gr.Row():
994
+ with gr.Column():
995
+ voxel_size_factor = gr.Slider(label="Voxel Size Factor", value=1.00, minimum=0.01, maximum=40.00, step=0.01)
996
+ with gr.Column():
997
+ depth_image_source = gr.Radio(label="Depth Image Source", choices=["Input Image", "Output Image", "Overlay Image","Image with Margins"], value="Input Image")
 
 
 
 
 
998
  with gr.Row():
999
+ generate_depth_button = gr.Button("Generate Depth Map and 3D Model From Selected Image", elem_classes="solid", variant="secondary")
1000
+ with gr.Row():
1001
+ depth_map_output = gr.Image(label="Depth Map", image_mode="L", elem_classes="centered solid imgcontainer", format="PNG", type="filepath", key="ImgDepth")
1002
+ model_output = gr.Model3D(label="3D Model", clear_color=[1.0, 1.0, 1.0, 0.25], key="Img3D", elem_classes="centered solid imgcontainer")
1003
+ with gr.Row():
1004
+ gr.Examples(examples=[
1005
+ ["assets//examples//hex_map_p1.png", False, True, -32,-31,80,80,-1.8,0,35,0,1,"#FFD0D0", 15],
1006
+ ["assets//examples//hex_map_p1_overlayed.png", False, False, -32,-31,80,80,-1.8,0,35,0,1,"#FFD0D0", 75],
1007
+ ["assets//examples//hex_flower_logo.png", False, True, -95,-95,100,100,-24,-2,190,30,2,"#FF8951", 50],
1008
+ ["assets//examples//hexed_fract_1.png", False, True, 0,0,0,0,0,0,10,0,0,"#000000", 5],
1009
+ ["assets//examples//tmpzt3mblvk.png", False, True, -20,10,0,0,-6,-2,35,30,1,"#ffffff", 0],
1010
+ ],
1011
+ inputs=[input_image, filter_color, fill_hex, start_x, start_y, end_x, end_y, x_spacing, y_spacing, hex_size, rotation, border_size, border_color, border_opacity],
1012
+ elem_id="examples")
1013
+ with gr.Row():
1014
+ gr.HTML(value=getVersions(), visible=True, elem_id="versions")
1015
+ # with gr.Row():
1016
+ # reinstall_torch = gr.Button("Reinstall Torch", elem_classes="solid small", variant="secondary")
1017
+ # reinstall_cuda_toolkit = gr.Button("Install CUDA Toolkit", elem_classes="solid small", variant="secondary")
1018
+ # reinitialize_cuda = gr.Button("Reinitialize CUDA", elem_classes="solid small", variant="secondary")
1019
+ # torch_release = gr.Button("Release Torch Resources", elem_classes="solid small", variant="secondary")
1020
+
1021
+ # reinitialize_cuda.click(
1022
+ # fn=initialize_cuda,
1023
+ # inputs=[],
1024
+ # outputs=[]
1025
+ # )
1026
+ # torch_release.click(
1027
+ # fn=release_torch_resources,
1028
+ # inputs=[],
1029
+ # outputs=[]
1030
+ # )
1031
+ # reinstall_torch.click(
1032
+ # fn=install_torch,
1033
+ # inputs=[],
1034
+ # outputs=[]
1035
+ # )
1036
+
1037
+ # reinstall_cuda_toolkit.click(
1038
+ # fn=install_cuda_toolkit,
1039
+ # inputs=[],
1040
+ # outputs=[]
1041
+ # )
1042
+
1043
+ color_display.select(on_color_display_select,inputs=[color_display], outputs=[selected_row])
1044
+ color_display.input(on_input,inputs=[color_display], outputs=[color_display, gr.State(excluded_color_list)])
1045
+
1046
+ delete_button.click(fn=delete_color, inputs=[selected_row, color_display], outputs=[color_display])
1047
+ exclude_color_button.click(fn=add_color, inputs=[color_picker, gr.State(excluded_color_list)], outputs=[color_display, gr.State(excluded_color_list)])
1048
+ hex_button.click(
1049
+ fn=lambda hex_size, border_size, input_image, start_x, start_y, end_x, end_y, rotation, background_color, background_opacity, border_color, border_opacity, fill_hex, color_display, filter_color, x_spacing, y_spacing, add_hex_text, custom_text_list, custom_text_color_list:
1050
+ gr.Warning("Please upload an Input Image to get started.") if input_image is None else hex_create(hex_size, border_size, input_image, start_x, start_y, end_x, end_y, rotation, background_color, background_opacity, border_color, border_opacity, fill_hex, color_display, filter_color, x_spacing, y_spacing, add_hex_text, custom_text_list, custom_text_color_list),
1051
+ inputs=[hex_size, border_size, input_image, start_x, start_y, end_x, end_y, rotation, background_color, background_opacity, border_color, border_opacity, fill_hex, color_display, filter_color, x_spacing, y_spacing, add_hex_text, custom_text_list, custom_text_color_list],
1052
+ outputs=[output_image, overlay_image],
1053
+ scroll_to_output=True
1054
+ )
1055
+ generate_input_image.click(
1056
+ fn=generate_input_image_click,
1057
+ inputs=[map_options, prompt_textbox, negative_prompt_textbox, model_textbox, randomize_seed, seed_slider, gr.State(False), gr.State(0.5), image_size_ratio],
1058
+ outputs=[input_image], scroll_to_output=True
1059
+ )
1060
+ # generate_depth_button.click(
1061
+ # fn=generate_depth_button_click,
1062
+ # inputs=[depth_image_source, voxel_size_factor, input_image, output_image, overlay_image, bordered_image_output],
1063
+ # outputs=[depth_map_output, model_output], scroll_to_output=True
1064
+ # )
1065
+ model_textbox.change(
1066
+ fn=update_prompt_notes,
1067
+ inputs=model_textbox,
1068
+ outputs=prompt_notes_label,preprocess=False
1069
+ )
1070
+ model_options.change(
1071
+ fn=lambda x: (gr.update(visible=(x == "Manual Entry")), gr.update(value=x) if x != "Manual Entry" else gr.update()),
1072
+ inputs=model_options,
1073
+ outputs=[model_textbox, model_textbox]
1074
+ )
1075
+ model_options.change(
1076
+ fn=update_prompt_notes,
1077
+ inputs=model_options,
1078
+ outputs=prompt_notes_label
1079
+ )
1080
+ composite_button.click(
1081
+ fn=lambda input_image, composite_color, composite_opacity: gr.Warning("Please upload an Input Image to get started.") if input_image is None else change_color(input_image, composite_color, composite_opacity),
1082
+ inputs=[input_image, composite_color, composite_opacity],
1083
+ outputs=[input_image]
1084
+ )
1085
 
1086
+ #use conditioned_image as the input_image for generate_input_image_click
1087
+ generate_input_image_from_gallery.click(
1088
+ fn=generate_input_image_click,
1089
+ inputs=[map_options, prompt_textbox, negative_prompt_textbox, model_textbox,randomize_seed, seed_slider, gr.State(True), image_guidance_stength, image_size_ratio],
1090
+ outputs=[input_image], scroll_to_output=True
1091
+ )
1092
 
1093
+ # Update the state variable with the prerendered image filepath when an image is selected
1094
+ prerendered_image_gallery.select(
1095
+ fn=on_prerendered_gallery_selection,
1096
+ inputs=None,
1097
+ outputs=[gr.State(current_prerendered_image)], # Update the state with the selected image
1098
+ show_api=False
1099
+ )
1100
+ # replace input image with selected gallery image
1101
+ replace_input_image_button.click(
1102
+ lambda: current_prerendered_image.value,
1103
+ inputs=None,
1104
+ outputs=[input_image], scroll_to_output=True
1105
+ )
1106
+ output_overlay_composite.change(
1107
+ fn=combine_images_with_lerp,
1108
+ inputs=[input_image, output_image, output_overlay_composite],
1109
+ outputs=[overlay_image], scroll_to_output=True
1110
+ )
1111
+ output_blend_multiply_composite.change(
1112
+ fn=multiply_and_blend_images,
1113
+ inputs=[input_image, output_image, output_blend_multiply_composite],
1114
+ outputs=[overlay_image],
1115
+ scroll_to_output=True
1116
+ )
1117
+ output_alpha_composite.change(
1118
+ fn=alpha_composite_with_control,
1119
+ inputs=[input_image, output_image, output_alpha_composite],
1120
+ outputs=[overlay_image],
1121
+ scroll_to_output=True
1122
+ )
1123
+ add_border_button.click(
1124
+ fn=lambda image_source, mask_w, mask_h, color, opacity, input_img, overlay_img: add_border(input_img if image_source == "Input Image" else overlay_img, mask_w, mask_h, update_color_opacity(detect_color_format(color), opacity * 2.55)),
1125
+ inputs=[border_image_source, mask_width, mask_height, margin_color, margin_opacity, input_image, overlay_image],
1126
+ outputs=[bordered_image_output],
1127
+ scroll_to_output=True
1128
+ )
1129
 
 
 
1130
 
1131
 
1132
+ #if __name__ == "__main__":
1133
+ logging.basicConfig(
1134
+ format="[%(levelname)s] %(asctime)s %(message)s", level=logging.INFO
1135
+ )
1136
+ logging.info("Environment Variables: %s" % os.environ)
1137
  # if _get_output(["nvcc", "--version"]) is None:
1138
  # logging.info("Installing CUDA toolkit...")
1139
  # install_cuda_toolkit()
 
1143
  # logging.info("Installing CUDA extensions...")
1144
  # setup_runtime_env()
1145
  #main(os.getenv("DEBUG") == "1")
1146
+ #main()
1147
+
1148
+ hexaGrid.queue(default_concurrency_limit=1,max_size=12,api_open=False)
1149
+ hexaGrid.launch(allowed_paths=["assets","/","./assets","images","./images", "./images/prerendered"], favicon_path="./assets/favicon.ico", max_file_size="10mb")
src/condition.py CHANGED
@@ -1,4 +1,3 @@
1
- import spaces
2
  import gradio as gr
3
  from torch import Tensor, ones_like
4
  from typing import Optional, Union, List, Tuple
@@ -15,7 +14,7 @@ condition_dict = {
15
  "deblurring": 7,
16
  "fill": 9,
17
  }
18
- @spaces.GPU(progress=gr.Progress(track_tqdm=True))
19
  class Condition(object):
20
  def __init__(
21
  self,
 
 
1
  import gradio as gr
2
  from torch import Tensor, ones_like
3
  from typing import Optional, Union, List, Tuple
 
14
  "deblurring": 7,
15
  "fill": 9,
16
  }
17
+
18
  class Condition(object):
19
  def __init__(
20
  self,