Aklavya commited on
Commit
bd117de
·
verified ·
1 Parent(s): a1de646

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -59
app.py CHANGED
@@ -4,32 +4,50 @@ import uuid
4
  import gradio as gr
5
  import numpy as np
6
  from PIL import Image
 
7
  import torch
8
- from huggingface_hub import login
9
- from diffusers import StableDiffusionPipeline
10
  from typing import Tuple
11
 
12
- # Use the Hugging Face token from environment variable
13
- token = os.getenv("HF_TOKEN") # Get token from environment variable
 
 
 
 
 
 
 
14
 
15
- # Log in to Hugging Face using the token
16
- login(token=token)
17
 
18
- # Function to load and prepare the model
19
- def load_and_prepare_model(model_id: str):
20
- # Load the model using the Stable Diffusion pipeline
21
- pipe = StableDiffusionPipeline.from_pretrained(
22
  model_id,
23
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
24
- use_safetensors=True
25
- ).to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
26
-
 
27
  return pipe
28
 
29
- # Function to generate the image
 
 
 
 
 
 
 
 
 
 
 
 
30
  def generate(
31
  prompt: str,
32
- model_choice: str,
33
  seed: int = 1,
34
  width: int = 1024,
35
  height: int = 1024,
@@ -37,28 +55,10 @@ def generate(
37
  num_inference_steps: int = 25,
38
  randomize_seed: bool = False,
39
  ):
40
- # Set the seed
41
- if randomize_seed:
42
- seed = random.randint(0, np.iinfo(np.int32).max)
43
 
44
- generator = torch.Generator(device="cuda" if torch.cuda.is_available() else "cpu").manual_seed(seed)
45
-
46
- # Choose model based on the user's selection
47
- model_id = "DeepFloyd/IF-I-XL-v1.0" if model_choice == "DeepFloyd/IF-I-XL-v1.0" else "RealVisXL_V5.0_Lightning"
48
- model = load_and_prepare_model(model_id)
49
-
50
- # Style functions (if needed)
51
- def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
52
- styles = {
53
- "3840 x 2160": (
54
- "hyper-realistic 8K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
55
- "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
56
- ),
57
- "Style Zero": ("{prompt}", ""),
58
- }
59
- DEFAULT_STYLE_NAME = "3840 x 2160"
60
- p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
61
- return p.replace("{prompt}", positive), n + negative
62
 
63
  positive_prompt, negative_prompt = apply_style("3840 x 2160", prompt)
64
 
@@ -73,15 +73,14 @@ def generate(
73
  "output_type": "pil",
74
  }
75
 
76
- # Generate the image
77
  images = model(**options).images
78
- return images[0]
 
79
 
80
- # Gradio interface setup
81
  with gr.Blocks(theme="soft") as demo:
82
  # Centered text "SNAPSCRIBE" at the top of the screen
83
  gr.Markdown("<h1 style='text-align:center; color:white; font-weight:bold; text-decoration:underline;'>SNAPSCRIBE</h1>")
84
-
85
  with gr.Row():
86
  with gr.Column(scale=3):
87
  prompt = gr.Textbox(
@@ -89,37 +88,36 @@ with gr.Blocks(theme="soft") as demo:
89
  placeholder="Describe the image you want to create",
90
  lines=2,
91
  )
92
- # Drop down to select model
93
- model_choice = gr.Dropdown(
94
- choices=["DeepFloyd/IF-I-XL-v1.0", "RealVisXL_V5.0_Lightning"],
95
- label="Choose a Model"
96
- )
97
  run_button = gr.Button("Generate Image")
 
98
  with gr.Column(scale=7):
99
- result = gr.Image(label="Generated Image", type="pil")
100
 
101
  run_button.click(
102
  fn=generate,
103
- inputs=[prompt, model_choice],
104
- outputs=[result],
105
  )
106
 
107
  # Footer with custom style and text
108
- gr.Markdown("""
109
  <style>
110
- .footer {
111
- position: relative;
112
- left: 0;
113
- bottom: 0;
114
- width: 100%;
115
- background-color: white;
116
- color: black;
117
- text-align: center;
118
- }
 
 
119
  </style>
120
  <div class="footer">
121
- <p>Developed with ❤ by Aklavya(Bucky)</p>
122
  </div>
123
  """)
124
 
125
  demo.launch()
 
 
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": (
15
+ "hyper-realistic 8K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
16
+ "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
17
+ ),
18
+ "Style Zero": ("{prompt}", ""),
19
+ }
20
+ DEFAULT_STYLE_NAME = "3840 x 2160"
21
 
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(
 
28
  model_id,
29
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
30
+ use_safetensors=True,
31
+ add_watermarker=False,
32
+ ).to(torch.device("cuda:0" if torch.cuda.is_available() else "cpu"))
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,
52
  width: int = 1024,
53
  height: int = 1024,
 
55
  num_inference_steps: int = 25,
56
  randomize_seed: bool = False,
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
 
 
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
  # Centered text "SNAPSCRIBE" at the top of the screen
82
  gr.Markdown("<h1 style='text-align:center; color:white; font-weight:bold; text-decoration:underline;'>SNAPSCRIBE</h1>")
83
+
84
  with gr.Row():
85
  with gr.Column(scale=3):
86
  prompt = gr.Textbox(
 
88
  placeholder="Describe the image you want to create",
89
  lines=2,
90
  )
 
 
 
 
 
91
  run_button = gr.Button("Generate Image")
92
+ gr.Markdown("Developed using the RealVisXL_V5.0_Lightning model.", elem_id="model_info")
93
  with gr.Column(scale=7):
94
+ result_image = gr.Image(label="Generated Image", type="filepath")
95
 
96
  run_button.click(
97
  fn=generate,
98
+ inputs=[prompt],
99
+ outputs=[result_image],
100
  )
101
 
102
  # Footer with custom style and text
103
+ gr.HTML("""
104
  <style>
105
+ .footer {
106
+ position: relative;
107
+ left: 0;
108
+ bottom: 0;
109
+ width: 100%;
110
+ background-color: white;
111
+ color: black;
112
+ text-align: center;
113
+ padding: 10px;
114
+ margin-top: 20px;
115
+ }
116
  </style>
117
  <div class="footer">
118
+ <p>Developed with ❤ by Aklavya(Bucky)</p>
119
  </div>
120
  """)
121
 
122
  demo.launch()
123
+