Add application file2
Browse files
app.py
CHANGED
|
@@ -1,19 +1,21 @@
|
|
| 1 |
-
import
|
| 2 |
import gradio as gr
|
| 3 |
import torch
|
| 4 |
from PIL import Image, PngImagePlugin
|
| 5 |
from diffusers import DiffusionPipeline
|
| 6 |
import random
|
|
|
|
|
|
|
| 7 |
from datetime import datetime
|
| 8 |
import json
|
| 9 |
from gradio_client import Client as client_gradio
|
| 10 |
from supabase import create_client, Client
|
| 11 |
-
from huggingface_hub import login
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
| 17 |
|
| 18 |
# Obter o token do Hugging Face a partir dos secrets
|
| 19 |
hf_token = os.getenv("HF_TOKEN")
|
|
@@ -21,43 +23,47 @@ hf_token = os.getenv("HF_TOKEN")
|
|
| 21 |
# Autenticar com o Hugging Face
|
| 22 |
login(token=hf_token)
|
| 23 |
|
| 24 |
-
#
|
| 25 |
base_model = "black-forest-labs/FLUX.1-dev"
|
| 26 |
-
pipe = DiffusionPipeline.from_pretrained(
|
| 27 |
-
base_model,
|
| 28 |
-
torch_dtype=torch.bfloat16,
|
| 29 |
-
use_auth_token=True
|
| 30 |
-
)
|
| 31 |
|
| 32 |
lora_repo = "markury/AndroFlux"
|
| 33 |
-
trigger_word = ""
|
| 34 |
-
pipe.load_lora_weights(lora_repo, weight_name="AndroFlux-v19.safetensors")
|
| 35 |
|
| 36 |
pipe.to("cuda")
|
| 37 |
|
| 38 |
MAX_SEED = 2**32-1
|
| 39 |
|
| 40 |
-
|
| 41 |
-
def run_lora(prompt, cfg_scale, steps, randomize_seed, seed, width, height, lora_scale):
|
|
|
|
| 42 |
if randomize_seed:
|
| 43 |
seed = random.randint(0, MAX_SEED)
|
| 44 |
generator = torch.Generator(device="cuda").manual_seed(seed)
|
| 45 |
|
| 46 |
-
#
|
|
|
|
| 47 |
moderation_client = client_gradio("duchaba/Friendly_Text_Moderation")
|
| 48 |
result = moderation_client.predict(
|
| 49 |
-
|
|
|
|
|
|
|
| 50 |
)
|
| 51 |
-
|
| 52 |
-
if float(json.loads(result[1])[
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
raise gr.Error("Unauthorized request 💥!")
|
| 59 |
|
| 60 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
image = pipe(
|
| 62 |
prompt=f"{prompt} {trigger_word}",
|
| 63 |
num_inference_steps=steps,
|
|
@@ -69,55 +75,81 @@ def run_lora(prompt, cfg_scale, steps, randomize_seed, seed, width, height, lora
|
|
| 69 |
max_sequence_length=512
|
| 70 |
).images[0]
|
| 71 |
|
| 72 |
-
#
|
| 73 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 74 |
image_filename = f"generated_image_{timestamp}.png"
|
| 75 |
image_path = os.path.join("/tmp/gradio", image_filename)
|
| 76 |
|
| 77 |
-
#
|
|
|
|
| 78 |
metadata = PngImagePlugin.PngInfo()
|
| 79 |
-
metadata.add_text("parameters",
|
|
|
|
|
|
|
| 80 |
image.save(image_path, pnginfo=metadata)
|
| 81 |
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
| 83 |
try:
|
| 84 |
if "girl" not in prompt and "woman" not in prompt:
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
)
|
| 88 |
-
image_url = response.full_path
|
| 89 |
-
supabase.table("requests").insert({
|
| 90 |
-
"prompt": prompt, "cfg_scale": cfg_scale, "steps": steps,
|
| 91 |
-
"randomized_seed": randomize_seed, "seed": seed,
|
| 92 |
-
"lora_scale": lora_scale, "image_url": image_url
|
| 93 |
-
}).execute()
|
| 94 |
-
except Exception as error:
|
| 95 |
-
print("Erro ao salvar no Supabase:", error)
|
| 96 |
-
|
| 97 |
-
return image, seed
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
gr.Markdown("# Androflux Image Generator")
|
| 102 |
with gr.Row():
|
| 103 |
with gr.Column(scale=3):
|
| 104 |
-
prompt = gr.TextArea(label="Prompt", placeholder="
|
| 105 |
-
generate_button = gr.Button("
|
| 106 |
-
cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=
|
| 107 |
-
steps = gr.Slider(label="Steps", minimum=1, maximum=100, step=1, value=
|
| 108 |
-
width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=
|
| 109 |
-
height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=
|
| 110 |
randomize_seed = gr.Checkbox(False, label="Randomize seed")
|
| 111 |
-
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=
|
| 112 |
-
lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=1, step=0.01, value=
|
| 113 |
with gr.Column(scale=1):
|
| 114 |
result = gr.Image(label="Generated Image")
|
|
|
|
| 115 |
|
|
|
|
|
|
|
|
|
|
| 116 |
generate_button.click(
|
| 117 |
run_lora,
|
| 118 |
inputs=[prompt, cfg_scale, steps, randomize_seed, seed, width, height, lora_scale],
|
| 119 |
-
outputs=[result, seed]
|
| 120 |
)
|
| 121 |
|
| 122 |
app.queue()
|
| 123 |
-
app.launch()
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
import gradio as gr
|
| 3 |
import torch
|
| 4 |
from PIL import Image, PngImagePlugin
|
| 5 |
from diffusers import DiffusionPipeline
|
| 6 |
import random
|
| 7 |
+
import os
|
| 8 |
+
import pygsheets
|
| 9 |
from datetime import datetime
|
| 10 |
import json
|
| 11 |
from gradio_client import Client as client_gradio
|
| 12 |
from supabase import create_client, Client
|
|
|
|
| 13 |
|
| 14 |
+
|
| 15 |
+
# Initialize supabase
|
| 16 |
+
url: str = os.getenv('SUPABASE_URL')
|
| 17 |
+
key: str = os.getenv('SUPABASE_KEY')
|
| 18 |
+
supabase: Client = create_client(url, key)
|
| 19 |
|
| 20 |
# Obter o token do Hugging Face a partir dos secrets
|
| 21 |
hf_token = os.getenv("HF_TOKEN")
|
|
|
|
| 23 |
# Autenticar com o Hugging Face
|
| 24 |
login(token=hf_token)
|
| 25 |
|
| 26 |
+
# Initialize the base model and specific LoRA
|
| 27 |
base_model = "black-forest-labs/FLUX.1-dev"
|
| 28 |
+
pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=torch.bfloat16)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
lora_repo = "markury/AndroFlux"
|
| 31 |
+
trigger_word = "" # Leave trigger_word blank if not used.
|
| 32 |
+
pipe.load_lora_weights(lora_repo, weight_name = "AndroFlux-v19.safetensors")
|
| 33 |
|
| 34 |
pipe.to("cuda")
|
| 35 |
|
| 36 |
MAX_SEED = 2**32-1
|
| 37 |
|
| 38 |
+
@spaces.GPU(duration=80)
|
| 39 |
+
def run_lora(prompt, cfg_scale, steps, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
|
| 40 |
+
# Set random seed for reproducibility
|
| 41 |
if randomize_seed:
|
| 42 |
seed = random.randint(0, MAX_SEED)
|
| 43 |
generator = torch.Generator(device="cuda").manual_seed(seed)
|
| 44 |
|
| 45 |
+
#Moderation
|
| 46 |
+
|
| 47 |
moderation_client = client_gradio("duchaba/Friendly_Text_Moderation")
|
| 48 |
result = moderation_client.predict(
|
| 49 |
+
msg=f"{prompt}",
|
| 50 |
+
safer=0.02,
|
| 51 |
+
api_name="/fetch_toxicity_level"
|
| 52 |
)
|
| 53 |
+
|
| 54 |
+
if float(json.loads(result[1])['sexual_minors']) > 0.03 :
|
| 55 |
+
print('Minors')
|
| 56 |
+
response_data = (supabase.table("requests")
|
| 57 |
+
.insert({"prompt":prompt, "cfg_scale":cfg_scale, "steps":steps, "randomized_seed": randomize_seed, "seed":seed, "lora_scale" : lora_scale, "moderated" : 'true'})
|
| 58 |
+
.execute()
|
| 59 |
+
)
|
| 60 |
raise gr.Error("Unauthorized request 💥!")
|
| 61 |
|
| 62 |
+
# Update progress bar (0% saat mulai)
|
| 63 |
+
progress(0, "Starting image generation...")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# Generate image using the pipeline
|
| 67 |
image = pipe(
|
| 68 |
prompt=f"{prompt} {trigger_word}",
|
| 69 |
num_inference_steps=steps,
|
|
|
|
| 75 |
max_sequence_length=512
|
| 76 |
).images[0]
|
| 77 |
|
| 78 |
+
# Save the image to a file with a unique name in /tmp directory
|
| 79 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 80 |
image_filename = f"generated_image_{timestamp}.png"
|
| 81 |
image_path = os.path.join("/tmp/gradio", image_filename)
|
| 82 |
|
| 83 |
+
# Add Metadata
|
| 84 |
+
new_metadata_string = f"{prompt}\nNegative prompt: none \nSteps: {steps}, CFG scale: {cfg_scale}, Seed: {seed}, Lora hashes: AndroFlux-v19: c44afd41ece1"
|
| 85 |
metadata = PngImagePlugin.PngInfo()
|
| 86 |
+
metadata.add_text("parameters", new_metadata_string)
|
| 87 |
+
|
| 88 |
+
#Save the tmp image
|
| 89 |
image.save(image_path, pnginfo=metadata)
|
| 90 |
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
#Log queries
|
| 95 |
try:
|
| 96 |
if "girl" not in prompt and "woman" not in prompt:
|
| 97 |
+
#Save image in supabase
|
| 98 |
+
response = supabase.storage.from_('generated_images').upload(image_filename, image_path,file_options={"content-type":"image/png;charset=UTF-8"})
|
| 99 |
+
print(response.dict)
|
| 100 |
+
#Log request in supabase
|
| 101 |
+
response_data = (supabase.table("requests")
|
| 102 |
+
.insert({"prompt":prompt, "cfg_scale":cfg_scale, "steps":steps, "randomized_seed": randomize_seed, "seed":seed, "lora_scale" : lora_scale, "image_url" : response.full_path})
|
| 103 |
+
.execute()
|
| 104 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
+
except Exception as error:
|
| 107 |
+
# handle the exception
|
| 108 |
+
print("An exception occurred:", error)
|
| 109 |
+
|
| 110 |
+
yield image, seed
|
| 111 |
+
|
| 112 |
+
# Example cached image and settings
|
| 113 |
+
example_image_path = "blond_5.webp" # Replace with the actual path to the example image
|
| 114 |
+
example_prompt = """a full frontal view photo of a athletic man with olive skin in his late twenties standing on a flowery terrace at golden hour. He is fully naked with a thick uncut penis and blond pubic hair. The man has long blond hair and has a dominant expression. The setting is outdoors, with a peaceful and aesthetic atmosphere."""
|
| 115 |
+
example_cfg_scale = 3.5
|
| 116 |
+
example_steps = 25
|
| 117 |
+
example_width = 896
|
| 118 |
+
example_height = 1152
|
| 119 |
+
example_seed = 556215326
|
| 120 |
+
example_lora_scale = 1
|
| 121 |
+
|
| 122 |
+
def load_example():
|
| 123 |
+
# Load example image from file
|
| 124 |
+
example_image = Image.open(example_image_path)
|
| 125 |
+
return example_prompt, example_cfg_scale, example_steps, True, example_seed, example_width, example_height, example_lora_scale, example_image
|
| 126 |
+
|
| 127 |
+
gr_theme = os.getenv("THEME")
|
| 128 |
+
with gr.Blocks(theme=gr_theme) as app:
|
| 129 |
gr.Markdown("# Androflux Image Generator")
|
| 130 |
with gr.Row():
|
| 131 |
with gr.Column(scale=3):
|
| 132 |
+
prompt = gr.TextArea(label="Prompt", placeholder="Type a prompt of max 77 characters", lines=3)
|
| 133 |
+
generate_button = gr.Button("Generate")
|
| 134 |
+
cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=example_cfg_scale)
|
| 135 |
+
steps = gr.Slider(label="Steps", minimum=1, maximum=100, step=1, value=example_steps)
|
| 136 |
+
width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=example_width)
|
| 137 |
+
height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=example_height)
|
| 138 |
randomize_seed = gr.Checkbox(False, label="Randomize seed")
|
| 139 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=example_seed)
|
| 140 |
+
lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=1, step=0.01, value=example_lora_scale)
|
| 141 |
with gr.Column(scale=1):
|
| 142 |
result = gr.Image(label="Generated Image")
|
| 143 |
+
gr.Markdown("Generate images using Androflux Lora and a text prompt.\n[[non-commercial license, Flux.1 Dev](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md)]")
|
| 144 |
|
| 145 |
+
# Automatically load example data and image when the interface is launched
|
| 146 |
+
app.load(load_example, inputs=[], outputs=[prompt, cfg_scale, steps, randomize_seed, seed, width, height, lora_scale, result])
|
| 147 |
+
|
| 148 |
generate_button.click(
|
| 149 |
run_lora,
|
| 150 |
inputs=[prompt, cfg_scale, steps, randomize_seed, seed, width, height, lora_scale],
|
| 151 |
+
outputs=[result, seed],
|
| 152 |
)
|
| 153 |
|
| 154 |
app.queue()
|
| 155 |
+
app.launch()
|