|
import huggingface_hub |
|
import subprocess |
|
subprocess.run(["pip", "install", "text_generation"]) |
|
import text_generation |
|
|
|
|
|
print("huggingface_hub version:", huggingface_hub.__version__) |
|
print("text_generation version:", text_generation.__version__) |
|
import gradio as gr |
|
from random import randint |
|
from all_models import models |
|
|
|
from externalmod import gr_Interface_load, randomize_seed |
|
|
|
import asyncio |
|
import os |
|
from threading import RLock |
|
|
|
|
|
lock = RLock() |
|
|
|
HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None |
|
|
|
|
|
def load_fn(models): |
|
global models_load |
|
models_load = {} |
|
|
|
|
|
for model in models: |
|
if model not in models_load.keys(): |
|
try: |
|
|
|
print(f"Attempting to load model: {model}") |
|
|
|
m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN) |
|
print(f"Successfully loaded model: {model}") |
|
except Exception as error: |
|
|
|
print(f"Error loading model {model}: {error}") |
|
m = gr.Interface(lambda: None, ['text'], ['image']) |
|
|
|
models_load.update({model: m}) |
|
|
|
|
|
print("Loading models...") |
|
load_fn(models) |
|
print("Models loaded successfully.") |
|
|
|
num_models = 6 |
|
|
|
|
|
default_models = models[:num_models] |
|
inference_timeout = 600 |
|
MAX_SEED = 3999999999 |
|
|
|
starting_seed = randint(1941, 2024) |
|
print(f"Starting seed: {starting_seed}") |
|
|
|
|
|
def extend_choices(choices): |
|
print(f"Extending choices: {choices}") |
|
extended = choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA'] |
|
print(f"Extended choices: {extended}") |
|
return extended |
|
|
|
|
|
def update_imgbox(choices): |
|
print(f"Updating image boxes with choices: {choices}") |
|
choices_plus = extend_choices(choices[:num_models]) |
|
imgboxes = [gr.Image(None, label=m, visible=(m != 'NA')) for m in choices_plus] |
|
print(f"Updated image boxes: {imgboxes}") |
|
return imgboxes |
|
|
|
|
|
async def infer(model_str, prompt, seed=1, timeout=inference_timeout): |
|
from pathlib import Path |
|
kwargs = {} |
|
noise = "" |
|
kwargs["seed"] = seed |
|
|
|
print(f"Starting inference for model: {model_str} with prompt: '{prompt}' and seed: {seed}") |
|
task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn, |
|
prompt=f'{prompt} {noise}', **kwargs, token=HF_TOKEN)) |
|
await asyncio.sleep(0) |
|
try: |
|
|
|
result = await asyncio.wait_for(task, timeout=timeout) |
|
print(f"Inference completed for model: {model_str}") |
|
except (Exception, asyncio.TimeoutError) as e: |
|
|
|
print(f"Error during inference for model {model_str}: {e}") |
|
if not task.done(): |
|
task.cancel() |
|
print(f"Task cancelled for model: {model_str}") |
|
result = None |
|
|
|
if task.done() and result is not None: |
|
with lock: |
|
png_path = "image.png" |
|
result.save(png_path) |
|
image = str(Path(png_path).resolve()) |
|
print(f"Result saved as image: {image}") |
|
return image |
|
print(f"No result for model: {model_str}") |
|
return None |
|
|
|
|
|
def gen_fnseed(model_str, prompt, seed=1): |
|
if model_str == 'NA': |
|
print(f"Model is 'NA', skipping generation.") |
|
return None |
|
try: |
|
|
|
print(f"Generating image for model: {model_str} with prompt: '{prompt}' and seed: {seed}") |
|
loop = asyncio.new_event_loop() |
|
result = loop.run_until_complete(infer(model_str, prompt, seed, inference_timeout)) |
|
except (Exception, asyncio.CancelledError) as e: |
|
|
|
print(f"Error during generation for model {model_str}: {e}") |
|
result = None |
|
finally: |
|
|
|
loop.close() |
|
print(f"Event loop closed for model: {model_str}") |
|
return result |
|
|
|
|
|
print("Creating Gradio interface...") |
|
with gr.Blocks(theme="Nymbo/Nymbo_Theme") as demo: |
|
gr.HTML("<center><h1>Compare-6</h1></center>") |
|
with gr.Tab('Compare-6'): |
|
|
|
txt_input = gr.Textbox(label='Your prompt:', lines=4) |
|
|
|
gen_button = gr.Button('Generate up to 6 images in up to 3 minutes total') |
|
with gr.Row(): |
|
|
|
seed = gr.Slider(label="Use a seed to replicate the same image later (maximum 3999999999)", minimum=0, maximum=MAX_SEED, step=1, value=starting_seed, scale=3) |
|
|
|
seed_rand = gr.Button("Randomize Seed 🎲", size="sm", variant="secondary", scale=1) |
|
|
|
seed_rand.click(randomize_seed, None, [seed], queue=False) |
|
print("Seed randomization button set up.") |
|
|
|
gen_button.click(lambda s: gr.update(interactive=True), None) |
|
print("Generation button set up.") |
|
|
|
with gr.Row(): |
|
|
|
output = [gr.Image(label=m, min_width=480) for m in default_models] |
|
|
|
current_models = [gr.Textbox(m, visible=False) for m in default_models] |
|
|
|
|
|
for m, o in zip(current_models, output): |
|
print(f"Setting up generation event for model: {m.value}") |
|
gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fnseed, |
|
inputs=[m, txt_input, seed], outputs=[o], concurrency_limit=None, queue=False) |
|
|
|
|
|
|
|
with gr.Accordion('Model selection'): |
|
|
|
model_choice = gr.CheckboxGroup(models, label=f'Choose up to {int(num_models)} different models from the {len(models)} available!', value=default_models, interactive=True) |
|
|
|
model_choice.change(update_imgbox, model_choice, output) |
|
model_choice.change(extend_choices, model_choice, current_models) |
|
print("Model selection setup complete.") |
|
with gr.Row(): |
|
|
|
gr.HTML( |
|
) |
|
|
|
|
|
print("Setting up queue...") |
|
demo.queue(default_concurrency_limit=200, max_size=200) |
|
print("Launching Gradio interface...") |
|
demo.launch(show_api=False, max_threads=400) |
|
print("Gradio interface launched successfully.") |