disco.py 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623
  1. # %%
  2. # !! {"metadata": {
  3. # !! "id": "view-in-github",
  4. # !! "colab_type": "text"
  5. # !! }}
  6. """
  7. <a href="https://colab.research.google.com/github/alembics/disco-diffusion/blob/main/Disco_Diffusion.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
  8. """
  9. # %%
  10. # !! {"metadata": {
  11. # !! "id": "TitleTop"
  12. # !! }}
  13. """
  14. # Disco Diffusion v5.2 - Now with VR Mode
  15. In case of confusion, Disco is the name of this notebook edit. The diffusion model in use is Katherine Crowson's fine-tuned 512x512 model
  16. For issues, join the [Disco Diffusion Discord](https://discord.gg/msEZBy4HxA) or message us on twitter at [@somnai_dreams](https://twitter.com/somnai_dreams) or [@gandamu](https://twitter.com/gandamu_ml)
  17. """
  18. # %%
  19. # !! {"metadata": {
  20. # !! "id": "CreditsChTop"
  21. # !! }}
  22. """
  23. ### Credits & Changelog ⬇️
  24. """
  25. # %%
  26. # !! {"metadata": {
  27. # !! "id": "Credits"
  28. # !! }}
  29. """
  30. #### Credits
  31. Original notebook by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). It uses either OpenAI's 256x256 unconditional ImageNet or Katherine Crowson's fine-tuned 512x512 diffusion model (https://github.com/openai/guided-diffusion), together with CLIP (https://github.com/openai/CLIP) to connect text prompts with images.
  32. Modified by Daniel Russell (https://github.com/russelldc, https://twitter.com/danielrussruss) to include (hopefully) optimal params for quick generations in 15-100 timesteps rather than 1000, as well as more robust augmentations.
  33. Further improvements from Dango233 and nsheppard helped improve the quality of diffusion in general, and especially so for shorter runs like this notebook aims to achieve.
  34. Vark added code to load in multiple Clip models at once, which all prompts are evaluated against, which may greatly improve accuracy.
  35. The latest zoom, pan, rotation, and keyframes features were taken from Chigozie Nri's VQGAN Zoom Notebook (https://github.com/chigozienri, https://twitter.com/chigozienri)
  36. Advanced DangoCutn Cutout method is also from Dango223.
  37. --
  38. Disco:
  39. Somnai (https://twitter.com/Somnai_dreams) added Diffusion Animation techniques, QoL improvements and various implementations of tech and techniques, mostly listed in the changelog below.
  40. 3D animation implementation added by Adam Letts (https://twitter.com/gandamu_ml) in collaboration with Somnai. Creation of disco.py and ongoing maintenance.
  41. Turbo feature by Chris Allen (https://twitter.com/zippy731)
  42. Improvements to ability to run on local systems, Windows support, and dependency installation by HostsServer (https://twitter.com/HostsServer)
  43. VR Mode by Tom Mason (https://twitter.com/nin_artificial)
  44. """
  45. # %%
  46. # !! {"metadata": {
  47. # !! "id": "LicenseTop"
  48. # !! }}
  49. """
  50. #### License
  51. """
  52. # %%
  53. # !! {"metadata": {
  54. # !! "id": "License"
  55. # !! }}
  56. """
  57. Licensed under the MIT License
  58. Copyright (c) 2021 Katherine Crowson
  59. Permission is hereby granted, free of charge, to any person obtaining a copy
  60. of this software and associated documentation files (the "Software"), to deal
  61. in the Software without restriction, including without limitation the rights
  62. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  63. copies of the Software, and to permit persons to whom the Software is
  64. furnished to do so, subject to the following conditions:
  65. The above copyright notice and this permission notice shall be included in
  66. all copies or substantial portions of the Software.
  67. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  68. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  69. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  70. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  71. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  72. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  73. THE SOFTWARE.
  74. --
  75. MIT License
  76. Copyright (c) 2019 Intel ISL (Intel Intelligent Systems Lab)
  77. Permission is hereby granted, free of charge, to any person obtaining a copy
  78. of this software and associated documentation files (the "Software"), to deal
  79. in the Software without restriction, including without limitation the rights
  80. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  81. copies of the Software, and to permit persons to whom the Software is
  82. furnished to do so, subject to the following conditions:
  83. The above copyright notice and this permission notice shall be included in all
  84. copies or substantial portions of the Software.
  85. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  86. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  87. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  88. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  89. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  90. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  91. SOFTWARE.
  92. --
  93. Licensed under the MIT License
  94. Copyright (c) 2021 Maxwell Ingham
  95. Copyright (c) 2022 Adam Letts
  96. Permission is hereby granted, free of charge, to any person obtaining a copy
  97. of this software and associated documentation files (the "Software"), to deal
  98. in the Software without restriction, including without limitation the rights
  99. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  100. copies of the Software, and to permit persons to whom the Software is
  101. furnished to do so, subject to the following conditions:
  102. The above copyright notice and this permission notice shall be included in
  103. all copies or substantial portions of the Software.
  104. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  105. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  106. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  107. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  108. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  109. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  110. THE SOFTWARE.
  111. """
  112. # %%
  113. # !! {"metadata": {
  114. # !! "id": "ChangelogTop"
  115. # !! }}
  116. """
  117. #### Changelog
  118. """
  119. # %%
  120. # !! {"metadata": {
  121. # !! "cellView": "form",
  122. # !! "id": "Changelog"
  123. # !! }}
  124. #@title <- View Changelog
  125. skip_for_run_all = True #@param {type: 'boolean'}
  126. if skip_for_run_all == False:
  127. print(
  128. '''
  129. v1 Update: Oct 29th 2021 - Somnai
  130. QoL improvements added by Somnai (@somnai_dreams), including user friendly UI, settings+prompt saving and improved google drive folder organization.
  131. v1.1 Update: Nov 13th 2021 - Somnai
  132. Now includes sizing options, intermediate saves and fixed image prompts and perlin inits. unexposed batch option since it doesn't work
  133. v2 Update: Nov 22nd 2021 - Somnai
  134. Initial addition of Katherine Crowson's Secondary Model Method (https://colab.research.google.com/drive/1mpkrhOjoyzPeSWy2r7T8EYRaU7amYOOi#scrollTo=X5gODNAMEUCR)
  135. Noticed settings were saving with the wrong name so corrected it. Let me know if you preferred the old scheme.
  136. v3 Update: Dec 24th 2021 - Somnai
  137. Implemented Dango's advanced cutout method
  138. Added SLIP models, thanks to NeuralDivergent
  139. Fixed issue with NaNs resulting in black images, with massive help and testing from @Softology
  140. Perlin now changes properly within batches (not sure where this perlin_regen code came from originally, but thank you)
  141. v4 Update: Jan 2021 - Somnai
  142. Implemented Diffusion Zooming
  143. Added Chigozie keyframing
  144. Made a bunch of edits to processes
  145. v4.1 Update: Jan 14th 2021 - Somnai
  146. Added video input mode
  147. Added license that somehow went missing
  148. Added improved prompt keyframing, fixed image_prompts and multiple prompts
  149. Improved UI
  150. Significant under the hood cleanup and improvement
  151. Refined defaults for each mode
  152. Added latent-diffusion SuperRes for sharpening
  153. Added resume run mode
  154. v4.9 Update: Feb 5th 2022 - gandamu / Adam Letts
  155. Added 3D
  156. Added brightness corrections to prevent animation from steadily going dark over time
  157. v4.91 Update: Feb 19th 2022 - gandamu / Adam Letts
  158. Cleaned up 3D implementation and made associated args accessible via Colab UI elements
  159. v4.92 Update: Feb 20th 2022 - gandamu / Adam Letts
  160. Separated transform code
  161. v5.01 Update: Mar 10th 2022 - gandamu / Adam Letts
  162. IPython magic commands replaced by Python code
  163. v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts
  164. Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults.
  165. Implemented resume of turbo animations in such a way that it's now possible to resume from different batch folders and batch numbers.
  166. 3D rotation parameter units are now degrees (rather than radians)
  167. Corrected name collision in sampling_mode (now diffusion_sampling_mode for plms/ddim, and sampling_mode for 3D transform sampling)
  168. Added video_init_seed_continuity option to make init video animations more continuous
  169. v5.1 Update: Apr 4th 2022 - MSFTserver aka HostsServer
  170. Removed pytorch3d from needing to be compiled with a lite version specifically made for Disco Diffusion
  171. Remove Super Resolution
  172. Remove SLIP Models
  173. Update for crossplatform support
  174. v5.2 Update: Apr 10th 2022 - nin_artificial / Tom Mason
  175. VR Mode
  176. '''
  177. )
  178. # %%
  179. # !! {"metadata": {
  180. # !! "id": "TutorialTop"
  181. # !! }}
  182. """
  183. # Tutorial
  184. """
  185. # %%
  186. # !! {"metadata": {
  187. # !! "id": "DiffusionSet"
  188. # !! }}
  189. """
  190. **Diffusion settings (Defaults are heavily outdated)**
  191. ---
  192. Disco Diffusion is complex, and continually evolving with new features. The most current documentation on on Disco Diffusion settings can be found in the unofficial guidebook:
  193. [Zippy's Disco Diffusion Cheatsheet](https://docs.google.com/document/d/1l8s7uS2dGqjztYSjPpzlmXLjl5PM3IGkRWI3IiCuK7g/edit)
  194. We also encourage users to join the [Disco Diffusion User Discord](https://discord.gg/XGZrFFCRfN) to learn from the active user community.
  195. This section below is outdated as of v2
  196. Setting | Description | Default
  197. --- | --- | ---
  198. **Your vision:**
  199. `text_prompts` | A description of what you'd like the machine to generate. Think of it like writing the caption below your image on a website. | N/A
  200. `image_prompts` | Think of these images more as a description of their contents. | N/A
  201. **Image quality:**
  202. `clip_guidance_scale` | Controls how much the image should look like the prompt. | 1000
  203. `tv_scale` | Controls the smoothness of the final output. | 150
  204. `range_scale` | Controls how far out of range RGB values are allowed to be. | 150
  205. `sat_scale` | Controls how much saturation is allowed. From nshepperd's JAX notebook. | 0
  206. `cutn` | Controls how many crops to take from the image. | 16
  207. `cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts. | 2
  208. **Init settings:**
  209. `init_image` | URL or local path | None
  210. `init_scale` | This enhances the effect of the init image, a good value is 1000 | 0
  211. `skip_steps` | Controls the starting point along the diffusion timesteps | 0
  212. `perlin_init` | Option to start with random perlin noise | False
  213. `perlin_mode` | ('gray', 'color') | 'mixed'
  214. **Advanced:**
  215. `skip_augs` | Controls whether to skip torchvision augmentations | False
  216. `randomize_class` | Controls whether the imagenet class is randomly changed each iteration | True
  217. `clip_denoised` | Determines whether CLIP discriminates a noisy or denoised image | False
  218. `clamp_grad` | Experimental: Using adaptive clip grad in the cond_fn | True
  219. `seed` | Choose a random seed and print it at end of run for reproduction | random_seed
  220. `fuzzy_prompt` | Controls whether to add multiple noisy prompts to the prompt losses | False
  221. `rand_mag` | Controls the magnitude of the random noise | 0.1
  222. `eta` | DDIM hyperparameter | 0.5
  223. ..
  224. **Model settings**
  225. ---
  226. Setting | Description | Default
  227. --- | --- | ---
  228. **Diffusion:**
  229. `timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100
  230. `diffusion_steps` || 1000
  231. **Diffusion:**
  232. `clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4
  233. """
  234. # %%
  235. # !! {"metadata": {
  236. # !! "id": "SetupTop"
  237. # !! }}
  238. """
  239. # 1. Set Up
  240. """
  241. # %%
  242. # !! {"metadata": {
  243. # !! "cellView": "form",
  244. # !! "id": "CheckGPU"
  245. # !! }}
  246. #@title 1.1 Check GPU Status
  247. import subprocess
  248. simple_nvidia_smi_display = False#@param {type:"boolean"}
  249. if simple_nvidia_smi_display:
  250. #!nvidia-smi
  251. nvidiasmi_output = subprocess.run(['nvidia-smi', '-L'], stdout=subprocess.PIPE).stdout.decode('utf-8')
  252. print(nvidiasmi_output)
  253. else:
  254. #!nvidia-smi -i 0 -e 0
  255. nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8')
  256. print(nvidiasmi_output)
  257. nvidiasmi_ecc_note = subprocess.run(['nvidia-smi', '-i', '0', '-e', '0'], stdout=subprocess.PIPE).stdout.decode('utf-8')
  258. print(nvidiasmi_ecc_note)
  259. # %%
  260. # !! {"metadata": {
  261. # !! "cellView": "form",
  262. # !! "id": "PrepFolders"
  263. # !! }}
  264. #@title 1.2 Prepare Folders
  265. import subprocess, os, sys, ipykernel
  266. def gitclone(url):
  267. res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8')
  268. print(res)
  269. def pipi(modulestr):
  270. res = subprocess.run(['pip', 'install', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')
  271. print(res)
  272. def pipie(modulestr):
  273. res = subprocess.run(['git', 'install', '-e', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')
  274. print(res)
  275. def wget(url, outputdir):
  276. res = subprocess.run(['wget', url, '-P', f'{outputdir}'], stdout=subprocess.PIPE).stdout.decode('utf-8')
  277. print(res)
  278. try:
  279. from google.colab import drive
  280. print("Google Colab detected. Using Google Drive.")
  281. is_colab = True
  282. #@markdown If you connect your Google Drive, you can save the final image of each run on your drive.
  283. google_drive = True #@param {type:"boolean"}
  284. #@markdown Click here if you'd like to save the diffusion model checkpoint file to (and/or load from) your Google Drive:
  285. save_models_to_google_drive = True #@param {type:"boolean"}
  286. except:
  287. is_colab = False
  288. google_drive = False
  289. save_models_to_google_drive = False
  290. print("Google Colab not detected.")
  291. if is_colab:
  292. if google_drive is True:
  293. drive.mount('/content/drive')
  294. root_path = '/content/drive/MyDrive/AI/Disco_Diffusion'
  295. else:
  296. root_path = '/content'
  297. else:
  298. root_path = os.getcwd()
  299. import os
  300. def createPath(filepath):
  301. os.makedirs(filepath, exist_ok=True)
  302. initDirPath = f'{root_path}/init_images'
  303. createPath(initDirPath)
  304. outDirPath = f'{root_path}/images_out'
  305. createPath(outDirPath)
  306. if is_colab:
  307. if google_drive and not save_models_to_google_drive or not google_drive:
  308. model_path = '/content/models'
  309. createPath(model_path)
  310. if google_drive and save_models_to_google_drive:
  311. model_path = f'{root_path}/models'
  312. createPath(model_path)
  313. else:
  314. model_path = f'{root_path}/models'
  315. createPath(model_path)
  316. # libraries = f'{root_path}/libraries'
  317. # createPath(libraries)
  318. # %%
  319. # !! {"metadata": {
  320. # !! "cellView": "form",
  321. # !! "id": "InstallDeps"
  322. # !! }}
  323. #@title ### 1.3 Install and import dependencies
  324. import pathlib, shutil, os, sys
  325. if not is_colab:
  326. # If running locally, there's a good chance your env will need this in order to not crash upon np.matmul() or similar operations.
  327. os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'
  328. PROJECT_DIR = os.path.abspath(os.getcwd())
  329. USE_ADABINS = True
  330. if is_colab:
  331. if google_drive is not True:
  332. root_path = f'/content'
  333. model_path = '/content/models'
  334. else:
  335. root_path = os.getcwd()
  336. model_path = f'{root_path}/models'
  337. model_256_downloaded = False
  338. model_512_downloaded = False
  339. model_secondary_downloaded = False
  340. multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy', 'einops', 'pytorch-lightning', 'omegaconf'], stdout=subprocess.PIPE).stdout.decode('utf-8')
  341. print(multipip_res)
  342. if is_colab:
  343. subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8')
  344. try:
  345. from CLIP import clip
  346. except:
  347. if not os.path.exists("CLIP"):
  348. gitclone("https://github.com/openai/CLIP")
  349. sys.path.append(f'{PROJECT_DIR}/CLIP')
  350. try:
  351. from guided_diffusion.script_util import create_model_and_diffusion
  352. except:
  353. if not os.path.exists("guided-diffusion"):
  354. gitclone("https://github.com/crowsonkb/guided-diffusion")
  355. sys.path.append(f'{PROJECT_DIR}/guided-diffusion')
  356. try:
  357. from resize_right import resize
  358. except:
  359. if not os.path.exists("ResizeRight"):
  360. gitclone("https://github.com/assafshocher/ResizeRight.git")
  361. sys.path.append(f'{PROJECT_DIR}/ResizeRight')
  362. try:
  363. import py3d_tools
  364. except:
  365. if not os.path.exists('pytorch3d-lite'):
  366. gitclone("https://github.com/MSFTserver/pytorch3d-lite.git")
  367. sys.path.append(f'{PROJECT_DIR}/pytorch3d-lite')
  368. try:
  369. from midas.dpt_depth import DPTDepthModel
  370. except:
  371. if not os.path.exists('MiDaS'):
  372. gitclone("https://github.com/isl-org/MiDaS.git")
  373. if not os.path.exists('MiDaS/midas_utils.py'):
  374. shutil.move('MiDaS/utils.py', 'MiDaS/midas_utils.py')
  375. if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):
  376. wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", model_path)
  377. sys.path.append(f'{PROJECT_DIR}/MiDaS')
  378. try:
  379. sys.path.append(PROJECT_DIR)
  380. import disco_xform_utils as dxf
  381. except:
  382. if not os.path.exists("disco-diffusion"):
  383. gitclone("https://github.com/alembics/disco-diffusion.git")
  384. if os.path.exists('disco_xform_utils.py') is not True:
  385. shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py')
  386. sys.path.append(PROJECT_DIR)
  387. import torch
  388. from dataclasses import dataclass
  389. from functools import partial
  390. import cv2
  391. import pandas as pd
  392. import gc
  393. import io
  394. import math
  395. import timm
  396. from IPython import display
  397. import lpips
  398. from PIL import Image, ImageOps
  399. import requests
  400. from glob import glob
  401. import json
  402. from types import SimpleNamespace
  403. from torch import nn
  404. from torch.nn import functional as F
  405. import torchvision.transforms as T
  406. import torchvision.transforms.functional as TF
  407. from tqdm.notebook import tqdm
  408. from CLIP import clip
  409. from resize_right import resize
  410. from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults
  411. from datetime import datetime
  412. import numpy as np
  413. import matplotlib.pyplot as plt
  414. import random
  415. from ipywidgets import Output
  416. import hashlib
  417. from functools import partial
  418. if is_colab:
  419. os.chdir('/content')
  420. from google.colab import files
  421. else:
  422. os.chdir(f'{PROJECT_DIR}')
  423. from IPython.display import Image as ipyimg
  424. from numpy import asarray
  425. from einops import rearrange, repeat
  426. import torch, torchvision
  427. import time
  428. from omegaconf import OmegaConf
  429. import warnings
  430. warnings.filterwarnings("ignore", category=UserWarning)
  431. # AdaBins stuff
  432. if USE_ADABINS:
  433. try:
  434. from infer import InferenceHelper
  435. except:
  436. if os.path.exists("AdaBins") is not True:
  437. gitclone("https://github.com/shariqfarooq123/AdaBins.git")
  438. if not os.path.exists(f'{PROJECT_DIR}/pretrained/AdaBins_nyu.pt'):
  439. createPath(f'{PROJECT_DIR}/pretrained')
  440. wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", f'{PROJECT_DIR}/pretrained')
  441. sys.path.append(f'{PROJECT_DIR}/AdaBins')
  442. from infer import InferenceHelper
  443. MAX_ADABINS_AREA = 500000
  444. import torch
  445. DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
  446. print('Using device:', DEVICE)
  447. device = DEVICE # At least one of the modules expects this name..
  448. if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad
  449. print('Disabling CUDNN for A100 gpu', file=sys.stderr)
  450. torch.backends.cudnn.enabled = False
  451. # %%
  452. # !! {"metadata": {
  453. # !! "cellView": "form",
  454. # !! "id": "DefMidasFns"
  455. # !! }}
  456. #@title ### 1.4 Define Midas functions
  457. from midas.dpt_depth import DPTDepthModel
  458. from midas.midas_net import MidasNet
  459. from midas.midas_net_custom import MidasNet_small
  460. from midas.transforms import Resize, NormalizeImage, PrepareForNet
  461. # Initialize MiDaS depth model.
  462. # It remains resident in VRAM and likely takes around 2GB VRAM.
  463. # You could instead initialize it for each frame (and free it after each frame) to save VRAM.. but initializing it is slow.
  464. default_models = {
  465. "midas_v21_small": f"{model_path}/midas_v21_small-70d6b9c8.pt",
  466. "midas_v21": f"{model_path}/midas_v21-f6b98070.pt",
  467. "dpt_large": f"{model_path}/dpt_large-midas-2f21e586.pt",
  468. "dpt_hybrid": f"{model_path}/dpt_hybrid-midas-501f0c75.pt",
  469. "dpt_hybrid_nyu": f"{model_path}/dpt_hybrid_nyu-2ce69ec7.pt",}
  470. def init_midas_depth_model(midas_model_type="dpt_large", optimize=True):
  471. midas_model = None
  472. net_w = None
  473. net_h = None
  474. resize_mode = None
  475. normalization = None
  476. print(f"Initializing MiDaS '{midas_model_type}' depth model...")
  477. # load network
  478. midas_model_path = default_models[midas_model_type]
  479. if midas_model_type == "dpt_large": # DPT-Large
  480. midas_model = DPTDepthModel(
  481. path=midas_model_path,
  482. backbone="vitl16_384",
  483. non_negative=True,
  484. )
  485. net_w, net_h = 384, 384
  486. resize_mode = "minimal"
  487. normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
  488. elif midas_model_type == "dpt_hybrid": #DPT-Hybrid
  489. midas_model = DPTDepthModel(
  490. path=midas_model_path,
  491. backbone="vitb_rn50_384",
  492. non_negative=True,
  493. )
  494. net_w, net_h = 384, 384
  495. resize_mode="minimal"
  496. normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
  497. elif midas_model_type == "dpt_hybrid_nyu": #DPT-Hybrid-NYU
  498. midas_model = DPTDepthModel(
  499. path=midas_model_path,
  500. backbone="vitb_rn50_384",
  501. non_negative=True,
  502. )
  503. net_w, net_h = 384, 384
  504. resize_mode="minimal"
  505. normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
  506. elif midas_model_type == "midas_v21":
  507. midas_model = MidasNet(midas_model_path, non_negative=True)
  508. net_w, net_h = 384, 384
  509. resize_mode="upper_bound"
  510. normalization = NormalizeImage(
  511. mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
  512. )
  513. elif midas_model_type == "midas_v21_small":
  514. midas_model = MidasNet_small(midas_model_path, features=64, backbone="efficientnet_lite3", exportable=True, non_negative=True, blocks={'expand': True})
  515. net_w, net_h = 256, 256
  516. resize_mode="upper_bound"
  517. normalization = NormalizeImage(
  518. mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
  519. )
  520. else:
  521. print(f"midas_model_type '{midas_model_type}' not implemented")
  522. assert False
  523. midas_transform = T.Compose(
  524. [
  525. Resize(
  526. net_w,
  527. net_h,
  528. resize_target=None,
  529. keep_aspect_ratio=True,
  530. ensure_multiple_of=32,
  531. resize_method=resize_mode,
  532. image_interpolation_method=cv2.INTER_CUBIC,
  533. ),
  534. normalization,
  535. PrepareForNet(),
  536. ]
  537. )
  538. midas_model.eval()
  539. if optimize==True:
  540. if DEVICE == torch.device("cuda"):
  541. midas_model = midas_model.to(memory_format=torch.channels_last)
  542. midas_model = midas_model.half()
  543. midas_model.to(DEVICE)
  544. print(f"MiDaS '{midas_model_type}' depth model initialized.")
  545. return midas_model, midas_transform, net_w, net_h, resize_mode, normalization
  546. # %%
  547. # !! {"metadata": {
  548. # !! "cellView": "form",
  549. # !! "id": "DefFns"
  550. # !! }}
  551. #@title 1.5 Define necessary functions
  552. # https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869
  553. import py3d_tools as p3dT
  554. import disco_xform_utils as dxf
  555. def interp(t):
  556. return 3 * t**2 - 2 * t ** 3
  557. def perlin(width, height, scale=10, device=None):
  558. gx, gy = torch.randn(2, width + 1, height + 1, 1, 1, device=device)
  559. xs = torch.linspace(0, 1, scale + 1)[:-1, None].to(device)
  560. ys = torch.linspace(0, 1, scale + 1)[None, :-1].to(device)
  561. wx = 1 - interp(xs)
  562. wy = 1 - interp(ys)
  563. dots = 0
  564. dots += wx * wy * (gx[:-1, :-1] * xs + gy[:-1, :-1] * ys)
  565. dots += (1 - wx) * wy * (-gx[1:, :-1] * (1 - xs) + gy[1:, :-1] * ys)
  566. dots += wx * (1 - wy) * (gx[:-1, 1:] * xs - gy[:-1, 1:] * (1 - ys))
  567. dots += (1 - wx) * (1 - wy) * (-gx[1:, 1:] * (1 - xs) - gy[1:, 1:] * (1 - ys))
  568. return dots.permute(0, 2, 1, 3).contiguous().view(width * scale, height * scale)
  569. def perlin_ms(octaves, width, height, grayscale, device=device):
  570. out_array = [0.5] if grayscale else [0.5, 0.5, 0.5]
  571. # out_array = [0.0] if grayscale else [0.0, 0.0, 0.0]
  572. for i in range(1 if grayscale else 3):
  573. scale = 2 ** len(octaves)
  574. oct_width = width
  575. oct_height = height
  576. for oct in octaves:
  577. p = perlin(oct_width, oct_height, scale, device)
  578. out_array[i] += p * oct
  579. scale //= 2
  580. oct_width *= 2
  581. oct_height *= 2
  582. return torch.cat(out_array)
  583. def create_perlin_noise(octaves=[1, 1, 1, 1], width=2, height=2, grayscale=True):
  584. out = perlin_ms(octaves, width, height, grayscale)
  585. if grayscale:
  586. out = TF.resize(size=(side_y, side_x), img=out.unsqueeze(0))
  587. out = TF.to_pil_image(out.clamp(0, 1)).convert('RGB')
  588. else:
  589. out = out.reshape(-1, 3, out.shape[0]//3, out.shape[1])
  590. out = TF.resize(size=(side_y, side_x), img=out)
  591. out = TF.to_pil_image(out.clamp(0, 1).squeeze())
  592. out = ImageOps.autocontrast(out)
  593. return out
  594. def regen_perlin():
  595. if perlin_mode == 'color':
  596. init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
  597. init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)
  598. elif perlin_mode == 'gray':
  599. init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)
  600. init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
  601. else:
  602. init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
  603. init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
  604. init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)
  605. del init2
  606. return init.expand(batch_size, -1, -1, -1)
  607. def fetch(url_or_path):
  608. if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'):
  609. r = requests.get(url_or_path)
  610. r.raise_for_status()
  611. fd = io.BytesIO()
  612. fd.write(r.content)
  613. fd.seek(0)
  614. return fd
  615. return open(url_or_path, 'rb')
  616. def read_image_workaround(path):
  617. """OpenCV reads images as BGR, Pillow saves them as RGB. Work around
  618. this incompatibility to avoid colour inversions."""
  619. im_tmp = cv2.imread(path)
  620. return cv2.cvtColor(im_tmp, cv2.COLOR_BGR2RGB)
  621. def parse_prompt(prompt):
  622. if prompt.startswith('http://') or prompt.startswith('https://'):
  623. vals = prompt.rsplit(':', 2)
  624. vals = [vals[0] + ':' + vals[1], *vals[2:]]
  625. else:
  626. vals = prompt.rsplit(':', 1)
  627. vals = vals + ['', '1'][len(vals):]
  628. return vals[0], float(vals[1])
  629. def sinc(x):
  630. return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([]))
  631. def lanczos(x, a):
  632. cond = torch.logical_and(-a < x, x < a)
  633. out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([]))
  634. return out / out.sum()
  635. def ramp(ratio, width):
  636. n = math.ceil(width / ratio + 1)
  637. out = torch.empty([n])
  638. cur = 0
  639. for i in range(out.shape[0]):
  640. out[i] = cur
  641. cur += ratio
  642. return torch.cat([-out[1:].flip([0]), out])[1:-1]
  643. def resample(input, size, align_corners=True):
  644. n, c, h, w = input.shape
  645. dh, dw = size
  646. input = input.reshape([n * c, 1, h, w])
  647. if dh < h:
  648. kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype)
  649. pad_h = (kernel_h.shape[0] - 1) // 2
  650. input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect')
  651. input = F.conv2d(input, kernel_h[None, None, :, None])
  652. if dw < w:
  653. kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype)
  654. pad_w = (kernel_w.shape[0] - 1) // 2
  655. input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect')
  656. input = F.conv2d(input, kernel_w[None, None, None, :])
  657. input = input.reshape([n, c, h, w])
  658. return F.interpolate(input, size, mode='bicubic', align_corners=align_corners)
  659. class MakeCutouts(nn.Module):
  660. def __init__(self, cut_size, cutn, skip_augs=False):
  661. super().__init__()
  662. self.cut_size = cut_size
  663. self.cutn = cutn
  664. self.skip_augs = skip_augs
  665. self.augs = T.Compose([
  666. T.RandomHorizontalFlip(p=0.5),
  667. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  668. T.RandomAffine(degrees=15, translate=(0.1, 0.1)),
  669. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  670. T.RandomPerspective(distortion_scale=0.4, p=0.7),
  671. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  672. T.RandomGrayscale(p=0.15),
  673. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  674. # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
  675. ])
  676. def forward(self, input):
  677. input = T.Pad(input.shape[2]//4, fill=0)(input)
  678. sideY, sideX = input.shape[2:4]
  679. max_size = min(sideX, sideY)
  680. cutouts = []
  681. for ch in range(self.cutn):
  682. if ch > self.cutn - self.cutn//4:
  683. cutout = input.clone()
  684. else:
  685. size = int(max_size * torch.zeros(1,).normal_(mean=.8, std=.3).clip(float(self.cut_size/max_size), 1.))
  686. offsetx = torch.randint(0, abs(sideX - size + 1), ())
  687. offsety = torch.randint(0, abs(sideY - size + 1), ())
  688. cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
  689. if not self.skip_augs:
  690. cutout = self.augs(cutout)
  691. cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
  692. del cutout
  693. cutouts = torch.cat(cutouts, dim=0)
  694. return cutouts
  695. cutout_debug = False
  696. padargs = {}
  697. class MakeCutoutsDango(nn.Module):
  698. def __init__(self, cut_size,
  699. Overview=4,
  700. InnerCrop = 0, IC_Size_Pow=0.5, IC_Grey_P = 0.2
  701. ):
  702. super().__init__()
  703. self.cut_size = cut_size
  704. self.Overview = Overview
  705. self.InnerCrop = InnerCrop
  706. self.IC_Size_Pow = IC_Size_Pow
  707. self.IC_Grey_P = IC_Grey_P
  708. if args.animation_mode == 'None':
  709. self.augs = T.Compose([
  710. T.RandomHorizontalFlip(p=0.5),
  711. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  712. T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),
  713. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  714. T.RandomGrayscale(p=0.1),
  715. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  716. T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
  717. ])
  718. elif args.animation_mode == 'Video Input':
  719. self.augs = T.Compose([
  720. T.RandomHorizontalFlip(p=0.5),
  721. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  722. T.RandomAffine(degrees=15, translate=(0.1, 0.1)),
  723. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  724. T.RandomPerspective(distortion_scale=0.4, p=0.7),
  725. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  726. T.RandomGrayscale(p=0.15),
  727. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  728. # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
  729. ])
  730. elif args.animation_mode == '2D' or args.animation_mode == '3D':
  731. self.augs = T.Compose([
  732. T.RandomHorizontalFlip(p=0.4),
  733. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  734. T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),
  735. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  736. T.RandomGrayscale(p=0.1),
  737. T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
  738. T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.3),
  739. ])
  740. def forward(self, input):
  741. cutouts = []
  742. gray = T.Grayscale(3)
  743. sideY, sideX = input.shape[2:4]
  744. max_size = min(sideX, sideY)
  745. min_size = min(sideX, sideY, self.cut_size)
  746. l_size = max(sideX, sideY)
  747. output_shape = [1,3,self.cut_size,self.cut_size]
  748. output_shape_2 = [1,3,self.cut_size+2,self.cut_size+2]
  749. pad_input = F.pad(input,((sideY-max_size)//2,(sideY-max_size)//2,(sideX-max_size)//2,(sideX-max_size)//2), **padargs)
  750. cutout = resize(pad_input, out_shape=output_shape)
  751. if self.Overview>0:
  752. if self.Overview<=4:
  753. if self.Overview>=1:
  754. cutouts.append(cutout)
  755. if self.Overview>=2:
  756. cutouts.append(gray(cutout))
  757. if self.Overview>=3:
  758. cutouts.append(TF.hflip(cutout))
  759. if self.Overview==4:
  760. cutouts.append(gray(TF.hflip(cutout)))
  761. else:
  762. cutout = resize(pad_input, out_shape=output_shape)
  763. for _ in range(self.Overview):
  764. cutouts.append(cutout)
  765. if cutout_debug:
  766. if is_colab:
  767. TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("/content/cutout_overview0.jpg",quality=99)
  768. else:
  769. TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("cutout_overview0.jpg",quality=99)
  770. if self.InnerCrop >0:
  771. for i in range(self.InnerCrop):
  772. size = int(torch.rand([])**self.IC_Size_Pow * (max_size - min_size) + min_size)
  773. offsetx = torch.randint(0, sideX - size + 1, ())
  774. offsety = torch.randint(0, sideY - size + 1, ())
  775. cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
  776. if i <= int(self.IC_Grey_P * self.InnerCrop):
  777. cutout = gray(cutout)
  778. cutout = resize(cutout, out_shape=output_shape)
  779. cutouts.append(cutout)
  780. if cutout_debug:
  781. if is_colab:
  782. TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("/content/cutout_InnerCrop.jpg",quality=99)
  783. else:
  784. TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("cutout_InnerCrop.jpg",quality=99)
  785. cutouts = torch.cat(cutouts)
  786. if skip_augs is not True: cutouts=self.augs(cutouts)
  787. return cutouts
  788. def spherical_dist_loss(x, y):
  789. x = F.normalize(x, dim=-1)
  790. y = F.normalize(y, dim=-1)
  791. return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
  792. def tv_loss(input):
  793. """L2 total variation loss, as in Mahendran et al."""
  794. input = F.pad(input, (0, 1, 0, 1), 'replicate')
  795. x_diff = input[..., :-1, 1:] - input[..., :-1, :-1]
  796. y_diff = input[..., 1:, :-1] - input[..., :-1, :-1]
  797. return (x_diff**2 + y_diff**2).mean([1, 2, 3])
  798. def range_loss(input):
  799. return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3])
  800. stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete
  801. TRANSLATION_SCALE = 1.0/200.0
  802. def do_3d_step(img_filepath, frame_num, midas_model, midas_transform):
  803. if args.key_frames:
  804. translation_x = args.translation_x_series[frame_num]
  805. translation_y = args.translation_y_series[frame_num]
  806. translation_z = args.translation_z_series[frame_num]
  807. rotation_3d_x = args.rotation_3d_x_series[frame_num]
  808. rotation_3d_y = args.rotation_3d_y_series[frame_num]
  809. rotation_3d_z = args.rotation_3d_z_series[frame_num]
  810. print(
  811. f'translation_x: {translation_x}',
  812. f'translation_y: {translation_y}',
  813. f'translation_z: {translation_z}',
  814. f'rotation_3d_x: {rotation_3d_x}',
  815. f'rotation_3d_y: {rotation_3d_y}',
  816. f'rotation_3d_z: {rotation_3d_z}',
  817. )
  818. translate_xyz = [-translation_x*TRANSLATION_SCALE, translation_y*TRANSLATION_SCALE, -translation_z*TRANSLATION_SCALE]
  819. rotate_xyz_degrees = [rotation_3d_x, rotation_3d_y, rotation_3d_z]
  820. print('translation:',translate_xyz)
  821. print('rotation:',rotate_xyz_degrees)
  822. rotate_xyz = [math.radians(rotate_xyz_degrees[0]), math.radians(rotate_xyz_degrees[1]), math.radians(rotate_xyz_degrees[2])]
  823. rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0)
  824. print("rot_mat: " + str(rot_mat))
  825. next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE,
  826. rot_mat, translate_xyz, args.near_plane, args.far_plane,
  827. args.fov, padding_mode=args.padding_mode,
  828. sampling_mode=args.sampling_mode, midas_weight=args.midas_weight)
  829. return next_step_pil
  830. def do_run():
  831. seed = args.seed
  832. print(range(args.start_frame, args.max_frames))
  833. if (args.animation_mode == "3D") and (args.midas_weight > 0.0):
  834. midas_model, midas_transform, midas_net_w, midas_net_h, midas_resize_mode, midas_normalization = init_midas_depth_model(args.midas_depth_model)
  835. for frame_num in range(args.start_frame, args.max_frames):
  836. if stop_on_next_loop:
  837. break
  838. display.clear_output(wait=True)
  839. # Print Frame progress if animation mode is on
  840. if args.animation_mode != "None":
  841. batchBar = tqdm(range(args.max_frames), desc ="Frames")
  842. batchBar.n = frame_num
  843. batchBar.refresh()
  844. # Inits if not video frames
  845. if args.animation_mode != "Video Input":
  846. if args.init_image == '':
  847. init_image = None
  848. else:
  849. init_image = args.init_image
  850. init_scale = args.init_scale
  851. skip_steps = args.skip_steps
  852. if args.animation_mode == "2D":
  853. if args.key_frames:
  854. angle = args.angle_series[frame_num]
  855. zoom = args.zoom_series[frame_num]
  856. translation_x = args.translation_x_series[frame_num]
  857. translation_y = args.translation_y_series[frame_num]
  858. print(
  859. f'angle: {angle}',
  860. f'zoom: {zoom}',
  861. f'translation_x: {translation_x}',
  862. f'translation_y: {translation_y}',
  863. )
  864. if frame_num > 0:
  865. seed += 1
  866. if resume_run and frame_num == start_frame:
  867. img_0 = cv2.imread(batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png")
  868. else:
  869. img_0 = cv2.imread('prevFrame.png')
  870. center = (1*img_0.shape[1]//2, 1*img_0.shape[0]//2)
  871. trans_mat = np.float32(
  872. [[1, 0, translation_x],
  873. [0, 1, translation_y]]
  874. )
  875. rot_mat = cv2.getRotationMatrix2D( center, angle, zoom )
  876. trans_mat = np.vstack([trans_mat, [0,0,1]])
  877. rot_mat = np.vstack([rot_mat, [0,0,1]])
  878. transformation_matrix = np.matmul(rot_mat, trans_mat)
  879. img_0 = cv2.warpPerspective(
  880. img_0,
  881. transformation_matrix,
  882. (img_0.shape[1], img_0.shape[0]),
  883. borderMode=cv2.BORDER_WRAP
  884. )
  885. cv2.imwrite('prevFrameScaled.png', img_0)
  886. init_image = 'prevFrameScaled.png'
  887. init_scale = args.frames_scale
  888. skip_steps = args.calc_frames_skip_steps
  889. if args.animation_mode == "3D":
  890. if frame_num > 0:
  891. seed += 1
  892. if resume_run and frame_num == start_frame:
  893. img_filepath = batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png"
  894. if turbo_mode and frame_num > turbo_preroll:
  895. shutil.copyfile(img_filepath, 'oldFrameScaled.png')
  896. else:
  897. img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png'
  898. next_step_pil = do_3d_step(img_filepath, frame_num, midas_model, midas_transform)
  899. next_step_pil.save('prevFrameScaled.png')
  900. ### Turbo mode - skip some diffusions, use 3d morph for clarity and to save time
  901. if turbo_mode:
  902. if frame_num == turbo_preroll: #start tracking oldframe
  903. next_step_pil.save('oldFrameScaled.png')#stash for later blending
  904. elif frame_num > turbo_preroll:
  905. #set up 2 warped image sequences, old & new, to blend toward new diff image
  906. old_frame = do_3d_step('oldFrameScaled.png', frame_num, midas_model, midas_transform)
  907. old_frame.save('oldFrameScaled.png')
  908. if frame_num % int(turbo_steps) != 0:
  909. print('turbo skip this frame: skipping clip diffusion steps')
  910. filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png'
  911. blend_factor = ((frame_num % int(turbo_steps))+1)/int(turbo_steps)
  912. print('turbo skip this frame: skipping clip diffusion steps and saving blended frame')
  913. newWarpedImg = cv2.imread('prevFrameScaled.png')#this is already updated..
  914. oldWarpedImg = cv2.imread('oldFrameScaled.png')
  915. blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0)
  916. cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)
  917. next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration
  918. if vr_mode:
  919. generate_eye_views(TRANSLATION_SCALE,batchFolder,filename,frame_num,midas_model, midas_transform)
  920. continue
  921. else:
  922. #if not a skip frame, will run diffusion and need to blend.
  923. oldWarpedImg = cv2.imread('prevFrameScaled.png')
  924. cv2.imwrite(f'oldFrameScaled.png',oldWarpedImg)#swap in for blending later
  925. print('clip/diff this frame - generate clip diff image')
  926. init_image = 'prevFrameScaled.png'
  927. init_scale = args.frames_scale
  928. skip_steps = args.calc_frames_skip_steps
  929. if args.animation_mode == "Video Input":
  930. if not video_init_seed_continuity:
  931. seed += 1
  932. init_image = f'{videoFramesFolder}/{frame_num+1:04}.jpg'
  933. init_scale = args.frames_scale
  934. skip_steps = args.calc_frames_skip_steps
  935. loss_values = []
  936. if seed is not None:
  937. np.random.seed(seed)
  938. random.seed(seed)
  939. torch.manual_seed(seed)
  940. torch.cuda.manual_seed_all(seed)
  941. torch.backends.cudnn.deterministic = True
  942. target_embeds, weights = [], []
  943. if args.prompts_series is not None and frame_num >= len(args.prompts_series):
  944. frame_prompt = args.prompts_series[-1]
  945. elif args.prompts_series is not None:
  946. frame_prompt = args.prompts_series[frame_num]
  947. else:
  948. frame_prompt = []
  949. print(args.image_prompts_series)
  950. if args.image_prompts_series is not None and frame_num >= len(args.image_prompts_series):
  951. image_prompt = args.image_prompts_series[-1]
  952. elif args.image_prompts_series is not None:
  953. image_prompt = args.image_prompts_series[frame_num]
  954. else:
  955. image_prompt = []
  956. print(f'Frame {frame_num} Prompt: {frame_prompt}')
  957. model_stats = []
  958. for clip_model in clip_models:
  959. cutn = 16
  960. model_stat = {"clip_model":None,"target_embeds":[],"make_cutouts":None,"weights":[]}
  961. model_stat["clip_model"] = clip_model
  962. for prompt in frame_prompt:
  963. txt, weight = parse_prompt(prompt)
  964. txt = clip_model.encode_text(clip.tokenize(prompt).to(device)).float()
  965. if args.fuzzy_prompt:
  966. for i in range(25):
  967. model_stat["target_embeds"].append((txt + torch.randn(txt.shape).cuda() * args.rand_mag).clamp(0,1))
  968. model_stat["weights"].append(weight)
  969. else:
  970. model_stat["target_embeds"].append(txt)
  971. model_stat["weights"].append(weight)
  972. if image_prompt:
  973. model_stat["make_cutouts"] = MakeCutouts(clip_model.visual.input_resolution, cutn, skip_augs=skip_augs)
  974. for prompt in image_prompt:
  975. path, weight = parse_prompt(prompt)
  976. img = Image.open(fetch(path)).convert('RGB')
  977. img = TF.resize(img, min(side_x, side_y, *img.size), T.InterpolationMode.LANCZOS)
  978. batch = model_stat["make_cutouts"](TF.to_tensor(img).to(device).unsqueeze(0).mul(2).sub(1))
  979. embed = clip_model.encode_image(normalize(batch)).float()
  980. if fuzzy_prompt:
  981. for i in range(25):
  982. model_stat["target_embeds"].append((embed + torch.randn(embed.shape).cuda() * rand_mag).clamp(0,1))
  983. weights.extend([weight / cutn] * cutn)
  984. else:
  985. model_stat["target_embeds"].append(embed)
  986. model_stat["weights"].extend([weight / cutn] * cutn)
  987. model_stat["target_embeds"] = torch.cat(model_stat["target_embeds"])
  988. model_stat["weights"] = torch.tensor(model_stat["weights"], device=device)
  989. if model_stat["weights"].sum().abs() < 1e-3:
  990. raise RuntimeError('The weights must not sum to 0.')
  991. model_stat["weights"] /= model_stat["weights"].sum().abs()
  992. model_stats.append(model_stat)
  993. init = None
  994. if init_image is not None:
  995. init = Image.open(fetch(init_image)).convert('RGB')
  996. init = init.resize((args.side_x, args.side_y), Image.LANCZOS)
  997. init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1)
  998. if args.perlin_init:
  999. if args.perlin_mode == 'color':
  1000. init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
  1001. init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)
  1002. elif args.perlin_mode == 'gray':
  1003. init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)
  1004. init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
  1005. else:
  1006. init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
  1007. init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
  1008. # init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device)
  1009. init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)
  1010. del init2
  1011. cur_t = None
  1012. def cond_fn(x, t, y=None):
  1013. with torch.enable_grad():
  1014. x_is_NaN = False
  1015. x = x.detach().requires_grad_()
  1016. n = x.shape[0]
  1017. if use_secondary_model is True:
  1018. alpha = torch.tensor(diffusion.sqrt_alphas_cumprod[cur_t], device=device, dtype=torch.float32)
  1019. sigma = torch.tensor(diffusion.sqrt_one_minus_alphas_cumprod[cur_t], device=device, dtype=torch.float32)
  1020. cosine_t = alpha_sigma_to_t(alpha, sigma)
  1021. out = secondary_model(x, cosine_t[None].repeat([n])).pred
  1022. fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]
  1023. x_in = out * fac + x * (1 - fac)
  1024. x_in_grad = torch.zeros_like(x_in)
  1025. else:
  1026. my_t = torch.ones([n], device=device, dtype=torch.long) * cur_t
  1027. out = diffusion.p_mean_variance(model, x, my_t, clip_denoised=False, model_kwargs={'y': y})
  1028. fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]
  1029. x_in = out['pred_xstart'] * fac + x * (1 - fac)
  1030. x_in_grad = torch.zeros_like(x_in)
  1031. for model_stat in model_stats:
  1032. for i in range(args.cutn_batches):
  1033. t_int = int(t.item())+1 #errors on last step without +1, need to find source
  1034. #when using SLIP Base model the dimensions need to be hard coded to avoid AttributeError: 'VisionTransformer' object has no attribute 'input_resolution'
  1035. try:
  1036. input_resolution=model_stat["clip_model"].visual.input_resolution
  1037. except:
  1038. input_resolution=224
  1039. cuts = MakeCutoutsDango(input_resolution,
  1040. Overview= args.cut_overview[1000-t_int],
  1041. InnerCrop = args.cut_innercut[1000-t_int], IC_Size_Pow=args.cut_ic_pow, IC_Grey_P = args.cut_icgray_p[1000-t_int]
  1042. )
  1043. clip_in = normalize(cuts(x_in.add(1).div(2)))
  1044. image_embeds = model_stat["clip_model"].encode_image(clip_in).float()
  1045. dists = spherical_dist_loss(image_embeds.unsqueeze(1), model_stat["target_embeds"].unsqueeze(0))
  1046. dists = dists.view([args.cut_overview[1000-t_int]+args.cut_innercut[1000-t_int], n, -1])
  1047. losses = dists.mul(model_stat["weights"]).sum(2).mean(0)
  1048. loss_values.append(losses.sum().item()) # log loss, probably shouldn't do per cutn_batch
  1049. x_in_grad += torch.autograd.grad(losses.sum() * clip_guidance_scale, x_in)[0] / cutn_batches
  1050. tv_losses = tv_loss(x_in)
  1051. if use_secondary_model is True:
  1052. range_losses = range_loss(out)
  1053. else:
  1054. range_losses = range_loss(out['pred_xstart'])
  1055. sat_losses = torch.abs(x_in - x_in.clamp(min=-1,max=1)).mean()
  1056. loss = tv_losses.sum() * tv_scale + range_losses.sum() * range_scale + sat_losses.sum() * sat_scale
  1057. if init is not None and args.init_scale:
  1058. init_losses = lpips_model(x_in, init)
  1059. loss = loss + init_losses.sum() * args.init_scale
  1060. x_in_grad += torch.autograd.grad(loss, x_in)[0]
  1061. if torch.isnan(x_in_grad).any()==False:
  1062. grad = -torch.autograd.grad(x_in, x, x_in_grad)[0]
  1063. else:
  1064. # print("NaN'd")
  1065. x_is_NaN = True
  1066. grad = torch.zeros_like(x)
  1067. if args.clamp_grad and x_is_NaN == False:
  1068. magnitude = grad.square().mean().sqrt()
  1069. return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max,
  1070. return grad
  1071. if args.diffusion_sampling_mode == 'ddim':
  1072. sample_fn = diffusion.ddim_sample_loop_progressive
  1073. else:
  1074. sample_fn = diffusion.plms_sample_loop_progressive
  1075. image_display = Output()
  1076. for i in range(args.n_batches):
  1077. if args.animation_mode == 'None':
  1078. display.clear_output(wait=True)
  1079. batchBar = tqdm(range(args.n_batches), desc ="Batches")
  1080. batchBar.n = i
  1081. batchBar.refresh()
  1082. print('')
  1083. display.display(image_display)
  1084. gc.collect()
  1085. torch.cuda.empty_cache()
  1086. cur_t = diffusion.num_timesteps - skip_steps - 1
  1087. total_steps = cur_t
  1088. if perlin_init:
  1089. init = regen_perlin()
  1090. if args.diffusion_sampling_mode == 'ddim':
  1091. samples = sample_fn(
  1092. model,
  1093. (batch_size, 3, args.side_y, args.side_x),
  1094. clip_denoised=clip_denoised,
  1095. model_kwargs={},
  1096. cond_fn=cond_fn,
  1097. progress=True,
  1098. skip_timesteps=skip_steps,
  1099. init_image=init,
  1100. randomize_class=randomize_class,
  1101. eta=eta,
  1102. )
  1103. else:
  1104. samples = sample_fn(
  1105. model,
  1106. (batch_size, 3, args.side_y, args.side_x),
  1107. clip_denoised=clip_denoised,
  1108. model_kwargs={},
  1109. cond_fn=cond_fn,
  1110. progress=True,
  1111. skip_timesteps=skip_steps,
  1112. init_image=init,
  1113. randomize_class=randomize_class,
  1114. order=2,
  1115. )
  1116. # with run_display:
  1117. # display.clear_output(wait=True)
  1118. for j, sample in enumerate(samples):
  1119. cur_t -= 1
  1120. intermediateStep = False
  1121. if args.steps_per_checkpoint is not None:
  1122. if j % steps_per_checkpoint == 0 and j > 0:
  1123. intermediateStep = True
  1124. elif j in args.intermediate_saves:
  1125. intermediateStep = True
  1126. with image_display:
  1127. if j % args.display_rate == 0 or cur_t == -1 or intermediateStep == True:
  1128. for k, image in enumerate(sample['pred_xstart']):
  1129. # tqdm.write(f'Batch {i}, step {j}, output {k}:')
  1130. current_time = datetime.now().strftime('%y%m%d-%H%M%S_%f')
  1131. percent = math.ceil(j/total_steps*100)
  1132. if args.n_batches > 0:
  1133. #if intermediates are saved to the subfolder, don't append a step or percentage to the name
  1134. if cur_t == -1 and args.intermediates_in_subfolder is True:
  1135. save_num = f'{frame_num:04}' if animation_mode != "None" else i
  1136. filename = f'{args.batch_name}({args.batchNum})_{save_num}.png'
  1137. else:
  1138. #If we're working with percentages, append it
  1139. if args.steps_per_checkpoint is not None:
  1140. filename = f'{args.batch_name}({args.batchNum})_{i:04}-{percent:02}%.png'
  1141. # Or else, iIf we're working with specific steps, append those
  1142. else:
  1143. filename = f'{args.batch_name}({args.batchNum})_{i:04}-{j:03}.png'
  1144. image = TF.to_pil_image(image.add(1).div(2).clamp(0, 1))
  1145. if j % args.display_rate == 0 or cur_t == -1:
  1146. image.save('progress.png')
  1147. display.clear_output(wait=True)
  1148. display.display(display.Image('progress.png'))
  1149. if args.steps_per_checkpoint is not None:
  1150. if j % args.steps_per_checkpoint == 0 and j > 0:
  1151. if args.intermediates_in_subfolder is True:
  1152. image.save(f'{partialFolder}/{filename}')
  1153. else:
  1154. image.save(f'{batchFolder}/{filename}')
  1155. else:
  1156. if j in args.intermediate_saves:
  1157. if args.intermediates_in_subfolder is True:
  1158. image.save(f'{partialFolder}/{filename}')
  1159. else:
  1160. image.save(f'{batchFolder}/{filename}')
  1161. if cur_t == -1:
  1162. if frame_num == 0:
  1163. save_settings()
  1164. if args.animation_mode != "None":
  1165. image.save('prevFrame.png')
  1166. image.save(f'{batchFolder}/{filename}')
  1167. if args.animation_mode == "3D":
  1168. # If turbo, save a blended image
  1169. if turbo_mode and frame_num > 0:
  1170. # Mix new image with prevFrameScaled
  1171. blend_factor = (1)/int(turbo_steps)
  1172. newFrame = cv2.imread('prevFrame.png') # This is already updated..
  1173. prev_frame_warped = cv2.imread('prevFrameScaled.png')
  1174. blendedImage = cv2.addWeighted(newFrame, blend_factor, prev_frame_warped, (1-blend_factor), 0.0)
  1175. cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)
  1176. else:
  1177. image.save(f'{batchFolder}/{filename}')
  1178. if vr_mode:
  1179. generate_eye_views(TRANSLATION_SCALE, batchFolder, filename, frame_num, midas_model, midas_transform)
  1180. # if frame_num != args.max_frames-1:
  1181. # display.clear_output()
  1182. plt.plot(np.array(loss_values), 'r')
  1183. def generate_eye_views(trans_scale,batchFolder,filename,frame_num,midas_model, midas_transform):
  1184. for i in range(2):
  1185. theta = vr_eye_angle * (math.pi/180)
  1186. ray_origin = math.cos(theta) * vr_ipd / 2 * (-1.0 if i==0 else 1.0)
  1187. ray_rotation = (theta if i==0 else -theta)
  1188. translate_xyz = [-(ray_origin)*trans_scale, 0,0]
  1189. rotate_xyz = [0, (ray_rotation), 0]
  1190. rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0)
  1191. transformed_image = dxf.transform_image_3d(f'{batchFolder}/{filename}', midas_model, midas_transform, DEVICE,
  1192. rot_mat, translate_xyz, args.near_plane, args.far_plane,
  1193. args.fov, padding_mode=args.padding_mode,
  1194. sampling_mode=args.sampling_mode, midas_weight=args.midas_weight,spherical=True)
  1195. eye_file_path = batchFolder+f"/frame_{frame_num:04}" + ('_l' if i==0 else '_r')+'.png'
  1196. transformed_image.save(eye_file_path)
  1197. def save_settings():
  1198. setting_list = {
  1199. 'text_prompts': text_prompts,
  1200. 'image_prompts': image_prompts,
  1201. 'clip_guidance_scale': clip_guidance_scale,
  1202. 'tv_scale': tv_scale,
  1203. 'range_scale': range_scale,
  1204. 'sat_scale': sat_scale,
  1205. # 'cutn': cutn,
  1206. 'cutn_batches': cutn_batches,
  1207. 'max_frames': max_frames,
  1208. 'interp_spline': interp_spline,
  1209. # 'rotation_per_frame': rotation_per_frame,
  1210. 'init_image': init_image,
  1211. 'init_scale': init_scale,
  1212. 'skip_steps': skip_steps,
  1213. # 'zoom_per_frame': zoom_per_frame,
  1214. 'frames_scale': frames_scale,
  1215. 'frames_skip_steps': frames_skip_steps,
  1216. 'perlin_init': perlin_init,
  1217. 'perlin_mode': perlin_mode,
  1218. 'skip_augs': skip_augs,
  1219. 'randomize_class': randomize_class,
  1220. 'clip_denoised': clip_denoised,
  1221. 'clamp_grad': clamp_grad,
  1222. 'clamp_max': clamp_max,
  1223. 'seed': seed,
  1224. 'fuzzy_prompt': fuzzy_prompt,
  1225. 'rand_mag': rand_mag,
  1226. 'eta': eta,
  1227. 'width': width_height[0],
  1228. 'height': width_height[1],
  1229. 'diffusion_model': diffusion_model,
  1230. 'use_secondary_model': use_secondary_model,
  1231. 'steps': steps,
  1232. 'diffusion_steps': diffusion_steps,
  1233. 'diffusion_sampling_mode': diffusion_sampling_mode,
  1234. 'ViTB32': ViTB32,
  1235. 'ViTB16': ViTB16,
  1236. 'ViTL14': ViTL14,
  1237. 'RN101': RN101,
  1238. 'RN50': RN50,
  1239. 'RN50x4': RN50x4,
  1240. 'RN50x16': RN50x16,
  1241. 'RN50x64': RN50x64,
  1242. 'cut_overview': str(cut_overview),
  1243. 'cut_innercut': str(cut_innercut),
  1244. 'cut_ic_pow': cut_ic_pow,
  1245. 'cut_icgray_p': str(cut_icgray_p),
  1246. 'key_frames': key_frames,
  1247. 'max_frames': max_frames,
  1248. 'angle': angle,
  1249. 'zoom': zoom,
  1250. 'translation_x': translation_x,
  1251. 'translation_y': translation_y,
  1252. 'translation_z': translation_z,
  1253. 'rotation_3d_x': rotation_3d_x,
  1254. 'rotation_3d_y': rotation_3d_y,
  1255. 'rotation_3d_z': rotation_3d_z,
  1256. 'midas_depth_model': midas_depth_model,
  1257. 'midas_weight': midas_weight,
  1258. 'near_plane': near_plane,
  1259. 'far_plane': far_plane,
  1260. 'fov': fov,
  1261. 'padding_mode': padding_mode,
  1262. 'sampling_mode': sampling_mode,
  1263. 'video_init_path':video_init_path,
  1264. 'extract_nth_frame':extract_nth_frame,
  1265. 'video_init_seed_continuity': video_init_seed_continuity,
  1266. 'turbo_mode':turbo_mode,
  1267. 'turbo_steps':turbo_steps,
  1268. 'turbo_preroll':turbo_preroll,
  1269. }
  1270. # print('Settings:', setting_list)
  1271. with open(f"{batchFolder}/{batch_name}({batchNum})_settings.txt", "w+") as f: #save settings
  1272. json.dump(setting_list, f, ensure_ascii=False, indent=4)
  1273. # %%
  1274. # !! {"metadata": {
  1275. # !! "cellView": "form",
  1276. # !! "id": "DefSecModel"
  1277. # !! }}
  1278. #@title 1.6 Define the secondary diffusion model
  1279. def append_dims(x, n):
  1280. return x[(Ellipsis, *(None,) * (n - x.ndim))]
  1281. def expand_to_planes(x, shape):
  1282. return append_dims(x, len(shape)).repeat([1, 1, *shape[2:]])
  1283. def alpha_sigma_to_t(alpha, sigma):
  1284. return torch.atan2(sigma, alpha) * 2 / math.pi
  1285. def t_to_alpha_sigma(t):
  1286. return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2)
  1287. @dataclass
  1288. class DiffusionOutput:
  1289. v: torch.Tensor
  1290. pred: torch.Tensor
  1291. eps: torch.Tensor
  1292. class ConvBlock(nn.Sequential):
  1293. def __init__(self, c_in, c_out):
  1294. super().__init__(
  1295. nn.Conv2d(c_in, c_out, 3, padding=1),
  1296. nn.ReLU(inplace=True),
  1297. )
  1298. class SkipBlock(nn.Module):
  1299. def __init__(self, main, skip=None):
  1300. super().__init__()
  1301. self.main = nn.Sequential(*main)
  1302. self.skip = skip if skip else nn.Identity()
  1303. def forward(self, input):
  1304. return torch.cat([self.main(input), self.skip(input)], dim=1)
  1305. class FourierFeatures(nn.Module):
  1306. def __init__(self, in_features, out_features, std=1.):
  1307. super().__init__()
  1308. assert out_features % 2 == 0
  1309. self.weight = nn.Parameter(torch.randn([out_features // 2, in_features]) * std)
  1310. def forward(self, input):
  1311. f = 2 * math.pi * input @ self.weight.T
  1312. return torch.cat([f.cos(), f.sin()], dim=-1)
  1313. class SecondaryDiffusionImageNet(nn.Module):
  1314. def __init__(self):
  1315. super().__init__()
  1316. c = 64 # The base channel count
  1317. self.timestep_embed = FourierFeatures(1, 16)
  1318. self.net = nn.Sequential(
  1319. ConvBlock(3 + 16, c),
  1320. ConvBlock(c, c),
  1321. SkipBlock([
  1322. nn.AvgPool2d(2),
  1323. ConvBlock(c, c * 2),
  1324. ConvBlock(c * 2, c * 2),
  1325. SkipBlock([
  1326. nn.AvgPool2d(2),
  1327. ConvBlock(c * 2, c * 4),
  1328. ConvBlock(c * 4, c * 4),
  1329. SkipBlock([
  1330. nn.AvgPool2d(2),
  1331. ConvBlock(c * 4, c * 8),
  1332. ConvBlock(c * 8, c * 4),
  1333. nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
  1334. ]),
  1335. ConvBlock(c * 8, c * 4),
  1336. ConvBlock(c * 4, c * 2),
  1337. nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
  1338. ]),
  1339. ConvBlock(c * 4, c * 2),
  1340. ConvBlock(c * 2, c),
  1341. nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
  1342. ]),
  1343. ConvBlock(c * 2, c),
  1344. nn.Conv2d(c, 3, 3, padding=1),
  1345. )
  1346. def forward(self, input, t):
  1347. timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape)
  1348. v = self.net(torch.cat([input, timestep_embed], dim=1))
  1349. alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t))
  1350. pred = input * alphas - v * sigmas
  1351. eps = input * sigmas + v * alphas
  1352. return DiffusionOutput(v, pred, eps)
  1353. class SecondaryDiffusionImageNet2(nn.Module):
  1354. def __init__(self):
  1355. super().__init__()
  1356. c = 64 # The base channel count
  1357. cs = [c, c * 2, c * 2, c * 4, c * 4, c * 8]
  1358. self.timestep_embed = FourierFeatures(1, 16)
  1359. self.down = nn.AvgPool2d(2)
  1360. self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)
  1361. self.net = nn.Sequential(
  1362. ConvBlock(3 + 16, cs[0]),
  1363. ConvBlock(cs[0], cs[0]),
  1364. SkipBlock([
  1365. self.down,
  1366. ConvBlock(cs[0], cs[1]),
  1367. ConvBlock(cs[1], cs[1]),
  1368. SkipBlock([
  1369. self.down,
  1370. ConvBlock(cs[1], cs[2]),
  1371. ConvBlock(cs[2], cs[2]),
  1372. SkipBlock([
  1373. self.down,
  1374. ConvBlock(cs[2], cs[3]),
  1375. ConvBlock(cs[3], cs[3]),
  1376. SkipBlock([
  1377. self.down,
  1378. ConvBlock(cs[3], cs[4]),
  1379. ConvBlock(cs[4], cs[4]),
  1380. SkipBlock([
  1381. self.down,
  1382. ConvBlock(cs[4], cs[5]),
  1383. ConvBlock(cs[5], cs[5]),
  1384. ConvBlock(cs[5], cs[5]),
  1385. ConvBlock(cs[5], cs[4]),
  1386. self.up,
  1387. ]),
  1388. ConvBlock(cs[4] * 2, cs[4]),
  1389. ConvBlock(cs[4], cs[3]),
  1390. self.up,
  1391. ]),
  1392. ConvBlock(cs[3] * 2, cs[3]),
  1393. ConvBlock(cs[3], cs[2]),
  1394. self.up,
  1395. ]),
  1396. ConvBlock(cs[2] * 2, cs[2]),
  1397. ConvBlock(cs[2], cs[1]),
  1398. self.up,
  1399. ]),
  1400. ConvBlock(cs[1] * 2, cs[1]),
  1401. ConvBlock(cs[1], cs[0]),
  1402. self.up,
  1403. ]),
  1404. ConvBlock(cs[0] * 2, cs[0]),
  1405. nn.Conv2d(cs[0], 3, 3, padding=1),
  1406. )
  1407. def forward(self, input, t):
  1408. timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape)
  1409. v = self.net(torch.cat([input, timestep_embed], dim=1))
  1410. alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t))
  1411. pred = input * alphas - v * sigmas
  1412. eps = input * sigmas + v * alphas
  1413. return DiffusionOutput(v, pred, eps)
  1414. # %%
  1415. # !! {"metadata": {
  1416. # !! "id": "DiffClipSetTop"
  1417. # !! }}
  1418. """
  1419. # 2. Diffusion and CLIP model settings
  1420. """
  1421. # %%
  1422. # !! {"metadata": {
  1423. # !! "id": "ModelSettings"
  1424. # !! }}
  1425. #@markdown ####**Models Settings:**
  1426. diffusion_model = "512x512_diffusion_uncond_finetune_008100" #@param ["256x256_diffusion_uncond", "512x512_diffusion_uncond_finetune_008100"]
  1427. use_secondary_model = True #@param {type: 'boolean'}
  1428. diffusion_sampling_mode = 'ddim' #@param ['plms','ddim']
  1429. use_checkpoint = True #@param {type: 'boolean'}
  1430. ViTB32 = True #@param{type:"boolean"}
  1431. ViTB16 = True #@param{type:"boolean"}
  1432. ViTL14 = False #@param{type:"boolean"}
  1433. RN101 = False #@param{type:"boolean"}
  1434. RN50 = True #@param{type:"boolean"}
  1435. RN50x4 = False #@param{type:"boolean"}
  1436. RN50x16 = False #@param{type:"boolean"}
  1437. RN50x64 = False #@param{type:"boolean"}
  1438. #@markdown If you're having issues with model downloads, check this to compare SHA's:
  1439. check_model_SHA = False #@param{type:"boolean"}
  1440. model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'
  1441. model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648'
  1442. model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'
  1443. model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt'
  1444. model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt'
  1445. model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth'
  1446. model_256_path = f'{model_path}/256x256_diffusion_uncond.pt'
  1447. model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt'
  1448. model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth'
  1449. # Download the diffusion model
  1450. if diffusion_model == '256x256_diffusion_uncond':
  1451. if os.path.exists(model_256_path) and check_model_SHA:
  1452. print('Checking 256 Diffusion File')
  1453. with open(model_256_path,"rb") as f:
  1454. bytes = f.read()
  1455. hash = hashlib.sha256(bytes).hexdigest();
  1456. if hash == model_256_SHA:
  1457. print('256 Model SHA matches')
  1458. model_256_downloaded = True
  1459. else:
  1460. print("256 Model SHA doesn't match, redownloading...")
  1461. wget(model_256_link, model_path)
  1462. model_256_downloaded = True
  1463. elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True:
  1464. print('256 Model already downloaded, check check_model_SHA if the file is corrupt')
  1465. else:
  1466. wget(model_256_link, model_path)
  1467. model_256_downloaded = True
  1468. elif diffusion_model == '512x512_diffusion_uncond_finetune_008100':
  1469. if os.path.exists(model_512_path) and check_model_SHA:
  1470. print('Checking 512 Diffusion File')
  1471. with open(model_512_path,"rb") as f:
  1472. bytes = f.read()
  1473. hash = hashlib.sha256(bytes).hexdigest();
  1474. if hash == model_512_SHA:
  1475. print('512 Model SHA matches')
  1476. model_512_downloaded = True
  1477. else:
  1478. print("512 Model SHA doesn't match, redownloading...")
  1479. wget(model_512_link, model_path)
  1480. model_512_downloaded = True
  1481. elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True:
  1482. print('512 Model already downloaded, check check_model_SHA if the file is corrupt')
  1483. else:
  1484. wget(model_512_link, model_path)
  1485. model_512_downloaded = True
  1486. # Download the secondary diffusion model v2
  1487. if use_secondary_model == True:
  1488. if os.path.exists(model_secondary_path) and check_model_SHA:
  1489. print('Checking Secondary Diffusion File')
  1490. with open(model_secondary_path,"rb") as f:
  1491. bytes = f.read()
  1492. hash = hashlib.sha256(bytes).hexdigest();
  1493. if hash == model_secondary_SHA:
  1494. print('Secondary Model SHA matches')
  1495. model_secondary_downloaded = True
  1496. else:
  1497. print("Secondary Model SHA doesn't match, redownloading...")
  1498. wget(model_secondary_link, model_path)
  1499. model_secondary_downloaded = True
  1500. elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True:
  1501. print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt')
  1502. else:
  1503. wget(model_secondary_link, model_path)
  1504. model_secondary_downloaded = True
  1505. model_config = model_and_diffusion_defaults()
  1506. if diffusion_model == '512x512_diffusion_uncond_finetune_008100':
  1507. model_config.update({
  1508. 'attention_resolutions': '32, 16, 8',
  1509. 'class_cond': False,
  1510. 'diffusion_steps': 1000, #No need to edit this, it is taken care of later.
  1511. 'rescale_timesteps': True,
  1512. 'timestep_respacing': 250, #No need to edit this, it is taken care of later.
  1513. 'image_size': 512,
  1514. 'learn_sigma': True,
  1515. 'noise_schedule': 'linear',
  1516. 'num_channels': 256,
  1517. 'num_head_channels': 64,
  1518. 'num_res_blocks': 2,
  1519. 'resblock_updown': True,
  1520. 'use_checkpoint': use_checkpoint,
  1521. 'use_fp16': True,
  1522. 'use_scale_shift_norm': True,
  1523. })
  1524. elif diffusion_model == '256x256_diffusion_uncond':
  1525. model_config.update({
  1526. 'attention_resolutions': '32, 16, 8',
  1527. 'class_cond': False,
  1528. 'diffusion_steps': 1000, #No need to edit this, it is taken care of later.
  1529. 'rescale_timesteps': True,
  1530. 'timestep_respacing': 250, #No need to edit this, it is taken care of later.
  1531. 'image_size': 256,
  1532. 'learn_sigma': True,
  1533. 'noise_schedule': 'linear',
  1534. 'num_channels': 256,
  1535. 'num_head_channels': 64,
  1536. 'num_res_blocks': 2,
  1537. 'resblock_updown': True,
  1538. 'use_checkpoint': use_checkpoint,
  1539. 'use_fp16': True,
  1540. 'use_scale_shift_norm': True,
  1541. })
  1542. model_default = model_config['image_size']
  1543. if use_secondary_model:
  1544. secondary_model = SecondaryDiffusionImageNet2()
  1545. secondary_model.load_state_dict(torch.load(f'{model_path}/secondary_model_imagenet_2.pth', map_location='cpu'))
  1546. secondary_model.eval().requires_grad_(False).to(device)
  1547. clip_models = []
  1548. if ViTB32 is True: clip_models.append(clip.load('ViT-B/32', jit=False)[0].eval().requires_grad_(False).to(device))
  1549. if ViTB16 is True: clip_models.append(clip.load('ViT-B/16', jit=False)[0].eval().requires_grad_(False).to(device) )
  1550. if ViTL14 is True: clip_models.append(clip.load('ViT-L/14', jit=False)[0].eval().requires_grad_(False).to(device) )
  1551. if RN50 is True: clip_models.append(clip.load('RN50', jit=False)[0].eval().requires_grad_(False).to(device))
  1552. if RN50x4 is True: clip_models.append(clip.load('RN50x4', jit=False)[0].eval().requires_grad_(False).to(device))
  1553. if RN50x16 is True: clip_models.append(clip.load('RN50x16', jit=False)[0].eval().requires_grad_(False).to(device))
  1554. if RN50x64 is True: clip_models.append(clip.load('RN50x64', jit=False)[0].eval().requires_grad_(False).to(device))
  1555. if RN101 is True: clip_models.append(clip.load('RN101', jit=False)[0].eval().requires_grad_(False).to(device))
  1556. normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])
  1557. lpips_model = lpips.LPIPS(net='vgg').to(device)
  1558. # %%
  1559. # !! {"metadata": {
  1560. # !! "id": "SettingsTop"
  1561. # !! }}
  1562. """
  1563. # 3. Settings
  1564. """
  1565. # %%
  1566. # !! {"metadata": {
  1567. # !! "id": "BasicSettings"
  1568. # !! }}
  1569. #@markdown ####**Basic Settings:**
  1570. batch_name = 'TimeToDisco' #@param{type: 'string'}
  1571. steps = 250 #@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true}
  1572. width_height = [1280, 768]#@param{type: 'raw'}
  1573. clip_guidance_scale = 5000 #@param{type: 'number'}
  1574. tv_scale = 0#@param{type: 'number'}
  1575. range_scale = 150#@param{type: 'number'}
  1576. sat_scale = 0#@param{type: 'number'}
  1577. cutn_batches = 4 #@param{type: 'number'}
  1578. skip_augs = False#@param{type: 'boolean'}
  1579. #@markdown ---
  1580. #@markdown ####**Init Settings:**
  1581. init_image = None #@param{type: 'string'}
  1582. init_scale = 1000 #@param{type: 'integer'}
  1583. skip_steps = 10 #@param{type: 'integer'}
  1584. #@markdown *Make sure you set skip_steps to ~50% of your steps if you want to use an init image.*
  1585. #Get corrected sizes
  1586. side_x = (width_height[0]//64)*64;
  1587. side_y = (width_height[1]//64)*64;
  1588. if side_x != width_height[0] or side_y != width_height[1]:
  1589. print(f'Changing output size to {side_x}x{side_y}. Dimensions must by multiples of 64.')
  1590. #Update Model Settings
  1591. timestep_respacing = f'ddim{steps}'
  1592. diffusion_steps = (1000//steps)*steps if steps < 1000 else steps
  1593. model_config.update({
  1594. 'timestep_respacing': timestep_respacing,
  1595. 'diffusion_steps': diffusion_steps,
  1596. })
  1597. #Make folder for batch
  1598. batchFolder = f'{outDirPath}/{batch_name}'
  1599. createPath(batchFolder)
  1600. # %%
  1601. # !! {"metadata": {
  1602. # !! "id": "AnimSetTop"
  1603. # !! }}
  1604. """
  1605. ### Animation Settings
  1606. """
  1607. # %%
  1608. # !! {"metadata": {
  1609. # !! "id": "AnimSettings"
  1610. # !! }}
  1611. #@markdown ####**Animation Mode:**
  1612. animation_mode = 'None' #@param ['None', '2D', '3D', 'Video Input'] {type:'string'}
  1613. #@markdown *For animation, you probably want to turn `cutn_batches` to 1 to make it quicker.*
  1614. #@markdown ---
  1615. #@markdown ####**Video Input Settings:**
  1616. if is_colab:
  1617. video_init_path = "/content/training.mp4" #@param {type: 'string'}
  1618. else:
  1619. video_init_path = "training.mp4" #@param {type: 'string'}
  1620. extract_nth_frame = 2 #@param {type: 'number'}
  1621. video_init_seed_continuity = True #@param {type: 'boolean'}
  1622. if animation_mode == "Video Input":
  1623. if is_colab:
  1624. videoFramesFolder = f'/content/videoFrames'
  1625. else:
  1626. videoFramesFolder = f'videoFrames'
  1627. createPath(videoFramesFolder)
  1628. print(f"Exporting Video Frames (1 every {extract_nth_frame})...")
  1629. try:
  1630. for f in pathlib.Path(f'{videoFramesFolder}').glob('*.jpg'):
  1631. f.unlink()
  1632. except:
  1633. print('')
  1634. vf = f'select=not(mod(n\,{extract_nth_frame}))'
  1635. subprocess.run(['ffmpeg', '-i', f'{video_init_path}', '-vf', f'{vf}', '-vsync', 'vfr', '-q:v', '2', '-loglevel', 'error', '-stats', f'{videoFramesFolder}/%04d.jpg'], stdout=subprocess.PIPE).stdout.decode('utf-8')
  1636. #!ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg
  1637. #@markdown ---
  1638. #@markdown ####**2D Animation Settings:**
  1639. #@markdown `zoom` is a multiplier of dimensions, 1 is no zoom.
  1640. #@markdown All rotations are provided in degrees.
  1641. key_frames = True #@param {type:"boolean"}
  1642. max_frames = 10000#@param {type:"number"}
  1643. if animation_mode == "Video Input":
  1644. max_frames = len(glob(f'{videoFramesFolder}/*.jpg'))
  1645. interp_spline = 'Linear' #Do not change, currently will not look good. param ['Linear','Quadratic','Cubic']{type:"string"}
  1646. angle = "0:(0)"#@param {type:"string"}
  1647. zoom = "0: (1), 10: (1.05)"#@param {type:"string"}
  1648. translation_x = "0: (0)"#@param {type:"string"}
  1649. translation_y = "0: (0)"#@param {type:"string"}
  1650. translation_z = "0: (10.0)"#@param {type:"string"}
  1651. rotation_3d_x = "0: (0)"#@param {type:"string"}
  1652. rotation_3d_y = "0: (0)"#@param {type:"string"}
  1653. rotation_3d_z = "0: (0)"#@param {type:"string"}
  1654. midas_depth_model = "dpt_large"#@param {type:"string"}
  1655. midas_weight = 0.3#@param {type:"number"}
  1656. near_plane = 200#@param {type:"number"}
  1657. far_plane = 10000#@param {type:"number"}
  1658. fov = 40#@param {type:"number"}
  1659. padding_mode = 'border'#@param {type:"string"}
  1660. sampling_mode = 'bicubic'#@param {type:"string"}
  1661. #======= TURBO MODE
  1662. #@markdown ---
  1663. #@markdown ####**Turbo Mode (3D anim only):**
  1664. #@markdown (Starts after frame 10,) skips diffusion steps and just uses depth map to warp images for skipped frames.
  1665. #@markdown Speeds up rendering by 2x-4x, and may improve image coherence between frames. frame_blend_mode smooths abrupt texture changes across 2 frames.
  1666. #@markdown For different settings tuned for Turbo Mode, refer to the original Disco-Turbo Github: https://github.com/zippy731/disco-diffusion-turbo
  1667. turbo_mode = False #@param {type:"boolean"}
  1668. turbo_steps = "3" #@param ["2","3","4","5","6"] {type:"string"}
  1669. turbo_preroll = 10 # frames
  1670. #insist turbo be used only w 3d anim.
  1671. if turbo_mode and animation_mode != '3D':
  1672. print('=====')
  1673. print('Turbo mode only available with 3D animations. Disabling Turbo.')
  1674. print('=====')
  1675. turbo_mode = False
  1676. #@markdown ---
  1677. #@markdown ####**Coherency Settings:**
  1678. #@markdown `frame_scale` tries to guide the new frame to looking like the old one. A good default is 1500.
  1679. frames_scale = 1500 #@param{type: 'integer'}
  1680. #@markdown `frame_skip_steps` will blur the previous frame - higher values will flicker less but struggle to add enough new detail to zoom into.
  1681. frames_skip_steps = '60%' #@param ['40%', '50%', '60%', '70%', '80%'] {type: 'string'}
  1682. #======= VR MODE
  1683. #@markdown ---
  1684. #@markdown ####**VR Mode (3D anim only):**
  1685. #@markdown Enables stereo rendering of left/right eye views (supporting Turbo) which use a different (fish-eye) camera projection matrix.
  1686. #@markdown Note the images you're prompting will work better if they have some inherent wide-angle aspect
  1687. #@markdown The generated images will need to be combined into left/right videos. These can then be stitched into the VR180 format.
  1688. #@markdown Google made the VR180 Creator tool but subsequently stopped supporting it. It's available for download in a few places including https://www.patrickgrunwald.de/vr180-creator-download
  1689. #@markdown The tool is not only good for stitching (videos and photos) but also for adding the correct metadata into existing videos, which is needed for services like YouTube to identify the format correctly.
  1690. #@markdown Watching YouTube VR videos isn't necessarily the easiest depending on your headset. For instance Oculus have a dedicated media studio and store which makes the files easier to access on a Quest https://creator.oculus.com/manage/mediastudio/
  1691. #@markdown
  1692. #@markdown The command to get ffmpeg to concat your frames for each eye is in the form: `ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4` (repeat for r)
  1693. vr_mode = False #@param {type:"boolean"}
  1694. #@markdown `vr_eye_angle` is the y-axis rotation of the eyes towards the center
  1695. vr_eye_angle = 0.5 #@param{type:"number"}
  1696. #@markdown interpupillary distance (between the eyes)
  1697. vr_ipd = 5.0 #@param{type:"number"}
  1698. #insist VR be used only w 3d anim.
  1699. if vr_mode and animation_mode != '3D':
  1700. print('=====')
  1701. print('VR mode only available with 3D animations. Disabling VR.')
  1702. print('=====')
  1703. vr_mode = False
  1704. def parse_key_frames(string, prompt_parser=None):
  1705. """Given a string representing frame numbers paired with parameter values at that frame,
  1706. return a dictionary with the frame numbers as keys and the parameter values as the values.
  1707. Parameters
  1708. ----------
  1709. string: string
  1710. Frame numbers paired with parameter values at that frame number, in the format
  1711. 'framenumber1: (parametervalues1), framenumber2: (parametervalues2), ...'
  1712. prompt_parser: function or None, optional
  1713. If provided, prompt_parser will be applied to each string of parameter values.
  1714. Returns
  1715. -------
  1716. dict
  1717. Frame numbers as keys, parameter values at that frame number as values
  1718. Raises
  1719. ------
  1720. RuntimeError
  1721. If the input string does not match the expected format.
  1722. Examples
  1723. --------
  1724. >>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)")
  1725. {10: 'Apple: 1| Orange: 0', 20: 'Apple: 0| Orange: 1| Peach: 1'}
  1726. >>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)", prompt_parser=lambda x: x.lower()))
  1727. {10: 'apple: 1| orange: 0', 20: 'apple: 0| orange: 1| peach: 1'}
  1728. """
  1729. import re
  1730. pattern = r'((?P<frame>[0-9]+):[\s]*[\(](?P<param>[\S\s]*?)[\)])'
  1731. frames = dict()
  1732. for match_object in re.finditer(pattern, string):
  1733. frame = int(match_object.groupdict()['frame'])
  1734. param = match_object.groupdict()['param']
  1735. if prompt_parser:
  1736. frames[frame] = prompt_parser(param)
  1737. else:
  1738. frames[frame] = param
  1739. if frames == {} and len(string) != 0:
  1740. raise RuntimeError('Key Frame string not correctly formatted')
  1741. return frames
  1742. def get_inbetweens(key_frames, integer=False):
  1743. """Given a dict with frame numbers as keys and a parameter value as values,
  1744. return a pandas Series containing the value of the parameter at every frame from 0 to max_frames.
  1745. Any values not provided in the input dict are calculated by linear interpolation between
  1746. the values of the previous and next provided frames. If there is no previous provided frame, then
  1747. the value is equal to the value of the next provided frame, or if there is no next provided frame,
  1748. then the value is equal to the value of the previous provided frame. If no frames are provided,
  1749. all frame values are NaN.
  1750. Parameters
  1751. ----------
  1752. key_frames: dict
  1753. A dict with integer frame numbers as keys and numerical values of a particular parameter as values.
  1754. integer: Bool, optional
  1755. If True, the values of the output series are converted to integers.
  1756. Otherwise, the values are floats.
  1757. Returns
  1758. -------
  1759. pd.Series
  1760. A Series with length max_frames representing the parameter values for each frame.
  1761. Examples
  1762. --------
  1763. >>> max_frames = 5
  1764. >>> get_inbetweens({1: 5, 3: 6})
  1765. 0 5.0
  1766. 1 5.0
  1767. 2 5.5
  1768. 3 6.0
  1769. 4 6.0
  1770. dtype: float64
  1771. >>> get_inbetweens({1: 5, 3: 6}, integer=True)
  1772. 0 5
  1773. 1 5
  1774. 2 5
  1775. 3 6
  1776. 4 6
  1777. dtype: int64
  1778. """
  1779. key_frame_series = pd.Series([np.nan for a in range(max_frames)])
  1780. for i, value in key_frames.items():
  1781. key_frame_series[i] = value
  1782. key_frame_series = key_frame_series.astype(float)
  1783. interp_method = interp_spline
  1784. if interp_method == 'Cubic' and len(key_frames.items()) <=3:
  1785. interp_method = 'Quadratic'
  1786. if interp_method == 'Quadratic' and len(key_frames.items()) <= 2:
  1787. interp_method = 'Linear'
  1788. key_frame_series[0] = key_frame_series[key_frame_series.first_valid_index()]
  1789. key_frame_series[max_frames-1] = key_frame_series[key_frame_series.last_valid_index()]
  1790. # key_frame_series = key_frame_series.interpolate(method=intrp_method,order=1, limit_direction='both')
  1791. key_frame_series = key_frame_series.interpolate(method=interp_method.lower(),limit_direction='both')
  1792. if integer:
  1793. return key_frame_series.astype(int)
  1794. return key_frame_series
  1795. def split_prompts(prompts):
  1796. prompt_series = pd.Series([np.nan for a in range(max_frames)])
  1797. for i, prompt in prompts.items():
  1798. prompt_series[i] = prompt
  1799. # prompt_series = prompt_series.astype(str)
  1800. prompt_series = prompt_series.ffill().bfill()
  1801. return prompt_series
  1802. if key_frames:
  1803. try:
  1804. angle_series = get_inbetweens(parse_key_frames(angle))
  1805. except RuntimeError as e:
  1806. print(
  1807. "WARNING: You have selected to use key frames, but you have not "
  1808. "formatted `angle` correctly for key frames.\n"
  1809. "Attempting to interpret `angle` as "
  1810. f'"0: ({angle})"\n'
  1811. "Please read the instructions to find out how to use key frames "
  1812. "correctly.\n"
  1813. )
  1814. angle = f"0: ({angle})"
  1815. angle_series = get_inbetweens(parse_key_frames(angle))
  1816. try:
  1817. zoom_series = get_inbetweens(parse_key_frames(zoom))
  1818. except RuntimeError as e:
  1819. print(
  1820. "WARNING: You have selected to use key frames, but you have not "
  1821. "formatted `zoom` correctly for key frames.\n"
  1822. "Attempting to interpret `zoom` as "
  1823. f'"0: ({zoom})"\n'
  1824. "Please read the instructions to find out how to use key frames "
  1825. "correctly.\n"
  1826. )
  1827. zoom = f"0: ({zoom})"
  1828. zoom_series = get_inbetweens(parse_key_frames(zoom))
  1829. try:
  1830. translation_x_series = get_inbetweens(parse_key_frames(translation_x))
  1831. except RuntimeError as e:
  1832. print(
  1833. "WARNING: You have selected to use key frames, but you have not "
  1834. "formatted `translation_x` correctly for key frames.\n"
  1835. "Attempting to interpret `translation_x` as "
  1836. f'"0: ({translation_x})"\n'
  1837. "Please read the instructions to find out how to use key frames "
  1838. "correctly.\n"
  1839. )
  1840. translation_x = f"0: ({translation_x})"
  1841. translation_x_series = get_inbetweens(parse_key_frames(translation_x))
  1842. try:
  1843. translation_y_series = get_inbetweens(parse_key_frames(translation_y))
  1844. except RuntimeError as e:
  1845. print(
  1846. "WARNING: You have selected to use key frames, but you have not "
  1847. "formatted `translation_y` correctly for key frames.\n"
  1848. "Attempting to interpret `translation_y` as "
  1849. f'"0: ({translation_y})"\n'
  1850. "Please read the instructions to find out how to use key frames "
  1851. "correctly.\n"
  1852. )
  1853. translation_y = f"0: ({translation_y})"
  1854. translation_y_series = get_inbetweens(parse_key_frames(translation_y))
  1855. try:
  1856. translation_z_series = get_inbetweens(parse_key_frames(translation_z))
  1857. except RuntimeError as e:
  1858. print(
  1859. "WARNING: You have selected to use key frames, but you have not "
  1860. "formatted `translation_z` correctly for key frames.\n"
  1861. "Attempting to interpret `translation_z` as "
  1862. f'"0: ({translation_z})"\n'
  1863. "Please read the instructions to find out how to use key frames "
  1864. "correctly.\n"
  1865. )
  1866. translation_z = f"0: ({translation_z})"
  1867. translation_z_series = get_inbetweens(parse_key_frames(translation_z))
  1868. try:
  1869. rotation_3d_x_series = get_inbetweens(parse_key_frames(rotation_3d_x))
  1870. except RuntimeError as e:
  1871. print(
  1872. "WARNING: You have selected to use key frames, but you have not "
  1873. "formatted `rotation_3d_x` correctly for key frames.\n"
  1874. "Attempting to interpret `rotation_3d_x` as "
  1875. f'"0: ({rotation_3d_x})"\n'
  1876. "Please read the instructions to find out how to use key frames "
  1877. "correctly.\n"
  1878. )
  1879. rotation_3d_x = f"0: ({rotation_3d_x})"
  1880. rotation_3d_x_series = get_inbetweens(parse_key_frames(rotation_3d_x))
  1881. try:
  1882. rotation_3d_y_series = get_inbetweens(parse_key_frames(rotation_3d_y))
  1883. except RuntimeError as e:
  1884. print(
  1885. "WARNING: You have selected to use key frames, but you have not "
  1886. "formatted `rotation_3d_y` correctly for key frames.\n"
  1887. "Attempting to interpret `rotation_3d_y` as "
  1888. f'"0: ({rotation_3d_y})"\n'
  1889. "Please read the instructions to find out how to use key frames "
  1890. "correctly.\n"
  1891. )
  1892. rotation_3d_y = f"0: ({rotation_3d_y})"
  1893. rotation_3d_y_series = get_inbetweens(parse_key_frames(rotation_3d_y))
  1894. try:
  1895. rotation_3d_z_series = get_inbetweens(parse_key_frames(rotation_3d_z))
  1896. except RuntimeError as e:
  1897. print(
  1898. "WARNING: You have selected to use key frames, but you have not "
  1899. "formatted `rotation_3d_z` correctly for key frames.\n"
  1900. "Attempting to interpret `rotation_3d_z` as "
  1901. f'"0: ({rotation_3d_z})"\n'
  1902. "Please read the instructions to find out how to use key frames "
  1903. "correctly.\n"
  1904. )
  1905. rotation_3d_z = f"0: ({rotation_3d_z})"
  1906. rotation_3d_z_series = get_inbetweens(parse_key_frames(rotation_3d_z))
  1907. else:
  1908. angle = float(angle)
  1909. zoom = float(zoom)
  1910. translation_x = float(translation_x)
  1911. translation_y = float(translation_y)
  1912. translation_z = float(translation_z)
  1913. rotation_3d_x = float(rotation_3d_x)
  1914. rotation_3d_y = float(rotation_3d_y)
  1915. rotation_3d_z = float(rotation_3d_z)
  1916. # %%
  1917. # !! {"metadata": {
  1918. # !! "id": "ExtraSetTop"
  1919. # !! }}
  1920. """
  1921. ### Extra Settings
  1922. Partial Saves, Advanced Settings, Cutn Scheduling
  1923. """
  1924. # %%
  1925. # !! {"metadata": {
  1926. # !! "id": "ExtraSettings"
  1927. # !! }}
  1928. #@markdown ####**Saving:**
  1929. intermediate_saves = 0#@param{type: 'raw'}
  1930. intermediates_in_subfolder = True #@param{type: 'boolean'}
  1931. #@markdown Intermediate steps will save a copy at your specified intervals. You can either format it as a single integer or a list of specific steps
  1932. #@markdown A value of `2` will save a copy at 33% and 66%. 0 will save none.
  1933. #@markdown A value of `[5, 9, 34, 45]` will save at steps 5, 9, 34, and 45. (Make sure to include the brackets)
  1934. if type(intermediate_saves) is not list:
  1935. if intermediate_saves:
  1936. steps_per_checkpoint = math.floor((steps - skip_steps - 1) // (intermediate_saves+1))
  1937. steps_per_checkpoint = steps_per_checkpoint if steps_per_checkpoint > 0 else 1
  1938. print(f'Will save every {steps_per_checkpoint} steps')
  1939. else:
  1940. steps_per_checkpoint = steps+10
  1941. else:
  1942. steps_per_checkpoint = None
  1943. if intermediate_saves and intermediates_in_subfolder is True:
  1944. partialFolder = f'{batchFolder}/partials'
  1945. createPath(partialFolder)
  1946. #@markdown ---
  1947. #@markdown ####**Advanced Settings:**
  1948. #@markdown *There are a few extra advanced settings available if you double click this cell.*
  1949. #@markdown *Perlin init will replace your init, so uncheck if using one.*
  1950. perlin_init = False #@param{type: 'boolean'}
  1951. perlin_mode = 'mixed' #@param ['mixed', 'color', 'gray']
  1952. set_seed = 'random_seed' #@param{type: 'string'}
  1953. eta = 0.8#@param{type: 'number'}
  1954. clamp_grad = True #@param{type: 'boolean'}
  1955. clamp_max = 0.05 #@param{type: 'number'}
  1956. ### EXTRA ADVANCED SETTINGS:
  1957. randomize_class = True
  1958. clip_denoised = False
  1959. fuzzy_prompt = False
  1960. rand_mag = 0.05
  1961. #@markdown ---
  1962. #@markdown ####**Cutn Scheduling:**
  1963. #@markdown Format: `[40]*400+[20]*600` = 40 cuts for the first 400 /1000 steps, then 20 for the last 600/1000
  1964. #@markdown cut_overview and cut_innercut are cumulative for total cutn on any given step. Overview cuts see the entire image and are good for early structure, innercuts are your standard cutn.
  1965. cut_overview = "[12]*400+[4]*600" #@param {type: 'string'}
  1966. cut_innercut ="[4]*400+[12]*600"#@param {type: 'string'}
  1967. cut_ic_pow = 1#@param {type: 'number'}
  1968. cut_icgray_p = "[0.2]*400+[0]*600"#@param {type: 'string'}
  1969. # %%
  1970. # !! {"metadata": {
  1971. # !! "id": "PromptsTop"
  1972. # !! }}
  1973. """
  1974. ### Prompts
  1975. `animation_mode: None` will only use the first set. `animation_mode: 2D / Video` will run through them per the set frames and hold on the last one.
  1976. """
  1977. # %%
  1978. # !! {"metadata": {
  1979. # !! "id": "Prompts"
  1980. # !! }}
  1981. text_prompts = {
  1982. 0: ["A beautiful painting of a singular lighthouse, shining its light across a tumultuous sea of blood by greg rutkowski and thomas kinkade, Trending on artstation.", "yellow color scheme"],
  1983. 100: ["This set of prompts start at frame 100","This prompt has weight five:5"],
  1984. }
  1985. image_prompts = {
  1986. # 0:['ImagePromptsWorkButArentVeryGood.png:2',],
  1987. }
  1988. # %%
  1989. # !! {"metadata": {
  1990. # !! "id": "DiffuseTop"
  1991. # !! }}
  1992. """
  1993. # 4. Diffuse!
  1994. """
  1995. # %%
  1996. # !! {"metadata": {
  1997. # !! "id": "DoTheRun"
  1998. # !! }}
  1999. #@title Do the Run!
  2000. #@markdown `n_batches` ignored with animation modes.
  2001. display_rate = 50 #@param{type: 'number'}
  2002. n_batches = 50 #@param{type: 'number'}
  2003. #Update Model Settings
  2004. timestep_respacing = f'ddim{steps}'
  2005. diffusion_steps = (1000//steps)*steps if steps < 1000 else steps
  2006. model_config.update({
  2007. 'timestep_respacing': timestep_respacing,
  2008. 'diffusion_steps': diffusion_steps,
  2009. })
  2010. batch_size = 1
  2011. def move_files(start_num, end_num, old_folder, new_folder):
  2012. for i in range(start_num, end_num):
  2013. old_file = old_folder + f'/{batch_name}({batchNum})_{i:04}.png'
  2014. new_file = new_folder + f'/{batch_name}({batchNum})_{i:04}.png'
  2015. os.rename(old_file, new_file)
  2016. #@markdown ---
  2017. resume_run = False #@param{type: 'boolean'}
  2018. run_to_resume = 'latest' #@param{type: 'string'}
  2019. resume_from_frame = 'latest' #@param{type: 'string'}
  2020. retain_overwritten_frames = False #@param{type: 'boolean'}
  2021. if retain_overwritten_frames is True:
  2022. retainFolder = f'{batchFolder}/retained'
  2023. createPath(retainFolder)
  2024. skip_step_ratio = int(frames_skip_steps.rstrip("%")) / 100
  2025. calc_frames_skip_steps = math.floor(steps * skip_step_ratio)
  2026. if steps <= calc_frames_skip_steps:
  2027. sys.exit("ERROR: You can't skip more steps than your total steps")
  2028. if resume_run:
  2029. if run_to_resume == 'latest':
  2030. try:
  2031. batchNum
  2032. except:
  2033. batchNum = len(glob(f"{batchFolder}/{batch_name}(*)_settings.txt"))-1
  2034. else:
  2035. batchNum = int(run_to_resume)
  2036. if resume_from_frame == 'latest':
  2037. start_frame = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png"))
  2038. if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:
  2039. start_frame = start_frame - (start_frame % int(turbo_steps))
  2040. else:
  2041. start_frame = int(resume_from_frame)+1
  2042. if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:
  2043. start_frame = start_frame - (start_frame % int(turbo_steps))
  2044. if retain_overwritten_frames is True:
  2045. existing_frames = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png"))
  2046. frames_to_save = existing_frames - start_frame
  2047. print(f'Moving {frames_to_save} frames to the Retained folder')
  2048. move_files(start_frame, existing_frames, batchFolder, retainFolder)
  2049. else:
  2050. start_frame = 0
  2051. batchNum = len(glob(batchFolder+"/*.txt"))
  2052. while os.path.isfile(f"{batchFolder}/{batch_name}({batchNum})_settings.txt") is True or os.path.isfile(f"{batchFolder}/{batch_name}-{batchNum}_settings.txt") is True:
  2053. batchNum += 1
  2054. print(f'Starting Run: {batch_name}({batchNum}) at frame {start_frame}')
  2055. if set_seed == 'random_seed':
  2056. random.seed()
  2057. seed = random.randint(0, 2**32)
  2058. # print(f'Using seed: {seed}')
  2059. else:
  2060. seed = int(set_seed)
  2061. args = {
  2062. 'batchNum': batchNum,
  2063. 'prompts_series':split_prompts(text_prompts) if text_prompts else None,
  2064. 'image_prompts_series':split_prompts(image_prompts) if image_prompts else None,
  2065. 'seed': seed,
  2066. 'display_rate':display_rate,
  2067. 'n_batches':n_batches if animation_mode == 'None' else 1,
  2068. 'batch_size':batch_size,
  2069. 'batch_name': batch_name,
  2070. 'steps': steps,
  2071. 'diffusion_sampling_mode': diffusion_sampling_mode,
  2072. 'width_height': width_height,
  2073. 'clip_guidance_scale': clip_guidance_scale,
  2074. 'tv_scale': tv_scale,
  2075. 'range_scale': range_scale,
  2076. 'sat_scale': sat_scale,
  2077. 'cutn_batches': cutn_batches,
  2078. 'init_image': init_image,
  2079. 'init_scale': init_scale,
  2080. 'skip_steps': skip_steps,
  2081. 'side_x': side_x,
  2082. 'side_y': side_y,
  2083. 'timestep_respacing': timestep_respacing,
  2084. 'diffusion_steps': diffusion_steps,
  2085. 'animation_mode': animation_mode,
  2086. 'video_init_path': video_init_path,
  2087. 'extract_nth_frame': extract_nth_frame,
  2088. 'video_init_seed_continuity': video_init_seed_continuity,
  2089. 'key_frames': key_frames,
  2090. 'max_frames': max_frames if animation_mode != "None" else 1,
  2091. 'interp_spline': interp_spline,
  2092. 'start_frame': start_frame,
  2093. 'angle': angle,
  2094. 'zoom': zoom,
  2095. 'translation_x': translation_x,
  2096. 'translation_y': translation_y,
  2097. 'translation_z': translation_z,
  2098. 'rotation_3d_x': rotation_3d_x,
  2099. 'rotation_3d_y': rotation_3d_y,
  2100. 'rotation_3d_z': rotation_3d_z,
  2101. 'midas_depth_model': midas_depth_model,
  2102. 'midas_weight': midas_weight,
  2103. 'near_plane': near_plane,
  2104. 'far_plane': far_plane,
  2105. 'fov': fov,
  2106. 'padding_mode': padding_mode,
  2107. 'sampling_mode': sampling_mode,
  2108. 'angle_series':angle_series,
  2109. 'zoom_series':zoom_series,
  2110. 'translation_x_series':translation_x_series,
  2111. 'translation_y_series':translation_y_series,
  2112. 'translation_z_series':translation_z_series,
  2113. 'rotation_3d_x_series':rotation_3d_x_series,
  2114. 'rotation_3d_y_series':rotation_3d_y_series,
  2115. 'rotation_3d_z_series':rotation_3d_z_series,
  2116. 'frames_scale': frames_scale,
  2117. 'calc_frames_skip_steps': calc_frames_skip_steps,
  2118. 'skip_step_ratio': skip_step_ratio,
  2119. 'calc_frames_skip_steps': calc_frames_skip_steps,
  2120. 'text_prompts': text_prompts,
  2121. 'image_prompts': image_prompts,
  2122. 'cut_overview': eval(cut_overview),
  2123. 'cut_innercut': eval(cut_innercut),
  2124. 'cut_ic_pow': cut_ic_pow,
  2125. 'cut_icgray_p': eval(cut_icgray_p),
  2126. 'intermediate_saves': intermediate_saves,
  2127. 'intermediates_in_subfolder': intermediates_in_subfolder,
  2128. 'steps_per_checkpoint': steps_per_checkpoint,
  2129. 'perlin_init': perlin_init,
  2130. 'perlin_mode': perlin_mode,
  2131. 'set_seed': set_seed,
  2132. 'eta': eta,
  2133. 'clamp_grad': clamp_grad,
  2134. 'clamp_max': clamp_max,
  2135. 'skip_augs': skip_augs,
  2136. 'randomize_class': randomize_class,
  2137. 'clip_denoised': clip_denoised,
  2138. 'fuzzy_prompt': fuzzy_prompt,
  2139. 'rand_mag': rand_mag,
  2140. }
  2141. args = SimpleNamespace(**args)
  2142. print('Prepping model...')
  2143. model, diffusion = create_model_and_diffusion(**model_config)
  2144. model.load_state_dict(torch.load(f'{model_path}/{diffusion_model}.pt', map_location='cpu'))
  2145. model.requires_grad_(False).eval().to(device)
  2146. for name, param in model.named_parameters():
  2147. if 'qkv' in name or 'norm' in name or 'proj' in name:
  2148. param.requires_grad_()
  2149. if model_config['use_fp16']:
  2150. model.convert_to_fp16()
  2151. gc.collect()
  2152. torch.cuda.empty_cache()
  2153. try:
  2154. do_run()
  2155. except KeyboardInterrupt:
  2156. pass
  2157. finally:
  2158. print('Seed used:', seed)
  2159. gc.collect()
  2160. torch.cuda.empty_cache()
  2161. # %%
  2162. # !! {"metadata": {
  2163. # !! "id": "CreateVidTop"
  2164. # !! }}
  2165. """
  2166. # 5. Create the video
  2167. """
  2168. # %%
  2169. # !! {"metadata": {
  2170. # !! "id": "CreateVid"
  2171. # !! }}
  2172. # @title ### **Create video**
  2173. #@markdown Video file will save in the same folder as your images.
  2174. skip_video_for_run_all = True #@param {type: 'boolean'}
  2175. if skip_video_for_run_all == True:
  2176. print('Skipping video creation, uncheck skip_video_for_run_all if you want to run it')
  2177. else:
  2178. # import subprocess in case this cell is run without the above cells
  2179. import subprocess
  2180. from base64 import b64encode
  2181. latest_run = batchNum
  2182. folder = batch_name #@param
  2183. run = latest_run #@param
  2184. final_frame = 'final_frame'
  2185. init_frame = 1#@param {type:"number"} This is the frame where the video will start
  2186. last_frame = final_frame#@param {type:"number"} You can change i to the number of the last frame you want to generate. It will raise an error if that number of frames does not exist.
  2187. fps = 12#@param {type:"number"}
  2188. # view_video_in_cell = True #@param {type: 'boolean'}
  2189. frames = []
  2190. # tqdm.write('Generating video...')
  2191. if last_frame == 'final_frame':
  2192. last_frame = len(glob(batchFolder+f"/{folder}({run})_*.png"))
  2193. print(f'Total frames: {last_frame}')
  2194. image_path = f"{outDirPath}/{folder}/{folder}({run})_%04d.png"
  2195. filepath = f"{outDirPath}/{folder}/{folder}({run}).mp4"
  2196. cmd = [
  2197. 'ffmpeg',
  2198. '-y',
  2199. '-vcodec',
  2200. 'png',
  2201. '-r',
  2202. str(fps),
  2203. '-start_number',
  2204. str(init_frame),
  2205. '-i',
  2206. image_path,
  2207. '-frames:v',
  2208. str(last_frame+1),
  2209. '-c:v',
  2210. 'libx264',
  2211. '-vf',
  2212. f'fps={fps}',
  2213. '-pix_fmt',
  2214. 'yuv420p',
  2215. '-crf',
  2216. '17',
  2217. '-preset',
  2218. 'veryslow',
  2219. filepath
  2220. ]
  2221. process = subprocess.Popen(cmd, cwd=f'{batchFolder}', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  2222. stdout, stderr = process.communicate()
  2223. if process.returncode != 0:
  2224. print(stderr)
  2225. raise RuntimeError(stderr)
  2226. else:
  2227. print("The video is ready and saved to the images folder")
  2228. # if view_video_in_cell:
  2229. # mp4 = open(filepath,'rb').read()
  2230. # data_url = "data:video/mp4;base64," + b64encode(mp4).decode()
  2231. # display.HTML(f'<video width=400 controls><source src="{data_url}" type="video/mp4"></video>')