File size: 7,246 Bytes
15d3291
 
 
bab5770
 
15d3291
bab5770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15d3291
 
bab5770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15d3291
bab5770
 
dad57b3
 
bab5770
15d3291
bab5770
 
 
 
 
 
 
 
 
 
 
 
dda662d
bab5770
 
dad57b3
bab5770
 
 
 
 
 
 
 
 
 
 
 
 
 
dda662d
bab5770
 
 
 
 
 
 
 
 
 
 
15d3291
bab5770
15d3291
bab5770
 
15d3291
bab5770
 
15d3291
bab5770
 
 
 
15d3291
bab5770
 
15d3291
bab5770
 
15d3291
bab5770
 
15d3291
bab5770
 
15d3291
bab5770
 
15d3291
bab5770
 
 
 
 
15d3291
bab5770
 
 
dda662d
bab5770
15d3291
 
bab5770
 
 
15d3291
 
bab5770
 
 
15d3291
 
bab5770
 
 
 
 
 
15d3291
bab5770
 
15d3291
bab5770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15d3291
 
 
bab5770
 
 
 
 
 
 
 
15d3291
 
 
bab5770
15d3291
bab5770
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import gradio as gr
import numpy as np
import random
import os
from huggingface_hub import login, hf_hub_download
import torch
import spaces
from diffusers import FluxPipeline
import logging

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("app.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger("moroccan-ghibli-flux-compare")

# Constants
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
DEFAULT_SEED = 42
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Global pipelines
pipeline_base = None
pipeline_lora = None

def load_base_pipeline():
    api_key = os.getenv("HF_TOKEN")
    if not api_key:
        raise ValueError("HF_TOKEN environment variable not set.")
    login(token=api_key)

    logger.info("Loading base Flux model (no LoRA)")
    pipe = FluxPipeline.from_pretrained(
        "black-forest-labs/FLUX.1-dev",
        torch_dtype=torch.bfloat16,
    )
    return pipe

def load_lora_pipeline(revision: str):
    api_key = os.getenv("HF_TOKEN")
    if not api_key:
        raise ValueError("HF_TOKEN environment variable not set.")
    login(token=api_key)

    logger.info(f"Loading Flux model with LoRA revision: {revision}")
    pipe = FluxPipeline.from_pretrained(
        "black-forest-labs/FLUX.1-dev",
        torch_dtype=torch.bfloat16,
    )

    # Extract step number from revision name (e.g., "step_1500" -> "1500")
    step_num = revision.split('_')[-1]
    if len(step_num) < 4:
        step_num = '0' + step_num
    filename = f"moroccan_ghibli_flux_lora_00000{step_num}.safetensors"

    logger.info(f"Downloading LoRA weights: {filename}")
    lora_path = hf_hub_download(
        repo_id="atlasia/moroccan-ghibli-flux-lora",
        filename=filename,
        revision=revision,
        token=api_key
    )

    logger.info("Loading LoRA weights into the pipeline")
    pipe.load_lora_weights(lora_path)
    return pipe

def init_pipelines(style_intensity: str = "low"):
    global pipeline_base, pipeline_lora
    revision_map = {
        "low": "step_750",
        "medium": "step_1500",
        "high": "step_2500"
    }
    revision = revision_map[style_intensity]

    if pipeline_base is None:
        pipeline_base = load_base_pipeline()
        logger.info("Base pipeline loaded")

    logger.info(f"Initializing LoRA pipeline with style: {style_intensity} ({revision})")
    pipeline_lora = load_lora_pipeline(revision)
    logger.info("LoRA pipeline loaded")

# Initial pipelines
init_pipelines("low")

def update_lora_pipeline(style_intensity):
    logger.info(f"Updating LoRA pipeline to style: {style_intensity}")
    init_pipelines(style_intensity)

def _run_pipeline(pipe: FluxPipeline, prompt: str, seed: int, width: int, height: int, guidance_scale: float):
    pipe.to(device)
    generator = torch.Generator(device=device).manual_seed(seed)
    max_sequence_length = 512
    output = pipe(
        prompt=[prompt],
        guidance_scale=guidance_scale,
        num_inference_steps=50,
        height=height,
        width=width,
        max_sequence_length=max_sequence_length,
        generator=generator,
    )
    return output.images[0]

@spaces.GPU(duration=120)
def infer(prompt, seed, width, height, guidance_scale, progress=gr.Progress()):
    logger.info(f"Generating comparison for prompt: '{prompt[:50]}...'")
    logger.info(f"Parameters: seed={seed}, width={width}, height={height}, guidance={guidance_scale}")

    progress(0.1, desc="Preparing base model")
    base_image = _run_pipeline(pipeline_base, prompt, seed, width, height, guidance_scale)

    progress(0.55, desc="Preparing LoRA model")
    lora_image = _run_pipeline(pipeline_lora, prompt, seed, width, height, guidance_scale)

    progress(0.95, desc="Processing results")
    logger.info("Comparison generation completed successfully")

    # Return both images and the used seed
    return base_image, lora_image, seed

def randomize_seed():
    return random.randint(0, MAX_SEED)

with gr.Blocks() as demo:
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("# Flux: Base vs Moroccan-Ghibli LoRA")
            gr.Markdown("Generate side-by-side images with identical settings to compare the base model and the Moroccan Ghibli LoRA.")

            style_intensity = gr.Dropdown(
                label="LoRA Style Intensity",
                choices=["low", "medium", "high"],
                value="low",
                interactive=True
            )

            prompt = gr.Textbox(
                label="Prompt",
                placeholder="Enter your prompt (e.g., 'Moroccan Ghibli studio style portrait')",
            )

            with gr.Row():
                seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=DEFAULT_SEED, interactive=True)
                randomize_button = gr.Button("Randomize Seed")

            with gr.Row():
                width = gr.Slider(label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=1024)
                height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=1024)

            guidance_scale = gr.Slider(label="Guidance scale", minimum=0.0, maximum=10.0, step=0.1, value=3.5)

            run_button = gr.Button("Generate", variant="primary")

        with gr.Column(scale=2):
            gr.Markdown("## Generated Images")
            with gr.Row():
                base_image = gr.Image(label="Base Model", height=512)
                lora_image = gr.Image(label="Moroccan Ghibli LoRA", height=512)
            output_seed = gr.Number(label="Used Seed", precision=0)

            gr.Markdown("## Example Prompts")
            examples = [
                ["Moroccan Ghibli studio style portrait of a character in a riad courtyard", DEFAULT_SEED, 1024, 1024, 3.5],
                ["Moroccan Ghibli studio style image of a bustling souk with flying carpets", DEFAULT_SEED, 1024, 1024, 3.5],
                ["Moroccan Ghibli studio style landscape of a desert oasis under starry skies", DEFAULT_SEED, 1024, 1024, 3.5],
                ["Moroccan Ghibli studio style depiction of a magical lantern festival", DEFAULT_SEED, 1024, 1024, 3.5],
                ["Moroccan Ghibli studio style portrait of a medina at sunset", DEFAULT_SEED, 1024, 1024, 3.5]
            ]
            gr.Examples(
                examples=examples,
                inputs=[prompt, seed, width, height, guidance_scale],
                outputs=[base_image, lora_image, output_seed],
                fn=infer,
                cache_examples=True
            )

    style_intensity.change(
        fn=update_lora_pipeline,
        inputs=[style_intensity],
        outputs=[]
    )

    gr.on(
        triggers=[run_button.click, prompt.submit],
        fn=infer,
        inputs=[prompt, seed, width, height, guidance_scale],
        outputs=[base_image, lora_image, output_seed]
    )

    randomize_button.click(
        fn=randomize_seed,
        inputs=[],
        outputs=[seed]
    )

if __name__ == "__main__":
    logger.info("Starting application")
    demo.launch()
    logger.info("Application closed")