Aklavya commited on
Commit
ba185bd
·
verified ·
1 Parent(s): e49f6b3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -48
app.py CHANGED
@@ -3,12 +3,14 @@ import random
3
  import uuid
4
  import gradio as gr
5
  import numpy as np
6
- from PIL import Image
7
- import spaces
8
  import torch
 
 
9
  from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
10
  from typing import Tuple
11
 
 
 
12
  def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
13
  styles = {
14
  "3840 x 2160": (
@@ -22,6 +24,8 @@ def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str
22
  p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
23
  return p.replace("{prompt}", positive), n + negative
24
 
 
 
25
  def load_and_prepare_model():
26
  model_id = "SG161222/RealVisXL_V5.0_Lightning"
27
  pipe = StableDiffusionXLPipeline.from_pretrained(
@@ -33,19 +37,25 @@ def load_and_prepare_model():
33
  pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
34
  return pipe
35
 
 
36
  model = load_and_prepare_model()
37
 
 
 
38
  def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
39
  if randomize_seed:
40
  seed = random.randint(0, np.iinfo(np.int32).max)
41
  return seed
42
 
 
 
43
  def save_image(img):
44
  unique_name = str(uuid.uuid4()) + ".png"
45
  img.save(unique_name)
46
  return unique_name
47
 
48
- @spaces.GPU(duration=60, enable_queue=True)
 
49
  def generate(
50
  prompt: str,
51
  seed: int = 1,
@@ -57,26 +67,37 @@ def generate(
57
  ):
58
  global model
59
 
60
- seed = int(randomize_seed_fn(seed, randomize_seed))
61
- generator = torch.Generator(device=model.device).manual_seed(seed)
62
-
63
- positive_prompt, negative_prompt = apply_style("3840 x 2160", prompt)
64
-
65
- options = {
66
- "prompt": [positive_prompt],
67
- "negative_prompt": [negative_prompt],
68
- "width": width,
69
- "height": height,
70
- "guidance_scale": guidance_scale,
71
- "num_inference_steps": num_inference_steps,
72
- "generator": generator,
73
- "output_type": "pil",
74
- }
75
-
76
- images = model(**options).images
77
- image_path = save_image(images[0]) # Saving the first generated image
78
- return image_path
79
-
 
 
 
 
 
 
 
 
 
 
 
80
  with gr.Blocks(theme="soft") as demo:
81
  # Block for "SNAPSCRIBE" centered at the top
82
  with gr.Row():
@@ -94,7 +115,6 @@ with gr.Blocks(theme="soft") as demo:
94
  run_button = gr.Button("Generate Image")
95
 
96
  # Example prompts box
97
- # gr.Markdown("<h3 style='text-align:center;'>Sample Inputs</h3>")
98
  example_prompts = gr.Textbox(
99
  value="Dew-covered spider web in morning sunlight, with blurred greenery\n"
100
  "--------------------------------------------\n"
@@ -115,34 +135,10 @@ with gr.Blocks(theme="soft") as demo:
115
  height=600 # Increased the height by 100%
116
  )
117
 
118
- # with gr.Column(scale=12):
119
- # gr.Markdown("<h2 style='text-align:center; color:white; font-weight:bold; text-decoration:underline;'>Developed using RealVisXL_V5.0_Lightning model with ❤ by Aklavya</h1>")
120
-
121
  run_button.click(
122
  fn=generate,
123
  inputs=[prompt],
124
  outputs=[result_image],
125
  )
126
 
127
- # # Footer added to center-align the text
128
- # gr.HTML("""
129
- # <style>
130
- # .footer {
131
- # position: relative;
132
- # left: 0;
133
- # bottom: 0;
134
- # width: 100%;
135
- # background-color: white;
136
- # color: black;
137
- # text-align: center;
138
- # padding: 10px;
139
- # margin-top: 20px;
140
- # font-weight: bold;
141
- # }
142
- # </style>
143
- # <div class="footer">
144
- # <p>Developed using RealVisXL_V5.0_Lightning model with ❤ by Aklavya (Bucky)</p>
145
- # </div>
146
- # """)
147
-
148
  demo.launch()
 
3
  import uuid
4
  import gradio as gr
5
  import numpy as np
 
 
6
  import torch
7
+ import concurrent.futures
8
+ from PIL import Image
9
  from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
10
  from typing import Tuple
11
 
12
+
13
+ # Function to apply styles
14
  def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
15
  styles = {
16
  "3840 x 2160": (
 
24
  p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
25
  return p.replace("{prompt}", positive), n + negative
26
 
27
+
28
+ # Function to load and prepare the model
29
  def load_and_prepare_model():
30
  model_id = "SG161222/RealVisXL_V5.0_Lightning"
31
  pipe = StableDiffusionXLPipeline.from_pretrained(
 
37
  pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
38
  return pipe
39
 
40
+
41
  model = load_and_prepare_model()
42
 
43
+
44
+ # Function to randomize or apply a fixed seed
45
  def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
46
  if randomize_seed:
47
  seed = random.randint(0, np.iinfo(np.int32).max)
48
  return seed
49
 
50
+
51
+ # Function to save generated images
52
  def save_image(img):
53
  unique_name = str(uuid.uuid4()) + ".png"
54
  img.save(unique_name)
55
  return unique_name
56
 
57
+
58
+ # Main generation function with timeout
59
  def generate(
60
  prompt: str,
61
  seed: int = 1,
 
67
  ):
68
  global model
69
 
70
+ def run_model():
71
+ seed = int(randomize_seed_fn(seed, randomize_seed))
72
+ generator = torch.Generator(device=model.device).manual_seed(seed)
73
+
74
+ positive_prompt, negative_prompt = apply_style("3840 x 2160", prompt)
75
+
76
+ options = {
77
+ "prompt": [positive_prompt],
78
+ "negative_prompt": [negative_prompt],
79
+ "width": width,
80
+ "height": height,
81
+ "guidance_scale": guidance_scale,
82
+ "num_inference_steps": num_inference_steps,
83
+ "generator": generator,
84
+ "output_type": "pil",
85
+ }
86
+
87
+ images = model(**options).images
88
+ return save_image(images[0]) # Save and return the image path
89
+
90
+ # Use a timeout for CPU-bound operations
91
+ with concurrent.futures.ThreadPoolExecutor() as executor:
92
+ future = executor.submit(run_model)
93
+ try:
94
+ image_path = future.result(timeout=180) # Set timeout to 180 seconds
95
+ return image_path
96
+ except concurrent.futures.TimeoutError:
97
+ return "Error: Image generation timed out. Please try again with different settings or on a GPU-enabled setup."
98
+
99
+
100
+ # Gradio interface setup
101
  with gr.Blocks(theme="soft") as demo:
102
  # Block for "SNAPSCRIBE" centered at the top
103
  with gr.Row():
 
115
  run_button = gr.Button("Generate Image")
116
 
117
  # Example prompts box
 
118
  example_prompts = gr.Textbox(
119
  value="Dew-covered spider web in morning sunlight, with blurred greenery\n"
120
  "--------------------------------------------\n"
 
135
  height=600 # Increased the height by 100%
136
  )
137
 
 
 
 
138
  run_button.click(
139
  fn=generate,
140
  inputs=[prompt],
141
  outputs=[result_image],
142
  )
143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  demo.launch()