├── .gitignore
├── LICENSE
├── README.md
├── install.py
├── javascript
└── temporaljavascript.js
├── readme_img
├── 1.png
├── 2.png
├── 3.png
├── 4.png
└── 5.png
├── requirements.txt
├── scripts
├── Berry_Method.py
├── Ebsynth_Processing.py
├── TemporalKitImg2ImgTab.py
├── berry_utility.py
├── optical_flow_raft.py
├── optical_flow_simple.py
├── sd-TemporalKit-UI.py
└── stable_diffusion_processing.py
├── style.css
└── temp_file.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Example user template template
2 | ### Example user template
3 |
4 | # IntelliJ project files
5 | .idea
6 | *.iml
7 | out
8 | gen
9 | ### Python template
10 | # Byte-compiled / optimized / DLL files
11 | __pycache__/
12 | *.py[cod]
13 | *$py.class
14 |
15 | # C extensions
16 | *.so
17 |
18 | # Distribution / packaging
19 | .Python
20 | build/
21 | develop-eggs/
22 | dist/
23 | downloads/
24 | eggs/
25 | .eggs/
26 | lib/
27 | lib64/
28 | parts/
29 | sdist/
30 | var/
31 | wheels/
32 | share/python-wheels/
33 | *.egg-info/
34 | .installed.cfg
35 | *.egg
36 | MANIFEST
37 |
38 | # PyInstaller
39 | # Usually these files are written by a python script from a template
40 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
41 | *.manifest
42 | *.spec
43 |
44 | # Installer logs
45 | pip-log.txt
46 | pip-delete-this-directory.txt
47 |
48 | # Unit test / coverage reports
49 | htmlcov/
50 | .tox/
51 | .nox/
52 | .coverage
53 | .coverage.*
54 | .cache
55 | nosetests.xml
56 | coverage.xml
57 | *.cover
58 | *.py,cover
59 | .hypothesis/
60 | .pytest_cache/
61 | cover/
62 |
63 | # Translations
64 | *.mo
65 | *.pot
66 |
67 | # Django stuff:
68 | *.log
69 | local_settings.py
70 | db.sqlite3
71 | db.sqlite3-journal
72 |
73 | # Flask stuff:
74 | instance/
75 | .webassets-cache
76 |
77 | # Scrapy stuff:
78 | .scrapy
79 |
80 | # Sphinx documentation
81 | docs/_build/
82 |
83 | # PyBuilder
84 | .pybuilder/
85 | target/
86 |
87 | # Jupyter Notebook
88 | .ipynb_checkpoints
89 |
90 | # IPython
91 | profile_default/
92 | ipython_config.py
93 |
94 | # pyenv
95 | # For a library or package, you might want to ignore these files since the code is
96 | # intended to run in multiple environments; otherwise, check them in:
97 | # .python-version
98 |
99 | # pipenv
100 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
101 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
102 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
103 | # install all needed dependencies.
104 | #Pipfile.lock
105 |
106 | # poetry
107 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
108 | # This is especially recommended for binary packages to ensure reproducibility, and is more
109 | # commonly ignored for libraries.
110 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
111 | #poetry.lock
112 |
113 | # pdm
114 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
115 | #pdm.lock
116 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
117 | # in version control.
118 | # https://pdm.fming.dev/#use-with-ide
119 | .pdm.toml
120 |
121 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
122 | __pypackages__/
123 |
124 | # Celery stuff
125 | celerybeat-schedule
126 | celerybeat.pid
127 |
128 | # SageMath parsed files
129 | *.sage.py
130 |
131 | # Environments
132 | .env
133 | .venv
134 | env/
135 | venv/
136 | ENV/
137 | env.bak/
138 | venv.bak/
139 |
140 | # Spyder project settings
141 | .spyderproject
142 | .spyproject
143 |
144 | # Rope project settings
145 | .ropeproject
146 |
147 | # mkdocs documentation
148 | /site
149 |
150 | # mypy
151 | .mypy_cache/
152 | .dmypy.json
153 | dmypy.json
154 |
155 | # Pyre type checker
156 | .pyre/
157 |
158 | # pytype static type analyzer
159 | .pytype/
160 |
161 | # Cython debug symbols
162 | cython_debug/
163 |
164 | # PyCharm
165 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
166 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
167 | # and can be added to the global gitignore or merged into this file. For a more nuclear
168 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
169 | #.idea/
170 |
171 | ### PyCharm+all template
172 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
173 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
174 |
175 | # User-specific stuff
176 | .idea/**/workspace.xml
177 | .idea/**/tasks.xml
178 | .idea/**/usage.statistics.xml
179 | .idea/**/dictionaries
180 | .idea/**/shelf
181 |
182 | # AWS User-specific
183 | .idea/**/aws.xml
184 |
185 | # Generated files
186 | .idea/**/contentModel.xml
187 |
188 | # Sensitive or high-churn files
189 | .idea/**/dataSources/
190 | .idea/**/dataSources.ids
191 | .idea/**/dataSources.local.xml
192 | .idea/**/sqlDataSources.xml
193 | .idea/**/dynamic.xml
194 | .idea/**/uiDesigner.xml
195 | .idea/**/dbnavigator.xml
196 |
197 | # Gradle
198 | .idea/**/gradle.xml
199 | .idea/**/libraries
200 |
201 | # Gradle and Maven with auto-import
202 | # When using Gradle or Maven with auto-import, you should exclude module files,
203 | # since they will be recreated, and may cause churn. Uncomment if using
204 | # auto-import.
205 | # .idea/artifacts
206 | # .idea/compiler.xml
207 | # .idea/jarRepositories.xml
208 | # .idea/modules.xml
209 | # .idea/*.iml
210 | # .idea/modules
211 | # *.iml
212 | # *.ipr
213 |
214 | # CMake
215 | cmake-build-*/
216 |
217 | # Mongo Explorer plugin
218 | .idea/**/mongoSettings.xml
219 |
220 | # File-based project format
221 | *.iws
222 |
223 | # IntelliJ
224 | out/
225 |
226 | # mpeltonen/sbt-idea plugin
227 | .idea_modules/
228 |
229 | # JIRA plugin
230 | atlassian-ide-plugin.xml
231 |
232 | # Cursive Clojure plugin
233 | .idea/replstate.xml
234 |
235 | # SonarLint plugin
236 | .idea/sonarlint/
237 |
238 | # Crashlytics plugin (for Android Studio and IntelliJ)
239 | com_crashlytics_export_strings.xml
240 | crashlytics.properties
241 | crashlytics-build.properties
242 | fabric.properties
243 |
244 | # Editor-based Rest Client
245 | .idea/httpRequests
246 |
247 | # Android studio 3.1+ serialized cache file
248 | .idea/caches/build_file_checksums.ser
249 |
250 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | TemporalKit
2 | ===
3 | An all in one solution for adding Temporal Stability to a Stable Diffusion Render via an automatic1111 extension
4 |
5 |
6 |
7 | ---
8 |
9 | ***You must install FFMPEG to path before running this***
10 |
11 | You can find a demonstration run through with a single batch here:
12 | https://twitter.com/CiaraRowles1/status/1645923461343363072
13 |
14 | And a batch demonstration here:
15 | https://mobile.twitter.com/CiaraRowles1/status/1646458056803250178
16 |
17 | Ebsynth tutorial:
18 | https://twitter.com/CiaraRowles1/status/1648462374125576192
19 | **NOTE: EBSYNTH DOES NOT REGISTER THE KEYFRAMES IF YOU USE ABOVE 20.**
20 |
21 | Ebsynth split frames tutorial:
22 | https://www.youtube.com/watch?v=z3YNHiuvxyg&ab_channel=CiaraRowles
23 |
24 | Example results you can get:
25 |
26 | https://user-images.githubusercontent.com/13116982/234425054-9a1bbf30-93a8-4f5b-9e80-4376ab3c510a.mp4
27 |
28 |
29 |
30 | ---
31 |
32 | The values in the extension are as follows
33 | ---
34 |
35 | | Variable | Description |
36 | |---------------------| --- |
37 | | `FPS` | The fps the video is extracted and produced at. |
38 | | `batch_Size` | This is the number of frames between each keyframe, so for example if you had an fps of 30, and a batch size of 10, it would make 3 keyframes a second and estimate the rest. |
39 | | `per side` | This is the square root of the number of frames per plate, so for example a per side value of 2 would make 4 plates, 3, 9 plates, 4 16 plates. |
40 | | `Resolution` | The size of each plate, it is strongly reccomended you set this to a multiple of your per side variable |
41 | | `batch settings` | Only open this drop down if you want to generate a folder of plates. |
42 | | `Max Frames` | When generating a folder of plates, this gets how many frames at the above fps you want to get, and then divides them into plates in groups of (per side * per side * batch size) |
43 | | `Border Frames` | Every batch generated plate will contain this many frames from the next plate and blend between them. |
44 | | `Batch Folder` | If you're generating a batch of plates, just specify a empty folder and on clicking run, it will populate it with the relevant folders and files, all you need to do is go to img2img batch processing in original sd, enter the newly create input folder as the input, the newly created output folder as the output, generate, move back to the temporal-kit Batch-Warp Tab, put in the whole folder directory and click read and it will set everything up. |
45 | | `Output Resolution` | The maximum resolution on any side of the output video. |
46 |
47 |
48 |
49 | ---
50 |
51 | FAQ:
52 | ---
53 |
54 | > **Q:** My video has smearing.
55 | >
56 | > **A:** Use a higher fps and/or lower batchnumber, the closer together the keyframes the less artifacts.
57 |
58 | > **Q:** Stable diffusion cannot be turned on after installing this Extension. `ModuleNotFoundError: No module named 'tqdm.auto'`
59 | >
60 | > **A:** Because the dependency currently used by this plug-in uses an old version of tqdm, an error occurs. The short-term solution is to manually install a new version(4.66.1) of tqdm.
61 | > ```bash
62 | > pip install tqdm==4.66.1
63 | > ```
64 | > [More information](https://github.com/CiaraStrawberry/TemporalKit/issues/104#issuecomment-1722527970)
65 |
66 |
67 |
68 | ---
69 |
70 | Step-by-Step Tutorial
71 | ---
72 | Written with reference to this [web page](https://stable-diffusion-art.com/video-to-video/#Method_5_Temporal_Kit) teaching and my [own(cocomine)](https://github.com/cocomine/) experience
73 |
74 |
75 |
76 | ### Step 1: Install Extensions on WebUI
77 |
78 | Open `Extensions` tab > `Install from URL` > Paste follow link in `URL for extension’s git repository` > Click `Install`
79 |
80 | ```
81 | https://github.com/CiaraStrawberry/TemporalKit
82 | ```
83 |
84 | ### Step 2: Install FFMPEG
85 |
86 | #### Ubuntu
87 |
88 | ```bash
89 | sudo apt install ffmpeg
90 | ```
91 |
92 | #### Arch Linux
93 | ```bash
94 | sudo pacman -S ffmpeg
95 | ```
96 |
97 | #### Windows
98 | Download and install from https://ffmpeg.org/download.html
99 | Make sure to add ffmpeg to your PATH.
100 | Learn more: https://www.wikihow.com/Install-FFmpeg-on-Windows
101 |
102 | ### Step 4: Prepare your video
103 | Create a folder in your desired location. This folder will be used to store the files that need to be processed.
104 | Prepare the video you need to use (referred to as the original video in subsequent teaching), and understand the format of the original video, such as resolution and frame.
105 |
106 | ### Step 5: Extract frames from the original video
107 | 1. Open `Temporal-Kit` Tab on Top.
108 | 2. Open `Pre-Process` Tab.
109 | 2. Drag & Drop the original video into the `Input Video`.
110 | 3. Set `fps` to the frame rate of the original video.
111 | 4. Set `frames per keyframe` to the number of frames between each keyframe. For example, if the original video is 30fps and you set it to 10, then 3 keyframes will be generated per second, and the rest will be estimated.
112 | 5. Set `Side` to the square root of the number of frames per plate. For example, if you set it to 2, 4 plates(2x2) will be generated, 3, 9 plates(3x3), 4, 16 plates(4x4).
113 | 6. Set `Height Resolution` to the size of each plate. It is strongly recommended that you set this to a multiple of your side variable.
For example, if you want to generate 4 plates and set the side to 2, each plate high 512, then you need to set the height resolution to 1024(512x2).
114 | 7. Set `Target Folder` to the folder you created in [step 4](#step-4-prepare-your-video).
115 | 8. Open `Batch Settings` Tab.
116 | 9. Tick the `Batch Run`.
117 | 10. Open `EBsynth` Tab.
118 | 11. Tick the `Split Video`
119 |
120 | When you complete the above steps you should see a structure similar to this in the folder you specified (depending on the length of your video)
121 |
122 | 
123 |
124 | You will see a structure like this in the video clips divided into folders named by numbers.
125 |
126 | 
127 |
128 | > If you encounter out of memory issue in the next **img2img** step, reduce the `side` or `Height Resolution` parameters.
129 |
130 | ### Step 6: Perform Img2img on keyframes
131 | Let’s deal with the folder named `0` first.
132 | Go to the **Img2img** page. Switch to the **Batch** tab. Set the following parameters:
133 |
134 | **Input directory**: The name of your [target directory](#step-4-prepare-your-video) with `\input` appended. E.g. `YOUR_FOLDER_PATH_IN_SETP_4\0\input`
135 | **Output directory**: Similarly but with `\output` appended. E.g. `YOUR_FOLDER_PATH_IN_SETP_4\0\output`
136 |
137 | Enter a **prompt** and a **negative prompt** like txt2img.
138 | **Sampling method:** DPM++2M Karras
139 | **Sampling steps:** 20
140 | **CFG scale:** 7
141 | **Denoising strength:** 0.5 (adjust accordingly)
142 | > The above parameters can be changed as needed.
143 |
144 |
145 | ##### Control Net (option, which would give better results if available)
146 | In ControlNet (Unit 0) section, set:
147 | + Enable: Yes
148 | + Pixel Perfect: Yes
149 | + ControlType: Tile
150 | + Preprocessor: tile_resample
151 | + Model: control_xxxx_tile
152 |
153 | Press **Generate**. After it is done, you will find the image in the batch output folder.
154 |
155 | > Make sure to open the image in full size and inspect the details in full size. Make sure they look sharp and have a consistent style.
156 |
157 | > If you want to obtain high-resolution images, please put the output images back into img2img, and adjust resizd by `1.5-2.0`, Denoising strength `0.3-0.4`, and then generate.
158 |
159 | ### Step 7: Prepare EbSynth data
160 | Go to `Temporal-Kit` page and switch to the `Ebsynth-Process` tab.
161 |
162 | **Input Folder:** Put in the same [target folder](#step-4-prepare-your-video) path you put in the Pre-Processing page. E.g. `YOUR_FOLDER_PATH_IN_SETP_4\0`
163 |
164 | Click read last_settings. If your input folder is correct, the video and the settings will be populated.
165 |
166 | Click prepare ebsynth. After it is done, you should see the keys folder populated with your stylized keyframes, and the frames folder populated with your images.
167 |
168 | 
169 | 
170 |
171 | > Please note that this program does not generate `.ebs` files. When your images are imported into the program, they will be automatically populated.
172 |
173 | ### Step 8: Process with EbSynth
174 | Now open the **EbSynth** program.
175 |
176 | Open the File Explorer and navigate to the folder your creation in [step4](#step-4-prepare-your-video). You should folder like the ones showed below. We need the **keys** folder and the **frames** folder for EbSynth.
177 |
178 | Drag the **keys** folder from the File Explorer and drop it to the **Keyframes** field in EbSynth.
179 | Drag the **frames** folder from the File Explorer and drop it to the **frames** field in EbSynth.
180 |
181 | 
182 |
183 | Click **Run All** and wait for them to complete.
184 | When it is done, you should see a series of `out_#####` directories generated in the [target project folder](#step-4-prepare-your-video).
185 |
186 | > Please download the program from the official website.
187 | > https://ebsynth.com/
188 |
189 | ### Step 9: Generate the final video
190 | Now go back to **AUTOMATIC1111**(webUI). You should still be on the **Temporal Kit** page and **Ebsynth-Process** tab.
191 |
192 | Click **recombine ebsynth** and you are done!
193 |
194 | 
195 |
196 | Look how smooth the video is. With some tweaking, you can probably make it better!
197 |
198 | ### Step 10: Continue processing other split segments
199 | Repeat steps [6](#step-6-perform-img2img-on-keyframes) to [9](#step-9-generate-the-final-video). Process other folders `(1,2,3,4,...)`
200 |
201 | ### Step 11: Combine the split videos
202 | Use a video splicing program to merge segmented videos
203 |
204 |
205 |
206 | ---
207 |
208 | TODO
209 | ---
210 |
211 | - set up diffusion based upscaling for the plates output
212 | - get the img2img button working with batch processing.
213 | - add a check to see if the output folder was added.
214 | - fix that weird shutdown error it gives after running
215 | - hook up to the api.
216 | - flowmaps from game engine export\import support
217 |
218 | _Thanks to RAFT for the optical flow system._
219 |
--------------------------------------------------------------------------------
/install.py:
--------------------------------------------------------------------------------
1 | import launch
2 |
3 | if not launch.is_installed("ffmpeg"):
4 | launch.run_pip("install ffmpeg-python", "Install \"ffmpeg-python\" requirements for TemporalKit extension")
5 |
6 | if not launch.is_installed("moviepy"):
7 | launch.run_pip("install moviepy", "Install \"moviepy\" requirements for TemporalKit extension")
8 |
9 | if not launch.is_installed("imageio_ffmpeg"):
10 | launch.run_pip("install imageio_ffmpeg", "Install \"imageio_ffmpeg\" requirements for TemporalKit extension")
11 |
12 | if not launch.is_installed("scenedetect"):
13 | launch.run_pip("install scenedetect", "Install \"scenedetect\" requirements for TemporalKit extension")
14 |
--------------------------------------------------------------------------------
/javascript/temporaljavascript.js:
--------------------------------------------------------------------------------
1 | function switch_to_temporal_kit() {
2 | gradioApp().querySelector('#tabs').querySelectorAll('button')[6].click();
3 | // gradioApp().getElementById('TemporalKit').querySelectorAll('button')[0].click();
4 | }
5 |
6 | function switch_to_temporal_kit_final2() {
7 | // Get the current image source
8 | // const gallery = document.getElementById('img2img_gallery');
9 | // const firstImageSource = gallery.getElementsByTagName('img')[0].src;
10 | //firstImageSource = document.getElementById('svelte-1tkea93').src;
11 | // Switch to the "temporal-kit" tab and the "final" subtab
12 |
13 | switch_to_temporal_kit_final();
14 | const tabList = document.querySelector("#TemporalKit-Tab");
15 |
16 | if (tabList) {
17 | const firstChild = tabList.firstElementChild;
18 |
19 | if (firstChild) {
20 | const secondTab = firstChild.querySelector(":nth-child(2)");
21 |
22 | if (secondTab) {
23 | secondTab.click();
24 | } else {
25 | console.error("Second tab element not found.");
26 | }
27 | } else {
28 | console.error("First child element not found.");
29 | }
30 | } else {
31 | console.error("Tab list element not found.");
32 | }
33 | document.getElementById("read_last_settings").click();
34 | document.getElementById("read_last_image").click();
35 |
36 | // Paste the image source into the "final" subtab's image element
37 | // document.getElementById('output_image').src = firstImageSource;
38 | }
39 |
40 |
--------------------------------------------------------------------------------
/readme_img/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CiaraStrawberry/TemporalKit/f46d255cfeb9c4b0c682bae5660a04ac7b7cd8dc/readme_img/1.png
--------------------------------------------------------------------------------
/readme_img/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CiaraStrawberry/TemporalKit/f46d255cfeb9c4b0c682bae5660a04ac7b7cd8dc/readme_img/2.png
--------------------------------------------------------------------------------
/readme_img/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CiaraStrawberry/TemporalKit/f46d255cfeb9c4b0c682bae5660a04ac7b7cd8dc/readme_img/3.png
--------------------------------------------------------------------------------
/readme_img/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CiaraStrawberry/TemporalKit/f46d255cfeb9c4b0c682bae5660a04ac7b7cd8dc/readme_img/4.png
--------------------------------------------------------------------------------
/readme_img/5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CiaraStrawberry/TemporalKit/f46d255cfeb9c4b0c682bae5660a04ac7b7cd8dc/readme_img/5.png
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | ffmpeg-python
2 | moviepy
3 | imageio_ffmpeg
4 | scenedetect
--------------------------------------------------------------------------------
/scripts/Berry_Method.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import base64
3 | from PIL import Image
4 | import numpy as np
5 | import math
6 | import scripts.berry_utility as utilityb
7 | import scripts.stable_diffusion_processing as sdprocess
8 | from moviepy.editor import *
9 | import os
10 | import subprocess
11 | import json
12 | import tempfile
13 | import uuid
14 | from torchvision.io import write_jpeg
15 | import re
16 | import gradio as gr
17 | from io import BytesIO
18 | import shutil
19 |
20 | resolution = 1400
21 | smol_resolution = 512
22 | prompt = "cyborg humans photo realistic"
23 | fill_in_denoise = 0
24 | edge_denoise = 0.4 # this is a factor of fill in denoise
25 | initial_denoise = 0.85
26 | frames_limit = 50
27 | seed = 5434536443
28 | diffuse = False
29 | check_edges = False
30 |
31 | def split_into_batches(frames, batch_size, max_batches):
32 | groups = [frames[i:i+batch_size] for i in range(0, len(frames), batch_size)][:max_batches]
33 |
34 | # Add any remaining images to the last group
35 | if len(frames) > max_batches * batch_size:
36 | groups[-1] += frames[max_batches*batch_size:]
37 |
38 | return groups
39 |
40 | def create_square_texture(frames, max_size, side_length=3):
41 |
42 | original_height, original_width = frames[0].shape[:2]
43 | # Calculate the average aspect ratio of the input frames
44 | big_frame_width = original_width * side_length
45 | big_frame_height = original_height * side_length
46 |
47 | texture_aspect_ratio = float(big_frame_width) / float(big_frame_height)
48 | _smol_frame_height = max_size
49 | _smol_frame_width = int(_smol_frame_height * texture_aspect_ratio)
50 |
51 |
52 | actual_texture_width, actual_texture_height = utilityb.resize_to_nearest_multiple(_smol_frame_width, _smol_frame_height, side_length)
53 |
54 | frames_per_row = side_length
55 | frame_width = int (actual_texture_width / side_length)
56 | frame_height = int(actual_texture_height / side_length)
57 | print (f"generating square of width {actual_texture_width} and height {actual_texture_height}")
58 |
59 | texture = np.zeros((actual_texture_height, actual_texture_width, 3), dtype=np.uint8)
60 |
61 | for i, frame in enumerate(frames):
62 | if frame is not None and not frame.size == 0:
63 | resized_frame = cv2.resize(frame, (frame_width, frame_height), interpolation=cv2.INTER_AREA)
64 | row, col = i // frames_per_row, i % frames_per_row
65 | texture[row * frame_height:(row + 1) * frame_height, col * frame_width:(col + 1) * frame_width] = resized_frame
66 | #truth be told i am not entirely sure why this is needed
67 | fixed_texture = cv2.resize(texture, (actual_texture_width, actual_texture_height), interpolation=cv2.INTER_AREA)
68 |
69 | return fixed_texture
70 |
71 | def split_frames_into_big_batches(frames, batch_size, border,ebsynth,returnframe_locations=False):
72 | """
73 | Splits an array of numpy frames into batches of a given size, adding a certain number of border
74 | frames from the next batch to each batch.
75 |
76 | Parameters:
77 | frames (numpy.ndarray): The input frames to be split.
78 | batch_size (int): The number of frames per batch.
79 | border (int): The number of border frames from the next batch to add to each batch.
80 |
81 | Returns:
82 | List[numpy.ndarray]: A list of batches, each containing `batch_size` + `border` frames (except for the last batch).
83 | """
84 | num_frames = len(frames)
85 | num_batches = int(np.ceil(num_frames / batch_size))
86 | print(f"frames num = {len(frames)} while num batches = {num_batches}")
87 | batches = []
88 |
89 | frame_locations = []
90 | for i in range(num_batches):
91 | start_idx = i * batch_size
92 | end_idx = start_idx + batch_size
93 | if ebsynth == False:
94 | # Add border frames if not the last batch and if available
95 | if i < num_batches - 1:
96 | end_idx += min(border, num_frames - end_idx)
97 | else:
98 | # Combine the last batch with the previous batch if the number of frames in the last batch is smaller than the border size
99 | if end_idx - start_idx < border and len(batches) > 0:
100 | batches[-1] = np.concatenate((batches[-1], frames[start_idx:end_idx]))
101 | break
102 | else:
103 | if i < num_batches - 1:
104 | end_idx = end_idx + border
105 |
106 | end_idx = min(end_idx, num_frames)
107 | batches.append(frames[start_idx:end_idx])
108 | print (f"batch {i} has {len(batches[i])} frames")
109 | frame_locations.append((start_idx,end_idx))
110 |
111 | if returnframe_locations == False:
112 | return batches
113 | else:
114 | return batches,frame_locations
115 |
116 | def split_square_texture(texture, num_frames,max_frames, _smol_resolution,ebsynth=False):
117 |
118 | texture_height, texture_width = texture.shape[:2]
119 | texture_aspect_ratio = float(texture_width) / float(texture_height)
120 |
121 | frames_per_row = int(math.ceil(math.sqrt(max_frames)))
122 | frame_height = int (texture_height / frames_per_row)
123 | frame_width = int(texture_width / frames_per_row)
124 |
125 | _smol_frame_height = _smol_resolution
126 | _smol_frame_width = int(_smol_frame_height * texture_aspect_ratio)
127 |
128 | if ebsynth == False:
129 | _smol_frame_resized_width, _smol_frame_resized_height = utilityb.resize_to_nearest_multiple_of_8(_smol_frame_width, _smol_frame_height)
130 | else:
131 | _smol_frame_resized_width, _smol_frame_resized_height = _smol_frame_width, _smol_frame_height
132 | #_smol_frame_resized_width, _smol_frame_resized_height = _smol_frame_width, _smol_frame_height
133 | frames = []
134 |
135 | for i in range(num_frames):
136 | row, col = i // frames_per_row, i % frames_per_row
137 | frame = texture[row * frame_height:(row + 1) * frame_height, col * frame_width:(col + 1) * frame_width]
138 |
139 | if not frame.size == 0:
140 | resized_frame = cv2.resize(frame, (_smol_frame_resized_width, _smol_frame_resized_height), interpolation=cv2.INTER_AREA)
141 | frames.append(resized_frame)
142 | else:
143 | print("frame size 0")
144 | frames.append(np.zeros((_smol_frame_resized_width, _smol_frame_resized_height, 3), dtype=np.uint8))
145 |
146 | return frames
147 |
148 | def save_square_texture(texture, file_path):
149 | # Check if the input has the correct data type and convert if necessary
150 | if texture.dtype != np.uint8:
151 | texture = (texture * 255).astype(np.uint8)
152 |
153 | # Check if the input has the intended shape (3 channels for an RGB image)
154 | if texture.ndim != 3 or texture.shape[2] != 3:
155 | raise ValueError("Invalid texture shape. Expected a 3-channel RGB image.")
156 |
157 | # Convert the NumPy array to a PIL Image
158 | image = Image.fromarray(texture)
159 |
160 | # Save the image to the specified file path
161 | print(f'saved to {file_path} at size {image.size}')
162 | image.save(file_path, format="PNG")
163 |
164 |
165 | def convert_video_to_bytes(input_file):
166 | # Read the uploaded video file
167 | print(f"reading video file... {input_file}")
168 | with open(input_file, "rb") as f:
169 | video_bytes = f.read()
170 |
171 | # Return the processed video bytes (or any other output you want)
172 | return video_bytes
173 |
174 |
175 |
176 | def generate_square_from_video(video_path, fps, batch_size,resolution,size_size):
177 | video_data = convert_video_to_bytes(video_path)
178 | frames_limit = (size_size * size_size) * batch_size
179 | frames = utilityb.extract_frames_movpie(video_data, fps, frames_limit)
180 | print(len(frames))
181 | number_of_batches = size_size * size_size
182 | batches = split_into_batches(frames, batch_size,number_of_batches)
183 | print("Number of batches:", len(batches))
184 | first_frames = [batch[0] for batch in batches]
185 |
186 | square_texture = create_square_texture(first_frames, resolution,side_length=size_size)
187 | #save_square_texture(square_texture, "./result/original.png")
188 |
189 | return square_texture
190 |
191 | def generate_squares_to_folder (video_path, fps, batch_size,resolution,size_size,max_frames,output_folder,border,ebsynth_mode,max_frames_to_save):
192 | fps = int(fps)
193 | if ebsynth_mode == False:
194 | if border >= (batch_size * size_size * size_size) / 2:
195 | raise Exception("too many border frames, reduce border or increase batch size")
196 |
197 |
198 | input_folder_loc = os.path.join(output_folder, "input")
199 | output_folder_loc = os.path.join(output_folder, "output")
200 | debug_result = os.path.join(output_folder, "result")
201 | if not os.path.exists(output_folder):
202 | os.makedirs(output_folder)
203 | if not os.path.exists(input_folder_loc):
204 | os.makedirs(input_folder_loc)
205 | if not os.path.exists(output_folder_loc):
206 | os.makedirs(output_folder_loc)
207 | if not os.path.exists(debug_result):
208 | os.makedirs(debug_result)
209 | frames_loc = os.path.join(output_folder, "frames")
210 | keys_loc = os.path.join(output_folder, "keys")
211 |
212 | if ebsynth_mode == True:
213 | if not os.path.exists(frames_loc):
214 | os.makedirs(frames_loc)
215 | if not os.path.exists(keys_loc):
216 | os.makedirs(keys_loc)
217 |
218 | video_data = convert_video_to_bytes(video_path)
219 | per_batch_limmit = ((size_size * size_size) * batch_size) + border
220 | #if ebsynth_mode == False:
221 | # per_batch_limmit = per_batch_limmit + border
222 | frames = utilityb.extract_frames_movpie(video_data, fps, max_frames,False)
223 |
224 | bigbatches = split_frames_into_big_batches(frames, per_batch_limmit,border,ebsynth=ebsynth_mode)
225 | square_textures = []
226 | height = 0
227 | width = 0
228 | for i in range(len(bigbatches)):
229 | batches = split_into_batches(bigbatches[i], batch_size, size_size * size_size)
230 | print("Number of batches:", len(batches))
231 | if ebsynth_mode == False:
232 | keyframes = [batch[0] for batch in batches]
233 | else:
234 | keyframes = [batch[int(len(batch)/2)] for batch in batches]
235 | #for batch in batches:
236 | #print (f"framenum = {int(len(batch)/2)} out of batch length {len(batch)} and size {len(frames)}")
237 | square_texture = create_square_texture(keyframes, resolution,side_length=size_size)
238 | save_square_texture(square_texture, os.path.join(input_folder_loc, f"input{i}.png"))
239 | square_textures.append(square_texture)
240 | height = square_texture.shape[0]
241 | width = square_texture.shape[1]
242 |
243 | batch_settings_loc = os.path.join(output_folder, "batch_settings.txt")
244 | with open(batch_settings_loc, "w") as f:
245 | f.write(str(fps) + "\n")
246 | f.write(str(size_size) + "\n")
247 | f.write(str(batch_size) + "\n")
248 | f.write(str(video_path) + "\n")
249 | f.write(str(max_frames_to_save) + "\n")
250 | f.write(str(border) + "\n")
251 | #return list of urls
252 |
253 |
254 |
255 | return square_textures
256 |
257 |
258 |
259 | def merge_image_batches(image_batches, border):
260 | merged_batches = []
261 | height, width = image_batches[0][0].shape[:2]
262 |
263 | for i in range(len(image_batches) - 1):
264 | current_batch = image_batches[i]
265 | next_batch = image_batches[i + 1]
266 | for i in range(len(current_batch)):
267 | current_batch[i] = cv2.resize(current_batch[i], (width, height))
268 | for i in range(len(next_batch)):
269 | next_batch[i] = cv2.resize(next_batch[i], (width, height))
270 |
271 | # If it's not the first batch, remove the blended images from the current batch
272 | if i > 0:
273 | current_batch = current_batch[border:]
274 |
275 | # Copy all images except the border ones from the current batch
276 | for j in range(len(current_batch) - border):
277 | merged_batches.append(current_batch[j])
278 |
279 | # Blend the border images between the current and next batch
280 | for j in range(border):
281 | try:
282 | alpha = float(j) / float(border)
283 | blended_image = cv2.addWeighted(current_batch[len(current_batch) - border + j], 1 - alpha, next_batch[j], alpha, 0)
284 | merged_batches.append(blended_image)
285 | except IndexError:
286 | print ("merge failed")
287 |
288 | # Add remaining images from the last batch
289 | merged_batches.extend(image_batches[-1][border:])
290 |
291 | return merged_batches
292 |
293 | def process_video_batch (video_path_old, fps, per_side, batch_size, fillindenoise, edgedenoise, _smol_resolution,square_textures,max_frames,output_folder,border):
294 | video_path = os.path.join (output_folder, "input_video.mp4")
295 | per_batch_limmit = (((per_side * per_side) * batch_size)) + border
296 | video_data = convert_video_to_bytes(video_path)
297 | frames = utilityb.extract_frames_movpie(video_data, fps, max_frames)
298 | print(f"splitting into batches with per_batch_limmit = {per_batch_limmit} and border {border}" )
299 | bigbatches = split_frames_into_big_batches(frames, per_batch_limmit,border,ebsynth=False)
300 | bigprocessedbatches = []
301 | for i , batch in enumerate(bigbatches):
302 | if i < len(square_textures):
303 | new_batch = process_video(batch, per_side, batch_size, fillindenoise, edgedenoise, _smol_resolution,square_textures[i])
304 | bigprocessedbatches.append(new_batch)
305 | for a, image in enumerate(new_batch):
306 | Image.fromarray(image).save(os.path.join(output_folder, f"result/output{a + (len(new_batch) * i)}.png"))
307 |
308 | just_frame_groups = []
309 | print (f"bigprocessedbatches len = {len(bigprocessedbatches)}")
310 | for i in range(len(bigprocessedbatches)):
311 | newgroup = []
312 | for b in range(len(bigprocessedbatches[i])):
313 | newgroup.append(bigprocessedbatches[i][b])
314 | just_frame_groups.append(newgroup)
315 |
316 | combined = merge_image_batches(just_frame_groups, border)
317 |
318 | save_loc = os.path.join(output_folder, "blended.mp4")
319 | generated_vid = utilityb.pil_images_to_video(combined,save_loc, fps)
320 | return generated_vid
321 |
322 |
323 | def process_video_single(video_path, fps, per_side, batch_size, fillindenoise, edgedenoise, _smol_resolution,square_texture):
324 |
325 | extension_path = os.path.abspath(__file__)
326 | extension_dir = os.path.dirname(os.path.dirname(extension_path))
327 | output_folder = os.path.join(extension_dir, "result")
328 | extension_path = os.path.abspath(__file__)
329 | frames_limit = (per_side * per_side) * batch_size
330 | extension_dir = os.path.dirname(os.path.dirname(extension_path))
331 | extension_save_folder = os.path.join(extension_dir, "result")
332 | if not os.path.exists(extension_save_folder):
333 | os.makedirs(extension_save_folder)
334 | utilityb.delete_folder_contents(extension_save_folder)
335 | #rerun the generatesquarefromvideo function to get the unaltered square texture
336 | video_data = convert_video_to_bytes(video_path)
337 | frames = utilityb.extract_frames_movpie(video_data, fps, frames_limit)
338 | processed_frames = process_video(frames,per_side,batch_size,fillindenoise,edgedenoise,_smol_resolution,square_texture)
339 | output_video_path = os.path.join(output_folder, "output.mp4")
340 | generated_video = utilityb.pil_images_to_video(processed_frames, output_video_path, fps)
341 | return generated_video
342 |
343 |
344 | def process_video(frames, per_side, batch_size, fillindenoise, edgedenoise, _smol_resolution,square_texture):
345 |
346 | frame_count = 0
347 | print(len(frames))
348 | batches = split_into_batches(frames, batch_size, per_side * per_side)
349 | print("Number of batches:", len(batches))
350 | first_frames = [batch[0] for batch in batches]
351 | #actuallyprocessthevideo
352 | debug = False
353 |
354 | frame_count = 0
355 | global resolution
356 | print(len(frames))
357 |
358 |
359 | if debug is False:
360 | #result_texture = sdprocess.square_Image_request(encoded_square_texture, prompt, initial_denoise, resolution, seed)
361 | result_texture = square_texture
362 | #save_square_texture(encoded_returns, "./result/processed.png")
363 |
364 | else:
365 | f = open("./result/processed.png", "rb")
366 | bytes = f.read()
367 | result_texture = base64.b64encode(bytes).decode("utf-8")
368 | resolution_get = Image.open("./result/processed.png")
369 | resolution= resolution_get.height
370 | # this is stupid and inefficiant i dont care
371 | #its not really encoded anymore is it
372 | encoded_returns = result_texture
373 | #encoded_returns = cv2.cvtColor(utilityb.base64_to_texture(result_texture), cv2.COLOR_BGR2RGB)
374 |
375 | new_frames = split_square_texture(encoded_returns,len(first_frames), per_side * per_side,_smol_resolution,False)
376 |
377 | if check_edges:
378 | for i, image in enumerate(new_frames):
379 | image = utilityb.check_edges(image)
380 | #:(
381 |
382 | # Save first frames
383 | #for idx, first_frame in enumerate(first_frames):
384 | # save_square_texture(first_frame, os.path.join(output_folder, f"first_frame_{idx}.png"))
385 | # save_square_texture(new_frames[idx], os.path.join(output_folder, f"first_frame_processed_{idx}.png"))
386 | """
387 | Turns out merging each frame backwards and forwards doesn't actually work, you'd think it did because each frame is conceptually closer to it's origin, but it breaks the flowmap in all sorts of weird ways if you tell it to go backwards, very very annoying
388 | last_processed = None
389 | for i, batch in enumerate(batches):
390 |
391 | encoded_batch = []
392 | for b, image in enumerate(batch):
393 | encoded_batch.append(utilityb.texture_to_base64(image))
394 | encoded_new_frame = utilityb.texture_to_base64(new_frames[i])
395 |
396 | processed_batch_before,all_flow_before = sdprocess.batch_sd_run(encoded_batch, encoded_new_frame, frame_count, seed, False, fillindenoise, edgedenoise, _smol_resolution,False,encoded_new_frame,False)
397 |
398 | if i < len(batches) - 1:
399 |
400 | encoded_batch_next = []
401 | for b, image in enumerate(batches[i+1]):
402 | encoded_batch_next.append(utilityb.texture_to_base64(image))
403 | encoded_ext_frame = utilityb.texture_to_base64(new_frames[i + 1])
404 | encoded_batch.insert(0,utilityb.texture_to_base64(first_frames[i]))
405 | processed_batch_after,all_flow_after = sdprocess.batch_sd_run(encoded_batch_next, encoded_new_frame, frame_count, seed, True, fillindenoise, edgedenoise, _smol_resolution,True,encoded_new_frame,False)
406 | processed_batch_after.append(encoded_ext_frame)
407 |
408 | if last_processed is not None:
409 | print (len(last_processed))
410 | print (len(processed_batch_before))
411 | blended_frames = blend_batches(last_processed, processed_batch_before, resolution=_smol_resolution)
412 | for b, blended_frame in enumerate(blended_frames):
413 | savepath = os.path.join(output_folder, f"frame_{frame_count + b}.png")
414 | #save_square_texture(blended_frame, savepath)
415 | save_square_texture(cv2.cvtColor(utilityb.base64_to_texture(processed_batch_before[b]), cv2.COLOR_BGR2RGB), savepath)
416 |
417 |
418 |
419 | #save_square_texture(cv2.cvtColor(utilityb.base64_to_texture(last_processed[b]), cv2.COLOR_BGR2RGB), f"./debug/before_{frame_count + b}.png")
420 | #save_square_texture(cv2.cvtColor(utilityb.base64_to_texture(processed_batch_before[b]), cv2.COLOR_BGR2RGB), f"./debug/after_{frame_count + b}.png")
421 | #for c, flow in enumerate(all_flow_before):
422 | #write_jpeg(flow, f"./debug/before_flow_{frame_count + c + 1}.png")
423 | else:
424 | for b, frame in enumerate(processed_batch_before):
425 | savepath = os.path.join(output_folder, f"frame_{frame_count + b}.png")
426 | save_square_texture(cv2.cvtColor(utilityb.base64_to_texture(frame), cv2.COLOR_BGR2RGB), savepath)
427 |
428 |
429 | frame_count += len(batch)
430 | last_processed = processed_batch_after
431 |
432 |
433 |
434 |
435 | """
436 |
437 | output_pil_images = []
438 | last_processed = None
439 | for i, batch in enumerate(batches):
440 |
441 | encoded_new_frame = utilityb.texture_to_base64(new_frames[i])
442 |
443 |
444 | encoded_batch = []
445 | for b, image in enumerate(batches[i]):
446 | encoded_batch.append(utilityb.texture_to_base64(image))
447 |
448 | processed_batch,all_flow_after = sdprocess.batch_sd_run(encoded_batch, encoded_new_frame, frame_count, seed, False, fillindenoise, edgedenoise, _smol_resolution,True,encoded_new_frame,False)
449 | print (f"number {i} processed batch length {len(processed_batch)} and batch length {len(batch)} and num batches {len(batches)}")
450 | if last_processed is not None:
451 | encoded_batch.insert(0,utilityb.texture_to_base64(batches[i - 1][-1]))
452 | processed_batch_from_before,all_flow_after = sdprocess.batch_sd_run(encoded_batch, last_processed, frame_count, seed, True, fillindenoise, edgedenoise, _smol_resolution,True,last_processed,False)
453 | if not min(len (processed_batch_from_before),len(processed_batch)) > 1:
454 | output_pil_images.append(cv2.cvtColor(utilityb.base64_to_texture(processed_batch[0]), cv2.COLOR_BGR2RGB))
455 | continue
456 | blended_frames = blend_batches(processed_batch_from_before, processed_batch, resolution=_smol_resolution)
457 | print (f"blended frames {len(blended_frames)}")
458 | for b, blended_frame in enumerate(blended_frames):
459 | #savepath = os.path.join(output_folder, f"frame_{frame_count + b}.png")
460 | #save_square_texture(blended_frame, savepath)
461 | output_pil_images.append(blended_frame)
462 | else:
463 | for b, frame in enumerate(processed_batch):
464 | #savepath = os.path.join(output_folder, f"frame_{frame_count + b}.png")
465 | #save_square_texture(cv2.cvtColor(utilityb.base64_to_texture(frame), cv2.COLOR_BGR2RGB), savepath)
466 | output_pil_images.append(cv2.cvtColor(utilityb.base64_to_texture(frame), cv2.COLOR_BGR2RGB))
467 |
468 |
469 | frame_count += len(batch)
470 | last_processed = processed_batch[-1]
471 | print (f"output pil images {len(output_pil_images)}")
472 | return output_pil_images
473 |
474 |
475 | def image_folder_to_video(folder_path, output_file, fps=24):
476 | """
477 | Turns a folder of images into a video using MoviePy.
478 |
479 | :param folder_path: str, path to the folder containing the images
480 | :param output_file: str, path to the output video file (e.g., 'output.mp4')
481 | :param fps: int, frames per second (default: 24)
482 | """
483 | # Get a list of image file names
484 | image_files = [f for f in os.listdir(folder_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif'))]
485 |
486 | # Sort image files by their names
487 | image_files.sort(key=lambda x: int(re.search(r'\d+', x).group()))
488 |
489 | # Create a list of full image file paths
490 | image_paths = [os.path.join(folder_path, image) for image in image_files]
491 |
492 | # Create a clip from the image sequence
493 | clip = ImageSequenceClip(image_paths, fps=fps)
494 |
495 | # Write the clip to a video file
496 | clip.write_videofile(output_file, codec='libx264')
497 |
498 | return output_file
499 |
500 |
501 |
502 |
503 |
504 | def blend_batches(batch_before, current_batch,resolution, blend_start_ratio=0.9, blend_end_ratio=0.1):
505 | blended_frames = []
506 | num_frames = min(len (batch_before),len(current_batch))
507 | decoded_batch_before = [cv2.cvtColor(utilityb.base64_to_texture(frame), cv2.COLOR_BGR2RGB) for frame in batch_before]
508 | decoded_current_batch = [cv2.cvtColor(utilityb.base64_to_texture(frame), cv2.COLOR_BGR2RGB) for frame in current_batch]
509 |
510 | #target_width, target_height = resolution, resolution
511 | height, width = decoded_batch_before[0].shape[:2]
512 | # Resize the images in decoded_batch_before and decoded_current_batch
513 | decoded_batch_before = [cv2.resize(img, (width,height)) for img in decoded_batch_before]
514 | decoded_current_batch = [cv2.resize(img, (width,height)) for img in decoded_current_batch]
515 |
516 | output_folder = "moretemp"
517 | if not os.path.exists(output_folder):
518 | os.makedirs(output_folder)
519 |
520 | if not num_frames > 1:
521 | return [current_batch[0]]
522 | for i in range(num_frames):
523 | alpha = blend_start_ratio - (i / (num_frames - 1)) * (blend_start_ratio - blend_end_ratio)
524 | blended_frame = cv2.addWeighted(decoded_batch_before[i], alpha, decoded_current_batch[i], 1 - alpha, 0)
525 | print(f"blended frame {i}")
526 |
527 | # Concatenate the two input frames and the blended frame horizontally
528 | concatenated_frame = cv2.hconcat([decoded_batch_before[i], decoded_current_batch[i], blended_frame])
529 |
530 | cv2.imwrite(os.path.join(output_folder, f"concatenated_{i}.png"), concatenated_frame)
531 |
532 | blended_frames.append(blended_frame)
533 | return blended_frames
534 |
535 |
536 |
537 | def interpolate_frames(frame1, frame2, alpha):
538 | gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
539 | gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
540 |
541 | flow = cv2.calcOpticalFlowFarneback(gray1, gray2, None, pyr_scale=0.5, levels=3, winsize=15, iterations=3, poly_n=5, poly_sigma=1.2, flags=0)
542 | h, w = flow.shape[:2]
543 |
544 | flow_map = -alpha * flow + np.indices((h, w)).transpose(1, 2, 0)
545 | flow_map = flow_map.astype(np.float32) # Convert flow_map to float32 data type
546 | return cv2.remap(frame1, flow_map, None, cv2.INTER_LINEAR)
547 |
548 | def interpolate_video(input_path, output_path, output_fps):
549 | clip = VideoFileClip(input_path)
550 | input_fps = clip.fps
551 |
552 | frames = [frame for frame in clip.iter_frames()]
553 | new_frames = []
554 |
555 | if output_fps <= input_fps:
556 | raise ValueError("Output fps should be greater than input fps")
557 |
558 | frame_ratio = input_fps / output_fps
559 |
560 | for i in range(len(frames) - 1):
561 | new_frames.append(frames[i])
562 | print(f"interpolating for frame {i}")
563 | extra_frames = int(round((i + 1) / frame_ratio) - round(i / frame_ratio))
564 | for j in range(1, extra_frames + 1):
565 |
566 | alpha = j / (extra_frames + 1)
567 | frame1 = frames[i] # Transpose the dimensions of frame1 (HxWxC to WxHxC)
568 | frame2 = frames[i + 1] # Transpose the dimensions of frame2 (HxWxC to WxHxC)
569 | interpolated_frame = interpolate_frames(frame1, frame2, alpha)
570 | interpolated_frame = interpolated_frame.transpose(1, 0, 2) # Transpose back the dimensions of interpolated_frame (WxHxC to HxWxC)
571 | new_frames.append(interpolated_frame)
572 |
573 | new_frames.append(frames[-1])
574 |
575 | new_clip = ImageSequenceClip(new_frames, fps=output_fps)
576 | new_clip.write_videofile(output_path)
577 | return output_path
578 |
579 |
580 | def split_videos_into_smaller_videos(max_keys,video,fps,max_frames,target_path,border_number, scenecuts = False):
581 | max_total_frames = int((max_keys / 20) * max_frames)
582 | split_frames,border_indices = divideFrames(video, max_frames,border_number)
583 | split_frames_trimmed,trimmed_borders = trim_images(split_frames,max_total_frames,border_indices )
584 | print(f" trim_imagestransitions {border_indices}")
585 | output_files = []
586 | print(f"frames_total_size = {len(split_frames_trimmed)}, frames batch size = {max_frames} array length = {len(split_frames_trimmed)}")
587 |
588 | for i,frames in enumerate(split_frames_trimmed):
589 | print (f"splitting video {i}")
590 | new_folder_location = os.path.join(target_path, f"{i}")
591 | if not os.path.exists(new_folder_location):
592 | os.makedirs(new_folder_location)
593 | new_video_loc = os.path.join(new_folder_location, f"input_video.mp4")
594 | output_files.append(utilityb.pil_images_to_video(frames, new_video_loc, fps))
595 | return output_files,trimmed_borders
596 |
597 |
598 | def divideFrames(frame_groups, x, y):
599 | result = []
600 | transitions = []
601 |
602 | for index, group in enumerate(frame_groups):
603 | print (f"frame_groups {len(group)}")
604 | start = 0
605 | while start < len(group):
606 | end = start + x
607 | new_group = group[start:end]
608 |
609 | if end + y <= len(group):
610 | overlap_group = group[end:end+y]
611 |
612 |
613 | # Concatenate the images from new_group and overlap_group
614 | if y > 0:
615 | combined_group = np.concatenate((new_group, overlap_group), axis=0)
616 | else:
617 | combined_group = new_group
618 | print (f"overlap group size {len(overlap_group)}")
619 | transitions.append(len(result))
620 |
621 | else:
622 | combined_group = new_group
623 |
624 | result.append(combined_group)
625 | start += x
626 |
627 | return result,transitions
628 |
629 |
630 | def trim_images(images_list_of_lists, max_images, border_indices):
631 | """
632 | Trims the given list of lists of image arrays so that the total number of image arrays is below the specified maximum.
633 | Removes whole image arrays from the end of the list of lists if the max_images doesn't include them.
634 |
635 | Parameters:
636 | images_list_of_lists (list): List of lists of NumPy image arrays
637 | max_images (int): Maximum number of image arrays allowed
638 |
639 | Returns:
640 | list: List of lists of trimmed image arrays
641 | """
642 | total_images = sum([len(img_list) for img_list in images_list_of_lists])
643 |
644 | while total_images > max_images:
645 | print(f"total_images = {total_images}, max_images = {max_images}")
646 | last_list_idx = len(images_list_of_lists) - 1
647 | last_img_idx = len(images_list_of_lists[last_list_idx]) - 1
648 |
649 | if last_img_idx >= 0:
650 | total_images -= 1
651 | images_list_of_lists[last_list_idx] = images_list_of_lists[last_list_idx][:-1]
652 |
653 | if len(images_list_of_lists[last_list_idx]) == 0:
654 | images_list_of_lists.pop()
655 | if last_list_idx in border_indices:
656 | border_indices.pop()
657 |
658 | return images_list_of_lists, border_indices
659 |
--------------------------------------------------------------------------------
/scripts/Ebsynth_Processing.py:
--------------------------------------------------------------------------------
1 | import os
2 | import glob
3 | #om nom nom nom
4 | import requests
5 | import json
6 | from pprint import pprint
7 | import base64
8 | import numpy as np
9 | from io import BytesIO
10 | import extensions.TemporalKit.scripts.berry_utility
11 | import scripts.optical_flow_simple as opflow
12 | from PIL import Image, ImageOps,ImageFilter
13 | import io
14 | from collections import deque
15 | import cv2
16 | import scripts.Berry_Method as bmethod
17 | import scripts.berry_utility as butility
18 | import re
19 |
20 |
21 |
22 | def sort_into_folders(video_path, fps, per_side, batch_size, _smol_resolution,square_textures,max_frames,output_folder,border):
23 | border = 0
24 | per_batch_limmit = (((per_side * per_side) * batch_size)) + border
25 |
26 | frames = []
27 | # original_frames_directory = os.path.join(output_folder, "original_frames")
28 | # if os.path.exists(original_frames_directory):
29 | # for filename in os.listdir(original_frames_directory):
30 | # frames.append(cv2.imread(os.path.join(original_frames_directory, filename), cv2.COLOR_BGR2RGB))
31 | # else:
32 | video_data = bmethod.convert_video_to_bytes(video_path)
33 | frames = butility.extract_frames_movpie(video_data, fps, max_frames)
34 |
35 | print(f"full frames num = {len(frames)}")
36 |
37 |
38 | output_frames_folder = os.path.join(output_folder, "frames")
39 | if not os.path.exists(output_frames_folder):
40 | os.makedirs(output_frames_folder)
41 | output_keys_folder = os.path.join(output_folder, "keys")
42 | if not os.path.exists(output_keys_folder):
43 | os.makedirs(output_keys_folder)
44 | input_folder = os.path.join(output_folder, "input")
45 |
46 | filenames = os.listdir(input_folder)
47 | img = Image.open(os.path.join(input_folder, filenames[0]))
48 | original_width, original_height = img.size
49 | height,width = frames[0].shape[:2]
50 |
51 | texture_aspect_ratio = float(width) / float(height)
52 |
53 |
54 | _smol_frame_height = _smol_resolution
55 | _smol_frame_width = int(_smol_frame_height * texture_aspect_ratio)
56 | print(f"saving size = {_smol_frame_width}x{_smol_frame_height}")
57 |
58 |
59 | for i, frame in enumerate(frames):
60 | frame_to_save = cv2.resize(frame, (_smol_frame_width, _smol_frame_height), interpolation=cv2.INTER_LINEAR)
61 | bmethod.save_square_texture(frame_to_save, os.path.join(output_frames_folder, "frames{:05d}.png".format(i)))
62 | original_frame_height,original_frame_width = frames[0].shape[:2]
63 |
64 |
65 |
66 | bigbatches,frameLocs = bmethod.split_frames_into_big_batches(frames, per_batch_limmit,border,ebsynth=True,returnframe_locations=True)
67 | bigprocessedbatches = []
68 |
69 | last_frame_end = 0
70 | print (len(square_textures))
71 | for a,bigbatch in enumerate(bigbatches):
72 | batches = bmethod.split_into_batches(bigbatches[a], batch_size,per_side* per_side)
73 |
74 | keyframes = [batch[int(len(batch)/2)] for batch in batches]
75 | if a < len(square_textures):
76 | resized_square_texture = cv2.resize(square_textures[a], (original_width, original_height), interpolation=cv2.INTER_LINEAR)
77 | new_frames = bmethod.split_square_texture(resized_square_texture,len(keyframes), per_side* per_side,_smol_resolution,True)
78 | new_frame_start,new_frame_end = frameLocs[a]
79 |
80 | for b in range(len(new_frames)):
81 | print (new_frame_start)
82 | inner_start = last_frame_end
83 | inner_end = inner_start + len(batches[b])
84 | last_frame_end = inner_end
85 | frame_position = inner_start + int((inner_end - inner_start)/2)
86 | print (f"saving at frame {frame_position}")
87 | frame_to_save = cv2.resize(new_frames[b], (_smol_frame_width, _smol_frame_height), interpolation=cv2.INTER_LINEAR)
88 | bmethod.save_square_texture(frame_to_save, os.path.join(output_keys_folder, "keys{:05d}.png".format(frame_position)))
89 |
90 | just_frame_groups = []
91 | for i in range(len(bigprocessedbatches)):
92 | newgroup = []
93 | for b in range(len(bigprocessedbatches[i])):
94 | newgroup.append(bigprocessedbatches[i][b])
95 | just_frame_groups.append(newgroup)
96 |
97 | return
98 |
99 |
100 | def recombine (video_path, fps, per_side, batch_size, fillindenoise, edgedenoise, _smol_resolution,square_textures,max_frames,output_folder,border):
101 | just_frame_groups = []
102 | per_batch_limmit = (((per_side * per_side) * batch_size)) - border
103 | video_data = bmethod.convert_video_to_bytes(video_path)
104 | frames = bmethod.extract_frames_movpie(video_data, fps, max_frames)
105 | bigbatches,frameLocs = bmethod.split_frames_into_big_batches(frames, per_batch_limmit,border,returnframe_locations=True)
106 | bigprocessedbatches = []
107 | for i in range(len(bigprocessedbatches)):
108 | newgroup = []
109 | for b in range(len(bigprocessedbatches[i])):
110 | newgroup.append(bigprocessedbatches[i][b])
111 | just_frame_groups.append(newgroup)
112 |
113 | combined = bmethod.merge_image_batches(just_frame_groups, border)
114 |
115 | save_loc = os.path.join(output_folder, "non_blended.mp4")
116 | generated_vid = extensions.TemporalKit.scripts.berry_utility.pil_images_to_video(combined,save_loc, fps)
117 |
118 |
119 |
120 |
121 | def crossfade_folder_of_folders(output_folder, fps,return_generated_video_path=False):
122 | """Crossfade between images in a folder of folders and save the results."""
123 | root_folder = output_folder
124 | all_dirs = [d for d in os.listdir(root_folder) if os.path.isdir(os.path.join(root_folder, d))]
125 | dirs = [d for d in all_dirs if d.startswith("out_")]
126 |
127 | dirs.sort()
128 |
129 | output_images = []
130 | allkeynums = getkeynums(os.path.join(root_folder, "keys"))
131 | print(allkeynums)
132 |
133 | for b in range(allkeynums[0]):
134 | current_dir = os.path.join(root_folder, dirs[0])
135 | images_current = sorted(os.listdir(current_dir))
136 | image1_path = os.path.join(current_dir, images_current[b])
137 | image1 = Image.open(image1_path)
138 | output_images.append(np.array(image1))
139 |
140 | for i in range(len(dirs) - 1):
141 | current_dir = os.path.join(root_folder, dirs[i])
142 | next_dir = os.path.join(root_folder, dirs[i + 1])
143 |
144 | images_current = sorted(os.listdir(current_dir))
145 | images_next = sorted(os.listdir(next_dir))
146 |
147 | startnum = get_num_at_index(current_dir,0)
148 | bigkeynum = allkeynums[i]
149 | keynum = bigkeynum - startnum
150 | print(f"recombining directory {dirs[i]} and {dirs[i+1]}, len {keynum}")
151 |
152 |
153 |
154 |
155 | for j in range(keynum, len(images_current) - 1):
156 | alpha = (j - keynum) / (len(images_current) - keynum)
157 | image1_path = os.path.join(current_dir, images_current[j])
158 | next_image_index = j - keynum if j - keynum < len(images_next) else len(images_next) - 1
159 | image2_path = os.path.join(next_dir, images_next[next_image_index])
160 |
161 | image1 = Image.open(image1_path)
162 | image2 = Image.open(image2_path)
163 |
164 | blended_image = butility.crossfade_images(image1, image2, alpha)
165 | output_images.append(np.array(blended_image))
166 | # blended_image.save(os.path.join(output_folder, f"{dirs[i]}_{dirs[i+1]}_crossfade_{j:04}.png"))
167 |
168 | final_dir = os.path.join(root_folder, dirs[-1])
169 | final_dir_images = sorted(os.listdir(final_dir))
170 |
171 | # Find the index of the image with the last keyframe number in its name
172 | last_keyframe_number = allkeynums[-1]
173 | last_keyframe_index = None
174 | for index, image_name in enumerate(final_dir_images):
175 | number_in_name = int(''.join(filter(str.isdigit, image_name)))
176 | if number_in_name == last_keyframe_number:
177 | last_keyframe_index = index
178 | break
179 |
180 | if last_keyframe_index is not None:
181 | print(f"going from dir {last_keyframe_number} to end at {len(final_dir_images)}")
182 |
183 | # Iterate from the last keyframe number to the end
184 | for c in range(last_keyframe_index, len(final_dir_images)):
185 | image1_path = os.path.join(final_dir, final_dir_images[c])
186 | image1 = Image.open(image1_path)
187 | output_images.append(np.array(image1))
188 | else:
189 | print("Last keyframe not found in the final directory")
190 |
191 |
192 | print (f"outputting {len(output_images)} images")
193 | output_save_location = os.path.join(output_folder, "crossfade.mp4")
194 | generated_vid = extensions.TemporalKit.scripts.berry_utility.pil_images_to_video(output_images, output_save_location, fps)
195 |
196 | if return_generated_video_path == True:
197 | return generated_vid
198 | else:
199 | return output_images
200 |
201 | def getkeynums (folder_path):
202 | filenames = os.listdir(folder_path)
203 |
204 | # Filter filenames to keep only the ones starting with "keys" and ending with ".png"
205 | keys_filenames = [f for f in filenames if f.startswith("keys") and f.endswith(".png")]
206 |
207 | # Sort the filtered filenames
208 | sorted_keys_filenames = sorted(keys_filenames, key=lambda f: int(re.search(r'(\d+)', f).group(0)))
209 |
210 | # Extract the numbers from the sorted filenames
211 | return [int(re.search(r'(\d+)', f).group(0)) for f in sorted_keys_filenames]
212 |
213 |
214 | def get_num_at_index(folder_path,index):
215 | """Get the starting number of the output images in a folder."""
216 | filenames = os.listdir(folder_path)
217 |
218 | # Filter filenames to keep only the ones starting with "keys" and ending with ".png"
219 | #keys_filenames = [f for f in filenames if f.startswith("keys") and f.endswith(".png")]
220 |
221 | # Sort the filtered filenames
222 | sorted_keys_filenames = sorted(filenames, key=lambda f: int(re.search(r'(\d+)', f).group(0)))
223 |
224 | # Extract the numbers from the sorted filenames
225 | numbers = [int(re.search(r'(\d+)', f).group(0)) for f in sorted_keys_filenames]
226 | return numbers[index]
--------------------------------------------------------------------------------
/scripts/TemporalKitImg2ImgTab.py:
--------------------------------------------------------------------------------
1 | import gradio as gr
2 | from einops import rearrange
3 | from omegaconf import OmegaConf
4 | from PIL import Image, ImageOps
5 | from torch import autocast
6 | import modules.scripts as scripts
7 | import gradio as gr
8 | from modules import processing, images, shared, sd_samplers, devices
9 | import modules.generation_parameters_copypaste as parameters_copypaste
10 | import modules.images as images
11 | import os
12 | import glob
13 | lastimage = None
14 |
15 | def save_image(image, filename, directory):
16 | os.makedirs(directory, exist_ok=True)
17 |
18 | # create the full file path by joining the directory and filename
19 | file_path = os.path.join(directory, filename)
20 |
21 | # save the image to the specified file path
22 | image.save(file_path)
23 |
24 | def on_button_click():
25 | global lastimage
26 | extension_path = os.path.abspath(__file__)
27 | extension_dir = os.path.dirname(os.path.dirname(extension_path))
28 | extension_folder = os.path.join(extension_dir,"squares")
29 |
30 | # save the image to the parent directory with a new filename
31 | save_image(lastimage, 'last.png', extension_folder)
32 |
33 |
34 | class Script(scripts.Script):
35 | global button
36 | def title(self):
37 | return "TemporalKit"
38 |
39 | def show(self, is_img2img):
40 | if is_img2img:
41 | return True
42 | return True
43 |
44 |
45 | def ui(self, is_img2img):
46 | global lastimage
47 | savebutton = gr.Button("save", label="Save")
48 | savebutton.click(
49 | fn=on_button_click,
50 | )
51 | movebutton = gr.Button("move", label="Move")
52 | movebutton.click(
53 | fn=None,
54 | _js="switch_to_temporal_kit",
55 | )
56 |
57 |
58 | def run(self, p):
59 | global lastimage
60 | processed = processing.process_images(p)
61 | lastimage = processed.images[0]
62 | #registerbuttons(button)
63 | return processed
64 |
65 |
--------------------------------------------------------------------------------
/scripts/berry_utility.py:
--------------------------------------------------------------------------------
1 | import os
2 | import glob
3 | from moviepy.editor import *
4 | import tempfile
5 | #om nom nom nom
6 | import requests
7 | import json
8 | from pprint import pprint
9 | import base64
10 | import numpy as np
11 | from io import BytesIO
12 | import scripts.optical_flow_simple as opflow
13 | from PIL import Image, ImageOps,ImageFilter
14 | import io
15 | from collections import deque
16 | import cv2
17 | import copy
18 | import shutil
19 | import subprocess
20 | import scenedetect
21 |
22 | window_size = 5
23 |
24 | intensity_window = deque(maxlen=window_size)
25 |
26 | def calculate_intensity(flow_map,frame_count):
27 | global min_intensity, max_intensity
28 | intensity_map = np.sqrt(np.sum(flow_map**2, axis=2))
29 |
30 | intensity_window.append(intensity_map)
31 |
32 | min_intensity = min(im.min() for im in intensity_window)
33 | max_intensity = max(im.max() for im in intensity_window)
34 |
35 | normalized_intensity_map = (intensity_map - min_intensity) / (max_intensity - min_intensity)
36 |
37 | intensity_image = Image.fromarray((normalized_intensity_map * 255).astype(np.uint8))
38 | intensity_image.save(f'intensitymaps/intensity_map_{frame_count:04d}.png')
39 |
40 | return normalized_intensity_map
41 |
42 | def scale_mask_intensity(mask, intensity):
43 | scaled_mask = np.clip(mask * intensity, 0, 255).astype(np.uint8)
44 | return scaled_mask
45 |
46 | def mask_to_grayscale(mask):
47 | grayscale_mask = 0.2989 * mask[:, :, 0] + 0.5870 * mask[:, :, 1] + 0.1140 * mask[:, :, 2]
48 | return grayscale_mask
49 |
50 |
51 |
52 | def replace_masked_area(flow,index, base_image_path, mask_base64_str, replacement_image_path, threshold=128):
53 |
54 | #intensity = 0.2
55 |
56 | #intensity_map = calculate_intensity(flow)
57 |
58 |
59 | # Load images
60 | base_image = Image.open(base_image_path).convert("RGBA")
61 | #mask_image = Image.open(io.BytesIO(base64.b64decode(mask_base64_str))).convert("L")
62 | mask_image = mask_base64_str # its not base64 encoded anymore
63 | #replacement_tex_unmodified = base64_to_texture(replacement_image_path)
64 | #replacement_image = Image.fromarray(np.uint8(replacement_tex_unmodified)).convert("RGBA")
65 | replacement_image = Image.open(replacement_image_path).convert("RGBA")
66 | print(mask_image)
67 | print(mask_image.size)
68 |
69 | # Resize the mask image and replacement image to match the base image size
70 | base_width, base_height = base_image.size
71 | alpha_mask = np.array(mask_image)
72 |
73 | mask_image = alpha_mask.resize((base_width, base_height))
74 | replacement_image = replacement_image.resize((base_width, base_height))
75 |
76 | alpha_mask_intensity = (alpha_mask).astype(np.uint8)
77 | alpha_image = Image.fromarray(alpha_mask_intensity)
78 |
79 | blended_image = Image.composite(replacement_image, base_image, alpha_image)
80 | # print(alpha_mask_intensity.size)
81 | # print (f"image{intensity_map.size}")
82 |
83 | output_image_path = os.path.join("./debug3/", f"output_image_{index}.png")
84 | # Save the output image
85 | os.makedirs("./debug3/", exist_ok=True)
86 | blended_image.save(output_image_path)
87 |
88 |
89 | return output_image_path
90 | # return base_image_path
91 |
92 | #not in use rn
93 | def invert_base64_image(base64_str: str) -> str:
94 | # Decode the base64 string
95 | img_data = base64.b64decode(base64_str)
96 |
97 | # Convert the decoded data to a PIL Image object
98 | img = Image.open(io.BytesIO(img_data))
99 |
100 | # Invert the image colors
101 | inverted_img = ImageOps.invert(img)
102 |
103 | # Convert the inverted image back to a byte stream
104 | img_byte_arr = io.BytesIO()
105 | inverted_img.save(img_byte_arr, format='PNG')
106 | img_byte_arr = img_byte_arr.getvalue()
107 |
108 | # Encode the inverted image as a base64 string
109 | inverted_base64_str = base64.b64encode(img_byte_arr).decode('utf-8')
110 |
111 | return inverted_base64_str
112 |
113 | # hardens the mask
114 | def harden_mask(encoded_image,taper):
115 | decoded_image = base64.b64decode(encoded_image)
116 | image = Image.open(BytesIO(decoded_image)).convert("RGBA")
117 | new_image = image
118 | # Make every pixel not black solid white
119 | width, height = image.size
120 | for x in range(width):
121 | for y in range(height):
122 | r, g, b, a = image.getpixel((x, y))
123 | # if r != 0 or g != 0 or b != 0:
124 | # image.putpixel((x, y), (255, 255, 255, a))
125 | if r > 180 or g > 180 or b > 180:
126 | new_image.putpixel((x, y), (255, 255, 255, a))
127 |
128 | #Taper for 3 pixels around
129 | if taper == True:
130 | new_image = new_image.filter(ImageFilter.BoxBlur(9))
131 |
132 |
133 | for x in range(width):
134 | for y in range(height):
135 | r, g, b, a = image.getpixel((x, y))
136 | # if r != 0 or g != 0 or b != 0:
137 | # image.putpixel((x, y), (255, 255, 255, a))
138 | if r > 180 or g > 180 or b > 180:
139 | new_image.putpixel((x, y), (255, 255, 255, a))
140 |
141 |
142 | for x in range(width):
143 | for y in range(height):
144 | r, g, b, a = new_image.getpixel((x, y))
145 | # if r != 0 or g != 0 or b != 0:
146 | # image.putpixel((x, y), (255, 255, 255, a))
147 | if r < 128 or g < 128 or b < 128:
148 | new_image.putpixel((x, y), (r + 5, g + 5, b + 5,a))
149 |
150 | output_buffer = BytesIO()
151 | new_image.save(output_buffer, format="PNG")
152 | processed_image_base64 = base64.b64encode(output_buffer.getvalue()).decode()
153 | # combined = overlay_base64_images(encoded_image,processed_image_base64)
154 | return processed_image_base64
155 |
156 |
157 | def resize_base64_image(base64_str, new_width: int, new_height: int) -> str:
158 | # Decode the base64 string
159 | #img_data = base64.b64decode(base64_str)
160 | #img_data2 = Image.fromarray( base64_to_texture(base64_str))
161 | # Convert the decoded data to a PIL Image object
162 | #img = Image.open(io.BytesIO(img_data))
163 |
164 | # Resize the image
165 | #resized_img = img_data2.resize((new_width, new_height), Image.ANTIALIAS)
166 |
167 | #decoded_data = base64.b64decode(base64_str)
168 | with open(base64_str, "rb") as f:
169 | bytes = f.read()
170 |
171 | # Create a BytesIO object
172 | buffered_data = io.BytesIO(bytes)
173 |
174 | # Open the image from the BytesIO object
175 | image = Image.open(buffered_data)
176 | resized_img = image.resize((new_width, new_height), Image.ANTIALIAS)
177 |
178 | # Convert the resized image back to a byte stream
179 | img_byte_arr = io.BytesIO()
180 | resized_img.save(img_byte_arr, format='PNG')
181 | img_byte_arr = img_byte_arr.getvalue()
182 |
183 | # Encode the resized image as a base64 string
184 | resized_base64_str = base64.b64encode(img_byte_arr).decode('utf-8')
185 |
186 | return resized_base64_str
187 |
188 | def overlay_base64_images(encoded_image1, encoded_image2):
189 | decoded_image1 = base64.b64decode(encoded_image1)
190 | decoded_image2 = base64.b64decode(encoded_image2)
191 |
192 | image1 = Image.open(BytesIO(decoded_image1))
193 | image2 = Image.open(BytesIO(decoded_image2))
194 |
195 | # Overlay the images
196 | result = Image.blend(image1, image2,0.5)
197 |
198 | # Convert the overlaid image back to base64
199 | output_buffer = BytesIO()
200 | result.save(output_buffer, format="PNG")
201 | result_base64 = base64.b64encode(output_buffer.getvalue()).decode()
202 |
203 | return result_base64
204 |
205 | #get all images inthe server
206 | def get_image_paths(folder):
207 | image_extensions = ("*.jpg", "*.jpeg", "*.png", "*.bmp")
208 | files = []
209 | for ext in image_extensions:
210 | files.extend(glob.glob(os.path.join(folder, ext)))
211 | return sorted(files)
212 |
213 | # convert image to base64
214 | # is this really th best way to do this?
215 | def texture_to_base64(texture):
216 | # Convert the NumPy array to a PIL Image
217 | image = Image.fromarray(texture).convert("RGBA")
218 |
219 | # Save the image to an in-memory buffer
220 | buffer = BytesIO()
221 | image.save(buffer, format="PNG")
222 |
223 | # Get the byte data from the buffer and encode it as a base64 string
224 | img_base64 = base64.b64encode(buffer.getvalue()).decode()
225 |
226 | return img_base64
227 |
228 | # thanks to https://github.com/jinnsp ❤
229 | def base64_to_texture(base64_string):
230 | if base64_string.lower().endswith('png'):
231 | image = Image.open(base64_string)
232 | else:
233 | decoded_data = base64.b64decode(base64_string)
234 | buffer = BytesIO(decoded_data)
235 | image = Image.open(buffer)
236 | texture = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
237 | return texture
238 |
239 | def combine_masks(masks):
240 | """
241 | Combine three grayscale masks into one by overlaying them.
242 |
243 | Args:
244 | mask1 (np.ndarray): First grayscale mask with shape (height, width).
245 | mask2 (np.ndarray): Second grayscale mask with shape (height, width).
246 | mask3 (np.ndarray): Third grayscale mask with shape (height, width).
247 |
248 | Returns:
249 | np.ndarray: Combined grayscale mask with the same shape as the input masks.
250 | """
251 | combined_mask = np.maximum.reduce(masks)
252 | return combined_mask
253 |
254 | def create_hole_mask(flow_map):
255 | h, w, _ = flow_map.shape
256 | x_coords, y_coords = np.meshgrid(np.arange(w), np.arange(h))
257 |
258 | # Compute the new coordinates of each pixel after the optical flow is applied
259 | new_x_coords = np.clip(x_coords + flow_map[..., 0], 0, w - 1).astype(int)
260 | new_y_coords = np.clip(y_coords + flow_map[..., 1], 0, h - 1).astype(int)
261 |
262 | # Create a 2D array to keep track of whether a pixel is occupied or not
263 | occupied = np.zeros((h, w), dtype=bool)
264 |
265 | # Mark the pixels that are occupied after the optical flow is applied
266 | occupied[new_y_coords, new_x_coords] = True
267 |
268 | # Create the hole mask by marking unoccupied pixels as holes (value of 1)
269 | hole_mask = np.logical_not(occupied).astype(np.uint8)
270 |
271 |
272 |
273 | expanded = filter_mask(hole_mask) * 255
274 | #expanded = hole_mask * 255
275 | #blurred_hole_mask = box_(expanded, sigma=3)
276 | toblur = Image.fromarray(expanded).convert('L')
277 | blurred_hole_mask = np.array(toblur.filter(ImageFilter.GaussianBlur(3)))
278 |
279 | #blurred_numpy = np.array( Image.fromarray(expanded).filter(ImageFilter.GaussianBlur(3)))
280 | #blurred_hole_mask[blurred_hole_mask > 150] = 255
281 | filtered_smol = filter_mask(hole_mask,4,0.4,0.3) * 255
282 | return blurred_hole_mask + filtered_smol
283 |
284 | # there are pixels all over the place that are not holes, so this only gets the holes with a high concentration
285 | def filter_mask(mask, kernel_size=4, threshold_ratio=0.3,grayscale_intensity=1.0):
286 | # Create a custom kernel
287 | kernel = np.ones((kernel_size, kernel_size), np.uint8)
288 |
289 | # Convolve the mask with the kernel
290 | conv_result = cv2.filter2D(mask, -1, kernel)
291 |
292 | # Calculate the threshold based on the ratio
293 | threshold = int(kernel.size * threshold_ratio)
294 |
295 | # Filter the mask using the calculated threshold
296 | filtered_mask = np.where(conv_result >= threshold, mask, 0)
297 |
298 | # thanks to https://github.com/jinnsp ❤
299 | grayscale_mask = np.where(conv_result >= threshold, int(255 * grayscale_intensity), 0).astype(np.uint8)
300 |
301 | # Combine the filtered mask and grayscale mask
302 | combined_mask = np.maximum(filtered_mask, grayscale_mask)
303 |
304 |
305 | return combined_mask
306 |
307 |
308 | def resize_image(image, max_dimension_x, max_dimension_y):
309 | h, w = image.shape[:2]
310 | aspect_ratio = float(w) / float(h)
311 | if h > w:
312 | new_height = max_dimension_y
313 | new_width = int(new_height * aspect_ratio)
314 | else:
315 | new_width = max_dimension_x
316 | new_height = int(new_width / aspect_ratio)
317 | resized_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_LINEAR)
318 | return resized_image
319 |
320 | #delete this later
321 | def replaced_mask_from_other_direction_debug(index,image, mask, flowmap, original, output_folder1='./debug',forwards=True):
322 | # Ensure inputs are numpy arrays
323 | image = np.array(image)
324 | mask = np.array(mask)
325 |
326 | flowmap_detached = flowmap.detach().cpu().numpy()
327 | if original is not None:
328 | original = np.array(original)
329 | original = resize_image(original, image.shape[1], image.shape[0])
330 |
331 |
332 |
333 | # Get the height and width of the image
334 | height, width, _ = image.shape
335 |
336 | # Get the coordinates of the masked pixels
337 | masked_coords = np.argwhere(mask)
338 |
339 | # Initialize a new_image to store the result
340 | new_image = image.copy()
341 |
342 | # Initialize debug_image to store debug information
343 |
344 |
345 | for y, x in masked_coords:
346 | border_limit = 10
347 | # Skip if pixel is within 20 pixels of the border
348 | if border_limit <= y < height - border_limit and border_limit <= x < width - border_limit:
349 |
350 | # Get the opposite flow vector
351 | flow_vector = np.array([flowmap_detached[0, y, x], flowmap_detached[1, y, x]])
352 |
353 | # Calculate the new coordinates after applying the flow
354 | new_y = int(round(y - flow_vector[1] * 2))
355 | new_x = int(round(x - flow_vector[0] * 2))
356 |
357 | # Check if the new coordinates are inside the image bounds
358 | if 0 <= new_y < height and 0 <= new_x < width:
359 | # Replace the pixel in the new_image with the pixel from the opposite flow direction
360 | intensity = mask[y, x] / 255
361 | weight = gaussian_weight(intensity, sigma=0.5)
362 |
363 | # Replace the pixel in the new_image with the pixel from the opposite flow direction, weighted by the Gaussian weight
364 | #new_image[y, x] = weight * image[new_y, new_x] + (1 - weight) * image[y, x]
365 | #if original is not None and not is_similar_color(image[y, x], original[y, x],50):
366 | # weird edge case where if the background is moving and the foreground is not, the foreground will be replaced by the background
367 | ### new_image[y, x] = weight * image[y, x] + (1 - weight) * original[y, x]
368 | #else:
369 | new_image[y, x] = (1 - weight) * image[new_y, new_x] + weight * image[y, x]
370 |
371 |
372 | # Replace the pixel in the new_image with the pixel from the opposite flow direction, weighted by the intensity
373 | #new_image[y, x] = intensity * image[new_y, new_x] + (1 - intensity) * image[y, x]
374 | #new_image[y, x] = image[new_y, new_x]
375 | #new_image[y, x] = image[new_y, new_x] + (1 - intensity) * image[y, x]
376 | # Update debug_image
377 | #debug_image[y, x] = [0,0,255 * (1 - weight)] # Red color for the mask
378 | #debug_image[new_y, new_x] = [0, 255 * (1 - weight),0] # Green color for the moved pixel content
379 | #debug_image[y, x] = [0,0,255 * (1 - weight)] # Blue color for the moved pixel destination
380 |
381 |
382 | #output_folder = os.path.join(output_folder1, f'newmaskimg{index}.png')
383 | # Save the debug image to the specified folder
384 |
385 |
386 | #if original is not None:
387 | #debug_image_pil = Image.fromarray(debug_image)
388 | #debug_image_pil.save(output_folder)
389 |
390 | return texture_to_base64(new_image)
391 |
392 |
393 | def is_similar_color(pixel1, pixel2, threshold):
394 | """
395 | Returns True if pixel1 and pixel2 are similar in color within the given threshold, False otherwise.
396 | """
397 | r1, g1, b1,a1 = pixel1
398 | r2, g2, b2,a2 = pixel2
399 | color_difference = ((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2) ** 0.5
400 | return color_difference <= threshold
401 |
402 | def gaussian_weight(d, sigma=1.0):
403 | return np.exp(-(d ** 2) / (2 * sigma ** 2))
404 |
405 | def avg_edge_pixels(img):
406 | height, width = img.shape[:2]
407 | edge_pixels = []
408 |
409 | # top and bottom edges
410 | edge_pixels.extend(img[0,:])
411 | edge_pixels.extend(img[height-1,:])
412 |
413 | # left and right edges
414 | edge_pixels.extend(img[:,0])
415 | edge_pixels.extend(img[:,width-1])
416 |
417 | # calculate average of edge pixels
418 | avg_edge_pixel = np.mean(edge_pixels)
419 |
420 | return avg_edge_pixel
421 |
422 | def check_edges(image):
423 | h, w, c = image.shape
424 | threshold = 0.4
425 |
426 | def is_different(pixel1, pixel2):
427 | return np.any(np.abs(pixel1 - pixel2) > threshold * 255)
428 |
429 | for i in range(h):
430 | for j in range(w):
431 | if i < 2 or i > h - 3 or j < 2 or j > w - 3:
432 | central_i = i + 5 if i < h // 2 else i - 5
433 | central_j = j + 5 if j < w // 2 else j - 5
434 |
435 | # Ensure the central pixel is within the image boundaries
436 | central_i = max(0, min(central_i, h - 1))
437 | central_j = max(0, min(central_j, w - 1))
438 |
439 | if is_different(image[i, j], image[central_i, central_j]):
440 | image[i, j] = image[central_i, central_j]
441 |
442 |
443 | def resize_to_nearest_multiple_of_8(width, height):
444 | def nearest_multiple(n, factor):
445 | return round(n / factor) * factor
446 |
447 | new_width = nearest_multiple(width, 8)
448 | new_height = nearest_multiple(height, 8)
449 | return new_width, new_height
450 |
451 |
452 |
453 | def resize_to_nearest_multiple(width, height, a):
454 | def nearest_common_multiple(target, a, b):
455 | multiple = 1
456 | nearest_multiple = 0
457 | min_diff = float('inf')
458 |
459 | while True:
460 | current_multiple = a * multiple
461 | if current_multiple % b == 0:
462 | diff = abs(target - current_multiple)
463 | if diff < min_diff:
464 | min_diff = diff
465 | nearest_multiple = current_multiple
466 | else:
467 | break
468 | multiple += 1
469 |
470 | return nearest_multiple
471 |
472 | new_width = nearest_common_multiple(width, a, 8)
473 | new_height = nearest_common_multiple(height, a, 8)
474 | return int(new_width), int(new_height)
475 |
476 |
477 | def delete_folder_contents(folder_path):
478 | for filename in os.listdir(folder_path):
479 | file_path = os.path.join(folder_path, filename)
480 | try:
481 | if os.path.isfile(file_path) or os.path.islink(file_path):
482 | os.unlink(file_path)
483 | elif os.path.isdir(file_path):
484 | shutil.rmtree(file_path)
485 | except Exception as e:
486 | print(f'Failed to delete {file_path}. Reason: {e}')
487 |
488 | def blend_images(img1, img2, alpha=0.5):
489 | blended = cv2.addWeighted(img1, alpha, img2, 1-alpha, 0)
490 | return blended
491 |
492 |
493 | def pil_images_to_video(pil_images, output_file, fps=24):
494 | """
495 | Saves an array of PIL images to a video file using MoviePy.
496 |
497 | Args:
498 | pil_images (list): A list of PIL images.
499 | output_file (str): The output file path for the video.
500 | fps (int, optional): The desired frames per second. Defaults to 24.
501 |
502 | Returns:
503 | the filepath of the video file
504 | """
505 | # Convert PIL images to NumPy arrays
506 | np_images = [np.array(img) for img in pil_images]
507 |
508 | # Create an ImageSequenceClip instance with the array of NumPy images and the specified fps
509 | clip = ImageSequenceClip(np_images, fps=fps)
510 |
511 | # Write the video file to the specified output location
512 | clip.write_videofile(output_file,fps,codec='libx264')
513 |
514 | return output_file
515 |
516 | def copy_video(source_path, destination_path):
517 | """
518 | Copy a video file from source_path to destination_path.
519 |
520 | :param source_path: str, path to the source video file
521 | :param destination_path: str, path to the destination video file
522 | :return: None
523 | """
524 | try:
525 | shutil.copy(source_path, destination_path)
526 | print(f"Video copied successfully from {source_path} to {destination_path}")
527 | except IOError as e:
528 | print(f"Unable to copy video. Error: {e}")
529 | except Exception as e:
530 | print(f"Unexpected error: {e}")
531 |
532 | def crossfade_frames(frame1, frame2, alpha):
533 | """Crossfade between two video frames with a given alpha value."""
534 | image1 = Image.fromarray(frame1)
535 | image2 = Image.fromarray(frame2)
536 | blended_image = crossfade_images(image1, image2, alpha)
537 | blended_image = blended_image.convert('RGB')
538 | #THIS FUNCTION CONSUMED 3 HOURS OF DEBUGING AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
539 | return np.array(blended_image)
540 |
541 |
542 |
543 |
544 | def crossfade_videos(video_paths,fps, overlap_indexes, num_overlap_frames, output_path):
545 |
546 | """
547 | a python function and i need it to input an array of video paths,
548 | an array of the indexes where the videos overlap with the next video,
549 | the number of overlapping frames and the next file and i need it to combine these
550 | clips while crossfading between the clips where there is overlapping happening and
551 | output it to the output file location
552 | """
553 |
554 | #not video paths any more frame arrays
555 | original_frames_arrays = video_paths
556 | #for i in range(len(video_paths)):
557 | # data = convert_video_to_bytes(video_paths[i])
558 | ## frames_list = extract_frames_movpie(data, fps)
559 | # original_frames_arrays.append(frames_list)
560 | # print (f"video {i} has {len(frames_list)} frames")
561 | new_frames_arrays = copy.deepcopy(original_frames_arrays)
562 |
563 | for index, frames_array in enumerate(original_frames_arrays):
564 | if index < len(original_frames_arrays) - 1 and index in overlap_indexes:
565 | next_array = original_frames_arrays[index+1]
566 | print (f"crossfading between video {index} and video {index+1}")
567 | first_of_next = next_array[:num_overlap_frames]
568 | last_of_current = frames_array[-num_overlap_frames:]
569 | #last_of_current = last_of_current[::-1]
570 | if len(first_of_next) != len(last_of_current):
571 | print ("crossfade frames are not the same length")
572 | while len(first_of_next) != len(last_of_current):
573 | if len(first_of_next) > len(last_of_current):
574 | first_of_next.pop() # remove the last element from array1
575 | else:
576 | last_of_current.pop() # remove the last element from array2
577 |
578 | crossfaded = []
579 | for i in range(num_overlap_frames):
580 | alpha = 1 - (i / num_overlap_frames) # set alpha value
581 | if i > len(last_of_current) - 1 or i > len(first_of_next) - 1:
582 |
583 | print ("ran out of crossfade space at index ",str(i))
584 | break;
585 |
586 | new_frame = crossfade_frames(last_of_current[i], first_of_next[i], alpha)
587 | #print (new_frame.shape)
588 | crossfaded.append(new_frame)
589 | print (f"crossfaded {len(crossfaded)} frames with num overlap = {num_overlap_frames}, the last of current array is of length {len(last_of_current)} and the first of next is of length {len(first_of_next)}")
590 | #saving first of next and last of current
591 | new_frames_arrays[index][-num_overlap_frames:] = crossfaded
592 |
593 | if index > 0 and index - 1 in overlap_indexes:
594 | new_frames_arrays[index] = new_frames_arrays[index][num_overlap_frames:]
595 |
596 | for arr in new_frames_arrays:
597 | print(len(arr))
598 | #combined_arrays = np.concatenate(new_frames_arrays)
599 | output_array = []
600 | for arr in new_frames_arrays:
601 | for frame in arr:
602 | #frame = cv2.resize(frame, (new_frames_arrays, new_height), interpolation=cv2.INTER_LINEAR)
603 | #print (frame.shape)
604 | output_array.append(Image.fromarray(frame).convert("RGB"))
605 | return pil_images_to_video(output_array, output_path, fps)
606 |
607 |
608 |
609 |
610 | def crossfade_images(image1, image2, alpha):
611 | """Crossfade between two images with a given alpha value."""
612 | image1 = image1.convert("RGBA")
613 | image2 = image2.convert("RGBA")
614 | return Image.blend(image1, image2, alpha)
615 |
616 |
617 | def extract_frames_movpie(input_video, target_fps, max_frames=None, perform_interpolation=False):
618 | print(f"Interpolating extra frames with max frames {max_frames} and interpolating = {perform_interpolation}" )
619 |
620 | def get_video_info(video_path):
621 | cmd = ['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_streams', video_path]
622 |
623 | try:
624 | result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
625 | except FileNotFoundError as e:
626 | print(f"Error: {e}. Please ensure that ffmpeg is installed and available in your system's PATH.")
627 | return None
628 |
629 | return json.loads(result.stdout)
630 |
631 |
632 | def interpolate_frames(frame1, frame2, ratio):
633 | flow = cv2.calcOpticalFlowFarneback(cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY), cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY), None, 0.5, 3, 15, 3, 5, 1.2, 0)
634 | return cv2.addWeighted(frame1, 1 - ratio, frame2, ratio, 0) + ratio * cv2.remap(frame1, flow * (1 - ratio), None, cv2.INTER_LINEAR)
635 |
636 | with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as f:
637 | f.write(input_video)
638 | video_path = f.name
639 |
640 | video_info = get_video_info(video_path)
641 | video_stream = next((stream for stream in video_info['streams'] if stream['codec_type'] == 'video'), None)
642 | numerator, denominator = map(int, video_stream['avg_frame_rate'].split('/'))
643 | original_fps = float(numerator) / float(denominator) if denominator != 0 else 0.0
644 |
645 | video_clip = VideoFileClip(video_path)
646 | video_duration = video_clip.duration
647 | print (f"video duration is {video_duration}")
648 | frames = []
649 | frame_ratio = original_fps / target_fps
650 | frame_time = 1 / target_fps
651 | current_time = 0
652 |
653 |
654 | if max_frames is None:
655 | max_frames = int(video_duration * target_fps)
656 | else:
657 | max_frames = min(max_frames, int(video_duration * target_fps))
658 |
659 | if not perform_interpolation or target_fps <= original_fps:
660 | frame_repeat = int(target_fps / original_fps)
661 | print (f"frame repeat is {frame_repeat}, target fps is {target_fps} and original fps is {original_fps}")
662 | if frame_repeat == 0:
663 | frame_repeat = 1
664 | input_frame_time = 0
665 | input_frame_step = 1 / original_fps
666 |
667 | while len(frames) < max_frames and input_frame_time < video_duration:
668 | frame = video_clip.get_frame(input_frame_time)
669 | for _ in range(frame_repeat):
670 | frames.append(frame)
671 | if len(frames) >= max_frames:
672 | break
673 | input_frame_time += input_frame_step
674 | else:
675 | while len(frames) < max_frames:
676 | current_time = (len(frames) / target_fps) * video_duration
677 | frame1_time = current_time * frame_ratio
678 | frame2_time = min(current_time * frame_ratio + frame_ratio, video_duration)
679 |
680 | if frame2_time >= video_duration:
681 | break
682 |
683 | frame1 = video_clip.get_frame(frame1_time)
684 | frame2 = video_clip.get_frame(frame2_time)
685 |
686 | ratio = (current_time * original_fps) % 1
687 | frame = interpolate_frames(frame1, frame2, ratio)
688 |
689 | frames.append(frame)
690 |
691 | print(f"Extracted {len(frames)} frames at {target_fps} fps over a clip with a length of {len(frames) / target_fps} seconds with the old duration of {video_duration} seconds")
692 | return frames
693 |
694 |
695 |
696 | def convert_video_to_bytes(input_file):
697 | # Read the uploaded video file
698 | print(f"reading video file... {input_file}")
699 | with open(input_file, "rb") as f:
700 | video_bytes = f.read()
701 |
702 | # Return the processed video bytes (or any other output you want)
703 | return video_bytes
704 |
705 | def split_video_into_numpy_arrays(video_path, target_fps=None, perform_interpolation=False):
706 |
707 | video_manager = scenedetect.VideoManager([video_path])
708 | scene_manager = scenedetect.SceneManager()
709 | scene_manager.add_detector(scenedetect.ContentDetector())
710 |
711 | video_manager.set_downscale_factor()
712 | video_manager.start()
713 |
714 | scene_manager.detect_scenes(frame_source=video_manager)
715 | scene_list = scene_manager.get_scene_list(start_in_scene=True)
716 |
717 | if target_fps is not None:
718 | original_fps = video_manager.get(cv2.CAP_PROP_FPS)
719 |
720 | if len(scene_list) == 0:
721 | start_time = 0
722 | end_time = video_manager.get(cv2.CAP_PROP_FRAME_COUNT) / video_manager.get(cv2.CAP_PROP_FPS)
723 | scene_list.append((start_time, end_time))
724 |
725 | print (f"Detected {len(scene_list)} scenes")
726 | numpy_arrays = save_scenes_as_numpy_arrays(scene_list, video_path, target_fps, original_fps if target_fps else None, perform_interpolation)
727 |
728 | print(f"Total scenes: {len(numpy_arrays)}")
729 | return numpy_arrays
730 |
731 | def save_scenes_as_numpy_arrays(scene_list, video_path, target_fps=None, original_fps=None, perform_interpolation=True):
732 | def interpolate_frames(frame1, frame2, ratio):
733 | flow = cv2.calcOpticalFlowFarneback(cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY), cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY), None, 0.5, 3, 15, 3, 5, 1.2, 0)
734 | return cv2.addWeighted(frame1, 1 - ratio, frame2, ratio, 0) + ratio * cv2.remap(frame1, flow * (1 - ratio), None, cv2.INTER_LINEAR)
735 |
736 | numpy_arrays = []
737 | video_capture = cv2.VideoCapture(video_path)
738 |
739 | if target_fps and original_fps:
740 | frame_ratio = original_fps / target_fps
741 | frame_time = 1 / target_fps
742 |
743 | for i, (start_time, end_time) in enumerate(scene_list):
744 | start_frame = int(start_time.get_frames())
745 | end_frame = int(end_time.get_frames())
746 | scene_frames = []
747 | current_time = start_frame / original_fps if target_fps else start_frame
748 |
749 | print(f"Processing scene {i + 1}: start_frame={start_frame}, end_frame={end_frame} original fps={original_fps} target fps={target_fps}")
750 |
751 | while current_time < end_frame / original_fps if target_fps else end_frame:
752 | if target_fps and original_fps and perform_interpolation:
753 | frame1_time = current_time * frame_ratio
754 | frame2_time = min((current_time + frame_time) * frame_ratio, end_frame / original_fps)
755 | else:
756 | frame1_time = current_time
757 | frame2_time = current_time
758 |
759 | video_capture.set(cv2.CAP_PROP_POS_FRAMES, frame1_time * original_fps if target_fps else frame1_time)
760 | ret, frame1 = video_capture.read()
761 |
762 | if ret:
763 | frame1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB)
764 |
765 | if target_fps and original_fps and perform_interpolation:
766 | video_capture.set(cv2.CAP_PROP_POS_FRAMES, frame2_time * original_fps)
767 | ret, frame2 = video_capture.read()
768 |
769 | if ret:
770 | frame2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2RGB)
771 |
772 | ratio = (frame1_time * original_fps) % 1
773 | frame = interpolate_frames(frame1, frame2, ratio)
774 | else:
775 | frame = frame1
776 |
777 | scene_frames.append(frame)
778 |
779 | current_time += frame_time if target_fps else 1
780 | print(f"Scene {i + 1} has {len(scene_frames)} frames with length of {len(scene_frames)} frames with the old duration of {end_frame - start_frame} frames")
781 | numpy_arrays.append(np.array(scene_frames))
782 |
783 | video_capture.release()
784 | return numpy_arrays
785 |
--------------------------------------------------------------------------------
/scripts/optical_flow_raft.py:
--------------------------------------------------------------------------------
1 | import cv2
2 | import numpy as np
3 | import os
4 | import sys
5 | import torch
6 | from PIL import Image
7 | import matplotlib.pyplot as plt
8 | import torchvision.transforms.functional as F
9 | from torchvision.io import read_video, read_image, ImageReadMode
10 | from torchvision.models.optical_flow import Raft_Large_Weights
11 | from torchvision.models.optical_flow import raft_large
12 | from torchvision.io import write_jpeg
13 | import torchvision.transforms as T
14 | import scripts.berry_utility as utilityb
15 | import tempfile
16 | from pathlib import Path
17 | from urllib.request import urlretrieve
18 | from scipy.interpolate import LinearNDInterpolator
19 | from imageio import imread, imwrite
20 | from torchvision.utils import flow_to_image
21 |
22 | device = "cuda" if torch.cuda.is_available() else "cpu"
23 | model = raft_large(weights=Raft_Large_Weights.DEFAULT, progress=False).to(device)
24 | model = model.eval()
25 |
26 | #no clue if this works
27 | def flow_to_rgb(flow):
28 | """
29 | Convert optical flow to RGB image
30 |
31 | :param flow: optical flow map
32 | :return: RGB image
33 |
34 | """
35 | # forcing conversion to float32 precision
36 | flow = flow.numpy()
37 | hsv = np.zeros(flow.shape, dtype=np.uint8)
38 | hsv[..., 1] = 255
39 |
40 | mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
41 | hsv[..., 0] = ang * 180 / np.pi / 2
42 | hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
43 | #bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
44 | #cv2.imshow("colored flow", bgr)
45 | #cv2.waitKey(0)
46 | #cv2.destroyAllWindows()
47 |
48 | return hsv
49 |
50 | def write_flo(flow, filename):
51 | """
52 | Write optical flow in Middlebury .flo format
53 |
54 | :param flow: optical flow map
55 | :param filename: optical flow file path to be saved
56 | :return: None
57 |
58 | from https://github.com/liruoteng/OpticalFlowToolkit/
59 |
60 | """
61 | # forcing conversion to float32 precision
62 | flow = flow.cpu().data.numpy()
63 | flow = flow.astype(np.float32)
64 | f = open(filename, 'wb')
65 | magic = np.array([202021.25], dtype=np.float32)
66 | (height, width) = flow.shape[0:2]
67 | w = np.array([width], dtype=np.int32)
68 | h = np.array([height], dtype=np.int32)
69 | magic.tofile(f)
70 | w.tofile(f)
71 | h.tofile(f)
72 | flow.tofile(f)
73 | f.close()
74 |
75 |
76 | #def infer_old (frameA,frameB)
77 |
78 | def infer(frameA, frameB):
79 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
80 | model = raft_large(weights=Raft_Large_Weights.DEFAULT, progress=False).to(device)
81 | model = model.eval()
82 |
83 | # Check if both frames have the same size
84 | if frameA.size != frameB.size:
85 | raise ValueError("Both input frames must have the same size")
86 |
87 | transform = T.ToTensor()
88 |
89 | img1_batch = transform(frameA)
90 | img2_batch = transform(frameB)
91 | img1_batch = torch.stack([img1_batch])
92 | img2_batch = torch.stack([img2_batch])
93 | weights = Raft_Large_Weights.DEFAULT
94 | transforms = weights.transforms()
95 |
96 | def preprocess(img1_batch, img2_batch):
97 | return transforms(img1_batch, img2_batch)
98 |
99 | img1_batch, img2_batch = preprocess(img1_batch, img2_batch)
100 |
101 | return img1_batch, img2_batch
102 |
103 |
104 |
105 | def apply_flow_based_on_images (image1_path, image2_path, provided_image_path,max_dimension, index,output_folder):
106 | w,h = get_target_size(utilityb.base64_to_texture(image1_path), max_dimension)
107 | w = int(w / 8) * 8
108 | h = int(h / 8) * 8
109 | image1 = resize_image(utilityb.base64_to_texture(image1_path),h,w)
110 | h, w = image1.shape[:2]
111 | image2 = cv2.resize(utilityb.base64_to_texture(image2_path), (w,h), interpolation=cv2.INTER_LINEAR)
112 |
113 | # image1 = utilityb.base64_to_texture(image1_path),max_dimension
114 | # image2 = utilityb.base64_to_texture(image2_path),max_dimension
115 | # provided_image = read_image(provided_image_path)
116 | provided_image = utilityb.base64_to_texture(provided_image_path)
117 | provided_image = cv2.resize(provided_image, (w,h), interpolation=cv2.INTER_LINEAR)
118 |
119 |
120 |
121 | img1_batch,img2_batch = infer(image1,image2)
122 | list_of_flows = model(img1_batch.to(device), img2_batch.to(device))
123 | predicted_flows = list_of_flows[-1]
124 | predicted_flow = list_of_flows[-1][0]
125 | flow_img = flow_to_image(predicted_flow).to("cpu")
126 | #flo_file = write_flo(predicted_flow, "flofile.flo")
127 |
128 | #write_jpeg(flow_img, f"./flow/predicted_flow{index}.jpg")
129 | #write_jpeg(flow_img, os.path.join("temp", f'flow_{index + 1}.flo'))
130 |
131 | #print(flow.shape)
132 | #warped_image = apply_flow_to_image_try3(provided_image,predicted_flow)
133 | warped_image,unused_mask,white_pixels = apply_flow_to_image_with_unused_mask(provided_image,predicted_flow)
134 |
135 |
136 |
137 |
138 | warped_image_path = os.path.join(output_folder, f'warped_provided_image_{index + 1}.png')
139 | save_image(warped_image, warped_image_path)
140 | return warped_image_path,predicted_flow,unused_mask,white_pixels,flow_img
141 |
142 | def apply_flow_to_image(image, flow):
143 | """
144 | Apply optical flow transforms to an input image
145 |
146 | :param image: input image
147 | :param flow: optical flow map
148 | :return: warped image
149 |
150 | """
151 |
152 | # forcing conversion to float32 precision
153 | #flow = flow.numpy()
154 | flow = flow.astype(np.float32)
155 |
156 | # Get the height and width of the input image
157 | height, width = image.shape[:2]
158 |
159 | # Create a grid of (x, y) coordinates
160 | x, y = np.meshgrid(np.arange(width), np.arange(height))
161 |
162 | # Apply the optical flow to the coordinates
163 | x_warped = (x + flow[..., 0]).astype(np.float32)
164 | y_warped = (y + flow[..., 1]).astype(np.float32)
165 |
166 | # Remap the input image using the warped coordinates
167 | warped_image = cv2.remap(image, x_warped, y_warped, cv2.INTER_LINEAR)
168 |
169 | return warped_image
170 |
171 | def warp_image(image, flow):
172 | h, w = image.shape[:2]
173 |
174 | flow_map = np.array([[x, y] for y in range(h) for x in range(w)], dtype=np.float32) - flow.reshape(-1, 2)
175 | flow_map = flow_map.reshape(h, w, 2).astype(np.float32) # Ensure the flow_map is in the correct format
176 |
177 | # Clip the flow_map to the image bounds
178 | flow_map[:, :, 0] = np.clip(flow_map[:, :, 0], 0, w - 1)
179 | flow_map[:, :, 1] = np.clip(flow_map[:, :, 1], 0, h - 1)
180 |
181 | warped_image = cv2.remap(image, flow_map, None, cv2.INTER_LANCZOS4)
182 | return warped_image
183 |
184 | def save_image(image, file_path):
185 | cv2.imwrite(file_path, image)
186 |
187 | def resize_image(image, new_height,new_width):
188 | resized_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_LINEAR)
189 | return resized_image
190 |
191 | def get_target_size (image,max_dimension):
192 | h, w = image.shape[:2]
193 | aspect_ratio = float(w) / float(h)
194 | if h > w:
195 | new_height = max_dimension
196 | new_width = int(new_height * aspect_ratio)
197 | else:
198 | new_width = max_dimension
199 | new_height = int(new_width / aspect_ratio)
200 | return new_width,new_height
201 |
202 |
203 | def apply_flow_to_image_try3(image,flow):
204 | """
205 | Apply an optical flow tensor to a NumPy image by moving the pixels based on the flow.
206 |
207 | Args:
208 | image (np.ndarray): Input image with shape (height, width, channels).
209 | flow (np.ndarray): Optical flow tensor with shape (height, width, 2).
210 |
211 | Returns:
212 | np.ndarray: Warped image with the same shape as the input image.
213 | """
214 | height, width, _ = image.shape
215 | x_coords, y_coords = np.meshgrid(np.arange(width), np.arange(height))
216 | coords = np.stack([x_coords, y_coords], axis=-1).astype(np.float32)
217 |
218 | # Add the flow to the original coordinates
219 | if isinstance(flow, torch.Tensor):
220 | flow = flow.detach().cpu().numpy()
221 | flow = flow.transpose(1, 2, 0)
222 | new_coords = np.subtract(coords, flow)
223 |
224 |
225 | # Map the new coordinates to the pixel values in the original image
226 | warped_image = cv2.remap(image, new_coords, None, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)
227 |
228 | return warped_image
229 |
230 |
231 | def apply_flow_to_image_with_unused_mask(image, flow):
232 | """
233 | Apply an optical flow tensor to a NumPy image by moving the pixels based on the flow and create a mask where the remap meant there was nothing there.
234 |
235 | Args:
236 | image (np.ndarray): Input image with shape (height, width, channels).
237 | flow (np.ndarray): Optical flow tensor with shape (height, width, 2).
238 |
239 | Returns:
240 | tuple: Warped image with the same shape as the input image, and a mask where the remap meant there was nothing there.
241 | """
242 | height, width, _ = image.shape
243 | x_coords, y_coords = np.meshgrid(np.arange(width), np.arange(height))
244 | coords = np.stack([x_coords, y_coords], axis=-1).astype(np.float32)
245 |
246 | # Add the flow to the original coordinates
247 | if isinstance(flow, torch.Tensor):
248 | flow = flow.detach().cpu().numpy()
249 | flow = flow.transpose(1, 2, 0)
250 | new_coords = np.subtract(coords, flow)
251 | avg = utilityb.avg_edge_pixels(image)
252 | warped_image = cv2.remap(image, new_coords, None, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)
253 |
254 | # Create a mask where the remap meant there was nothing there
255 | mask = utilityb.create_hole_mask(flow)
256 | white_pixels = np.sum(mask > 0)
257 | #print(f'white pixels {white_pixels}')
258 |
259 | #remove later
260 | #warped_image = warp_image2(image,flow)
261 |
262 | return warped_image, mask,white_pixels
263 |
264 | def warp_image2(image, flow):
265 | h, w = image.shape[:2]
266 | flow_map = np.array([[x, y] for y in range(h) for x in range(w)], dtype=np.float32) - flow.reshape(-1, 2)
267 | flow_map = flow_map.reshape(h, w, 2).astype(np.float32) # Ensure the flow_map is in the correct format
268 |
269 | # Clip the flow_map to the image bounds
270 | flow_map[:, :, 0] = np.clip(flow_map[:, :, 0], 0, w - 1)
271 | flow_map[:, :, 1] = np.clip(flow_map[:, :, 1], 0, h - 1)
272 |
273 | warped_image = cv2.remap(image, flow_map, None, cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT, borderValue=(0, 0, 0) )
274 | return warped_image
--------------------------------------------------------------------------------
/scripts/optical_flow_simple.py:
--------------------------------------------------------------------------------
1 | import os
2 | import glob
3 | import cv2
4 | import numpy as np
5 | from PIL import Image
6 | import scripts.berry_utility as utilityb
7 |
8 | def read_image(file_path):
9 | image = cv2.imread(file_path, cv2.IMREAD_COLOR)
10 | if image is None:
11 | raise ValueError(f"Image '{file_path}' not found.")
12 | return image
13 |
14 | def save_image(image, file_path):
15 | cv2.imwrite(file_path, image)
16 |
17 | def resize_image(image, max_dimension):
18 | h, w = image.shape[:2]
19 | aspect_ratio = float(w) / float(h)
20 | if h > w:
21 | new_height = max_dimension
22 | new_width = int(new_height * aspect_ratio)
23 | else:
24 | new_width = max_dimension
25 | new_height = int(new_width / aspect_ratio)
26 | resized_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_LINEAR)
27 | return resized_image
28 |
29 | def flow_to_color(flow, max_flow=None):
30 | hsv = np.zeros((flow.shape[0], flow.shape[1], 3), dtype=np.float32)
31 | hsv[..., 1] = 1.0
32 |
33 | mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
34 | hsv[..., 0] = ang * 180 / np.pi / 2
35 | if max_flow is not None:
36 | hsv[..., 2] = np.clip(mag / max_flow, 0, 1)
37 | else:
38 | hsv[..., 2] = np.clip(mag / (np.max(mag) + 1e-5), 0, 1)
39 | rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
40 | return (rgb * 255).astype(np.uint8)
41 |
42 | def save_optical_flow(flow, file_path, max_flow=None):
43 | flow_color = flow_to_color(flow, max_flow)
44 | save_image(flow_color, file_path)
45 |
46 |
47 | def compute_optical_flow(image1, image2):
48 | flow = cv2.calcOpticalFlowFarneback(image1, image2, None, pyr_scale=0.5, levels=3, winsize=15, iterations=3, poly_n=5, poly_sigma=1.2, flags=0)
49 | return flow
50 |
51 | def warp_image(image, flow):
52 | h, w = image.shape[:2]
53 | flow_map = np.array([[x, y] for y in range(h) for x in range(w)], dtype=np.float32) - flow.reshape(-1, 2)
54 | flow_map = flow_map.reshape(h, w, 2).astype(np.float32) # Ensure the flow_map is in the correct format
55 |
56 | # Clip the flow_map to the image bounds
57 | flow_map[:, :, 0] = np.clip(flow_map[:, :, 0], 0, w - 1)
58 | flow_map[:, :, 1] = np.clip(flow_map[:, :, 1], 0, h - 1)
59 |
60 | warped_image = cv2.remap(image, flow_map, None, cv2.INTER_LANCZOS4 )
61 | return warped_image
62 |
63 | def process_image_basic (image1_path, image2_path, provided_image_path,max_dimension, index,output_folder):
64 |
65 | #image1 = read_image(image1_path)
66 | # image2 = read_image(image2_path)
67 |
68 | # image1 = resize_image(image1, max_dimension)
69 | # image2 = resize_image(image2, max_dimension)
70 | image1 = resize_image(utilityb.base64_to_texture(image1_path),max_dimension)
71 | image2 = resize_image(utilityb.base64_to_texture(image2_path),max_dimension)
72 |
73 | # provided_image = read_image(provided_image_path)
74 | provided_image = utilityb.base64_to_texture(provided_image_path)
75 | provided_image = resize_image(provided_image, max_dimension)
76 |
77 | flow = compute_optical_flow(cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY), cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY))
78 | warped_image = warp_image(provided_image, flow)
79 |
80 | warped_image_path = os.path.join(output_folder, f'warped_provided_image_{index + 1}.png')
81 | save_image(warped_image, warped_image_path)
82 | print(f"Warped image saved as '{warped_image_path}'")
83 | combine_images(image1,image2,provided_image,warped_image,f"{index}.png")
84 | return warped_image_path,flow
85 | # return provided_image_path,flow
86 | #AAAAAAAAAAAAAAAAAAA
87 |
88 | def process_image(image1, image2, provided_image, output_folder, flow_output_folder, max_dimension, index):
89 | image1 = resize_image(image1, max_dimension)
90 | image2 = resize_image(image2, max_dimension)
91 |
92 | flow = compute_optical_flow(cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY), cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY))
93 | warped_image = warp_image(provided_image, flow)
94 |
95 | warped_image_path = os.path.join(output_folder, f'warped_provided_image_{index + 1}.png')
96 | save_image(warped_image, warped_image_path)
97 | print(f"Warped image saved as '{warped_image_path}'")
98 |
99 | flow_image_path = os.path.join(flow_output_folder, f'optical_flow_{index + 1}.png')
100 | save_optical_flow(flow, flow_image_path)
101 | print(f"Optical flow map saved as '{flow_image_path}'")
102 |
103 | return warped_image
104 |
105 | def process_images(input_folder, output_folder, flow_output_folder, provided_image_path, max_dimension):
106 | if not os.path.exists(output_folder):
107 | os.makedirs(output_folder)
108 | if not os.path.exists(flow_output_folder):
109 | os.makedirs(flow_output_folder)
110 |
111 | image_files = sorted(glob.glob(os.path.join(input_folder, '*.png')))
112 | num_images = len(image_files)
113 |
114 | if num_images < 1:
115 | raise ValueError("At least one image is required to compute optical flow.")
116 |
117 | provided_image = read_image(provided_image_path)
118 | provided_image = resize_image(provided_image, max_dimension)
119 |
120 | for i in range(num_images - 1):
121 | image1 = read_image(image_files[i])
122 | image2 = read_image(image_files[i + 1])
123 |
124 | provided_image = process_image(image1, image2, provided_image, output_folder, flow_output_folder, max_dimension, i)
125 |
126 | def main():
127 | input_folder = "Input_Images"
128 | output_folder = "output_images"
129 | flow_output_folder = "flow_output_images"
130 | provided_image_path = "init.png"
131 | max_dimension = 320 # Change this value to your preferred maximum dimension
132 | #process_images(input_folder, output_folder, flow_output_folder, provided_image_path, max_dimension)
133 |
134 |
135 | if __name__ == "__main__":
136 | main()
137 |
138 | def combine_images(img1, img2, img3, img4, output_file, output_folder="debug"):
139 | img1_pil = Image.fromarray(np.uint8(img1))
140 | img2_pil = Image.fromarray(np.uint8(img2))
141 | img3_pil = Image.fromarray(np.uint8(img3))
142 | img4_pil = Image.fromarray(np.uint8(img4))
143 |
144 | # Create output folder if it doesn't exist
145 | if not os.path.exists(output_folder):
146 | os.makedirs(output_folder)
147 |
148 | # Combine images horizontally
149 | combined_horizontal1 = Image.new('RGB', (img1_pil.width + img2_pil.width, img1_pil.height))
150 | combined_horizontal1.paste(img1_pil, (0, 0))
151 | combined_horizontal1.paste(img2_pil, (img1_pil.width, 0))
152 |
153 | combined_horizontal2 = Image.new('RGB', (img3_pil.width + img4_pil.width, img3_pil.height))
154 | combined_horizontal2.paste(img3_pil, (0, 0))
155 | combined_horizontal2.paste(img4_pil, (img3_pil.width, 0))
156 |
157 | # Combine images vertically
158 | combined_image = Image.new('RGB', (combined_horizontal1.width, combined_horizontal1.height + combined_horizontal2.height))
159 | combined_image.paste(combined_horizontal1, (0, 0))
160 | combined_image.paste(combined_horizontal2, (0, combined_horizontal1.height))
161 |
162 | # Save combined image to output folder
163 | output_path = os.path.join(output_folder, output_file)
164 | combined_image.save(output_path)
165 |
166 |
--------------------------------------------------------------------------------
/scripts/sd-TemporalKit-UI.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import math
3 | import random
4 | import sys
5 | from argparse import ArgumentParser
6 | from collections import namedtuple, deque
7 | import einops
8 | import gradio as gr
9 | import numpy as np
10 | import torch
11 | import torch.nn as nn
12 | from einops import rearrange
13 | from omegaconf import OmegaConf
14 | from PIL import Image, ImageOps
15 | from torch import autocast
16 | import os
17 | import shutil
18 | import time
19 | import stat
20 | import gradio as gr
21 | import modules.extras
22 | from modules.ui_components import FormRow, FormGroup, ToolButton, FormHTML
23 | from modules.ui import create_sampler_and_steps_selection
24 | import json
25 | from modules.sd_samplers import samplers, samplers_for_img2img
26 | import re
27 | import modules.images as images
28 | from modules.call_queue import wrap_gradio_gpu_call, wrap_queued_call, wrap_gradio_call
29 | from modules import ui_extra_networks, devices, shared, scripts, script_callbacks, sd_hijack_unet, sd_hijack_utils
30 | from modules.shared import opts, cmd_opts, OptionInfo
31 | from pathlib import Path
32 | from typing import List, Tuple
33 | from PIL.ExifTags import TAGS
34 | from PIL.PngImagePlugin import PngImageFile, PngInfo
35 | from datetime import datetime
36 | from modules.generation_parameters_copypaste import quote
37 | from copy import deepcopy
38 | import platform
39 | import modules.generation_parameters_copypaste as parameters_copypaste
40 | import scripts.Berry_Method as General_SD
41 | import glob
42 | import base64
43 | import io
44 | import scripts.Ebsynth_Processing as ebsynth
45 | import scripts.berry_utility as sd_utility
46 |
47 |
48 | diffuseimg = None
49 | SamplerData = namedtuple('SamplerData', ['name', 'constructor', 'aliases', 'options'])
50 | lastmadefilename = ""
51 | def upload_file(files):
52 | file_paths = [file.name for file in files]
53 | return file_paths
54 |
55 |
56 | def preprocess_video(video,fps,batch_size,per_side,resolution,batch_run,max_frames,output_path,border_frames,ebsynth_mode,split_video,split_based_on_cuts):
57 | input_folder_loc = os.path.join(output_path, "input")
58 | output_folder_loc = os.path.join(output_path, "output")
59 | if not os.path.exists(input_folder_loc):
60 | os.makedirs(input_folder_loc)
61 | if not os.path.exists(output_folder_loc):
62 | os.makedirs(output_folder_loc)
63 |
64 | max_keys = max_frames
65 | if max_keys < 0:
66 | max_keys = 100000
67 | max_frames = (max_frames * (batch_size))
68 | if max_frames < 1:
69 | max_frames = 100000
70 | # would use mathf.inf in c#, dunno what that is in python
71 | # potential bug later, low priority
72 | if ebsynth_mode == True:
73 | if split_video == False:
74 | border_frames = 0
75 | if batch_run == False:
76 | max_frames = per_side * per_side * (batch_size + 1)
77 |
78 |
79 | if split_video == True:
80 |
81 | #max frames only applies in batch mode
82 | #otherwise it limmits the number of *total frames*
83 | border_frames = border_frames * batch_size
84 |
85 | max_frames = (20 * batch_size) - border_frames
86 | max_total_frames = int((max_keys / 20) * max_frames)
87 | existing_frames = []
88 |
89 | if split_based_on_cuts == True:
90 | existing_frames = sd_utility.split_video_into_numpy_arrays(video,fps,False)
91 | else:
92 | data = General_SD.convert_video_to_bytes(video)
93 | existing_frames = [sd_utility.extract_frames_movpie(data, fps,max_frames=max_total_frames,perform_interpolation=False)]
94 |
95 |
96 | split_video_paths,transition_data = General_SD.split_videos_into_smaller_videos(max_keys,existing_frames,fps,max_frames,output_path,border_frames,split_based_on_cuts)
97 | for index,individual_video in enumerate(split_video_paths):
98 |
99 | generated_textures = General_SD.generate_squares_to_folder(individual_video,fps=fps,batch_size=batch_size, resolution=resolution,size_size=per_side,max_frames=None, output_folder=os.path.dirname(individual_video),border=0, ebsynth_mode=ebsynth_mode,max_frames_to_save=max_frames)
100 | input_location = os.path.join(os.path.dirname(os.path.dirname(individual_video)),"input")
101 | for tex_index,texture in enumerate(generated_textures):
102 | individual_file_name = os.path.join(input_location,f"{index}and{tex_index}.png")
103 | General_SD.save_square_texture(texture,individual_file_name)
104 | transitiondatapath = os.path.join(output_path,"transition_data.txt")
105 | with open(transitiondatapath, "w") as f:
106 | f.write(str(transition_data) + "\n")
107 | f.write(str(border_frames) + "\n")
108 | main_video_path = os.path.join(output_path,"main_video.mp4")
109 | sd_utility.copy_video(video,main_video_path)
110 | return main_video_path
111 |
112 | new_video_loc = os.path.join(output_path, f"input_video.mp4")
113 | shutil.copyfile(video,new_video_loc)
114 | if ebsynth_mode == True:
115 | border = 0
116 |
117 | image = General_SD.generate_squares_to_folder(video,fps=fps,batch_size=batch_size, resolution=resolution,size_size=per_side,max_frames=max_frames, output_folder=output_path,border=border_frames, ebsynth_mode=True,max_frames_to_save=max_frames)
118 | return image[0]
119 |
120 | if batch_run == False:
121 | image = General_SD.generate_square_from_video(video,fps=fps,batch_size=batch_size, resolution=resolution,size_size=per_side )
122 | processed = numpy_array_to_temp_url(image)
123 | else:
124 | image = General_SD.generate_squares_to_folder(video,fps=fps,batch_size=batch_size, resolution=resolution,size_size=per_side,max_frames=max_frames, output_folder=output_path,border=border_frames,ebsynth_mode=False,max_frames_to_save=max_frames)
125 | processed = image[0]
126 | return processed
127 |
128 |
129 |
130 | def apply_image_to_video(image,video,fps,per_side,output_resolution,batch_size):
131 | return General_SD.process_video_single(video_path=video,fps=fps,per_side=per_side,batch_size=batch_size,fillindenoise=0,edgedenoise=0,_smol_resolution=output_resolution,square_texture=image)
132 |
133 | def apply_image_to_vide_batch(input_folder,video,fps,per_side,output_resolution,batch_size,max_frames,border_frames):
134 | input_images_folder = os.path.join (input_folder,"output")
135 | images = read_images_folder(input_images_folder)
136 | print(len(images))
137 | return General_SD.process_video_batch(video_path_old=video,fps=fps,per_side=per_side,batch_size=batch_size,fillindenoise=0,edgedenoise=0,_smol_resolution=output_resolution,square_textures=images,max_frames=max_frames,output_folder=input_folder,border=border_frames)
138 |
139 | def post_process_ebsynth(input_folder,video,fps,per_side,output_resolution,batch_size,max_frames,border_frames):
140 | input_images_folder = os.path.join (input_folder,"output")
141 | images = read_images_folder(input_images_folder)
142 | print(len(images))
143 | split_mode = os.path.join(input_folder, "keys")
144 | if os.path.exists(split_mode):
145 | return ebsynth.sort_into_folders(video_path=video,fps=fps,per_side=per_side,batch_size=batch_size,_smol_resolution=output_resolution,square_textures=images,max_frames=max_frames,output_folder=input_folder,border=border_frames)
146 | else:
147 | img_folder = os.path.join(input_folder, "output")
148 | # define a regular expression pattern to match directory names with one or more digits
149 | pattern = r'^\d+$'
150 |
151 | # get a list of all directories in the specified path
152 | all_dirs = os.listdir(input_folder)
153 |
154 | # use a list comprehension to filter the directories based on the pattern
155 | numeric_dirs = sorted([d for d in all_dirs if re.match(pattern, d)], key=lambda x: int(x))
156 | max_frames = max_frames + border_frames
157 | for d in numeric_dirs:
158 | # create a list to store the filenames of the images that match the directory name
159 | img_names = []
160 | folder_video = os.path.join(input_folder, d, "input_video.mp4")
161 | # loop through each image file in the image folder
162 | for img_file in os.listdir(img_folder):
163 | # check if the image filename starts with the directory name followed by the word "and" and a sequence of one or more digits, then ends with '.png'
164 | if re.match(f"^{d}and\d+.*\.png$", img_file):
165 | img_names.append(img_file)
166 | print(f"post processing = {os.path.dirname(folder_video)}")
167 | square_textures = []
168 | # loop through each image file name
169 | for img_name in sorted(img_names, key=lambda x: int(re.search(r'and(\d+)', x).group(1))):
170 | img = Image.open(os.path.join(input_images_folder, img_name))
171 | # Convert image to NumPy array and append to images list
172 | print(f"saving {os.path.join(input_images_folder, img_name)}")
173 | square_textures.append(np.array(img))
174 |
175 | ebsynth.sort_into_folders(video_path=folder_video, fps=fps, per_side=per_side, batch_size=batch_size,
176 | _smol_resolution=output_resolution, square_textures=square_textures,
177 | max_frames=max_frames, output_folder=os.path.dirname(folder_video),
178 | border=border_frames)
179 |
180 | def recombine_ebsynth(input_folder,fps,border_frames,batch):
181 | if os.path.exists(os.path.join(input_folder, "keys")):
182 | return ebsynth.crossfade_folder_of_folders(input_folder,fps=fps,return_generated_video_path=True)
183 | else:
184 | generated_videos = []
185 | pattern = r'^\d+$'
186 |
187 | # get a list of all directories in the specified path
188 | all_dirs = os.listdir(input_folder)
189 |
190 | # use a list comprehension to filter the directories based on the pattern
191 | numeric_dirs = sorted([d for d in all_dirs if re.match(pattern, d)], key=lambda x: int(x))
192 |
193 | for d in numeric_dirs:
194 | folder_loc = os.path.join(input_folder,d)
195 | # loop through each image file in the image folder
196 | new_video = ebsynth.crossfade_folder_of_folders(folder_loc,fps=fps)
197 | #print(f"generated new video at location {new_video}")
198 | generated_videos.append(new_video)
199 |
200 | overlap_data_path = os.path.join(input_folder,"transition_data.txt")
201 | with open(overlap_data_path, "r") as f:
202 | merge = str(f.readline().strip())
203 |
204 | overlap_indicies = []
205 | int_list = eval(merge)
206 | for num in int_list:
207 | overlap_indicies.append(int(num))
208 |
209 |
210 |
211 | output_video = sd_utility.crossfade_videos(video_paths=generated_videos,fps=fps,overlap_indexes= overlap_indicies,num_overlap_frames= border_frames,output_path=os.path.join(input_folder,"output.mp4"))
212 | return output_video
213 | return None
214 |
215 |
216 | def atoi(text):
217 | return int(text) if text.isdigit() else text
218 |
219 | def natural_keys(text):
220 | return [atoi(c) for c in re.split(r'(\d+)', text)]
221 |
222 | def read_images_folder(folder_path):
223 | images = []
224 | filenames = os.listdir(folder_path)
225 |
226 | # Sort filenames based on the order of the numbers in their names
227 | filenames.sort(key=natural_keys)
228 |
229 | for filename in filenames:
230 | # Check if file is an image (assumes only image files are in the folder)
231 | if (filename.endswith('.jpg') or filename.endswith('.png') or filename.endswith('.jpeg')) and (not re.search(r'-\d', filename)):
232 | if re.match(r".*(input).*", filename):
233 | # Open image using Pillow library
234 |
235 | img = Image.open(os.path.join(folder_path, filename))
236 | # Convert image to NumPy array and append to images list
237 | images.append(np.array(img))
238 | else:
239 | print(f"[${filename}] File name must contain \"input\". Skip processing.")
240 | return images
241 |
242 |
243 |
244 | def numpy_array_to_data_uri(img_array):
245 | # convert the array to an image using PIL
246 | img = Image.fromarray(img_array)
247 |
248 | # create a BytesIO object to hold the image data
249 | buffer = io.BytesIO()
250 |
251 | # save the image to the BytesIO object as PNG
252 | img.save(buffer, format='PNG')
253 |
254 | # get the PNG data from the BytesIO object
255 | png_data = buffer.getvalue()
256 |
257 | # convert the PNG data to base64-encoded string
258 | base64_str = base64.b64encode(png_data).decode()
259 |
260 | # combine the base64-encoded string with the image format prefix
261 | data_uri = 'data:image/png;base64,' + base64_str
262 |
263 | return data_uri
264 |
265 | def numpy_array_to_temp_url(img_array):
266 | # create a filename for the temporary file
267 | filename = 'generatedsquare.png'
268 | extension_path = os.path.abspath(__file__)
269 | extension_dir = os.path.dirname(os.path.dirname(extension_path))
270 | extension_folder = os.path.join(extension_dir,"squares")
271 | if not os.path.exists(extension_folder):
272 | os.makedirs(extension_folder)
273 | # create a path for the temporary file
274 | file_path = os.path.join(extension_folder, filename)
275 |
276 | # convert the array to an image using PIL
277 | img = Image.fromarray(img_array)
278 |
279 | # save the image to the temporary file as PNG
280 | img.save(file_path, format='PNG')
281 |
282 | # create a URL for the temporary file
283 | #url = 'file://' + file_path
284 |
285 | return file_path
286 |
287 | def display_interface(interface):
288 | return interface.display()
289 |
290 |
291 | def get_most_recent_file(provided_directory):
292 | if not os.path.exists(provided_directory) or not os.path.isdir(provided_directory):
293 | raise ValueError("Invalid directory provided")
294 |
295 | # Get all files in the provided directory
296 | files = glob.glob(os.path.join(provided_directory, '*'))
297 |
298 | if not files:
299 | return None
300 |
301 | # Sort the files based on modification time and get the most recent one
302 | most_recent_file = max(files, key=os.path.getmtime)
303 |
304 | return most_recent_file
305 |
306 | def update_image():
307 | global diffuseimg
308 | extension_path = os.path.abspath(__file__)
309 | # get the directory name of the extension
310 | extension_dir = os.path.dirname(os.path.dirname(extension_path))
311 | extension_folder = os.path.join(extension_dir,"squares")
312 | most_recent_image = get_most_recent_file(extension_folder)
313 | print(most_recent_image)
314 | pilImage = Image.open(most_recent_image)
315 | print("running")
316 | return most_recent_image
317 |
318 | def update_settings():
319 | extension_path = os.path.abspath(__file__)
320 | extension_dir = os.path.dirname(os.path.dirname(extension_path))
321 | tempfile = os.path.join(extension_dir,"temp_file.txt")
322 | with open(tempfile, "r") as f:
323 | fps = int(f.readline().strip())
324 | sides = int(f.readline().strip())
325 | batch_size = int(f.readline().strip())
326 | video_path = f.readline().strip()
327 | return fps,sides,batch_size,video_path
328 |
329 | def update_settings_from_file(folderpath):
330 | read_path = os.path.join(folderpath,"batch_settings.txt")
331 | border = None
332 | print (f"batch settings exists = {os.path.exists(read_path)}")
333 | if os.path.exists(read_path) == False:
334 | read_path = os.path.join(folderpath,"0/batch_settings.txt")
335 | video_path = os.path.join(folderpath,"main_video.mp4")
336 | transition_data_path = os.path.join(folderpath,"transition_data.txt")
337 | if os.path.exists(transition_data_path):
338 | with open(transition_data_path, "r") as b:
339 | merge = str(b.readline().strip())
340 | border = int(b.readline().strip())
341 | print (f"reading path at {read_path}")
342 | with open(read_path, "r") as f:
343 | fps = int(f.readline().strip())
344 | sides = int(f.readline().strip())
345 | batch_size = int(f.readline().strip())
346 | video_path = f.readline().strip()
347 | max_frames = int(f.readline().strip())
348 | if border == None:
349 | border = int(f.readline().strip())
350 |
351 |
352 | return fps,sides,batch_size,video_path,max_frames,border
353 |
354 |
355 | def save_settings(fps,sides,batch_size,video):
356 | extension_path = os.path.abspath(__file__)
357 | extension_dir = os.path.dirname(os.path.dirname(extension_path))
358 | tempfile = os.path.join(extension_dir,"temp_file.txt")
359 | with open(tempfile, "w") as f:
360 | f.write(str(fps) + "\n")
361 | f.write(str(sides) + "\n")
362 | f.write(str(batch_size) + "\n")
363 | f.write(str(video) + "\n")
364 |
365 | def create_video_Processing_Tab():
366 | with gr.Column(visible=True, elem_id="Temporal_Kit") as main_panel:
367 | dummy_component = gr.Label(visible=False)
368 | with gr.Row():
369 | with gr.Tabs(elem_id="mode_TemporalKit"):
370 | with gr.Row():
371 | with gr.Tab(elem_id="input_TemporalKit", label="Input"):
372 | with gr.Row():
373 | with gr.Column():
374 | video = gr.Video(label="Input Video", elem_id="input_video",type="filepath")
375 | with gr.Row():
376 | sides = gr.Number(value=2,label="Sides", precision=0, interactive=True)
377 | resolution = gr.Number(value=1024,label="Height Resolution", precision=1, interactive=True)
378 | with gr.Row():
379 | batch_size = gr.Number(value=5, label="frames per keyframe", precision=1, interactive=True)
380 | fps = gr.Number(value=30, precision=1, label="fps", interactive=True)
381 | ebsynth_mode = gr.Checkbox(label="EBSynth Mode", value=False)
382 | with gr.Row():
383 | savesettings = gr.Button("Save Settings")
384 | with gr.Row():
385 | batch_folder = gr.Textbox(label="Target Folder",placeholder="This is ignored if neither batch run or ebsynth are checked")
386 |
387 | with gr.Row():
388 | with gr.Accordion("Batch Settings",open=False):
389 | with gr.Row():
390 | batch_checkbox = gr.Checkbox(label="Batch Run", value=False)
391 | max_keyframes = gr.Number(value=-1, label="Max key frames", precision=1, interactive=True,placeholder="for all frames")
392 | border_frames = gr.Number(value=2, label="Border Key Frames", precision=1, interactive=True,placeholder="border frames")
393 | with gr.Row():
394 | with gr.Accordion("EBSynth Settings",open=False):
395 | with gr.Row():
396 | split_video = gr.Checkbox(label="Split Video", value=False)
397 | split_based_on_cuts = gr.Checkbox(label="Split based on cuts (as well)", value=False)
398 | #interpolate = gr.Checkbox(label="Interpolate(high memory)", value=False)
399 |
400 |
401 | savesettings.click(
402 | fn=save_settings,
403 | inputs=[fps,sides,batch_size,video]
404 | )
405 | with gr.Tabs(elemn_id="TemporalKit_gallery_container"):
406 | with gr.TabItem(elem_id="output_TemporalKit", label="Output"):
407 | with gr.Row():
408 | result_image = gr.outputs.Image(type='pil')
409 | with gr.Row():
410 | runbutton = gr.Button("Run")
411 | with gr.Row():
412 | send_to_buttons = parameters_copypaste.create_buttons(["img2img"])
413 |
414 | try:
415 | parameters_copypaste.bind_buttons(send_to_buttons, result_image, [""])
416 | except:
417 | print("failed")
418 | pass
419 | parameters_copypaste.add_paste_fields("TemporalKit", result_image,None)
420 | runbutton.click(preprocess_video, [video,fps,batch_size,sides,resolution,batch_checkbox,max_keyframes,batch_folder,border_frames,ebsynth_mode,split_video,split_based_on_cuts], result_image)
421 |
422 |
423 | def show_textbox(option):
424 | if option == True:
425 | return gr.inputs.Textbox(lines=2, placeholder="Enter your text here")
426 | else:
427 | return False
428 |
429 | def create_diffusing_tab ():
430 | global diffuseimg
431 | with gr.Column(visible=True, elem_id="Processid") as second_panel:
432 | dummy_component = gr.Label(visible=False)
433 | with gr.Row():
434 | with gr.Tabs(elem_id="mode_TemporalKit"):
435 | with gr.Row():
436 | with gr.Tab(elem_id="input_diffuse", label="Generate"):
437 | with gr.Column():
438 | with gr.Row():
439 | input_image = gr.Image(label="Input_Image", elem_id="input_page2")
440 | input_video = gr.Video(label="Input Video", elem_id="input_videopage2")
441 | with gr.Row():
442 | read_last_settings = gr.Button("read_last_settings", elem_id="read_last_settings")
443 | read_last_image = gr.Button("read_last_image", elem_id="read_last_image")
444 | with gr.Row():
445 | fps = gr.Number(label="FPS",value=10,precision=1)
446 | per_side = gr.Number(label="per side",value=3,precision=1)
447 | output_resolution_single = gr.Number(label="output height resolution",value=1024,precision=1)
448 | batch_size_diffuse = gr.Number(label="batch size",value=10,precision=1)
449 | with gr.Row():
450 | runButton = gr.Button("run", elem_id="run_button")
451 |
452 |
453 | with gr.Tabs(elem_id="mode_TemporalKit"):
454 | with gr.Row():
455 | with gr.Tab(elem_id="input_diffuse", label="Output"):
456 | with gr.Column():
457 | #newbutton = gr.Button("update", elem_id="update_button")
458 | outputfile = gr.Video()
459 |
460 | read_last_image.click(
461 | fn=update_image,
462 | outputs=input_image
463 | )
464 | read_last_settings.click(
465 | fn=update_settings,
466 | outputs=[fps,per_side,batch_size_diffuse,input_video]
467 | )
468 | runButton.click(
469 | fn=apply_image_to_video,
470 | inputs=[input_image, input_video,fps,per_side,output_resolution_single,batch_size_diffuse],
471 | outputs=outputfile
472 | )
473 |
474 |
475 | def create_batch_tab ():
476 | with gr.Column(visible=True, elem_id="batch_process") as second_panel:
477 | with gr.Row():
478 | with gr.Tabs(elem_id="mode_TemporalKit"):
479 | with gr.Row():
480 | with gr.Tab(elem_id="input_diffuse", label="Generate Batch"):
481 | with gr.Column():
482 | with gr.Row():
483 | input_folder = gr.Textbox(label="Input Folder",placeholder="the whole folder, generated before, not just the output folder")
484 | input_video = gr.Video(label="Input Video", elem_id="input_videopage2")
485 | with gr.Row():
486 | read_last_settings = gr.Button("read_last_settings", elem_id="read_last_settings")
487 | with gr.Row():
488 | fps = gr.Number(label="FPS",value=10,precision=1)
489 | per_side = gr.Number(label="per side",value=3,precision=1)
490 | output_resolution_batch = gr.Number(label="output resolution",value=1024,precision=1)
491 | batch_size = gr.Number(label="batch size",value=5,precision=1)
492 | max_frames = gr.Number(label="max frames",value=100,precision=1)
493 | border_frames = gr.Number(label="border frames",value=1,precision=1)
494 | with gr.Row():
495 | runButton = gr.Button("run", elem_id="run_button")
496 |
497 |
498 |
499 | with gr.Tabs(elem_id="mode_TemporalKit"):
500 | with gr.Row():
501 | with gr.Tab(elem_id="input_diffuse", label="Output"):
502 | with gr.Column():
503 | #newbutton = gr.Button("update", elem_id="update_button")
504 | outputfile = gr.Video()
505 |
506 | read_last_settings.click(
507 | fn=update_settings_from_file,
508 | inputs=[input_folder],
509 | outputs=[fps,per_side,batch_size,input_video,max_frames,border_frames]
510 | )
511 | runButton.click(
512 | fn=apply_image_to_vide_batch,
513 | inputs=[input_folder,input_video,fps,per_side,output_resolution_batch,batch_size,max_frames,border_frames],
514 | outputs=outputfile
515 | )
516 |
517 |
518 | def create_ebsynth_tab():
519 | with gr.Column(visible=True, elem_id="batch_process") as second_panel:
520 | with gr.Row():
521 | with gr.Tabs(elem_id="mode_TemporalKit"):
522 | with gr.Row():
523 | with gr.Tab(elem_id="input_diffuse", label="Generate Batch"):
524 | with gr.Column():
525 | with gr.Row():
526 | input_folder = gr.Textbox(label="Input Folder",placeholder="the whole folder, generated before, not just the output folder")
527 | input_video = gr.Video(label="Input Video", elem_id="input_videopage2")
528 | with gr.Row():
529 | read_last_settings_synth = gr.Button("read_last_settings", elem_id="read_last_settings")
530 | with gr.Row():
531 | fps = gr.Number(label="FPS",value=10,precision=1)
532 | per_side = gr.Number(label="per side",value=3,precision=1)
533 | output_resolution_batch = gr.Number(label="output resolution",value=1024,precision=1)
534 | batch_size = gr.Number(label="batch size",value=5,precision=1)
535 | max_frames = gr.Number(label="max frames",value=100,precision=1)
536 | border_frames = gr.Number(value=1, label="Border Frames", precision=1, interactive=True,placeholder="border frames")
537 | with gr.Row():
538 | runButton = gr.Button("prepare ebsynth", elem_id="run_button")
539 | recombineButton = gr.Button("recombine ebsynth", elem_id="recombine_button")
540 | with gr.Tabs(elem_id="mode_TemporalKit"):
541 | with gr.Row():
542 | with gr.Tab(elem_id="input_diffuse", label="Output"):
543 | with gr.Column():
544 | #newbutton = gr.Button("update", elem_id="update_button")
545 | outputvideo = gr.File()
546 | read_last_settings_synth.click(
547 | fn=update_settings_from_file,
548 | inputs=[input_folder],
549 | outputs=[fps,per_side,batch_size,input_video,max_frames,border_frames]
550 | )
551 | runButton.click(
552 | fn=post_process_ebsynth,
553 | inputs=[input_folder,input_video,fps,per_side,output_resolution_batch,batch_size,max_frames,border_frames],
554 | outputs=outputvideo
555 | )
556 | recombineButton.click(
557 | fn=recombine_ebsynth,
558 | inputs=[input_folder,fps,border_frames,batch_size],
559 | outputs=outputvideo
560 | )
561 | tabs_list = ["TemporalKit"]
562 |
563 | def on_ui_tabs():
564 |
565 | with gr.Blocks(analytics_enabled=False) as temporalkit:
566 | with gr.Tabs(elem_id="TemporalKit-Tab") as tabs:
567 | with gr.Tab(label="Pre-Processing"):
568 | with gr.Blocks(analytics_enabled=False):
569 | create_video_Processing_Tab()
570 | with gr.Tab(label="Temporal-Warp",elem_id="processbutton"):
571 | with gr.Blocks(analytics_enabled=False):
572 | create_diffusing_tab()
573 | with gr.Tab(label="Batch-Warp",elem_id="batch-button"):
574 | with gr.Blocks(analytics_enabled=False):
575 | create_batch_tab()
576 | with gr.Tab(label="Ebsynth-Process",elem_id="Ebsynth-Process"):
577 | with gr.Blocks(analytics_enabled=False):
578 | create_ebsynth_tab()
579 | return (temporalkit, "Temporal-Kit", "TemporalKit"),
580 |
581 |
582 |
583 | def generate(
584 | input_image: Image.Image,
585 | instruction: str,
586 | steps: int,
587 | randomize_seed: bool,
588 | seed: int,
589 | randomize_cfg: bool,
590 | text_cfg_scale: float,
591 | image_cfg_scale: float,
592 | negative_prompt: str,
593 | batch_number: int,
594 | scale: int,
595 | batch_in_check,
596 | batch_in_dir,
597 | sampler
598 | ):
599 |
600 | model = shared.sd_model
601 | model.eval().to(shared.device)
602 |
603 | animated_gifs = []
604 |
605 |
606 | def on_ui_settings():
607 | section = ('TemporalKit', "Temporal-Kit")
608 | shared.opts.add_option("def_img_cfg", shared.OptionInfo("1.5", "Default Image CFG", section=('ip2p', "Instruct-pix2pix")))
609 |
610 |
611 |
612 | from fastapi import FastAPI, Body
613 | from base64 import b64decode, b64encode
614 | from io import BytesIO
615 |
616 | def img_to_b64(image: Image.Image):
617 | buf = BytesIO()
618 | image.save(buf, format="png")
619 | return b64encode(buf.getvalue()).decode("utf-8")
620 |
621 | def b64_to_img(enc: str):
622 | if enc.startswith('data:image'):
623 | enc = enc[enc.find(',')+1:]
624 | return Image.open(BytesIO(b64decode(enc)))
625 |
626 |
627 |
628 |
629 | script_callbacks.on_ui_settings(on_ui_settings)
630 | script_callbacks.on_ui_tabs(on_ui_tabs)
631 |
--------------------------------------------------------------------------------
/scripts/stable_diffusion_processing.py:
--------------------------------------------------------------------------------
1 | import os
2 | import glob
3 | import requests
4 | import json
5 | from pprint import pprint
6 | import base64
7 | import numpy as np
8 | from io import BytesIO
9 | import scripts.optical_flow_simple as opflow
10 | from PIL import Image, ImageOps,ImageFilter
11 | import io
12 | from collections import deque
13 | import scripts.berry_utility as utilityb
14 | import cv2
15 | import scripts.optical_flow_raft as raft
16 |
17 | # Replace with the actual path to your image file and folder
18 | x_path = "./init.png"
19 | y_folder = "./Input_Images"
20 | temp_folder = "./temp"
21 | frame_count = 0
22 |
23 | img2imgurl = "http://localhost:7860/sdapi/v1/img2img"
24 |
25 | output_folder = "output"
26 | os.makedirs(output_folder, exist_ok=True)
27 |
28 | if not os.path.exists('intensitymaps'):
29 | os.makedirs('intensitymaps')
30 |
31 | if not os.path.exists('temp'):
32 | os.makedirs('temp')
33 |
34 | y_paths = utilityb.get_image_paths(y_folder)
35 |
36 |
37 | # get the initial image
38 | def square_Image_request (image_path,prompt,denoise_strength,resolution,seed):
39 | print(len(image_path),prompt,denoise_strength,resolution,seed)
40 | data = {
41 | "init_images": [image_path],
42 | "resize_mode": 0,
43 | "denoising_strength": denoise_strength,
44 | "prompt": prompt,
45 | "negative_prompt": "",
46 | #"control_net_enabled": "true",
47 | "alwayson_scripts": {
48 | "ControlNet":{
49 | "args": [
50 | {
51 | "input_image": image_path,
52 | "module": "hed",
53 | # "model": "control_canny-fp16 [e3fe7712]",
54 | "model": "control_hed-fp16 [13fee50b]",
55 | "processor_res": 1024,
56 | "weight": 1
57 | }
58 | ]
59 | }
60 | },
61 | "seed": seed,
62 | "sampler_index": "Euler a",
63 | "batch_size": 1,
64 | "n_iter": 1,
65 | "steps": 20,
66 | "cfg_scale": 6,
67 | "width": resolution,
68 | "height": resolution,
69 | "restore_faces": True,
70 | "include_init_images": False,
71 | "override_settings": {},
72 | "override_settings_restore_afterwards": True
73 | }
74 | response = requests.post(img2imgurl, json=data)
75 | #print (response.content)
76 | print(len(json.loads(response.content)["images"]))
77 | if response.status_code == 200:
78 | return json.loads(response.content)["images"][0]
79 | else:
80 | try:
81 | error_data = response.json()
82 | print("Error:")
83 | print(str(error_data))
84 |
85 | except json.JSONDecodeError:
86 | error_data = response.content
87 | print(f"Error: Unable to parse JSON error data. {error_data}")
88 | return None
89 |
90 |
91 | def prepare_request(allpaths,index,last_stylized,resolution,seed,last_mask,last_last_mask,fillindenoise,edgedenoise,target,diffuse,forwards):
92 |
93 | warped_path,flow,unused_mask,whitepixels,flow_img = raft.apply_flow_based_on_images(allpaths[index - 1],allpaths[index],last_stylized,resolution,index,temp_folder)
94 |
95 | #warped_path,flow,unused_mask,whitepixels,flow_img = raft.apply_flow_based_on_images(allpaths[index - 1],allpaths[index],allpaths[index],resolution,index,temp_folder)
96 | if diffuse:
97 | hed = gethedfromsd(warped_path,resolution)
98 | hed = utilityb.mask_to_grayscale( utilityb.scale_mask_intensity(utilityb.base64_to_texture(hed),edgedenoise))
99 | #hardened_hed = utilityb.harden_mask(hed,True)
100 | # flow_adjusted_mask = utilityb.modify_intensity_based_on_flow(hardened_hed,flow)
101 | if last_mask is None:
102 | last_mask = np.zeros((resolution,resolution))
103 | if last_last_mask is None:
104 | last_last_mask = np.zeros((resolution,resolution))
105 | if diffuse:
106 | combined_mask = utilityb.combine_masks([unused_mask,utilityb.scale_mask_intensity(last_mask,0.6),utilityb.scale_mask_intensity(last_last_mask,0.3),hed])
107 | #combine_mask_no_hed = utilityb.combine_masks([unused_mask,utilityb.scale_mask_intensity(last_mask,0.6),utilityb.scale_mask_intensity(last_last_mask,0.3)])
108 | #if whitepixels > 0:
109 | #replaced = utilityb.replace_masked_area(flow,index,warped_path,unused_mask,warped_path)
110 | if target is not None and index > 1:
111 | replaced = utilityb.replaced_mask_from_other_direction_debug(index,Image.open(warped_path).convert("RGBA"),unused_mask,flow,Image.fromarray(cv2.cvtColor(utilityb.base64_to_texture( target), cv2.COLOR_BGR2RGB)).convert("RGBA"),forwards)
112 | else:
113 | replaced = utilityb.replaced_mask_from_other_direction_debug(index,Image.open(warped_path).convert("RGBA"),unused_mask,flow,None)
114 | #else:
115 | # replaced = warped_path
116 | #replaced = replace_masked_area(flow,index,last_stylized,hed,allpaths[index])
117 |
118 |
119 | # Save the mask as a PNG file in the temporary folder
120 | file_path = os.path.join("debug2", f'mask{index}.png')
121 | cv2.imwrite(file_path, unused_mask)
122 |
123 |
124 |
125 | if diffuse:
126 | return send_request_in_chain(last_stylized,allpaths[index],replaced,utilityb.texture_to_base64(combined_mask),index,seed,fillindenoise,resolution),unused_mask,flow_img
127 | else:
128 | return replaced, unused_mask,flow_img
129 | # return send_request(last_stylized,y_folder,allpaths[index],replaced,hed,index)
130 |
131 |
132 | # Send the request for hed map from the server based on a filepath
133 | def gethedfromsd(image_path,resolution):
134 | print(resolution)
135 | #with open(image_path, "rb") as f:
136 | # image = base64.b64encode(f.read()).decode("utf-8")
137 | image_smol = utilityb.resize_base64_image(image_path,resolution,resolution)
138 | url = "http://127.0.0.1:7860/controlnet/detect"
139 | data2 = {
140 | "controlnet_module": "hed",
141 | "controlnet_input_images": [image_smol],
142 | "controlnet_processor_res": resolution,
143 | }
144 |
145 | response = requests.post(url, json=data2)
146 | if response.status_code == 200:
147 | data = response.content
148 | loaded = json.loads(data)
149 | #print(response.content)
150 | encoded_image = loaded["images"][0]
151 | #print(f"encoded: {encoded_image}")
152 |
153 | return encoded_image
154 | elif response.status_code == 422:
155 | error = response.json()
156 | print("Validation error:", error)
157 | else:
158 | print("Unexpected error from hed:", response.status_code, response.text)
159 |
160 |
161 |
162 |
163 |
164 | #send based on current situation
165 | def send_request_in_chain(last_image_path,current_image_path,last_warped_path,mask,index,seed,fillindenoise,resolution):
166 |
167 | # with open(last_image_path, "rb") as f:
168 | # last_image = base64.b64encode(f.read()).decode("utf-8")
169 | # last_image = last_image_path
170 | #with open(current_image_path, "rb") as b:
171 | # current_image = base64.b64encode(b.read()).decode("utf-8")
172 | current_image = current_image_path
173 |
174 | if not last_warped_path == "":
175 | if os.path.isfile(last_warped_path):
176 | with open(last_warped_path, "rb") as c:
177 | last_warped = base64.b64encode(c.read()).decode("utf-8")
178 | else:
179 | last_warped = last_warped_path
180 | else:
181 | last_warped = current_image
182 |
183 |
184 |
185 |
186 | data = {
187 | "init_images": [last_warped],
188 | "inpainting_fill": 1,
189 | "inpaint_full_res": False,
190 | "inpaint_full_res_padding": 1,
191 | "inpainting_mask_invert": 0,
192 | "resize_mode": 0,
193 | "denoising_strength": fillindenoise,
194 | "prompt":"",
195 | "negative_prompt": "(ugly:1.3), (fused fingers), (too many fingers), (bad anatomy:1.5), (watermark:1.5), (words), letters, untracked eyes, asymmetric eyes, floating head, (logo:1.5), (bad hands:1.3), (mangled hands:1.2), (missing hands), (missing arms), backward hands, floating jewelry, unattached jewelry, floating head, doubled head, unattached head, doubled head, head in body, (misshapen body:1.1), (badly fitted headwear:1.2), floating arms, (too many arms:1.5), limbs fused with body, (facial blemish:1.5), badly fitted clothes, imperfect eyes, untracked eyes, crossed eyes, hair growing from clothes, partial faces, hair not attached to head",
196 | "alwayson_scripts": {
197 | "ControlNet":{
198 | "args": [
199 | {
200 | "input_image": current_image,
201 | "module": "hed",
202 | "model": "control_hed-fp16 [13fee50b]",
203 | "weight": 1,
204 | "guidance": 1,
205 | },
206 | {
207 | "input_image": last_warped,
208 | "model": "diff_control_sd15_temporalnet_fp16 [adc6bd97]",
209 | "module": "none",
210 | "weight": 1,
211 | "guidance": 1,
212 | }
213 |
214 | ]
215 | }
216 | },
217 | "seed": seed,
218 | "subseed": -1,
219 | "subseed_strength": -1,
220 | "sampler_index": "Euler a",
221 | "batch_size": 1,
222 | "n_iter": 1,
223 | "steps": 20,
224 | "cfg_scale": 6,
225 | "width": resolution,
226 | "height": resolution,
227 | "restore_faces": True,
228 | "include_init_images": True,
229 | "override_settings": {},
230 | "override_settings_restore_afterwards": True
231 | }
232 |
233 | if not mask == "":
234 | data["mask"] = mask
235 | if not os.path.exists("./debug2/"):
236 | os.makedirs("./debug2/")
237 | with open(f"./debug2/{index}.png", "wb") as e:
238 | e.write(base64.b64decode(mask))
239 | print(f"debug mask saved at ./debug2/{index}.png")
240 | else:
241 | data['denoising_strength'] = 0
242 | response = requests.post(img2imgurl, json=data)
243 | # print (response.content)
244 | print(response.status_code)
245 | if response.status_code == 200:
246 | return json.loads(response.content)["images"][0]
247 | else:
248 | try:
249 | error_data = response.json()
250 | print("Error:")
251 | print(str(error_data))
252 |
253 | except json.JSONDecodeError:
254 | error_data = response.content
255 | print(f"Error: Unable to parse JSON error data. {error_data}")
256 | return None
257 |
258 |
259 | def batch_sd_run (y_paths, initial,count,seed,skip_first,fillindenoise,edgedenoise,smol_resolution,Forwards,target,diffuse):
260 | output_images = []
261 | all_flow = []
262 | output_images.append(initial)
263 | last_mask = None
264 | last_last_mask = None
265 | allpaths = y_paths
266 | for i in range(1, len(y_paths)):
267 | current_frame = count + i
268 | result,mask,flow = prepare_request(allpaths,i,output_images[i-1],smol_resolution,seed,last_mask,last_last_mask,fillindenoise,edgedenoise,target,diffuse,Forwards)
269 | all_flow.append(flow)
270 | output_images.append(result)
271 | print(f"Written data for frame {current_frame}:")
272 | last_last_mask = last_mask
273 | last_mask = mask
274 | if (skip_first == True):
275 | output_images.pop(0)
276 |
277 |
278 |
279 | return output_images,all_flow
280 |
281 |
282 | #output_images = []
283 | #datanew = send_request_in_chain(y_paths[0], x_path,"","",0)
284 | #output_images.append(datanew)
285 | #output_paths = []
286 |
287 | #for i in range(1, len(y_paths)):
288 | # frame_count = frame_count + 1
289 | # result_image = output_images[i-1]
290 | # temp_image_path = os.path.join(output_folder, f"temp_image_{i}.png")
291 | # data = json.loads(result_image)
292 | # encoded_image = data["images"][0]
293 | # with open(temp_image_path, "wb") as f:
294 | # f.write(base64.b64decode(encoded_image))
295 | # output_paths.append(temp_image_path)
296 | # #result = send_request(temp_image_path, y_folder, y_paths[i])
297 | # result = prepare_request(y_paths,i,temp_image_path,512)
298 | # output_images.append(result)
299 | # print(f"Written data for frame {i}:")
300 |
301 |
302 |
--------------------------------------------------------------------------------
/style.css:
--------------------------------------------------------------------------------
1 | video.svelte-1vnmhm4 {
2 | max-height: 500px;
3 | }
--------------------------------------------------------------------------------
/temp_file.txt:
--------------------------------------------------------------------------------
1 | 10
2 | 3
3 | 5
4 | C:\Users\crowl\AppData\Local\Temp\f9a5b76a71d3fb93d978662b3488fbd4a4fd00fc\006f4310-402eea6f.mp4
5 |
--------------------------------------------------------------------------------