awacke1 commited on
Commit
c123c04
1 Parent(s): fde5572

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +208 -0
app.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ import random
5
+ import uuid
6
+ import base64
7
+ import gradio as gr
8
+ import numpy as np
9
+ from PIL import Image
10
+ import spaces
11
+ import torch
12
+
13
+ from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
14
+
15
+ DESCRIPTION = """# DALL•E 3 XL v2 High Fi"""
16
+
17
+ def create_download_link(filename):
18
+ with open(filename, "rb") as file:
19
+ encoded_string = base64.b64encode(file.read()).decode('utf-8')
20
+ download_link = f'<a href="data:image/png;base64,{encoded_string}" download="{filename}">Download Image</a>'
21
+ return download_link
22
+
23
+ def save_image(img, prompt):
24
+ unique_name = str(uuid.uuid4()) + ".png"
25
+ img.save(unique_name)
26
+
27
+ # save with prompt to save prompt as image file name
28
+ filename = f"{prompt}.png"
29
+ img.save(filename)
30
+ return filename
31
+
32
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
33
+ if randomize_seed:
34
+ seed = random.randint(0, MAX_SEED)
35
+ return seed
36
+
37
+ MAX_SEED = np.iinfo(np.int32).max
38
+
39
+ if not torch.cuda.is_available():
40
+ DESCRIPTION += "\n<p>Running on CPU 🥶 This demo may not work on CPU.</p>"
41
+
42
+ MAX_SEED = np.iinfo(np.int32).max
43
+
44
+ USE_TORCH_COMPILE = 0
45
+ ENABLE_CPU_OFFLOAD = 0
46
+
47
+ if torch.cuda.is_available():
48
+ pipe = StableDiffusionXLPipeline.from_pretrained(
49
+ "fluently/Fluently-XL-v4",
50
+ torch_dtype=torch.float16,
51
+ use_safetensors=True,
52
+ )
53
+ pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
54
+
55
+ pipe.load_lora_weights("ehristoforu/dalle-3-xl-v2", weight_name="dalle-3-xl-lora-v2.safetensors", adapter_name="dalle")
56
+ pipe.set_adapters("dalle")
57
+
58
+ pipe.to("cuda")
59
+
60
+ @spaces.GPU(enable_queue=True)
61
+ def generate(
62
+ prompt: str,
63
+ negative_prompt: str = "",
64
+ use_negative_prompt: bool = False,
65
+ seed: int = 0,
66
+ width: int = 1024,
67
+ height: int = 1024,
68
+ guidance_scale: float = 3,
69
+ randomize_seed: bool = False,
70
+ progress=gr.Progress(track_tqdm=True),
71
+ ):
72
+ seed = int(randomize_seed_fn(seed, randomize_seed))
73
+
74
+ if not use_negative_prompt:
75
+ negative_prompt = "" # type: ignore
76
+
77
+ images = pipe(
78
+ prompt=prompt,
79
+ negative_prompt=negative_prompt,
80
+ width=width,
81
+ height=height,
82
+ guidance_scale=guidance_scale,
83
+ num_inference_steps=20,
84
+ num_images_per_prompt=1,
85
+ cross_attention_kwargs={"scale": 0.65},
86
+ output_type="pil",
87
+ ).images
88
+ image_paths = [save_image(img, prompt) for img in images]
89
+ download_links = [create_download_link(path) for path in image_paths]
90
+
91
+ print(image_paths)
92
+ return image_paths, seed, download_links
93
+
94
+ examples = [
95
+ "An elderly man engages in a virtual reality physical therapy session, guided by a compassionate AI therapist that adapts the exercises to his abilities and provides encouragement, all from the comfort of his own home.",
96
+ "In a bright, welcoming dental office, a young patient watches in awe as a dental robot efficiently and painlessly repairs a cavity using a laser system, while the dentist explains the procedure using interactive 3D images.",
97
+ "A team of biomedical engineers collaborate in a state-of-the-art research facility, designing and testing advanced prosthetic limbs that seamlessly integrate with the patient's nervous system for natural, intuitive control.",
98
+ "A pregnant woman undergoes a routine check-up, as a gentle robotic ultrasound system captures high-resolution 3D images of her developing baby, while the obstetrician provides reassurance and guidance via a holographic display.",
99
+ "In a cutting-edge cancer treatment center, a patient undergoes a precision radiation therapy session, where an AI-guided system delivers highly targeted doses to destroy cancer cells while preserving healthy tissue.",
100
+ "A group of medical students attend a virtual reality lecture, where they can interact with detailed, 3D anatomical models and simulate complex surgical procedures under the guidance of renowned experts from around the world.",
101
+ "In a remote village, a local healthcare worker uses a portable, AI-powered diagnostic device to quickly and accurately assess a patient's symptoms, while seamlessly connecting with specialists in distant cities for expert advice and treatment planning.",
102
+ "At an advanced fertility clinic, a couple watches in wonder as an AI-assisted system carefully selects the most viable embryos for implantation, while providing personalized guidance and emotional support throughout the process."
103
+ ]
104
+
105
+ css = '''
106
+ .gradio-container{max-width: 1024px !important}
107
+ h1{text-align:center}
108
+ footer {
109
+ visibility: hidden
110
+ }
111
+ '''
112
+
113
+ with gr.Blocks(css=css, theme="pseudolab/huggingface-korea-theme") as demo:
114
+ gr.Markdown(DESCRIPTION)
115
+
116
+ with gr.Group():
117
+ with gr.Row():
118
+ prompt = gr.Text(
119
+ label="Prompt",
120
+ show_label=False,
121
+ max_lines=1,
122
+ placeholder="Enter your prompt",
123
+ container=False,
124
+ )
125
+ run_button = gr.Button("Run", scale=0)
126
+ result = gr.Gallery(label="Result", columns=1, preview=True, show_label=False)
127
+ gallery = gr.Gallery(label="Gallery", show_label=False).style(columns=[2], rows=[2], object_fit="cover", height="auto")
128
+ with gr.Accordion("Advanced options", open=False):
129
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
130
+ negative_prompt = gr.Text(
131
+ label="Negative prompt",
132
+ lines=4,
133
+ max_lines=6,
134
+ value="""(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers:1.4), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, (NSFW:1.25)""",
135
+ placeholder="Enter a negative prompt",
136
+ visible=True,
137
+ )
138
+ seed = gr.Slider(
139
+ label="Seed",
140
+ minimum=0,
141
+ maximum=MAX_SEED,
142
+ step=1,
143
+ value=0,
144
+ visible=True
145
+ )
146
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
147
+ with gr.Row(visible=True):
148
+ width = gr.Slider(
149
+ label="Width",
150
+ minimum=512,
151
+ maximum=2048,
152
+ step=8,
153
+ value=1920,
154
+ )
155
+ height = gr.Slider(
156
+ label="Height",
157
+ minimum=512,
158
+ maximum=2048,
159
+ step=8,
160
+ value=1080,
161
+ )
162
+ with gr.Row():
163
+ guidance_scale = gr.Slider(
164
+ label="Guidance Scale",
165
+ minimum=0.1,
166
+ maximum=20.0,
167
+ step=0.1,
168
+ value=20.0,
169
+ )
170
+
171
+ gr.Examples(
172
+ examples=examples,
173
+ inputs=prompt,
174
+ outputs=[result, seed],
175
+ fn=generate,
176
+ cache_examples=False,
177
+ )
178
+
179
+ use_negative_prompt.change(
180
+ fn=lambda x: gr.update(visible=x),
181
+ inputs=use_negative_prompt,
182
+ outputs=negative_prompt,
183
+ api_name=False,
184
+ )
185
+
186
+ gr.on(
187
+ triggers=[
188
+ prompt.submit,
189
+ negative_prompt.submit,
190
+ run_button.click,
191
+ ],
192
+ fn=generate,
193
+ inputs=[
194
+ prompt,
195
+ negative_prompt,
196
+ use_negative_prompt,
197
+ seed,
198
+ width,
199
+ height,
200
+ guidance_scale,
201
+ randomize_seed,
202
+ ],
203
+ outputs=[result, seed, gallery],
204
+ api_name="run",
205
+ )
206
+
207
+ if __name__ == "__main__":
208
+ demo.queue(max_size=20).launch(show_api=False, debug=False)