Spaces:
vilarin
/
Running on Zero

flux-labs / app.py
vilarin's picture
Update app.py
fda59ae verified
raw
history blame
7.89 kB
import spaces
import os
import gradio as gr
import torch
import numpy as np
import random
from diffusers import FluxPipeline
from translatepy import Translator
from huggingface_hub import hf_hub_download
import requests
import re
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
translator = Translator()
HF_TOKEN = os.environ.get("HF_TOKEN", None)
# Constants
model = "black-forest-labs/FLUX.1-dev"
MAX_SEED = np.iinfo(np.int32).max
CSS = """
footer {
visibility: hidden;
}
"""
JS = """function () {
gradioURL = window.location.href
if (!gradioURL.endsWith('?__theme=dark')) {
window.location.replace(gradioURL + '?__theme=dark');
}
}"""
if torch.cuda.is_available():
pipe = FluxPipeline.from_pretrained(model, torch_dtype=torch.bfloat16)
def scrape_lora_link(url):
try:
# Send a GET request to the URL
response = requests.get(url)
response.raise_for_status() # Raise an exception for bad status codes
# Get the content of the page
content = response.text
# Use regular expression to find the link
pattern = r'href="(.*?lora.*?\.safetensors\?download=true)"'
match = re.search(pattern, content)
if match:
safetensors_url = match.group(1)
filename = safetensors_url.split('/')[-1].split('?')[0] # Extract the filename from the URL
return filename
else:
return None
except requests.RequestException as e:
print(f"An error occurred while fetching the URL: {e}")
return None
def enable_lora(lora_scale,lora_add):
if not lora_add:
gradio.Info("No Lora Loaded, Use basemodel", duration=5)
else:
url = f'https://huggingface.co/{lora_add}/tree/main'
lora_name = scrape_lora_link(url)
pipe.load_lora_weights(lora_add, weight_name=lora_name)
pipe.fuse_lora(lora_scale=lora_scale)
gradio.Info(f"{lora_add} Loaded", duration=5)
@spaces.GPU()
def generate_image(
prompt:str,
lora_word:str,
width:int=768,
height:int=1024,
scales:float=3.5,
steps:int=24,
seed:int=-1,
nums:int=1):
pipe.to(device="cuda")
if seed == -1:
seed = random.randint(0, MAX_SEED)
seed = int(seed)
print(f'prompt:{prompt}')
text = str(translator.translate(prompt, 'English')) + "," + lora_word
generator = torch.Generator().manual_seed(seed)
image = pipe(
prompt=text,
height=height,
width=width,
guidance_scale=scales,
output_type="pil",
num_inference_steps=steps,
max_sequence_length=512,
num_images_per_prompt=nums,
generator=generator,
).images
return image, seed
examples = [
["close up portrait, Amidst the interplay of light and shadows in a photography studio,a soft spotlight traces the contours of a face,highlighting a figure clad in a sleek black turtleneck. The garment,hugging the skin with subtle luxury,complements the Caucasian model's understated makeup,embodying minimalist elegance. Behind,a pale gray backdrop extends,its fine texture shimmering subtly in the dim light,artfully balancing the composition and focusing attention on the subject. In a palette of black,gray,and skin tones,simplicity intertwines with profundity,as every detail whispers untold stories.",0.9,"Shakker-Labs/AWPortrait-FL",""],
["Caucasian,The image features a young woman of European descent standing in an studio setting,surrounded by silk. (She is wearing a silk dress),paired with a bold. Her brown hair is wet and tousled,falling naturally around her face,giving her a raw and edgy look. The woman has an intense and direct gaze,adding to the dramatic feel of the image. The backdrop is flowing silk,big silk. The overall composition blends elements of fashion and nature,creating a striking and powerful visual",0.9,"Shakker-Labs/AWPortrait-FL",""],
["A black and white portrait of a young woman with a captivating gaze. She's bundled up in a cozy black sweater,hands gently cupped near her face. The monochromatic tones highlight her delicate features and the contemplative mood of the image",0.9,"Shakker-Labs/AWPortrait-FL",""],
["Fashion photography portrait,close up portrait,(a woman of European descent is surrounded by lava rock and magma from head to neck, red magma hair, wear volcanic lava rock magma outfit coat lava rock magma fashion costume with ruffled layers",0.9,"Shakker-Labs/AWPortrait-FL",""]
]
# Gradio Interface
with gr.Blocks(css=CSS, js=JS, theme="Nymbo/Nymbo_Theme") as demo:
gr.HTML("<h1><center>Flux Labs</center></h1>")
gr.HTML("<p><center>Choose the LoRA model on the right menu</center></p>")
with gr.Row():
with gr.Column(scale=4):
img = gr.Gallery(label='flux Generated Image', columns = 1, preview=True, height=600)
with gr.Row():
prompt = gr.Textbox(label='Enter Your Prompt (Multi-Languages)', placeholder="Enter prompt...", scale=6)
sendBtn = gr.Button(scale=1, variant='primary')
with gr.Accordion("Advanced Options", open=True):
with gr.Column(scale=1):
width = gr.Slider(
label="Width",
minimum=512,
maximum=1280,
step=8,
value=768,
)
height = gr.Slider(
label="Height",
minimum=512,
maximum=1280,
step=8,
value=1024,
)
scales = gr.Slider(
label="Guidance",
minimum=3.5,
maximum=7,
step=0.1,
value=3.5,
)
steps = gr.Slider(
label="Steps",
minimum=1,
maximum=100,
step=1,
value=24,
)
seed = gr.Slider(
label="Seeds",
minimum=-1,
maximum=MAX_SEED,
step=1,
value=-1,
)
nums = gr.Slider(
label="Image Numbers",
minimum=1,
maximum=4,
step=1,
value=1,
)
lora_scale = gr.Slider(
label="LoRA Scale",
minimum=0.1,
maximum=1.0,
step=0.1,
value=1.0,
)
lora_add = gr.Textbox(
label="Add Flux LoRA",
info="Copy the HF LoRA model name here",
lines=1,
value="Shakker-Labs/AWPortrait-FL",
)
lora_word = gr.Textbox(
label="Add Flux LoRA Trigger Word",
info="Add the Trigger Word",
lines=1,
value="",
)
load_lora = gr.Button(value="Load LoRA", variant='secondary')
gr.Examples(
examples=examples,
inputs=[prompt,lora_scale,lora_add,lora_word],
cache_examples=False,
examples_per_page=4,
)
load_lora.click(fn=enable_lora, inputs=[lora_scale,lora_add])
gr.on(
triggers=[
prompt.submit,
sendBtn.click,
],
fn=generate_image,
inputs=[
prompt,
lora_word,
width,
height,
scales,
steps,
seed,
nums
],
outputs=[img, seed],
api_name="run",
)
demo.queue().launch()