Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -3,6 +3,7 @@ import numpy as np
|
|
3 |
import spaces
|
4 |
import torch
|
5 |
import random
|
|
|
6 |
from PIL import Image
|
7 |
|
8 |
# Import the pipeline from diffusers
|
@@ -11,13 +12,24 @@ from diffusers import FluxKontextPipeline
|
|
11 |
# --- Constants and Model Loading ---
|
12 |
MAX_SEED = np.iinfo(np.int32).max
|
13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
# Load the pretrained model
|
15 |
-
# Note: This requires a CUDA-enabled GPU. Error handling is added for environments without it.
|
16 |
try:
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
21 |
except Exception as e:
|
22 |
pipe = None
|
23 |
print(f"Warning: Could not load the model on CUDA. GPU is required. Error: {e}")
|
@@ -28,40 +40,23 @@ except Exception as e:
|
|
28 |
def chat_fn(message, chat_history, seed, randomize_seed, guidance_scale, steps, progress=gr.Progress(track_tqdm=True)):
|
29 |
"""
|
30 |
Performs image generation or editing based on user input from the chat interface.
|
31 |
-
|
32 |
-
Args:
|
33 |
-
message (dict): A dictionary from gr.MultimodalTextbox, containing:
|
34 |
-
- "text" (str): The user's text prompt.
|
35 |
-
- "files" (list): A list of paths to uploaded files.
|
36 |
-
chat_history (list): The history of the conversation (managed by ChatInterface).
|
37 |
-
seed (int): The random seed for generation.
|
38 |
-
randomize_seed (bool): If True, a random seed is used.
|
39 |
-
guidance_scale (float): Controls adherence to the prompt.
|
40 |
-
steps (int): Number of inference steps.
|
41 |
-
progress (gr.Progress): Gradio progress tracker.
|
42 |
-
|
43 |
-
Returns:
|
44 |
-
PIL.Image.Image: The generated or edited image to be displayed in the chat.
|
45 |
"""
|
46 |
if pipe is None:
|
47 |
-
raise gr.Error("Model could not be loaded.
|
48 |
|
49 |
prompt = message["text"]
|
50 |
files = message["files"]
|
51 |
|
52 |
-
# Input validation
|
53 |
if not prompt and not files:
|
54 |
raise gr.Error("Please provide a prompt and/or upload an image.")
|
55 |
|
56 |
if randomize_seed:
|
57 |
seed = random.randint(0, MAX_SEED)
|
58 |
|
59 |
-
|
60 |
-
generator = torch.Generator(device="cuda").manual_seed(seed)
|
61 |
|
62 |
input_image = None
|
63 |
if files:
|
64 |
-
# User has uploaded an image for editing (image-to-image)
|
65 |
print(f"Received image: {files[0]}")
|
66 |
input_image = Image.open(files[0]).convert("RGB")
|
67 |
image = pipe(
|
@@ -72,7 +67,6 @@ def chat_fn(message, chat_history, seed, randomize_seed, guidance_scale, steps,
|
|
72 |
generator=generator,
|
73 |
).images[0]
|
74 |
else:
|
75 |
-
# No image uploaded, perform text-to-image generation
|
76 |
print(f"Received prompt for text-to-image: {prompt}")
|
77 |
image = pipe(
|
78 |
prompt=prompt,
|
@@ -81,20 +75,32 @@ def chat_fn(message, chat_history, seed, randomize_seed, guidance_scale, steps,
|
|
81 |
generator=generator,
|
82 |
).images[0]
|
83 |
|
84 |
-
# To also inform the user of the seed, you could optionally return a tuple,
|
85 |
-
# but for a clean image output, we just return the image.
|
86 |
-
# For example: return (image, f"Seed: {seed}")
|
87 |
return image
|
88 |
|
89 |
# --- UI Definition using gr.ChatInterface ---
|
90 |
|
91 |
-
# Define the components for "Advanced Settings" that will be passed to `additional_inputs`
|
92 |
seed_slider = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42)
|
93 |
randomize_checkbox = gr.Checkbox(label="Randomize seed", value=False)
|
94 |
guidance_slider = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=10.0, step=0.1, value=2.5)
|
95 |
steps_slider = gr.Slider(label="Steps", minimum=1, maximum=30, value=28, step=1)
|
96 |
|
97 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
demo = gr.ChatInterface(
|
99 |
fn=chat_fn,
|
100 |
title="FLUX.1 Kontext [dev]",
|
@@ -107,11 +113,10 @@ demo = gr.ChatInterface(
|
|
107 |
<br>
|
108 |
Find the model on <a href='https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev' target='_blank'>Hugging Face</a>.
|
109 |
</p>""",
|
110 |
-
# Use a multimodal textbox to allow both text and image uploads
|
111 |
textbox=gr.MultimodalTextbox(
|
112 |
file_types=["image"],
|
113 |
placeholder="Type a prompt and/or upload an image...",
|
114 |
-
render=False
|
115 |
),
|
116 |
additional_inputs=[
|
117 |
seed_slider,
|
@@ -119,14 +124,9 @@ demo = gr.ChatInterface(
|
|
119 |
guidance_slider,
|
120 |
steps_slider
|
121 |
],
|
122 |
-
examples=
|
123 |
-
{"text": "A cute robot reading a book", "files": []},
|
124 |
-
{"text": "change his shirt to a hawaiian shirt", "files": ["https://gradio-builds.s3.amazonaws.com/demo-files/chewbacca.png"]},
|
125 |
-
{"text": "make it a wooden house", "files": ["https://gradio-builds.s3.amazonaws.com/demo-files/house.png"]},
|
126 |
-
],
|
127 |
theme="soft"
|
128 |
)
|
129 |
|
130 |
-
# Launch the application
|
131 |
if __name__ == "__main__":
|
132 |
demo.launch()
|
|
|
3 |
import spaces
|
4 |
import torch
|
5 |
import random
|
6 |
+
import os
|
7 |
from PIL import Image
|
8 |
|
9 |
# Import the pipeline from diffusers
|
|
|
12 |
# --- Constants and Model Loading ---
|
13 |
MAX_SEED = np.iinfo(np.int32).max
|
14 |
|
15 |
+
# --- FIX 1: Handle Hugging Face Authentication ---
|
16 |
+
# This is a gated model. You must have access on Hugging Face and provide a token.
|
17 |
+
# 1. Visit https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev and accept the terms.
|
18 |
+
# 2. Get an access token from https://huggingface.co/settings/tokens
|
19 |
+
# 3. Add the token below or set it as an environment variable `HF_TOKEN`.
|
20 |
+
HF_TOKEN = os.getenv("HF_TOKEN", "YOUR_HUGGING_FACE_TOKEN") # Replace with your token
|
21 |
+
|
22 |
# Load the pretrained model
|
|
|
23 |
try:
|
24 |
+
if HF_TOKEN == "YOUR_HUGGING_FACE_TOKEN":
|
25 |
+
pipe = None
|
26 |
+
print("Warning: Hugging Face token not provided. Please replace 'YOUR_HUGGING_FACE_TOKEN' with your actual token.")
|
27 |
+
else:
|
28 |
+
pipe = FluxKontextPipeline.from_pretrained(
|
29 |
+
"black-forest-labs/FLUX.1-Kontext-dev",
|
30 |
+
torch_dtype=torch.bfloat16,
|
31 |
+
token=HF_TOKEN, # Use the token for authentication
|
32 |
+
).to("cuda")
|
33 |
except Exception as e:
|
34 |
pipe = None
|
35 |
print(f"Warning: Could not load the model on CUDA. GPU is required. Error: {e}")
|
|
|
40 |
def chat_fn(message, chat_history, seed, randomize_seed, guidance_scale, steps, progress=gr.Progress(track_tqdm=True)):
|
41 |
"""
|
42 |
Performs image generation or editing based on user input from the chat interface.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
"""
|
44 |
if pipe is None:
|
45 |
+
raise gr.Error("Model could not be loaded. This could be due to a missing Hugging Face token, no access to the model, or no CUDA-enabled GPU.")
|
46 |
|
47 |
prompt = message["text"]
|
48 |
files = message["files"]
|
49 |
|
|
|
50 |
if not prompt and not files:
|
51 |
raise gr.Error("Please provide a prompt and/or upload an image.")
|
52 |
|
53 |
if randomize_seed:
|
54 |
seed = random.randint(0, MAX_SEED)
|
55 |
|
56 |
+
generator = torch.Generator(device="cuda").manual_seed(int(seed))
|
|
|
57 |
|
58 |
input_image = None
|
59 |
if files:
|
|
|
60 |
print(f"Received image: {files[0]}")
|
61 |
input_image = Image.open(files[0]).convert("RGB")
|
62 |
image = pipe(
|
|
|
67 |
generator=generator,
|
68 |
).images[0]
|
69 |
else:
|
|
|
70 |
print(f"Received prompt for text-to-image: {prompt}")
|
71 |
image = pipe(
|
72 |
prompt=prompt,
|
|
|
75 |
generator=generator,
|
76 |
).images[0]
|
77 |
|
|
|
|
|
|
|
78 |
return image
|
79 |
|
80 |
# --- UI Definition using gr.ChatInterface ---
|
81 |
|
|
|
82 |
seed_slider = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42)
|
83 |
randomize_checkbox = gr.Checkbox(label="Randomize seed", value=False)
|
84 |
guidance_slider = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=10.0, step=0.1, value=2.5)
|
85 |
steps_slider = gr.Slider(label="Steps", minimum=1, maximum=30, value=28, step=1)
|
86 |
|
87 |
+
# --- FIX 2: Correctly format the examples as a list of lists ---
|
88 |
+
# Format: [ [message_dict, seed, randomize, guidance, steps], ... ]
|
89 |
+
examples = [
|
90 |
+
[
|
91 |
+
{"text": "A cute robot reading a book", "files": []},
|
92 |
+
42, False, 2.5, 28
|
93 |
+
],
|
94 |
+
[
|
95 |
+
{"text": "change his shirt to a hawaiian shirt", "files": ["https://gradio-builds.s3.amazonaws.com/demo-files/chewbacca.png"]},
|
96 |
+
12345, False, 3.0, 25
|
97 |
+
],
|
98 |
+
[
|
99 |
+
{"text": "make it a wooden house, add a chimney", "files": ["https://gradio-builds.s3.amazonaws.com/demo-files/house.png"]},
|
100 |
+
54321, False, 2.0, 30
|
101 |
+
],
|
102 |
+
]
|
103 |
+
|
104 |
demo = gr.ChatInterface(
|
105 |
fn=chat_fn,
|
106 |
title="FLUX.1 Kontext [dev]",
|
|
|
113 |
<br>
|
114 |
Find the model on <a href='https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev' target='_blank'>Hugging Face</a>.
|
115 |
</p>""",
|
|
|
116 |
textbox=gr.MultimodalTextbox(
|
117 |
file_types=["image"],
|
118 |
placeholder="Type a prompt and/or upload an image...",
|
119 |
+
render=False
|
120 |
),
|
121 |
additional_inputs=[
|
122 |
seed_slider,
|
|
|
124 |
guidance_slider,
|
125 |
steps_slider
|
126 |
],
|
127 |
+
examples=examples, # Use the correctly formatted list
|
|
|
|
|
|
|
|
|
128 |
theme="soft"
|
129 |
)
|
130 |
|
|
|
131 |
if __name__ == "__main__":
|
132 |
demo.launch()
|