clone3 commited on
Commit
1de9bec
·
1 Parent(s): 534cf72

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -182
app.py CHANGED
@@ -1,185 +1,12 @@
1
  #!/usr/bin/env python
2
- from __future__ import annotations
3
 
4
- import os
5
- import random
6
- import time
7
 
8
- import gradio as gr
9
- import numpy as np
10
- import PIL.Image
11
-
12
- from huggingface_hub import snapshot_download
13
- from diffusers import DiffusionPipeline
14
-
15
- from lcm_scheduler import LCMScheduler
16
- from lcm_ov_pipeline import OVLatentConsistencyModelPipeline
17
-
18
- from optimum.intel.openvino.modeling_diffusion import OVModelVaeDecoder, OVBaseModel
19
-
20
- import os
21
- from tqdm import tqdm
22
-
23
- from concurrent.futures import ThreadPoolExecutor
24
- import uuid
25
-
26
- DESCRIPTION = '''# Latent Consistency Model OpenVino CPU
27
- Based on [Latency Consistency Model](https://huggingface.co/spaces/SimianLuo/Latent_Consistency_Model) HF space
28
-
29
- <p>Running on CPU 🥶.</p>
30
- '''
31
-
32
- MAX_SEED = np.iinfo(np.int32).max
33
- CACHE_EXAMPLES = os.getenv("CACHE_EXAMPLES") == "1"
34
-
35
- model_id = "Kano001/Dreamshaper_v7-Openvino"
36
- batch_size = 1
37
- width = int(os.getenv("IMAGE_WIDTH", "512"))
38
- height = int(os.getenv("IMAGE_HEIGHT", "512"))
39
- num_images = int(os.getenv("NUM_IMAGES", "1"))
40
-
41
- class CustomOVModelVaeDecoder(OVModelVaeDecoder):
42
- def __init__(
43
- self, model: openvino.runtime.Model, parent_model: OVBaseModel, ov_config: Optional[Dict[str, str]] = None, model_dir: str = None,
44
- ):
45
- super(OVModelVaeDecoder, self).__init__(model, parent_model, ov_config, "vae_decoder", model_dir)
46
-
47
- scheduler = LCMScheduler.from_pretrained(model_id, subfolder="scheduler")
48
- pipe = OVLatentConsistencyModelPipeline.from_pretrained(model_id, scheduler = scheduler, compile = False, ov_config = {"CACHE_DIR":""})
49
-
50
- # Inject TAESD
51
-
52
- taesd_dir = snapshot_download(repo_id="Kano001/taesd-openvino")
53
- pipe.vae_decoder = CustomOVModelVaeDecoder(model = OVBaseModel.load_model(f"{taesd_dir}/vae_decoder/openvino_model.xml"), parent_model = pipe, model_dir = taesd_dir)
54
-
55
- pipe.reshape(batch_size=batch_size, height=height, width=width, num_images_per_prompt=num_images)
56
- pipe.compile()
57
-
58
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
59
- if randomize_seed:
60
- seed = random.randint(0, MAX_SEED)
61
- return seed
62
-
63
- def save_image(img, profile: gr.OAuthProfile | None, metadata: dict):
64
- unique_name = str(uuid.uuid4()) + '.png'
65
- img.save(unique_name)
66
- return unique_name
67
-
68
- def save_images(image_array, profile: gr.OAuthProfile | None, metadata: dict):
69
- paths = []
70
- with ThreadPoolExecutor() as executor:
71
- paths = list(executor.map(save_image, image_array, [profile]*len(image_array), [metadata]*len(image_array)))
72
- return paths
73
-
74
- def generate(
75
- prompt: str,
76
- seed: int = 0,
77
- guidance_scale: float = 8.0,
78
- num_inference_steps: int = 4,
79
- randomize_seed: bool = False,
80
- progress = gr.Progress(track_tqdm=True),
81
- profile: gr.OAuthProfile | None = None,
82
- ) -> PIL.Image.Image:
83
- global batch_size
84
- global width
85
- global height
86
- global num_images
87
-
88
- seed = randomize_seed_fn(seed, randomize_seed)
89
- np.random.seed(seed)
90
- start_time = time.time()
91
- result = pipe(
92
- prompt=prompt,
93
- width=width,
94
- height=height,
95
- guidance_scale=guidance_scale,
96
- num_inference_steps=num_inference_steps,
97
- num_images_per_prompt=num_images,
98
- output_type="pil",
99
- ).images
100
- paths = save_images(result, profile, metadata={"prompt": prompt, "seed": seed, "width": width, "height": height, "guidance_scale": guidance_scale, "num_inference_steps": num_inference_steps})
101
- print(time.time() - start_time)
102
- return paths, seed
103
-
104
- examples = [
105
- "portrait photo of a girl, photograph, highly detailed face, depth of field, moody light, golden hour, style by Dan Winters, Russell James, Steve McCurry, centered, extremely detailed, Nikon D850, award winning photography",
106
- "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k",
107
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
108
- "A photo of beautiful mountain with realistic sunset and blue lake, highly detailed, masterpiece",
109
- ]
110
-
111
- with gr.Blocks(css="style.css") as demo:
112
- gr.Markdown(DESCRIPTION)
113
- gr.DuplicateButton(
114
- value="Duplicate Space for private use",
115
- elem_id="duplicate-button",
116
- visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
117
- )
118
- with gr.Group():
119
- with gr.Row():
120
- prompt = gr.Text(
121
- label="Prompt",
122
- show_label=False,
123
- max_lines=1,
124
- placeholder="Enter your prompt",
125
- container=False,
126
- )
127
- run_button = gr.Button("Run", scale=0)
128
- result = gr.Gallery(
129
- label="Generated images", show_label=False, elem_id="gallery", grid=[2]
130
- )
131
- with gr.Accordion("Advanced options", open=False):
132
- seed = gr.Slider(
133
- label="Seed",
134
- minimum=0,
135
- maximum=MAX_SEED,
136
- step=1,
137
- value=0,
138
- randomize=True
139
- )
140
- randomize_seed = gr.Checkbox(label="Randomize seed across runs", value=True)
141
- with gr.Row():
142
- guidance_scale = gr.Slider(
143
- label="Guidance scale for base",
144
- minimum=2,
145
- maximum=14,
146
- step=0.1,
147
- value=8.0,
148
- )
149
- num_inference_steps = gr.Slider(
150
- label="Number of inference steps for base",
151
- minimum=1,
152
- maximum=8,
153
- step=1,
154
- value=4,
155
- )
156
-
157
- gr.Examples(
158
- examples=examples,
159
- inputs=prompt,
160
- outputs=result,
161
- fn=generate,
162
- cache_examples=CACHE_EXAMPLES,
163
- )
164
-
165
- gr.on(
166
- triggers=[
167
- prompt.submit,
168
- run_button.click,
169
- ],
170
- fn=generate,
171
- inputs=[
172
- prompt,
173
- seed,
174
- guidance_scale,
175
- num_inference_steps,
176
- randomize_seed
177
- ],
178
- outputs=[result, seed],
179
- api_name="run",
180
- )
181
-
182
- if __name__ == "__main__":
183
- demo.queue(api_open=False)
184
- # demo.queue(max_size=20).launch()
185
- demo.launch()
 
1
  #!/usr/bin/env python
2
+ import gradio
3
 
4
+ def my_inference_function(name):
5
+ return "Hello " + name + "!"
 
6
 
7
+ gradio_interface = gradio.Interface(
8
+ fn = my_inference_function,
9
+ inputs = "text",
10
+ outputs = "text"
11
+ )
12
+ gradio_interface.launch()