rokmr commited on
Commit
93977a4
·
verified ·
1 Parent(s): daf37c1

updating app.py with fixes

Browse files
Files changed (1) hide show
  1. app.py +67 -29
app.py CHANGED
@@ -1,35 +1,57 @@
1
  import torch
2
- from diffusers import Flux2Pipeline, Flux2Transformer2DModel
3
- from diffusers.utils import load_image
4
  from huggingface_hub import get_token
5
  import requests
6
  import io
7
  import gradio as gr
8
  from PIL import Image
 
9
 
 
10
  repo_id = "diffusers/FLUX.2-dev-bnb-4bit"
11
- device = "cuda:0"
12
- torch_dtype = torch.bfloat16
13
 
14
- def remote_text_encoder(prompts):
15
- response = requests.post(
16
- "https://remote-text-encoder-flux-2.huggingface.co/predict",
17
- json={"prompt": prompts},
18
- headers={
19
- "Authorization": f"Bearer {get_token()}",
20
- "Content-Type": "application/json"
21
- }
22
- )
23
- prompt_embeds = torch.load(io.BytesIO(response.content))
24
 
25
- return prompt_embeds.to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  # Load the pipeline
28
  print("Loading Flux2 pipeline...")
29
- pipe = Flux2Pipeline.from_pretrained(
30
- repo_id, text_encoder=None, torch_dtype=torch_dtype
31
- ).to(device)
32
- print("Pipeline loaded successfully!")
 
 
 
 
 
 
 
 
 
33
 
34
  def generate_image(
35
  prompt: str,
@@ -52,6 +74,9 @@ def generate_image(
52
  if not prompt or prompt.strip() == "":
53
  raise gr.Error("Please enter a prompt!")
54
 
 
 
 
55
  progress(0, desc="Encoding prompt...")
56
 
57
  try:
@@ -61,17 +86,19 @@ def generate_image(
61
  progress(0.3, desc="Generating image...")
62
 
63
  # Set up generator
 
64
  if seed == -1:
65
- generator = torch.Generator(device=device)
66
- else:
67
- generator = torch.Generator(device=device).manual_seed(seed)
 
68
 
69
  # Prepare pipeline arguments
70
  pipe_kwargs = {
71
  "prompt_embeds": prompt_embeds,
72
  "generator": generator,
73
- "num_inference_steps": num_inference_steps,
74
- "guidance_scale": guidance_scale,
75
  }
76
 
77
  # Add input image if provided
@@ -80,22 +107,32 @@ def generate_image(
80
  progress(0.4, desc="Processing input image...")
81
 
82
  # Generate image
83
- image = pipe(**pipe_kwargs).images[0]
 
84
 
85
  progress(1.0, desc="Done!")
86
 
87
  return image
88
 
89
  except Exception as e:
 
 
 
90
  raise gr.Error(f"Error generating image: {str(e)}")
91
 
 
92
  # Create Gradio interface
93
- with gr.Blocks(title="Flux2 Image Generator", theme=gr.themes.Soft()) as demo:
 
 
94
  gr.Markdown(
95
  """
96
  # 🎨 Flux2 Image Generator
97
- Generate stunning images using FLUX.2-dev with 4-bit quantization.
 
98
  Supports both **text-to-image** and **image-to-image** generation.
 
 
99
  """
100
  )
101
 
@@ -148,7 +185,8 @@ with gr.Blocks(title="Flux2 Image Generator", theme=gr.themes.Soft()) as demo:
148
  generate_btn = gr.Button(
149
  "🚀 Generate Image",
150
  variant="primary",
151
- size="lg"
 
152
  )
153
 
154
  gr.Markdown(
@@ -223,4 +261,4 @@ with gr.Blocks(title="Flux2 Image Generator", theme=gr.themes.Soft()) as demo:
223
  )
224
 
225
  if __name__ == "__main__":
226
- demo.launch(share=False, server_name="0.0.0.0", server_port=7860)
 
1
  import torch
2
+ from diffusers import Flux2Pipeline
 
3
  from huggingface_hub import get_token
4
  import requests
5
  import io
6
  import gradio as gr
7
  from PIL import Image
8
+ import os
9
 
10
+ # Configuration
11
  repo_id = "diffusers/FLUX.2-dev-bnb-4bit"
12
+ device = "cuda" if torch.cuda.is_available() else "cpu"
13
+ torch_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
14
 
15
+ print(f"Using device: {device}")
16
+ print(f"Using dtype: {torch_dtype}")
 
 
 
 
 
 
 
 
17
 
18
+ def remote_text_encoder(prompts):
19
+ """Encode prompts using remote text encoder API."""
20
+ try:
21
+ token = get_token()
22
+ if not token:
23
+ raise ValueError("HuggingFace token not found. Please login using 'huggingface-cli login'")
24
+
25
+ response = requests.post(
26
+ "https://remote-text-encoder-flux-2.huggingface.co/predict",
27
+ json={"prompt": prompts},
28
+ headers={
29
+ "Authorization": f"Bearer {token}",
30
+ "Content-Type": "application/json"
31
+ },
32
+ timeout=60
33
+ )
34
+ response.raise_for_status()
35
+ prompt_embeds = torch.load(io.BytesIO(response.content))
36
+ return prompt_embeds.to(device)
37
+ except Exception as e:
38
+ raise Exception(f"Failed to encode prompt: {str(e)}")
39
 
40
  # Load the pipeline
41
  print("Loading Flux2 pipeline...")
42
+ try:
43
+ pipe = Flux2Pipeline.from_pretrained(
44
+ repo_id,
45
+ text_encoder=None,
46
+ torch_dtype=torch_dtype,
47
+ device_map="cuda"
48
+ )
49
+ if not torch.cuda.is_available():
50
+ pipe = pipe.to(device)
51
+ print("Pipeline loaded successfully!")
52
+ except Exception as e:
53
+ print(f"Error loading pipeline: {e}")
54
+ raise
55
 
56
  def generate_image(
57
  prompt: str,
 
74
  if not prompt or prompt.strip() == "":
75
  raise gr.Error("Please enter a prompt!")
76
 
77
+ if not torch.cuda.is_available():
78
+ raise gr.Error("This Space requires a GPU to run. Please try a different Space or upgrade your hardware.")
79
+
80
  progress(0, desc="Encoding prompt...")
81
 
82
  try:
 
86
  progress(0.3, desc="Generating image...")
87
 
88
  # Set up generator
89
+ generator_device = "cuda" if torch.cuda.is_available() else "cpu"
90
  if seed == -1:
91
+ import random
92
+ seed = random.randint(0, 2**32 - 1)
93
+
94
+ generator = torch.Generator(device=generator_device).manual_seed(int(seed))
95
 
96
  # Prepare pipeline arguments
97
  pipe_kwargs = {
98
  "prompt_embeds": prompt_embeds,
99
  "generator": generator,
100
+ "num_inference_steps": int(num_inference_steps),
101
+ "guidance_scale": float(guidance_scale),
102
  }
103
 
104
  # Add input image if provided
 
107
  progress(0.4, desc="Processing input image...")
108
 
109
  # Generate image
110
+ with torch.inference_mode():
111
+ image = pipe(**pipe_kwargs).images[0]
112
 
113
  progress(1.0, desc="Done!")
114
 
115
  return image
116
 
117
  except Exception as e:
118
+ import traceback
119
+ error_msg = f"Error generating image: {str(e)}\n{traceback.format_exc()}"
120
+ print(error_msg)
121
  raise gr.Error(f"Error generating image: {str(e)}")
122
 
123
+
124
  # Create Gradio interface
125
+ with gr.Blocks(
126
+ title="Flux2 Image Generator",
127
+ ) as demo:
128
  gr.Markdown(
129
  """
130
  # 🎨 Flux2 Image Generator
131
+ Generate stunning images using **FLUX.2-dev** with 4-bit quantization for efficient inference.
132
+
133
  Supports both **text-to-image** and **image-to-image** generation.
134
+
135
+ ⚠️ **Note**: This Space requires a GPU to run.
136
  """
137
  )
138
 
 
185
  generate_btn = gr.Button(
186
  "🚀 Generate Image",
187
  variant="primary",
188
+ size="lg",
189
+ elem_classes="generate-btn"
190
  )
191
 
192
  gr.Markdown(
 
261
  )
262
 
263
  if __name__ == "__main__":
264
+ demo.queue(max_size=20).launch()