parvezalmuqtadir commited on
Commit
d73bbda
1 Parent(s): 9344f0c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -0
app.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ import os
7
+ import random
8
+ import tempfile
9
+
10
+ # # set the environment variable before importing torch
11
+ # os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
12
+
13
+ import gradio as gr
14
+ import imageio
15
+ import numpy as np
16
+ import torch
17
+ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
18
+
19
+ DESCRIPTION = '# [ModelScope Text to Video Synthesis](https://modelscope.cn/models/damo/text-to-video-synthesis/summary)'
20
+ # DESCRIPTION += '\n<p>For Colab usage, you can view <a href="https://colab.research.google.com/drive/1uW1ZqswkQ9Z9bp5Nbo5z59cAn7I0hE6R?usp=sharing" style="text-decoration: underline;" target="_blank">this webpage</a>.(the latest update on 2023.03.21)</p>'
21
+ # DESCRIPTION += '\n<p>This model can only be used for non-commercial purposes. To learn more about the model, take a look at the <a href="https://huggingface.co/damo-vilab/modelscope-damo-text-to-video-synthesis" style="text-decoration: underline;" target="_blank">model card</a>.</p>'
22
+ if (SPACE_ID := os.getenv('SPACE_ID')) is not None:
23
+ DESCRIPTION += f'\n<p>For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings. <a href="https://huggingface.co/spaces/{SPACE_ID}?duplicate=true"><img style="display: inline; margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space" /></a></p>'
24
+
25
+ MAX_NUM_FRAMES = int(os.getenv('MAX_NUM_FRAMES', '200'))
26
+ DEFAULT_NUM_FRAMES = min(MAX_NUM_FRAMES,
27
+ int(os.getenv('DEFAULT_NUM_FRAMES', '16')))
28
+
29
+ pipe = DiffusionPipeline.from_pretrained('damo-vilab/text-to-video-ms-1.7b',
30
+ torch_dtype=torch.float16,
31
+ variant='fp16')
32
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
33
+ pipe.enable_model_cpu_offload()
34
+ pipe.enable_vae_slicing()
35
+
36
+
37
+ def to_video(frames: list[np.ndarray], fps: int) -> str:
38
+ out_file = tempfile.NamedTemporaryFile(suffix='.mp4', delete=False)
39
+ writer = imageio.get_writer(out_file.name, format='FFMPEG', fps=fps)
40
+ for frame in frames:
41
+ writer.append_data(frame)
42
+ writer.close()
43
+ return out_file.name
44
+
45
+
46
+ def generate(prompt: str, seed: int, num_frames: int,
47
+ num_inference_steps: int) -> str:
48
+ if seed == -1:
49
+ seed = random.randint(0, 1000000)
50
+ generator = torch.Generator().manual_seed(seed)
51
+ frames = pipe(prompt,
52
+ num_inference_steps=num_inference_steps,
53
+ num_frames=num_frames,
54
+ generator=generator).frames
55
+ return to_video(frames, 8)
56
+
57
+
58
+ examples = [
59
+ ['An astronaut riding a horse.', 0, 16, 25],
60
+ ['A panda eating bamboo on a rock.', 0, 16, 25],
61
+ ['Spiderman is surfing.', 0, 16, 25],
62
+ ]
63
+
64
+ with gr.Blocks(css='style.css') as demo:
65
+ gr.Markdown(DESCRIPTION)
66
+ with gr.Group():
67
+ with gr.Box():
68
+ with gr.Row(elem_id='prompt-container').style(equal_height=True):
69
+ prompt = gr.Text(
70
+ label='Prompt',
71
+ show_label=False,
72
+ max_lines=1,
73
+ placeholder='Enter your prompt',
74
+ elem_id='prompt-text-input').style(container=False)
75
+ run_button = gr.Button('Generate video').style(
76
+ full_width=False)
77
+ result = gr.Video(label='Result', show_label=False, elem_id='gallery')
78
+ with gr.Accordion('Advanced options', open=False):
79
+ seed = gr.Slider(
80
+ label='Seed',
81
+ minimum=-1,
82
+ maximum=1000000,
83
+ step=1,
84
+ value=-1,
85
+ info='If set to -1, a different seed will be used each time.')
86
+ num_frames = gr.Slider(
87
+ label='Number of frames',
88
+ minimum=16,
89
+ maximum=MAX_NUM_FRAMES,
90
+ step=1,
91
+ value=16,
92
+ info=
93
+ 'Note that the content of the video also changes when you change the number of frames.'
94
+ )
95
+ num_inference_steps = gr.Slider(label='Number of inference steps',
96
+ minimum=10,
97
+ maximum=50,
98
+ step=1,
99
+ value=25)
100
+
101
+ inputs = [
102
+ prompt,
103
+ seed,
104
+ num_frames,
105
+ num_inference_steps,
106
+ ]
107
+ gr.Examples(examples=examples,
108
+ inputs=inputs,
109
+ outputs=result,
110
+ fn=generate,
111
+ cache_examples=os.getenv('SYSTEM') == 'spaces')
112
+
113
+ prompt.submit(fn=generate, inputs=inputs, outputs=result)
114
+ run_button.click(fn=generate, inputs=inputs, outputs=result)
115
+
116
+ # with gr.Accordion(label='We are hiring(Based in Beijing / Hangzhou, China.)', open=False):
117
+ # gr.HTML("""<div class="acknowledgments">
118
+ # <p>
119
+ # If you're looking for an exciting challenge and the opportunity to work with cutting-edge technologies in AIGC and large-scale pretraining, then we are the place for you. We are looking for talented, motivated and creative individuals to join our team. If you are interested, please send your CV to us.
120
+ # </p>
121
+ # <p>
122
+ # <b>EMAIL: yingya.zyy@alibaba-inc.com</b>.
123
+ # </p>
124
+ # </div>
125
+ # """)
126
+
127
+ # with gr.Accordion(label='Biases and content acknowledgment', open=False):
128
+ # gr.HTML("""<div class="acknowledgments">
129
+ # <h4>Biases and content acknowledgment</h4>
130
+ # <p>
131
+ # Despite how impressive being able to turn text into video is, beware to the fact that this model may output content that reinforces or exacerbates societal biases. The training data includes LAION5B, ImageNet, Webvid and other public datasets. The model was not trained to realistically represent people or events, so using it to generate such content is beyond the model's capabilities.
132
+ # </p>
133
+ # <p>
134
+ # It is not intended to generate content that is demeaning or harmful to people or their environment, culture, religion, etc. Similarly, it is not allowed to generate pornographic, violent and bloody content generation. <b>The model is meant for research purposes</b>.
135
+ # </p>
136
+ # <p>
137
+ # To learn more about the model, head to its <a href="https://huggingface.co/damo-vilab/modelscope-damo-text-to-video-synthesis" style="text-decoration: underline;" target="_blank">model card</a>.
138
+ # </p>
139
+ # </div>
140
+ # """)
141
+
142
+ demo.queue(api_open=False, max_size=15).launch(share=True)
143
+