|
import os |
|
import gradio as gr |
|
import json |
|
import logging |
|
from PIL import Image |
|
|
|
from huggingface_hub import ModelCard, HfFileSystem |
|
from huggingface_hub import InferenceClient |
|
import copy |
|
import random |
|
import time |
|
import re |
|
|
|
|
|
|
|
HF_API_KEY = os.getenv("HF_API_KEY") |
|
if not HF_API_KEY: |
|
|
|
try: |
|
HF_API_KEY = gr.secrets.get("HF_API_KEY") |
|
except (AttributeError, KeyError): |
|
HF_API_KEY = None |
|
|
|
if not HF_API_KEY: |
|
logging.warning("HF_API_KEY not found in environment variables or Gradio secrets. Inference API calls will likely fail.") |
|
|
|
|
|
client = None |
|
else: |
|
client = InferenceClient(provider="fal-ai", token=HF_API_KEY) |
|
|
|
|
|
|
|
with open('loras.json', 'r') as f: |
|
loras = json.load(f) |
|
|
|
|
|
|
|
MAX_SEED = 2**32-1 |
|
|
|
class calculateDuration: |
|
def __init__(self, activity_name=""): |
|
self.activity_name = activity_name |
|
|
|
def __enter__(self): |
|
self.start_time = time.time() |
|
return self |
|
|
|
def __exit__(self, exc_type, exc_value, traceback): |
|
self.end_time = time.time() |
|
self.elapsed_time = self.end_time - self.start_time |
|
if self.activity_name: |
|
print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds") |
|
else: |
|
print(f"Elapsed time: {self.elapsed_time:.6f} seconds") |
|
|
|
|
|
def update_selection(evt: gr.SelectData): |
|
selected_lora = loras[evt.index] |
|
new_placeholder = f"Type a prompt for {selected_lora['title']}" |
|
lora_repo = selected_lora["repo"] |
|
|
|
updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨ (Model ID: `{lora_repo}`)" |
|
|
|
|
|
width = 1024 |
|
height = 1024 |
|
|
|
if "aspect" in selected_lora: |
|
if selected_lora["aspect"] == "portrait": |
|
width = 768 |
|
height = 1024 |
|
elif selected_lora["aspect"] == "landscape": |
|
width = 1024 |
|
height = 768 |
|
|
|
|
|
|
|
return ( |
|
gr.update(placeholder=new_placeholder), |
|
updated_text, |
|
evt.index, |
|
gr.update(value=width), |
|
gr.update(value=height), |
|
) |
|
|
|
def run_lora(prompt, selected_index, current_seed, current_width, current_height): |
|
global client |
|
|
|
if client is None: |
|
raise gr.Error("InferenceClient could not be initialized. Missing HF_API_KEY.") |
|
|
|
if selected_index is None: |
|
raise gr.Error("You must select a LoRA/Model before proceeding.") |
|
|
|
|
|
cfg_scale = 7.0 |
|
steps = 30 |
|
|
|
randomize_seed = True |
|
|
|
|
|
selected_lora = loras[selected_index] |
|
|
|
model_id = selected_lora["repo"] |
|
trigger_word = selected_lora.get("trigger_word", "") |
|
|
|
|
|
if trigger_word: |
|
trigger_position = selected_lora.get("trigger_position", "prepend") |
|
if trigger_position == "prepend": |
|
prompt_mash = f"{trigger_word} {prompt}" |
|
else: |
|
prompt_mash = f"{prompt} {trigger_word}" |
|
else: |
|
prompt_mash = prompt |
|
|
|
|
|
seed_to_use = current_seed |
|
if randomize_seed: |
|
seed_to_use = random.randint(0, MAX_SEED) |
|
|
|
|
|
|
|
|
|
|
|
final_image = None |
|
try: |
|
with calculateDuration(f"API Inference (txt2img) for {model_id}"): |
|
print(f"Running Text-to-Image for Model: {model_id}") |
|
final_image = client.text_to_image( |
|
prompt=prompt_mash, |
|
model=model_id, |
|
guidance_scale=cfg_scale, |
|
num_inference_steps=steps, |
|
seed=seed_to_use, |
|
width=current_width, |
|
height=current_height, |
|
|
|
|
|
) |
|
|
|
except Exception as e: |
|
print(f"Error during API call: {e}") |
|
|
|
if "authorization" in str(e).lower() or "401" in str(e): |
|
raise gr.Error(f"Authorization error calling the Inference API. Please ensure your HF_API_KEY is valid and has the necessary permissions. Error: {e}") |
|
elif "model is currently loading" in str(e).lower() or "503" in str(e): |
|
raise gr.Error(f"Model '{model_id}' is currently loading or unavailable. Please try again in a few moments. Error: {e}") |
|
else: |
|
raise gr.Error(f"Failed to generate image using the API. Model: {model_id}. Error: {e}") |
|
|
|
|
|
return final_image, seed_to_use, gr.update(visible=False) |
|
|
|
|
|
|
|
|
|
def parse_hf_link(link): |
|
"""Parses a Hugging Face link or repo ID string.""" |
|
if link.startswith("https://huggingface.co/"): |
|
link = link.replace("https://huggingface.co/", "") |
|
elif link.startswith("www.huggingface.co/"): |
|
link = link.replace("www.huggingface.co/", "") |
|
|
|
if "/" not in link or len(link.split("/")) != 2: |
|
raise ValueError("Invalid Hugging Face repository ID format. Expected 'user/model'.") |
|
return link.strip() |
|
|
|
def get_model_details(repo_id): |
|
"""Fetches model card details (image, trigger word) if possible.""" |
|
try: |
|
model_card = ModelCard.load(repo_id) |
|
image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None) |
|
trigger_word = model_card.data.get("instance_prompt", "") |
|
|
|
if not trigger_word: |
|
trigger_word = model_card.data.get("trigger_words", [""])[0] |
|
|
|
image_url = f"https://huggingface.co/{repo_id}/resolve/main/{image_path}" if image_path else None |
|
|
|
|
|
if not image_url: |
|
fs = HfFileSystem() |
|
files = fs.ls(repo_id, detail=False) |
|
image_extensions = (".jpg", ".jpeg", ".png", ".webp") |
|
for file in files: |
|
filename = file.split("/")[-1] |
|
if filename.lower().endswith(image_extensions): |
|
image_url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}" |
|
break |
|
|
|
|
|
title = model_card.data.get("model_display_name", repo_id.split('/')[-1]) |
|
|
|
return title, trigger_word, image_url |
|
except Exception as e: |
|
print(f"Could not fetch model card details for {repo_id}: {e}") |
|
|
|
return repo_id.split('/')[-1], "", None |
|
|
|
|
|
def add_custom_lora(custom_lora_input): |
|
global loras |
|
if not custom_lora_input: |
|
|
|
return gr.update(visible=False, value=""), gr.update(visible=False), gr.update(), "", None, "" |
|
|
|
try: |
|
repo_id = parse_hf_link(custom_lora_input) |
|
print(f"Attempting to add custom model: {repo_id}") |
|
|
|
|
|
existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo_id), None) |
|
|
|
if existing_item_index is not None: |
|
print(f"Model {repo_id} already exists in the list.") |
|
|
|
selected_lora = loras[existing_item_index] |
|
title = selected_lora.get('title', repo_id.split('/')[-1]) |
|
image = selected_lora.get('image', None) |
|
trigger_word = selected_lora.get('trigger_word', '') |
|
else: |
|
|
|
title, trigger_word, image = get_model_details(repo_id) |
|
print(f"Adding new model: {repo_id}, Title: {title}, Trigger: '{trigger_word}', Image: {image}") |
|
new_item = { |
|
"image": image, |
|
"title": title, |
|
"repo": repo_id, |
|
|
|
"trigger_word": trigger_word |
|
} |
|
loras.append(new_item) |
|
existing_item_index = len(loras) - 1 |
|
|
|
|
|
card = f''' |
|
<div class="custom_lora_card"> |
|
<span>Loaded custom model:</span> |
|
<div class="card_internal"> |
|
{f'<img src="{image}" alt="{title} preview"/>' if image else '<div class="no-image">No Image</div>'} |
|
<div> |
|
<h3>{title}</h3> |
|
<small>Model ID: <code>{repo_id}</code><br></small> |
|
<small>{"Using trigger word: <code><b>"+trigger_word+"</code></b>" if trigger_word else "No specific trigger word found in card. Include if needed."}<br></small> |
|
</div> |
|
</div> |
|
</div> |
|
''' |
|
|
|
|
|
updated_gallery_items = [(item.get("image"), item.get("title", item["repo"].split('/')[-1])) for item in loras] |
|
|
|
|
|
return ( |
|
gr.update(visible=True, value=card), |
|
gr.update(visible=True), |
|
gr.Gallery(value=updated_gallery_items, selected_index=existing_item_index), |
|
f"### Selected: [{repo_id}](https://huggingface.co/{repo_id}) ✨ (Model ID: `{repo_id}`)", |
|
existing_item_index, |
|
gr.update(placeholder=f"Type a prompt for {title}") |
|
) |
|
|
|
except ValueError as e: |
|
gr.Warning(f"Invalid Input: {e}") |
|
return gr.update(visible=True, value=f"Invalid input: {e}"), gr.update(visible=False), gr.update(), "", None, "" |
|
except Exception as e: |
|
gr.Warning(f"Error adding custom model: {e}") |
|
|
|
return gr.update(visible=True, value=f"Error adding custom model: {e}"), gr.update(visible=False), gr.update(), "", None, "" |
|
|
|
|
|
def remove_custom_lora(): |
|
|
|
|
|
|
|
return gr.update(visible=False, value=""), gr.update(visible=False), gr.update(selected_index=None), "", None, gr.update(value="") |
|
|
|
|
|
|
|
css = ''' |
|
#gen_btn{height: 100%} |
|
#gen_column{align-self: stretch} |
|
#title{text-align: center} |
|
#title h1{font-size: 3em; display:inline-flex; align-items:center} |
|
#title img{width: 100px; margin-right: 0.5em} |
|
#gallery .grid-wrap{height: 10vh} |
|
#lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%} |
|
.card_internal{display: flex;height: 100px;margin-top: .5em; align-items: center;} |
|
.card_internal img{margin-right: 1em; height: 100%; width: auto; object-fit: cover;} |
|
.card_internal .no-image { width: 100px; height: 100px; background-color: #eee; display: flex; align-items: center; justify-content: center; color: #aaa; margin-right: 1em; font-size: small;} |
|
.styler{--form-gap-width: 0px !important} |
|
#progress{height:30px} |
|
#progress .generating{display:none} |
|
/* Keep progress bar CSS for potential future use or remove if definitely not needed */ |
|
.progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px} |
|
.progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.5s ease-in-out} |
|
''' |
|
font=[gr.themes.GoogleFont("Source Sans Pro"), "Arial", "sans-serif"] |
|
with gr.Blocks(theme=gr.themes.Soft(font=font), css=css, delete_cache=(60, 60)) as app: |
|
title = gr.HTML( |
|
"""<h1><img src="https://huggingface.co/spaces/reach-vb/Blazingly-fast-LoRA/resolve/main/flux_lora.png" alt="LoRA"> <a href="https://huggingface.co/docs/inference-providers/en/index">Blazingly Fast LoRA by Fal & HF</a> 🤗</h1>""", |
|
elem_id="title", |
|
) |
|
|
|
selected_index = gr.State(None) |
|
width = gr.State(1024) |
|
height = gr.State(1024) |
|
seed = gr.State(0) |
|
|
|
|
|
with gr.Row(): |
|
with gr.Column(scale=3): |
|
prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA/Model") |
|
with gr.Column(scale=1, elem_id="gen_column"): |
|
generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn") |
|
with gr.Row(): |
|
with gr.Column(): |
|
selected_info = gr.Markdown("Select a base model or add a custom one below.") |
|
gallery = gr.Gallery( |
|
|
|
[(item.get("image"), item.get("title", item["repo"].split('/')[-1])) for item in loras], |
|
label="Model Gallery", |
|
allow_preview=False, |
|
columns=3, |
|
elem_id="gallery", |
|
show_share_button=False |
|
) |
|
with gr.Group(): |
|
custom_lora = gr.Textbox(label="Custom Model", info="Hugging Face model ID (e.g., user/model-name) or URL", placeholder="stabilityai/stable-diffusion-xl-base-1.0") |
|
gr.Markdown("[Check Hugging Face Models](https://huggingface.co/models?inference_provider=fal-ai&pipeline_tag=text-to-image&sort=trending)", elem_id="lora_list") |
|
custom_lora_info = gr.HTML(visible=False) |
|
custom_lora_button = gr.Button("Clear custom model info", visible=False) |
|
with gr.Column(): |
|
|
|
progress_bar = gr.Markdown(elem_id="progress", visible=False, value="Generating...") |
|
result = gr.Image(label="Generated Image") |
|
|
|
used_seed_display = gr.Textbox(label="Seed Used", value=0, interactive=False) |
|
|
|
|
|
|
|
|
|
|
|
|
|
gallery.select( |
|
update_selection, |
|
inputs=[], |
|
|
|
outputs=[prompt, selected_info, selected_index, width, height], |
|
api_name=False |
|
) |
|
|
|
custom_lora.submit( |
|
add_custom_lora, |
|
inputs=[custom_lora], |
|
|
|
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt], |
|
api_name=False |
|
) |
|
custom_lora_button.click( |
|
remove_custom_lora, |
|
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora], |
|
api_name=False |
|
|
|
) |
|
gr.on( |
|
triggers=[generate_button.click, prompt.submit], |
|
fn=run_lora, |
|
|
|
inputs=[prompt, selected_index, seed, width, height], |
|
|
|
outputs=[result, seed, progress_bar], |
|
api_name=False |
|
).then( |
|
|
|
lambda s: gr.update(value=s), |
|
inputs=[seed], |
|
outputs=[used_seed_display], |
|
api_name=False |
|
) |
|
|
|
|
|
app.queue() |
|
app.launch() |