akhaliq HF Staff commited on
Commit
920a718
·
verified ·
1 Parent(s): 10a36a8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -18
app.py CHANGED
@@ -9,29 +9,32 @@ from PIL import Image
9
  # Import the pipeline from diffusers
10
  from diffusers import FluxKontextPipeline
11
 
12
- # --- Constants and Model Loading ---
13
  MAX_SEED = np.iinfo(np.int32).max
14
 
15
- # Load the pretrained model
16
- try:
17
- pipe = FluxKontextPipeline.from_pretrained(
18
- "black-forest-labs/FLUX.1-Kontext-dev",
19
- torch_dtype=torch.bfloat16,
20
- ).to("cuda")
21
- except Exception as e:
22
- pipe = None
23
- print(f"Warning: Could not load the model on CUDA. GPU is required. Error: {e}")
24
 
25
- # --- Core Inference Function for ChatInterface ---
 
 
 
 
 
 
 
 
26
 
27
- @spaces.GPU
 
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
- if pipe is None:
33
- raise gr.Error("Model could not be loaded. This could be due to no access to the model or no CUDA-enabled GPU.")
34
-
 
35
  prompt = message["text"]
36
  files = message["files"]
37
 
@@ -62,6 +65,10 @@ def chat_fn(message, chat_history, seed, randomize_seed, guidance_scale, steps,
62
  num_inference_steps=steps,
63
  generator=generator,
64
  ).images[0]
 
 
 
 
65
 
66
  return image
67
 
@@ -72,8 +79,7 @@ randomize_checkbox = gr.Checkbox(label="Randomize seed", value=False)
72
  guidance_slider = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=10.0, step=0.1, value=2.5)
73
  steps_slider = gr.Slider(label="Steps", minimum=1, maximum=30, value=28, step=1)
74
 
75
- # --- FIX 2: Remove examples with external URLs that cause 403 errors ---
76
- # Instead, provide text-only examples that work without external image dependencies
77
  examples = [
78
  [
79
  {"text": "A cute robot reading a book in a cozy library", "files": []},
@@ -93,7 +99,7 @@ demo = gr.ChatInterface(
93
  fn=chat_fn,
94
  title="FLUX.1 Kontext [dev]",
95
  description="""<p style='text-align: center;'>
96
- A simple chat UI for the <b>FLUX.1 Kontext</b> model.
97
  <br>
98
  To edit an image, upload it and type your instructions (e.g., "Add a hat").
99
  <br>
 
9
  # Import the pipeline from diffusers
10
  from diffusers import FluxKontextPipeline
11
 
12
+ # --- Constants ---
13
  MAX_SEED = np.iinfo(np.int32).max
14
 
15
+ # --- Global pipeline variable ---
16
+ pipe = None
 
 
 
 
 
 
 
17
 
18
+ def load_model():
19
+ """Load the model on CPU first, then move to GPU when needed"""
20
+ global pipe
21
+ if pipe is None:
22
+ pipe = FluxKontextPipeline.from_pretrained(
23
+ "black-forest-labs/FLUX.1-Kontext-dev",
24
+ torch_dtype=torch.bfloat16,
25
+ )
26
+ return pipe
27
 
28
+ # --- Core Inference Function for ChatInterface ---
29
+ @spaces.GPU(duration=120) # Set duration based on expected inference time
30
  def chat_fn(message, chat_history, seed, randomize_seed, guidance_scale, steps, progress=gr.Progress(track_tqdm=True)):
31
  """
32
  Performs image generation or editing based on user input from the chat interface.
33
  """
34
+ # Load and move model to GPU within the decorated function
35
+ pipe = load_model()
36
+ pipe = pipe.to("cuda")
37
+
38
  prompt = message["text"]
39
  files = message["files"]
40
 
 
65
  num_inference_steps=steps,
66
  generator=generator,
67
  ).images[0]
68
+
69
+ # Move model back to CPU to free GPU memory
70
+ pipe = pipe.to("cpu")
71
+ torch.cuda.empty_cache()
72
 
73
  return image
74
 
 
79
  guidance_slider = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=10.0, step=0.1, value=2.5)
80
  steps_slider = gr.Slider(label="Steps", minimum=1, maximum=30, value=28, step=1)
81
 
82
+ # --- Examples without external URLs ---
 
83
  examples = [
84
  [
85
  {"text": "A cute robot reading a book in a cozy library", "files": []},
 
99
  fn=chat_fn,
100
  title="FLUX.1 Kontext [dev]",
101
  description="""<p style='text-align: center;'>
102
+ A simple chat UI for the <b>FLUX.1 Kontext</b> model running on ZeroGPU.
103
  <br>
104
  To edit an image, upload it and type your instructions (e.g., "Add a hat").
105
  <br>