Spaces:
Runtime error
Runtime error
Demo version 3
Browse files- LICENSE +83 -0
- app_canny.py +15 -9
- app_canny_db.py +6 -0
- app_pix2pix_video.py +22 -10
- app_pose.py +14 -17
- app_text_to_video.py +60 -16
- gradio_utils.py +26 -14
- model.py +152 -70
- text_to_video/text_to_video_generator.py +0 -79
- text_to_video/text_to_video_pipeline.py +183 -106
- utils.py +37 -22
LICENSE
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright (c) 2023 Levon Khachatryan and Andranik Movsisyan and Vahram Tadevosyan and Roberto Henschel and Zhangyang Wang and Shant Navasardyan and Humphrey Shi
|
2 |
+
|
3 |
+
|
4 |
+
CreativeML Open RAIL-M
|
5 |
+
dated March 28, 2023
|
6 |
+
|
7 |
+
Section I: PREAMBLE
|
8 |
+
|
9 |
+
Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation.
|
10 |
+
|
11 |
+
Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
|
12 |
+
|
13 |
+
In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation.
|
14 |
+
|
15 |
+
Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI.
|
16 |
+
|
17 |
+
This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
|
18 |
+
|
19 |
+
NOW THEREFORE, You and Licensor agree as follows:
|
20 |
+
|
21 |
+
1. Definitions
|
22 |
+
|
23 |
+
- "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
|
24 |
+
- "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
|
25 |
+
- "Output" means the results of operating a Model as embodied in informational content resulting therefrom.
|
26 |
+
- "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
|
27 |
+
- "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
|
28 |
+
- "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
|
29 |
+
- "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
|
30 |
+
- "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model.
|
31 |
+
- "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator.
|
32 |
+
- "Third Parties" means individuals or legal entities that are not under common control with Licensor or You.
|
33 |
+
- "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
34 |
+
- "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
|
35 |
+
|
36 |
+
Section II: INTELLECTUAL PROPERTY RIGHTS
|
37 |
+
|
38 |
+
Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
|
39 |
+
|
40 |
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
|
41 |
+
3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed.
|
42 |
+
|
43 |
+
Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
|
44 |
+
|
45 |
+
4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:
|
46 |
+
Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.
|
47 |
+
You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
|
48 |
+
You must cause any modified files to carry prominent notices stating that You changed the files;
|
49 |
+
You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.
|
50 |
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
|
51 |
+
5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
|
52 |
+
6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
|
53 |
+
|
54 |
+
Section IV: OTHER PROVISIONS
|
55 |
+
|
56 |
+
7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License, update the Model through electronic means, or modify the Output of the Model based on updates. You shall undertake reasonable efforts to use the latest version of the Model.
|
57 |
+
8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.
|
58 |
+
9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
|
59 |
+
10. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
60 |
+
11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
61 |
+
12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
|
62 |
+
|
63 |
+
END OF TERMS AND CONDITIONS
|
64 |
+
|
65 |
+
|
66 |
+
|
67 |
+
|
68 |
+
Attachment A
|
69 |
+
|
70 |
+
Use Restrictions
|
71 |
+
|
72 |
+
You agree not to use the Model or Derivatives of the Model:
|
73 |
+
- In any way that violates any applicable national, federal, state, local or international law or regulation;
|
74 |
+
- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
|
75 |
+
- To generate or disseminate verifiably false information and/or content with the purpose of harming others;
|
76 |
+
- To generate or disseminate personal identifiable information that can be used to harm an individual;
|
77 |
+
- To defame, disparage or otherwise harass others;
|
78 |
+
- For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
|
79 |
+
- For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
|
80 |
+
- To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
|
81 |
+
- For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;
|
82 |
+
- To provide medical advice and medical results interpretation;
|
83 |
+
- To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use).
|
app_canny.py
CHANGED
@@ -4,13 +4,13 @@ from model import Model
|
|
4 |
def create_demo(model: Model):
|
5 |
|
6 |
examples = [
|
7 |
-
["__assets__/
|
8 |
-
["__assets__/
|
9 |
-
["__assets__/
|
10 |
-
["__assets__/
|
11 |
-
["__assets__/
|
12 |
-
["__assets__/
|
13 |
-
["__assets__/
|
14 |
]
|
15 |
|
16 |
with gr.Blocks() as demo:
|
@@ -28,16 +28,22 @@ def create_demo(model: Model):
|
|
28 |
|
29 |
with gr.Row():
|
30 |
with gr.Column():
|
31 |
-
input_video = gr.Video(
|
|
|
32 |
with gr.Column():
|
33 |
prompt = gr.Textbox(label='Prompt')
|
34 |
run_button = gr.Button(label='Run')
|
|
|
|
|
|
|
35 |
with gr.Column():
|
36 |
result = gr.Video(label="Generated Video").style(height="auto")
|
37 |
|
38 |
inputs = [
|
39 |
input_video,
|
40 |
-
prompt,
|
|
|
|
|
41 |
]
|
42 |
|
43 |
gr.Examples(examples=examples,
|
|
|
4 |
def create_demo(model: Model):
|
5 |
|
6 |
examples = [
|
7 |
+
["__assets__/canny_videos_edge_2fps/butterfly.mp4", "white butterfly, a high-quality, detailed, and professional photo"],
|
8 |
+
["__assets__/canny_videos_edge_2fps/deer.mp4", "oil painting of a deer, a high-quality, detailed, and professional photo"],
|
9 |
+
["__assets__/canny_videos_edge_2fps/fox.mp4", "wild red fox is walking on the grass, a high-quality, detailed, and professional photo"],
|
10 |
+
["__assets__/canny_videos_edge_2fps/girl_dancing.mp4", "oil painting of a girl dancing close-up, masterpiece, a high-quality, detailed, and professional photo"],
|
11 |
+
["__assets__/canny_videos_edge_2fps/girl_turning.mp4", "oil painting of a beautiful girl, a high-quality, detailed, and professional photo"],
|
12 |
+
["__assets__/canny_videos_edge_2fps/halloween.mp4", "beautiful girl halloween style, a high-quality, detailed, and professional photo"],
|
13 |
+
["__assets__/canny_videos_edge_2fps/santa.mp4", "a santa claus, a high-quality, detailed, and professional photo"],
|
14 |
]
|
15 |
|
16 |
with gr.Blocks() as demo:
|
|
|
28 |
|
29 |
with gr.Row():
|
30 |
with gr.Column():
|
31 |
+
input_video = gr.Video(
|
32 |
+
label="Input Video", source='upload', format="mp4", visible=True).style(height="auto")
|
33 |
with gr.Column():
|
34 |
prompt = gr.Textbox(label='Prompt')
|
35 |
run_button = gr.Button(label='Run')
|
36 |
+
with gr.Accordion('Advanced options', open=False):
|
37 |
+
watermark = gr.Radio(["Picsart AI Research", "Text2Video-Zero", "None"], label="Watermark", value='Picsart AI Research')
|
38 |
+
chunk_size = gr.Slider(label="Chunk size", minimum=2, maximum=8, value=8, step=1)
|
39 |
with gr.Column():
|
40 |
result = gr.Video(label="Generated Video").style(height="auto")
|
41 |
|
42 |
inputs = [
|
43 |
input_video,
|
44 |
+
prompt,
|
45 |
+
chunk_size,
|
46 |
+
watermark,
|
47 |
]
|
48 |
|
49 |
gr.Examples(examples=examples,
|
app_canny_db.py
CHANGED
@@ -38,11 +38,15 @@ def create_demo(model: Model):
|
|
38 |
|
39 |
with gr.Row():
|
40 |
with gr.Column():
|
|
|
41 |
gr.Markdown("## Selection")
|
42 |
db_text_field = gr.Markdown('DB Model: **Anime DB** ')
|
43 |
canny_text_field = gr.Markdown('Motion: **woman1**')
|
44 |
prompt = gr.Textbox(label='Prompt')
|
45 |
run_button = gr.Button(label='Run')
|
|
|
|
|
|
|
46 |
with gr.Column():
|
47 |
result = gr.Image(label="Generated Video").style(height=400)
|
48 |
|
@@ -65,6 +69,8 @@ def create_demo(model: Model):
|
|
65 |
db_selection,
|
66 |
canny_selection,
|
67 |
prompt,
|
|
|
|
|
68 |
]
|
69 |
|
70 |
gr.Examples(examples=examples,
|
|
|
38 |
|
39 |
with gr.Row():
|
40 |
with gr.Column():
|
41 |
+
# input_video_path = gr.Video(source='upload', format="mp4", visible=False)
|
42 |
gr.Markdown("## Selection")
|
43 |
db_text_field = gr.Markdown('DB Model: **Anime DB** ')
|
44 |
canny_text_field = gr.Markdown('Motion: **woman1**')
|
45 |
prompt = gr.Textbox(label='Prompt')
|
46 |
run_button = gr.Button(label='Run')
|
47 |
+
with gr.Accordion('Advanced options', open=False):
|
48 |
+
watermark = gr.Radio(["Picsart AI Research", "Text2Video-Zero", "None"], label="Watermark", value='Picsart AI Research')
|
49 |
+
chunk_size = gr.Slider(label="Chunk size", minimum=2, maximum=8, value=8, step=1)
|
50 |
with gr.Column():
|
51 |
result = gr.Image(label="Generated Video").style(height=400)
|
52 |
|
|
|
69 |
db_selection,
|
70 |
canny_selection,
|
71 |
prompt,
|
72 |
+
chunk_size,
|
73 |
+
watermark,
|
74 |
]
|
75 |
|
76 |
gr.Examples(examples=examples,
|
app_pix2pix_video.py
CHANGED
@@ -4,10 +4,12 @@ from model import Model
|
|
4 |
|
5 |
def create_demo(model: Model):
|
6 |
examples = [
|
7 |
-
['__assets__/
|
8 |
-
['__assets__/
|
9 |
-
['__assets__/
|
10 |
-
['__assets__/
|
|
|
|
|
11 |
]
|
12 |
with gr.Blocks() as demo:
|
13 |
with gr.Row():
|
@@ -29,6 +31,7 @@ def create_demo(model: Model):
|
|
29 |
prompt = gr.Textbox(label='Prompt')
|
30 |
run_button = gr.Button(label='Run')
|
31 |
with gr.Accordion('Advanced options', open=False):
|
|
|
32 |
image_resolution = gr.Slider(label='Image Resolution',
|
33 |
minimum=256,
|
34 |
maximum=1024,
|
@@ -39,31 +42,40 @@ def create_demo(model: Model):
|
|
39 |
maximum=65536,
|
40 |
value=0,
|
41 |
step=1)
|
|
|
|
|
|
|
|
|
|
|
42 |
start_t = gr.Slider(label='Starting time in seconds',
|
43 |
minimum=0,
|
44 |
maximum=10,
|
45 |
value=0,
|
46 |
step=1)
|
47 |
-
end_t = gr.Slider(label='End time in seconds',
|
48 |
minimum=0,
|
49 |
-
maximum=
|
|
|
50 |
step=1)
|
51 |
-
out_fps = gr.Slider(label='Output video fps',
|
52 |
minimum=1,
|
53 |
maximum=30,
|
54 |
value=-1,
|
55 |
step=1)
|
|
|
56 |
with gr.Column():
|
57 |
-
result = gr.Video(label='Output',
|
58 |
-
show_label=True)
|
59 |
inputs = [
|
60 |
input_image,
|
61 |
prompt,
|
62 |
image_resolution,
|
63 |
seed,
|
|
|
64 |
start_t,
|
65 |
end_t,
|
66 |
-
out_fps
|
|
|
|
|
67 |
]
|
68 |
|
69 |
gr.Examples(examples=examples,
|
|
|
4 |
|
5 |
def create_demo(model: Model):
|
6 |
examples = [
|
7 |
+
['__assets__/pix2pix_video_2fps/camel.mp4', 'make it Van Gogh Starry Night style', 512, 0, 1.0],
|
8 |
+
['__assets__/pix2pix_video_2fps/mini-cooper.mp4', 'make it Picasso style', 512, 0, 1.5],
|
9 |
+
['__assets__/pix2pix_video_2fps/snowboard.mp4', 'replace man with robot', 512, 0, 1.0],
|
10 |
+
['__assets__/pix2pix_video_2fps/white-swan.mp4', 'replace swan with mallard', 512, 0, 1.5],
|
11 |
+
['__assets__/pix2pix_video_2fps/boat.mp4', 'add city skyline in the background', 512, 0, 1.5],
|
12 |
+
['__assets__/pix2pix_video_2fps/ballet.mp4', 'make her a golden sculpture', 512, 0, 1.0],
|
13 |
]
|
14 |
with gr.Blocks() as demo:
|
15 |
with gr.Row():
|
|
|
31 |
prompt = gr.Textbox(label='Prompt')
|
32 |
run_button = gr.Button(label='Run')
|
33 |
with gr.Accordion('Advanced options', open=False):
|
34 |
+
watermark = gr.Radio(["Picsart AI Research", "Text2Video-Zero", "None"], label="Watermark", value='Picsart AI Research')
|
35 |
image_resolution = gr.Slider(label='Image Resolution',
|
36 |
minimum=256,
|
37 |
maximum=1024,
|
|
|
42 |
maximum=65536,
|
43 |
value=0,
|
44 |
step=1)
|
45 |
+
image_guidance = gr.Slider(label='Image guidance scale',
|
46 |
+
minimum=0.5,
|
47 |
+
maximum=2,
|
48 |
+
value=1.0,
|
49 |
+
step=0.1)
|
50 |
start_t = gr.Slider(label='Starting time in seconds',
|
51 |
minimum=0,
|
52 |
maximum=10,
|
53 |
value=0,
|
54 |
step=1)
|
55 |
+
end_t = gr.Slider(label='End time in seconds (-1 corresponds to uploaded video duration)',
|
56 |
minimum=0,
|
57 |
+
maximum=10,
|
58 |
+
value=-1,
|
59 |
step=1)
|
60 |
+
out_fps = gr.Slider(label='Output video fps (-1 corresponds to uploaded video fps)',
|
61 |
minimum=1,
|
62 |
maximum=30,
|
63 |
value=-1,
|
64 |
step=1)
|
65 |
+
chunk_size = gr.Slider(label="Chunk size", minimum=2, maximum=8, value=8, step=1)
|
66 |
with gr.Column():
|
67 |
+
result = gr.Video(label='Output', show_label=True)
|
|
|
68 |
inputs = [
|
69 |
input_image,
|
70 |
prompt,
|
71 |
image_resolution,
|
72 |
seed,
|
73 |
+
image_guidance,
|
74 |
start_t,
|
75 |
end_t,
|
76 |
+
out_fps,
|
77 |
+
chunk_size,
|
78 |
+
watermark
|
79 |
]
|
80 |
|
81 |
gr.Examples(examples=examples,
|
app_pose.py
CHANGED
@@ -4,29 +4,20 @@ import os
|
|
4 |
from model import Model
|
5 |
|
6 |
examples = [
|
7 |
-
['Motion 1', "
|
8 |
-
['Motion 2', "
|
9 |
-
['Motion 3', "
|
10 |
-
['Motion 4', "
|
11 |
-
['Motion 5', "
|
12 |
]
|
13 |
|
14 |
def create_demo(model: Model):
|
15 |
with gr.Blocks() as demo:
|
16 |
with gr.Row():
|
17 |
gr.Markdown('## Text and Pose Conditional Video Generation')
|
18 |
-
# with gr.Row():
|
19 |
-
# gr.HTML(
|
20 |
-
# """
|
21 |
-
# <div style="text-align: left; auto;">
|
22 |
-
# <h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
|
23 |
-
# Description:
|
24 |
-
# </h3>
|
25 |
-
# </div>
|
26 |
-
# """)
|
27 |
|
28 |
with gr.Row():
|
29 |
-
gr.Markdown('
|
30 |
with gr.Column():
|
31 |
gallery_pose_sequence = gr.Gallery(label="Pose Sequence", value=[('__assets__/poses_skeleton_gifs/dance1.gif', "Motion 1"), ('__assets__/poses_skeleton_gifs/dance2.gif', "Motion 2"), ('__assets__/poses_skeleton_gifs/dance3.gif', "Motion 3"), ('__assets__/poses_skeleton_gifs/dance4.gif', "Motion 4"), ('__assets__/poses_skeleton_gifs/dance5.gif', "Motion 5")]).style(grid=[2], height="auto")
|
32 |
input_video_path = gr.Textbox(label="Pose Sequence",visible=False,value="Motion 1")
|
@@ -35,6 +26,9 @@ def create_demo(model: Model):
|
|
35 |
with gr.Column():
|
36 |
prompt = gr.Textbox(label='Prompt')
|
37 |
run_button = gr.Button(label='Run')
|
|
|
|
|
|
|
38 |
with gr.Column():
|
39 |
result = gr.Image(label="Generated Video")
|
40 |
|
@@ -43,6 +37,8 @@ def create_demo(model: Model):
|
|
43 |
inputs = [
|
44 |
input_video_path,
|
45 |
prompt,
|
|
|
|
|
46 |
]
|
47 |
|
48 |
gr.Examples(examples=examples,
|
@@ -61,7 +57,8 @@ def create_demo(model: Model):
|
|
61 |
|
62 |
|
63 |
def on_video_path_update(evt: gr.EventData):
|
64 |
-
return f'
|
|
|
65 |
|
66 |
def pose_gallery_callback(evt: gr.SelectData):
|
67 |
-
return f"Motion {evt.index+1}"
|
|
|
4 |
from model import Model
|
5 |
|
6 |
examples = [
|
7 |
+
['Motion 1', "An astronaut dancing in the outer space"],
|
8 |
+
['Motion 2', "An astronaut dancing in the outer space"],
|
9 |
+
['Motion 3', "An astronaut dancing in the outer space"],
|
10 |
+
['Motion 4', "An astronaut dancing in the outer space"],
|
11 |
+
['Motion 5', "An astronaut dancing in the outer space"],
|
12 |
]
|
13 |
|
14 |
def create_demo(model: Model):
|
15 |
with gr.Blocks() as demo:
|
16 |
with gr.Row():
|
17 |
gr.Markdown('## Text and Pose Conditional Video Generation')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
with gr.Row():
|
20 |
+
gr.Markdown('Selection: **one motion** and a **prompt**, or use the examples below.')
|
21 |
with gr.Column():
|
22 |
gallery_pose_sequence = gr.Gallery(label="Pose Sequence", value=[('__assets__/poses_skeleton_gifs/dance1.gif', "Motion 1"), ('__assets__/poses_skeleton_gifs/dance2.gif', "Motion 2"), ('__assets__/poses_skeleton_gifs/dance3.gif', "Motion 3"), ('__assets__/poses_skeleton_gifs/dance4.gif', "Motion 4"), ('__assets__/poses_skeleton_gifs/dance5.gif', "Motion 5")]).style(grid=[2], height="auto")
|
23 |
input_video_path = gr.Textbox(label="Pose Sequence",visible=False,value="Motion 1")
|
|
|
26 |
with gr.Column():
|
27 |
prompt = gr.Textbox(label='Prompt')
|
28 |
run_button = gr.Button(label='Run')
|
29 |
+
with gr.Accordion('Advanced options', open=False):
|
30 |
+
watermark = gr.Radio(["Picsart AI Research", "Text2Video-Zero", "None"], label="Watermark",value='Picsart AI Research')
|
31 |
+
chunk_size = gr.Slider(label="Chunk size", minimum=2, maximum=8, value=8, step=1)
|
32 |
with gr.Column():
|
33 |
result = gr.Image(label="Generated Video")
|
34 |
|
|
|
37 |
inputs = [
|
38 |
input_video_path,
|
39 |
prompt,
|
40 |
+
chunk_size,
|
41 |
+
watermark,
|
42 |
]
|
43 |
|
44 |
gr.Examples(examples=examples,
|
|
|
57 |
|
58 |
|
59 |
def on_video_path_update(evt: gr.EventData):
|
60 |
+
return f'Selection: **{evt._data}**'
|
61 |
+
|
62 |
|
63 |
def pose_gallery_callback(evt: gr.SelectData):
|
64 |
+
return f"Motion {evt.index+1}"
|
app_text_to_video.py
CHANGED
@@ -1,6 +1,8 @@
|
|
1 |
import gradio as gr
|
2 |
from model import Model
|
3 |
from functools import partial
|
|
|
|
|
4 |
|
5 |
examples = [
|
6 |
["an astronaut waving the arm on the moon"],
|
@@ -15,6 +17,38 @@ examples = [
|
|
15 |
]
|
16 |
|
17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
def create_demo(model: Model):
|
19 |
|
20 |
with gr.Blocks() as demo:
|
@@ -25,37 +59,47 @@ def create_demo(model: Model):
|
|
25 |
"""
|
26 |
<div style="text-align: left; auto;">
|
27 |
<h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
|
28 |
-
Description: Simply input <b>any textual prompt</b> to generate videos right away and unleash your creativity and imagination! You can also select from the examples below. For performance purposes, our current preview release generates only 8 output frames and output 4s videos.
|
29 |
</h3>
|
30 |
</div>
|
31 |
""")
|
32 |
|
33 |
with gr.Row():
|
34 |
with gr.Column():
|
|
|
|
|
|
|
|
|
|
|
35 |
prompt = gr.Textbox(label='Prompt')
|
36 |
run_button = gr.Button(label='Run')
|
37 |
with gr.Accordion('Advanced options', open=False):
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
motion_field_strength_y = gr.Slider(label='Global Translation $\delta_{y}$',
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
n_prompt = gr.Textbox(label="Optional Negative Prompt",
|
51 |
-
value='')
|
52 |
with gr.Column():
|
53 |
result = gr.Video(label="Generated Video")
|
|
|
54 |
inputs = [
|
55 |
prompt,
|
|
|
56 |
motion_field_strength_x,
|
57 |
motion_field_strength_y,
|
58 |
-
|
|
|
|
|
|
|
|
|
|
|
59 |
]
|
60 |
|
61 |
gr.Examples(examples=examples,
|
|
|
1 |
import gradio as gr
|
2 |
from model import Model
|
3 |
from functools import partial
|
4 |
+
from bs4 import BeautifulSoup
|
5 |
+
import requests
|
6 |
|
7 |
examples = [
|
8 |
["an astronaut waving the arm on the moon"],
|
|
|
17 |
]
|
18 |
|
19 |
|
20 |
+
def model_url_list():
|
21 |
+
url_list = []
|
22 |
+
for i in range(0, 5):
|
23 |
+
url_list.append(f"https://huggingface.co/models?p={i}&sort=downloads&search=dreambooth")
|
24 |
+
return url_list
|
25 |
+
|
26 |
+
def data_scraping(url_list):
|
27 |
+
model_list = []
|
28 |
+
for url in url_list:
|
29 |
+
response = requests.get(url)
|
30 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
31 |
+
div_class = 'grid grid-cols-1 gap-5 2xl:grid-cols-2'
|
32 |
+
div = soup.find('div', {'class': div_class})
|
33 |
+
for a in div.find_all('a', href=True):
|
34 |
+
model_list.append(a['href'])
|
35 |
+
return model_list
|
36 |
+
|
37 |
+
model_list = data_scraping(model_url_list())
|
38 |
+
for i in range(len(model_list)):
|
39 |
+
model_list[i] = model_list[i][1:]
|
40 |
+
|
41 |
+
best_model_list = [
|
42 |
+
"dreamlike-art/dreamlike-photoreal-2.0",
|
43 |
+
"dreamlike-art/dreamlike-diffusion-1.0",
|
44 |
+
"runwayml/stable-diffusion-v1-5",
|
45 |
+
"CompVis/stable-diffusion-v1-4",
|
46 |
+
"prompthero/openjourney",
|
47 |
+
]
|
48 |
+
|
49 |
+
model_list = best_model_list + model_list
|
50 |
+
|
51 |
+
|
52 |
def create_demo(model: Model):
|
53 |
|
54 |
with gr.Blocks() as demo:
|
|
|
59 |
"""
|
60 |
<div style="text-align: left; auto;">
|
61 |
<h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
|
62 |
+
Description: Simply input <b>any textual prompt</b> to generate videos right away and unleash your creativity and imagination! You can also select from the examples below. For performance purposes, our current preview release by default generates only 8 output frames and output 4s videos, but you can increase it from Advanced Options.
|
63 |
</h3>
|
64 |
</div>
|
65 |
""")
|
66 |
|
67 |
with gr.Row():
|
68 |
with gr.Column():
|
69 |
+
model_name = gr.Dropdown(
|
70 |
+
label="Model",
|
71 |
+
choices=model_list,
|
72 |
+
value="dreamlike-art/dreamlike-photoreal-2.0",
|
73 |
+
)
|
74 |
prompt = gr.Textbox(label='Prompt')
|
75 |
run_button = gr.Button(label='Run')
|
76 |
with gr.Accordion('Advanced options', open=False):
|
77 |
+
watermark = gr.Radio(["Picsart AI Research", "Text2Video-Zero", "None"], label="Watermark", value='Picsart AI Research')
|
78 |
+
|
79 |
+
video_length = gr.Number(label="Video length", value=8, min=2, precision=0)
|
80 |
+
chunk_size = gr.Slider(label="Chunk size", minimum=2, maximum=32, value=8, step=1)
|
81 |
+
|
82 |
+
motion_field_strength_x = gr.Slider(label='Global Translation $\delta_{x}$', minimum=-20, maximum=20, value=12, step=1)
|
83 |
+
motion_field_strength_y = gr.Slider(label='Global Translation $\delta_{y}$', minimum=-20, maximum=20, value=12, step=1)
|
84 |
+
|
85 |
+
t0 = gr.Slider(label="Timestep t0", minimum=0, maximum=49, value=44, step=1)
|
86 |
+
t1 = gr.Slider(label="Timestep t1", minimum=0, maximum=49, value=47, step=1)
|
87 |
+
|
88 |
+
n_prompt = gr.Textbox(label="Optional Negative Prompt", value='')
|
|
|
|
|
89 |
with gr.Column():
|
90 |
result = gr.Video(label="Generated Video")
|
91 |
+
|
92 |
inputs = [
|
93 |
prompt,
|
94 |
+
model_name,
|
95 |
motion_field_strength_x,
|
96 |
motion_field_strength_y,
|
97 |
+
t0,
|
98 |
+
t1,
|
99 |
+
n_prompt,
|
100 |
+
chunk_size,
|
101 |
+
video_length,
|
102 |
+
watermark,
|
103 |
]
|
104 |
|
105 |
gr.Examples(examples=examples,
|
gradio_utils.py
CHANGED
@@ -4,23 +4,22 @@ def edge_path_to_video_path(edge_path):
|
|
4 |
|
5 |
vid_name = edge_path.split("/")[-1]
|
6 |
if vid_name == "butterfly.mp4":
|
7 |
-
video_path = "__assets__/
|
8 |
elif vid_name == "deer.mp4":
|
9 |
-
video_path = "__assets__/
|
10 |
elif vid_name == "fox.mp4":
|
11 |
-
video_path = "__assets__/
|
12 |
elif vid_name == "girl_dancing.mp4":
|
13 |
-
video_path = "__assets__/
|
14 |
elif vid_name == "girl_turning.mp4":
|
15 |
-
video_path = "__assets__/
|
16 |
elif vid_name == "halloween.mp4":
|
17 |
-
video_path = "__assets__/
|
18 |
elif vid_name == "santa.mp4":
|
19 |
-
video_path = "__assets__/
|
20 |
return video_path
|
21 |
|
22 |
|
23 |
-
# App Pose utils
|
24 |
def motion_to_video_path(motion):
|
25 |
videos = [
|
26 |
"__assets__/poses_skeleton_gifs/dance1_corr.mp4",
|
@@ -29,23 +28,26 @@ def motion_to_video_path(motion):
|
|
29 |
"__assets__/poses_skeleton_gifs/dance4_corr.mp4",
|
30 |
"__assets__/poses_skeleton_gifs/dance5_corr.mp4"
|
31 |
]
|
32 |
-
|
33 |
-
|
|
|
|
|
|
|
34 |
|
35 |
|
36 |
# App Canny Dreambooth utils
|
37 |
def get_video_from_canny_selection(canny_selection):
|
38 |
if canny_selection == "woman1":
|
39 |
-
input_video_path = "__assets__/
|
40 |
|
41 |
elif canny_selection == "woman2":
|
42 |
-
input_video_path = "__assets__/
|
43 |
|
44 |
elif canny_selection == "man1":
|
45 |
-
input_video_path = "__assets__/
|
46 |
|
47 |
elif canny_selection == "woman3":
|
48 |
-
input_video_path = "__assets__/
|
49 |
else:
|
50 |
raise Exception
|
51 |
|
@@ -75,3 +77,13 @@ def get_canny_name_from_id(id):
|
|
75 |
canny_names = ["woman1", "woman2", "man1", "woman3"]
|
76 |
return canny_names[id]
|
77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
vid_name = edge_path.split("/")[-1]
|
6 |
if vid_name == "butterfly.mp4":
|
7 |
+
video_path = "__assets__/canny_videos_mp4_2fps/butterfly.mp4"
|
8 |
elif vid_name == "deer.mp4":
|
9 |
+
video_path = "__assets__/canny_videos_mp4_2fps/deer.mp4"
|
10 |
elif vid_name == "fox.mp4":
|
11 |
+
video_path = "__assets__/canny_videos_mp4_2fps/fox.mp4"
|
12 |
elif vid_name == "girl_dancing.mp4":
|
13 |
+
video_path = "__assets__/canny_videos_mp4_2fps/girl_dancing.mp4"
|
14 |
elif vid_name == "girl_turning.mp4":
|
15 |
+
video_path = "__assets__/canny_videos_mp4_2fps/girl_turning.mp4"
|
16 |
elif vid_name == "halloween.mp4":
|
17 |
+
video_path = "__assets__/canny_videos_mp4_2fps/halloween.mp4"
|
18 |
elif vid_name == "santa.mp4":
|
19 |
+
video_path = "__assets__/canny_videos_mp4_2fps/santa.mp4"
|
20 |
return video_path
|
21 |
|
22 |
|
|
|
23 |
def motion_to_video_path(motion):
|
24 |
videos = [
|
25 |
"__assets__/poses_skeleton_gifs/dance1_corr.mp4",
|
|
|
28 |
"__assets__/poses_skeleton_gifs/dance4_corr.mp4",
|
29 |
"__assets__/poses_skeleton_gifs/dance5_corr.mp4"
|
30 |
]
|
31 |
+
if len(motion.split(" ")) > 1 and motion.split(" ")[1].isnumeric():
|
32 |
+
id = int(motion.split(" ")[1]) - 1
|
33 |
+
return videos[id]
|
34 |
+
else:
|
35 |
+
return motion
|
36 |
|
37 |
|
38 |
# App Canny Dreambooth utils
|
39 |
def get_video_from_canny_selection(canny_selection):
|
40 |
if canny_selection == "woman1":
|
41 |
+
input_video_path = "__assets__/db_files_2fps/woman1.mp4"
|
42 |
|
43 |
elif canny_selection == "woman2":
|
44 |
+
input_video_path = "__assets__/db_files_2fps/woman2.mp4"
|
45 |
|
46 |
elif canny_selection == "man1":
|
47 |
+
input_video_path = "__assets__/db_files_2fps/man1.mp4"
|
48 |
|
49 |
elif canny_selection == "woman3":
|
50 |
+
input_video_path = "__assets__/db_files_2fps/woman3.mp4"
|
51 |
else:
|
52 |
raise Exception
|
53 |
|
|
|
77 |
canny_names = ["woman1", "woman2", "man1", "woman3"]
|
78 |
return canny_names[id]
|
79 |
|
80 |
+
|
81 |
+
def logo_name_to_path(name):
|
82 |
+
logo_paths = {
|
83 |
+
'Picsart AI Research': '__assets__/pair_watermark.png',
|
84 |
+
'Text2Video-Zero': '__assets__/t2v-z_watermark.png',
|
85 |
+
'None': None
|
86 |
+
}
|
87 |
+
if name in logo_paths:
|
88 |
+
return logo_paths[name]
|
89 |
+
return name
|
model.py
CHANGED
@@ -11,7 +11,7 @@ from text_to_video.text_to_video_pipeline import TextToVideoPipeline
|
|
11 |
import utils
|
12 |
import gradio_utils
|
13 |
|
14 |
-
decord.bridge.set_bridge('torch')
|
15 |
|
16 |
|
17 |
class ModelType(Enum):
|
@@ -55,14 +55,19 @@ class Model:
|
|
55 |
def inference_chunk(self, frame_ids, **kwargs):
|
56 |
if self.pipe is None:
|
57 |
return
|
58 |
-
|
59 |
prompt = np.array(kwargs.pop('prompt'))
|
60 |
negative_prompt = np.array(kwargs.pop('negative_prompt', ''))
|
61 |
latents = None
|
62 |
if 'latents' in kwargs:
|
63 |
latents = kwargs.pop('latents')[frame_ids]
|
64 |
-
|
65 |
-
|
|
|
|
|
|
|
|
|
|
|
66 |
negative_prompt=negative_prompt[frame_ids].tolist(),
|
67 |
latents=latents,
|
68 |
generator=self.generator,
|
@@ -72,15 +77,21 @@ class Model:
|
|
72 |
if self.pipe is None:
|
73 |
return
|
74 |
seed = kwargs.pop('seed', 0)
|
|
|
|
|
75 |
kwargs.pop('generator', '')
|
76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
if split_to_chunks:
|
78 |
-
assert 'image' in kwargs
|
79 |
-
assert 'prompt' in kwargs
|
80 |
-
image = kwargs.pop('image')
|
81 |
-
prompt = kwargs.pop('prompt')
|
82 |
-
negative_prompt = kwargs.pop('negative_prompt', '')
|
83 |
-
f = image.shape[0]
|
84 |
chunk_ids = np.arange(0, f, chunk_size - 1)
|
85 |
result = []
|
86 |
for i in range(len(chunk_ids)):
|
@@ -90,18 +101,19 @@ class Model:
|
|
90 |
self.generator.manual_seed(seed)
|
91 |
print(f'Processing chunk {i + 1} / {len(chunk_ids)}')
|
92 |
result.append(self.inference_chunk(frame_ids=frame_ids,
|
93 |
-
|
94 |
-
|
95 |
-
negative_prompt=[negative_prompt] * f,
|
96 |
**kwargs).images[1:])
|
97 |
result = np.concatenate(result)
|
98 |
return result
|
99 |
else:
|
100 |
-
return self.pipe(generator=self.generator, **kwargs).
|
101 |
|
102 |
def process_controlnet_canny(self,
|
103 |
video_path,
|
104 |
prompt,
|
|
|
|
|
105 |
num_inference_steps=20,
|
106 |
controlnet_conditioning_scale=1.0,
|
107 |
guidance_scale=9.0,
|
@@ -109,24 +121,32 @@ class Model:
|
|
109 |
eta=0.0,
|
110 |
low_threshold=100,
|
111 |
high_threshold=200,
|
112 |
-
resolution=512
|
|
|
|
|
113 |
video_path = gradio_utils.edge_path_to_video_path(video_path)
|
114 |
if self.model_type != ModelType.ControlNetCanny:
|
115 |
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny")
|
116 |
-
self.set_model(ModelType.ControlNetCanny,
|
117 |
-
self.pipe.scheduler = DDIMScheduler.from_config(
|
118 |
-
|
119 |
-
|
|
|
|
|
|
|
|
|
120 |
|
121 |
-
# TODO: Check scheduler
|
122 |
added_prompt = 'best quality, extremely detailed'
|
123 |
negative_prompts = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
124 |
|
125 |
-
video, fps = utils.prepare_video(
|
126 |
-
|
|
|
|
|
127 |
f, _, h, w = video.shape
|
128 |
self.generator.manual_seed(seed)
|
129 |
-
latents = torch.randn((1, 4, h//8, w//8), dtype=self.dtype,
|
|
|
130 |
latents = latents.repeat(f, 1, 1, 1)
|
131 |
result = self.inference(image=control,
|
132 |
prompt=prompt + ', ' + added_prompt,
|
@@ -141,35 +161,49 @@ class Model:
|
|
141 |
seed=seed,
|
142 |
output_type='numpy',
|
143 |
split_to_chunks=True,
|
144 |
-
chunk_size=
|
145 |
)
|
146 |
-
return utils.create_video(result, fps)
|
147 |
|
148 |
def process_controlnet_pose(self,
|
149 |
video_path,
|
150 |
prompt,
|
|
|
|
|
151 |
num_inference_steps=20,
|
152 |
controlnet_conditioning_scale=1.0,
|
153 |
guidance_scale=9.0,
|
154 |
seed=42,
|
155 |
eta=0.0,
|
156 |
-
resolution=512
|
|
|
|
|
157 |
video_path = gradio_utils.motion_to_video_path(video_path)
|
158 |
if self.model_type != ModelType.ControlNetPose:
|
159 |
controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-openpose")
|
160 |
self.set_model(ModelType.ControlNetPose, model_id="runwayml/stable-diffusion-v1-5", controlnet=controlnet)
|
161 |
-
self.pipe.scheduler = DDIMScheduler.from_config(
|
162 |
-
|
163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
164 |
|
165 |
added_prompt = 'best quality, extremely detailed, HD, ultra-realistic, 8K, HQ, masterpiece, trending on artstation, art, smooth'
|
166 |
negative_prompts = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer difits, cropped, worst quality, low quality, deformed body, bloated, ugly, unrealistic'
|
167 |
|
168 |
-
video, fps = utils.prepare_video(
|
169 |
-
|
|
|
|
|
170 |
f, _, h, w = video.shape
|
171 |
self.generator.manual_seed(seed)
|
172 |
-
latents = torch.randn((1, 4, h//8, w//8), dtype=self.dtype,
|
|
|
173 |
latents = latents.repeat(f, 1, 1, 1)
|
174 |
result = self.inference(image=control,
|
175 |
prompt=prompt + ', ' + added_prompt,
|
@@ -184,15 +218,16 @@ class Model:
|
|
184 |
seed=seed,
|
185 |
output_type='numpy',
|
186 |
split_to_chunks=True,
|
187 |
-
chunk_size=
|
188 |
)
|
189 |
-
return utils.create_gif(result, fps)
|
190 |
-
# return utils.create_video(result, fps)
|
191 |
|
192 |
def process_controlnet_canny_db(self,
|
193 |
db_path,
|
194 |
video_path,
|
195 |
prompt,
|
|
|
|
|
196 |
num_inference_steps=20,
|
197 |
controlnet_conditioning_scale=1.0,
|
198 |
guidance_scale=9.0,
|
@@ -200,26 +235,36 @@ class Model:
|
|
200 |
eta=0.0,
|
201 |
low_threshold=100,
|
202 |
high_threshold=200,
|
203 |
-
resolution=512
|
|
|
|
|
204 |
db_path = gradio_utils.get_model_from_db_selection(db_path)
|
205 |
video_path = gradio_utils.get_video_from_canny_selection(video_path)
|
206 |
# Load db and controlnet weights
|
207 |
if 'db_path' not in self.states or db_path != self.states['db_path']:
|
208 |
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny")
|
209 |
self.set_model(ModelType.ControlNetCannyDB, model_id=db_path, controlnet=controlnet)
|
210 |
-
self.pipe.scheduler = DDIMScheduler.from_config(
|
211 |
-
|
212 |
-
self.pipe.controlnet.set_attn_processor(processor=self.controlnet_attn_proc)
|
213 |
self.states['db_path'] = db_path
|
214 |
|
|
|
|
|
|
|
|
|
|
|
|
|
215 |
added_prompt = 'best quality, extremely detailed'
|
216 |
negative_prompts = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
217 |
|
218 |
-
video, fps = utils.prepare_video(
|
219 |
-
|
|
|
|
|
220 |
f, _, h, w = video.shape
|
221 |
self.generator.manual_seed(seed)
|
222 |
-
latents = torch.randn((1, 4, h//8, w//8), dtype=self.dtype,
|
|
|
223 |
latents = latents.repeat(f, 1, 1, 1)
|
224 |
result = self.inference(image=control,
|
225 |
prompt=prompt + ', ' + added_prompt,
|
@@ -234,57 +279,91 @@ class Model:
|
|
234 |
seed=seed,
|
235 |
output_type='numpy',
|
236 |
split_to_chunks=True,
|
237 |
-
chunk_size=
|
238 |
)
|
239 |
-
return utils.create_gif(result, fps)
|
240 |
|
241 |
-
def process_pix2pix(self,
|
242 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
243 |
if self.model_type != ModelType.Pix2Pix_Video:
|
244 |
-
self.set_model(ModelType.Pix2Pix_Video,
|
245 |
-
|
246 |
-
self.pipe.
|
247 |
-
|
|
|
|
|
|
|
|
|
|
|
248 |
self.generator.manual_seed(seed)
|
249 |
result = self.inference(image=video,
|
250 |
prompt=prompt,
|
251 |
seed=seed,
|
252 |
output_type='numpy',
|
253 |
num_inference_steps=50,
|
254 |
-
image_guidance_scale=
|
255 |
split_to_chunks=True,
|
256 |
-
chunk_size=
|
257 |
)
|
258 |
-
return utils.create_video(result, fps)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
259 |
|
260 |
-
def process_text2video(self, prompt, motion_field_strength_x=12,motion_field_strength_y=12, n_prompt="", resolution=512, seed=24, num_frames=8, fps=2, t0=881, t1=941,
|
261 |
-
use_cf_attn=True, use_motion_field=True,
|
262 |
-
smooth_bg=False, smooth_bg_strength=0.4 ):
|
263 |
-
|
264 |
if self.model_type != ModelType.Text2Video:
|
265 |
-
unet = UNet2DConditionModel.from_pretrained(
|
266 |
-
self.set_model(ModelType.Text2Video, model_id=
|
267 |
-
self.pipe.scheduler = DDIMScheduler.from_config(
|
|
|
268 |
if use_cf_attn:
|
269 |
-
self.pipe.unet.set_attn_processor(
|
|
|
270 |
self.generator.manual_seed(seed)
|
271 |
|
272 |
-
|
273 |
added_prompt = "high quality, HD, 8K, trending on artstation, high focus, dramatic lighting"
|
274 |
negative_prompts = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer difits, cropped, worst quality, low quality, deformed body, bloated, ugly, unrealistic'
|
275 |
|
276 |
prompt = prompt.rstrip()
|
277 |
-
if len(prompt) > 0 and (prompt[-1] == "," or prompt[-1]
|
278 |
prompt = prompt.rstrip()[:-1]
|
279 |
prompt = prompt.rstrip()
|
280 |
prompt = prompt + ", "+added_prompt
|
281 |
-
if len(n_prompt)>0:
|
282 |
-
negative_prompt =
|
283 |
else:
|
284 |
negative_prompt = None
|
285 |
|
286 |
-
result = self.inference(prompt=
|
287 |
-
video_length=
|
288 |
height=resolution,
|
289 |
width=resolution,
|
290 |
num_inference_steps=50,
|
@@ -299,6 +378,9 @@ class Model:
|
|
299 |
smooth_bg_strength=smooth_bg_strength,
|
300 |
seed=seed,
|
301 |
output_type='numpy',
|
302 |
-
negative_prompt
|
|
|
|
|
|
|
303 |
)
|
304 |
-
return utils.create_video(result, fps)
|
|
|
11 |
import utils
|
12 |
import gradio_utils
|
13 |
|
14 |
+
# decord.bridge.set_bridge('torch')
|
15 |
|
16 |
|
17 |
class ModelType(Enum):
|
|
|
55 |
def inference_chunk(self, frame_ids, **kwargs):
|
56 |
if self.pipe is None:
|
57 |
return
|
58 |
+
|
59 |
prompt = np.array(kwargs.pop('prompt'))
|
60 |
negative_prompt = np.array(kwargs.pop('negative_prompt', ''))
|
61 |
latents = None
|
62 |
if 'latents' in kwargs:
|
63 |
latents = kwargs.pop('latents')[frame_ids]
|
64 |
+
if 'image' in kwargs:
|
65 |
+
kwargs['image'] = kwargs['image'][frame_ids]
|
66 |
+
if 'video_length' in kwargs:
|
67 |
+
kwargs['video_length'] = len(frame_ids)
|
68 |
+
if self.model_type == ModelType.Text2Video:
|
69 |
+
kwargs["frame_ids"] = frame_ids
|
70 |
+
return self.pipe(prompt=prompt[frame_ids].tolist(),
|
71 |
negative_prompt=negative_prompt[frame_ids].tolist(),
|
72 |
latents=latents,
|
73 |
generator=self.generator,
|
|
|
77 |
if self.pipe is None:
|
78 |
return
|
79 |
seed = kwargs.pop('seed', 0)
|
80 |
+
if seed < 0:
|
81 |
+
seed = self.generator.seed()
|
82 |
kwargs.pop('generator', '')
|
83 |
+
|
84 |
+
if 'image' in kwargs:
|
85 |
+
f = kwargs['image'].shape[0]
|
86 |
+
else:
|
87 |
+
f = kwargs['video_length']
|
88 |
+
|
89 |
+
assert 'prompt' in kwargs
|
90 |
+
prompt = [kwargs.pop('prompt')] * f
|
91 |
+
negative_prompt = [kwargs.pop('negative_prompt', '')] * f
|
92 |
+
|
93 |
+
# Processing chunk-by-chunk
|
94 |
if split_to_chunks:
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
chunk_ids = np.arange(0, f, chunk_size - 1)
|
96 |
result = []
|
97 |
for i in range(len(chunk_ids)):
|
|
|
101 |
self.generator.manual_seed(seed)
|
102 |
print(f'Processing chunk {i + 1} / {len(chunk_ids)}')
|
103 |
result.append(self.inference_chunk(frame_ids=frame_ids,
|
104 |
+
prompt=prompt,
|
105 |
+
negative_prompt=negative_prompt,
|
|
|
106 |
**kwargs).images[1:])
|
107 |
result = np.concatenate(result)
|
108 |
return result
|
109 |
else:
|
110 |
+
return self.pipe(prompt=prompt, negative_prompt=negative_prompt, generator=self.generator, **kwargs).images
|
111 |
|
112 |
def process_controlnet_canny(self,
|
113 |
video_path,
|
114 |
prompt,
|
115 |
+
chunk_size=8,
|
116 |
+
watermark=None,
|
117 |
num_inference_steps=20,
|
118 |
controlnet_conditioning_scale=1.0,
|
119 |
guidance_scale=9.0,
|
|
|
121 |
eta=0.0,
|
122 |
low_threshold=100,
|
123 |
high_threshold=200,
|
124 |
+
resolution=512,
|
125 |
+
use_cf_attn=True,
|
126 |
+
save_path=None):
|
127 |
video_path = gradio_utils.edge_path_to_video_path(video_path)
|
128 |
if self.model_type != ModelType.ControlNetCanny:
|
129 |
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny")
|
130 |
+
self.set_model(ModelType.ControlNetCanny,model_id="runwayml/stable-diffusion-v1-5", controlnet=controlnet)
|
131 |
+
self.pipe.scheduler = DDIMScheduler.from_config(
|
132 |
+
self.pipe.scheduler.config)
|
133 |
+
if use_cf_attn:
|
134 |
+
self.pipe.unet.set_attn_processor(
|
135 |
+
processor=self.controlnet_attn_proc)
|
136 |
+
self.pipe.controlnet.set_attn_processor(
|
137 |
+
processor=self.controlnet_attn_proc)
|
138 |
|
|
|
139 |
added_prompt = 'best quality, extremely detailed'
|
140 |
negative_prompts = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
141 |
|
142 |
+
video, fps = utils.prepare_video(
|
143 |
+
video_path, resolution, self.device, self.dtype, False)
|
144 |
+
control = utils.pre_process_canny(
|
145 |
+
video, low_threshold, high_threshold).to(self.device).to(self.dtype)
|
146 |
f, _, h, w = video.shape
|
147 |
self.generator.manual_seed(seed)
|
148 |
+
latents = torch.randn((1, 4, h//8, w//8), dtype=self.dtype,
|
149 |
+
device=self.device, generator=self.generator)
|
150 |
latents = latents.repeat(f, 1, 1, 1)
|
151 |
result = self.inference(image=control,
|
152 |
prompt=prompt + ', ' + added_prompt,
|
|
|
161 |
seed=seed,
|
162 |
output_type='numpy',
|
163 |
split_to_chunks=True,
|
164 |
+
chunk_size=chunk_size,
|
165 |
)
|
166 |
+
return utils.create_video(result, fps, path=save_path, watermark=gradio_utils.logo_name_to_path(watermark))
|
167 |
|
168 |
def process_controlnet_pose(self,
|
169 |
video_path,
|
170 |
prompt,
|
171 |
+
chunk_size=8,
|
172 |
+
watermark=None,
|
173 |
num_inference_steps=20,
|
174 |
controlnet_conditioning_scale=1.0,
|
175 |
guidance_scale=9.0,
|
176 |
seed=42,
|
177 |
eta=0.0,
|
178 |
+
resolution=512,
|
179 |
+
use_cf_attn=True,
|
180 |
+
save_path=None):
|
181 |
video_path = gradio_utils.motion_to_video_path(video_path)
|
182 |
if self.model_type != ModelType.ControlNetPose:
|
183 |
controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-openpose")
|
184 |
self.set_model(ModelType.ControlNetPose, model_id="runwayml/stable-diffusion-v1-5", controlnet=controlnet)
|
185 |
+
self.pipe.scheduler = DDIMScheduler.from_config(
|
186 |
+
self.pipe.scheduler.config)
|
187 |
+
if use_cf_attn:
|
188 |
+
self.pipe.unet.set_attn_processor(
|
189 |
+
processor=self.controlnet_attn_proc)
|
190 |
+
self.pipe.controlnet.set_attn_processor(
|
191 |
+
processor=self.controlnet_attn_proc)
|
192 |
+
|
193 |
+
video_path = gradio_utils.motion_to_video_path(
|
194 |
+
video_path) if 'Motion' in video_path else video_path
|
195 |
|
196 |
added_prompt = 'best quality, extremely detailed, HD, ultra-realistic, 8K, HQ, masterpiece, trending on artstation, art, smooth'
|
197 |
negative_prompts = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer difits, cropped, worst quality, low quality, deformed body, bloated, ugly, unrealistic'
|
198 |
|
199 |
+
video, fps = utils.prepare_video(
|
200 |
+
video_path, resolution, self.device, self.dtype, False, output_fps=4)
|
201 |
+
control = utils.pre_process_pose(
|
202 |
+
video, apply_pose_detect=False).to(self.device).to(self.dtype)
|
203 |
f, _, h, w = video.shape
|
204 |
self.generator.manual_seed(seed)
|
205 |
+
latents = torch.randn((1, 4, h//8, w//8), dtype=self.dtype,
|
206 |
+
device=self.device, generator=self.generator)
|
207 |
latents = latents.repeat(f, 1, 1, 1)
|
208 |
result = self.inference(image=control,
|
209 |
prompt=prompt + ', ' + added_prompt,
|
|
|
218 |
seed=seed,
|
219 |
output_type='numpy',
|
220 |
split_to_chunks=True,
|
221 |
+
chunk_size=chunk_size,
|
222 |
)
|
223 |
+
return utils.create_gif(result, fps, path=save_path, watermark=gradio_utils.logo_name_to_path(watermark))
|
|
|
224 |
|
225 |
def process_controlnet_canny_db(self,
|
226 |
db_path,
|
227 |
video_path,
|
228 |
prompt,
|
229 |
+
chunk_size=8,
|
230 |
+
watermark=None,
|
231 |
num_inference_steps=20,
|
232 |
controlnet_conditioning_scale=1.0,
|
233 |
guidance_scale=9.0,
|
|
|
235 |
eta=0.0,
|
236 |
low_threshold=100,
|
237 |
high_threshold=200,
|
238 |
+
resolution=512,
|
239 |
+
use_cf_attn=True,
|
240 |
+
save_path=None):
|
241 |
db_path = gradio_utils.get_model_from_db_selection(db_path)
|
242 |
video_path = gradio_utils.get_video_from_canny_selection(video_path)
|
243 |
# Load db and controlnet weights
|
244 |
if 'db_path' not in self.states or db_path != self.states['db_path']:
|
245 |
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny")
|
246 |
self.set_model(ModelType.ControlNetCannyDB, model_id=db_path, controlnet=controlnet)
|
247 |
+
self.pipe.scheduler = DDIMScheduler.from_config(
|
248 |
+
self.pipe.scheduler.config)
|
|
|
249 |
self.states['db_path'] = db_path
|
250 |
|
251 |
+
if use_cf_attn:
|
252 |
+
self.pipe.unet.set_attn_processor(
|
253 |
+
processor=self.controlnet_attn_proc)
|
254 |
+
self.pipe.controlnet.set_attn_processor(
|
255 |
+
processor=self.controlnet_attn_proc)
|
256 |
+
|
257 |
added_prompt = 'best quality, extremely detailed'
|
258 |
negative_prompts = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
|
259 |
|
260 |
+
video, fps = utils.prepare_video(
|
261 |
+
video_path, resolution, self.device, self.dtype, False)
|
262 |
+
control = utils.pre_process_canny(
|
263 |
+
video, low_threshold, high_threshold).to(self.device).to(self.dtype)
|
264 |
f, _, h, w = video.shape
|
265 |
self.generator.manual_seed(seed)
|
266 |
+
latents = torch.randn((1, 4, h//8, w//8), dtype=self.dtype,
|
267 |
+
device=self.device, generator=self.generator)
|
268 |
latents = latents.repeat(f, 1, 1, 1)
|
269 |
result = self.inference(image=control,
|
270 |
prompt=prompt + ', ' + added_prompt,
|
|
|
279 |
seed=seed,
|
280 |
output_type='numpy',
|
281 |
split_to_chunks=True,
|
282 |
+
chunk_size=chunk_size,
|
283 |
)
|
284 |
+
return utils.create_gif(result, fps, path=save_path, watermark=gradio_utils.logo_name_to_path(watermark))
|
285 |
|
286 |
+
def process_pix2pix(self,
|
287 |
+
video,
|
288 |
+
prompt,
|
289 |
+
resolution=512,
|
290 |
+
seed=0,
|
291 |
+
image_guidance_scale=1.0,
|
292 |
+
start_t=0,
|
293 |
+
end_t=-1,
|
294 |
+
out_fps=-1,
|
295 |
+
chunk_size=8,
|
296 |
+
watermark=None,
|
297 |
+
use_cf_attn=True,
|
298 |
+
save_path=None,):
|
299 |
if self.model_type != ModelType.Pix2Pix_Video:
|
300 |
+
self.set_model(ModelType.Pix2Pix_Video,
|
301 |
+
model_id="timbrooks/instruct-pix2pix")
|
302 |
+
self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(
|
303 |
+
self.pipe.scheduler.config)
|
304 |
+
if use_cf_attn:
|
305 |
+
self.pipe.unet.set_attn_processor(
|
306 |
+
processor=self.pix2pix_attn_proc)
|
307 |
+
video, fps = utils.prepare_video(
|
308 |
+
video, resolution, self.device, self.dtype, True, start_t, end_t, out_fps)
|
309 |
self.generator.manual_seed(seed)
|
310 |
result = self.inference(image=video,
|
311 |
prompt=prompt,
|
312 |
seed=seed,
|
313 |
output_type='numpy',
|
314 |
num_inference_steps=50,
|
315 |
+
image_guidance_scale=image_guidance_scale,
|
316 |
split_to_chunks=True,
|
317 |
+
chunk_size=chunk_size,
|
318 |
)
|
319 |
+
return utils.create_video(result, fps, path=save_path, watermark=gradio_utils.logo_name_to_path(watermark))
|
320 |
+
|
321 |
+
def process_text2video(self,
|
322 |
+
prompt,
|
323 |
+
model_name,
|
324 |
+
motion_field_strength_x=12,
|
325 |
+
motion_field_strength_y=12,
|
326 |
+
t0=44,
|
327 |
+
t1=47,
|
328 |
+
n_prompt="",
|
329 |
+
chunk_size=8,
|
330 |
+
video_length=8,
|
331 |
+
watermark=None,
|
332 |
+
inject_noise_to_warp=False,
|
333 |
+
resolution=512,
|
334 |
+
seed=-1,
|
335 |
+
fps=2,
|
336 |
+
use_cf_attn=True,
|
337 |
+
use_motion_field=True,
|
338 |
+
smooth_bg=False,
|
339 |
+
smooth_bg_strength=0.4,
|
340 |
+
path=None):
|
341 |
|
|
|
|
|
|
|
|
|
342 |
if self.model_type != ModelType.Text2Video:
|
343 |
+
unet = UNet2DConditionModel.from_pretrained(model_name, subfolder="unet")
|
344 |
+
self.set_model(ModelType.Text2Video, model_id=model_name, unet=unet)
|
345 |
+
self.pipe.scheduler = DDIMScheduler.from_config(
|
346 |
+
self.pipe.scheduler.config)
|
347 |
if use_cf_attn:
|
348 |
+
self.pipe.unet.set_attn_processor(
|
349 |
+
processor=self.text2video_attn_proc)
|
350 |
self.generator.manual_seed(seed)
|
351 |
|
|
|
352 |
added_prompt = "high quality, HD, 8K, trending on artstation, high focus, dramatic lighting"
|
353 |
negative_prompts = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer difits, cropped, worst quality, low quality, deformed body, bloated, ugly, unrealistic'
|
354 |
|
355 |
prompt = prompt.rstrip()
|
356 |
+
if len(prompt) > 0 and (prompt[-1] == "," or prompt[-1] == "."):
|
357 |
prompt = prompt.rstrip()[:-1]
|
358 |
prompt = prompt.rstrip()
|
359 |
prompt = prompt + ", "+added_prompt
|
360 |
+
if len(n_prompt) > 0:
|
361 |
+
negative_prompt = n_prompt
|
362 |
else:
|
363 |
negative_prompt = None
|
364 |
|
365 |
+
result = self.inference(prompt=prompt,
|
366 |
+
video_length=video_length,
|
367 |
height=resolution,
|
368 |
width=resolution,
|
369 |
num_inference_steps=50,
|
|
|
378 |
smooth_bg_strength=smooth_bg_strength,
|
379 |
seed=seed,
|
380 |
output_type='numpy',
|
381 |
+
negative_prompt=negative_prompt,
|
382 |
+
inject_noise_to_warp=inject_noise_to_warp,
|
383 |
+
split_to_chunks=True,
|
384 |
+
chunk_size=chunk_size,
|
385 |
)
|
386 |
+
return utils.create_video(result, fps, path=path, watermark=gradio_utils.logo_name_to_path(watermark))
|
text_to_video/text_to_video_generator.py
DELETED
@@ -1,79 +0,0 @@
|
|
1 |
-
from text_to_video.tuneavideo.pipelines.pipeline_text_to_video import TuneAVideoPipeline
|
2 |
-
from text_to_video.tuneavideo.models.unet import UNet3DConditionModel
|
3 |
-
import torch
|
4 |
-
from diffusers import AutoencoderKL, DDIMScheduler
|
5 |
-
from transformers import CLIPTextModel, CLIPTokenizer
|
6 |
-
|
7 |
-
|
8 |
-
class TextToVideo():
|
9 |
-
|
10 |
-
|
11 |
-
def __init__(self,sd_path = None,motion_field_strength = 12, video_length = 8,t0 = 881, t1=941,use_cf_attn=True,use_motion_field=True) -> None:
|
12 |
-
g = torch.Generator(device='cuda')
|
13 |
-
g.manual_seed(22)
|
14 |
-
self.g = g
|
15 |
-
|
16 |
-
assert sd_path is not None
|
17 |
-
|
18 |
-
print(f"Loading model SD-Net model file from {sd_path}")
|
19 |
-
|
20 |
-
self.dtype = torch.float16
|
21 |
-
noise_scheduler = DDIMScheduler.from_pretrained(
|
22 |
-
sd_path, subfolder="scheduler")
|
23 |
-
tokenizer = CLIPTokenizer.from_pretrained(
|
24 |
-
sd_path, subfolder="tokenizer")
|
25 |
-
text_encoder = CLIPTextModel.from_pretrained(
|
26 |
-
sd_path, subfolder="text_encoder")
|
27 |
-
vae = AutoencoderKL.from_pretrained(sd_path, subfolder="vae")
|
28 |
-
|
29 |
-
|
30 |
-
unet = UNet3DConditionModel.from_pretrained_2d(
|
31 |
-
sd_path, subfolder="unet", use_cf_attn=use_cf_attn)
|
32 |
-
self.pipe = TuneAVideoPipeline(
|
33 |
-
vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet,
|
34 |
-
scheduler=DDIMScheduler.from_pretrained(
|
35 |
-
sd_path, subfolder="scheduler")
|
36 |
-
).to('cuda').to(self.dtype)
|
37 |
-
|
38 |
-
noise_scheduler.set_timesteps(50, device='cuda')
|
39 |
-
|
40 |
-
# t0 parameter (DDIM backward from noise until t0)
|
41 |
-
self.t0 = t0
|
42 |
-
|
43 |
-
|
44 |
-
# from t0 apply DDPM forward until t1
|
45 |
-
self.t1 = t1
|
46 |
-
|
47 |
-
self.use_foreground_motion_field = False # apply motion field on forground object (not used)
|
48 |
-
|
49 |
-
# strength of motion field (delta_x = delta_y in Sect 3.3.1)
|
50 |
-
self.motion_field_strength = motion_field_strength
|
51 |
-
self.use_motion_field = use_motion_field # apply general motion field
|
52 |
-
self.smooth_bg = False # temporally smooth background
|
53 |
-
self.smooth_bg_strength = 0.4 # alpha = (1-self.smooth_bg_strength) in Eq (9)
|
54 |
-
|
55 |
-
|
56 |
-
self.video_length = video_length
|
57 |
-
|
58 |
-
def inference(self, prompt):
|
59 |
-
|
60 |
-
prompt_compute = [prompt]
|
61 |
-
xT = torch.randn((1, 4, 1, 64, 64), dtype=self.dtype, device="cuda")
|
62 |
-
result = self.pipe(prompt_compute,
|
63 |
-
video_length=self.video_length,
|
64 |
-
height=512,
|
65 |
-
width=512,
|
66 |
-
num_inference_steps=50,
|
67 |
-
guidance_scale=7.5,
|
68 |
-
guidance_stop_step=1.0,
|
69 |
-
t0=self.t0,
|
70 |
-
t1=self.t1,
|
71 |
-
xT=xT,
|
72 |
-
use_foreground_motion_field=self.use_foreground_motion_field,
|
73 |
-
motion_field_strength=self.motion_field_strength,
|
74 |
-
use_motion_field=self.use_motion_field,
|
75 |
-
smooth_bg=self.smooth_bg,
|
76 |
-
smooth_bg_strength=self.smooth_bg_strength,
|
77 |
-
generator=self.g)
|
78 |
-
|
79 |
-
return result.videos[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
text_to_video/text_to_video_pipeline.py
CHANGED
@@ -11,22 +11,27 @@ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
|
|
11 |
from diffusers.models import AutoencoderKL, UNet2DConditionModel
|
12 |
from diffusers.schedulers import KarrasDiffusionSchedulers
|
13 |
from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
|
|
|
|
|
|
|
|
|
14 |
|
15 |
@dataclass
|
16 |
class TextToVideoPipelineOutput(BaseOutput):
|
17 |
-
videos: Union[torch.Tensor, np.ndarray]
|
18 |
-
code: Union[torch.Tensor, np.ndarray]
|
19 |
-
|
|
|
20 |
|
21 |
|
22 |
def coords_grid(batch, ht, wd, device):
|
23 |
# Adapted from https://github.com/princeton-vl/RAFT/blob/master/core/utils/utils.py
|
24 |
-
coords = torch.meshgrid(torch.arange(
|
|
|
25 |
coords = torch.stack(coords[::-1], dim=0).float()
|
26 |
return coords[None].repeat(batch, 1, 1, 1)
|
27 |
|
28 |
|
29 |
-
|
30 |
class TextToVideoPipeline(StableDiffusionPipeline):
|
31 |
def __init__(
|
32 |
self,
|
@@ -38,14 +43,13 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
38 |
safety_checker: StableDiffusionSafetyChecker,
|
39 |
feature_extractor: CLIPFeatureExtractor,
|
40 |
requires_safety_checker: bool = True,
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
|
46 |
def DDPM_forward(self, x0, t0, tMax, generator, device, shape, text_embeddings):
|
47 |
rand_device = "cpu" if device.type == "mps" else device
|
48 |
-
|
49 |
if x0 is None:
|
50 |
return torch.randn(shape, generator=generator, device=rand_device, dtype=text_embeddings.dtype).to(device)
|
51 |
else:
|
@@ -55,7 +59,6 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
55 |
torch.sqrt(1-alpha_vec) * eps
|
56 |
return xt
|
57 |
|
58 |
-
|
59 |
def prepare_latents(self, batch_size, num_channels_latents, video_length, height, width, dtype, device, generator, latents=None):
|
60 |
shape = (batch_size, num_channels_latents, video_length, height //
|
61 |
self.vae_scale_factor, width // self.vae_scale_factor)
|
@@ -86,9 +89,7 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
86 |
latents = latents * self.scheduler.init_noise_sigma
|
87 |
return latents
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
def warp_latents(self, latents, reference_flow):
|
92 |
_, _, H, W = reference_flow.size()
|
93 |
b, c, f, h, w = latents.size()
|
94 |
coords0 = coords_grid(f, H, W, device=latents.device).to(latents.dtype)
|
@@ -101,19 +102,20 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
101 |
latents_0 = latents[:, :, 0]
|
102 |
latents_0 = latents_0.repeat(f, 1, 1, 1)
|
103 |
warped = grid_sample(latents_0, coords_t0,
|
104 |
-
|
105 |
warped = rearrange(warped, '(b f) c h w -> b c f h w', f=f)
|
106 |
return warped
|
107 |
|
108 |
-
def warp_latents_independently(self, latents, reference_flow):
|
109 |
_, _, H, W = reference_flow.size()
|
110 |
-
b,
|
111 |
assert b == 1
|
112 |
coords0 = coords_grid(f, H, W, device=latents.device).to(latents.dtype)
|
113 |
-
coords_t0 = coords0 + reference_flow
|
114 |
|
|
|
115 |
coords_t0[:, 0] /= W
|
116 |
coords_t0[:, 1] /= H
|
|
|
117 |
coords_t0 = coords_t0 * 2.0 - 1.0
|
118 |
|
119 |
coords_t0 = T.Resize((h, w))(coords_t0)
|
@@ -121,23 +123,32 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
121 |
coords_t0 = rearrange(coords_t0, 'f c h w -> f h w c')
|
122 |
|
123 |
latents_0 = rearrange(latents[0], 'c f h w -> f c h w')
|
124 |
-
|
125 |
warped = grid_sample(latents_0, coords_t0,
|
126 |
mode='nearest', padding_mode='reflection')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
warped = rearrange(warped, '(b f) c h w -> b c f h w', f=f)
|
128 |
return warped
|
129 |
|
130 |
-
def DDIM_backward(self, num_inference_steps, timesteps, skip_t, t0, t1, do_classifier_free_guidance, null_embs, text_embeddings, latents_local,
|
|
|
131 |
entered = False
|
132 |
-
|
133 |
f = latents_local.shape[2]
|
134 |
-
|
135 |
-
|
|
|
136 |
latents = latents_local.detach().clone()
|
137 |
x_t0_1 = None
|
138 |
x_t1_1 = None
|
139 |
-
|
140 |
-
|
141 |
|
142 |
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
143 |
for i, t in enumerate(timesteps):
|
@@ -160,7 +171,8 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
160 |
with torch.no_grad():
|
161 |
if null_embs is not None:
|
162 |
text_embeddings[0] = null_embs[i][0]
|
163 |
-
te = torch.cat([repeat(text_embeddings[0
|
|
|
164 |
noise_pred = self.unet(
|
165 |
latent_model_input, t, encoder_hidden_states=te).sample.to(dtype=latents_dtype)
|
166 |
|
@@ -191,17 +203,14 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
191 |
if callback is not None and i % callback_steps == 0:
|
192 |
callback(i, t, latents)
|
193 |
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
res = {"x0": latents.detach().clone()}
|
200 |
if x_t0_1 is not None:
|
201 |
-
x_t0_1 = rearrange(x_t0_1,"(b f) c w h -> b c f w h",f
|
202 |
res["x_t0_1"] = x_t0_1.detach().clone()
|
203 |
if x_t1_1 is not None:
|
204 |
-
x_t1_1 = rearrange(x_t1_1,"(b f) c w h -> b c f w h",f
|
205 |
res["x_t1_1"] = x_t1_1.detach().clone()
|
206 |
return res
|
207 |
|
@@ -213,9 +222,28 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
213 |
video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length)
|
214 |
video = (video / 2 + 0.5).clamp(0, 1)
|
215 |
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
|
|
|
216 |
return video
|
217 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
218 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
219 |
|
220 |
@torch.no_grad()
|
221 |
def __call__(
|
@@ -234,22 +262,46 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
234 |
List[torch.Generator]]] = None,
|
235 |
xT: Optional[torch.FloatTensor] = None,
|
236 |
null_embs: Optional[torch.FloatTensor] = None,
|
237 |
-
#motion_field_strength: float = 12,
|
238 |
motion_field_strength_x: float = 12,
|
239 |
-
motion_field_strength_y: float = 12,
|
240 |
output_type: Optional[str] = "tensor",
|
241 |
return_dict: bool = True,
|
242 |
callback: Optional[Callable[[
|
243 |
int, int, torch.FloatTensor], None]] = None,
|
244 |
callback_steps: Optional[int] = 1,
|
245 |
use_motion_field: bool = True,
|
246 |
-
smooth_bg: bool =
|
247 |
smooth_bg_strength: float = 0.4,
|
|
|
|
|
|
|
248 |
**kwargs,
|
249 |
):
|
250 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
251 |
print(f" Use: Motion field = {use_motion_field}")
|
252 |
print(f" Use: Background smoothing = {smooth_bg}")
|
|
|
253 |
# Default height and width to unet
|
254 |
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
255 |
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
@@ -269,11 +321,11 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
269 |
text_embeddings = self._encode_prompt(
|
270 |
prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt
|
271 |
)
|
272 |
-
|
273 |
# Prepare timesteps
|
274 |
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
275 |
timesteps = self.scheduler.timesteps
|
276 |
-
|
277 |
# print(f" Latent shape = {latents.shape}")
|
278 |
|
279 |
# Prepare latent variables
|
@@ -282,7 +334,7 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
282 |
xT = self.prepare_latents(
|
283 |
batch_size * num_videos_per_prompt,
|
284 |
num_channels_latents,
|
285 |
-
|
286 |
height,
|
287 |
width,
|
288 |
text_embeddings.dtype,
|
@@ -309,27 +361,43 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
309 |
None,
|
310 |
)
|
311 |
xT = torch.cat([xT, xT_missing], dim=2)
|
312 |
-
|
313 |
|
314 |
xInit = xT.clone()
|
315 |
-
|
316 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
317 |
x_t1_1 = None
|
318 |
|
319 |
-
|
320 |
# Prepare extra step kwargs.
|
321 |
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
322 |
# Denoising loop
|
323 |
num_warmup_steps = len(timesteps) - \
|
324 |
num_inference_steps * self.scheduler.order
|
325 |
-
|
326 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
327 |
|
328 |
ddim_res = self.DDIM_backward(num_inference_steps=num_inference_steps, timesteps=timesteps, skip_t=1000, t0=t0, t1=t1, do_classifier_free_guidance=do_classifier_free_guidance,
|
329 |
-
|
330 |
-
|
|
|
331 |
x0 = ddim_res["x0"].detach()
|
332 |
-
|
333 |
if "x_t0_1" in ddim_res:
|
334 |
x_t0_1 = ddim_res["x_t0_1"].detach()
|
335 |
if "x_t1_1" in ddim_res:
|
@@ -337,25 +405,36 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
337 |
del ddim_res
|
338 |
del xT
|
339 |
|
340 |
-
if use_motion_field:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
341 |
del x0
|
342 |
-
shape = (batch_size, num_channels_latents, 1, height //
|
343 |
-
self.vae_scale_factor, width // self.vae_scale_factor)
|
344 |
-
|
345 |
-
|
346 |
-
x_t0_k = x_t0_1[:, :, :1, :, :].repeat(1, 1, video_length-1, 1, 1)
|
347 |
|
348 |
-
|
349 |
-
reference_flow = torch.zeros(
|
350 |
-
(video_length-1, 2, 512, 512), device=x_t0_1.device, dtype=x_t0_1.dtype)
|
351 |
-
for fr_idx in range(video_length-1):
|
352 |
-
#reference_flow[fr_idx, :, :, :] = motion_field_strength*(fr_idx+1)
|
353 |
-
reference_flow[fr_idx, 0, :, :] = motion_field_strength_x*(fr_idx+1)
|
354 |
-
reference_flow[fr_idx, 1, :, :] = motion_field_strength_y*(fr_idx+1)
|
355 |
|
356 |
-
|
357 |
-
x_t0_k
|
358 |
-
|
359 |
|
360 |
# assuming t0=t1=1000, if t0 = 1000
|
361 |
if t1 > t0:
|
@@ -370,16 +449,21 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
370 |
x_t1 = torch.cat([x_t1_1, x_t1_k], dim=2).clone().detach()
|
371 |
|
372 |
ddim_res = self.DDIM_backward(num_inference_steps=num_inference_steps, timesteps=timesteps, skip_t=t1, t0=-1, t1=-1, do_classifier_free_guidance=do_classifier_free_guidance,
|
373 |
-
null_embs=null_embs, text_embeddings=text_embeddings, latents_local=x_t1, latents_dtype=dtype, guidance_scale=guidance_scale,
|
|
|
374 |
|
375 |
x0 = ddim_res["x0"].detach()
|
376 |
del ddim_res
|
|
|
|
|
|
|
|
|
377 |
else:
|
378 |
x_t1 = x_t1_1.clone()
|
379 |
-
x_t1_1 = x_t1_1[
|
380 |
-
x_t1_k = x_t1_1[
|
381 |
x_t0_k = x_t0_1[:, :, 1:, :, :].clone()
|
382 |
-
x_t0_1 = x_t0_1[
|
383 |
|
384 |
# smooth background
|
385 |
if smooth_bg:
|
@@ -401,12 +485,10 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
401 |
mask = dilation(mask[None].to(x0.device), kernel)[0]
|
402 |
M_FG[batch_idx, frame_idx, :, :] = mask
|
403 |
|
404 |
-
|
405 |
x_t1_1_fg_masked = x_t1_1 * \
|
406 |
(1 - repeat(M_FG[:, 0, :, :],
|
407 |
"b w h -> b c 1 w h", c=x_t1_1.shape[1]))
|
408 |
|
409 |
-
|
410 |
x_t1_1_fg_masked_moved = []
|
411 |
for batch_idx, x_t1_1_fg_masked_b in enumerate(x_t1_1_fg_masked):
|
412 |
x_t1_fg_masked_b = x_t1_1_fg_masked_b.clone()
|
@@ -416,7 +498,7 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
416 |
if use_motion_field:
|
417 |
x_t1_fg_masked_b = x_t1_fg_masked_b[None]
|
418 |
x_t1_fg_masked_b = self.warp_latents_independently(
|
419 |
-
x_t1_fg_masked_b, reference_flow)
|
420 |
else:
|
421 |
x_t1_fg_masked_b = x_t1_fg_masked_b[None]
|
422 |
|
@@ -432,9 +514,9 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
432 |
for batch_idx, m_fg_1_b in enumerate(M_FG_1):
|
433 |
m_fg_1_b = m_fg_1_b[None, None]
|
434 |
m_fg_b = m_fg_1_b.repeat(1, 1, video_length-1, 1, 1)
|
435 |
-
if
|
436 |
m_fg_b = self.warp_latents_independently(
|
437 |
-
m_fg_b.clone(), reference_flow)
|
438 |
M_FG_warped.append(
|
439 |
torch.cat([m_fg_1_b[:1, 0], m_fg_b[:1, 0]], dim=1))
|
440 |
|
@@ -445,45 +527,40 @@ class TextToVideoPipeline(StableDiffusionPipeline):
|
|
445 |
M_BG = (1-M_FG) * (1 - M_FG_warped)
|
446 |
M_BG = repeat(M_BG, "b f h w -> b c f h w", c=channels)
|
447 |
a_convex = smooth_bg_strength
|
448 |
-
|
449 |
-
x_t1_blending = (1-M_BG) * x_t1 + M_BG * (a_convex *
|
450 |
-
x_t1 + (1-a_convex) * x_t1_1_fg_masked_moved)
|
451 |
|
452 |
-
|
453 |
-
|
454 |
-
x0=x_t1_blending, t0=t1, tMax=961, device=device, shape=shape, text_embeddings=text_embeddings, generator=generator)
|
455 |
-
t1 = 961
|
456 |
-
'''
|
457 |
-
latents = x_t1_blending
|
458 |
|
459 |
ddim_res = self.DDIM_backward(num_inference_steps=num_inference_steps, timesteps=timesteps, skip_t=t1, t0=-1, t1=-1, do_classifier_free_guidance=do_classifier_free_guidance,
|
460 |
-
null_embs=null_embs, text_embeddings=text_embeddings, latents_local=latents, latents_dtype=dtype, guidance_scale=guidance_scale,
|
|
|
461 |
x0 = ddim_res["x0"].detach()
|
462 |
del ddim_res
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
463 |
|
|
|
|
|
|
|
464 |
|
465 |
-
# Post-processing
|
466 |
-
video_list = []
|
467 |
-
for latent in x0:
|
468 |
-
tmp = latent[None]
|
469 |
-
print("Frame spit shape", tmp.shape)
|
470 |
-
frames = []
|
471 |
-
for fr_split in range(tmp.shape[2]):
|
472 |
-
print("frame decoding")
|
473 |
-
frames.append(self.decode_latents(
|
474 |
-
tmp[:, :, fr_split, None]).detach())
|
475 |
-
|
476 |
-
video_list.append(torch.cat(frames, dim=2).cpu().float().numpy())
|
477 |
-
|
478 |
-
# Convert to tensor
|
479 |
-
videos = []
|
480 |
-
if output_type == "tensor":
|
481 |
-
for video in video_list:
|
482 |
-
videos.append(torch.from_numpy(video))
|
483 |
-
if output_type == 'numpy':
|
484 |
-
for video in video_list:
|
485 |
-
videos.append(rearrange(video, 'b c f h w -> (b f) h w c'))
|
486 |
if not return_dict:
|
487 |
-
return
|
488 |
|
489 |
-
return TextToVideoPipelineOutput(
|
|
|
11 |
from diffusers.models import AutoencoderKL, UNet2DConditionModel
|
12 |
from diffusers.schedulers import KarrasDiffusionSchedulers
|
13 |
from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
|
14 |
+
import PIL
|
15 |
+
from PIL import Image
|
16 |
+
from kornia.morphology import dilation
|
17 |
+
|
18 |
|
19 |
@dataclass
|
20 |
class TextToVideoPipelineOutput(BaseOutput):
|
21 |
+
# videos: Union[torch.Tensor, np.ndarray]
|
22 |
+
# code: Union[torch.Tensor, np.ndarray]
|
23 |
+
images: Union[List[PIL.Image.Image], np.ndarray]
|
24 |
+
nsfw_content_detected: Optional[List[bool]]
|
25 |
|
26 |
|
27 |
def coords_grid(batch, ht, wd, device):
|
28 |
# Adapted from https://github.com/princeton-vl/RAFT/blob/master/core/utils/utils.py
|
29 |
+
coords = torch.meshgrid(torch.arange(
|
30 |
+
ht, device=device), torch.arange(wd, device=device))
|
31 |
coords = torch.stack(coords[::-1], dim=0).float()
|
32 |
return coords[None].repeat(batch, 1, 1, 1)
|
33 |
|
34 |
|
|
|
35 |
class TextToVideoPipeline(StableDiffusionPipeline):
|
36 |
def __init__(
|
37 |
self,
|
|
|
43 |
safety_checker: StableDiffusionSafetyChecker,
|
44 |
feature_extractor: CLIPFeatureExtractor,
|
45 |
requires_safety_checker: bool = True,
|
46 |
+
):
|
47 |
+
super().__init__(vae, text_encoder, tokenizer, unet, scheduler,
|
48 |
+
safety_checker, feature_extractor, requires_safety_checker)
|
|
|
49 |
|
50 |
def DDPM_forward(self, x0, t0, tMax, generator, device, shape, text_embeddings):
|
51 |
rand_device = "cpu" if device.type == "mps" else device
|
52 |
+
|
53 |
if x0 is None:
|
54 |
return torch.randn(shape, generator=generator, device=rand_device, dtype=text_embeddings.dtype).to(device)
|
55 |
else:
|
|
|
59 |
torch.sqrt(1-alpha_vec) * eps
|
60 |
return xt
|
61 |
|
|
|
62 |
def prepare_latents(self, batch_size, num_channels_latents, video_length, height, width, dtype, device, generator, latents=None):
|
63 |
shape = (batch_size, num_channels_latents, video_length, height //
|
64 |
self.vae_scale_factor, width // self.vae_scale_factor)
|
|
|
89 |
latents = latents * self.scheduler.init_noise_sigma
|
90 |
return latents
|
91 |
|
92 |
+
def warp_latents_from_f0(self, latents, reference_flow):
|
|
|
|
|
93 |
_, _, H, W = reference_flow.size()
|
94 |
b, c, f, h, w = latents.size()
|
95 |
coords0 = coords_grid(f, H, W, device=latents.device).to(latents.dtype)
|
|
|
102 |
latents_0 = latents[:, :, 0]
|
103 |
latents_0 = latents_0.repeat(f, 1, 1, 1)
|
104 |
warped = grid_sample(latents_0, coords_t0,
|
105 |
+
mode='nearest', padding_mode='reflection')
|
106 |
warped = rearrange(warped, '(b f) c h w -> b c f h w', f=f)
|
107 |
return warped
|
108 |
|
109 |
+
def warp_latents_independently(self, latents, reference_flow, inject_noise=False):
|
110 |
_, _, H, W = reference_flow.size()
|
111 |
+
b, _, f, h, w = latents.size()
|
112 |
assert b == 1
|
113 |
coords0 = coords_grid(f, H, W, device=latents.device).to(latents.dtype)
|
|
|
114 |
|
115 |
+
coords_t0 = coords0 + reference_flow
|
116 |
coords_t0[:, 0] /= W
|
117 |
coords_t0[:, 1] /= H
|
118 |
+
|
119 |
coords_t0 = coords_t0 * 2.0 - 1.0
|
120 |
|
121 |
coords_t0 = T.Resize((h, w))(coords_t0)
|
|
|
123 |
coords_t0 = rearrange(coords_t0, 'f c h w -> f h w c')
|
124 |
|
125 |
latents_0 = rearrange(latents[0], 'c f h w -> f c h w')
|
|
|
126 |
warped = grid_sample(latents_0, coords_t0,
|
127 |
mode='nearest', padding_mode='reflection')
|
128 |
+
|
129 |
+
if inject_noise:
|
130 |
+
idx = torch.logical_or(coords_t0 >= 1, coords_t0 < -1)
|
131 |
+
reset_noise = torch.randn(idx.shape)
|
132 |
+
idx = torch.logical_or(idx[:, :, :, 0], idx[:, :, :, 1])
|
133 |
+
idx = repeat(idx, "f w h -> f c w h", c=warped.shape[1])
|
134 |
+
reset_noise = torch.randn(
|
135 |
+
size=warped.shape, dtype=warped.dtype, device=warped.device)
|
136 |
+
warped[idx] = reset_noise[idx]
|
137 |
+
|
138 |
warped = rearrange(warped, '(b f) c h w -> b c f h w', f=f)
|
139 |
return warped
|
140 |
|
141 |
+
def DDIM_backward(self, num_inference_steps, timesteps, skip_t, t0, t1, do_classifier_free_guidance, null_embs, text_embeddings, latents_local,
|
142 |
+
latents_dtype, guidance_scale, guidance_stop_step, callback, callback_steps, extra_step_kwargs, num_warmup_steps):
|
143 |
entered = False
|
144 |
+
|
145 |
f = latents_local.shape[2]
|
146 |
+
|
147 |
+
latents_local = rearrange(latents_local, "b c f w h -> (b f) c w h")
|
148 |
+
|
149 |
latents = latents_local.detach().clone()
|
150 |
x_t0_1 = None
|
151 |
x_t1_1 = None
|
|
|
|
|
152 |
|
153 |
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
154 |
for i, t in enumerate(timesteps):
|
|
|
171 |
with torch.no_grad():
|
172 |
if null_embs is not None:
|
173 |
text_embeddings[0] = null_embs[i][0]
|
174 |
+
te = torch.cat([repeat(text_embeddings[0, :, :], "c k -> f c k", f=f),
|
175 |
+
repeat(text_embeddings[1, :, :], "c k -> f c k", f=f)])
|
176 |
noise_pred = self.unet(
|
177 |
latent_model_input, t, encoder_hidden_states=te).sample.to(dtype=latents_dtype)
|
178 |
|
|
|
203 |
if callback is not None and i % callback_steps == 0:
|
204 |
callback(i, t, latents)
|
205 |
|
206 |
+
latents = rearrange(latents, "(b f) c w h -> b c f w h", f=f)
|
207 |
+
|
|
|
|
|
|
|
208 |
res = {"x0": latents.detach().clone()}
|
209 |
if x_t0_1 is not None:
|
210 |
+
x_t0_1 = rearrange(x_t0_1, "(b f) c w h -> b c f w h", f=f)
|
211 |
res["x_t0_1"] = x_t0_1.detach().clone()
|
212 |
if x_t1_1 is not None:
|
213 |
+
x_t1_1 = rearrange(x_t1_1, "(b f) c w h -> b c f w h", f=f)
|
214 |
res["x_t1_1"] = x_t1_1.detach().clone()
|
215 |
return res
|
216 |
|
|
|
222 |
video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length)
|
223 |
video = (video / 2 + 0.5).clamp(0, 1)
|
224 |
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
|
225 |
+
video = video.detach().cpu()
|
226 |
return video
|
227 |
|
228 |
+
def create_motion_field(self, motion_field_strength_x, motion_field_strength_y, frame_ids, video_length, latents):
|
229 |
+
|
230 |
+
reference_flow = torch.zeros(
|
231 |
+
(video_length-1, 2, 512, 512), device=latents.device, dtype=latents.dtype)
|
232 |
+
for fr_idx in range(video_length-1):
|
233 |
+
reference_flow[fr_idx, 0, :,
|
234 |
+
:] = motion_field_strength_x*(frame_ids[fr_idx]+1)
|
235 |
+
reference_flow[fr_idx, 1, :,
|
236 |
+
:] = motion_field_strength_y*(frame_ids[fr_idx]+1)
|
237 |
+
return reference_flow
|
238 |
|
239 |
+
def create_motion_field_and_warp_latents(self, motion_field_strength_x, motion_field_strength_y, frame_ids, video_length, inject_noise_to_warp, latents):
|
240 |
+
|
241 |
+
motion_field = self.create_motion_field(motion_field_strength_x=motion_field_strength_x,
|
242 |
+
motion_field_strength_y=motion_field_strength_y, latents=latents, video_length=video_length, frame_ids=frame_ids)
|
243 |
+
for idx, latent in enumerate(latents):
|
244 |
+
latents[idx] = self.warp_latents_independently(
|
245 |
+
latent[None], motion_field, inject_noise=inject_noise_to_warp)
|
246 |
+
return motion_field, latents
|
247 |
|
248 |
@torch.no_grad()
|
249 |
def __call__(
|
|
|
262 |
List[torch.Generator]]] = None,
|
263 |
xT: Optional[torch.FloatTensor] = None,
|
264 |
null_embs: Optional[torch.FloatTensor] = None,
|
|
|
265 |
motion_field_strength_x: float = 12,
|
266 |
+
motion_field_strength_y: float = 12,
|
267 |
output_type: Optional[str] = "tensor",
|
268 |
return_dict: bool = True,
|
269 |
callback: Optional[Callable[[
|
270 |
int, int, torch.FloatTensor], None]] = None,
|
271 |
callback_steps: Optional[int] = 1,
|
272 |
use_motion_field: bool = True,
|
273 |
+
smooth_bg: bool = False,
|
274 |
smooth_bg_strength: float = 0.4,
|
275 |
+
inject_noise_to_warp: bool = False,
|
276 |
+
t0: int = 44,
|
277 |
+
t1: int = 47,
|
278 |
**kwargs,
|
279 |
):
|
280 |
+
frame_ids = kwargs.pop("frame_ids", list(range(video_length)))
|
281 |
+
|
282 |
+
assert num_videos_per_prompt == 1
|
283 |
+
assert isinstance(prompt, list) and len(prompt) > 0
|
284 |
+
assert isinstance(negative_prompt, list) or negative_prompt is None
|
285 |
+
|
286 |
+
prompt_types = [prompt, negative_prompt]
|
287 |
+
|
288 |
+
for idx, prompt_type in enumerate(prompt_types):
|
289 |
+
prompt_template = None
|
290 |
+
for prompt in prompt_type:
|
291 |
+
if prompt_template is None:
|
292 |
+
prompt_template = prompt
|
293 |
+
else:
|
294 |
+
assert prompt == prompt_template
|
295 |
+
if prompt_types[idx] is not None:
|
296 |
+
prompt_types[idx] = prompt_types[idx][0]
|
297 |
+
prompt = prompt_types[0]
|
298 |
+
negative_prompt = prompt_types[1]
|
299 |
+
|
300 |
+
print(
|
301 |
+
f" Motion field strength x = {motion_field_strength_x}, y = {motion_field_strength_y}")
|
302 |
print(f" Use: Motion field = {use_motion_field}")
|
303 |
print(f" Use: Background smoothing = {smooth_bg}")
|
304 |
+
print(f"Inject noise to warp = {inject_noise_to_warp}")
|
305 |
# Default height and width to unet
|
306 |
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
307 |
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
|
|
321 |
text_embeddings = self._encode_prompt(
|
322 |
prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt
|
323 |
)
|
324 |
+
|
325 |
# Prepare timesteps
|
326 |
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
327 |
timesteps = self.scheduler.timesteps
|
328 |
+
|
329 |
# print(f" Latent shape = {latents.shape}")
|
330 |
|
331 |
# Prepare latent variables
|
|
|
334 |
xT = self.prepare_latents(
|
335 |
batch_size * num_videos_per_prompt,
|
336 |
num_channels_latents,
|
337 |
+
1,
|
338 |
height,
|
339 |
width,
|
340 |
text_embeddings.dtype,
|
|
|
361 |
None,
|
362 |
)
|
363 |
xT = torch.cat([xT, xT_missing], dim=2)
|
|
|
364 |
|
365 |
xInit = xT.clone()
|
366 |
+
|
367 |
+
timesteps_ddpm = [981, 961, 941, 921, 901, 881, 861, 841, 821, 801, 781, 761, 741, 721,
|
368 |
+
701, 681, 661, 641, 621, 601, 581, 561, 541, 521, 501, 481, 461, 441,
|
369 |
+
421, 401, 381, 361, 341, 321, 301, 281, 261, 241, 221, 201, 181, 161,
|
370 |
+
141, 121, 101, 81, 61, 41, 21, 1]
|
371 |
+
timesteps_ddpm.reverse()
|
372 |
+
|
373 |
+
t0 = timesteps_ddpm[t0]
|
374 |
+
t1 = timesteps_ddpm[t1]
|
375 |
+
print(f"t0 = {t0} t1 = {t1}")
|
376 |
x_t1_1 = None
|
377 |
|
|
|
378 |
# Prepare extra step kwargs.
|
379 |
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
380 |
# Denoising loop
|
381 |
num_warmup_steps = len(timesteps) - \
|
382 |
num_inference_steps * self.scheduler.order
|
|
|
383 |
|
384 |
+
shape = (batch_size, num_channels_latents, 1, height //
|
385 |
+
self.vae_scale_factor, width // self.vae_scale_factor)
|
386 |
+
if inject_noise_to_warp and use_motion_field:
|
387 |
+
# if we inject to noise to warp function, we do it for timesteps T = 1000
|
388 |
+
|
389 |
+
x_t0_k = xT[:, :, :1, :, :].repeat(1, 1, video_length-1, 1, 1)
|
390 |
+
|
391 |
+
# reference_flow, x_t0_k = self.create_motion_field_and_warp_latents(motion_field_strength_x=motion_field_strength_x, motion_field_strength_y=motion_field_strength_y,
|
392 |
+
# frame_ids=frame_ids,video_length=video_length,inject_noise_to_warp=inject_noise_to_warp,latents = x_t0_k)
|
393 |
+
# xT =torch.cat([xT, x_t0_k], dim=2).clone().detach()
|
394 |
|
395 |
ddim_res = self.DDIM_backward(num_inference_steps=num_inference_steps, timesteps=timesteps, skip_t=1000, t0=t0, t1=t1, do_classifier_free_guidance=do_classifier_free_guidance,
|
396 |
+
null_embs=null_embs, text_embeddings=text_embeddings, latents_local=xT, latents_dtype=dtype, guidance_scale=guidance_scale, guidance_stop_step=guidance_stop_step,
|
397 |
+
callback=callback, callback_steps=callback_steps, extra_step_kwargs=extra_step_kwargs, num_warmup_steps=num_warmup_steps)
|
398 |
+
|
399 |
x0 = ddim_res["x0"].detach()
|
400 |
+
|
401 |
if "x_t0_1" in ddim_res:
|
402 |
x_t0_1 = ddim_res["x_t0_1"].detach()
|
403 |
if "x_t1_1" in ddim_res:
|
|
|
405 |
del ddim_res
|
406 |
del xT
|
407 |
|
408 |
+
if inject_noise_to_warp and use_motion_field:
|
409 |
+
# DDPM forward to allow for more motion
|
410 |
+
if t1 > t0:
|
411 |
+
x_t1_k = self.DDPM_forward(
|
412 |
+
x0=x_t0_1, t0=t0, tMax=t1, device=device, shape=shape, text_embeddings=text_embeddings, generator=generator)
|
413 |
+
else:
|
414 |
+
x_t1_k = x_t0_k
|
415 |
+
|
416 |
+
if x_t1_1 is None:
|
417 |
+
raise Exception
|
418 |
+
|
419 |
+
x_t1 = x_t1_k.clone().detach()
|
420 |
+
|
421 |
+
ddim_res = self.DDIM_backward(num_inference_steps=num_inference_steps, timesteps=timesteps, skip_t=t1, t0=-1, t1=-1, do_classifier_free_guidance=do_classifier_free_guidance,
|
422 |
+
null_embs=null_embs, text_embeddings=text_embeddings, latents_local=x_t1, latents_dtype=dtype, guidance_scale=guidance_scale, guidance_stop_step=guidance_stop_step,
|
423 |
+
callback=callback, callback_steps=callback_steps, extra_step_kwargs=extra_step_kwargs, num_warmup_steps=num_warmup_steps)
|
424 |
+
|
425 |
+
x0 = ddim_res["x0"].detach()
|
426 |
+
del ddim_res
|
427 |
+
del x_t1
|
428 |
+
del x_t1_k
|
429 |
+
|
430 |
+
if use_motion_field and not inject_noise_to_warp:
|
431 |
del x0
|
|
|
|
|
|
|
|
|
|
|
432 |
|
433 |
+
x_t0_k = x_t0_1[:, :, :1, :, :].repeat(1, 1, video_length-1, 1, 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
434 |
|
435 |
+
reference_flow, x_t0_k = self.create_motion_field_and_warp_latents(
|
436 |
+
motion_field_strength_x=motion_field_strength_x, motion_field_strength_y=motion_field_strength_y, latents=x_t0_k, video_length=video_length,
|
437 |
+
inject_noise_to_warp=inject_noise_to_warp, frame_ids=frame_ids)
|
438 |
|
439 |
# assuming t0=t1=1000, if t0 = 1000
|
440 |
if t1 > t0:
|
|
|
449 |
x_t1 = torch.cat([x_t1_1, x_t1_k], dim=2).clone().detach()
|
450 |
|
451 |
ddim_res = self.DDIM_backward(num_inference_steps=num_inference_steps, timesteps=timesteps, skip_t=t1, t0=-1, t1=-1, do_classifier_free_guidance=do_classifier_free_guidance,
|
452 |
+
null_embs=null_embs, text_embeddings=text_embeddings, latents_local=x_t1, latents_dtype=dtype, guidance_scale=guidance_scale,
|
453 |
+
guidance_stop_step=guidance_stop_step, callback=callback, callback_steps=callback_steps, extra_step_kwargs=extra_step_kwargs, num_warmup_steps=num_warmup_steps)
|
454 |
|
455 |
x0 = ddim_res["x0"].detach()
|
456 |
del ddim_res
|
457 |
+
del x_t1
|
458 |
+
del x_t1_1
|
459 |
+
del x_t1_k
|
460 |
+
|
461 |
else:
|
462 |
x_t1 = x_t1_1.clone()
|
463 |
+
x_t1_1 = x_t1_1[:, :, :1, :, :].clone()
|
464 |
+
x_t1_k = x_t1_1[:, :, 1:, :, :].clone()
|
465 |
x_t0_k = x_t0_1[:, :, 1:, :, :].clone()
|
466 |
+
x_t0_1 = x_t0_1[:, :, :1, :, :].clone()
|
467 |
|
468 |
# smooth background
|
469 |
if smooth_bg:
|
|
|
485 |
mask = dilation(mask[None].to(x0.device), kernel)[0]
|
486 |
M_FG[batch_idx, frame_idx, :, :] = mask
|
487 |
|
|
|
488 |
x_t1_1_fg_masked = x_t1_1 * \
|
489 |
(1 - repeat(M_FG[:, 0, :, :],
|
490 |
"b w h -> b c 1 w h", c=x_t1_1.shape[1]))
|
491 |
|
|
|
492 |
x_t1_1_fg_masked_moved = []
|
493 |
for batch_idx, x_t1_1_fg_masked_b in enumerate(x_t1_1_fg_masked):
|
494 |
x_t1_fg_masked_b = x_t1_1_fg_masked_b.clone()
|
|
|
498 |
if use_motion_field:
|
499 |
x_t1_fg_masked_b = x_t1_fg_masked_b[None]
|
500 |
x_t1_fg_masked_b = self.warp_latents_independently(
|
501 |
+
x_t1_fg_masked_b, reference_flow, inject_noise=False)
|
502 |
else:
|
503 |
x_t1_fg_masked_b = x_t1_fg_masked_b[None]
|
504 |
|
|
|
514 |
for batch_idx, m_fg_1_b in enumerate(M_FG_1):
|
515 |
m_fg_1_b = m_fg_1_b[None, None]
|
516 |
m_fg_b = m_fg_1_b.repeat(1, 1, video_length-1, 1, 1)
|
517 |
+
if use_motion_field:
|
518 |
m_fg_b = self.warp_latents_independently(
|
519 |
+
m_fg_b.clone(), reference_flow, inject_noise=False)
|
520 |
M_FG_warped.append(
|
521 |
torch.cat([m_fg_1_b[:1, 0], m_fg_b[:1, 0]], dim=1))
|
522 |
|
|
|
527 |
M_BG = (1-M_FG) * (1 - M_FG_warped)
|
528 |
M_BG = repeat(M_BG, "b f h w -> b c f h w", c=channels)
|
529 |
a_convex = smooth_bg_strength
|
|
|
|
|
|
|
530 |
|
531 |
+
latents = (1-M_BG) * x_t1 + M_BG * (a_convex *
|
532 |
+
x_t1 + (1-a_convex) * x_t1_1_fg_masked_moved)
|
|
|
|
|
|
|
|
|
533 |
|
534 |
ddim_res = self.DDIM_backward(num_inference_steps=num_inference_steps, timesteps=timesteps, skip_t=t1, t0=-1, t1=-1, do_classifier_free_guidance=do_classifier_free_guidance,
|
535 |
+
null_embs=null_embs, text_embeddings=text_embeddings, latents_local=latents, latents_dtype=dtype, guidance_scale=guidance_scale,
|
536 |
+
guidance_stop_step=guidance_stop_step, callback=callback, callback_steps=callback_steps, extra_step_kwargs=extra_step_kwargs, num_warmup_steps=num_warmup_steps)
|
537 |
x0 = ddim_res["x0"].detach()
|
538 |
del ddim_res
|
539 |
+
del latents
|
540 |
+
|
541 |
+
latents = x0
|
542 |
+
|
543 |
+
# manually for max memory savings
|
544 |
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
545 |
+
self.unet.to("cpu")
|
546 |
+
torch.cuda.empty_cache()
|
547 |
+
|
548 |
+
if output_type == "latent":
|
549 |
+
image = latents
|
550 |
+
has_nsfw_concept = None
|
551 |
+
else:
|
552 |
+
image = self.decode_latents(latents)
|
553 |
+
|
554 |
+
# Run safety checker
|
555 |
+
image, has_nsfw_concept = self.run_safety_checker(
|
556 |
+
image, device, text_embeddings.dtype)
|
557 |
+
image = rearrange(image, "b c f h w -> (b f) h w c")
|
558 |
|
559 |
+
# Offload last model to CPU
|
560 |
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
561 |
+
self.final_offload_hook.offload()
|
562 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
563 |
if not return_dict:
|
564 |
+
return (image, has_nsfw_concept)
|
565 |
|
566 |
+
return TextToVideoPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|
utils.py
CHANGED
@@ -1,8 +1,10 @@
|
|
1 |
import os
|
|
|
|
|
2 |
import numpy as np
|
3 |
import torch
|
4 |
import torchvision
|
5 |
-
from torchvision.transforms import Resize
|
6 |
import imageio
|
7 |
from einops import rearrange
|
8 |
import cv2
|
@@ -11,23 +13,33 @@ from annotator.util import resize_image, HWC3
|
|
11 |
from annotator.canny import CannyDetector
|
12 |
from annotator.openpose import OpenposeDetector
|
13 |
import decord
|
14 |
-
decord.bridge.set_bridge('torch')
|
15 |
|
16 |
apply_canny = CannyDetector()
|
17 |
apply_openpose = OpenposeDetector()
|
18 |
|
19 |
|
20 |
-
def add_watermark(image,
|
21 |
-
wmsize=16, bbuf=5, opacity=0.9):
|
22 |
'''
|
23 |
Creates a watermark on the saved inference image.
|
24 |
We request that you do not remove this to properly assign credit to
|
25 |
Shi-Lab's work.
|
26 |
'''
|
27 |
-
watermark = Image.open(watermark_path)
|
28 |
-
|
29 |
-
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
return image
|
32 |
|
33 |
|
@@ -61,7 +73,7 @@ def pre_process_pose(input_video, apply_pose_detect: bool = True):
|
|
61 |
return rearrange(control, 'f h w c -> f c h w')
|
62 |
|
63 |
|
64 |
-
def create_video(frames, fps, rescale=False, path=None):
|
65 |
if path is None:
|
66 |
dir = "temporal"
|
67 |
os.makedirs(dir, exist_ok=True)
|
@@ -74,18 +86,19 @@ def create_video(frames, fps, rescale=False, path=None):
|
|
74 |
x = (x + 1.0) / 2.0 # -1,1 -> 0,1
|
75 |
x = (x * 255).numpy().astype(np.uint8)
|
76 |
|
77 |
-
|
78 |
-
|
79 |
outputs.append(x)
|
80 |
# imageio.imsave(os.path.join(dir, os.path.splitext(name)[0] + f'_{i}.jpg'), x)
|
81 |
|
82 |
imageio.mimsave(path, outputs, fps=fps)
|
83 |
return path
|
84 |
|
85 |
-
def create_gif(frames, fps, rescale=False):
|
86 |
-
|
87 |
-
|
88 |
-
|
|
|
89 |
|
90 |
outputs = []
|
91 |
for i, x in enumerate(frames):
|
@@ -93,8 +106,8 @@ def create_gif(frames, fps, rescale=False):
|
|
93 |
if rescale:
|
94 |
x = (x + 1.0) / 2.0 # -1,1 -> 0,1
|
95 |
x = (x * 255).numpy().astype(np.uint8)
|
96 |
-
|
97 |
-
|
98 |
outputs.append(x)
|
99 |
# imageio.imsave(os.path.join(dir, os.path.splitext(name)[0] + f'_{i}.jpg'), x)
|
100 |
|
@@ -103,7 +116,6 @@ def create_gif(frames, fps, rescale=False):
|
|
103 |
|
104 |
def prepare_video(video_path:str, resolution:int, device, dtype, normalize=True, start_t:float=0, end_t:float=-1, output_fps:int=-1):
|
105 |
vr = decord.VideoReader(video_path)
|
106 |
-
video = vr.get_batch(range(0, len(vr))).asnumpy()
|
107 |
initial_fps = vr.get_avg_fps()
|
108 |
if output_fps == -1:
|
109 |
output_fps = int(initial_fps)
|
@@ -113,24 +125,27 @@ def prepare_video(video_path:str, resolution:int, device, dtype, normalize=True,
|
|
113 |
end_t = min(len(vr) / initial_fps, end_t)
|
114 |
assert 0 <= start_t < end_t
|
115 |
assert output_fps > 0
|
116 |
-
f, h, w, c = video.shape
|
117 |
start_f_ind = int(start_t * initial_fps)
|
118 |
end_f_ind = int(end_t * initial_fps)
|
119 |
num_f = int((end_t - start_t) * output_fps)
|
120 |
sample_idx = np.linspace(start_f_ind, end_f_ind, num_f, endpoint=False).astype(int)
|
121 |
-
video =
|
|
|
|
|
|
|
|
|
|
|
122 |
video = rearrange(video, "f h w c -> f c h w")
|
123 |
video = torch.Tensor(video).to(device).to(dtype)
|
124 |
if h > w:
|
125 |
w = int(w * resolution / h)
|
126 |
w = w - w % 8
|
127 |
h = resolution - resolution % 8
|
128 |
-
video = Resize((h, w))(video)
|
129 |
else:
|
130 |
h = int(h * resolution / w)
|
131 |
h = h - h % 8
|
132 |
w = resolution - resolution % 8
|
133 |
-
|
134 |
if normalize:
|
135 |
video = video / 127.5 - 1.0
|
136 |
return video, output_fps
|
|
|
1 |
import os
|
2 |
+
|
3 |
+
import PIL.Image
|
4 |
import numpy as np
|
5 |
import torch
|
6 |
import torchvision
|
7 |
+
from torchvision.transforms import Resize, InterpolationMode
|
8 |
import imageio
|
9 |
from einops import rearrange
|
10 |
import cv2
|
|
|
13 |
from annotator.canny import CannyDetector
|
14 |
from annotator.openpose import OpenposeDetector
|
15 |
import decord
|
16 |
+
# decord.bridge.set_bridge('torch')
|
17 |
|
18 |
apply_canny = CannyDetector()
|
19 |
apply_openpose = OpenposeDetector()
|
20 |
|
21 |
|
22 |
+
def add_watermark(image, watermark_path, wm_rel_size=1/16, boundary=5):
|
|
|
23 |
'''
|
24 |
Creates a watermark on the saved inference image.
|
25 |
We request that you do not remove this to properly assign credit to
|
26 |
Shi-Lab's work.
|
27 |
'''
|
28 |
+
watermark = Image.open(watermark_path)
|
29 |
+
w_0, h_0 = watermark.size
|
30 |
+
H, W, _ = image.shape
|
31 |
+
wmsize = int(max(H, W) * wm_rel_size)
|
32 |
+
aspect = h_0 / w_0
|
33 |
+
if aspect > 1.0:
|
34 |
+
watermark = watermark.resize((wmsize, int(aspect * wmsize)), Image.LANCZOS)
|
35 |
+
else:
|
36 |
+
watermark = watermark.resize((int(wmsize / aspect), wmsize), Image.LANCZOS)
|
37 |
+
w, h = watermark.size
|
38 |
+
loc_h = H - h - boundary
|
39 |
+
loc_w = W - w - boundary
|
40 |
+
image = Image.fromarray(image)
|
41 |
+
mask = watermark if watermark.mode in ('RGBA', 'LA') else None
|
42 |
+
image.paste(watermark, (loc_w, loc_h), mask)
|
43 |
return image
|
44 |
|
45 |
|
|
|
73 |
return rearrange(control, 'f h w c -> f c h w')
|
74 |
|
75 |
|
76 |
+
def create_video(frames, fps, rescale=False, path=None, watermark=None):
|
77 |
if path is None:
|
78 |
dir = "temporal"
|
79 |
os.makedirs(dir, exist_ok=True)
|
|
|
86 |
x = (x + 1.0) / 2.0 # -1,1 -> 0,1
|
87 |
x = (x * 255).numpy().astype(np.uint8)
|
88 |
|
89 |
+
if watermark is not None:
|
90 |
+
x = add_watermark(x, watermark)
|
91 |
outputs.append(x)
|
92 |
# imageio.imsave(os.path.join(dir, os.path.splitext(name)[0] + f'_{i}.jpg'), x)
|
93 |
|
94 |
imageio.mimsave(path, outputs, fps=fps)
|
95 |
return path
|
96 |
|
97 |
+
def create_gif(frames, fps, rescale=False, path=None, watermark=None):
|
98 |
+
if path is None:
|
99 |
+
dir = "temporal"
|
100 |
+
os.makedirs(dir, exist_ok=True)
|
101 |
+
path = os.path.join(dir, 'canny_db.gif')
|
102 |
|
103 |
outputs = []
|
104 |
for i, x in enumerate(frames):
|
|
|
106 |
if rescale:
|
107 |
x = (x + 1.0) / 2.0 # -1,1 -> 0,1
|
108 |
x = (x * 255).numpy().astype(np.uint8)
|
109 |
+
if watermark is not None:
|
110 |
+
x = add_watermark(x, watermark)
|
111 |
outputs.append(x)
|
112 |
# imageio.imsave(os.path.join(dir, os.path.splitext(name)[0] + f'_{i}.jpg'), x)
|
113 |
|
|
|
116 |
|
117 |
def prepare_video(video_path:str, resolution:int, device, dtype, normalize=True, start_t:float=0, end_t:float=-1, output_fps:int=-1):
|
118 |
vr = decord.VideoReader(video_path)
|
|
|
119 |
initial_fps = vr.get_avg_fps()
|
120 |
if output_fps == -1:
|
121 |
output_fps = int(initial_fps)
|
|
|
125 |
end_t = min(len(vr) / initial_fps, end_t)
|
126 |
assert 0 <= start_t < end_t
|
127 |
assert output_fps > 0
|
|
|
128 |
start_f_ind = int(start_t * initial_fps)
|
129 |
end_f_ind = int(end_t * initial_fps)
|
130 |
num_f = int((end_t - start_t) * output_fps)
|
131 |
sample_idx = np.linspace(start_f_ind, end_f_ind, num_f, endpoint=False).astype(int)
|
132 |
+
video = vr.get_batch(sample_idx)
|
133 |
+
if torch.is_tensor(video):
|
134 |
+
video = video.detach().cpu().numpy()
|
135 |
+
else:
|
136 |
+
video = video.asnumpy()
|
137 |
+
_, h, w, _ = video.shape
|
138 |
video = rearrange(video, "f h w c -> f c h w")
|
139 |
video = torch.Tensor(video).to(device).to(dtype)
|
140 |
if h > w:
|
141 |
w = int(w * resolution / h)
|
142 |
w = w - w % 8
|
143 |
h = resolution - resolution % 8
|
|
|
144 |
else:
|
145 |
h = int(h * resolution / w)
|
146 |
h = h - h % 8
|
147 |
w = resolution - resolution % 8
|
148 |
+
video = Resize((h, w), interpolation=InterpolationMode.BILINEAR, antialias=True)(video)
|
149 |
if normalize:
|
150 |
video = video / 127.5 - 1.0
|
151 |
return video, output_fps
|