diff --git a/.gitignore b/.gitignore index 0b1d17ca35412ca084975f4efb4ab27fc6f69abe..f5557719e5a4ff762ba9b3a76b46c483ab2c323d 100644 --- a/.gitignore +++ b/.gitignore @@ -29,7 +29,7 @@ notification.mp3 /SwinIR /textual_inversion .vscode -/extensions +# /extensions /test/stdout.txt /test/stderr.txt /cache.json diff --git a/extensions/deforum/.github/FUNDING.yml b/extensions/deforum/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..e707ddb03c159bc5fc649349fe8303dbf43ddedc --- /dev/null +++ b/extensions/deforum/.github/FUNDING.yml @@ -0,0 +1,13 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: deforum +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/extensions/deforum/.github/ISSUE_TEMPLATE/bug_report.yml b/extensions/deforum/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000000000000000000000000000000000..c86f978adbda56d77e669f5541b3f86300733f72 --- /dev/null +++ b/extensions/deforum/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,97 @@ +name: Bug Report +description: Create a bug report for the Deforum extension +title: "[Bug]: " +labels: ["bug-report"] + +body: + - type: checkboxes + attributes: + label: Have you read the latest version of the FAQ? + description: Please visit the page called FAQ & Troubleshooting on the Deforum wiki in this repository and see if your problem has already been described there. + options: + - label: I have visited the FAQ page right now and my issue is not present there + required: true + - type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an issue already exists for the bug you encountered (including the closed issues). + options: + - label: I have searched the existing issues and checked the recent builds/commits of both this extension and the webui + required: true + - type: checkboxes + attributes: + label: Are you using the latest version of the Deforum extension? + description: Please, check if your Deforum is based on the latest repo commit (git log) or update it through the 'Extensions' tab and check if the issue still persist. Otherwise, check this box. + options: + - label: I have Deforum updated to the lastest version and I still have the issue. + required: true + - type: markdown + attributes: + value: | + *Please fill this form with as much information as possible, don't forget to fill "What OS..." and "What browsers" and *provide screenshots if possible** + - type: textarea + id: what-did + attributes: + label: What happened? + description: Tell us what happened in a very clear and simple way + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce the problem + description: Please provide us with precise step by step information on how to reproduce the bug + value: | + 1. Go to .... + 2. Press .... + 3. ... + validations: + required: true + - type: textarea + id: what-should + attributes: + label: What should have happened? + description: Tell what you think the normal behavior should be + - type: textarea + id: commits + attributes: + label: WebUI and Deforum extension Commit IDs + description: Which commit of the webui/deforum extension are you running on? (Do not write *Latest version/repo/commit*, as this means nothing and will have changed by the time we read your issue. Rather, copy the **Commit** link at the bottom of the UI, or if you can't launch the webui at all, enter your cmd/terminal, CD into the main webui folder to get the webui commit id, and cd into the extensions/deforum folder to get the deforum commit id, both using the command 'git rev-parse HEAD'.) + value: | + webui commit id - + deforum exten commit id - + validations: + required: true + - type: dropdown + id: where + attributes: + label: On which platform are you launching the webui with the extension? + multiple: true + options: + - Local PC setup (Windows) + - Local PC setup (Linux) + - Local PC setup (Mac) + - Google Colab (The Last Ben's) + - Google Colab (Other) + - Cloud server (Linux) + - Other (please specify in "additional information") + - type: textarea + id: customsettings + attributes: + label: Webui core settings + description: Send here a link to your ui-config.json file in the core 'stable-diffusion-webui' folder (ideally, upload it to GitHub gists). Friendly reminder - if you have 'With img2img, do exactly the amount of steps the slider specified' checked, your issue will be discarded immediately. 😉 + validations: + required: true + - type: textarea + id: logs + attributes: + label: Console logs + description: Please provide **full** cmd/terminal logs from the moment you started UI to the end of it, after your bug happened. If it's very long, provide a link to GitHub gists or similar service. + render: Shell + validations: + required: true + - type: textarea + id: misc + attributes: + label: Additional information + description: Please provide us with any relevant additional info or context. diff --git a/extensions/deforum/.github/ISSUE_TEMPLATE/config.yml b/extensions/deforum/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..b15e609d9f1315070a1bcc0d82bd9d3dfc7b81f0 --- /dev/null +++ b/extensions/deforum/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Deforum Github discussions + url: https://github.com/deforum-art/deforum-for-automatic1111-webui/discussions + about: Please ask and answer questions here. + - name: Deforum Discord + url: https://discord.gg/deforum + about: Or here :) \ No newline at end of file diff --git a/extensions/deforum/.github/ISSUE_TEMPLATE/feature_request.yml b/extensions/deforum/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000000000000000000000000000000000000..58a6332ef1bec7637bbbad898eddd06a0a2e1cf4 --- /dev/null +++ b/extensions/deforum/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,40 @@ +name: Feature request +description: Suggest an idea for the Deforum extension +title: "[Feature Request]: " +labels: ["enhancement"] + +body: + - type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an issue already exists for the feature you want, and that it's not implemented in a recent build/commit. + options: + - label: I have searched the existing issues and checked the recent builds/commits + required: true + - type: markdown + attributes: + value: | + *Please fill this form with as much information as possible, provide screenshots and/or illustrations of the feature if possible* + - type: textarea + id: feature + attributes: + label: What would your feature do ? + description: Tell us about your feature in a very clear and simple way, and what problem it would solve + validations: + required: true + - type: textarea + id: workflow + attributes: + label: Proposed workflow + description: Please provide us with step by step information on how you'd like the feature to be accessed and used + value: | + 1. Go to .... + 2. Press .... + 3. ... + validations: + required: true + - type: textarea + id: misc + attributes: + label: Additional information + description: Add any other context or screenshots about the feature request here. \ No newline at end of file diff --git a/extensions/deforum/.gitignore b/extensions/deforum/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5cc8a723f7ba813d56294d38c6859dc1ce195e42 --- /dev/null +++ b/extensions/deforum/.gitignore @@ -0,0 +1,10 @@ +# Unnecessary compiled python files. +__pycache__ +*.pyc +*.pyo + +# Output Images +outputs + +# Log files for colab-convert +cc-outputs.log diff --git a/extensions/deforum/CONTRIBUTING.md b/extensions/deforum/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..c5df29a13e839422129b9e5e1919cafac4a651e5 --- /dev/null +++ b/extensions/deforum/CONTRIBUTING.md @@ -0,0 +1,7 @@ +# Contributing + +As a part of the Deforum team I (kabachuha) want this script extension to remain a part of the Deforum project. + +Thus, if you want to submit feature request or bugfix, unless it only relates to automatic1111's porting issues, consider making a PR first to the parent repository notebook https://github.com/deforum/stable-diffusion. + +Also, you may want to inforum the dev team about your work via Discord https://discord.gg/deforum to ensure that no one else is working on the same stuff. diff --git a/extensions/deforum/LICENSE b/extensions/deforum/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1e315f0d1cf6154f77fbd35af88d0b8c8c5d933e --- /dev/null +++ b/extensions/deforum/LICENSE @@ -0,0 +1,2496 @@ +deforum-stable-diffusion: +MIT License + +Copyright (c) 2022 deforum and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +k-diffusion: +MIT License + +Copyright (c) 2022 Katherine Crowson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +clip: +MIT License + +Copyright (c) 2021 OpenAI + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +MiDaS: +MIT License + +Copyright (c) 2019 Intel ISL (Intel Intelligent Systems Lab) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +pytorch3d-lite: +BSD License + +For PyTorch3D software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Meta nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +taming-transformers: +Copyright (c) 2020 Patrick Esser and Robin Rombach and Björn Ommer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE./ + +stable diffusion: +Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors + +CreativeML Open RAIL-M +dated August 22, 2022 + +Section I: PREAMBLE + +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. + +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. + +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. + +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. + +This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model. + +NOW THEREFORE, You and Licensor agree as follows: + +1. Definitions + +- "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document. +- "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. +- "Output" means the results of operating a Model as embodied in informational content resulting therefrom. +- "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. +- "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. +- "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. +- "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. +- "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. +- "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. +- "Third Parties" means individuals or legal entities that are not under common control with Licensor or You. +- "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." +- "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. + +Section II: INTELLECTUAL PROPERTY RIGHTS + +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. + +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. +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. + +Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION + +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: +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. +You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License; +You must cause any modified files to carry prominent notices stating that You changed the files; +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. +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. +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). +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. + +Section IV: OTHER PROVISIONS + +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. +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. +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. +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. +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. +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. + +END OF TERMS AND CONDITIONS + + + + +Attachment A + +Use Restrictions + +You agree not to use the Model or Derivatives of the Model: +- In any way that violates any applicable national, federal, state, local or international law or regulation; +- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way; +- To generate or disseminate verifiably false information and/or content with the purpose of harming others; +- To generate or disseminate personal identifiable information that can be used to harm an individual; +- To defame, disparage or otherwise harass others; +- For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation; +- 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; +- 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; +- For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories; +- To provide medical advice and medical results interpretation; +- 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). + +transformers: +Copyright 2018- The Hugging Face team. All rights reserved. + +transformers, FILM Interpolation: + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work 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 Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 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 Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent 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 + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + 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 Work 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 Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (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 Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. 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 + Work (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. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works 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. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +adabins: + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + +adabins: + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + +Clipseg: +MIT License + +This license does not apply to the model weights. + +RIFE: +MIT License + +Copyright (c) 2021 hzwer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +gifski: +GNU AFFERO GENERAL PUBLIC LICENSE ++ +pngquant.c + +### pngquant.c +© 1989, 1991 by Jef Poskanzer. + +Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. This software is provided "as is" without express or implied warranty. + +© 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider. + +All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +### GNU AFFERO GENERAL PUBLIC LICENSE + +Version 3, 19 November 2007 + +© 2007 Free Software Foundation, Inc. + + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +### Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains +free software for all its users. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing +under this license. + +The precise terms and conditions for copying, distribution and +modification follow. + +### TERMS AND CONDITIONS + +#### 0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public +License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +#### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +#### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +#### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +#### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +#### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +#### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +#### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +#### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +#### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +#### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +#### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +#### 13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your +version supports such interaction) an opportunity to receive the +Corresponding Source of your version by providing access to the +Corresponding Source from a network server at no charge, through some +standard or customary means of facilitating copying of software. This +Corresponding Source shall include the Corresponding Source for any +work covered by version 3 of the GNU General Public License that is +incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + +#### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU Affero General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever +published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +#### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +#### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +#### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +REALESRGAN/ REALESRGAN-NCNN-VULKAN: +MIT License (MIT) + +Copyright (c) 2021 Xintao Wang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------ +The following is the License of realsr-ncnn-vulkan + +The MIT License (MIT) + +Copyright (c) 2019 nihui + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/extensions/deforum/README.md b/extensions/deforum/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f94beee68a7475e89fe4f1eca62b8567320ed473 --- /dev/null +++ b/extensions/deforum/README.md @@ -0,0 +1,81 @@ + +# Deforum Stable Diffusion — official extension for AUTOMATIC1111's webui + +

+ Last Commit + GitHub issues + GitHub stars + GitHub forks + +

+ +## Before Starting + +**Important note about versions updating:**
+As auto's webui is getting updated multiple times a day, every day, things tend to break with regards to extensions compatability. +Therefore, it is best recommended to keep two folders: +1. "Stable" folder that you don't regularly update, with versions that you know *work* together (we will provide info on this soon). +2. "Experimental" folder in which you can add 'git pull' to your webui-user.bat, update deforum every day, etc. Keep it wild - but be prepared for bugs. + + +## Getting Started + +1. Install [AUTOMATIC1111's webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui/).
If the repo link doesn't work, please use the alternate official download source: [https://gitgud.io/AUTOMATIC1111/stable-diffusion-webui](https://gitgud.io/AUTOMATIC1111/stable-diffusion-webui). To change your existing webui's installation origin, execute `git remote set-url origin https://gitgud.io/AUTOMATIC1111/stable-diffusion-webui` in the webui starting folder. + +2. Now two ways: either clone the repo into the `extensions` directory via git commandline launched within in the `stable-diffusion-webui` folder + +```sh +git clone https://github.com/deforum-art/deforum-for-automatic1111-webui extensions/deforum +``` + +Or download this repository, locate the `extensions` folder within your WebUI installation, create a folder named `deforum` and put the contents of the downloaded directory inside of it. Then restart WebUI. **Warning: the extension folder has to be named 'deforum' or 'deforum-for-automatic1111-webui', otherwise it will fail to locate the 3D modules as the PATH addition is hardcoded** + +3. Open the webui, find the Deforum tab at the top of the page. + +4. Enter the animation settings. Refer to [this general guide](https://docs.google.com/document/d/1pEobUknMFMkn8F5TMsv8qRzamXX_75BShMMXV8IFslI/edit) and [this guide to math keyframing functions in Deforum](https://docs.google.com/document/d/1pfW1PwbDIuW0cv-dnuyYj1UzPqe23BlSLTJsqazffXM/edit?usp=sharing). However, **in this version prompt weights less than zero don't just like in original Deforum!** Split the positive and the negative prompt in the json section using --neg argument like this "apple:\`where(cos(t)>=0, cos(t), 0)\`, snow --neg strawberry:\`where(cos(t)<0, -cos(t), 0)\`" + +5. To view animation frames as they're being made, without waiting for the completion of an animation, go to the 'Settings' tab and set the value of this toolbar **above zero**. Warning: it may slow down the generation process. If you have 'Do exactly the amount of steps the slider specifies' checkbox selected in the tab, unselect it as it won't allow you to use Deforum schedules and you will get adrupt frame changes without transitions. Then click 'Apply settings' at the top of the page. Now return to the 'Deforum' tab. + +![adsdasunknown](https://user-images.githubusercontent.com/14872007/196064311-1b79866a-e55b-438a-84a7-004ff30829ad.png) + + +6. Run the script and see if you got it working or even got something. **In 3D mode a large delay is expected at first** as the script loads the depth models. In the end, using the default settings the whole thing should consume 6.4 GBs of VRAM at 3D mode peaks and no more than 3.8 GB VRAM in 3D mode if you launch the webui with the '--lowvram' command line argument. + +7. After the generation process is completed, click the button with the self-describing name to show the video or gif result right in the GUI! + +8. Join our Discord where you can post generated stuff, ask questions and more: https://discord.gg/deforum.
+* There's also the 'Issues' tab in the repo, for well... reporting issues ;) + +9. Profit! + +## Known issues + +* This port is not fully backward-compatible with the notebook and the local version both due to the changes in how AUTOMATIC1111's webui handles Stable Diffusion models and the changes in this script to get it to work in the new environment. *Expect* that you may not get exactly the same result or that the thing may break down because of the older settings. + +## Screenshots + +https://user-images.githubusercontent.com/121192995/215522284-d6fbedd5-09e2-4d2c-bd10-f9bbb4a20f82.mp4 + +Main extension tab: + +![maintab](https://user-images.githubusercontent.com/121192995/215362176-4e5599c1-9cb6-4bf9-964d-0ff882661993.png) + +Keyframes tab: + +![keyframes](https://user-images.githubusercontent.com/121192995/215362228-c239c43a-d565-4862-b490-d18b19eaaaa5.png) + +Math evaluation: + +![math-eval](https://user-images.githubusercontent.com/121192995/215362467-481127a4-247a-4b0d-924a-d10719aa4c01.png) + + +## Benchmarks + +3D mode without additional WebUI flags + +![image](https://user-images.githubusercontent.com/14872007/196294447-7817f138-ec4b-4001-885f-454f8667100d.png) + +3D mode when WebUI is launched with '--lowvram' + +![image](https://user-images.githubusercontent.com/14872007/196294517-125fbb27-c06d-4c4b-bcbc-7c743103eff6.png) + diff --git a/extensions/deforum/install.py b/extensions/deforum/install.py new file mode 100644 index 0000000000000000000000000000000000000000..b9166e71c44972d8582836239636d0f483a51ff5 --- /dev/null +++ b/extensions/deforum/install.py @@ -0,0 +1,14 @@ +import launch +import os +import sys + +req_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "requirements.txt") + +with open(req_file) as file: + for lib in file: + lib = lib.strip() + if not launch.is_installed(lib): + if lib == 'rich': + launch.run(f'"{sys.executable}" -m pip install {lib}', desc=f"Installing Deforum requirement: {lib}", errdesc=f"Couldn't install {lib}") + else: + launch.run_pip(f"install {lib}", f"Deforum requirement: {lib}") diff --git a/extensions/deforum/javascript/deforum-hints.js b/extensions/deforum/javascript/deforum-hints.js new file mode 100644 index 0000000000000000000000000000000000000000..bc50ffc016ee93cd88050b7e4d0fbd50f3c96718 --- /dev/null +++ b/extensions/deforum/javascript/deforum-hints.js @@ -0,0 +1,191 @@ +// mouseover tooltips for various UI elements + +deforum_titles = { + //Run + "Override settings": "specify a custom settings file and ignore settings displayed in the interface", + "Custom settings file": "the path to a custom settings file", + "Width": "The width of the output images, in pixels (must be a multiple of 64)", + "Height": "The height of the output images, in pixels (must be a multiple of 64)", + "Restore faces": "Restore low quality faces using GFPGAN neural network", + "Tiling": "Produce an image that can be tiled.", + "Highres. fix": "Use a two step process to partially create an image at smaller resolution, upscale, and then improve details in it without changing composition", + "Seed": "A value that determines the output of random number generator - if you create an image with same parameters and seed as another image, you'll get the same result", + "Sampler": "Which algorithm to use to produce the image", + "Enable extras": "enable additional seed settings", + "Subseed": "Seed of a different picture to be mixed into the generation.", + "Subseed strength": "How strong of a variation to produce. At 0, there will be no effect. At 1, you will get the complete picture with variation seed (except for ancestral samplers, where you will just get something).", + "Resize seed from width": "Normally, changing the resolution will completely change an image, even when using the same seed. If you generated an image with a particular seed and then changed the resolution, put the original resolution here to get an image that more closely resemles the original", + "Resize seed from height": "Normally, changing the resolution will completely change an image, even when using the same seed. If you generated an image with a particular seed and then changed the resolution, put the original resolution here to get an image that more closely resemles the original", + "Steps": "How many times to improve the generated image iteratively; higher values take longer; very low values can produce bad results", + //"ddim_eta": ""; + //"n_batch": "", + //"make_grid": "", + //"grid_rows": "", + //"save_settings": "", + //"save_samples": "", + "Batch name": "output images will be placed in a folder with this name, inside of the img2img output folder", + "Pix2Pix img CFG schedule": "*Only in use with pix2pix checkpoints!*", + "Filename format": "specify the format of the filename for output images", + "Seed behavior": "defines the seed behavior that is used for animations", + "iter": "the seed value will increment by 1 for each subsequent frame of the animation", + "fixed": "the seed will remain fixed across all frames of animation", + "random": "a random seed will be used on each frame of the animation", + "schedule": "specify your own seed schedule (found on the Keyframes page)", + + //Keyframes + "Animation mode": "selects the type of animation", + "2D": "only 2D motion parameters will be used, but this mode uses the least amount of VRAM. You can optionally enable flip_2d_perspective to enable some psuedo-3d animation parameters while in 2D mode.", + "3D": "enables all 3D motion parameters.", + "Video Input": "will ignore all motion parameters and attempt to reference a video loaded into the runtime, specified by the video_init_path. Max_frames is ignored during video_input mode, and instead, follows the number of frames pulled from the video’s length. Resume_from_timestring is NOT available with Video_Input mode.", + "Max frames": "the maximum number of output images to be created", + "Border": "controls handling method of pixels to be generated when the image is smaller than the frame.", + "wrap": "pulls pixels from the opposite edge of the image", + "replicate": "repeats the edge of the pixels, and extends them. Animations with quick motion may yield lines where this border function was attempting to populate pixels into the empty space created.", + "Angle": "2D operator to rotate canvas clockwise/anticlockwise in degrees per frame", + "Zoom": "2D operator that scales the canvas size, multiplicatively. [static = 1.0]", + "Translation X": "2D & 3D operator to move canvas left/right in pixels per frame", + "Translation Y": "2D & 3D operator to move canvas up/down in pixels per frame", + "Translation Z": "3D operator to move canvas towards/away from view [speed set by FOV]", + "Rotation 3D X": "3D operator to tilt canvas up/down in degrees per frame", + "Rotation 3D Y": "3D operator to pan canvas left/right in degrees per frame", + "Rotation 3D Z": "3D operator to roll canvas clockwise/anticlockwise", + "Enable perspective flip": "enables 2D mode functions to simulate faux 3D movement", + "Perspective flip theta": "the roll effect angle", + "Perspective flip phi": "the tilt effect angle", + "Perspective flip gamma": "the pan effect angle", + "Perspective flip fv": "the 2D vanishing point of perspective (recommended range 30-160)", + "Noise schedule": "amount of graininess to add per frame for diffusion diversity", + "Strength schedule": "amount of presence of previous frame to influence next frame, also controls steps in the following formula [steps - (strength_schedule * steps)]", + "Sampler schedule": "controls which sampler to use at a specific scheduled frame", + "Contrast schedule": "adjusts the overall contrast per frame [default neutral at 1.0]", + "CFG scale schedule": "how closely the image should conform to the prompt. Lower values produce more creative results. (recommended range 5-15)", + "FOV schedule": "adjusts the scale at which the canvas is moved in 3D by the translation_z value. [maximum range -180 to +180, with 0 being undefined. Values closer to 180 will make the image have less depth, while values closer to 0 will allow more depth]", + //"near_schedule": "", + //"far_schedule": "", + "Seed schedule": "allows you to specify seeds at a specific schedule, if seed_behavior is set to schedule.", + "Color coherence": "The color coherence will attempt to sample the overall pixel color information, and trend those values analyzed in the first frame to be applied to future frames.", + // "None": "Disable color coherence", + "Match Frame 0 HSV": "HSV is a good method for balancing presence of vibrant colors, but may produce unrealistic results - (ie.blue apples)", + "Match Frame 0 LAB": "LAB is a more linear approach to mimic human perception of color space - a good default setting for most users.", + "Match Frame 0 RGB": "RGB is good for enforcing unbiased amounts of color in each red, green and blue channel - some images may yield colorized artifacts if sampling is too low.", + "Cadence": "A setting of 1 will cause every frame to receive diffusion in the sequence of image outputs. A setting of 2 will only diffuse on every other frame, yet motion will still be in effect. The output of images during the cadence sequence will be automatically blended, additively and saved to the specified drive. This may improve the illusion of coherence in some workflows as the content and context of an image will not change or diffuse during frames that were skipped. Higher values of 4-8 cadence will skip over a larger amount of frames and only diffuse the “Nth” frame as set by the diffusion_cadence value. This may produce more continuity in an animation, at the cost of little opportunity to add more diffused content. In extreme examples, motion within a frame will fail to produce diverse prompt context, and the space will be filled with lines or approximations of content - resulting in unexpected animation patterns and artifacts. Video Input & Interpolation modes are not affected by diffusion_cadence.", + "Noise type": "Selects the type of noise being added to each frame", + "uniform": "Uniform noise covers the entire frame. It somewhat flattens and sharpens the video over time, but may be good for cartoonish look. This is the old default setting.", + "perlin": "Perlin noise is a more natural looking noise. It is heterogeneous and less sharp than uniform noise, this way it is more likely that new details will appear in a more coherent way. This is the new default setting.", + "Perlin W": "The width of the Perlin sample. Lower values will make larger noise regions. Think of it as inverse brush stroke width. The greater this setting, the smaller details it will affect.", + "Perlin H": "The height of the Perlin sample. Lower values will make larger noise regions. Think of it as inverse brush stroke width. The greater this setting, the smaller details it will affect.", + "Perlin octaves": "The number of Perlin noise octaves, that is the count of P-noise iterations. Higher values will make the noise more soft and smoke-like, whereas lower values will make it look more organic and spotty. It is limited by 8 octaves as the resulting gain will run out of bounds.", + "Perlin persistence": "How much of noise from each octave is added on each iteration. Higher values will make it more straighter and sharper, while lower values will make it rounder and smoother. It is limited by 1.0 as the resulting gain fill the frame completely with noise.", + "Use depth warping": "enables instructions to warp an image dynamically in 3D mode only.", + "MiDaS weight": "sets a midpoint at which a depthmap is to be drawn: range [-1 to +1]", + "Padding mode": "instructs the handling of pixels outside the field of view as they come into the scene.", + //"border": "Border will attempt to use the edges of the canvas as the pixels to be drawn", //duplicate name as another property + "reflection": "reflection will attempt to approximate the image and tile/repeat pixels", + "zeros": "zeros will not add any new pixel information", + "sampling_mode": "choose from Bicubic, Bilinear or Nearest modes. (Recommended: Bicubic)", + "Save depth maps": "will output a greyscale depth map image alongside the output images.", + + // Prompts + "Prompts": "prompts for your animation in a JSON format. Use --neg words to add 'words' as negative prompt", + "Prompts positive": "positive prompt to be appended to *all* prompts", + "Prompts negative": "negative prompt to be appended to *all* prompts. DON'T use --neg here!", + + //Init + "Use init": "Diffuse the first frame based on an image, similar to img2img.", + "Strength": "Controls the strength of the diffusion on the init image. 0 = disabled", + "Strength 0 no init": "Set the strength to 0 automatically when no init image is used", + "Init image": "the path to your init image", + "Use mask": "Use a grayscale image as a mask on your init image. Whiter areas of the mask are areas that change more.", + "Use alpha as mask": "use the alpha channel of the init image as the mask", + "Mask file": "the path to your mask image", + "Invert mask": "Inverts the colors of the mask", + "Mask brightness adjust": "adjust the brightness of the mask. Should be a positive number, with 1.0 meaning no adjustment.", + "Mask contrast adjust": "adjust the brightness of the mask. Should be a positive number, with 1.0 meaning no adjustment.", + "overlay mask": "Overlay the masked image at the end of the generation so it does not get degraded by encoding and decoding", + "Mask overlay blur": "Blur edges of final overlay mask, if used. Minimum = 0 (no blur)", + "Video init path": "the directory \/ URL at which your video file is located for Video Input mode only", + "Extract nth frame": "during the run sequence, only frames specified by this value will be extracted, saved, and diffused upon. A value of 1 indicates that every frame is to be accounted for. Values of 2 will use every other frame for the sequence. Higher values will skip that number of frames respectively.", + "Extract from frame":"start extracting the input video only from this frame number", + "Extract to frame": "stop the extraction of the video at this frame number. -1 for no limits", + "Overwrite extracted frames": "when enabled, will re-extract video frames each run. When using video_input mode, the run will be instructed to write video frames to the drive. If you’ve already populated the frames needed, uncheck this box to skip past redundant extraction, and immediately start the render. If you have not extracted frames, you must run at least once with this box checked to write the necessary frames.", + "Use mask video": "video_input mode only, enables the extraction and use of a separate video file intended for use as a mask. White areas of the extracted video frames will not be affected by diffusion, while black areas will be fully effected. Lighter/darker areas are affected dynamically.", + "Video mask path": "the directory in which your mask video is located.", + "Interpolate key frames": "selects whether to ignore prompt schedule or _x_frames.", + "Interpolate x frames": "the number of frames to transition thru between prompts (when interpolate_key_frames = true, then the numbers in front of the animation prompts will dynamically guide the images based on their value. If set to false, will ignore the prompt numbers and force interpole_x_frames value regardless of prompt number)", + "Resume from timestring": "instructs the run to start from a specified point", + "Resume timestring": "the required timestamp to reference when resuming. Currently only available in 2D & 3D mode, the timestamp is saved as the settings .txt file name as well as images produced during your previous run. The format follows: yyyymmddhhmmss - a timestamp of when the run was started to diffuse.", + + //Video Output + "Skip video for run all": "when checked, do not output a video", + "Make GIF": "create a gif in addition to .mp4 file. supports up to 30 fps, will self-disable at higher fps values", + "Upscale":"upscale the images of the next run once it's finished + make a video out of them", + "Upscale model":"model of the upscaler to use. 'realesr-animevideov3' is much faster but yields smoother, less detailed results. the other models only do x4", + "Upscale factor":"how many times to upscale, actual options depend on the chosen upscale model", + "FPS": "The frames per second that the video will run at", + "Output format": "select the type of video file to output", + "PIL gif": "create an animated GIF", + "FFMPEG mp4": "create an MP4 video file", + "FFmpeg location": "the path to where ffmpeg is located. Leave at default 'ffmpeg' if ffmpeg is in your PATH!", + "FFmpeg crf": "controls quality where lower is better, less compressed. values: 0 to 51, default 17", + "FFmpeg preset": "controls how good the compression is, and the operation speed. If you're not in a rush keep it at 'veryslow'", + "Add soundtrack": "when this box is checked, and FFMPEG mp4 is selected as the output format, an audio file will be multiplexed with the video.", + "Soundtrack path": "the path\/ URL to an audio file to accompany the video", + "Use manual settings": "when this is unchecked, the video will automatically be created in the same output folder as the images. Check this box to specify different settings for the creation of the video, specified by the following options", + "Render steps": "render each step of diffusion as a separate frame", + "Max video frames": "the maximum number of frames to include in the video, when use_manual_settings is checked", + //"path_name_modifier": "", + "Image path": "the location of images to create the video from, when use_manual_settings is checked", + "MP4 path": "the output location of the mp4 file, when use_manual_settings is checked", + "Engine": "choose the frame interpolation engine and version", + "Interp X":"how many times to interpolate the source video. e.g source video fps of 12 and a value of x2 will yield a 24fps interpolated video", + "Slow-Mo X":"how many times to slow-down the video. *Naturally affects output fps as well", + "Keep Imgs": "delete or keep raw affected (interpolated/ upscaled depending on the UI section) png imgs", + "Interpolate an existing video":"This feature allows you to interpolate any video with a dedicated button. Video could be completly unrelated to deforum", + "In Frame Count": "uploaded video total frame count", + "In FPS":"uploaded video FPS", + "Interpolated Vid FPS":"calculated output-interpolated video FPS", + "In Res":"uploaded video resolution", + "Out Res":"output video resolution", + + // Looper Args + // "use_looper": "", + "Enable guided images mode": "check this box to enable guided images mode", + "Images to use for keyframe guidance": "images you iterate over, you can do local or web paths (no single backslashes!)", + "Image strength schedule": "how much the image should look like the previou one and new image frame init. strength schedule might be better if this is higher, around .75 during the keyfames you want to switch on", + "Blend factor max": "blendFactor = blendFactorMax - blendFactorSlope * cos((frame % tweening_frames_schedule) / (tweening_frames_schedule / 2))", + "Blend factor slope": "blendFactor = blendFactorMax - blendFactorSlope * cos((frame % tweening_frames_schedule) / (tweening_frames_schedule / 2))", + "Tweening frames schedule": "number of the frames that we will blend between current imagined image and input frame image", + "Color correction factor": "how close to get to the colors of the input frame image/ the amount each frame during a tweening step to use the new images colors" +} + + +onUiUpdate(function(){ + gradioApp().querySelectorAll('span, button, select, p').forEach(function(span){ + tooltip = deforum_titles[span.textContent]; + + if(!tooltip){ + tooltip = deforum_titles[span.value]; + } + + if(!tooltip){ + for (const c of span.classList) { + if (c in deforum_titles) { + tooltip = deforum_titles[c]; + break; + } + } + } + + if(tooltip){ + span.title = tooltip; + } + }) + + gradioApp().querySelectorAll('select').forEach(function(select){ + if (select.onchange != null) return; + + select.onchange = function(){ + select.title = deforum_titles[select.value] || ""; + } + }) +}) \ No newline at end of file diff --git a/extensions/deforum/javascript/deforum.js b/extensions/deforum/javascript/deforum.js new file mode 100644 index 0000000000000000000000000000000000000000..889e76f39c937d9eb3b602aa5510d8ac637f5e3c --- /dev/null +++ b/extensions/deforum/javascript/deforum.js @@ -0,0 +1,21 @@ +function submit_deforum(){ + // alert('Hello, Deforum!') + rememberGallerySelection('deforum_gallery') + showSubmitButtons('deforum', false) + + var id = randomId() + requestProgress(id, gradioApp().getElementById('deforum_gallery_container'), gradioApp().getElementById('deforum_gallery'), function(){ + showSubmitButtons('deforum', true) + }) + + var res = create_submit_args(arguments) + + res[0] = id + // res[1] = get_tab_index('deforum') + + return res +} + +onUiUpdate(function(){ + check_gallery('deforum_gallery') +}) diff --git a/extensions/deforum/requirements.txt b/extensions/deforum/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..0c9d5f4ea9c75368bd75aa3804a7b9aea47254b2 --- /dev/null +++ b/extensions/deforum/requirements.txt @@ -0,0 +1,7 @@ +numexpr +matplotlib +pandas +av +pims +imageio_ffmpeg +rich \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum.py b/extensions/deforum/scripts/deforum.py new file mode 100644 index 0000000000000000000000000000000000000000..50c188c2475f58572540f615d957f8d28d3f019d --- /dev/null +++ b/extensions/deforum/scripts/deforum.py @@ -0,0 +1,318 @@ +# Detach 'deforum_helpers' from 'scripts' to prevent "No module named 'scripts.deforum_helpers'" error +# causing Deforum's tab not show up in some cases when you've might've broken the environment with webui packages updates +import sys, os, shutil + +basedirs = [os.getcwd()] +if 'google.colab' in sys.modules: + basedirs.append('/content/gdrive/MyDrive/sd/stable-diffusion-webui') #hardcode as TheLastBen's colab seems to be the primal source + +for basedir in basedirs: + deforum_paths_to_ensure = [basedir + '/extensions/deforum-for-automatic1111-webui/scripts', basedir + '/extensions/sd-webui-controlnet', basedir + '/extensions/deforum/scripts', basedir + '/scripts/deforum_helpers/src', basedir + '/extensions/deforum/scripts/deforum_helpers/src', basedir +'/extensions/deforum-for-automatic1111-webui/scripts/deforum_helpers/src',basedir] + + for deforum_scripts_path_fix in deforum_paths_to_ensure: + if not deforum_scripts_path_fix in sys.path: + sys.path.extend([deforum_scripts_path_fix]) + +# Main deforum stuff +import deforum_helpers.args as deforum_args +import deforum_helpers.settings as deforum_settings +from deforum_helpers.save_images import dump_frames_cache, reset_frames_cache +from deforum_helpers.frame_interpolation import process_video_interpolation + +import modules.scripts as wscripts +from modules import script_callbacks +import gradio as gr +import json + +from modules.processing import Processed, StableDiffusionProcessingImg2Img, process_images +from PIL import Image +from deforum_helpers.video_audio_utilities import ffmpeg_stitch_video, make_gifski_gif +from deforum_helpers.upscaling import make_upscale_v2 +import gc +import torch +from webui import wrap_gradio_gpu_call +import modules.shared as shared +from modules.shared import opts, cmd_opts, state +from modules.ui import create_output_panel, plaintext_to_html, wrap_gradio_call +from types import SimpleNamespace + +def run_deforum(*args, **kwargs): + args_dict = {deforum_args.component_names[i]: args[i+2] for i in range(0, len(deforum_args.component_names))} + p = StableDiffusionProcessingImg2Img( + sd_model=shared.sd_model, + outpath_samples = opts.outdir_samples or opts.outdir_img2img_samples, + outpath_grids = opts.outdir_grids or opts.outdir_img2img_grids, + #we'll setup the rest later + ) + + print("\033[4;33mDeforum extension for auto1111 webui, v2.2b\033[0m") + args_dict['self'] = None + args_dict['p'] = p + + root, args, anim_args, video_args, parseq_args, loop_args, controlnet_args = deforum_args.process_args(args_dict) + root.clipseg_model = None + root.initial_clipskip = opts.data["CLIP_stop_at_last_layers"] + root.basedirs = basedirs + + for basedir in basedirs: + sys.path.extend([ + basedir + '/scripts/deforum_helpers/src', + basedir + '/extensions/deforum/scripts/deforum_helpers/src', + basedir + '/extensions/deforum-for-automatic1111-webui/scripts/deforum_helpers/src', + ]) + + # clean up unused memory + reset_frames_cache(root) + gc.collect() + torch.cuda.empty_cache() + + from deforum_helpers.render import render_animation + from deforum_helpers.render_modes import render_input_video, render_animation_with_video_mask, render_interpolation + + tqdm_backup = shared.total_tqdm + shared.total_tqdm = deforum_settings.DeforumTQDM(args, anim_args, parseq_args) + try: + # dispatch to appropriate renderer + if anim_args.animation_mode == '2D' or anim_args.animation_mode == '3D': + if anim_args.use_mask_video: + render_animation_with_video_mask(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, root.animation_prompts, root) # allow mask video without an input video + else: + render_animation(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, root.animation_prompts, root) + elif anim_args.animation_mode == 'Video Input': + render_input_video(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, root.animation_prompts, root)#TODO: prettify code + elif anim_args.animation_mode == 'Interpolation': + render_interpolation(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, root.animation_prompts, root) + else: + print('Other modes are not available yet!') + finally: + shared.total_tqdm = tqdm_backup + opts.data["CLIP_stop_at_last_layers"] = root.initial_clipskip + + if video_args.store_frames_in_ram: + dump_frames_cache(root) + + from base64 import b64encode + + real_audio_track = None + if video_args.add_soundtrack != 'None': + real_audio_track = anim_args.video_init_path if video_args.add_soundtrack == 'Init Video' else video_args.soundtrack_path + + # Delete folder with duplicated imgs from OS temp folder + shutil.rmtree(root.tmp_deforum_run_duplicated_folder, ignore_errors=True) + + # Decide whether or not we need to try and frame interpolate laters + need_to_frame_interpolate = False + if video_args.frame_interpolation_engine != "None" and not video_args.skip_video_for_run_all and not video_args.store_frames_in_ram: + need_to_frame_interpolate = True + + if video_args.skip_video_for_run_all: + print('Skipping video creation, uncheck skip_video_for_run_all if you want to run it') + else: + import subprocess + + path_name_modifier = video_args.path_name_modifier + if video_args.render_steps: # render steps from a single image + fname = f"{path_name_modifier}_%05d.png" + all_step_dirs = [os.path.join(args.outdir, d) for d in os.listdir(args.outdir) if os.path.isdir(os.path.join(args.outdir,d))] + newest_dir = max(all_step_dirs, key=os.path.getmtime) + image_path = os.path.join(newest_dir, fname) + print(f"Reading images from {image_path}") + mp4_path = os.path.join(newest_dir, f"{args.timestring}_{path_name_modifier}.mp4") + max_video_frames = args.steps + else: # render images for a video + image_path = os.path.join(args.outdir, f"{args.timestring}_%05d.png") + mp4_path = os.path.join(args.outdir, f"{args.timestring}.mp4") + max_video_frames = anim_args.max_frames + + exclude_keys = deforum_settings.get_keys_to_exclude('video') + video_settings_filename = os.path.join(args.outdir, f"{args.timestring}_video-settings.txt") + with open(video_settings_filename, "w+", encoding="utf-8") as f: + s = {} + for key, value in dict(video_args.__dict__).items(): + if key not in exclude_keys: + s[key] = value + json.dump(s, f, ensure_ascii=False, indent=4) + + # Stitch video using ffmpeg! + try: + ffmpeg_stitch_video(ffmpeg_location=video_args.ffmpeg_location, fps=video_args.fps, outmp4_path=mp4_path, stitch_from_frame=0, stitch_to_frame=max_video_frames, imgs_path=image_path, add_soundtrack=video_args.add_soundtrack, audio_path=real_audio_track, crf=video_args.ffmpeg_crf, preset=video_args.ffmpeg_preset) + mp4 = open(mp4_path,'rb').read() + data_url = "data:video/mp4;base64," + b64encode(mp4).decode() + deforum_args.i1_store = f'

Deforum v0.5-webui-beta

' + except Exception as e: + if need_to_frame_interpolate: + print(f"FFMPEG DID NOT STITCH ANY VIDEO. However, you requested to frame interpolate - so we will continue to frame interpolation, but you'll be left only with the interpolated frames and not a video, since ffmpeg couldn't run. Original ffmpeg error: {e}") + else: + print(f"** FFMPEG DID NOT STITCH ANY VIDEO ** Error: {e}") + pass + + if root.initial_info is None: + root.initial_info = "An error has occured and nothing has been generated!" + root.initial_info += "\nPlease, report the bug to https://github.com/deforum-art/deforum-for-automatic1111-webui/issues" + import numpy as np + a = np.random.rand(args.W, args.H, 3)*255 + root.first_frame = Image.fromarray(a.astype('uint8')).convert('RGB') + root.initial_seed = 6934 + # FRAME INTERPOLATION TIME + if need_to_frame_interpolate: + print(f"Got a request to *frame interpolate* using {video_args.frame_interpolation_engine}") + process_video_interpolation(frame_interpolation_engine=video_args.frame_interpolation_engine, frame_interpolation_x_amount=video_args.frame_interpolation_x_amount,frame_interpolation_slow_mo_enabled=video_args.frame_interpolation_slow_mo_enabled, frame_interpolation_slow_mo_amount=video_args.frame_interpolation_slow_mo_amount, orig_vid_fps=video_args.fps, deforum_models_path=root.models_path, real_audio_track=real_audio_track, raw_output_imgs_path=args.outdir, img_batch_id=args.timestring, ffmpeg_location=video_args.ffmpeg_location, ffmpeg_crf=video_args.ffmpeg_crf, ffmpeg_preset=video_args.ffmpeg_preset, keep_interp_imgs=video_args.frame_interpolation_keep_imgs, orig_vid_name=None, resolution=None) + + if video_args.make_gif and not video_args.skip_video_for_run_all and not video_args.store_frames_in_ram: + make_gifski_gif(imgs_raw_path = args.outdir, imgs_batch_id = args.timestring, fps = video_args.fps, models_folder = root.models_path, current_user_os = root.current_user_os) + + # Upscale video once generation is done: + if video_args.r_upscale_video and not video_args.skip_video_for_run_all and not video_args.store_frames_in_ram: + + # out mp4 path is defined in make_upscale func + make_upscale_v2(upscale_factor = video_args.r_upscale_factor, upscale_model = video_args.r_upscale_model, keep_imgs = video_args.r_upscale_keep_imgs, imgs_raw_path = args.outdir, imgs_batch_id = args.timestring, fps = video_args.fps, deforum_models_path = root.models_path, current_user_os = root.current_user_os, ffmpeg_location=video_args.ffmpeg_location, stitch_from_frame=0, stitch_to_frame=max_video_frames, ffmpeg_crf=video_args.ffmpeg_crf, ffmpeg_preset=video_args.ffmpeg_preset, add_soundtrack = video_args.add_soundtrack ,audio_path=real_audio_track) + + root.initial_info += "\n The animation is stored in " + args.outdir + root.initial_info += "\n Timestring = " + args.timestring + '\n' + root.initial_info += "Only the first frame is shown in webui not to clutter the memory" + reset_frames_cache(root) # cleanup the RAM in any case + processed = Processed(p, [root.first_frame], root.initial_seed, root.initial_info) + + if processed is None: + processed = process_images(p) + + shared.total_tqdm.clear() + + generation_info_js = processed.js() + if opts.samples_log_stdout: + print(generation_info_js) + + if opts.do_not_show_images: + processed.images = [] + + return processed.images, generation_info_js, plaintext_to_html(processed.info), plaintext_to_html('') + +def on_ui_tabs(): + with gr.Blocks(analytics_enabled=False) as deforum_interface: + components = {} + dummy_component = gr.Label(visible=False) + with gr.Row(elem_id='deforum_progress_row').style(equal_height=False): + with gr.Column(scale=1, variant='panel'): + components = deforum_args.setup_deforum_setting_dictionary(None, True, True) + + with gr.Column(scale=1): + with gr.Row(): + btn = gr.Button("Click here after the generation to show the video") + components['btn'] = btn + close_btn = gr.Button("Close the video", visible=False) + with gr.Row(): + i1 = gr.HTML(deforum_args.i1_store, elem_id='deforum_header') + components['i1'] = i1 + # Show video + def show_vid(): + return { + i1: gr.update(value=deforum_args.i1_store, visible=True), + close_btn: gr.update(visible=True), + btn: gr.update(value="Update the video", visible=True), + } + + btn.click( + show_vid, + [], + [i1, close_btn, btn], + ) + # Close video + def close_vid(): + return { + i1: gr.update(value=deforum_args.i1_store_backup, visible=True), + close_btn: gr.update(visible=False), + btn: gr.update(value="Click here after the generation to show the video", visible=True), + } + + close_btn.click( + close_vid, + [], + [i1, close_btn, btn], + ) + id_part = 'deforum' + with gr.Row(elem_id=f"{id_part}_generate_box"): + skip = gr.Button('Skip', elem_id=f"{id_part}_skip", visible=False) + interrupt = gr.Button('Interrupt', elem_id=f"{id_part}_interrupt", visible=True) + submit = gr.Button('Generate', elem_id=f"{id_part}_generate", variant='primary') + + skip.click( + fn=lambda: state.skip(), + inputs=[], + outputs=[], + ) + + interrupt.click( + fn=lambda: state.interrupt(), + inputs=[], + outputs=[], + ) + + deforum_gallery, generation_info, html_info, html_log = create_output_panel("deforum", opts.outdir_img2img_samples) + + gr.HTML("

* Paths can be relative to webui folder OR full - absolute

") + with gr.Row(): + settings_path = gr.Textbox("deforum_settings.txt", elem_id='deforum_settings_path', label="General Settings File") + #reuse_latest_settings_btn = gr.Button('Reuse Latest', elem_id='deforum_reuse_latest_settings_btn')#TODO + with gr.Row(): + save_settings_btn = gr.Button('Save Settings', elem_id='deforum_save_settings_btn') + load_settings_btn = gr.Button('Load Settings', elem_id='deforum_load_settings_btn') + with gr.Row(): + video_settings_path = gr.Textbox("deforum_video-settings.txt", elem_id='deforum_video_settings_path', label="Video Settings File") + #reuse_latest_video_settings_btn = gr.Button('Reuse Latest', elem_id='deforum_reuse_latest_video_settings_btn')#TODO + with gr.Row(): + save_video_settings_btn = gr.Button('Save Video Settings', elem_id='deforum_save_video_settings_btn') + load_video_settings_btn = gr.Button('Load Video Settings', elem_id='deforum_load_video_settings_btn') + + # components['prompts'].visible = False#hide prompts for the time being + #TODO clean up the code + components['save_sample_per_step'].visible = False + components['show_sample_per_step'].visible = False + components['display_samples'].visible = False + + component_list = [components[name] for name in deforum_args.component_names] + + submit.click( + fn=wrap_gradio_gpu_call(run_deforum, extra_outputs=[None, '', '']), + _js="submit_deforum", + inputs=[dummy_component, dummy_component] + component_list, + outputs=[ + deforum_gallery, + generation_info, + html_info, + html_log, + ], + ) + + settings_component_list = [components[name] for name in deforum_args.settings_component_names] + video_settings_component_list = [components[name] for name in deforum_args.video_args_names] + stuff = gr.HTML("") # wrap gradio call garbage + stuff.visible = False + + save_settings_btn.click( + fn=wrap_gradio_call(deforum_settings.save_settings), + inputs=[settings_path] + settings_component_list, + outputs=[stuff], + ) + + load_settings_btn.click( + fn=wrap_gradio_call(deforum_settings.load_settings), + inputs=[settings_path]+ settings_component_list, + outputs=settings_component_list + [stuff], + ) + + save_video_settings_btn.click( + fn=wrap_gradio_call(deforum_settings.save_video_settings), + inputs=[video_settings_path] + video_settings_component_list, + outputs=[stuff], + ) + + load_video_settings_btn.click( + fn=wrap_gradio_call(deforum_settings.load_video_settings), + inputs=[video_settings_path] + video_settings_component_list, + outputs=video_settings_component_list + [stuff], + ) + + + return [(deforum_interface, "Deforum", "deforum_interface")] + +script_callbacks.on_ui_tabs(on_ui_tabs) diff --git a/extensions/deforum/scripts/deforum_helpers/__init__.py b/extensions/deforum/scripts/deforum_helpers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe08549e9c92f0e8a7bc96cead3277dedd12583c --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/__init__.py @@ -0,0 +1,7 @@ +""" +from .save_images import save_samples, get_output_folder +from .depth import DepthModel +from .prompt import sanitize +from .animation import construct_RotationMatrixHomogenous, getRotationMatrixManual, getPoints_for_PerspectiveTranformEstimation, warpMatrix, anim_frame_warp_2d, anim_frame_warp_3d +from .generate import add_noise, load_img, load_mask_latent, prepare_mask +""" \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/animation.py b/extensions/deforum/scripts/deforum_helpers/animation.py new file mode 100644 index 0000000000000000000000000000000000000000..ccb6dbd206b09ada3627e89398655964fdd72845 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/animation.py @@ -0,0 +1,258 @@ +import numpy as np +import cv2 +from functools import reduce +import math +import py3d_tools as p3d +import torch +from einops import rearrange +from .prompt import check_is_number + +# Webui +from modules.shared import state + +def sample_from_cv2(sample: np.ndarray) -> torch.Tensor: + sample = ((sample.astype(float) / 255.0) * 2) - 1 + sample = sample[None].transpose(0, 3, 1, 2).astype(np.float16) + sample = torch.from_numpy(sample) + return sample + +def sample_to_cv2(sample: torch.Tensor, type=np.uint8) -> np.ndarray: + sample_f32 = rearrange(sample.squeeze().cpu().numpy(), "c h w -> h w c").astype(np.float32) + sample_f32 = ((sample_f32 * 0.5) + 0.5).clip(0, 1) + sample_int8 = (sample_f32 * 255) + return sample_int8.astype(type) + +def construct_RotationMatrixHomogenous(rotation_angles): + assert(type(rotation_angles)==list and len(rotation_angles)==3) + RH = np.eye(4,4) + cv2.Rodrigues(np.array(rotation_angles), RH[0:3, 0:3]) + return RH + +# https://en.wikipedia.org/wiki/Rotation_matrix +def getRotationMatrixManual(rotation_angles): + + rotation_angles = [np.deg2rad(x) for x in rotation_angles] + + phi = rotation_angles[0] # around x + gamma = rotation_angles[1] # around y + theta = rotation_angles[2] # around z + + # X rotation + Rphi = np.eye(4,4) + sp = np.sin(phi) + cp = np.cos(phi) + Rphi[1,1] = cp + Rphi[2,2] = Rphi[1,1] + Rphi[1,2] = -sp + Rphi[2,1] = sp + + # Y rotation + Rgamma = np.eye(4,4) + sg = np.sin(gamma) + cg = np.cos(gamma) + Rgamma[0,0] = cg + Rgamma[2,2] = Rgamma[0,0] + Rgamma[0,2] = sg + Rgamma[2,0] = -sg + + # Z rotation (in-image-plane) + Rtheta = np.eye(4,4) + st = np.sin(theta) + ct = np.cos(theta) + Rtheta[0,0] = ct + Rtheta[1,1] = Rtheta[0,0] + Rtheta[0,1] = -st + Rtheta[1,0] = st + + R = reduce(lambda x,y : np.matmul(x,y), [Rphi, Rgamma, Rtheta]) + + return R + +def getPoints_for_PerspectiveTranformEstimation(ptsIn, ptsOut, W, H, sidelength): + + ptsIn2D = ptsIn[0,:] + ptsOut2D = ptsOut[0,:] + ptsOut2Dlist = [] + ptsIn2Dlist = [] + + for i in range(0,4): + ptsOut2Dlist.append([ptsOut2D[i,0], ptsOut2D[i,1]]) + ptsIn2Dlist.append([ptsIn2D[i,0], ptsIn2D[i,1]]) + + pin = np.array(ptsIn2Dlist) + [W/2.,H/2.] + pout = (np.array(ptsOut2Dlist) + [1.,1.]) * (0.5*sidelength) + pin = pin.astype(np.float32) + pout = pout.astype(np.float32) + + return pin, pout + + +def warpMatrix(W, H, theta, phi, gamma, scale, fV): + + # M is to be estimated + M = np.eye(4, 4) + + fVhalf = np.deg2rad(fV/2.) + d = np.sqrt(W*W+H*H) + sideLength = scale*d/np.cos(fVhalf) + h = d/(2.0*np.sin(fVhalf)) + n = h-(d/2.0) + f = h+(d/2.0) + + # Translation along Z-axis by -h + T = np.eye(4,4) + T[2,3] = -h + + # Rotation matrices around x,y,z + R = getRotationMatrixManual([phi, gamma, theta]) + + + # Projection Matrix + P = np.eye(4,4) + P[0,0] = 1.0/np.tan(fVhalf) + P[1,1] = P[0,0] + P[2,2] = -(f+n)/(f-n) + P[2,3] = -(2.0*f*n)/(f-n) + P[3,2] = -1.0 + + # pythonic matrix multiplication + F = reduce(lambda x,y : np.matmul(x,y), [P, T, R]) + + # shape should be 1,4,3 for ptsIn and ptsOut since perspectiveTransform() expects data in this way. + # In C++, this can be achieved by Mat ptsIn(1,4,CV_64FC3); + ptsIn = np.array([[ + [-W/2., H/2., 0.],[ W/2., H/2., 0.],[ W/2.,-H/2., 0.],[-W/2.,-H/2., 0.] + ]]) + ptsOut = np.array(np.zeros((ptsIn.shape), dtype=ptsIn.dtype)) + ptsOut = cv2.perspectiveTransform(ptsIn, F) + + ptsInPt2f, ptsOutPt2f = getPoints_for_PerspectiveTranformEstimation(ptsIn, ptsOut, W, H, sideLength) + + # check float32 otherwise OpenCV throws an error + assert(ptsInPt2f.dtype == np.float32) + assert(ptsOutPt2f.dtype == np.float32) + M33 = cv2.getPerspectiveTransform(ptsInPt2f,ptsOutPt2f) + + return M33, sideLength + +def get_flip_perspective_matrix(W, H, keys, frame_idx): + perspective_flip_theta = keys.perspective_flip_theta_series[frame_idx] + perspective_flip_phi = keys.perspective_flip_phi_series[frame_idx] + perspective_flip_gamma = keys.perspective_flip_gamma_series[frame_idx] + perspective_flip_fv = keys.perspective_flip_fv_series[frame_idx] + M,sl = warpMatrix(W, H, perspective_flip_theta, perspective_flip_phi, perspective_flip_gamma, 1., perspective_flip_fv); + post_trans_mat = np.float32([[1, 0, (W-sl)/2], [0, 1, (H-sl)/2]]) + post_trans_mat = np.vstack([post_trans_mat, [0,0,1]]) + bM = np.matmul(M, post_trans_mat) + return bM + +def flip_3d_perspective(anim_args, prev_img_cv2, keys, frame_idx): + W, H = (prev_img_cv2.shape[1], prev_img_cv2.shape[0]) + return cv2.warpPerspective( + prev_img_cv2, + get_flip_perspective_matrix(W, H, keys, frame_idx), + (W, H), + borderMode=cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE + ) + +def anim_frame_warp(prev_img_cv2, args, anim_args, keys, frame_idx, depth_model=None, depth=None, device='cuda', half_precision = False): + + if anim_args.use_depth_warping: + if depth is None and depth_model is not None: + depth = depth_model.predict(prev_img_cv2, anim_args, half_precision) + else: + depth = None + + if anim_args.animation_mode == '2D': + prev_img = anim_frame_warp_2d(prev_img_cv2, args, anim_args, keys, frame_idx) + else: # '3D' + prev_img = anim_frame_warp_3d(device, prev_img_cv2, depth, anim_args, keys, frame_idx) + + return prev_img, depth + +def anim_frame_warp_2d(prev_img_cv2, args, anim_args, keys, frame_idx): + angle = keys.angle_series[frame_idx] + zoom = keys.zoom_series[frame_idx] + translation_x = keys.translation_x_series[frame_idx] + translation_y = keys.translation_y_series[frame_idx] + + center = (args.W // 2, args.H // 2) + trans_mat = np.float32([[1, 0, translation_x], [0, 1, translation_y]]) + rot_mat = cv2.getRotationMatrix2D(center, angle, zoom) + trans_mat = np.vstack([trans_mat, [0,0,1]]) + rot_mat = np.vstack([rot_mat, [0,0,1]]) + if anim_args.enable_perspective_flip: + bM = get_flip_perspective_matrix(args.W, args.H, keys, frame_idx) + rot_mat = np.matmul(bM, rot_mat, trans_mat) + else: + rot_mat = np.matmul(rot_mat, trans_mat) + return cv2.warpPerspective( + prev_img_cv2, + rot_mat, + (prev_img_cv2.shape[1], prev_img_cv2.shape[0]), + borderMode=cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE + ) + +def anim_frame_warp_3d(device, prev_img_cv2, depth, anim_args, keys, frame_idx): + TRANSLATION_SCALE = 1.0/200.0 # matches Disco + translate_xyz = [ + -keys.translation_x_series[frame_idx] * TRANSLATION_SCALE, + keys.translation_y_series[frame_idx] * TRANSLATION_SCALE, + -keys.translation_z_series[frame_idx] * TRANSLATION_SCALE + ] + rotate_xyz = [ + math.radians(keys.rotation_3d_x_series[frame_idx]), + math.radians(keys.rotation_3d_y_series[frame_idx]), + math.radians(keys.rotation_3d_z_series[frame_idx]) + ] + if anim_args.enable_perspective_flip: + prev_img_cv2 = flip_3d_perspective(anim_args, prev_img_cv2, keys, frame_idx) + rot_mat = p3d.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0) + result = transform_image_3d(device if not device.type.startswith('mps') else torch.device('cpu'), prev_img_cv2, depth, rot_mat, translate_xyz, anim_args, keys, frame_idx) + torch.cuda.empty_cache() + return result + +def transform_image_3d(device, prev_img_cv2, depth_tensor, rot_mat, translate, anim_args, keys, frame_idx): + # adapted and optimized version of transform_image_3d from Disco Diffusion https://github.com/alembics/disco-diffusion + w, h = prev_img_cv2.shape[1], prev_img_cv2.shape[0] + + aspect_ratio = float(w)/float(h) + near = keys.near_series[frame_idx] + far = keys.far_series[frame_idx] + fov_deg = keys.fov_series[frame_idx] + persp_cam_old = p3d.FoVPerspectiveCameras(near, far, aspect_ratio, fov=fov_deg, degrees=True, device=device) + persp_cam_new = p3d.FoVPerspectiveCameras(near, far, aspect_ratio, fov=fov_deg, degrees=True, R=rot_mat, T=torch.tensor([translate]), device=device) + + # range of [-1,1] is important to torch grid_sample's padding handling + y,x = torch.meshgrid(torch.linspace(-1.,1.,h,dtype=torch.float32,device=device),torch.linspace(-1.,1.,w,dtype=torch.float32,device=device)) + if depth_tensor is None: + z = torch.ones_like(x) + else: + z = torch.as_tensor(depth_tensor, dtype=torch.float32, device=device) + xyz_old_world = torch.stack((x.flatten(), y.flatten(), z.flatten()), dim=1) + + xyz_old_cam_xy = persp_cam_old.get_full_projection_transform().transform_points(xyz_old_world)[:,0:2] + xyz_new_cam_xy = persp_cam_new.get_full_projection_transform().transform_points(xyz_old_world)[:,0:2] + + offset_xy = xyz_new_cam_xy - xyz_old_cam_xy + # affine_grid theta param expects a batch of 2D mats. Each is 2x3 to do rotation+translation. + identity_2d_batch = torch.tensor([[1.,0.,0.],[0.,1.,0.]], device=device).unsqueeze(0) + # coords_2d will have shape (N,H,W,2).. which is also what grid_sample needs. + coords_2d = torch.nn.functional.affine_grid(identity_2d_batch, [1,1,h,w], align_corners=False) + offset_coords_2d = coords_2d - torch.reshape(offset_xy, (h,w,2)).unsqueeze(0) + + image_tensor = rearrange(torch.from_numpy(prev_img_cv2.astype(np.float32)), 'h w c -> c h w').to(device) + new_image = torch.nn.functional.grid_sample( + image_tensor.add(1/512 - 0.0001).unsqueeze(0), + offset_coords_2d, + mode=anim_args.sampling_mode, + padding_mode=anim_args.padding_mode, + align_corners=False + ) + + # convert back to cv2 style numpy array + result = rearrange( + new_image.squeeze().clamp(0,255), + 'c h w -> h w c' + ).cpu().numpy().astype(prev_img_cv2.dtype) + return result diff --git a/extensions/deforum/scripts/deforum_helpers/animation_key_frames.py b/extensions/deforum/scripts/deforum_helpers/animation_key_frames.py new file mode 100644 index 0000000000000000000000000000000000000000..824a0f6d8ea36d77a30cba71c0265ad44d4b0eec --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/animation_key_frames.py @@ -0,0 +1,106 @@ +import re +import numpy as np +import numexpr +import pandas as pd +from .prompt import check_is_number + +class DeformAnimKeys(): + def __init__(self, anim_args): + self.angle_series = get_inbetweens(parse_key_frames(anim_args.angle), anim_args.max_frames) + self.zoom_series = get_inbetweens(parse_key_frames(anim_args.zoom), anim_args.max_frames) + self.translation_x_series = get_inbetweens(parse_key_frames(anim_args.translation_x), anim_args.max_frames) + self.translation_y_series = get_inbetweens(parse_key_frames(anim_args.translation_y), anim_args.max_frames) + self.translation_z_series = get_inbetweens(parse_key_frames(anim_args.translation_z), anim_args.max_frames) + self.rotation_3d_x_series = get_inbetweens(parse_key_frames(anim_args.rotation_3d_x), anim_args.max_frames) + self.rotation_3d_y_series = get_inbetweens(parse_key_frames(anim_args.rotation_3d_y), anim_args.max_frames) + self.rotation_3d_z_series = get_inbetweens(parse_key_frames(anim_args.rotation_3d_z), anim_args.max_frames) + self.perspective_flip_theta_series = get_inbetweens(parse_key_frames(anim_args.perspective_flip_theta), anim_args.max_frames) + self.perspective_flip_phi_series = get_inbetweens(parse_key_frames(anim_args.perspective_flip_phi), anim_args.max_frames) + self.perspective_flip_gamma_series = get_inbetweens(parse_key_frames(anim_args.perspective_flip_gamma), anim_args.max_frames) + self.perspective_flip_fv_series = get_inbetweens(parse_key_frames(anim_args.perspective_flip_fv), anim_args.max_frames) + self.noise_schedule_series = get_inbetweens(parse_key_frames(anim_args.noise_schedule), anim_args.max_frames) + self.strength_schedule_series = get_inbetweens(parse_key_frames(anim_args.strength_schedule), anim_args.max_frames) + self.contrast_schedule_series = get_inbetweens(parse_key_frames(anim_args.contrast_schedule), anim_args.max_frames) + self.cfg_scale_schedule_series = get_inbetweens(parse_key_frames(anim_args.cfg_scale_schedule), anim_args.max_frames) + self.pix2pix_img_cfg_scale_series = get_inbetweens(parse_key_frames(anim_args.pix2pix_img_cfg_scale_schedule), anim_args.max_frames) + self.subseed_schedule_series = get_inbetweens(parse_key_frames(anim_args.subseed_schedule), anim_args.max_frames) + self.subseed_strength_schedule_series = get_inbetweens(parse_key_frames(anim_args.subseed_strength_schedule), anim_args.max_frames) + self.checkpoint_schedule_series = get_inbetweens(parse_key_frames(anim_args.checkpoint_schedule), anim_args.max_frames, is_single_string = True) + self.steps_schedule_series = get_inbetweens(parse_key_frames(anim_args.steps_schedule), anim_args.max_frames) + self.seed_schedule_series = get_inbetweens(parse_key_frames(anim_args.seed_schedule), anim_args.max_frames) + self.sampler_schedule_series = get_inbetweens(parse_key_frames(anim_args.sampler_schedule), anim_args.max_frames, is_single_string = True) + self.clipskip_schedule_series = get_inbetweens(parse_key_frames(anim_args.clipskip_schedule), anim_args.max_frames) + self.mask_schedule_series = get_inbetweens(parse_key_frames(anim_args.mask_schedule), anim_args.max_frames, is_single_string = True) + self.noise_mask_schedule_series = get_inbetweens(parse_key_frames(anim_args.noise_mask_schedule), anim_args.max_frames, is_single_string = True) + self.kernel_schedule_series = get_inbetweens(parse_key_frames(anim_args.kernel_schedule), anim_args.max_frames) + self.sigma_schedule_series = get_inbetweens(parse_key_frames(anim_args.sigma_schedule), anim_args.max_frames) + self.amount_schedule_series = get_inbetweens(parse_key_frames(anim_args.amount_schedule), anim_args.max_frames) + self.threshold_schedule_series = get_inbetweens(parse_key_frames(anim_args.threshold_schedule), anim_args.max_frames) + self.fov_series = get_inbetweens(parse_key_frames(anim_args.fov_schedule), anim_args.max_frames) + self.near_series = get_inbetweens(parse_key_frames(anim_args.near_schedule), anim_args.max_frames) + self.far_series = get_inbetweens(parse_key_frames(anim_args.far_schedule), anim_args.max_frames) + self.hybrid_comp_alpha_schedule_series = get_inbetweens(parse_key_frames(anim_args.hybrid_comp_alpha_schedule), anim_args.max_frames) + self.hybrid_comp_mask_blend_alpha_schedule_series = get_inbetweens(parse_key_frames(anim_args.hybrid_comp_mask_blend_alpha_schedule), anim_args.max_frames) + self.hybrid_comp_mask_contrast_schedule_series = get_inbetweens(parse_key_frames(anim_args.hybrid_comp_mask_contrast_schedule), anim_args.max_frames) + self.hybrid_comp_mask_auto_contrast_cutoff_high_schedule_series = get_inbetweens(parse_key_frames(anim_args.hybrid_comp_mask_auto_contrast_cutoff_high_schedule), anim_args.max_frames) + self.hybrid_comp_mask_auto_contrast_cutoff_low_schedule_series = get_inbetweens(parse_key_frames(anim_args.hybrid_comp_mask_auto_contrast_cutoff_low_schedule), anim_args.max_frames) + +class LooperAnimKeys(): + def __init__(self, loop_args, anim_args): + self.use_looper = loop_args.use_looper + self.imagesToKeyframe = loop_args.init_images + self.image_strength_schedule_series = get_inbetweens(parse_key_frames(loop_args.image_strength_schedule), anim_args.max_frames) + self.blendFactorMax_series = get_inbetweens(parse_key_frames(loop_args.blendFactorMax), anim_args.max_frames) + self.blendFactorSlope_series = get_inbetweens(parse_key_frames(loop_args.blendFactorSlope), anim_args.max_frames) + self.tweening_frames_schedule_series = get_inbetweens(parse_key_frames(loop_args.tweening_frames_schedule), anim_args.max_frames) + self.color_correction_factor_series = get_inbetweens(parse_key_frames(loop_args.color_correction_factor), anim_args.max_frames) + +def get_inbetweens(key_frames, max_frames, integer=False, interp_method='Linear', is_single_string = False): + key_frame_series = pd.Series([np.nan for a in range(max_frames)]) + for i in range(0, max_frames): + if i in key_frames: + value = key_frames[i] + value_is_number = check_is_number(value) + # if it's only a number, leave the rest for the default interpolation + if value_is_number: + t = i + key_frame_series[i] = value + if not value_is_number: + t = i + if is_single_string: + if value.find("'") > -1: + value = value.replace("'","") + if value.find('"') > -1: + value = value.replace('"',"") + key_frame_series[i] = numexpr.evaluate(value) if not is_single_string else value # workaround for values formatted like 0:("I am test") //used for sampler schedules + key_frame_series = key_frame_series.astype(float) if not is_single_string else key_frame_series # as string + + if interp_method == 'Cubic' and len(key_frames.items()) <= 3: + interp_method = 'Quadratic' + if interp_method == 'Quadratic' and len(key_frames.items()) <= 2: + interp_method = 'Linear' + + key_frame_series[0] = key_frame_series[key_frame_series.first_valid_index()] + key_frame_series[max_frames-1] = key_frame_series[key_frame_series.last_valid_index()] + key_frame_series = key_frame_series.interpolate(method=interp_method.lower(), limit_direction='both') + if integer: + return key_frame_series.astype(int) + return key_frame_series + +def parse_key_frames(string, prompt_parser=None): + # because math functions (i.e. sin(t)) can utilize brackets + # it extracts the value in form of some stuff + # which has previously been enclosed with brackets and + # with a comma or end of line existing after the closing one + pattern = r'((?P[0-9]+):[\s]*\((?P[\S\s]*?)\)([,][\s]?|[\s]?$))' + frames = dict() + for match_object in re.finditer(pattern, string): + frame = int(match_object.groupdict()['frame']) + param = match_object.groupdict()['param'] + if prompt_parser: + frames[frame] = prompt_parser(param) + else: + frames[frame] = param + if frames == {} and len(string) != 0: + raise RuntimeError('Key Frame string not correctly formatted') + return frames \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/args.py b/extensions/deforum/scripts/deforum_helpers/args.py new file mode 100644 index 0000000000000000000000000000000000000000..cd86df83a1247111560a23920971e4d702bf4f7b --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/args.py @@ -0,0 +1,1214 @@ +from modules.shared import cmd_opts +from modules.processing import get_fixed_seed +from modules.ui_components import FormRow +import modules.shared as sh +import modules.paths as ph +import os +from .frame_interpolation import set_interp_out_fps, gradio_f_interp_get_fps_and_fcount, process_interp_vid_upload_logic +from .upscaling import process_upscale_vid_upload_logic, process_ncnn_upscale_vid_upload_logic +from .video_audio_utilities import find_ffmpeg_binary, ffmpeg_stitch_video, direct_stitch_vid_from_frames, get_quick_vid_info, extract_number +from .gradio_funcs import * +from .general_utils import get_os +from .deforum_controlnet import controlnet_component_names, setup_controlnet_ui +import tempfile + +def Root(): + device = sh.device + models_path = ph.models_path + '/Deforum' + half_precision = not cmd_opts.no_half + mask_preset_names = ['everywhere','init_mask','video_mask'] + p = None + frames_cache = [] + initial_seed = None + initial_info = None + first_frame = None + outpath_samples = "" + animation_prompts = None + color_corrections = None + initial_clipskip = None + current_user_os = get_os() + tmp_deforum_run_duplicated_folder = os.path.join(tempfile.gettempdir(), 'tmp_run_deforum') + return locals() + +def DeforumAnimArgs(): + + #@markdown ####**Animation:** + animation_mode = '2D' #@param ['None', '2D', '3D', 'Video Input', 'Interpolation'] {type:'string'} + max_frames = 120 #@param {type:"number"} + border = 'replicate' #@param ['wrap', 'replicate'] {type:'string'} + #@markdown ####**Motion Parameters:** + angle = "0:(0)"#@param {type:"string"} + zoom = "0:(1.0025+0.002*sin(1.25*3.14*t/30))"#@param {type:"string"} + translation_x = "0:(0)"#@param {type:"string"} + translation_y = "0:(0)"#@param {type:"string"} + translation_z = "0:(1.75)"#@param {type:"string"} + rotation_3d_x = "0:(0)"#@param {type:"string"} + rotation_3d_y = "0:(0)"#@param {type:"string"} + rotation_3d_z = "0:(0)"#@param {type:"string"} + enable_perspective_flip = False #@param {type:"boolean"} + perspective_flip_theta = "0:(0)"#@param {type:"string"} + perspective_flip_phi = "0:(0)"#@param {type:"string"} + perspective_flip_gamma = "0:(0)"#@param {type:"string"} + perspective_flip_fv = "0:(53)"#@param {type:"string"} + noise_schedule = "0: (0.065)"#@param {type:"string"} + strength_schedule = "0: (0.65)"#@param {type:"string"} + contrast_schedule = "0: (1.0)"#@param {type:"string"} + cfg_scale_schedule = "0: (7)" + enable_steps_scheduling = False#@param {type:"boolean"} + steps_schedule = "0: (25)"#@param {type:"string"} + fov_schedule = "0: (70)" + near_schedule = "0: (200)" + far_schedule = "0: (10000)" + seed_schedule = "0:(5), 1:(-1), 219:(-1), 220:(5)" + pix2pix_img_cfg_scale = "1.5" + pix2pix_img_cfg_scale_schedule = "0:(1.5)" + enable_subseed_scheduling = False + subseed_schedule = "0:(1)" + subseed_strength_schedule = "0:(0)" + + # Sampler Scheduling + enable_sampler_scheduling = False #@param {type:"boolean"} + sampler_schedule = '0: ("Euler a")' + + # Composable mask scheduling + use_noise_mask = False + mask_schedule = '0: ("!({everywhere}^({init_mask}|{video_mask}) ) ")' + noise_mask_schedule = '0: ("!({everywhere}^({init_mask}|{video_mask}) ) ")' + # Checkpoint Scheduling + enable_checkpoint_scheduling = False#@param {type:"boolean"} + checkpoint_schedule = '0: ("model1.ckpt"), 100: ("model2.ckpt")' + + # CLIP skip Scheduling + enable_clipskip_scheduling = False #@param {type:"boolean"} + clipskip_schedule = '0: (2)' + + # Anti-blur + kernel_schedule = "0: (5)" + sigma_schedule = "0: (1.0)" + amount_schedule = "0: (0.35)" + threshold_schedule = "0: (0.0)" + # Hybrid video + hybrid_comp_alpha_schedule = "0:(1)" #@param {type:"string"} + hybrid_comp_mask_blend_alpha_schedule = "0:(0.5)" #@param {type:"string"} + hybrid_comp_mask_contrast_schedule = "0:(1)" #@param {type:"string"} + hybrid_comp_mask_auto_contrast_cutoff_high_schedule = "0:(100)" #@param {type:"string"} + hybrid_comp_mask_auto_contrast_cutoff_low_schedule = "0:(0)" #@param {type:"string"} + + #@markdown ####**Coherence:** + color_coherence = 'Match Frame 0 LAB' #@param ['None', 'Match Frame 0 HSV', 'Match Frame 0 LAB', 'Match Frame 0 RGB', 'Video Input'] {type:'string'} + color_coherence_video_every_N_frames = 1 #@param {type:"integer"} + color_force_grayscale = False #@param {type:"boolean"} + diffusion_cadence = '2' #@param ['1','2','3','4','5','6','7','8'] {type:'string'} + + #@markdown ####**Noise settings:** + noise_type = 'perlin' #@param ['uniform', 'perlin'] {type:'string'} + # Perlin params + perlin_w = 8 #@param {type:"number"} + perlin_h = 8 #@param {type:"number"} + perlin_octaves = 4 #@param {type:"number"} + perlin_persistence = 0.5 #@param {type:"number"} + + #@markdown ####**3D Depth Warping:** + use_depth_warping = True #@param {type:"boolean"} + midas_weight = 0.2 #@param {type:"number"} + + padding_mode = 'border'#@param ['border', 'reflection', 'zeros'] {type:'string'} + sampling_mode = 'bicubic'#@param ['bicubic', 'bilinear', 'nearest'] {type:'string'} + save_depth_maps = False #@param {type:"boolean"} + + #@markdown ####**Video Input:** + video_init_path ='https://github.com/hithereai/d/releases/download/m/vid.mp4' #@param {type:"string"} + extract_nth_frame = 1#@param {type:"number"} + extract_from_frame = 0 #@param {type:"number"} + extract_to_frame = -1 #@param {type:"number"} minus 1 for unlimited frames + overwrite_extracted_frames = True #@param {type:"boolean"} + use_mask_video = False #@param {type:"boolean"} + video_mask_path ='/content/video_in.mp4'#@param {type:"string"} + + #@markdown ####**Hybrid Video for 2D/3D Animation Mode:** + hybrid_generate_inputframes = False #@param {type:"boolean"} + hybrid_generate_human_masks = "None" #@param ['None','PNGs','Video', 'Both'] + hybrid_use_first_frame_as_init_image = True #@param {type:"boolean"} + hybrid_motion = "None" #@param ['None','Optical Flow','Perspective','Affine'] + hybrid_motion_use_prev_img = False #@param {type:"boolean"} + hybrid_flow_method = "Farneback" #@param ['DIS Medium','Farneback'] + hybrid_composite = False #@param {type:"boolean"} + hybrid_comp_mask_type = "None" #@param ['None', 'Depth', 'Video Depth', 'Blend', 'Difference'] + hybrid_comp_mask_inverse = False #@param {type:"boolean"} + hybrid_comp_mask_equalize = "None" #@param ['None','Before','After','Both'] + hybrid_comp_mask_auto_contrast = False #@param {type:"boolean"} + hybrid_comp_save_extra_frames = False #@param {type:"boolean"} + + #@markdown ####**Resume Animation:** + resume_from_timestring = False #@param {type:"boolean"} + resume_timestring = "20220829210106" #@param {type:"string"} + + return locals() + +# def DeforumPrompts(): + # return + +def DeforumAnimPrompts(): + return r"""{ + "0": "tiny cute swamp bunny, highly detailed, intricate, ultra hd, sharp photo, crepuscular rays, in focus, by tomasz alen kopera", + "30": "anthropomorphic clean cat, surrounded by fractals, epic angle and pose, symmetrical, 3d, depth of field, ruan jia and fenghua zhong", + "60": "a beautiful coconut --neg photo, realistic", + "90": "a beautiful durian, trending on Artstation" +} + """ + +def DeforumArgs(): + #@markdown **Image Settings** + W = 512 #@param + H = 512 #@param + W, H = map(lambda x: x - x % 64, (W, H)) # resize to integer multiple of 64 + + #@markdonw **Webui stuff** + tiling = False + restore_faces = False + seed_enable_extras = False + subseed = -1 + subseed_strength = 0 + seed_resize_from_w = 0 + seed_resize_from_h = 0 + + #@markdown **Sampling Settings** + seed = -1 #@param + sampler = 'euler_ancestral' #@param ["klms","dpm2","dpm2_ancestral","heun","euler","euler_ancestral","plms", "ddim"] + steps = 25 #@param + scale = 7 #@param + ddim_eta = 0.0 #@param + dynamic_threshold = None + static_threshold = None + + #@markdown **Save & Display Settings** + save_samples = True #@param {type:"boolean"} + save_settings = True #@param {type:"boolean"} + display_samples = True #@param {type:"boolean"} + save_sample_per_step = False #@param {type:"boolean"} + show_sample_per_step = False #@param {type:"boolean"} + + #@markdown **Prompt Settings** + prompt_weighting = False #@param {type:"boolean"} + normalize_prompt_weights = True #@param {type:"boolean"} + log_weighted_subprompts = False #@param {type:"boolean"} + + #@markdown **Batch Settings** + n_batch = 1 #@param + batch_name = "Deforum" #@param {type:"string"} + filename_format = "{timestring}_{index}_{prompt}.png" #@param ["{timestring}_{index}_{seed}.png","{timestring}_{index}_{prompt}.png"] + seed_behavior = "iter" #@param ["iter","fixed","random","ladder","alternate","schedule"] + seed_iter_N = 1 #@param {type:'integer'} + # make_grid = False #@param {type:"boolean"} + # grid_rows = 2 #@param + outdir = ""#get_output_folder(output_path, batch_name) + + #@markdown **Init Settings** + use_init = False #@param {type:"boolean"} + strength = 0.0 #@param {type:"number"} + strength_0_no_init = True # Set the strength to 0 automatically when no init image is used + init_image = "https://github.com/hithereai/d/releases/download/m/kaba.png" #@param {type:"string"} + # Whiter areas of the mask are areas that change more + use_mask = False #@param {type:"boolean"} + use_alpha_as_mask = False # use the alpha channel of the init image as the mask + mask_file = "https://github.com/hithereai/d/releases/download/m/mask.jpg" #@param {type:"string"} + invert_mask = False #@param {type:"boolean"} + # Adjust mask image, 1.0 is no adjustment. Should be positive numbers. + mask_contrast_adjust = 1.0 #@param {type:"number"} + mask_brightness_adjust = 1.0 #@param {type:"number"} + # Overlay the masked image at the end of the generation so it does not get degraded by encoding and decoding + overlay_mask = True # {type:"boolean"} + # Blur edges of final overlay mask, if used. Minimum = 0 (no blur) + mask_overlay_blur = 4 # {type:"number"} + + fill = 1 #MASKARGSEXPANSION Todo : Rename and convert to same formatting as used in img2img masked content + full_res_mask = True + full_res_mask_padding = 4 + reroll_blank_frames = 'reroll' # reroll, interrupt, or ignore + + n_samples = 1 # doesnt do anything + precision = 'autocast' + C = 4 + f = 8 + + prompt = "" + timestring = "" + init_latent = None + init_sample = None + init_c = None + mask_image = None + noise_mask = None + seed_internal = 0 + + return locals() + +def keyframeExamples(): + return '''{ + "0": "https://user-images.githubusercontent.com/121192995/215279228-1673df8a-f919-4380-b04c-19379b2041ff.png", + "50": "https://user-images.githubusercontent.com/121192995/215279281-7989fd6f-4b9b-4d90-9887-b7960edd59f8.png", + "100": "https://user-images.githubusercontent.com/121192995/215279284-afc14543-d220-4142-bbf4-503776ca2b8b.png", + "150": "https://user-images.githubusercontent.com/121192995/215279286-23378635-85b3-4457-b248-23e62c048049.jpg", + "200": "https://user-images.githubusercontent.com/121192995/215279228-1673df8a-f919-4380-b04c-19379b2041ff.png" +}''' + +def LoopArgs(): + use_looper = False + init_images = keyframeExamples() + image_strength_schedule = "0:(0.75)" + blendFactorMax = "0:(0.35)" + blendFactorSlope = "0:(0.25)" + tweening_frames_schedule = "0:(20)" + color_correction_factor = "0:(0.075)" + return locals() + +def ParseqArgs(): + parseq_manifest = None + parseq_use_deltas = True + return locals() + +def DeforumOutputArgs(): + skip_video_for_run_all = False #@param {type: 'boolean'} + fps = 15 #@param {type:"number"} + make_gif = False + image_path = "C:/SD/20230124234916_%05d.png" #@param {type:"string"} + mp4_path = "testvidmanualsettings.mp4" #@param {type:"string"} + ffmpeg_location = find_ffmpeg_binary() + ffmpeg_crf = '17' + ffmpeg_preset = 'slow' + add_soundtrack = 'None' #@param ["File","Init Video"] + soundtrack_path = "https://freetestdata.com/wp-content/uploads/2021/09/Free_Test_Data_1MB_MP3.mp3" + # End-Run upscaling + r_upscale_video = False + r_upscale_factor = 'x2' # ['2x', 'x3', 'x4'] + # **model below** - 'realesr-animevideov3' (default of realesrgan engine, does 2-4x), the rest do only 4x: 'realesrgan-x4plus', 'realesrgan-x4plus-anime' + r_upscale_model = 'realesr-animevideov3' + r_upscale_keep_imgs = True + + render_steps = False #@param {type: 'boolean'} + path_name_modifier = "x0_pred" #@param ["x0_pred","x"] + # max_video_frames = 200 #@param {type:"string"} + store_frames_in_ram = False #@param {type: 'boolean'} + #@markdown **Interpolate Video Settings** + # todo: change them to support FILM interpolation as well + frame_interpolation_engine = "None" #@param ["None", "RIFE v4.6", "FILM"] + frame_interpolation_x_amount = 2 # [2 to 1000 depends on the engine] + frame_interpolation_slow_mo_enabled = False + frame_interpolation_slow_mo_amount = 2 #@param [2 to 10] + frame_interpolation_keep_imgs = False #@param {type: 'boolean'} + return locals() + +import gradio as gr +import os +import time +from types import SimpleNamespace + +i1_store_backup = "

Deforum extension for auto1111 — version 2.2b

" +i1_store = i1_store_backup + +mask_fill_choices=['fill', 'original', 'latent noise', 'latent nothing'] + +def setup_deforum_setting_dictionary(self, is_img2img, is_extension = True): + d = SimpleNamespace(**DeforumArgs()) #default args + da = SimpleNamespace(**DeforumAnimArgs()) #default anim args + dp = SimpleNamespace(**ParseqArgs()) #default parseq ars + dv = SimpleNamespace(**DeforumOutputArgs()) #default video args + dr = SimpleNamespace(**Root()) # ROOT args + dloopArgs = SimpleNamespace(**LoopArgs()) + if not is_extension: + with gr.Row(): + btn = gr.Button("Click here after the generation to show the video") + with gr.Row(): + i1 = gr.HTML(i1_store, elem_id='deforum_header') + else: + btn = i1 = gr.HTML("") + + # MAIN (TOP) EXTENSION INFO ACCORD + with gr.Accordion("Info, Links and Help", open=False, elem_id='main_top_info_accord'): + gr.HTML("""Made by deforum.github.io, port for AUTOMATIC1111's webui maintained by kabachuha""") + gr.HTML("""FOR HELP CLICK HERE +
  • The code for this extension: here.
  • +
  • Join the official Deforum Discord to share your creations and suggestions.
  • +
  • Official Deforum Wiki: here.
  • +
  • Anime-inclined great guide (by FizzleDorf) with lots of examples: here.
  • +
  • For advanced keyframing with Math functions, see here.
  • +
  • Alternatively, use sd-parseq as a UI to define your animation schedules (see the Parseq section in the Keyframes tab).
  • +
  • framesync.xyz is also a good option, it makes compact math formulae for Deforum keyframes by selecting various waveforms.
  • +
  • The other site allows for making keyframes using interactive splines and Bezier curves (select Disco output format).
  • +
  • If you want to use Width/Height which are not multiples of 64, please change noise_type to 'Uniform', in Keyframes --> Noise.
  • + + If you liked this extension, please give it a star on GitHub! 😊""") + if not is_extension: + def show_vid(): + return { + i1: gr.update(value=i1_store, visible=True) + } + + btn.click( + show_vid, + [], + [i1] + ) + + with gr.Blocks(): + # RUN TAB + with gr.Tab('Run'): + from modules.sd_samplers import samplers_for_img2img + with gr.Row(variant='compact'): + sampler = gr.Dropdown(label="Sampler", choices=[x.name for x in samplers_for_img2img], value=samplers_for_img2img[0].name, type="value", elem_id="sampler", interactive=True) + steps = gr.Slider(label="Steps", minimum=0, maximum=200, step=1, value=d.steps, interactive=True) + with gr.Row(variant='compact'): + W = gr.Slider(label="Width", minimum=64, maximum=2048, step=64, value=d.W, interactive=True) + H = gr.Slider(label="Height", minimum=64, maximum=2048, step=64, value=d.H, interactive=True) + with gr.Row(variables='compact'): + seed = gr.Number(label="Seed", value=d.seed, interactive=True, precision=0) + batch_name = gr.Textbox(label="Batch name", lines=1, interactive=True, value = d.batch_name) + with gr.Accordion('Restore Faces, Tiling & more', open=False) as run_more_settings_accord: + with gr.Row(variant='compact'): + restore_faces = gr.Checkbox(label='Restore Faces', value=d.restore_faces) + tiling = gr.Checkbox(label='Tiling', value=False) + ddim_eta = gr.Number(label="DDIM Eta", value=d.ddim_eta, interactive=True) + with gr.Row() as pix2pix_img_cfg_scale_row: + pix2pix_img_cfg_scale_schedule = gr.Textbox(label="Pix2Pix img CFG schedule", value=da.pix2pix_img_cfg_scale_schedule, interactive=True) + # RUN FROM SETTING FILE ACCORD + with gr.Accordion('Resume & Run from file', open=False): + with gr.Tab('Run from Settings file'): + with gr.Row(variant='compact'): + override_settings_with_file = gr.Checkbox(label="Override settings", value=False, interactive=True, elem_id='override_settings') + custom_settings_file = gr.Textbox(label="Custom settings file", lines=1, interactive=True, elem_id='custom_settings_file') + # RESUME ANIMATION ACCORD + with gr.Tab('Resume Animation'): + with gr.Row(variant='compact'): + resume_from_timestring = gr.Checkbox(label="Resume from timestring", value=da.resume_from_timestring, interactive=True) + resume_timestring = gr.Textbox(label="Resume timestring", lines=1, value = da.resume_timestring, interactive=True) + # KEYFRAMES TAB + with gr.Tab('Keyframes'): #TODO make a some sort of the original dictionary parsing + with gr.Row(variant='compact'): + with gr.Column(scale=2): + animation_mode = gr.Radio(['2D', '3D', 'Interpolation', 'Video Input'], label="Animation mode", value=da.animation_mode, elem_id="animation_mode") + with gr.Column(scale=1, min_width=180): + border = gr.Radio(['replicate', 'wrap'], label="Border", value=da.border, elem_id="border") + with gr.Row(variant='compact'): + diffusion_cadence = gr.Slider(label="Cadence", minimum=1, maximum=50, step=1, value=da.diffusion_cadence, interactive=True) + max_frames = gr.Number(label="Max frames", lines=1, value = da.max_frames, interactive=True, precision=0) + # GUIDED IMAGES ACCORD + with gr.Accordion('Guided Images', open=False, elem_id='guided_images_accord') as guided_images_accord: + # GUIDED IMAGES INFO ACCORD + with gr.Accordion('*READ ME before you use this mode!*', open=False): + gr.HTML("""You can use this as a guided image tool or as a looper depending on your settings in the keyframe images field. + Set the keyframes and the images that you want to show up. + Note: the number of frames between each keyframe should be greater than the tweening frames.""") + # In later versions this should be also in the strength schedule, but for now you need to set it. + gr.HTML("""Prerequisites and Important Info: +
      +
    • This mode works ONLY with 2D/3D animation modes. Interpolation and Video Input modes aren't supported. +
    • Set Init tab's strength slider greater than 0. Recommended value (.65 - .80). +
    • Set 'seed_behavior' to 'schedule' under the Seed Scheduling section below.
    • +
    + """) + gr.HTML("""Looping recommendations: +
      +
    • seed_schedule should start and end on the same seed.
      + Example: seed_schedule could use 0:(5), 1:(-1), 219:(-1), 220:(5)
    • +
    • The 1st and last keyframe images should match.
    • +
    • Set your total number of keyframes to be 21 more than the last inserted keyframe image.
      + Example: Default args should use 221 as total keyframes.
    • +
    • Prompts are stored in JSON format. If you've got an error, check it in validator, like here
    • +
    + """) + with gr.Row(): + use_looper = gr.Checkbox(label="Enable guided images mode", value=dloopArgs.use_looper, interactive=True) + with gr.Row(): + init_images = gr.Textbox(label="Images to use for keyframe guidance", lines=9, value = keyframeExamples(), interactive=True) + # GUIDED IMAGES SCHEDULES ACCORD + with gr.Accordion('Guided images schedules', open=False): + with gr.Row(): + image_strength_schedule = gr.Textbox(label="Image strength schedule", lines=1, value = dloopArgs.image_strength_schedule, interactive=True) + with gr.Row(): + blendFactorMax = gr.Textbox(label="Blend factor max", lines=1, value = dloopArgs.blendFactorMax, interactive=True) + with gr.Row(): + blendFactorSlope = gr.Textbox(label="Blend factor slope", lines=1, value = dloopArgs.blendFactorSlope, interactive=True) + with gr.Row(): + tweening_frames_schedule = gr.Textbox(label="Tweening frames schedule", lines=1, value = dloopArgs.tweening_frames_schedule, interactive=True) + with gr.Row(): + color_correction_factor = gr.Textbox(label="Color correction factor", lines=1, value = dloopArgs.color_correction_factor, interactive=True) + # EXTA SCHEDULES TABS + with gr.Tabs(elem_id='extra_schedules'): + with gr.TabItem('Strength'): + strength_schedule = gr.Textbox(label="Strength schedule", lines=1, value = da.strength_schedule, interactive=True) + with gr.TabItem('CFG'): + cfg_scale_schedule = gr.Textbox(label="CFG scale schedule", lines=1, value = da.cfg_scale_schedule, interactive=True) + with gr.TabItem('Seed') as a3: + with gr.Row(): + seed_behavior = gr.Radio(['iter', 'fixed', 'random', 'ladder', 'alternate', 'schedule'], label="Seed behavior", value=d.seed_behavior, elem_id="seed_behavior") + with gr.Row() as seed_iter_N_row: + seed_iter_N = gr.Number(label="Seed iter N", value=d.seed_iter_N, interactive=True, precision=0) + with gr.Row(visible=False) as seed_schedule_row: + seed_schedule = gr.Textbox(label="Seed schedule", lines=1, value = da.seed_schedule, interactive=True) + with gr.TabItem('SubSeed', open=False) as subseed_sch_tab: + enable_subseed_scheduling = gr.Checkbox(label="Enable Subseed scheduling", value=da.enable_subseed_scheduling, interactive=True) + subseed_schedule = gr.Textbox(label="Subseed schedule", lines=1, value = da.subseed_schedule, interactive=True) + subseed_strength_schedule = gr.Textbox(label="Subseed strength schedule", lines=1, value = da.subseed_strength_schedule, interactive=True) + with gr.Row(variant='compact'): + seed_resize_from_w = gr.Slider(minimum=0, maximum=2048, step=64, label="Resize seed from width", value=0) + seed_resize_from_h = gr.Slider(minimum=0, maximum=2048, step=64, label="Resize seed from height", value=0) + # Steps Scheduling + with gr.TabItem('Step') as a13: + with gr.Row(): + enable_steps_scheduling = gr.Checkbox(label="Enable steps scheduling", value=da.enable_steps_scheduling, interactive=True) + with gr.Row(): + steps_schedule = gr.Textbox(label="Steps schedule", lines=1, value = da.steps_schedule, interactive=True) + # Sampler Scheduling + with gr.TabItem('Sampler') as a14: + with gr.Row(): + enable_sampler_scheduling = gr.Checkbox(label="Enable sampler scheduling", value=da.enable_sampler_scheduling, interactive=True) + with gr.Row(): + sampler_schedule = gr.Textbox(label="Sampler schedule", lines=1, value = da.sampler_schedule, interactive=True) + # Checkpoint Scheduling + with gr.TabItem('Checkpoint') as a15: + with gr.Row(): + enable_checkpoint_scheduling = gr.Checkbox(label="Enable checkpoint scheduling", value=da.enable_checkpoint_scheduling, interactive=True) + with gr.Row(): + checkpoint_schedule = gr.Textbox(label="Checkpoint schedule", lines=1, value = da.checkpoint_schedule, interactive=True) + with gr.TabItem('CLIP Skip', open=False) as a16: + with gr.Row(): + enable_clipskip_scheduling = gr.Checkbox(label="Enable CLIP skip scheduling", value=da.enable_clipskip_scheduling, interactive=True) + with gr.Row(): + clipskip_schedule = gr.Textbox(label="CLIP skip schedule", lines=1, value = da.clipskip_schedule, interactive=True) + # MOTION INNER TAB + with gr.Tab('Motion') as motion_tab: + with gr.Column(visible=True) as only_2d_motion_column: + with gr.Row(variant='compact'): + angle = gr.Textbox(label="Angle", lines=1, value = da.angle, interactive=True) + with gr.Row(variant='compact'): + zoom = gr.Textbox(label="Zoom", lines=1, value = da.zoom, interactive=True) + with gr.Column(visible=True) as both_anim_mode_motion_params_column: + with gr.Row(variant='compact'): + translation_x = gr.Textbox(label="Translation X", lines=1, value = da.translation_x, interactive=True) + with gr.Row(variant='compact'): + translation_y = gr.Textbox(label="Translation Y", lines=1, value = da.translation_y, interactive=True) + with gr.Column(visible=False) as only_3d_motion_column: + with gr.Row(variant='compact'): + translation_z = gr.Textbox(label="Translation Z", lines=1, value = da.translation_z, interactive=True) + with gr.Row(variant='compact'): + rotation_3d_x = gr.Textbox(label="Rotation 3D X", lines=1, value = da.rotation_3d_x, interactive=True) + with gr.Row(variant='compact'): + rotation_3d_y = gr.Textbox(label="Rotation 3D Y", lines=1, value = da.rotation_3d_y, interactive=True) + with gr.Row(variant='compact'): + rotation_3d_z = gr.Textbox(label="Rotation 3D Z", lines=1, value = da.rotation_3d_z, interactive=True) + # 3D DEPTH & FOV ACCORD + with gr.Accordion('Depth Warping & FOV', visible=False, open=False) as depth_3d_warping_accord: + with gr.Tab('Depth Warping'): + with gr.Row(variant='compact'): + use_depth_warping = gr.Checkbox(label="Use depth warping", value=da.use_depth_warping, interactive=True) + midas_weight = gr.Number(label="MiDaS weight", value=da.midas_weight, interactive=True) + with gr.Row(variant='compact'): + padding_mode = gr.Radio(['border', 'reflection', 'zeros'], label="Padding mode", value=da.padding_mode, elem_id="padding_mode") + sampling_mode = gr.Radio(['bicubic', 'bilinear', 'nearest'], label="Sampling mode", value=da.sampling_mode, elem_id="sampling_mode") + with gr.Tab('Field Of View', visible=False, open=False) as fov_accord: + with gr.Row(variant='compact'): + fov_schedule = gr.Textbox(label="FOV schedule", lines=1, value = da.fov_schedule, interactive=True) + with gr.Row(): + near_schedule = gr.Textbox(label="Near schedule", lines=1, value = da.near_schedule, interactive=True) + with gr.Row(): + far_schedule = gr.Textbox(label="Far schedule", lines=1, value = da.far_schedule, interactive=True) + # PERSPECTIVE FLIP ACCORD + with gr.Accordion('Perspective Flip', open=False) as perspective_flip_accord: + with gr.Row(): + enable_perspective_flip = gr.Checkbox(label="Enable perspective flip", value=da.enable_perspective_flip, interactive=True) + with gr.Row(): + perspective_flip_theta = gr.Textbox(label="Perspective flip theta", lines=1, value = da.perspective_flip_theta, interactive=True) + with gr.Row(): + perspective_flip_phi = gr.Textbox(label="Perspective flip phi", lines=1, value = da.perspective_flip_phi, interactive=True) + with gr.Row(): + perspective_flip_gamma = gr.Textbox(label="Perspective flip gamma", lines=1, value = da.perspective_flip_gamma, interactive=True) + with gr.Row(): + perspective_flip_fv = gr.Textbox(label="Perspective flip fv", lines=1, value = da.perspective_flip_fv, interactive=True) + # NOISE INNER TAB + with gr.Tab('Noise', open=True) as a8: + with gr.Row(): + noise_type = gr.Radio(['uniform', 'perlin'], label="Noise type", value=da.noise_type, elem_id="noise_type") + with gr.Row(): + noise_schedule = gr.Textbox(label="Noise schedule", lines=1, value = da.noise_schedule, interactive=True) + with gr.Row() as perlin_row: + with gr.Column(min_width=220): + perlin_octaves = gr.Slider(label="Perlin octaves", minimum=1, maximum=7, value=da.perlin_octaves, step=1, interactive=True) + with gr.Column(min_width=220): + perlin_persistence = gr.Slider(label="Perlin persistence", minimum=0, maximum=1, value=da.perlin_persistence, step=0.02, interactive=True) + # COHERENCE INNER TAB + with gr.Tab('Coherence', open=False) as coherence_accord: + with gr.Row(equal_height=True): + # Future TODO: remove 'match frame 0' prefix (after we manage the deprecated-names settings import), then convert from Dropdown to Radio! + color_coherence = gr.Dropdown(label="Color coherence", choices=['None', 'Match Frame 0 HSV', 'Match Frame 0 LAB', 'Match Frame 0 RGB', 'Video Input'], value=da.color_coherence, type="value", elem_id="color_coherence", interactive=True) + with gr.Column() as force_grayscale_column: + color_force_grayscale = gr.Checkbox(label="Color force Grayscale", value=da.color_force_grayscale, interactive=True) + with gr.Row(visible=False) as color_coherence_video_every_N_frames_row: + color_coherence_video_every_N_frames = gr.Number(label="Color coherence video every N frames", value=1, interactive=True) + with gr.Row(): + contrast_schedule = gr.Textbox(label="Contrast schedule", lines=1, value = da.contrast_schedule, interactive=True) + with gr.Row(): + # what to do with blank frames (they may result from glitches or the NSFW filter being turned on): reroll with +1 seed, interrupt the animation generation, or do nothing + reroll_blank_frames = gr.Radio(['reroll', 'interrupt', 'ignore'], label="Reroll blank frames", value=d.reroll_blank_frames, elem_id="reroll_blank_frames") + # ANTI BLUR INNER TAB + with gr.Tab('Anti Blur', open=False, elem_id='anti_blur_accord') as anti_blur_tab: + with gr.Row(variant='compact'): + kernel_schedule = gr.Textbox(label="Kernel schedule", lines=1, value = da.kernel_schedule, interactive=True) + with gr.Row(variant='compact'): + sigma_schedule = gr.Textbox(label="Sigma schedule", lines=1, value = da.sigma_schedule, interactive=True) + with gr.Row(variant='compact'): + amount_schedule = gr.Textbox(label="Amount schedule", lines=1, value = da.amount_schedule, interactive=True) + with gr.Row(variant='compact'): + threshold_schedule = gr.Textbox(label="Threshold schedule", lines=1, value = da.threshold_schedule, interactive=True) + # PROMPTS TAB + with gr.Tab('Prompts'): + # PROMPTS INFO ACCORD + with gr.Accordion(label='*Important* notes on Prompts', elem_id='prompts_info_accord', open=False, visible=True) as prompts_info_accord: + gr.HTML(""" +
      +
    • Please always keep values in math functions above 0.
    • +
    • There is *no* Batch mode like in vanilla deforum. Please Use the txt2img tab for that.
    • +
    • For negative prompts, please write your positive prompt, then --neg ugly, text, assymetric, or any other negative tokens of your choice. OR:
    • +
    • Use the negative_prompts field to automatically append all words as a negative prompt. *Don't* add --neg in the negative_prompts field!
    • +
    • Prompts are stored in JSON format. If you've got an error, check it in a JSON Validator
    • +
    + """) + with gr.Row(): + animation_prompts = gr.Textbox(label="Prompts", lines=8, interactive=True, value = DeforumAnimPrompts()) + with gr.Row(): + animation_prompts_positive = gr.Textbox(label="Prompts positive", lines=1, interactive=True, value = "") + with gr.Row(): + animation_prompts_negative = gr.Textbox(label="Prompts negative", lines=1, interactive=True, value = "") + # COMPOSABLE MASK SCHEDULING ACCORD + with gr.Accordion('Composable Mask scheduling', open=False): + gr.HTML(""" +
      +
    • To enable, check use_mask in the Init tab
    • +
    • Supports boolean operations: (! - negation, & - and, | - or, ^ - xor, \ - difference, () - nested operations)
    • +
    • default variables: in \{\}, like \{init_mask\}, \{video_mask\}, \{everywhere\}
    • +
    • masks from files: in [], like [mask1.png]
    • +
    • description-based: word masks in <>, like <apple>, <hair>
    • +
    + """) + with gr.Row(): + mask_schedule = gr.Textbox(label="Mask schedule", lines=1, value = da.mask_schedule, interactive=True) + with gr.Row(): + use_noise_mask = gr.Checkbox(label="Use noise mask", value=da.use_noise_mask, interactive=True) + with gr.Row(): + noise_mask_schedule = gr.Textbox(label="Noise mask schedule", lines=1, value = da.noise_mask_schedule, interactive=True) + # INIT MAIN TAB + with gr.Tab('Init'): + # IMAGE INIT INNER-TAB + with gr.Tab('Image Init'): + with gr.Row(): + with gr.Column(min_width=150): + use_init = gr.Checkbox(label="Use init", value=d.use_init, interactive=True, visible=True) + with gr.Column(min_width=150): + strength_0_no_init = gr.Checkbox(label="Strength 0 no init", value=True, interactive=True) + with gr.Column(min_width=170): + strength = gr.Slider(label="Strength", minimum=0, maximum=1, step=0.01, value=0, interactive=True) + with gr.Row(): + init_image = gr.Textbox(label="Init image", lines=1, interactive=True, value = d.init_image) + # VIDEO INIT INNER-TAB + with gr.Tab('Video Init'): + with gr.Row(): + video_init_path = gr.Textbox(label="Video init path", lines=1, value = da.video_init_path, interactive=True) + with gr.Row(): + extract_from_frame = gr.Number(label="Extract from frame", value=da.extract_from_frame, interactive=True, precision=0) + extract_to_frame = gr.Number(label="Extract to frame", value=da.extract_to_frame, interactive=True, precision=0) + extract_nth_frame = gr.Number(label="Extract nth frame", value=da.extract_nth_frame, interactive=True, precision=0) + overwrite_extracted_frames = gr.Checkbox(label="Overwrite extracted frames", value=False, interactive=True) + use_mask_video = gr.Checkbox(label="Use mask video", value=False, interactive=True) + with gr.Row(): + video_mask_path = gr.Textbox(label="Video mask path", lines=1, value = da.video_mask_path, interactive=True) + # MASK INIT INNER-TAB + with gr.Tab('Mask Init'): + with gr.Row(): + use_mask = gr.Checkbox(label="Use mask", value=d.use_mask, interactive=True) + use_alpha_as_mask = gr.Checkbox(label="Use alpha as mask", value=d.use_alpha_as_mask, interactive=True) + invert_mask = gr.Checkbox(label="Invert mask", value=d.invert_mask, interactive=True) + overlay_mask = gr.Checkbox(label="Overlay mask", value=d.overlay_mask, interactive=True) + with gr.Row(): + mask_file = gr.Textbox(label="Mask file", lines=1, interactive=True, value = d.mask_file) + with gr.Row(): + mask_overlay_blur = gr.Slider(label="Mask overlay blur", minimum=0, maximum=64, step=1, value=d.mask_overlay_blur, interactive=True) + with gr.Row(): + choice = mask_fill_choices[d.fill] + fill = gr.Radio(label='Mask fill', choices=mask_fill_choices, value=choice, type="index") + with gr.Row(): + full_res_mask = gr.Checkbox(label="Full res mask", value=d.full_res_mask, interactive=True) + full_res_mask_padding = gr.Slider(minimum=0, maximum=512, step=1, label="Full res mask padding", value=d.full_res_mask_padding, interactive=True) + # PARSEQ ACCORD + with gr.Accordion('Parseq', open=False): + gr.HTML(""" + Use an sd-parseq manifest for your animation (leave blank to ignore).

    +

    + Note that parseq overrides: +

      +
    • Run: seed, subseed, subseed strength.
    • +
    • Keyframes: generation settings (noise, strength, contrast, scale).
    • +
    • Keyframes: motion parameters for 2D and 3D (angle, zoom, translation, rotation, perspective flip).
    • +
    +

    + + Parseq does not override: +
      +
    • Run: Sampler, Width, Height, tiling, resize seed.
    • +
    • Keyframes: animation settings (animation mode, max frames, border)
    • +
    • Keyframes: coherence (color coherence & cadence)
    • +
    • Keyframes: depth warping
    • +
    • Output settings: all settings (including fps and max frames)
    • +
    +

    + """) + with gr.Row(): + parseq_manifest = gr.Textbox(label="Parseq Manifest (JSON or URL)", lines=4, value = dp.parseq_manifest, interactive=True) + with gr.Row(): + parseq_use_deltas = gr.Checkbox(label="Use delta values for movement parameters", value=dp.parseq_use_deltas, interactive=True) + def show_hybrid_html_msg(choice): + if choice not in ['2D','3D']: + return gr.update(visible=True) + else: + return gr.update(visible=False) + def change_hybrid_tab_status(choice): + if choice in ['2D','3D']: + return gr.update(visible=True) + else: + return gr.update(visible=False) + # CONTROLNET TAB + with gr.Tab('ControlNet'): + gr.HTML(""" + Requires the ControlNet extension to be installed.

    +

    + *Work In Progress*. All params below are going to be keyframable at some point. If you want to speedup the integration, join Deforum's development. 😉 +

    + + Due to ControlNet base extension's inner works it needs its models to be located at 'extensions/deforum-for-automatic1111-webui/models'. So copy, symlink or move them there until a more elegant solution is found. And, as of now, it requires use_init checked for the first run. The ControlNet extension version used in the dev process is a24089a62e70a7fae44b7bf35b51fd584dd55e25, if even with all the other options above used it still breaks, upgrade/downgrade your CN version to this one. +

    + """) + controlnet_dict = setup_controlnet_ui() + # HYBRID VIDEO TAB + with gr.Tab('Hybrid Video'): + # this html only shows when not in 2d/3d mode + hybrid_msg_html = gr.HTML(value='Please, change animation mode to 2D or 3D to enable Hybrid Mode',visible=False, elem_id='hybrid_msg_html') + # HYBRID INFO ACCORD + with gr.Accordion("Info & Help", open=False): + hybrid_html = "

    Hybrid Video Compositing in 2D/3D Modeby reallybigname

    " + hybrid_html += "
    • Composite video with previous frame init image in 2D or 3D animation_mode (not for Video Input mode)
    • " + hybrid_html += "
    • Uses your Init settings for video_init_path, extract_nth_frame, overwrite_extracted_frames
    • " + hybrid_html += "
    • In Keyframes tab, you can also set color_coherence = 'Video Input'
    • " + hybrid_html += "
    • color_coherence_video_every_N_frames lets you only match every N frames
    • " + hybrid_html += "
    • Color coherence may be used with hybrid composite off, to just use video color.
    • " + hybrid_html += "
    • Hybrid motion may be used with hybrid composite off, to just use video motion.
    " + hybrid_html += "Hybrid Video Schedules" + hybrid_html += "
    • The alpha schedule controls overall alpha for video mix, whether using a composite mask or not.
    • " + hybrid_html += "
    • The hybrid_comp_mask_blend_alpha_schedule only affects the 'Blend' hybrid_comp_mask_type.
    • " + hybrid_html += "
    • Mask contrast schedule is from 0-255. Normal is 1. Affects all masks.
    • " + hybrid_html += "
    • Autocontrast low/high cutoff schedules 0-100. Low 0 High 100 is full range.
      (hybrid_comp_mask_auto_contrast must be enabled)
    " + hybrid_html += "Click Here for more info/ a Guide." + gr.HTML(hybrid_html) + # HYBRID SETTINGS ACCORD + with gr.Accordion("Hybrid Settings", open=True) as hybrid_settings_accord: + with gr.Row(variant='compact'): + with gr.Column(min_width=340): + with gr.Row(variant='compact'): + hybrid_generate_inputframes = gr.Checkbox(label="Generate inputframes", value=False, interactive=True) + hybrid_composite = gr.Checkbox(label="Hybrid composite", value=False, interactive=True) + with gr.Column(min_width=340) as hybrid_2nd_column: + with gr.Row(variant='compact'): + hybrid_use_first_frame_as_init_image = gr.Checkbox(label="First frame as init image", value=da.hybrid_use_first_frame_as_init_image, interactive=True, visible=False) + hybrid_motion_use_prev_img = gr.Checkbox(label="Motion use prev img", value=False, interactive=True, visible=False) + with gr.Row() as hybrid_flow_row: + with gr.Column(variant='compact'): + with gr.Row(variant='compact'): + hybrid_motion = gr.Radio(['None', 'Optical Flow', 'Perspective', 'Affine'], label="Hybrid motion", value=da.hybrid_motion, elem_id="hybrid_motion") + with gr.Column(variant='compact'): + with gr.Row(variant='compact'): + with gr.Column(scale=1): + hybrid_flow_method = gr.Radio(['DIS Medium', 'Farneback'], label="Flow method", value=da.hybrid_flow_method, elem_id="hybrid_flow_method", visible=False) + hybrid_comp_mask_type = gr.Radio(['None', 'Depth', 'Video Depth', 'Blend', 'Difference'], label="Comp mask type", value=da.hybrid_comp_mask_type, elem_id="hybrid_comp_mask_type", visible=False) + with gr.Row(visible=False, variant='compact') as hybrid_comp_mask_row: + hybrid_comp_mask_equalize = gr.Radio(['None', 'Before', 'After', 'Both'], label="Comp mask equalize", value=da.hybrid_comp_mask_equalize, elem_id="hybrid_comp_mask_equalize") + with gr.Column(variant='compact'): + hybrid_comp_mask_auto_contrast = gr.Checkbox(label="Comp mask auto contrast", value=False, interactive=True) + hybrid_comp_mask_inverse = gr.Checkbox(label="Comp mask inverse", value=False, interactive=True) + with gr.Row(variant='compact'): + hybrid_comp_save_extra_frames = gr.Checkbox(label="Comp save extra frames", value=False, interactive=True) + # HYBRID SCHEDULES ACCORD + with gr.Accordion("Hybrid Schedules", open=False, visible=False) as hybrid_sch_accord: + with gr.Row(variant='compact') as hybrid_comp_alpha_schedule_row: + hybrid_comp_alpha_schedule = gr.Textbox(label="Comp alpha schedule", lines=1, value = da.hybrid_comp_alpha_schedule, interactive=True) + with gr.Row(variant='compact', visible=False) as hybrid_comp_mask_blend_alpha_schedule_row: + hybrid_comp_mask_blend_alpha_schedule = gr.Textbox(label="Comp mask blend alpha schedule", lines=1, value = da.hybrid_comp_mask_blend_alpha_schedule, interactive=True, elem_id="hybridelemtest") + with gr.Row(variant='compact', visible=False) as hybrid_comp_mask_contrast_schedule_row: + hybrid_comp_mask_contrast_schedule = gr.Textbox(label="Comp mask contrast schedule", lines=1, value = da.hybrid_comp_mask_contrast_schedule, interactive=True) + with gr.Row(variant='compact', visible=False) as hybrid_comp_mask_auto_contrast_cutoff_high_schedule_row : + hybrid_comp_mask_auto_contrast_cutoff_high_schedule = gr.Textbox(label="Comp mask auto contrast cutoff high schedule", lines=1, value = da.hybrid_comp_mask_auto_contrast_cutoff_high_schedule, interactive=True) + with gr.Row(variant='compact', visible=False) as hybrid_comp_mask_auto_contrast_cutoff_low_schedule_row: + hybrid_comp_mask_auto_contrast_cutoff_low_schedule = gr.Textbox(label="Comp mask auto contrast cutoff low schedule", lines=1, value = da.hybrid_comp_mask_auto_contrast_cutoff_low_schedule, interactive=True) + # HUMANS MASKING ACCORD + with gr.Accordion("Humans Masking", open=False, visible=False) as humans_masking_accord: + with gr.Row(variant='compact'): + hybrid_generate_human_masks = gr.Radio(['None', 'PNGs', 'Video', 'Both'], label="Generate human masks", value=da.hybrid_generate_human_masks, elem_id="hybrid_generate_human_masks") + # OUTPUT TAB + with gr.Tab('Output'): + # VID OUTPUT ACCORD + with gr.Accordion('Video Output Settings', open=True): + with gr.Row(variant='compact') as fps_out_format_row: + fps = gr.Slider(label="FPS", value=dv.fps, minimum=1, maximum=240, step=1) + # NOT VISIBLE AS OF 11-02-23 moving to ffmpeg-only! + output_format = gr.Dropdown(visible=False, label="Output format", choices=['FFMPEG mp4'], value='FFMPEG mp4', type="value", elem_id="output_format", interactive=True) + with gr.Column(variant='compact'): + with gr.Row(variant='compact') as soundtrack_row: + add_soundtrack = gr.Radio(['None', 'File', 'Init Video'], label="Add soundtrack", value=dv.add_soundtrack) + soundtrack_path = gr.Textbox(label="Soundtrack path", lines=1, interactive=True, value = dv.soundtrack_path) + with gr.Row(variant='compact'): + skip_video_for_run_all = gr.Checkbox(label="Skip video for run all", value=dv.skip_video_for_run_all, interactive=True) + store_frames_in_ram = gr.Checkbox(label="Store frames in ram", value=dv.store_frames_in_ram, interactive=True) + save_depth_maps = gr.Checkbox(label="Save depth maps", value=da.save_depth_maps, interactive=True) + # the following param only shows for windows and linux users! + make_gif = gr.Checkbox(label="Make GIF", value=dv.make_gif, interactive=True) + with gr.Row(equal_height=True, variant='compact', visible=(True if dr.current_user_os in ["Windows", "Linux", "Mac"] else False)) as r_upscale_row: + r_upscale_video = gr.Checkbox(label="Upscale", value=dv.r_upscale_video, interactive=True) + r_upscale_model = gr.Dropdown(label="Upscale model", choices=['realesr-animevideov3', 'realesrgan-x4plus', 'realesrgan-x4plus-anime'], interactive=True, value = dv.r_upscale_model, type="value") + r_upscale_factor = gr.Dropdown(choices=['x2', 'x3', 'x4'], label="Upscale factor", interactive=True, value=dv.r_upscale_factor, type="value") + r_upscale_keep_imgs = gr.Checkbox(label="Keep Imgs", value=dv.r_upscale_keep_imgs, interactive=True) + with gr.Accordion('FFmpeg settings', visible=True, open=False) as ffmpeg_quality_accordion: + with gr.Row(equal_height=True, variant='compact', visible=True) as ffmpeg_set_row: + ffmpeg_crf = gr.Slider(minimum=0, maximum=51, step=1, label="CRF", value=dv.ffmpeg_crf, interactive=True) + ffmpeg_preset = gr.Dropdown(label="Preset", choices=['veryslow', 'slower', 'slow', 'medium', 'fast', 'faster', 'veryfast', 'superfast', 'ultrafast'], interactive=True, value = dv.ffmpeg_preset, type="value") + with gr.Row(equal_height=True, variant='compact', visible=True) as ffmpeg_location_row: + ffmpeg_location = gr.Textbox(label="Location", lines=1, interactive=True, value = dv.ffmpeg_location) + # FRAME INTERPOLATION TAB + with gr.Tab('Frame Interoplation') as frame_interp_tab: + with gr.Accordion('Important notes and Help', open=False): + gr.HTML(""" + Use RIFE / FILM Frame Interpolation to smooth out, slow-mo (or both) any video.

    +

    + Supported engines: +

      +
    • RIFE v4.6 and FILM.
    • +
    +

    +

    + Important notes: +

      +
    • Frame Interpolation will *not* run if any of the following are enabled: 'Store frames in ram' / 'Skip video for run all'.
    • +
    • Audio (if provided) will *not* be transferred to the interpolated video if Slow-Mo is enabled.
    • +
    • 'add_soundtrack' and 'soundtrack_path' aren't being honoured in "Interpolate an existing video" mode. Original vid audio will be used instead with the same slow-mo rules above.
    • +
    +

    + """) + with gr.Column(variant='compact'): + with gr.Row(variant='compact'): + # Interpolation Engine + frame_interpolation_engine = gr.Dropdown(label="Engine", choices=['None','RIFE v4.6','FILM'], value=dv.frame_interpolation_engine, type="value", elem_id="frame_interpolation_engine", interactive=True) + frame_interpolation_slow_mo_enabled = gr.Checkbox(label="Slow Mo", elem_id="frame_interpolation_slow_mo_enabled", value=dv.frame_interpolation_slow_mo_enabled, interactive=True, visible=False) + # If this is set to True, we keep all of the interpolated frames in a folder. Default is False - means we delete them at the end of the run + frame_interpolation_keep_imgs = gr.Checkbox(label="Keep Imgs", elem_id="frame_interpolation_keep_imgs", value=dv.frame_interpolation_keep_imgs, interactive=True, visible=False) + with gr.Row(variant='compact', visible=False) as frame_interp_amounts_row: + with gr.Column(min_width=180) as frame_interp_x_amount_column: + # How many times to interpolate (interp X) + frame_interpolation_x_amount = gr.Slider(minimum=2, maximum=10, step=1, label="Interp X", value=dv.frame_interpolation_x_amount, interactive=True) + with gr.Column(min_width=180, visible=False) as frame_interp_slow_mo_amount_column: + # Interp Slow-Mo (setting final output fps, not really doing anything direclty with RIFE/FILM) + frame_interpolation_slow_mo_amount = gr.Slider(minimum=2, maximum=10, step=1, label="Slow-Mo X", value=dv.frame_interpolation_x_amount, interactive=True) + # TODO: move these from here when done + def hide_slow_mo(choice): + return gr.update(visible=True) if choice else gr.update(visible=False) + def hide_interp_by_interp_status(choice): + return gr.update(visible=False) if choice == 'None' else gr.update(visible=True) + def change_interp_x_max_limit(engine_name, current_value): + if engine_name == 'FILM': + return gr.update(maximum=300) + elif current_value > 10: + return gr.update(maximum=10, value=2) + return gr.update(maximum=10) + frame_interpolation_slow_mo_enabled.change(fn=hide_slow_mo,inputs=frame_interpolation_slow_mo_enabled,outputs=frame_interp_slow_mo_amount_column) + interp_hide_list = [frame_interpolation_slow_mo_enabled,frame_interpolation_keep_imgs,frame_interp_amounts_row] + for output in interp_hide_list: + frame_interpolation_engine.change(fn=hide_interp_by_interp_status,inputs=frame_interpolation_engine,outputs=output) + frame_interpolation_engine.change(fn=change_interp_x_max_limit,inputs=[frame_interpolation_engine,frame_interpolation_x_amount],outputs=frame_interpolation_x_amount) + with gr.Row(visible=False) as interp_existing_video_row: + # Intrpolate any existing video from the connected PC + with gr.Accordion('Interpolate an existing video', open=False) as interp_existing_video_accord: + # A drag-n-drop UI box to which the user uploads a *single* (at this stage) video + vid_to_interpolate_chosen_file = gr.File(label="Video to Interpolate", interactive=True, file_count="single", file_types=["video"], elem_id="vid_to_interpolate_chosen_file") + with gr.Row(variant='compact'): + # Non interactive textbox showing uploaded input vid total Frame Count + in_vid_frame_count_window = gr.Textbox(label="In Frame Count", lines=1, interactive=False, value='---') + # Non interactive textbox showing uploaded input vid FPS + in_vid_fps_ui_window = gr.Textbox(label="In FPS", lines=1, interactive=False, value='---') + # Non interactive textbox showing expected output interpolated video FPS + out_interp_vid_estimated_fps = gr.Textbox(label="Interpolated Vid FPS", value='---') + # This is the actual button that's pressed to initiate the interpolation: + interpolate_button = gr.Button(value="*Interpolate uploaded video*") + # Show a text about CLI outputs: + gr.HTML("* check your CLI for outputs") + # make the functin call when the interpolation button is clicked + interpolate_button.click(upload_vid_to_interpolate,inputs=[vid_to_interpolate_chosen_file, frame_interpolation_engine, frame_interpolation_x_amount, frame_interpolation_slow_mo_enabled, frame_interpolation_slow_mo_amount, frame_interpolation_keep_imgs, ffmpeg_location, ffmpeg_crf, ffmpeg_preset, in_vid_fps_ui_window]) + [change_fn.change(set_interp_out_fps, inputs=[frame_interpolation_x_amount, frame_interpolation_slow_mo_enabled, frame_interpolation_slow_mo_amount, in_vid_fps_ui_window], outputs=out_interp_vid_estimated_fps) for change_fn in [frame_interpolation_x_amount, frame_interpolation_slow_mo_amount, frame_interpolation_slow_mo_enabled]] + # Populate the above FPS and FCount values as soon as a video is uploaded to the FileUploadBox (vid_to_interpolate_chosen_file) + vid_to_interpolate_chosen_file.change(gradio_f_interp_get_fps_and_fcount,inputs=[vid_to_interpolate_chosen_file, frame_interpolation_x_amount, frame_interpolation_slow_mo_enabled, frame_interpolation_slow_mo_amount],outputs=[in_vid_fps_ui_window,in_vid_frame_count_window, out_interp_vid_estimated_fps]) + #TODO: move this from here + interp_hide_list = [frame_interpolation_slow_mo_enabled,frame_interpolation_keep_imgs,frame_interp_amounts_row,interp_existing_video_row] + for output in interp_hide_list: + frame_interpolation_engine.change(fn=hide_interp_by_interp_status,inputs=frame_interpolation_engine,outputs=output) + # TODO: add upscalers parameters to the settings and make them a part of the pipeline + # VIDEO UPSCALE TAB + with gr.Tab('Video Upscaling'): + vid_to_upscale_chosen_file = gr.File(label="Video to Upscale", interactive=True, file_count="single", file_types=["video"], elem_id="vid_to_upscale_chosen_file") + with gr.Column(): + # NCNN UPSCALE TAB + with gr.Tab('Upscale V2') as ncnn_upscale_tab: + with gr.Row(variant='compact') as ncnn_upload_vid_stats_row: + # Non interactive textbox showing uploaded input vid total Frame Count + ncnn_upscale_in_vid_frame_count_window = gr.Textbox(label="In Frame Count", lines=1, interactive=False, value='---') + # Non interactive textbox showing uploaded input vid FPS + ncnn_upscale_in_vid_fps_ui_window = gr.Textbox(label="In FPS", lines=1, interactive=False, value='---') + # Non interactive textbox showing uploaded input resolution + ncnn_upscale_in_vid_res = gr.Textbox(label="In Res", lines=1, interactive=False, value='---') + # Non interactive textbox showing expected output resolution + ncnn_upscale_out_vid_res = gr.Textbox(label="Out Res", value='---') + with gr.Column(): + with gr.Row(variant='compact', visible=(True if dr.current_user_os in ["Windows", "Linux", "Mac"] else False)) as ncnn_actual_upscale_row: + ncnn_upscale_model = gr.Dropdown(label="Upscale model", choices=['realesr-animevideov3', 'realesrgan-x4plus', 'realesrgan-x4plus-anime'], interactive=True, value = "realesr-animevideov3", type="value") + ncnn_upscale_factor = gr.Dropdown(choices=['x2', 'x3', 'x4'], label="Upscale factor", interactive=True, value="x2", type="value") + ncnn_upscale_keep_imgs = gr.Checkbox(label="Keep Imgs", value=True, interactive=True) # fix value + ncnn_upscale_btn = gr.Button(value="*Upscale uploaded video*") + ncnn_upscale_btn.click(ncnn_upload_vid_to_upscale,inputs=[vid_to_upscale_chosen_file, ncnn_upscale_in_vid_fps_ui_window, ncnn_upscale_in_vid_res, ncnn_upscale_out_vid_res, ncnn_upscale_model, ncnn_upscale_factor, ncnn_upscale_keep_imgs, ffmpeg_location, ffmpeg_crf, ffmpeg_preset]) + with gr.Tab('Upscale V1'): + with gr.Column(): + selected_tab = gr.State(value=0) + with gr.Tabs(elem_id="extras_resize_mode"): + with gr.TabItem('Scale by', elem_id="extras_scale_by_tab") as tab_scale_by: + upscaling_resize = gr.Slider(minimum=1.0, maximum=8.0, step=0.05, label="Resize", value=2, elem_id="extras_upscaling_resize") + with gr.TabItem('Scale to', elem_id="extras_scale_to_tab") as tab_scale_to: + with FormRow(): + upscaling_resize_w = gr.Slider(label="Width", minimum=1, maximum=7680, step=1, value=512, elem_id="extras_upscaling_resize_w") + upscaling_resize_h = gr.Slider(label="Height", minimum=1, maximum=7680, step=1, value=512, elem_id="extras_upscaling_resize_h") + upscaling_crop = gr.Checkbox(label='Crop to fit', value=True, elem_id="extras_upscaling_crop") + with FormRow(): + extras_upscaler_1 = gr.Dropdown(label='Upscaler 1', elem_id="extras_upscaler_1", choices=[x.name for x in sh.sd_upscalers], value=sh.sd_upscalers[3].name) + extras_upscaler_2 = gr.Dropdown(label='Upscaler 2', elem_id="extras_upscaler_2", choices=[x.name for x in sh.sd_upscalers], value=sh.sd_upscalers[0].name) + with FormRow(): + with gr.Column(scale=3): + extras_upscaler_2_visibility = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="Upscaler 2 visibility", value=0.0, elem_id="extras_upscaler_2_visibility") + with gr.Column(scale=1, min_width=80): + upscale_keep_imgs = gr.Checkbox(label="Keep Imgs", elem_id="upscale_keep_imgs", value=True, interactive=True) + tab_scale_by.select(fn=lambda: 0, inputs=[], outputs=[selected_tab]) + tab_scale_to.select(fn=lambda: 1, inputs=[], outputs=[selected_tab]) + # This is the actual button that's pressed to initiate the Upscaling: + upscale_btn = gr.Button(value="*Upscale uploaded video*") + # Show a text about CLI outputs: + gr.HTML("* check your CLI for outputs") + # make the function call when the UPSCALE button is clicked + upscale_btn.click(upload_vid_to_upscale,inputs=[vid_to_upscale_chosen_file, selected_tab, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, upscale_keep_imgs, ffmpeg_location, ffmpeg_crf, ffmpeg_preset]) + # STITCH FRAMES TO VID TAB + with gr.Tab('Frames to Video') as stitch_imgs_to_vid_row: + with gr.Row(visible=False): + path_name_modifier = gr.Dropdown(label="Path name modifier", choices=['x0_pred', 'x'], value=dv.path_name_modifier, type="value", elem_id="path_name_modifier", interactive=True, visible=False) + gr.HTML(""" +

    + Important Notes: +

      +
    • Enter relative to webui folder or Full-Absolute path, and make sure it ends with something like this: '20230124234916_%05d.png', just replace 20230124234916 with your batch ID. The %05d is important, don't forget it!
    • +
    + """) + with gr.Row(variant='compact'): + image_path = gr.Textbox(label="Image path", lines=1, interactive=True, value = dv.image_path) + with gr.Row(visible=False): + mp4_path = gr.Textbox(label="MP4 path", lines=1, interactive=True, value = dv.mp4_path) + # not visible as of 06-02-23 since render_steps is disabled as well and they work together. Need to fix both. + with gr.Row(visible=False): + # rend_step Never worked - set to visible false 28-1-23 # MOVE OUT FROM HERE! + render_steps = gr.Checkbox(label="Render steps", value=dv.render_steps, interactive=True, visible=False) + ffmpeg_stitch_imgs_but = gr.Button(value="*Stitch frames to video*") + ffmpeg_stitch_imgs_but.click(direct_stitch_vid_from_frames,inputs=[image_path, fps, ffmpeg_location, ffmpeg_crf, ffmpeg_preset, add_soundtrack, soundtrack_path]) + # **OLD + NON ACTIVES AREA** + with gr.Accordion(visible=False, label='INVISIBLE') as not_in_use_accordion: + # NOT VISIBLE AS OF 09-02-23 + mask_contrast_adjust = gr.Slider(label="Mask contrast adjust", minimum=0, maximum=1, step=0.01, value=d.mask_contrast_adjust, interactive=True) + mask_brightness_adjust = gr.Slider(label="Mask brightness adjust", minimum=0, maximum=1, step=0.01, value=d.mask_brightness_adjust, interactive=True) + from_img2img_instead_of_link = gr.Checkbox(label="from_img2img_instead_of_link", value=False, interactive=False, visible=False) + # INVISIBLE AS OF 08-02 (with static value of 8 for both W and H). Was in Perlin section before Perlin Octaves/Persistence + with gr.Column(min_width=200, visible=False): + perlin_w = gr.Slider(label="Perlin W", minimum=0.1, maximum=16, step=0.1, value=da.perlin_w, interactive=True) + perlin_h = gr.Slider(label="Perlin H", minimum=0.1, maximum=16, step=0.1, value=da.perlin_h, interactive=True) + with gr.Row(visible=False): + filename_format = gr.Textbox(label="Filename format", lines=1, interactive=True, value = d.filename_format, visible=False) + with gr.Row(visible=False): + save_settings = gr.Checkbox(label="save_settings", value=d.save_settings, interactive=True) + with gr.Row(visible=False): + save_samples = gr.Checkbox(label="save_samples", value=d.save_samples, interactive=True) + display_samples = gr.Checkbox(label="display_samples", value=False, interactive=False) + # NOT VISIBLE 11-02-23 htai + with gr.Accordion('Subseed controls & More', open=False, visible=False): + # Not visible until fixed, 06-02-23 + # NOT VISIBLE as of 11-02 - we have sch now. will delete the actual params in a later date + with gr.Row(variant='compact', visible=False): + seed_enable_extras = gr.Checkbox(label="Enable subseed controls", value=False) + n_batch = gr.Number(label="N Batch", value=d.n_batch, interactive=True, precision=0, visible=False) + with gr.Row(visible=False): + save_sample_per_step = gr.Checkbox(label="Save sample per step", value=d.save_sample_per_step, interactive=True) + show_sample_per_step = gr.Checkbox(label="Show sample per step", value=d.show_sample_per_step, interactive=True) + # Gradio's Change functions - hiding and renaming elements based on other elements + fps.change(fn=change_gif_button_visibility, inputs=fps, outputs=make_gif) + r_upscale_model.change(fn=update_r_upscale_factor, inputs=r_upscale_model, outputs=r_upscale_factor) + ncnn_upscale_model.change(fn=update_r_upscale_factor, inputs=ncnn_upscale_model, outputs=ncnn_upscale_factor) + ncnn_upscale_model.change(update_upscale_out_res_by_model_name, inputs=[ncnn_upscale_in_vid_res, ncnn_upscale_model], outputs=ncnn_upscale_out_vid_res) + ncnn_upscale_factor.change(update_upscale_out_res, inputs=[ncnn_upscale_in_vid_res, ncnn_upscale_factor], outputs=ncnn_upscale_out_vid_res) + vid_to_upscale_chosen_file.change(vid_upscale_gradio_update_stats,inputs=[vid_to_upscale_chosen_file, ncnn_upscale_factor],outputs=[ncnn_upscale_in_vid_fps_ui_window, ncnn_upscale_in_vid_frame_count_window, ncnn_upscale_in_vid_res, ncnn_upscale_out_vid_res]) + animation_mode.change(fn=change_max_frames_visibility, inputs=animation_mode, outputs=max_frames) + animation_mode.change(fn=change_diffusion_cadence_visibility, inputs=animation_mode, outputs=diffusion_cadence) + animation_mode.change(fn=disble_3d_related_stuff, inputs=animation_mode, outputs=depth_3d_warping_accord) + animation_mode.change(fn=disble_3d_related_stuff, inputs=animation_mode, outputs=fov_accord) + animation_mode.change(fn=disble_3d_related_stuff, inputs=animation_mode, outputs=only_3d_motion_column) + animation_mode.change(fn=enable_2d_related_stuff, inputs=animation_mode, outputs=only_2d_motion_column) + animation_mode.change(fn=disable_by_interpolation, inputs=animation_mode, outputs=force_grayscale_column) + animation_mode.change(fn=disable_pers_flip_accord, inputs=animation_mode, outputs=perspective_flip_accord) + animation_mode.change(fn=disable_pers_flip_accord, inputs=animation_mode, outputs=both_anim_mode_motion_params_column) + #Hybrid related: + animation_mode.change(fn=show_hybrid_html_msg, inputs=animation_mode, outputs=hybrid_msg_html) + animation_mode.change(fn=change_hybrid_tab_status, inputs=animation_mode, outputs=hybrid_sch_accord) + animation_mode.change(fn=change_hybrid_tab_status, inputs=animation_mode, outputs=hybrid_settings_accord) + animation_mode.change(fn=change_hybrid_tab_status, inputs=animation_mode, outputs=humans_masking_accord) + hybrid_comp_mask_type.change(fn=change_comp_mask_x_visibility, inputs=hybrid_comp_mask_type, outputs=hybrid_comp_mask_row) + hybrid_motion.change(fn=disable_by_non_optical_flow, inputs=hybrid_motion, outputs=hybrid_flow_method) + hybrid_motion.change(fn=disable_by_comp_mask, inputs=hybrid_motion, outputs=hybrid_motion_use_prev_img) + hybrid_composite.change(fn=disable_by_hybrid_composite_dynamic, inputs=[hybrid_composite, hybrid_comp_mask_type], outputs=hybrid_comp_mask_row) + hybrid_composite_outputs = [humans_masking_accord, hybrid_sch_accord, hybrid_comp_mask_type, hybrid_use_first_frame_as_init_image] + for output in hybrid_composite_outputs: + hybrid_composite.change(fn=disable_by_hybrid_composite, inputs=hybrid_composite, outputs=output) + hybrid_comp_mask_type_outputs = [hybrid_comp_mask_blend_alpha_schedule_row, hybrid_comp_mask_contrast_schedule_row, hybrid_comp_mask_auto_contrast_cutoff_high_schedule_row, hybrid_comp_mask_auto_contrast_cutoff_low_schedule_row] + for output in hybrid_comp_mask_type_outputs: + hybrid_comp_mask_type.change(fn=disable_by_comp_mask, inputs=hybrid_comp_mask_type, outputs=output) + # End of hybrid related + seed_behavior.change(fn=change_seed_iter_visibility, inputs=seed_behavior, outputs=seed_iter_N_row) + seed_behavior.change(fn=change_seed_schedule_visibility, inputs=seed_behavior, outputs=seed_schedule_row) + color_coherence.change(fn=change_color_coherence_video_every_N_frames_visibility, inputs=color_coherence, outputs=color_coherence_video_every_N_frames_row) + noise_type.change(fn=change_perlin_visibility, inputs=noise_type, outputs=perlin_row) + skip_video_for_run_all_outputs = [fps_out_format_row, soundtrack_row, ffmpeg_quality_accordion, store_frames_in_ram, make_gif, r_upscale_row] + for output in skip_video_for_run_all_outputs: + skip_video_for_run_all.change(fn=change_visibility_from_skip_video, inputs=skip_video_for_run_all, outputs=output) + # END OF UI TABS + stuff = locals() + stuff = {**stuff, **controlnet_dict} + stuff.pop('controlnet_dict') + return stuff + +### SETTINGS STORAGE UPDATE! 2023-01-27 +### To Reduce The Number Of Settings Overrides, +### They Are Being Passed As Dictionaries +### It Would Have Been Also Nice To Retrieve Them +### From Functions Like Deforumoutputargs(), +### But Over Time There Was Some Cross-Polination, +### So They Are Now Hardcoded As 'List'-Strings Below +### If you're adding a new setting, add it to one of the lists +### besides writing it in the setup functions above + +anim_args_names = str(r'''animation_mode, max_frames, border, + angle, zoom, translation_x, translation_y, translation_z, + rotation_3d_x, rotation_3d_y, rotation_3d_z, + enable_perspective_flip, + perspective_flip_theta, perspective_flip_phi, perspective_flip_gamma, perspective_flip_fv, + noise_schedule, strength_schedule, contrast_schedule, cfg_scale_schedule, pix2pix_img_cfg_scale_schedule, + enable_subseed_scheduling, subseed_schedule, subseed_strength_schedule, + enable_steps_scheduling, steps_schedule, + fov_schedule, near_schedule, far_schedule, + seed_schedule, + enable_sampler_scheduling, sampler_schedule, + mask_schedule, use_noise_mask, noise_mask_schedule, + enable_checkpoint_scheduling, checkpoint_schedule, + enable_clipskip_scheduling, clipskip_schedule, + kernel_schedule, sigma_schedule, amount_schedule, threshold_schedule, + color_coherence, color_coherence_video_every_N_frames, color_force_grayscale, + diffusion_cadence, + noise_type, perlin_w, perlin_h, perlin_octaves, perlin_persistence, + use_depth_warping, midas_weight, + padding_mode, sampling_mode, save_depth_maps, + video_init_path, extract_nth_frame, extract_from_frame, extract_to_frame, overwrite_extracted_frames, + use_mask_video, video_mask_path, + resume_from_timestring, resume_timestring''' + ).replace("\n", "").replace("\r", "").replace(" ", "").split(',') +hybrid_args_names = str(r'''hybrid_generate_inputframes, hybrid_generate_human_masks, hybrid_use_first_frame_as_init_image, + hybrid_motion, hybrid_motion_use_prev_img, hybrid_flow_method, hybrid_composite, hybrid_comp_mask_type, hybrid_comp_mask_inverse, + hybrid_comp_mask_equalize, hybrid_comp_mask_auto_contrast, hybrid_comp_save_extra_frames, + hybrid_comp_alpha_schedule, hybrid_comp_mask_blend_alpha_schedule, hybrid_comp_mask_contrast_schedule, + hybrid_comp_mask_auto_contrast_cutoff_high_schedule, hybrid_comp_mask_auto_contrast_cutoff_low_schedule''' + ).replace("\n", "").replace("\r", "").replace(" ", "").split(',') +args_names = str(r'''W, H, tiling, restore_faces, + seed, sampler, + seed_enable_extras, seed_resize_from_w, seed_resize_from_h, + steps, ddim_eta, + n_batch, + save_settings, save_samples, display_samples, + save_sample_per_step, show_sample_per_step, + batch_name, filename_format, + seed_behavior, seed_iter_N, + use_init, from_img2img_instead_of_link, strength_0_no_init, strength, init_image, + use_mask, use_alpha_as_mask, invert_mask, overlay_mask, + mask_file, mask_contrast_adjust, mask_brightness_adjust, mask_overlay_blur, + fill, full_res_mask, full_res_mask_padding, + reroll_blank_frames''' + ).replace("\n", "").replace("\r", "").replace(" ", "").split(',') +video_args_names = str(r'''skip_video_for_run_all, + fps, make_gif, output_format, ffmpeg_location, ffmpeg_crf, ffmpeg_preset, + add_soundtrack, soundtrack_path, + r_upscale_video, r_upscale_model, r_upscale_factor, r_upscale_keep_imgs, + render_steps, + path_name_modifier, image_path, mp4_path, store_frames_in_ram, + frame_interpolation_engine, frame_interpolation_x_amount, frame_interpolation_slow_mo_enabled, frame_interpolation_slow_mo_amount, + frame_interpolation_keep_imgs''' + ).replace("\n", "").replace("\r", "").replace(" ", "").split(',') +parseq_args_names = str(r'''parseq_manifest, parseq_use_deltas''' + ).replace("\n", "").replace("\r", "").replace(" ", "").split(',') +loop_args_names = str(r'''use_looper, init_images, image_strength_schedule, blendFactorMax, blendFactorSlope, + tweening_frames_schedule, color_correction_factor''' + ).replace("\n", "").replace("\r", "").replace(" ", "").split(',') + +component_names = ['override_settings_with_file', 'custom_settings_file'] + anim_args_names +['animation_prompts', 'animation_prompts_positive', 'animation_prompts_negative'] + args_names + video_args_names + parseq_args_names + hybrid_args_names + loop_args_names + controlnet_component_names() +settings_component_names = [name for name in component_names if name not in video_args_names] + +def setup_deforum_setting_ui(self, is_img2img, is_extension = True): + ds = setup_deforum_setting_dictionary(self, is_img2img, is_extension) + return [ds[name] for name in (['btn'] + component_names)] + +def pack_anim_args(args_dict): + return {name: args_dict[name] for name in (anim_args_names + hybrid_args_names)} + +def pack_args(args_dict): + args_dict = {name: args_dict[name] for name in args_names} + args_dict['precision'] = 'autocast' + args_dict['scale'] = 7 + args_dict['subseed'] = -1 + args_dict['subseed_strength'] = 0 + args_dict['C'] = 4 + args_dict['f'] = 8 + args_dict['timestring'] = "" + args_dict['init_latent'] = None + args_dict['init_sample'] = None + args_dict['init_c'] = None + args_dict['noise_mask'] = None + args_dict['seed_internal'] = 0 + return args_dict + +def pack_video_args(args_dict): + return {name: args_dict[name] for name in video_args_names} + +def pack_parseq_args(args_dict): + return {name: args_dict[name] for name in parseq_args_names} + +def pack_loop_args(args_dict): + return {name: args_dict[name] for name in loop_args_names} + +def pack_controlnet_args(args_dict): + return {name: args_dict[name] for name in controlnet_component_names()} + +def process_args(args_dict_main): + override_settings_with_file = args_dict_main['override_settings_with_file'] + custom_settings_file = args_dict_main['custom_settings_file'] + args_dict = pack_args(args_dict_main) + anim_args_dict = pack_anim_args(args_dict_main) + video_args_dict = pack_video_args(args_dict_main) + parseq_args_dict = pack_parseq_args(args_dict_main) + loop_args_dict = pack_loop_args(args_dict_main) + controlnet_args_dict = pack_controlnet_args(args_dict_main) + + import json + + root = SimpleNamespace(**Root()) + root.p = args_dict_main['p'] + p = root.p + root.animation_prompts = json.loads(args_dict_main['animation_prompts']) + positive_prompts = args_dict_main['animation_prompts_positive'] + negative_prompts = args_dict_main['animation_prompts_negative'] + # remove --neg from negative_prompts if recieved by mistake + negative_prompts = negative_prompts.replace('--neg', '') + for key in root.animation_prompts: + animationPromptCurr = root.animation_prompts[key] + root.animation_prompts[key] = f"{positive_prompts} {animationPromptCurr} {'' if '--neg' in animationPromptCurr else '--neg'} {negative_prompts}" + from deforum_helpers.settings import load_args + + if override_settings_with_file: + load_args(args_dict, anim_args_dict, parseq_args_dict, loop_args_dict, controlnet_args_dict, custom_settings_file, root) + + if not os.path.exists(root.models_path): + os.mkdir(root.models_path) + + args = SimpleNamespace(**args_dict) + anim_args = SimpleNamespace(**anim_args_dict) + video_args = SimpleNamespace(**video_args_dict) + parseq_args = SimpleNamespace(**parseq_args_dict) + loop_args = SimpleNamespace(**loop_args_dict) + controlnet_args = SimpleNamespace(**controlnet_args_dict) + + p.width, p.height = map(lambda x: x - x % 64, (args.W, args.H)) + p.steps = args.steps + p.seed = args.seed + p.sampler_name = args.sampler + p.batch_size = args.n_batch + p.tiling = args.tiling + p.restore_faces = args.restore_faces + p.seed_enable_extras = args.seed_enable_extras + p.subseed = args.subseed + p.subseed_strength = args.subseed_strength + p.seed_resize_from_w = args.seed_resize_from_w + p.seed_resize_from_h = args.seed_resize_from_h + p.fill = args.fill + p.ddim_eta = args.ddim_eta + + # TODO: Handle batch name dynamically? + current_arg_list = [args, anim_args, video_args, parseq_args] + args.outdir = os.path.join(p.outpath_samples, args.batch_name) + root.outpath_samples = args.outdir + args.outdir = os.path.join(os.getcwd(), args.outdir) + if not os.path.exists(args.outdir): + os.makedirs(args.outdir) + + args.seed = get_fixed_seed(args.seed) + + args.timestring = time.strftime('%Y%m%d%H%M%S') + args.strength = max(0.0, min(1.0, args.strength)) + + if not args.use_init: + args.init_image = None + + if anim_args.animation_mode == 'None': + anim_args.max_frames = 1 + elif anim_args.animation_mode == 'Video Input': + args.use_init = True + + return root, args, anim_args, video_args, parseq_args, loop_args, controlnet_args + +def print_args(args): + print("ARGS: /n") + for key, value in args.__dict__.items(): + print(f"{key}: {value}") + +# Local gradio-to-frame-interoplation function. *Needs* to stay here since we do Root() and use gradio elements directly, to be changed in the future +def upload_vid_to_interpolate(file, engine, x_am, sl_enabled, sl_am, keep_imgs, f_location, f_crf, f_preset, in_vid_fps): + # print msg and do nothing if vid not uploaded or interp_x not provided + if not file or engine == 'None': + return print("Please upload a video and set a proper value for 'Interp X'. Can't interpolate x0 times :)") + + root_params = Root() + f_models_path = root_params['models_path'] + + process_interp_vid_upload_logic(file, engine, x_am, sl_enabled, sl_am, keep_imgs, f_location, f_crf, f_preset, in_vid_fps, f_models_path, file.orig_name) + +# Local gradio-to-upscalers function. *Needs* to stay here since we do Root() and use gradio elements directly, to be changed in the future +def upload_vid_to_upscale(vid_to_upscale_chosen_file, selected_tab, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, upscale_keep_imgs, ffmpeg_location, ffmpeg_crf, ffmpeg_preset): + # print msg and do nothing if vid not uploaded + if not vid_to_upscale_chosen_file: + return print("Please upload a video :)") + + process_upscale_vid_upload_logic(vid_to_upscale_chosen_file, selected_tab, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, vid_to_upscale_chosen_file.orig_name, upscale_keep_imgs, ffmpeg_location, ffmpeg_crf, ffmpeg_preset) + +def ncnn_upload_vid_to_upscale(vid_path, in_vid_fps, in_vid_res, out_vid_res, upscale_model, upscale_factor, keep_imgs, f_location, f_crf, f_preset): + if vid_path is None: + print("Please upload a video :)") + return + root_params = Root() + f_models_path = root_params['models_path'] + current_user = root_params['current_user_os'] + process_ncnn_upscale_vid_upload_logic(vid_path, in_vid_fps, in_vid_res, out_vid_res, f_models_path, upscale_model, upscale_factor, keep_imgs, f_location, f_crf, f_preset, current_user) \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/blank_frame_reroll.py b/extensions/deforum/scripts/deforum_helpers/blank_frame_reroll.py new file mode 100644 index 0000000000000000000000000000000000000000..e7c5954921ffada030cdf24104b211e630a05295 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/blank_frame_reroll.py @@ -0,0 +1,24 @@ +from .generate import generate +#WebUI +from modules.shared import opts, cmd_opts, state + +def blank_frame_reroll(image, args, root, frame_idx): + patience = 10 + print("Blank frame detected! If you don't have the NSFW filter enabled, this may be due to a glitch!") + if args.reroll_blank_frames == 'reroll': + while not image.getbbox(): + print("Rerolling with +1 seed...") + args.seed += 1 + image = generate(args, root, frame_idx) + patience -= 1 + if patience == 0: + print("Rerolling with +1 seed failed for 10 iterations! Try setting webui's precision to 'full' and if it fails, please report this to the devs! Interrupting...") + state.interrupted = True + state.current_image = image + return None + elif args.reroll_blank_frames == 'interrupt': + print("Interrupting to save your eyes...") + state.interrupted = True + state.current_image = image + return None + return image \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/colors.py b/extensions/deforum/scripts/deforum_helpers/colors.py new file mode 100644 index 0000000000000000000000000000000000000000..6ec81e197ef2b918a352d04f57337b956137b0e6 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/colors.py @@ -0,0 +1,16 @@ +from skimage.exposure import match_histograms +import cv2 + +def maintain_colors(prev_img, color_match_sample, mode): + if mode == 'Match Frame 0 RGB': + return match_histograms(prev_img, color_match_sample, multichannel=True) + elif mode == 'Match Frame 0 HSV': + prev_img_hsv = cv2.cvtColor(prev_img, cv2.COLOR_RGB2HSV) + color_match_hsv = cv2.cvtColor(color_match_sample, cv2.COLOR_RGB2HSV) + matched_hsv = match_histograms(prev_img_hsv, color_match_hsv, multichannel=True) + return cv2.cvtColor(matched_hsv, cv2.COLOR_HSV2RGB) + else: # Match Frame 0 LAB + prev_img_lab = cv2.cvtColor(prev_img, cv2.COLOR_RGB2LAB) + color_match_lab = cv2.cvtColor(color_match_sample, cv2.COLOR_RGB2LAB) + matched_lab = match_histograms(prev_img_lab, color_match_lab, multichannel=True) + return cv2.cvtColor(matched_lab, cv2.COLOR_LAB2RGB) \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/composable_masks.py b/extensions/deforum/scripts/deforum_helpers/composable_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a509a1a517df1fcca8c7e1dadaaa9be97f5769 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/composable_masks.py @@ -0,0 +1,198 @@ +# At the moment there are three types of masks: mask from variable, file mask and word mask +# Variable masks include init_mask for the predefined whole-video mask, frame_mask from video-masking system +# and human_mask for a model which better segments people in the background video +# They are put in {}-brackets +# Word masks are framed with <>-bracets, like: , +# File masks are put in []-brackes +# Empty strings are counted as the whole frame +# We want to put them all into a sequence of boolean operations + +# Example: +# \ +# (({human_mask} & [mask1.png]) ^ ) + +# Writing the parser for the boolean sequence +# using regex and PIL operations +import re +from .load_images import get_mask_from_file, check_mask_for_errors, blank_if_none +from .word_masking import get_word_mask +from torch import Tensor +import PIL +from PIL import Image, ImageChops + +# val_masks: name, PIL Image mask +# Returns an image in mode '1' (needed for bool ops), convert to 'L' in the sender function +def compose_mask(root, args, mask_seq, val_masks, frame_image, inner_idx:int = 0): + # Compose_mask recursively: go to inner brackets, then b-op it and go upstack + + # Step 1: + # recursive parenthesis pass + # regex is not powerful here + + seq = "" + inner_seq = "" + parentheses_counter = 0 + + for c in mask_seq: + if c == ')': + parentheses_counter = parentheses_counter - 1 + if parentheses_counter > 0: + inner_seq += c + if c == '(': + parentheses_counter = parentheses_counter + 1 + if parentheses_counter == 0: + if len(inner_seq) > 0: + inner_idx += 1 + seq += compose_mask(root, args, inner_seq, val_masks, frame_image, inner_idx) + inner_seq = "" + else: + seq += c + + if parentheses_counter != 0: + raise Exception('Mismatched parentheses in {mask_seq}!') + + mask_seq = seq + + # Step 2: + # Load the word masks and file masks as vars + + # File masks + pattern = r'\[(?P[\S\s]*?)\]' + + def parse(match_object): + nonlocal inner_idx + inner_idx += 1 + content = match_object.groupdict()['inner'] + val_masks[str(inner_idx)] = get_mask_from_file(content, args).convert('1') # TODO: add caching + return f"{{{inner_idx}}}" + + mask_seq = re.sub(pattern, parse, mask_seq) + + # Word masks + pattern = r'<(?P[\S\s]*?)>' + + def parse(match_object): + nonlocal inner_idx + inner_idx += 1 + content = match_object.groupdict()['inner'] + val_masks[str(inner_idx)] = get_word_mask(root, frame_image, content).convert('1') + return f"{{{inner_idx}}}" + + mask_seq = re.sub(pattern, parse, mask_seq) + + # Now that all inner parenthesis are eliminated we're left with a linear string + + # Step 3: + # Boolean operations with masks + # Operators: invert !, and &, or |, xor ^, difference \ + + # Invert vars with '!' + pattern = r'![\S\s]*{(?P[\S\s]*?)}' + def parse(match_object): + nonlocal inner_idx + inner_idx += 1 + content = match_object.groupdict()['inner'] + savename = content + if content in root.mask_preset_names: + inner_idx += 1 + savename = str(inner_idx) + val_masks[savename] = ImageChops.invert(val_masks[content]) + return f"{{{savename}}}" + + mask_seq = re.sub(pattern, parse, mask_seq) + + # Multiply neighbouring vars with '&' + # Wait for replacements stall (like in Markov chains) + while True: + pattern = r'{(?P[\S\s]*?)}[\s]*&[\s]*{(?P[\S\s]*?)}' + def parse(match_object): + nonlocal inner_idx + inner_idx += 1 + content = match_object.groupdict()['inner1'] + content_second = match_object.groupdict()['inner2'] + savename = content + if content in root.mask_preset_names: + inner_idx += 1 + savename = str(inner_idx) + val_masks[savename] = ImageChops.logical_and(val_masks[content], val_masks[content_second]) + return f"{{{savename}}}" + + prev_mask_seq = mask_seq + mask_seq = re.sub(pattern, parse, mask_seq) + if mask_seq is prev_mask_seq: + break + + # Add neighbouring vars with '|' + while True: + pattern = r'{(?P[\S\s]*?)}[\s]*?\|[\s]*?{(?P[\S\s]*?)}' + def parse(match_object): + nonlocal inner_idx + inner_idx += 1 + content = match_object.groupdict()['inner1'] + content_second = match_object.groupdict()['inner2'] + savename = content + if content in root.mask_preset_names: + inner_idx += 1 + savename = str(inner_idx) + val_masks[savename] = ImageChops.logical_or(val_masks[content], val_masks[content_second]) + return f"{{{savename}}}" + + prev_mask_seq = mask_seq + mask_seq = re.sub(pattern, parse, mask_seq) + if mask_seq is prev_mask_seq: + break + + # Mutually exclude neighbouring vars with '^' + while True: + pattern = r'{(?P[\S\s]*?)}[\s]*\^[\s]*{(?P[\S\s]*?)}' + def parse(match_object): + nonlocal inner_idx + inner_idx += 1 + content = match_object.groupdict()['inner1'] + content_second = match_object.groupdict()['inner2'] + savename = content + if content in root.mask_preset_names: + inner_idx += 1 + savename = str(inner_idx) + val_masks[savename] = ImageChops.logical_xor(val_masks[content], val_masks[content_second]) + return f"{{{savename}}}" + + prev_mask_seq = mask_seq + mask_seq = re.sub(pattern, parse, mask_seq) + if mask_seq is prev_mask_seq: + break + + # Set-difference the regions with '\' + while True: + pattern = r'{(?P[\S\s]*?)}[\s]*\\[\s]*{(?P[\S\s]*?)}' + def parse(match_object): + content = match_object.groupdict()['inner1'] + content_second = match_object.groupdict()['inner2'] + savename = content + if content in root.mask_preset_names: + nonlocal inner_idx + inner_idx += 1 + savename = str(inner_idx) + val_masks[savename] = ImageChops.logical_and(val_masks[content], ImageChops.invert(val_masks[content_second])) + return f"{{{savename}}}" + + prev_mask_seq = mask_seq + mask_seq = re.sub(pattern, parse, mask_seq) + if mask_seq is prev_mask_seq: + break + + # Step 4: + # Output + # Now we should have a single var left to return. If not, raise an error message + pattern = r'{(?P[\S\s]*?)}' + matches = re.findall(pattern, mask_seq) + + if len(matches) != 1: + raise Exception(f'Wrong composable mask expression format! Broken mask sequence: {mask_seq}') + + return f"{{{matches[0]}}}" + +def compose_mask_with_check(root, args, mask_seq, val_masks, frame_image): + for k, v in val_masks.items(): + val_masks[k] = blank_if_none(v, args.W, args.H, '1').convert('1') + return check_mask_for_errors(val_masks[compose_mask(root, args, mask_seq, val_masks, frame_image, 0)[1:-1]].convert('L')) diff --git a/extensions/deforum/scripts/deforum_helpers/deforum_controlnet.py b/extensions/deforum/scripts/deforum_helpers/deforum_controlnet.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b72c8d4723a32721ce3c1242d6b8b33a7b21b2 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/deforum_controlnet.py @@ -0,0 +1,462 @@ +# This helper script is responsible for ControlNet/Deforum integration +# https://github.com/Mikubill/sd-webui-controlnet — controlnet repo + +import os, sys +import gradio as gr +import scripts +import modules.scripts as scrpts +from PIL import Image +import numpy as np +from modules.processing import process_images +from .rich import console +from rich.table import Table +from rich import box + +has_controlnet = None + +def find_controlnet(): + global has_controlnet + if has_controlnet is not None: + return has_controlnet + + try: + from scripts import controlnet + except Exception as e: + print(f'\033[33mFailed to import controlnet! The exact error is {e}. Deforum support for ControlNet will not be activated\033[0m') + has_controlnet = False + return False + has_controlnet = True + print(f"\033[0;32m*Deforum ControlNet support: enabled*\033[0m") + return True + +# The most parts below are plainly copied from controlnet.py +# TODO: come up with a cleaner way + +gradio_compat = True +try: + from distutils.version import LooseVersion + from importlib_metadata import version + if LooseVersion(version("gradio")) < LooseVersion("3.10"): + gradio_compat = False +except ImportError: + pass + +# svgsupports +svgsupport = False +try: + import io + import base64 + from svglib.svglib import svg2rlg + from reportlab.graphics import renderPM + svgsupport = True +except ImportError: + pass + +def ControlnetArgs(): + controlnet_enabled = False + controlnet_scribble_mode = False + controlnet_rgbbgr_mode = False + controlnet_lowvram = False + controlnet_module = "none" + controlnet_model = "None" + controlnet_weight = 1.0 + controlnet_guidance_strength = 1.0 + blendFactorMax = "0:(0.35)" + blendFactorSlope = "0:(0.25)" + tweening_frames_schedule = "0:(20)" + color_correction_factor = "0:(0.075)" + return locals() + +def setup_controlnet_ui_raw(): + # Already under an accordion + from scripts import controlnet + from scripts.controlnet import update_cn_models, cn_models, cn_models_names + + refresh_symbol = '\U0001f504' # 🔄 + switch_values_symbol = '\U000021C5' # ⇅ + model_dropdowns = [] + infotext_fields = [] + # Main part + class ToolButton(gr.Button, gr.components.FormComponent): + """Small button with single emoji as text, fits inside gradio forms""" + + def __init__(self, **kwargs): + super().__init__(variant="tool", **kwargs) + + def get_block_name(self): + return "button" + + from scripts.processor import canny, midas, midas_normal, leres, hed, mlsd, openpose, pidinet, simple_scribble, fake_scribble, uniformer + + preprocessor = { + "none": lambda x, *args, **kwargs: x, + "canny": canny, + "depth": midas, + "depth_leres": leres, + "hed": hed, + "mlsd": mlsd, + "normal_map": midas_normal, + "openpose": openpose, + # "openpose_hand": openpose_hand, + "pidinet": pidinet, + # "scribble": simple_scribble, + "fake_scribble": fake_scribble, + "segmentation": uniformer, + } + + # Copying the main ControlNet widgets while getting rid of static elements such as the scribble pad + with gr.Row(): + controlnet_enabled = gr.Checkbox(label='Enable', value=False) + controlnet_scribble_mode = gr.Checkbox(label='Scribble Mode (Invert colors)', value=False, visible=False) + controlnet_rgbbgr_mode = gr.Checkbox(label='RGB to BGR', value=False, visible=False) + controlnet_lowvram = gr.Checkbox(label='Low VRAM', value=False, visible=False) + + def refresh_all_models(*inputs): + update_cn_models() + + dd = inputs[0] + selected = dd if dd in cn_models else "None" + return gr.Dropdown.update(value=selected, choices=list(cn_models.keys())) + + with gr.Row(visible=False) as cn_mod_row: + controlnet_module = gr.Dropdown(list(preprocessor.keys()), label=f"Preprocessor", value="none") + controlnet_model = gr.Dropdown(list(cn_models.keys()), label=f"Model", value="None") + refresh_models = ToolButton(value=refresh_symbol) + refresh_models.click(refresh_all_models, controlnet_model, controlnet_model) + # ctrls += (refresh_models, ) + with gr.Row(visible=False) as cn_weight_row: + controlnet_weight = gr.Slider(label=f"Weight", value=1.0, minimum=0.0, maximum=2.0, step=.05) + controlnet_guidance_strength = gr.Slider(label="Guidance strength (T)", value=1.0, minimum=0.0, maximum=1.0, interactive=True) + # ctrls += (module, model, weight,) + # model_dropdowns.append(model) + + # advanced options + controlnet_advanced = gr.Column(visible=False) + with controlnet_advanced: + controlnet_processor_res = gr.Slider(label="Annotator resolution", value=64, minimum=64, maximum=2048, interactive=False) + controlnet_threshold_a = gr.Slider(label="Threshold A", value=64, minimum=64, maximum=1024, interactive=False) + controlnet_threshold_b = gr.Slider(label="Threshold B", value=64, minimum=64, maximum=1024, interactive=False) + + if gradio_compat: + controlnet_module.change(build_sliders, inputs=[controlnet_module], outputs=[controlnet_processor_res, controlnet_threshold_a, controlnet_threshold_b, controlnet_advanced]) + + infotext_fields.extend([ + (controlnet_module, f"ControlNet Preprocessor"), + (controlnet_model, f"ControlNet Model"), + (controlnet_weight, f"ControlNet Weight"), + ]) + + with gr.Row(visible=False) as cn_env_row: + controlnet_resize_mode = gr.Radio(choices=["Envelope (Outer Fit)", "Scale to Fit (Inner Fit)", "Just Resize"], value="Scale to Fit (Inner Fit)", label="Resize Mode") + + # Video input to be fed into ControlNet + #input_video_url = gr.Textbox(source='upload', type='numpy', tool='sketch') # TODO + controlnet_input_video_chosen_file = gr.File(label="ControlNet Video Input", interactive=True, file_count="single", file_types=["video"], elem_id="controlnet_input_video_chosen_file", visible=False) + controlnet_input_video_mask_chosen_file = gr.File(label="ControlNet Video Mask Input", interactive=True, file_count="single", file_types=["video"], elem_id="controlnet_input_video_mask_chosen_file", visible=False) + + cn_hide_output_list = [controlnet_scribble_mode,controlnet_rgbbgr_mode,controlnet_lowvram,cn_mod_row,cn_weight_row,cn_env_row,controlnet_input_video_chosen_file,controlnet_input_video_mask_chosen_file] + for cn_output in cn_hide_output_list: + controlnet_enabled.change(fn=hide_ui_by_cn_status, inputs=controlnet_enabled,outputs=cn_output) + + return locals() + + +def setup_controlnet_ui(): + if not find_controlnet(): + gr.HTML(""" + ControlNet not found. Please install it :) + """, elem_id='controlnet_not_found_html_msg') + return {} + + return setup_controlnet_ui_raw() + +def controlnet_component_names(): + if not find_controlnet(): + return [] + + controlnet_args_names = str(r'''controlnet_input_video_chosen_file, controlnet_input_video_mask_chosen_file, +controlnet_enabled, controlnet_scribble_mode, controlnet_rgbbgr_mode, controlnet_lowvram, +controlnet_module, controlnet_model, +controlnet_weight, controlnet_guidance_strength, +controlnet_processor_res, +controlnet_threshold_a, controlnet_threshold_b, controlnet_resize_mode''' + ).replace("\n", "").replace("\r", "").replace(" ", "").split(',') + + return controlnet_args_names + +def is_controlnet_enabled(controlnet_args): + return 'controlnet_enabled' in vars(controlnet_args) and controlnet_args.controlnet_enabled + +def process_txt2img_with_controlnet(p, args, anim_args, loop_args, controlnet_args, root, frame_idx = 1): + # TODO: use init image and mask here + p.control_net_enabled = False # we don't want to cause concurrence + p.init_images = [] + controlnet_frame_path = os.path.join(args.outdir, 'controlnet_inputframes', f"{frame_idx:05}.jpg") + controlnet_mask_frame_path = os.path.join(args.outdir, 'controlnet_maskframes', f"{frame_idx:05}.jpg") + cn_mask_np = None + cn_image_np = None + + if not os.path.exists(controlnet_frame_path) and not os.path.exists(controlnet_mask_frame_path): + print(f'\033[33mNeither the base nor the masking frames for ControlNet were found. Using the regular pipeline\033[0m') + from .deforum_controlnet_hardcode import restore_networks + unet = p.sd_model.model.diffusion_model + restore_networks(unet) + return process_images(p) + + if os.path.exists(controlnet_frame_path): + cn_image_np = Image.open(controlnet_frame_path).convert("RGB") + + if os.path.exists(controlnet_mask_frame_path): + cn_mask_np = Image.open(controlnet_mask_frame_path).convert("RGB") + + cn_args = { + "enabled": True, + "module": controlnet_args.controlnet_module, + "model": controlnet_args.controlnet_model, + "weight": controlnet_args.controlnet_weight, + "input_image": {'image': cn_image_np, 'mask': cn_mask_np}, + "scribble_mode": controlnet_args.controlnet_scribble_mode, + "resize_mode": controlnet_args.controlnet_resize_mode, + "rgbbgr_mode": controlnet_args.controlnet_rgbbgr_mode, + "lowvram": controlnet_args.controlnet_lowvram, + "processor_res": controlnet_args.controlnet_processor_res, + "threshold_a": controlnet_args.controlnet_threshold_a, + "threshold_b": controlnet_args.controlnet_threshold_b, + "guidance_strength": controlnet_args.controlnet_guidance_strength,"guidance_strength": controlnet_args.controlnet_guidance_strength, + } + + from .deforum_controlnet_hardcode import process + p.script_args = ( + cn_args["enabled"], + cn_args["module"], + cn_args["model"], + cn_args["weight"], + cn_args["input_image"], + cn_args["scribble_mode"], + cn_args["resize_mode"], + cn_args["rgbbgr_mode"], + cn_args["lowvram"], + cn_args["processor_res"], + cn_args["threshold_a"], + cn_args["threshold_b"], + cn_args["guidance_strength"], + ) + + table = Table(title="ControlNet params",padding=0, box=box.ROUNDED) + + field_names = [] + field_names += ["module", "model", "weight", "guidance", "scribble", "resize", "rgb->bgr", "proc res", "thr a", "thr b"] + for field_name in field_names: + table.add_column(field_name, justify="center") + + rows = [] + rows += [cn_args["module"], cn_args["model"], cn_args["weight"], cn_args["guidance_strength"], cn_args["scribble_mode"], cn_args["resize_mode"], cn_args["rgbbgr_mode"], cn_args["processor_res"], cn_args["threshold_a"], cn_args["threshold_b"]] + rows = [str(x) for x in rows] + + table.add_row(*rows) + + console.print(table) + + processed = process(p, *(p.script_args)) + + if processed is None: # the script just swaps the pipeline, so failing is OK for the first time + processed = process_images(p) + + if processed is None: # now it's definitely not OK + raise Exception("\033[31mFailed to process a frame with ControlNet enabled!\033[0m") + + p.close() + + return processed + +def process_img2img_with_controlnet(p, args, anim_args, loop_args, controlnet_args, root, frame_idx = 0): + p.control_net_enabled = False # we don't want to cause concurrence + controlnet_frame_path = os.path.join(args.outdir, 'controlnet_inputframes', f"{frame_idx:05}.jpg") + controlnet_mask_frame_path = os.path.join(args.outdir, 'controlnet_maskframes', f"{frame_idx:05}.jpg") + + print(f'Reading ControlNet base frame {frame_idx} at {controlnet_frame_path}') + print(f'Reading ControlNet mask frame {frame_idx} at {controlnet_mask_frame_path}') + + cn_mask_np = None + cn_image_np = None + + if not os.path.exists(controlnet_frame_path) and not os.path.exists(controlnet_mask_frame_path): + print(f'\033[33mNeither the base nor the masking frames for ControlNet were found. Using the regular pipeline\033[0m') + return process_images(p) + + if os.path.exists(controlnet_frame_path): + cn_image_np = np.array(Image.open(controlnet_frame_path).convert("RGB")).astype('uint8') + + if os.path.exists(controlnet_mask_frame_path): + cn_mask_np = np.array(Image.open(controlnet_mask_frame_path).convert("RGB")).astype('uint8') + + cn_args = { + "enabled": True, + "module": controlnet_args.controlnet_module, + "model": controlnet_args.controlnet_model, + "weight": controlnet_args.controlnet_weight, + "input_image": {'image': cn_image_np, 'mask': cn_mask_np}, + "scribble_mode": controlnet_args.controlnet_scribble_mode, + "resize_mode": controlnet_args.controlnet_resize_mode, + "rgbbgr_mode": controlnet_args.controlnet_rgbbgr_mode, + "lowvram": controlnet_args.controlnet_lowvram, + "processor_res": controlnet_args.controlnet_processor_res, + "threshold_a": controlnet_args.controlnet_threshold_a, + "threshold_b": controlnet_args.controlnet_threshold_b, + "guidance_strength": controlnet_args.controlnet_guidance_strength, + } + + from .deforum_controlnet_hardcode import process + p.script_args = ( + cn_args["enabled"], + cn_args["module"], + cn_args["model"], + cn_args["weight"], + cn_args["input_image"], + cn_args["scribble_mode"], + cn_args["resize_mode"], + cn_args["rgbbgr_mode"], + cn_args["lowvram"], + cn_args["processor_res"], + cn_args["threshold_a"], + cn_args["threshold_b"], + cn_args["guidance_strength"], + ) + + table = Table(title="ControlNet params",padding=0, box=box.ROUNDED) + + field_names = [] + field_names += ["module", "model", "weight", "guidance", "scribble", "resize", "rgb->bgr", "proc res", "thr a", "thr b"] + for field_name in field_names: + table.add_column(field_name, justify="center") + + rows = [] + rows += [cn_args["module"], cn_args["model"], cn_args["weight"], cn_args["guidance_strength"], cn_args["scribble_mode"], cn_args["resize_mode"], cn_args["rgbbgr_mode"], cn_args["processor_res"], cn_args["threshold_a"], cn_args["threshold_b"]] + rows = [str(x) for x in rows] + + table.add_row(*rows) + + console.print(table) + + processed = process(p, *(p.script_args)) + + if processed is None: # the script just swaps the pipeline, so failing is OK for the first time + processed = process_images(p) + + if processed is None: # now it's definitely not OK + raise Exception("\033[31mFailed to process a frame with ControlNet enabled!\033[0m") + + p.close() + + return processed + +import pathlib +from .video_audio_utilities import vid2frames + +def unpack_controlnet_vids(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, animation_prompts, root): + if controlnet_args.controlnet_input_video_chosen_file is not None and len(controlnet_args.controlnet_input_video_chosen_file.name) > 0: + print(f'Unpacking ControlNet base video') + # create a folder for the video input frames to live in + mask_in_frame_path = os.path.join(args.outdir, 'controlnet_inputframes') + os.makedirs(mask_in_frame_path, exist_ok=True) + + # save the video frames from mask video + print(f"Exporting Video Frames (1 every {anim_args.extract_nth_frame}) frames to {mask_in_frame_path}...") + vid2frames(video_path=controlnet_args.controlnet_input_video_chosen_file.name, video_in_frame_path=mask_in_frame_path, n=anim_args.extract_nth_frame, overwrite=anim_args.overwrite_extracted_frames, extract_from_frame=anim_args.extract_from_frame, extract_to_frame=anim_args.extract_to_frame, numeric_files_output=True) + + print(f"Loading {anim_args.max_frames} input frames from {mask_in_frame_path} and saving video frames to {args.outdir}") + print(f'ControlNet base video unpacked!') + + if controlnet_args.controlnet_input_video_mask_chosen_file is not None and len(controlnet_args.controlnet_input_video_mask_chosen_file.name) > 0: + print(f'Unpacking ControlNet video mask') + # create a folder for the video input frames to live in + mask_in_frame_path = os.path.join(args.outdir, 'controlnet_maskframes') + os.makedirs(mask_in_frame_path, exist_ok=True) + + # save the video frames from mask video + print(f"Exporting Video Frames (1 every {anim_args.extract_nth_frame}) frames to {mask_in_frame_path}...") + vid2frames(video_path=controlnet_args.controlnet_input_video_mask_chosen_file.name, video_in_frame_path=mask_in_frame_path, n=anim_args.extract_nth_frame, overwrite=anim_args.overwrite_extracted_frames, extract_from_frame=anim_args.extract_from_frame, extract_to_frame=anim_args.extract_to_frame, numeric_files_output=True) + + print(f"Loading {anim_args.max_frames} input frames from {mask_in_frame_path} and saving video frames to {args.outdir}") + print(f'ControlNet video mask unpacked!') + +def hide_ui_by_cn_status(choice): + return gr.update(visible=True) if choice else gr.update(visible=False) + +def build_sliders(cn_model): + if cn_model == "canny": + return [ + gr.update(label="Annotator resolution", value=512, minimum=64, maximum=2048, step=1, interactive=True), + gr.update(label="Canny low threshold", minimum=1, maximum=255, value=100, step=1, interactive=True), + gr.update(label="Canny high threshold", minimum=1, maximum=255, value=200, step=1, interactive=True), + gr.update(visible=True) + ] + elif cn_model == "mlsd": #Hough + return [ + gr.update(label="Hough Resolution", minimum=64, maximum=2048, value=512, step=1, interactive=True), + gr.update(label="Hough value threshold (MLSD)", minimum=0.01, maximum=2.0, value=0.1, step=0.01, interactive=True), + gr.update(label="Hough distance threshold (MLSD)", minimum=0.01, maximum=20.0, value=0.1, step=0.01, interactive=True), + gr.update(visible=True) + ] + elif cn_model in ["hed", "fake_scribble"]: + return [ + gr.update(label="HED Resolution", minimum=64, maximum=2048, value=512, step=1, interactive=True), + gr.update(label="Threshold A", value=64, minimum=64, maximum=1024, interactive=False), + gr.update(label="Threshold B", value=64, minimum=64, maximum=1024, interactive=False), + gr.update(visible=True) + ] + elif cn_model in ["openpose", "openpose_hand", "segmentation"]: + return [ + gr.update(label="Annotator Resolution", minimum=64, maximum=2048, value=512, step=1, interactive=True), + gr.update(label="Threshold A", value=64, minimum=64, maximum=1024, interactive=False), + gr.update(label="Threshold B", value=64, minimum=64, maximum=1024, interactive=False), + gr.update(visible=True) + ] + elif cn_model == "depth": + return [ + gr.update(label="Midas Resolution", minimum=64, maximum=2048, value=384, step=1, interactive=True), + gr.update(label="Threshold A", value=64, minimum=64, maximum=1024, interactive=False), + gr.update(label="Threshold B", value=64, minimum=64, maximum=1024, interactive=False), + gr.update(visible=True) + ] + elif cn_model == "depth_leres": + return [ + gr.update(label="LeReS Resolution", minimum=64, maximum=2048, value=512, step=1, interactive=True), + gr.update(label="Remove Near %", value=0, minimum=0, maximum=100, step=0.1, interactive=True), + gr.update(label="Remove Background %", value=0, minimum=0, maximum=100, step=0.1, interactive=True), + gr.update(visible=True) + ] + elif cn_model == "normal_map": + return [ + gr.update(label="Normal Resolution", minimum=64, maximum=2048, value=512, step=1, interactive=True), + gr.update(label="Normal background threshold", minimum=0.0, maximum=1.0, value=0.4, step=0.01, interactive=True), + gr.update(label="Threshold B", value=64, minimum=64, maximum=1024, interactive=False), + gr.update(visible=True) + ] + elif cn_model == "none": + return [ + gr.update(label="Normal Resolution", value=64, minimum=64, maximum=2048, interactive=False), + gr.update(label="Threshold A", value=64, minimum=64, maximum=1024, interactive=False), + gr.update(label="Threshold B", value=64, minimum=64, maximum=1024, interactive=False), + gr.update(visible=False) + ] + else: + return [ + gr.update(label="Annotator resolution", value=512, minimum=64, maximum=2048, step=1, interactive=True), + gr.update(label="Threshold A", value=64, minimum=64, maximum=1024, interactive=False), + gr.update(label="Threshold B", value=64, minimum=64, maximum=1024, interactive=False), + gr.update(visible=True) + ] + + # def svgPreprocess(inputs): + # if (inputs): + # if (inputs['image'].startswith("data:image/svg+xml;base64,") and svgsupport): + # svg_data = base64.b64decode(inputs['image'].replace('data:image/svg+xml;base64,','')) + # drawing = svg2rlg(io.BytesIO(svg_data)) + # png_data = renderPM.drawToString(drawing, fmt='PNG') + # encoded_string = base64.b64encode(png_data) + # base64_str = str(encoded_string, "utf-8") + # base64_str = "data:image/png;base64,"+ base64_str + # inputs['image'] = base64_str + # return input_image.orgpreprocess(inputs) + # return None \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/deforum_controlnet_hardcode.py b/extensions/deforum/scripts/deforum_helpers/deforum_controlnet_hardcode.py new file mode 100644 index 0000000000000000000000000000000000000000..1446f77634a54c294eb1327786ae33c1ee7b4dcd --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/deforum_controlnet_hardcode.py @@ -0,0 +1,193 @@ +# TODO HACK FIXME HARDCODE — as using the scripts doesn't seem to work for some reason +deforum_latest_network = None +deforum_latest_params = (None, 'placeholder to trigger the model loading') +deforum_input_image = None +from scripts.processor import unload_hed, unload_mlsd, unload_midas, unload_leres, unload_pidinet, unload_openpose, unload_uniformer, HWC3 +import modules.shared as shared +import modules.devices as devices +import modules.processing as processing +from modules.processing import StableDiffusionProcessingImg2Img, StableDiffusionProcessingTxt2Img +import numpy as np +from scripts.controlnet import update_cn_models, cn_models, cn_models_names +import os +import modules.scripts as scrpts +import torch +from scripts.cldm import PlugableControlModel +from scripts.adapter import PlugableAdapter +from scripts.utils import load_state_dict +from torchvision.transforms import Resize, InterpolationMode, CenterCrop, Compose +from einops import rearrange +cn_models_dir = os.path.join(scrpts.basedir(), "models") +default_conf_adapter = os.path.join(cn_models_dir, "sketch_adapter_v14.yaml") +default_conf = os.path.join(cn_models_dir, "cldm_v15.yaml") +unloadable = { + "hed": unload_hed, + "fake_scribble": unload_hed, + "mlsd": unload_mlsd, + "depth": unload_midas, + "depth_leres": unload_leres, + "normal_map": unload_midas, + "pidinet": unload_pidinet, + "openpose": unload_openpose, + "openpose_hand": unload_openpose, + "segmentation": unload_uniformer, +} +deforum_latest_model_hash = "" + +def restore_networks(unet): + global deforum_latest_network + global deforum_latest_params + if deforum_latest_network is not None: + print("restoring last networks") + deforum_input_image = None + deforum_latest_network.restore(unet) + deforum_latest_network = None + + last_module = deforum_latest_params[0] + if last_module is not None: + unloadable.get(last_module, lambda:None)() + +def process(p, *args): + + global deforum_latest_network + global deforum_latest_params + global deforum_input_image + global deforum_latest_model_hash + + unet = p.sd_model.model.diffusion_model + + enabled, module, model, weight, image, scribble_mode, \ + resize_mode, rgbbgr_mode, lowvram, pres, pthr_a, pthr_b, guidance_strength = args + + if not enabled: + restore_networks(unet) + return + + models_changed = deforum_latest_params[1] != model \ + or deforum_latest_model_hash != p.sd_model.sd_model_hash or deforum_latest_network == None \ + or (deforum_latest_network is not None and deforum_latest_network.lowvram != lowvram) + + deforum_latest_params = (module, model) + deforum_latest_model_hash = p.sd_model.sd_model_hash + if models_changed: + restore_networks(unet) + model_path = cn_models.get(model, None) + + if model_path is None: + raise RuntimeError(f"model not found: {model}") + + # trim '"' at start/end + if model_path.startswith("\"") and model_path.endswith("\""): + model_path = model_path[1:-1] + + if not os.path.exists(model_path): + raise ValueError(f"file not found: {model_path}") + + print(f"Loading preprocessor: {module}, model: {model}") + state_dict = load_state_dict(model_path) + network_module = PlugableControlModel + network_config = shared.opts.data.get("control_net_model_config", default_conf) + if any([k.startswith("body.") for k, v in state_dict.items()]): + # adapter model + network_module = PlugableAdapter + network_config = shared.opts.data.get("control_net_model_adapter_config", default_conf_adapter) + + network = network_module( + state_dict=state_dict, + config_path=network_config, + weight=weight, + lowvram=lowvram, + base_model=unet, + ) + network.to(p.sd_model.device, dtype=p.sd_model.dtype) + network.hook(unet, p.sd_model) + + print(f"ControlNet model {model} loaded.") + deforum_latest_network = network + + if image is not None: + deforum_input_image = HWC3(image['image']) + if 'mask' in image and image['mask'] is not None and not ((image['mask'][:, :, 0]==0).all() or (image['mask'][:, :, 0]==255).all()): + print("using mask as input") + deforum_input_image = HWC3(image['mask'][:, :, 0]) + scribble_mode = True + else: + # use img2img init_image as default + deforum_input_image = getattr(p, "init_images", [None])[0] + if deforum_input_image is None: + raise ValueError('controlnet is enabled but no input image is given') + deforum_input_image = HWC3(np.asarray(deforum_input_image)) + + if scribble_mode: + detected_map = np.zeros_like(deforum_input_image, dtype=np.uint8) + detected_map[np.min(deforum_input_image, axis=2) < 127] = 255 + deforum_input_image = detected_map + + from scripts.processor import canny, midas, midas_normal, leres, hed, mlsd, openpose, pidinet, simple_scribble, fake_scribble, uniformer + + preprocessor = { + "none": lambda x, *args, **kwargs: x, + "canny": canny, + "depth": midas, + "depth_leres": leres, + "hed": hed, + "mlsd": mlsd, + "normal_map": midas_normal, + "openpose": openpose, + # "openpose_hand": openpose_hand, + "pidinet": pidinet, + "scribble": simple_scribble, + "fake_scribble": fake_scribble, + "segmentation": uniformer, + } + + preprocessor = preprocessor[deforum_latest_params[0]] + h, w, bsz = p.height, p.width, p.batch_size + if pres > 64: + detected_map = preprocessor(deforum_input_image, res=pres, thr_a=pthr_a, thr_b=pthr_b) + else: + detected_map = preprocessor(deforum_input_image) + detected_map = HWC3(detected_map) + + if module == "normal_map" or rgbbgr_mode: + control = torch.from_numpy(detected_map[:, :, ::-1].copy()).float().to(devices.get_device_for("controlnet")) / 255.0 + else: + control = torch.from_numpy(detected_map.copy()).float().to(devices.get_device_for("controlnet")) / 255.0 + + control = rearrange(control, 'h w c -> c h w') + detected_map = rearrange(torch.from_numpy(detected_map), 'h w c -> c h w') + if resize_mode == "Scale to Fit (Inner Fit)": + transform = Compose([ + Resize(h if hw else w, interpolation=InterpolationMode.BICUBIC), + CenterCrop(size=(h, w)) + ]) + control = transform(control) + detected_map = transform(detected_map) + else: + control = Resize((h,w), interpolation=InterpolationMode.BICUBIC)(control) + detected_map = Resize((h,w), interpolation=InterpolationMode.BICUBIC)(detected_map) + + # for log use + detected_map = rearrange(detected_map, 'c h w -> h w c').numpy().astype(np.uint8) + + # control = torch.stack([control for _ in range(bsz)], dim=0) + deforum_latest_network.notify(control, weight, guidance_strength) + + if shared.opts.data.get("control_net_skip_img2img_processing") and hasattr(p, "init_images"): + swap_img2img_pipeline(p) + +def swap_img2img_pipeline(p: processing.StableDiffusionProcessingImg2Img): + p.__class__ = processing.StableDiffusionProcessingTxt2Img + dummy = processing.StableDiffusionProcessingTxt2Img() + for k,v in dummy.__dict__.items(): + if hasattr(p, k): + continue + setattr(p, k, v) + diff --git a/extensions/deforum/scripts/deforum_helpers/deprecation_utils.py b/extensions/deforum/scripts/deforum_helpers/deprecation_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9485b1b39629ce1c0c1c584e1294e64e300c06db --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/deprecation_utils.py @@ -0,0 +1,20 @@ +# This file is used to map deprecated setting names in a dictionary +# and print a message containing the old and the new names +# if the latter is removed completely, put a warning + +# as of 2023-02-05 +# "histogram_matching" -> None + +deprecation_map = { + "histogram_matching": None, + "flip_2d_perspective": "enable_perspective_flip" +} + +def handle_deprecated_settings(settings_json): + for old_name, new_name in deprecation_map.items(): + if old_name in settings_json: + if new_name is None: + print(f"WARNING: Setting '{old_name}' has been removed. It will be discarded and the default value used instead!") + else: + print(f"WARNING: Setting '{old_name}' has been renamed to '{new_name}'. The saved settings file will reflect the change") + settings_json[new_name] = settings_json.pop(old_name) diff --git a/extensions/deforum/scripts/deforum_helpers/depth.py b/extensions/deforum/scripts/deforum_helpers/depth.py new file mode 100644 index 0000000000000000000000000000000000000000..61a50459a4a3ed046ed1c4cdcbd914437026fc0d --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/depth.py @@ -0,0 +1,166 @@ +import math, os, subprocess +import cv2 +import hashlib +import numpy as np +import torch +import gc +import torchvision.transforms as T +from einops import rearrange, repeat +from PIL import Image +from infer import InferenceHelper +from midas.dpt_depth import DPTDepthModel +from midas.transforms import Resize, NormalizeImage, PrepareForNet +import torchvision.transforms.functional as TF +from .general_utils import checksum + +class DepthModel(): + def __init__(self, device): + self.adabins_helper = None + self.depth_min = 1000 + self.depth_max = -1000 + self.device = device + self.midas_model = None + self.midas_transform = None + + def load_adabins(self, models_path): + if not os.path.exists(os.path.join(models_path,'AdaBins_nyu.pt')): + from basicsr.utils.download_util import load_file_from_url + load_file_from_url(r"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", models_path) + if checksum(os.path.join(models_path,'AdaBins_nyu.pt')) != "643db9785c663aca72f66739427642726b03acc6c4c1d3755a4587aa2239962746410d63722d87b49fc73581dbc98ed8e3f7e996ff7b9c0d56d0fbc98e23e41a": + raise Exception(r"Error while downloading AdaBins_nyu.pt. Please download from here: https://drive.google.com/file/d/1lvyZZbC9NLcS8a__YPcUP7rDiIpbRpoF and place in: " + models_path) + self.adabins_helper = InferenceHelper(models_path=models_path, dataset='nyu', device=self.device) + + def load_midas(self, models_path, half_precision=True): + if not os.path.exists(os.path.join(models_path, 'dpt_large-midas-2f21e586.pt')): + from basicsr.utils.download_util import load_file_from_url + load_file_from_url(r"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", models_path) + if checksum(os.path.join(models_path,'dpt_large-midas-2f21e586.pt')) != "fcc4829e65d00eeed0a38e9001770676535d2e95c8a16965223aba094936e1316d569563552a852d471f310f83f597e8a238987a26a950d667815e08adaebc06": + raise Exception(r"Error while downloading dpt_large-midas-2f21e586.pt. Please download from here: https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt and place in: " + models_path) + + self.midas_model = DPTDepthModel( + path=f"{models_path}/dpt_large-midas-2f21e586.pt", + backbone="vitl16_384", + non_negative=True, + ) + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + self.midas_transform = T.Compose([ + Resize( + 384, 384, + resize_target=None, + keep_aspect_ratio=True, + ensure_multiple_of=32, + resize_method="minimal", + image_interpolation_method=cv2.INTER_CUBIC, + ), + normalization, + PrepareForNet() + ]) + + self.midas_model.eval() + if self.device == torch.device("cuda"): + self.midas_model = self.midas_model.to(memory_format=torch.channels_last) + if half_precision: + self.midas_model = self.midas_model.half() + self.midas_model.to(self.device) + + def predict(self, prev_img_cv2, anim_args, half_precision) -> torch.Tensor: + w, h = prev_img_cv2.shape[1], prev_img_cv2.shape[0] + + # predict depth with AdaBins + use_adabins = anim_args.midas_weight < 1.0 and self.adabins_helper is not None + if use_adabins: + MAX_ADABINS_AREA = 500000 + MIN_ADABINS_AREA = 448*448 + + # resize image if too large or too small + img_pil = Image.fromarray(cv2.cvtColor(prev_img_cv2.astype(np.uint8), cv2.COLOR_RGB2BGR)) + image_pil_area = w*h + resized = True + if image_pil_area > MAX_ADABINS_AREA: + scale = math.sqrt(MAX_ADABINS_AREA) / math.sqrt(image_pil_area) + depth_input = img_pil.resize((int(w*scale), int(h*scale)), Image.LANCZOS) # LANCZOS is good for downsampling + print(f" resized to {depth_input.width}x{depth_input.height}") + elif image_pil_area < MIN_ADABINS_AREA: + scale = math.sqrt(MIN_ADABINS_AREA) / math.sqrt(image_pil_area) + depth_input = img_pil.resize((int(w*scale), int(h*scale)), Image.BICUBIC) + print(f" resized to {depth_input.width}x{depth_input.height}") + else: + depth_input = img_pil + resized = False + + # predict depth and resize back to original dimensions + try: + with torch.no_grad(): + _, adabins_depth = self.adabins_helper.predict_pil(depth_input) + if resized: + adabins_depth = TF.resize( + torch.from_numpy(adabins_depth), + torch.Size([h, w]), + interpolation=TF.InterpolationMode.BICUBIC + ) + adabins_depth = adabins_depth.cpu().numpy() + adabins_depth = adabins_depth.squeeze() + except: + print(f" exception encountered, falling back to pure MiDaS") + use_adabins = False + torch.cuda.empty_cache() + + if self.midas_model is not None: + # convert image from 0->255 uint8 to 0->1 float for feeding to MiDaS + img_midas = prev_img_cv2.astype(np.float32) / 255.0 + img_midas_input = self.midas_transform({"image": img_midas})["image"] + + # MiDaS depth estimation implementation + sample = torch.from_numpy(img_midas_input).float().to(self.device).unsqueeze(0) + if self.device == torch.device("cuda"): + sample = sample.to(memory_format=torch.channels_last) + if half_precision: + sample = sample.half() + with torch.no_grad(): + midas_depth = self.midas_model.forward(sample) + midas_depth = torch.nn.functional.interpolate( + midas_depth.unsqueeze(1), + size=img_midas.shape[:2], + mode="bicubic", + align_corners=False, + ).squeeze() + midas_depth = midas_depth.cpu().numpy() + torch.cuda.empty_cache() + + # MiDaS makes the near values greater, and the far values lesser. Let's reverse that and try to align with AdaBins a bit better. + midas_depth = np.subtract(50.0, midas_depth) + midas_depth = midas_depth / 19.0 + + # blend between MiDaS and AdaBins predictions + if use_adabins: + depth_map = midas_depth*anim_args.midas_weight + adabins_depth*(1.0-anim_args.midas_weight) + else: + depth_map = midas_depth + + depth_map = np.expand_dims(depth_map, axis=0) + depth_tensor = torch.from_numpy(depth_map).squeeze().to(self.device) + else: + depth_tensor = torch.ones((h, w), device=self.device) + + return depth_tensor + + def save(self, filename: str, depth: torch.Tensor): + depth = depth.cpu().numpy() + if len(depth.shape) == 2: + depth = np.expand_dims(depth, axis=0) + self.depth_min = min(self.depth_min, depth.min()) + self.depth_max = max(self.depth_max, depth.max()) + print(f" depth min:{depth.min()} max:{depth.max()}") + denom = max(1e-8, self.depth_max - self.depth_min) + temp = rearrange((depth - self.depth_min) / denom * 255, 'c h w -> h w c') + temp = repeat(temp, 'h w 1 -> h w c', c=3) + Image.fromarray(temp.astype(np.uint8)).save(filename) + + def to(self, device): + self.device = device + self.midas_model.to(device) + if self.adabins_helper is not None: + self.adabins_helper.to(device) + gc.collect() + torch.cuda.empty_cache() diff --git a/extensions/deforum/scripts/deforum_helpers/frame_interpolation.py b/extensions/deforum/scripts/deforum_helpers/frame_interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..59d205fdc3294a39b46a9347aa174d2503d37e00 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/frame_interpolation.py @@ -0,0 +1,192 @@ +import os +from pathlib import Path +from rife.inference_video import run_rife_new_video_infer +from .video_audio_utilities import get_quick_vid_info, vid2frames, media_file_has_audio, extract_number, ffmpeg_stitch_video +from film_interpolation.film_inference import run_film_interp_infer +from .general_utils import duplicate_pngs_from_folder, checksum + +# gets 'RIFE v4.3', returns: 'RIFE43' +def extract_rife_name(string): + parts = string.split() + if len(parts) != 2 or parts[0] != "RIFE" or (parts[1][0] != "v" or not parts[1][1:].replace('.','').isdigit()): + raise ValueError("Input string should contain exactly 2 words, first word should be 'RIFE' and second word should start with 'v' followed by 2 numbers") + return "RIFE"+parts[1][1:].replace('.','') + +# This function usually gets a filename, and converts it to a legal linux/windows *folder* name +def clean_folder_name(string): + illegal_chars = ["/", "\\", "<", ">", ":", "\"", "|", "?", "*", "."] + for char in illegal_chars: + string = string.replace(char, "_") + return string + +def set_interp_out_fps(interp_x, slow_x_enabled, slom_x, in_vid_fps): + if interp_x == 'Disabled' or in_vid_fps in ('---', None, '', 'None'): + return '---' + + # clean_interp_x = extract_number(interp_x) + # clean_slom_x = extract_number(slom_x) + fps = float(in_vid_fps) * int(interp_x) + # if slom_x != -1: + if slow_x_enabled: + fps /= int(slom_x) + return int(fps) if fps.is_integer() else fps + +# get uploaded video frame count, fps, and return 3 valuees for the gradio UI: in fcount, in fps, out fps (using the set_interp_out_fps function above) +def gradio_f_interp_get_fps_and_fcount(vid_path, interp_x, slow_x_enabled, slom_x): + if vid_path is None: + return '---', '---', '---' + fps, fcount, resolution = get_quick_vid_info(vid_path.name) + expected_out_fps = set_interp_out_fps(interp_x, slow_x_enabled, slom_x, fps) + return (str(round(fps,2)) if fps is not None else '---', (round(fcount,2)) if fcount is not None else '---', round(expected_out_fps,2)) + +# handle call to interpolate an uploaded video from gradio button in args.py (the function that calls this func is named 'upload_vid_to_rife') +def process_interp_vid_upload_logic(file, engine, x_am, sl_enabled, sl_am, keep_imgs, f_location, f_crf, f_preset, in_vid_fps, f_models_path, vid_file_name): + + print("got a request to *frame interpolate* an existing video.") + + _, _, resolution = get_quick_vid_info(file.name) + folder_name = clean_folder_name(Path(vid_file_name).stem) + outdir_no_tmp = os.path.join(os.getcwd(), 'outputs', 'frame-interpolation', folder_name) + i = 1 + while os.path.exists(outdir_no_tmp): + outdir_no_tmp = os.path.join(os.getcwd(), 'outputs', 'frame-interpolation', folder_name + '_' + str(i)) + i += 1 + + outdir = os.path.join(outdir_no_tmp, 'tmp_input_frames') + os.makedirs(outdir, exist_ok=True) + + vid2frames(video_path=file.name, video_in_frame_path=outdir, overwrite=True, extract_from_frame=0, extract_to_frame=-1, numeric_files_output=True, out_img_format='png') + + # check if the uploaded vid has an audio stream. If it doesn't, set audio param to None so that ffmpeg won't try to add non-existing audio to final video. + audio_file_to_pass = None + if media_file_has_audio(file.name, f_location): + audio_file_to_pass = file.name + + process_video_interpolation(frame_interpolation_engine=engine, frame_interpolation_x_amount=x_am, frame_interpolation_slow_mo_enabled = sl_enabled,frame_interpolation_slow_mo_amount=sl_am, orig_vid_fps=in_vid_fps, deforum_models_path=f_models_path, real_audio_track=audio_file_to_pass, raw_output_imgs_path=outdir, img_batch_id=None, ffmpeg_location=f_location, ffmpeg_crf=f_crf, ffmpeg_preset=f_preset, keep_interp_imgs=keep_imgs, orig_vid_name=folder_name, resolution=resolution) + +# handle params before talking with the actual interpolation module (rifee/film, more to be added) +def process_video_interpolation(frame_interpolation_engine, frame_interpolation_x_amount, frame_interpolation_slow_mo_enabled, frame_interpolation_slow_mo_amount, orig_vid_fps, deforum_models_path, real_audio_track, raw_output_imgs_path, img_batch_id, ffmpeg_location, ffmpeg_crf, ffmpeg_preset, keep_interp_imgs, orig_vid_name, resolution): + + # set initial output vid fps + fps = float(orig_vid_fps) * frame_interpolation_x_amount + + # re-calculate fps param to pass if slow_mo mode is enabled + if frame_interpolation_slow_mo_enabled: + fps = float(orig_vid_fps) * frame_interpolation_x_amount / int(frame_interpolation_slow_mo_amount) + # disable audio-adding by setting real_audio_track to None if slow-mo is enabled + if real_audio_track is not None and frame_interpolation_slow_mo_enabled: + real_audio_track = None + + if frame_interpolation_engine == 'None': + return + elif frame_interpolation_engine.startswith("RIFE"): + # make sure interp_x is valid and in range + if frame_interpolation_x_amount not in range(2, 11): + raise Error("frame_interpolation_x_amount must be between 2x and 10x") + + # set UHD to True if res' is 2K or higher + if resolution: + UHD = resolution[0] >= 2048 and resolution[1] >= 2048 + else: + UHD = False + # e.g from "RIFE v2.3 to RIFE23" + actual_model_folder_name = extract_rife_name(frame_interpolation_engine) + + # run actual rife interpolation and video stitching etc - the whole suite + run_rife_new_video_infer(interp_x_amount=frame_interpolation_x_amount, slow_mo_enabled = frame_interpolation_slow_mo_enabled, slow_mo_x_amount=frame_interpolation_slow_mo_amount, model=actual_model_folder_name, fps=fps, deforum_models_path=deforum_models_path, audio_track=real_audio_track, raw_output_imgs_path=raw_output_imgs_path, img_batch_id=img_batch_id, ffmpeg_location=ffmpeg_location, ffmpeg_crf=ffmpeg_crf, ffmpeg_preset=ffmpeg_preset, keep_imgs=keep_interp_imgs, orig_vid_name=orig_vid_name, UHD=UHD) + elif frame_interpolation_engine == 'FILM': + prepare_film_inference(deforum_models_path=deforum_models_path, x_am=frame_interpolation_x_amount, sl_enabled=frame_interpolation_slow_mo_enabled, sl_am=frame_interpolation_slow_mo_amount, keep_imgs=keep_interp_imgs, raw_output_imgs_path=raw_output_imgs_path, img_batch_id=img_batch_id, f_location=ffmpeg_location, f_crf=ffmpeg_crf, f_preset=ffmpeg_preset, fps=fps, audio_track=real_audio_track, orig_vid_name=orig_vid_name) + else: + print("Unknown Frame Interpolation engine chosen. Doing nothing.") + return + +def prepare_film_inference(deforum_models_path, x_am, sl_enabled, sl_am, keep_imgs, raw_output_imgs_path, img_batch_id, f_location, f_crf, f_preset, fps, audio_track, orig_vid_name): + import shutil + + parent_folder = os.path.dirname(raw_output_imgs_path) + grandparent_folder = os.path.dirname(parent_folder) + if orig_vid_name is not None: + interp_vid_path = os.path.join(parent_folder, str(orig_vid_name) +'_FILM_x' + str(x_am)) + else: + interp_vid_path = os.path.join(raw_output_imgs_path, str(img_batch_id) +'_FILM_x' + str(x_am)) + + film_model_name = 'film_net_fp16.pt' + film_model_folder = os.path.join(deforum_models_path,'film_interpolation') + film_model_path = os.path.join(film_model_folder, film_model_name) # actual full path to the film .pt model file + output_interp_imgs_folder = os.path.join(raw_output_imgs_path, 'interpolated_frames_film') + # set custom name depending on if we interpolate after a run, or interpolate a video (related/unrelated to deforum, we don't know) directly from within the interpolation tab + # interpolated_path = os.path.join(args.raw_output_imgs_path, 'interpolated_frames_rife') + if orig_vid_name is not None: # interpolating a video (deforum or unrelated) + custom_interp_path = "{}_{}".format(output_interp_imgs_folder, orig_vid_name) + else: # interpolating after a deforum run: + custom_interp_path = "{}_{}".format(output_interp_imgs_folder, img_batch_id) + + # interp_vid_path = os.path.join(raw_output_imgs_path, str(img_batch_id) + '_FILM_x' + str(x_am)) + img_path_for_ffmpeg = os.path.join(custom_interp_path, "frame_%05d.png") + + if sl_enabled: + interp_vid_path = interp_vid_path + '_slomo_x' + str(sl_am) + interp_vid_path = interp_vid_path + '.mp4' + + # In this folder we temporarily keep the original frames (converted/ copy-pasted and img format depends on scenario) + # the convertion case is done to avert a problem with 24 and 32 mixed outputs from the same animation run + temp_convert_raw_png_path = os.path.join(raw_output_imgs_path, "tmp_film_folder") + total_frames = duplicate_pngs_from_folder(raw_output_imgs_path, temp_convert_raw_png_path, img_batch_id, None) + check_and_download_film_model('film_net_fp16.pt', film_model_folder) # TODO: split this part + + # get number of in-between-frames to provide to FILM - mimics how RIFE works, we should get the same amount of total frames in the end + film_in_between_frames_count = calculate_frames_to_add(total_frames, x_am) + # Run actual FILM inference + run_film_interp_infer( + model_path = film_model_path, + input_folder = temp_convert_raw_png_path, + save_folder = custom_interp_path, # output folder is created in the infer part + inter_frames = film_in_between_frames_count) + + add_soundtrack = 'None' + if not audio_track is None: + add_soundtrack = 'File' + + print (f"*Passing interpolated frames to ffmpeg...*") + exception_raised = False + try: + ffmpeg_stitch_video(ffmpeg_location=f_location, fps=fps, outmp4_path=interp_vid_path, stitch_from_frame=0, stitch_to_frame=999999, imgs_path=img_path_for_ffmpeg, add_soundtrack=add_soundtrack, audio_path=audio_track, crf=f_crf, preset=f_preset) + except Exception as e: + exception_raised = True + print(f"An error occurred while stitching the video: {e}") + + if orig_vid_name and (keep_imgs or exception_raised): + shutil.move(custom_interp_path, parent_folder) + if not keep_imgs and not exception_raised: + if fps <= 450: # keep interp frames automatically if out_vid fps is above 450 + shutil.rmtree(custom_interp_path, ignore_errors=True) + # delete duplicated raw non-interpolated frames + shutil.rmtree(temp_convert_raw_png_path, ignore_errors=True) + # remove folder with raw (non-interpolated) vid input frames in case of input VID and not PNGs + if orig_vid_name: + shutil.rmtree(raw_output_imgs_path, ignore_errors=True) + +def check_and_download_film_model(model_name, model_dest_folder): + from basicsr.utils.download_util import load_file_from_url + if model_name == 'film_net_fp16.pt': + model_dest_path = os.path.join(model_dest_folder, model_name) + download_url = 'https://github.com/hithereai/frame-interpolation-pytorch/releases/download/film_net_fp16.pt/film_net_fp16.pt' + film_model_hash = '0a823815b111488ac2b7dd7fe6acdd25d35a22b703e8253587764cf1ee3f8f93676d24154d9536d2ce5bc3b2f102fb36dfe0ca230dfbe289d5cd7bde5a34ec12' + else: # Unknown FILM model + raise Exception("Got a request to download an unknown FILM model. Can't proceed.") + if os.path.exists(model_dest_path): + return + try: + os.makedirs(model_dest_folder, exist_ok=True) + # download film model from url + load_file_from_url(download_url, model_dest_folder) + # verify checksum + if checksum(model_dest_path) != film_model_hash: + raise Exception(f"Error while downloading {model_name}. Please download from: {download_url}, and put in: {model_dest_folder}") + except Exception as e: + raise Exception(f"Error while downloading {model_name}. Please download from: {download_url}, and put in: {model_dest_folder}") + +# get film no. of frames to add after each pic from tot frames in interp_x values +def calculate_frames_to_add(total_frames, interp_x): + frames_to_add = (total_frames * interp_x - total_frames) / (total_frames - 1) + return int(round(frames_to_add)) \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/general_utils.py b/extensions/deforum/scripts/deforum_helpers/general_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..893a7ff2870a93c64822c3e1a9cbe8c51faca811 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/general_utils.py @@ -0,0 +1,32 @@ +import hashlib +def checksum(filename, hash_factory=hashlib.blake2b, chunk_num_blocks=128): + h = hash_factory() + with open(filename,'rb') as f: + while chunk := f.read(chunk_num_blocks*h.block_size): + h.update(chunk) + return h.hexdigest() + +def get_os(): + import platform + return {"Windows": "Windows", "Linux": "Linux", "Darwin": "Mac"}.get(platform.system(), "Unknown") + +# used in src/rife/inference_video.py and more, soon +def duplicate_pngs_from_folder(from_folder, to_folder, img_batch_id, orig_vid_name): + import os, cv2, shutil #, subprocess + #TODO: don't copy-paste at all if the input is a video (now it copy-pastes, and if input is deforum run is also converts to make sure no errors rise cuz of 24-32 bit depth differences) + temp_convert_raw_png_path = os.path.join(from_folder, to_folder) + if not os.path.exists(temp_convert_raw_png_path): + os.makedirs(temp_convert_raw_png_path) + + frames_handled = 0 + for f in os.listdir(from_folder): + if ('png' in f or 'jpg' in f) and '-' not in f and '_depth_' not in f and ((img_batch_id is not None and f.startswith(img_batch_id) or img_batch_id is None)): + frames_handled +=1 + original_img_path = os.path.join(from_folder, f) + if orig_vid_name is not None: + shutil.copy(original_img_path, temp_convert_raw_png_path) + else: + image = cv2.imread(original_img_path) + new_path = os.path.join(temp_convert_raw_png_path, f) + cv2.imwrite(new_path, image, [cv2.IMWRITE_PNG_COMPRESSION, 0]) + return frames_handled \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/generate.py b/extensions/deforum/scripts/deforum_helpers/generate.py new file mode 100644 index 0000000000000000000000000000000000000000..4203405bdf3a06330a655ebc6b58c5bd9dcccca6 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/generate.py @@ -0,0 +1,244 @@ +import numpy as np +import cv2 +from PIL import Image +from .prompt import split_weighted_subprompts +from .load_images import load_img, prepare_mask, check_mask_for_errors +from .webui_sd_pipeline import get_webui_sd_pipeline +from .animation import sample_from_cv2, sample_to_cv2 +from .rich import console +#Webui +import cv2 +from .animation import sample_from_cv2, sample_to_cv2 +from modules import processing, sd_models +from modules.shared import opts, sd_model +from modules.processing import process_images, StableDiffusionProcessingTxt2Img +from .deforum_controlnet import is_controlnet_enabled, process_txt2img_with_controlnet, process_img2img_with_controlnet + +import math, json, itertools +import requests + +def load_mask_latent(mask_input, shape): + # mask_input (str or PIL Image.Image): Path to the mask image or a PIL Image object + # shape (list-like len(4)): shape of the image to match, usually latent_image.shape + + if isinstance(mask_input, str): # mask input is probably a file name + if mask_input.startswith('http://') or mask_input.startswith('https://'): + mask_image = Image.open(requests.get(mask_input, stream=True).raw).convert('RGBA') + else: + mask_image = Image.open(mask_input).convert('RGBA') + elif isinstance(mask_input, Image.Image): + mask_image = mask_input + else: + raise Exception("mask_input must be a PIL image or a file name") + + mask_w_h = (shape[-1], shape[-2]) + mask = mask_image.resize(mask_w_h, resample=Image.LANCZOS) + mask = mask.convert("L") + return mask + +def isJson(myjson): + try: + json.loads(myjson) + except ValueError as e: + return False + return True + +# Add pairwise implementation here not to upgrade +# the whole python to 3.10 just for one function +def pairwise_repl(iterable): + a, b = itertools.tee(iterable) + next(b, None) + return zip(a, b) + +def generate(args, anim_args, loop_args, controlnet_args, root, frame = 0, return_sample=False, sampler_name=None): + assert args.prompt is not None + + # Setup the pipeline + p = get_webui_sd_pipeline(args, root, frame) + p.prompt, p.negative_prompt = split_weighted_subprompts(args.prompt, frame) + + if not args.use_init and args.strength > 0 and args.strength_0_no_init: + print("\nNo init image, but strength > 0. Strength has been auto set to 0, since use_init is False.") + print("If you want to force strength > 0 with no init, please set strength_0_no_init to False.\n") + args.strength = 0 + processed = None + mask_image = None + init_image = None + image_init0 = None + + if loop_args.use_looper: + # TODO find out why we need to set this in the init tab + if args.strength == 0: + raise RuntimeError("Strength needs to be greater than 0 in Init tab and strength_0_no_init should *not* be checked") + if args.seed_behavior != "schedule": + raise RuntimeError("seed_behavior needs to be set to schedule in under 'Keyframes' tab --> 'Seed scheduling'") + if not isJson(loop_args.imagesToKeyframe): + raise RuntimeError("The images set for use with keyframe-guidance are not in a proper JSON format") + args.strength = loop_args.imageStrength + tweeningFrames = loop_args.tweeningFrameSchedule + blendFactor = .07 + colorCorrectionFactor = loop_args.colorCorrectionFactor + jsonImages = json.loads(loop_args.imagesToKeyframe) + framesToImageSwapOn = list(map(int, list(jsonImages.keys()))) + # find which image to show + frameToChoose = 0 + for swappingFrame in framesToImageSwapOn[1:]: + frameToChoose += (frame >= int(swappingFrame)) + + #find which frame to do our swapping on for tweening + skipFrame = 25 + for fs, fe in pairwise_repl(framesToImageSwapOn): + if fs <= frame <= fe: + skipFrame = fe - fs + + if frame % skipFrame <= tweeningFrames: # number of tweening frames + blendFactor = loop_args.blendFactorMax - loop_args.blendFactorSlope*math.cos((frame % tweeningFrames) / (tweeningFrames / 2)) + init_image2, _ = load_img(list(jsonImages.values())[frameToChoose], + shape=(args.W, args.H), + use_alpha_as_mask=args.use_alpha_as_mask) + image_init0 = list(jsonImages.values())[0] + + else: # they passed in a single init image + image_init0 = args.init_image + + + available_samplers = { + 'euler a':'Euler a', + 'euler':'Euler', + 'lms':'LMS', + 'heun':'Heun', + 'dpm2':'DPM2', + 'dpm2 a':'DPM2 a', + 'dpm++ 2s a':'DPM++ 2S a', + 'dpm++ 2m':'DPM++ 2M', + 'dpm++ sde':'DPM++ SDE', + 'dpm fast':'DPM fast', + 'dpm adaptive':'DPM adaptive', + 'lms karras':'LMS Karras' , + 'dpm2 karras':'DPM2 Karras', + 'dpm2 a karras':'DPM2 a Karras', + 'dpm++ 2s a karras':'DPM++ 2S a Karras', + 'dpm++ 2m karras':'DPM++ 2M Karras', + 'dpm++ sde karras':'DPM++ SDE Karras' + } + if sampler_name is not None: + if sampler_name in available_samplers.keys(): + args.sampler = available_samplers[sampler_name] + + if args.checkpoint is not None: + info = sd_models.get_closet_checkpoint_match(args.checkpoint) + if info is None: + raise RuntimeError(f"Unknown checkpoint: {args.checkpoint}") + sd_models.reload_model_weights(info=info) + + if args.init_sample is not None: + # TODO: cleanup init_sample remains later + img = args.init_sample + init_image = img + image_init0 = img + if loop_args.use_looper and isJson(loop_args.imagesToKeyframe): + init_image = Image.blend(init_image, init_image2, blendFactor) + correction_colors = Image.blend(init_image, init_image2, colorCorrectionFactor) + p.color_corrections = [processing.setup_color_correction(correction_colors)] + + # this is the first pass + elif loop_args.use_looper or (args.use_init and ((args.init_image != None and args.init_image != ''))): + init_image, mask_image = load_img(image_init0, # initial init image + shape=(args.W, args.H), + use_alpha_as_mask=args.use_alpha_as_mask) + + else: + + if anim_args.animation_mode != 'Interpolation': + print(f"Not using an init image (doing pure txt2img)") + p_txt = StableDiffusionProcessingTxt2Img( + sd_model=sd_model, + outpath_samples=root.tmp_deforum_run_duplicated_folder, + outpath_grids=root.tmp_deforum_run_duplicated_folder, + prompt=p.prompt, + styles=p.styles, + negative_prompt=p.negative_prompt, + seed=p.seed, + subseed=p.subseed, + subseed_strength=p.subseed_strength, + seed_resize_from_h=p.seed_resize_from_h, + seed_resize_from_w=p.seed_resize_from_w, + sampler_name=p.sampler_name, + batch_size=p.batch_size, + n_iter=p.n_iter, + steps=p.steps, + cfg_scale=p.cfg_scale, + width=p.width, + height=p.height, + restore_faces=p.restore_faces, + tiling=p.tiling, + enable_hr=None, + denoising_strength=None, + ) + # print dynamic table to cli + print_generate_table(args, anim_args, p_txt) + + if is_controlnet_enabled(controlnet_args): + processed = process_txt2img_with_controlnet(p, args, anim_args, loop_args, controlnet_args, root, frame) + else: + processed = processing.process_images(p_txt) + + if processed is None: + # Mask functions + if args.use_mask: + mask = args.mask_image + #assign masking options to pipeline + if mask is not None: + p.inpainting_mask_invert = args.invert_mask + p.inpainting_fill = args.fill + p.inpaint_full_res= args.full_res_mask + p.inpaint_full_res_padding = args.full_res_mask_padding + else: + mask = None + + assert not ( (mask is not None and args.use_mask and args.overlay_mask) and (args.init_sample is None and init_image is None)), "Need an init image when use_mask == True and overlay_mask == True" + + p.init_images = [init_image] + p.image_mask = mask + p.image_cfg_scale = args.pix2pix_img_cfg_scale + + # print dynamic table to cli + print_generate_table(args, anim_args, p) + + if is_controlnet_enabled(controlnet_args): + processed = process_img2img_with_controlnet(p, args, anim_args, loop_args, controlnet_args, root, frame) + else: + processed = processing.process_images(p) + + if root.initial_info == None: + root.initial_seed = processed.seed + root.initial_info = processed.info + + if root.first_frame == None: + root.first_frame = processed.images[0] + + results = processed.images[0] + + return results + +def print_generate_table(args, anim_args, p): + from rich.table import Table + from rich import box + table = Table(padding=0, box=box.ROUNDED) + field_names = ["Steps", "CFG"] + if anim_args.animation_mode != 'Interpolation': + field_names.append("Denoise") + field_names += ["Subseed", "Subs. str"] * (anim_args.enable_subseed_scheduling) + field_names += ["Sampler"] * anim_args.enable_sampler_scheduling + field_names += ["Checkpoint"] * anim_args.enable_checkpoint_scheduling + for field_name in field_names: + table.add_column(field_name, justify="center") + rows = [str(p.steps), str(p.cfg_scale)] + if anim_args.animation_mode != 'Interpolation': + rows.append(str(p.denoising_strength)) + rows += [str(p.subseed), str(p.subseed_strength)] * (anim_args.enable_subseed_scheduling) + rows += [p.sampler_name] * anim_args.enable_sampler_scheduling + rows += [str(args.checkpoint)] * anim_args.enable_checkpoint_scheduling + table.add_row(*rows) + + console.print(table) \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/gradio_funcs.py b/extensions/deforum/scripts/deforum_helpers/gradio_funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..2656647b66a0dca9c71759e98016251f22a02815 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/gradio_funcs.py @@ -0,0 +1,83 @@ +import gradio as gr +from .video_audio_utilities import extract_number, get_quick_vid_info + +def change_visibility_from_skip_video(choice): + return gr.update(visible=False) if choice else gr.update(visible=True) + +def update_r_upscale_factor(choice): + return gr.update(value='x4', choices = ['x4']) if choice != 'realesr-animevideov3' else gr.update(value='x2', choices = ['x2', 'x3', 'x4']) + +def change_perlin_visibility(choice): + return gr.update(visible=choice=="perlin") + +def change_color_coherence_video_every_N_frames_visibility(choice): + return gr.update(visible=choice=="Video Input") + +def change_seed_iter_visibility(choice): + return gr.update(visible=choice=="iter") + +def change_seed_schedule_visibility(choice): + return gr.update(visible=choice=="schedule") + +def disable_pers_flip_accord(choice): + return gr.update(visible=True) if choice in ['2D','3D'] else gr.update(visible=False) + +def change_max_frames_visibility(choice): + return gr.update(visible=choice != "Video Input") + +def change_diffusion_cadence_visibility(choice): + return gr.update(visible=choice not in ['Video Input', 'Interpolation']) + +def disble_3d_related_stuff(choice): + return gr.update(visible=False) if choice != '3D' else gr.update(visible=True) + +def enable_2d_related_stuff(choice): + return gr.update(visible=True) if choice == '2D' else gr.update(visible=False) + +def disable_by_interpolation(choice): + return gr.update(visible=False) if choice in ['Interpolation'] else gr.update(visible=True) + +def disable_by_video_input(choice): + return gr.update(visible=False) if choice in ['Video Input'] else gr.update(visible=True) + +def change_comp_mask_x_visibility(choice): + return gr.update(visible=choice != "None") + +def change_gif_button_visibility(choice): + return gr.update(visible=False, value=False) if int(choice) > 30 else gr.update(visible=True) + +def disable_by_hybrid_composite(choice): + return gr.update(visible=True) if choice else gr.update(visible=False) + +def disable_by_hybrid_composite_dynamic(choice, comp_mask_type): + if choice == True: + if comp_mask_type != 'None': + return gr.update(visible=True) + return gr.update(visible=False) + +def disable_by_comp_mask(choice): + return gr.update(visible=False) if choice == 'None' else gr.update(visible=True) + +def disable_by_non_optical_flow(choice): + return gr.update(visible=False) if choice != 'Optical Flow' else gr.update(visible=True) + +# Upscaling Gradio UI related funcs +def vid_upscale_gradio_update_stats(vid_path, upscale_factor): + if not vid_path: + return '---', '---', '---', '---' + factor = extract_number(upscale_factor) + fps, fcount, resolution = get_quick_vid_info(vid_path.name) + in_res_str = f"{resolution[0]}*{resolution[1]}" + out_res_str = f"{resolution[0] * factor}*{resolution[1] * factor}" + return fps, fcount, in_res_str, out_res_str +def update_upscale_out_res(in_res, upscale_factor): + if not in_res: + return '---' + factor = extract_number(upscale_factor) + w, h = [int(x) * factor for x in in_res.split('*')] + return f"{w}*{h}" +def update_upscale_out_res_by_model_name(in_res, upscale_model_name): + if not upscale_model_name or in_res == '---': + return '---' + factor = 2 if upscale_model_name == 'realesr-animevideov3' else 4 + return f"{int(in_res.split('*')[0]) * factor}*{int(in_res.split('*')[1]) * factor}" \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/human_masking.py b/extensions/deforum/scripts/deforum_helpers/human_masking.py new file mode 100644 index 0000000000000000000000000000000000000000..daabbe8f4436fdccba90c3a11c9439543446d187 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/human_masking.py @@ -0,0 +1,72 @@ +import os, cv2 +import torch +from pathlib import Path +from multiprocessing import freeze_support + +def extract_frames(input_video_path, output_imgs_path): + # Open the video file + vidcap = cv2.VideoCapture(input_video_path) + + # Get the total number of frames in the video + frame_count = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT)) + + # Create the output directory if it does not exist + if not os.path.exists(output_imgs_path): + os.makedirs(output_imgs_path) + + # Extract the frames + for i in range(frame_count): + success, image = vidcap.read() + if success: + cv2.imwrite(os.path.join(output_imgs_path, f"frame{i}.png"), image) + print(f"{frame_count} frames extracted and saved to {output_imgs_path}") + + +def video2humanmasks(input_frames_path, output_folder_path, output_type, fps): + # freeze support is needed for video outputting + freeze_support() + + # check if input path exists and is a directory + if not os.path.exists(input_frames_path) or not os.path.isdir(input_frames_path): + raise ValueError("Invalid input path: {}".format(input_frames_path)) + + # check if output path exists and is a directory + if not os.path.exists(output_folder_path) or not os.path.isdir(output_folder_path): + raise ValueError("Invalid output path: {}".format(output_folder_path)) + + # check if output_type is valid + valid_output_types = ["video", "pngs", "both"] + if output_type.lower() not in valid_output_types: + raise ValueError("Invalid output type: {}. Must be one of {}".format(output_type, valid_output_types)) + + # try to predict where torch cache lives, so we can try and fetch models from cache in the next step + predicted_torch_model_cache_path = os.path.join(Path.home(), ".cache", "torch", "hub", "hithereai_RobustVideoMatting_master") + predicted_rvm_cache_testilfe = os.path.join(predicted_torch_model_cache_path, "hubconf.py") + + # try to fetch the models from cache, and only if it can't be find, download from the internet (to enable offline usage) + try: + # Try to fetch the models from cache + convert_video = torch.hub.load(predicted_torch_model_cache_path, "converter", source='local') + model = torch.hub.load(predicted_torch_model_cache_path, "mobilenetv3", source='local').cuda() + except: + # Download from the internet if not found in cache + convert_video = torch.hub.load("hithereai/RobustVideoMatting", "converter") + model = torch.hub.load("hithereai/RobustVideoMatting", "mobilenetv3").cuda() + + output_alpha_vid_path = os.path.join(output_folder_path, "human_masked_video.mp4") + # extract humans masks from the input folder' imgs. + # in this step PNGs will be extracted only if output_type is set to PNGs. Otherwise a video will be made, and in the case of Both, the video will be extracted in the next step to PNGs + convert_video( + model, + input_source=input_frames_path, # full path of the folder that contains all of the extracted input imgs + output_type='video' if output_type.upper() in ("VIDEO", "BOTH") else 'png_sequence', + output_alpha=output_alpha_vid_path if output_type.upper() in ("VIDEO", "BOTH") else output_folder_path, + output_video_mbps=4, + output_video_fps=fps, + downsample_ratio=None, # None for auto + seq_chunk=12, # Process n frames at once for better parallelism + progress=True # show extraction progress + ) + + if output_type.lower() == "both": + extract_frames(output_alpha_vid_path, output_folder_path) diff --git a/extensions/deforum/scripts/deforum_helpers/hybrid_video.py b/extensions/deforum/scripts/deforum_helpers/hybrid_video.py new file mode 100644 index 0000000000000000000000000000000000000000..76401712387cbda1bb29dbd6669fc9f774903c7e --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/hybrid_video.py @@ -0,0 +1,436 @@ +import cv2 +import os +import pathlib +import numpy as np +import random +from PIL import Image, ImageChops, ImageOps, ImageEnhance +from .video_audio_utilities import vid2frames, get_quick_vid_info, get_frame_name, get_next_frame +from .human_masking import video2humanmasks + +def delete_all_imgs_in_folder(folder_path): + files = list(pathlib.Path(folder_path).glob('*.jpg')) + files.extend(list(pathlib.Path(folder_path).glob('*.png'))) + for f in files: os.remove(f) + +def hybrid_generation(args, anim_args, root): + video_in_frame_path = os.path.join(args.outdir, 'inputframes') + hybrid_frame_path = os.path.join(args.outdir, 'hybridframes') + human_masks_path = os.path.join(args.outdir, 'human_masks') + + if anim_args.hybrid_generate_inputframes: + # create folders for the video input frames and optional hybrid frames to live in + os.makedirs(video_in_frame_path, exist_ok=True) + os.makedirs(hybrid_frame_path, exist_ok=True) + + # delete frames if overwrite = true + if anim_args.overwrite_extracted_frames: + delete_all_imgs_in_folder(hybrid_frame_path) + + # save the video frames from input video + print(f"Video to extract: {anim_args.video_init_path}") + print(f"Extracting video (1 every {anim_args.extract_nth_frame}) frames to {video_in_frame_path}...") + video_fps = vid2frames(video_path=anim_args.video_init_path, video_in_frame_path=video_in_frame_path, n=anim_args.extract_nth_frame, overwrite=anim_args.overwrite_extracted_frames, extract_from_frame=anim_args.extract_from_frame, extract_to_frame=anim_args.extract_to_frame) + + # extract alpha masks of humans from the extracted input video imgs + if anim_args.hybrid_generate_human_masks != "None": + # create a folder for the human masks imgs to live in + print(f"Checking /creating a folder for the human masks") + os.makedirs(human_masks_path, exist_ok=True) + + # delete frames if overwrite = true + if anim_args.overwrite_extracted_frames: + delete_all_imgs_in_folder(human_masks_path) + + # in case that generate_input_frames isn't selected, we won't get the video fps rate as vid2frames isn't called, So we'll check the video fps in here instead + if not anim_args.hybrid_generate_inputframes: + _, video_fps, _ = get_quick_vid_info(anim_args.video_init_path) + + # calculate the correct fps of the masked video according to the original video fps and 'extract_nth_frame' + output_fps = video_fps/anim_args.extract_nth_frame + + # generate the actual alpha masks from the input imgs + print(f"Extracting alpha humans masks from the input frames") + video2humanmasks(video_in_frame_path, human_masks_path, anim_args.hybrid_generate_human_masks, output_fps) + + # determine max frames from length of input frames + anim_args.max_frames = len([f for f in pathlib.Path(video_in_frame_path).glob('*.jpg')]) + print(f"Using {anim_args.max_frames} input frames from {video_in_frame_path}...") + + # get sorted list of inputfiles + inputfiles = sorted(pathlib.Path(video_in_frame_path).glob('*.jpg')) + + # use first frame as init + if anim_args.hybrid_use_first_frame_as_init_image: + for f in inputfiles: + args.init_image = str(f) + args.use_init = True + print(f"Using init_image from video: {args.init_image}") + break + + return args, anim_args, inputfiles + +def hybrid_composite(args, anim_args, frame_idx, prev_img, depth_model, hybrid_comp_schedules, root): + video_frame = os.path.join(args.outdir, 'inputframes', get_frame_name(anim_args.video_init_path) + f"{frame_idx:05}.jpg") + video_depth_frame = os.path.join(args.outdir, 'hybridframes', get_frame_name(anim_args.video_init_path) + f"_vid_depth{frame_idx:05}.jpg") + depth_frame = os.path.join(args.outdir, f"{args.timestring}_depth_{frame_idx-1:05}.png") + mask_frame = os.path.join(args.outdir, 'hybridframes', get_frame_name(anim_args.video_init_path) + f"_mask{frame_idx:05}.jpg") + comp_frame = os.path.join(args.outdir, 'hybridframes', get_frame_name(anim_args.video_init_path) + f"_comp{frame_idx:05}.jpg") + prev_frame = os.path.join(args.outdir, 'hybridframes', get_frame_name(anim_args.video_init_path) + f"_prev{frame_idx:05}.jpg") + prev_img = cv2.cvtColor(prev_img, cv2.COLOR_BGR2RGB) + prev_img_hybrid = Image.fromarray(prev_img) + video_image = Image.open(video_frame) + video_image = video_image.resize((args.W, args.H), Image.Resampling.LANCZOS) + hybrid_mask = None + + # composite mask types + if anim_args.hybrid_comp_mask_type == 'Depth': # get depth from last generation + hybrid_mask = Image.open(depth_frame) + elif anim_args.hybrid_comp_mask_type == 'Video Depth': # get video depth + video_depth = depth_model.predict(np.array(video_image), anim_args, root.half_precision) + depth_model.save(video_depth_frame, video_depth) + hybrid_mask = Image.open(video_depth_frame) + elif anim_args.hybrid_comp_mask_type == 'Blend': # create blend mask image + hybrid_mask = Image.blend(ImageOps.grayscale(prev_img_hybrid), ImageOps.grayscale(video_image), hybrid_comp_schedules['mask_blend_alpha']) + elif anim_args.hybrid_comp_mask_type == 'Difference': # create difference mask image + hybrid_mask = ImageChops.difference(ImageOps.grayscale(prev_img_hybrid), ImageOps.grayscale(video_image)) + + # optionally invert mask, if mask type is defined + if anim_args.hybrid_comp_mask_inverse and anim_args.hybrid_comp_mask_type != "None": + hybrid_mask = ImageOps.invert(hybrid_mask) + + # if a mask type is selected, make composition + if hybrid_mask == None: + hybrid_comp = video_image + else: + # ensure grayscale + hybrid_mask = ImageOps.grayscale(hybrid_mask) + # equalization before + if anim_args.hybrid_comp_mask_equalize in ['Before', 'Both']: + hybrid_mask = ImageOps.equalize(hybrid_mask) + # contrast + hybrid_mask = ImageEnhance.Contrast(hybrid_mask).enhance(hybrid_comp_schedules['mask_contrast']) + # auto contrast with cutoffs lo/hi + if anim_args.hybrid_comp_mask_auto_contrast: + hybrid_mask = autocontrast_grayscale(np.array(hybrid_mask), hybrid_comp_schedules['mask_auto_contrast_cutoff_low'], hybrid_comp_schedules['mask_auto_contrast_cutoff_high']) + hybrid_mask = Image.fromarray(hybrid_mask) + hybrid_mask = ImageOps.grayscale(hybrid_mask) + if anim_args.hybrid_comp_save_extra_frames: + hybrid_mask.save(mask_frame) + # equalization after + if anim_args.hybrid_comp_mask_equalize in ['After', 'Both']: + hybrid_mask = ImageOps.equalize(hybrid_mask) + # do compositing and save + hybrid_comp = Image.composite(prev_img_hybrid, video_image, hybrid_mask) + if anim_args.hybrid_comp_save_extra_frames: + hybrid_comp.save(comp_frame) + + # final blend of composite with prev_img, or just a blend if no composite is selected + hybrid_blend = Image.blend(prev_img_hybrid, hybrid_comp, hybrid_comp_schedules['alpha']) + if anim_args.hybrid_comp_save_extra_frames: + hybrid_blend.save(prev_frame) + + prev_img = cv2.cvtColor(np.array(hybrid_blend), cv2.COLOR_RGB2BGR) + + # restore to np array and return + return args, prev_img + +def get_matrix_for_hybrid_motion(frame_idx, dimensions, inputfiles, hybrid_motion): + img1 = cv2.cvtColor(get_resized_image_from_filename(str(inputfiles[frame_idx-1]), dimensions), cv2.COLOR_BGR2GRAY) + img2 = cv2.cvtColor(get_resized_image_from_filename(str(inputfiles[frame_idx]), dimensions), cv2.COLOR_BGR2GRAY) + matrix = get_transformation_matrix_from_images(img1, img2, hybrid_motion) + print(f"Calculating {hybrid_motion} RANSAC matrix for frames {frame_idx} to {frame_idx+1}") + return matrix + +def get_matrix_for_hybrid_motion_prev(frame_idx, dimensions, inputfiles, prev_img, hybrid_motion): + # first handle invalid images from cadence by returning default matrix + height, width = prev_img.shape[:2] + if height == 0 or width == 0 or prev_img != np.uint8: + return get_hybrid_motion_default_matrix(hybrid_motion) + else: + prev_img_gray = cv2.cvtColor(prev_img, cv2.COLOR_BGR2GRAY) + img = cv2.cvtColor(get_resized_image_from_filename(str(inputfiles[frame_idx]), dimensions), cv2.COLOR_BGR2GRAY) + matrix = get_transformation_matrix_from_images(prev_img_gray, img, hybrid_motion) + print(f"Calculating {hybrid_motion} RANSAC matrix for frames {frame_idx} to {frame_idx+1}") + return matrix + +def get_flow_for_hybrid_motion(frame_idx, dimensions, inputfiles, hybrid_frame_path, method, do_flow_visualization=False): + print(f"Calculating {method} optical flow for frames {frame_idx} to {frame_idx+1}") + i1 = get_resized_image_from_filename(str(inputfiles[frame_idx]), dimensions) + i2 = get_resized_image_from_filename(str(inputfiles[frame_idx+1]), dimensions) + flow = get_flow_from_images(i1, i2, method) + if do_flow_visualization: + save_flow_visualization(frame_idx, dimensions, flow, inputfiles, hybrid_frame_path) + return flow + +def get_flow_for_hybrid_motion_prev(frame_idx, dimensions, inputfiles, hybrid_frame_path, prev_img, method, do_flow_visualization=False): + print(f"Calculating {method} optical flow for frames {frame_idx} to {frame_idx+1}") + # first handle invalid images from cadence by returning default matrix + height, width = prev_img.shape[:2] + if height == 0 or width == 0: + flow = get_hybrid_motion_default_flow(dimensions) + else: + i1 = prev_img.astype(np.uint8) + i2 = get_resized_image_from_filename(str(inputfiles[frame_idx]), dimensions) + flow = get_flow_from_images(i1, i2, method) + if do_flow_visualization: + save_flow_visualization(frame_idx, dimensions, flow, inputfiles, hybrid_frame_path) + return flow + +def image_transform_ransac(image_cv2, xform, hybrid_motion, border_mode=cv2.BORDER_REPLICATE): + if hybrid_motion == "Perspective": + return image_transform_perspective(image_cv2, xform, border_mode=border_mode) + else: # Affine + return image_transform_affine(image_cv2, xform, border_mode=border_mode) + +def image_transform_optical_flow(img, flow, border_mode=cv2.BORDER_REPLICATE, flow_reverse=False): + if not flow_reverse: + flow = -flow + h, w = img.shape[:2] + flow[:, :, 0] += np.arange(w) + flow[:, :, 1] += np.arange(h)[:,np.newaxis] + return remap(img, flow, border_mode) + +def image_transform_affine(image_cv2, xform, border_mode=cv2.BORDER_REPLICATE): + return cv2.warpAffine( + image_cv2, + xform, + (image_cv2.shape[1],image_cv2.shape[0]), + borderMode=border_mode + ) + +def image_transform_perspective(image_cv2, xform, border_mode=cv2.BORDER_REPLICATE): + return cv2.warpPerspective( + image_cv2, + xform, + (image_cv2.shape[1], image_cv2.shape[0]), + borderMode=border_mode + ) + +def get_hybrid_motion_default_matrix(hybrid_motion): + if hybrid_motion == "Perspective": + arr = np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) + else: + arr = np.array([[1., 0., 0.], [0., 1., 0.]]) + return arr + +def get_hybrid_motion_default_flow(dimensions): + cols, rows = dimensions + flow = np.zeros((rows, cols, 2), np.float32) + return flow + +def get_transformation_matrix_from_images(img1, img2, hybrid_motion, max_corners=200, quality_level=0.01, min_distance=30, block_size=3): + # Detect feature points in previous frame + prev_pts = cv2.goodFeaturesToTrack(img1, + maxCorners=max_corners, + qualityLevel=quality_level, + minDistance=min_distance, + blockSize=block_size) + + if prev_pts is None or len(prev_pts) < 8 or img1 is None or img2 is None: + return get_hybrid_motion_default_matrix(hybrid_motion) + + # Get optical flow + curr_pts, status, err = cv2.calcOpticalFlowPyrLK(img1, img2, prev_pts, None) + + # Filter only valid points + idx = np.where(status==1)[0] + prev_pts = prev_pts[idx] + curr_pts = curr_pts[idx] + + if len(prev_pts) < 8 or len(curr_pts) < 8: + return get_hybrid_motion_default_matrix(hybrid_motion) + + if hybrid_motion == "Perspective": # Perspective - Find the transformation between points + transformation_matrix, mask = cv2.findHomography(prev_pts, curr_pts, cv2.RANSAC, 5.0) + return transformation_matrix + else: # Affine - Compute a rigid transformation (without depth, only scale + rotation + translation) + transformation_rigid_matrix, rigid_mask = cv2.estimateAffinePartial2D(prev_pts, curr_pts) + return transformation_rigid_matrix + +def get_flow_from_images(i1, i2, method): + if method =="DIS Medium": + r = get_flow_from_images_DIS(i1, i2, cv2.DISOPTICAL_FLOW_PRESET_MEDIUM) + elif method =="DIS Fast": + r = get_flow_from_images_DIS(i1, i2, cv2.DISOPTICAL_FLOW_PRESET_FAST) + elif method =="DIS UltraFast": + r = get_flow_from_images_DIS(i1, i2, cv2.DISOPTICAL_FLOW_PRESET_ULTRAFAST) + elif method == "DenseRLOF": # requires running opencv-contrib-python (full opencv) INSTEAD of opencv-python + r = get_flow_from_images_Dense_RLOF(i1, i2) + elif method == "SF": # requires running opencv-contrib-python (full opencv) INSTEAD of opencv-python + r = get_flow_from_images_SF(i1, i2) + elif method =="Farneback Fine": + r = get_flow_from_images_Farneback(i1, i2, 'fine') + else: # Farneback Normal: + r = get_flow_from_images_Farneback(i1, i2) + return r + +def get_flow_from_images_DIS(i1, i2, preset): + i1 = cv2.cvtColor(i1, cv2.COLOR_BGR2GRAY) + i2 = cv2.cvtColor(i2, cv2.COLOR_BGR2GRAY) + dis=cv2.DISOpticalFlow_create(preset) + return dis.calc(i1, i2, None) + +def get_flow_from_images_Dense_RLOF(i1, i2, last_flow=None): + return cv2.optflow.calcOpticalFlowDenseRLOF(i1, i2, flow = last_flow) + +def get_flow_from_images_SF(i1, i2, last_flow=None, layers = 3, averaging_block_size = 2, max_flow = 4): + return cv2.optflow.calcOpticalFlowSF(i1, i2, layers, averaging_block_size, max_flow) + +def get_flow_from_images_Farneback(i1, i2, preset="normal", last_flow=None, pyr_scale = 0.5, levels = 3, winsize = 15, iterations = 3, poly_n = 5, poly_sigma = 1.2, flags = 0): + flags = cv2.OPTFLOW_FARNEBACK_GAUSSIAN # Specify the operation flags + pyr_scale = 0.5 # The image scale (<1) to build pyramids for each image + if preset == "fine": + levels = 13 # The number of pyramid layers, including the initial image + winsize = 77 # The averaging window size + iterations = 13 # The number of iterations at each pyramid level + poly_n = 15 # The size of the pixel neighborhood used to find polynomial expansion in each pixel + poly_sigma = 0.8 # The standard deviation of the Gaussian used to smooth derivatives used as a basis for the polynomial expansion + else: # "normal" + levels = 5 # The number of pyramid layers, including the initial image + winsize = 21 # The averaging window size + iterations = 5 # The number of iterations at each pyramid level + poly_n = 7 # The size of the pixel neighborhood used to find polynomial expansion in each pixel + poly_sigma = 1.2 # The standard deviation of the Gaussian used to smooth derivatives used as a basis for the polynomial expansion + i1 = cv2.cvtColor(i1, cv2.COLOR_BGR2GRAY) + i2 = cv2.cvtColor(i2, cv2.COLOR_BGR2GRAY) + flags = 0 # flags = cv2.OPTFLOW_USE_INITIAL_FLOW + flow = cv2.calcOpticalFlowFarneback(i1, i2, last_flow, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags) + return flow + +def save_flow_visualization(frame_idx, dimensions, flow, inputfiles, hybrid_frame_path): + flow_img_file = os.path.join(hybrid_frame_path, f"flow{frame_idx:05}.jpg") + flow_img = cv2.imread(str(inputfiles[frame_idx])) + flow_img = cv2.resize(flow_img, (dimensions[0], dimensions[1]), cv2.INTER_AREA) + flow_img = cv2.cvtColor(flow_img, cv2.COLOR_RGB2GRAY) + flow_img = cv2.cvtColor(flow_img, cv2.COLOR_GRAY2BGR) + flow_img = draw_flow_lines_in_grid_in_color(flow_img, flow) + flow_img = cv2.cvtColor(flow_img, cv2.COLOR_BGR2RGB) + cv2.imwrite(flow_img_file, flow_img) + print(f"Saved optical flow visualization: {flow_img_file}") + +def draw_flow_lines_in_grid_in_color(img, flow, step=8, magnitude_multiplier=1, min_magnitude = 1, max_magnitude = 10000): + flow = flow * magnitude_multiplier + h, w = img.shape[:2] + y, x = np.mgrid[step/2:h:step, step/2:w:step].reshape(2,-1).astype(int) + fx, fy = flow[y,x].T + lines = np.vstack([x, y, x+fx, y+fy]).T.reshape(-1, 2, 2) + lines = np.int32(lines + 0.5) + vis = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + vis = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR) + + mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1]) + hsv = np.zeros((flow.shape[0], flow.shape[1], 3), dtype=np.uint8) + hsv[...,0] = ang*180/np.pi/2 + hsv[...,1] = 255 + hsv[...,2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) + bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) + vis = cv2.add(vis, bgr) + + # Iterate through the lines + for (x1, y1), (x2, y2) in lines: + # Calculate the magnitude of the line + magnitude = np.sqrt((x2 - x1)**2 + (y2 - y1)**2) + + # Only draw the line if it falls within the magnitude range + if min_magnitude <= magnitude <= max_magnitude: + b = int(bgr[y1, x1, 0]) + g = int(bgr[y1, x1, 1]) + r = int(bgr[y1, x1, 2]) + color = (b, g, r) + cv2.arrowedLine(vis, (x1, y1), (x2, y2), color, thickness=1, tipLength=0.1) + return vis + +def draw_flow_lines_in_color(img, flow, threshold=3, magnitude_multiplier=1, min_magnitude = 0, max_magnitude = 10000): + # h, w = img.shape[:2] + vis = img.copy() # Create a copy of the input image + + # Find the locations in the flow field where the magnitude of the flow is greater than the threshold + mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1]) + idx = np.where(mag > threshold) + + # Create HSV image + hsv = np.zeros((flow.shape[0], flow.shape[1], 3), dtype=np.uint8) + hsv[...,0] = ang*180/np.pi/2 + hsv[...,1] = 255 + hsv[...,2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) + + # Convert HSV image to BGR + bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) + + # Add color from bgr + vis = cv2.add(vis, bgr) + + # Draw an arrow at each of these locations to indicate the direction of the flow + for i, (y, x) in enumerate(zip(idx[0], idx[1])): + # Calculate the magnitude of the line + x2 = x + magnitude_multiplier * int(flow[y, x, 0]) + y2 = y + magnitude_multiplier * int(flow[y, x, 1]) + magnitude = np.sqrt((x2 - x)**2 + (y2 - y)**2) + + # Only draw the line if it falls within the magnitude range + if min_magnitude <= magnitude <= max_magnitude: + if i % random.randint(100, 200) == 0: + b = int(bgr[y, x, 0]) + g = int(bgr[y, x, 1]) + r = int(bgr[y, x, 2]) + color = (b, g, r) + cv2.arrowedLine(vis, (x, y), (x2, y2), color, thickness=1, tipLength=0.25) + + return vis + +def autocontrast_grayscale(image, low_cutoff=0, high_cutoff=100): + # Perform autocontrast on a grayscale np array image. + # Find the minimum and maximum values in the image + min_val = np.percentile(image, low_cutoff) + max_val = np.percentile(image, high_cutoff) + + # Scale the image so that the minimum value is 0 and the maximum value is 255 + image = 255 * (image - min_val) / (max_val - min_val) + + # Clip values that fall outside the range [0, 255] + image = np.clip(image, 0, 255) + + return image + +def get_resized_image_from_filename(im, dimensions): + img = cv2.imread(im) + return cv2.resize(img, (dimensions[0], dimensions[1]), cv2.INTER_AREA) + +def remap(img, flow, border_mode = cv2.BORDER_REFLECT_101): + # copyMakeBorder doesn't support wrap, but supports replicate. Replaces wrap with reflect101. + if border_mode == cv2.BORDER_WRAP: + border_mode = cv2.BORDER_REFLECT_101 + h, w = img.shape[:2] + displacement = int(h * 0.25), int(w * 0.25) + larger_img = cv2.copyMakeBorder(img, displacement[0], displacement[0], displacement[1], displacement[1], border_mode) + lh, lw = larger_img.shape[:2] + larger_flow = extend_flow(flow, lw, lh) + remapped_img = cv2.remap(larger_img, larger_flow, None, cv2.INTER_LINEAR, border_mode) + output_img = center_crop_image(remapped_img, w, h) + return output_img + +def center_crop_image(img, w, h): + y, x, _ = img.shape + width_indent = int((x - w) / 2) + height_indent = int((y - h) / 2) + cropped_img = img[height_indent:y-height_indent, width_indent:x-width_indent] + return cropped_img + +def extend_flow(flow, w, h): + # Get the shape of the original flow image + flow_h, flow_w = flow.shape[:2] + # Calculate the position of the image in the new image + x_offset = int((w - flow_w) / 2) + y_offset = int((h - flow_h) / 2) + # Generate the X and Y grids + x_grid, y_grid = np.meshgrid(np.arange(w), np.arange(h)) + # Create the new flow image and set it to the X and Y grids + new_flow = np.dstack((x_grid, y_grid)).astype(np.float32) + # Shift the values of the original flow by the size of the border + flow[:,:,0] += x_offset + flow[:,:,1] += y_offset + # Overwrite the middle of the grid with the original flow + new_flow[y_offset:y_offset+flow_h, x_offset:x_offset+flow_w, :] = flow + # Return the extended image + return new_flow + \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/image_sharpening.py b/extensions/deforum/scripts/deforum_helpers/image_sharpening.py new file mode 100644 index 0000000000000000000000000000000000000000..aea81449e3c61808c44de72450ed4d1c0ce88fc4 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/image_sharpening.py @@ -0,0 +1,22 @@ +import cv2 +import numpy as np + +def unsharp_mask(img, kernel_size=(5, 5), sigma=1.0, amount=1.0, threshold=0, mask=None): + if amount == 0: + return img + # Return a sharpened version of the image, using an unsharp mask. + # If mask is not None, only areas under mask are handled + blurred = cv2.GaussianBlur(img, kernel_size, sigma) + sharpened = float(amount + 1) * img - float(amount) * blurred + sharpened = np.maximum(sharpened, np.zeros(sharpened.shape)) + sharpened = np.minimum(sharpened, 255 * np.ones(sharpened.shape)) + sharpened = sharpened.round().astype(np.uint8) + if threshold > 0: + low_contrast_mask = np.absolute(img - blurred) < threshold + np.copyto(sharpened, img, where=low_contrast_mask) + if mask is not None: + mask = np.array(mask) + masked_sharpened = cv2.bitwise_and(sharpened, sharpened, mask=mask) + masked_img = cv2.bitwise_and(img, img, mask=255-mask) + sharpened = cv2.add(masked_img, masked_sharpened) + return sharpened diff --git a/extensions/deforum/scripts/deforum_helpers/load_images.py b/extensions/deforum/scripts/deforum_helpers/load_images.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc5726f8aed86fb190ae15aa6098c3bcac8ec2c --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/load_images.py @@ -0,0 +1,102 @@ +import requests +import os +from PIL import Image, ImageOps +import cv2 +import numpy as np +import socket +import torchvision.transforms.functional as TF + +def load_img(path : str, shape=None, use_alpha_as_mask=False): + # use_alpha_as_mask: Read the alpha channel of the image as the mask image + image = load_image(path) + if use_alpha_as_mask: + image = image.convert('RGBA') + else: + image = image.convert('RGB') + + if shape is not None: + image = image.resize(shape, resample=Image.LANCZOS) + + mask_image = None + if use_alpha_as_mask: + # Split alpha channel into a mask_image + red, green, blue, alpha = Image.Image.split(image) + mask_image = alpha.convert('L') + image = image.convert('RGB') + + # check using init image alpha as mask if mask is not blank + extrema = mask_image.getextrema() + if (extrema == (0,0)) or extrema == (255,255): + print("use_alpha_as_mask==True: Using the alpha channel from the init image as a mask, but the alpha channel is blank.") + print("ignoring alpha as mask.") + mask_image = None + + return image, mask_image + +def load_image(image_path :str): + image = None + if image_path.startswith('http://') or image_path.startswith('https://'): + try: + host = socket.gethostbyname("www.google.com") + s = socket.create_connection((host, 80), 2) + s.close() + except: + raise ConnectionError("There is no active internet connection available - please use local masks and init files only.") + + try: + response = requests.get(image_path, stream=True) + except requests.exceptions.RequestException as e: + raise ConnectionError("Failed to download image due to no internet connection. Error: {}".format(e)) + if response.status_code == 404 or response.status_code != 200: + raise ConnectionError("Init image url or mask image url is not valid") + image = Image.open(response.raw).convert('RGB') + else: + if not os.path.exists(image_path): + raise RuntimeError("Init image path or mask image path is not valid") + image = Image.open(image_path).convert('RGB') + + return image + +def prepare_mask(mask_input, mask_shape, mask_brightness_adjust=1.0, mask_contrast_adjust=1.0): + """ + prepares mask for use in webui + """ + if isinstance(mask_input, Image.Image): + mask = mask_input + else : + mask = load_image(mask_input) + mask = mask.resize(mask_shape, resample=Image.LANCZOS) + if mask_brightness_adjust != 1: + mask = TF.adjust_brightness(mask, mask_brightness_adjust) + if mask_contrast_adjust != 1: + mask = TF.adjust_contrast(mask, mask_contrast_adjust) + mask = mask.convert('L') + return mask + +def check_mask_for_errors(mask_input, invert_mask=False): + extrema = mask_input.getextrema() + if (invert_mask): + if extrema == (255,255): + print("after inverting mask will be blank. ignoring mask") + return None + elif extrema == (0,0): + print("mask is blank. ignoring mask") + return None + else: + return mask_input + +def get_mask(args): + return check_mask_for_errors( + prepare_mask(args.mask_file, (args.W, args.H), args.mask_contrast_adjust, args.mask_brightness_adjust) + ) + +def get_mask_from_file(mask_file, args): + return check_mask_for_errors( + prepare_mask(mask_file, (args.W, args.H), args.mask_contrast_adjust, args.mask_brightness_adjust) + ) + +def blank_if_none(mask, w, h, mode): + return Image.new(mode, (w, h), (0)) if mask is None else mask + +def none_if_blank(mask): + return None if mask.getextrema() == (0,0) else mask diff --git a/extensions/deforum/scripts/deforum_helpers/noise.py b/extensions/deforum/scripts/deforum_helpers/noise.py new file mode 100644 index 0000000000000000000000000000000000000000..768f0e9f73ea50b3262c643b712730f614488895 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/noise.py @@ -0,0 +1,64 @@ +import torch +import numpy as np +from PIL import ImageOps +import math +from .animation import sample_to_cv2 +import cv2 + +deforum_noise_gen = torch.Generator(device='cpu') + +# 2D Perlin noise in PyTorch https://gist.github.com/vadimkantorov/ac1b097753f217c5c11bc2ff396e0a57 +def rand_perlin_2d(shape, res, fade = lambda t: 6*t**5 - 15*t**4 + 10*t**3): + delta = (res[0] / shape[0], res[1] / shape[1]) + d = (shape[0] // res[0], shape[1] // res[1]) + + grid = torch.stack(torch.meshgrid(torch.arange(0, res[0], delta[0]), torch.arange(0, res[1], delta[1]), indexing='ij'), dim = -1) % 1 + angles = 2*math.pi*torch.rand(res[0]+1, res[1]+1, generator=deforum_noise_gen) + gradients = torch.stack((torch.cos(angles), torch.sin(angles)), dim = -1) + + tile_grads = lambda slice1, slice2: gradients[slice1[0]:slice1[1], slice2[0]:slice2[1]].repeat_interleave(d[0], 0).repeat_interleave(d[1], 1) + dot = lambda grad, shift: (torch.stack((grid[:shape[0],:shape[1],0] + shift[0], grid[:shape[0],:shape[1], 1] + shift[1] ), dim = -1) * grad[:shape[0], :shape[1]]).sum(dim = -1) + + n00 = dot(tile_grads([0, -1], [0, -1]), [0, 0]) + n10 = dot(tile_grads([1, None], [0, -1]), [-1, 0]) + n01 = dot(tile_grads([0, -1],[1, None]), [0, -1]) + n11 = dot(tile_grads([1, None], [1, None]), [-1,-1]) + t = fade(grid[:shape[0], :shape[1]]) + return math.sqrt(2) * torch.lerp(torch.lerp(n00, n10, t[..., 0]), torch.lerp(n01, n11, t[..., 0]), t[..., 1]) + +def rand_perlin_2d_octaves(shape, res, octaves=1, persistence=0.5): + noise = torch.zeros(shape) + frequency = 1 + amplitude = 1 + for _ in range(int(octaves)): + noise += amplitude * rand_perlin_2d(shape, (frequency*res[0], frequency*res[1])) + frequency *= 2 + amplitude *= persistence + return noise + +def condition_noise_mask(noise_mask, invert_mask = False): + if invert_mask: + noise_mask = ImageOps.invert(noise_mask) + noise_mask = np.array(noise_mask.convert("L")) + noise_mask = noise_mask.astype(np.float32) / 255.0 + noise_mask = np.around(noise_mask, decimals=0) + noise_mask = torch.from_numpy(noise_mask) + #noise_mask = torch.round(noise_mask) + return noise_mask + +def add_noise(sample, noise_amt: float, seed: int, noise_type: str, noise_args, noise_mask = None, invert_mask = False): + deforum_noise_gen.manual_seed(seed) # Reproducibility + sample2dshape = (sample.shape[0], sample.shape[1]) #sample is cv2, so height - width + noise = torch.randn((sample.shape[2], sample.shape[0], sample.shape[1]), generator=deforum_noise_gen) # White noise + if noise_type == 'perlin': + # rand_perlin_2d_octaves is between -1 and 1, so we need to shift it to be between 0 and 1 + # print(sample.shape) + noise = noise * ((rand_perlin_2d_octaves(sample2dshape, (int(noise_args[0]), int(noise_args[1])), octaves=noise_args[2], persistence=noise_args[3]) + torch.ones(sample2dshape)) / 2) + if noise_mask is not None: + noise_mask = condition_noise_mask(noise_mask, invert_mask) + noise_to_add = sample_to_cv2(noise * noise_mask) + else: + noise_to_add = sample_to_cv2(noise) + sample = cv2.addWeighted(sample, 1-noise_amt, noise_to_add, noise_amt, 0) + + return sample diff --git a/extensions/deforum/scripts/deforum_helpers/parseq_adapter.py b/extensions/deforum/scripts/deforum_helpers/parseq_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..314b594ac25792358807bdb602cae7f97387edf4 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/parseq_adapter.py @@ -0,0 +1,164 @@ +import copy +import json +import logging +import operator +from operator import itemgetter + +import numpy as np +import pandas as pd +import requests + +from .animation_key_frames import DeformAnimKeys + +logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) + + +class ParseqAnimKeys(): + def __init__(self, parseq_args, anim_args): + + # Resolve manifest either directly from supplied value + # or via supplied URL + manifestOrUrl = parseq_args.parseq_manifest.strip() + if (manifestOrUrl.startswith('http')): + logging.info(f"Loading Parseq manifest from URL: {manifestOrUrl}") + try: + body = requests.get(manifestOrUrl).text + logging.debug(f"Loaded remote manifest: {body}") + self.parseq_json = json.loads(body) + + # Add the parseq manifest without the detailed frame data to parseq_args. + # This ensures it will be saved in the settings file, so that you can always + # see exactly what parseq prompts and keyframes were used, even if what the URL + # points to changes. + parseq_args.fetched_parseq_manifest_summary = copy.deepcopy(self.parseq_json) + if parseq_args.fetched_parseq_manifest_summary['rendered_frames']: + del parseq_args.fetched_parseq_manifest_summary['rendered_frames'] + if parseq_args.fetched_parseq_manifest_summary['rendered_frames_meta']: + del parseq_args.fetched_parseq_manifest_summary['rendered_frames_meta'] + + except Exception as e: + logging.error(f"Unable to load Parseq manifest from URL: {manifestOrUrl}") + raise e + else: + self.parseq_json = json.loads(manifestOrUrl) + + self.default_anim_keys = DeformAnimKeys(anim_args) + self.rendered_frames = self.parseq_json['rendered_frames'] + self.max_frame = self.get_max('frame') + count_defined_frames = len(self.rendered_frames) + expected_defined_frames = self.max_frame+1 # frames are 0-indexed + + self.required_frames = anim_args.max_frames + + if (expected_defined_frames != count_defined_frames): + logging.warning(f"There may be duplicated or missing frame data in the Parseq input: expected {expected_defined_frames} frames including frame 0 because the highest frame number is {self.max_frame}, but there are {count_defined_frames} frames defined.") + + if (anim_args.max_frames > count_defined_frames): + logging.info(f"Parseq data defines {count_defined_frames} frames, but the requested animation is {anim_args.max_frames} frames. The last Parseq frame definition will be duplicated to match the expected frame count.") + if (anim_args.max_frames < count_defined_frames): + logging.info(f"Parseq data defines {count_defined_frames} frames, but the requested animation is {anim_args.max_frames} frames. The last Parseq frame definitions will be ignored.") + else: + logging.info(f"Parseq data defines {count_defined_frames} frames.") + + # Parseq treats input values as absolute values. So if you want to + # progressively rotate 180 degrees over 4 frames, you specify: 45, 90, 135, 180. + # However, many animation parameters are relative to the previous frame if there is enough + # loopback strength. So if you want to rotate 180 degrees over 5 frames, the animation engine expects: + # 45, 45, 45, 45. Therefore, for such parameter, we use the fact that Parseq supplies delta values. + optional_delta = '_delta' if parseq_args.parseq_use_deltas else '' + self.angle_series = self.parseq_to_anim_series('angle' + optional_delta) + self.zoom_series = self.parseq_to_anim_series('zoom' + optional_delta) + self.translation_x_series = self.parseq_to_anim_series('translation_x' + optional_delta) + self.translation_y_series = self.parseq_to_anim_series('translation_y' + optional_delta) + self.translation_z_series = self.parseq_to_anim_series('translation_z' + optional_delta) + self.rotation_3d_x_series = self.parseq_to_anim_series('rotation_3d_x' + optional_delta) + self.rotation_3d_y_series = self.parseq_to_anim_series('rotation_3d_y' + optional_delta) + self.rotation_3d_z_series = self.parseq_to_anim_series('rotation_3d_z' + optional_delta) + self.perspective_flip_theta_series = self.parseq_to_anim_series('perspective_flip_theta' + optional_delta) + self.perspective_flip_phi_series = self.parseq_to_anim_series('perspective_flip_phi' + optional_delta) + self.perspective_flip_gamma_series = self.parseq_to_anim_series('perspective_flip_gamma' + optional_delta) + + # Non-motion animation args + self.perspective_flip_fv_series = self.parseq_to_anim_series('perspective_flip_fv') + self.noise_schedule_series = self.parseq_to_anim_series('noise') + self.strength_schedule_series = self.parseq_to_anim_series('strength') + self.sampler_schedule_series = self.parseq_to_anim_series('sampler_schedule') + self.contrast_schedule_series = self.parseq_to_anim_series('contrast') + self.cfg_scale_schedule_series = self.parseq_to_anim_series('scale') + self.steps_schedule_series = self.parseq_to_anim_series("steps_schedule") + self.seed_schedule_series = self.parseq_to_anim_series('seed') + self.fov_series = self.parseq_to_anim_series('fov') + self.near_series = self.parseq_to_anim_series('near') + self.far_series = self.parseq_to_anim_series('far') + self.prompts = self.parseq_to_anim_series('deforum_prompt') # formatted as "{positive} --neg {negative}" + self.subseed_series = self.parseq_to_anim_series('subseed') + self.subseed_strength_series = self.parseq_to_anim_series('subseed_strength') + self.kernel_schedule_series = self.parseq_to_anim_series('antiblur_kernel') + self.sigma_schedule_series = self.parseq_to_anim_series('antiblur_sigma') + self.amount_schedule_series = self.parseq_to_anim_series('antiblur_amount') + self.threshold_schedule_series = self.parseq_to_anim_series('antiblur_threshold') + + # Config: + # TODO this is currently ignored. User must ensure the output FPS set in parseq + # matches the one set in Deforum to avoid unexpected results. + self.config_output_fps = self.parseq_json['options']['output_fps'] + + def get_max(self, seriesName): + return max(self.rendered_frames, key=itemgetter(seriesName))[seriesName] + + def parseq_to_anim_series(self, seriesName): + + # Check if valus is present in first frame of JSON data. If not, assume it's undefined. + # The Parseq contract is that the first frame (at least) must define values for all fields. + try: + if self.rendered_frames[0][seriesName] is not None: + logging.info(f"Found {seriesName} in first frame of Parseq data. Assuming it's defined.") + except KeyError: + return None + + key_frame_series = pd.Series([np.nan for a in range(self.required_frames)]) + + for frame in self.rendered_frames: + frame_idx = frame['frame'] + if frame_idx < self.required_frames: + if not np.isnan(key_frame_series[frame_idx]): + logging.warning(f"Duplicate frame definition {frame_idx} detected for data {seriesName}. Latest wins.") + key_frame_series[frame_idx] = frame[seriesName] + + # If the animation will have more frames than Parseq defines, + # duplicate final value to match the required frame count. + while (frame_idx < self.required_frames): + key_frame_series[frame_idx] = operator.itemgetter(-1)(self.rendered_frames)[seriesName] + frame_idx += 1 + + return key_frame_series + + # fallback to anim_args if the series is not defined in the Parseq data + def __getattribute__(inst, name): + try: + definedField = super(ParseqAnimKeys, inst).__getattribute__(name) + except AttributeError: + # No field with this name has been explicitly extracted from the JSON data. + # It must be a new parameter. Let's see if it's in the raw JSON. + + # parseq doesn't use _series, _schedule or _schedule_series suffixes in the + # JSON data - remove them. + strippableSuffixes = ['_series', '_schedule'] + parseqName = name + while any(parseqName.endswith(suffix) for suffix in strippableSuffixes): + for suffix in strippableSuffixes: + if parseqName.endswith(suffix): + parseqName = parseqName[:-len(suffix)] + + # returns None if not defined in Parseq JSON data + definedField = inst.parseq_to_anim_series(parseqName) + if (definedField is not None): + # add the field to the instance so we don't compute it again. + setattr(inst, name, definedField) + + if (definedField is not None): + return definedField + else: + logging.info(f"Data for {name} not defined in Parseq data (looked for: '{parseqName}'). Falling back to standard Deforum values.") + return getattr(inst.default_anim_keys, name) + diff --git a/extensions/deforum/scripts/deforum_helpers/prompt.py b/extensions/deforum/scripts/deforum_helpers/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..f81aa7c281376933c95c854ed2ecc8ae99ad92a7 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/prompt.py @@ -0,0 +1,113 @@ +import re + +def check_is_number(value): + float_pattern = r'^(?=.)([+-]?([0-9]*)(\.([0-9]+))?)$' + return re.match(float_pattern, value) + +def parse_weight(match, frame = 0)->float: + import numexpr + w_raw = match.group("weight") + if w_raw == None: + return 1 + if check_is_number(w_raw): + return float(w_raw) + else: + t = frame + if len(w_raw) < 3: + print('the value inside `-characters cannot represent a math function') + return 1 + return float(numexpr.evaluate(w_raw[1:-1])) + +def split_weighted_subprompts(text, frame = 0): + """ + splits the prompt based on deforum webui implementation, moved from generate.py + """ + math_parser = re.compile(""" + (?P( + `[\S\s]*?`# a math function wrapped in `-characters + )) + """, re.VERBOSE) + + parsed_prompt = re.sub(math_parser, lambda m: str(parse_weight(m, frame)), text) + + negative_prompts = [] + positive_prompts = [] + + prompt_split = parsed_prompt.split("--neg") + if len(prompt_split) > 1: + positive_prompts, negative_prompts = parsed_prompt.split("--neg") #TODO: add --neg to vanilla Deforum for compat + else: + positive_prompts = prompt_split[0] + negative_prompts = "" + + return positive_prompts, negative_prompts + +def interpolate_prompts(animation_prompts, max_frames): + import numpy as np + import pandas as pd + # Get prompts sorted by keyframe + sorted_prompts = sorted(animation_prompts.items(), key=lambda item: int(item[0])) + + # Setup container for interpolated prompts + prompt_series = pd.Series([np.nan for a in range(max_frames)]) + + # For every keyframe prompt except the last + for i in range(0,len(sorted_prompts)-1): + + # Get current and next keyframe + current_frame = int(sorted_prompts[i][0]) + next_frame = int(sorted_prompts[i+1][0]) + + # Ensure there's no weird ordering issues or duplication in the animation prompts + # (unlikely because we sort above, and the json parser will strip dupes) + if current_frame>=next_frame: + print(f"WARNING: Sequential prompt keyframes {i}:{current_frame} and {i+1}:{next_frame} are not monotonously increasing; skipping interpolation.") + continue + + # Get current and next keyframes' positive and negative prompts (if any) + current_prompt = sorted_prompts[i][1] + next_prompt = sorted_prompts[i+1][1] + current_positive, current_negative, *_ = current_prompt.split("--neg") + [None] + next_positive, next_negative, *_ = next_prompt.split("--neg") + [None] + + # Calculate how much to shift the weight from current to next prompt at each frame + weight_step = 1/(next_frame-current_frame) + + # Apply weighted prompt interpolation for each frame between current and next keyframe + # using the syntax: prompt1 :weight1 AND prompt1 :weight2 --neg nprompt1 :weight1 AND nprompt1 :weight2 + # (See: https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#composable-diffusion ) + for f in range(current_frame,next_frame): + next_weight = weight_step * (f-current_frame) + current_weight = 1 - next_weight + + # We will build the prompt incrementally depending on which prompts are present + prompt_series[f] = '' + + # Cater for the case where neither, either or both current & next have positive prompts: + if current_positive: + prompt_series[f] += f"{current_positive} :{current_weight}" + if current_positive and next_positive: + prompt_series[f] += f" AND " + if next_positive: + prompt_series[f] += f"{next_positive} :{next_weight}" + + # Cater for the case where neither, either or both current & next have negative prompts: + if current_negative or next_negative: + prompt_series[f] += " --neg " + if current_negative: + prompt_series[f] += f" {current_negative} :{current_weight}" + if current_negative and next_negative: + prompt_series[f] += f" AND " + if next_negative: + prompt_series[f] += f" {next_negative} :{next_weight}" + + # Set explicitly declared keyframe prompts (overwriting interpolated values at the keyframe idx). This ensures: + # - That final prompt is set, and + # - Gives us a chance to emit warnings if any keyframe prompts are already using composable diffusion + for i, prompt in animation_prompts.items(): + prompt_series[int(i)] = prompt + if ' AND ' in prompt: + print(f"WARNING: keyframe {i}'s prompt is using composable diffusion (aka the 'AND' keyword). This will cause unexpected behaviour with interpolation.") + + # Return the filled series, in case max_frames is greater than the last keyframe or any ranges were skipped. + return prompt_series.ffill().bfill() diff --git a/extensions/deforum/scripts/deforum_helpers/render.py b/extensions/deforum/scripts/deforum_helpers/render.py new file mode 100644 index 0000000000000000000000000000000000000000..7a3d141f3e00216b530d05c205c5f94f0ad814ab --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/render.py @@ -0,0 +1,507 @@ +import os +import json +import pandas as pd +import cv2 +import numpy as np +from PIL import Image, ImageOps +from .rich import console + +from .generate import generate +from .noise import add_noise +from .animation import sample_from_cv2, sample_to_cv2, anim_frame_warp +from .animation_key_frames import DeformAnimKeys, LooperAnimKeys +from .video_audio_utilities import get_frame_name, get_next_frame +from .depth import DepthModel +from .colors import maintain_colors +from .parseq_adapter import ParseqAnimKeys +from .seed import next_seed +from .blank_frame_reroll import blank_frame_reroll +from .image_sharpening import unsharp_mask +from .load_images import get_mask, load_img, get_mask_from_file +from .hybrid_video import hybrid_generation, hybrid_composite +from .hybrid_video import get_matrix_for_hybrid_motion, get_matrix_for_hybrid_motion_prev, get_flow_for_hybrid_motion, get_flow_for_hybrid_motion_prev, image_transform_ransac, image_transform_optical_flow +from .save_images import save_image +from .composable_masks import compose_mask_with_check +from .settings import get_keys_to_exclude +from .deforum_controlnet import unpack_controlnet_vids, is_controlnet_enabled +# Webui +from modules.shared import opts, cmd_opts, state, sd_model +from modules import lowvram, devices, sd_hijack + +def render_animation(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, animation_prompts, root): + # handle hybrid video generation + if anim_args.animation_mode in ['2D','3D']: + if anim_args.hybrid_composite or anim_args.hybrid_motion in ['Affine', 'Perspective', 'Optical Flow']: + args, anim_args, inputfiles = hybrid_generation(args, anim_args, root) + # path required by hybrid functions, even if hybrid_comp_save_extra_frames is False + hybrid_frame_path = os.path.join(args.outdir, 'hybridframes') + + # handle controlnet video input frames generation + if is_controlnet_enabled(controlnet_args): + unpack_controlnet_vids(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, animation_prompts, root) + + # use parseq if manifest is provided + use_parseq = parseq_args.parseq_manifest != None and parseq_args.parseq_manifest.strip() + # expand key frame strings to values + keys = DeformAnimKeys(anim_args) if not use_parseq else ParseqAnimKeys(parseq_args, anim_args) + loopSchedulesAndData = LooperAnimKeys(loop_args, anim_args) + # resume animation + start_frame = 0 + if anim_args.resume_from_timestring: + for tmp in os.listdir(args.outdir): + if ".txt" in tmp : + pass + else: + filename = tmp.split("_") + # don't use saved depth maps to count number of frames + if anim_args.resume_timestring in filename and "depth" not in filename: + start_frame += 1 + #start_frame = start_frame - 1 + + # create output folder for the batch + os.makedirs(args.outdir, exist_ok=True) + print(f"Saving animation frames to:\n{args.outdir}") + + # save settings for the batch + exclude_keys = get_keys_to_exclude('general') + settings_filename = os.path.join(args.outdir, f"{args.timestring}_settings.txt") + with open(settings_filename, "w+", encoding="utf-8") as f: + args.__dict__["prompts"] = animation_prompts + s = {} + for d in [dict(args.__dict__), dict(anim_args.__dict__), dict(parseq_args.__dict__), dict(loop_args.__dict__)]: + for key, value in d.items(): + if key not in exclude_keys: + s[key] = value + json.dump(s, f, ensure_ascii=False, indent=4) + + # resume from timestring + if anim_args.resume_from_timestring: + args.timestring = anim_args.resume_timestring + + # Always enable pseudo-3d with parseq. No need for an extra toggle: + # Whether it's used or not in practice is defined by the schedules + if use_parseq: + anim_args.flip_2d_perspective = True + + # expand prompts out to per-frame + if use_parseq: + prompt_series = keys.prompts + else: + prompt_series = pd.Series([np.nan for a in range(anim_args.max_frames)]) + for i, prompt in animation_prompts.items(): + prompt_series[int(i)] = prompt + prompt_series = prompt_series.ffill().bfill() + + # check for video inits + using_vid_init = anim_args.animation_mode == 'Video Input' + + # load depth model for 3D + predict_depths = (anim_args.animation_mode == '3D' and anim_args.use_depth_warping) or anim_args.save_depth_maps + predict_depths = predict_depths or (anim_args.hybrid_composite and anim_args.hybrid_comp_mask_type in ['Depth','Video Depth']) + if predict_depths: + depth_model = DepthModel('cpu' if cmd_opts.lowvram or cmd_opts.medvram else root.device) + depth_model.load_midas(root.models_path, root.half_precision) + if anim_args.midas_weight < 1.0: + depth_model.load_adabins(root.models_path) + # depth-based hybrid composite mask requires saved depth maps + if anim_args.hybrid_composite and anim_args.hybrid_comp_mask_type =='Depth': + anim_args.save_depth_maps = True + else: + depth_model = None + anim_args.save_depth_maps = False + + # state for interpolating between diffusion steps + turbo_steps = 1 if using_vid_init else int(anim_args.diffusion_cadence) + turbo_prev_image, turbo_prev_frame_idx = None, 0 + turbo_next_image, turbo_next_frame_idx = None, 0 + + # resume animation + prev_img = None + color_match_sample = None + if anim_args.resume_from_timestring: + last_frame = start_frame-1 + if turbo_steps > 1: + last_frame -= last_frame%turbo_steps + path = os.path.join(args.outdir,f"{args.timestring}_{last_frame:05}.png") + img = cv2.imread(path) + #img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Changed the colors on resume + prev_img = img + if anim_args.color_coherence != 'None': + color_match_sample = img + if turbo_steps > 1: + turbo_next_image, turbo_next_frame_idx = prev_img, last_frame + turbo_prev_image, turbo_prev_frame_idx = turbo_next_image, turbo_next_frame_idx + start_frame = last_frame+turbo_steps + + args.n_samples = 1 + frame_idx = start_frame + + # reset the mask vals as they are overwritten in the compose_mask algorithm + mask_vals = {} + noise_mask_vals = {} + + mask_vals['everywhere'] = Image.new('1', (args.W, args.H), 1) + noise_mask_vals['everywhere'] = Image.new('1', (args.W, args.H), 1) + + mask_image = None + + if args.use_init and args.init_image != None and args.init_image != '': + _, mask_image = load_img(args.init_image, + shape=(args.W, args.H), + use_alpha_as_mask=args.use_alpha_as_mask) + mask_vals['init_mask'] = mask_image + noise_mask_vals['init_mask'] = mask_image + + # Grab the first frame masks since they wont be provided until next frame + if mask_image is None and args.use_mask: + mask_vals['init_mask'] = get_mask(args) + noise_mask_vals['init_mask'] = get_mask(args) # TODO?: add a different default noise mask + + if anim_args.use_mask_video: + mask_vals['video_mask'] = get_mask_from_file(get_next_frame(args.outdir, anim_args.video_mask_path, frame_idx, True), args) + noise_mask_vals['video_mask'] = get_mask_from_file(get_next_frame(args.outdir, anim_args.video_mask_path, frame_idx, True), args) + else: + mask_vals['video_mask'] = None + noise_mask_vals['video_mask'] = None + + #Webui + state.job_count = anim_args.max_frames + + while frame_idx < anim_args.max_frames: + #Webui + state.job = f"frame {frame_idx + 1}/{anim_args.max_frames}" + state.job_no = frame_idx + 1 + if state.interrupted: + break + + print(f"\033[36mAnimation frame: \033[0m{frame_idx}/{anim_args.max_frames} ") + + noise = keys.noise_schedule_series[frame_idx] + strength = keys.strength_schedule_series[frame_idx] + scale = keys.cfg_scale_schedule_series[frame_idx] + contrast = keys.contrast_schedule_series[frame_idx] + kernel = int(keys.kernel_schedule_series[frame_idx]) + sigma = keys.sigma_schedule_series[frame_idx] + amount = keys.amount_schedule_series[frame_idx] + threshold = keys.threshold_schedule_series[frame_idx] + hybrid_comp_schedules = { + "alpha": keys.hybrid_comp_alpha_schedule_series[frame_idx], + "mask_blend_alpha": keys.hybrid_comp_mask_blend_alpha_schedule_series[frame_idx], + "mask_contrast": keys.hybrid_comp_mask_contrast_schedule_series[frame_idx], + "mask_auto_contrast_cutoff_low": int(keys.hybrid_comp_mask_auto_contrast_cutoff_low_schedule_series[frame_idx]), + "mask_auto_contrast_cutoff_high": int(keys.hybrid_comp_mask_auto_contrast_cutoff_high_schedule_series[frame_idx]), + } + scheduled_sampler_name = None + scheduled_clipskip = None + mask_seq = None + noise_mask_seq = None + if anim_args.enable_steps_scheduling and keys.steps_schedule_series[frame_idx] is not None: + args.steps = int(keys.steps_schedule_series[frame_idx]) + if anim_args.enable_sampler_scheduling and keys.sampler_schedule_series[frame_idx] is not None: + scheduled_sampler_name = keys.sampler_schedule_series[frame_idx].casefold() + if anim_args.enable_clipskip_scheduling and keys.clipskip_schedule_series[frame_idx] is not None: + scheduled_clipskip = int(keys.clipskip_schedule_series[frame_idx]) + if args.use_mask and keys.mask_schedule_series[frame_idx] is not None: + mask_seq = keys.mask_schedule_series[frame_idx] + if anim_args.use_noise_mask and keys.noise_mask_schedule_series[frame_idx] is not None: + noise_mask_seq = keys.noise_mask_schedule_series[frame_idx] + + if args.use_mask and not anim_args.use_noise_mask: + noise_mask_seq = mask_seq + + depth = None + + if anim_args.animation_mode == '3D' and (cmd_opts.lowvram or cmd_opts.medvram): + # Unload the main checkpoint and load the depth model + lowvram.send_everything_to_cpu() + sd_hijack.model_hijack.undo_hijack(sd_model) + devices.torch_gc() + depth_model.to(root.device) + + # emit in-between frames + if turbo_steps > 1: + tween_frame_start_idx = max(0, frame_idx-turbo_steps) + for tween_frame_idx in range(tween_frame_start_idx, frame_idx): + tween = float(tween_frame_idx - tween_frame_start_idx + 1) / float(frame_idx - tween_frame_start_idx) + print(f" Creating in-between frame: {tween_frame_idx}; tween:{tween:0.2f};") + + advance_prev = turbo_prev_image is not None and tween_frame_idx > turbo_prev_frame_idx + advance_next = tween_frame_idx > turbo_next_frame_idx + + if depth_model is not None: + assert(turbo_next_image is not None) + depth = depth_model.predict(turbo_next_image, anim_args, root.half_precision) + + if advance_prev: + turbo_prev_image, _ = anim_frame_warp(turbo_prev_image, args, anim_args, keys, tween_frame_idx, depth_model, depth=depth, device=root.device, half_precision=root.half_precision) + if advance_next: + turbo_next_image, _ = anim_frame_warp(turbo_next_image, args, anim_args, keys, tween_frame_idx, depth_model, depth=depth, device=root.device, half_precision=root.half_precision) + + # hybrid video motion - warps turbo_prev_image or turbo_next_image to match motion + if tween_frame_idx > 0: + if anim_args.hybrid_motion in ['Affine', 'Perspective']: + if anim_args.hybrid_motion_use_prev_img: + if advance_prev: + matrix = get_matrix_for_hybrid_motion_prev(tween_frame_idx, (args.W, args.H), inputfiles, turbo_prev_image, anim_args.hybrid_motion) + turbo_prev_image = image_transform_ransac(turbo_prev_image, matrix, anim_args.hybrid_motion, cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE) + if advance_next: + matrix = get_matrix_for_hybrid_motion_prev(tween_frame_idx, (args.W, args.H), inputfiles, turbo_next_image, anim_args.hybrid_motion) + turbo_next_image = image_transform_ransac(turbo_next_image, matrix, anim_args.hybrid_motion, cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE) + else: + matrix = get_matrix_for_hybrid_motion(tween_frame_idx-1, (args.W, args.H), inputfiles, anim_args.hybrid_motion) + if advance_prev: + turbo_prev_image = image_transform_ransac(turbo_prev_image, matrix, anim_args.hybrid_motion, cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE) + if advance_next: + turbo_next_image = image_transform_ransac(turbo_next_image, matrix, anim_args.hybrid_motion, cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE) + if anim_args.hybrid_motion in ['Optical Flow']: + if anim_args.hybrid_motion_use_prev_img: + if advance_prev: + flow = get_flow_for_hybrid_motion_prev(tween_frame_idx-1, (args.W, args.H), inputfiles, hybrid_frame_path, turbo_prev_image, anim_args.hybrid_flow_method, anim_args.hybrid_comp_save_extra_frames) + turbo_prev_image = image_transform_optical_flow(turbo_prev_image, flow, cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE) + if advance_next: + flow = get_flow_for_hybrid_motion_prev(tween_frame_idx-1, (args.W, args.H), inputfiles, hybrid_frame_path, turbo_next_image, anim_args.hybrid_flow_method, anim_args.hybrid_comp_save_extra_frames) + turbo_next_image = image_transform_optical_flow(turbo_next_image, flow, cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE) + else: + flow = get_flow_for_hybrid_motion(tween_frame_idx-1, (args.W, args.H), inputfiles, hybrid_frame_path, anim_args.hybrid_flow_method, anim_args.hybrid_comp_save_extra_frames) + if advance_prev: + turbo_prev_image = image_transform_optical_flow(turbo_prev_image, flow, cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE) + if advance_next: + turbo_next_image = image_transform_optical_flow(turbo_next_image, flow, cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE) + + turbo_prev_frame_idx = turbo_next_frame_idx = tween_frame_idx + + if turbo_prev_image is not None and tween < 1.0: + img = turbo_prev_image*(1.0-tween) + turbo_next_image*tween + else: + img = turbo_next_image + + # intercept and override to grayscale + if anim_args.color_force_grayscale: + img = cv2.cvtColor(img.astype(np.uint8), cv2.COLOR_BGR2GRAY) + img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) + + filename = f"{args.timestring}_{tween_frame_idx:05}.png" + cv2.imwrite(os.path.join(args.outdir, filename), img) + if anim_args.save_depth_maps: + depth_model.save(os.path.join(args.outdir, f"{args.timestring}_depth_{tween_frame_idx:05}.png"), depth) + if turbo_next_image is not None: + prev_img = turbo_next_image + + # apply transforms to previous frame + if prev_img is not None: + prev_img, depth = anim_frame_warp(prev_img, args, anim_args, keys, frame_idx, depth_model, depth=None, device=root.device, half_precision=root.half_precision) + + # hybrid video motion - warps prev_img to match motion, usually to prepare for compositing + if frame_idx > 0: + if anim_args.hybrid_motion in ['Affine', 'Perspective']: + if anim_args.hybrid_motion_use_prev_img: + matrix = get_matrix_for_hybrid_motion_prev(frame_idx, (args.W, args.H), inputfiles, prev_img, anim_args.hybrid_motion) + else: + matrix = get_matrix_for_hybrid_motion(frame_idx-1, (args.W, args.H), inputfiles, anim_args.hybrid_motion) + prev_img = image_transform_ransac(prev_img, matrix, anim_args.hybrid_motion, cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE) + if anim_args.hybrid_motion in ['Optical Flow']: + if anim_args.hybrid_motion_use_prev_img: + flow = get_flow_for_hybrid_motion_prev(frame_idx-1, (args.W, args.H), inputfiles, hybrid_frame_path, prev_img, anim_args.hybrid_flow_method, anim_args.hybrid_comp_save_extra_frames) + else: + flow = get_flow_for_hybrid_motion(frame_idx-1, (args.W, args.H), inputfiles, hybrid_frame_path, anim_args.hybrid_flow_method, anim_args.hybrid_comp_save_extra_frames) + prev_img = image_transform_optical_flow(prev_img, flow, cv2.BORDER_WRAP if anim_args.border == 'wrap' else cv2.BORDER_REPLICATE) + + # do hybrid video - composites video frame into prev_img (now warped if using motion) + if anim_args.hybrid_composite: + args, prev_img = hybrid_composite(args, anim_args, frame_idx, prev_img, depth_model, hybrid_comp_schedules, root) + + # apply color matching + if anim_args.color_coherence != 'None': + # video color matching + hybrid_available = anim_args.hybrid_composite or anim_args.hybrid_motion in ['Optical Flow', 'Affine', 'Perspective'] + if anim_args.color_coherence == 'Video Input' and hybrid_available: + video_color_coherence_frame = int(frame_idx) % int(anim_args.color_coherence_video_every_N_frames) == 0 + if video_color_coherence_frame: + prev_vid_img = Image.open(os.path.join(args.outdir, 'inputframes', get_frame_name(anim_args.video_init_path) + f"{frame_idx:05}.jpg")) + prev_vid_img = prev_vid_img.resize((args.W, args.H), Image.Resampling.LANCZOS) + color_match_sample = np.asarray(prev_vid_img) + color_match_sample = cv2.cvtColor(color_match_sample, cv2.COLOR_RGB2BGR) + if color_match_sample is None: + color_match_sample = prev_img.copy() + else: + prev_img = maintain_colors(prev_img, color_match_sample, anim_args.color_coherence) + + # intercept and override to grayscale + if anim_args.color_force_grayscale: + prev_img = cv2.cvtColor(prev_img, cv2.COLOR_BGR2GRAY) + prev_img = cv2.cvtColor(prev_img, cv2.COLOR_GRAY2BGR) + + # apply scaling + contrast_image = (prev_img * contrast).round().astype(np.uint8) + # anti-blur + if amount > 0: + contrast_image = unsharp_mask(contrast_image, (kernel, kernel), sigma, amount, threshold, mask_image if args.use_mask else None) + # apply frame noising + if args.use_mask or anim_args.use_noise_mask: + args.noise_mask = compose_mask_with_check(root, args, noise_mask_seq, noise_mask_vals, Image.fromarray(cv2.cvtColor(contrast_image, cv2.COLOR_BGR2RGB))) + noised_image = add_noise(contrast_image, noise, args.seed, anim_args.noise_type, + (anim_args.perlin_w, anim_args.perlin_h, anim_args.perlin_octaves, anim_args.perlin_persistence), + args.noise_mask, args.invert_mask) + + # use transformed previous frame as init for current + args.use_init = True + args.init_sample = Image.fromarray(cv2.cvtColor(noised_image, cv2.COLOR_BGR2RGB)) + args.strength = max(0.0, min(1.0, strength)) + + args.scale = scale + + # Pix2Pix Image CFG Scale - does *nothing* with non pix2pix checkpoints + args.pix2pix_img_cfg_scale = float(keys.pix2pix_img_cfg_scale_series[frame_idx]) + + # grab prompt for current frame + args.prompt = prompt_series[frame_idx] + + if args.seed_behavior == 'schedule' or use_parseq: + args.seed = int(keys.seed_schedule_series[frame_idx]) + + if anim_args.enable_checkpoint_scheduling: + args.checkpoint = keys.checkpoint_schedule_series[frame_idx] + else: + args.checkpoint = None + + #SubSeed scheduling + if anim_args.enable_subseed_scheduling: + args.subseed = int(keys.subseed_schedule_series[frame_idx]) + args.subseed_strength = float(keys.subseed_strength_schedule_series[frame_idx]) + + if use_parseq: + args.seed_enable_extras = True + args.subseed = int(keys.subseed_series[frame_idx]) + args.subseed_strength = keys.subseed_strength_series[frame_idx] + + prompt_to_print, *after_neg = args.prompt.strip().split("--neg") + prompt_to_print = prompt_to_print.strip() + after_neg = "".join(after_neg).strip() + + print(f"\033[32mSeed: \033[0m{args.seed}") + print(f"\033[35mPrompt: \033[0m{prompt_to_print}") + if after_neg and after_neg.strip(): + print(f"\033[91mNeg Prompt: \033[0m{after_neg}") + if not using_vid_init: + # print motion table to cli if anim mode = 2D or 3D + if anim_args.animation_mode in ['2D','3D']: + print_render_table(anim_args, keys, frame_idx) + + # grab init image for current frame + elif using_vid_init: + init_frame = get_next_frame(args.outdir, anim_args.video_init_path, frame_idx, False) + print(f"Using video init frame {init_frame}") + args.init_image = init_frame + if anim_args.use_mask_video: + mask_vals['video_mask'] = get_mask_from_file(get_next_frame(args.outdir, anim_args.video_mask_path, frame_idx, True), args) + + if args.use_mask: + args.mask_image = compose_mask_with_check(root, args, mask_seq, mask_vals, args.init_sample) if args.init_sample is not None else None # we need it only after the first frame anyway + + # setting up some arguments for the looper + loop_args.imageStrength = loopSchedulesAndData.image_strength_schedule_series[frame_idx] + loop_args.blendFactorMax = loopSchedulesAndData.blendFactorMax_series[frame_idx] + loop_args.blendFactorSlope = loopSchedulesAndData.blendFactorSlope_series[frame_idx] + loop_args.tweeningFrameSchedule = loopSchedulesAndData.tweening_frames_schedule_series[frame_idx] + loop_args.colorCorrectionFactor = loopSchedulesAndData.color_correction_factor_series[frame_idx] + loop_args.use_looper = loopSchedulesAndData.use_looper + loop_args.imagesToKeyframe = loopSchedulesAndData.imagesToKeyframe + + if scheduled_clipskip is not None: + opts.data["CLIP_stop_at_last_layers"] = scheduled_clipskip + + if anim_args.animation_mode == '3D' and (cmd_opts.lowvram or cmd_opts.medvram): + depth_model.to('cpu') + devices.torch_gc() + lowvram.setup_for_low_vram(sd_model, cmd_opts.medvram) + sd_hijack.model_hijack.hijack(sd_model) + + # sample the diffusion model + image = generate(args, anim_args, loop_args, controlnet_args, root, frame_idx, sampler_name=scheduled_sampler_name) + patience = 10 + + # intercept and override to grayscale + if anim_args.color_force_grayscale: + image = ImageOps.grayscale(image) + image = ImageOps.colorize(image, black ="black", white ="white") + + # reroll blank frame + if not image.getbbox(): + print("Blank frame detected! If you don't have the NSFW filter enabled, this may be due to a glitch!") + if args.reroll_blank_frames == 'reroll': + while not image.getbbox(): + print("Rerolling with +1 seed...") + args.seed += 1 + image = generate(args, anim_args, loop_args, controlnet_args, root, frame_idx, sampler_name=scheduled_sampler_name) + patience -= 1 + if patience == 0: + print("Rerolling with +1 seed failed for 10 iterations! Try setting webui's precision to 'full' and if it fails, please report this to the devs! Interrupting...") + state.interrupted = True + state.current_image = image + return + elif args.reroll_blank_frames == 'interrupt': + print("Interrupting to save your eyes...") + state.interrupted = True + state.current_image = image + image = blank_frame_reroll(image, args, root, frame_idx) + if image == None: + return + + opencv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) + if not using_vid_init: + prev_img = opencv_image + + if turbo_steps > 1: + turbo_prev_image, turbo_prev_frame_idx = turbo_next_image, turbo_next_frame_idx + turbo_next_image, turbo_next_frame_idx = opencv_image, frame_idx + frame_idx += turbo_steps + else: + filename = f"{args.timestring}_{frame_idx:05}.png" + save_image(image, 'PIL', filename, args, video_args, root) + + if anim_args.save_depth_maps: + if cmd_opts.lowvram or cmd_opts.medvram: + lowvram.send_everything_to_cpu() + sd_hijack.model_hijack.undo_hijack(sd_model) + devices.torch_gc() + depth_model.to(root.device) + depth = depth_model.predict(opencv_image, anim_args, root.half_precision) + depth_model.save(os.path.join(args.outdir, f"{args.timestring}_depth_{frame_idx:05}.png"), depth) + if cmd_opts.lowvram or cmd_opts.medvram: + depth_model.to('cpu') + devices.torch_gc() + lowvram.setup_for_low_vram(sd_model, cmd_opts.medvram) + sd_hijack.model_hijack.hijack(sd_model) + frame_idx += 1 + + state.current_image = image + + args.seed = next_seed(args) + +def print_render_table(anim_args, keys, frame_idx): + from rich.table import Table + from rich import box + table = Table(padding=0, box=box.ROUNDED) + field_names = [] + if anim_args.animation_mode == '2D': + short_zoom = round(keys.zoom_series[frame_idx], 6) + field_names += ["Angle", "Zoom"] + field_names += ["Tr X", "Tr Y"] + if anim_args.animation_mode == '3D': + field_names += ["Tr Z", "Ro X", "Ro Y", "Ro Z"] + if anim_args.enable_perspective_flip: + field_names += ["Pf T", "Pf P", "Pf G", "Pf F"] + for field_name in field_names: + table.add_column(field_name, justify="center") + + rows = [] + if anim_args.animation_mode == '2D': + rows += [str(keys.angle_series[frame_idx]),str(short_zoom)] + rows += [str(keys.translation_x_series[frame_idx]),str(keys.translation_y_series[frame_idx])] + if anim_args.animation_mode == '3D': + rows += [str(keys.translation_z_series[frame_idx]),str(keys.rotation_3d_x_series[frame_idx]),str(keys.rotation_3d_y_series[frame_idx]),str(keys.rotation_3d_z_series[frame_idx])] + if anim_args.enable_perspective_flip: + rows +=[str(keys.perspective_flip_theta_series[frame_idx]), str(keys.perspective_flip_phi_series[frame_idx]), str(keys.perspective_flip_gamma_series[frame_idx]), str(keys.perspective_flip_fv_series[frame_idx])] + table.add_row(*rows) + + console.print(table) \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/render_modes.py b/extensions/deforum/scripts/deforum_helpers/render_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..3b53601ffdef213d1c54a182631347193cf21949 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/render_modes.py @@ -0,0 +1,154 @@ +import os +import pathlib +import json +from .render import render_animation +from .seed import next_seed +from .video_audio_utilities import vid2frames +from .prompt import interpolate_prompts +from .generate import generate +from .animation_key_frames import DeformAnimKeys +from .parseq_adapter import ParseqAnimKeys +from .save_images import save_image +from .settings import get_keys_to_exclude + +# Webui +from modules.shared import opts, cmd_opts, state + +def render_input_video(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, animation_prompts, root): + # create a folder for the video input frames to live in + video_in_frame_path = os.path.join(args.outdir, 'inputframes') + os.makedirs(video_in_frame_path, exist_ok=True) + + # save the video frames from input video + print(f"Exporting Video Frames (1 every {anim_args.extract_nth_frame}) frames to {video_in_frame_path}...") + vid2frames(video_path = anim_args.video_init_path, video_in_frame_path=video_in_frame_path, n=anim_args.extract_nth_frame, overwrite=anim_args.overwrite_extracted_frames, extract_from_frame=anim_args.extract_from_frame, extract_to_frame=anim_args.extract_to_frame) + + # determine max frames from length of input frames + anim_args.max_frames = len([f for f in pathlib.Path(video_in_frame_path).glob('*.jpg')]) + args.use_init = True + print(f"Loading {anim_args.max_frames} input frames from {video_in_frame_path} and saving video frames to {args.outdir}") + + if anim_args.use_mask_video: + # create a folder for the mask video input frames to live in + mask_in_frame_path = os.path.join(args.outdir, 'maskframes') + os.makedirs(mask_in_frame_path, exist_ok=True) + + # save the video frames from mask video + print(f"Exporting Video Frames (1 every {anim_args.extract_nth_frame}) frames to {mask_in_frame_path}...") + vid2frames(video_path=anim_args.video_mask_path,video_in_frame_path=mask_in_frame_path, n=anim_args.extract_nth_frame, overwrite=anim_args.overwrite_extracted_frames, extract_from_frame=anim_args.extract_from_frame, extract_to_frame=anim_args.extract_to_frame) + max_mask_frames = len([f for f in pathlib.Path(mask_in_frame_path).glob('*.jpg')]) + + # limit max frames if there are less frames in the video mask compared to input video + if max_mask_frames < anim_args.max_frames : + anim_args.max_mask_frames + print ("Video mask contains less frames than init video, max frames limited to number of mask frames.") + args.use_mask = True + args.overlay_mask = True + + + render_animation(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, animation_prompts, root) + +# Modified a copy of the above to allow using masking video with out a init video. +def render_animation_with_video_mask(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, animation_prompts, root): + # create a folder for the video input frames to live in + mask_in_frame_path = os.path.join(args.outdir, 'maskframes') + os.makedirs(mask_in_frame_path, exist_ok=True) + + # save the video frames from mask video + print(f"Exporting Video Frames (1 every {anim_args.extract_nth_frame}) frames to {mask_in_frame_path}...") + vid2frames(video_path=anim_args.video_mask_path, video_in_frame_path=mask_in_frame_path, n=anim_args.extract_nth_frame, overwrite=anim_args.overwrite_extracted_frames, extract_from_frame=anim_args.extract_from_frame, extract_to_frame=anim_args.extract_to_frame) + args.use_mask = True + #args.overlay_mask = True + + # determine max frames from length of input frames + anim_args.max_frames = len([f for f in pathlib.Path(mask_in_frame_path).glob('*.jpg')]) + #args.use_init = True + print(f"Loading {anim_args.max_frames} input frames from {mask_in_frame_path} and saving video frames to {args.outdir}") + + render_animation(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, animation_prompts, root) + + +def render_interpolation(args, anim_args, video_args, parseq_args, loop_args, controlnet_args, animation_prompts, root): + + # use parseq if manifest is provided + use_parseq = parseq_args.parseq_manifest != None and parseq_args.parseq_manifest.strip() + + # expand key frame strings to values + keys = DeformAnimKeys(anim_args) if not use_parseq else ParseqAnimKeys(parseq_args, anim_args) + + # create output folder for the batch + os.makedirs(args.outdir, exist_ok=True) + print(f"Saving interpolation animation frames to {args.outdir}") + + # save settings for the batch + exclude_keys = get_keys_to_exclude('general') + settings_filename = os.path.join(args.outdir, f"{args.timestring}_settings.txt") + with open(settings_filename, "w+", encoding="utf-8") as f: + s = {} + for d in [dict(args.__dict__), dict(anim_args.__dict__), dict(parseq_args.__dict__)]: + for key, value in d.items(): + if key not in exclude_keys: + s[key] = value + json.dump(s, f, ensure_ascii=False, indent=4) + + # Compute interpolated prompts + if use_parseq: + print("Parseq prompts are assumed to already be interpolated - not doing any additional prompt interpolation") + prompt_series = keys.prompts + else: + print("Generating interpolated prompts for all frames") + prompt_series = interpolate_prompts(animation_prompts, anim_args.max_frames) + + state.job_count = anim_args.max_frames + frame_idx = 0 + # INTERPOLATION MODE + while frame_idx < anim_args.max_frames: + # print data to cli + prompt_to_print = prompt_series[frame_idx].strip() + if prompt_to_print.endswith("--neg"): + prompt_to_print = prompt_to_print[:-5] + print(f"\033[36mInterpolation frame: \033[0m{frame_idx}/{anim_args.max_frames} ") + print(f"\033[32mSeed: \033[0m{args.seed}") + print(f"\033[35mPrompt: \033[0m{prompt_to_print}") + + state.job = f"frame {frame_idx + 1}/{anim_args.max_frames}" + state.job_no = frame_idx + 1 + + if state.interrupted: + break + + # grab inputs for current frame generation + args.n_samples = 1 + args.prompt = prompt_series[frame_idx] + args.scale = keys.cfg_scale_schedule_series[frame_idx] + args.pix2pix_img_cfg_scale = keys.pix2pix_img_cfg_scale_series[frame_idx] + + if anim_args.enable_checkpoint_scheduling: + args.checkpoint = keys.checkpoint_schedule_series[frame_idx] + print(f"Checkpoint changed to: {args.checkpoint}") + else: + args.checkpoint = None + + if anim_args.enable_subseed_scheduling: + args.subseed = keys.subseed_schedule_series[frame_idx] + args.subseed_strength = keys.subseed_strength_schedule_series[frame_idx] + + if use_parseq: + anim_args.enable_subseed_scheduling = True + args.subseed = int(keys.subseed_series[frame_idx]) + args.subseed_strength = keys.subseed_strength_series[frame_idx] + + if args.seed_behavior == 'schedule' or use_parseq: + args.seed = int(keys.seed_schedule_series[frame_idx]) + + image = generate(args, anim_args, loop_args, controlnet_args, root, frame_idx) + filename = f"{args.timestring}_{frame_idx:05}.png" + + save_image(image, 'PIL', filename, args, video_args, root) + + state.current_image = image + + if args.seed_behavior != 'schedule': + args.seed = next_seed(args) + + frame_idx += 1 \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/rich.py b/extensions/deforum/scripts/deforum_helpers/rich.py new file mode 100644 index 0000000000000000000000000000000000000000..745d8c8bc41116fe1ead73e18569c075a03450e1 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/rich.py @@ -0,0 +1,2 @@ +from rich.console import Console +console = Console() \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/save_images.py b/extensions/deforum/scripts/deforum_helpers/save_images.py new file mode 100644 index 0000000000000000000000000000000000000000..8b6c60c5bfec5947b0a9bf7f9fb87512e97e5ad6 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/save_images.py @@ -0,0 +1,80 @@ +from typing import List, Tuple +from einops import rearrange +import numpy as np, os, torch +from PIL import Image +from torchvision.utils import make_grid +import time + + +def get_output_folder(output_path, batch_folder): + out_path = os.path.join(output_path,time.strftime('%Y-%m')) + if batch_folder != "": + out_path = os.path.join(out_path, batch_folder) + os.makedirs(out_path, exist_ok=True) + return out_path + + +def save_samples( + args, x_samples: torch.Tensor, seed: int, n_rows: int +) -> Tuple[Image.Image, List[Image.Image]]: + """Function to save samples to disk. + Args: + args: Stable deforum diffusion arguments. + x_samples: Samples to save. + seed: Seed for the experiment. + n_rows: Number of rows in the grid. + Returns: + A tuple of the grid image and a list of the generated images. + ( grid_image, generated_images ) + """ + + # save samples + images = [] + grid_image = None + if args.display_samples or args.save_samples: + for index, x_sample in enumerate(x_samples): + x_sample = 255.0 * rearrange(x_sample.cpu().numpy(), "c h w -> h w c") + images.append(Image.fromarray(x_sample.astype(np.uint8))) + if args.save_samples: + images[-1].save( + os.path.join( + args.outdir, f"{args.timestring}_{index:02}_{seed}.png" + ) + ) + + # save grid + if args.display_grid or args.save_grid: + grid = torch.stack([x_samples], 0) + grid = rearrange(grid, "n b c h w -> (n b) c h w") + grid = make_grid(grid, nrow=n_rows, padding=0) + + # to image + grid = 255.0 * rearrange(grid, "c h w -> h w c").cpu().numpy() + grid_image = Image.fromarray(grid.astype(np.uint8)) + if args.save_grid: + grid_image.save( + os.path.join(args.outdir, f"{args.timestring}_{seed}_grid.png") + ) + + # return grid_image and individual sample images + return grid_image, images + +def save_image(image, image_type, filename, args, video_args, root): + if video_args.store_frames_in_ram: + root.frames_cache.append({'path':os.path.join(args.outdir, filename), 'image':image, 'image_type':image_type}) + else: + image.save(os.path.join(args.outdir, filename)) + +import cv2, gc + +def reset_frames_cache(root): + root.frames_cache = [] + gc.collect() + +def dump_frames_cache(root): + for image_cache in root.frames_cache: + if image_cache['image_type'] == 'cv2': + cv2.imwrite(image_cache['path'], image_cache['image']) + elif image_cache['image_type'] == 'PIL': + image_cache['image'].save(image_cache['path']) + # do not reset the cache since we're going to add frame erasing later function #TODO diff --git a/extensions/deforum/scripts/deforum_helpers/seed.py b/extensions/deforum/scripts/deforum_helpers/seed.py new file mode 100644 index 0000000000000000000000000000000000000000..5c379d709bebdc16d654e872c4870e769a31e5ac --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/seed.py @@ -0,0 +1,26 @@ +import random + +def next_seed(args): + if args.seed_behavior == 'iter': + if args.seed_internal % args.seed_iter_N == 0: + args.seed += 1 + args.seed_internal += 1 + elif args.seed_behavior == 'ladder': + if args.seed_internal == 0: + args.seed += 2 + args.seed_internal = 1 + else: + args.seed -= 1 + args.seed_internal = 0 + elif args.seed_behavior == 'alternate': + if args.seed_internal == 0: + args.seed += 1 + args.seed_internal = 1 + else: + args.seed -= 1 + args.seed_internal = 0 + elif args.seed_behavior == 'fixed': + pass # always keep seed the same + else: + args.seed = random.randint(0, 2**32 - 1) + return args.seed \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/settings.py b/extensions/deforum/scripts/deforum_helpers/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..8aed504edb3246e60d4508bab6c92c3512f3ee80 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/settings.py @@ -0,0 +1,272 @@ +from math import ceil +import os +import json +import deforum_helpers.args as deforum_args +from .args import mask_fill_choices, DeforumArgs, DeforumAnimArgs +from .deprecation_utils import handle_deprecated_settings +import logging + +def get_keys_to_exclude(setting_type): + if setting_type == 'general': + return ["n_batch", "restore_faces", "seed_enable_extras", "save_samples", "display_samples", "show_sample_per_step", "filename_format", "from_img2img_instead_of_link", "scale", "subseed", "subseed_strength", "C", "f", "init_latent", "init_sample", "init_c", "noise_mask", "seed_internal"] + else: #video + return ["mp4_path", "image_path", "output_format","render_steps","path_name_modifier"] + +def load_args(args_dict,anim_args_dict, parseq_args_dict, loop_args_dict, controlnet_args_dict, custom_settings_file, root): + print(f"reading custom settings from {custom_settings_file}") + if not os.path.isfile(custom_settings_file): + print('The custom settings file does not exist. The in-notebook settings will be used instead') + else: + with open(custom_settings_file, "r") as f: + jdata = json.loads(f.read()) + handle_deprecated_settings(jdata) + root.animation_prompts = jdata["prompts"] + if "animation_prompts_positive" in jdata: + root.animation_prompts_positive = jdata["animation_prompts_positive"] + if "animation_prompts_negative" in jdata: + root.animation_prompts_negative = jdata["animation_prompts_negative"] + for i, k in enumerate(args_dict): + if k in jdata: + args_dict[k] = jdata[k] + else: + print(f"key {k} doesn't exist in the custom settings data! using the default value of {args_dict[k]}") + for i, k in enumerate(anim_args_dict): + if k in jdata: + anim_args_dict[k] = jdata[k] + else: + print(f"key {k} doesn't exist in the custom settings data! using the default value of {anim_args_dict[k]}") + for i, k in enumerate(parseq_args_dict): + if k in jdata: + parseq_args_dict[k] = jdata[k] + else: + print(f"key {k} doesn't exist in the custom settings data! using the default value of {parseq_args_dict[k]}") + for i, k in enumerate(loop_args_dict): + if k in jdata: + loop_args_dict[k] = jdata[k] + else: + print(f"key {k} doesn't exist in the custom settings data! using the default value of {loop_args_dict[k]}") + print(args_dict) + print(anim_args_dict) + print(parseq_args_dict) + print(loop_args_dict) + +# In gradio gui settings save/ load funs: +def save_settings(*args, **kwargs): + settings_path = args[0].strip() + data = {deforum_args.settings_component_names[i]: args[i+1] for i in range(0, len(deforum_args.settings_component_names))} + from deforum_helpers.args import pack_args, pack_anim_args, pack_parseq_args, pack_loop_args, pack_controlnet_args + args_dict = pack_args(data) + anim_args_dict = pack_anim_args(data) + parseq_dict = pack_parseq_args(data) + args_dict["prompts"] = json.loads(data['animation_prompts']) + args_dict["animation_prompts_positive"] = data['animation_prompts_positive'] + args_dict["animation_prompts_negative"] = data['animation_prompts_negative'] + loop_dict = pack_loop_args(data) + controlnet_dict = pack_controlnet_args(data) + + combined = {**args_dict, **anim_args_dict, **parseq_dict, **loop_dict, **controlnet_dict} + exclude_keys = get_keys_to_exclude('general') + ['controlnet_input_video_chosen_file', 'controlnet_input_video_mask_chosen_file'] + filtered_combined = {k: v for k, v in combined.items() if k not in exclude_keys} + + print(f"saving custom settings to {settings_path}") + with open(settings_path, "w") as f: + f.write(json.dumps(filtered_combined, ensure_ascii=False, indent=4)) + + return [""] + +def save_video_settings(*args, **kwargs): + video_settings_path = args[0].strip() + data = {deforum_args.video_args_names[i]: args[i+1] for i in range(0, len(deforum_args.video_args_names))} + from deforum_helpers.args import pack_video_args + video_args_dict = pack_video_args(data) + exclude_keys = get_keys_to_exclude('video') + filtered_data = video_args_dict if exclude_keys is None else {k: v for k, v in video_args_dict.items() if k not in exclude_keys} + print(f"saving video settings to {video_settings_path}") + with open(video_settings_path, "w") as f: + f.write(json.dumps(filtered_data, ensure_ascii=False, indent=4)) + return [""] + +def load_settings(*args, **kwargs): + settings_path = args[0].strip() + data = {deforum_args.settings_component_names[i]: args[i+1] for i in range(0, len(deforum_args.settings_component_names))} + print(f"reading custom settings from {settings_path}") + jdata = {} + if not os.path.isfile(settings_path): + print('The custom settings file does not exist. The values will be unchanged.') + return [data[name] for name in deforum_args.settings_component_names] + [""] + else: + with open(settings_path, "r") as f: + jdata = json.loads(f.read()) + handle_deprecated_settings(jdata) + ret = [] + if 'animation_prompts' in jdata: + jdata['prompts'] = jdata['animation_prompts']#compatibility with old versions + if 'animation_prompts_positive' in jdata: + data["animation_prompts_positive"] = jdata['animation_prompts_positive'] + if 'animation_prompts_negative' in jdata: + data["animation_prompts_negative"] = jdata['animation_prompts_negative'] + for key in data: + if key == 'sampler': + sampler_val = jdata[key] + if type(sampler_val) == int: + from modules.sd_samplers import samplers_for_img2img + ret.append(samplers_for_img2img[sampler_val].name) + else: + ret.append(sampler_val) + + elif key == 'fill': + if key in jdata: + fill_val = jdata[key] + if type(fill_val) == int: + ret.append(mask_fill_choices[fill_val]) + else: + ret.append(fill_val) + else: + fill_default = DeforumArgs()['fill'] + logging.debug(f"Fill not found in load file, using default value: {fill_default}") + ret.append(mask_fill_choices[fill_default]) + + elif key == 'reroll_blank_frames': + if key in jdata: + reroll_blank_frames_val = jdata[key] + ret.append(reroll_blank_frames_val) + else: + reroll_blank_frames_default = DeforumArgs()['reroll_blank_frames'] + logging.debug(f"Reroll blank frames not found in load file, using default value: {reroll_blank_frames_default}") + ret.append(reroll_blank_frames_default) + + elif key == 'noise_type': + if key in jdata: + noise_type_val = jdata[key] + ret.append(noise_type_val) + else: + noise_type_default = DeforumAnimArgs()['noise_type'] + logging.debug(f"Noise type not found in load file, using default value: {noise_type_default}") + ret.append(noise_type_default) + + elif key in jdata: + ret.append(jdata[key]) + else: + if key == 'animation_prompts': + ret.append(json.dumps(jdata['prompts'], ensure_ascii=False, indent=4)) + elif key == 'animation_prompts_positive' and 'animation_prompts_positive' in jdata: + ret.append(jdata['animation_prompts_positive']) + elif key == 'animation_prompts_negative' and 'animation_prompts_negative' in jdata: + ret.append(jdata['animation_prompts_negative']) + else: + ret.append(data[key]) + + #stuff + ret.append("") + + return ret + +def load_video_settings(*args, **kwargs): + video_settings_path = args[0].strip() + data = {deforum_args.video_args_names[i]: args[i+1] for i in range(0, len(deforum_args.video_args_names))} + print(f"reading custom video settings from {video_settings_path}") + jdata = {} + if not os.path.isfile(video_settings_path): + print('The custom video settings file does not exist. The values will be unchanged.') + return [data[name] for name in deforum_args.video_args_names] + [""] + else: + with open(video_settings_path, "r") as f: + jdata = json.loads(f.read()) + handle_deprecated_settings(jdata) + ret = [] + + for key in data: + if key == 'add_soundtrack': + add_soundtrack_val = jdata[key] + if type(add_soundtrack_val) == bool: + ret.append('File' if add_soundtrack_val else 'None') + else: + ret.append(add_soundtrack_val) + elif key in jdata: + ret.append(jdata[key]) + else: + ret.append(data[key]) + + #stuff + ret.append("") + + return ret + +import tqdm +from modules.shared import state, progress_print_out, opts, cmd_opts +class DeforumTQDM: + def __init__(self, args, anim_args, parseq_args): + self._tqdm = None + self._args = args + self._anim_args = anim_args + self._parseq_args = parseq_args + + def reset(self): + from .animation_key_frames import DeformAnimKeys + from .parseq_adapter import ParseqAnimKeys + deforum_total = 0 + # FIXME: get only amount of steps + use_parseq = self._parseq_args.parseq_manifest != None and self._parseq_args.parseq_manifest.strip() + keys = DeformAnimKeys(self._anim_args) if not use_parseq else ParseqAnimKeys(self._parseq_args, self._anim_args) + + start_frame = 0 + if self._anim_args.resume_from_timestring: + for tmp in os.listdir(self._args.outdir): + filename = tmp.split("_") + # don't use saved depth maps to count number of frames + if self._anim_args.resume_timestring in filename and "depth" not in filename: + start_frame += 1 + start_frame = start_frame - 1 + using_vid_init = self._anim_args.animation_mode == 'Video Input' + turbo_steps = 1 if using_vid_init else int(self._anim_args.diffusion_cadence) + if self._anim_args.resume_from_timestring: + last_frame = start_frame-1 + if turbo_steps > 1: + last_frame -= last_frame%turbo_steps + if turbo_steps > 1: + turbo_next_frame_idx = last_frame + turbo_prev_frame_idx = turbo_next_frame_idx + start_frame = last_frame+turbo_steps + frame_idx = start_frame + had_first = False + while frame_idx < self._anim_args.max_frames: + strength = keys.strength_schedule_series[frame_idx] + if not had_first and self._args.use_init and self._args.init_image != None and self._args.init_image != '': + deforum_total += int(ceil(self._args.steps * (1-strength))) + had_first = True + elif not had_first: + deforum_total += self._args.steps + had_first = True + else: + deforum_total += int(ceil(self._args.steps * (1-strength))) + + if turbo_steps > 1: + frame_idx += turbo_steps + else: + frame_idx += 1 + + self._tqdm = tqdm.tqdm( + desc="Deforum progress", + total=deforum_total, + position=1, + file=progress_print_out + ) + + def update(self): + if not opts.multiple_tqdm or cmd_opts.disable_console_progressbars: + return + if self._tqdm is None: + self.reset() + self._tqdm.update() + + def updateTotal(self, new_total): + if not opts.multiple_tqdm or cmd_opts.disable_console_progressbars: + return + if self._tqdm is None: + self.reset() + self._tqdm.total=new_total + + def clear(self): + if self._tqdm is not None: + self._tqdm.close() + self._tqdm = None diff --git a/extensions/deforum/scripts/deforum_helpers/src/adabins/__init__.py b/extensions/deforum/scripts/deforum_helpers/src/adabins/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b2a0eea190658f294d0a49363ea28543087bdf6 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/adabins/__init__.py @@ -0,0 +1 @@ +from .unet_adaptive_bins import UnetAdaptiveBins diff --git a/extensions/deforum/scripts/deforum_helpers/src/adabins/layers.py b/extensions/deforum/scripts/deforum_helpers/src/adabins/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..499cd8cc1ec5973da5718d184d36b187869f9c28 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/adabins/layers.py @@ -0,0 +1,36 @@ +import torch +import torch.nn as nn + + +class PatchTransformerEncoder(nn.Module): + def __init__(self, in_channels, patch_size=10, embedding_dim=128, num_heads=4): + super(PatchTransformerEncoder, self).__init__() + encoder_layers = nn.TransformerEncoderLayer(embedding_dim, num_heads, dim_feedforward=1024) + self.transformer_encoder = nn.TransformerEncoder(encoder_layers, num_layers=4) # takes shape S,N,E + + self.embedding_convPxP = nn.Conv2d(in_channels, embedding_dim, + kernel_size=patch_size, stride=patch_size, padding=0) + + self.positional_encodings = nn.Parameter(torch.rand(500, embedding_dim), requires_grad=True) + + def forward(self, x): + embeddings = self.embedding_convPxP(x).flatten(2) # .shape = n,c,s = n, embedding_dim, s + # embeddings = nn.functional.pad(embeddings, (1,0)) # extra special token at start ? + embeddings = embeddings + self.positional_encodings[:embeddings.shape[2], :].T.unsqueeze(0) + + # change to S,N,E format required by transformer + embeddings = embeddings.permute(2, 0, 1) + x = self.transformer_encoder(embeddings) # .shape = S, N, E + return x + + +class PixelWiseDotProduct(nn.Module): + def __init__(self): + super(PixelWiseDotProduct, self).__init__() + + def forward(self, x, K): + n, c, h, w = x.size() + _, cout, ck = K.size() + assert c == ck, "Number of channels in x and Embedding dimension (at dim 2) of K matrix must match" + y = torch.matmul(x.view(n, c, h * w).permute(0, 2, 1), K.permute(0, 2, 1)) # .shape = n, hw, cout + return y.permute(0, 2, 1).view(n, cout, h, w) diff --git a/extensions/deforum/scripts/deforum_helpers/src/adabins/miniViT.py b/extensions/deforum/scripts/deforum_helpers/src/adabins/miniViT.py new file mode 100644 index 0000000000000000000000000000000000000000..8a619734aaa82e73fbe37800a6a1dd12e83020a2 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/adabins/miniViT.py @@ -0,0 +1,45 @@ +import torch +import torch.nn as nn + +from .layers import PatchTransformerEncoder, PixelWiseDotProduct + + +class mViT(nn.Module): + def __init__(self, in_channels, n_query_channels=128, patch_size=16, dim_out=256, + embedding_dim=128, num_heads=4, norm='linear'): + super(mViT, self).__init__() + self.norm = norm + self.n_query_channels = n_query_channels + self.patch_transformer = PatchTransformerEncoder(in_channels, patch_size, embedding_dim, num_heads) + self.dot_product_layer = PixelWiseDotProduct() + + self.conv3x3 = nn.Conv2d(in_channels, embedding_dim, kernel_size=3, stride=1, padding=1) + self.regressor = nn.Sequential(nn.Linear(embedding_dim, 256), + nn.LeakyReLU(), + nn.Linear(256, 256), + nn.LeakyReLU(), + nn.Linear(256, dim_out)) + + def forward(self, x): + # n, c, h, w = x.size() + tgt = self.patch_transformer(x.clone()) # .shape = S, N, E + + x = self.conv3x3(x) + + regression_head, queries = tgt[0, ...], tgt[1:self.n_query_channels + 1, ...] + + # Change from S, N, E to N, S, E + queries = queries.permute(1, 0, 2) + range_attention_maps = self.dot_product_layer(x, queries) # .shape = n, n_query_channels, h, w + + y = self.regressor(regression_head) # .shape = N, dim_out + if self.norm == 'linear': + y = torch.relu(y) + eps = 0.1 + y = y + eps + elif self.norm == 'softmax': + return torch.softmax(y, dim=1), range_attention_maps + else: + y = torch.sigmoid(y) + y = y / y.sum(dim=1, keepdim=True) + return y, range_attention_maps diff --git a/extensions/deforum/scripts/deforum_helpers/src/adabins/unet_adaptive_bins.py b/extensions/deforum/scripts/deforum_helpers/src/adabins/unet_adaptive_bins.py new file mode 100644 index 0000000000000000000000000000000000000000..733927795146fe13563d07d20fbb461da596a181 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/adabins/unet_adaptive_bins.py @@ -0,0 +1,154 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import os +from pathlib import Path + +from .miniViT import mViT + + +class UpSampleBN(nn.Module): + def __init__(self, skip_input, output_features): + super(UpSampleBN, self).__init__() + + self._net = nn.Sequential(nn.Conv2d(skip_input, output_features, kernel_size=3, stride=1, padding=1), + nn.BatchNorm2d(output_features), + nn.LeakyReLU(), + nn.Conv2d(output_features, output_features, kernel_size=3, stride=1, padding=1), + nn.BatchNorm2d(output_features), + nn.LeakyReLU()) + + def forward(self, x, concat_with): + up_x = F.interpolate(x, size=[concat_with.size(2), concat_with.size(3)], mode='bilinear', align_corners=True) + f = torch.cat([up_x, concat_with], dim=1) + return self._net(f) + + +class DecoderBN(nn.Module): + def __init__(self, num_features=2048, num_classes=1, bottleneck_features=2048): + super(DecoderBN, self).__init__() + features = int(num_features) + + self.conv2 = nn.Conv2d(bottleneck_features, features, kernel_size=1, stride=1, padding=1) + + self.up1 = UpSampleBN(skip_input=features // 1 + 112 + 64, output_features=features // 2) + self.up2 = UpSampleBN(skip_input=features // 2 + 40 + 24, output_features=features // 4) + self.up3 = UpSampleBN(skip_input=features // 4 + 24 + 16, output_features=features // 8) + self.up4 = UpSampleBN(skip_input=features // 8 + 16 + 8, output_features=features // 16) + + # self.up5 = UpSample(skip_input=features // 16 + 3, output_features=features//16) + self.conv3 = nn.Conv2d(features // 16, num_classes, kernel_size=3, stride=1, padding=1) + # self.act_out = nn.Softmax(dim=1) if output_activation == 'softmax' else nn.Identity() + + def forward(self, features): + x_block0, x_block1, x_block2, x_block3, x_block4 = features[4], features[5], features[6], features[8], features[ + 11] + + x_d0 = self.conv2(x_block4) + + x_d1 = self.up1(x_d0, x_block3) + x_d2 = self.up2(x_d1, x_block2) + x_d3 = self.up3(x_d2, x_block1) + x_d4 = self.up4(x_d3, x_block0) + # x_d5 = self.up5(x_d4, features[0]) + out = self.conv3(x_d4) + # out = self.act_out(out) + # if with_features: + # return out, features[-1] + # elif with_intermediate: + # return out, [x_block0, x_block1, x_block2, x_block3, x_block4, x_d1, x_d2, x_d3, x_d4] + return out + + +class Encoder(nn.Module): + def __init__(self, backend): + super(Encoder, self).__init__() + self.original_model = backend + + def forward(self, x): + features = [x] + for k, v in self.original_model._modules.items(): + if (k == 'blocks'): + for ki, vi in v._modules.items(): + features.append(vi(features[-1])) + else: + features.append(v(features[-1])) + return features + + +class UnetAdaptiveBins(nn.Module): + def __init__(self, backend, n_bins=100, min_val=0.1, max_val=10, norm='linear'): + super(UnetAdaptiveBins, self).__init__() + self.num_classes = n_bins + self.min_val = min_val + self.max_val = max_val + self.encoder = Encoder(backend) + self.adaptive_bins_layer = mViT(128, n_query_channels=128, patch_size=16, + dim_out=n_bins, + embedding_dim=128, norm=norm) + + self.decoder = DecoderBN(num_classes=128) + self.conv_out = nn.Sequential(nn.Conv2d(128, n_bins, kernel_size=1, stride=1, padding=0), + nn.Softmax(dim=1)) + + def forward(self, x, **kwargs): + unet_out = self.decoder(self.encoder(x), **kwargs) + bin_widths_normed, range_attention_maps = self.adaptive_bins_layer(unet_out) + out = self.conv_out(range_attention_maps) + + # Post process + # n, c, h, w = out.shape + # hist = torch.sum(out.view(n, c, h * w), dim=2) / (h * w) # not used for training + + bin_widths = (self.max_val - self.min_val) * bin_widths_normed # .shape = N, dim_out + bin_widths = nn.functional.pad(bin_widths, (1, 0), mode='constant', value=self.min_val) + bin_edges = torch.cumsum(bin_widths, dim=1) + + centers = 0.5 * (bin_edges[:, :-1] + bin_edges[:, 1:]) + n, dout = centers.size() + centers = centers.view(n, dout, 1, 1) + + pred = torch.sum(out * centers, dim=1, keepdim=True) + + return bin_edges, pred + + def get_1x_lr_params(self): # lr/10 learning rate + return self.encoder.parameters() + + def get_10x_lr_params(self): # lr learning rate + modules = [self.decoder, self.adaptive_bins_layer, self.conv_out] + for m in modules: + yield from m.parameters() + + @classmethod + def build(cls, n_bins, **kwargs): + basemodel_name = 'tf_efficientnet_b5_ap' + + print('Loading base model ()...'.format(basemodel_name), end='') + predicted_torch_model_cache_path = str(Path.home()) + '\\.cache\\torch\\hub\\rwightman_gen-efficientnet-pytorch_master' + predicted_gep_cache_testilfe = Path(predicted_torch_model_cache_path + '\\hubconf.py') + #print(f"predicted_gep_cache_testilfe: {predicted_gep_cache_testilfe}") + # try to fetch the models from cache, and only if it can't be find, download from the internet (to enable offline usage) + if os.path.isfile(predicted_gep_cache_testilfe): + basemodel = torch.hub.load(predicted_torch_model_cache_path, basemodel_name, pretrained=True, source = 'local') + else: + basemodel = torch.hub.load('rwightman/gen-efficientnet-pytorch', basemodel_name, pretrained=True) + print('Done.') + + # Remove last layer + print('Removing last two layers (global_pool & classifier).') + basemodel.global_pool = nn.Identity() + basemodel.classifier = nn.Identity() + + # Building Encoder-Decoder model + print('Building Encoder-Decoder model..', end='') + m = cls(basemodel, n_bins=n_bins, **kwargs) + print('Done.') + return m + + +if __name__ == '__main__': + model = UnetAdaptiveBins.build(100) + x = torch.rand(2, 3, 480, 640) + bins, pred = model(x) + print(bins.shape, pred.shape) diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/LICENSE b/extensions/deforum/scripts/deforum_helpers/src/clipseg/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..033c8f5ac0e93624d1890d03581d940b9fa850ac --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/LICENSE @@ -0,0 +1,21 @@ +MIT License + +This license does not apply to the model weights. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/Quickstart.ipynb b/extensions/deforum/scripts/deforum_helpers/src/clipseg/Quickstart.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a06690b4606fa533c1cb2429610c983c989570b2 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/Quickstart.ipynb @@ -0,0 +1,107 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import torch\n", + "import requests\n", + "\n", + "! wget https://owncloud.gwdg.de/index.php/s/ioHbRzFx6th32hn/download -O weights.zip\n", + "! unzip -d weights -j weights.zip\n", + "from models.clipseg import CLIPDensePredT\n", + "from PIL import Image\n", + "from torchvision import transforms\n", + "from matplotlib import pyplot as plt\n", + "\n", + "# load model\n", + "model = CLIPDensePredT(version='ViT-B/16', reduce_dim=64)\n", + "model.eval();\n", + "\n", + "# non-strict, because we only stored decoder weights (not CLIP weights)\n", + "model.load_state_dict(torch.load('weights/rd64-uni.pth', map_location=torch.device('cpu')), strict=False);" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Load and normalize `example_image.jpg`. You can also load through an URL." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# load and normalize image\n", + "input_image = Image.open('example_image.jpg')\n", + "\n", + "# or load from URL...\n", + "# image_url = 'https://farm5.staticflickr.com/4141/4856248695_03475782dc_z.jpg'\n", + "# input_image = Image.open(requests.get(image_url, stream=True).raw)\n", + "\n", + "transform = transforms.Compose([\n", + " transforms.ToTensor(),\n", + " transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n", + " transforms.Resize((352, 352)),\n", + "])\n", + "img = transform(input_image).unsqueeze(0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Predict and visualize (this might take a few seconds if running without GPU support)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "prompts = ['a glass', 'something to fill', 'wood', 'a jar']\n", + "\n", + "# predict\n", + "with torch.no_grad():\n", + " preds = model(img.repeat(4,1,1,1), prompts)[0]\n", + "\n", + "# visualize prediction\n", + "_, ax = plt.subplots(1, 5, figsize=(15, 4))\n", + "[a.axis('off') for a in ax.flatten()]\n", + "ax[0].imshow(input_image)\n", + "[ax[i+1].imshow(torch.sigmoid(preds[i][0])) for i in range(4)];\n", + "[ax[i+1].text(0, -15, prompts[i]) for i in range(4)];" + ] + } + ], + "metadata": { + "interpreter": { + "hash": "800ed241f7db2bd3aa6942aa3be6809cdb30ee6b0a9e773dfecfa9fef1f4c586" + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.10" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/Readme.md b/extensions/deforum/scripts/deforum_helpers/src/clipseg/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..070220ae51af60a601657dfc6c8093ad3192ee28 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/Readme.md @@ -0,0 +1,84 @@ +# Image Segmentation Using Text and Image Prompts +This repository contains the code used in the paper ["Image Segmentation Using Text and Image Prompts"](https://arxiv.org/abs/2112.10003). + +**The Paper has been accepted to CVPR 2022!** + +drawing + +The systems allows to create segmentation models without training based on: +- An arbitrary text query +- Or an image with a mask highlighting stuff or an object. + +### Quick Start + +In the `Quickstart.ipynb` notebook we provide the code for using a pre-trained CLIPSeg model. If you run the notebook locally, make sure you downloaded the `rd64-uni.pth` weights, either manually or via git lfs extension. +It can also be used interactively using [MyBinder](https://mybinder.org/v2/gh/timojl/clipseg/HEAD?labpath=Quickstart.ipynb) +(please note that the VM does not use a GPU, thus inference takes a few seconds). + + +### Dependencies +This code base depends on pytorch, torchvision and clip (`pip install git+https://github.com/openai/CLIP.git`). +Additional dependencies are hidden for double blind review. + + +### Datasets + +* `PhraseCut` and `PhraseCutPlus`: Referring expression dataset +* `PFEPascalWrapper`: Wrapper class for PFENet's Pascal-5i implementation +* `PascalZeroShot`: Wrapper class for PascalZeroShot +* `COCOWrapper`: Wrapper class for COCO. + +### Models + +* `CLIPDensePredT`: CLIPSeg model with transformer-based decoder. +* `ViTDensePredT`: CLIPSeg model with transformer-based decoder. + +### Third Party Dependencies +For some of the datasets third party dependencies are required. Run the following commands in the `third_party` folder. +```bash +git clone https://github.com/cvlab-yonsei/JoEm +git clone https://github.com/Jia-Research-Lab/PFENet.git +git clone https://github.com/ChenyunWu/PhraseCutDataset.git +git clone https://github.com/juhongm999/hsnet.git +``` + +### Weights + +The MIT license does not apply to these weights. + +We provide two model weights, for D=64 (4.1MB) and D=16 (1.1MB). +``` +wget https://owncloud.gwdg.de/index.php/s/ioHbRzFx6th32hn/download -O weights.zip +unzip -d weights -j weights.zip +``` + + +### Training and Evaluation + +To train use the `training.py` script with experiment file and experiment id parameters. E.g. `python training.py phrasecut.yaml 0` will train the first phrasecut experiment which is defined by the `configuration` and first `individual_configurations` parameters. Model weights will be written in `logs/`. + +For evaluation use `score.py`. E.g. `python score.py phrasecut.yaml 0 0` will train the first phrasecut experiment of `test_configuration` and the first configuration in `individual_configurations`. + + +### Usage of PFENet Wrappers + +In order to use the dataset and model wrappers for PFENet, the PFENet repository needs to be cloned to the root folder. +`git clone https://github.com/Jia-Research-Lab/PFENet.git ` + + +### License + +The source code files in this repository (excluding model weights) are released under MIT license. + +### Citation +``` +@InProceedings{lueddecke22_cvpr, + author = {L\"uddecke, Timo and Ecker, Alexander}, + title = {Image Segmentation Using Text and Image Prompts}, + booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, + month = {June}, + year = {2022}, + pages = {7086-7096} +} + +``` diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/Tables.ipynb b/extensions/deforum/scripts/deforum_helpers/src/clipseg/Tables.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..354f6b9e9a8dabd5f202f9cce4d5d4ca7759e8f9 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/Tables.ipynb @@ -0,0 +1,349 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%load_ext autoreload\n", + "%autoreload 2\n", + "\n", + "import clip\n", + "from evaluation_utils import norm, denorm\n", + "from general_utils import *\n", + "from datasets.lvis_oneshot3 import LVIS_OneShot3, LVIS_OneShot" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# PhraseCut" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "pc = experiment('experiments/phrasecut.yaml', nums=':6').dataframe()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tab1 = pc[['name', 'pc_miou_best', 'pc_fgiou_best', 'pc_ap']]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "cols = ['pc_miou_0.3', 'pc_fgiou_0.3', 'pc_ap']\n", + "tab1 = pc[['name'] + cols]\n", + "for k in cols:\n", + " tab1.loc[:, k] = (100 * tab1.loc[:, k]).round(1)\n", + "tab1.loc[:, 'name'] = ['CLIPSeg (PC+)', 'CLIPSeg (PC, $D=128$)', 'CLIPSeg (PC)', 'CLIP-Deconv', 'ViTSeg (PC+)', 'ViTSeg (PC)']\n", + "tab1.insert(1, 't', [0.3]*tab1.shape[0])\n", + "print(tab1.to_latex(header=False, index=False))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For 0.1 threshold" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "cols = ['pc_miou_0.1', 'pc_fgiou_0.1', 'pc_ap']\n", + "tab1 = pc[['name'] + cols]\n", + "for k in cols:\n", + " tab1.loc[:, k] = (100 * tab1.loc[:, k]).round(1)\n", + "tab1.loc[:, 'name'] = ['CLIPSeg (PC+)', 'CLIPSeg (PC, $D=128$)', 'CLIPSeg (PC)', 'CLIP-Deconv', 'ViTSeg (PC+)', 'ViTSeg (PC)']\n", + "tab1.insert(1, 't', [0.1]*tab1.shape[0])\n", + "print(tab1.to_latex(header=False, index=False))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# One-shot" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Pascal" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "pas = experiment('experiments/pascal_1shot.yaml', nums=':19').dataframe()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "pas[['name', 'pas_h2_miou_0.3', 'pas_h2_biniou_0.3', 'pas_h2_ap', 'pas_h2_fgiou_ct']]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "pas = experiment('experiments/pascal_1shot.yaml', nums=':8').dataframe()\n", + "tab1 = pas[['pas_h2_miou_0.3', 'pas_h2_biniou_0.3', 'pas_h2_ap']]\n", + "print('CLIPSeg (PC+) & 0.3 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[0:4].mean(0).values), '\\\\\\\\')\n", + "print('CLIPSeg (PC) & 0.3 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[4:8].mean(0).values), '\\\\\\\\')\n", + "\n", + "pas = experiment('experiments/pascal_1shot.yaml', nums='12:16').dataframe()\n", + "tab1 = pas[['pas_h2_miou_0.2', 'pas_h2_biniou_0.2', 'pas_h2_ap']]\n", + "print('CLIP-Deconv (PC+) & 0.2 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[0:4].mean(0).values), '\\\\\\\\')\n", + "\n", + "pas = experiment('experiments/pascal_1shot.yaml', nums='16:20').dataframe()\n", + "tab1 = pas[['pas_t_miou_0.2', 'pas_t_biniou_0.2', 'pas_t_ap']]\n", + "print('ViTSeg (PC+) & 0.2 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[0:4].mean(0).values), '\\\\\\\\')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Pascal Zero-shot (in one-shot setting)\n", + "\n", + "Using the same setting as one-shot (hence different from the other zero-shot benchmark)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "pas = experiment('experiments/pascal_1shot.yaml', nums=':8').dataframe()\n", + "tab1 = pas[['pas_t_miou_0.3', 'pas_t_biniou_0.3', 'pas_t_ap']]\n", + "print('CLIPSeg (PC+) & 0.3 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[0:4].mean(0).values), '\\\\\\\\')\n", + "print('CLIPSeg (PC) & 0.3 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[4:8].mean(0).values), '\\\\\\\\')\n", + "\n", + "pas = experiment('experiments/pascal_1shot.yaml', nums='12:16').dataframe()\n", + "tab1 = pas[['pas_t_miou_0.3', 'pas_t_biniou_0.3', 'pas_t_ap']]\n", + "print('CLIP-Deconv (PC+) & 0.3 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[0:4].mean(0).values), '\\\\\\\\')\n", + "\n", + "pas = experiment('experiments/pascal_1shot.yaml', nums='16:20').dataframe()\n", + "tab1 = pas[['pas_t_miou_0.2', 'pas_t_biniou_0.2', 'pas_t_ap']]\n", + "print('ViTSeg (PC+) & 0.2 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[0:4].mean(0).values), '\\\\\\\\')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# without fixed thresholds...\n", + "\n", + "pas = experiment('experiments/pascal_1shot.yaml', nums=':8').dataframe()\n", + "tab1 = pas[['pas_t_best_miou', 'pas_t_best_biniou', 'pas_t_ap']]\n", + "print('CLIPSeg (PC+) & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[0:4].mean(0).values), '\\\\\\\\')\n", + "print('CLIPSeg (PC) & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[4:8].mean(0).values), '\\\\\\\\')\n", + "\n", + "pas = experiment('experiments/pascal_1shot.yaml', nums='12:16').dataframe()\n", + "tab1 = pas[['pas_t_best_miou', 'pas_t_best_biniou', 'pas_t_ap']]\n", + "print('CLIP-Deconv (PC+) & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[0:4].mean(0).values), '\\\\\\\\')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### COCO" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "coco = experiment('experiments/coco.yaml', nums=':29').dataframe()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tab1 = coco[['coco_h2_miou_0.1', 'coco_h2_biniou_0.1', 'coco_h2_ap']]\n", + "tab2 = coco[['coco_h2_miou_0.2', 'coco_h2_biniou_0.2', 'coco_h2_ap']]\n", + "tab3 = coco[['coco_h2_miou_best', 'coco_h2_biniou_best', 'coco_h2_ap']]\n", + "print('CLIPSeg (COCO) & 0.1 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[:4].mean(0).values), '\\\\\\\\')\n", + "print('CLIPSeg (COCO+N) & 0.1 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[4:8].mean(0).values), '\\\\\\\\')\n", + "print('CLIP-Deconv (COCO+N) & 0.1 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[12:16].mean(0).values), '\\\\\\\\')\n", + "print('ViTSeg (COCO) & 0.1 & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[8:12].mean(0).values), '\\\\\\\\')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Zero-shot" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "zs = experiment('experiments/pascal_0shot.yaml', nums=':11').dataframe()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "tab1 = zs[['pas_zs_seen', 'pas_zs_unseen']]\n", + "print('CLIPSeg (PC+) & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[8:9].values[0].tolist() + tab1[10:11].values[0].tolist()), '\\\\\\\\')\n", + "print('CLIP-Deconv & CLIP & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[2:3].values[0].tolist() + tab1[3:4].values[0].tolist()), '\\\\\\\\')\n", + "print('ViTSeg & ImageNet-1K & ' + ' & '.join(f'{x*100:.1f}' for x in tab1[4:5].values[0].tolist() + tab1[5:6].values[0].tolist()), '\\\\\\\\')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Ablation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ablation = experiment('experiments/ablation.yaml', nums=':8').dataframe()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tab1 = ablation[['name', 'pc_miou_best', 'pc_ap', 'pc-vis_miou_best', 'pc-vis_ap']]\n", + "for k in ['pc_miou_best', 'pc_ap', 'pc-vis_miou_best', 'pc-vis_ap']:\n", + " tab1.loc[:, k] = (100 * tab1.loc[:, k]).round(1)\n", + "tab1.loc[:, 'name'] = ['CLIPSeg', 'no CLIP pre-training', 'no-negatives', '50% negatives', 'no visual', '$D=16$', 'only layer 3', 'highlight mask']" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print(tab1.loc[[0,1,4,5,6,7],:].to_latex(header=False, index=False))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print(tab1.loc[[0,1,4,5,6,7],:].to_latex(header=False, index=False))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Generalization" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "generalization = experiment('experiments/generalize.yaml').dataframe()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "gen = generalization[['aff_best_fgiou', 'aff_ap', 'ability_best_fgiou', 'ability_ap', 'part_best_fgiou', 'part_ap']].values" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print(\n", + " 'CLIPSeg (PC+) & ' + ' & '.join(f'{x*100:.1f}' for x in gen[1]) + ' \\\\\\\\ \\n' + \\\n", + " 'CLIPSeg (LVIS) & ' + ' & '.join(f'{x*100:.1f}' for x in gen[0]) + ' \\\\\\\\ \\n' + \\\n", + " 'CLIP-Deconv & ' + ' & '.join(f'{x*100:.1f}' for x in gen[2]) + ' \\\\\\\\ \\n' + \\\n", + " 'VITSeg & ' + ' & '.join(f'{x*100:.1f}' for x in gen[3]) + ' \\\\\\\\'\n", + ")" + ] + } + ], + "metadata": { + "interpreter": { + "hash": "800ed241f7db2bd3aa6942aa3be6809cdb30ee6b0a9e773dfecfa9fef1f4c586" + }, + "kernelspec": { + "display_name": "env2", + "language": "python", + "name": "env2" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/Visual_Feature_Engineering.ipynb b/extensions/deforum/scripts/deforum_helpers/src/clipseg/Visual_Feature_Engineering.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e6acdacff75fd48011f2f8940f99c5124bee88cd --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/Visual_Feature_Engineering.ipynb @@ -0,0 +1,366 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Systematic" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%load_ext autoreload\n", + "%autoreload 2\n", + "\n", + "import clip\n", + "from evaluation_utils import norm, denorm\n", + "from general_utils import *\n", + "from datasets.lvis_oneshot3 import LVIS_OneShot3\n", + "\n", + "clip_device = 'cuda'\n", + "clip_model, preprocess = clip.load(\"ViT-B/16\", device=clip_device)\n", + "clip_model.eval();\n", + "\n", + "from models.clipseg import CLIPDensePredTMasked\n", + "\n", + "clip_mask_model = CLIPDensePredTMasked(version='ViT-B/16').to(clip_device)\n", + "clip_mask_model.eval();" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "lvis = LVIS_OneShot3('train_fixed', mask='separate', normalize=True, with_class_label=True, add_bar=False, \n", + " text_class_labels=True, image_size=352, min_area=0.1,\n", + " min_frac_s=0.05, min_frac_q=0.05, fix_find_crop=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "plot_data(lvis)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from collections import defaultdict\n", + "import json\n", + "\n", + "lvis_raw = json.load(open(expanduser('~/datasets/LVIS/lvis_v1_train.json')))\n", + "lvis_val_raw = json.load(open(expanduser('~/datasets/LVIS/lvis_v1_val.json')))\n", + "\n", + "objects_per_image = defaultdict(lambda : set())\n", + "for ann in lvis_raw['annotations']:\n", + " objects_per_image[ann['image_id']].add(ann['category_id'])\n", + " \n", + "for ann in lvis_val_raw['annotations']:\n", + " objects_per_image[ann['image_id']].add(ann['category_id']) \n", + " \n", + "objects_per_image = {o: [lvis.category_names[o] for o in v] for o, v in objects_per_image.items()}\n", + "\n", + "del lvis_raw, lvis_val_raw" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#bs = 32\n", + "#batches = [get_batch(lvis, i*bs, (i+1)*bs, cuda=True) for i in range(10)]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from general_utils import get_batch\n", + "from functools import partial\n", + "from evaluation_utils import img_preprocess\n", + "import torch\n", + "\n", + "def get_similarities(batches_or_dataset, process, mask=lambda x: None, clipmask=False):\n", + "\n", + " # base_words = [f'a photo of {x}' for x in ['a person', 'an animal', 'a knife', 'a cup']]\n", + "\n", + " all_prompts = []\n", + " \n", + " with torch.no_grad():\n", + " valid_sims = []\n", + " torch.manual_seed(571)\n", + " \n", + " if type(batches_or_dataset) == list:\n", + " loader = batches_or_dataset # already loaded\n", + " max_iter = float('inf')\n", + " else:\n", + " loader = DataLoader(batches_or_dataset, shuffle=False, batch_size=32)\n", + " max_iter = 50\n", + " \n", + " global batch\n", + " for i_batch, (batch, batch_y) in enumerate(loader):\n", + " \n", + " if i_batch >= max_iter: break\n", + " \n", + " processed_batch = process(batch)\n", + " if type(processed_batch) == dict:\n", + " \n", + " # processed_batch = {k: v.to(clip_device) for k, v in processed_batch.items()}\n", + " image_features = clip_mask_model.visual_forward(**processed_batch)[0].to(clip_device).half()\n", + " else:\n", + " processed_batch = process(batch).to(clip_device)\n", + " processed_batch = nnf.interpolate(processed_batch, (224, 224), mode='bilinear')\n", + " #image_features = clip_model.encode_image(processed_batch.to(clip_device)) \n", + " image_features = clip_mask_model.visual_forward(processed_batch)[0].to(clip_device).half()\n", + " \n", + " image_features = image_features / image_features.norm(dim=-1, keepdim=True)\n", + " bs = len(batch[0])\n", + " for j in range(bs):\n", + " \n", + " c, _, sid, qid = lvis.sample_ids[bs * i_batch + j]\n", + " support_image = basename(lvis.samples[c][sid])\n", + " \n", + " img_objs = [o for o in objects_per_image[int(support_image)]]\n", + " img_objs = [o.replace('_', ' ') for o in img_objs]\n", + " \n", + " other_words = [f'a photo of a {o.replace(\"_\", \" \")}' for o in img_objs \n", + " if o != batch_y[2][j]]\n", + " \n", + " prompts = [f'a photo of a {batch_y[2][j]}'] + other_words\n", + " all_prompts += [prompts]\n", + " \n", + " text_cond = clip_model.encode_text(clip.tokenize(prompts).to(clip_device))\n", + " text_cond = text_cond / text_cond.norm(dim=-1, keepdim=True) \n", + "\n", + " global logits\n", + " logits = clip_model.logit_scale.exp() * image_features[j] @ text_cond.T\n", + "\n", + " global sim\n", + " sim = torch.softmax(logits, dim=-1)\n", + " \n", + " valid_sims += [sim]\n", + " \n", + " #valid_sims = torch.stack(valid_sims)\n", + " return valid_sims, all_prompts\n", + " \n", + "\n", + "def new_img_preprocess(x):\n", + " return {'x_inp': x[1], 'mask': (11, 'cls_token', x[2])}\n", + " \n", + "#get_similarities(lvis, partial(img_preprocess, center_context=0.5));\n", + "get_similarities(lvis, lambda x: x[1]);" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "preprocessing_functions = [\n", + "# ['clip mask CLS L11', lambda x: {'x_inp': x[1].cuda(), 'mask': (11, 'cls_token', x[2].cuda())}],\n", + "# ['clip mask CLS all', lambda x: {'x_inp': x[1].cuda(), 'mask': ('all', 'cls_token', x[2].cuda())}],\n", + "# ['clip mask all all', lambda x: {'x_inp': x[1].cuda(), 'mask': ('all', 'all', x[2].cuda())}],\n", + "# ['colorize object red', partial(img_preprocess, colorize=True)],\n", + "# ['add red outline', partial(img_preprocess, outline=True)],\n", + " \n", + "# ['BG brightness 50%', partial(img_preprocess, bg_fac=0.5)],\n", + "# ['BG brightness 10%', partial(img_preprocess, bg_fac=0.1)],\n", + "# ['BG brightness 0%', partial(img_preprocess, bg_fac=0.0)],\n", + "# ['BG blur', partial(img_preprocess, blur=3)],\n", + "# ['BG blur & intensity 10%', partial(img_preprocess, blur=3, bg_fac=0.1)],\n", + " \n", + "# ['crop large context', partial(img_preprocess, center_context=0.5)],\n", + "# ['crop small context', partial(img_preprocess, center_context=0.1)],\n", + " ['crop & background blur', partial(img_preprocess, blur=3, center_context=0.5)],\n", + " ['crop & intensity 10%', partial(img_preprocess, blur=3, bg_fac=0.1)],\n", + "# ['crop & background blur & intensity 10%', partial(img_preprocess, blur=3, center_context=0.1, bg_fac=0.1)],\n", + "]\n", + "\n", + "preprocessing_functions = preprocessing_functions\n", + "\n", + "base, base_p = get_similarities(lvis, lambda x: x[1])\n", + "outs = [get_similarities(lvis, fun) for _, fun in preprocessing_functions]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "outs2 = [get_similarities(lvis, fun) for _, fun in [['BG brightness 0%', partial(img_preprocess, bg_fac=0.0)]]]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for j in range(1):\n", + " print(np.mean([outs2[j][0][i][0].cpu() - base[i][0].cpu() for i in range(len(base)) if len(base_p[i]) >= 3]))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from pandas import DataFrame\n", + "tab = dict()\n", + "for j, (name, _) in enumerate(preprocessing_functions):\n", + " tab[name] = np.mean([outs[j][0][i][0].cpu() - base[i][0].cpu() for i in range(len(base)) if len(base_p[i]) >= 3])\n", + " \n", + " \n", + "print('\\n'.join(f'{k} & {v*100:.2f} \\\\\\\\' for k,v in tab.items())) " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Visual" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from evaluation_utils import denorm, norm" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def load_sample(filename, filename2):\n", + " from os.path import join\n", + " bp = expanduser('~/cloud/resources/sample_images')\n", + " tf = transforms.Compose([\n", + " transforms.ToTensor(),\n", + " transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n", + " transforms.Resize(224),\n", + " transforms.CenterCrop(224)\n", + " ])\n", + " tf2 = transforms.Compose([\n", + " transforms.ToTensor(),\n", + " transforms.Resize(224),\n", + " transforms.CenterCrop(224)\n", + " ])\n", + " inp1 = [None, tf(Image.open(join(bp, filename))), tf2(Image.open(join(bp, filename2)))]\n", + " inp1[1] = inp1[1].unsqueeze(0)\n", + " inp1[2] = inp1[2][:1] \n", + " return inp1\n", + "\n", + "def all_preprocessing(inp1):\n", + " return [\n", + " img_preprocess(inp1),\n", + " img_preprocess(inp1, colorize=True),\n", + " img_preprocess(inp1, outline=True), \n", + " img_preprocess(inp1, blur=3),\n", + " img_preprocess(inp1, bg_fac=0.1),\n", + " #img_preprocess(inp1, bg_fac=0.5),\n", + " #img_preprocess(inp1, blur=3, bg_fac=0.5), \n", + " img_preprocess(inp1, blur=3, bg_fac=0.5, center_context=0.5),\n", + " ]\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from torchvision import transforms\n", + "from PIL import Image\n", + "from matplotlib import pyplot as plt\n", + "from evaluation_utils import img_preprocess\n", + "import clip\n", + "\n", + "images_queries = [\n", + " [load_sample('things1.jpg', 'things1_jar.png'), ['jug', 'knife', 'car', 'animal', 'sieve', 'nothing']],\n", + " [load_sample('own_photos/IMG_2017s_square.jpg', 'own_photos/IMG_2017s_square_trash_can.png'), ['trash bin', 'house', 'car', 'bike', 'window', 'nothing']],\n", + "]\n", + "\n", + "\n", + "_, ax = plt.subplots(2 * len(images_queries), 6, figsize=(14, 4.5 * len(images_queries)))\n", + "\n", + "for j, (images, objects) in enumerate(images_queries):\n", + " \n", + " joint_image = all_preprocessing(images)\n", + " \n", + " joint_image = torch.stack(joint_image)[:,0]\n", + " clip_model, preprocess = clip.load(\"ViT-B/16\", device='cpu')\n", + " image_features = clip_model.encode_image(joint_image)\n", + " image_features = image_features / image_features.norm(dim=-1, keepdim=True)\n", + " \n", + " prompts = [f'a photo of a {obj}'for obj in objects]\n", + " text_cond = clip_model.encode_text(clip.tokenize(prompts))\n", + " text_cond = text_cond / text_cond.norm(dim=-1, keepdim=True)\n", + " logits = clip_model.logit_scale.exp() * image_features @ text_cond.T\n", + " sim = torch.softmax(logits, dim=-1).detach().cpu()\n", + "\n", + " for i, img in enumerate(joint_image):\n", + " ax[2*j, i].axis('off')\n", + " \n", + " ax[2*j, i].imshow(torch.clamp(denorm(joint_image[i]).permute(1,2,0), 0, 1))\n", + " ax[2*j+ 1, i].grid(True)\n", + " \n", + " ax[2*j + 1, i].set_ylim(0,1)\n", + " ax[2*j + 1, i].set_yticklabels([])\n", + " ax[2*j + 1, i].set_xticks([]) # set_xticks(range(len(prompts)))\n", + "# ax[1, i].set_xticklabels(objects, rotation=90)\n", + " for k in range(len(sim[i])):\n", + " ax[2*j + 1, i].bar(k, sim[i][k], color=plt.cm.tab20(1) if k!=0 else plt.cm.tab20(3))\n", + " ax[2*j + 1, i].text(k, 0.07, objects[k], rotation=90, ha='center', fontsize=15)\n", + "\n", + "plt.tight_layout()\n", + "plt.savefig('figures/prompt_engineering.pdf', bbox_inches='tight')" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "env2", + "language": "python", + "name": "env2" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.8" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/coco_wrapper.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/coco_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..6844d63ef849ffa19e37c7a49f8cc2a590dc92a5 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/coco_wrapper.py @@ -0,0 +1,99 @@ +import pickle +from types import new_class +import torch +import numpy as np +import os +import json + +from os.path import join, dirname, isdir, isfile, expanduser, realpath, basename +from random import shuffle, seed as set_seed +from PIL import Image + +from itertools import combinations +from torchvision import transforms +from torchvision.transforms.transforms import Resize + +from datasets.utils import blend_image_segmentation +from general_utils import get_from_repository + +COCO_CLASSES = {0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant', 11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard', 32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove', 36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle', 40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl', 46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table', 61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'} + +class COCOWrapper(object): + + def __init__(self, split, fold=0, image_size=400, aug=None, mask='separate', negative_prob=0, + with_class_label=False): + super().__init__() + + self.mask = mask + self.with_class_label = with_class_label + self.negative_prob = negative_prob + + from third_party.hsnet.data.coco import DatasetCOCO + + get_from_repository('COCO-20i', ['COCO-20i.tar']) + + foldpath = join(dirname(__file__), '../third_party/hsnet/data/splits/coco/%s/fold%d.pkl') + + def build_img_metadata_classwise(self): + with open(foldpath % (self.split, self.fold), 'rb') as f: + img_metadata_classwise = pickle.load(f) + return img_metadata_classwise + + + DatasetCOCO.build_img_metadata_classwise = build_img_metadata_classwise + # DatasetCOCO.read_mask = read_mask + + mean = [0.485, 0.456, 0.406] + std = [0.229, 0.224, 0.225] + transform = transforms.Compose([ + transforms.Resize((image_size, image_size)), + transforms.ToTensor(), + transforms.Normalize(mean, std) + ]) + + self.coco = DatasetCOCO(expanduser('~/datasets/COCO-20i/'), fold, transform, split, 1, False) + + self.all_classes = [self.coco.class_ids] + self.coco.base_path = join(expanduser('~/datasets/COCO-20i')) + + def __len__(self): + return len(self.coco) + + def __getitem__(self, i): + sample = self.coco[i] + + label_name = COCO_CLASSES[int(sample['class_id'])] + + img_s, seg_s = sample['support_imgs'][0], sample['support_masks'][0] + + if self.negative_prob > 0 and torch.rand(1).item() < self.negative_prob: + new_class_id = sample['class_id'] + while new_class_id == sample['class_id']: + sample2 = self.coco[torch.randint(0, len(self), (1,)).item()] + new_class_id = sample2['class_id'] + img_s = sample2['support_imgs'][0] + seg_s = torch.zeros_like(seg_s) + + mask = self.mask + if mask == 'separate': + supp = (img_s, seg_s) + elif mask == 'text_label': + # DEPRECATED + supp = [int(sample['class_id'])] + elif mask == 'text': + supp = [label_name] + else: + if mask.startswith('text_and_'): + mask = mask[9:] + label_add = [label_name] + else: + label_add = [] + + supp = label_add + blend_image_segmentation(img_s, seg_s, mode=mask) + + if self.with_class_label: + label = (torch.zeros(0), sample['class_id'],) + else: + label = (torch.zeros(0), ) + + return (sample['query_img'],) + tuple(supp), (sample['query_mask'].unsqueeze(0),) + label \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/pascal_classes.json b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/pascal_classes.json new file mode 100644 index 0000000000000000000000000000000000000000..1d8ad2b9ff453a88af7d50c412fd291ec6567644 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/pascal_classes.json @@ -0,0 +1 @@ +[{"id": 1, "synonyms": ["aeroplane"]}, {"id": 2, "synonyms": ["bicycle"]}, {"id": 3, "synonyms": ["bird"]}, {"id": 4, "synonyms": ["boat"]}, {"id": 5, "synonyms": ["bottle"]}, {"id": 6, "synonyms": ["bus"]}, {"id": 7, "synonyms": ["car"]}, {"id": 8, "synonyms": ["cat"]}, {"id": 9, "synonyms": ["chair"]}, {"id": 10, "synonyms": ["cow"]}, {"id": 11, "synonyms": ["diningtable"]}, {"id": 12, "synonyms": ["dog"]}, {"id": 13, "synonyms": ["horse"]}, {"id": 14, "synonyms": ["motorbike"]}, {"id": 15, "synonyms": ["person"]}, {"id": 16, "synonyms": ["pottedplant"]}, {"id": 17, "synonyms": ["sheep"]}, {"id": 18, "synonyms": ["sofa"]}, {"id": 19, "synonyms": ["train"]}, {"id": 20, "synonyms": ["tvmonitor"]}] \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/pascal_zeroshot.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/pascal_zeroshot.py new file mode 100644 index 0000000000000000000000000000000000000000..f3cfd20f6b63a815776278cc0a4780a2e9b263c2 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/pascal_zeroshot.py @@ -0,0 +1,60 @@ +from os.path import expanduser +import torch +import json +import torchvision +from general_utils import get_from_repository +from general_utils import log +from torchvision import transforms + +PASCAL_VOC_CLASSES_ZS = [['cattle.n.01', 'motorcycle.n.01'], ['aeroplane.n.01', 'sofa.n.01'], + ['cat.n.01', 'television.n.03'], ['train.n.01', 'bottle.n.01'], + ['chair.n.01', 'pot_plant.n.01']] + + +class PascalZeroShot(object): + + def __init__(self, split, n_unseen, image_size=224) -> None: + super().__init__() + + import sys + sys.path.append('third_party/JoEm') + from third_party.JoEm.data_loader.dataset import VOCSegmentation + from third_party.JoEm.data_loader import get_seen_idx, get_unseen_idx, VOC + + self.pascal_classes = VOC + self.image_size = image_size + + self.transform = transforms.Compose([ + transforms.Resize((image_size, image_size)), + ]) + + if split == 'train': + self.voc = VOCSegmentation(get_unseen_idx(n_unseen), get_seen_idx(n_unseen), + split=split, transform=True, transform_args=dict(base_size=312, crop_size=312), + ignore_bg=False, ignore_unseen=False, remv_unseen_img=True) + elif split == 'val': + self.voc = VOCSegmentation(get_unseen_idx(n_unseen), get_seen_idx(n_unseen), + split=split, transform=False, + ignore_bg=False, ignore_unseen=False) + + self.unseen_idx = get_unseen_idx(n_unseen) + + def __len__(self): + return len(self.voc) + + def __getitem__(self, i): + + sample = self.voc[i] + label = sample['label'].long() + all_labels = [l for l in torch.where(torch.bincount(label.flatten())>0)[0].numpy().tolist() if l != 255] + class_indices = [l for l in all_labels] + class_names = [self.pascal_classes[l] for l in all_labels] + + image = self.transform(sample['image']) + + label = transforms.Resize((self.image_size, self.image_size), + interpolation=torchvision.transforms.InterpolationMode.NEAREST)(label.unsqueeze(0))[0] + + return (image,), (label, ) + + diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/pfe_dataset.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/pfe_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab6833fea3cdbbe997228e540ea16486c899cbc --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/pfe_dataset.py @@ -0,0 +1,129 @@ +from os.path import expanduser +import torch +import json +from general_utils import get_from_repository +from datasets.lvis_oneshot3 import blend_image_segmentation +from general_utils import log + +PASCAL_CLASSES = {a['id']: a['synonyms'] for a in json.load(open('datasets/pascal_classes.json'))} + + +class PFEPascalWrapper(object): + + def __init__(self, mode, split, mask='separate', image_size=473, label_support=None, size=None, p_negative=0, aug=None): + import sys + # sys.path.append(expanduser('~/projects/new_one_shot')) + from third_party.PFENet.util.dataset import SemData + + get_from_repository('PascalVOC2012', ['Pascal5i.tar']) + + self.p_negative = p_negative + self.size = size + self.mode = mode + self.image_size = image_size + + if label_support in {True, False}: + log.warning('label_support argument is deprecated. Use mask instead.') + #raise ValueError() + + self.mask = mask + + value_scale = 255 + mean = [0.485, 0.456, 0.406] + mean = [item * value_scale for item in mean] + std = [0.229, 0.224, 0.225] + std = [item * value_scale for item in std] + + import third_party.PFENet.util.transform as transform + + if mode == 'val': + data_list = expanduser('~/projects/old_one_shot/PFENet/lists/pascal/val.txt') + + data_transform = [transform.test_Resize(size=image_size)] if image_size != 'original' else [] + data_transform += [ + transform.ToTensor(), + transform.Normalize(mean=mean, std=std) + ] + + + elif mode == 'train': + data_list = expanduser('~/projects/old_one_shot/PFENet/lists/pascal/voc_sbd_merge_noduplicate.txt') + + assert image_size != 'original' + + data_transform = [ + transform.RandScale([0.9, 1.1]), + transform.RandRotate([-10, 10], padding=mean, ignore_label=255), + transform.RandomGaussianBlur(), + transform.RandomHorizontalFlip(), + transform.Crop((image_size, image_size), crop_type='rand', padding=mean, ignore_label=255), + transform.ToTensor(), + transform.Normalize(mean=mean, std=std) + ] + + data_transform = transform.Compose(data_transform) + + self.dataset = SemData(split=split, mode=mode, data_root=expanduser('~/datasets/PascalVOC2012/VOC2012'), + data_list=data_list, shot=1, transform=data_transform, use_coco=False, use_split_coco=False) + + self.class_list = self.dataset.sub_val_list if mode == 'val' else self.dataset.sub_list + + # verify that subcls_list always has length 1 + # assert len(set([len(d[4]) for d in self.dataset])) == 1 + + print('actual length', len(self.dataset.data_list)) + + def __len__(self): + if self.mode == 'val': + return len(self.dataset.data_list) + else: + return len(self.dataset.data_list) + + def __getitem__(self, index): + if self.dataset.mode == 'train': + image, label, s_x, s_y, subcls_list = self.dataset[index % len(self.dataset.data_list)] + elif self.dataset.mode == 'val': + image, label, s_x, s_y, subcls_list, ori_label = self.dataset[index % len(self.dataset.data_list)] + ori_label = torch.from_numpy(ori_label).unsqueeze(0) + + if self.image_size != 'original': + longerside = max(ori_label.size(1), ori_label.size(2)) + backmask = torch.ones(ori_label.size(0), longerside, longerside).cuda()*255 + backmask[0, :ori_label.size(1), :ori_label.size(2)] = ori_label + label = backmask.clone().long() + else: + label = label.unsqueeze(0) + + # assert label.shape == (473, 473) + + if self.p_negative > 0: + if torch.rand(1).item() < self.p_negative: + while True: + idx = torch.randint(0, len(self.dataset.data_list), (1,)).item() + _, _, s_x, s_y, subcls_list_tmp, _ = self.dataset[idx] + if subcls_list[0] != subcls_list_tmp[0]: + break + + s_x = s_x[0] + s_y = (s_y == 1)[0] + label_fg = (label == 1).float() + val_mask = (label != 255).float() + + class_id = self.class_list[subcls_list[0]] + + label_name = PASCAL_CLASSES[class_id][0] + label_add = () + mask = self.mask + + if mask == 'text': + support = ('a photo of a ' + label_name + '.',) + elif mask == 'separate': + support = (s_x, s_y) + else: + if mask.startswith('text_and_'): + label_add = (label_name,) + mask = mask[9:] + + support = (blend_image_segmentation(s_x, s_y.float(), mask)[0],) + + return (image,) + label_add + support, (label_fg.unsqueeze(0), val_mask.unsqueeze(0), subcls_list[0]) diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/phrasecut.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/phrasecut.py new file mode 100644 index 0000000000000000000000000000000000000000..a88cf324b8df132667110be2b03eed1433c2671e --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/phrasecut.py @@ -0,0 +1,335 @@ + +import torch +import numpy as np +import os + +from os.path import join, isdir, isfile, expanduser +from PIL import Image + +from torchvision import transforms +from torchvision.transforms.transforms import Resize + +from torch.nn import functional as nnf +from general_utils import get_from_repository + +from skimage.draw import polygon2mask + + + +def random_crop_slices(origin_size, target_size): + """Gets slices of a random crop. """ + assert origin_size[0] >= target_size[0] and origin_size[1] >= target_size[1], f'actual size: {origin_size}, target size: {target_size}' + + offset_y = torch.randint(0, origin_size[0] - target_size[0] + 1, (1,)).item() # range: 0 <= value < high + offset_x = torch.randint(0, origin_size[1] - target_size[1] + 1, (1,)).item() + + return slice(offset_y, offset_y + target_size[0]), slice(offset_x, offset_x + target_size[1]) + + +def find_crop(seg, image_size, iterations=1000, min_frac=None, best_of=None): + + + best_crops = [] + best_crop_not_ok = float('-inf'), None, None + min_sum = 0 + + seg = seg.astype('bool') + + if min_frac is not None: + #min_sum = seg.sum() * min_frac + min_sum = seg.shape[0] * seg.shape[1] * min_frac + + for iteration in range(iterations): + sl_y, sl_x = random_crop_slices(seg.shape, image_size) + seg_ = seg[sl_y, sl_x] + sum_seg_ = seg_.sum() + + if sum_seg_ > min_sum: + + if best_of is None: + return sl_y, sl_x, False + else: + best_crops += [(sum_seg_, sl_y, sl_x)] + if len(best_crops) >= best_of: + best_crops.sort(key=lambda x:x[0], reverse=True) + sl_y, sl_x = best_crops[0][1:] + + return sl_y, sl_x, False + + else: + if sum_seg_ > best_crop_not_ok[0]: + best_crop_not_ok = sum_seg_, sl_y, sl_x + + else: + # return best segmentation found + return best_crop_not_ok[1:] + (best_crop_not_ok[0] <= min_sum,) + + +class PhraseCut(object): + + def __init__(self, split, image_size=400, negative_prob=0, aug=None, aug_color=False, aug_crop=True, + min_size=0, remove_classes=None, with_visual=False, only_visual=False, mask=None): + super().__init__() + + self.negative_prob = negative_prob + self.image_size = image_size + self.with_visual = with_visual + self.only_visual = only_visual + self.phrase_form = '{}' + self.mask = mask + self.aug_crop = aug_crop + + if aug_color: + self.aug_color = transforms.Compose([ + transforms.ColorJitter(0.5, 0.5, 0.2, 0.05), + ]) + else: + self.aug_color = None + + get_from_repository('PhraseCut', ['PhraseCut.tar'], integrity_check=lambda local_dir: all([ + isdir(join(local_dir, 'VGPhraseCut_v0')), + isdir(join(local_dir, 'VGPhraseCut_v0', 'images')), + isfile(join(local_dir, 'VGPhraseCut_v0', 'refer_train.json')), + len(os.listdir(join(local_dir, 'VGPhraseCut_v0', 'images'))) in {108250, 108249} + ])) + + from third_party.PhraseCutDataset.utils.refvg_loader import RefVGLoader + self.refvg_loader = RefVGLoader(split=split) + + # img_ids where the size in the annotations does not match actual size + invalid_img_ids = set([150417, 285665, 498246, 61564, 285743, 498269, 498010, 150516, 150344, 286093, 61530, + 150333, 286065, 285814, 498187, 285761, 498042]) + + mean = [0.485, 0.456, 0.406] + std = [0.229, 0.224, 0.225] + self.normalize = transforms.Normalize(mean, std) + + self.sample_ids = [(i, j) + for i in self.refvg_loader.img_ids + for j in range(len(self.refvg_loader.get_img_ref_data(i)['phrases'])) + if i not in invalid_img_ids] + + + # self.all_phrases = list(set([p for i in self.refvg_loader.img_ids for p in self.refvg_loader.get_img_ref_data(i)['phrases']])) + + from nltk.stem import WordNetLemmatizer + wnl = WordNetLemmatizer() + + # Filter by class (if remove_classes is set) + if remove_classes is None: + pass + else: + from datasets.generate_lvis_oneshot import PASCAL_SYNSETS, traverse_lemmas, traverse_lemmas_hypo + from nltk.corpus import wordnet + + print('remove pascal classes...') + + get_data = self.refvg_loader.get_img_ref_data # shortcut + keep_sids = None + + if remove_classes[0] == 'pas5i': + subset_id = remove_classes[1] + from datasets.generate_lvis_oneshot import PASCAL_5I_SYNSETS_ORDERED, PASCAL_5I_CLASS_IDS + avoid = [PASCAL_5I_SYNSETS_ORDERED[i] for i in range(20) if i+1 not in PASCAL_5I_CLASS_IDS[subset_id]] + + + elif remove_classes[0] == 'zs': + stop = remove_classes[1] + + from datasets.pascal_zeroshot import PASCAL_VOC_CLASSES_ZS + + avoid = [c for class_set in PASCAL_VOC_CLASSES_ZS[:stop] for c in class_set] + print(avoid) + + elif remove_classes[0] == 'aff': + # avoid = ['drink.v.01', 'sit.v.01', 'ride.v.02'] + # all_lemmas = set(['drink', 'sit', 'ride']) + avoid = ['drink', 'drinks', 'drinking', 'sit', 'sits', 'sitting', + 'ride', 'rides', 'riding', + 'fly', 'flies', 'flying', 'drive', 'drives', 'driving', 'driven', + 'swim', 'swims', 'swimming', + 'wheels', 'wheel', 'legs', 'leg', 'ear', 'ears'] + keep_sids = [(i, j) for i, j in self.sample_ids if + all(x not in avoid for x in get_data(i)['phrases'][j].split(' '))] + + print('avoid classes:', avoid) + + + if keep_sids is None: + all_lemmas = [s for ps in avoid for s in traverse_lemmas_hypo(wordnet.synset(ps), max_depth=None)] + all_lemmas = list(set(all_lemmas)) + all_lemmas = [h.replace('_', ' ').lower() for h in all_lemmas] + all_lemmas = set(all_lemmas) + + # divide into multi word and single word + all_lemmas_s = set(l for l in all_lemmas if ' ' not in l) + all_lemmas_m = set(l for l in all_lemmas if l not in all_lemmas_s) + + # new3 + phrases = [get_data(i)['phrases'][j] for i, j in self.sample_ids] + remove_sids = set((i,j) for (i,j), phrase in zip(self.sample_ids, phrases) + if any(l in phrase for l in all_lemmas_m) or + len(set(wnl.lemmatize(w) for w in phrase.split(' ')).intersection(all_lemmas_s)) > 0 + ) + keep_sids = [(i, j) for i, j in self.sample_ids if (i,j) not in remove_sids] + + print(f'Reduced to {len(keep_sids) / len(self.sample_ids):.3f}') + removed_ids = set(self.sample_ids) - set(keep_sids) + + print('Examples of removed', len(removed_ids)) + for i, j in list(removed_ids)[:20]: + print(i, get_data(i)['phrases'][j]) + + self.sample_ids = keep_sids + + from itertools import groupby + samples_by_phrase = [(self.refvg_loader.get_img_ref_data(i)['phrases'][j], (i, j)) + for i, j in self.sample_ids] + samples_by_phrase = sorted(samples_by_phrase) + samples_by_phrase = groupby(samples_by_phrase, key=lambda x: x[0]) + + self.samples_by_phrase = {prompt: [s[1] for s in prompt_sample_ids] for prompt, prompt_sample_ids in samples_by_phrase} + + self.all_phrases = list(set(self.samples_by_phrase.keys())) + + + if self.only_visual: + assert self.with_visual + self.sample_ids = [(i, j) for i, j in self.sample_ids + if len(self.samples_by_phrase[self.refvg_loader.get_img_ref_data(i)['phrases'][j]]) > 1] + + # Filter by size (if min_size is set) + sizes = [self.refvg_loader.get_img_ref_data(i)['gt_boxes'][j] for i, j in self.sample_ids] + image_sizes = [self.refvg_loader.get_img_ref_data(i)['width'] * self.refvg_loader.get_img_ref_data(i)['height'] for i, j in self.sample_ids] + #self.sizes = [sum([(s[2] - s[0]) * (s[3] - s[1]) for s in size]) for size in sizes] + self.sizes = [sum([s[2] * s[3] for s in size]) / img_size for size, img_size in zip(sizes, image_sizes)] + + if min_size: + print('filter by size') + + self.sample_ids = [self.sample_ids[i] for i in range(len(self.sample_ids)) if self.sizes[i] > min_size] + + self.base_path = join(expanduser('~/datasets/PhraseCut/VGPhraseCut_v0/images/')) + + def __len__(self): + return len(self.sample_ids) + + + def load_sample(self, sample_i, j): + + img_ref_data = self.refvg_loader.get_img_ref_data(sample_i) + + polys_phrase0 = img_ref_data['gt_Polygons'][j] + phrase = img_ref_data['phrases'][j] + phrase = self.phrase_form.format(phrase) + + masks = [] + for polys in polys_phrase0: + for poly in polys: + poly = [p[::-1] for p in poly] # swap x,y + masks += [polygon2mask((img_ref_data['height'], img_ref_data['width']), poly)] + + seg = np.stack(masks).max(0) + img = np.array(Image.open(join(self.base_path, str(img_ref_data['image_id']) + '.jpg'))) + + min_shape = min(img.shape[:2]) + + if self.aug_crop: + sly, slx, exceed = find_crop(seg, (min_shape, min_shape), iterations=50, min_frac=0.05) + else: + sly, slx = slice(0, None), slice(0, None) + + seg = seg[sly, slx] + img = img[sly, slx] + + seg = seg.astype('uint8') + seg = torch.from_numpy(seg).view(1, 1, *seg.shape) + + if img.ndim == 2: + img = np.dstack([img] * 3) + + img = torch.from_numpy(img).permute(2,0,1).unsqueeze(0).float() + + seg = nnf.interpolate(seg, (self.image_size, self.image_size), mode='nearest')[0,0] + img = nnf.interpolate(img, (self.image_size, self.image_size), mode='bilinear', align_corners=True)[0] + + # img = img.permute([2,0, 1]) + img = img / 255.0 + + if self.aug_color is not None: + img = self.aug_color(img) + + img = self.normalize(img) + + + + return img, seg, phrase + + def __getitem__(self, i): + + sample_i, j = self.sample_ids[i] + + img, seg, phrase = self.load_sample(sample_i, j) + + if self.negative_prob > 0: + if torch.rand((1,)).item() < self.negative_prob: + + new_phrase = None + while new_phrase is None or new_phrase == phrase: + idx = torch.randint(0, len(self.all_phrases), (1,)).item() + new_phrase = self.all_phrases[idx] + phrase = new_phrase + seg = torch.zeros_like(seg) + + if self.with_visual: + # find a corresponding visual image + if phrase in self.samples_by_phrase and len(self.samples_by_phrase[phrase]) > 1: + idx = torch.randint(0, len(self.samples_by_phrase[phrase]), (1,)).item() + other_sample = self.samples_by_phrase[phrase][idx] + #print(other_sample) + img_s, seg_s, _ = self.load_sample(*other_sample) + + from datasets.utils import blend_image_segmentation + + if self.mask in {'separate', 'text_and_separate'}: + # assert img.shape[1:] == img_s.shape[1:] == seg_s.shape == seg.shape[1:] + add_phrase = [phrase] if self.mask == 'text_and_separate' else [] + vis_s = add_phrase + [img_s, seg_s, True] + else: + if self.mask.startswith('text_and_'): + mask_mode = self.mask[9:] + label_add = [phrase] + else: + mask_mode = self.mask + label_add = [] + + masked_img_s = torch.from_numpy(blend_image_segmentation(img_s, seg_s, mode=mask_mode, image_size=self.image_size)[0]) + vis_s = label_add + [masked_img_s, True] + + else: + # phrase is unique + vis_s = torch.zeros_like(img) + + if self.mask in {'separate', 'text_and_separate'}: + add_phrase = [phrase] if self.mask == 'text_and_separate' else [] + vis_s = add_phrase + [vis_s, torch.zeros(*vis_s.shape[1:], dtype=torch.uint8), False] + elif self.mask.startswith('text_and_'): + vis_s = [phrase, vis_s, False] + else: + vis_s = [vis_s, False] + else: + assert self.mask == 'text' + vis_s = [phrase] + + seg = seg.unsqueeze(0).float() + + data_x = (img,) + tuple(vis_s) + + return data_x, (seg, torch.zeros(0), i) + + +class PhraseCutPlus(PhraseCut): + + def __init__(self, split, image_size=400, aug=None, aug_color=False, aug_crop=True, min_size=0, remove_classes=None, only_visual=False, mask=None): + super().__init__(split, image_size=image_size, negative_prob=0.2, aug=aug, aug_color=aug_color, aug_crop=aug_crop, min_size=min_size, + remove_classes=remove_classes, with_visual=True, only_visual=only_visual, mask=mask) \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/utils.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..07b17449991c6ebe58776b64982c75ed30ca6c82 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/datasets/utils.py @@ -0,0 +1,68 @@ + +import numpy as np +import torch + + +def blend_image_segmentation(img, seg, mode, image_size=224): + + + if mode in {'blur_highlight', 'blur3_highlight', 'blur3_highlight01', 'blur_highlight_random', 'crop'}: + if isinstance(img, np.ndarray): + img = torch.from_numpy(img) + + if isinstance(seg, np.ndarray): + seg = torch.from_numpy(seg) + + if mode == 'overlay': + out = img * seg + out = [out.astype('float32')] + elif mode == 'highlight': + out = img * seg[None, :, :] * 0.85 + 0.15 * img + out = [out.astype('float32')] + elif mode == 'highlight2': + img = img / 2 + out = (img+0.1) * seg[None, :, :] + 0.3 * img + out = [out.astype('float32')] + elif mode == 'blur_highlight': + from evaluation_utils import img_preprocess + out = [img_preprocess((None, [img], [seg]), blur=1, bg_fac=0.5).numpy()[0] - 0.01] + elif mode == 'blur3_highlight': + from evaluation_utils import img_preprocess + out = [img_preprocess((None, [img], [seg]), blur=3, bg_fac=0.5).numpy()[0] - 0.01] + elif mode == 'blur3_highlight01': + from evaluation_utils import img_preprocess + out = [img_preprocess((None, [img], [seg]), blur=3, bg_fac=0.1).numpy()[0] - 0.01] + elif mode == 'blur_highlight_random': + from evaluation_utils import img_preprocess + out = [img_preprocess((None, [img], [seg]), blur=0 + torch.randint(0, 3, (1,)).item(), bg_fac=0.1 + 0.8*torch.rand(1).item()).numpy()[0] - 0.01] + elif mode == 'crop': + from evaluation_utils import img_preprocess + out = [img_preprocess((None, [img], [seg]), blur=1, center_context=0.1, image_size=image_size)[0].numpy()] + elif mode == 'crop_blur_highlight': + from evaluation_utils import img_preprocess + out = [img_preprocess((None, [img], [seg]), blur=3, center_context=0.1, bg_fac=0.1, image_size=image_size)[0].numpy()] + elif mode == 'crop_blur_highlight352': + from evaluation_utils import img_preprocess + out = [img_preprocess((None, [img], [seg]), blur=3, center_context=0.1, bg_fac=0.1, image_size=352)[0].numpy()] + elif mode == 'shape': + out = [np.stack([seg[:, :]]*3).astype('float32')] + elif mode == 'concat': + out = [np.concatenate([img, seg[None, :, :]]).astype('float32')] + elif mode == 'image_only': + out = [img.astype('float32')] + elif mode == 'image_black': + out = [img.astype('float32')*0] + elif mode is None: + out = [img.astype('float32')] + elif mode == 'separate': + out = [img.astype('float32'), seg.astype('int64')] + elif mode == 'separate_img_black': + out = [img.astype('float32')*0, seg.astype('int64')] + elif mode == 'separate_seg_ones': + out = [img.astype('float32'), np.ones_like(seg).astype('int64')] + elif mode == 'separate_both_black': + out = [img.astype('float32')*0, seg.astype('int64')*0] + else: + raise ValueError(f'invalid mode: {mode}') + + return out \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/environment.yml b/extensions/deforum/scripts/deforum_helpers/src/clipseg/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..40bb99f79ee06ae85c5f7934d74997de295e95a3 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/environment.yml @@ -0,0 +1,15 @@ +name: clipseg-environment +channels: + - conda-forge + - pytorch +dependencies: + - numpy + - scipy + - matplotlib-base + - pip + - pip: + - --find-links https://download.pytorch.org/whl/torch_stable.html + - torch==1.10.0+cpu + - torchvision==0.11.1+cpu + - opencv-python + - git+https://github.com/openai/CLIP.git diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/evaluation_utils.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/evaluation_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..13e482f081106fce43305376a35b8c4b11676cd7 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/evaluation_utils.py @@ -0,0 +1,292 @@ +from torch.functional import Tensor +from general_utils import load_model +from torch.utils.data import DataLoader +import torch +import numpy as np + +def denorm(img): + + np_input = False + if isinstance(img, np.ndarray): + img = torch.from_numpy(img) + np_input = True + + mean = torch.Tensor([0.485, 0.456, 0.406]) + std = torch.Tensor([0.229, 0.224, 0.225]) + + img_denorm = (img*std[:,None,None]) + mean[:,None,None] + + if np_input: + img_denorm = np.clip(img_denorm.numpy(), 0, 1) + else: + img_denorm = torch.clamp(img_denorm, 0, 1) + + return img_denorm + + +def norm(img): + mean = torch.Tensor([0.485, 0.456, 0.406]) + std = torch.Tensor([0.229, 0.224, 0.225]) + return (img - mean[:,None,None]) / std[:,None,None] + + +def fast_iou_curve(p, g): + + g = g[p.sort().indices] + p = torch.sigmoid(p.sort().values) + + scores = [] + vals = np.linspace(0, 1, 50) + + for q in vals: + + n = int(len(g) * q) + + valid = torch.where(p > q)[0] + if len(valid) > 0: + n = int(valid[0]) + else: + n = len(g) + + fn = g[:n].sum() + tn = n - fn + tp = g[n:].sum() + fp = len(g) - n - tp + + iou = tp / (tp + fn + fp) + + precision = tp / (tp + fp) + recall = tp / (tp + fn) + + scores += [iou] + + return vals, scores + + +def fast_rp_curve(p, g): + + g = g[p.sort().indices] + p = torch.sigmoid(p.sort().values) + + precisions, recalls = [], [] + vals = np.linspace(p.min(), p.max(), 250) + + for q in p[::100000]: + + n = int(len(g) * q) + + valid = torch.where(p > q)[0] + if len(valid) > 0: + n = int(valid[0]) + else: + n = len(g) + + fn = g[:n].sum() + tn = n - fn + tp = g[n:].sum() + fp = len(g) - n - tp + + iou = tp / (tp + fn + fp) + + precision = tp / (tp + fp) + recall = tp / (tp + fn) + + precisions += [precision] + recalls += [recall] + + return recalls, precisions + + +# Image processing + +def img_preprocess(batch, blur=0, grayscale=False, center_context=None, rect=False, rect_color=(255,0,0), rect_width=2, + brightness=1.0, bg_fac=1, colorize=False, outline=False, image_size=224): + import cv2 + + rw = rect_width + + out = [] + for img, mask in zip(batch[1], batch[2]): + + img = img.cpu() if isinstance(img, torch.Tensor) else torch.from_numpy(img) + mask = mask.cpu() if isinstance(mask, torch.Tensor) else torch.from_numpy(mask) + + img *= brightness + img_bl = img + if blur > 0: # best 5 + img_bl = torch.from_numpy(cv2.GaussianBlur(img.permute(1,2,0).numpy(), (15, 15), blur)).permute(2,0,1) + + if grayscale: + img_bl = img_bl[1][None] + + #img_inp = img_ratio*img*mask + (1-img_ratio)*img_bl + # img_inp = img_ratio*img*mask + (1-img_ratio)*img_bl * (1-mask) + img_inp = img*mask + (bg_fac) * img_bl * (1-mask) + + if rect: + _, bbox = crop_mask(img, mask, context=0.1) + img_inp[:, bbox[2]: bbox[3], max(0, bbox[0]-rw):bbox[0]+rw] = torch.tensor(rect_color)[:,None,None] + img_inp[:, bbox[2]: bbox[3], max(0, bbox[1]-rw):bbox[1]+rw] = torch.tensor(rect_color)[:,None,None] + img_inp[:, max(0, bbox[2]-1): bbox[2]+rw, bbox[0]:bbox[1]] = torch.tensor(rect_color)[:,None,None] + img_inp[:, max(0, bbox[3]-1): bbox[3]+rw, bbox[0]:bbox[1]] = torch.tensor(rect_color)[:,None,None] + + + if center_context is not None: + img_inp = object_crop(img_inp, mask, context=center_context, image_size=image_size) + + if colorize: + img_gray = denorm(img) + img_gray = cv2.cvtColor(img_gray.permute(1,2,0).numpy(), cv2.COLOR_RGB2GRAY) + img_gray = torch.stack([torch.from_numpy(img_gray)]*3) + img_inp = torch.tensor([1,0.2,0.2])[:,None,None] * img_gray * mask + bg_fac * img_gray * (1-mask) + img_inp = norm(img_inp) + + if outline: + cont = cv2.findContours(mask.byte().numpy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + outline_img = np.zeros(mask.shape, dtype=np.uint8) + cv2.drawContours(outline_img, cont[0], -1, thickness=5, color=(255, 255, 255)) + outline_img = torch.stack([torch.from_numpy(outline_img)]*3).float() / 255. + img_inp = torch.tensor([1,0,0])[:,None,None] * outline_img + denorm(img_inp) * (1- outline_img) + img_inp = norm(img_inp) + + out += [img_inp] + + return torch.stack(out) + + +def object_crop(img, mask, context=0.0, square=False, image_size=224): + img_crop, bbox = crop_mask(img, mask, context=context, square=square) + img_crop = pad_to_square(img_crop, channel_dim=0) + img_crop = torch.nn.functional.interpolate(img_crop.unsqueeze(0), (image_size, image_size)).squeeze(0) + return img_crop + + +def crop_mask(img, mask, context=0.0, square=False): + + assert img.shape[1:] == mask.shape + + bbox = [mask.max(0).values.argmax(), mask.size(0) - mask.max(0).values.flip(0).argmax()] + bbox += [mask.max(1).values.argmax(), mask.size(1) - mask.max(1).values.flip(0).argmax()] + bbox = [int(x) for x in bbox] + + width, height = (bbox[3] - bbox[2]), (bbox[1] - bbox[0]) + + # square mask + if square: + bbox[0] = int(max(0, bbox[0] - context * height)) + bbox[1] = int(min(mask.size(0), bbox[1] + context * height)) + bbox[2] = int(max(0, bbox[2] - context * width)) + bbox[3] = int(min(mask.size(1), bbox[3] + context * width)) + + width, height = (bbox[3] - bbox[2]), (bbox[1] - bbox[0]) + if height > width: + bbox[2] = int(max(0, (bbox[2] - 0.5*height))) + bbox[3] = bbox[2] + height + else: + bbox[0] = int(max(0, (bbox[0] - 0.5*width))) + bbox[1] = bbox[0] + width + else: + bbox[0] = int(max(0, bbox[0] - context * height)) + bbox[1] = int(min(mask.size(0), bbox[1] + context * height)) + bbox[2] = int(max(0, bbox[2] - context * width)) + bbox[3] = int(min(mask.size(1), bbox[3] + context * width)) + + width, height = (bbox[3] - bbox[2]), (bbox[1] - bbox[0]) + img_crop = img[:, bbox[2]: bbox[3], bbox[0]: bbox[1]] + return img_crop, bbox + + +def pad_to_square(img, channel_dim=2, fill=0): + """ + + + add padding such that a squared image is returned """ + + from torchvision.transforms.functional import pad + + if channel_dim == 2: + img = img.permute(2, 0, 1) + elif channel_dim == 0: + pass + else: + raise ValueError('invalid channel_dim') + + h, w = img.shape[1:] + pady1 = pady2 = padx1 = padx2 = 0 + + if h > w: + padx1 = (h - w) // 2 + padx2 = h - w - padx1 + elif w > h: + pady1 = (w - h) // 2 + pady2 = w - h - pady1 + + img_padded = pad(img, padding=(padx1, pady1, padx2, pady2), padding_mode='constant') + + if channel_dim == 2: + img_padded = img_padded.permute(1, 2, 0) + + return img_padded + + +# qualitative + +def split_sentence(inp, limit=9): + t_new, current_len = [], 0 + for k, t in enumerate(inp.split(' ')): + current_len += len(t) + 1 + t_new += [t+' '] + # not last + if current_len > limit and k != len(inp.split(' ')) - 1: + current_len = 0 + t_new += ['\n'] + + t_new = ''.join(t_new) + return t_new + + +from matplotlib import pyplot as plt + + +def plot(imgs, *preds, labels=None, scale=1, cmap=plt.cm.magma, aps=None, gt_labels=None, vmax=None): + + row_off = 0 if labels is None else 1 + _, ax = plt.subplots(len(imgs) + row_off, 1 + len(preds), figsize=(scale * float(1 + 2*len(preds)), scale * float(len(imgs)*2))) + [a.axis('off') for a in ax.flatten()] + + if labels is not None: + for j in range(len(labels)): + t_new = split_sentence(labels[j], limit=6) + ax[0, 1+ j].text(0.5, 0.1, t_new, ha='center', fontsize=3+ 10*scale) + + + for i in range(len(imgs)): + ax[i + row_off,0].imshow(imgs[i]) + for j in range(len(preds)): + img = preds[j][i][0].detach().cpu().numpy() + + if gt_labels is not None and labels[j] == gt_labels[i]: + print(j, labels[j], gt_labels[i]) + edgecolor = 'red' + if aps is not None: + ax[i + row_off, 1 + j].text(30, 70, f'AP: {aps[i]:.3f}', color='red', fontsize=8) + else: + edgecolor = 'k' + + rect = plt.Rectangle([0,0], img.shape[0], img.shape[1], facecolor="none", + edgecolor=edgecolor, linewidth=3) + ax[i + row_off,1 + j].add_patch(rect) + + if vmax is None: + this_vmax = 1 + elif vmax == 'per_prompt': + this_vmax = max([preds[j][_i][0].max() for _i in range(len(imgs))]) + elif vmax == 'per_image': + this_vmax = max([preds[_j][i][0].max() for _j in range(len(preds))]) + + ax[i + row_off,1 + j].imshow(img, vmin=0, vmax=this_vmax, cmap=cmap) + + + # ax[i,1 + j].imshow(preds[j][i][0].detach().cpu().numpy(), vmin=preds[j].min(), vmax=preds[j].max()) + plt.tight_layout() + plt.subplots_adjust(wspace=0.05, hspace=0.05) \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/example_image.jpg b/extensions/deforum/scripts/deforum_helpers/src/clipseg/example_image.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7e47c8223599929bc45f0d64f22ca581b3442dae --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/example_image.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bffef4c76aa9ad56fa072c3b61f1733ea60a204994c5eae2262621e8c8edd686 +size 91493 diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/ablation.yaml b/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/ablation.yaml new file mode 100644 index 0000000000000000000000000000000000000000..133c7f096095da6a085618b418e1b692ca9a1a2c --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/ablation.yaml @@ -0,0 +1,84 @@ +configuration: + batch_size: 64 + optimizer: torch.optim.AdamW + + lr: 0.001 + + trainer: experiment_setup.train_loop + scorer: experiment_setup.score + model: models.clipseg.CLIPDensePredT + + lr_scheduler: cosine + T_max: 20000 + eta_min: 0.0001 + + max_iterations: 20000 # <-########################################## + val_interval: null + + # dataset + dataset: datasets.phrasecut.PhraseCut # <----------------- + split_mode: pascal_test + split: train + mask: text_and_crop_blur_highlight352 + image_size: 352 + negative_prob: 0.2 + mix_text_max: 0.5 + + # general + mix: True # <----------------- + prompt: shuffle+ + norm_cond: True + mix_text_min: 0.0 + with_visual: True + + # model + version: 'ViT-B/16' + extract_layers: [3, 7, 9] + reduce_dim: 64 + depth: 3 + fix_shift: False # <-########################################## + + loss: torch.nn.functional.binary_cross_entropy_with_logits + amp: True + +test_configuration_common: + normalize: True + image_size: 352 + batch_size: 32 + sigmoid: True + split: test + label_support: True + +test_configuration: + + - + name: pc + metric: metrics.FixedIntervalMetrics + test_dataset: phrasecut + mask: text + + - + name: pc-vis + metric: metrics.FixedIntervalMetrics + test_dataset: phrasecut + mask: crop_blur_highlight352 + with_visual: True + visual_only: True + + +columns: [name, +pc_fgiou_best, pc_miou_best, pc_fgiou_0.5, +pc-vis_fgiou_best, pc-vis_miou_best, pc-vis_fgiou_0.5, +duration] + + +individual_configurations: + +- {name: rd64-uni} +- {name: rd64-no-pretrain, not_pretrained: True, lr: 0.0003} +- {name: rd64-no-negatives, negative_prob: 0.0} +- {name: rd64-neg0.5, negative_prob: 0.5} +- {name: rd64-no-visual, with_visual: False, mix: False} +- {name: rd16-uni, reduce_dim: 16} +- {name: rd64-layer3, extract_layers: [3], depth: 1} +- {name: rd64-blur-highlight, mask: text_and_blur_highlight, test_configuration: {mask: blur_highlight}} \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/coco.yaml b/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/coco.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e240eebda8a2b96a20335732b1091b40e818e9d --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/coco.yaml @@ -0,0 +1,101 @@ +configuration: + batch_size: 64 + optimizer: torch.optim.AdamW + + lr: 0.001 + + trainer: experiment_setup.train_loop + scorer: experiment_setup.score + model: models.clipseg.CLIPDensePredT + + lr_scheduler: cosine + T_max: 20000 + eta_min: 0.0001 + + max_iterations: 20000 + val_interval: null + + # dataset + dataset: datasets.coco_wrapper.COCOWrapper + # split_mode: pascal_test + split: train + mask: text_and_blur3_highlight01 + image_size: 352 + normalize: True + pre_crop_image_size: [sample, 1, 1.5] + aug: 1new + + # general + mix: True + prompt: shuffle+ + norm_cond: True + mix_text_min: 0.0 + + # model + out: 1 + extract_layers: [3, 7, 9] + reduce_dim: 64 + depth: 3 + fix_shift: False + + loss: torch.nn.functional.binary_cross_entropy_with_logits + amp: True + +test_configuration_common: + normalize: True + image_size: 352 + # max_iterations: 10 + batch_size: 8 + sigmoid: True + test_dataset: coco + metric: metrics.FixedIntervalMetrics + +test_configuration: + + - + name: coco_t + mask: text + + - + name: coco_h + mask: blur3_highlight01 + + - + name: coco_h2 + mask: crop_blur_highlight352 + + +columns: [i, name, +coco_t_fgiou_best, coco_t_miou_best, coco_t_fgiou_0.5, +coco_h_fgiou_best, coco_h_miou_best, coco_h_fgiou_0.5, +coco_h2_fgiou_best, coco_h2_miou_best, coco_h2_fgiou_0.5, coco_h2_fgiou_best_t, +train_loss, duration, date +] + +individual_configurations: + + +- {name: rd64-7K-vit16-cbh-coco-0, version: 'ViT-B/16', fold: 0, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} +- {name: rd64-7K-vit16-cbh-coco-1, version: 'ViT-B/16', fold: 1, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} +- {name: rd64-7K-vit16-cbh-coco-2, version: 'ViT-B/16', fold: 2, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} +- {name: rd64-7K-vit16-cbh-coco-3, version: 'ViT-B/16', fold: 3, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} + + +- {name: rd64-7K-vit16-cbh-neg0.2-coco-0, version: 'ViT-B/16', negative_prob: 0.2, fold: 0, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} +- {name: rd64-7K-vit16-cbh-neg0.2-coco-1, version: 'ViT-B/16', negative_prob: 0.2, fold: 1, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} +- {name: rd64-7K-vit16-cbh-neg0.2-coco-2, version: 'ViT-B/16', negative_prob: 0.2, fold: 2, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} +- {name: rd64-7K-vit16-cbh-neg0.2-coco-3, version: 'ViT-B/16', negative_prob: 0.2, fold: 3, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} + + +# ViT +- {name: vit64-7K-vit16-cbh-coco-0, version: 'ViT-B/16', model: models.vitseg.VITDensePredT, fold: 0, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000, lr: 0.0001} +- {name: vit64-7K-vit16-cbh-coco-1, version: 'ViT-B/16', model: models.vitseg.VITDensePredT, fold: 1, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000, lr: 0.0001} +- {name: vit64-7K-vit16-cbh-coco-2, version: 'ViT-B/16', model: models.vitseg.VITDensePredT, fold: 2, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000, lr: 0.0001} +- {name: vit64-7K-vit16-cbh-coco-3, version: 'ViT-B/16', model: models.vitseg.VITDensePredT, fold: 3, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000, lr: 0.0001} + + +# BASELINE +- {name: bl64-7K-vit16-cbh-neg0.2-coco-0, model: models.clipseg.CLIPDenseBaseline, reduce2_dim: 64, version: 'ViT-B/16', negative_prob: 0.2, fold: 0, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} +- {name: bl64-7K-vit16-cbh-neg0.2-coco-1, model: models.clipseg.CLIPDenseBaseline, reduce2_dim: 64, version: 'ViT-B/16', negative_prob: 0.2, fold: 1, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} +- {name: bl64-7K-vit16-cbh-neg0.2-coco-2, model: models.clipseg.CLIPDenseBaseline, reduce2_dim: 64, version: 'ViT-B/16', negative_prob: 0.2, fold: 2, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} +- {name: bl64-7K-vit16-cbh-neg0.2-coco-3, model: models.clipseg.CLIPDenseBaseline, reduce2_dim: 64, version: 'ViT-B/16', negative_prob: 0.2, fold: 3, reduce_dim: 64, mask: text_and_crop_blur_highlight352, T_max: 7000, max_iterations: 7000} \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/pascal_1shot.yaml b/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/pascal_1shot.yaml new file mode 100644 index 0000000000000000000000000000000000000000..287915c5554d92f095349815b7d356e831831b58 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/pascal_1shot.yaml @@ -0,0 +1,101 @@ +configuration: + batch_size: 64 + optimizer: torch.optim.AdamW + + lr: 0.001 + + trainer: experiment_setup.train_loop + scorer: experiment_setup.score + model: models.clipseg.CLIPDensePredT + + lr_scheduler: cosine + T_max: 20000 + eta_min: 0.0001 + + max_iterations: 20000 # <-########################################## + val_interval: null + + # dataset + dataset: datasets.phrasecut.PhraseCut + split_mode: pascal_test + mode: train + mask: text_and_crop_blur_highlight352 + image_size: 352 + normalize: True + pre_crop_image_size: [sample, 1, 1.5] + aug: 1new + with_visual: True + split: train + + # general + mix: True + prompt: shuffle+ + norm_cond: True + mix_text_min: 0.0 + + # model + out: 1 + version: 'ViT-B/16' + extract_layers: [3, 7, 9] + reduce_dim: 64 + depth: 3 + + loss: torch.nn.functional.binary_cross_entropy_with_logits + amp: True + +test_configuration_common: + normalize: True + image_size: 352 + metric: metrics.FixedIntervalMetrics + batch_size: 1 + test_dataset: pascal + sigmoid: True + # max_iterations: 250 + +test_configuration: + + - + name: pas_t + mask: text + + - + name: pas_h + mask: blur3_highlight01 + + - + name: pas_h2 + mask: crop_blur_highlight352 + + +columns: [name, +pas_t_fgiou_best, pas_t_miou_best, pas_t_fgiou_ct, +pas_h_fgiou_best, pas_h_miou_best, pas_h_fgiou_ct, +pas_h2_fgiou_best, pas_h2_miou_best, pas_h2_fgiou_ct, pas_h2_fgiou_best_t, +train_loss, duration, date +] + +individual_configurations: + +- {name: rd64-uni-phrasepas5i-0, remove_classes: [pas5i, 0], negative_prob: 0.2, mix_text_max: 0.5, test_configuration: {splits: [0], custom_threshold: 0.24}} +- {name: rd64-uni-phrasepas5i-1, remove_classes: [pas5i, 1], negative_prob: 0.2, mix_text_max: 0.5, test_configuration: {splits: [1], custom_threshold: 0.24}} +- {name: rd64-uni-phrasepas5i-2, remove_classes: [pas5i, 2], negative_prob: 0.2, mix_text_max: 0.5, test_configuration: {splits: [2], custom_threshold: 0.24}} +- {name: rd64-uni-phrasepas5i-3, remove_classes: [pas5i, 3], negative_prob: 0.2, mix_text_max: 0.5, test_configuration: {splits: [3], custom_threshold: 0.24}} + + +- {name: rd64-phrasepas5i-0, remove_classes: [pas5i, 0], negative_prob: 0.0, test_configuration: {splits: [0], custom_threshold: 0.28}} +- {name: rd64-phrasepas5i-1, remove_classes: [pas5i, 1], negative_prob: 0.0, test_configuration: {splits: [1], custom_threshold: 0.28}} +- {name: rd64-phrasepas5i-2, remove_classes: [pas5i, 2], negative_prob: 0.0, test_configuration: {splits: [2], custom_threshold: 0.28}} +- {name: rd64-phrasepas5i-3, remove_classes: [pas5i, 3], negative_prob: 0.0, test_configuration: {splits: [3], custom_threshold: 0.28}} + + +# baseline +- {name: bl64-phrasepas5i-0, model: models.clipseg.CLIPDenseBaseline, remove_classes: [pas5i, 0], reduce2_dim: 64, negative_prob: 0.0, test_configuration: {splits: [0], custom_threshold: 0.24}} +- {name: bl64-phrasepas5i-1, model: models.clipseg.CLIPDenseBaseline, remove_classes: [pas5i, 1], reduce2_dim: 64, negative_prob: 0.0, test_configuration: {splits: [1], custom_threshold: 0.24}} +- {name: bl64-phrasepas5i-2, model: models.clipseg.CLIPDenseBaseline, remove_classes: [pas5i, 2], reduce2_dim: 64, negative_prob: 0.0, test_configuration: {splits: [2], custom_threshold: 0.24}} +- {name: bl64-phrasepas5i-3, model: models.clipseg.CLIPDenseBaseline, remove_classes: [pas5i, 3], reduce2_dim: 64, negative_prob: 0.0, test_configuration: {splits: [3], custom_threshold: 0.24}} + +# ViT +- {name: vit64-uni-phrasepas5i-0, remove_classes: [pas5i, 0], model: models.vitseg.VITDensePredT, negative_prob: 0.2, mix_text_max: 0.5, lr: 0.0001, test_configuration: {splits: [0], custom_threshold: 0.02}} +- {name: vit64-uni-phrasepas5i-1, remove_classes: [pas5i, 1], model: models.vitseg.VITDensePredT, negative_prob: 0.2, mix_text_max: 0.5, lr: 0.0001, test_configuration: {splits: [1], custom_threshold: 0.02}} +- {name: vit64-uni-phrasepas5i-2, remove_classes: [pas5i, 2], model: models.vitseg.VITDensePredT, negative_prob: 0.2, mix_text_max: 0.5, lr: 0.0001, test_configuration: {splits: [2], custom_threshold: 0.02}} +- {name: vit64-uni-phrasepas5i-3, remove_classes: [pas5i, 3], model: models.vitseg.VITDensePredT, negative_prob: 0.2, mix_text_max: 0.5, lr: 0.0001, test_configuration: {splits: [3], custom_threshold: 0.02}} diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/phrasecut.yaml b/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/phrasecut.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ad1bc5e111651836874ba997043442bd50303669 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/experiments/phrasecut.yaml @@ -0,0 +1,80 @@ +configuration: + batch_size: 64 + optimizer: torch.optim.AdamW + + lr: 0.001 + + trainer: experiment_setup.train_loop + scorer: experiment_setup.score + model: models.clipseg.CLIPDensePredT + + lr_scheduler: cosine + T_max: 20000 + eta_min: 0.0001 + + max_iterations: 20000 + val_interval: null + + # dataset + dataset: datasets.phrasecut.PhraseCut # <----------------- + split_mode: pascal_test + split: train + mask: text_and_crop_blur_highlight352 + image_size: 352 + normalize: True + pre_crop_image_size: [sample, 1, 1.5] + aug: 1new + + # general + mix: False # <----------------- + prompt: shuffle+ + norm_cond: True + mix_text_min: 0.0 + + # model + out: 1 + extract_layers: [3, 7, 9] + reduce_dim: 64 + depth: 3 + fix_shift: False + + loss: torch.nn.functional.binary_cross_entropy_with_logits + amp: True + +test_configuration_common: + normalize: True + image_size: 352 + batch_size: 32 + # max_iterations: 5 + # max_iterations: 150 + +test_configuration: + + - + name: pc # old: phrasecut + metric: metrics.FixedIntervalMetrics + test_dataset: phrasecut + split: test + mask: text + label_support: True + sigmoid: True + + +columns: [i, name, pc_miou_0.3, pc_fgiou_0.3, pc_fgiou_0.5, pc_ap, duration, date] + + +individual_configurations: + +# important ones + + +- {name: rd64-uni, version: 'ViT-B/16', reduce_dim: 64, with_visual: True, negative_prob: 0.2, mix: True, mix_text_max: 0.5} + +# this was accedentally trained using old mask +- {name: rd128-vit16-phrasecut, version: 'ViT-B/16', reduce_dim: 128, mask: text_and_blur3_highlight01} +- {name: rd64-uni-novis, version: 'ViT-B/16', reduce_dim: 64, with_visual: False, negative_prob: 0.2, mix: False} +# this was accedentally trained using old mask +- {name: baseline3-vit16-phrasecut, model: models.clipseg.CLIPDenseBaseline, version: 'ViT-B/16', reduce_dim: 64, reduce2_dim: 64, mask: text_and_blur3_highlight01} + +- {name: vit64-uni, version: 'ViT-B/16', model: models.vitseg.VITDensePredT, reduce_dim: 64, with_visual: True, only_visual: True, negative_prob: 0.2, mask: crop_blur_highlight352, lr: 0.0003} +- {name: vit64-uni-novis, version: 'ViT-B/16', model: models.vitseg.VITDensePredT, with_visual: False, reduce_dim: 64, lr: 0.0001} \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/general_utils.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/general_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f5ba5552ef2b8340ae9daa29924e2c95255bf7de --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/general_utils.py @@ -0,0 +1,272 @@ +import json +import inspect +import torch +import os +import sys +import yaml +from shutil import copy, copytree +from os.path import join, dirname, realpath, expanduser, isfile, isdir, basename + + +class Logger(object): + + def __getattr__(self, k): + return print + +log = Logger() + +def training_config_from_cli_args(): + experiment_name = sys.argv[1] + experiment_id = int(sys.argv[2]) + + yaml_config = yaml.load(open(f'experiments/{experiment_name}'), Loader=yaml.SafeLoader) + + config = yaml_config['configuration'] + config = {**config, **yaml_config['individual_configurations'][experiment_id]} + config = AttributeDict(config) + return config + + +def score_config_from_cli_args(): + experiment_name = sys.argv[1] + experiment_id = int(sys.argv[2]) + + + yaml_config = yaml.load(open(f'experiments/{experiment_name}'), Loader=yaml.SafeLoader) + + config = yaml_config['test_configuration_common'] + + if type(yaml_config['test_configuration']) == list: + test_id = int(sys.argv[3]) + config = {**config, **yaml_config['test_configuration'][test_id]} + else: + config = {**config, **yaml_config['test_configuration']} + + if 'test_configuration' in yaml_config['individual_configurations'][experiment_id]: + config = {**config, **yaml_config['individual_configurations'][experiment_id]['test_configuration']} + + train_checkpoint_id = yaml_config['individual_configurations'][experiment_id]['name'] + + config = AttributeDict(config) + return config, train_checkpoint_id + + +def get_from_repository(local_name, repo_files, integrity_check=None, repo_dir='~/dataset_repository', + local_dir='~/datasets'): + """ copies files from repository to local folder. + + repo_files: list of filenames or list of tuples [filename, target path] + + e.g. get_from_repository('MyDataset', [['data/dataset1.tar', 'other/path/ds03.tar']) + will create a folder 'MyDataset' in local_dir, and extract the content of + '/data/dataset1.tar' to /MyDataset/other/path. + """ + + local_dir = realpath(join(expanduser(local_dir), local_name)) + + dataset_exists = True + + # check if folder is available + if not isdir(local_dir): + dataset_exists = False + + if integrity_check is not None: + try: + integrity_ok = integrity_check(local_dir) + except BaseException: + integrity_ok = False + + if integrity_ok: + log.hint('Passed custom integrity check') + else: + log.hint('Custom integrity check failed') + + dataset_exists = dataset_exists and integrity_ok + + if not dataset_exists: + + repo_dir = realpath(expanduser(repo_dir)) + + for i, filename in enumerate(repo_files): + + if type(filename) == str: + origin, target = filename, filename + archive_target = join(local_dir, basename(origin)) + extract_target = join(local_dir) + else: + origin, target = filename + archive_target = join(local_dir, dirname(target), basename(origin)) + extract_target = join(local_dir, dirname(target)) + + archive_origin = join(repo_dir, origin) + + log.hint(f'copy: {archive_origin} to {archive_target}') + + # make sure the path exists + os.makedirs(dirname(archive_target), exist_ok=True) + + if os.path.isfile(archive_target): + # only copy if size differs + if os.path.getsize(archive_target) != os.path.getsize(archive_origin): + log.hint(f'file exists but filesize differs: target {os.path.getsize(archive_target)} vs. origin {os.path.getsize(archive_origin)}') + copy(archive_origin, archive_target) + else: + copy(archive_origin, archive_target) + + extract_archive(archive_target, extract_target, noarchive_ok=True) + + # concurrent processes might have deleted the file + if os.path.isfile(archive_target): + os.remove(archive_target) + + +def extract_archive(filename, target_folder=None, noarchive_ok=False): + from subprocess import run, PIPE + + if filename.endswith('.tgz') or filename.endswith('.tar'): + command = f'tar -xf {filename}' + command += f' -C {target_folder}' if target_folder is not None else '' + elif filename.endswith('.tar.gz'): + command = f'tar -xzf {filename}' + command += f' -C {target_folder}' if target_folder is not None else '' + elif filename.endswith('zip'): + command = f'unzip {filename}' + command += f' -d {target_folder}' if target_folder is not None else '' + else: + if noarchive_ok: + return + else: + raise ValueError(f'unsuppored file ending of {filename}') + + log.hint(command) + result = run(command.split(), stdout=PIPE, stderr=PIPE) + if result.returncode != 0: + print(result.stdout, result.stderr) + + +class AttributeDict(dict): + """ + An extended dictionary that allows access to elements as atttributes and counts + these accesses. This way, we know if some attributes were never used. + """ + + def __init__(self, *args, **kwargs): + from collections import Counter + super().__init__(*args, **kwargs) + self.__dict__['counter'] = Counter() + + def __getitem__(self, k): + self.__dict__['counter'][k] += 1 + return super().__getitem__(k) + + def __getattr__(self, k): + self.__dict__['counter'][k] += 1 + return super().get(k) + + def __setattr__(self, k, v): + return super().__setitem__(k, v) + + def __delattr__(self, k, v): + return super().__delitem__(k, v) + + def unused_keys(self, exceptions=()): + return [k for k in super().keys() if self.__dict__['counter'][k] == 0 and k not in exceptions] + + def assume_no_unused_keys(self, exceptions=()): + if len(self.unused_keys(exceptions=exceptions)) > 0: + log.warning('Unused keys:', self.unused_keys(exceptions=exceptions)) + + +def get_attribute(name): + import importlib + + if name is None: + raise ValueError('The provided attribute is None') + + name_split = name.split('.') + mod = importlib.import_module('.'.join(name_split[:-1])) + return getattr(mod, name_split[-1]) + + + +def filter_args(input_args, default_args): + + updated_args = {k: input_args[k] if k in input_args else v for k, v in default_args.items()} + used_args = {k: v for k, v in input_args.items() if k in default_args} + unused_args = {k: v for k, v in input_args.items() if k not in default_args} + + return AttributeDict(updated_args), AttributeDict(used_args), AttributeDict(unused_args) + + +def load_model(checkpoint_id, weights_file=None, strict=True, model_args='from_config', with_config=False): + + config = json.load(open(join('logs', checkpoint_id, 'config.json'))) + + if model_args != 'from_config' and type(model_args) != dict: + raise ValueError('model_args must either be "from_config" or a dictionary of values') + + model_cls = get_attribute(config['model']) + + # load model + if model_args == 'from_config': + _, model_args, _ = filter_args(config, inspect.signature(model_cls).parameters) + + model = model_cls(**model_args) + + if weights_file is None: + weights_file = realpath(join('logs', checkpoint_id, 'weights.pth')) + else: + weights_file = realpath(join('logs', checkpoint_id, weights_file)) + + if isfile(weights_file): + weights = torch.load(weights_file) + for _, w in weights.items(): + assert not torch.any(torch.isnan(w)), 'weights contain NaNs' + model.load_state_dict(weights, strict=strict) + else: + raise FileNotFoundError(f'model checkpoint {weights_file} was not found') + + if with_config: + return model, config + + return model + + +class TrainingLogger(object): + + def __init__(self, model, log_dir, config=None, *args): + super().__init__() + self.model = model + self.base_path = join(f'logs/{log_dir}') if log_dir is not None else None + + os.makedirs('logs/', exist_ok=True) + os.makedirs(self.base_path, exist_ok=True) + + if config is not None: + json.dump(config, open(join(self.base_path, 'config.json'), 'w')) + + def iter(self, i, **kwargs): + if i % 100 == 0 and 'loss' in kwargs: + loss = kwargs['loss'] + print(f'iteration {i}: loss {loss:.4f}') + + def save_weights(self, only_trainable=False, weight_file='weights.pth'): + if self.model is None: + raise AttributeError('You need to provide a model reference when initializing TrainingTracker to save weights.') + + weights_path = join(self.base_path, weight_file) + + weight_dict = self.model.state_dict() + + if only_trainable: + weight_dict = {n: weight_dict[n] for n, p in self.model.named_parameters() if p.requires_grad} + + torch.save(weight_dict, weights_path) + log.info(f'Saved weights to {weights_path}') + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """ automatically stop processes if used in a context manager """ + pass \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/metrics.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..85473387dd355dd1d9b6b158e1b0431b13a1c1f3 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/metrics.py @@ -0,0 +1,271 @@ +from torch.functional import Tensor +from general_utils import log +from collections import defaultdict +import numpy as np + +import torch +from torch.nn import functional as nnf + + +class BaseMetric(object): + + def __init__(self, metric_names, pred_range=None, gt_index=0, pred_index=0, eval_intermediate=True, + eval_validation=True): + self._names = tuple(metric_names) + self._eval_intermediate = eval_intermediate + self._eval_validation = eval_validation + + self._pred_range = pred_range + self._pred_index = pred_index + self._gt_index = gt_index + + self.predictions = [] + self.ground_truths = [] + + def eval_intermediate(self): + return self._eval_intermediate + + def eval_validation(self): + return self._eval_validation + + def names(self): + return self._names + + def add(self, predictions, ground_truth): + raise NotImplementedError + + def value(self): + raise NotImplementedError + + def scores(self): + # similar to value but returns dict + value = self.value() + if type(value) == dict: + return value + else: + assert type(value) in {list, tuple} + return list(zip(self.names(), self.value())) + + def _get_pred_gt(self, predictions, ground_truth): + pred = predictions[self._pred_index] + gt = ground_truth[self._gt_index] + + if self._pred_range is not None: + pred = pred[:, self._pred_range[0]: self._pred_range[1]] + + return pred, gt + + +class FixedIntervalMetrics(BaseMetric): + + def __init__(self, sigmoid=False, ignore_mask=False, resize_to=None, + resize_pred=None, n_values=51, custom_threshold=None): + + + super().__init__(('ap', 'best_fgiou', 'best_miou', 'fgiou0.5', 'fgiou0.1', 'mean_iou_0p5', 'mean_iou_0p1', 'best_biniou', 'biniou_0.5', 'fgiou_thresh')) + self.intersections = [] + self.unions = [] + # self.threshold = threshold + self.sigmoid = sigmoid + self.resize_to = resize_to + self.resize_pred = resize_pred # resize prediction to match ground truth + self.class_count = defaultdict(lambda: 0) + self.per_class = defaultdict(lambda : [0,0]) + self.ignore_mask = ignore_mask + self.custom_threshold = custom_threshold + + self.scores_ap = [] + self.scores_iou = [] + self.gts, self.preds = [], [] + self.classes = [] + + # [1:-1] ignores 0 and 1 + self.threshold_values = np.linspace(0, 1, n_values)[1:-1] + + self.metrics = dict(tp=[], fp=[], fn=[], tn=[]) + + def add(self, pred, gt): + + pred_batch = pred[0].cpu() + + if self.sigmoid: + pred_batch = torch.sigmoid(pred_batch) + + gt_batch = gt[0].cpu() + mask_batch = gt[1] if len(gt) > 1 and not self.ignore_mask and gt[1].numel() > 0 else ([None] * len(pred_batch)) + cls_batch = gt[2] if len(gt) > 2 else [None] * len(pred_batch) + + if self.resize_to is not None: + gt_batch = nnf.interpolate(gt_batch, self.resize_to, mode='nearest') + pred_batch = nnf.interpolate(pred_batch, self.resize_to, mode='bilinear', align_corners=False) + + if isinstance(cls_batch, torch.Tensor): + cls_batch = cls_batch.cpu().numpy().tolist() + + assert len(gt_batch) == len(pred_batch) == len(cls_batch), f'{len(gt_batch)} {len(pred_batch)} {len(cls_batch)}' + + for predictions, ground_truth, mask, cls in zip(pred_batch, gt_batch, mask_batch, cls_batch): + + if self.resize_pred: + predictions = nnf.interpolate(predictions.unsqueeze(0).float(), size=ground_truth.size()[-2:], mode='bilinear', align_corners=True) + + p = predictions.flatten() + g = ground_truth.flatten() + + assert len(p) == len(g) + + if mask is not None: + m = mask.flatten().bool() + p = p[m] + g = g[m] + + p_sorted = p.sort() + p = p_sorted.values + g = g[p_sorted.indices] + + tps, fps, fns, tns = [], [], [], [] + for thresh in self.threshold_values: + + valid = torch.where(p > thresh)[0] + if len(valid) > 0: + n = int(valid[0]) + else: + n = len(g) + + fn = int(g[:n].sum()) + tp = int(g[n:].sum()) + fns += [fn] + tns += [n - fn] + tps += [tp] + fps += [len(g) - n - tp] + + self.metrics['tp'] += [tps] + self.metrics['fp'] += [fps] + self.metrics['fn'] += [fns] + self.metrics['tn'] += [tns] + + self.classes += [cls.item() if isinstance(cls, torch.Tensor) else cls] + + def value(self): + + import time + t_start = time.time() + + if set(self.classes) == set([None]): + all_classes = None + log.warning('classes were not provided, cannot compute mIoU') + else: + all_classes = set(int(c) for c in self.classes) + # log.info(f'compute metrics for {len(all_classes)} classes') + + summed = {k: [sum([self.metrics[k][i][j] + for i in range(len(self.metrics[k]))]) + for j in range(len(self.threshold_values))] + for k in self.metrics.keys()} + + if all_classes is not None: + + assert len(self.classes) == len(self.metrics['tp']) == len(self.metrics['fn']) + # group by class + metrics_by_class = {c: {k: [] for k in self.metrics.keys()} for c in all_classes} + for i in range(len(self.metrics['tp'])): + for k in self.metrics.keys(): + metrics_by_class[self.classes[i]][k] += [self.metrics[k][i]] + + # sum over all instances within the classes + summed_by_cls = {k: {c: np.array(metrics_by_class[c][k]).sum(0).tolist() for c in all_classes} for k in self.metrics.keys()} + + + # Compute average precision + + assert (np.array(summed['fp']) + np.array(summed['tp']) ).sum(), 'no predictions is made' + + # only consider values where a prediction is made + precisions = [summed['tp'][j] / (1 + summed['tp'][j] + summed['fp'][j]) for j in range(len(self.threshold_values)) + if summed['tp'][j] + summed['fp'][j] > 0] + recalls = [summed['tp'][j] / (1 + summed['tp'][j] + summed['fn'][j]) for j in range(len(self.threshold_values)) + if summed['tp'][j] + summed['fp'][j] > 0] + + # remove duplicate recall-precision-pairs (and sort by recall value) + recalls, precisions = zip(*sorted(list(set(zip(recalls, precisions))), key=lambda x: x[0])) + + from scipy.integrate import simps + ap = simps(precisions, recalls) + + # Compute best IoU + fgiou_scores = [summed['tp'][j] / (1 + summed['tp'][j] + summed['fp'][j] + summed['fn'][j]) for j in range(len(self.threshold_values))] + + biniou_scores = [ + 0.5*(summed['tp'][j] / (1 + summed['tp'][j] + summed['fp'][j] + summed['fn'][j])) + + 0.5*(summed['tn'][j] / (1 + summed['tn'][j] + summed['fn'][j] + summed['fp'][j])) + for j in range(len(self.threshold_values)) + ] + + index_0p5 = self.threshold_values.tolist().index(0.5) + index_0p1 = self.threshold_values.tolist().index(0.1) + index_0p2 = self.threshold_values.tolist().index(0.2) + index_0p3 = self.threshold_values.tolist().index(0.3) + + if self.custom_threshold is not None: + index_ct = self.threshold_values.tolist().index(self.custom_threshold) + + if all_classes is not None: + # mean IoU + mean_ious = [np.mean([summed_by_cls['tp'][c][j] / (1 + summed_by_cls['tp'][c][j] + summed_by_cls['fp'][c][j] + summed_by_cls['fn'][c][j]) + for c in all_classes]) + for j in range(len(self.threshold_values))] + + mean_iou_dict = { + 'miou_best': max(mean_ious) if all_classes is not None else None, + 'miou_0.5': mean_ious[index_0p5] if all_classes is not None else None, + 'miou_0.1': mean_ious[index_0p1] if all_classes is not None else None, + 'miou_0.2': mean_ious[index_0p2] if all_classes is not None else None, + 'miou_0.3': mean_ious[index_0p3] if all_classes is not None else None, + 'miou_best_t': self.threshold_values[np.argmax(mean_ious)], + 'mean_iou_ct': mean_ious[index_ct] if all_classes is not None and self.custom_threshold is not None else None, + 'mean_iou_scores': mean_ious, + } + + print(f'metric computation on {(len(all_classes) if all_classes is not None else "no")} classes took {time.time() - t_start:.1f}s') + + return { + 'ap': ap, + + # fgiou + 'fgiou_best': max(fgiou_scores), + 'fgiou_0.5': fgiou_scores[index_0p5], + 'fgiou_0.1': fgiou_scores[index_0p1], + 'fgiou_0.2': fgiou_scores[index_0p2], + 'fgiou_0.3': fgiou_scores[index_0p3], + 'fgiou_best_t': self.threshold_values[np.argmax(fgiou_scores)], + + # mean iou + + + # biniou + 'biniou_best': max(biniou_scores), + 'biniou_0.5': biniou_scores[index_0p5], + 'biniou_0.1': biniou_scores[index_0p1], + 'biniou_0.2': biniou_scores[index_0p2], + 'biniou_0.3': biniou_scores[index_0p3], + 'biniou_best_t': self.threshold_values[np.argmax(biniou_scores)], + + # custom threshold + 'fgiou_ct': fgiou_scores[index_ct] if self.custom_threshold is not None else None, + 'biniou_ct': biniou_scores[index_ct] if self.custom_threshold is not None else None, + 'ct': self.custom_threshold, + + # statistics + 'fgiou_scores': fgiou_scores, + 'biniou_scores': biniou_scores, + 'precision_recall_curve': sorted(list(set(zip(recalls, precisions)))), + 'summed_statistics': summed, + 'summed_by_cls_statistics': summed_by_cls, + + **mean_iou_dict + } + + # ('ap', 'best_fgiou', 'best_miou', 'fgiou0.5', 'fgiou0.1', 'mean_iou_0p5', 'mean_iou_0p1', 'best_biniou', 'biniou_0.5', 'fgiou_thresh' + + # return ap, best_fgiou, best_mean_iou, iou_0p5, iou_0p1, mean_iou_0p5, mean_iou_0p1, best_biniou, biniou0p5, best_fgiou_thresh, {'summed': summed, 'summed_by_cls': summed_by_cls} + diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/models/clipseg.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/models/clipseg.py new file mode 100644 index 0000000000000000000000000000000000000000..430953620b0737a2db5cf6ccd9a8f98d6f518feb --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/models/clipseg.py @@ -0,0 +1,552 @@ +import math +from os.path import basename, dirname, join, isfile +import torch +from torch import nn +from torch.nn import functional as nnf +from torch.nn.modules.activation import ReLU + + +def precompute_clip_vectors(): + + from trails.initialization import init_dataset + lvis = init_dataset('LVIS_OneShot3', split='train', mask='text_label', image_size=224, aug=1, normalize=True, + reduce_factor=None, add_bar=False, negative_prob=0.5) + + all_names = list(lvis.category_names.values()) + + import clip + from models.clip_prompts import imagenet_templates + clip_model = clip.load("ViT-B/32", device='cuda', jit=False)[0] + prompt_vectors = {} + for name in all_names[:100]: + with torch.no_grad(): + conditionals = [t.format(name).replace('_', ' ') for t in imagenet_templates] + text_tokens = clip.tokenize(conditionals).cuda() + cond = clip_model.encode_text(text_tokens).cpu() + + for cond, vec in zip(conditionals, cond): + prompt_vectors[cond] = vec.cpu() + + import pickle + + pickle.dump(prompt_vectors, open('precomputed_prompt_vectors.pickle', 'wb')) + + +def get_prompt_list(prompt): + if prompt == 'plain': + return ['{}'] + elif prompt == 'fixed': + return ['a photo of a {}.'] + elif prompt == 'shuffle': + return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.'] + elif prompt == 'shuffle+': + return ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.', + 'a cropped photo of a {}.', 'a good photo of a {}.', 'a photo of one {}.', + 'a bad photo of a {}.', 'a photo of the {}.'] + elif prompt == 'shuffle_clip': + from models.clip_prompts import imagenet_templates + return imagenet_templates + else: + raise ValueError('Invalid value for prompt') + + +def forward_multihead_attention(x, b, with_aff=False, attn_mask=None): + """ + Simplified version of multihead attention (taken from torch source code but without tons of if clauses). + The mlp and layer norm come from CLIP. + x: input. + b: multihead attention module. + """ + + x_ = b.ln_1(x) + q, k, v = nnf.linear(x_, b.attn.in_proj_weight, b.attn.in_proj_bias).chunk(3, dim=-1) + tgt_len, bsz, embed_dim = q.size() + + head_dim = embed_dim // b.attn.num_heads + scaling = float(head_dim) ** -0.5 + + q = q.contiguous().view(tgt_len, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1) + k = k.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1) + v = v.contiguous().view(-1, bsz * b.attn.num_heads, b.attn.head_dim).transpose(0, 1) + + q = q * scaling + + attn_output_weights = torch.bmm(q, k.transpose(1, 2)) # n_heads * batch_size, tokens^2, tokens^2 + if attn_mask is not None: + + + attn_mask_type, attn_mask = attn_mask + n_heads = attn_output_weights.size(0) // attn_mask.size(0) + attn_mask = attn_mask.repeat(n_heads, 1) + + if attn_mask_type == 'cls_token': + # the mask only affects similarities compared to the readout-token. + attn_output_weights[:, 0, 1:] = attn_output_weights[:, 0, 1:] * attn_mask[None,...] + # attn_output_weights[:, 0, 0] = 0*attn_output_weights[:, 0, 0] + + if attn_mask_type == 'all': + # print(attn_output_weights.shape, attn_mask[:, None].shape) + attn_output_weights[:, 1:, 1:] = attn_output_weights[:, 1:, 1:] * attn_mask[:, None] + + + attn_output_weights = torch.softmax(attn_output_weights, dim=-1) + + attn_output = torch.bmm(attn_output_weights, v) + attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) + attn_output = b.attn.out_proj(attn_output) + + x = x + attn_output + x = x + b.mlp(b.ln_2(x)) + + if with_aff: + return x, attn_output_weights + else: + return x + + +class CLIPDenseBase(nn.Module): + + def __init__(self, version, reduce_cond, reduce_dim, prompt, n_tokens): + super().__init__() + + import clip + + # prec = torch.FloatTensor + self.clip_model, _ = clip.load(version, device='cpu', jit=False) + self.model = self.clip_model.visual + + # if not None, scale conv weights such that we obtain n_tokens. + self.n_tokens = n_tokens + + for p in self.clip_model.parameters(): + p.requires_grad_(False) + + # conditional + if reduce_cond is not None: + self.reduce_cond = nn.Linear(512, reduce_cond) + for p in self.reduce_cond.parameters(): + p.requires_grad_(False) + else: + self.reduce_cond = None + + self.film_mul = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim) + self.film_add = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim) + + self.reduce = nn.Linear(768, reduce_dim) + + self.prompt_list = get_prompt_list(prompt) + + # precomputed prompts + import pickle + if isfile('precomputed_prompt_vectors.pickle'): + precomp = pickle.load(open('precomputed_prompt_vectors.pickle', 'rb')) + self.precomputed_prompts = {k: torch.from_numpy(v) for k, v in precomp.items()} + else: + self.precomputed_prompts = dict() + + def rescaled_pos_emb(self, new_size): + assert len(new_size) == 2 + + a = self.model.positional_embedding[1:].T.view(1, 768, *self.token_shape) + b = nnf.interpolate(a, new_size, mode='bicubic', align_corners=False).squeeze(0).view(768, new_size[0]*new_size[1]).T + return torch.cat([self.model.positional_embedding[:1], b]) + + def visual_forward(self, x_inp, extract_layers=(), skip=False, mask=None): + + + with torch.no_grad(): + + inp_size = x_inp.shape[2:] + + if self.n_tokens is not None: + stride2 = x_inp.shape[2] // self.n_tokens + conv_weight2 = nnf.interpolate(self.model.conv1.weight, (stride2, stride2), mode='bilinear', align_corners=True) + x = nnf.conv2d(x_inp, conv_weight2, bias=self.model.conv1.bias, stride=stride2, dilation=self.model.conv1.dilation) + else: + x = self.model.conv1(x_inp) # shape = [*, width, grid, grid] + + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + + x = torch.cat([self.model.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width] + + standard_n_tokens = 50 if self.model.conv1.kernel_size[0] == 32 else 197 + + if x.shape[1] != standard_n_tokens: + new_shape = int(math.sqrt(x.shape[1]-1)) + x = x + self.rescaled_pos_emb((new_shape, new_shape)).to(x.dtype)[None,:,:] + else: + x = x + self.model.positional_embedding.to(x.dtype) + + x = self.model.ln_pre(x) + + x = x.permute(1, 0, 2) # NLD -> LND + + activations, affinities = [], [] + for i, res_block in enumerate(self.model.transformer.resblocks): + + if mask is not None: + mask_layer, mask_type, mask_tensor = mask + if mask_layer == i or mask_layer == 'all': + # import ipdb; ipdb.set_trace() + size = int(math.sqrt(x.shape[0] - 1)) + + attn_mask = (mask_type, nnf.interpolate(mask_tensor.unsqueeze(1).float(), (size, size)).view(mask_tensor.shape[0], size * size)) + + else: + attn_mask = None + else: + attn_mask = None + + x, aff_per_head = forward_multihead_attention(x, res_block, with_aff=True, attn_mask=attn_mask) + + if i in extract_layers: + affinities += [aff_per_head] + + #if self.n_tokens is not None: + # activations += [nnf.interpolate(x, inp_size, mode='bilinear', align_corners=True)] + #else: + activations += [x] + + if len(extract_layers) > 0 and i == max(extract_layers) and skip: + print('early skip') + break + + x = x.permute(1, 0, 2) # LND -> NLD + x = self.model.ln_post(x[:, 0, :]) + + if self.model.proj is not None: + x = x @ self.model.proj + + return x, activations, affinities + + def sample_prompts(self, words, prompt_list=None): + + prompt_list = prompt_list if prompt_list is not None else self.prompt_list + + prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True) + prompts = [prompt_list[i] for i in prompt_indices] + return [promt.format(w) for promt, w in zip(prompts, words)] + + def get_cond_vec(self, conditional, batch_size): + # compute conditional from a single string + if conditional is not None and type(conditional) == str: + cond = self.compute_conditional(conditional) + cond = cond.repeat(batch_size, 1) + + # compute conditional from string list/tuple + elif conditional is not None and type(conditional) in {list, tuple} and type(conditional[0]) == str: + assert len(conditional) == batch_size + cond = self.compute_conditional(conditional) + + # use conditional directly + elif conditional is not None and type(conditional) == torch.Tensor and conditional.ndim == 2: + cond = conditional + + # compute conditional from image + elif conditional is not None and type(conditional) == torch.Tensor: + with torch.no_grad(): + cond, _, _ = self.visual_forward(conditional) + else: + raise ValueError('invalid conditional') + return cond + + def compute_conditional(self, conditional): + import clip + + dev = next(self.parameters()).device + + if type(conditional) in {list, tuple}: + text_tokens = clip.tokenize(conditional).to(dev) + cond = self.clip_model.encode_text(text_tokens) + else: + if conditional in self.precomputed_prompts: + cond = self.precomputed_prompts[conditional].float().to(dev) + else: + text_tokens = clip.tokenize([conditional]).to(dev) + cond = self.clip_model.encode_text(text_tokens)[0] + + if self.shift_vector is not None: + return cond + self.shift_vector + else: + return cond + + +def clip_load_untrained(version): + assert version == 'ViT-B/16' + from clip.model import CLIP + from clip.clip import _MODELS, _download + model = torch.jit.load(_download(_MODELS['ViT-B/16'])).eval() + state_dict = model.state_dict() + + vision_width = state_dict["visual.conv1.weight"].shape[0] + vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) + vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] + grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) + image_resolution = vision_patch_size * grid_size + embed_dim = state_dict["text_projection"].shape[1] + context_length = state_dict["positional_embedding"].shape[0] + vocab_size = state_dict["token_embedding.weight"].shape[0] + transformer_width = state_dict["ln_final.weight"].shape[0] + transformer_heads = transformer_width // 64 + transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks"))) + + return CLIP(embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size, + context_length, vocab_size, transformer_width, transformer_heads, transformer_layers) + + +class CLIPDensePredT(CLIPDenseBase): + + def __init__(self, version='ViT-B/32', extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4, prompt='fixed', + extra_blocks=0, reduce_cond=None, fix_shift=False, + learn_trans_conv_only=False, limit_to_clip_only=False, upsample=False, + add_calibration=False, rev_activations=False, trans_conv=None, n_tokens=None): + + super().__init__(version, reduce_cond, reduce_dim, prompt, n_tokens) + # device = 'cpu' + + self.extract_layers = extract_layers + self.cond_layer = cond_layer + self.limit_to_clip_only = limit_to_clip_only + self.process_cond = None + self.rev_activations = rev_activations + + depth = len(extract_layers) + + if add_calibration: + self.calibration_conds = 1 + + self.upsample_proj = nn.Conv2d(reduce_dim, 1, kernel_size=1) if upsample else None + + self.add_activation1 = True + + self.version = version + + self.token_shape = {'ViT-B/32': (7, 7), 'ViT-B/16': (14, 14)}[version] + + if fix_shift: + # self.shift_vector = nn.Parameter(torch.load(join(dirname(basename(__file__)), 'clip_text_shift_vector.pth')), requires_grad=False) + self.shift_vector = nn.Parameter(torch.load(join(dirname(basename(__file__)), 'shift_text_to_vis.pth')), requires_grad=False) + # self.shift_vector = nn.Parameter(-1*torch.load(join(dirname(basename(__file__)), 'shift2.pth')), requires_grad=False) + else: + self.shift_vector = None + + if trans_conv is None: + trans_conv_ks = {'ViT-B/32': (32, 32), 'ViT-B/16': (16, 16)}[version] + else: + # explicitly define transposed conv kernel size + trans_conv_ks = (trans_conv, trans_conv) + + self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks) + + assert len(self.extract_layers) == depth + + self.reduces = nn.ModuleList([nn.Linear(768, reduce_dim) for _ in range(depth)]) + self.blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(len(self.extract_layers))]) + self.extra_blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(extra_blocks)]) + + # refinement and trans conv + + if learn_trans_conv_only: + for p in self.parameters(): + p.requires_grad_(False) + + for p in self.trans_conv.parameters(): + p.requires_grad_(True) + + self.prompt_list = get_prompt_list(prompt) + + + def forward(self, inp_image, conditional=None, return_features=False, mask=None): + + assert type(return_features) == bool + + inp_image = inp_image.to(self.model.positional_embedding.device) + + if mask is not None: + raise ValueError('mask not supported') + + # x_inp = normalize(inp_image) + x_inp = inp_image + + bs, dev = inp_image.shape[0], x_inp.device + + cond = self.get_cond_vec(conditional, bs) + + visual_q, activations, _ = self.visual_forward(x_inp, extract_layers=[0] + list(self.extract_layers)) + + activation1 = activations[0] + activations = activations[1:] + + _activations = activations[::-1] if not self.rev_activations else activations + + a = None + for i, (activation, block, reduce) in enumerate(zip(_activations, self.blocks, self.reduces)): + + if a is not None: + a = reduce(activation) + a + else: + a = reduce(activation) + + if i == self.cond_layer: + if self.reduce_cond is not None: + cond = self.reduce_cond(cond) + + a = self.film_mul(cond) * a + self.film_add(cond) + + a = block(a) + + for block in self.extra_blocks: + a = a + block(a) + + a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens + + size = int(math.sqrt(a.shape[2])) + + a = a.view(bs, a.shape[1], size, size) + + a = self.trans_conv(a) + + if self.n_tokens is not None: + a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear', align_corners=True) + + if self.upsample_proj is not None: + a = self.upsample_proj(a) + a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear') + + if return_features: + return a, visual_q, cond, [activation1] + activations + else: + return a, + + + +class CLIPDensePredTMasked(CLIPDensePredT): + + def __init__(self, version='ViT-B/32', extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4, + prompt='fixed', extra_blocks=0, reduce_cond=None, fix_shift=False, learn_trans_conv_only=False, + refine=None, limit_to_clip_only=False, upsample=False, add_calibration=False, n_tokens=None): + + super().__init__(version=version, extract_layers=extract_layers, cond_layer=cond_layer, reduce_dim=reduce_dim, + n_heads=n_heads, prompt=prompt, extra_blocks=extra_blocks, reduce_cond=reduce_cond, + fix_shift=fix_shift, learn_trans_conv_only=learn_trans_conv_only, + limit_to_clip_only=limit_to_clip_only, upsample=upsample, add_calibration=add_calibration, + n_tokens=n_tokens) + + def visual_forward_masked(self, img_s, seg_s): + return super().visual_forward(img_s, mask=('all', 'cls_token', seg_s)) + + def forward(self, img_q, cond_or_img_s, seg_s=None, return_features=False): + + if seg_s is None: + cond = cond_or_img_s + else: + img_s = cond_or_img_s + + with torch.no_grad(): + cond, _, _ = self.visual_forward_masked(img_s, seg_s) + + return super().forward(img_q, cond, return_features=return_features) + + + +class CLIPDenseBaseline(CLIPDenseBase): + + def __init__(self, version='ViT-B/32', cond_layer=0, + extract_layer=9, reduce_dim=128, reduce2_dim=None, prompt='fixed', + reduce_cond=None, limit_to_clip_only=False, n_tokens=None): + + super().__init__(version, reduce_cond, reduce_dim, prompt, n_tokens) + device = 'cpu' + + # self.cond_layer = cond_layer + self.extract_layer = extract_layer + self.limit_to_clip_only = limit_to_clip_only + self.shift_vector = None + + self.token_shape = {'ViT-B/32': (7, 7), 'ViT-B/16': (14, 14)}[version] + + assert reduce2_dim is not None + + self.reduce2 = nn.Sequential( + nn.Linear(reduce_dim, reduce2_dim), + nn.ReLU(), + nn.Linear(reduce2_dim, reduce_dim) + ) + + trans_conv_ks = {'ViT-B/32': (32, 32), 'ViT-B/16': (16, 16)}[version] + self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks) + + + def forward(self, inp_image, conditional=None, return_features=False): + + inp_image = inp_image.to(self.model.positional_embedding.device) + + # x_inp = normalize(inp_image) + x_inp = inp_image + + bs, dev = inp_image.shape[0], x_inp.device + + cond = self.get_cond_vec(conditional, bs) + + visual_q, activations, affinities = self.visual_forward(x_inp, extract_layers=[self.extract_layer]) + + a = activations[0] + a = self.reduce(a) + a = self.film_mul(cond) * a + self.film_add(cond) + + if self.reduce2 is not None: + a = self.reduce2(a) + + # the original model would execute a transformer block here + + a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens + + size = int(math.sqrt(a.shape[2])) + + a = a.view(bs, a.shape[1], size, size) + a = self.trans_conv(a) + + if return_features: + return a, visual_q, cond, activations + else: + return a, + + +class CLIPSegMultiLabel(nn.Module): + + def __init__(self, model) -> None: + super().__init__() + + from third_party.JoEm.data_loader import get_seen_idx, get_unseen_idx, VOC + + self.pascal_classes = VOC + + from models.clipseg import CLIPDensePredT + from general_utils import load_model + # self.clipseg = load_model('rd64-vit16-neg0.2-phrasecut', strict=False) + self.clipseg = load_model(model, strict=False) + + self.clipseg.eval() + + def forward(self, x): + + bs = x.shape[0] + out = torch.ones(21, bs, 352, 352).to(x.device) * -10 + + for class_id, class_name in enumerate(self.pascal_classes): + + fac = 3 if class_name == 'background' else 1 + + with torch.no_grad(): + pred = torch.sigmoid(self.clipseg(x, class_name)[0][:,0]) * fac + + out[class_id] += pred + + + out = out.permute(1, 0, 2, 3) + + return out + + # construct output tensor + \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/models/vitseg.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/models/vitseg.py new file mode 100644 index 0000000000000000000000000000000000000000..d3231e5b6ecb81863eec0c021865ea52e9b70a15 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/models/vitseg.py @@ -0,0 +1,286 @@ +import math +from posixpath import basename, dirname, join +# import clip +from clip.model import convert_weights +import torch +import json +from torch import nn +from torch.nn import functional as nnf +from torch.nn.modules import activation +from torch.nn.modules.activation import ReLU +from torchvision import transforms + +normalize = transforms.Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711)) + +from torchvision.models import ResNet + + +def process_prompts(conditional, prompt_list, conditional_map): + # DEPRECATED + + # randomly sample a synonym + words = [conditional_map[int(i)] for i in conditional] + words = [syns[torch.multinomial(torch.ones(len(syns)), 1, replacement=True).item()] for syns in words] + words = [w.replace('_', ' ') for w in words] + + if prompt_list is not None: + prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True) + prompts = [prompt_list[i] for i in prompt_indices] + else: + prompts = ['a photo of {}'] * (len(words)) + + return [promt.format(w) for promt, w in zip(prompts, words)] + + +class VITDenseBase(nn.Module): + + def rescaled_pos_emb(self, new_size): + assert len(new_size) == 2 + + a = self.model.positional_embedding[1:].T.view(1, 768, *self.token_shape) + b = nnf.interpolate(a, new_size, mode='bicubic', align_corners=False).squeeze(0).view(768, new_size[0]*new_size[1]).T + return torch.cat([self.model.positional_embedding[:1], b]) + + def visual_forward(self, x_inp, extract_layers=(), skip=False, mask=None): + + with torch.no_grad(): + + x_inp = nnf.interpolate(x_inp, (384, 384)) + + x = self.model.patch_embed(x_inp) + cls_token = self.model.cls_token.expand(x.shape[0], -1, -1) # stole cls_tokens impl from Phil Wang, thanks + if self.model.dist_token is None: + x = torch.cat((cls_token, x), dim=1) + else: + x = torch.cat((cls_token, self.model.dist_token.expand(x.shape[0], -1, -1), x), dim=1) + x = self.model.pos_drop(x + self.model.pos_embed) + + activations = [] + for i, block in enumerate(self.model.blocks): + x = block(x) + + if i in extract_layers: + # permute to be compatible with CLIP + activations += [x.permute(1,0,2)] + + x = self.model.norm(x) + x = self.model.head(self.model.pre_logits(x[:, 0])) + + # again for CLIP compatibility + # x = x.permute(1, 0, 2) + + return x, activations, None + + def sample_prompts(self, words, prompt_list=None): + + prompt_list = prompt_list if prompt_list is not None else self.prompt_list + + prompt_indices = torch.multinomial(torch.ones(len(prompt_list)), len(words), replacement=True) + prompts = [prompt_list[i] for i in prompt_indices] + return [promt.format(w) for promt, w in zip(prompts, words)] + + def get_cond_vec(self, conditional, batch_size): + # compute conditional from a single string + if conditional is not None and type(conditional) == str: + cond = self.compute_conditional(conditional) + cond = cond.repeat(batch_size, 1) + + # compute conditional from string list/tuple + elif conditional is not None and type(conditional) in {list, tuple} and type(conditional[0]) == str: + assert len(conditional) == batch_size + cond = self.compute_conditional(conditional) + + # use conditional directly + elif conditional is not None and type(conditional) == torch.Tensor and conditional.ndim == 2: + cond = conditional + + # compute conditional from image + elif conditional is not None and type(conditional) == torch.Tensor: + with torch.no_grad(): + cond, _, _ = self.visual_forward(conditional) + else: + raise ValueError('invalid conditional') + return cond + + def compute_conditional(self, conditional): + import clip + + dev = next(self.parameters()).device + + if type(conditional) in {list, tuple}: + text_tokens = clip.tokenize(conditional).to(dev) + cond = self.clip_model.encode_text(text_tokens) + else: + if conditional in self.precomputed_prompts: + cond = self.precomputed_prompts[conditional].float().to(dev) + else: + text_tokens = clip.tokenize([conditional]).to(dev) + cond = self.clip_model.encode_text(text_tokens)[0] + + return cond + + +class VITDensePredT(VITDenseBase): + + def __init__(self, extract_layers=(3, 6, 9), cond_layer=0, reduce_dim=128, n_heads=4, prompt='fixed', + depth=3, extra_blocks=0, reduce_cond=None, fix_shift=False, + learn_trans_conv_only=False, refine=None, limit_to_clip_only=False, upsample=False, + add_calibration=False, process_cond=None, not_pretrained=False): + super().__init__() + # device = 'cpu' + + self.extract_layers = extract_layers + self.cond_layer = cond_layer + self.limit_to_clip_only = limit_to_clip_only + self.process_cond = None + + if add_calibration: + self.calibration_conds = 1 + + self.upsample_proj = nn.Conv2d(reduce_dim, 1, kernel_size=1) if upsample else None + + self.add_activation1 = True + + import timm + self.model = timm.create_model('vit_base_patch16_384', pretrained=True) + self.model.head = nn.Linear(768, 512 if reduce_cond is None else reduce_cond) + + for p in self.model.parameters(): + p.requires_grad_(False) + + import clip + self.clip_model, _ = clip.load('ViT-B/16', device='cpu', jit=False) + # del self.clip_model.visual + + + self.token_shape = (14, 14) + + # conditional + if reduce_cond is not None: + self.reduce_cond = nn.Linear(512, reduce_cond) + for p in self.reduce_cond.parameters(): + p.requires_grad_(False) + else: + self.reduce_cond = None + + # self.film = AVAILABLE_BLOCKS['film'](512, 128) + self.film_mul = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim) + self.film_add = nn.Linear(512 if reduce_cond is None else reduce_cond, reduce_dim) + + # DEPRECATED + # self.conditional_map = {c['id']: c['synonyms'] for c in json.load(open(cond_map))} + + assert len(self.extract_layers) == depth + + self.reduces = nn.ModuleList([nn.Linear(768, reduce_dim) for _ in range(depth)]) + self.blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(len(self.extract_layers))]) + self.extra_blocks = nn.ModuleList([nn.TransformerEncoderLayer(d_model=reduce_dim, nhead=n_heads) for _ in range(extra_blocks)]) + + trans_conv_ks = (16, 16) + self.trans_conv = nn.ConvTranspose2d(reduce_dim, 1, trans_conv_ks, stride=trans_conv_ks) + + # refinement and trans conv + + if learn_trans_conv_only: + for p in self.parameters(): + p.requires_grad_(False) + + for p in self.trans_conv.parameters(): + p.requires_grad_(True) + + if prompt == 'fixed': + self.prompt_list = ['a photo of a {}.'] + elif prompt == 'shuffle': + self.prompt_list = ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.'] + elif prompt == 'shuffle+': + self.prompt_list = ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.', + 'a cropped photo of a {}.', 'a good photo of a {}.', 'a photo of one {}.', + 'a bad photo of a {}.', 'a photo of the {}.'] + elif prompt == 'shuffle_clip': + from models.clip_prompts import imagenet_templates + self.prompt_list = imagenet_templates + + if process_cond is not None: + if process_cond == 'clamp' or process_cond[0] == 'clamp': + + val = process_cond[1] if type(process_cond) in {list, tuple} else 0.2 + + def clamp_vec(x): + return torch.clamp(x, -val, val) + + self.process_cond = clamp_vec + + elif process_cond.endswith('.pth'): + + shift = torch.load(process_cond) + def add_shift(x): + return x + shift.to(x.device) + + self.process_cond = add_shift + + import pickle + precomp = pickle.load(open('precomputed_prompt_vectors.pickle', 'rb')) + self.precomputed_prompts = {k: torch.from_numpy(v) for k, v in precomp.items()} + + + def forward(self, inp_image, conditional=None, return_features=False, mask=None): + + assert type(return_features) == bool + + # inp_image = inp_image.to(self.model.positional_embedding.device) + + if mask is not None: + raise ValueError('mask not supported') + + # x_inp = normalize(inp_image) + x_inp = inp_image + + bs, dev = inp_image.shape[0], x_inp.device + + inp_image_size = inp_image.shape[2:] + + cond = self.get_cond_vec(conditional, bs) + + visual_q, activations, _ = self.visual_forward(x_inp, extract_layers=[0] + list(self.extract_layers)) + + activation1 = activations[0] + activations = activations[1:] + + a = None + for i, (activation, block, reduce) in enumerate(zip(activations[::-1], self.blocks, self.reduces)): + + if a is not None: + a = reduce(activation) + a + else: + a = reduce(activation) + + if i == self.cond_layer: + if self.reduce_cond is not None: + cond = self.reduce_cond(cond) + + a = self.film_mul(cond) * a + self.film_add(cond) + + a = block(a) + + for block in self.extra_blocks: + a = a + block(a) + + a = a[1:].permute(1, 2, 0) # rm cls token and -> BS, Feats, Tokens + + size = int(math.sqrt(a.shape[2])) + + a = a.view(bs, a.shape[1], size, size) + + if self.trans_conv is not None: + a = self.trans_conv(a) + + if self.upsample_proj is not None: + a = self.upsample_proj(a) + a = nnf.interpolate(a, x_inp.shape[2:], mode='bilinear') + + a = nnf.interpolate(a, inp_image_size) + + if return_features: + return a, visual_q, cond, [activation1] + activations + else: + return a, diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/overview.png b/extensions/deforum/scripts/deforum_helpers/src/clipseg/overview.png new file mode 100644 index 0000000000000000000000000000000000000000..1f77bc7743746108fa34bfbaa6e9e8c4db213c8c --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/overview.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c46050cecb3068b9b4b263458b5d0da154a95a7a47b8ce312ba402f0dda3cbfe +size 53964 diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/score.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/score.py new file mode 100644 index 0000000000000000000000000000000000000000..944f17d3978919f63cca7f8c16274bb3b1dd8c79 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/score.py @@ -0,0 +1,453 @@ +from torch.functional import Tensor + +import torch +import inspect +import json +import yaml +import time +import sys + +from general_utils import log + +import numpy as np +from os.path import expanduser, join, isfile, realpath + +from torch.utils.data import DataLoader + +from metrics import FixedIntervalMetrics + +from general_utils import load_model, log, score_config_from_cli_args, AttributeDict, get_attribute, filter_args + + +DATASET_CACHE = dict() + +def load_model(checkpoint_id, weights_file=None, strict=True, model_args='from_config', with_config=False, ignore_weights=False): + + config = json.load(open(join('logs', checkpoint_id, 'config.json'))) + + if model_args != 'from_config' and type(model_args) != dict: + raise ValueError('model_args must either be "from_config" or a dictionary of values') + + model_cls = get_attribute(config['model']) + + # load model + if model_args == 'from_config': + _, model_args, _ = filter_args(config, inspect.signature(model_cls).parameters) + + model = model_cls(**model_args) + + if weights_file is None: + weights_file = realpath(join('logs', checkpoint_id, 'weights.pth')) + else: + weights_file = realpath(join('logs', checkpoint_id, weights_file)) + + if isfile(weights_file) and not ignore_weights: + weights = torch.load(weights_file) + for _, w in weights.items(): + assert not torch.any(torch.isnan(w)), 'weights contain NaNs' + model.load_state_dict(weights, strict=strict) + else: + if not ignore_weights: + raise FileNotFoundError(f'model checkpoint {weights_file} was not found') + + if with_config: + return model, config + + return model + + +def compute_shift2(model, datasets, seed=123, repetitions=1): + """ computes shift """ + + model.eval() + model.cuda() + + import random + random.seed(seed) + + preds, gts = [], [] + for i_dataset, dataset in enumerate(datasets): + + loader = DataLoader(dataset, batch_size=1, num_workers=0, shuffle=False, drop_last=False) + + max_iterations = int(repetitions * len(dataset.dataset.data_list)) + + with torch.no_grad(): + + i, losses = 0, [] + for i_all, (data_x, data_y) in enumerate(loader): + + data_x = [v.cuda(non_blocking=True) if v is not None else v for v in data_x] + data_y = [v.cuda(non_blocking=True) if v is not None else v for v in data_y] + + pred, = model(data_x[0], data_x[1], data_x[2]) + preds += [pred.detach()] + gts += [data_y] + + i += 1 + if max_iterations and i >= max_iterations: + break + + from metrics import FixedIntervalMetrics + n_values = 51 + thresholds = np.linspace(0, 1, n_values)[1:-1] + metric = FixedIntervalMetrics(resize_pred=True, sigmoid=True, n_values=n_values) + + for p, y in zip(preds, gts): + metric.add(p.unsqueeze(1), y) + + best_idx = np.argmax(metric.value()['fgiou_scores']) + best_thresh = thresholds[best_idx] + + return best_thresh + + +def get_cached_pascal_pfe(split, config): + from datasets.pfe_dataset import PFEPascalWrapper + try: + dataset = DATASET_CACHE[(split, config.image_size, config.label_support, config.mask)] + except KeyError: + dataset = PFEPascalWrapper(mode='val', split=split, mask=config.mask, image_size=config.image_size, label_support=config.label_support) + DATASET_CACHE[(split, config.image_size, config.label_support, config.mask)] = dataset + return dataset + + + + +def main(): + config, train_checkpoint_id = score_config_from_cli_args() + + metrics = score(config, train_checkpoint_id, None) + + for dataset in metrics.keys(): + for k in metrics[dataset]: + if type(metrics[dataset][k]) in {float, int}: + print(dataset, f'{k:<16} {metrics[dataset][k]:.3f}') + + +def score(config, train_checkpoint_id, train_config): + + config = AttributeDict(config) + + print(config) + + # use training dataset and loss + train_config = AttributeDict(json.load(open(f'logs/{train_checkpoint_id}/config.json'))) + + cp_str = f'_{config.iteration_cp}' if config.iteration_cp is not None else '' + + + model_cls = get_attribute(train_config['model']) + + _, model_args, _ = filter_args(train_config, inspect.signature(model_cls).parameters) + + model_args = {**model_args, **{k: config[k] for k in ['process_cond', 'fix_shift'] if k in config}} + + strict_models = {'ConditionBase4', 'PFENetWrapper'} + model = load_model(train_checkpoint_id, strict=model_cls.__name__ in strict_models, model_args=model_args, + weights_file=f'weights{cp_str}.pth', ) + + + model.eval() + model.cuda() + + metric_args = dict() + + if 'threshold' in config: + if config.metric.split('.')[-1] == 'SkLearnMetrics': + metric_args['threshold'] = config.threshold + + if 'resize_to' in config: + metric_args['resize_to'] = config.resize_to + + if 'sigmoid' in config: + metric_args['sigmoid'] = config.sigmoid + + if 'custom_threshold' in config: + metric_args['custom_threshold'] = config.custom_threshold + + if config.test_dataset == 'pascal': + + loss_fn = get_attribute(train_config.loss) + # assume that if no split is specified in train_config, test on all splits, + + if 'splits' in config: + splits = config.splits + else: + if 'split' in train_config and type(train_config.split) == int: + # unless train_config has a split set, in that case assume train mode in training + splits = [train_config.split] + assert train_config.mode == 'train' + else: + splits = [0,1,2,3] + + log.info('Test on these splits', splits) + + scores = dict() + for split in splits: + + shift = config.shift if 'shift' in config else 0 + + # automatic shift + if shift == 'auto': + shift_compute_t = time.time() + shift = compute_shift2(model, [get_cached_pascal_pfe(s, config) for s in range(4) if s != split], repetitions=config.compute_shift_fac) + log.info(f'Best threshold is {shift}, computed on splits: {[s for s in range(4) if s != split]}, took {time.time() - shift_compute_t:.1f}s') + + dataset = get_cached_pascal_pfe(split, config) + + eval_start_t = time.time() + + loader = DataLoader(dataset, batch_size=1, num_workers=0, shuffle=False, drop_last=False) + + assert config.batch_size is None or config.batch_size == 1, 'When PFE Dataset is used, batch size must be 1' + + metric = FixedIntervalMetrics(resize_pred=True, sigmoid=True, custom_threshold=shift, **metric_args) + + with torch.no_grad(): + + i, losses = 0, [] + for i_all, (data_x, data_y) in enumerate(loader): + + data_x = [v.cuda(non_blocking=True) if isinstance(v, torch.Tensor) else v for v in data_x] + data_y = [v.cuda(non_blocking=True) if isinstance(v, torch.Tensor) else v for v in data_y] + + if config.mask == 'separate': # for old CondBase model + pred, = model(data_x[0], data_x[1], data_x[2]) + else: + # assert config.mask in {'text', 'highlight'} + pred, _, _, _ = model(data_x[0], data_x[1], return_features=True) + + # loss = loss_fn(pred, data_y[0]) + metric.add(pred.unsqueeze(1) + shift, data_y) + + # losses += [float(loss)] + + i += 1 + if config.max_iterations and i >= config.max_iterations: + break + + #scores[split] = {m: s for m, s in zip(metric.names(), metric.value())} + + log.info(f'Dataset length: {len(dataset)}, took {time.time() - eval_start_t:.1f}s to evaluate.') + + print(metric.value()['mean_iou_scores']) + + scores[split] = metric.scores() + + log.info(f'Completed split {split}') + + key_prefix = config['name'] if 'name' in config else 'pas' + + all_keys = set.intersection(*[set(v.keys()) for v in scores.values()]) + + valid_keys = [k for k in all_keys if all(v[k] is not None and isinstance(v[k], (int, float, np.float)) for v in scores.values())] + + return {key_prefix: {k: np.mean([s[k] for s in scores.values()]) for k in valid_keys}} + + + if config.test_dataset == 'coco': + from datasets.coco_wrapper import COCOWrapper + + coco_dataset = COCOWrapper('test', fold=train_config.fold, image_size=train_config.image_size, mask=config.mask, + with_class_label=True) + + log.info('Dataset length', len(coco_dataset)) + loader = DataLoader(coco_dataset, batch_size=config.batch_size, num_workers=2, shuffle=False, drop_last=False) + + metric = get_attribute(config.metric)(resize_pred=True, **metric_args) + + shift = config.shift if 'shift' in config else 0 + + with torch.no_grad(): + + i, losses = 0, [] + for i_all, (data_x, data_y) in enumerate(loader): + data_x = [v.cuda(non_blocking=True) if isinstance(v, torch.Tensor) else v for v in data_x] + data_y = [v.cuda(non_blocking=True) if isinstance(v, torch.Tensor) else v for v in data_y] + + if config.mask == 'separate': # for old CondBase model + pred, = model(data_x[0], data_x[1], data_x[2]) + else: + # assert config.mask in {'text', 'highlight'} + pred, _, _, _ = model(data_x[0], data_x[1], return_features=True) + + metric.add([pred + shift], data_y) + + i += 1 + if config.max_iterations and i >= config.max_iterations: + break + + key_prefix = config['name'] if 'name' in config else 'coco' + return {key_prefix: metric.scores()} + #return {key_prefix: {k: v for k, v in zip(metric.names(), metric.value())}} + + + if config.test_dataset == 'phrasecut': + from datasets.phrasecut import PhraseCut + + only_visual = config.only_visual is not None and config.only_visual + with_visual = config.with_visual is not None and config.with_visual + + dataset = PhraseCut('test', + image_size=train_config.image_size, + mask=config.mask, + with_visual=with_visual, only_visual=only_visual, aug_crop=False, + aug_color=False) + + loader = DataLoader(dataset, batch_size=config.batch_size, num_workers=2, shuffle=False, drop_last=False) + metric = get_attribute(config.metric)(resize_pred=True, **metric_args) + + shift = config.shift if 'shift' in config else 0 + + + with torch.no_grad(): + + i, losses = 0, [] + for i_all, (data_x, data_y) in enumerate(loader): + data_x = [v.cuda(non_blocking=True) if isinstance(v, torch.Tensor) else v for v in data_x] + data_y = [v.cuda(non_blocking=True) if isinstance(v, torch.Tensor) else v for v in data_y] + + pred, _, _, _ = model(data_x[0], data_x[1], return_features=True) + metric.add([pred + shift], data_y) + + i += 1 + if config.max_iterations and i >= config.max_iterations: + break + + key_prefix = config['name'] if 'name' in config else 'phrasecut' + return {key_prefix: metric.scores()} + #return {key_prefix: {k: v for k, v in zip(metric.names(), metric.value())}} + + if config.test_dataset == 'pascal_zs': + from third_party.JoEm.model.metric import Evaluator + from third_party.JoEm.data_loader import get_seen_idx, get_unseen_idx, VOC + from datasets.pascal_zeroshot import PascalZeroShot, PASCAL_VOC_CLASSES_ZS + + from models.clipseg import CLIPSegMultiLabel + + n_unseen = train_config.remove_classes[1] + + pz = PascalZeroShot('val', n_unseen, image_size=352) + m = CLIPSegMultiLabel(model=train_config.name).cuda() + m.eval(); + + print(len(pz), n_unseen) + print('training removed', [c for class_set in PASCAL_VOC_CLASSES_ZS[:n_unseen // 2] for c in class_set]) + + print('unseen', [VOC[i] for i in get_unseen_idx(n_unseen)]) + print('seen', [VOC[i] for i in get_seen_idx(n_unseen)]) + + loader = DataLoader(pz, batch_size=8) + evaluator = Evaluator(21, get_unseen_idx(n_unseen), get_seen_idx(n_unseen)) + + for i, (data_x, data_y) in enumerate(loader): + pred = m(data_x[0].cuda()) + evaluator.add_batch(data_y[0].numpy(), pred.argmax(1).cpu().detach().numpy()) + + if config.max_iter is not None and i > config.max_iter: + break + + scores = evaluator.Mean_Intersection_over_Union() + key_prefix = config['name'] if 'name' in config else 'pas_zs' + + return {key_prefix: {k: scores[k] for k in ['seen', 'unseen', 'harmonic', 'overall']}} + + elif config.test_dataset in {'same_as_training', 'affordance'}: + loss_fn = get_attribute(train_config.loss) + + metric_cls = get_attribute(config.metric) + metric = metric_cls(**metric_args) + + if config.test_dataset == 'same_as_training': + dataset_cls = get_attribute(train_config.dataset) + elif config.test_dataset == 'affordance': + dataset_cls = get_attribute('datasets.lvis_oneshot3.LVIS_Affordance') + dataset_name = 'aff' + else: + dataset_cls = get_attribute('datasets.lvis_oneshot3.LVIS_OneShot') + dataset_name = 'lvis' + + _, dataset_args, _ = filter_args(config, inspect.signature(dataset_cls).parameters) + + dataset_args['image_size'] = train_config.image_size # explicitly use training image size for evaluation + + if model.__class__.__name__ == 'PFENetWrapper': + dataset_args['image_size'] = config.image_size + + log.info('init dataset', str(dataset_cls)) + dataset = dataset_cls(**dataset_args) + + log.info(f'Score on {model.__class__.__name__} on {dataset_cls.__name__}') + + data_loader = torch.utils.data.DataLoader(dataset, batch_size=config.batch_size, shuffle=config.shuffle) + + # explicitly set prompts + if config.prompt == 'plain': + model.prompt_list = ['{}'] + elif config.prompt == 'fixed': + model.prompt_list = ['a photo of a {}.'] + elif config.prompt == 'shuffle': + model.prompt_list = ['a photo of a {}.', 'a photograph of a {}.', 'an image of a {}.', '{}.'] + elif config.prompt == 'shuffle_clip': + from models.clip_prompts import imagenet_templates + model.prompt_list = imagenet_templates + + config.assume_no_unused_keys(exceptions=['max_iterations']) + + t_start = time.time() + + with torch.no_grad(): # TODO: switch to inference_mode (torch 1.9) + i, losses = 0, [] + for data_x, data_y in data_loader: + + data_x = [x.cuda() if isinstance(x, torch.Tensor) else x for x in data_x] + data_y = [x.cuda() if isinstance(x, torch.Tensor) else x for x in data_y] + + if model.__class__.__name__ in {'ConditionBase4', 'PFENetWrapper'}: + pred, = model(data_x[0], data_x[1], data_x[2]) + visual_q = None + else: + pred, visual_q, _, _ = model(data_x[0], data_x[1], return_features=True) + + loss = loss_fn(pred, data_y[0]) + + metric.add([pred], data_y) + + losses += [float(loss)] + + i += 1 + if config.max_iterations and i >= config.max_iterations: + break + + # scores = {m: s for m, s in zip(metric.names(), metric.value())} + scores = metric.scores() + + keys = set(scores.keys()) + if dataset.negative_prob > 0 and 'mIoU' in keys: + keys.remove('mIoU') + + name_mask = dataset.mask.replace('text_label', 'txt')[:3] + name_neg = '' if dataset.negative_prob == 0 else '_' + str(dataset.negative_prob) + + score_name = config.name if 'name' in config else f'{dataset_name}_{name_mask}{name_neg}' + + scores = {score_name: {k: v for k,v in scores.items() if k in keys}} + scores[score_name].update({'test_loss': np.mean(losses)}) + + log.info(f'Evaluation took {time.time() - t_start:.1f}s') + + return scores + else: + raise ValueError('invalid test dataset') + + + + + + + + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/setup.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..3cfa1567b1da2beec4eda74513cfdf23f8464242 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/setup.py @@ -0,0 +1,30 @@ +from setuptools import setup + +with open("README.md", "r", encoding="utf-8") as readme_file: + readme = readme_file.read() + +requirements = [ + "numpy", + "scipy", + "matplotlib", + "torch", + "torchvision", + "opencv-python", + "CLIP @ git+https://github.com/openai/CLIP.git" +] + +setup( + name='clipseg', + packages=['clipseg'], + package_dir={'clipseg': 'models'}, + package_data={'clipseg': [ + "../weights/*.pth", + ]}, + version='0.0.1', + url='https://github.com/timojl/clipseg', + python_requires='>=3.9', + install_requires=requirements, + description='This repository contains the code used in the paper "Image Segmentation Using Text and Image Prompts".', + long_description=readme, + long_description_content_type="text/markdown", +) diff --git a/extensions/deforum/scripts/deforum_helpers/src/clipseg/training.py b/extensions/deforum/scripts/deforum_helpers/src/clipseg/training.py new file mode 100644 index 0000000000000000000000000000000000000000..4e07418261e4e14e81f99cb1e9422d6d11309854 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/clipseg/training.py @@ -0,0 +1,266 @@ +import torch +import inspect +import json +import yaml +import math +import os +import sys + +from general_utils import log + +import numpy as np +from functools import partial +from os.path import expanduser, join, isfile, basename + +from torch.cuda.amp import autocast, GradScaler +from torch.optim.lr_scheduler import LambdaLR +from contextlib import nullcontext +from torch.utils.data import DataLoader + +from general_utils import TrainingLogger, get_attribute, filter_args, log, training_config_from_cli_args + + +def cosine_warmup_lr(i, warmup=10, max_iter=90): + """ Cosine LR with Warmup """ + if i < warmup: + return (i+1)/(warmup+1) + else: + return 0.5 + 0.5*math.cos(math.pi*(((i-warmup)/(max_iter- warmup)))) + + +def validate(model, dataset, config): + data_loader = torch.utils.data.DataLoader(dataset, batch_size=4, shuffle=False) + + metric_class, use_metric = config.val_metric_class, config.use_val_metric + loss_fn = get_attribute(config.loss) + + model.eval() + model.cuda() + + if metric_class is not None: + metric = get_attribute(metric_class)() + + with torch.no_grad(): + + i, losses = 0, [] + for data_x, data_y in data_loader: + + data_x = [x.cuda() if isinstance(x, torch.Tensor) else x for x in data_x] + data_y = [x.cuda() if isinstance(x, torch.Tensor) else x for x in data_y] + + prompts = model.sample_prompts(data_x[1], prompt_list=('a photo of a {}',)) + pred, visual_q, _, _ = model(data_x[0], prompts, return_features=True) + + if metric_class is not None: + metric.add([pred], data_y) + + # pred = model(data_x[0], prompts) + # loss = loss_fn(pred[0], data_y[0]) + loss = loss_fn(pred, data_y[0]) + losses += [float(loss)] + + i += 1 + + if config.val_max_iterations is not None and i > config.val_max_iterations: + break + + if use_metric is None: + return np.mean(losses), {}, False + else: + metric_scores = {m: s for m, s in zip(metric.names(), metric.value())} if metric is not None else {} + return np.mean(losses), metric_scores, True + + +def main(): + + config = training_config_from_cli_args() + + val_interval, best_val_loss, best_val_score = config.val_interval, float('inf'), float('-inf') + + model_cls = get_attribute(config.model) + _, model_args, _ = filter_args(config, inspect.signature(model_cls).parameters) + model = model_cls(**model_args).cuda() + + dataset_cls = get_attribute(config.dataset) + _, dataset_args, _ = filter_args(config, inspect.signature(dataset_cls).parameters) + + dataset = dataset_cls(**dataset_args) + + log.info(f'Train dataset {dataset.__class__.__name__} (length: {len(dataset)})') + + if val_interval is not None: + dataset_val_args = {k[4:]: v for k,v in config.items() if k.startswith('val_') and k != 'val_interval'} + _, dataset_val_args, _ = filter_args(dataset_val_args, inspect.signature(dataset_cls).parameters) + print('val args', {**dataset_args, **{'split': 'val', 'aug': 0}, **dataset_val_args}) + + dataset_val = dataset_cls(**{**dataset_args, **{'split': 'val', 'aug': 0}, **dataset_val_args}) + + # optimizer + opt_cls = get_attribute(config.optimizer) + if config.optimize == 'torch.optim.SGD': + opt_args = {'momentum': config.momentum if 'momentum' in config else 0} + else: + opt_args = {} + opt = opt_cls(model.parameters(), lr=config.lr, **opt_args) + + if config.lr_scheduler == 'cosine': + assert config.T_max is not None and config.eta_min is not None + lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(opt, config.T_max, config.eta_min) + elif config.lr_scheduler == 'warmup_cosine': + lr_scheduler = LambdaLR(opt, partial(cosine_warmup_lr, max_iter=(config.max_iterations), warmup=config.warmup)) + else: + lr_scheduler = None + + batch_size, max_iterations = config.batch_size, config.max_iterations + + loss_fn = get_attribute(config.loss) + + if config.amp: + log.info('Using AMP') + autocast_fn = autocast + scaler = GradScaler() + else: + autocast_fn, scaler = nullcontext, None + + + save_only_trainable = True + data_loader = DataLoader(dataset, batch_size=batch_size, num_workers=4) + + # disable config when hyperparam. opt. to avoid writing logs. + tracker_config = config if not config.hyperparameter_optimization else None + + with TrainingLogger(log_dir=config.name, model=model, config=tracker_config) as logger: + + i = 0 + while True: + for data_x, data_y in data_loader: + + # between caption and output feature. + # 1. Sample random captions + # 2. Check alignment with CLIP + + # randomly mix text and visual support conditionals + if config.mix: + + assert config.mask.startswith('text_and') + + with autocast_fn(): + # data_x[1] = text label + prompts = model.sample_prompts(data_x[1]) + + # model.clip_model() + + text_cond = model.compute_conditional(prompts) + if model.__class__.__name__ == 'CLIPDensePredTMasked': + # when mask=='separate' + visual_s_cond, _, _ = model.visual_forward_masked(data_x[2].cuda(), data_x[3].cuda()) + else: + # data_x[2] = visual prompt + visual_s_cond, _, _ = model.visual_forward(data_x[2].cuda()) + + max_txt = config.mix_text_max if config.mix_text_max is not None else 1 + batch_size = text_cond.shape[0] + + # sample weights for each element in batch + text_weights = torch.distributions.Uniform(config.mix_text_min, max_txt).sample((batch_size,))[:, None] + text_weights = text_weights.cuda() + + if dataset.__class__.__name__ == 'PhraseCut': + # give full weight to text where support_image is invalid + visual_is_valid = data_x[4] if model.__class__.__name__ == 'CLIPDensePredTMasked' else data_x[3] + text_weights = torch.max(text_weights[:,0], 1 - visual_is_valid.float().cuda()).unsqueeze(1) + + cond = text_cond * text_weights + visual_s_cond * (1 - text_weights) + + else: + # no mix + + if model.__class__.__name__ == 'CLIPDensePredTMasked': + # compute conditional vector using CLIP masking + with autocast_fn(): + assert config.mask == 'separate' + cond, _, _ = model.visual_forward_masked(data_x[1].cuda(), data_x[2].cuda()) + else: + cond = data_x[1] + if isinstance(cond, torch.Tensor): + cond = cond.cuda() + + with autocast_fn(): + visual_q = None + + pred, visual_q, _, _ = model(data_x[0].cuda(), cond, return_features=True) + + loss = loss_fn(pred, data_y[0].cuda()) + + if torch.isnan(loss) or torch.isinf(loss): + # skip if loss is nan + log.warning('Training stopped due to inf/nan loss.') + sys.exit(-1) + + extra_loss = 0 + loss += extra_loss + + opt.zero_grad() + + if scaler is None: + loss.backward() + opt.step() + else: + scaler.scale(loss).backward() + scaler.step(opt) + scaler.update() + + if lr_scheduler is not None: + lr_scheduler.step() + if i % 2000 == 0: + current_lr = [g['lr'] for g in opt.param_groups][0] + log.info(f'current lr: {current_lr:.5f} ({len(opt.param_groups)} parameter groups)') + + logger.iter(i=i, loss=loss) + i += 1 + + if i >= max_iterations: + + if not isfile(join(logger.base_path, 'weights.pth')): + # only write if no weights were already written + logger.save_weights(only_trainable=save_only_trainable) + + sys.exit(0) + + + if config.checkpoint_iterations is not None and i in config.checkpoint_iterations: + logger.save_weights(only_trainable=save_only_trainable, weight_file=f'weights_{i}.pth') + + + if val_interval is not None and i % val_interval == val_interval - 1: + + val_loss, val_scores, maximize = validate(model, dataset_val, config) + + if len(val_scores) > 0: + + score_str = f', scores: ' + ', '.join(f'{k}: {v}' for k, v in val_scores.items()) + + if maximize and val_scores[config.use_val_metric] > best_val_score: + logger.save_weights(only_trainable=save_only_trainable) + best_val_score = val_scores[config.use_val_metric] + + elif not maximize and val_scores[config.use_val_metric] < best_val_score: + logger.save_weights(only_trainable=save_only_trainable) + best_val_score = val_scores[config.use_val_metric] + + else: + score_str = '' + # if no score is used, fall back to loss + if val_loss < best_val_loss: + logger.save_weights(only_trainable=save_only_trainable) + best_val_loss = val_loss + + log.info(f'Validation loss: {val_loss}' + score_str) + logger.iter(i=i, val_loss=val_loss, extra_loss=float(extra_loss), **val_scores) + model.train() + + print('epoch complete') + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/film_interpolation/film_inference.py b/extensions/deforum/scripts/deforum_helpers/src/film_interpolation/film_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..12a07696d4abaf2d3d145e75e044a8879f69be0e --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/film_interpolation/film_inference.py @@ -0,0 +1,118 @@ +import os +from glob import glob +import bisect +from tqdm import tqdm +import torch +import numpy as np +import cv2 +from .film_util import load_image +import time +from types import SimpleNamespace +import warnings +warnings.filterwarnings("ignore") + +def run_film_interp_infer( + model_path = None, + input_folder = None, + save_folder = None, + inter_frames = None): + + args = SimpleNamespace() + args.model_path = model_path + args.input_folder = input_folder + args.save_folder = save_folder + args.inter_frames = inter_frames + + # Check if the folder exists + if not os.path.exists(args.input_folder): + print(f"Error: Folder '{args.input_folder}' does not exist.") + return + # Check if the folder contains any PNG or JPEG images + if not any([f.endswith(".png") or f.endswith(".jpg") for f in os.listdir(args.input_folder)]): + print(f"Error: Folder '{args.input_folder}' does not contain any PNG or JPEG images.") + return + + start_time = time.time() # Timer START + + # Sort Jpg/Png images by name + image_paths = sorted(glob(os.path.join(args.input_folder, "*.[jJ][pP][gG]")) + glob(os.path.join(args.input_folder, "*.[pP][nN][gG]"))) + print(f"Total frames to FILM-interpolate: {len(image_paths)}. Total frame-pairs: {len(image_paths)-1}.") + + model = torch.jit.load(args.model_path, map_location='cpu') + model.eval() + + for i in tqdm(range(len(image_paths) - 1), desc='FILM progress'): + img1 = image_paths[i] + img2 = image_paths[i+1] + img_batch_1, crop_region_1 = load_image(img1) + img_batch_2, crop_region_2 = load_image(img2) + img_batch_1 = torch.from_numpy(img_batch_1).permute(0, 3, 1, 2) + img_batch_2 = torch.from_numpy(img_batch_2).permute(0, 3, 1, 2) + + model = model.half() + model = model.cuda() + + save_path = os.path.join(args.save_folder, f"{i}_to_{i+1}.jpg") + + results = [ + img_batch_1, + img_batch_2 + ] + + idxes = [0, inter_frames + 1] + remains = list(range(1, inter_frames + 1)) + + splits = torch.linspace(0, 1, inter_frames + 2) + + inner_loop_progress = tqdm(range(len(remains)), leave=False, disable=True) + for _ in inner_loop_progress: + starts = splits[idxes[:-1]] + ends = splits[idxes[1:]] + distances = ((splits[None, remains] - starts[:, None]) / (ends[:, None] - starts[:, None]) - .5).abs() + matrix = torch.argmin(distances).item() + start_i, step = np.unravel_index(matrix, distances.shape) + end_i = start_i + 1 + + x0 = results[start_i] + x1 = results[end_i] + + x0 = x0.half() + x1 = x1.half() + x0 = x0.cuda() + x1 = x1.cuda() + + dt = x0.new_full((1, 1), (splits[remains[step]] - splits[idxes[start_i]])) / (splits[idxes[end_i]] - splits[idxes[start_i]]) + + with torch.no_grad(): + prediction = model(x0, x1, dt) + insert_position = bisect.bisect_left(idxes, remains[step]) + idxes.insert(insert_position, remains[step]) + results.insert(insert_position, prediction.clamp(0, 1).cpu().float()) + inner_loop_progress.update(1) + del remains[step] + inner_loop_progress.close() + # create output folder for interoplated imgs to live in + os.makedirs(args.save_folder, exist_ok=True) + + y1, x1, y2, x2 = crop_region_1 + frames = [(tensor[0] * 255).byte().flip(0).permute(1, 2, 0).numpy()[y1:y2, x1:x2].copy() for tensor in results] + + existing_files = os.listdir(args.save_folder) + if len(existing_files) > 0: + existing_numbers = [int(file.split("_")[1].split(".")[0]) for file in existing_files] + next_number = max(existing_numbers) + 1 + else: + next_number = 0 + + outer_loop_count = i + for i, frame in enumerate(frames): + frame_path = os.path.join(args.save_folder, f"frame_{next_number:05d}.png") + # last pair, save all frames including the last one + if len(image_paths) - 2 == outer_loop_count: + cv2.imwrite(frame_path, frame) + else: # not last pair, don't save the last frame + if not i == len(frames) - 1: + cv2.imwrite(frame_path, frame) + next_number += 1 + + print(f"Interpolation \033[0;32mdone\033[0m in {time.time()-start_time:.2f} seconds!") \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/film_interpolation/film_util.py b/extensions/deforum/scripts/deforum_helpers/src/film_interpolation/film_util.py new file mode 100644 index 0000000000000000000000000000000000000000..e510758e53ced0af433fc14f63bf9b504e256544 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/film_interpolation/film_util.py @@ -0,0 +1,161 @@ +"""Various utilities used in the film_net frame interpolator model.""" +from typing import List, Optional + +import cv2 +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + + +def pad_batch(batch, align): + height, width = batch.shape[1:3] + height_to_pad = (align - height % align) if height % align != 0 else 0 + width_to_pad = (align - width % align) if width % align != 0 else 0 + + crop_region = [height_to_pad >> 1, width_to_pad >> 1, height + (height_to_pad >> 1), width + (width_to_pad >> 1)] + batch = np.pad(batch, ((0, 0), (height_to_pad >> 1, height_to_pad - (height_to_pad >> 1)), + (width_to_pad >> 1, width_to_pad - (width_to_pad >> 1)), (0, 0)), mode='constant') + return batch, crop_region + + +def load_image(path, align=64): + image = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB).astype(np.float32) / np.float32(255) + image_batch, crop_region = pad_batch(np.expand_dims(image, axis=0), align) + return image_batch, crop_region + + +def build_image_pyramid(image: torch.Tensor, pyramid_levels: int = 3) -> List[torch.Tensor]: + """Builds an image pyramid from a given image. + + The original image is included in the pyramid and the rest are generated by + successively halving the resolution. + + Args: + image: the input image. + options: film_net options object + + Returns: + A list of images starting from the finest with options.pyramid_levels items + """ + + pyramid = [] + for i in range(pyramid_levels): + pyramid.append(image) + if i < pyramid_levels - 1: + image = F.avg_pool2d(image, 2, 2) + return pyramid + + +def warp(image: torch.Tensor, flow: torch.Tensor) -> torch.Tensor: + """Backward warps the image using the given flow. + + Specifically, the output pixel in batch b, at position x, y will be computed + as follows: + (flowed_y, flowed_x) = (y+flow[b, y, x, 1], x+flow[b, y, x, 0]) + output[b, y, x] = bilinear_lookup(image, b, flowed_y, flowed_x) + + Note that the flow vectors are expected as [x, y], e.g. x in position 0 and + y in position 1. + + Args: + image: An image with shape BxHxWxC. + flow: A flow with shape BxHxWx2, with the two channels denoting the relative + offset in order: (dx, dy). + Returns: + A warped image. + """ + flow = -flow.flip(1) + + dtype = flow.dtype + device = flow.device + + # warped = tfa_image.dense_image_warp(image, flow) + # Same as above but with pytorch + ls1 = 1 - 1 / flow.shape[3] + ls2 = 1 - 1 / flow.shape[2] + + normalized_flow2 = flow.permute(0, 2, 3, 1) / torch.tensor( + [flow.shape[2] * .5, flow.shape[3] * .5], dtype=dtype, device=device)[None, None, None] + normalized_flow2 = torch.stack([ + torch.linspace(-ls1, ls1, flow.shape[3], dtype=dtype, device=device)[None, None, :] - normalized_flow2[..., 1], + torch.linspace(-ls2, ls2, flow.shape[2], dtype=dtype, device=device)[None, :, None] - normalized_flow2[..., 0], + ], dim=3) + + warped = F.grid_sample(image, normalized_flow2, + mode='bilinear', padding_mode='border', align_corners=False) + return warped.reshape(image.shape) + + +def multiply_pyramid(pyramid: List[torch.Tensor], + scalar: torch.Tensor) -> List[torch.Tensor]: + """Multiplies all image batches in the pyramid by a batch of scalars. + + Args: + pyramid: Pyramid of image batches. + scalar: Batch of scalars. + + Returns: + An image pyramid with all images multiplied by the scalar. + """ + # To multiply each image with its corresponding scalar, we first transpose + # the batch of images from BxHxWxC-format to CxHxWxB. This can then be + # multiplied with a batch of scalars, then we transpose back to the standard + # BxHxWxC form. + return [image * scalar for image in pyramid] + + +def flow_pyramid_synthesis( + residual_pyramid: List[torch.Tensor]) -> List[torch.Tensor]: + """Converts a residual flow pyramid into a flow pyramid.""" + flow = residual_pyramid[-1] + flow_pyramid: List[torch.Tensor] = [flow] + for residual_flow in residual_pyramid[:-1][::-1]: + level_size = residual_flow.shape[2:4] + flow = F.interpolate(2 * flow, size=level_size, mode='bilinear') + flow = residual_flow + flow + flow_pyramid.insert(0, flow) + return flow_pyramid + + +def pyramid_warp(feature_pyramid: List[torch.Tensor], + flow_pyramid: List[torch.Tensor]) -> List[torch.Tensor]: + """Warps the feature pyramid using the flow pyramid. + + Args: + feature_pyramid: feature pyramid starting from the finest level. + flow_pyramid: flow fields, starting from the finest level. + + Returns: + Reverse warped feature pyramid. + """ + warped_feature_pyramid = [] + for features, flow in zip(feature_pyramid, flow_pyramid): + warped_feature_pyramid.append(warp(features, flow)) + return warped_feature_pyramid + + +def concatenate_pyramids(pyramid1: List[torch.Tensor], + pyramid2: List[torch.Tensor]) -> List[torch.Tensor]: + """Concatenates each pyramid level together in the channel dimension.""" + result = [] + for features1, features2 in zip(pyramid1, pyramid2): + result.append(torch.cat([features1, features2], dim=1)) + return result + + +def conv(in_channels, out_channels, size, activation: Optional[str] = 'relu'): + # Since PyTorch doesn't have an in-built activation in Conv2d, we use a + # Sequential layer to combine Conv2d and Leaky ReLU in one module. + _conv = nn.Conv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=size, + padding='same') + if activation is None: + return _conv + assert activation == 'relu' + return nn.Sequential( + _conv, + nn.LeakyReLU(.2) + ) diff --git a/extensions/deforum/scripts/deforum_helpers/src/infer.py b/extensions/deforum/scripts/deforum_helpers/src/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..4474e972a7c2ad25e1078b6549805dc26164fdbb --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/infer.py @@ -0,0 +1,165 @@ +import glob +import os + +import numpy as np +import torch +import torch.nn as nn +from PIL import Image +from torchvision import transforms +from tqdm import tqdm + +import model_io +import utils +from adabins import UnetAdaptiveBins + + +def _is_pil_image(img): + return isinstance(img, Image.Image) + + +def _is_numpy_image(img): + return isinstance(img, np.ndarray) and (img.ndim in {2, 3}) + + +class ToTensor(object): + def __init__(self): + self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) + + def __call__(self, image, target_size=(640, 480)): + # image = image.resize(target_size) + image = self.to_tensor(image) + image = self.normalize(image) + return image + + def to_tensor(self, pic): + if not (_is_pil_image(pic) or _is_numpy_image(pic)): + raise TypeError( + 'pic should be PIL Image or ndarray. Got {}'.format(type(pic))) + + if isinstance(pic, np.ndarray): + img = torch.from_numpy(pic.transpose((2, 0, 1))) + return img + + # handle PIL Image + if pic.mode == 'I': + img = torch.from_numpy(np.array(pic, np.int32, copy=False)) + elif pic.mode == 'I;16': + img = torch.from_numpy(np.array(pic, np.int16, copy=False)) + else: + img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes())) + # PIL image mode: 1, L, P, I, F, RGB, YCbCr, RGBA, CMYK + if pic.mode == 'YCbCr': + nchannel = 3 + elif pic.mode == 'I;16': + nchannel = 1 + else: + nchannel = len(pic.mode) + img = img.view(pic.size[1], pic.size[0], nchannel) + + img = img.transpose(0, 1).transpose(0, 2).contiguous() + if isinstance(img, torch.ByteTensor): + return img.float() + else: + return img + + +class InferenceHelper: + def __init__(self, models_path, dataset='nyu', device='cuda:0'): + self.toTensor = ToTensor() + self.device = device + if dataset == 'nyu': + self.min_depth = 1e-3 + self.max_depth = 10 + self.saving_factor = 1000 # used to save in 16 bit + model = UnetAdaptiveBins.build(n_bins=256, min_val=self.min_depth, max_val=self.max_depth) + pretrained_path = os.path.join(models_path, "AdaBins_nyu.pt") + elif dataset == 'kitti': + self.min_depth = 1e-3 + self.max_depth = 80 + self.saving_factor = 256 + model = UnetAdaptiveBins.build(n_bins=256, min_val=self.min_depth, max_val=self.max_depth) + pretrained_path = os.path.join(models_path, "AdaBins_kitti.pt") + else: + raise ValueError("dataset can be either 'nyu' or 'kitti' but got {}".format(dataset)) + + model, _, _ = model_io.load_checkpoint(pretrained_path, model) + model.eval() + self.model = model.to(self.device) + + @torch.no_grad() + def predict_pil(self, pil_image, visualized=False): + # pil_image = pil_image.resize((640, 480)) + img = np.asarray(pil_image) / 255. + + img = self.toTensor(img).unsqueeze(0).float().to(self.device) + bin_centers, pred = self.predict(img) + + if visualized: + viz = utils.colorize(torch.from_numpy(pred).unsqueeze(0), vmin=None, vmax=None, cmap='magma') + # pred = np.asarray(pred*1000, dtype='uint16') + viz = Image.fromarray(viz) + return bin_centers, pred, viz + return bin_centers, pred + + @torch.no_grad() + def predict(self, image): + bins, pred = self.model(image) + pred = np.clip(pred.cpu().numpy(), self.min_depth, self.max_depth) + + # Flip + image = torch.Tensor(np.array(image.cpu().numpy())[..., ::-1].copy()).to(self.device) + pred_lr = self.model(image)[-1] + pred_lr = np.clip(pred_lr.cpu().numpy()[..., ::-1], self.min_depth, self.max_depth) + + # Take average of original and mirror + final = 0.5 * (pred + pred_lr) + final = nn.functional.interpolate(torch.Tensor(final), image.shape[-2:], + mode='bilinear', align_corners=True).cpu().numpy() + + final[final < self.min_depth] = self.min_depth + final[final > self.max_depth] = self.max_depth + final[np.isinf(final)] = self.max_depth + final[np.isnan(final)] = self.min_depth + + centers = 0.5 * (bins[:, 1:] + bins[:, :-1]) + centers = centers.cpu().squeeze().numpy() + centers = centers[centers > self.min_depth] + centers = centers[centers < self.max_depth] + + return centers, final + + @torch.no_grad() + def predict_dir(self, test_dir, out_dir): + os.makedirs(out_dir, exist_ok=True) + transform = ToTensor() + all_files = glob.glob(os.path.join(test_dir, "*")) + self.model.eval() + for f in tqdm(all_files): + image = np.asarray(Image.open(f), dtype='float32') / 255. + image = transform(image).unsqueeze(0).to(self.device) + + centers, final = self.predict(image) + # final = final.squeeze().cpu().numpy() + + final = (final * self.saving_factor).astype('uint16') + basename = os.path.basename(f).split('.')[0] + save_path = os.path.join(out_dir, basename + ".png") + + Image.fromarray(final.squeeze()).save(save_path) + + def to(self, device): + self.device = device + self.model.to(device) + + +if __name__ == '__main__': + import matplotlib.pyplot as plt + from time import time + + img = Image.open("test_imgs/classroom__rgb_00283.jpg") + start = time() + inferHelper = InferenceHelper() + centers, pred = inferHelper.predict_pil(img) + print(f"took :{time() - start}s") + plt.imshow(pred.squeeze(), cmap='magma_r') + plt.show() diff --git a/extensions/deforum/scripts/deforum_helpers/src/midas/base_model.py b/extensions/deforum/scripts/deforum_helpers/src/midas/base_model.py new file mode 100644 index 0000000000000000000000000000000000000000..5cf430239b47ec5ec07531263f26f5c24a2311cd --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/midas/base_model.py @@ -0,0 +1,16 @@ +import torch + + +class BaseModel(torch.nn.Module): + def load(self, path): + """Load model from file. + + Args: + path (str): file path + """ + parameters = torch.load(path, map_location=torch.device('cpu')) + + if "optimizer" in parameters: + parameters = parameters["model"] + + self.load_state_dict(parameters) diff --git a/extensions/deforum/scripts/deforum_helpers/src/midas/blocks.py b/extensions/deforum/scripts/deforum_helpers/src/midas/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..2145d18fa98060a618536d9a64fe6589e9be4f78 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/midas/blocks.py @@ -0,0 +1,342 @@ +import torch +import torch.nn as nn + +from .vit import ( + _make_pretrained_vitb_rn50_384, + _make_pretrained_vitl16_384, + _make_pretrained_vitb16_384, + forward_vit, +) + +def _make_encoder(backbone, features, use_pretrained, groups=1, expand=False, exportable=True, hooks=None, use_vit_only=False, use_readout="ignore",): + if backbone == "vitl16_384": + pretrained = _make_pretrained_vitl16_384( + use_pretrained, hooks=hooks, use_readout=use_readout + ) + scratch = _make_scratch( + [256, 512, 1024, 1024], features, groups=groups, expand=expand + ) # ViT-L/16 - 85.0% Top1 (backbone) + elif backbone == "vitb_rn50_384": + pretrained = _make_pretrained_vitb_rn50_384( + use_pretrained, + hooks=hooks, + use_vit_only=use_vit_only, + use_readout=use_readout, + ) + scratch = _make_scratch( + [256, 512, 768, 768], features, groups=groups, expand=expand + ) # ViT-H/16 - 85.0% Top1 (backbone) + elif backbone == "vitb16_384": + pretrained = _make_pretrained_vitb16_384( + use_pretrained, hooks=hooks, use_readout=use_readout + ) + scratch = _make_scratch( + [96, 192, 384, 768], features, groups=groups, expand=expand + ) # ViT-B/16 - 84.6% Top1 (backbone) + elif backbone == "resnext101_wsl": + pretrained = _make_pretrained_resnext101_wsl(use_pretrained) + scratch = _make_scratch([256, 512, 1024, 2048], features, groups=groups, expand=expand) # efficientnet_lite3 + elif backbone == "efficientnet_lite3": + pretrained = _make_pretrained_efficientnet_lite3(use_pretrained, exportable=exportable) + scratch = _make_scratch([32, 48, 136, 384], features, groups=groups, expand=expand) # efficientnet_lite3 + else: + print(f"Backbone '{backbone}' not implemented") + assert False + + return pretrained, scratch + + +def _make_scratch(in_shape, out_shape, groups=1, expand=False): + scratch = nn.Module() + + out_shape1 = out_shape + out_shape2 = out_shape + out_shape3 = out_shape + out_shape4 = out_shape + if expand==True: + out_shape1 = out_shape + out_shape2 = out_shape*2 + out_shape3 = out_shape*4 + out_shape4 = out_shape*8 + + scratch.layer1_rn = nn.Conv2d( + in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + scratch.layer2_rn = nn.Conv2d( + in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + scratch.layer3_rn = nn.Conv2d( + in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + scratch.layer4_rn = nn.Conv2d( + in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + + return scratch + + +def _make_pretrained_efficientnet_lite3(use_pretrained, exportable=False): + efficientnet = torch.hub.load( + "rwightman/gen-efficientnet-pytorch", + "tf_efficientnet_lite3", + pretrained=use_pretrained, + exportable=exportable + ) + return _make_efficientnet_backbone(efficientnet) + + +def _make_efficientnet_backbone(effnet): + pretrained = nn.Module() + + pretrained.layer1 = nn.Sequential( + effnet.conv_stem, effnet.bn1, effnet.act1, *effnet.blocks[0:2] + ) + pretrained.layer2 = nn.Sequential(*effnet.blocks[2:3]) + pretrained.layer3 = nn.Sequential(*effnet.blocks[3:5]) + pretrained.layer4 = nn.Sequential(*effnet.blocks[5:9]) + + return pretrained + + +def _make_resnet_backbone(resnet): + pretrained = nn.Module() + pretrained.layer1 = nn.Sequential( + resnet.conv1, resnet.bn1, resnet.relu, resnet.maxpool, resnet.layer1 + ) + + pretrained.layer2 = resnet.layer2 + pretrained.layer3 = resnet.layer3 + pretrained.layer4 = resnet.layer4 + + return pretrained + + +def _make_pretrained_resnext101_wsl(use_pretrained): + resnet = torch.hub.load("facebookresearch/WSL-Images", "resnext101_32x8d_wsl") + return _make_resnet_backbone(resnet) + + + +class Interpolate(nn.Module): + """Interpolation module. + """ + + def __init__(self, scale_factor, mode, align_corners=False): + """Init. + + Args: + scale_factor (float): scaling + mode (str): interpolation mode + """ + super(Interpolate, self).__init__() + + self.interp = nn.functional.interpolate + self.scale_factor = scale_factor + self.mode = mode + self.align_corners = align_corners + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input + + Returns: + tensor: interpolated data + """ + + x = self.interp( + x, scale_factor=self.scale_factor, mode=self.mode, align_corners=self.align_corners + ) + + return x + + +class ResidualConvUnit(nn.Module): + """Residual convolution module. + """ + + def __init__(self, features): + """Init. + + Args: + features (int): number of features + """ + super().__init__() + + self.conv1 = nn.Conv2d( + features, features, kernel_size=3, stride=1, padding=1, bias=True + ) + + self.conv2 = nn.Conv2d( + features, features, kernel_size=3, stride=1, padding=1, bias=True + ) + + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input + + Returns: + tensor: output + """ + out = self.relu(x) + out = self.conv1(out) + out = self.relu(out) + out = self.conv2(out) + + return out + x + + +class FeatureFusionBlock(nn.Module): + """Feature fusion block. + """ + + def __init__(self, features): + """Init. + + Args: + features (int): number of features + """ + super(FeatureFusionBlock, self).__init__() + + self.resConfUnit1 = ResidualConvUnit(features) + self.resConfUnit2 = ResidualConvUnit(features) + + def forward(self, *xs): + """Forward pass. + + Returns: + tensor: output + """ + output = xs[0] + + if len(xs) == 2: + output += self.resConfUnit1(xs[1]) + + output = self.resConfUnit2(output) + + output = nn.functional.interpolate( + output, scale_factor=2, mode="bilinear", align_corners=True + ) + + return output + + + + +class ResidualConvUnit_custom(nn.Module): + """Residual convolution module. + """ + + def __init__(self, features, activation, bn): + """Init. + + Args: + features (int): number of features + """ + super().__init__() + + self.bn = bn + + self.groups=1 + + self.conv1 = nn.Conv2d( + features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups + ) + + self.conv2 = nn.Conv2d( + features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups + ) + + if self.bn==True: + self.bn1 = nn.BatchNorm2d(features) + self.bn2 = nn.BatchNorm2d(features) + + self.activation = activation + + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input + + Returns: + tensor: output + """ + + out = self.activation(x) + out = self.conv1(out) + if self.bn==True: + out = self.bn1(out) + + out = self.activation(out) + out = self.conv2(out) + if self.bn==True: + out = self.bn2(out) + + if self.groups > 1: + out = self.conv_merge(out) + + return self.skip_add.add(out, x) + + # return out + x + + +class FeatureFusionBlock_custom(nn.Module): + """Feature fusion block. + """ + + def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True): + """Init. + + Args: + features (int): number of features + """ + super(FeatureFusionBlock_custom, self).__init__() + + self.deconv = deconv + self.align_corners = align_corners + + self.groups=1 + + self.expand = expand + out_features = features + if self.expand==True: + out_features = features//2 + + self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1) + + self.resConfUnit1 = ResidualConvUnit_custom(features, activation, bn) + self.resConfUnit2 = ResidualConvUnit_custom(features, activation, bn) + + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, *xs): + """Forward pass. + + Returns: + tensor: output + """ + output = xs[0] + + if len(xs) == 2: + res = self.resConfUnit1(xs[1]) + output = self.skip_add.add(output, res) + # output += res + + output = self.resConfUnit2(output) + + output = nn.functional.interpolate( + output, scale_factor=2, mode="bilinear", align_corners=self.align_corners + ) + + output = self.out_conv(output) + + return output + diff --git a/extensions/deforum/scripts/deforum_helpers/src/midas/dpt_depth.py b/extensions/deforum/scripts/deforum_helpers/src/midas/dpt_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..4e9aab5d2767dffea39da5b3f30e2798688216f1 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/midas/dpt_depth.py @@ -0,0 +1,109 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .base_model import BaseModel +from .blocks import ( + FeatureFusionBlock, + FeatureFusionBlock_custom, + Interpolate, + _make_encoder, + forward_vit, +) + + +def _make_fusion_block(features, use_bn): + return FeatureFusionBlock_custom( + features, + nn.ReLU(False), + deconv=False, + bn=use_bn, + expand=False, + align_corners=True, + ) + + +class DPT(BaseModel): + def __init__( + self, + head, + features=256, + backbone="vitb_rn50_384", + readout="project", + channels_last=False, + use_bn=False, + ): + + super(DPT, self).__init__() + + self.channels_last = channels_last + + hooks = { + "vitb_rn50_384": [0, 1, 8, 11], + "vitb16_384": [2, 5, 8, 11], + "vitl16_384": [5, 11, 17, 23], + } + + # Instantiate backbone and reassemble blocks + self.pretrained, self.scratch = _make_encoder( + backbone, + features, + False, # Set to true of you want to train from scratch, uses ImageNet weights + groups=1, + expand=False, + exportable=False, + hooks=hooks[backbone], + use_readout=readout, + ) + + self.scratch.refinenet1 = _make_fusion_block(features, use_bn) + self.scratch.refinenet2 = _make_fusion_block(features, use_bn) + self.scratch.refinenet3 = _make_fusion_block(features, use_bn) + self.scratch.refinenet4 = _make_fusion_block(features, use_bn) + + self.scratch.output_conv = head + + + def forward(self, x): + if self.channels_last == True: + x.contiguous(memory_format=torch.channels_last) + + layer_1, layer_2, layer_3, layer_4 = forward_vit(self.pretrained, x) + + layer_1_rn = self.scratch.layer1_rn(layer_1) + layer_2_rn = self.scratch.layer2_rn(layer_2) + layer_3_rn = self.scratch.layer3_rn(layer_3) + layer_4_rn = self.scratch.layer4_rn(layer_4) + + path_4 = self.scratch.refinenet4(layer_4_rn) + path_3 = self.scratch.refinenet3(path_4, layer_3_rn) + path_2 = self.scratch.refinenet2(path_3, layer_2_rn) + path_1 = self.scratch.refinenet1(path_2, layer_1_rn) + + out = self.scratch.output_conv(path_1) + + return out + + +class DPTDepthModel(DPT): + def __init__(self, path=None, non_negative=True, **kwargs): + features = kwargs["features"] if "features" in kwargs else 256 + + head = nn.Sequential( + nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1), + Interpolate(scale_factor=2, mode="bilinear", align_corners=True), + nn.Conv2d(features // 2, 32, kernel_size=3, stride=1, padding=1), + nn.ReLU(True), + nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0), + nn.ReLU(True) if non_negative else nn.Identity(), + nn.Identity(), + ) + + super().__init__(head, **kwargs) + + if path is not None: + self.load(path) + + def forward(self, x): + return super().forward(x).squeeze(dim=1) + diff --git a/extensions/deforum/scripts/deforum_helpers/src/midas/midas_net.py b/extensions/deforum/scripts/deforum_helpers/src/midas/midas_net.py new file mode 100644 index 0000000000000000000000000000000000000000..8a954977800b0a0f48807e80fa63041910e33c1f --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/midas/midas_net.py @@ -0,0 +1,76 @@ +"""MidashNet: Network for monocular depth estimation trained by mixing several datasets. +This file contains code that is adapted from +https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py +""" +import torch +import torch.nn as nn + +from .base_model import BaseModel +from .blocks import FeatureFusionBlock, Interpolate, _make_encoder + + +class MidasNet(BaseModel): + """Network for monocular depth estimation. + """ + + def __init__(self, path=None, features=256, non_negative=True): + """Init. + + Args: + path (str, optional): Path to saved model. Defaults to None. + features (int, optional): Number of features. Defaults to 256. + backbone (str, optional): Backbone network for encoder. Defaults to resnet50 + """ + print("Loading weights: ", path) + + super(MidasNet, self).__init__() + + use_pretrained = False if path is None else True + + self.pretrained, self.scratch = _make_encoder(backbone="resnext101_wsl", features=features, use_pretrained=use_pretrained) + + self.scratch.refinenet4 = FeatureFusionBlock(features) + self.scratch.refinenet3 = FeatureFusionBlock(features) + self.scratch.refinenet2 = FeatureFusionBlock(features) + self.scratch.refinenet1 = FeatureFusionBlock(features) + + self.scratch.output_conv = nn.Sequential( + nn.Conv2d(features, 128, kernel_size=3, stride=1, padding=1), + Interpolate(scale_factor=2, mode="bilinear"), + nn.Conv2d(128, 32, kernel_size=3, stride=1, padding=1), + nn.ReLU(True), + nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0), + nn.ReLU(True) if non_negative else nn.Identity(), + ) + + if path: + self.load(path) + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input data (image) + + Returns: + tensor: depth + """ + + layer_1 = self.pretrained.layer1(x) + layer_2 = self.pretrained.layer2(layer_1) + layer_3 = self.pretrained.layer3(layer_2) + layer_4 = self.pretrained.layer4(layer_3) + + layer_1_rn = self.scratch.layer1_rn(layer_1) + layer_2_rn = self.scratch.layer2_rn(layer_2) + layer_3_rn = self.scratch.layer3_rn(layer_3) + layer_4_rn = self.scratch.layer4_rn(layer_4) + + path_4 = self.scratch.refinenet4(layer_4_rn) + path_3 = self.scratch.refinenet3(path_4, layer_3_rn) + path_2 = self.scratch.refinenet2(path_3, layer_2_rn) + path_1 = self.scratch.refinenet1(path_2, layer_1_rn) + + out = self.scratch.output_conv(path_1) + + return torch.squeeze(out, dim=1) diff --git a/extensions/deforum/scripts/deforum_helpers/src/midas/midas_net_custom.py b/extensions/deforum/scripts/deforum_helpers/src/midas/midas_net_custom.py new file mode 100644 index 0000000000000000000000000000000000000000..50e4acb5e53d5fabefe3dde16ab49c33c2b7797c --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/midas/midas_net_custom.py @@ -0,0 +1,128 @@ +"""MidashNet: Network for monocular depth estimation trained by mixing several datasets. +This file contains code that is adapted from +https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py +""" +import torch +import torch.nn as nn + +from .base_model import BaseModel +from .blocks import FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder + + +class MidasNet_small(BaseModel): + """Network for monocular depth estimation. + """ + + def __init__(self, path=None, features=64, backbone="efficientnet_lite3", non_negative=True, exportable=True, channels_last=False, align_corners=True, + blocks={'expand': True}): + """Init. + + Args: + path (str, optional): Path to saved model. Defaults to None. + features (int, optional): Number of features. Defaults to 256. + backbone (str, optional): Backbone network for encoder. Defaults to resnet50 + """ + print("Loading weights: ", path) + + super(MidasNet_small, self).__init__() + + use_pretrained = False if path else True + + self.channels_last = channels_last + self.blocks = blocks + self.backbone = backbone + + self.groups = 1 + + features1=features + features2=features + features3=features + features4=features + self.expand = False + if "expand" in self.blocks and self.blocks['expand'] == True: + self.expand = True + features1=features + features2=features*2 + features3=features*4 + features4=features*8 + + self.pretrained, self.scratch = _make_encoder(self.backbone, features, use_pretrained, groups=self.groups, expand=self.expand, exportable=exportable) + + self.scratch.activation = nn.ReLU(False) + + self.scratch.refinenet4 = FeatureFusionBlock_custom(features4, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners) + self.scratch.refinenet3 = FeatureFusionBlock_custom(features3, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners) + self.scratch.refinenet2 = FeatureFusionBlock_custom(features2, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners) + self.scratch.refinenet1 = FeatureFusionBlock_custom(features1, self.scratch.activation, deconv=False, bn=False, align_corners=align_corners) + + + self.scratch.output_conv = nn.Sequential( + nn.Conv2d(features, features//2, kernel_size=3, stride=1, padding=1, groups=self.groups), + Interpolate(scale_factor=2, mode="bilinear"), + nn.Conv2d(features//2, 32, kernel_size=3, stride=1, padding=1), + self.scratch.activation, + nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0), + nn.ReLU(True) if non_negative else nn.Identity(), + nn.Identity(), + ) + + if path: + self.load(path) + + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input data (image) + + Returns: + tensor: depth + """ + if self.channels_last==True: + print("self.channels_last = ", self.channels_last) + x.contiguous(memory_format=torch.channels_last) + + + layer_1 = self.pretrained.layer1(x) + layer_2 = self.pretrained.layer2(layer_1) + layer_3 = self.pretrained.layer3(layer_2) + layer_4 = self.pretrained.layer4(layer_3) + + layer_1_rn = self.scratch.layer1_rn(layer_1) + layer_2_rn = self.scratch.layer2_rn(layer_2) + layer_3_rn = self.scratch.layer3_rn(layer_3) + layer_4_rn = self.scratch.layer4_rn(layer_4) + + + path_4 = self.scratch.refinenet4(layer_4_rn) + path_3 = self.scratch.refinenet3(path_4, layer_3_rn) + path_2 = self.scratch.refinenet2(path_3, layer_2_rn) + path_1 = self.scratch.refinenet1(path_2, layer_1_rn) + + out = self.scratch.output_conv(path_1) + + return torch.squeeze(out, dim=1) + + + +def fuse_model(m): + prev_previous_type = nn.Identity() + prev_previous_name = '' + previous_type = nn.Identity() + previous_name = '' + for name, module in m.named_modules(): + if prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d and type(module) == nn.ReLU: + # print("FUSED ", prev_previous_name, previous_name, name) + torch.quantization.fuse_modules(m, [prev_previous_name, previous_name, name], inplace=True) + elif prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d: + # print("FUSED ", prev_previous_name, previous_name) + torch.quantization.fuse_modules(m, [prev_previous_name, previous_name], inplace=True) + # elif previous_type == nn.Conv2d and type(module) == nn.ReLU: + # print("FUSED ", previous_name, name) + # torch.quantization.fuse_modules(m, [previous_name, name], inplace=True) + + prev_previous_type = previous_type + prev_previous_name = previous_name + previous_type = type(module) + previous_name = name \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/midas/transforms.py b/extensions/deforum/scripts/deforum_helpers/src/midas/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..350cbc11662633ad7f8968eb10be2e7de6e384e9 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/midas/transforms.py @@ -0,0 +1,234 @@ +import numpy as np +import cv2 +import math + + +def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA): + """Rezise the sample to ensure the given size. Keeps aspect ratio. + + Args: + sample (dict): sample + size (tuple): image size + + Returns: + tuple: new size + """ + shape = list(sample["disparity"].shape) + + if shape[0] >= size[0] and shape[1] >= size[1]: + return sample + + scale = [0, 0] + scale[0] = size[0] / shape[0] + scale[1] = size[1] / shape[1] + + scale = max(scale) + + shape[0] = math.ceil(scale * shape[0]) + shape[1] = math.ceil(scale * shape[1]) + + # resize + sample["image"] = cv2.resize( + sample["image"], tuple(shape[::-1]), interpolation=image_interpolation_method + ) + + sample["disparity"] = cv2.resize( + sample["disparity"], tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST + ) + sample["mask"] = cv2.resize( + sample["mask"].astype(np.float32), + tuple(shape[::-1]), + interpolation=cv2.INTER_NEAREST, + ) + sample["mask"] = sample["mask"].astype(bool) + + return tuple(shape) + + +class Resize(object): + """Resize sample to given size (width, height). + """ + + def __init__( + self, + width, + height, + resize_target=True, + keep_aspect_ratio=False, + ensure_multiple_of=1, + resize_method="lower_bound", + image_interpolation_method=cv2.INTER_AREA, + ): + """Init. + + Args: + width (int): desired output width + height (int): desired output height + resize_target (bool, optional): + True: Resize the full sample (image, mask, target). + False: Resize image only. + Defaults to True. + keep_aspect_ratio (bool, optional): + True: Keep the aspect ratio of the input sample. + Output sample might not have the given width and height, and + resize behaviour depends on the parameter 'resize_method'. + Defaults to False. + ensure_multiple_of (int, optional): + Output width and height is constrained to be multiple of this parameter. + Defaults to 1. + resize_method (str, optional): + "lower_bound": Output will be at least as large as the given size. + "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.) + "minimal": Scale as least as possible. (Output size might be smaller than given size.) + Defaults to "lower_bound". + """ + self.__width = width + self.__height = height + + self.__resize_target = resize_target + self.__keep_aspect_ratio = keep_aspect_ratio + self.__multiple_of = ensure_multiple_of + self.__resize_method = resize_method + self.__image_interpolation_method = image_interpolation_method + + def constrain_to_multiple_of(self, x, min_val=0, max_val=None): + y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int) + + if max_val is not None and y > max_val: + y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int) + + if y < min_val: + y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int) + + return y + + def get_size(self, width, height): + # determine new height and width + scale_height = self.__height / height + scale_width = self.__width / width + + if self.__keep_aspect_ratio: + if self.__resize_method == "lower_bound": + # scale such that output size is lower bound + if scale_width > scale_height: + # fit width + scale_height = scale_width + else: + # fit height + scale_width = scale_height + elif self.__resize_method == "upper_bound": + # scale such that output size is upper bound + if scale_width < scale_height: + # fit width + scale_height = scale_width + else: + # fit height + scale_width = scale_height + elif self.__resize_method == "minimal": + # scale as least as possbile + if abs(1 - scale_width) < abs(1 - scale_height): + # fit width + scale_height = scale_width + else: + # fit height + scale_width = scale_height + else: + raise ValueError( + f"resize_method {self.__resize_method} not implemented" + ) + + if self.__resize_method == "lower_bound": + new_height = self.constrain_to_multiple_of( + scale_height * height, min_val=self.__height + ) + new_width = self.constrain_to_multiple_of( + scale_width * width, min_val=self.__width + ) + elif self.__resize_method == "upper_bound": + new_height = self.constrain_to_multiple_of( + scale_height * height, max_val=self.__height + ) + new_width = self.constrain_to_multiple_of( + scale_width * width, max_val=self.__width + ) + elif self.__resize_method == "minimal": + new_height = self.constrain_to_multiple_of(scale_height * height) + new_width = self.constrain_to_multiple_of(scale_width * width) + else: + raise ValueError(f"resize_method {self.__resize_method} not implemented") + + return (new_width, new_height) + + def __call__(self, sample): + width, height = self.get_size( + sample["image"].shape[1], sample["image"].shape[0] + ) + + # resize sample + sample["image"] = cv2.resize( + sample["image"], + (width, height), + interpolation=self.__image_interpolation_method, + ) + + if self.__resize_target: + if "disparity" in sample: + sample["disparity"] = cv2.resize( + sample["disparity"], + (width, height), + interpolation=cv2.INTER_NEAREST, + ) + + if "depth" in sample: + sample["depth"] = cv2.resize( + sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST + ) + + sample["mask"] = cv2.resize( + sample["mask"].astype(np.float32), + (width, height), + interpolation=cv2.INTER_NEAREST, + ) + sample["mask"] = sample["mask"].astype(bool) + + return sample + + +class NormalizeImage(object): + """Normlize image by given mean and std. + """ + + def __init__(self, mean, std): + self.__mean = mean + self.__std = std + + def __call__(self, sample): + sample["image"] = (sample["image"] - self.__mean) / self.__std + + return sample + + +class PrepareForNet(object): + """Prepare sample for usage as network input. + """ + + def __init__(self): + pass + + def __call__(self, sample): + image = np.transpose(sample["image"], (2, 0, 1)) + sample["image"] = np.ascontiguousarray(image).astype(np.float32) + + if "mask" in sample: + sample["mask"] = sample["mask"].astype(np.float32) + sample["mask"] = np.ascontiguousarray(sample["mask"]) + + if "disparity" in sample: + disparity = sample["disparity"].astype(np.float32) + sample["disparity"] = np.ascontiguousarray(disparity) + + if "depth" in sample: + depth = sample["depth"].astype(np.float32) + sample["depth"] = np.ascontiguousarray(depth) + + return sample diff --git a/extensions/deforum/scripts/deforum_helpers/src/midas/vit.py b/extensions/deforum/scripts/deforum_helpers/src/midas/vit.py new file mode 100644 index 0000000000000000000000000000000000000000..ea46b1be88b261b0dec04f3da0256f5f66f88a74 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/midas/vit.py @@ -0,0 +1,491 @@ +import torch +import torch.nn as nn +import timm +import types +import math +import torch.nn.functional as F + + +class Slice(nn.Module): + def __init__(self, start_index=1): + super(Slice, self).__init__() + self.start_index = start_index + + def forward(self, x): + return x[:, self.start_index :] + + +class AddReadout(nn.Module): + def __init__(self, start_index=1): + super(AddReadout, self).__init__() + self.start_index = start_index + + def forward(self, x): + if self.start_index == 2: + readout = (x[:, 0] + x[:, 1]) / 2 + else: + readout = x[:, 0] + return x[:, self.start_index :] + readout.unsqueeze(1) + + +class ProjectReadout(nn.Module): + def __init__(self, in_features, start_index=1): + super(ProjectReadout, self).__init__() + self.start_index = start_index + + self.project = nn.Sequential(nn.Linear(2 * in_features, in_features), nn.GELU()) + + def forward(self, x): + readout = x[:, 0].unsqueeze(1).expand_as(x[:, self.start_index :]) + features = torch.cat((x[:, self.start_index :], readout), -1) + + return self.project(features) + + +class Transpose(nn.Module): + def __init__(self, dim0, dim1): + super(Transpose, self).__init__() + self.dim0 = dim0 + self.dim1 = dim1 + + def forward(self, x): + x = x.transpose(self.dim0, self.dim1) + return x + + +def forward_vit(pretrained, x): + b, c, h, w = x.shape + + glob = pretrained.model.forward_flex(x) + + layer_1 = pretrained.activations["1"] + layer_2 = pretrained.activations["2"] + layer_3 = pretrained.activations["3"] + layer_4 = pretrained.activations["4"] + + layer_1 = pretrained.act_postprocess1[0:2](layer_1) + layer_2 = pretrained.act_postprocess2[0:2](layer_2) + layer_3 = pretrained.act_postprocess3[0:2](layer_3) + layer_4 = pretrained.act_postprocess4[0:2](layer_4) + + unflatten = nn.Sequential( + nn.Unflatten( + 2, + torch.Size( + [ + h // pretrained.model.patch_size[1], + w // pretrained.model.patch_size[0], + ] + ), + ) + ) + + if layer_1.ndim == 3: + layer_1 = unflatten(layer_1) + if layer_2.ndim == 3: + layer_2 = unflatten(layer_2) + if layer_3.ndim == 3: + layer_3 = unflatten(layer_3) + if layer_4.ndim == 3: + layer_4 = unflatten(layer_4) + + layer_1 = pretrained.act_postprocess1[3 : len(pretrained.act_postprocess1)](layer_1) + layer_2 = pretrained.act_postprocess2[3 : len(pretrained.act_postprocess2)](layer_2) + layer_3 = pretrained.act_postprocess3[3 : len(pretrained.act_postprocess3)](layer_3) + layer_4 = pretrained.act_postprocess4[3 : len(pretrained.act_postprocess4)](layer_4) + + return layer_1, layer_2, layer_3, layer_4 + + +def _resize_pos_embed(self, posemb, gs_h, gs_w): + posemb_tok, posemb_grid = ( + posemb[:, : self.start_index], + posemb[0, self.start_index :], + ) + + gs_old = int(math.sqrt(len(posemb_grid))) + + posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2) + posemb_grid = F.interpolate(posemb_grid, size=(gs_h, gs_w), mode="bilinear") + posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_h * gs_w, -1) + + posemb = torch.cat([posemb_tok, posemb_grid], dim=1) + + return posemb + + +def forward_flex(self, x): + b, c, h, w = x.shape + + pos_embed = self._resize_pos_embed( + self.pos_embed, h // self.patch_size[1], w // self.patch_size[0] + ) + + B = x.shape[0] + + if hasattr(self.patch_embed, "backbone"): + x = self.patch_embed.backbone(x) + if isinstance(x, (list, tuple)): + x = x[-1] # last feature if backbone outputs list/tuple of features + + x = self.patch_embed.proj(x).flatten(2).transpose(1, 2) + + if getattr(self, "dist_token", None) is not None: + cls_tokens = self.cls_token.expand( + B, -1, -1 + ) # stole cls_tokens impl from Phil Wang, thanks + dist_token = self.dist_token.expand(B, -1, -1) + x = torch.cat((cls_tokens, dist_token, x), dim=1) + else: + cls_tokens = self.cls_token.expand( + B, -1, -1 + ) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + + x = x + pos_embed + x = self.pos_drop(x) + + for blk in self.blocks: + x = blk(x) + + x = self.norm(x) + + return x + + +activations = {} + + +def get_activation(name): + def hook(model, input, output): + activations[name] = output + + return hook + + +def get_readout_oper(vit_features, features, use_readout, start_index=1): + if use_readout == "ignore": + readout_oper = [Slice(start_index)] * len(features) + elif use_readout == "add": + readout_oper = [AddReadout(start_index)] * len(features) + elif use_readout == "project": + readout_oper = [ + ProjectReadout(vit_features, start_index) for out_feat in features + ] + else: + assert ( + False + ), "wrong operation for readout token, use_readout can be 'ignore', 'add', or 'project'" + + return readout_oper + + +def _make_vit_b16_backbone( + model, + features=[96, 192, 384, 768], + size=[384, 384], + hooks=[2, 5, 8, 11], + vit_features=768, + use_readout="ignore", + start_index=1, +): + pretrained = nn.Module() + + pretrained.model = model + pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1")) + pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2")) + pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3")) + pretrained.model.blocks[hooks[3]].register_forward_hook(get_activation("4")) + + pretrained.activations = activations + + readout_oper = get_readout_oper(vit_features, features, use_readout, start_index) + + # 32, 48, 136, 384 + pretrained.act_postprocess1 = nn.Sequential( + readout_oper[0], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[0], + kernel_size=1, + stride=1, + padding=0, + ), + nn.ConvTranspose2d( + in_channels=features[0], + out_channels=features[0], + kernel_size=4, + stride=4, + padding=0, + bias=True, + dilation=1, + groups=1, + ), + ) + + pretrained.act_postprocess2 = nn.Sequential( + readout_oper[1], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[1], + kernel_size=1, + stride=1, + padding=0, + ), + nn.ConvTranspose2d( + in_channels=features[1], + out_channels=features[1], + kernel_size=2, + stride=2, + padding=0, + bias=True, + dilation=1, + groups=1, + ), + ) + + pretrained.act_postprocess3 = nn.Sequential( + readout_oper[2], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[2], + kernel_size=1, + stride=1, + padding=0, + ), + ) + + pretrained.act_postprocess4 = nn.Sequential( + readout_oper[3], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[3], + kernel_size=1, + stride=1, + padding=0, + ), + nn.Conv2d( + in_channels=features[3], + out_channels=features[3], + kernel_size=3, + stride=2, + padding=1, + ), + ) + + pretrained.model.start_index = start_index + pretrained.model.patch_size = [16, 16] + + # We inject this function into the VisionTransformer instances so that + # we can use it with interpolated position embeddings without modifying the library source. + pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model) + pretrained.model._resize_pos_embed = types.MethodType( + _resize_pos_embed, pretrained.model + ) + + return pretrained + + +def _make_pretrained_vitl16_384(pretrained, use_readout="ignore", hooks=None): + model = timm.create_model("vit_large_patch16_384", pretrained=pretrained) + + hooks = [5, 11, 17, 23] if hooks == None else hooks + return _make_vit_b16_backbone( + model, + features=[256, 512, 1024, 1024], + hooks=hooks, + vit_features=1024, + use_readout=use_readout, + ) + + +def _make_pretrained_vitb16_384(pretrained, use_readout="ignore", hooks=None): + model = timm.create_model("vit_base_patch16_384", pretrained=pretrained) + + hooks = [2, 5, 8, 11] if hooks == None else hooks + return _make_vit_b16_backbone( + model, features=[96, 192, 384, 768], hooks=hooks, use_readout=use_readout + ) + + +def _make_pretrained_deitb16_384(pretrained, use_readout="ignore", hooks=None): + model = timm.create_model("vit_deit_base_patch16_384", pretrained=pretrained) + + hooks = [2, 5, 8, 11] if hooks == None else hooks + return _make_vit_b16_backbone( + model, features=[96, 192, 384, 768], hooks=hooks, use_readout=use_readout + ) + + +def _make_pretrained_deitb16_distil_384(pretrained, use_readout="ignore", hooks=None): + model = timm.create_model( + "vit_deit_base_distilled_patch16_384", pretrained=pretrained + ) + + hooks = [2, 5, 8, 11] if hooks == None else hooks + return _make_vit_b16_backbone( + model, + features=[96, 192, 384, 768], + hooks=hooks, + use_readout=use_readout, + start_index=2, + ) + + +def _make_vit_b_rn50_backbone( + model, + features=[256, 512, 768, 768], + size=[384, 384], + hooks=[0, 1, 8, 11], + vit_features=768, + use_vit_only=False, + use_readout="ignore", + start_index=1, +): + pretrained = nn.Module() + + pretrained.model = model + + if use_vit_only == True: + pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1")) + pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2")) + else: + pretrained.model.patch_embed.backbone.stages[0].register_forward_hook( + get_activation("1") + ) + pretrained.model.patch_embed.backbone.stages[1].register_forward_hook( + get_activation("2") + ) + + pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3")) + pretrained.model.blocks[hooks[3]].register_forward_hook(get_activation("4")) + + pretrained.activations = activations + + readout_oper = get_readout_oper(vit_features, features, use_readout, start_index) + + if use_vit_only == True: + pretrained.act_postprocess1 = nn.Sequential( + readout_oper[0], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[0], + kernel_size=1, + stride=1, + padding=0, + ), + nn.ConvTranspose2d( + in_channels=features[0], + out_channels=features[0], + kernel_size=4, + stride=4, + padding=0, + bias=True, + dilation=1, + groups=1, + ), + ) + + pretrained.act_postprocess2 = nn.Sequential( + readout_oper[1], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[1], + kernel_size=1, + stride=1, + padding=0, + ), + nn.ConvTranspose2d( + in_channels=features[1], + out_channels=features[1], + kernel_size=2, + stride=2, + padding=0, + bias=True, + dilation=1, + groups=1, + ), + ) + else: + pretrained.act_postprocess1 = nn.Sequential( + nn.Identity(), nn.Identity(), nn.Identity() + ) + pretrained.act_postprocess2 = nn.Sequential( + nn.Identity(), nn.Identity(), nn.Identity() + ) + + pretrained.act_postprocess3 = nn.Sequential( + readout_oper[2], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[2], + kernel_size=1, + stride=1, + padding=0, + ), + ) + + pretrained.act_postprocess4 = nn.Sequential( + readout_oper[3], + Transpose(1, 2), + nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])), + nn.Conv2d( + in_channels=vit_features, + out_channels=features[3], + kernel_size=1, + stride=1, + padding=0, + ), + nn.Conv2d( + in_channels=features[3], + out_channels=features[3], + kernel_size=3, + stride=2, + padding=1, + ), + ) + + pretrained.model.start_index = start_index + pretrained.model.patch_size = [16, 16] + + # We inject this function into the VisionTransformer instances so that + # we can use it with interpolated position embeddings without modifying the library source. + pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model) + + # We inject this function into the VisionTransformer instances so that + # we can use it with interpolated position embeddings without modifying the library source. + pretrained.model._resize_pos_embed = types.MethodType( + _resize_pos_embed, pretrained.model + ) + + return pretrained + + +def _make_pretrained_vitb_rn50_384( + pretrained, use_readout="ignore", hooks=None, use_vit_only=False +): + model = timm.create_model("vit_base_resnet50_384", pretrained=pretrained) + + hooks = [0, 1, 8, 11] if hooks == None else hooks + return _make_vit_b_rn50_backbone( + model, + features=[256, 512, 768, 768], + size=[384, 384], + hooks=hooks, + use_vit_only=use_vit_only, + use_readout=use_readout, + ) diff --git a/extensions/deforum/scripts/deforum_helpers/src/model_io.py b/extensions/deforum/scripts/deforum_helpers/src/model_io.py new file mode 100644 index 0000000000000000000000000000000000000000..3427be8176f178c4c3ef09664a3f28d9fbaab4c3 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/model_io.py @@ -0,0 +1,74 @@ +import os + +import torch + + +def save_weights(model, filename, path="./saved_models"): + if not os.path.isdir(path): + os.makedirs(path) + + fpath = os.path.join(path, filename) + torch.save(model.state_dict(), fpath) + return + + +def save_checkpoint(model, optimizer, epoch, filename, root="./checkpoints"): + if not os.path.isdir(root): + os.makedirs(root) + + fpath = os.path.join(root, filename) + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + "epoch": epoch + } + , fpath) + + +def load_weights(model, filename, path="./saved_models"): + fpath = os.path.join(path, filename) + state_dict = torch.load(fpath) + model.load_state_dict(state_dict) + return model + + +def load_checkpoint(fpath, model, optimizer=None): + ckpt = torch.load(fpath, map_location='cpu') + if ckpt is None: + raise Exception(f"\nERROR Loading AdaBins_nyu.pt. Read this for a fix:\nhttps://github.com/deforum-art/deforum-for-automatic1111-webui/wiki/FAQ-&-Troubleshooting#3d-animation-mode-is-not-working-only-2d-works") + if optimizer is None: + optimizer = ckpt.get('optimizer', None) + else: + optimizer.load_state_dict(ckpt['optimizer']) + epoch = ckpt['epoch'] + + if 'model' in ckpt: + ckpt = ckpt['model'] + load_dict = {} + for k, v in ckpt.items(): + if k.startswith('module.'): + k_ = k.replace('module.', '') + load_dict[k_] = v + else: + load_dict[k] = v + + modified = {} # backward compatibility to older naming of architecture blocks + for k, v in load_dict.items(): + if k.startswith('adaptive_bins_layer.embedding_conv.'): + k_ = k.replace('adaptive_bins_layer.embedding_conv.', + 'adaptive_bins_layer.conv3x3.') + modified[k_] = v + # del load_dict[k] + + elif k.startswith('adaptive_bins_layer.patch_transformer.embedding_encoder'): + + k_ = k.replace('adaptive_bins_layer.patch_transformer.embedding_encoder', + 'adaptive_bins_layer.patch_transformer.embedding_convPxP') + modified[k_] = v + # del load_dict[k] + else: + modified[k] = v # else keep the original + + model.load_state_dict(modified) + return model, optimizer, epoch diff --git a/extensions/deforum/scripts/deforum_helpers/src/py3d_tools.py b/extensions/deforum/scripts/deforum_helpers/src/py3d_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..5eb958607c4fd405a06bb67e33963e744fd2306f --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/py3d_tools.py @@ -0,0 +1,1801 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import sys +import math +import warnings +from typing import List, Optional, Sequence, Tuple, Union, Any + +import numpy as np +import torch +import torch.nn.functional as F + +import copy +import inspect +import torch.nn as nn + +Device = Union[str, torch.device] + +# Default values for rotation and translation matrices. +_R = torch.eye(3)[None] # (1, 3, 3) +_T = torch.zeros(1, 3) # (1, 3) + + +# Provide get_origin and get_args even in Python 3.7. + +if sys.version_info >= (3, 8, 0): + from typing import get_args, get_origin +elif sys.version_info >= (3, 7, 0): + + def get_origin(cls): # pragma: no cover + return getattr(cls, "__origin__", None) + + def get_args(cls): # pragma: no cover + return getattr(cls, "__args__", None) + + +else: + raise ImportError("This module requires Python 3.7+") + +################################################################ +## ██████╗██╗ █████╗ ███████╗███████╗███████╗███████╗ ## +## ██╔════╝██║ ██╔══██╗██╔════╝██╔════╝██╔════╝██╔════╝ ## +## ██║ ██║ ███████║███████╗███████╗█████╗ ███████╗ ## +## ██║ ██║ ██╔══██║╚════██║╚════██║██╔══╝ ╚════██║ ## +## ╚██████╗███████╗██║ ██║███████║███████║███████╗███████║ ## +## ╚═════╝╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝╚══════╝ ## +################################################################ + +class Transform3d: + """ + A Transform3d object encapsulates a batch of N 3D transformations, and knows + how to transform points and normal vectors. Suppose that t is a Transform3d; + then we can do the following: + + .. code-block:: python + + N = len(t) + points = torch.randn(N, P, 3) + normals = torch.randn(N, P, 3) + points_transformed = t.transform_points(points) # => (N, P, 3) + normals_transformed = t.transform_normals(normals) # => (N, P, 3) + + + BROADCASTING + Transform3d objects supports broadcasting. Suppose that t1 and tN are + Transform3d objects with len(t1) == 1 and len(tN) == N respectively. Then we + can broadcast transforms like this: + + .. code-block:: python + + t1.transform_points(torch.randn(P, 3)) # => (P, 3) + t1.transform_points(torch.randn(1, P, 3)) # => (1, P, 3) + t1.transform_points(torch.randn(M, P, 3)) # => (M, P, 3) + tN.transform_points(torch.randn(P, 3)) # => (N, P, 3) + tN.transform_points(torch.randn(1, P, 3)) # => (N, P, 3) + + + COMBINING TRANSFORMS + Transform3d objects can be combined in two ways: composing and stacking. + Composing is function composition. Given Transform3d objects t1, t2, t3, + the following all compute the same thing: + + .. code-block:: python + + y1 = t3.transform_points(t2.transform_points(t1.transform_points(x))) + y2 = t1.compose(t2).compose(t3).transform_points(x) + y3 = t1.compose(t2, t3).transform_points(x) + + + Composing transforms should broadcast. + + .. code-block:: python + + if len(t1) == 1 and len(t2) == N, then len(t1.compose(t2)) == N. + + We can also stack a sequence of Transform3d objects, which represents + composition along the batch dimension; then the following should compute the + same thing. + + .. code-block:: python + + N, M = len(tN), len(tM) + xN = torch.randn(N, P, 3) + xM = torch.randn(M, P, 3) + y1 = torch.cat([tN.transform_points(xN), tM.transform_points(xM)], dim=0) + y2 = tN.stack(tM).transform_points(torch.cat([xN, xM], dim=0)) + + BUILDING TRANSFORMS + We provide convenience methods for easily building Transform3d objects + as compositions of basic transforms. + + .. code-block:: python + + # Scale by 0.5, then translate by (1, 2, 3) + t1 = Transform3d().scale(0.5).translate(1, 2, 3) + + # Scale each axis by a different amount, then translate, then scale + t2 = Transform3d().scale(1, 3, 3).translate(2, 3, 1).scale(2.0) + + t3 = t1.compose(t2) + tN = t1.stack(t3, t3) + + + BACKPROP THROUGH TRANSFORMS + When building transforms, we can also parameterize them by Torch tensors; + in this case we can backprop through the construction and application of + Transform objects, so they could be learned via gradient descent or + predicted by a neural network. + + .. code-block:: python + + s1_params = torch.randn(N, requires_grad=True) + t_params = torch.randn(N, 3, requires_grad=True) + s2_params = torch.randn(N, 3, requires_grad=True) + + t = Transform3d().scale(s1_params).translate(t_params).scale(s2_params) + x = torch.randn(N, 3) + y = t.transform_points(x) + loss = compute_loss(y) + loss.backward() + + with torch.no_grad(): + s1_params -= lr * s1_params.grad + t_params -= lr * t_params.grad + s2_params -= lr * s2_params.grad + + CONVENTIONS + We adopt a right-hand coordinate system, meaning that rotation about an axis + with a positive angle results in a counter clockwise rotation. + + This class assumes that transformations are applied on inputs which + are row vectors. The internal representation of the Nx4x4 transformation + matrix is of the form: + + .. code-block:: python + + M = [ + [Rxx, Ryx, Rzx, 0], + [Rxy, Ryy, Rzy, 0], + [Rxz, Ryz, Rzz, 0], + [Tx, Ty, Tz, 1], + ] + + To apply the transformation to points which are row vectors, the M matrix + can be pre multiplied by the points: + + .. code-block:: python + + points = [[0, 1, 2]] # (1 x 3) xyz coordinates of a point + transformed_points = points * M + + """ + + def __init__( + self, + dtype: torch.dtype = torch.float32, + device: Device = "cpu", + matrix: Optional[torch.Tensor] = None, + ) -> None: + """ + Args: + dtype: The data type of the transformation matrix. + to be used if `matrix = None`. + device: The device for storing the implemented transformation. + If `matrix != None`, uses the device of input `matrix`. + matrix: A tensor of shape (4, 4) or of shape (minibatch, 4, 4) + representing the 4x4 3D transformation matrix. + If `None`, initializes with identity using + the specified `device` and `dtype`. + """ + + if matrix is None: + self._matrix = torch.eye(4, dtype=dtype, device=device).view(1, 4, 4) + else: + if matrix.ndim not in (2, 3): + raise ValueError('"matrix" has to be a 2- or a 3-dimensional tensor.') + if matrix.shape[-2] != 4 or matrix.shape[-1] != 4: + raise ValueError( + '"matrix" has to be a tensor of shape (minibatch, 4, 4)' + ) + # set dtype and device from matrix + dtype = matrix.dtype + device = matrix.device + self._matrix = matrix.view(-1, 4, 4) + + self._transforms = [] # store transforms to compose + self._lu = None + self.device = make_device(device) + self.dtype = dtype + + def __len__(self) -> int: + return self.get_matrix().shape[0] + + def __getitem__( + self, index: Union[int, List[int], slice, torch.Tensor] + ) -> "Transform3d": + """ + Args: + index: Specifying the index of the transform to retrieve. + Can be an int, slice, list of ints, boolean, long tensor. + Supports negative indices. + + Returns: + Transform3d object with selected transforms. The tensors are not cloned. + """ + if isinstance(index, int): + index = [index] + return self.__class__(matrix=self.get_matrix()[index]) + + def compose(self, *others: "Transform3d") -> "Transform3d": + """ + Return a new Transform3d representing the composition of self with the + given other transforms, which will be stored as an internal list. + + Args: + *others: Any number of Transform3d objects + + Returns: + A new Transform3d with the stored transforms + """ + out = Transform3d(dtype=self.dtype, device=self.device) + out._matrix = self._matrix.clone() + for other in others: + if not isinstance(other, Transform3d): + msg = "Only possible to compose Transform3d objects; got %s" + raise ValueError(msg % type(other)) + out._transforms = self._transforms + list(others) + return out + + def get_matrix(self) -> torch.Tensor: + """ + Return a matrix which is the result of composing this transform + with others stored in self.transforms. Where necessary transforms + are broadcast against each other. + For example, if self.transforms contains transforms t1, t2, and t3, and + given a set of points x, the following should be true: + + .. code-block:: python + + y1 = t1.compose(t2, t3).transform(x) + y2 = t3.transform(t2.transform(t1.transform(x))) + y1.get_matrix() == y2.get_matrix() + + Returns: + A transformation matrix representing the composed inputs. + """ + composed_matrix = self._matrix.clone() + if len(self._transforms) > 0: + for other in self._transforms: + other_matrix = other.get_matrix() + composed_matrix = _broadcast_bmm(composed_matrix, other_matrix) + return composed_matrix + + def _get_matrix_inverse(self) -> torch.Tensor: + """ + Return the inverse of self._matrix. + """ + return torch.inverse(self._matrix) + + def inverse(self, invert_composed: bool = False) -> "Transform3d": + """ + Returns a new Transform3d object that represents an inverse of the + current transformation. + + Args: + invert_composed: + - True: First compose the list of stored transformations + and then apply inverse to the result. This is + potentially slower for classes of transformations + with inverses that can be computed efficiently + (e.g. rotations and translations). + - False: Invert the individual stored transformations + independently without composing them. + + Returns: + A new Transform3d object containing the inverse of the original + transformation. + """ + + tinv = Transform3d(dtype=self.dtype, device=self.device) + + if invert_composed: + # first compose then invert + tinv._matrix = torch.inverse(self.get_matrix()) + else: + # self._get_matrix_inverse() implements efficient inverse + # of self._matrix + i_matrix = self._get_matrix_inverse() + + # 2 cases: + if len(self._transforms) > 0: + # a) Either we have a non-empty list of transforms: + # Here we take self._matrix and append its inverse at the + # end of the reverted _transforms list. After composing + # the transformations with get_matrix(), this correctly + # right-multiplies by the inverse of self._matrix + # at the end of the composition. + tinv._transforms = [t.inverse() for t in reversed(self._transforms)] + last = Transform3d(dtype=self.dtype, device=self.device) + last._matrix = i_matrix + tinv._transforms.append(last) + else: + # b) Or there are no stored transformations + # we just set inverted matrix + tinv._matrix = i_matrix + + return tinv + + def stack(self, *others: "Transform3d") -> "Transform3d": + """ + Return a new batched Transform3d representing the batch elements from + self and all the given other transforms all batched together. + + Args: + *others: Any number of Transform3d objects + + Returns: + A new Transform3d. + """ + transforms = [self] + list(others) + matrix = torch.cat([t.get_matrix() for t in transforms], dim=0) + out = Transform3d(dtype=self.dtype, device=self.device) + out._matrix = matrix + return out + + def transform_points(self, points, eps: Optional[float] = None) -> torch.Tensor: + """ + Use this transform to transform a set of 3D points. Assumes row major + ordering of the input points. + + Args: + points: Tensor of shape (P, 3) or (N, P, 3) + eps: If eps!=None, the argument is used to clamp the + last coordinate before performing the final division. + The clamping corresponds to: + last_coord := (last_coord.sign() + (last_coord==0)) * + torch.clamp(last_coord.abs(), eps), + i.e. the last coordinates that are exactly 0 will + be clamped to +eps. + + Returns: + points_out: points of shape (N, P, 3) or (P, 3) depending + on the dimensions of the transform + """ + points_batch = points.clone() + if points_batch.dim() == 2: + points_batch = points_batch[None] # (P, 3) -> (1, P, 3) + if points_batch.dim() != 3: + msg = "Expected points to have dim = 2 or dim = 3: got shape %r" + raise ValueError(msg % repr(points.shape)) + + N, P, _3 = points_batch.shape + ones = torch.ones(N, P, 1, dtype=points.dtype, device=points.device) + points_batch = torch.cat([points_batch, ones], dim=2) + + composed_matrix = self.get_matrix() + points_out = _broadcast_bmm(points_batch, composed_matrix) + denom = points_out[..., 3:] # denominator + if eps is not None: + denom_sign = denom.sign() + (denom == 0.0).type_as(denom) + denom = denom_sign * torch.clamp(denom.abs(), eps) + points_out = points_out[..., :3] / denom + + # When transform is (1, 4, 4) and points is (P, 3) return + # points_out of shape (P, 3) + if points_out.shape[0] == 1 and points.dim() == 2: + points_out = points_out.reshape(points.shape) + + return points_out + + def transform_normals(self, normals) -> torch.Tensor: + """ + Use this transform to transform a set of normal vectors. + + Args: + normals: Tensor of shape (P, 3) or (N, P, 3) + + Returns: + normals_out: Tensor of shape (P, 3) or (N, P, 3) depending + on the dimensions of the transform + """ + if normals.dim() not in [2, 3]: + msg = "Expected normals to have dim = 2 or dim = 3: got shape %r" + raise ValueError(msg % (normals.shape,)) + composed_matrix = self.get_matrix() + + # TODO: inverse is bad! Solve a linear system instead + mat = composed_matrix[:, :3, :3] + normals_out = _broadcast_bmm(normals, mat.transpose(1, 2).inverse()) + + # This doesn't pass unit tests. TODO investigate further + # if self._lu is None: + # self._lu = self._matrix[:, :3, :3].transpose(1, 2).lu() + # normals_out = normals.lu_solve(*self._lu) + + # When transform is (1, 4, 4) and normals is (P, 3) return + # normals_out of shape (P, 3) + if normals_out.shape[0] == 1 and normals.dim() == 2: + normals_out = normals_out.reshape(normals.shape) + + return normals_out + + def translate(self, *args, **kwargs) -> "Transform3d": + return self.compose( + Translate(device=self.device, dtype=self.dtype, *args, **kwargs) + ) + + def scale(self, *args, **kwargs) -> "Transform3d": + return self.compose( + Scale(device=self.device, dtype=self.dtype, *args, **kwargs) + ) + + def rotate(self, *args, **kwargs) -> "Transform3d": + return self.compose( + Rotate(device=self.device, dtype=self.dtype, *args, **kwargs) + ) + + def rotate_axis_angle(self, *args, **kwargs) -> "Transform3d": + return self.compose( + RotateAxisAngle(device=self.device, dtype=self.dtype, *args, **kwargs) + ) + + def clone(self) -> "Transform3d": + """ + Deep copy of Transforms object. All internal tensors are cloned + individually. + + Returns: + new Transforms object. + """ + other = Transform3d(dtype=self.dtype, device=self.device) + if self._lu is not None: + other._lu = [elem.clone() for elem in self._lu] + other._matrix = self._matrix.clone() + other._transforms = [t.clone() for t in self._transforms] + return other + + def to( + self, + device: Device, + copy: bool = False, + dtype: Optional[torch.dtype] = None, + ) -> "Transform3d": + """ + Match functionality of torch.Tensor.to() + If copy = True or the self Tensor is on a different device, the + returned tensor is a copy of self with the desired torch.device. + If copy = False and the self Tensor already has the correct torch.device, + then self is returned. + + Args: + device: Device (as str or torch.device) for the new tensor. + copy: Boolean indicator whether or not to clone self. Default False. + dtype: If not None, casts the internal tensor variables + to a given torch.dtype. + + Returns: + Transform3d object. + """ + device_ = make_device(device) + dtype_ = self.dtype if dtype is None else dtype + skip_to = self.device == device_ and self.dtype == dtype_ + + if not copy and skip_to: + return self + + other = self.clone() + + if skip_to: + return other + + other.device = device_ + other.dtype = dtype_ + other._matrix = other._matrix.to(device=device_, dtype=dtype_) + other._transforms = [ + t.to(device_, copy=copy, dtype=dtype_) for t in other._transforms + ] + return other + + def cpu(self) -> "Transform3d": + return self.to("cpu") + + def cuda(self) -> "Transform3d": + return self.to("cuda") + +class Translate(Transform3d): + def __init__( + self, + x, + y=None, + z=None, + dtype: torch.dtype = torch.float32, + device: Optional[Device] = None, + ) -> None: + """ + Create a new Transform3d representing 3D translations. + + Option I: Translate(xyz, dtype=torch.float32, device='cpu') + xyz should be a tensor of shape (N, 3) + + Option II: Translate(x, y, z, dtype=torch.float32, device='cpu') + Here x, y, and z will be broadcast against each other and + concatenated to form the translation. Each can be: + - A python scalar + - A torch scalar + - A 1D torch tensor + """ + xyz = _handle_input(x, y, z, dtype, device, "Translate") + super().__init__(device=xyz.device, dtype=dtype) + N = xyz.shape[0] + + mat = torch.eye(4, dtype=dtype, device=self.device) + mat = mat.view(1, 4, 4).repeat(N, 1, 1) + mat[:, 3, :3] = xyz + self._matrix = mat + + def _get_matrix_inverse(self) -> torch.Tensor: + """ + Return the inverse of self._matrix. + """ + inv_mask = self._matrix.new_ones([1, 4, 4]) + inv_mask[0, 3, :3] = -1.0 + i_matrix = self._matrix * inv_mask + return i_matrix + +class Rotate(Transform3d): + def __init__( + self, + R: torch.Tensor, + dtype: torch.dtype = torch.float32, + device: Optional[Device] = None, + orthogonal_tol: float = 1e-5, + ) -> None: + """ + Create a new Transform3d representing 3D rotation using a rotation + matrix as the input. + + Args: + R: a tensor of shape (3, 3) or (N, 3, 3) + orthogonal_tol: tolerance for the test of the orthogonality of R + + """ + device_ = get_device(R, device) + super().__init__(device=device_, dtype=dtype) + if R.dim() == 2: + R = R[None] + if R.shape[-2:] != (3, 3): + msg = "R must have shape (3, 3) or (N, 3, 3); got %s" + raise ValueError(msg % repr(R.shape)) + R = R.to(device=device_, dtype=dtype) + _check_valid_rotation_matrix(R, tol=orthogonal_tol) + N = R.shape[0] + mat = torch.eye(4, dtype=dtype, device=device_) + mat = mat.view(1, 4, 4).repeat(N, 1, 1) + mat[:, :3, :3] = R + self._matrix = mat + + def _get_matrix_inverse(self) -> torch.Tensor: + """ + Return the inverse of self._matrix. + """ + return self._matrix.permute(0, 2, 1).contiguous() + +class TensorAccessor(nn.Module): + """ + A helper class to be used with the __getitem__ method. This can be used for + getting/setting the values for an attribute of a class at one particular + index. This is useful when the attributes of a class are batched tensors + and one element in the batch needs to be modified. + """ + + def __init__(self, class_object, index: Union[int, slice]) -> None: + """ + Args: + class_object: this should be an instance of a class which has + attributes which are tensors representing a batch of + values. + index: int/slice, an index indicating the position in the batch. + In __setattr__ and __getattr__ only the value of class + attributes at this index will be accessed. + """ + self.__dict__["class_object"] = class_object + self.__dict__["index"] = index + + def __setattr__(self, name: str, value: Any): + """ + Update the attribute given by `name` to the value given by `value` + at the index specified by `self.index`. + Args: + name: str, name of the attribute. + value: value to set the attribute to. + """ + v = getattr(self.class_object, name) + if not torch.is_tensor(v): + msg = "Can only set values on attributes which are tensors; got %r" + raise AttributeError(msg % type(v)) + + # Convert the attribute to a tensor if it is not a tensor. + if not torch.is_tensor(value): + value = torch.tensor( + value, device=v.device, dtype=v.dtype, requires_grad=v.requires_grad + ) + + # Check the shapes match the existing shape and the shape of the index. + if v.dim() > 1 and value.dim() > 1 and value.shape[1:] != v.shape[1:]: + msg = "Expected value to have shape %r; got %r" + raise ValueError(msg % (v.shape, value.shape)) + if ( + v.dim() == 0 + and isinstance(self.index, slice) + and len(value) != len(self.index) + ): + msg = "Expected value to have len %r; got %r" + raise ValueError(msg % (len(self.index), len(value))) + self.class_object.__dict__[name][self.index] = value + + def __getattr__(self, name: str): + """ + Return the value of the attribute given by "name" on self.class_object + at the index specified in self.index. + Args: + name: string of the attribute name + """ + if hasattr(self.class_object, name): + return self.class_object.__dict__[name][self.index] + else: + msg = "Attribute %s not found on %r" + return AttributeError(msg % (name, self.class_object.__name__)) + +BROADCAST_TYPES = (float, int, list, tuple, torch.Tensor, np.ndarray) + +class TensorProperties(nn.Module): + """ + A mix-in class for storing tensors as properties with helper methods. + """ + + def __init__( + self, + dtype: torch.dtype = torch.float32, + device: Device = "cpu", + **kwargs, + ) -> None: + """ + Args: + dtype: data type to set for the inputs + device: Device (as str or torch.device) + kwargs: any number of keyword arguments. Any arguments which are + of type (float/int/list/tuple/tensor/array) are broadcasted and + other keyword arguments are set as attributes. + """ + super().__init__() + self.device = make_device(device) + self._N = 0 + if kwargs is not None: + + # broadcast all inputs which are float/int/list/tuple/tensor/array + # set as attributes anything else e.g. strings, bools + args_to_broadcast = {} + for k, v in kwargs.items(): + if v is None or isinstance(v, (str, bool)): + setattr(self, k, v) + elif isinstance(v, BROADCAST_TYPES): + args_to_broadcast[k] = v + else: + msg = "Arg %s with type %r is not broadcastable" + warnings.warn(msg % (k, type(v))) + + names = args_to_broadcast.keys() + # convert from type dict.values to tuple + values = tuple(v for v in args_to_broadcast.values()) + + if len(values) > 0: + broadcasted_values = convert_to_tensors_and_broadcast( + *values, device=device + ) + + # Set broadcasted values as attributes on self. + for i, n in enumerate(names): + setattr(self, n, broadcasted_values[i]) + if self._N == 0: + self._N = broadcasted_values[i].shape[0] + + def __len__(self) -> int: + return self._N + + def isempty(self) -> bool: + return self._N == 0 + + def __getitem__(self, index: Union[int, slice]) -> TensorAccessor: + """ + Args: + index: an int or slice used to index all the fields. + Returns: + if `index` is an index int/slice return a TensorAccessor class + with getattribute/setattribute methods which return/update the value + at the index in the original class. + """ + if isinstance(index, (int, slice)): + return TensorAccessor(class_object=self, index=index) + + msg = "Expected index of type int or slice; got %r" + raise ValueError(msg % type(index)) + + # pyre-fixme[14]: `to` overrides method defined in `Module` inconsistently. + def to(self, device: Device = "cpu") -> "TensorProperties": + """ + In place operation to move class properties which are tensors to a + specified device. If self has a property "device", update this as well. + """ + device_ = make_device(device) + for k in dir(self): + v = getattr(self, k) + if k == "device": + setattr(self, k, device_) + if torch.is_tensor(v) and v.device != device_: + setattr(self, k, v.to(device_)) + return self + + def cpu(self) -> "TensorProperties": + return self.to("cpu") + + # pyre-fixme[14]: `cuda` overrides method defined in `Module` inconsistently. + def cuda(self, device: Optional[int] = None) -> "TensorProperties": + return self.to(f"cuda:{device}" if device is not None else "cuda") + + def clone(self, other) -> "TensorProperties": + """ + Update the tensor properties of other with the cloned properties of self. + """ + for k in dir(self): + v = getattr(self, k) + if inspect.ismethod(v) or k.startswith("__"): + continue + if torch.is_tensor(v): + v_clone = v.clone() + else: + v_clone = copy.deepcopy(v) + setattr(other, k, v_clone) + return other + + def gather_props(self, batch_idx) -> "TensorProperties": + """ + This is an in place operation to reformat all tensor class attributes + based on a set of given indices using torch.gather. This is useful when + attributes which are batched tensors e.g. shape (N, 3) need to be + multiplied with another tensor which has a different first dimension + e.g. packed vertices of shape (V, 3). + Example + .. code-block:: python + self.specular_color = (N, 3) tensor of specular colors for each mesh + A lighting calculation may use + .. code-block:: python + verts_packed = meshes.verts_packed() # (V, 3) + To multiply these two tensors the batch dimension needs to be the same. + To achieve this we can do + .. code-block:: python + batch_idx = meshes.verts_packed_to_mesh_idx() # (V) + This gives index of the mesh for each vertex in verts_packed. + .. code-block:: python + self.gather_props(batch_idx) + self.specular_color = (V, 3) tensor with the specular color for + each packed vertex. + torch.gather requires the index tensor to have the same shape as the + input tensor so this method takes care of the reshaping of the index + tensor to use with class attributes with arbitrary dimensions. + Args: + batch_idx: shape (B, ...) where `...` represents an arbitrary + number of dimensions + Returns: + self with all properties reshaped. e.g. a property with shape (N, 3) + is transformed to shape (B, 3). + """ + # Iterate through the attributes of the class which are tensors. + for k in dir(self): + v = getattr(self, k) + if torch.is_tensor(v): + if v.shape[0] > 1: + # There are different values for each batch element + # so gather these using the batch_idx. + # First clone the input batch_idx tensor before + # modifying it. + _batch_idx = batch_idx.clone() + idx_dims = _batch_idx.shape + tensor_dims = v.shape + if len(idx_dims) > len(tensor_dims): + msg = "batch_idx cannot have more dimensions than %s. " + msg += "got shape %r and %s has shape %r" + raise ValueError(msg % (k, idx_dims, k, tensor_dims)) + if idx_dims != tensor_dims: + # To use torch.gather the index tensor (_batch_idx) has + # to have the same shape as the input tensor. + new_dims = len(tensor_dims) - len(idx_dims) + new_shape = idx_dims + (1,) * new_dims + expand_dims = (-1,) + tensor_dims[1:] + _batch_idx = _batch_idx.view(*new_shape) + _batch_idx = _batch_idx.expand(*expand_dims) + + v = v.gather(0, _batch_idx) + setattr(self, k, v) + return self + +class CamerasBase(TensorProperties): + """ + `CamerasBase` implements a base class for all cameras. + For cameras, there are four different coordinate systems (or spaces) + - World coordinate system: This is the system the object lives - the world. + - Camera view coordinate system: This is the system that has its origin on the camera + and the and the Z-axis perpendicular to the image plane. + In PyTorch3D, we assume that +X points left, and +Y points up and + +Z points out from the image plane. + The transformation from world --> view happens after applying a rotation (R) + and translation (T) + - NDC coordinate system: This is the normalized coordinate system that confines + in a volume the rendered part of the object or scene. Also known as view volume. + For square images, given the PyTorch3D convention, (+1, +1, znear) + is the top left near corner, and (-1, -1, zfar) is the bottom right far + corner of the volume. + The transformation from view --> NDC happens after applying the camera + projection matrix (P) if defined in NDC space. + For non square images, we scale the points such that smallest side + has range [-1, 1] and the largest side has range [-u, u], with u > 1. + - Screen coordinate system: This is another representation of the view volume with + the XY coordinates defined in image space instead of a normalized space. + A better illustration of the coordinate systems can be found in + pytorch3d/docs/notes/cameras.md. + It defines methods that are common to all camera models: + - `get_camera_center` that returns the optical center of the camera in + world coordinates + - `get_world_to_view_transform` which returns a 3D transform from + world coordinates to the camera view coordinates (R, T) + - `get_full_projection_transform` which composes the projection + transform (P) with the world-to-view transform (R, T) + - `transform_points` which takes a set of input points in world coordinates and + projects to the space the camera is defined in (NDC or screen) + - `get_ndc_camera_transform` which defines the transform from screen/NDC to + PyTorch3D's NDC space + - `transform_points_ndc` which takes a set of points in world coordinates and + projects them to PyTorch3D's NDC space + - `transform_points_screen` which takes a set of points in world coordinates and + projects them to screen space + For each new camera, one should implement the `get_projection_transform` + routine that returns the mapping from camera view coordinates to camera + coordinates (NDC or screen). + Another useful function that is specific to each camera model is + `unproject_points` which sends points from camera coordinates (NDC or screen) + back to camera view or world coordinates depending on the `world_coordinates` + boolean argument of the function. + """ + + # Used in __getitem__ to index the relevant fields + # When creating a new camera, this should be set in the __init__ + _FIELDS: Tuple[str, ...] = () + + # Names of fields which are a constant property of the whole batch, rather + # than themselves a batch of data. + # When joining objects into a batch, they will have to agree. + _SHARED_FIELDS: Tuple[str, ...] = () + + def get_projection_transform(self): + """ + Calculate the projective transformation matrix. + Args: + **kwargs: parameters for the projection can be passed in as keyword + arguments to override the default values set in `__init__`. + Return: + a `Transform3d` object which represents a batch of projection + matrices of shape (N, 3, 3) + """ + raise NotImplementedError() + + def unproject_points(self, xy_depth: torch.Tensor, **kwargs): + """ + Transform input points from camera coodinates (NDC or screen) + to the world / camera coordinates. + Each of the input points `xy_depth` of shape (..., 3) is + a concatenation of the x, y location and its depth. + For instance, for an input 2D tensor of shape `(num_points, 3)` + `xy_depth` takes the following form: + `xy_depth[i] = [x[i], y[i], depth[i]]`, + for a each point at an index `i`. + The following example demonstrates the relationship between + `transform_points` and `unproject_points`: + .. code-block:: python + cameras = # camera object derived from CamerasBase + xyz = # 3D points of shape (batch_size, num_points, 3) + # transform xyz to the camera view coordinates + xyz_cam = cameras.get_world_to_view_transform().transform_points(xyz) + # extract the depth of each point as the 3rd coord of xyz_cam + depth = xyz_cam[:, :, 2:] + # project the points xyz to the camera + xy = cameras.transform_points(xyz)[:, :, :2] + # append depth to xy + xy_depth = torch.cat((xy, depth), dim=2) + # unproject to the world coordinates + xyz_unproj_world = cameras.unproject_points(xy_depth, world_coordinates=True) + print(torch.allclose(xyz, xyz_unproj_world)) # True + # unproject to the camera coordinates + xyz_unproj = cameras.unproject_points(xy_depth, world_coordinates=False) + print(torch.allclose(xyz_cam, xyz_unproj)) # True + Args: + xy_depth: torch tensor of shape (..., 3). + world_coordinates: If `True`, unprojects the points back to world + coordinates using the camera extrinsics `R` and `T`. + `False` ignores `R` and `T` and unprojects to + the camera view coordinates. + from_ndc: If `False` (default), assumes xy part of input is in + NDC space if self.in_ndc(), otherwise in screen space. If + `True`, assumes xy is in NDC space even if the camera + is defined in screen space. + Returns + new_points: unprojected points with the same shape as `xy_depth`. + """ + raise NotImplementedError() + + def get_camera_center(self, **kwargs) -> torch.Tensor: + """ + Return the 3D location of the camera optical center + in the world coordinates. + Args: + **kwargs: parameters for the camera extrinsics can be passed in + as keyword arguments to override the default values + set in __init__. + Setting T here will update the values set in init as this + value may be needed later on in the rendering pipeline e.g. for + lighting calculations. + Returns: + C: a batch of 3D locations of shape (N, 3) denoting + the locations of the center of each camera in the batch. + """ + w2v_trans = self.get_world_to_view_transform(**kwargs) + P = w2v_trans.inverse().get_matrix() + # the camera center is the translation component (the first 3 elements + # of the last row) of the inverted world-to-view + # transform (4x4 RT matrix) + C = P[:, 3, :3] + return C + + def get_world_to_view_transform(self, **kwargs) -> Transform3d: + """ + Return the world-to-view transform. + Args: + **kwargs: parameters for the camera extrinsics can be passed in + as keyword arguments to override the default values + set in __init__. + Setting R and T here will update the values set in init as these + values may be needed later on in the rendering pipeline e.g. for + lighting calculations. + Returns: + A Transform3d object which represents a batch of transforms + of shape (N, 3, 3) + """ + R: torch.Tensor = kwargs.get("R", self.R) + T: torch.Tensor = kwargs.get("T", self.T) + self.R = R # pyre-ignore[16] + self.T = T # pyre-ignore[16] + world_to_view_transform = get_world_to_view_transform(R=R, T=T) + return world_to_view_transform + + def get_full_projection_transform(self, **kwargs) -> Transform3d: + """ + Return the full world-to-camera transform composing the + world-to-view and view-to-camera transforms. + If camera is defined in NDC space, the projected points are in NDC space. + If camera is defined in screen space, the projected points are in screen space. + Args: + **kwargs: parameters for the projection transforms can be passed in + as keyword arguments to override the default values + set in __init__. + Setting R and T here will update the values set in init as these + values may be needed later on in the rendering pipeline e.g. for + lighting calculations. + Returns: + a Transform3d object which represents a batch of transforms + of shape (N, 3, 3) + """ + self.R: torch.Tensor = kwargs.get("R", self.R) # pyre-ignore[16] + self.T: torch.Tensor = kwargs.get("T", self.T) # pyre-ignore[16] + world_to_view_transform = self.get_world_to_view_transform(R=self.R, T=self.T) + view_to_proj_transform = self.get_projection_transform(**kwargs) + return world_to_view_transform.compose(view_to_proj_transform) + + def transform_points( + self, points, eps: Optional[float] = None, **kwargs + ) -> torch.Tensor: + """ + Transform input points from world to camera space with the + projection matrix defined by the camera. + For `CamerasBase.transform_points`, setting `eps > 0` + stabilizes gradients since it leads to avoiding division + by excessively low numbers for points close to the camera plane. + Args: + points: torch tensor of shape (..., 3). + eps: If eps!=None, the argument is used to clamp the + divisor in the homogeneous normalization of the points + transformed to the ndc space. Please see + `transforms.Transform3d.transform_points` for details. + For `CamerasBase.transform_points`, setting `eps > 0` + stabilizes gradients since it leads to avoiding division + by excessively low numbers for points close to the + camera plane. + Returns + new_points: transformed points with the same shape as the input. + """ + world_to_proj_transform = self.get_full_projection_transform(**kwargs) + return world_to_proj_transform.transform_points(points, eps=eps) + + def get_ndc_camera_transform(self, **kwargs) -> Transform3d: + """ + Returns the transform from camera projection space (screen or NDC) to NDC space. + For cameras that can be specified in screen space, this transform + allows points to be converted from screen to NDC space. + The default transform scales the points from [0, W]x[0, H] + to [-1, 1]x[-u, u] or [-u, u]x[-1, 1] where u > 1 is the aspect ratio of the image. + This function should be modified per camera definitions if need be, + e.g. for Perspective/Orthographic cameras we provide a custom implementation. + This transform assumes PyTorch3D coordinate system conventions for + both the NDC space and the input points. + This transform interfaces with the PyTorch3D renderer which assumes + input points to the renderer to be in NDC space. + """ + if self.in_ndc(): + return Transform3d(device=self.device, dtype=torch.float32) + else: + # For custom cameras which can be defined in screen space, + # users might might have to implement the screen to NDC transform based + # on the definition of the camera parameters. + # See PerspectiveCameras/OrthographicCameras for an example. + # We don't flip xy because we assume that world points are in + # PyTorch3D coordinates, and thus conversion from screen to ndc + # is a mere scaling from image to [-1, 1] scale. + image_size = kwargs.get("image_size", self.get_image_size()) + return get_screen_to_ndc_transform( + self, with_xyflip=False, image_size=image_size + ) + + def transform_points_ndc( + self, points, eps: Optional[float] = None, **kwargs + ) -> torch.Tensor: + """ + Transforms points from PyTorch3D world/camera space to NDC space. + Input points follow the PyTorch3D coordinate system conventions: +X left, +Y up. + Output points are in NDC space: +X left, +Y up, origin at image center. + Args: + points: torch tensor of shape (..., 3). + eps: If eps!=None, the argument is used to clamp the + divisor in the homogeneous normalization of the points + transformed to the ndc space. Please see + `transforms.Transform3d.transform_points` for details. + For `CamerasBase.transform_points`, setting `eps > 0` + stabilizes gradients since it leads to avoiding division + by excessively low numbers for points close to the + camera plane. + Returns + new_points: transformed points with the same shape as the input. + """ + world_to_ndc_transform = self.get_full_projection_transform(**kwargs) + if not self.in_ndc(): + to_ndc_transform = self.get_ndc_camera_transform(**kwargs) + world_to_ndc_transform = world_to_ndc_transform.compose(to_ndc_transform) + + return world_to_ndc_transform.transform_points(points, eps=eps) + + def transform_points_screen( + self, points, eps: Optional[float] = None, **kwargs + ) -> torch.Tensor: + """ + Transforms points from PyTorch3D world/camera space to screen space. + Input points follow the PyTorch3D coordinate system conventions: +X left, +Y up. + Output points are in screen space: +X right, +Y down, origin at top left corner. + Args: + points: torch tensor of shape (..., 3). + eps: If eps!=None, the argument is used to clamp the + divisor in the homogeneous normalization of the points + transformed to the ndc space. Please see + `transforms.Transform3d.transform_points` for details. + For `CamerasBase.transform_points`, setting `eps > 0` + stabilizes gradients since it leads to avoiding division + by excessively low numbers for points close to the + camera plane. + Returns + new_points: transformed points with the same shape as the input. + """ + points_ndc = self.transform_points_ndc(points, eps=eps, **kwargs) + image_size = kwargs.get("image_size", self.get_image_size()) + return get_ndc_to_screen_transform( + self, with_xyflip=True, image_size=image_size + ).transform_points(points_ndc, eps=eps) + + def clone(self): + """ + Returns a copy of `self`. + """ + cam_type = type(self) + other = cam_type(device=self.device) + return super().clone(other) + + def is_perspective(self): + raise NotImplementedError() + + def in_ndc(self): + """ + Specifies whether the camera is defined in NDC space + or in screen (image) space + """ + raise NotImplementedError() + + def get_znear(self): + return self.znear if hasattr(self, "znear") else None + + def get_image_size(self): + """ + Returns the image size, if provided, expected in the form of (height, width) + The image size is used for conversion of projected points to screen coordinates. + """ + return self.image_size if hasattr(self, "image_size") else None + + def __getitem__( + self, index: Union[int, List[int], torch.LongTensor] + ) -> "CamerasBase": + """ + Override for the __getitem__ method in TensorProperties which needs to be + refactored. + Args: + index: an int/list/long tensor used to index all the fields in the cameras given by + self._FIELDS. + Returns: + if `index` is an index int/list/long tensor return an instance of the current + cameras class with only the values at the selected index. + """ + + kwargs = {} + + if not isinstance(index, (int, list, torch.LongTensor, torch.cuda.LongTensor)): + msg = "Invalid index type, expected int, List[int] or torch.LongTensor; got %r" + raise ValueError(msg % type(index)) + + if isinstance(index, int): + index = [index] + + if max(index) >= len(self): + raise ValueError(f"Index {max(index)} is out of bounds for select cameras") + + for field in self._FIELDS: + val = getattr(self, field, None) + if val is None: + continue + + # e.g. "in_ndc" is set as attribute "_in_ndc" on the class + # but provided as "in_ndc" on initialization + if field.startswith("_"): + field = field[1:] + + if isinstance(val, (str, bool)): + kwargs[field] = val + elif isinstance(val, torch.Tensor): + # In the init, all inputs will be converted to + # tensors before setting as attributes + kwargs[field] = val[index] + else: + raise ValueError(f"Field {field} type is not supported for indexing") + + kwargs["device"] = self.device + return self.__class__(**kwargs) + +class FoVPerspectiveCameras(CamerasBase): + """ + A class which stores a batch of parameters to generate a batch of + projection matrices by specifying the field of view. + The definition of the parameters follow the OpenGL perspective camera. + + The extrinsics of the camera (R and T matrices) can also be set in the + initializer or passed in to `get_full_projection_transform` to get + the full transformation from world -> ndc. + + The `transform_points` method calculates the full world -> ndc transform + and then applies it to the input points. + + The transforms can also be returned separately as Transform3d objects. + + * Setting the Aspect Ratio for Non Square Images * + + If the desired output image size is non square (i.e. a tuple of (H, W) where H != W) + the aspect ratio needs special consideration: There are two aspect ratios + to be aware of: + - the aspect ratio of each pixel + - the aspect ratio of the output image + The `aspect_ratio` setting in the FoVPerspectiveCameras sets the + pixel aspect ratio. When using this camera with the differentiable rasterizer + be aware that in the rasterizer we assume square pixels, but allow + variable image aspect ratio (i.e rectangle images). + + In most cases you will want to set the camera `aspect_ratio=1.0` + (i.e. square pixels) and only vary the output image dimensions in pixels + for rasterization. + """ + + # For __getitem__ + _FIELDS = ( + "K", + "znear", + "zfar", + "aspect_ratio", + "fov", + "R", + "T", + "degrees", + ) + + _SHARED_FIELDS = ("degrees",) + + def __init__( + self, + znear=1.0, + zfar=100.0, + aspect_ratio=1.0, + fov=60.0, + degrees: bool = True, + R: torch.Tensor = _R, + T: torch.Tensor = _T, + K: Optional[torch.Tensor] = None, + device: Device = "cpu", + ) -> None: + """ + + Args: + znear: near clipping plane of the view frustrum. + zfar: far clipping plane of the view frustrum. + aspect_ratio: aspect ratio of the image pixels. + 1.0 indicates square pixels. + fov: field of view angle of the camera. + degrees: bool, set to True if fov is specified in degrees. + R: Rotation matrix of shape (N, 3, 3) + T: Translation matrix of shape (N, 3) + K: (optional) A calibration matrix of shape (N, 4, 4) + If provided, don't need znear, zfar, fov, aspect_ratio, degrees + device: Device (as str or torch.device) + """ + # The initializer formats all inputs to torch tensors and broadcasts + # all the inputs to have the same batch dimension where necessary. + super().__init__( + device=device, + znear=znear, + zfar=zfar, + aspect_ratio=aspect_ratio, + fov=fov, + R=R, + T=T, + K=K, + ) + + # No need to convert to tensor or broadcast. + self.degrees = degrees + + def compute_projection_matrix( + self, znear, zfar, fov, aspect_ratio, degrees: bool + ) -> torch.Tensor: + """ + Compute the calibration matrix K of shape (N, 4, 4) + + Args: + znear: near clipping plane of the view frustrum. + zfar: far clipping plane of the view frustrum. + fov: field of view angle of the camera. + aspect_ratio: aspect ratio of the image pixels. + 1.0 indicates square pixels. + degrees: bool, set to True if fov is specified in degrees. + + Returns: + torch.FloatTensor of the calibration matrix with shape (N, 4, 4) + """ + K = torch.zeros((self._N, 4, 4), device=self.device, dtype=torch.float32) + ones = torch.ones((self._N), dtype=torch.float32, device=self.device) + if degrees: + fov = (np.pi / 180) * fov + + if not torch.is_tensor(fov): + fov = torch.tensor(fov, device=self.device) + tanHalfFov = torch.tan((fov / 2)) + max_y = tanHalfFov * znear + min_y = -max_y + max_x = max_y * aspect_ratio + min_x = -max_x + + # NOTE: In OpenGL the projection matrix changes the handedness of the + # coordinate frame. i.e the NDC space positive z direction is the + # camera space negative z direction. This is because the sign of the z + # in the projection matrix is set to -1.0. + # In pytorch3d we maintain a right handed coordinate system throughout + # so the so the z sign is 1.0. + z_sign = 1.0 + + K[:, 0, 0] = 2.0 * znear / (max_x - min_x) + K[:, 1, 1] = 2.0 * znear / (max_y - min_y) + K[:, 0, 2] = (max_x + min_x) / (max_x - min_x) + K[:, 1, 2] = (max_y + min_y) / (max_y - min_y) + K[:, 3, 2] = z_sign * ones + + # NOTE: This maps the z coordinate from [0, 1] where z = 0 if the point + # is at the near clipping plane and z = 1 when the point is at the far + # clipping plane. + K[:, 2, 2] = z_sign * zfar / (zfar - znear) + K[:, 2, 3] = -(zfar * znear) / (zfar - znear) + + return K + + def get_projection_transform(self, **kwargs) -> Transform3d: + """ + Calculate the perspective projection matrix with a symmetric + viewing frustrum. Use column major order. + The viewing frustrum will be projected into ndc, s.t. + (max_x, max_y) -> (+1, +1) + (min_x, min_y) -> (-1, -1) + + Args: + **kwargs: parameters for the projection can be passed in as keyword + arguments to override the default values set in `__init__`. + + Return: + a Transform3d object which represents a batch of projection + matrices of shape (N, 4, 4) + + .. code-block:: python + + h1 = (max_y + min_y)/(max_y - min_y) + w1 = (max_x + min_x)/(max_x - min_x) + tanhalffov = tan((fov/2)) + s1 = 1/tanhalffov + s2 = 1/(tanhalffov * (aspect_ratio)) + + # To map z to the range [0, 1] use: + f1 = far / (far - near) + f2 = -(far * near) / (far - near) + + # Projection matrix + K = [ + [s1, 0, w1, 0], + [0, s2, h1, 0], + [0, 0, f1, f2], + [0, 0, 1, 0], + ] + """ + K = kwargs.get("K", self.K) + if K is not None: + if K.shape != (self._N, 4, 4): + msg = "Expected K to have shape of (%r, 4, 4)" + raise ValueError(msg % (self._N)) + else: + K = self.compute_projection_matrix( + kwargs.get("znear", self.znear), + kwargs.get("zfar", self.zfar), + kwargs.get("fov", self.fov), + kwargs.get("aspect_ratio", self.aspect_ratio), + kwargs.get("degrees", self.degrees), + ) + + # Transpose the projection matrix as PyTorch3D transforms use row vectors. + transform = Transform3d( + matrix=K.transpose(1, 2).contiguous(), device=self.device + ) + return transform + + def unproject_points( + self, + xy_depth: torch.Tensor, + world_coordinates: bool = True, + scaled_depth_input: bool = False, + **kwargs, + ) -> torch.Tensor: + """>! + FoV cameras further allow for passing depth in world units + (`scaled_depth_input=False`) or in the [0, 1]-normalized units + (`scaled_depth_input=True`) + + Args: + scaled_depth_input: If `True`, assumes the input depth is in + the [0, 1]-normalized units. If `False` the input depth is in + the world units. + """ + + # obtain the relevant transformation to ndc + if world_coordinates: + to_ndc_transform = self.get_full_projection_transform() + else: + to_ndc_transform = self.get_projection_transform() + + if scaled_depth_input: + # the input is scaled depth, so we don't have to do anything + xy_sdepth = xy_depth + else: + # parse out important values from the projection matrix + K_matrix = self.get_projection_transform(**kwargs.copy()).get_matrix() + # parse out f1, f2 from K_matrix + unsqueeze_shape = [1] * xy_depth.dim() + unsqueeze_shape[0] = K_matrix.shape[0] + f1 = K_matrix[:, 2, 2].reshape(unsqueeze_shape) + f2 = K_matrix[:, 3, 2].reshape(unsqueeze_shape) + # get the scaled depth + sdepth = (f1 * xy_depth[..., 2:3] + f2) / xy_depth[..., 2:3] + # concatenate xy + scaled depth + xy_sdepth = torch.cat((xy_depth[..., 0:2], sdepth), dim=-1) + + # unproject with inverse of the projection + unprojection_transform = to_ndc_transform.inverse() + return unprojection_transform.transform_points(xy_sdepth) + + def is_perspective(self): + return True + + def in_ndc(self): + return True + +####################################################################################### +## ██████╗ ███████╗███████╗██╗███╗ ██╗██╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ ## +## ██╔══██╗██╔════╝██╔════╝██║████╗ ██║██║╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ ## +## ██║ ██║█████╗ █████╗ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ ## +## ██║ ██║██╔══╝ ██╔══╝ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ ## +## ██████╔╝███████╗██║ ██║██║ ╚████║██║ ██║ ██║╚██████╔╝██║ ╚████║███████║ ## +## ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ## +####################################################################################### + +def make_device(device: Device) -> torch.device: + """ + Makes an actual torch.device object from the device specified as + either a string or torch.device object. If the device is `cuda` without + a specific index, the index of the current device is assigned. + Args: + device: Device (as str or torch.device) + Returns: + A matching torch.device object + """ + device = torch.device(device) if isinstance(device, str) else device + if device.type == "cuda" and device.index is None: # pyre-ignore[16] + # If cuda but with no index, then the current cuda device is indicated. + # In that case, we fix to that device + device = torch.device(f"cuda:{torch.cuda.current_device()}") + return device + +def get_device(x, device: Optional[Device] = None) -> torch.device: + """ + Gets the device of the specified variable x if it is a tensor, or + falls back to a default CPU device otherwise. Allows overriding by + providing an explicit device. + Args: + x: a torch.Tensor to get the device from or another type + device: Device (as str or torch.device) to fall back to + Returns: + A matching torch.device object + """ + + # User overrides device + if device is not None: + return make_device(device) + + # Set device based on input tensor + if torch.is_tensor(x): + return x.device + + # Default device is cpu + return torch.device("cpu") + +def _axis_angle_rotation(axis: str, angle: torch.Tensor) -> torch.Tensor: + """ + Return the rotation matrices for one of the rotations about an axis + of which Euler angles describe, for each value of the angle given. + + Args: + axis: Axis label "X" or "Y or "Z". + angle: any shape tensor of Euler angles in radians + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + + cos = torch.cos(angle) + sin = torch.sin(angle) + one = torch.ones_like(angle) + zero = torch.zeros_like(angle) + + if axis == "X": + R_flat = (one, zero, zero, zero, cos, -sin, zero, sin, cos) + elif axis == "Y": + R_flat = (cos, zero, sin, zero, one, zero, -sin, zero, cos) + elif axis == "Z": + R_flat = (cos, -sin, zero, sin, cos, zero, zero, zero, one) + else: + raise ValueError("letter must be either X, Y or Z.") + + return torch.stack(R_flat, -1).reshape(angle.shape + (3, 3)) + +def euler_angles_to_matrix(euler_angles: torch.Tensor, convention: str) -> torch.Tensor: + """ + Convert rotations given as Euler angles in radians to rotation matrices. + + Args: + euler_angles: Euler angles in radians as tensor of shape (..., 3). + convention: Convention string of three uppercase letters from + {"X", "Y", and "Z"}. + + Returns: + Rotation matrices as tensor of shape (..., 3, 3). + """ + if euler_angles.dim() == 0 or euler_angles.shape[-1] != 3: + raise ValueError("Invalid input euler angles.") + if len(convention) != 3: + raise ValueError("Convention must have 3 letters.") + if convention[1] in (convention[0], convention[2]): + raise ValueError(f"Invalid convention {convention}.") + for letter in convention: + if letter not in ("X", "Y", "Z"): + raise ValueError(f"Invalid letter {letter} in convention string.") + matrices = [ + _axis_angle_rotation(c, e) + for c, e in zip(convention, torch.unbind(euler_angles, -1)) + ] + # return functools.reduce(torch.matmul, matrices) + return torch.matmul(torch.matmul(matrices[0], matrices[1]), matrices[2]) + +def _broadcast_bmm(a, b) -> torch.Tensor: + """ + Batch multiply two matrices and broadcast if necessary. + + Args: + a: torch tensor of shape (P, K) or (M, P, K) + b: torch tensor of shape (N, K, K) + + Returns: + a and b broadcast multiplied. The output batch dimension is max(N, M). + + To broadcast transforms across a batch dimension if M != N then + expect that either M = 1 or N = 1. The tensor with batch dimension 1 is + expanded to have shape N or M. + """ + if a.dim() == 2: + a = a[None] + if len(a) != len(b): + if not ((len(a) == 1) or (len(b) == 1)): + msg = "Expected batch dim for bmm to be equal or 1; got %r, %r" + raise ValueError(msg % (a.shape, b.shape)) + if len(a) == 1: + a = a.expand(len(b), -1, -1) + if len(b) == 1: + b = b.expand(len(a), -1, -1) + return a.bmm(b) + +def _safe_det_3x3(t: torch.Tensor): + """ + Fast determinant calculation for a batch of 3x3 matrices. + Note, result of this function might not be the same as `torch.det()`. + The differences might be in the last significant digit. + Args: + t: Tensor of shape (N, 3, 3). + Returns: + Tensor of shape (N) with determinants. + """ + + det = ( + t[..., 0, 0] * (t[..., 1, 1] * t[..., 2, 2] - t[..., 1, 2] * t[..., 2, 1]) + - t[..., 0, 1] * (t[..., 1, 0] * t[..., 2, 2] - t[..., 2, 0] * t[..., 1, 2]) + + t[..., 0, 2] * (t[..., 1, 0] * t[..., 2, 1] - t[..., 2, 0] * t[..., 1, 1]) + ) + + return det + +def get_world_to_view_transform( + R: torch.Tensor = _R, T: torch.Tensor = _T +) -> Transform3d: + """ + This function returns a Transform3d representing the transformation + matrix to go from world space to view space by applying a rotation and + a translation. + PyTorch3D uses the same convention as Hartley & Zisserman. + I.e., for camera extrinsic parameters R (rotation) and T (translation), + we map a 3D point `X_world` in world coordinates to + a point `X_cam` in camera coordinates with: + `X_cam = X_world R + T` + Args: + R: (N, 3, 3) matrix representing the rotation. + T: (N, 3) matrix representing the translation. + Returns: + a Transform3d object which represents the composed RT transformation. + """ + # TODO: also support the case where RT is specified as one matrix + # of shape (N, 4, 4). + + if T.shape[0] != R.shape[0]: + msg = "Expected R, T to have the same batch dimension; got %r, %r" + raise ValueError(msg % (R.shape[0], T.shape[0])) + if T.dim() != 2 or T.shape[1:] != (3,): + msg = "Expected T to have shape (N, 3); got %r" + raise ValueError(msg % repr(T.shape)) + if R.dim() != 3 or R.shape[1:] != (3, 3): + msg = "Expected R to have shape (N, 3, 3); got %r" + raise ValueError(msg % repr(R.shape)) + + # Create a Transform3d object + T_ = Translate(T, device=T.device) + R_ = Rotate(R, device=R.device) + return R_.compose(T_) + +def _check_valid_rotation_matrix(R, tol: float = 1e-7) -> None: + """ + Determine if R is a valid rotation matrix by checking it satisfies the + following conditions: + + ``RR^T = I and det(R) = 1`` + + Args: + R: an (N, 3, 3) matrix + + Returns: + None + + Emits a warning if R is an invalid rotation matrix. + """ + N = R.shape[0] + eye = torch.eye(3, dtype=R.dtype, device=R.device) + eye = eye.view(1, 3, 3).expand(N, -1, -1) + orthogonal = torch.allclose(R.bmm(R.transpose(1, 2)), eye, atol=tol) + det_R = _safe_det_3x3(R) + no_distortion = torch.allclose(det_R, torch.ones_like(det_R)) + if not (orthogonal and no_distortion): + msg = "R is not a valid rotation matrix" + warnings.warn(msg) + return + +def format_tensor( + input, + dtype: torch.dtype = torch.float32, + device: Device = "cpu", +) -> torch.Tensor: + """ + Helper function for converting a scalar value to a tensor. + Args: + input: Python scalar, Python list/tuple, torch scalar, 1D torch tensor + dtype: data type for the input + device: Device (as str or torch.device) on which the tensor should be placed. + Returns: + input_vec: torch tensor with optional added batch dimension. + """ + device_ = make_device(device) + if not torch.is_tensor(input): + input = torch.tensor(input, dtype=dtype, device=device_) + elif not input.device.type.startswith('mps'): + input = torch.tensor(input, dtype=torch.float32,device=device_) + + if input.dim() == 0: + input = input.view(1) + + if input.device == device_: + return input + + input = input.to(device=device) + return input + +def convert_to_tensors_and_broadcast( + *args, + dtype: torch.dtype = torch.float32, + device: Device = "cpu", +): + """ + Helper function to handle parsing an arbitrary number of inputs (*args) + which all need to have the same batch dimension. + The output is a list of tensors. + Args: + *args: an arbitrary number of inputs + Each of the values in `args` can be one of the following + - Python scalar + - Torch scalar + - Torch tensor of shape (N, K_i) or (1, K_i) where K_i are + an arbitrary number of dimensions which can vary for each + value in args. In this case each input is broadcast to a + tensor of shape (N, K_i) + dtype: data type to use when creating new tensors. + device: torch device on which the tensors should be placed. + Output: + args: A list of tensors of shape (N, K_i) + """ + # Convert all inputs to tensors with a batch dimension + args_1d = [format_tensor(c, dtype, device) for c in args] + + # Find broadcast size + sizes = [c.shape[0] for c in args_1d] + N = max(sizes) + + args_Nd = [] + for c in args_1d: + if c.shape[0] != 1 and c.shape[0] != N: + msg = "Got non-broadcastable sizes %r" % sizes + raise ValueError(msg) + + # Expand broadcast dim and keep non broadcast dims the same size + expand_sizes = (N,) + (-1,) * len(c.shape[1:]) + args_Nd.append(c.expand(*expand_sizes)) + + return args_Nd + +def _handle_coord(c, dtype: torch.dtype, device: torch.device) -> torch.Tensor: + """ + Helper function for _handle_input. + + Args: + c: Python scalar, torch scalar, or 1D torch tensor + + Returns: + c_vec: 1D torch tensor + """ + if not torch.is_tensor(c): + c = torch.tensor(c, dtype=dtype, device=device) + if c.dim() == 0: + c = c.view(1) + if c.device != device or c.dtype != dtype: + c = c.to(device=device, dtype=dtype) + return c + +def _handle_input( + x, + y, + z, + dtype: torch.dtype, + device: Optional[Device], + name: str, + allow_singleton: bool = False, +) -> torch.Tensor: + """ + Helper function to handle parsing logic for building transforms. The output + is always a tensor of shape (N, 3), but there are several types of allowed + input. + + Case I: Single Matrix + In this case x is a tensor of shape (N, 3), and y and z are None. Here just + return x. + + Case II: Vectors and Scalars + In this case each of x, y, and z can be one of the following + - Python scalar + - Torch scalar + - Torch tensor of shape (N, 1) or (1, 1) + In this case x, y and z are broadcast to tensors of shape (N, 1) + and concatenated to a tensor of shape (N, 3) + + Case III: Singleton (only if allow_singleton=True) + In this case y and z are None, and x can be one of the following: + - Python scalar + - Torch scalar + - Torch tensor of shape (N, 1) or (1, 1) + Here x will be duplicated 3 times, and we return a tensor of shape (N, 3) + + Returns: + xyz: Tensor of shape (N, 3) + """ + device_ = get_device(x, device) + # If x is actually a tensor of shape (N, 3) then just return it + if torch.is_tensor(x) and x.dim() == 2: + if x.shape[1] != 3: + msg = "Expected tensor of shape (N, 3); got %r (in %s)" + raise ValueError(msg % (x.shape, name)) + if y is not None or z is not None: + msg = "Expected y and z to be None (in %s)" % name + raise ValueError(msg) + return x.to(device=device_, dtype=dtype) + + if allow_singleton and y is None and z is None: + y = x + z = x + + # Convert all to 1D tensors + xyz = [_handle_coord(c, dtype, device_) for c in [x, y, z]] + + # Broadcast and concatenate + sizes = [c.shape[0] for c in xyz] + N = max(sizes) + for c in xyz: + if c.shape[0] != 1 and c.shape[0] != N: + msg = "Got non-broadcastable sizes %r (in %s)" % (sizes, name) + raise ValueError(msg) + xyz = [c.expand(N) for c in xyz] + xyz = torch.stack(xyz, dim=1) + return xyz diff --git a/extensions/deforum/scripts/deforum_helpers/src/rife/inference_video.py b/extensions/deforum/scripts/deforum_helpers/src/rife/inference_video.py new file mode 100644 index 0000000000000000000000000000000000000000..5f2358610802582f9681de236ea29b4a37186685 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/rife/inference_video.py @@ -0,0 +1,282 @@ +# thanks to https://github.com/n00mkrad for the inspiration and a bit of code. Also thanks for https://github.com/XmYx for the initial reorganization of this script +import os, sys +from types import SimpleNamespace +import cv2 +import torch +import argparse +import shutil +import numpy as np +from tqdm import tqdm +from torch.nn import functional as F +import warnings +import _thread +from queue import Queue, Empty +import subprocess +import time +from .model.pytorch_msssim import ssim_matlab + +sys.path.append('../../') +from deforum_helpers.video_audio_utilities import ffmpeg_stitch_video +from deforum_helpers.general_utils import duplicate_pngs_from_folder + +warnings.filterwarnings("ignore") + +def run_rife_new_video_infer( + output=None, + model=None, + fp16=False, + UHD=False, # *Will be received as *True* if imgs/vid resolution is 2K or higher* + scale=1.0, + fps=None, + deforum_models_path=None, + raw_output_imgs_path=None, + img_batch_id=None, + ffmpeg_location=None, + audio_track=None, + interp_x_amount=2, + slow_mo_enabled=False, + slow_mo_x_amount=2, + ffmpeg_crf=17, + ffmpeg_preset='veryslow', + keep_imgs=False, + orig_vid_name = None): + + args = SimpleNamespace() + args.output = output + args.modelDir = model + args.fp16 = fp16 + args.UHD = UHD + args.scale = scale + args.fps = fps + args.deforum_models_path = deforum_models_path + args.raw_output_imgs_path = raw_output_imgs_path + args.img_batch_id = img_batch_id + args.ffmpeg_location = ffmpeg_location + args.audio_track = audio_track + args.interp_x_amount = interp_x_amount + args.slow_mo_enabled = slow_mo_enabled + args.slow_mo_x_amount = slow_mo_x_amount + args.ffmpeg_crf = ffmpeg_crf + args.ffmpeg_preset = ffmpeg_preset + args.keep_imgs = keep_imgs + args.orig_vid_name = orig_vid_name + + if args.UHD and args.scale == 1.0: + args.scale = 0.5 + + start_time = time.time() + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + torch.set_grad_enabled(False) + if torch.cuda.is_available(): + torch.backends.cudnn.enabled = True + torch.backends.cudnn.benchmark = True + # TODO: Can/ need to handle this? currently it's always False and give errors if True but faster speeds on tensortcore equipped gpus? + if (args.fp16): + torch.set_default_tensor_type(torch.cuda.HalfTensor) + if args.modelDir is not None: + try: + from .rife_new_gen.RIFE_HDv3 import Model + except ImportError as e: + raise ValueError(f"{args.modelDir} could not be found. Please contact deforum support {e}") + except Exception as e: + raise ValueError(f"An error occured while trying to import {args.modelDir}: {e}") + else: + print("Got a request to frame-interpolate but no valid frame interpolation engine value provided. Doing... nothing") + return + + model = Model() + if not hasattr(model, 'version'): + model.version = 0 + model.load_model(args.modelDir, -1, deforum_models_path) + model.eval() + model.device() + + print(f"{args.modelDir}.pkl model successfully loaded into memory") + print("Interpolation progress (it's OK if it finishes before 100%):") + + interpolated_path = os.path.join(args.raw_output_imgs_path, 'interpolated_frames_rife') + # set custom name depending on if we interpolate after a run, or interpolate a video (related/unrelated to deforum, we don't know) directly from within the RIFE tab + if args.orig_vid_name is not None: # interpolating a video (deforum or unrelated) + custom_interp_path = "{}_{}".format(interpolated_path, args.orig_vid_name) + else: # interpolating after a deforum run: + custom_interp_path = "{}_{}".format(interpolated_path, args.img_batch_id) + + # In this folder we temporarily keep the original frames (converted/ copy-pasted and img format depends on scenario) + # the convertion case is done to avert a problem with 24 and 32 mixed outputs from the same animation run + temp_convert_raw_png_path = os.path.join(args.raw_output_imgs_path, "tmp_rife_folder") + + duplicate_pngs_from_folder(args.raw_output_imgs_path, temp_convert_raw_png_path, args.img_batch_id, args.orig_vid_name) + + videogen = [] + for f in os.listdir(temp_convert_raw_png_path): + # double check for old _depth_ files, not really needed probably but keeping it for now + if '_depth_' not in f: + videogen.append(f) + tot_frame = len(videogen) + videogen.sort(key= lambda x:int(x.split('.')[0])) + img_path = os.path.join(temp_convert_raw_png_path, videogen[0]) + lastframe = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)[:, :, ::-1].copy() + videogen = videogen[1:] + h, w, _ = lastframe.shape + vid_out = None + + if not os.path.exists(custom_interp_path): + os.mkdir(custom_interp_path) + + tmp = max(128, int(128 / args.scale)) + ph = ((h - 1) // tmp + 1) * tmp + pw = ((w - 1) // tmp + 1) * tmp + padding = (0, pw - w, 0, ph - h) + pbar = tqdm(total=tot_frame) + + write_buffer = Queue(maxsize=500) + read_buffer = Queue(maxsize=500) + + _thread.start_new_thread(build_read_buffer, (args, read_buffer, videogen, temp_convert_raw_png_path)) + _thread.start_new_thread(clear_write_buffer, (args, write_buffer, custom_interp_path)) + + I1 = torch.from_numpy(np.transpose(lastframe, (2, 0, 1))).to(device, non_blocking=True).unsqueeze(0).float() / 255. + I1 = pad_image(I1, args.fp16, padding) + temp = None # save lastframe when processing static frame + + while True: + if temp is not None: + frame = temp + temp = None + else: + frame = read_buffer.get() + if frame is None: + break + I0 = I1 + I1 = torch.from_numpy(np.transpose(frame, (2, 0, 1))).to(device, non_blocking=True).unsqueeze(0).float() / 255. + I1 = pad_image(I1, args.fp16, padding) + I0_small = F.interpolate(I0, (32, 32), mode='bilinear', align_corners=False) + I1_small = F.interpolate(I1, (32, 32), mode='bilinear', align_corners=False) + ssim = ssim_matlab(I0_small[:, :3], I1_small[:, :3]) + + break_flag = False + if ssim > 0.996: + frame = read_buffer.get() # read a new frame + if frame is None: + break_flag = True + frame = lastframe + else: + temp = frame + I1 = torch.from_numpy(np.transpose(frame, (2, 0, 1))).to(device, non_blocking=True).unsqueeze(0).float() / 255. + I1 = pad_image(I1, args.fp16, padding) + I1 = model.inference(I0, I1, args.scale) + I1_small = F.interpolate(I1, (32, 32), mode='bilinear', align_corners=False) + ssim = ssim_matlab(I0_small[:, :3], I1_small[:, :3]) + frame = (I1[0] * 255).byte().cpu().numpy().transpose(1, 2, 0)[:h, :w] + + if ssim < 0.2: + output = [] + for i in range(args.interp_x_amount - 1): + output.append(I0) + else: + output = make_inference(model, I0, I1, args.interp_x_amount - 1, scale) + + write_buffer.put(lastframe) + for mid in output: + mid = (((mid[0] * 255.).byte().cpu().numpy().transpose(1, 2, 0))) + write_buffer.put(mid[:h, :w]) + pbar.update(1) + lastframe = frame + if break_flag: + break + + write_buffer.put(lastframe) + + while (not write_buffer.empty()): + time.sleep(0.1) + pbar.close() + shutil.rmtree(temp_convert_raw_png_path) + + print(f"Interpolation \033[0;32mdone\033[0m in {time.time()-start_time:.2f} seconds!") + # stitch video from interpolated frames, and add audio if needed + try: + print (f"*Passing interpolated frames to ffmpeg...*") + vid_out_path = stitch_video(args.img_batch_id, args.fps, custom_interp_path, args.audio_track, args.ffmpeg_location, args.interp_x_amount, args.slow_mo_enabled, args.slow_mo_x_amount, args.ffmpeg_crf, args.ffmpeg_preset, args.keep_imgs, args.orig_vid_name) + # remove folder with raw (non-interpolated) vid input frames in case of input VID and not PNGs + if orig_vid_name is not None: + shutil.rmtree(raw_output_imgs_path) + except Exception as e: + print(f'Video stitching gone wrong. *Interpolated frames were saved to HD as backup!*. Actual error: {e}') + +def clear_write_buffer(user_args, write_buffer, custom_interp_path): + cnt = 0 + + while True: + item = write_buffer.get() + if item is None: + break + filename = '{}/{:0>7d}.png'.format(custom_interp_path, cnt) + + cv2.imwrite(filename, item[:, :, ::-1]) + + cnt += 1 + +def build_read_buffer(user_args, read_buffer, videogen, temp_convert_raw_png_path): + for frame in videogen: + if not temp_convert_raw_png_path is None: + img_path = os.path.join(temp_convert_raw_png_path, frame) + frame = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)[:, :, ::-1].copy() + read_buffer.put(frame) + read_buffer.put(None) + +def make_inference(model, I0, I1, n, scale): + if model.version >= 3.9: + res = [] + for i in range(n): + res.append(model.inference(I0, I1, (i + 1) * 1. / (n + 1), scale)) + return res + else: + middle = model.inference(I0, I1, scale) + if n == 1: + return [middle] + first_half = make_inference(model, I0, middle, n=n // 2, scale=scale) + second_half = make_inference(model, middle, I1, n=n // 2, scale=scale) + if n % 2: + return [*first_half, middle, *second_half] + else: + return [*first_half, *second_half] + +def pad_image(img, fp16, padding): + if (fp16): + return F.pad(img, padding).half() + else: + return F.pad(img, padding) + +# TODO: move to fream_interpolation and add FILM to it! +def stitch_video(img_batch_id, fps, img_folder_path, audio_path, ffmpeg_location, interp_x_amount, slow_mo_enabled, slow_mo_x_amount, f_crf, f_preset, keep_imgs, orig_vid_name): + parent_folder = os.path.dirname(img_folder_path) + grandparent_folder = os.path.dirname(parent_folder) + if orig_vid_name is not None: + mp4_path = os.path.join(grandparent_folder, str(orig_vid_name) +'_RIFE_' + 'x' + str(interp_x_amount)) + else: + mp4_path = os.path.join(parent_folder, str(img_batch_id) +'_RIFE_' + 'x' + str(interp_x_amount)) + + if slow_mo_enabled: + mp4_path = mp4_path + '_slomo_x' + str(slow_mo_x_amount) + mp4_path = mp4_path + '.mp4' + + t = os.path.join(img_folder_path, "%07d.png") + add_soundtrack = 'None' + if not audio_path is None: + add_soundtrack = 'File' + + exception_raised = False + try: + ffmpeg_stitch_video(ffmpeg_location=ffmpeg_location, fps=fps, outmp4_path=mp4_path, stitch_from_frame=0, stitch_to_frame=1000000, imgs_path=t, add_soundtrack=add_soundtrack, audio_path=audio_path, crf=f_crf, preset=f_preset) + except Exception as e: + exception_raised = True + print(f"An error occurred while stitching the video: {e}") + + if not exception_raised and not keep_imgs: + shutil.rmtree(img_folder_path) + + if (keep_imgs and orig_vid_name is not None) or (orig_vid_name is not None and exception_raised is True): + shutil.move(img_folder_path, grandparent_folder) + + return mp4_path \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/rife/model/loss.py b/extensions/deforum/scripts/deforum_helpers/src/rife/model/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..72e5de6af050df7d55c2871a69637077970ddfb9 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/rife/model/loss.py @@ -0,0 +1,128 @@ +import torch +import numpy as np +import torch.nn as nn +import torch.nn.functional as F +import torchvision.models as models + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + +class EPE(nn.Module): + def __init__(self): + super(EPE, self).__init__() + + def forward(self, flow, gt, loss_mask): + loss_map = (flow - gt.detach()) ** 2 + loss_map = (loss_map.sum(1, True) + 1e-6) ** 0.5 + return (loss_map * loss_mask) + + +class Ternary(nn.Module): + def __init__(self): + super(Ternary, self).__init__() + patch_size = 7 + out_channels = patch_size * patch_size + self.w = np.eye(out_channels).reshape( + (patch_size, patch_size, 1, out_channels)) + self.w = np.transpose(self.w, (3, 2, 0, 1)) + self.w = torch.tensor(self.w).float().to(device) + + def transform(self, img): + patches = F.conv2d(img, self.w, padding=3, bias=None) + transf = patches - img + transf_norm = transf / torch.sqrt(0.81 + transf**2) + return transf_norm + + def rgb2gray(self, rgb): + r, g, b = rgb[:, 0:1, :, :], rgb[:, 1:2, :, :], rgb[:, 2:3, :, :] + gray = 0.2989 * r + 0.5870 * g + 0.1140 * b + return gray + + def hamming(self, t1, t2): + dist = (t1 - t2) ** 2 + dist_norm = torch.mean(dist / (0.1 + dist), 1, True) + return dist_norm + + def valid_mask(self, t, padding): + n, _, h, w = t.size() + inner = torch.ones(n, 1, h - 2 * padding, w - 2 * padding).type_as(t) + mask = F.pad(inner, [padding] * 4) + return mask + + def forward(self, img0, img1): + img0 = self.transform(self.rgb2gray(img0)) + img1 = self.transform(self.rgb2gray(img1)) + return self.hamming(img0, img1) * self.valid_mask(img0, 1) + + +class SOBEL(nn.Module): + def __init__(self): + super(SOBEL, self).__init__() + self.kernelX = torch.tensor([ + [1, 0, -1], + [2, 0, -2], + [1, 0, -1], + ]).float() + self.kernelY = self.kernelX.clone().T + self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device) + self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device) + + def forward(self, pred, gt): + N, C, H, W = pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3] + img_stack = torch.cat( + [pred.reshape(N*C, 1, H, W), gt.reshape(N*C, 1, H, W)], 0) + sobel_stack_x = F.conv2d(img_stack, self.kernelX, padding=1) + sobel_stack_y = F.conv2d(img_stack, self.kernelY, padding=1) + pred_X, gt_X = sobel_stack_x[:N*C], sobel_stack_x[N*C:] + pred_Y, gt_Y = sobel_stack_y[:N*C], sobel_stack_y[N*C:] + + L1X, L1Y = torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y) + loss = (L1X+L1Y) + return loss + +class MeanShift(nn.Conv2d): + def __init__(self, data_mean, data_std, data_range=1, norm=True): + c = len(data_mean) + super(MeanShift, self).__init__(c, c, kernel_size=1) + std = torch.Tensor(data_std) + self.weight.data = torch.eye(c).view(c, c, 1, 1) + if norm: + self.weight.data.div_(std.view(c, 1, 1, 1)) + self.bias.data = -1 * data_range * torch.Tensor(data_mean) + self.bias.data.div_(std) + else: + self.weight.data.mul_(std.view(c, 1, 1, 1)) + self.bias.data = data_range * torch.Tensor(data_mean) + self.requires_grad = False + +class VGGPerceptualLoss(torch.nn.Module): + def __init__(self, rank=0): + super(VGGPerceptualLoss, self).__init__() + blocks = [] + pretrained = True + self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features + self.normalize = MeanShift([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], norm=True).cuda() + for param in self.parameters(): + param.requires_grad = False + + def forward(self, X, Y, indices=None): + X = self.normalize(X) + Y = self.normalize(Y) + indices = [2, 7, 12, 21, 30] + weights = [1.0/2.6, 1.0/4.8, 1.0/3.7, 1.0/5.6, 10/1.5] + k = 0 + loss = 0 + for i in range(indices[-1]): + X = self.vgg_pretrained_features[i](X) + Y = self.vgg_pretrained_features[i](Y) + if (i+1) in indices: + loss += weights[k] * (X - Y.detach()).abs().mean() * 0.1 + k += 1 + return loss + +if __name__ == '__main__': + img0 = torch.zeros(3, 3, 256, 256).float().to(device) + img1 = torch.tensor(np.random.normal( + 0, 1, (3, 3, 256, 256))).float().to(device) + ternary_loss = Ternary() + print(ternary_loss(img0, img1).shape) diff --git a/extensions/deforum/scripts/deforum_helpers/src/rife/model/pytorch_msssim/__init__.py b/extensions/deforum/scripts/deforum_helpers/src/rife/model/pytorch_msssim/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d30326188cf6afacf2fc84c7ae18efe14dae2e --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/rife/model/pytorch_msssim/__init__.py @@ -0,0 +1,200 @@ +import torch +import torch.nn.functional as F +from math import exp +import numpy as np + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +def gaussian(window_size, sigma): + gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)]) + return gauss/gauss.sum() + + +def create_window(window_size, channel=1): + _1D_window = gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0).to(device) + window = _2D_window.expand(channel, 1, window_size, window_size).contiguous() + return window + +def create_window_3d(window_size, channel=1): + _1D_window = gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()) + _3D_window = _2D_window.unsqueeze(2) @ (_1D_window.t()) + window = _3D_window.expand(1, channel, window_size, window_size, window_size).contiguous().to(device) + return window + + +def ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None): + # Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh). + if val_range is None: + if torch.max(img1) > 128: + max_val = 255 + else: + max_val = 1 + + if torch.min(img1) < -0.5: + min_val = -1 + else: + min_val = 0 + L = max_val - min_val + else: + L = val_range + + padd = 0 + (_, channel, height, width) = img1.size() + if window is None: + real_size = min(window_size, height, width) + window = create_window(real_size, channel=channel).to(img1.device) + + # mu1 = F.conv2d(img1, window, padding=padd, groups=channel) + # mu2 = F.conv2d(img2, window, padding=padd, groups=channel) + mu1 = F.conv2d(F.pad(img1, (5, 5, 5, 5), mode='replicate'), window, padding=padd, groups=channel) + mu2 = F.conv2d(F.pad(img2, (5, 5, 5, 5), mode='replicate'), window, padding=padd, groups=channel) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1 * mu2 + + sigma1_sq = F.conv2d(F.pad(img1 * img1, (5, 5, 5, 5), 'replicate'), window, padding=padd, groups=channel) - mu1_sq + sigma2_sq = F.conv2d(F.pad(img2 * img2, (5, 5, 5, 5), 'replicate'), window, padding=padd, groups=channel) - mu2_sq + sigma12 = F.conv2d(F.pad(img1 * img2, (5, 5, 5, 5), 'replicate'), window, padding=padd, groups=channel) - mu1_mu2 + + C1 = (0.01 * L) ** 2 + C2 = (0.03 * L) ** 2 + + v1 = 2.0 * sigma12 + C2 + v2 = sigma1_sq + sigma2_sq + C2 + cs = torch.mean(v1 / v2) # contrast sensitivity + + ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2) + + if size_average: + ret = ssim_map.mean() + else: + ret = ssim_map.mean(1).mean(1).mean(1) + + if full: + return ret, cs + return ret + + +def ssim_matlab(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None): + # Value range can be different from 255. Other common ranges are 1 (sigmoid) and 2 (tanh). + if val_range is None: + if torch.max(img1) > 128: + max_val = 255 + else: + max_val = 1 + + if torch.min(img1) < -0.5: + min_val = -1 + else: + min_val = 0 + L = max_val - min_val + else: + L = val_range + + padd = 0 + (_, _, height, width) = img1.size() + if window is None: + real_size = min(window_size, height, width) + window = create_window_3d(real_size, channel=1).to(img1.device) + # Channel is set to 1 since we consider color images as volumetric images + + img1 = img1.unsqueeze(1) + img2 = img2.unsqueeze(1) + + mu1 = F.conv3d(F.pad(img1, (5, 5, 5, 5, 5, 5), mode='replicate'), window, padding=padd, groups=1) + mu2 = F.conv3d(F.pad(img2, (5, 5, 5, 5, 5, 5), mode='replicate'), window, padding=padd, groups=1) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1 * mu2 + + sigma1_sq = F.conv3d(F.pad(img1 * img1, (5, 5, 5, 5, 5, 5), 'replicate'), window, padding=padd, groups=1) - mu1_sq + sigma2_sq = F.conv3d(F.pad(img2 * img2, (5, 5, 5, 5, 5, 5), 'replicate'), window, padding=padd, groups=1) - mu2_sq + sigma12 = F.conv3d(F.pad(img1 * img2, (5, 5, 5, 5, 5, 5), 'replicate'), window, padding=padd, groups=1) - mu1_mu2 + + C1 = (0.01 * L) ** 2 + C2 = (0.03 * L) ** 2 + + v1 = 2.0 * sigma12 + C2 + v2 = sigma1_sq + sigma2_sq + C2 + cs = torch.mean(v1 / v2) # contrast sensitivity + + ssim_map = ((2 * mu1_mu2 + C1) * v1) / ((mu1_sq + mu2_sq + C1) * v2) + + if size_average: + ret = ssim_map.mean() + else: + ret = ssim_map.mean(1).mean(1).mean(1) + + if full: + return ret, cs + return ret + + +def msssim(img1, img2, window_size=11, size_average=True, val_range=None, normalize=False): + device = img1.device + weights = torch.FloatTensor([0.0448, 0.2856, 0.3001, 0.2363, 0.1333]).to(device) + levels = weights.size()[0] + mssim = [] + mcs = [] + for _ in range(levels): + sim, cs = ssim(img1, img2, window_size=window_size, size_average=size_average, full=True, val_range=val_range) + mssim.append(sim) + mcs.append(cs) + + img1 = F.avg_pool2d(img1, (2, 2)) + img2 = F.avg_pool2d(img2, (2, 2)) + + mssim = torch.stack(mssim) + mcs = torch.stack(mcs) + + # Normalize (to avoid NaNs during training unstable models, not compliant with original definition) + if normalize: + mssim = (mssim + 1) / 2 + mcs = (mcs + 1) / 2 + + pow1 = mcs ** weights + pow2 = mssim ** weights + # From Matlab implementation https://ece.uwaterloo.ca/~z70wang/research/iwssim/ + output = torch.prod(pow1[:-1] * pow2[-1]) + return output + + +# Classes to re-use window +class SSIM(torch.nn.Module): + def __init__(self, window_size=11, size_average=True, val_range=None): + super(SSIM, self).__init__() + self.window_size = window_size + self.size_average = size_average + self.val_range = val_range + + # Assume 3 channel for SSIM + self.channel = 3 + self.window = create_window(window_size, channel=self.channel) + + def forward(self, img1, img2): + (_, channel, _, _) = img1.size() + + if channel == self.channel and self.window.dtype == img1.dtype: + window = self.window + else: + window = create_window(self.window_size, channel).to(img1.device).type(img1.dtype) + self.window = window + self.channel = channel + + _ssim = ssim(img1, img2, window=window, window_size=self.window_size, size_average=self.size_average) + dssim = (1 - _ssim) / 2 + return dssim + +class MSSSIM(torch.nn.Module): + def __init__(self, window_size=11, size_average=True, channel=3): + super(MSSSIM, self).__init__() + self.window_size = window_size + self.size_average = size_average + self.channel = channel + + def forward(self, img1, img2): + return msssim(img1, img2, window_size=self.window_size, size_average=self.size_average) diff --git a/extensions/deforum/scripts/deforum_helpers/src/rife/model/warplayer.py b/extensions/deforum/scripts/deforum_helpers/src/rife/model/warplayer.py new file mode 100644 index 0000000000000000000000000000000000000000..21b0b904cf71b297fd43813134c57d13a3ae9e4a --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/rife/model/warplayer.py @@ -0,0 +1,22 @@ +import torch +import torch.nn as nn + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") +backwarp_tenGrid = {} + + +def warp(tenInput, tenFlow): + k = (str(tenFlow.device), str(tenFlow.size())) + if k not in backwarp_tenGrid: + tenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3], device=device).view( + 1, 1, 1, tenFlow.shape[3]).expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1) + tenVertical = torch.linspace(-1.0, 1.0, tenFlow.shape[2], device=device).view( + 1, 1, tenFlow.shape[2], 1).expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3]) + backwarp_tenGrid[k] = torch.cat( + [tenHorizontal, tenVertical], 1).to(device) + + tenFlow = torch.cat([tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0), + tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0)], 1) + + g = (backwarp_tenGrid[k] + tenFlow).permute(0, 2, 3, 1) + return torch.nn.functional.grid_sample(input=tenInput, grid=g, mode='bilinear', padding_mode='border', align_corners=True) diff --git a/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/IFNet_HDv3.py b/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/IFNet_HDv3.py new file mode 100644 index 0000000000000000000000000000000000000000..2360c9e7d15ad4c73e8bb34112999e3d46aeb8c2 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/IFNet_HDv3.py @@ -0,0 +1,129 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from ..model.warplayer import warp +# from train_log.refine import * + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1): + return nn.Sequential( + nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, + padding=padding, dilation=dilation, bias=True), + nn.LeakyReLU(0.2, True) + ) + +def conv_bn(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1): + return nn.Sequential( + nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, + padding=padding, dilation=dilation, bias=False), + nn.BatchNorm2d(out_planes), + nn.LeakyReLU(0.2, True) + ) + +class ResConv(nn.Module): + def __init__(self, c, dilation=1): + super(ResConv, self).__init__() + self.conv = nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1\ +) + self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True) + self.relu = nn.LeakyReLU(0.2, True) + + def forward(self, x): + return self.relu(self.conv(x) * self.beta + x) + +class IFBlock(nn.Module): + def __init__(self, in_planes, c=64): + super(IFBlock, self).__init__() + self.conv0 = nn.Sequential( + conv(in_planes, c//2, 3, 2, 1), + conv(c//2, c, 3, 2, 1), + ) + self.convblock = nn.Sequential( + ResConv(c), + ResConv(c), + ResConv(c), + ResConv(c), + ResConv(c), + ResConv(c), + ResConv(c), + ResConv(c), + ) + self.lastconv = nn.Sequential( + nn.ConvTranspose2d(c, 4*6, 4, 2, 1), + nn.PixelShuffle(2) + ) + + def forward(self, x, flow=None, scale=1): + x = F.interpolate(x, scale_factor= 1. / scale, mode="bilinear", align_corners=False) + if flow is not None: + flow = F.interpolate(flow, scale_factor= 1. / scale, mode="bilinear", align_corners=False) * 1. / scale + x = torch.cat((x, flow), 1) + feat = self.conv0(x) + feat = self.convblock(feat) + tmp = self.lastconv(feat) + tmp = F.interpolate(tmp, scale_factor=scale, mode="bilinear", align_corners=False) + flow = tmp[:, :4] * scale + mask = tmp[:, 4:5] + return flow, mask + +class IFNet(nn.Module): + def __init__(self): + super(IFNet, self).__init__() + self.block0 = IFBlock(7, c=192) + self.block1 = IFBlock(8+4, c=128) + self.block2 = IFBlock(8+4, c=96) + self.block3 = IFBlock(8+4, c=64) + # self.contextnet = Contextnet() + # self.unet = Unet() + + def forward( self, x, timestep=0.5, scale_list=[8, 4, 2, 1], training=False, fastmode=True, ensemble=False): + if training == False: + channel = x.shape[1] // 2 + img0 = x[:, :channel] + img1 = x[:, channel:] + if not torch.is_tensor(timestep): + timestep = (x[:, :1].clone() * 0 + 1) * timestep + else: + timestep = timestep.repeat(1, 1, img0.shape[2], img0.shape[3]) + flow_list = [] + merged = [] + mask_list = [] + warped_img0 = img0 + warped_img1 = img1 + flow = None + mask = None + loss_cons = 0 + block = [self.block0, self.block1, self.block2, self.block3] + for i in range(4): + if flow is None: + flow, mask = block[i](torch.cat((img0[:, :3], img1[:, :3], timestep), 1), None, scale=scale_list[i]) + if ensemble: + f1, m1 = block[i](torch.cat((img1[:, :3], img0[:, :3], 1-timestep), 1), None, scale=scale_list[i]) + flow = (flow + torch.cat((f1[:, 2:4], f1[:, :2]), 1)) / 2 + mask = (mask + (-m1)) / 2 + else: + f0, m0 = block[i](torch.cat((warped_img0[:, :3], warped_img1[:, :3], timestep, mask), 1), flow, scale=scale_list[i]) + if ensemble: + f1, m1 = block[i](torch.cat((warped_img1[:, :3], warped_img0[:, :3], 1-timestep, -mask), 1), torch.cat((flow[:, 2:4], flow[:, :2]), 1), scale=scale_list[i]) + f0 = (f0 + torch.cat((f1[:, 2:4], f1[:, :2]), 1)) / 2 + m0 = (m0 + (-m1)) / 2 + flow = flow + f0 + mask = mask + m0 + mask_list.append(mask) + flow_list.append(flow) + warped_img0 = warp(img0, flow[:, :2]) + warped_img1 = warp(img1, flow[:, 2:4]) + merged.append((warped_img0, warped_img1)) + mask_list[3] = torch.sigmoid(mask_list[3]) + merged[3] = merged[3][0] * mask_list[3] + merged[3][1] * (1 - mask_list[3]) + if not fastmode: + print('contextnet is removed') + ''' + c0 = self.contextnet(img0, flow[:, :2]) + c1 = self.contextnet(img1, flow[:, 2:4]) + tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1) + res = tmp[:, :3] * 2 - 1 + merged[3] = torch.clamp(merged[3] + res, 0, 1) + ''' + return flow_list, mask_list[3], merged diff --git a/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/RIFE_HDv3.py b/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/RIFE_HDv3.py new file mode 100644 index 0000000000000000000000000000000000000000..e51408af7e574bc4c8b03739cda0bacd73cd0081 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/RIFE_HDv3.py @@ -0,0 +1,108 @@ +import os, sys +import torch +import torch.nn as nn +import numpy as np +from torch.optim import AdamW +import torch.optim as optim +import itertools +from ..model.warplayer import warp +from torch.nn.parallel import DistributedDataParallel as DDP +from .IFNet_HDv3 import * +import torch.nn.functional as F +from ..model.loss import * +sys.path.append('../../') +from deforum_helpers.general_utils import checksum + +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +class Model: + def __init__(self, local_rank=-1): + self.flownet = IFNet() + self.device() + self.optimG = AdamW(self.flownet.parameters(), lr=1e-6, weight_decay=1e-4) + self.epe = EPE() + self.version = 3.9 + # self.vgg = VGGPerceptualLoss().to(device) + self.sobel = SOBEL() + if local_rank != -1: + self.flownet = DDP(self.flownet, device_ids=[local_rank], output_device=local_rank) + + def train(self): + self.flownet.train() + + def eval(self): + self.flownet.eval() + + def device(self): + self.flownet.to(device) + + def load_model(self, path, rank, deforum_models_path): + + download_rife_model(path, deforum_models_path) + + def convert(param): + if rank == -1: + return { + k.replace("module.", ""): v + for k, v in param.items() + if "module." in k + } + else: + return param + if rank <= 0: + if torch.cuda.is_available(): + self.flownet.load_state_dict(convert(torch.load(os.path.join(deforum_models_path,'{}.pkl').format(path))), False) + else: + self.flownet.load_state_dict(convert(torch.load(os.path.join(deforum_models_path,'{}.pkl').format(path), map_location ='cpu')), False) + + def inference(self, img0, img1, timestep=0.5, scale=1.0): + imgs = torch.cat((img0, img1), 1) + scale_list = [8/scale, 4/scale, 2/scale, 1/scale] + flow, mask, merged = self.flownet(imgs, timestep, scale_list) + return merged[3] + + def update(self, imgs, gt, learning_rate=0, mul=1, training=True, flow_gt=None): + for param_group in self.optimG.param_groups: + param_group['lr'] = learning_rate + img0 = imgs[:, :3] + img1 = imgs[:, 3:] + if training: + self.train() + else: + self.eval() + scale = [8, 4, 2, 1] + flow, mask, merged = self.flownet(torch.cat((imgs, gt), 1), scale=scale, training=training) + loss_l1 = (merged[3] - gt).abs().mean() + loss_smooth = self.sobel(flow[3], flow[3]*0).mean() + # loss_vgg = self.vgg(merged[2], gt) + if training: + self.optimG.zero_grad() + loss_G = loss_l1 + loss_cons + loss_smooth * 0.1 + loss_G.backward() + self.optimG.step() + else: + flow_teacher = flow[2] + return merged[3], { + 'mask': mask, + 'flow': flow[3][:, :2], + 'loss_l1': loss_l1, + 'loss_cons': loss_cons, + 'loss_smooth': loss_smooth, + } + +def download_rife_model(path, deforum_models_path): + options = {'RIFE46': ( + 'af6f0b4bed96dea2c9f0624b449216c7adfaf7f0b722fba0c8f5c6e20b2ec39559cf33f3d238d53b160c22f00c6eaa47dc54a6e4f8aa4f59a6e4a9e90e1a808a', + "https://github.com/hithereai/Practical-RIFE/releases/download/rife46/RIFE46.pkl"), + 'RIFE43': ('ed660f58708ee369a0b3855f64d2d07a6997d949f33067faae51d740123c5ee015901cc57553594f2df8ec08131a1c5f7c883c481eac0f9addd84379acea90c8', + "https://github.com/hithereai/Practical-RIFE/releases/download/rife43/RIFE43.pkl"), + 'RIFE40': ('0baf0bed23597cda402a97a80a7d14c26a9ed797d2fc0790aac93b19ca5b0f50676ba07aa9f8423cf061ed881ece6e67922f001ea402bfced83ef67675142ce7', + "https://github.com/hithereai/Practical-RIFE/releases/download/rife40/RIFE40.pkl")} + if path in options: + target_file = f"{path}.pkl" + target_path = os.path.join(deforum_models_path, target_file) + if not os.path.exists(target_path): + from basicsr.utils.download_util import load_file_from_url + load_file_from_url(options[path][1], deforum_models_path) + if checksum(target_path) != options[path][0]: + raise Exception(f"Error while downloading {target_file}. Please download from here: {options[path][1]} and place in: " + deforum_models_path) \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/refine.py b/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/refine.py new file mode 100644 index 0000000000000000000000000000000000000000..ff3807c636d461862f13200fe0017b62db5c20c5 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/refine.py @@ -0,0 +1,90 @@ +import torch +import torch.nn as nn +import numpy as np +from torch.optim import AdamW +import torch.optim as optim +import itertools +from model.warplayer import warp +from torch.nn.parallel import DistributedDataParallel as DDP +import torch.nn.functional as F + +device = torch.device("cuda") + +def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1): + return nn.Sequential( + nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, + padding=padding, dilation=dilation, bias=True), + nn.PReLU(out_planes) + ) + +def conv_woact(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1): + return nn.Sequential( + nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, + padding=padding, dilation=dilation, bias=True), + ) + +def deconv(in_planes, out_planes, kernel_size=4, stride=2, padding=1): + return nn.Sequential( + torch.nn.ConvTranspose2d(in_channels=in_planes, out_channels=out_planes, kernel_size=4, stride=2, padding=1, bias=True), + nn.PReLU(out_planes) + ) + +class Conv2(nn.Module): + def __init__(self, in_planes, out_planes, stride=2): + super(Conv2, self).__init__() + self.conv1 = conv(in_planes, out_planes, 3, stride, 1) + self.conv2 = conv(out_planes, out_planes, 3, 1, 1) + + def forward(self, x): + x = self.conv1(x) + x = self.conv2(x) + return x + +c = 16 +class Contextnet(nn.Module): + def __init__(self): + super(Contextnet, self).__init__() + self.conv1 = Conv2(3, c) + self.conv2 = Conv2(c, 2*c) + self.conv3 = Conv2(2*c, 4*c) + self.conv4 = Conv2(4*c, 8*c) + + def forward(self, x, flow): + x = self.conv1(x) + flow = F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False) * 0.5 + f1 = warp(x, flow) + x = self.conv2(x) + flow = F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False) * 0.5 + f2 = warp(x, flow) + x = self.conv3(x) + flow = F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False) * 0.5 + f3 = warp(x, flow) + x = self.conv4(x) + flow = F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False) * 0.5 + f4 = warp(x, flow) + return [f1, f2, f3, f4] + +class Unet(nn.Module): + def __init__(self): + super(Unet, self).__init__() + self.down0 = Conv2(17, 2*c) + self.down1 = Conv2(4*c, 4*c) + self.down2 = Conv2(8*c, 8*c) + self.down3 = Conv2(16*c, 16*c) + self.up0 = deconv(32*c, 8*c) + self.up1 = deconv(16*c, 4*c) + self.up2 = deconv(8*c, 2*c) + self.up3 = deconv(4*c, c) + self.conv = nn.Conv2d(c, 3, 3, 1, 1) + + def forward(self, img0, img1, warped_img0, warped_img1, mask, flow, c0, c1): + s0 = self.down0(torch.cat((img0, img1, warped_img0, warped_img1, mask, flow), 1)) + s1 = self.down1(torch.cat((s0, c0[0], c1[0]), 1)) + s2 = self.down2(torch.cat((s1, c0[1], c1[1]), 1)) + s3 = self.down3(torch.cat((s2, c0[2], c1[2]), 1)) + x = self.up0(torch.cat((s3, c0[3], c1[3]), 1)) + x = self.up1(torch.cat((x, s2), 1)) + x = self.up2(torch.cat((x, s1), 1)) + x = self.up3(torch.cat((x, s0), 1)) + x = self.conv(x) + return torch.sigmoid(x) diff --git a/extensions/deforum/scripts/deforum_helpers/src/utils.py b/extensions/deforum/scripts/deforum_helpers/src/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe08b0b1bd41f2bc59e9f8d188db08423fcf48a --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/src/utils.py @@ -0,0 +1,140 @@ +import base64 +import math +import re +from io import BytesIO + +import matplotlib.cm +import numpy as np +import torch +import torch.nn +from PIL import Image + + +class RunningAverage: + def __init__(self): + self.avg = 0 + self.count = 0 + + def append(self, value): + self.avg = (value + self.count * self.avg) / (self.count + 1) + self.count += 1 + + def get_value(self): + return self.avg + + +def denormalize(x, device='cpu'): + mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(device) + std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(device) + return x * std + mean + + +class RunningAverageDict: + def __init__(self): + self._dict = None + + def update(self, new_dict): + if self._dict is None: + self._dict = dict() + for key, value in new_dict.items(): + self._dict[key] = RunningAverage() + + for key, value in new_dict.items(): + self._dict[key].append(value) + + def get_value(self): + return {key: value.get_value() for key, value in self._dict.items()} + + +def colorize(value, vmin=10, vmax=1000, cmap='magma_r'): + value = value.cpu().numpy()[0, :, :] + invalid_mask = value == -1 + + # normalize + vmin = value.min() if vmin is None else vmin + vmax = value.max() if vmax is None else vmax + if vmin != vmax: + value = (value - vmin) / (vmax - vmin) # vmin..vmax + else: + # Avoid 0-division + value = value * 0. + # squeeze last dim if it exists + # value = value.squeeze(axis=0) + cmapper = matplotlib.cm.get_cmap(cmap) + value = cmapper(value, bytes=True) # (nxmx4) + value[invalid_mask] = 255 + img = value[:, :, :3] + + # return img.transpose((2, 0, 1)) + return img + + +def count_parameters(model): + return sum(p.numel() for p in model.parameters() if p.requires_grad) + + +def compute_errors(gt, pred): + thresh = np.maximum((gt / pred), (pred / gt)) + a1 = (thresh < 1.25).mean() + a2 = (thresh < 1.25 ** 2).mean() + a3 = (thresh < 1.25 ** 3).mean() + + abs_rel = np.mean(np.abs(gt - pred) / gt) + sq_rel = np.mean(((gt - pred) ** 2) / gt) + + rmse = (gt - pred) ** 2 + rmse = np.sqrt(rmse.mean()) + + rmse_log = (np.log(gt) - np.log(pred)) ** 2 + rmse_log = np.sqrt(rmse_log.mean()) + + err = np.log(pred) - np.log(gt) + silog = np.sqrt(np.mean(err ** 2) - np.mean(err) ** 2) * 100 + + log_10 = (np.abs(np.log10(gt) - np.log10(pred))).mean() + return dict(a1=a1, a2=a2, a3=a3, abs_rel=abs_rel, rmse=rmse, log_10=log_10, rmse_log=rmse_log, + silog=silog, sq_rel=sq_rel) + + +##################################### Demo Utilities ############################################ +def b64_to_pil(b64string): + image_data = re.sub('^data:image/.+;base64,', '', b64string) + # image = Image.open(cStringIO.StringIO(image_data)) + return Image.open(BytesIO(base64.b64decode(image_data))) + + +# Compute edge magnitudes +from scipy import ndimage + + +def edges(d): + dx = ndimage.sobel(d, 0) # horizontal derivative + dy = ndimage.sobel(d, 1) # vertical derivative + return np.abs(dx) + np.abs(dy) + + +class PointCloudHelper(): + def __init__(self, width=640, height=480): + self.xx, self.yy = self.worldCoords(width, height) + + def worldCoords(self, width=640, height=480): + hfov_degrees, vfov_degrees = 57, 43 + hFov = math.radians(hfov_degrees) + vFov = math.radians(vfov_degrees) + cx, cy = width / 2, height / 2 + fx = width / (2 * math.tan(hFov / 2)) + fy = height / (2 * math.tan(vFov / 2)) + xx, yy = np.tile(range(width), height), np.repeat(range(height), width) + xx = (xx - cx) / fx + yy = (yy - cy) / fy + return xx, yy + + def depth_to_points(self, depth): + depth[edges(depth) > 0.3] = np.nan # Hide depth edges + length = depth.shape[0] * depth.shape[1] + # depth[edges(depth) > 0.3] = 1e6 # Hide depth edges + z = depth.reshape(length) + + return np.dstack((self.xx * z, self.yy * z, z)).reshape((length, 3)) + +##################################################################################################### diff --git a/extensions/deforum/scripts/deforum_helpers/upscaling.py b/extensions/deforum/scripts/deforum_helpers/upscaling.py new file mode 100644 index 0000000000000000000000000000000000000000..b5b841722b936135bf1f65e86e0c26d7084053b2 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/upscaling.py @@ -0,0 +1,264 @@ +import os +import numpy as np +import cv2 +from pathlib import Path +from tqdm import tqdm +from PIL import Image +from modules.scripts_postprocessing import PostprocessedImage +from modules import devices +import shutil +from queue import Queue, Empty +import modules.scripts as scr +from .frame_interpolation import clean_folder_name +from .general_utils import duplicate_pngs_from_folder, checksum +# TODO: move some funcs to this file? +from .video_audio_utilities import get_quick_vid_info, vid2frames, ffmpeg_stitch_video, extract_number, media_file_has_audio +from basicsr.utils.download_util import load_file_from_url +from .rich import console +import time +import subprocess + +def process_upscale_vid_upload_logic(file, selected_tab, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, vid_file_name, keep_imgs, f_location, f_crf, f_preset): + print("Got a request to *upscale* an existing video.") + + in_vid_fps, _, _ = get_quick_vid_info(file.name) + folder_name = clean_folder_name(Path(vid_file_name).stem) + outdir_no_tmp = os.path.join(os.getcwd(), 'outputs', 'frame-upscaling', folder_name) + i = 1 + while os.path.exists(outdir_no_tmp): + outdir_no_tmp = os.path.join(os.getcwd(), 'outputs', 'frame-upscaling', folder_name + '_' + str(i)) + i += 1 + + outdir = os.path.join(outdir_no_tmp, 'tmp_input_frames') + os.makedirs(outdir, exist_ok=True) + + vid2frames(video_path=file.name, video_in_frame_path=outdir, overwrite=True, extract_from_frame=0, extract_to_frame=-1, numeric_files_output=True, out_img_format='png') + + process_video_upscaling(selected_tab, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, orig_vid_fps=in_vid_fps, real_audio_track=file.name, raw_output_imgs_path=outdir, img_batch_id=None, ffmpeg_location=f_location, ffmpeg_crf=f_crf, ffmpeg_preset=f_preset, keep_upscale_imgs=keep_imgs, orig_vid_name=folder_name) + +def process_video_upscaling(resize_mode, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, orig_vid_fps, real_audio_track, raw_output_imgs_path, img_batch_id, ffmpeg_location, ffmpeg_crf, ffmpeg_preset, keep_upscale_imgs, orig_vid_name): + devices.torch_gc() + + print("Upscaling progress (it's OK if it finishes before 100%):") + + upscaled_path = os.path.join(raw_output_imgs_path, 'upscaled_frames') + if orig_vid_name is not None: # upscaling a video (deforum or unrelated) + custom_upscale_path = "{}_{}".format(upscaled_path, orig_vid_name) + else: # upscaling after a deforum run: + custom_upscale_path = "{}_{}".format(upscaled_path, img_batch_id) + + temp_convert_raw_png_path = os.path.join(raw_output_imgs_path, "tmp_upscale_folder") + duplicate_pngs_from_folder(raw_output_imgs_path, temp_convert_raw_png_path, img_batch_id, orig_vid_name) + + videogen = [] + for f in os.listdir(temp_convert_raw_png_path): + # double check for old _depth_ files, not really needed probably but keeping it for now + if '_depth_' not in f: + videogen.append(f) + + videogen.sort(key= lambda x:int(x.split('.')[0])) + vid_out = None + + if not os.path.exists(custom_upscale_path): + os.mkdir(custom_upscale_path) + + # Upscaling is a slow and demanding operation, so we don't need as much parallelization here + for i in tqdm(range(len(videogen)), desc="Upscaling"): + lastframe = videogen[i] + img_path = os.path.join(temp_convert_raw_png_path, lastframe) + image = process_frame(resize_mode, Image.open(img_path).convert("RGB"), upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility) + filename = '{}/{:0>7d}.png'.format(custom_upscale_path, i) + image.save(filename) + + shutil.rmtree(temp_convert_raw_png_path) + # stitch video from upscaled frames, and add audio if needed + try: + print (f"*Passing upsc frames to ffmpeg...*") + vid_out_path = stitch_video(img_batch_id, orig_vid_fps, custom_upscale_path, real_audio_track, ffmpeg_location, resize_mode, upscaling_resize, upscaling_resize_w, upscaling_resize_h, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, ffmpeg_crf, ffmpeg_preset, keep_upscale_imgs, orig_vid_name) + # remove folder with raw (non-upscaled) vid input frames in case of input VID and not PNGs + if orig_vid_name is not None: + shutil.rmtree(raw_output_imgs_path) + except Exception as e: + print(f'Video stitching gone wrong. *Upscaled frames were saved to HD as backup!*. Actual error: {e}') + + devices.torch_gc() + +def process_frame(resize_mode, image, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility): + pp = PostprocessedImage(image) + postproc = scr.scripts_postproc + upscaler_script = next(s for s in postproc.scripts if s.name == "Upscale") + upscaler_script.process(pp, resize_mode, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility) + return pp.image + +def stitch_video(img_batch_id, fps, img_folder_path, audio_path, ffmpeg_location, resize_mode, upscaling_resize, upscaling_resize_w, upscaling_resize_h, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, f_crf, f_preset, keep_imgs, orig_vid_name): + parent_folder = os.path.dirname(img_folder_path) + grandparent_folder = os.path.dirname(parent_folder) + if orig_vid_name is not None: + mp4_path = os.path.join(grandparent_folder, str(orig_vid_name) +'_upscaled_' + (('by_' + str(upscaling_resize).replace('.', '-')) if resize_mode == 0 else f"to_{upscaling_resize_w}_{upscaling_resize_h}")) + f"_with_{extras_upscaler_1}" + (f"_then_{extras_upscaler_2}" if extras_upscaler_2_visibility > 0 else "") + else: + mp4_path = os.path.join(parent_folder, str(img_batch_id) +'_upscaled_' + (('by_' + str(upscaling_resize).replace('.', '-')) if resize_mode == 0 else f"to_{upscaling_resize_w}_{upscaling_resize_h}")) + f"_with_{extras_upscaler_1}_then_{extras_upscaler_2}" + + mp4_path = mp4_path + '.mp4' + + t = os.path.join(img_folder_path, "%07d.png") + add_soundtrack = 'None' + if not audio_path is None: + add_soundtrack = 'File' + + exception_raised = False + try: + ffmpeg_stitch_video(ffmpeg_location=ffmpeg_location, fps=fps, outmp4_path=mp4_path, stitch_from_frame=0, stitch_to_frame=1000000, imgs_path=t, add_soundtrack=add_soundtrack, audio_path=audio_path, crf=f_crf, preset=f_preset) + except Exception as e: + exception_raised = True + print(f"An error occurred while stitching the video: {e}") + + if not exception_raised and not keep_imgs: + shutil.rmtree(img_folder_path) + + if (keep_imgs and orig_vid_name is not None) or (orig_vid_name is not None and exception_raised is True): + shutil.move(img_folder_path, grandparent_folder) + + return mp4_path + +# NCNN Upscale section START +def process_ncnn_upscale_vid_upload_logic(vid_path, in_vid_fps, in_vid_res, out_vid_res, models_path, upscale_model, upscale_factor, keep_imgs, f_location, f_crf, f_preset, current_user_os): + print(f"Got a request to *upscale* a video using {upscale_model} at {upscale_factor}") + + folder_name = clean_folder_name(Path(vid_path.orig_name).stem) + outdir_no_tmp = os.path.join(os.getcwd(), 'outputs', 'frame-upscaling', folder_name) + i = 1 + while os.path.exists(outdir_no_tmp): + outdir_no_tmp = os.path.join(os.getcwd(), 'outputs', 'frame-upscaling', folder_name + '_' + str(i)) + i += 1 + + outdir = os.path.join(outdir_no_tmp, 'tmp_input_frames') + os.makedirs(outdir, exist_ok=True) + + vid2frames(video_path=vid_path.name, video_in_frame_path=outdir, overwrite=True, extract_from_frame=0, extract_to_frame=-1, numeric_files_output=True, out_img_format='png') + + process_ncnn_video_upscaling(vid_path, outdir, in_vid_fps, in_vid_res, out_vid_res, models_path, upscale_model, upscale_factor, keep_imgs, f_location, f_crf, f_preset, current_user_os) + +def process_ncnn_video_upscaling(vid_path, outdir, in_vid_fps, in_vid_res, out_vid_res, models_path, upscale_model, upscale_factor, keep_imgs, f_location, f_crf, f_preset, current_user_os): + # get clean number from 'x2, x3' etc + clean_num_r_up_factor = extract_number(upscale_factor) + # set paths + realesrgan_ncnn_location = os.path.join(models_path, 'realesrgan_ncnn', 'realesrgan-ncnn-vulkan' + ('.exe' if current_user_os == 'Windows' else '')) + upscaled_folder_path = os.path.join(os.path.dirname(outdir), 'Upscaled_frames') + # create folder for upscaled imgs to live in. this folder will stay alive if keep_imgs=True, otherwise get deleted at the end + os.makedirs(upscaled_folder_path, exist_ok=True) + out_upscaled_mp4_path = os.path.join(os.path.dirname(outdir), f"{vid_path.orig_name}_Upscaled_{upscale_factor}.mp4") + # download upscaling model if needed + check_and_download_realesrgan_ncnn(models_path, current_user_os) + # set cmd command + cmd = [realesrgan_ncnn_location, '-i', outdir, '-o', upscaled_folder_path, '-s', str(clean_num_r_up_factor), '-n', upscale_model] + # msg to print - need it to hide that text later on (!) + msg_to_print = f"Upscaling raw PNGs using {upscale_model} at {upscale_factor}..." + # blink the msg in the cli until action is done + console.print(msg_to_print, style="blink yellow", end="") + start_time = time.time() + # make call to ncnn upscaling executble + process = subprocess.run(cmd, capture_output=True, check=True, text=True) + print("\r" + " " * len(msg_to_print), end="", flush=True) + print(f"\r{msg_to_print}", flush=True) + print(f"\rUpscaling \033[0;32mdone\033[0m in {time.time() - start_time:.2f} seconds!", flush=True) + # set custom path for ffmpeg func below + upscaled_imgs_path_for_ffmpeg = os.path.join(upscaled_folder_path, "%05d.png") + add_soundtrack = 'None' + # don't pass add_soundtrack to ffmpeg if orig video doesn't contain any audio, so we won't get a message saying audio couldn't be added :) + if media_file_has_audio(vid_path.name, f_location): + add_soundtrack = 'File' + # stitch video from upscaled pngs + ffmpeg_stitch_video(ffmpeg_location=f_location, fps=in_vid_fps, outmp4_path=out_upscaled_mp4_path, stitch_from_frame=0, stitch_to_frame=-1, imgs_path=upscaled_imgs_path_for_ffmpeg, add_soundtrack=add_soundtrack, audio_path=vid_path.name, crf=f_crf, preset=f_preset) + # delete the raw video pngs + shutil.rmtree(outdir) + # delete upscaled imgs if user requested + if not keep_imgs: + shutil.rmtree(upscaled_folder_path) + +def check_and_download_realesrgan_ncnn(models_folder, current_user_os): + import zipfile + if current_user_os == 'Windows': + zip_file_name = 'realesrgan-ncnn-windows.zip' + executble_name = 'realesrgan-ncnn-vulkan.exe' + zip_checksum_value = '1d073f520a4a3f6438a500fea88407964da6d4a87489719bedfa7445b76c019fdd95a5c39576ca190d7ac22c906b33d5250a6f48cb7eda2b6af3e86ec5f09dfc' + download_url = 'https://github.com/hithereai/Real-ESRGAN/releases/download/real-esrgan-ncnn-windows/realesrgan-ncnn-windows.zip' + elif current_user_os == 'Linux': + zip_file_name = 'realesrgan-ncnn-linux.zip' + executble_name = 'realesrgan-ncnn-vulkan' + zip_checksum_value = 'df44c4e9a1ff66331079795f018a67fbad8ce37c4472929a56b5a38440cf96982d6e164a086b438c3d26d269025290dd6498bd50846bda8691521ecf8f0fafdf' + download_url = 'https://github.com/hithereai/Real-ESRGAN/releases/download/real-esrgan-ncnn-linux/realesrgan-ncnn-linux.zip' + elif current_user_os == 'Mac': + zip_file_name = 'realesrgan-ncnn-mac.zip' + executble_name = 'realesrgan-ncnn-vulkan' + zip_checksum_value = '65f09472025b55b18cf6ba64149ede8cded90c20e18d35a9edb1ab60715b383a6ffbf1be90d973fc2075cf99d4cc1411fbdc459411af5c904f544b8656111469' + download_url = 'https://github.com/hithereai/Real-ESRGAN/releases/download/real-esrgan-ncnn-mac/realesrgan-ncnn-mac.zip' + else: # who are you then? + raise Exception(f"No support for OS type: {current_user_os}") + + # set paths + realesrgan_ncnn_folder = os.path.join(models_folder, 'realesrgan_ncnn') + realesrgan_exec_path = os.path.join(realesrgan_ncnn_folder, executble_name) + realesrgan_zip_path = os.path.join(realesrgan_ncnn_folder, zip_file_name) + # return if exec file already exist + if os.path.exists(realesrgan_exec_path): + return + try: + os.makedirs(realesrgan_ncnn_folder, exist_ok=True) + # download exec and model files from url + load_file_from_url(download_url, realesrgan_ncnn_folder) + # check downloaded zip's hash + with open(realesrgan_zip_path, 'rb') as f: + file_hash = checksum(realesrgan_zip_path) + # wrong hash, file is probably broken/ download interrupted + if file_hash != zip_checksum_value: + raise Exception(f"Error while downloading {realesrgan_zip_path}. Please download from: {download_url}, and extract its contents into: {models_folder}/realesrgan_ncnn") + # hash ok, extract zip contents into our folder + with zipfile.ZipFile(realesrgan_zip_path, 'r') as zip_ref: + zip_ref.extractall(realesrgan_ncnn_folder) + # delete the zip file + os.remove(realesrgan_zip_path) + # chmod 755 the exec if we're in a linux machine, otherwise we'd get permission errors + if current_user_os in ('Linux', 'Mac'): + os.chmod(realesrgan_exec_path, 0o755) + # enable running the exec for mac users + if current_user_os == 'Mac': + os.system(f'xattr -d com.apple.quarantine "{realesrgan_exec_path}"') + + except Exception as e: + raise Exception(f"Error while downloading {realesrgan_zip_path}. Please download from: {download_url}, and extract its contents into: {models_folder}/realesrgan_ncnn") + +def make_upscale_v2(upscale_factor, upscale_model, keep_imgs, imgs_raw_path, imgs_batch_id, deforum_models_path, current_user_os, ffmpeg_location, ffmpeg_crf, ffmpeg_preset, fps, stitch_from_frame, stitch_to_frame, audio_path, add_soundtrack): + # get clean number from 'x2, x3' etc + clean_num_r_up_factor = extract_number(upscale_factor) + # set paths + realesrgan_ncnn_location = os.path.join(deforum_models_path, 'realesrgan_ncnn', 'realesrgan-ncnn-vulkan' + ('.exe' if current_user_os == 'Windows' else '')) + upscaled_folder_path = os.path.join(imgs_raw_path, f"{imgs_batch_id}_upscaled") + temp_folder_to_keep_raw_ims = os.path.join(upscaled_folder_path, 'temp_raw_imgs_to_upscale') + out_upscaled_mp4_path = os.path.join(imgs_raw_path, f"{imgs_batch_id}_Upscaled_{upscale_factor}.mp4") + # download upscaling model if needed + check_and_download_realesrgan_ncnn(deforum_models_path, current_user_os) + # make a folder with only the imgs we need to duplicate so we can call the ncnn with the folder syntax (quicker!) + duplicate_pngs_from_folder(from_folder=imgs_raw_path, to_folder=temp_folder_to_keep_raw_ims, img_batch_id=imgs_batch_id, orig_vid_name='Dummy') + # set dynamic cmd command + cmd = [realesrgan_ncnn_location, '-i', temp_folder_to_keep_raw_ims, '-o', upscaled_folder_path, '-s', str(clean_num_r_up_factor), '-n', upscale_model] + # msg to print - need it to hide that text later on (!) + msg_to_print = f"Upscaling raw output PNGs using {upscale_model} at {upscale_factor}..." + # blink the msg in the cli until action is done + console.print(msg_to_print, style="blink yellow", end="") + start_time = time.time() + # make call to ncnn upscaling executble + process = subprocess.run(cmd, capture_output=True, check=True, text=True, cwd=(os.path.join(deforum_models_path, 'realesrgan_ncnn') if current_user_os == 'Mac' else None)) + print("\r" + " " * len(msg_to_print), end="", flush=True) + print(f"\r{msg_to_print}", flush=True) + print(f"\rUpscaling \033[0;32mdone\033[0m in {time.time() - start_time:.2f} seconds!", flush=True) + # set custom path for ffmpeg func below + upscaled_imgs_path_for_ffmpeg = os.path.join(upscaled_folder_path, f"{imgs_batch_id}_%05d.png") + # stitch video from upscaled pngs + ffmpeg_stitch_video(ffmpeg_location=ffmpeg_location, fps=fps, outmp4_path=out_upscaled_mp4_path, stitch_from_frame=stitch_from_frame, stitch_to_frame=stitch_to_frame, imgs_path=upscaled_imgs_path_for_ffmpeg, add_soundtrack=add_soundtrack, audio_path=audio_path, crf=ffmpeg_crf, preset=ffmpeg_preset) + + # delete the duplicated raw imgs + shutil.rmtree(temp_folder_to_keep_raw_ims) + + if not keep_imgs: + shutil.rmtree(upscaled_folder_path) +# NCNN Upscale section END \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/video_audio_utilities.py b/extensions/deforum/scripts/deforum_helpers/video_audio_utilities.py new file mode 100644 index 0000000000000000000000000000000000000000..ebcf90119de1c6603abc3c905d0a902db499ca98 --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/video_audio_utilities.py @@ -0,0 +1,305 @@ +import os +import cv2 +import shutil +import math +import requests +import subprocess +import time +from pkg_resources import resource_filename +from modules.shared import state +from .general_utils import checksum, duplicate_pngs_from_folder +from basicsr.utils.download_util import load_file_from_url +from .rich import console + +# e.g gets 'x2' returns just 2 as int +def extract_number(string): + return int(string[1:]) if len(string) > 1 and string[1:].isdigit() else -1 + +def vid2frames(video_path, video_in_frame_path, n=1, overwrite=True, extract_from_frame=0, extract_to_frame=-1, out_img_format='jpg', numeric_files_output = False): + if (extract_to_frame <= extract_from_frame) and extract_to_frame != -1: + raise RuntimeError('Error: extract_to_frame can not be higher than extract_from_frame') + + if n < 1: n = 1 #HACK Gradio interface does not currently allow min/max in gr.Number(...) + + # check vid path using a function and only enter if we get True + if is_vid_path_valid(video_path): + + name = get_frame_name(video_path) + + vidcap = cv2.VideoCapture(video_path) + video_fps = vidcap.get(cv2.CAP_PROP_FPS) + + input_content = [] + if os.path.exists(video_in_frame_path) : + input_content = os.listdir(video_in_frame_path) + + # check if existing frame is the same video, if not we need to erase it and repopulate + if len(input_content) > 0: + #get the name of the existing frame + content_name = get_frame_name(input_content[0]) + if not content_name.startswith(name): + overwrite = True + + # grab the frame count to check against existing directory len + frame_count = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT)) + + # raise error if the user wants to skip more frames than exist + if n >= frame_count : + raise RuntimeError('Skipping more frames than input video contains. extract_nth_frames larger than input frames') + + expected_frame_count = math.ceil(frame_count / n) + # Check to see if the frame count is matches the number of files in path + if overwrite or expected_frame_count != len(input_content): + shutil.rmtree(video_in_frame_path) + os.makedirs(video_in_frame_path, exist_ok=True) # just deleted the folder so we need to make it again + input_content = os.listdir(video_in_frame_path) + + print(f"Trying to extract frames from video with input FPS of {video_fps}. Please wait patiently.") + if len(input_content) == 0: + vidcap.set(cv2.CAP_PROP_POS_FRAMES, extract_from_frame) # Set the starting frame + success,image = vidcap.read() + count = extract_from_frame + t=1 + success = True + while success: + if state.interrupted: + return + if (count <= extract_to_frame or extract_to_frame == -1) and count % n == 0: + if numeric_files_output == True: + cv2.imwrite(video_in_frame_path + os.path.sep + f"{t:05}.{out_img_format}" , image) # save frame as file + else: + cv2.imwrite(video_in_frame_path + os.path.sep + name + f"{t:05}.{out_img_format}" , image) # save frame as file + t += 1 + success,image = vidcap.read() + count += 1 + print(f"Successfully extracted {count} frames from video.") + else: + print("Frames already unpacked") + vidcap.release() + return video_fps + +# make sure the video_path provided is an existing local file or a web URL with a supported file extension +def is_vid_path_valid(video_path): + # make sure file format is supported! + file_formats = ["mov", "mpeg", "mp4", "m4v", "avi", "mpg", "webm"] + extension = video_path.rsplit('.', 1)[-1].lower() + # vid path is actually a URL, check it + if video_path.startswith('http://') or video_path.startswith('https://'): + response = requests.head(video_path, allow_redirects=True) + if response.status_code == 404: + raise ConnectionError("Video URL is not valid. Response status code: {}".format(response.status_code)) + elif response.status_code == 302: + response = requests.head(response.headers['location'], allow_redirects=True) + if response.status_code != 200: + raise ConnectionError("Video URL is not valid. Response status code: {}".format(response.status_code)) + if extension not in file_formats: + raise ValueError("Video file format '{}' not supported. Supported formats are: {}".format(extension, file_formats)) + else: + if not os.path.exists(video_path): + raise RuntimeError("Video path does not exist.") + if extension not in file_formats: + raise ValueError("Video file format '{}' not supported. Supported formats are: {}".format(extension, file_formats)) + return True + +# quick-retreive frame count, FPS and H/W dimensions of a video (local or URL-based) +def get_quick_vid_info(vid_path): + vidcap = cv2.VideoCapture(vid_path) + video_fps = vidcap.get(cv2.CAP_PROP_FPS) + video_frame_count = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT)) + video_width = int(vidcap.get(cv2.CAP_PROP_FRAME_WIDTH)) + video_height = int(vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + vidcap.release() + if video_fps.is_integer(): + video_fps = int(video_fps) + + return video_fps, video_frame_count, (video_width, video_height) + +# Stitch images to a h264 mp4 video using ffmpeg +def ffmpeg_stitch_video(ffmpeg_location=None, fps=None, outmp4_path=None, stitch_from_frame=0, stitch_to_frame=None, imgs_path=None, add_soundtrack=None, audio_path=None, crf=17, preset='veryslow'): + start_time = time.time() + + print(f"Got a request to stitch frames to video using FFmpeg.\nFrames:\n{imgs_path}\nTo Video:\n{outmp4_path}") + msg_to_print = f"Stitching *video*..." + console.print(msg_to_print, style="blink yellow", end="") + if stitch_to_frame == -1: + stitch_to_frame = 9999999 + try: + cmd = [ + ffmpeg_location, + '-y', + '-vcodec', 'png', + '-r', str(float(fps)), + '-start_number', str(stitch_from_frame), + '-i', imgs_path, + '-frames:v', str(stitch_to_frame), + '-c:v', 'libx264', + '-vf', + f'fps={float(fps)}', + '-pix_fmt', 'yuv420p', + '-crf', str(crf), + '-preset', preset, + '-pattern_type', 'sequence', + outmp4_path + ] + process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + except FileNotFoundError: + print("\r" + " " * len(msg_to_print), end="", flush=True) + print(f"\r{msg_to_print}", flush=True) + raise FileNotFoundError("FFmpeg not found. Please make sure you have a working ffmpeg path under 'ffmpeg_location' parameter.") + except Exception as e: + print("\r" + " " * len(msg_to_print), end="", flush=True) + print(f"\r{msg_to_print}", flush=True) + raise Exception(f'Error stitching frames to video. Actual runtime error:{e}') + + if add_soundtrack != 'None': + audio_add_start_time = time.time() + try: + cmd = [ + ffmpeg_location, + '-i', + outmp4_path, + '-i', + audio_path, + '-map', '0:v', + '-map', '1:a', + '-c:v', 'copy', + '-shortest', + outmp4_path+'.temp.mp4' + ] + process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + if process.returncode != 0: + print("\r" + " " * len(msg_to_print), end="", flush=True) + print(f"\r{msg_to_print}", flush=True) + raise RuntimeError(stderr) + os.replace(outmp4_path+'.temp.mp4', outmp4_path) + print("\r" + " " * len(msg_to_print), end="", flush=True) + print(f"\r{msg_to_print}", flush=True) + print(f"\rFFmpeg Video+Audio stitching \033[0;32mdone\033[0m in {time.time() - start_time:.2f} seconds!", flush=True) + except Exception as e: + print("\r" + " " * len(msg_to_print), end="", flush=True) + print(f"\r{msg_to_print}", flush=True) + print(f'\rError adding audio to video. Actual error: {e}', flush=True) + print(f"FFMPEG Video (sorry, no audio) stitching \033[33mdone\033[0m in {time.time() - start_time:.2f} seconds!", flush=True) + else: + print("\r" + " " * len(msg_to_print), end="", flush=True) + print(f"\r{msg_to_print}", flush=True) + print(f"\rVideo stitching \033[0;32mdone\033[0m in {time.time() - start_time:.2f} seconds!", flush=True) + +def get_frame_name(path): + name = os.path.basename(path) + name = os.path.splitext(name)[0] + return name + +def get_next_frame(outdir, video_path, frame_idx, mask=False): + frame_path = 'inputframes' + if (mask): frame_path = 'maskframes' + return os.path.join(outdir, frame_path, get_frame_name(video_path) + f"{frame_idx+1:05}.jpg") + +def find_ffmpeg_binary(): + try: + import google.colab + return 'ffmpeg' + except: + pass + for package in ['imageio_ffmpeg', 'imageio-ffmpeg']: + try: + package_path = resource_filename(package, 'binaries') + files = [os.path.join(package_path, f) for f in os.listdir(package_path) if f.startswith("ffmpeg-")] + files.sort(key=lambda x: os.path.getmtime(x), reverse=True) + return files[0] if files else 'ffmpeg' + except: + return 'ffmpeg' + +# These 2 functions belong to "stitch frames to video" in Output tab +def get_manual_frame_to_vid_output_path(input_path): + root, ext = os.path.splitext(input_path) + base, _ = root.rsplit("_", 1) + output_path = f"{base}.mp4" + i = 1 + while os.path.exists(output_path): + output_path = f"{base}_{i}.mp4" + i += 1 + return output_path + +def direct_stitch_vid_from_frames(image_path, fps, f_location, f_crf, f_preset, add_soundtrack, audio_path): + import re + # checking - do we actually have at least 4 matched files for the provided pattern + file_list = [image_path % i for i in range(4)] + exists_list = [os.path.isfile(file) for file in file_list] + # we got 4 files, moving on + if all(exists_list): + out_mp4_path = get_manual_frame_to_vid_output_path(image_path) + ffmpeg_stitch_video(ffmpeg_location=f_location, fps=fps, outmp4_path=out_mp4_path, stitch_from_frame=0, stitch_to_frame=-1, imgs_path=image_path, add_soundtrack=add_soundtrack, audio_path=audio_path, crf=f_crf, preset=f_preset) + else: + print("Couldn't find images that match the provided path/ pattern. At least 2 matched images are required.") +# end of 2 stitch frame to video funcs + +# returns True if filename (could be also media URL) contains an audio stream, othehrwise False +def media_file_has_audio(filename, ffmpeg_location): + result = subprocess.run([ffmpeg_location, "-i", filename, "-af", "volumedetect", "-f", "null", "-"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + output = result.stderr.decode() + return True if "Stream #0:1: Audio: " in output or "Stream #0:1(und): Audio" in output else False + +# download gifski binaries if needed - linux and windows only atm (apple users won't even see the option) +def check_and_download_gifski(models_folder, current_user_os): + if current_user_os == 'Windows': + file_name = 'gifski.exe' + checksum_value = 'b0dd261ad021c31c7fdb99db761b45165e6b2a7e8e09c5d070a2b8064b575d7a4976c364d8508b28a6940343119b16a23e9f7d76f1f3d5ff02289d3068b469cf' + download_url = 'https://github.com/hithereai/d/releases/download/giski-windows-bin/gifski.exe' + elif current_user_os == 'Linux': + file_name = 'gifski' + checksum_value = 'e65bf9502bca520a7fd373397e41078d5c73db12ec3e9b47458c282d076c04fa697adecb5debb5d37fc9cbbee0673bb95e78d92c1cf813b4f5cc1cabe96880ff' + download_url = 'https://github.com/hithereai/d/releases/download/gifski-linux-bin/gifski' + elif current_user_os == 'Mac': + file_name = 'gifski' + checksum_value = '622a65d25609677169ed2c1c53fd9aa496a98b357cf84d0c3627ae99c85a565d61ca42cdc4d24ed6d60403bb79b6866ce24f3c4b6fff58c4d27632264a96353c' + download_url = 'https://github.com/hithereai/d/releases/download/gifski-mac-bin/gifski' + else: # who are you then? + raise Exception(f"No support for OS type: {current_user_os}") + + file_path = os.path.join(models_folder, file_name) + + if not os.path.exists(file_path): + load_file_from_url(download_url, models_folder) + if current_user_os in ['Linux','Mac']: + os.chmod(file_path, 0o755) + if current_user_os == 'Mac': + # enable running the exec for mac users + os.system(f'xattr -d com.apple.quarantine "{file_path}"') + if checksum(file_path) != checksum_value: + raise Exception(f"Error while downloading {file_name}. Please download from: {download_url} and place in: {models_folder}") + +# create a gif using gifski - limited to up to 30 fps (from the ui; if users wanna try to hack it, results are not good, but possible up to 100 fps theoretically) +def make_gifski_gif(imgs_raw_path, imgs_batch_id, fps, models_folder, current_user_os): + import glob + msg_to_print = f"Stitching *gif* from frames using Gifski..." + # blink the msg in the cli until action is done + console.print(msg_to_print, style="blink yellow", end="") + start_time = time.time() + gifski_location = os.path.join(models_folder, 'gifski' + ('.exe' if current_user_os == 'Windows' else '')) + final_gif_path = os.path.join(imgs_raw_path, imgs_batch_id + '.gif') + if current_user_os == "Linux": + input_img_pattern = imgs_batch_id + '_0*.png' + input_img_files = [os.path.join(imgs_raw_path, file) for file in sorted(glob.glob(os.path.join(imgs_raw_path, input_img_pattern)))] + cmd = [gifski_location, '-o', final_gif_path] + input_img_files + ['--fps', str(fps), '--quality', str(95)] + elif current_user_os == "Windows": + input_img_pattern_for_gifski = os.path.join(imgs_raw_path, imgs_batch_id + '_0*.png') + cmd = [gifski_location, '-o', final_gif_path, input_img_pattern_for_gifski, '--fps', str(fps), '--quality', str(95)] + else: # should never this else as we check before, but just in case + print("\r" + " " * len(msg_to_print), end="", flush=True) + print(f"\r{msg_to_print}", flush=True) + raise Exception(f"No support for OS type: {current_user_os}") + + check_and_download_gifski(models_folder, current_user_os) + + try: + process = subprocess.run(cmd, capture_output=True, check=True, text=True, cwd=(models_folder if current_user_os == 'Mac' else None)) + print("\r" + " " * len(msg_to_print), end="", flush=True) + print(f"\r{msg_to_print}", flush=True) + print(f"GIF stitching \033[0;32mdone\033[0m in {time.time() - start_time:.2f} seconds!") + except Exception as e: + print("\r" + " " * len(msg_to_print), end="", flush=True) + print(f"\r{msg_to_print}", flush=True) + print(f"GIF stitching *failed* with error:\n{e}") \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/webui_sd_pipeline.py b/extensions/deforum/scripts/deforum_helpers/webui_sd_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..6bd1baab3461db6a4ee896dae2ddfc31cf22973f --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/webui_sd_pipeline.py @@ -0,0 +1,49 @@ +from modules.processing import StableDiffusionProcessingImg2Img +from modules.shared import opts, sd_model +import os + +def get_webui_sd_pipeline(args, root, frame): + import re + assert args.prompt is not None + + # Setup the pipeline + p = StableDiffusionProcessingImg2Img( + sd_model=sd_model, + outpath_samples = opts.outdir_samples or opts.outdir_img2img_samples, + #we'll setup the rest later + ) + + os.makedirs(args.outdir, exist_ok=True) + p.width, p.height = map(lambda x: x - x % 64, (args.W, args.H)) + p.steps = args.steps + p.seed = args.seed + p.sampler_name = args.sampler + p.batch_size = args.n_batch + p.tiling = args.tiling + p.restore_faces = args.restore_faces + p.subseed = args.subseed + p.subseed_strength = args.subseed_strength + p.seed_resize_from_w = args.seed_resize_from_w + p.seed_resize_from_h = args.seed_resize_from_h + p.fill = args.fill + p.ddim_eta = args.ddim_eta + p.batch_size = args.n_samples + p.width = args.W + p.height = args.H + p.seed = args.seed + p.do_not_save_samples = not args.save_sample_per_step + p.sampler_name = args.sampler + p.mask_blur = args.mask_overlay_blur + p.extra_generation_params["Mask blur"] = args.mask_overlay_blur + p.n_iter = 1 + p.steps = args.steps + if opts.img2img_fix_steps: + p.denoising_strength = 1 / (1 - args.strength + 1.0/args.steps) #see https://github.com/deforum-art/deforum-for-automatic1111-webui/issues/3 + else: + p.denoising_strength = 1 - args.strength + p.cfg_scale = args.scale + p.image_cfg_scale = args.pix2pix_img_cfg_scale + p.outpath_samples = root.outpath_samples + + + return p \ No newline at end of file diff --git a/extensions/deforum/scripts/deforum_helpers/word_masking.py b/extensions/deforum/scripts/deforum_helpers/word_masking.py new file mode 100644 index 0000000000000000000000000000000000000000..9b16ba64bfe798266f2de2436bd6802285d62c6e --- /dev/null +++ b/extensions/deforum/scripts/deforum_helpers/word_masking.py @@ -0,0 +1,41 @@ +import os +import torch +from PIL import Image +from torchvision import transforms +from clipseg.models.clipseg import CLIPDensePredT + +preclipseg_transform = transforms.Compose([ + transforms.ToTensor(), + transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), + transforms.Resize((512, 512)), #TODO: check if the size is hardcoded +]) + +def find_clipseg(root): + src_basedirs = [] + for basedir in root.basedirs: + src_basedirs.append(basedir + '/scripts/deforum_helpers/src') + src_basedirs.append(basedir + '/extensions/deforum/scripts/deforum_helpers/src') + src_basedirs.append(basedir + '/extensions/deforum-for-automatic1111-webui/scripts/deforum_helpers/src') + + for basedir in src_basedirs: + pth = os.path.join(basedir, './clipseg/weights/rd64-uni.pth') + if os.path.exists(pth): + return pth + raise Exception('CLIPseg weights not found!') + +def setup_clipseg(root): + model = CLIPDensePredT(version='ViT-B/16', reduce_dim=64) + model.eval() + model.load_state_dict(torch.load(find_clipseg(root), map_location=root.device), strict=False) + + model.to(root.device) + root.clipseg_model = model + +def get_word_mask(root, frame, word_mask): + if root.clipseg_model is None: + setup_clipseg(root) + img = preclipseg_transform(frame).to(root.device, dtype=torch.float32) + word_masks = [word_mask] + with torch.no_grad(): + preds = root.clipseg_model(img.repeat(len(word_masks),1,1,1), word_masks)[0] + return Image.fromarray(torch.sigmoid(preds[0][0]).multiply(255).to(dtype=torch.uint8,device='cpu').numpy()) diff --git a/extensions/deforum/style.css b/extensions/deforum/style.css new file mode 100644 index 0000000000000000000000000000000000000000..5b3615d207357b2b00c1ba32a737e213e1bdd5ce --- /dev/null +++ b/extensions/deforum/style.css @@ -0,0 +1,36 @@ +#vid_to_interpolate_chosen_file .w-full, #vid_to_upscale_chosen_file .w-full, #controlnet_input_video_chosen_file .w-full, #controlnet_input_video_mask_chosen_file .w-full { + display: flex !important; + align-items: flex-start !important; + justify-content: center !important; +} + +#vid_to_interpolate_chosen_file, #vid_to_upscale_chosen_file, #controlnet_input_video_chosen_file, #controlnet_input_video_mask_chosen_file { + height: 85px !important; +} + +#save_zip_deforum, #save_deforum { + display: none; +} + +#extra_schedules::before { + content: "Schedules:"; + font-size: 10px !important; +} + +#hybrid_msg_html { + color: Tomato !important; + margin-top: 5px !important; + text-align: center !important; + font-size: 20px !important; + font-weight: bold !important; +} + +#deforum_results .flex #image_buttons_deforum #img2img_tab, +#deforum_results .flex #image_buttons_deforum #inpaint_tab, +#deforum_results .flex #image_buttons_deforum #extras_tab { + display: none !important; +} + +#controlnet_not_found_html_msg { + color: Tomato; +}