├── .gitignore ├── LICENSE ├── README.md ├── assets └── data │ ├── dresscode │ ├── coarse_captions.json │ ├── dresses │ │ ├── im_sketch │ │ │ └── 052012_1.png │ │ ├── im_sketch_unpaired │ │ │ └── 052012_0_052033_1.png │ │ ├── images │ │ │ └── 052012_0.jpg │ │ ├── keypoints │ │ │ ├── 051994_2.json │ │ │ └── 052012_2.json │ │ ├── label_maps │ │ │ ├── 051994_4.png │ │ │ └── 052012_4.png │ │ ├── test_pairs_paired.txt │ │ └── test_pairs_unpaired.txt │ ├── fine_captions.json │ ├── lower_body │ │ ├── im_sketch │ │ │ ├── 050855_1.png │ │ │ └── 050915_1.png │ │ ├── im_sketch_unpaired │ │ │ ├── 050855_0_050908_1.png │ │ │ └── 050915_0_051078_1.png │ │ ├── images │ │ │ ├── 050855_0.jpg │ │ │ └── 050915_0.jpg │ │ ├── keypoints │ │ │ ├── 050855_2.json │ │ │ └── 050915_2.json │ │ ├── label_maps │ │ │ ├── 050855_4.png │ │ │ └── 050915_4.png │ │ ├── test_pairs_paired.txt │ │ └── test_pairs_unpaired.txt │ ├── test_stitchmap │ │ ├── 048462_0.png │ │ ├── 048466_0.png │ │ ├── 050855_0.png │ │ ├── 050915_0.png │ │ ├── 051994_0.png │ │ └── 052012_0.png │ └── upper_body │ │ ├── im_sketch │ │ └── 048462_1.png │ │ ├── im_sketch_unpaired │ │ ├── 048462_0_049951_1.png │ │ └── 048466_0_049534_1.png │ │ ├── images │ │ └── 048462_0.jpg │ │ ├── keypoints │ │ ├── 048462_2.json │ │ └── 048466_2.json │ │ ├── label_maps │ │ ├── 048462_4.png │ │ └── 048466_4.png │ │ ├── test_pairs_paired.txt │ │ └── test_pairs_unpaired.txt │ └── vitonhd │ ├── captions.json │ ├── test │ ├── im_sketch │ │ ├── 03191_00.png │ │ └── 12419_00.png │ ├── im_sketch_unpaired │ │ ├── 03191_00_00349_00.png │ │ └── 12419_00_01944_00.png │ ├── image-parse-v3 │ │ ├── 03191_00.png │ │ └── 12419_00.png │ ├── image │ │ ├── 03191_00.jpg │ │ └── 12419_00.jpg │ └── openpose_json │ │ ├── 03191_00_keypoints.json │ │ └── 12419_00_keypoints.json │ └── test_pairs.txt ├── environment.yml ├── hubconf.py ├── images └── 1.gif ├── output_dresscode ├── test_paired │ └── images │ │ ├── 048462_0.jpg │ │ ├── 050855_0.jpg │ │ ├── 050915_0.jpg │ │ └── 052012_0.jpg └── test_unpaired │ └── images │ ├── 048462_0.jpg │ ├── 050855_0.jpg │ ├── 050915_0.jpg │ └── 052012_0.jpg ├── output_vitonhd ├── test_paired │ └── images │ │ ├── 03191_00.jpg │ │ └── 12419_00.jpg └── test_unpaired │ └── images │ ├── 03191_00.jpg │ └── 12419_00.jpg └── src ├── datasets ├── dresscode.py └── vitonhd.py ├── eval.py ├── mgd_pipelines ├── mgd_pipe.py └── mgd_pipe_disentangled.py └── utils ├── __init__.py ├── arg_parser.py ├── image_composition.py ├── image_from_pipe.py ├── labelmap.py ├── posemap.py └── set_seeds.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/pycharm,visualstudiocode,opencv,python,git 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=pycharm,visualstudiocode,opencv,python,git 3 | 4 | ### Git ### 5 | # Created by git for backups. To disable backups in Git: 6 | # $ git config --global mergetool.keepBackup false 7 | *.orig 8 | 9 | # Created by git when using merge tools for conflicts 10 | *.BACKUP.* 11 | *.BASE.* 12 | *.LOCAL.* 13 | *.REMOTE.* 14 | *_BACKUP_*.txt 15 | *_BASE_*.txt 16 | *_LOCAL_*.txt 17 | *_REMOTE_*.txt 18 | 19 | ### OpenCV ### 20 | #OpenCV for Mac and Linux 21 | #build and release folders 22 | */CMakeFiles 23 | */CMakeCache.txt 24 | */Makefile 25 | */cmake_install.cmake 26 | .DS_Store 27 | 28 | ### PyCharm ### 29 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 30 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 31 | 32 | # User-specific stuff 33 | .idea/**/workspace.xml 34 | .idea/**/tasks.xml 35 | .idea/**/usage.statistics.xml 36 | .idea/**/dictionaries 37 | .idea/**/shelf 38 | 39 | # AWS User-specific 40 | .idea/**/aws.xml 41 | 42 | # Generated files 43 | .idea/**/contentModel.xml 44 | 45 | # Sensitive or high-churn files 46 | .idea/**/dataSources/ 47 | .idea/**/dataSources.ids 48 | .idea/**/dataSources.local.xml 49 | .idea/**/sqlDataSources.xml 50 | .idea/**/dynamic.xml 51 | .idea/**/uiDesigner.xml 52 | .idea/**/dbnavigator.xml 53 | 54 | # Gradle 55 | .idea/**/gradle.xml 56 | .idea/**/libraries 57 | 58 | # Gradle and Maven with auto-import 59 | # When using Gradle or Maven with auto-import, you should exclude module files, 60 | # since they will be recreated, and may cause churn. Uncomment if using 61 | # auto-import. 62 | # .idea/artifacts 63 | # .idea/compiler.xml 64 | # .idea/jarRepositories.xml 65 | # .idea/modules.xml 66 | # .idea/*.iml 67 | # .idea/modules 68 | # *.iml 69 | # *.ipr 70 | 71 | # CMake 72 | cmake-build-*/ 73 | 74 | # Mongo Explorer plugin 75 | .idea/**/mongoSettings.xml 76 | 77 | # File-based project format 78 | *.iws 79 | 80 | # IntelliJ 81 | out/ 82 | 83 | # mpeltonen/sbt-idea plugin 84 | .idea_modules/ 85 | 86 | # JIRA plugin 87 | atlassian-ide-plugin.xml 88 | 89 | # Cursive Clojure plugin 90 | .idea/replstate.xml 91 | 92 | # SonarLint plugin 93 | .idea/sonarlint/ 94 | 95 | # Crashlytics plugin (for Android Studio and IntelliJ) 96 | com_crashlytics_export_strings.xml 97 | crashlytics.properties 98 | crashlytics-build.properties 99 | fabric.properties 100 | 101 | # Editor-based Rest Client 102 | .idea/httpRequests 103 | 104 | # Android studio 3.1+ serialized cache file 105 | .idea/caches/build_file_checksums.ser 106 | 107 | ### PyCharm Patch ### 108 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 109 | 110 | # *.iml 111 | # modules.xml 112 | # .idea/misc.xml 113 | # *.ipr 114 | 115 | # Sonarlint plugin 116 | # https://plugins.jetbrains.com/plugin/7973-sonarlint 117 | .idea/**/sonarlint/ 118 | 119 | # SonarQube Plugin 120 | # https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin 121 | .idea/**/sonarIssues.xml 122 | 123 | # Markdown Navigator plugin 124 | # https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced 125 | .idea/**/markdown-navigator.xml 126 | .idea/**/markdown-navigator-enh.xml 127 | .idea/**/markdown-navigator/ 128 | 129 | # Cache file creation bug 130 | # See https://youtrack.jetbrains.com/issue/JBR-2257 131 | .idea/$CACHE_FILE$ 132 | 133 | # CodeStream plugin 134 | # https://plugins.jetbrains.com/plugin/12206-codestream 135 | .idea/codestream.xml 136 | 137 | # Azure Toolkit for IntelliJ plugin 138 | # https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij 139 | .idea/**/azureSettings.xml 140 | 141 | ### Python ### 142 | # Byte-compiled / optimized / DLL files 143 | __pycache__/ 144 | *.py[cod] 145 | *$py.class 146 | 147 | # C extensions 148 | *.so 149 | 150 | # Distribution / packaging 151 | .Python 152 | build/ 153 | develop-eggs/ 154 | dist/ 155 | downloads/ 156 | eggs/ 157 | .eggs/ 158 | lib/ 159 | lib64/ 160 | parts/ 161 | sdist/ 162 | var/ 163 | wheels/ 164 | share/python-wheels/ 165 | *.egg-info/ 166 | .installed.cfg 167 | *.egg 168 | MANIFEST 169 | 170 | # PyInstaller 171 | # Usually these files are written by a python script from a template 172 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 173 | *.manifest 174 | *.spec 175 | 176 | # Installer logs 177 | pip-log.txt 178 | pip-delete-this-directory.txt 179 | 180 | # Unit test / coverage reports 181 | htmlcov/ 182 | .tox/ 183 | .nox/ 184 | .coverage 185 | .coverage.* 186 | .cache 187 | nosetests.xml 188 | coverage.xml 189 | *.cover 190 | *.py,cover 191 | .hypothesis/ 192 | .pytest_cache/ 193 | cover/ 194 | 195 | # Translations 196 | *.mo 197 | *.pot 198 | 199 | # Django stuff: 200 | *.log 201 | local_settings.py 202 | db.sqlite3 203 | db.sqlite3-journal 204 | 205 | # Flask stuff: 206 | instance/ 207 | .webassets-cache 208 | 209 | # Scrapy stuff: 210 | .scrapy 211 | 212 | # Sphinx documentation 213 | docs/_build/ 214 | 215 | # PyBuilder 216 | .pybuilder/ 217 | target/ 218 | 219 | # Jupyter Notebook 220 | .ipynb_checkpoints 221 | 222 | # IPython 223 | profile_default/ 224 | ipython_config.py 225 | 226 | # pyenv 227 | # For a library or package, you might want to ignore these files since the code is 228 | # intended to run in multiple environments; otherwise, check them in: 229 | # .python-version 230 | 231 | # pipenv 232 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 233 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 234 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 235 | # install all needed dependencies. 236 | #Pipfile.lock 237 | 238 | # poetry 239 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 240 | # This is especially recommended for binary packages to ensure reproducibility, and is more 241 | # commonly ignored for libraries. 242 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 243 | #poetry.lock 244 | 245 | # pdm 246 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 247 | #pdm.lock 248 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 249 | # in version control. 250 | # https://pdm.fming.dev/#use-with-ide 251 | .pdm.toml 252 | 253 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 254 | __pypackages__/ 255 | 256 | # Celery stuff 257 | celerybeat-schedule 258 | celerybeat.pid 259 | 260 | # SageMath parsed files 261 | *.sage.py 262 | 263 | # Environments 264 | .env 265 | .venv 266 | env/ 267 | venv/ 268 | ENV/ 269 | env.bak/ 270 | venv.bak/ 271 | 272 | # Spyder project settings 273 | .spyderproject 274 | .spyproject 275 | 276 | # Rope project settings 277 | .ropeproject 278 | 279 | # mkdocs documentation 280 | /site 281 | 282 | # mypy 283 | .mypy_cache/ 284 | .dmypy.json 285 | dmypy.json 286 | 287 | # Pyre type checker 288 | .pyre/ 289 | 290 | # pytype static type analyzer 291 | .pytype/ 292 | 293 | # Cython debug symbols 294 | cython_debug/ 295 | 296 | # PyCharm 297 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 298 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 299 | # and can be added to the global gitignore or merged into this file. For a more nuclear 300 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 301 | .idea/ 302 | 303 | ### Python Patch ### 304 | # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration 305 | poetry.toml 306 | 307 | # ruff 308 | .ruff_cache/ 309 | 310 | # LSP config files 311 | pyrightconfig.json 312 | 313 | ### VisualStudioCode ### 314 | .vscode/* 315 | !.vscode/settings.json 316 | !.vscode/tasks.json 317 | !.vscode/launch.json 318 | !.vscode/extensions.json 319 | !.vscode/*.code-snippets 320 | 321 | # Local History for Visual Studio Code 322 | .history/ 323 | 324 | # Built Visual Studio Code Extensions 325 | *.vsix 326 | 327 | ### VisualStudioCode Patch ### 328 | # Ignore all local history of files 329 | .history 330 | .ionide 331 | 332 | 333 | images/ 334 | 335 | # End of https://www.toptal.com/developers/gitignore/api/pycharm,visualstudiocode,opencv,python,git -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. Copyright and Similar Rights means copyright and/or similar rights 88 | closely related to copyright including, without limitation, 89 | performance, broadcast, sound recording, and Sui Generis Database 90 | Rights, without regard to how the rights are labeled or 91 | categorized. For purposes of this Public License, the rights 92 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 93 | Rights. 94 | d. Effective Technological Measures means those measures that, in the 95 | absence of proper authority, may not be circumvented under laws 96 | fulfilling obligations under Article 11 of the WIPO Copyright 97 | Treaty adopted on December 20, 1996, and/or similar international 98 | agreements. 99 | 100 | e. Exceptions and Limitations means fair use, fair dealing, and/or 101 | any other exception or limitation to Copyright and Similar Rights 102 | that applies to Your use of the Licensed Material. 103 | 104 | f. Licensed Material means the artistic or literary work, database, 105 | or other material to which the Licensor applied this Public 106 | License. 107 | 108 | g. Licensed Rights means the rights granted to You subject to the 109 | terms and conditions of this Public License, which are limited to 110 | all Copyright and Similar Rights that apply to Your use of the 111 | Licensed Material and that the Licensor has authority to license. 112 | 113 | h. Licensor means the individual(s) or entity(ies) granting rights 114 | under this Public License. 115 | 116 | i. NonCommercial means not primarily intended for or directed towards 117 | commercial advantage or monetary compensation. For purposes of 118 | this Public License, the exchange of the Licensed Material for 119 | other material subject to Copyright and Similar Rights by digital 120 | file-sharing or similar means is NonCommercial provided there is 121 | no payment of monetary compensation in connection with the 122 | exchange. 123 | 124 | j. Share means to provide material to the public by any means or 125 | process that requires permission under the Licensed Rights, such 126 | as reproduction, public display, public performance, distribution, 127 | dissemination, communication, or importation, and to make material 128 | available to the public including in ways that members of the 129 | public may access the material from a place and at a time 130 | individually chosen by them. 131 | 132 | k. Sui Generis Database Rights means rights other than copyright 133 | resulting from Directive 96/9/EC of the European Parliament and of 134 | the Council of 11 March 1996 on the legal protection of databases, 135 | as amended and/or succeeded, as well as other essentially 136 | equivalent rights anywhere in the world. 137 | 138 | l. You means the individual or entity exercising the Licensed Rights 139 | under this Public License. Your has a corresponding meaning. 140 | 141 | 142 | Section 2 -- Scope. 143 | 144 | a. License grant. 145 | 146 | 1. Subject to the terms and conditions of this Public License, 147 | the Licensor hereby grants You a worldwide, royalty-free, 148 | non-sublicensable, non-exclusive, irrevocable license to 149 | exercise the Licensed Rights in the Licensed Material to: 150 | 151 | a. reproduce and Share the Licensed Material, in whole or 152 | in part, for NonCommercial purposes only; and 153 | 154 | b. produce, reproduce, and Share Adapted Material for 155 | NonCommercial purposes only. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. No downstream restrictions. You may not offer or impose 186 | any additional or different terms or conditions on, or 187 | apply any Effective Technological Measures to, the 188 | Licensed Material if doing so restricts exercise of the 189 | Licensed Rights by any recipient of the Licensed 190 | Material. 191 | 192 | 6. No endorsement. Nothing in this Public License constitutes or 193 | may be construed as permission to assert or imply that You 194 | are, or that Your use of the Licensed Material is, connected 195 | with, or sponsored, endorsed, or granted official status by, 196 | the Licensor or others designated to receive attribution as 197 | provided in Section 3(a)(1)(A)(i). 198 | 199 | b. Other rights. 200 | 201 | 1. Moral rights, such as the right of integrity, are not 202 | licensed under this Public License, nor are publicity, 203 | privacy, and/or other similar personality rights; however, to 204 | the extent possible, the Licensor waives and/or agrees not to 205 | assert any such rights held by the Licensor to the limited 206 | extent necessary to allow You to exercise the Licensed 207 | Rights, but not otherwise. 208 | 209 | 2. Patent and trademark rights are not licensed under this 210 | Public License. 211 | 212 | 3. To the extent possible, the Licensor waives any right to 213 | collect royalties from You for the exercise of the Licensed 214 | Rights, whether directly or through a collecting society 215 | under any voluntary or waivable statutory or compulsory 216 | licensing scheme. In all other cases the Licensor expressly 217 | reserves any right to collect such royalties, including when 218 | the Licensed Material is used other than for NonCommercial 219 | purposes. 220 | 221 | 222 | Section 3 -- License Conditions. 223 | 224 | Your exercise of the Licensed Rights is expressly made subject to the 225 | following conditions. 226 | 227 | a. Attribution. 228 | 229 | 1. If You Share the Licensed Material (including in modified 230 | form), You must: 231 | 232 | a. retain the following if it is supplied by the Licensor 233 | with the Licensed Material: 234 | 235 | i. identification of the creator(s) of the Licensed 236 | Material and any others designated to receive 237 | attribution, in any reasonable manner requested by 238 | the Licensor (including by pseudonym if 239 | designated); 240 | 241 | ii. a copyright notice; 242 | 243 | iii. a notice that refers to this Public License; 244 | 245 | iv. a notice that refers to the disclaimer of 246 | warranties; 247 | 248 | v. a URI or hyperlink to the Licensed Material to the 249 | extent reasonably practicable; 250 | 251 | b. indicate if You modified the Licensed Material and 252 | retain an indication of any previous modifications; and 253 | 254 | c. indicate the Licensed Material is licensed under this 255 | Public License, and include the text of, or the URI or 256 | hyperlink to, this Public License. 257 | 258 | 2. You may satisfy the conditions in Section 3(a)(1) in any 259 | reasonable manner based on the medium, means, and context in 260 | which You Share the Licensed Material. For example, it may be 261 | reasonable to satisfy the conditions by providing a URI or 262 | hyperlink to a resource that includes the required 263 | information. 264 | 265 | 3. If requested by the Licensor, You must remove any of the 266 | information required by Section 3(a)(1)(A) to the extent 267 | reasonably practicable. 268 | 269 | 4. If You Share Adapted Material You produce, the Adapter's 270 | License You apply must not prevent recipients of the Adapted 271 | Material from complying with this Public License. 272 | 273 | 274 | Section 4 -- Sui Generis Database Rights. 275 | 276 | Where the Licensed Rights include Sui Generis Database Rights that 277 | apply to Your use of the Licensed Material: 278 | 279 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 280 | to extract, reuse, reproduce, and Share all or a substantial 281 | portion of the contents of the database for NonCommercial purposes 282 | only; 283 | 284 | b. if You include all or a substantial portion of the database 285 | contents in a database in which You have Sui Generis Database 286 | Rights, then the database in which You have Sui Generis Database 287 | Rights (but not its individual contents) is Adapted Material; and 288 | 289 | c. You must comply with the conditions in Section 3(a) if You Share 290 | all or a substantial portion of the contents of the database. 291 | 292 | For the avoidance of doubt, this Section 4 supplements and does not 293 | replace Your obligations under this Public License where the Licensed 294 | Rights include other Copyright and Similar Rights. 295 | 296 | 297 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 298 | 299 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 300 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 301 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 302 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 303 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 304 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 305 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 306 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 307 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 308 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 309 | 310 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 311 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 312 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 313 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 314 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 315 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 316 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 317 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 318 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 319 | 320 | c. The disclaimer of warranties and limitation of liability provided 321 | above shall be interpreted in a manner that, to the extent 322 | possible, most closely approximates an absolute disclaimer and 323 | waiver of all liability. 324 | 325 | 326 | Section 6 -- Term and Termination. 327 | 328 | a. This Public License applies for the term of the Copyright and 329 | Similar Rights licensed here. However, if You fail to comply with 330 | this Public License, then Your rights under this Public License 331 | terminate automatically. 332 | 333 | b. Where Your right to use the Licensed Material has terminated under 334 | Section 6(a), it reinstates: 335 | 336 | 1. automatically as of the date the violation is cured, provided 337 | it is cured within 30 days of Your discovery of the 338 | violation; or 339 | 340 | 2. upon express reinstatement by the Licensor. 341 | 342 | For the avoidance of doubt, this Section 6(b) does not affect any 343 | right the Licensor may have to seek remedies for Your violations 344 | of this Public License. 345 | 346 | c. For the avoidance of doubt, the Licensor may also offer the 347 | Licensed Material under separate terms or conditions or stop 348 | distributing the Licensed Material at any time; however, doing so 349 | will not terminate this Public License. 350 | 351 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 352 | License. 353 | 354 | 355 | Section 7 -- Other Terms and Conditions. 356 | 357 | a. The Licensor shall not be bound by any additional or different 358 | terms or conditions communicated by You unless expressly agreed. 359 | 360 | b. Any arrangements, understandings, or agreements regarding the 361 | Licensed Material not stated herein are separate from and 362 | independent of the terms and conditions of this Public License. 363 | 364 | 365 | Section 8 -- Interpretation. 366 | 367 | a. For the avoidance of doubt, this Public License does not, and 368 | shall not be interpreted to, reduce, limit, restrict, or impose 369 | conditions on any use of the Licensed Material that could lawfully 370 | be made without permission under this Public License. 371 | 372 | b. To the extent possible, if any provision of this Public License is 373 | deemed unenforceable, it shall be automatically reformed to the 374 | minimum extent necessary to make it enforceable. If the provision 375 | cannot be reformed, it shall be severed from this Public License 376 | without affecting the enforceability of the remaining terms and 377 | conditions. 378 | 379 | c. No term or condition of this Public License will be waived and no 380 | failure to comply consented to unless expressly agreed to by the 381 | Licensor. 382 | 383 | d. Nothing in this Public License constitutes or may be interpreted 384 | as a limitation upon, or waiver of, any privileges and immunities 385 | that apply to the Licensor or You, including from the legal 386 | processes of any jurisdiction or authority. 387 | 388 | ======================================================================= 389 | 390 | Creative Commons is not a party to its public 391 | licenses. Notwithstanding, Creative Commons may elect to apply one of 392 | its public licenses to material it publishes and in those instances 393 | will be considered the "Licensor." The text of the Creative Commons 394 | public licenses is dedicated to the public domain under the CC0 Public 395 | Domain Dedication. Except for the limited purpose of indicating that 396 | material is shared under a Creative Commons public license or as 397 | otherwise permitted by the Creative Commons policies published at 398 | creativecommons.org/policies, Creative Commons does not authorize the 399 | use of the trademark "Creative Commons" or any other trademark or logo 400 | of Creative Commons without its prior written consent including, 401 | without limitation, in connection with any unauthorized modifications 402 | to any of its public licenses or any other arrangements, 403 | understandings, or agreements concerning use of licensed material. For 404 | the avoidance of doubt, this paragraph does not form part of the 405 | public licenses. 406 | 407 | Creative Commons may be contacted at creativecommons.org. 408 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Multimodal Garment Designer (ICCV 2023) 2 | ### Human-Centric Latent Diffusion Models for Fashion Image Editing 3 | [**Alberto Baldrati**](https://scholar.google.com/citations?hl=en&user=I1jaZecAAAAJ)**\***, 4 | [**Davide Morelli**](https://scholar.google.com/citations?user=UJ4D3rYAAAAJ&hl=en)**\***, 5 | [**Giuseppe Cartella**](https://scholar.google.com/citations?hl=en&user=0sJ4VCcAAAAJ), 6 | [**Marcella Cornia**](https://scholar.google.com/citations?hl=en&user=DzgmSJEAAAAJ), 7 | [**Marco Bertini**](https://scholar.google.com/citations?user=SBm9ZpYAAAAJ&hl=en), 8 | [**Rita Cucchiara**](https://scholar.google.com/citations?hl=en&user=OM3sZEoAAAAJ) 9 | 10 | **\*** Equal contribution. 11 | 12 | [![arXiv](https://img.shields.io/badge/arXiv-Paper-.svg)](https://arxiv.org/abs/2304.02051) 13 | [![GitHub Stars](https://img.shields.io/github/stars/aimagelab/multimodal-garment-designer?style=social)](https://github.com/aimagelab/multimodal-garment-designer) 14 | 15 | This is the **official repository** for the [**paper**](https://arxiv.org/abs/2304.02051) "*Multimodal Garment Designer: Human-Centric Latent Diffusion Models for Fashion Image Editing*". 16 | 17 | 🔥🔥 **[21/03/2024] If you are interested in multimodal fashion image editing take a look at our most recent work [Multimodal-Conditioned Latent Diffusion Models for Fashion Image Editing](https://arxiv.org/abs/2403.14828). We introduce Ti-MGD a novel approach that also integrates fabric texture conditioning [![Repo](https://badgen.net/badge/icon/GitHub?icon=github&label)](https://github.com/aimagelab/Ti-MGD)** 18 | 19 | ## Overview 20 | 21 |

22 | 23 |

24 | 25 | >**Abstract**:
26 | > Fashion illustration is used by designers to communicate their vision and to bring the design idea from conceptualization to realization, showing how clothes interact with the human body. In this context, computer vision can thus be used to improve the fashion design process. Differently from previous works that mainly focused on the virtual try-on of garments, we propose the task of multimodal-conditioned fashion image editing, guiding the generation of human-centric fashion images by following multimodal prompts, such as text, human body poses, and garment sketches. We tackle this problem by proposing a new architecture based on latent diffusion models, an approach that has not been used before in the fashion domain. Given the lack of existing datasets suitable for the task, we also extend two existing fashion datasets, namely Dress Code and VITON-HD, with multimodal annotations collected in a semi-automatic manner. Experimental results on these new datasets demonstrate the effectiveness of our proposal, both in terms of realism and coherence with the given multimodal inputs. 27 | 28 | ## Citation 29 | If you make use of our work, please cite our paper: 30 | 31 | ```bibtex 32 | @inproceedings{baldrati2023multimodal, 33 | title={Multimodal Garment Designer: Human-Centric Latent Diffusion Models for Fashion Image Editing}, 34 | author={Baldrati, Alberto and Morelli, Davide and Cartella, Giuseppe and Cornia, Marcella and Bertini, Marco and Cucchiara, Rita}, 35 | booktitle={Proceedings of the IEEE/CVF International Conference on Computer Vision}, 36 | year={2023} 37 | } 38 | ``` 39 | 40 | ## Getting Started 41 | 42 | We recommend using the [**Anaconda**](https://www.anaconda.com/) package manager to avoid dependency/reproducibility 43 | problems. 44 | For Linux systems, you can find a conda installation 45 | guide [here](https://docs.conda.io/projects/conda/en/latest/user-guide/install/linux.html). 46 | 47 | ### Installation 48 | 49 | 1. Clone the repository 50 | 51 | ```sh 52 | git clone https://github.com/aimagelab/multimodal-garment-designer 53 | ``` 54 | 55 | 2. Install Python dependencies 56 | 57 | ```sh 58 | conda env create -n mgd -f environment.yml 59 | conda activate mgd 60 | ``` 61 | 62 | Alternatively, you can create a new conda environment and install the required packages manually: 63 | 64 | ```sh 65 | conda create -n mgd -y python=3.9 66 | conda activate mgd 67 | pip install torch==1.12.1 torchmetrics==0.11.0 opencv-python==4.7.0.68 diffusers==0.12.0 transformers==4.25.1 accelerate==0.15.0 clean-fid==0.1.35 torchmetrics[image]==0.11.0 68 | ``` 69 | 70 | ## Inference 71 | 72 | To run the inference please use the following: 73 | 74 | ``` 75 | python src/eval.py --dataset_path --batch_size --mixed_precision fp16 --output_dir --save_name --num_workers_test --sketch_cond_rate 0.2 --dataset --start_cond_rate 0.0 --test_order 76 | ``` 77 | 78 | - ```dataset_path``` is the path to the dataset (change accordingly to the dataset parameter) 79 | - ```dataset``` dataset name to be used 80 | - ```output_dir``` path to the output directory 81 | - ```save_name``` name of the output dir subfolder where the generated images are saved 82 | - ```start_cond_rate``` rate {0.0,1.0} of denoising steps that will be used as offset to start sketch conditioning 83 | - ```sketch_cond_rate``` rate {0.0,1.0} of denoising steps in which sketch cond is applied 84 | - ```test_order``` test setting (paired | unpaired) 85 | 86 | Note that we provide a few sample images to test MGD simply by cloning this repo (*i.e.*, assets/data). To execute the code set 87 | - Dress Code Multimodal dataset 88 | - ```dataset_path``` to ```../assets/data/dresscode``` 89 | - ```dataset``` to ```dresscode``` 90 | - Viton-HD Multimodal dataset 91 | - ```dataset_path``` to ```../assets/data/vitonhd``` 92 | - ```dataset``` to ```vitonhd``` 93 | 94 | It is possible to run the inference on the whole Dress Code Multimodal or Viton-HD Multimodal dataset simply changing the ```dataset_path``` and ```dataset``` according with the downloaded and prepared datasets (see sections below). 95 | 96 | 97 | ## Pre-trained models 98 | The model and checkpoints are available via torch.hub. 99 | 100 | Load the MGD denoising UNet model using the following code: 101 | 102 | ``` 103 | import torch 104 | unet = torch.hub.load( 105 | dataset=, 106 | repo_or_dir='aimagelab/multimodal-garment-designer', 107 | source='github', 108 | model='mgd', 109 | pretrained=True 110 | ) 111 | ``` 112 | 113 | - ```dataset``` dataset name (dresscode | vitonhd) 114 | 115 | Use the denoising network with our custom diffusers pipeline as follow: 116 | 117 | ``` 118 | from src.mgd_pipelines.mgd_pipe import MGDPipe 119 | from diffusers import AutoencoderKL, DDIMScheduler 120 | from transformers import CLIPTextModel, CLIPTokenizer 121 | 122 | pretrained_model_name_or_path = "runwayml/stable-diffusion-inpainting" 123 | 124 | text_encoder = CLIPTextModel.from_pretrained( 125 | pretrained_model_name_or_path, 126 | subfolder="text_encoder" 127 | ) 128 | 129 | vae = AutoencoderKL.from_pretrained( 130 | pretrained_model_name_or_path, 131 | subfolder="vae" 132 | ) 133 | 134 | tokenizer = CLIPTokenizer.from_pretrained( 135 | pretrained_model_name_or_path, 136 | subfolder="tokenizer", 137 | ) 138 | 139 | val_scheduler = DDIMScheduler.from_pretrained( 140 | pretrained_model_name_or_path, 141 | subfolder="scheduler" 142 | ) 143 | val_scheduler.set_timesteps(50) 144 | 145 | mgd_pipe = MGDPipe( 146 | text_encoder=text_encoder, 147 | vae=vae, 148 | unet=unet, 149 | tokenizer=tokenizer, 150 | scheduler=val_scheduler, 151 | ) 152 | ``` 153 | 154 | For an extensive usage case see the file ```eval.py``` in the main repo. 155 | 156 | ## Datasets 157 | We do not hold rights on the original Dress Code and Viton-HD datasets. Please refer to the original papers for more information. 158 | 159 | Start by downloading the original datasets from the following links: 160 | - Viton-HD **[[link](https://github.com/shadow2496/VITON-HD)]** 161 | - Dress Code **[[link](https://github.com/aimagelab/dress-code)]** 162 | 163 | 164 | Download the Dress Code Multimodal and Viton-HD Multimodal additional data annotations from here. 165 | 166 | - Dress Code Multimodal **[[link](https://drive.google.com/file/d/1dwnAi1CNmmF_YdbIDfm8078dGh4ci47L/view?usp=sharing)]** 167 | - Viton-HD Multimodal **[[link](https://drive.google.com/file/d/1Z2b9YkyBPA_9ZDC54Y5muW9Q8yfAqWSH/view?usp=sharing)]** 168 | 169 | ### Dress Code Multimodal Data Preparation 170 | Once data is downloaded prepare the dataset folder as follows: 171 | 172 |
173 | Dress Code
174 | | fine_captions.json
175 | | coarse_captions.json
176 | | test_pairs_paired.txt
177 | | test_pairs_unpaired.txt
178 | | train_pairs.txt
179 | | test_stitch_map
180 | |---- [category]
181 | |-------- images
182 | |-------- keypoints
183 | |-------- skeletons
184 | |-------- dense
185 | |-------- im_sketch
186 | |-------- im_sketch_unpaired
187 | ...
188 | 
189 | 190 | ### Viton-HD Multimodal Data Preparation 191 | Once data is downloaded prepare the dataset folder as follows: 192 | 193 |
194 | Viton-HD
195 | | captions.json
196 | |---- train
197 | |-------- image
198 | |-------- cloth
199 | |-------- image-parse-v3
200 | |-------- openpose_json
201 | |-------- im_sketch
202 | |-------- im_sketch_unpaired
203 | ...
204 | |---- test
205 | ...
206 | |-------- im_sketch
207 | |-------- im_sketch_unpaired
208 | ...
209 | 
210 | 211 | 212 | ## TODO 213 | - [ ] training code 214 | 215 | ## Acknowledgements 216 | This work has partially been supported by the PNRR project “Future Artificial Intelligence Research (FAIR)”, by the PRIN project “CREATIVE: CRoss-modal understanding and gEnerATIon of Visual and tExtual content” (CUP B87G22000460001), both co-funded by the Italian Ministry of University and Research, and by the European Commission under European Horizon 2020 Programme, grant number 101004545 - ReInHerit. 217 | 218 | ## LICENSE 219 | Creative Commons License
All material is available under [Creative Commons BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/). You can **use, redistribute, and adapt** the material for **non-commercial purposes**, as long as you give appropriate credit by **citing our paper** and **indicate any changes** you've made. 220 | -------------------------------------------------------------------------------- /assets/data/dresscode/dresses/im_sketch/052012_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/dresses/im_sketch/052012_1.png -------------------------------------------------------------------------------- /assets/data/dresscode/dresses/im_sketch_unpaired/052012_0_052033_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/dresses/im_sketch_unpaired/052012_0_052033_1.png -------------------------------------------------------------------------------- /assets/data/dresscode/dresses/images/052012_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/dresses/images/052012_0.jpg -------------------------------------------------------------------------------- /assets/data/dresscode/dresses/keypoints/051994_2.json: -------------------------------------------------------------------------------- 1 | {"keypoints": [[205.0, 0.0, 0.7454180121421814, 0.0], [193.0, 54.0, 0.9695595502853394, 1.0], [153.0, 46.0, 0.9210028052330017, 2.0], [163.0, 133.0, 0.8196305632591248, 3.0], [182.0, 193.0, 0.8251658082008362, 4.0], [234.0, 59.0, 0.9184455871582031, 5.0], [252.0, 133.0, 0.9567239880561829, 6.0], [186.0, 139.0, 0.8934434652328491, 7.0], [180.0, 199.0, 0.803178071975708, 8.0], [164.0, 323.0, 0.9721584916114807, 9.0], [140.0, 438.0, 0.8884657025337219, 10.0], [230.0, 199.0, 0.7910050749778748, 11.0], [223.0, 322.0, 0.8632205128669739, 12.0], [211.0, 436.0, 0.8701340556144714, 13.0], [197.0, 0.0, 0.5216715931892395, 14.0], [214.0, 0.0, 0.610032856464386, 15.0], [186.0, 0.0, 0.5596458911895752, 16.0], [224.0, 0.0, 0.6544457077980042, 17.0]]} -------------------------------------------------------------------------------- /assets/data/dresscode/dresses/keypoints/052012_2.json: -------------------------------------------------------------------------------- 1 | {"keypoints": [[209.0, 0.0, 0.5854654312133789, 0.0], [194.0, 46.0, 0.9134835004806519, 1.0], [152.0, 37.0, 0.9346101880073547, 2.0], [137.0, 118.0, 0.8949743509292603, 3.0], [142.0, 188.0, 0.9262046813964844, 4.0], [235.0, 53.0, 0.9443597793579102, 5.0], [242.0, 134.0, 0.8160827159881592, 6.0], [249.0, 208.0, 0.7443605065345764, 7.0], [167.0, 194.0, 0.8199771046638489, 8.0], [160.0, 319.0, 0.907497763633728, 9.0], [143.0, 447.0, 0.8496435284614563, 10.0], [224.0, 195.0, 0.7766034007072449, 11.0], [214.0, 307.0, 0.8796323537826538, 12.0], [195.0, 430.0, 0.9041213393211365, 13.0], [201.0, 0.0, 0.36648842692375183, 14.0], [217.0, 0.0, 0.44042539596557617, 15.0], [187.0, 0.0, 0.40841901302337646, 16.0], [227.0, 0.0, 0.2826925814151764, 17.0]]} -------------------------------------------------------------------------------- /assets/data/dresscode/dresses/label_maps/051994_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/dresses/label_maps/051994_4.png -------------------------------------------------------------------------------- /assets/data/dresscode/dresses/label_maps/052012_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/dresses/label_maps/052012_4.png -------------------------------------------------------------------------------- /assets/data/dresscode/dresses/test_pairs_paired.txt: -------------------------------------------------------------------------------- 1 | 052012_0.jpg 052012_1.jpg -------------------------------------------------------------------------------- /assets/data/dresscode/dresses/test_pairs_unpaired.txt: -------------------------------------------------------------------------------- 1 | 052012_0.jpg 052033_1.jpg -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/im_sketch/050855_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/lower_body/im_sketch/050855_1.png -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/im_sketch/050915_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/lower_body/im_sketch/050915_1.png -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/im_sketch_unpaired/050855_0_050908_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/lower_body/im_sketch_unpaired/050855_0_050908_1.png -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/im_sketch_unpaired/050915_0_051078_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/lower_body/im_sketch_unpaired/050915_0_051078_1.png -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/images/050855_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/lower_body/images/050855_0.jpg -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/images/050915_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/lower_body/images/050915_0.jpg -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/keypoints/050855_2.json: -------------------------------------------------------------------------------- 1 | {"keypoints": [[183.0, 0.0, 0.5823147296905518, 0.0], [208.0, 53.0, 0.9465193152427673, 1.0], [166.0, 48.0, 0.9355934262275696, 2.0], [149.0, 138.0, 0.8791153430938721, 3.0], [142.0, 213.0, 0.9196943640708923, 4.0], [249.0, 54.0, 0.9031239151954651, 5.0], [257.0, 143.0, 0.8434740900993347, 6.0], [269.0, 214.0, 0.9049280881881714, 7.0], [181.0, 196.0, 0.7393415570259094, 8.0], [162.0, 321.0, 0.8804817795753479, 9.0], [125.0, 435.0, 0.8968222141265869, 10.0], [235.0, 199.0, 0.7837328314781189, 11.0], [233.0, 322.0, 0.927562415599823, 12.0], [217.0, 439.0, 0.8323052525520325, 13.0], [176.0, 0.0, 0.2889324426651001, 14.0], [190.0, 0.0, 0.395557701587677, 15.0], [-1.0, -1.0, 0.0, -1.0], [213.0, 0.0, 0.4816431403160095, 16.0]]} -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/keypoints/050915_2.json: -------------------------------------------------------------------------------- 1 | {"keypoints": [[204.0, 0.0, 0.7293938398361206, 0.0], [199.0, 62.0, 0.9325352907180786, 1.0], [152.0, 67.0, 0.9000401496887207, 2.0], [144.0, 146.0, 0.9149616956710815, 3.0], [132.0, 213.0, 0.8797067999839783, 4.0], [246.0, 59.0, 0.8685039281845093, 5.0], [279.0, 135.0, 0.9230703115463257, 6.0], [228.0, 163.0, 0.908068835735321, 7.0], [160.0, 218.0, 0.8140541315078735, 8.0], [160.0, 327.0, 0.9113076329231262, 9.0], [162.0, 432.0, 0.8555663228034973, 10.0], [220.0, 218.0, 0.7834039926528931, 11.0], [227.0, 327.0, 0.8965063691139221, 12.0], [225.0, 434.0, 0.876929759979248, 13.0], [190.0, 0.0, 0.510018527507782, 14.0], [211.0, 0.0, 0.48887312412261963, 15.0], [172.0, 0.0, 0.6903271079063416, 16.0], [219.0, 0.0, 0.19232189655303955, 17.0]]} -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/label_maps/050855_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/lower_body/label_maps/050855_4.png -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/label_maps/050915_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/lower_body/label_maps/050915_4.png -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/test_pairs_paired.txt: -------------------------------------------------------------------------------- 1 | 050855_0.jpg 050855_1.jpg 2 | 050915_0.jpg 050915_1.jpg 3 | -------------------------------------------------------------------------------- /assets/data/dresscode/lower_body/test_pairs_unpaired.txt: -------------------------------------------------------------------------------- 1 | 050855_0.jpg 050908_1.jpg 2 | 050915_0.jpg 051078_1.jpg 3 | -------------------------------------------------------------------------------- /assets/data/dresscode/test_stitchmap/048462_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/test_stitchmap/048462_0.png -------------------------------------------------------------------------------- /assets/data/dresscode/test_stitchmap/048466_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/test_stitchmap/048466_0.png -------------------------------------------------------------------------------- /assets/data/dresscode/test_stitchmap/050855_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/test_stitchmap/050855_0.png -------------------------------------------------------------------------------- /assets/data/dresscode/test_stitchmap/050915_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/test_stitchmap/050915_0.png -------------------------------------------------------------------------------- /assets/data/dresscode/test_stitchmap/051994_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/test_stitchmap/051994_0.png -------------------------------------------------------------------------------- /assets/data/dresscode/test_stitchmap/052012_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/test_stitchmap/052012_0.png -------------------------------------------------------------------------------- /assets/data/dresscode/upper_body/im_sketch/048462_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/upper_body/im_sketch/048462_1.png -------------------------------------------------------------------------------- /assets/data/dresscode/upper_body/im_sketch_unpaired/048462_0_049951_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/upper_body/im_sketch_unpaired/048462_0_049951_1.png -------------------------------------------------------------------------------- /assets/data/dresscode/upper_body/im_sketch_unpaired/048466_0_049534_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/upper_body/im_sketch_unpaired/048466_0_049534_1.png -------------------------------------------------------------------------------- /assets/data/dresscode/upper_body/images/048462_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/upper_body/images/048462_0.jpg -------------------------------------------------------------------------------- /assets/data/dresscode/upper_body/keypoints/048462_2.json: -------------------------------------------------------------------------------- 1 | {"keypoints": [[141.0, 0.0, 0.5669732689857483, 0.0], [138.0, 52.0, 0.9372020363807678, 1.0], [97.0, 51.0, 0.9566869735717773, 2.0], [91.0, 127.0, 0.9176412224769592, 3.0], [92.0, 196.0, 0.9124826192855835, 4.0], [175.0, 52.0, 0.9164174795150757, 5.0], [190.0, 126.0, 0.9348884224891663, 6.0], [200.0, 192.0, 0.9007474780082703, 7.0], [121.0, 186.0, 0.8528367280960083, 8.0], [131.0, 298.0, 0.9579567909240723, 9.0], [147.0, 408.0, 0.9156394600868225, 10.0], [171.0, 184.0, 0.8514549732208252, 11.0], [188.0, 299.0, 0.98090660572052, 12.0], [207.0, 421.0, 0.8863993287086487, 13.0], [133.0, 0.0, 0.38882675766944885, 14.0], [148.0, 0.0, 0.43583664298057556, 15.0], [120.0, 0.0, 0.44555413722991943, 16.0], [159.0, 0.0, 0.3003842532634735, 17.0]]} -------------------------------------------------------------------------------- /assets/data/dresscode/upper_body/keypoints/048466_2.json: -------------------------------------------------------------------------------- 1 | {"keypoints": [[200.0, 0.0, 0.688823401927948, 0.0], [201.0, 49.0, 0.9461612105369568, 1.0], [162.0, 46.0, 0.9666376709938049, 2.0], [151.0, 113.0, 0.938896894454956, 3.0], [146.0, 177.0, 0.9722222685813904, 4.0], [238.0, 52.0, 0.9425340890884399, 5.0], [247.0, 117.0, 0.9355710744857788, 6.0], [246.0, 180.0, 0.9147509932518005, 7.0], [170.0, 173.0, 0.8584168553352356, 8.0], [159.0, 281.0, 0.938974916934967, 9.0], [156.0, 372.0, 0.9198458790779114, 10.0], [221.0, 173.0, 0.8431934714317322, 11.0], [219.0, 280.0, 0.9141676425933838, 12.0], [214.0, 367.0, 0.944513201713562, 13.0], [192.0, 0.0, 0.4936670660972595, 14.0], [208.0, 0.0, 0.5329393148422241, 15.0], [182.0, 0.0, 0.4606328308582306, 16.0], [219.0, 0.0, 0.460784375667572, 17.0]]} -------------------------------------------------------------------------------- /assets/data/dresscode/upper_body/label_maps/048462_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/upper_body/label_maps/048462_4.png -------------------------------------------------------------------------------- /assets/data/dresscode/upper_body/label_maps/048466_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/dresscode/upper_body/label_maps/048466_4.png -------------------------------------------------------------------------------- /assets/data/dresscode/upper_body/test_pairs_paired.txt: -------------------------------------------------------------------------------- 1 | 048462_0.jpg 048462_1.jpg -------------------------------------------------------------------------------- /assets/data/dresscode/upper_body/test_pairs_unpaired.txt: -------------------------------------------------------------------------------- 1 | 048462_0.jpg 049951_1.jpg -------------------------------------------------------------------------------- /assets/data/vitonhd/test/im_sketch/03191_00.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/vitonhd/test/im_sketch/03191_00.png -------------------------------------------------------------------------------- /assets/data/vitonhd/test/im_sketch/12419_00.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/vitonhd/test/im_sketch/12419_00.png -------------------------------------------------------------------------------- /assets/data/vitonhd/test/im_sketch_unpaired/03191_00_00349_00.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/vitonhd/test/im_sketch_unpaired/03191_00_00349_00.png -------------------------------------------------------------------------------- /assets/data/vitonhd/test/im_sketch_unpaired/12419_00_01944_00.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/vitonhd/test/im_sketch_unpaired/12419_00_01944_00.png -------------------------------------------------------------------------------- /assets/data/vitonhd/test/image-parse-v3/03191_00.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/vitonhd/test/image-parse-v3/03191_00.png -------------------------------------------------------------------------------- /assets/data/vitonhd/test/image-parse-v3/12419_00.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/vitonhd/test/image-parse-v3/12419_00.png -------------------------------------------------------------------------------- /assets/data/vitonhd/test/image/03191_00.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/vitonhd/test/image/03191_00.jpg -------------------------------------------------------------------------------- /assets/data/vitonhd/test/image/12419_00.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/assets/data/vitonhd/test/image/12419_00.jpg -------------------------------------------------------------------------------- /assets/data/vitonhd/test/openpose_json/03191_00_keypoints.json: -------------------------------------------------------------------------------- 1 | {"version":1.3,"people":[{"person_id":[-1],"pose_keypoints_2d":[416.932,147.983,0.897289,419.886,323.564,0.823605,295.199,323.575,0.710266,247.078,553.188,0.845261,167.788,760.006,0.839517,547.427,317.9,0.678732,558.827,555.858,0.815472,572.928,779.771,0.816659,397.27,700.433,0.424303,317.926,697.611,0.385856,300.856,969.661,0.23729,0,0,0,485.062,703.303,0.382307,465.203,972.48,0.184967,0,0,0,383.025,122.292,0.896053,442.498,122.248,0.942278,351.819,145.093,0.790069,482.159,136.519,0.671479,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"face_keypoints_2d":[354.446,127.599,0.808671,356.595,142.643,0.809553,360.893,157.687,0.892167,363.042,174.163,0.84444,368.057,189.207,0.79902,378.086,202.818,0.82672,388.831,214.28,0.824691,401.01,224.309,0.842394,416.77,227.175,0.842865,431.097,223.593,0.78027,446.141,213.564,0.798111,457.603,201.386,0.764526,464.767,186.342,0.860417,469.781,169.865,0.836623,470.497,154.105,0.757279,474.796,138.345,0.686917,476.228,122.585,0.674373,361.609,111.123,0.890275,367.34,105.392,0.944614,378.086,103.959,0.885853,387.399,104.676,0.865673,395.995,106.825,0.928337,423.933,106.108,0.876463,433.963,101.094,0.847098,443.992,99.6609,0.891535,455.454,101.094,0.840891,464.05,108.974,0.840359,411.039,122.585,0.865094,411.755,134.047,0.900373,411.755,145.509,0.902167,412.472,156.971,0.886932,401.726,165.567,0.929022,407.457,167.716,0.912199,412.472,168.432,0.922348,418.202,167,0.88593,423.933,164.134,0.89659,372.355,123.301,0.937799,378.086,119.003,0.91301,388.115,119.719,0.852703,395.279,126.883,0.899933,387.399,128.316,0.889112,378.086,128.316,0.975661,428.948,124.018,0.915437,436.112,117.57,0.984511,446.141,116.854,0.92132,452.588,121.868,0.969951,446.857,126.167,0.888569,436.112,126.883,0.902612,393.13,186.342,0.886258,401.01,182.044,0.871408,408.173,179.894,0.916132,413.188,180.611,0.923757,418.919,179.894,0.908463,428.232,180.611,0.889455,436.112,184.909,0.896513,429.664,192.789,0.899923,421.784,197.087,0.877151,413.904,197.804,0.916279,407.457,197.804,0.952279,401.01,194.938,0.878204,395.995,186.342,0.910329,408.173,185.625,0.890515,413.904,185.625,0.906499,419.635,184.909,0.880725,433.246,185.625,0.876117,419.635,189.207,0.837431,413.904,190.64,0.878774,408.173,189.924,0.874297,383.817,122.585,0.863312,441.126,121.152,0.859384],"hand_left_keypoints_2d":[565.693,776.845,0.542976,552.89,801.536,0.678419,545.574,836.287,0.768888,550.146,871.038,0.833503,549.232,893.9,0.865609,580.325,852.748,0.609337,567.522,893.9,0.828608,551.975,914.019,0.795984,537.343,924.078,0.766036,583.983,855.491,0.627158,572.094,892.986,0.789977,552.89,910.361,0.538921,537.343,920.42,0.410428,585.812,850.919,0.656112,574.838,881.097,0.65846,556.548,901.216,0.531315,541.001,910.361,0.395474,581.239,846.346,0.689323,573.923,872.867,0.668061,560.206,880.183,0.523149,545.574,897.558,0.328769],"hand_right_keypoints_2d":[166.902,765.96,0.632211,166.902,790.336,0.735203,165.096,811.102,0.672094,153.36,845.409,0.939393,149.748,871.592,0.619071,132.594,830.061,0.808289,128.983,867.98,0.782519,138.011,891.454,0.756885,145.234,910.414,0.853907,134.4,835.478,0.617637,129.886,871.592,0.758741,143.428,895.968,0.768459,155.165,913.122,0.702863,139.817,837.284,0.584807,136.206,867.078,0.70512,150.651,888.746,0.801908,162.388,904.094,0.809094,149.748,833.673,0.443493,147.04,860.758,0.500639,154.262,875.203,0.701815,165.999,882.426,0.819218],"pose_keypoints_3d":[],"face_keypoints_3d":[],"hand_left_keypoints_3d":[],"hand_right_keypoints_3d":[]}]} -------------------------------------------------------------------------------- /assets/data/vitonhd/test/openpose_json/12419_00_keypoints.json: -------------------------------------------------------------------------------- 1 | {"version":1.3,"people":[{"person_id":[-1],"pose_keypoints_2d":[374.575,238.469,0.949289,337.721,374.564,0.8301,215.97,368.91,0.732457,173.452,604.043,0.810423,173.422,861.967,0.768282,456.755,380.306,0.76543,465.396,601.339,0.750355,527.56,844.897,0.734083,371.599,788.305,0.592811,283.936,793.987,0.534644,0,0,0,0,0,0,453.946,782.666,0.536147,0,0,0,0,0,0,351.821,201.756,0.89095,400.173,215.886,0.919544,303.749,212.944,0.836505,422.804,238.612,0.465832,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"face_keypoints_2d":[311.814,198.615,0.65869,308.136,214.552,0.718225,306.297,229.876,0.67781,305.684,247.039,0.660392,308.136,263.588,0.742804,314.266,278.299,0.792996,324.073,291.784,0.757003,337.558,302.817,0.862079,352.881,307.721,0.890189,366.979,307.721,0.87921,378.625,300.978,0.777896,391.497,293.01,0.815604,400.691,281.977,0.784073,406.821,269.105,0.862144,413.563,258.072,0.793081,420.306,244.587,0.794466,423.984,231.715,0.732577,328.976,190.647,0.872497,339.397,184.518,0.839534,352.268,183.292,0.875146,364.527,186.969,0.839053,375.561,194.938,0.876202,396.401,200.454,0.917688,406.208,199.841,0.901285,415.402,201.067,0.88975,422.145,206.584,0.819484,425.209,215.778,0.807623,381.077,211.487,0.853123,378.012,221.295,0.841805,376.786,231.102,0.913066,376.173,240.909,0.843938,360.237,248.877,0.879791,365.753,250.716,0.835396,371.27,254.394,0.914368,376.173,254.394,0.914862,381.69,254.394,0.916969,340.622,204.745,0.890919,347.978,201.067,0.972366,357.172,204.745,0.913174,362.689,211.487,0.881865,353.494,210.874,0.870807,346.139,209.649,0.909914,391.497,220.069,0.952839,399.466,216.391,0.860999,407.434,219.456,0.92136,411.725,224.972,0.943857,406.208,226.811,0.919377,397.014,224.359,0.94138,343.687,267.879,0.901622,352.881,262.975,0.908549,362.076,259.91,0.933249,367.592,263.588,0.93963,373.109,263.588,0.905823,378.625,269.105,0.85625,382.303,277.686,0.925362,376.173,282.59,0.882075,367.592,283.203,0.943062,362.076,282.59,0.937433,356.559,279.525,0.896022,348.591,274.621,0.883552,347.978,268.492,0.958477,359.624,269.105,0.894953,365.753,270.944,0.843438,371.27,272.782,0.89823,378.625,276.46,0.824877,371.27,273.395,0.897881,365.753,271.556,0.836231,359.011,269.105,0.885902,351.655,205.358,0.82943,401.917,220.069,0.941136],"hand_left_keypoints_2d":[521.435,846.377,0.651244,526.558,868.918,0.830186,535.779,896.582,0.739442,536.804,923.221,1.0176,534.755,945.762,0.950134,551.148,912.975,0.871023,549.099,946.787,0.928153,533.73,960.107,0.856091,519.386,968.303,0.856713,542.951,912.975,0.756564,539.878,946.787,0.637287,520.411,960.107,0.887973,502.993,962.156,0.871243,532.706,911.951,0.667567,528.607,938.59,0.600222,512.214,952.934,0.946885,496.845,958.057,0.856556,518.361,907.853,0.601498,512.214,933.467,0.540937,502.993,944.738,0.621017,494.796,946.787,0.741466],"hand_right_keypoints_2d":[176.566,860.874,0.71883,198.643,888.208,0.738061,210.208,918.696,0.810671,212.311,950.236,0.865716,211.259,969.159,0.71021,188.13,943.928,0.785603,196.541,977.57,0.788865,209.157,984.929,0.819588,216.516,984.929,0.907034,172.36,943.928,0.750136,178.668,980.724,0.838958,194.438,984.929,1.07872,202.849,978.621,0.706354,162.899,939.722,0.838518,169.206,971.262,0.890653,183.925,977.57,0.821722,193.387,974.416,0.549536,157.642,928.158,0.883011,160.796,956.544,0.852623,173.412,964.954,0.602694,180.771,962.852,0.455725],"pose_keypoints_3d":[],"face_keypoints_3d":[],"hand_left_keypoints_3d":[],"hand_right_keypoints_3d":[]}]} -------------------------------------------------------------------------------- /assets/data/vitonhd/test_pairs.txt: -------------------------------------------------------------------------------- 1 | 12419_00.jpg 01944_00.jpg 2 | 03191_00.jpg 00349_00.jpg 3 | -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: mgd 2 | channels: 3 | - defaults 4 | dependencies: 5 | - _libgcc_mutex=0.1=main 6 | - _openmp_mutex=5.1=1_gnu 7 | - ca-certificates=2023.08.22=h06a4308_0 8 | - ld_impl_linux-64=2.38=h1181459_1 9 | - libffi=3.4.4=h6a678d5_0 10 | - libgcc-ng=11.2.0=h1234567_1 11 | - libgomp=11.2.0=h1234567_1 12 | - libstdcxx-ng=11.2.0=h1234567_1 13 | - ncurses=6.4=h6a678d5_0 14 | - openssl=3.0.11=h7f8727e_2 15 | - pip=23.2.1=py39h06a4308_0 16 | - python=3.9.18=h955ad1f_0 17 | - readline=8.2=h5eee18b_0 18 | - setuptools=68.0.0=py39h06a4308_0 19 | - sqlite=3.41.2=h5eee18b_0 20 | - tk=8.6.12=h1ccaba5_0 21 | - tzdata=2023c=h04d1e81_0 22 | - wheel=0.38.4=py39h06a4308_0 23 | - xz=5.4.2=h5eee18b_0 24 | - zlib=1.2.13=h5eee18b_0 25 | - pip: 26 | - accelerate==0.15.0 27 | - certifi==2023.7.22 28 | - charset-normalizer==3.2.0 29 | - clean-fid==0.1.35 30 | - diffusers==0.12.0 31 | - filelock==3.12.4 32 | - fsspec==2023.9.1 33 | - huggingface-hub==0.17.2 34 | - idna==3.4 35 | - importlib-metadata==6.8.0 36 | - lpips==0.1.4 37 | - numpy==1.26.0 38 | - opencv-python==4.7.0.68 39 | - packaging==23.1 40 | - pillow==10.0.1 41 | - psutil==5.9.5 42 | - pyyaml==6.0.1 43 | - regex==2023.8.8 44 | - requests==2.31.0 45 | - scipy==1.11.2 46 | - tokenizers==0.13.3 47 | - torch==1.12.1 48 | - torch-fidelity==0.3.0 49 | - torchmetrics==0.11.0 50 | - torchvision==0.13.1 51 | - tqdm==4.66.1 52 | - transformers==4.25.1 53 | - typing-extensions==4.8.0 54 | - urllib3==2.0.5 55 | - zipp==3.17.0 56 | prefix: /home/abaldrati/miniconda3/envs/mgd 57 | -------------------------------------------------------------------------------- /hubconf.py: -------------------------------------------------------------------------------- 1 | dependencies = ['torch', 'diffusers'] 2 | import torch 3 | from diffusers import UNet2DConditionModel 4 | 5 | 6 | # mgd is the name of entrypoint 7 | def mgd(dataset: str, pretrained: bool = True, **kwargs) -> UNet2DConditionModel: 8 | """ # This docstring shows up in hub.help() 9 | MGD model 10 | pretrained (bool): kwargs, load pretrained weights into the model 11 | """ 12 | 13 | config = UNet2DConditionModel.load_config("runwayml/stable-diffusion-inpainting", subfolder="unet") 14 | config['in_channels'] = 28 15 | unet = UNet2DConditionModel.from_config(config) 16 | 17 | if pretrained: 18 | checkpoint = f"https://github.com/aimagelab/multimodal-garment-designer/releases/download/weights/{dataset}.pth" 19 | unet.load_state_dict(torch.hub.load_state_dict_from_url(checkpoint, progress=True)) 20 | 21 | return unet 22 | -------------------------------------------------------------------------------- /images/1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/images/1.gif -------------------------------------------------------------------------------- /output_dresscode/test_paired/images/048462_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_dresscode/test_paired/images/048462_0.jpg -------------------------------------------------------------------------------- /output_dresscode/test_paired/images/050855_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_dresscode/test_paired/images/050855_0.jpg -------------------------------------------------------------------------------- /output_dresscode/test_paired/images/050915_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_dresscode/test_paired/images/050915_0.jpg -------------------------------------------------------------------------------- /output_dresscode/test_paired/images/052012_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_dresscode/test_paired/images/052012_0.jpg -------------------------------------------------------------------------------- /output_dresscode/test_unpaired/images/048462_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_dresscode/test_unpaired/images/048462_0.jpg -------------------------------------------------------------------------------- /output_dresscode/test_unpaired/images/050855_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_dresscode/test_unpaired/images/050855_0.jpg -------------------------------------------------------------------------------- /output_dresscode/test_unpaired/images/050915_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_dresscode/test_unpaired/images/050915_0.jpg -------------------------------------------------------------------------------- /output_dresscode/test_unpaired/images/052012_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_dresscode/test_unpaired/images/052012_0.jpg -------------------------------------------------------------------------------- /output_vitonhd/test_paired/images/03191_00.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_vitonhd/test_paired/images/03191_00.jpg -------------------------------------------------------------------------------- /output_vitonhd/test_paired/images/12419_00.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_vitonhd/test_paired/images/12419_00.jpg -------------------------------------------------------------------------------- /output_vitonhd/test_unpaired/images/03191_00.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_vitonhd/test_unpaired/images/03191_00.jpg -------------------------------------------------------------------------------- /output_vitonhd/test_unpaired/images/12419_00.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/output_vitonhd/test_unpaired/images/12419_00.jpg -------------------------------------------------------------------------------- /src/datasets/dresscode.py: -------------------------------------------------------------------------------- 1 | # File havily based on https://github.com/aimagelab/dress-code/blob/main/data/dataset.py 2 | 3 | import json 4 | import pathlib 5 | import random 6 | import sys 7 | from typing import Tuple 8 | 9 | PROJECT_ROOT = pathlib.Path(__file__).absolute().parents[2].absolute() 10 | sys.path.insert(0, str(PROJECT_ROOT)) 11 | 12 | import cv2 13 | import numpy as np 14 | import torch 15 | import torch.utils.data as data 16 | import torchvision.transforms as transforms 17 | from PIL import Image, ImageDraw, ImageOps 18 | from torchvision.ops import masks_to_boxes 19 | from src.utils.labelmap import label_map 20 | from src.utils.posemap import kpoint_to_heatmap 21 | 22 | 23 | class DressCodeDataset(data.Dataset): 24 | def __init__(self, 25 | dataroot_path: str, 26 | phase: str, 27 | tokenizer, 28 | radius=5, 29 | caption_folder='fine_captions.json', 30 | coarse_caption_folder='coarse_captions.json', 31 | sketch_threshold_range: Tuple[int, int] = (20, 127), 32 | order: str = 'paired', 33 | outputlist: Tuple[str] = ('c_name', 'im_name', 'image', 'im_cloth', 'shape', 'pose_map', 34 | 'parse_array', 'im_mask', 'inpaint_mask', 'parse_mask_total', 35 | 'im_sketch', 'captions', 36 | 'original_captions', 'category', 'stitch_label'), 37 | category: Tuple[str] = ('dresses', 'upper_body', 'lower_body'), 38 | size: Tuple[int, int] = (512, 384), 39 | ): 40 | 41 | super(DressCodeDataset, self).__init__() 42 | self.dataroot = pathlib.Path(dataroot_path) 43 | self.phase = phase 44 | self.caption_folder = caption_folder 45 | self.sketch_threshold_range = sketch_threshold_range 46 | self.category = category 47 | self.outputlist = outputlist 48 | self.height = size[0] 49 | self.width = size[1] 50 | self.radius = radius 51 | self.tokenizer = tokenizer 52 | self.transform = transforms.Compose([ 53 | transforms.ToTensor(), 54 | transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) 55 | ]) 56 | self.transform2D = transforms.Compose([ 57 | transforms.ToTensor(), 58 | transforms.Normalize((0.5,), (0.5,)) 59 | ]) 60 | self.order = order 61 | 62 | im_names = [] 63 | c_names = [] 64 | dataroot_names = [] 65 | 66 | possible_outputs = ['c_name', 'im_name', 'cloth', 'image', 'im_cloth', 'shape', 'im_head', 'im_pose', 67 | 'pose_map', 'parse_array', 'dense_labels', 'dense_uv', 'skeleton', 68 | 'im_mask', 'inpaint_mask', 'parse_mask_total', 'cloth_sketch', 'im_sketch', 'captions', 69 | 'original_captions', 'category', 'hands', 'parse_head_2', 'stitch_label'] 70 | 71 | assert all(x in possible_outputs for x in outputlist) 72 | 73 | # Load Captions 74 | with open(self.dataroot / self.caption_folder) as f: 75 | self.captions_dict = json.load(f) 76 | self.captions_dict = {k: v for k, v in self.captions_dict.items() if len(v) >= 3} 77 | 78 | with open(self.dataroot / coarse_caption_folder) as f: 79 | self.captions_dict.update(json.load(f)) 80 | 81 | for c in category: 82 | assert c in ['dresses', 'upper_body', 'lower_body'] 83 | 84 | dataroot = self.dataroot / c 85 | if phase == 'train': 86 | filename = dataroot / f"{phase}_pairs.txt" 87 | else: 88 | filename = dataroot / f"{phase}_pairs_{order}.txt" 89 | 90 | with open(filename, 'r') as f: 91 | for line in f.readlines(): 92 | im_name, c_name = line.strip().split() 93 | if c_name.split('_')[0] not in self.captions_dict: 94 | continue 95 | 96 | im_names.append(im_name) 97 | c_names.append(c_name) 98 | dataroot_names.append(dataroot) 99 | 100 | self.im_names = im_names 101 | self.c_names = c_names 102 | self.dataroot_names = dataroot_names 103 | 104 | def __getitem__(self, index): 105 | """ 106 | For each index return the corresponding sample in the dataset 107 | :param index: data index 108 | :type index: int 109 | :return: dict containing dataset samples 110 | :rtype: dict 111 | """ 112 | 113 | c_name = self.c_names[index] 114 | im_name = self.im_names[index] 115 | dataroot = self.dataroot_names[index] 116 | 117 | sketch_threshold = random.randint(self.sketch_threshold_range[0], self.sketch_threshold_range[1]) 118 | 119 | if "captions" in self.outputlist or "original_captions" in self.outputlist: 120 | captions = self.captions_dict[c_name.split('_')[0]] 121 | # if train randomly shuffle captions if there are multiple, else concatenate with comma 122 | if self.phase == 'train': 123 | random.shuffle(captions) 124 | captions = ", ".join(captions) 125 | 126 | original_captions = captions 127 | 128 | if "captions" in self.outputlist: 129 | cond_input = self.tokenizer([captions], max_length=self.tokenizer.model_max_length, padding="max_length", 130 | truncation=True, return_tensors="pt").input_ids 131 | cond_input = cond_input.squeeze(0) 132 | max_length = cond_input.shape[-1] 133 | uncond_input = self.tokenizer( 134 | [""], padding="max_length", max_length=max_length, return_tensors="pt" 135 | ).input_ids.squeeze(0) 136 | captions = cond_input 137 | 138 | if "image" in self.outputlist or "im_head" in self.outputlist or "im_cloth" in self.outputlist: 139 | image = Image.open(dataroot / 'images' / im_name) 140 | 141 | image = image.resize((self.width, self.height)) 142 | image = self.transform(image) # [-1,1] 143 | 144 | if "im_sketch" in self.outputlist: 145 | 146 | if "unpaired" == self.order and self.phase == 'test': # Upper of multigarment is the same of unpaired 147 | im_sketch = Image.open( 148 | dataroot / 'im_sketch_unpaired' / f'{im_name.replace(".jpg", "")}_{c_name.replace(".jpg", ".png")}') 149 | else: 150 | im_sketch = Image.open(dataroot / 'im_sketch' / c_name.replace(".jpg", ".png")) 151 | 152 | im_sketch = im_sketch.resize((self.width, self.height)) 153 | im_sketch = ImageOps.invert(im_sketch) 154 | # threshold grayscale pil image 155 | im_sketch = im_sketch.point(lambda p: 255 if p > sketch_threshold else 0) 156 | # im_sketch = im_sketch.convert("RGB") 157 | im_sketch = transforms.functional.to_tensor(im_sketch) # [-1,1] 158 | im_sketch = 1 - im_sketch 159 | 160 | if "im_pose" in self.outputlist or "parser_mask" in self.outputlist or "im_mask" in self.outputlist or "parse_mask_total" in self.outputlist or "parse_array" in self.outputlist or "pose_map" in self.outputlist or "parse_array" in self.outputlist or "shape" in self.outputlist or "im_head" in self.outputlist: 161 | # Label Map 162 | parse_name = im_name.replace('_0.jpg', '_4.png') 163 | im_parse = Image.open(dataroot / 'label_maps' / parse_name) 164 | im_parse = im_parse.resize((self.width, self.height), Image.NEAREST) 165 | parse_array = np.array(im_parse) 166 | 167 | parse_shape = (parse_array > 0).astype(np.float32) 168 | 169 | parse_head = (parse_array == 1).astype(np.float32) + \ 170 | (parse_array == 2).astype(np.float32) + \ 171 | (parse_array == 3).astype(np.float32) + \ 172 | (parse_array == 11).astype(np.float32) 173 | 174 | parser_mask_fixed = (parse_array == label_map["hair"]).astype(np.float32) + \ 175 | (parse_array == label_map["left_shoe"]).astype(np.float32) + \ 176 | (parse_array == label_map["right_shoe"]).astype(np.float32) + \ 177 | (parse_array == label_map["hat"]).astype(np.float32) + \ 178 | (parse_array == label_map["sunglasses"]).astype(np.float32) + \ 179 | (parse_array == label_map["scarf"]).astype(np.float32) + \ 180 | (parse_array == label_map["bag"]).astype(np.float32) 181 | 182 | parser_mask_changeable = (parse_array == label_map["background"]).astype(np.float32) 183 | 184 | arms = (parse_array == 14).astype(np.float32) + (parse_array == 15).astype(np.float32) 185 | 186 | category = str(dataroot.name) 187 | if category == 'dresses': 188 | label_cat = 7 189 | parse_cloth = (parse_array == 7).astype(np.float32) 190 | parse_mask = (parse_array == 7).astype(np.float32) + \ 191 | (parse_array == 12).astype(np.float32) + \ 192 | (parse_array == 13).astype(np.float32) 193 | parser_mask_changeable += np.logical_and(parse_array, np.logical_not(parser_mask_fixed)) 194 | 195 | elif category == 'upper_body': 196 | label_cat = 4 197 | parse_cloth = (parse_array == 4).astype(np.float32) 198 | parse_mask = (parse_array == 4).astype(np.float32) 199 | 200 | parser_mask_fixed += (parse_array == label_map["skirt"]).astype(np.float32) + \ 201 | (parse_array == label_map["pants"]).astype(np.float32) 202 | 203 | parser_mask_changeable += np.logical_and(parse_array, np.logical_not(parser_mask_fixed)) 204 | elif category == 'lower_body': 205 | label_cat = 6 206 | parse_cloth = (parse_array == 6).astype(np.float32) 207 | parse_mask = (parse_array == 6).astype(np.float32) + \ 208 | (parse_array == 12).astype(np.float32) + \ 209 | (parse_array == 13).astype(np.float32) 210 | 211 | parser_mask_fixed += (parse_array == label_map["upper_clothes"]).astype(np.float32) + \ 212 | (parse_array == 14).astype(np.float32) + \ 213 | (parse_array == 15).astype(np.float32) 214 | parser_mask_changeable += np.logical_and(parse_array, np.logical_not(parser_mask_fixed)) 215 | else: 216 | raise NotImplementedError 217 | 218 | parse_head = torch.from_numpy(parse_head) # [0,1] 219 | parse_cloth = torch.from_numpy(parse_cloth) # [0,1] 220 | parse_mask = torch.from_numpy(parse_mask) # [0,1] 221 | parser_mask_fixed = torch.from_numpy(parser_mask_fixed) 222 | parser_mask_changeable = torch.from_numpy(parser_mask_changeable) 223 | 224 | # dilation 225 | parse_without_cloth = np.logical_and(parse_shape, np.logical_not(parse_mask)) 226 | parse_mask = parse_mask.cpu().numpy() 227 | 228 | if "im_head" in self.outputlist: 229 | # Masked cloth 230 | im_head = image * parse_head - (1 - parse_head) 231 | if "im_cloth" in self.outputlist: 232 | im_cloth = image * parse_cloth + (1 - parse_cloth) 233 | 234 | # Shape 235 | parse_shape = Image.fromarray((parse_shape * 255).astype(np.uint8)) 236 | parse_shape = parse_shape.resize((self.width // 16, self.height // 16), Image.BILINEAR) 237 | parse_shape = parse_shape.resize((self.width, self.height), Image.BILINEAR) 238 | shape = self.transform2D(parse_shape) # [-1,1] 239 | 240 | # Load pose points 241 | pose_name = im_name.replace('_0.jpg', '_2.json') 242 | with open(dataroot / 'keypoints' / pose_name, 'r') as f: 243 | pose_label = json.load(f) 244 | pose_data = pose_label['keypoints'] 245 | pose_data = np.array(pose_data) 246 | pose_data = pose_data.reshape((-1, 4)) 247 | 248 | point_num = pose_data.shape[0] 249 | pose_map = torch.zeros(point_num, self.height, self.width) 250 | r = self.radius * (self.height / 512.0) 251 | im_pose = Image.new('L', (self.width, self.height)) 252 | pose_draw = ImageDraw.Draw(im_pose) 253 | neck = Image.new('L', (self.width, self.height)) 254 | neck_draw = ImageDraw.Draw(neck) 255 | for i in range(point_num): 256 | one_map = Image.new('L', (self.width, self.height)) 257 | draw = ImageDraw.Draw(one_map) 258 | point_x = np.multiply(pose_data[i, 0], self.width / 384.0) 259 | point_y = np.multiply(pose_data[i, 1], self.height / 512.0) 260 | if point_x > 1 and point_y > 1: 261 | draw.rectangle((point_x - r, point_y - r, point_x + r, point_y + r), 'white', 'white') 262 | pose_draw.rectangle((point_x - r, point_y - r, point_x + r, point_y + r), 'white', 'white') 263 | if i == 2 or i == 5: 264 | neck_draw.ellipse((point_x - r * 4, point_y - r * 4, point_x + r * 4, point_y + r * 4), 'white', 265 | 'white') 266 | one_map = self.transform2D(one_map) 267 | pose_map[i] = one_map[0] 268 | 269 | d = [] 270 | for pose_d in pose_data: 271 | ux = pose_d[0] / 384.0 272 | uy = pose_d[1] / 512.0 273 | 274 | # scale posemap points 275 | px = ux * self.width 276 | py = uy * self.height 277 | 278 | d.append(kpoint_to_heatmap(np.array([px, py]), (self.height, self.width), 9)) 279 | 280 | pose_map = torch.stack(d) 281 | 282 | # just for visualization 283 | im_pose = self.transform2D(im_pose) 284 | 285 | im_arms = Image.new('L', (self.width, self.height)) 286 | arms_draw = ImageDraw.Draw(im_arms) 287 | if category == 'dresses' or category == 'upper_body' or category == 'lower_body': 288 | with open(dataroot / 'keypoints' / pose_name, 'r') as f: 289 | data = json.load(f) 290 | shoulder_right = np.multiply(tuple(data['keypoints'][2][:2]), self.height / 512.0) 291 | shoulder_left = np.multiply(tuple(data['keypoints'][5][:2]), self.height / 512.0) 292 | elbow_right = np.multiply(tuple(data['keypoints'][3][:2]), self.height / 512.0) 293 | elbow_left = np.multiply(tuple(data['keypoints'][6][:2]), self.height / 512.0) 294 | wrist_right = np.multiply(tuple(data['keypoints'][4][:2]), self.height / 512.0) 295 | wrist_left = np.multiply(tuple(data['keypoints'][7][:2]), self.height / 512.0) 296 | if wrist_right[0] <= 1. and wrist_right[1] <= 1.: 297 | if elbow_right[0] <= 1. and elbow_right[1] <= 1.: 298 | arms_draw.line( 299 | np.concatenate((wrist_left, elbow_left, shoulder_left, shoulder_right)).astype( 300 | np.uint16).tolist(), 'white', 45, 'curve') 301 | else: 302 | arms_draw.line(np.concatenate( 303 | (wrist_left, elbow_left, shoulder_left, shoulder_right, elbow_right)).astype( 304 | np.uint16).tolist(), 'white', 45, 'curve') 305 | elif wrist_left[0] <= 1. and wrist_left[1] <= 1.: 306 | if elbow_left[0] <= 1. and elbow_left[1] <= 1.: 307 | arms_draw.line( 308 | np.concatenate((shoulder_left, shoulder_right, elbow_right, wrist_right)).astype( 309 | np.uint16).tolist(), 'white', 45, 'curve') 310 | else: 311 | arms_draw.line(np.concatenate( 312 | (elbow_left, shoulder_left, shoulder_right, elbow_right, wrist_right)).astype( 313 | np.uint16).tolist(), 'white', 45, 'curve') 314 | else: 315 | arms_draw.line(np.concatenate( 316 | (wrist_left, elbow_left, shoulder_left, shoulder_right, elbow_right, wrist_right)).astype( 317 | np.uint16).tolist(), 'white', 45, 'curve') 318 | 319 | hands = np.logical_and(np.logical_not(im_arms), arms) 320 | 321 | if category == 'dresses' or category == 'upper_body': 322 | parse_mask += im_arms 323 | parser_mask_fixed += hands 324 | 325 | # delete neck 326 | parse_head_2 = torch.clone(parse_head) 327 | if category == 'dresses' or category == 'upper_body': 328 | with open(dataroot / 'keypoints' / pose_name, 'r') as f: 329 | data = json.load(f) 330 | points = [] 331 | points.append(np.multiply(tuple(data['keypoints'][2][:2]), self.height / 512.0)) 332 | points.append(np.multiply(tuple(data['keypoints'][5][:2]), self.height / 512.0)) 333 | x_coords, y_coords = zip(*points) 334 | A = np.vstack([x_coords, np.ones(len(x_coords))]).T 335 | m, c = np.linalg.lstsq(A, y_coords, rcond=None)[0] 336 | for i in range(parse_array.shape[1]): 337 | y = i * m + c 338 | parse_head_2[int(y - 20 * (self.height / 512.0)):, i] = 0 339 | 340 | parser_mask_fixed = np.logical_or(parser_mask_fixed, np.array(parse_head_2, dtype=np.uint16)) 341 | parse_mask += np.logical_or(parse_mask, np.logical_and(np.array(parse_head, dtype=np.uint16), 342 | np.logical_not( 343 | np.array(parse_head_2, dtype=np.uint16)))) 344 | 345 | # tune the amount of dilation here 346 | parse_mask = cv2.dilate(parse_mask, np.ones((5, 5), np.uint16), iterations=5) 347 | parse_mask = np.logical_and(parser_mask_changeable, np.logical_not(parse_mask)) 348 | parse_mask_total = np.logical_or(parse_mask, parser_mask_fixed) 349 | im_mask = image * parse_mask_total 350 | inpaint_mask = 1 - parse_mask_total 351 | 352 | # here we have to modify the mask and get the bounding box 353 | bboxes = masks_to_boxes(inpaint_mask.unsqueeze(0)) 354 | bboxes = bboxes.type(torch.int32) # xmin, ymin, xmax, ymax format 355 | xmin = bboxes[0, 0] 356 | xmax = bboxes[0, 2] 357 | ymin = bboxes[0, 1] 358 | ymax = bboxes[0, 3] 359 | 360 | inpaint_mask[ymin:ymax + 1, xmin:xmax + 1] = torch.logical_and( 361 | torch.ones_like(inpaint_mask[ymin:ymax + 1, xmin:xmax + 1]), 362 | torch.logical_not(parser_mask_fixed[ymin:ymax + 1, xmin:xmax + 1])) 363 | 364 | inpaint_mask = inpaint_mask.unsqueeze(0) 365 | im_mask = image * np.logical_not(inpaint_mask.repeat(3, 1, 1)) 366 | parse_mask_total = parse_mask_total.numpy() 367 | parse_mask_total = parse_array * parse_mask_total 368 | parse_mask_total = torch.from_numpy(parse_mask_total) 369 | 370 | if "stitch_label" in self.outputlist: 371 | stitch_labelmap = Image.open(self.dataroot / 'test_stitchmap' / im_name.replace(".jpg", ".png")) 372 | stitch_labelmap = transforms.ToTensor()(stitch_labelmap) * 255 373 | stitch_label = stitch_labelmap == 13 374 | 375 | result = {} 376 | for k in self.outputlist: 377 | result[k] = vars()[k] 378 | 379 | # Output interpretation 380 | # "c_name" -> filename of inshop cloth 381 | # "im_name" -> filename of model with cloth 382 | # "cloth" -> img of inshop cloth 383 | # "image" -> img of the model with that cloth 384 | # "im_cloth" -> cut cloth from the model 385 | # "im_mask" -> black mask of the cloth in the model img 386 | # "cloth_sketch" -> sketch of the inshop cloth 387 | # "im_sketch" -> sketch of "im_cloth" 388 | # ... 389 | return result 390 | 391 | def __len__(self): 392 | return len(self.c_names) 393 | -------------------------------------------------------------------------------- /src/datasets/vitonhd.py: -------------------------------------------------------------------------------- 1 | # File havily based on https://github.com/aimagelab/dress-code/blob/main/data/dataset.py 2 | 3 | 4 | import json 5 | import os 6 | import pathlib 7 | import random 8 | import sys 9 | from typing import Tuple 10 | 11 | PROJECT_ROOT = pathlib.Path(__file__).absolute().parents[2].absolute() 12 | sys.path.insert(0, str(PROJECT_ROOT)) 13 | 14 | import numpy as np 15 | import torch 16 | import torch.utils.data as data 17 | import torchvision.transforms as transforms 18 | from PIL import Image, ImageDraw, ImageOps 19 | from torchvision.ops import masks_to_boxes 20 | from src.utils.posemap import get_coco_body25_mapping 21 | from src.utils.posemap import kpoint_to_heatmap 22 | 23 | 24 | class VitonHDDataset(data.Dataset): 25 | def __init__( 26 | self, 27 | dataroot_path: str, 28 | phase: str, 29 | tokenizer, 30 | radius=5, 31 | caption_folder='captions.json', 32 | sketch_threshold_range: Tuple[int, int] = (20, 127), 33 | order: str = 'paired', 34 | outputlist: Tuple[str] = ('c_name', 'im_name', 'image', 'im_cloth', 'shape', 'pose_map', 35 | 'parse_array', 'im_mask', 'inpaint_mask', 'parse_mask_total', 36 | 'im_sketch', 'captions', 'original_captions'), 37 | size: Tuple[int, int] = (512, 384), 38 | ): 39 | 40 | super(VitonHDDataset, self).__init__() 41 | self.dataroot = dataroot_path 42 | self.phase = phase 43 | self.caption_folder = caption_folder 44 | self.sketch_threshold_range = sketch_threshold_range 45 | self.category = ('upper_body') 46 | self.outputlist = outputlist 47 | self.height = size[0] 48 | self.width = size[1] 49 | self.radius = radius 50 | self.tokenizer = tokenizer 51 | self.transform = transforms.Compose([ 52 | transforms.ToTensor(), 53 | transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) 54 | ]) 55 | self.transform2D = transforms.Compose([ 56 | transforms.ToTensor(), 57 | transforms.Normalize((0.5,), (0.5,)) 58 | ]) 59 | self.order = order 60 | 61 | im_names = [] 62 | c_names = [] 63 | dataroot_names = [] 64 | 65 | possible_outputs = ['c_name', 'im_name', 'image', 'im_cloth', 'shape', 'im_head', 'im_pose', 66 | 'pose_map', 'parse_array', 67 | 'im_mask', 'inpaint_mask', 'parse_mask_total', 'im_sketch', 'captions', 68 | 'original_captions', 'category'] 69 | 70 | assert all(x in possible_outputs for x in outputlist) 71 | 72 | # Load Captions 73 | with open(os.path.join(self.dataroot, self.caption_folder)) as f: 74 | # self.captions_dict = json.load(f)['items'] 75 | self.captions_dict = json.load(f) 76 | self.captions_dict = {k: v for k, v in self.captions_dict.items() if len(v) >= 3} 77 | 78 | dataroot = self.dataroot 79 | if phase == 'train': 80 | filename = os.path.join(dataroot, f"{phase}_pairs.txt") 81 | else: 82 | filename = os.path.join(dataroot, f"{phase}_pairs.txt") 83 | 84 | with open(filename, 'r') as f: 85 | data_len = len(f.readlines()) 86 | 87 | with open(filename, 'r') as f: 88 | for line in f.readlines(): 89 | if phase == 'train': 90 | im_name, _ = line.strip().split() 91 | c_name = im_name 92 | else: 93 | if order == 'paired': 94 | im_name, _ = line.strip().split() 95 | c_name = im_name 96 | else: 97 | im_name, c_name = line.strip().split() 98 | 99 | im_names.append(im_name) 100 | c_names.append(c_name) 101 | dataroot_names.append(dataroot) 102 | 103 | self.im_names = im_names 104 | self.c_names = c_names 105 | self.dataroot_names = dataroot_names 106 | 107 | def __getitem__(self, index): 108 | """ 109 | For each index return the corresponding sample in the dataset 110 | :param index: data index 111 | :type index: int 112 | :return: dict containing dataset samples 113 | :rtype: dict 114 | """ 115 | c_name = self.c_names[index] 116 | im_name = self.im_names[index] 117 | dataroot = self.dataroot_names[index] 118 | 119 | sketch_threshold = random.randint(self.sketch_threshold_range[0], self.sketch_threshold_range[1]) 120 | 121 | if "captions" in self.outputlist or "original_captions" in self.outputlist: 122 | captions = self.captions_dict[c_name.split('_')[0]] 123 | # take a random caption if there are multiple 124 | if self.phase == 'train': 125 | random.shuffle(captions) 126 | captions = ", ".join(captions) 127 | 128 | original_captions = captions 129 | 130 | if "captions" in self.outputlist: 131 | cond_input = self.tokenizer([captions], max_length=self.tokenizer.model_max_length, padding="max_length", 132 | truncation=True, return_tensors="pt").input_ids 133 | cond_input = cond_input.squeeze(0) 134 | max_length = cond_input.shape[-1] 135 | uncond_input = self.tokenizer( 136 | [""], padding="max_length", max_length=max_length, return_tensors="pt" 137 | ).input_ids.squeeze(0) 138 | captions = cond_input 139 | captions_uncond = uncond_input 140 | 141 | if "image" in self.outputlist or "im_head" in self.outputlist or "im_cloth" in self.outputlist: 142 | # Person image 143 | # image = Image.open(os.path.join(dataroot, 'images', im_name)) 144 | image = Image.open(os.path.join(dataroot, self.phase, 'image', im_name)) 145 | image = image.resize((self.width, self.height)) 146 | image = self.transform(image) # [-1,1] 147 | 148 | if "im_sketch" in self.outputlist: 149 | # Person image 150 | # im_sketch = Image.open(os.path.join(dataroot, 'im_sketch', c_name.replace(".jpg", ".png"))) 151 | if self.order == 'unpaired': 152 | im_sketch = Image.open( 153 | os.path.join(dataroot, self.phase, 'im_sketch_unpaired', 154 | os.path.splitext(im_name)[0] + '_' + c_name.replace(".jpg", ".png"))) 155 | elif self.order == 'paired': 156 | im_sketch = Image.open(os.path.join(dataroot, self.phase, 'im_sketch', im_name.replace(".jpg", ".png"))) 157 | else: 158 | raise ValueError( 159 | f"Order should be either paired or unpaired" 160 | ) 161 | 162 | im_sketch = im_sketch.resize((self.width, self.height)) 163 | im_sketch = ImageOps.invert(im_sketch) 164 | # threshold grayscale pil image 165 | im_sketch = im_sketch.point(lambda p: 255 if p > sketch_threshold else 0) 166 | # im_sketch = im_sketch.convert("RGB") 167 | im_sketch = transforms.functional.to_tensor(im_sketch) # [-1,1] 168 | im_sketch = 1 - im_sketch 169 | 170 | if "im_pose" in self.outputlist or "parser_mask" in self.outputlist or "im_mask" in self.outputlist or "parse_mask_total" in self.outputlist or "parse_array" in self.outputlist or "pose_map" in self.outputlist or "parse_array" in self.outputlist or "shape" in self.outputlist or "im_head" in self.outputlist: 171 | # Label Map 172 | # parse_name = im_name.replace('_0.jpg', '_4.png') 173 | parse_name = im_name.replace('.jpg', '.png') 174 | im_parse = Image.open(os.path.join(dataroot, self.phase, 'image-parse-v3', parse_name)) 175 | im_parse = im_parse.resize((self.width, self.height), Image.NEAREST) 176 | im_parse_final = transforms.ToTensor()(im_parse) * 255 177 | parse_array = np.array(im_parse) 178 | 179 | parse_shape = (parse_array > 0).astype(np.float32) 180 | 181 | parse_head = (parse_array == 1).astype(np.float32) + \ 182 | (parse_array == 2).astype(np.float32) + \ 183 | (parse_array == 4).astype(np.float32) + \ 184 | (parse_array == 13).astype(np.float32) 185 | 186 | parser_mask_fixed = (parse_array == 1).astype(np.float32) + \ 187 | (parse_array == 2).astype(np.float32) + \ 188 | (parse_array == 18).astype(np.float32) + \ 189 | (parse_array == 19).astype(np.float32) 190 | 191 | # parser_mask_changeable = (parse_array == label_map["background"]).astype(np.float32) 192 | parser_mask_changeable = (parse_array == 0).astype(np.float32) 193 | 194 | arms = (parse_array == 14).astype(np.float32) + (parse_array == 15).astype(np.float32) 195 | 196 | parse_cloth = (parse_array == 5).astype(np.float32) + \ 197 | (parse_array == 6).astype(np.float32) + \ 198 | (parse_array == 7).astype(np.float32) 199 | parse_mask = (parse_array == 5).astype(np.float32) + \ 200 | (parse_array == 6).astype(np.float32) + \ 201 | (parse_array == 7).astype(np.float32) 202 | 203 | parser_mask_fixed = parser_mask_fixed + (parse_array == 9).astype(np.float32) + \ 204 | (parse_array == 12).astype(np.float32) # the lower body is fixed 205 | 206 | parser_mask_changeable += np.logical_and(parse_array, np.logical_not(parser_mask_fixed)) 207 | 208 | parse_head = torch.from_numpy(parse_head) # [0,1] 209 | parse_cloth = torch.from_numpy(parse_cloth) # [0,1] 210 | parse_mask = torch.from_numpy(parse_mask) # [0,1] 211 | parser_mask_fixed = torch.from_numpy(parser_mask_fixed) 212 | parser_mask_changeable = torch.from_numpy(parser_mask_changeable) 213 | 214 | # dilation 215 | parse_without_cloth = np.logical_and(parse_shape, np.logical_not(parse_mask)) 216 | parse_mask = parse_mask.cpu().numpy() 217 | 218 | if "im_head" in self.outputlist: 219 | # Masked cloth 220 | im_head = image * parse_head - (1 - parse_head) 221 | if "im_cloth" in self.outputlist: 222 | im_cloth = image * parse_cloth + (1 - parse_cloth) 223 | 224 | # Shape 225 | parse_shape = Image.fromarray((parse_shape * 255).astype(np.uint8)) 226 | parse_shape = parse_shape.resize((self.width // 16, self.height // 16), Image.BILINEAR) 227 | parse_shape = parse_shape.resize((self.width, self.height), Image.BILINEAR) 228 | shape = self.transform2D(parse_shape) # [-1,1] 229 | 230 | # Load pose points 231 | pose_name = im_name.replace('.jpg', '_keypoints.json') 232 | with open(os.path.join(dataroot, self.phase, 'openpose_json', pose_name), 'r') as f: 233 | pose_label = json.load(f) 234 | pose_data = pose_label['people'][0]['pose_keypoints_2d'] 235 | pose_data = np.array(pose_data) 236 | pose_data = pose_data.reshape((-1, 3))[:, :2] 237 | 238 | # rescale keypoints on the base of height and width 239 | pose_data[:, 0] = pose_data[:, 0] * (self.width / 768) 240 | pose_data[:, 1] = pose_data[:, 1] * (self.height / 1024) 241 | 242 | pose_mapping = get_coco_body25_mapping() 243 | 244 | point_num = len(pose_mapping) 245 | 246 | pose_map = torch.zeros(point_num, self.height, self.width) 247 | r = self.radius * (self.height / 512.0) 248 | im_pose = Image.new('L', (self.width, self.height)) 249 | pose_draw = ImageDraw.Draw(im_pose) 250 | neck = Image.new('L', (self.width, self.height)) 251 | neck_draw = ImageDraw.Draw(neck) 252 | for i in range(point_num): 253 | one_map = Image.new('L', (self.width, self.height)) 254 | draw = ImageDraw.Draw(one_map) 255 | point_x = np.multiply(pose_data[pose_mapping[i], 0], 1) 256 | point_y = np.multiply(pose_data[pose_mapping[i], 1], 1) 257 | 258 | if point_x > 1 and point_y > 1: 259 | draw.rectangle((point_x - r, point_y - r, point_x + r, point_y + r), 'white', 'white') 260 | pose_draw.rectangle((point_x - r, point_y - r, point_x + r, point_y + r), 'white', 'white') 261 | if i == 2 or i == 5: 262 | neck_draw.ellipse((point_x - r * 4, point_y - r * 4, point_x + r * 4, point_y + r * 4), 'white', 263 | 'white') 264 | one_map = self.transform2D(one_map) 265 | pose_map[i] = one_map[0] 266 | 267 | d = [] 268 | 269 | for idx in range(point_num): 270 | ux = pose_data[pose_mapping[idx], 0] # / (192) 271 | uy = (pose_data[pose_mapping[idx], 1]) # / (256) 272 | 273 | # scale posemap points 274 | px = ux # * self.width 275 | py = uy # * self.height 276 | 277 | d.append(kpoint_to_heatmap(np.array([px, py]), (self.height, self.width), 9)) 278 | 279 | pose_map = torch.stack(d) 280 | 281 | # just for visualization 282 | im_pose = self.transform2D(im_pose) 283 | 284 | im_arms = Image.new('L', (self.width, self.height)) 285 | arms_draw = ImageDraw.Draw(im_arms) 286 | 287 | # do in any case because i have only upperbody 288 | with open(os.path.join(dataroot, self.phase, 'openpose_json', pose_name), 'r') as f: 289 | data = json.load(f) 290 | data = data['people'][0]['pose_keypoints_2d'] 291 | data = np.array(data) 292 | data = data.reshape((-1, 3))[:, :2] 293 | 294 | # rescale keypoints on the base of height and width 295 | data[:, 0] = data[:, 0] * (self.width / 768) 296 | data[:, 1] = data[:, 1] * (self.height / 1024) 297 | 298 | shoulder_right = np.multiply(tuple(data[pose_mapping[2]]), 1) 299 | shoulder_left = np.multiply(tuple(data[pose_mapping[5]]), 1) 300 | elbow_right = np.multiply(tuple(data[pose_mapping[3]]), 1) 301 | elbow_left = np.multiply(tuple(data[pose_mapping[6]]), 1) 302 | wrist_right = np.multiply(tuple(data[pose_mapping[4]]), 1) 303 | wrist_left = np.multiply(tuple(data[pose_mapping[7]]), 1) 304 | 305 | ARM_LINE_WIDTH = int(90 / 512 * self.height) 306 | if wrist_right[0] <= 1. and wrist_right[1] <= 1.: 307 | if elbow_right[0] <= 1. and elbow_right[1] <= 1.: 308 | arms_draw.line( 309 | np.concatenate((wrist_left, elbow_left, shoulder_left, shoulder_right)).astype( 310 | np.uint16).tolist(), 'white', ARM_LINE_WIDTH, 'curve') 311 | else: 312 | arms_draw.line(np.concatenate( 313 | (wrist_left, elbow_left, shoulder_left, shoulder_right, elbow_right)).astype( 314 | np.uint16).tolist(), 'white', ARM_LINE_WIDTH, 'curve') 315 | elif wrist_left[0] <= 1. and wrist_left[1] <= 1.: 316 | if elbow_left[0] <= 1. and elbow_left[1] <= 1.: 317 | arms_draw.line( 318 | np.concatenate((shoulder_left, shoulder_right, elbow_right, wrist_right)).astype( 319 | np.uint16).tolist(), 'white', ARM_LINE_WIDTH, 'curve') 320 | else: 321 | arms_draw.line(np.concatenate( 322 | (elbow_left, shoulder_left, shoulder_right, elbow_right, wrist_right)).astype( 323 | np.uint16).tolist(), 'white', ARM_LINE_WIDTH, 'curve') 324 | else: 325 | arms_draw.line(np.concatenate( 326 | (wrist_left, elbow_left, shoulder_left, shoulder_right, elbow_right, wrist_right)).astype( 327 | np.uint16).tolist(), 'white', ARM_LINE_WIDTH, 'curve') 328 | 329 | hands = np.logical_and(np.logical_not(im_arms), arms) 330 | parse_mask += im_arms 331 | parser_mask_fixed += hands 332 | 333 | # delete neck 334 | parse_head_2 = torch.clone(parse_head) 335 | 336 | parser_mask_fixed = np.logical_or(parser_mask_fixed, np.array(parse_head_2, dtype=np.uint16)) 337 | parse_mask += np.logical_or(parse_mask, np.logical_and(np.array(parse_head, dtype=np.uint16), 338 | np.logical_not( 339 | np.array(parse_head_2, dtype=np.uint16)))) 340 | 341 | parse_mask = np.logical_and(parser_mask_changeable, np.logical_not(parse_mask)) 342 | parse_mask_total = np.logical_or(parse_mask, parser_mask_fixed) 343 | # im_mask = image * parse_mask_total 344 | inpaint_mask = 1 - parse_mask_total 345 | 346 | # here we have to modify the mask and get the bounding box 347 | bboxes = masks_to_boxes(inpaint_mask.unsqueeze(0)) 348 | bboxes = bboxes.type(torch.int32) # xmin, ymin, xmax, ymax format 349 | xmin = bboxes[0, 0] 350 | xmax = bboxes[0, 2] 351 | ymin = bboxes[0, 1] 352 | ymax = bboxes[0, 3] 353 | 354 | inpaint_mask[ymin:ymax + 1, xmin:xmax + 1] = torch.logical_and( 355 | torch.ones_like(inpaint_mask[ymin:ymax + 1, xmin:xmax + 1]), 356 | torch.logical_not(parser_mask_fixed[ymin:ymax + 1, xmin:xmax + 1])) 357 | 358 | inpaint_mask = inpaint_mask.unsqueeze(0) 359 | im_mask = image * np.logical_not(inpaint_mask.repeat(3, 1, 1)) 360 | parse_mask_total = parse_mask_total.numpy() 361 | parse_mask_total = parse_array * parse_mask_total 362 | parse_mask_total = torch.from_numpy(parse_mask_total) 363 | 364 | result = {} 365 | for k in self.outputlist: 366 | result[k] = vars()[k] 367 | 368 | result['im_parse'] = im_parse_final 369 | result['hands'] = torch.from_numpy(hands) 370 | 371 | # Output interpretation 372 | # "c_name" -> filename of inshop cloth 373 | # "im_name" -> filename of model with cloth 374 | # "cloth" -> img of inshop cloth 375 | # "image" -> img of the model with that cloth 376 | # "im_cloth" -> cut cloth from the model 377 | # "im_mask" -> black mask of the cloth in the model img 378 | # "cloth_sketch" -> sketch of the inshop cloth 379 | # "im_sketch" -> sketch of "im_cloth" 380 | # inpaint_mask -> bb of the model img where the cloth is 381 | # ... 382 | return result 383 | 384 | def __len__(self): 385 | return len(self.c_names) 386 | -------------------------------------------------------------------------------- /src/eval.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | # external libraries 4 | import torch 5 | import torch.utils.checkpoint 6 | import torch.utils.checkpoint 7 | from accelerate import Accelerator 8 | from accelerate.logging import get_logger 9 | from diffusers import AutoencoderKL, DDIMScheduler 10 | from diffusers.utils import check_min_version 11 | from diffusers.utils.import_utils import is_xformers_available 12 | from transformers import CLIPTextModel, CLIPTokenizer 13 | 14 | # custom imports 15 | from datasets.dresscode import DressCodeDataset 16 | from datasets.vitonhd import VitonHDDataset 17 | from mgd_pipelines.mgd_pipe import MGDPipe 18 | from mgd_pipelines.mgd_pipe_disentangled import MGDPipeDisentangled 19 | from utils.arg_parser import eval_parse_args 20 | from utils.image_from_pipe import generate_images_from_mgd_pipe 21 | from utils.set_seeds import set_seed 22 | 23 | # Will error if the minimal version of diffusers is not installed. Remove at your own risks. 24 | check_min_version("0.10.0.dev0") 25 | 26 | logger = get_logger(__name__, log_level="INFO") 27 | os.environ["TOKENIZERS_PARALLELISM"] = "true" 28 | os.environ["WANDB_START_METHOD"] = "thread" 29 | 30 | 31 | def main() -> None: 32 | args = eval_parse_args() 33 | accelerator = Accelerator( 34 | mixed_precision=args.mixed_precision, 35 | ) 36 | device = accelerator.device 37 | 38 | # If passed along, set the training seed now. 39 | if args.seed is not None: 40 | set_seed(args.seed) 41 | 42 | # Load scheduler, tokenizer and models. 43 | val_scheduler = DDIMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler") 44 | val_scheduler.set_timesteps(50, device=device) 45 | 46 | tokenizer = CLIPTokenizer.from_pretrained( 47 | args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision 48 | ) 49 | text_encoder = CLIPTextModel.from_pretrained( 50 | args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision 51 | ) 52 | vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision) 53 | 54 | unet = torch.hub.load(dataset=args.dataset, repo_or_dir='aimagelab/multimodal-garment-designer', source='github', 55 | model='mgd', pretrained=True) 56 | 57 | # Freeze vae and text_encoder 58 | vae.requires_grad_(False) 59 | text_encoder.requires_grad_(False) 60 | 61 | # Enable memory efficient attention if requested 62 | if args.enable_xformers_memory_efficient_attention: 63 | if is_xformers_available(): 64 | unet.enable_xformers_memory_efficient_attention() 65 | else: 66 | raise ValueError("xformers is not available. Make sure it is installed correctly") 67 | 68 | if args.category: 69 | category = [args.category] 70 | else: 71 | category = ['dresses', 'upper_body', 'lower_body'] 72 | 73 | if args.dataset == "dresscode": 74 | test_dataset = DressCodeDataset( 75 | dataroot_path=args.dataset_path, 76 | phase='test', 77 | order=args.test_order, 78 | radius=5, 79 | sketch_threshold_range=(20, 20), 80 | tokenizer=tokenizer, 81 | category=category, 82 | size=(512, 384) 83 | ) 84 | elif args.dataset == "vitonhd": 85 | test_dataset = VitonHDDataset( 86 | dataroot_path=args.dataset_path, 87 | phase='test', 88 | order=args.test_order, 89 | sketch_threshold_range=(20, 20), 90 | radius=5, 91 | tokenizer=tokenizer, 92 | size=(512, 384), 93 | ) 94 | else: 95 | raise NotImplementedError 96 | 97 | test_dataloader = torch.utils.data.DataLoader( 98 | test_dataset, 99 | shuffle=False, 100 | batch_size=args.batch_size, 101 | num_workers=args.num_workers_test, 102 | ) 103 | 104 | # For mixed precision training we cast the text_encoder and vae weights to half-precision 105 | # as these models are only used for inference, keeping weights in full precision is not required. 106 | weight_dtype = torch.float32 107 | if args.mixed_precision == 'fp16': 108 | weight_dtype = torch.float16 109 | 110 | # Move text_encode and vae to gpu and cast to weight_dtype 111 | text_encoder.to(device, dtype=weight_dtype) 112 | vae.to(device, dtype=weight_dtype) 113 | 114 | unet.eval() 115 | # Select fast classifier free guidance or disentagle classifier free guidance according to the disentagle parameter in args 116 | with torch.inference_mode(): 117 | if args.disentagle: 118 | val_pipe = MGDPipeDisentangled( 119 | text_encoder=text_encoder, 120 | vae=vae, 121 | unet=unet.to(vae.dtype), 122 | tokenizer=tokenizer, 123 | scheduler=val_scheduler, 124 | ).to(device) 125 | else: 126 | val_pipe = MGDPipe( 127 | text_encoder=text_encoder, 128 | vae=vae, 129 | unet=unet.to(vae.dtype), 130 | tokenizer=tokenizer, 131 | scheduler=val_scheduler, 132 | ).to(device) 133 | 134 | val_pipe.enable_attention_slicing() 135 | test_dataloader = accelerator.prepare(test_dataloader) 136 | generate_images_from_mgd_pipe( 137 | test_order=args.test_order, 138 | pipe=val_pipe, 139 | test_dataloader=test_dataloader, 140 | save_name=args.save_name, 141 | dataset=args.dataset, 142 | output_dir=args.output_dir, 143 | guidance_scale=args.guidance_scale, 144 | guidance_scale_pose=args.guidance_scale_pose, 145 | guidance_scale_sketch=args.guidance_scale_sketch, 146 | sketch_cond_rate=args.sketch_cond_rate, 147 | start_cond_rate=args.start_cond_rate, 148 | no_pose=False, 149 | disentagle=False, 150 | seed=args.seed, 151 | ) 152 | 153 | 154 | if __name__ == "__main__": 155 | main() 156 | -------------------------------------------------------------------------------- /src/mgd_pipelines/mgd_pipe.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | from typing import Callable, List, Optional, Union 3 | 4 | from packaging import version 5 | import PIL 6 | import numpy as np 7 | import torch 8 | import torchvision 9 | from transformers import CLIPTextModel, CLIPTokenizer 10 | from diffusers.utils import is_accelerate_available 11 | from diffusers.configuration_utils import FrozenDict 12 | from diffusers.models import AutoencoderKL, UNet2DConditionModel 13 | from diffusers.pipeline_utils import DiffusionPipeline 14 | from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler 15 | from diffusers.utils import deprecate 16 | from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput 17 | from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint import prepare_mask_and_masked_image 18 | 19 | 20 | class MGDPipe(DiffusionPipeline): 21 | r""" 22 | Pipeline for text and posemap -guided image inpainting using Stable Diffusion. 23 | 24 | This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the 25 | library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) 26 | 27 | Args: 28 | vae ([`AutoencoderKL`]): 29 | Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. 30 | text_encoder ([`CLIPTextModel`]): 31 | Frozen text-encoder. Stable Diffusion uses the text portion of 32 | [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically 33 | the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. 34 | tokenizer (`CLIPTokenizer`): 35 | Tokenizer of class 36 | [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). 37 | unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. 38 | scheduler ([`SchedulerMixin`]): 39 | A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of 40 | [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. 41 | safety_checker ([`StableDiffusionSafetyChecker`]): 42 | Classification module that estimates whether generated images could be considered offensive or harmful. 43 | Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details. 44 | feature_extractor ([`CLIPFeatureExtractor`]): 45 | Model that extracts features from generated images to be used as inputs for the `safety_checker`. 46 | """ 47 | _optional_components = ["safety_checker"] 48 | 49 | def __init__( 50 | self, 51 | vae: AutoencoderKL, 52 | text_encoder: CLIPTextModel, 53 | tokenizer: CLIPTokenizer, 54 | unet: UNet2DConditionModel, 55 | scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler], 56 | safety_checker=None, 57 | feature_extractor=None, 58 | requires_safety_checker: bool = False, 59 | ): 60 | super().__init__() 61 | 62 | if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: 63 | deprecation_message = ( 64 | f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" 65 | f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " 66 | "to update the config accordingly as leaving `steps_offset` might led to incorrect results" 67 | " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," 68 | " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" 69 | " file" 70 | ) 71 | deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) 72 | new_config = dict(scheduler.config) 73 | new_config["steps_offset"] = 1 74 | scheduler._internal_dict = FrozenDict(new_config) 75 | 76 | if hasattr(scheduler.config, "skip_prk_steps") and scheduler.config.skip_prk_steps is False: 77 | deprecation_message = ( 78 | f"The configuration file of this scheduler: {scheduler} has not set the configuration" 79 | " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" 80 | " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" 81 | " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" 82 | " Hub, it would be very nice if you could open a Pull request for the" 83 | " `scheduler/scheduler_config.json` file" 84 | ) 85 | deprecate("skip_prk_steps not set", "1.0.0", deprecation_message, standard_warn=False) 86 | new_config = dict(scheduler.config) 87 | new_config["skip_prk_steps"] = True 88 | scheduler._internal_dict = FrozenDict(new_config) 89 | 90 | if safety_checker is None and requires_safety_checker: 91 | logger.warning( 92 | f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" 93 | " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" 94 | " results in services or applications open to the public. Both the diffusers team and Hugging Face" 95 | " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" 96 | " it only for use-cases that involve analyzing network behavior or auditing its results. For more" 97 | " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." 98 | ) 99 | 100 | if safety_checker is not None and feature_extractor is None: 101 | raise ValueError( 102 | "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" 103 | " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." 104 | ) 105 | 106 | is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse( 107 | version.parse(unet.config._diffusers_version).base_version 108 | ) < version.parse("0.9.0.dev0") 109 | is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 110 | if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: 111 | deprecation_message = ( 112 | "The configuration file of the unet has set the default `sample_size` to smaller than" 113 | " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the" 114 | " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" 115 | " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" 116 | " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" 117 | " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" 118 | " in the config might lead to incorrect results in future versions. If you have downloaded this" 119 | " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" 120 | " the `unet/config.json` file" 121 | ) 122 | deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) 123 | new_config = dict(unet.config) 124 | new_config["sample_size"] = 64 125 | unet._internal_dict = FrozenDict(new_config) 126 | 127 | self.register_modules( 128 | vae=vae, 129 | text_encoder=text_encoder, 130 | tokenizer=tokenizer, 131 | unet=unet, 132 | scheduler=scheduler, 133 | safety_checker=safety_checker, 134 | feature_extractor=feature_extractor, 135 | ) 136 | self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) 137 | self.register_to_config(requires_safety_checker=requires_safety_checker) 138 | 139 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_sequential_cpu_offload 140 | def enable_sequential_cpu_offload(self, gpu_id=0): 141 | r""" 142 | Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet, 143 | text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a 144 | `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called. 145 | """ 146 | if is_accelerate_available(): 147 | from accelerate import cpu_offload 148 | else: 149 | raise ImportError("Please install accelerate via `pip install accelerate`") 150 | 151 | device = torch.device(f"cuda:{gpu_id}") 152 | 153 | for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]: 154 | if cpu_offloaded_model is not None: 155 | cpu_offload(cpu_offloaded_model, device) 156 | 157 | if self.safety_checker is not None: 158 | # TODO(Patrick) - there is currently a bug with cpu offload of nn.Parameter in accelerate 159 | # fix by only offloading self.safety_checker for now 160 | cpu_offload(self.safety_checker.vision_model, device) 161 | 162 | @property 163 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device 164 | def _execution_device(self): 165 | r""" 166 | Returns the device on which the pipeline's models will be executed. After calling 167 | `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module 168 | hooks. 169 | """ 170 | if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"): 171 | return self.device 172 | for module in self.unet.modules(): 173 | if ( 174 | hasattr(module, "_hf_hook") 175 | and hasattr(module._hf_hook, "execution_device") 176 | and module._hf_hook.execution_device is not None 177 | ): 178 | return torch.device(module._hf_hook.execution_device) 179 | return self.device 180 | 181 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt 182 | def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt): 183 | r""" 184 | Encodes the prompt into text encoder hidden states. 185 | 186 | Args: 187 | prompt (`str` or `list(int)`): 188 | prompt to be encoded 189 | device: (`torch.device`): 190 | torch device 191 | num_images_per_prompt (`int`): 192 | number of images that should be generated per prompt 193 | do_classifier_free_guidance (`bool`): 194 | whether to use classifier free guidance or not 195 | negative_prompt (`str` or `List[str]`): 196 | The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored 197 | if `guidance_scale` is less than `1`). 198 | """ 199 | batch_size = len(prompt) if isinstance(prompt, list) else 1 200 | 201 | text_inputs = self.tokenizer( 202 | prompt, 203 | padding="max_length", 204 | max_length=self.tokenizer.model_max_length, 205 | truncation=True, 206 | return_tensors="pt", 207 | ) 208 | text_input_ids = text_inputs.input_ids 209 | untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids 210 | 211 | if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids): 212 | removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1: -1]) 213 | logger.warning( 214 | "The following part of your input was truncated because CLIP can only handle sequences up to" 215 | f" {self.tokenizer.model_max_length} tokens: {removed_text}" 216 | ) 217 | 218 | if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: 219 | attention_mask = text_inputs.attention_mask.to(device) 220 | else: 221 | attention_mask = None 222 | 223 | text_embeddings = self.text_encoder( 224 | text_input_ids.to(device), 225 | attention_mask=attention_mask, 226 | ) 227 | text_embeddings = text_embeddings[0] 228 | 229 | # duplicate text embeddings for each generation per prompt, using mps friendly method 230 | bs_embed, seq_len, _ = text_embeddings.shape 231 | text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1) 232 | text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1) 233 | 234 | # get unconditional embeddings for classifier free guidance 235 | if do_classifier_free_guidance: 236 | uncond_tokens: List[str] 237 | if negative_prompt is None: 238 | uncond_tokens = [""] * batch_size 239 | elif type(prompt) is not type(negative_prompt): 240 | raise TypeError( 241 | f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" 242 | f" {type(prompt)}." 243 | ) 244 | elif isinstance(negative_prompt, str): 245 | uncond_tokens = [negative_prompt] 246 | elif batch_size != len(negative_prompt): 247 | raise ValueError( 248 | f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" 249 | f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" 250 | " the batch size of `prompt`." 251 | ) 252 | else: 253 | uncond_tokens = negative_prompt 254 | 255 | max_length = text_input_ids.shape[-1] 256 | uncond_input = self.tokenizer( 257 | uncond_tokens, 258 | padding="max_length", 259 | max_length=max_length, 260 | truncation=True, 261 | return_tensors="pt", 262 | ) 263 | 264 | if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: 265 | attention_mask = uncond_input.attention_mask.to(device) 266 | else: 267 | attention_mask = None 268 | 269 | uncond_embeddings = self.text_encoder( 270 | uncond_input.input_ids.to(device), 271 | attention_mask=attention_mask, 272 | ) 273 | uncond_embeddings = uncond_embeddings[0] 274 | 275 | # duplicate unconditional embeddings for each generation per prompt, using mps friendly method 276 | seq_len = uncond_embeddings.shape[1] 277 | uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1) 278 | uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1) 279 | 280 | # For classifier free guidance, we need to do two forward passes. 281 | # Here we concatenate the unconditional and text embeddings into a single batch 282 | # to avoid doing two forward passes 283 | text_embeddings = torch.cat([uncond_embeddings, text_embeddings]) 284 | 285 | return text_embeddings 286 | 287 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs 288 | def prepare_extra_step_kwargs(self, generator, eta): 289 | # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature 290 | # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. 291 | # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 292 | # and should be between [0, 1] 293 | 294 | accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) 295 | extra_step_kwargs = {} 296 | if accepts_eta: 297 | extra_step_kwargs["eta"] = eta 298 | 299 | # check if the scheduler accepts generator 300 | accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) 301 | if accepts_generator: 302 | extra_step_kwargs["generator"] = generator 303 | return extra_step_kwargs 304 | 305 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents 306 | def decode_latents(self, latents): 307 | latents = 1 / 0.18215 * latents 308 | image = self.vae.decode(latents).sample 309 | image = (image / 2 + 0.5).clamp(0, 1) 310 | # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16 311 | image = image.cpu().permute(0, 2, 3, 1).float().numpy() 312 | return image 313 | 314 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs 315 | def check_inputs(self, prompt, height, width, callback_steps): 316 | if not isinstance(prompt, str) and not isinstance(prompt, list): 317 | raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") 318 | 319 | if height % 8 != 0 or width % 8 != 0: 320 | raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") 321 | 322 | if (callback_steps is None) or ( 323 | callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) 324 | ): 325 | raise ValueError( 326 | f"`callback_steps` has to be a positive integer but is {callback_steps} of type" 327 | f" {type(callback_steps)}." 328 | ) 329 | 330 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents 331 | def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None): 332 | shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor) 333 | if isinstance(generator, list) and len(generator) != batch_size: 334 | raise ValueError( 335 | f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" 336 | f" size of {batch_size}. Make sure the batch size matches the length of the generators." 337 | ) 338 | 339 | if latents is None: 340 | rand_device = "cpu" if device.type == "mps" else device 341 | 342 | if isinstance(generator, list): 343 | shape = (1,) + shape[1:] 344 | latents = [ 345 | torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype) 346 | for i in range(batch_size) 347 | ] 348 | latents = torch.cat(latents, dim=0).to(device) 349 | else: 350 | latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype).to(device) 351 | else: 352 | if latents.shape != shape: 353 | raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}") 354 | latents = latents.to(device) 355 | 356 | # scale the initial noise by the standard deviation required by the scheduler 357 | latents = latents * self.scheduler.init_noise_sigma 358 | return latents 359 | 360 | def prepare_mask_latents( 361 | self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance 362 | ): 363 | # resize the mask to latents shape as we concatenate the mask to the latents 364 | # we do that before converting to dtype to avoid breaking in case we're using cpu_offload 365 | # and half precision 366 | mask = torch.nn.functional.interpolate( 367 | mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor) 368 | ) 369 | mask = mask.to(device=device, dtype=dtype) 370 | 371 | masked_image = masked_image.to(device=device, dtype=dtype) 372 | 373 | # encode the mask image into latents space so we can concatenate it to the latents 374 | if isinstance(generator, list): 375 | masked_image_latents = [ 376 | self.vae.encode(masked_image[i: i + 1]).latent_dist.sample(generator=generator[i]) 377 | for i in range(batch_size) 378 | ] 379 | masked_image_latents = torch.cat(masked_image_latents, dim=0) 380 | else: 381 | masked_image_latents = self.vae.encode(masked_image).latent_dist.sample(generator=generator) 382 | masked_image_latents = 0.18215 * masked_image_latents 383 | 384 | # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method 385 | if mask.shape[0] < batch_size: 386 | if not batch_size % mask.shape[0] == 0: 387 | raise ValueError( 388 | "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to" 389 | f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number" 390 | " of masks that you pass is divisible by the total requested batch size." 391 | ) 392 | mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1) 393 | if masked_image_latents.shape[0] < batch_size: 394 | if not batch_size % masked_image_latents.shape[0] == 0: 395 | raise ValueError( 396 | "The passed images and the required batch size don't match. Images are supposed to be duplicated" 397 | f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed." 398 | " Make sure the number of images that you pass is divisible by the total requested batch size." 399 | ) 400 | masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1) 401 | 402 | mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask 403 | masked_image_latents = ( 404 | torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents 405 | ) 406 | 407 | # aligning device to prevent device errors when concating it with the latent model input 408 | masked_image_latents = masked_image_latents.to(device=device, dtype=dtype) 409 | return mask, masked_image_latents 410 | 411 | @torch.no_grad() 412 | def __call__( 413 | self, 414 | prompt: Union[str, List[str]], 415 | image: Union[torch.FloatTensor, PIL.Image.Image], 416 | mask_image: Union[torch.FloatTensor, PIL.Image.Image], 417 | pose_map: torch.FloatTensor, 418 | sketch: torch.FloatTensor, 419 | height: Optional[int] = None, 420 | width: Optional[int] = None, 421 | num_inference_steps: int = 50, 422 | guidance_scale: float = 7.5, 423 | negative_prompt: Optional[Union[str, List[str]]] = None, 424 | num_images_per_prompt: Optional[int] = 1, 425 | eta: float = 0.0, 426 | generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, 427 | latents: Optional[torch.FloatTensor] = None, 428 | output_type: Optional[str] = "pil", 429 | return_dict: bool = True, 430 | callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, 431 | callback_steps: Optional[int] = 1, 432 | sketch_cond_rate: float = 1.0, 433 | start_cond_rate: float = 0, 434 | no_pose: bool = False, 435 | ): 436 | r""" 437 | Function invoked when calling the pipeline for generation. 438 | 439 | Args: 440 | prompt (`str` or `List[str]`): 441 | The prompt or prompts to guide the image generation. 442 | image (`PIL.Image.Image`): 443 | `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will 444 | be masked out with `mask_image` and repainted according to `prompt`. 445 | mask_image (`PIL.Image.Image`): 446 | `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be 447 | repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted 448 | to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L) 449 | instead of 3, so the expected shape would be `(B, H, W, 1)`. 450 | height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): 451 | The height in pixels of the generated image. 452 | width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): 453 | The width in pixels of the generated image. 454 | num_inference_steps (`int`, *optional*, defaults to 50): 455 | The number of denoising steps. More denoising steps usually lead to a higher quality image at the 456 | expense of slower inference. 457 | guidance_scale (`float`, *optional*, defaults to 7.5): 458 | Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). 459 | `guidance_scale` is defined as `w` of equation 2. of [Imagen 460 | Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > 461 | 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, 462 | usually at the expense of lower image quality. 463 | negative_prompt (`str` or `List[str]`, *optional*): 464 | The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored 465 | if `guidance_scale` is less than `1`). 466 | num_images_per_prompt (`int`, *optional*, defaults to 1): 467 | The number of images to generate per prompt. 468 | eta (`float`, *optional*, defaults to 0.0): 469 | Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to 470 | [`schedulers.DDIMScheduler`], will be ignored for others. 471 | generator (`torch.Generator`, *optional*): 472 | One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) 473 | to make generation deterministic. 474 | latents (`torch.FloatTensor`, *optional*): 475 | Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image 476 | generation. Can be used to tweak the same generation with different prompts. If not provided, a latents 477 | tensor will ge generated by sampling using the supplied random `generator`. 478 | output_type (`str`, *optional*, defaults to `"pil"`): 479 | The output format of the generate image. Choose between 480 | [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. 481 | return_dict (`bool`, *optional*, defaults to `True`): 482 | Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a 483 | plain tuple. 484 | callback (`Callable`, *optional*): 485 | A function that will be called every `callback_steps` steps during inference. The function will be 486 | called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. 487 | callback_steps (`int`, *optional*, defaults to 1): 488 | The frequency at which the `callback` function will be called. If not specified, the callback will be 489 | called at every step. 490 | 491 | Returns: 492 | [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: 493 | [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. 494 | When returning a tuple, the first element is a list with the generated images, and the second element is a 495 | list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" 496 | (nsfw) content, according to the `safety_checker`. 497 | """ 498 | # 0. Default height and width to unet 499 | height = height or self.unet.config.sample_size * self.vae_scale_factor 500 | width = width or self.unet.config.sample_size * self.vae_scale_factor 501 | 502 | # 1. Check inputs 503 | self.check_inputs(prompt, height, width, callback_steps) 504 | 505 | # 2. Define call parameters 506 | batch_size = 1 if isinstance(prompt, str) else len(prompt) 507 | device = self._execution_device 508 | # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) 509 | # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` 510 | # corresponds to doing no classifier free guidance. 511 | do_classifier_free_guidance = guidance_scale > 1.0 512 | 513 | # 3. Encode input prompt 514 | text_embeddings = self._encode_prompt( 515 | prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt 516 | ) 517 | 518 | # 4. Preprocess mask, image and posemap 519 | mask, masked_image = prepare_mask_and_masked_image(image, mask_image) 520 | pose_map = torch.nn.functional.interpolate( 521 | pose_map, size=(pose_map.shape[2] // 8, pose_map.shape[3] // 8), mode="bilinear" 522 | ) 523 | if no_pose: 524 | pose_map = torch.zeros_like(pose_map) 525 | 526 | sketch = torchvision.transforms.functional.resize( 527 | sketch, size=(sketch.shape[2] // 8, sketch.shape[3] // 8), 528 | interpolation=torchvision.transforms.InterpolationMode.BILINEAR, 529 | antialias=True) 530 | sketch = sketch 531 | 532 | # 5. set timesteps 533 | self.scheduler.set_timesteps(num_inference_steps, device=device) 534 | timesteps = self.scheduler.timesteps 535 | 536 | # 5a. Compute the number of steps to run sketch conditioning 537 | # sketch_conditioning_steps = (1 - sketch_cond_rate) * num_inference_steps 538 | start_cond_step = int(num_inference_steps * start_cond_rate) 539 | 540 | sketch_start = start_cond_step 541 | sketch_end = sketch_cond_rate * num_inference_steps + start_cond_step 542 | 543 | # 6. Prepare latent variables 544 | num_channels_latents = self.vae.config.latent_channels 545 | latents = self.prepare_latents( 546 | batch_size * num_images_per_prompt, 547 | num_channels_latents, 548 | height, 549 | width, 550 | text_embeddings.dtype, 551 | device, 552 | generator, 553 | latents, 554 | ) 555 | 556 | # 7. Prepare mask latent variables 557 | mask, masked_image_latents = self.prepare_mask_latents( 558 | mask, 559 | masked_image, 560 | batch_size * num_images_per_prompt, 561 | height, 562 | width, 563 | text_embeddings.dtype, 564 | device, 565 | generator, 566 | do_classifier_free_guidance, 567 | ) 568 | 569 | # 7a. Prepare pose map latent variables 570 | pose_map = torch.cat([torch.zeros_like(pose_map), pose_map]) if do_classifier_free_guidance else pose_map 571 | sketch = torch.cat([torch.zeros_like(sketch), sketch]) if do_classifier_free_guidance else sketch 572 | 573 | # 8. Check that sizes of mask, masked image and latents match 574 | num_channels_mask = mask.shape[1] 575 | num_channels_masked_image = masked_image_latents.shape[1] 576 | num_channels_pose_map = pose_map.shape[1] 577 | num_channels_sketch = sketch.shape[1] 578 | 579 | if num_channels_latents + num_channels_mask + num_channels_masked_image + num_channels_pose_map + num_channels_sketch != self.unet.config.in_channels: 580 | raise ValueError( 581 | f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects" 582 | f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +" 583 | f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}" 584 | f" = {num_channels_latents + num_channels_masked_image + num_channels_mask}. Please verify the config of" 585 | " `pipeline.unet` or your `mask_image` or `image` input." 586 | ) 587 | 588 | # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline 589 | extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) 590 | 591 | # 10. Denoising loop 592 | num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order 593 | with self.progress_bar(total=num_inference_steps) as progress_bar: 594 | for i, t in enumerate(timesteps): 595 | # expand the latents if we are doing classifier free guidance 596 | latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents 597 | 598 | # 10a. Sketch conditioning 599 | if i < sketch_start or i > sketch_end: 600 | local_sketch = torch.zeros_like(sketch) 601 | else: 602 | local_sketch = sketch 603 | 604 | # concat latents, mask, masked_image_latents in the channel dimension 605 | latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) 606 | latent_model_input = torch.cat( 607 | [latent_model_input, mask, masked_image_latents, pose_map.to(mask.dtype), local_sketch.to(mask.dtype)], 608 | dim=1) 609 | 610 | # predict the noise residual 611 | noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample 612 | 613 | # perform guidance 614 | if do_classifier_free_guidance: 615 | noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) 616 | noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) 617 | 618 | # compute the previous noisy sample x_t -> x_t-1 619 | latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample.to( 620 | self.vae.dtype) 621 | 622 | # call the callback, if provided 623 | if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): 624 | progress_bar.update() 625 | if callback is not None and i % callback_steps == 0: 626 | callback(i, t, latents) 627 | 628 | # 11. Post-processing 629 | image = self.decode_latents(latents) 630 | 631 | # 13. Convert to PIL 632 | if output_type == "pil": 633 | image = self.numpy_to_pil(image) 634 | 635 | if not return_dict: 636 | return (image, None) 637 | 638 | return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None) 639 | -------------------------------------------------------------------------------- /src/mgd_pipelines/mgd_pipe_disentangled.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | from typing import Callable, List, Optional, Union 3 | 4 | import PIL 5 | import torch 6 | import torchvision 7 | 8 | from diffusers.utils import is_accelerate_available 9 | from packaging import version 10 | from transformers import CLIPTextModel, CLIPTokenizer 11 | from diffusers.configuration_utils import FrozenDict 12 | from diffusers.models import AutoencoderKL, UNet2DConditionModel 13 | from diffusers.pipeline_utils import DiffusionPipeline 14 | from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler 15 | from diffusers.utils import deprecate 16 | from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput 17 | from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint import prepare_mask_and_masked_image 18 | 19 | 20 | class MGDPipeDisentangled(DiffusionPipeline): 21 | r""" 22 | Pipeline for text and posemap -guided image inpainting using Stable Diffusion. 23 | 24 | This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the 25 | library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) 26 | 27 | Args: 28 | vae ([`AutoencoderKL`]): 29 | Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. 30 | text_encoder ([`CLIPTextModel`]): 31 | Frozen text-encoder. Stable Diffusion uses the text portion of 32 | [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically 33 | the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. 34 | tokenizer (`CLIPTokenizer`): 35 | Tokenizer of class 36 | [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). 37 | unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. 38 | scheduler ([`SchedulerMixin`]): 39 | A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of 40 | [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. 41 | safety_checker ([`StableDiffusionSafetyChecker`]): 42 | Classification module that estimates whether generated images could be considered offensive or harmful. 43 | Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details. 44 | feature_extractor ([`CLIPFeatureExtractor`]): 45 | Model that extracts features from generated images to be used as inputs for the `safety_checker`. 46 | """ 47 | _optional_components = ["safety_checker"] 48 | 49 | def __init__( 50 | self, 51 | vae: AutoencoderKL, 52 | text_encoder: CLIPTextModel, 53 | tokenizer: CLIPTokenizer, 54 | unet: UNet2DConditionModel, 55 | scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler], 56 | safety_checker = None, 57 | feature_extractor = None, 58 | requires_safety_checker: bool = False, 59 | ): 60 | super().__init__() 61 | 62 | if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: 63 | deprecation_message = ( 64 | f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" 65 | f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " 66 | "to update the config accordingly as leaving `steps_offset` might led to incorrect results" 67 | " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," 68 | " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" 69 | " file" 70 | ) 71 | deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) 72 | new_config = dict(scheduler.config) 73 | new_config["steps_offset"] = 1 74 | scheduler._internal_dict = FrozenDict(new_config) 75 | 76 | if hasattr(scheduler.config, "skip_prk_steps") and scheduler.config.skip_prk_steps is False: 77 | deprecation_message = ( 78 | f"The configuration file of this scheduler: {scheduler} has not set the configuration" 79 | " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" 80 | " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" 81 | " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" 82 | " Hub, it would be very nice if you could open a Pull request for the" 83 | " `scheduler/scheduler_config.json` file" 84 | ) 85 | deprecate("skip_prk_steps not set", "1.0.0", deprecation_message, standard_warn=False) 86 | new_config = dict(scheduler.config) 87 | new_config["skip_prk_steps"] = True 88 | scheduler._internal_dict = FrozenDict(new_config) 89 | 90 | if safety_checker is None and requires_safety_checker: 91 | logger.warning( 92 | f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" 93 | " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" 94 | " results in services or applications open to the public. Both the diffusers team and Hugging Face" 95 | " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" 96 | " it only for use-cases that involve analyzing network behavior or auditing its results. For more" 97 | " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." 98 | ) 99 | 100 | if safety_checker is not None and feature_extractor is None: 101 | raise ValueError( 102 | "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" 103 | " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." 104 | ) 105 | 106 | is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse( 107 | version.parse(unet.config._diffusers_version).base_version 108 | ) < version.parse("0.9.0.dev0") 109 | is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 110 | if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: 111 | deprecation_message = ( 112 | "The configuration file of the unet has set the default `sample_size` to smaller than" 113 | " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the" 114 | " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" 115 | " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" 116 | " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" 117 | " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" 118 | " in the config might lead to incorrect results in future versions. If you have downloaded this" 119 | " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" 120 | " the `unet/config.json` file" 121 | ) 122 | deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) 123 | new_config = dict(unet.config) 124 | new_config["sample_size"] = 64 125 | unet._internal_dict = FrozenDict(new_config) 126 | 127 | self.register_modules( 128 | vae=vae, 129 | text_encoder=text_encoder, 130 | tokenizer=tokenizer, 131 | unet=unet, 132 | scheduler=scheduler, 133 | safety_checker=safety_checker, 134 | feature_extractor=feature_extractor, 135 | ) 136 | self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) 137 | self.register_to_config(requires_safety_checker=requires_safety_checker) 138 | 139 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_sequential_cpu_offload 140 | def enable_sequential_cpu_offload(self, gpu_id=0): 141 | r""" 142 | Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet, 143 | text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a 144 | `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called. 145 | """ 146 | if is_accelerate_available(): 147 | from accelerate import cpu_offload 148 | else: 149 | raise ImportError("Please install accelerate via `pip install accelerate`") 150 | 151 | device = torch.device(f"cuda:{gpu_id}") 152 | 153 | for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]: 154 | if cpu_offloaded_model is not None: 155 | cpu_offload(cpu_offloaded_model, device) 156 | 157 | if self.safety_checker is not None: 158 | # TODO(Patrick) - there is currently a bug with cpu offload of nn.Parameter in accelerate 159 | # fix by only offloading self.safety_checker for now 160 | cpu_offload(self.safety_checker.vision_model, device) 161 | 162 | @property 163 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device 164 | def _execution_device(self): 165 | r""" 166 | Returns the device on which the pipeline's models will be executed. After calling 167 | `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module 168 | hooks. 169 | """ 170 | if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"): 171 | return self.device 172 | for module in self.unet.modules(): 173 | if ( 174 | hasattr(module, "_hf_hook") 175 | and hasattr(module._hf_hook, "execution_device") 176 | and module._hf_hook.execution_device is not None 177 | ): 178 | return torch.device(module._hf_hook.execution_device) 179 | return self.device 180 | 181 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt 182 | def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt): 183 | r""" 184 | Encodes the prompt into text encoder hidden states. 185 | 186 | Args: 187 | prompt (`str` or `list(int)`): 188 | prompt to be encoded 189 | device: (`torch.device`): 190 | torch device 191 | num_images_per_prompt (`int`): 192 | number of images that should be generated per prompt 193 | do_classifier_free_guidance (`bool`): 194 | whether to use classifier free guidance or not 195 | negative_prompt (`str` or `List[str]`): 196 | The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored 197 | if `guidance_scale` is less than `1`). 198 | """ 199 | batch_size = len(prompt) if isinstance(prompt, list) else 1 200 | 201 | text_inputs = self.tokenizer( 202 | prompt, 203 | padding="max_length", 204 | max_length=self.tokenizer.model_max_length, 205 | truncation=True, 206 | return_tensors="pt", 207 | ) 208 | text_input_ids = text_inputs.input_ids 209 | untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids 210 | 211 | if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids): 212 | removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]) 213 | logger.warning( 214 | "The following part of your input was truncated because CLIP can only handle sequences up to" 215 | f" {self.tokenizer.model_max_length} tokens: {removed_text}" 216 | ) 217 | 218 | if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: 219 | attention_mask = text_inputs.attention_mask.to(device) 220 | else: 221 | attention_mask = None 222 | 223 | text_embeddings = self.text_encoder( 224 | text_input_ids.to(device), 225 | attention_mask=attention_mask, 226 | ) 227 | text_embeddings = text_embeddings[0] 228 | 229 | # duplicate text embeddings for each generation per prompt, using mps friendly method 230 | bs_embed, seq_len, _ = text_embeddings.shape 231 | text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1) 232 | text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1) 233 | 234 | # get unconditional embeddings for classifier free guidance 235 | if do_classifier_free_guidance: 236 | uncond_tokens: List[str] 237 | if negative_prompt is None: 238 | uncond_tokens = [""] * batch_size 239 | elif type(prompt) is not type(negative_prompt): 240 | raise TypeError( 241 | f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" 242 | f" {type(prompt)}." 243 | ) 244 | elif isinstance(negative_prompt, str): 245 | uncond_tokens = [negative_prompt] 246 | elif batch_size != len(negative_prompt): 247 | raise ValueError( 248 | f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" 249 | f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" 250 | " the batch size of `prompt`." 251 | ) 252 | else: 253 | uncond_tokens = negative_prompt 254 | 255 | max_length = text_input_ids.shape[-1] 256 | uncond_input = self.tokenizer( 257 | uncond_tokens, 258 | padding="max_length", 259 | max_length=max_length, 260 | truncation=True, 261 | return_tensors="pt", 262 | ) 263 | 264 | if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: 265 | attention_mask = uncond_input.attention_mask.to(device) 266 | else: 267 | attention_mask = None 268 | 269 | uncond_embeddings = self.text_encoder( 270 | uncond_input.input_ids.to(device), 271 | attention_mask=attention_mask, 272 | ) 273 | uncond_embeddings = uncond_embeddings[0] 274 | 275 | # duplicate unconditional embeddings for each generation per prompt, using mps friendly method 276 | seq_len = uncond_embeddings.shape[1] 277 | uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1) 278 | uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1) 279 | 280 | # For classifier free guidance, we need to do two forward passes. 281 | # Here we concatenate the unconditional and text embeddings into a single batch 282 | # to avoid doing two forward passes 283 | text_embeddings = torch.cat([uncond_embeddings, text_embeddings, uncond_embeddings, uncond_embeddings]) 284 | 285 | return text_embeddings 286 | 287 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs 288 | def prepare_extra_step_kwargs(self, generator, eta): 289 | # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature 290 | # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. 291 | # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 292 | # and should be between [0, 1] 293 | 294 | accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) 295 | extra_step_kwargs = {} 296 | if accepts_eta: 297 | extra_step_kwargs["eta"] = eta 298 | 299 | # check if the scheduler accepts generator 300 | accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) 301 | if accepts_generator: 302 | extra_step_kwargs["generator"] = generator 303 | return extra_step_kwargs 304 | 305 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents 306 | def decode_latents(self, latents): 307 | latents = 1 / 0.18215 * latents 308 | image = self.vae.decode(latents).sample 309 | image = (image / 2 + 0.5).clamp(0, 1) 310 | # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16 311 | image = image.cpu().permute(0, 2, 3, 1).float().numpy() 312 | return image 313 | 314 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs 315 | def check_inputs(self, prompt, height, width, callback_steps): 316 | if not isinstance(prompt, str) and not isinstance(prompt, list): 317 | raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") 318 | 319 | if height % 8 != 0 or width % 8 != 0: 320 | raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") 321 | 322 | if (callback_steps is None) or ( 323 | callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) 324 | ): 325 | raise ValueError( 326 | f"`callback_steps` has to be a positive integer but is {callback_steps} of type" 327 | f" {type(callback_steps)}." 328 | ) 329 | 330 | # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents 331 | def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None): 332 | shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor) 333 | if isinstance(generator, list) and len(generator) != batch_size: 334 | raise ValueError( 335 | f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" 336 | f" size of {batch_size}. Make sure the batch size matches the length of the generators." 337 | ) 338 | 339 | if latents is None: 340 | rand_device = "cpu" if device.type == "mps" else device 341 | 342 | if isinstance(generator, list): 343 | shape = (1,) + shape[1:] 344 | latents = [ 345 | torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype) 346 | for i in range(batch_size) 347 | ] 348 | latents = torch.cat(latents, dim=0).to(device) 349 | else: 350 | latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype).to(device) 351 | else: 352 | if latents.shape != shape: 353 | raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}") 354 | latents = latents.to(device) 355 | 356 | # scale the initial noise by the standard deviation required by the scheduler 357 | latents = latents * self.scheduler.init_noise_sigma 358 | return latents 359 | 360 | def prepare_mask_latents( 361 | self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance 362 | ): 363 | # resize the mask to latents shape as we concatenate the mask to the latents 364 | # we do that before converting to dtype to avoid breaking in case we're using cpu_offload 365 | # and half precision 366 | mask = torch.nn.functional.interpolate( 367 | mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor) 368 | ) 369 | mask = mask.to(device=device, dtype=dtype) 370 | 371 | masked_image = masked_image.to(device=device, dtype=dtype) 372 | 373 | # encode the mask image into latents space so we can concatenate it to the latents 374 | if isinstance(generator, list): 375 | masked_image_latents = [ 376 | self.vae.encode(masked_image[i : i + 1]).latent_dist.sample(generator=generator[i]) 377 | for i in range(batch_size) 378 | ] 379 | masked_image_latents = torch.cat(masked_image_latents, dim=0) 380 | else: 381 | masked_image_latents = self.vae.encode(masked_image).latent_dist.sample(generator=generator) 382 | masked_image_latents = 0.18215 * masked_image_latents 383 | 384 | # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method 385 | if mask.shape[0] < batch_size: 386 | if not batch_size % mask.shape[0] == 0: 387 | raise ValueError( 388 | "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to" 389 | f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number" 390 | " of masks that you pass is divisible by the total requested batch size." 391 | ) 392 | mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1) 393 | if masked_image_latents.shape[0] < batch_size: 394 | if not batch_size % masked_image_latents.shape[0] == 0: 395 | raise ValueError( 396 | "The passed images and the required batch size don't match. Images are supposed to be duplicated" 397 | f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed." 398 | " Make sure the number of images that you pass is divisible by the total requested batch size." 399 | ) 400 | masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1) 401 | 402 | mask = torch.cat([mask] * 4) if do_classifier_free_guidance else mask 403 | masked_image_latents = ( 404 | torch.cat([masked_image_latents] * 4) if do_classifier_free_guidance else masked_image_latents 405 | ) 406 | 407 | # aligning device to prevent device errors when concating it with the latent model input 408 | masked_image_latents = masked_image_latents.to(device=device, dtype=dtype) 409 | return mask, masked_image_latents 410 | 411 | @torch.no_grad() 412 | def __call__( 413 | self, 414 | prompt: Union[str, List[str]], 415 | image: Union[torch.FloatTensor, PIL.Image.Image], 416 | mask_image: Union[torch.FloatTensor, PIL.Image.Image], 417 | pose_map: torch.FloatTensor, 418 | sketch: torch.FloatTensor, 419 | height: Optional[int] = None, 420 | width: Optional[int] = None, 421 | num_inference_steps: int = 50, 422 | guidance_scale: float = 7.5, 423 | guidance_scale_pose: float = 7.5, 424 | guidance_scale_sketch: float = 7.5, 425 | negative_prompt: Optional[Union[str, List[str]]] = None, 426 | num_images_per_prompt: Optional[int] = 1, 427 | eta: float = 0.0, 428 | generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, 429 | latents: Optional[torch.FloatTensor] = None, 430 | output_type: Optional[str] = "pil", 431 | return_dict: bool = True, 432 | callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, 433 | callback_steps: Optional[int] = 1, 434 | sketch_cond_rate: float = 1.0, 435 | start_cond_rate: float = 0, 436 | no_pose: bool = False, 437 | ): 438 | r""" 439 | Function invoked when calling the pipeline for generation. 440 | 441 | Args: 442 | prompt (`str` or `List[str]`): 443 | The prompt or prompts to guide the image generation. 444 | image (`PIL.Image.Image`): 445 | `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will 446 | be masked out with `mask_image` and repainted according to `prompt`. 447 | mask_image (`PIL.Image.Image`): 448 | `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be 449 | repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted 450 | to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L) 451 | instead of 3, so the expected shape would be `(B, H, W, 1)`. 452 | height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): 453 | The height in pixels of the generated image. 454 | width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): 455 | The width in pixels of the generated image. 456 | num_inference_steps (`int`, *optional*, defaults to 50): 457 | The number of denoising steps. More denoising steps usually lead to a higher quality image at the 458 | expense of slower inference. 459 | guidance_scale (`float`, *optional*, defaults to 7.5): 460 | Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). 461 | `guidance_scale` is defined as `w` of equation 2. of [Imagen 462 | Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > 463 | 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, 464 | usually at the expense of lower image quality. 465 | negative_prompt (`str` or `List[str]`, *optional*): 466 | The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored 467 | if `guidance_scale` is less than `1`). 468 | num_images_per_prompt (`int`, *optional*, defaults to 1): 469 | The number of images to generate per prompt. 470 | eta (`float`, *optional*, defaults to 0.0): 471 | Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to 472 | [`schedulers.DDIMScheduler`], will be ignored for others. 473 | generator (`torch.Generator`, *optional*): 474 | One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) 475 | to make generation deterministic. 476 | latents (`torch.FloatTensor`, *optional*): 477 | Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image 478 | generation. Can be used to tweak the same generation with different prompts. If not provided, a latents 479 | tensor will ge generated by sampling using the supplied random `generator`. 480 | output_type (`str`, *optional*, defaults to `"pil"`): 481 | The output format of the generate image. Choose between 482 | [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. 483 | return_dict (`bool`, *optional*, defaults to `True`): 484 | Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a 485 | plain tuple. 486 | callback (`Callable`, *optional*): 487 | A function that will be called every `callback_steps` steps during inference. The function will be 488 | called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. 489 | callback_steps (`int`, *optional*, defaults to 1): 490 | The frequency at which the `callback` function will be called. If not specified, the callback will be 491 | called at every step. 492 | 493 | Returns: 494 | [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: 495 | [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. 496 | When returning a tuple, the first element is a list with the generated images, and the second element is a 497 | list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" 498 | (nsfw) content, according to the `safety_checker`. 499 | """ 500 | # 0. Default height and width to unet 501 | height = height or self.unet.config.sample_size * self.vae_scale_factor 502 | width = width or self.unet.config.sample_size * self.vae_scale_factor 503 | 504 | # 1. Check inputs 505 | self.check_inputs(prompt, height, width, callback_steps) 506 | 507 | # 2. Define call parameters 508 | batch_size = 1 if isinstance(prompt, str) else len(prompt) 509 | device = self._execution_device 510 | # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) 511 | # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` 512 | # corresponds to doing no classifier free guidance. 513 | do_classifier_free_guidance = True 514 | 515 | # 3. Encode input prompt 516 | text_embeddings = self._encode_prompt( 517 | prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt 518 | ) 519 | # pose_map_vis = pose_map.sum(dim=1).unsqueeze(1).clamp(0,1) 520 | # plt.imsave("Pose.jpg", pose_map_vis[0].repeat(3,1,1).permute(1,2,0).cpu().numpy()) 521 | 522 | # 4. Preprocess mask, image and posemap 523 | mask, masked_image = prepare_mask_and_masked_image(image, mask_image) 524 | pose_map = torch.nn.functional.interpolate( 525 | pose_map, size=(pose_map.shape[2] // 8, pose_map.shape[3] // 8), mode="bilinear" 526 | ) 527 | if no_pose: 528 | pose_map = torch.zeros_like(pose_map) 529 | 530 | # plt.imsave("Sketch.jpg", sketch[0].repeat(3,1,1).permute(1,2,0).cpu().numpy()) 531 | sketch = torchvision.transforms.functional.resize( 532 | sketch, size=(sketch.shape[2] // 8, sketch.shape[3] // 8), 533 | interpolation=torchvision.transforms.InterpolationMode.BILINEAR, 534 | antialias=True) 535 | sketch = sketch 536 | # plt.imsave("Image.png", ((image[0] + 1) / 2).permute(1,2,0).cpu().numpy()) 537 | 538 | # 5. set timesteps 539 | self.scheduler.set_timesteps(num_inference_steps, device=device) 540 | timesteps = self.scheduler.timesteps 541 | 542 | # 5a. Compute the number of steps to run sketch conditioning 543 | # sketch_conditioning_steps = (1 - sketch_cond_rate) * num_inference_steps 544 | start_cond_step = int(num_inference_steps * start_cond_rate) 545 | 546 | sketch_start = start_cond_step 547 | sketch_end = sketch_cond_rate * num_inference_steps + start_cond_step 548 | 549 | # 6. Prepare latent variables 550 | num_channels_latents = self.vae.config.latent_channels 551 | latents = self.prepare_latents( 552 | batch_size * num_images_per_prompt, 553 | num_channels_latents, 554 | height, 555 | width, 556 | text_embeddings.dtype, 557 | device, 558 | generator, 559 | latents, 560 | ) 561 | 562 | # 7. Prepare mask latent variables 563 | mask, masked_image_latents = self.prepare_mask_latents( 564 | mask, 565 | masked_image, 566 | batch_size * num_images_per_prompt, 567 | height, 568 | width, 569 | text_embeddings.dtype, 570 | device, 571 | generator, 572 | do_classifier_free_guidance, 573 | ) 574 | 575 | # 7a. Prepare pose map latent variables 576 | pose_map = torch.cat([torch.zeros_like(pose_map), torch.zeros_like(pose_map), pose_map, torch.zeros_like(pose_map)]) if do_classifier_free_guidance else pose_map 577 | sketch = torch.cat([torch.zeros_like(sketch), torch.zeros_like(sketch), torch.zeros_like(sketch), sketch]) if do_classifier_free_guidance else sketch 578 | 579 | # 8. Check that sizes of mask, masked image and latents match 580 | num_channels_mask = mask.shape[1] 581 | num_channels_masked_image = masked_image_latents.shape[1] 582 | if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels: 583 | raise ValueError( 584 | f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects" 585 | f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +" 586 | f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}" 587 | f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of" 588 | " `pipeline.unet` or your `mask_image` or `image` input." 589 | ) 590 | 591 | # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline 592 | extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) 593 | 594 | # 10. Denoising loop 595 | num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order 596 | with self.progress_bar(total=num_inference_steps) as progress_bar: 597 | for i, t in enumerate(timesteps): 598 | # expand the latents if we are doing classifier free guidance 599 | latent_model_input = torch.cat([latents] * 4) if do_classifier_free_guidance else latents 600 | 601 | # 10a. Sketch conditioning 602 | if i < sketch_start or i > sketch_end: 603 | local_sketch = torch.zeros_like(sketch) 604 | else: 605 | local_sketch = sketch 606 | 607 | # concat latents, mask, masked_image_latents in the channel dimension 608 | latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) 609 | latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents, pose_map.to(mask.dtype), local_sketch.to(mask.dtype)], dim=1) 610 | 611 | # predict the noise residual 612 | noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample 613 | 614 | # perform guidance 615 | if do_classifier_free_guidance: 616 | noise_pred_uncond, noise_pred_text, noise_pred_pose, noise_pred_sketch = noise_pred.chunk(4) 617 | noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) + guidance_scale_pose * (noise_pred_pose - noise_pred_uncond) + guidance_scale_sketch * (noise_pred_sketch - noise_pred_uncond) 618 | 619 | # compute the previous noisy sample x_t -> x_t-1 620 | latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample 621 | 622 | # call the callback, if provided 623 | if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): 624 | progress_bar.update() 625 | if callback is not None and i % callback_steps == 0: 626 | callback(i, t, latents) 627 | 628 | # 11. Post-processing 629 | image = self.decode_latents(latents) 630 | 631 | # 13. Convert to PIL 632 | if output_type == "pil": 633 | image = self.numpy_to_pil(image) 634 | 635 | if not return_dict: 636 | return (image, None) 637 | 638 | return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None) 639 | -------------------------------------------------------------------------------- /src/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aimagelab/multimodal-garment-designer/f51e94e50eaaaa998a1b1ab18ad5ff3456d49339/src/utils/__init__.py -------------------------------------------------------------------------------- /src/utils/arg_parser.py: -------------------------------------------------------------------------------- 1 | import os 2 | import argparse 3 | 4 | 5 | def eval_parse_args() -> argparse.Namespace: 6 | """ This function parses the arguments passed to the script. 7 | 8 | Returns: 9 | argparse.Namespace: Namespace containing the arguments. 10 | """ 11 | 12 | parser = argparse.ArgumentParser(description="Multimodal Garment Designer argparse.") 13 | 14 | # Diffusion parameters 15 | parser.add_argument( 16 | "--pretrained_model_name_or_path", 17 | type=str, 18 | default="runwayml/stable-diffusion-inpainting", 19 | help="Path to pretrained model or model identifier from huggingface.co/models.", 20 | ) 21 | parser.add_argument( 22 | "--revision", 23 | type=str, 24 | default=None, 25 | required=False, 26 | help="Revision of pretrained model identifier from huggingface.co/models.", 27 | ) 28 | 29 | # destination folder 30 | parser.add_argument( 31 | "--output_dir", 32 | type=str, 33 | required=True, 34 | help="The output directory where the model predictions will be written.", 35 | ) 36 | 37 | # Accelerator parameters 38 | parser.add_argument( 39 | "--mixed_precision", 40 | type=str, 41 | default=None, 42 | choices=["no", "fp16", "bf16"], 43 | help=( 44 | "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >=" 45 | " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the" 46 | " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config." 47 | ), 48 | ) 49 | parser.add_argument( 50 | "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers." 51 | ) 52 | 53 | # dataset parameters 54 | parser.add_argument("--dataset", type=str, required=True, choices=["dresscode", "vitonhd"], help="dataset to use") 55 | parser.add_argument( 56 | "--dataset_path", 57 | type=str, 58 | required=True, 59 | help="Path to the dataset", 60 | ) 61 | parser.add_argument("--category", type=str, default="", help="category to use") 62 | parser.add_argument("--test_order", type=str, required=True, choices=["unpaired", "paired"], 63 | help="Test order, should be either paired or unpaired") 64 | 65 | # dataloader parameters 66 | parser.add_argument("--batch_size", type=int, default=1, help="Batch size (per device) for the test dataloader.") 67 | parser.add_argument("--num_workers_test", type=int, default=8, 68 | help="Number of workers for the test dataloader.") 69 | 70 | 71 | # input parameters 72 | parser.add_argument("--mask_type", type=str, default="bounding_box", choices=["keypoints", "bounding_box"]) 73 | parser.add_argument("--no_pose", action="store_true", help="exclude posemap from input") 74 | 75 | 76 | # disentagle classifier free guidance parameters 77 | parser.add_argument("--disentagle", action="store_true") 78 | parser.add_argument("--guidance_scale", type=float, default=7.5, help="text guidance scale, use with disentagle") 79 | parser.add_argument("--guidance_scale_pose", type=float, default=7.5, 80 | help="pose guidance scale, use with disentagle") 81 | parser.add_argument("--guidance_scale_sketch", type=float, default=7.5, 82 | help="sketch guidance scale, use with disentagle") 83 | 84 | # sketch conditioninig paramters 85 | parser.add_argument("--sketch_cond_rate", type=float, default=0.2, help="Sketch conditioning rate") 86 | parser.add_argument("--start_cond_rate", type=float, default=0.0, help="offset sketch cond rate") 87 | 88 | # miscelaneous parameters 89 | parser.add_argument("--seed", type=int, default=1234, help="A seed for reproducible training.") 90 | parser.add_argument("--save_name", type=str, required=True, help="Folder name of the saved images") 91 | 92 | args = parser.parse_args() 93 | 94 | # if not, set default local rank 95 | env_local_rank = int(os.environ.get("LOCAL_RANK", -1)) 96 | if env_local_rank != -1 and env_local_rank != args.local_rank: 97 | args.local_rank = env_local_rank 98 | 99 | return args 100 | -------------------------------------------------------------------------------- /src/utils/image_composition.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torchvision.transforms.functional as F 3 | 4 | def compose_img(gt_img, fake_img, im_parse): 5 | 6 | seg_head = torch.logical_or(im_parse == 1, im_parse == 2) 7 | seg_head = torch.logical_or(seg_head, im_parse == 4) 8 | seg_head = torch.logical_or(seg_head, im_parse == 13) 9 | 10 | true_head = gt_img * seg_head 11 | true_parts = true_head 12 | 13 | generated_body = (F.pil_to_tensor(fake_img).cuda() / 255) * (~(seg_head)) 14 | 15 | return true_parts + generated_body 16 | 17 | def compose_img_dresscode(gt_img, fake_img, im_head): 18 | 19 | seg_head = im_head 20 | true_head = gt_img * seg_head 21 | generated_body = fake_img * ~(seg_head) 22 | 23 | return true_head + generated_body -------------------------------------------------------------------------------- /src/utils/image_from_pipe.py: -------------------------------------------------------------------------------- 1 | import os 2 | from tqdm import tqdm 3 | import torch 4 | 5 | import torchvision.transforms as T 6 | from diffusers.pipeline_utils import DiffusionPipeline 7 | from torch.utils.data import DataLoader 8 | from src.utils.image_composition import compose_img, compose_img_dresscode 9 | 10 | 11 | @torch.inference_mode() 12 | def generate_images_from_mgd_pipe( 13 | test_order: bool, 14 | pipe: DiffusionPipeline, 15 | test_dataloader: DataLoader, 16 | save_name: str, 17 | dataset: str, 18 | output_dir: str, 19 | guidance_scale: float = 7.5, 20 | guidance_scale_pose: float = 7.5, 21 | guidance_scale_sketch: float = 7.5, 22 | sketch_cond_rate: float = 1.0, 23 | start_cond_rate: float = 0.0, 24 | no_pose: bool = False, 25 | disentagle: bool = False, 26 | seed: int = 1234, 27 | ) -> None: 28 | #This function generates images from the given test dataloader and saves them to the output directory. 29 | """ 30 | Args: 31 | test_order: The order of the test dataset. 32 | pipe: The diffusion pipeline. 33 | test_dataloader: The test dataloader. 34 | save_name: The name of the saved images. 35 | dataset: The name of the dataset. 36 | output_dir: The output directory. 37 | guidance_scale: The guidance scale. 38 | guidance_scale_pose: The guidance scale for the pose. 39 | guidance_scale_sketch: The guidance scale for the sketch. 40 | sketch_cond_rate: The sketch condition rate. 41 | start_cond_rate: The start condition rate. 42 | no_pose: Whether to use the pose. 43 | disentagle: Whether to use disentagle. 44 | seed: The seed. 45 | 46 | Returns: 47 | None 48 | """ 49 | assert(save_name != ""), "save_name must be specified" 50 | assert(output_dir != ""), "output_dir must be specified" 51 | 52 | path = os.path.join(output_dir, f"{save_name}_{test_order}", "images") 53 | 54 | os.makedirs(path, exist_ok=True) 55 | generator = torch.Generator("cuda").manual_seed(seed) 56 | 57 | for batch in tqdm(test_dataloader): 58 | model_img = batch["image"] 59 | mask_img = batch["inpaint_mask"] 60 | mask_img = mask_img.type(torch.float32) 61 | prompts = batch["original_captions"] # prompts is a list of length N, where N=batch size. 62 | pose_map = batch["pose_map"] 63 | sketch = batch["im_sketch"] 64 | ext = ".jpg" 65 | 66 | if disentagle: 67 | guidance_scale = guidance_scale 68 | num_samples = 1 69 | guidance_scale_pose = guidance_scale_pose 70 | guidance_scale_sketch = guidance_scale_sketch 71 | generated_images = pipe( 72 | prompt=prompts, 73 | image=model_img, 74 | mask_image=mask_img, 75 | pose_map=pose_map, 76 | sketch=sketch, 77 | height=512, 78 | width=384, 79 | guidance_scale=guidance_scale, 80 | num_images_per_prompt=num_samples, 81 | generator=generator, 82 | sketch_cond_rate=sketch_cond_rate, 83 | guidance_scale_pose=guidance_scale_pose, 84 | guidance_scale_sketch=guidance_scale_sketch, 85 | start_cond_rate=start_cond_rate, 86 | no_pose=no_pose, 87 | ).images 88 | else: 89 | guidance_scale = 7.5 90 | num_samples = 1 91 | generated_images = pipe( 92 | prompt=prompts, 93 | image=model_img, 94 | mask_image=mask_img, 95 | pose_map=pose_map, 96 | sketch=sketch, 97 | height=512, 98 | width=384, 99 | guidance_scale=guidance_scale, 100 | num_images_per_prompt=num_samples, 101 | generator=generator, 102 | sketch_cond_rate=sketch_cond_rate, 103 | start_cond_rate=start_cond_rate, 104 | no_pose=no_pose, 105 | ).images 106 | 107 | for i in range(len(generated_images)): 108 | model_i = model_img[i] * 0.5 + 0.5 109 | if dataset == "vitonhd": 110 | final_img = compose_img(model_i, generated_images[i], batch['im_parse'][i]) 111 | else: # dataset == Dresscode 112 | face = batch["stitch_label"][i].to(model_img.device) 113 | face = T.functional.resize(face, 114 | size=(512,384), 115 | interpolation=T.InterpolationMode.BILINEAR, 116 | antialias = True 117 | ) 118 | 119 | final_img = compose_img_dresscode( 120 | gt_img = model_i, 121 | fake_img = T.functional.to_tensor(generated_images[i]).to(model_img.device), 122 | im_head = face 123 | ) 124 | 125 | final_img = T.functional.to_pil_image(final_img) 126 | final_img.save( 127 | os.path.join(path, batch["im_name"][i].replace(".jpg", ext))) 128 | -------------------------------------------------------------------------------- /src/utils/labelmap.py: -------------------------------------------------------------------------------- 1 | label_map={ 2 | "background": 0, 3 | "hat": 1, 4 | "hair": 2, 5 | "sunglasses": 3, 6 | "upper_clothes": 4, 7 | "skirt": 5, 8 | "pants": 6, 9 | "dress": 7, 10 | "belt": 8, 11 | "left_shoe": 9, 12 | "right_shoe": 10, 13 | "head": 11, 14 | "left_leg": 12, 15 | "right_leg": 13, 16 | "left_arm": 14, 17 | "right_arm": 15, 18 | "bag": 16, 19 | "scarf": 17, 20 | } 21 | 22 | label_map_vitonhd = { 23 | 0: ['background', [0, 10]], # 0 is background, 10 is neck 24 | 1: ['hair', [1, 2]], # 1 and 2 are hair 25 | 2: ['face', [4, 13]], 26 | 3: ['upper', [5, 6, 7]], 27 | 4: ['bottom', [9, 12]], 28 | 5: ['left_arm', [14]], 29 | 6: ['right_arm', [15]], 30 | 7: ['left_leg', [16]], 31 | 8: ['right_leg', [17]], 32 | 9: ['left_shoe', [18]], 33 | 10: ['right_shoe', [19]], 34 | 11: ['socks', [8]], 35 | 12: ['noise', [3, 11]] 36 | } -------------------------------------------------------------------------------- /src/utils/posemap.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import numpy as np 3 | 4 | 5 | 6 | def kpoint_to_heatmap(kpoint, shape, sigma): 7 | """Converts a 2D keypoint to a gaussian heatmap 8 | 9 | Parameters 10 | ---------- 11 | kpoint: np.array 12 | 2D coordinates of keypoint [x, y]. 13 | shape: tuple 14 | Heatmap dimension (HxW). 15 | sigma: float 16 | Variance value of the gaussian. 17 | 18 | Returns 19 | ------- 20 | heatmap: np.array 21 | A gaussian heatmap HxW. 22 | """ 23 | map_h = shape[0] 24 | map_w = shape[1] 25 | if np.any(kpoint > 0): 26 | x, y = kpoint 27 | # x = x * map_w / 384.0 28 | # y = y * map_h / 512.0 29 | xy_grid = np.mgrid[:map_w, :map_h].transpose(2, 1, 0) 30 | heatmap = np.exp(-np.sum((xy_grid - (x, y)) ** 2, axis=-1) / sigma ** 2) 31 | heatmap /= (heatmap.max() + np.finfo('float32').eps) 32 | else: 33 | heatmap = np.zeros((map_h, map_w)) 34 | return torch.Tensor(heatmap) 35 | 36 | 37 | def get_coco_body25_mapping(): 38 | #left numbers are coco format while right numbers are body25 format 39 | return { 40 | 0:0, 41 | 1:1, 42 | 2:2, 43 | 3:3, 44 | 4:4, 45 | 5:5, 46 | 6:6, 47 | 7:7, 48 | 8:9, 49 | 9:10, 50 | 10:11, 51 | 11:12, 52 | 12:13, 53 | 13:14, 54 | 14:15, 55 | 15:16, 56 | 16:17, 57 | 17:18 58 | } -------------------------------------------------------------------------------- /src/utils/set_seeds.py: -------------------------------------------------------------------------------- 1 | import random 2 | import os 3 | import numpy as np 4 | import torch 5 | import accelerate 6 | 7 | 8 | def set_seed(seed): 9 | random.seed(seed) 10 | os.environ['PYTHONHASHSEED'] = str(seed) 11 | np.random.seed(seed) 12 | torch.manual_seed(seed) 13 | torch.cuda.manual_seed(seed) 14 | torch.backends.cudnn.deterministic = True 15 | accelerate.utils.set_seed(seed) 16 | --------------------------------------------------------------------------------