vilarin commited on
Commit
b25c76b
1 Parent(s): 21ac7d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -62
app.py CHANGED
@@ -1,23 +1,22 @@
1
  import os
2
  import gradio as gr
3
  import torch
4
- from diffusers import StableAudioPipeline
5
- import spaces
6
- from translatepy import Translator
7
  import numpy as np
8
  import random
9
- import soundfile as sf
 
 
 
10
 
11
- translator = Translator()
12
 
 
 
 
13
  # Constants
14
- model = "stabilityai/stable-audio-open-1.0"
15
  MAX_SEED = np.iinfo(np.int32).max
16
 
17
  CSS = """
18
- .gradio-container {
19
- max-width: 690px !important;
20
- }
21
  footer {
22
  visibility: hidden;
23
  }
@@ -29,73 +28,135 @@ JS = """function () {
29
  window.location.replace(gradioURL + '?__theme=dark');
30
  }
31
  }"""
32
- DESCRIPTION = """
33
- <center>
34
- Stable Audio Open 1.0 generates variable-length (up to 47s) stereo audio at 44.1kHz from text prompts. \
35
- It comprises three components: an autoencoder that compresses waveforms into a manageable sequence length, \
36
- a T5-based text embedding for text conditioning, and a transformer-based diffusion (DiT) model that operates in the latent space of the autoencoder.
37
- </center>
38
- """
39
-
40
- pipe = StableAudioPipeline.from_pretrained(
41
- model,
42
- torch_dtype=torch.float16)
43
- pipe = pipe.to("cuda")
44
 
 
 
 
 
45
 
46
  # Function
47
- @spaces.GPU(duration=120)
48
- def main(
49
  prompt,
50
- negative="low quality",
51
- second: float = 10.0,
52
- seed: int = -1):
53
-
 
 
 
 
54
  if seed == -1:
55
- seed = random.randint(0, MAX_SEED)
56
  seed = int(seed)
57
- generator = torch.Generator().manual_seed(seed)
58
 
59
- prompt = str(translator.translate(prompt, 'English'))
60
 
61
- print(f'prompt:{prompt}')
 
 
62
 
63
- audio = pipe(
64
- prompt,
65
- negative_prompt=negative,
66
- audio_end_in_s=second,
67
- num_inference_steps=200,
68
- num_waveforms_per_prompt=3,
 
 
 
69
  generator=generator,
70
- ).audios
71
 
72
- os.makedirs("outputs", exist_ok=True)
73
- base_count = len(glob(os.path.join("outputs", "*.mp4")))
74
- audio_path = os.path.join("outputs", f"{base_count:06d}.wav")
75
-
76
- sf.write(audio_path, audio[0].T.float().cpu().numpy(), pipe.vae.samping_rate)
77
-
78
- return audio_path, seed
79
 
80
- # Gradio Interface
81
 
82
- with gr.Blocks(theme='soft', css=CSS, js=JS, title="Stable Audio Open") as iface:
83
- with gr.Accordion(""):
84
- gr.Markdown(DESCRIPTION)
85
- output = gr.Audio(label="Podcast", type="filepath", interactive=False, autoplay=True, elem_classes="audio") # Create an output textbox
86
- prompt = gr.Textbox(label="Prompt", placeholder="1000 BPM percussive sound of water drops")
87
- negative = gr.Textbox(label="Negative prompt", placeholder="Low quality")
88
- with gr.Row():
89
- second = gr.Slider(5.0, 60.0, value=10.0, label="Second", step=0.1),
90
- seed = gr.Slider(-1, MAX_SEED, value=-1, label="Seed", step=1),
91
- with gr.Row():
92
- submit_btn = gr.Button("🚀 Send") # Create a submit button
93
- clear_btn = gr.ClearButton([prompt, seed, output], value="🗑️ Clear") # Create a clear button
 
94
 
95
- # Set up the event listeners
96
- submit_btn.click(main, inputs=[prompt, negative, second, seed], outputs=[output, seed])
97
 
 
98
 
99
- #gr.close_all()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
- iface.queue().launch(show_api=False) # Launch the Gradio interface
 
 
1
  import os
2
  import gradio as gr
3
  import torch
 
 
 
4
  import numpy as np
5
  import random
6
+ from diffusers import FluxPipeline
7
+ import spaces
8
+ import transformers
9
+ from translatepy import Translator
10
 
 
11
 
12
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
13
+ translator = Translator()
14
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
15
  # Constants
16
+ model = "black-forest-labs/FLUX.1-dev"
17
  MAX_SEED = np.iinfo(np.int32).max
18
 
19
  CSS = """
 
 
 
20
  footer {
21
  visibility: hidden;
22
  }
 
28
  window.location.replace(gradioURL + '?__theme=dark');
29
  }
30
  }"""
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+ if torch.cuda.is_available():
33
+ pipe = FluxPipeline.from_pretrained(
34
+ model,
35
+ torch_dtype=torch.bfloat16)
36
 
37
  # Function
38
+ @spaces.GPU()
39
+ def generate_image(
40
  prompt,
41
+ width=1024,
42
+ height=1024,
43
+ scales=5,
44
+ steps=30,
45
+ seed: int =-1,
46
+ nums=1,
47
+ progress=gr.Progress(track_tqdm=True)):
48
+
49
  if seed == -1:
50
+ seed = random.randint(0, MAX_SEED)
51
  seed = int(seed)
52
+ print(f'prompt:{prompt}')
53
 
54
+ text = str(translator.translate(prompt['text'], 'English'))
55
 
56
+
57
+ generator = torch.Generator().manual_seed(seed)
58
+
59
 
60
+ image = pipe(
61
+ prompt,
62
+ height=height,
63
+ width=width,
64
+ guidance_scale=scale,
65
+ output_type="pil",
66
+ num_inference_steps=steps,
67
+ max_sequence_length=512,
68
+ num_images_per_prompt=nums,
69
  generator=generator,
70
+ ).images
71
 
72
+ print(image)
73
+ print(seed)
74
+ return image, seed
 
 
 
 
75
 
 
76
 
77
+ examples = [
78
+ "a female character with long, flowing hair that appears to be made of ethereal, swirling patterns resembling the Northern Lights or Aurora Borealis. The background is dominated by deep blues and purples, creating a mysterious and dramatic atmosphere. The character's face is serene, with pale skin and striking features. She wears a dark-colored outfit with subtle patterns. The overall style of the artwork is reminiscent of fantasy or supernatural genres",
79
+ "Digital art, portrait of an anthropomorphic roaring Tiger warrior with full armor, close up in the middle of a battle, behind him there is a banner with the text \"Open Source\".",
80
+ "photo of a dog and a cat both standing on a red box, with a blue ball in the middle with a parrot standing on top of the ball. The box has the text \"FLUX\"",
81
+ "selfie photo of a wizard with long beard and purple robes, he is apparently in the middle of Tokyo. Probably taken from a phone.",
82
+ "A vibrant street wall covered in colorful graffiti, the centerpiece spells \"FLUX\", in a storm of colors",
83
+ "photo of a young woman with long, wavy brown hair tied in a bun and glasses. She has a fair complexion and is wearing subtle makeup, emphasizing her eyes and lips. She is dressed in a black top. The background appears to be an urban setting with a building facade, and the sunlight casts a warm glow on her face.",
84
+ "anime art of a steampunk inventor in their workshop, surrounded by gears, gadgets, and steam. He is holding a blue potion and a red potion, one in each hand",
85
+ "photo of picturesque scene of a road surrounded by lush green trees and shrubs. The road is wide and smooth, leading into the distance. On the right side of the road, there's a blue sports car parked with the license plate spelling \"FLUX\". The sky above is partly cloudy, suggesting a pleasant day. The trees have a mix of green and brown foliage. There are no people visible in the image. The overall composition is balanced, with the car serving as a focal point.",
86
+ "photo of young man in a black suit, white shirt, and black tie. He has a neatly styled haircut and is looking directly at the camera with a neutral expression. The background consists of a textured wall with horizontal lines. The photograph is in black and white, emphasizing contrasts and shadows. The man appears to be in his late twenties or early thirties, with fair skin and short, dark hair.",
87
+ "photo of a woman on the beach, shot from above. She is facing the sea, while wearing a white dress. She has long blonde hair"
88
+ ]
89
+
90
 
 
 
91
 
92
+ # Gradio Interface
93
 
94
+ with gr.Blocks(css=CSS, js=JS, theme="soft") as demo:
95
+ gr.HTML("<h1><center>Flux Dev</center></h1>")
96
+ gr.HTML("<p><center><a href='https://huggingface.co/black-forest-labs/FLUX.1-dev'>FLUX</a> text-to-image generation<br><b>Feature</b>: Support 512 token and multi-languages</center></p>")
97
+ with gr.Row():
98
+ with gr.Column(scale=4):
99
+ img = gr.Gallery(label='flux Generated Image', columns = 1, preview=True, height=600)
100
+ prompt = gr.Textbox(label='Enter Your Prompt (Multi-Languages)', placeholder="Enter prompt...")
101
+ with gr.Accordion("Advanced Options", open=True):
102
+ with gr.Column(scale=1):
103
+ width = gr.Slider(
104
+ label="Width",
105
+ minimum=512,
106
+ maximum=1280,
107
+ step=8,
108
+ value=1024,
109
+ )
110
+ height = gr.Slider(
111
+ label="Height",
112
+ minimum=512,
113
+ maximum=1280,
114
+ step=8,
115
+ value=1024,
116
+ )
117
+ scales = gr.Slider(
118
+ label="Guidance",
119
+ minimum=3.5,
120
+ maximum=7,
121
+ step=0.1,
122
+ value=3.5,
123
+ )
124
+ steps = gr.Slider(
125
+ label="Steps",
126
+ minimum=1,
127
+ maximum=50,
128
+ step=1,
129
+ value=30,
130
+ )
131
+ seed = gr.Slider(
132
+ label="Seed (-1 Random)",
133
+ minimum=-1,
134
+ maximum=MAX_SEED,
135
+ step=1,
136
+ value=-1,
137
+ scale=2,
138
+ )
139
+ nums = gr.Slider(
140
+ label="Image Numbers",
141
+ minimum=1,
142
+ maximum=4,
143
+ step=1,
144
+ value=1,
145
+ scale=1,
146
+ )
147
+ gr.Examples(
148
+ examples=examples,
149
+ inputs=prompt,
150
+ outputs=[img, seed],
151
+ fn=generate_image,
152
+ cache_examples="lazy",
153
+ examples_per_page=4,
154
+ )
155
+
156
+ prompt.submit(fn=generate_image,
157
+ inputs=[prompt, width, height, scales, steps, seed, nums],
158
+ outputs=[img, seed],
159
+ )
160
 
161
+
162
+ demo.queue().launch()