ovi054 commited on
Commit
e9beed4
·
verified ·
1 Parent(s): 1eae428

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -123
app.py CHANGED
@@ -7,7 +7,6 @@ from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler, Autoe
7
  from transformers import CLIPTextModel, CLIPTokenizer,T5EncoderModel, T5TokenizerFast
8
  from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
9
 
10
-
11
  dtype = torch.bfloat16
12
  device = "cuda" if torch.cuda.is_available() else "cpu"
13
 
@@ -21,20 +20,6 @@ MAX_IMAGE_SIZE = 2048
21
 
22
  pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
23
 
24
- article_text = """
25
- <div style="text-align: center;">
26
- <p>Enjoying the tool? Buy me a coffee and get exclusive prompt guides!</p>
27
- <p><i>Instantly unlock helpful tips for creating better prompts!</i></p>
28
- <div style="display: flex; justify-content: center;">
29
- <a href="https://piczify.lemonsqueezy.com/buy/0f5206fa-68e8-42f6-9ca8-4f80c587c83e">
30
- <img src="https://www.buymeacoffee.com/assets/img/custom_images/yellow_img.png"
31
- alt="Buy Me a Coffee"
32
- style="height: 40px; width: auto; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); border-radius: 10px;">
33
- </a>
34
- </div>
35
- </div>
36
- """
37
-
38
  @spaces.GPU()
39
  def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidance_scale=3.5, num_inference_steps=28, lora_id=None, lora_scale=0.95, progress=gr.Progress(track_tqdm=True)):
40
  if randomize_seed:
@@ -81,128 +66,117 @@ def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidan
81
  # Unload LoRA weights if they were loaded
82
  if lora_id:
83
  pipe.unload_lora_weights()
84
-
85
- # def query(lora_id, prompt, steps=28, cfg_scale=3.5, randomize_seed=True, seed=-1, width=1024, height=1024):
86
- # if prompt == "" or prompt == None:
87
- # return None
88
-
89
- # if lora_id.strip() == "" or lora_id == None:
90
- # lora_id = "black-forest-labs/FLUX.1-dev"
91
-
92
- # key = random.randint(0, 999)
93
-
94
- # API_URL = "https://api-inference.huggingface.co/models/"+ lora_id.strip()
95
-
96
- # API_TOKEN = random.choice([os.getenv("HF_READ_TOKEN")])
97
- # headers = {"Authorization": f"Bearer {API_TOKEN}"}
98
-
99
- # # prompt = GoogleTranslator(source='ru', target='en').translate(prompt)
100
- # # print(f'\033[1mGeneration {key} translation:\033[0m {prompt}')
101
-
102
- # prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
103
- # # print(f'\033[1mGeneration {key}:\033[0m {prompt}')
104
-
105
- # # If seed is -1, generate a random seed and use it
106
- # if randomize_seed:
107
- # seed = random.randint(1, 4294967296)
108
-
109
- # payload = {
110
- # "inputs": prompt,
111
- # "steps": steps,
112
- # "cfg_scale": cfg_scale,
113
- # "seed": seed,
114
- # "parameters": {
115
- # "width": width, # Pass the width to the API
116
- # "height": height # Pass the height to the API
117
- # }
118
- # }
119
-
120
- # response = requests.post(API_URL, headers=headers, json=payload, timeout=timeout)
121
- # if response.status_code != 200:
122
- # print(f"Error: Failed to get image. Response status: {response.status_code}")
123
- # print(f"Response content: {response.text}")
124
- # if response.status_code == 503:
125
- # raise gr.Error(f"{response.status_code} : The model is being loaded")
126
- # raise gr.Error(f"{response.status_code}")
127
 
128
- # try:
129
- # image_bytes = response.content
130
- # image = Image.open(io.BytesIO(image_bytes))
131
- # print(f'\033[1mGeneration {key} completed!\033[0m ({prompt})')
132
- # return image, seed, seed
133
- # except Exception as e:
134
- # print(f"Error when trying to open the image: {e}")
135
- # return None
136
-
137
-
138
  examples = [
139
  "a tiny astronaut hatching from an egg on the moon",
140
  "a cat holding a sign that says hello world",
141
  "an anime illustration of a wiener schnitzel",
142
  ]
143
 
144
- css = """
145
  #col-container {
146
  margin: 0 auto;
147
- max-width: 960px;
148
- }
149
- .generate-btn {
150
- background: linear-gradient(90deg, #4B79A1 0%, #283E51 100%) !important;
151
- border: none !important;
152
- color: white !important;
153
- }
154
- .generate-btn:hover {
155
- transform: translateY(-2px);
156
- box-shadow: 0 5px 15px rgba(0,0,0,0.2);
157
  }
158
  """
159
 
160
- with gr.Blocks(css=css) as app:
161
- gr.HTML("<center><h1>FLUX.1-Dev with LoRA support</h1></center>")
162
  with gr.Column(elem_id="col-container"):
 
 
 
 
 
163
  with gr.Row():
164
- with gr.Column():
165
- with gr.Row():
166
- text_prompt = gr.Textbox(label="Prompt", placeholder="Enter a prompt here", lines=3, elem_id="prompt-text-input")
167
- with gr.Row():
168
- custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path (optional)", placeholder="multimodalart/vintage-ads-flux")
169
- with gr.Row():
170
- with gr.Accordion("Advanced Settings", open=False):
171
- with gr.Row():
172
- lora_scale = gr.Slider(
173
- label="LoRA Scale",
174
- minimum=0,
175
- maximum=2,
176
- step=0.01,
177
- value=0.95,
178
- )
179
- width = gr.Slider(label="Width", value=1024, minimum=64, maximum=1216, step=8)
180
- height = gr.Slider(label="Height", value=1024, minimum=64, maximum=1216, step=8)
181
- seed = gr.Slider(label="Seed", value=-1, minimum=-1, maximum=4294967296, step=1)
182
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
183
- with gr.Row():
184
- steps = gr.Slider(label="Inference steps steps", value=28, minimum=1, maximum=100, step=1)
185
- cfg = gr.Slider(label="Guidance Scale", value=3.5, minimum=1, maximum=20, step=0.5)
186
- # method = gr.Radio(label="Sampling method", value="DPM++ 2M Karras", choices=["DPM++ 2M Karras", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "DDIM"])
187
-
188
- with gr.Row():
189
- # text_button = gr.Button("Run", variant='primary', elem_id="gen-button")
190
- text_button = gr.Button("✨ Generate Image", variant='primary', elem_classes=["generate-btn"])
191
- with gr.Column():
192
- with gr.Row():
193
- image_output = gr.Image(type="pil", label="Image Output", elem_id="gallery")
194
- with gr.Row():
195
- seed_output = gr.Textbox(label="Seed Used", show_copy_button = True)
196
 
197
- gr.Markdown(article_text)
198
- with gr.Column():
199
- gr.Examples(
200
- examples = examples,
201
- inputs = [text_prompt],
 
 
 
 
 
202
  )
203
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
- # text_button.click(query, inputs=[custom_lora, text_prompt, steps, cfg, randomize_seed, seed, width, height], outputs=[image_output,seed_output, seed])
206
- text_button.click(infer, inputs=[text_prompt, seed, randomize_seed, width, height, cfg, steps, custom_lora, lora_scale], outputs=[image_output,seed_output, seed])
207
-
208
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  from transformers import CLIPTextModel, CLIPTokenizer,T5EncoderModel, T5TokenizerFast
8
  from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
9
 
 
10
  dtype = torch.bfloat16
11
  device = "cuda" if torch.cuda.is_available() else "cpu"
12
 
 
20
 
21
  pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  @spaces.GPU()
24
  def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidance_scale=3.5, num_inference_steps=28, lora_id=None, lora_scale=0.95, progress=gr.Progress(track_tqdm=True)):
25
  if randomize_seed:
 
66
  # Unload LoRA weights if they were loaded
67
  if lora_id:
68
  pipe.unload_lora_weights()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
 
 
 
 
 
 
 
 
 
 
70
  examples = [
71
  "a tiny astronaut hatching from an egg on the moon",
72
  "a cat holding a sign that says hello world",
73
  "an anime illustration of a wiener schnitzel",
74
  ]
75
 
76
+ css="""
77
  #col-container {
78
  margin: 0 auto;
79
+ max-width: 520px;
 
 
 
 
 
 
 
 
 
80
  }
81
  """
82
 
83
+ with gr.Blocks(css=css) as demo:
84
+
85
  with gr.Column(elem_id="col-container"):
86
+ gr.Markdown(f"""# FLUX.1 [dev] LoRA
87
+ 12B param rectified flow transformer guidance-distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/)
88
+ [[non-commercial license](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md)] [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-dev)]
89
+ """)
90
+
91
  with gr.Row():
92
+
93
+ prompt = gr.Text(
94
+ label="Prompt",
95
+ show_label=False,
96
+ max_lines=1,
97
+ placeholder="Enter your prompt",
98
+ container=False,
99
+ )
100
+
101
+ run_button = gr.Button("Run", scale=0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
+ result = gr.Image(label="Result", show_label=False)
104
+
105
+ with gr.Accordion("Advanced Settings", open=False):
106
+
107
+ seed = gr.Slider(
108
+ label="Seed",
109
+ minimum=0,
110
+ maximum=MAX_SEED,
111
+ step=1,
112
+ value=0,
113
  )
114
+
115
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
116
+
117
+ with gr.Row():
118
+
119
+ width = gr.Slider(
120
+ label="Width",
121
+ minimum=256,
122
+ maximum=MAX_IMAGE_SIZE,
123
+ step=8,
124
+ value=1024,
125
+ )
126
+
127
+ height = gr.Slider(
128
+ label="Height",
129
+ minimum=256,
130
+ maximum=MAX_IMAGE_SIZE,
131
+ step=8,
132
+ value=1024,
133
+ )
134
+
135
+ with gr.Row():
136
+
137
+ guidance_scale = gr.Slider(
138
+ label="Guidance Scale",
139
+ minimum=1,
140
+ maximum=15,
141
+ step=0.1,
142
+ value=3.5,
143
+ )
144
+
145
+ num_inference_steps = gr.Slider(
146
+ label="Number of inference steps",
147
+ minimum=1,
148
+ maximum=50,
149
+ step=1,
150
+ value=28,
151
+ )
152
+
153
+ with gr.Row():
154
+ lora_id = gr.Textbox(
155
+ label="LoRA Model ID (HuggingFace path)",
156
+ placeholder="username/lora-model",
157
+ max_lines=1
158
+ )
159
+ lora_scale = gr.Slider(
160
+ label="LoRA Scale",
161
+ minimum=0,
162
+ maximum=2,
163
+ step=0.01,
164
+ value=0.95,
165
+ )
166
 
167
+ gr.Examples(
168
+ examples = examples,
169
+ fn = infer,
170
+ inputs = [prompt],
171
+ outputs = [result, seed],
172
+ cache_examples="lazy"
173
+ )
174
+
175
+ gr.on(
176
+ triggers=[run_button.click, prompt.submit],
177
+ fn = infer,
178
+ inputs = [prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps,lora_id,lora_scale],
179
+ outputs = [result, seed]
180
+ )
181
+
182
+ demo.launch()