[
  {
    "path": ".github/workflows/publish-pip.yml",
    "content": "name: PyPI Publish\n\non: push\n\njobs:\n  build-n-publish:\n    runs-on: ubuntu-latest\n    if: startsWith(github.event.ref, 'refs/tags')\n\n    steps:\n      - uses: actions/checkout@v2\n      - name: Set up Python 3.8\n        uses: actions/setup-python@v1\n        with:\n          python-version: 3.8\n      - name: Upgrade pip\n        run: pip install pip --upgrade\n      - name: Install PyTorch (cpu)\n        run: pip install torch==1.7.0+cpu torchvision==0.8.1+cpu -f https://download.pytorch.org/whl/torch_stable.html\n      - name: Install dependencies\n        run: pip install -r requirements.txt\n      - name: Build and install\n        run: rm -rf .eggs && pip install -e .\n      - name: Build for distribution\n        run: python setup.py sdist bdist_wheel\n      - name: Publish distribution to PyPI\n        uses: pypa/gh-action-pypi-publish@master\n        with:\n          password: ${{ secrets.PYPI_API_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/pylint.yml",
    "content": "name: PyLint\n\non: [push, pull_request]\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        python-version: [3.8]\n\n    steps:\n    - uses: actions/checkout@v2\n    - name: Set up Python ${{ matrix.python-version }}\n      uses: actions/setup-python@v2\n      with:\n        python-version: ${{ matrix.python-version }}\n\n    - name: Install dependencies\n      run: |\n        python -m pip install --upgrade pip\n        pip install codespell flake8 isort yapf\n\n    - name: Lint\n      run: |\n        codespell\n        flake8 .\n        isort --check-only --diff gfpgan/ scripts/ inference_gfpgan.py setup.py\n        yapf -r -d gfpgan/ scripts/ inference_gfpgan.py setup.py\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: release\non:\n  push:\n    tags:\n      - '*'\n\njobs:\n  build:\n    permissions: write-all\n    name: Create Release\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v2\n      - name: Create Release\n        id: create_release\n        uses: actions/create-release@v1\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          tag_name: ${{ github.ref }}\n          release_name: GFPGAN ${{ github.ref }} Release Note\n          body: |\n            🚀 See you again 😸\n            🚀Have a nice day 😸 and happy everyday 😃\n            🚀 Long time no see ☄️\n\n            ✨ **Highlights**\n            ✅ [Features] Support ...\n\n            🐛 **Bug Fixes**\n\n            🌴 **Improvements**\n\n            📢📢📢\n\n            <p align=\"center\">\n               <img src=\"https://raw.githubusercontent.com/TencentARC/GFPGAN/master/assets/gfpgan_logo.png\" height=150>\n            </p>\n          draft: true\n          prerelease: false\n"
  },
  {
    "path": ".gitignore",
    "content": "# ignored folders\ndatasets/*\nexperiments/*\nresults/*\ntb_logger/*\nwandb/*\ntmp/*\n\nversion.py\n\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "repos:\n  # flake8\n  - repo: https://github.com/PyCQA/flake8\n    rev: 3.8.3\n    hooks:\n      - id: flake8\n        args: [\"--config=setup.cfg\", \"--ignore=W504, W503\"]\n\n  # modify known_third_party\n  - repo: https://github.com/asottile/seed-isort-config\n    rev: v2.2.0\n    hooks:\n      - id: seed-isort-config\n\n  # isort\n  - repo: https://github.com/timothycrosley/isort\n    rev: 5.2.2\n    hooks:\n      - id: isort\n\n  # yapf\n  - repo: https://github.com/pre-commit/mirrors-yapf\n    rev: v0.30.0\n    hooks:\n      - id: yapf\n\n  # codespell\n  - repo: https://github.com/codespell-project/codespell\n    rev: v2.1.0\n    hooks:\n      - id: codespell\n\n  # pre-commit-hooks\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v3.2.0\n    hooks:\n      - id: trailing-whitespace  # Trim trailing whitespace\n      - id: check-yaml  # Attempt to load all yaml files to verify syntax\n      - id: check-merge-conflict  # Check for files that contain merge conflict strings\n      - id: double-quote-string-fixer  # Replace double quoted strings with single quoted strings\n      - id: end-of-file-fixer  # Make sure files end in a newline and only a newline\n      - id: requirements-txt-fixer  # Sort entries in requirements.txt and remove incorrect entry for pkg-resources==0.0.0\n      - id: fix-encoding-pragma  # Remove the coding pragma: # -*- coding: utf-8 -*-\n        args: [\"--remove\"]\n      - id: mixed-line-ending  # Replace or check mixed line ending\n        args: [\"--fix=lf\"]\n"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n    \"files.trimTrailingWhitespace\": true,\n    \"editor.wordWrap\": \"on\",\n    \"editor.rulers\": [\n        80,\n        120\n    ],\n    \"editor.renderWhitespace\": \"all\",\n    \"editor.renderControlCharacters\": true,\n    \"python.formatting.provider\": \"yapf\",\n    \"python.formatting.yapfArgs\": [\n        \"--style\",\n        \"{BASED_ON_STYLE = pep8, BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF = true, SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN = true, COLUMN_LIMIT = 120}\"\n    ],\n    \"python.linting.flake8Enabled\": true,\n    \"python.linting.flake8Args\": [\n        \"max-line-length=120\"\n    ],\n}\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, religion, or sexual identity\nand orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the\n  overall community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or\n  advances of any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email\n  address, without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Enforcement Responsibilities\n\nCommunity leaders are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nCommunity leaders have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported to the community leaders responsible for enforcement at\nxintao.wang@outlook.com or xintaowang@tencent.com.\nAll complaints will be reviewed and investigated promptly and fairly.\n\nAll community leaders are obligated to respect the privacy and security of the\nreporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining\nthe consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed\nunprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from community leaders, providing\nclarity around the nature of the violation and an explanation of why the\nbehavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series\nof actions.\n\n**Consequence**: A warning with consequences for continued behavior. No\ninteraction with the people involved, including unsolicited interaction with\nthose enforcing the Code of Conduct, for a specified period of time. This\nincludes avoiding interactions in community spaces as well as external channels\nlike social media. Violating these terms may lead to a temporary or\npermanent ban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including\nsustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public\ncommunication with the community for a specified period of time. No public or\nprivate interaction with the people involved, including unsolicited interaction\nwith those enforcing the Code of Conduct, is allowed during this period.\nViolating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community\nstandards, including sustained inappropriate behavior,  harassment of an\nindividual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within\nthe community.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.0, available at\nhttps://www.contributor-covenant.org/version/2/0/code_of_conduct.html.\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct\nenforcement ladder](https://github.com/mozilla/diversity).\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see the FAQ at\nhttps://www.contributor-covenant.org/faq. Translations are available at\nhttps://www.contributor-covenant.org/translations.\n"
  },
  {
    "path": "Comparisons.md",
    "content": "# Comparisons\n\n## Comparisons among different model versions\n\nNote that V1.3 is not always better than V1.2. You may need to try different models based on your purpose and inputs.\n\n| Version | Strengths  | Weaknesses |\n| :---: | :---:        |     :---:      |\n|V1.3 |  ✓ natural outputs<br> ✓better results on very low-quality inputs <br> ✓ work on relatively high-quality inputs <br>✓ can have repeated (twice) restorations | ✗ not very sharp <br> ✗ have a slight change on identity |\n|V1.2 |  ✓ sharper output <br> ✓ with beauty makeup | ✗ some outputs are unnatural|\n\nFor the following images, you may need to **zoom in** for comparing details, or **click the image** to see in the full size.\n\n| Input | V1  | V1.2 | V1.3\n| :---: | :---:        |     :---:      |  :---:      |\n|![019_Anne_Hathaway_01_00](https://user-images.githubusercontent.com/17445847/153762146-96b25999-4ddd-42a5-a3fe-bb90565f4c4f.png)|  ![](https://user-images.githubusercontent.com/17445847/153762256-ef41e749-5a27-495c-8a9c-d8403be55869.png)  | ![](https://user-images.githubusercontent.com/17445847/153762297-d41582fc-6253-4e7e-a1ce-4dc237ae3bf3.png)   | ![](https://user-images.githubusercontent.com/17445847/153762215-e0535e94-b5ba-426e-97b5-35c00873604d.png)  |\n| ![106_Harry_Styles_00_00](https://user-images.githubusercontent.com/17445847/153789040-632c0eda-c15a-43e9-a63c-9ead64f92d4a.png) | ![](https://user-images.githubusercontent.com/17445847/153789172-93cd4980-5318-4633-a07e-1c8f8064ff89.png) | ![](https://user-images.githubusercontent.com/17445847/153789185-f7b268a7-d1db-47b0-ae4a-335e5d657a18.png) | ![](https://user-images.githubusercontent.com/17445847/153789198-7c7f3bca-0ef0-4494-92f0-20aa6f7d7464.png)|\n| ![076_Paris_Hilton_00_00](https://user-images.githubusercontent.com/17445847/153789607-86387770-9db8-441f-b08a-c9679b121b85.png) | ![](https://user-images.githubusercontent.com/17445847/153789619-e56b438a-78a0-425d-8f44-ec4692a43dda.png) | ![](https://user-images.githubusercontent.com/17445847/153789633-5b28f778-3b7f-4e08-8a1d-740ca6e82d8a.png) | ![](https://user-images.githubusercontent.com/17445847/153789645-bc623f21-b32d-4fc3-bfe9-61203407a180.png)|\n| ![008_George_Clooney_00_00](https://user-images.githubusercontent.com/17445847/153790017-0c3ca94d-1c9d-4a0e-b539-ab12d4da98ff.png) | ![](https://user-images.githubusercontent.com/17445847/153790028-fb0d38ab-399d-4a30-8154-2dcd72ca90e8.png) | ![](https://user-images.githubusercontent.com/17445847/153790044-1ef68e34-6120-4439-a5d9-0b6cdbe9c3d0.png) | ![](https://user-images.githubusercontent.com/17445847/153790059-a8d3cece-8989-4e9a-9ffe-903e1690cfd6.png)|\n| ![057_Madonna_01_00](https://user-images.githubusercontent.com/17445847/153790624-2d0751d0-8fb4-4806-be9d-71b833c2c226.png) | ![](https://user-images.githubusercontent.com/17445847/153790639-7eb870e5-26b2-41dc-b139-b698bb40e6e6.png) | ![](https://user-images.githubusercontent.com/17445847/153790651-86899b7a-a1b6-4242-9e8a-77b462004998.png) | ![](https://user-images.githubusercontent.com/17445847/153790655-c8f6c25b-9b4e-4633-b16f-c43da86cff8f.png)|\n| ![044_Amy_Schumer_01_00](https://user-images.githubusercontent.com/17445847/153790811-3fb4fc46-5b4f-45fe-8fcb-a128de2bfa60.png) | ![](https://user-images.githubusercontent.com/17445847/153790817-d45aa4ff-bfc4-4163-b462-75eef9426fab.png) | ![](https://user-images.githubusercontent.com/17445847/153790824-5f93c3a0-fe5a-42f6-8b4b-5a5de8cd0ac3.png) | ![](https://user-images.githubusercontent.com/17445847/153790835-0edf9944-05c7-41c4-8581-4dc5ffc56c9d.png)|\n| ![012_Jackie_Chan_01_00](https://user-images.githubusercontent.com/17445847/153791176-737b016a-e94f-4898-8db7-43e7762141c9.png) | ![](https://user-images.githubusercontent.com/17445847/153791183-2f25a723-56bf-4cd5-aafe-a35513a6d1c5.png) | ![](https://user-images.githubusercontent.com/17445847/153791194-93416cf9-2b58-4e70-b806-27e14c58d4fd.png) | ![](https://user-images.githubusercontent.com/17445847/153791202-aa98659c-b702-4bce-9c47-a2fa5eccc5ae.png)|\n\n<!-- | ![]() | ![]() | ![]() | ![]()|  -->\n"
  },
  {
    "path": "FAQ.md",
    "content": "# FAQ\n\n1. **How to finetune the GFPGANCleanv1-NoCE-C2 (v1.2) model**\n\n**A:** 1) The GFPGANCleanv1-NoCE-C2 (v1.2) model uses the *clean* architecture, which is more friendly for deploying.\n2) This model is not directly trained. Instead, it is converted from another *bilinear* model.\n3) If you want to finetune the GFPGANCleanv1-NoCE-C2 (v1.2), you need to finetune its original *bilinear* model, and then do the conversion.\n"
  },
  {
    "path": "LICENSE",
    "content": "Tencent is pleased to support the open source community by making GFPGAN available.\n\nCopyright (C) 2021 THL A29 Limited, a Tencent company.  All rights reserved.\n\nGFPGAN is licensed under the Apache License Version 2.0 except for the third-party components listed below.\n\n\nTerms of the Apache License Version 2.0:\n---------------------------------------------\nApache License\n\nVersion 2.0, January 2004\n\nhttp://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n1. Definitions.\n\n“License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\n\n“Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\n\n“Legal Entity” shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, “control” means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.\n\n“You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.\n\n“Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\n\n“Object” form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.\n\n“Work” shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).\n\n“Derivative Works” shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.\n\n“Contribution” shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as “Not a Contribution.”\n\n“Contributor” shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:\n\nYou must give any other recipients of the Work or Derivative Works a copy of this License; and\n\nYou must cause any modified files to carry prominent notices stating that You changed the files; and\n\nYou must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and\n\nIf the Work includes a “NOTICE” text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.\n\nYou may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\n\n\nOther  dependencies and licenses:\n\n\nOpen Source Software licensed under the Apache 2.0 license and Other Licenses of the Third-Party Components therein:\n---------------------------------------------\n1. basicsr\nCopyright 2018-2020 BasicSR Authors\n\n\nThis BasicSR project is released under the Apache 2.0 license.\n\nA copy of Apache 2.0 is included in this file.\n\nStyleGAN2\nThe codes are modified from the repository stylegan2-pytorch. Many thanks to the author - Kim Seonghyeon 😊 for translating from the official TensorFlow codes to PyTorch ones. Here is the license of stylegan2-pytorch.\nThe official repository is https://github.com/NVlabs/stylegan2, and here is the NVIDIA license.\nDFDNet\nThe codes are largely modified from the repository DFDNet. Their license is Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.\n\nTerms of the Nvidia License:\n---------------------------------------------\n\n1. Definitions\n\n\"Licensor\" means any person or entity that distributes its Work.\n\n\"Software\" means the original work of authorship made available under\nthis License.\n\n\"Work\" means the Software and any additions to or derivative works of\nthe Software that are made available under this License.\n\n\"Nvidia Processors\" means any central processing unit (CPU), graphics\nprocessing unit (GPU), field-programmable gate array (FPGA),\napplication-specific integrated circuit (ASIC) or any combination\nthereof designed, made, sold, or provided by Nvidia or its affiliates.\n\nThe terms \"reproduce,\" \"reproduction,\" \"derivative works,\" and\n\"distribution\" have the meaning as provided under U.S. copyright law;\nprovided, however, that for the purposes of this License, derivative\nworks shall not include works that remain separable from, or merely\nlink (or bind by name) to the interfaces of, the Work.\n\nWorks, including the Software, are \"made available\" under this License\nby including in or with the Work either (a) a copyright notice\nreferencing the applicability of this License to the Work, or (b) a\ncopy of this License.\n\n2. License Grants\n\n    2.1 Copyright Grant. Subject to the terms and conditions of this\n    License, each Licensor grants to you a perpetual, worldwide,\n    non-exclusive, royalty-free, copyright license to reproduce,\n    prepare derivative works of, publicly display, publicly perform,\n    sublicense and distribute its Work and any resulting derivative\n    works in any form.\n\n3. Limitations\n\n    3.1 Redistribution. You may reproduce or distribute the Work only\n    if (a) you do so under this License, (b) you include a complete\n    copy of this License with your distribution, and (c) you retain\n    without modification any copyright, patent, trademark, or\n    attribution notices that are present in the Work.\n\n    3.2 Derivative Works. You may specify that additional or different\n    terms apply to the use, reproduction, and distribution of your\n    derivative works of the Work (\"Your Terms\") only if (a) Your Terms\n    provide that the use limitation in Section 3.3 applies to your\n    derivative works, and (b) you identify the specific derivative\n    works that are subject to Your Terms. Notwithstanding Your Terms,\n    this License (including the redistribution requirements in Section\n    3.1) will continue to apply to the Work itself.\n\n    3.3 Use Limitation. The Work and any derivative works thereof only\n    may be used or intended for use non-commercially. The Work or\n    derivative works thereof may be used or intended for use by Nvidia\n    or its affiliates commercially or non-commercially. As used herein,\n    \"non-commercially\" means for research or evaluation purposes only.\n\n    3.4 Patent Claims. If you bring or threaten to bring a patent claim\n    against any Licensor (including any claim, cross-claim or\n    counterclaim in a lawsuit) to enforce any patents that you allege\n    are infringed by any Work, then your rights under this License from\n    such Licensor (including the grants in Sections 2.1 and 2.2) will\n    terminate immediately.\n\n    3.5 Trademarks. This License does not grant any rights to use any\n    Licensor's or its affiliates' names, logos, or trademarks, except\n    as necessary to reproduce the notices described in this License.\n\n    3.6 Termination. If you violate any term of this License, then your\n    rights under this License (including the grants in Sections 2.1 and\n    2.2) will terminate immediately.\n\n4. Disclaimer of Warranty.\n\nTHE WORK IS PROVIDED \"AS IS\" WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR\nNON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER\nTHIS LICENSE.\n\n5. Limitation of Liability.\n\nEXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL\nTHEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE\nSHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT,\nINDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF\nOR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK\n(INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION,\nLOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER\nCOMMERCIAL DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF\nTHE POSSIBILITY OF SUCH DAMAGES.\n\nMIT License\n\nCopyright (c) 2019 Kim Seonghyeon\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n\n\nOpen Source Software licensed under the BSD 3-Clause license:\n---------------------------------------------\n1. torchvision\nCopyright (c) Soumith Chintala 2016,\nAll rights reserved.\n\n2. torch\nCopyright (c) 2016-     Facebook, Inc            (Adam Paszke)\nCopyright (c) 2014-     Facebook, Inc            (Soumith Chintala)\nCopyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)\nCopyright (c) 2012-2014 Deepmind Technologies    (Koray Kavukcuoglu)\nCopyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)\nCopyright (c) 2011-2013 NYU                      (Clement Farabet)\nCopyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)\nCopyright (c) 2006      Idiap Research Institute (Samy Bengio)\nCopyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)\n\n\nTerms of the BSD 3-Clause License:\n---------------------------------------------\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\nOpen Source Software licensed under the BSD 3-Clause License and Other Licenses of the Third-Party Components therein:\n---------------------------------------------\n1. numpy\nCopyright (c) 2005-2020, NumPy Developers.\nAll rights reserved.\n\nA copy of BSD 3-Clause License is included in this file.\n\nThe NumPy repository and source distributions bundle several libraries that are\ncompatibly licensed.  We list these here.\n\nName: Numpydoc\nFiles: doc/sphinxext/numpydoc/*\nLicense: BSD-2-Clause\n  For details, see doc/sphinxext/LICENSE.txt\n\nName: scipy-sphinx-theme\nFiles: doc/scipy-sphinx-theme/*\nLicense: BSD-3-Clause AND PSF-2.0 AND Apache-2.0\n  For details, see doc/scipy-sphinx-theme/LICENSE.txt\n\nName: lapack-lite\nFiles: numpy/linalg/lapack_lite/*\nLicense: BSD-3-Clause\n  For details, see numpy/linalg/lapack_lite/LICENSE.txt\n\nName: tempita\nFiles: tools/npy_tempita/*\nLicense: MIT\n  For details, see tools/npy_tempita/license.txt\n\nName: dragon4\nFiles: numpy/core/src/multiarray/dragon4.c\nLicense: MIT\n  For license text, see numpy/core/src/multiarray/dragon4.c\n\n\n\nOpen Source Software licensed under the MIT license:\n---------------------------------------------\n1. facexlib\nCopyright (c) 2020 Xintao Wang\n\n2. opencv-python\nCopyright (c) Olli-Pekka Heinisuo\nPlease note that only files in cv2 package are used.\n\n\nTerms of the MIT License:\n---------------------------------------------\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\nOpen Source Software licensed under the MIT license and Other Licenses of the Third-Party Components therein:\n---------------------------------------------\n1. tqdm\nCopyright (c) 2013 noamraph\n\n`tqdm` is a product of collaborative work.\nUnless otherwise stated, all authors (see commit logs) retain copyright\nfor their respective work, and release the work under the MIT licence\n(text below).\n\nExceptions or notable authors are listed below\nin reverse chronological order:\n\n* files: *\n  MPLv2.0 2015-2020 (c) Casper da Costa-Luis\n  [casperdcl](https://github.com/casperdcl).\n* files: tqdm/_tqdm.py\n  MIT 2016 (c) [PR #96] on behalf of Google Inc.\n* files: tqdm/_tqdm.py setup.py README.rst MANIFEST.in .gitignore\n  MIT 2013 (c) Noam Yorav-Raphael, original author.\n\n[PR #96]: https://github.com/tqdm/tqdm/pull/96\n\n\nMozilla Public Licence (MPL) v. 2.0 - Exhibit A\n-----------------------------------------------\n\nThis Source Code Form is subject to the terms of the\nMozilla Public License, v. 2.0.\nIf a copy of the MPL was not distributed with this file,\nYou can obtain one at https://mozilla.org/MPL/2.0/.\n\n\nMIT License (MIT)\n-----------------\n\nCopyright (c) 2013 noamraph\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include assets/*\ninclude inputs/*\ninclude scripts/*.py\ninclude inference_gfpgan.py\ninclude VERSION\ninclude LICENSE\ninclude requirements.txt\ninclude gfpgan/weights/README.md\n"
  },
  {
    "path": "PaperModel.md",
    "content": "# Installation\n\nWe now provide a *clean* version of GFPGAN, which does not require customized CUDA extensions. See [here](README.md#installation) for this easier installation.<br>\nIf you want want to use the original model in our paper, please follow the instructions below.\n\n1. Clone repo\n\n    ```bash\n    git clone https://github.com/xinntao/GFPGAN.git\n    cd GFPGAN\n    ```\n\n1. Install dependent packages\n\n    As StyleGAN2 uses customized PyTorch C++ extensions, you need to **compile them during installation** or **load them just-in-time(JIT)**.\n    You can refer to [BasicSR-INSTALL.md](https://github.com/xinntao/BasicSR/blob/master/INSTALL.md) for more details.\n\n    **Option 1: Load extensions just-in-time(JIT)** (For those just want to do simple inferences, may have less issues)\n\n    ```bash\n    # Install basicsr - https://github.com/xinntao/BasicSR\n    # We use BasicSR for both training and inference\n    pip install basicsr\n\n    # Install facexlib - https://github.com/xinntao/facexlib\n    # We use face detection and face restoration helper in the facexlib package\n    pip install facexlib\n\n    pip install -r requirements.txt\n    python setup.py develop\n\n    # remember to set BASICSR_JIT=True before your running commands\n    ```\n\n    **Option 2: Compile extensions during installation** (For those need to train/inference for many times)\n\n    ```bash\n    # Install basicsr - https://github.com/xinntao/BasicSR\n    # We use BasicSR for both training and inference\n    # Set BASICSR_EXT=True to compile the cuda extensions in the BasicSR - It may take several minutes to compile, please be patient\n    # Add -vvv for detailed log prints\n    BASICSR_EXT=True pip install basicsr -vvv\n\n    # Install facexlib - https://github.com/xinntao/facexlib\n    # We use face detection and face restoration helper in the facexlib package\n    pip install facexlib\n\n    pip install -r requirements.txt\n    python setup.py develop\n    ```\n\n## :zap: Quick Inference\n\nDownload pre-trained models: [GFPGANv1.pth](https://github.com/TencentARC/GFPGAN/releases/download/v0.1.0/GFPGANv1.pth)\n\n```bash\nwget https://github.com/TencentARC/GFPGAN/releases/download/v0.1.0/GFPGANv1.pth -P experiments/pretrained_models\n```\n\n- Option 1: Load extensions just-in-time(JIT)\n\n    ```bash\n    BASICSR_JIT=True python inference_gfpgan.py --input inputs/whole_imgs --output results --version 1\n\n    # for aligned images\n    BASICSR_JIT=True python inference_gfpgan.py --input inputs/whole_imgs --output results --version 1 --aligned\n    ```\n\n- Option 2: Have successfully compiled extensions during installation\n\n    ```bash\n    python inference_gfpgan.py --input inputs/whole_imgs --output results --version 1\n\n    # for aligned images\n    python inference_gfpgan.py --input inputs/whole_imgs --output results --version 1 --aligned\n    ```\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n  <img src=\"assets/gfpgan_logo.png\" height=130>\n</p>\n\n## <div align=\"center\"><b><a href=\"README.md\">English</a> | <a href=\"README_CN.md\">简体中文</a></b></div>\n\n<div align=\"center\">\n<!-- <a href=\"https://twitter.com/_Xintao_\" style=\"text-decoration:none;\">\n    <img src=\"https://user-images.githubusercontent.com/17445847/187162058-c764ced6-952f-404b-ac85-ba95cce18e7b.png\" width=\"4%\" alt=\"\" />\n</a> -->\n\n[![download](https://img.shields.io/github/downloads/TencentARC/GFPGAN/total.svg)](https://github.com/TencentARC/GFPGAN/releases)\n[![PyPI](https://img.shields.io/pypi/v/gfpgan)](https://pypi.org/project/gfpgan/)\n[![Open issue](https://img.shields.io/github/issues/TencentARC/GFPGAN)](https://github.com/TencentARC/GFPGAN/issues)\n[![Closed issue](https://img.shields.io/github/issues-closed/TencentARC/GFPGAN)](https://github.com/TencentARC/GFPGAN/issues)\n[![LICENSE](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/TencentARC/GFPGAN/blob/master/LICENSE)\n[![python lint](https://github.com/TencentARC/GFPGAN/actions/workflows/pylint.yml/badge.svg)](https://github.com/TencentARC/GFPGAN/blob/master/.github/workflows/pylint.yml)\n[![Publish-pip](https://github.com/TencentARC/GFPGAN/actions/workflows/publish-pip.yml/badge.svg)](https://github.com/TencentARC/GFPGAN/blob/master/.github/workflows/publish-pip.yml)\n</div>\n\n1. :boom: **Updated** online demo: [![Replicate](https://img.shields.io/static/v1?label=Demo&message=Replicate&color=blue)](https://replicate.com/tencentarc/gfpgan). Here is the [backup](https://replicate.com/xinntao/gfpgan).\n1. :boom: **Updated** online demo: [![Huggingface Gradio](https://img.shields.io/static/v1?label=Demo&message=Huggingface%20Gradio&color=orange)](https://huggingface.co/spaces/Xintao/GFPGAN)\n1. [Colab Demo](https://colab.research.google.com/drive/1sVsoBd9AjckIXThgtZhGrHRfFI6UUYOo) for GFPGAN <a href=\"https://colab.research.google.com/drive/1sVsoBd9AjckIXThgtZhGrHRfFI6UUYOo\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"google colab logo\"></a>; (Another [Colab Demo](https://colab.research.google.com/drive/1Oa1WwKB4M4l1GmR7CtswDVgOCOeSLChA?usp=sharing) for the original paper model)\n\n<!-- 3. Online demo: [Replicate.ai](https://replicate.com/xinntao/gfpgan) (may need to sign in, return the whole image)\n4. Online demo: [Baseten.co](https://app.baseten.co/applications/Q04Lz0d/operator_views/8qZG6Bg) (backed by GPU, returns the whole image)\n5. We provide a *clean* version of GFPGAN, which can run without CUDA extensions. So that it can run in **Windows** or on **CPU mode**. -->\n\n> :rocket: **Thanks for your interest in our work. You may also want to check our new updates on the *tiny models* for *anime images and videos* in [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN/blob/master/docs/anime_video_model.md)** :blush:\n\nGFPGAN aims at developing a **Practical Algorithm for Real-world Face Restoration**.<br>\nIt leverages rich and diverse priors encapsulated in a pretrained face GAN (*e.g.*, StyleGAN2) for blind face restoration.\n\n:question: Frequently Asked Questions can be found in [FAQ.md](FAQ.md).\n\n:triangular_flag_on_post: **Updates**\n\n- :white_check_mark: Add [RestoreFormer](https://github.com/wzhouxiff/RestoreFormer) inference codes.\n- :white_check_mark: Add [V1.4 model](https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth), which produces slightly more details and better identity than V1.3.\n- :white_check_mark: Add **[V1.3 model](https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth)**, which produces **more natural** restoration results, and better results on *very low-quality* / *high-quality* inputs. See more in [Model zoo](#european_castle-model-zoo), [Comparisons.md](Comparisons.md)\n- :white_check_mark: Integrated to [Huggingface Spaces](https://huggingface.co/spaces) with [Gradio](https://github.com/gradio-app/gradio). See [Gradio Web Demo](https://huggingface.co/spaces/akhaliq/GFPGAN).\n- :white_check_mark: Support enhancing non-face regions (background) with [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN).\n- :white_check_mark: We provide a *clean* version of GFPGAN, which does not require CUDA extensions.\n- :white_check_mark: We provide an updated model without colorizing faces.\n\n---\n\nIf GFPGAN is helpful in your photos/projects, please help to :star: this repo or recommend it to your friends. Thanks:blush:\nOther recommended projects:<br>\n:arrow_forward: [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN): A practical algorithm for general image restoration<br>\n:arrow_forward: [BasicSR](https://github.com/xinntao/BasicSR): An open-source image and video restoration toolbox<br>\n:arrow_forward: [facexlib](https://github.com/xinntao/facexlib): A collection that provides useful face-relation functions<br>\n:arrow_forward: [HandyView](https://github.com/xinntao/HandyView): A PyQt5-based image viewer that is handy for view and comparison<br>\n\n---\n\n### :book: GFP-GAN: Towards Real-World Blind Face Restoration with Generative Facial Prior\n\n> [[Paper](https://arxiv.org/abs/2101.04061)] &emsp; [[Project Page](https://xinntao.github.io/projects/gfpgan)] &emsp; [Demo] <br>\n> [Xintao Wang](https://xinntao.github.io/), [Yu Li](https://yu-li.github.io/), [Honglun Zhang](https://scholar.google.com/citations?hl=en&user=KjQLROoAAAAJ), [Ying Shan](https://scholar.google.com/citations?user=4oXBp9UAAAAJ&hl=en) <br>\n> Applied Research Center (ARC), Tencent PCG\n\n<p align=\"center\">\n  <img src=\"https://xinntao.github.io/projects/GFPGAN_src/gfpgan_teaser.jpg\">\n</p>\n\n---\n\n## :wrench: Dependencies and Installation\n\n- Python >= 3.7 (Recommend to use [Anaconda](https://www.anaconda.com/download/#linux) or [Miniconda](https://docs.conda.io/en/latest/miniconda.html))\n- [PyTorch >= 1.7](https://pytorch.org/)\n- Option: NVIDIA GPU + [CUDA](https://developer.nvidia.com/cuda-downloads)\n- Option: Linux\n\n### Installation\n\nWe now provide a *clean* version of GFPGAN, which does not require customized CUDA extensions. <br>\nIf you want to use the original model in our paper, please see [PaperModel.md](PaperModel.md) for installation.\n\n1. Clone repo\n\n    ```bash\n    git clone https://github.com/TencentARC/GFPGAN.git\n    cd GFPGAN\n    ```\n\n1. Install dependent packages\n\n    ```bash\n    # Install basicsr - https://github.com/xinntao/BasicSR\n    # We use BasicSR for both training and inference\n    pip install basicsr\n\n    # Install facexlib - https://github.com/xinntao/facexlib\n    # We use face detection and face restoration helper in the facexlib package\n    pip install facexlib\n\n    pip install -r requirements.txt\n    python setup.py develop\n\n    # If you want to enhance the background (non-face) regions with Real-ESRGAN,\n    # you also need to install the realesrgan package\n    pip install realesrgan\n    ```\n\n## :zap: Quick Inference\n\nWe take the v1.3 version for an example. More models can be found [here](#european_castle-model-zoo).\n\nDownload pre-trained models: [GFPGANv1.3.pth](https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth)\n\n```bash\nwget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth -P experiments/pretrained_models\n```\n\n**Inference!**\n\n```bash\npython inference_gfpgan.py -i inputs/whole_imgs -o results -v 1.3 -s 2\n```\n\n```console\nUsage: python inference_gfpgan.py -i inputs/whole_imgs -o results -v 1.3 -s 2 [options]...\n\n  -h                   show this help\n  -i input             Input image or folder. Default: inputs/whole_imgs\n  -o output            Output folder. Default: results\n  -v version           GFPGAN model version. Option: 1 | 1.2 | 1.3. Default: 1.3\n  -s upscale           The final upsampling scale of the image. Default: 2\n  -bg_upsampler        background upsampler. Default: realesrgan\n  -bg_tile             Tile size for background sampler, 0 for no tile during testing. Default: 400\n  -suffix              Suffix of the restored faces\n  -only_center_face    Only restore the center face\n  -aligned             Input are aligned faces\n  -ext                 Image extension. Options: auto | jpg | png, auto means using the same extension as inputs. Default: auto\n```\n\nIf you want to use the original model in our paper, please see [PaperModel.md](PaperModel.md) for installation and inference.\n\n## :european_castle: Model Zoo\n\n| Version | Model Name  | Description |\n| :---: | :---:        |     :---:      |\n| V1.3 | [GFPGANv1.3.pth](https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth) | Based on V1.2; **more natural** restoration results; better results on very low-quality / high-quality inputs. |\n| V1.2 | [GFPGANCleanv1-NoCE-C2.pth](https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth) | No colorization; no CUDA extensions are required. Trained with more data with pre-processing. |\n| V1 | [GFPGANv1.pth](https://github.com/TencentARC/GFPGAN/releases/download/v0.1.0/GFPGANv1.pth) | The paper model, with colorization. |\n\nThe comparisons are in [Comparisons.md](Comparisons.md).\n\nNote that V1.3 is not always better than V1.2. You may need to select different models based on your purpose and inputs.\n\n| Version | Strengths  | Weaknesses |\n| :---: | :---:        |     :---:      |\n|V1.3 |  ✓ natural outputs<br> ✓better results on very low-quality inputs <br> ✓ work on relatively high-quality inputs <br>✓ can have repeated (twice) restorations | ✗ not very sharp <br> ✗ have a slight change on identity |\n|V1.2 |  ✓ sharper output <br> ✓ with beauty makeup | ✗ some outputs are unnatural |\n\nYou can find **more models (such as the discriminators)** here: [[Google Drive](https://drive.google.com/drive/folders/17rLiFzcUMoQuhLnptDsKolegHWwJOnHu?usp=sharing)], OR [[Tencent Cloud 腾讯微云](https://share.weiyun.com/ShYoCCoc)]\n\n## :computer: Training\n\nWe provide the training codes for GFPGAN (used in our paper). <br>\nYou could improve it according to your own needs.\n\n**Tips**\n\n1. More high quality faces can improve the restoration quality.\n2. You may need to perform some pre-processing, such as beauty makeup.\n\n**Procedures**\n\n(You can try a simple version ( `options/train_gfpgan_v1_simple.yml`) that does not require face component landmarks.)\n\n1. Dataset preparation: [FFHQ](https://github.com/NVlabs/ffhq-dataset)\n\n1. Download pre-trained models and other data. Put them in the `experiments/pretrained_models` folder.\n    1. [Pre-trained StyleGAN2 model: StyleGAN2_512_Cmul1_FFHQ_B12G4_scratch_800k.pth](https://github.com/TencentARC/GFPGAN/releases/download/v0.1.0/StyleGAN2_512_Cmul1_FFHQ_B12G4_scratch_800k.pth)\n    1. [Component locations of FFHQ: FFHQ_eye_mouth_landmarks_512.pth](https://github.com/TencentARC/GFPGAN/releases/download/v0.1.0/FFHQ_eye_mouth_landmarks_512.pth)\n    1. [A simple ArcFace model: arcface_resnet18.pth](https://github.com/TencentARC/GFPGAN/releases/download/v0.1.0/arcface_resnet18.pth)\n\n1. Modify the configuration file `options/train_gfpgan_v1.yml` accordingly.\n\n1. Training\n\n> python -m torch.distributed.launch --nproc_per_node=4 --master_port=22021 gfpgan/train.py -opt options/train_gfpgan_v1.yml --launcher pytorch\n\n## :scroll: License and Acknowledgement\n\nGFPGAN is released under Apache License Version 2.0.\n\n## BibTeX\n\n    @InProceedings{wang2021gfpgan,\n        author = {Xintao Wang and Yu Li and Honglun Zhang and Ying Shan},\n        title = {Towards Real-World Blind Face Restoration with Generative Facial Prior},\n        booktitle={The IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},\n        year = {2021}\n    }\n\n## :e-mail: Contact\n\nIf you have any question, please email `xintao.wang@outlook.com` or `xintaowang@tencent.com`.\n"
  },
  {
    "path": "README_CN.md",
    "content": "<p align=\"center\">\n  <img src=\"assets/gfpgan_logo.png\" height=130>\n</p>\n\n## <div align=\"center\"><b><a href=\"README.md\">English</a> | <a href=\"README_CN.md\">简体中文</a></b></div>\n\n还未完工，欢迎贡献！\n"
  },
  {
    "path": "VERSION",
    "content": "1.3.8\n"
  },
  {
    "path": "cog.yaml",
    "content": "# This file is used for constructing replicate env\nimage: \"r8.im/tencentarc/gfpgan\"\n\nbuild:\n  gpu: true\n  python_version: \"3.8\"\n  system_packages:\n    - \"libgl1-mesa-glx\"\n    - \"libglib2.0-0\"\n  python_packages:\n    - \"torch==1.7.1\"\n    - \"torchvision==0.8.2\"\n    - \"numpy==1.21.1\"\n    - \"lmdb==1.2.1\"\n    - \"opencv-python==4.5.3.56\"\n    - \"PyYAML==5.4.1\"\n    - \"tqdm==4.62.2\"\n    - \"yapf==0.31.0\"\n    - \"basicsr==1.4.2\"\n    - \"facexlib==0.2.5\"\n\npredict: \"cog_predict.py:Predictor\"\n"
  },
  {
    "path": "cog_predict.py",
    "content": "# flake8: noqa\n# This file is used for deploying replicate models\n# running: cog predict -i img=@inputs/whole_imgs/10045.png -i version='v1.4' -i scale=2\n# push: cog push r8.im/tencentarc/gfpgan\n# push (backup): cog push r8.im/xinntao/gfpgan\n\nimport os\n\nos.system('python setup.py develop')\nos.system('pip install realesrgan')\n\nimport cv2\nimport shutil\nimport tempfile\nimport torch\nfrom basicsr.archs.srvgg_arch import SRVGGNetCompact\n\nfrom gfpgan import GFPGANer\n\ntry:\n    from cog import BasePredictor, Input, Path\n    from realesrgan.utils import RealESRGANer\nexcept Exception:\n    print('please install cog and realesrgan package')\n\n\nclass Predictor(BasePredictor):\n\n    def setup(self):\n        os.makedirs('output', exist_ok=True)\n        # download weights\n        if not os.path.exists('gfpgan/weights/realesr-general-x4v3.pth'):\n            os.system(\n                'wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth -P ./gfpgan/weights'\n            )\n        if not os.path.exists('gfpgan/weights/GFPGANv1.2.pth'):\n            os.system(\n                'wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.2.pth -P ./gfpgan/weights')\n        if not os.path.exists('gfpgan/weights/GFPGANv1.3.pth'):\n            os.system(\n                'wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth -P ./gfpgan/weights')\n        if not os.path.exists('gfpgan/weights/GFPGANv1.4.pth'):\n            os.system(\n                'wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P ./gfpgan/weights')\n        if not os.path.exists('gfpgan/weights/RestoreFormer.pth'):\n            os.system(\n                'wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth -P ./gfpgan/weights'\n            )\n\n        # background enhancer with RealESRGAN\n        model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')\n        model_path = 'gfpgan/weights/realesr-general-x4v3.pth'\n        half = True if torch.cuda.is_available() else False\n        self.upsampler = RealESRGANer(\n            scale=4, model_path=model_path, model=model, tile=0, tile_pad=10, pre_pad=0, half=half)\n\n        # Use GFPGAN for face enhancement\n        self.face_enhancer = GFPGANer(\n            model_path='gfpgan/weights/GFPGANv1.4.pth',\n            upscale=2,\n            arch='clean',\n            channel_multiplier=2,\n            bg_upsampler=self.upsampler)\n        self.current_version = 'v1.4'\n\n    def predict(\n            self,\n            img: Path = Input(description='Input'),\n            version: str = Input(\n                description='GFPGAN version. v1.3: better quality. v1.4: more details and better identity.',\n                choices=['v1.2', 'v1.3', 'v1.4', 'RestoreFormer'],\n                default='v1.4'),\n            scale: float = Input(description='Rescaling factor', default=2),\n    ) -> Path:\n        weight = 0.5\n        print(img, version, scale, weight)\n        try:\n            extension = os.path.splitext(os.path.basename(str(img)))[1]\n            img = cv2.imread(str(img), cv2.IMREAD_UNCHANGED)\n            if len(img.shape) == 3 and img.shape[2] == 4:\n                img_mode = 'RGBA'\n            elif len(img.shape) == 2:\n                img_mode = None\n                img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n            else:\n                img_mode = None\n\n            h, w = img.shape[0:2]\n            if h < 300:\n                img = cv2.resize(img, (w * 2, h * 2), interpolation=cv2.INTER_LANCZOS4)\n\n            if self.current_version != version:\n                if version == 'v1.2':\n                    self.face_enhancer = GFPGANer(\n                        model_path='gfpgan/weights/GFPGANv1.2.pth',\n                        upscale=2,\n                        arch='clean',\n                        channel_multiplier=2,\n                        bg_upsampler=self.upsampler)\n                    self.current_version = 'v1.2'\n                elif version == 'v1.3':\n                    self.face_enhancer = GFPGANer(\n                        model_path='gfpgan/weights/GFPGANv1.3.pth',\n                        upscale=2,\n                        arch='clean',\n                        channel_multiplier=2,\n                        bg_upsampler=self.upsampler)\n                    self.current_version = 'v1.3'\n                elif version == 'v1.4':\n                    self.face_enhancer = GFPGANer(\n                        model_path='gfpgan/weights/GFPGANv1.4.pth',\n                        upscale=2,\n                        arch='clean',\n                        channel_multiplier=2,\n                        bg_upsampler=self.upsampler)\n                    self.current_version = 'v1.4'\n                elif version == 'RestoreFormer':\n                    self.face_enhancer = GFPGANer(\n                        model_path='gfpgan/weights/RestoreFormer.pth',\n                        upscale=2,\n                        arch='RestoreFormer',\n                        channel_multiplier=2,\n                        bg_upsampler=self.upsampler)\n\n            try:\n                _, _, output = self.face_enhancer.enhance(\n                    img, has_aligned=False, only_center_face=False, paste_back=True, weight=weight)\n            except RuntimeError as error:\n                print('Error', error)\n\n            try:\n                if scale != 2:\n                    interpolation = cv2.INTER_AREA if scale < 2 else cv2.INTER_LANCZOS4\n                    h, w = img.shape[0:2]\n                    output = cv2.resize(output, (int(w * scale / 2), int(h * scale / 2)), interpolation=interpolation)\n            except Exception as error:\n                print('wrong scale input.', error)\n\n            if img_mode == 'RGBA':  # RGBA images should be saved in png format\n                extension = 'png'\n            # save_path = f'output/out.{extension}'\n            # cv2.imwrite(save_path, output)\n            out_path = Path(tempfile.mkdtemp()) / f'out.{extension}'\n            cv2.imwrite(str(out_path), output)\n        except Exception as error:\n            print('global exception: ', error)\n        finally:\n            clean_folder('output')\n        return out_path\n\n\ndef clean_folder(folder):\n    for filename in os.listdir(folder):\n        file_path = os.path.join(folder, filename)\n        try:\n            if os.path.isfile(file_path) or os.path.islink(file_path):\n                os.unlink(file_path)\n            elif os.path.isdir(file_path):\n                shutil.rmtree(file_path)\n        except Exception as e:\n            print(f'Failed to delete {file_path}. Reason: {e}')\n"
  },
  {
    "path": "gfpgan/__init__.py",
    "content": "# flake8: noqa\nfrom .archs import *\nfrom .data import *\nfrom .models import *\nfrom .utils import *\n\n# from .version import *\n"
  },
  {
    "path": "gfpgan/archs/__init__.py",
    "content": "import importlib\nfrom basicsr.utils import scandir\nfrom os import path as osp\n\n# automatically scan and import arch modules for registry\n# scan all the files that end with '_arch.py' under the archs folder\narch_folder = osp.dirname(osp.abspath(__file__))\narch_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(arch_folder) if v.endswith('_arch.py')]\n# import all the arch modules\n_arch_modules = [importlib.import_module(f'gfpgan.archs.{file_name}') for file_name in arch_filenames]\n"
  },
  {
    "path": "gfpgan/archs/arcface_arch.py",
    "content": "import torch.nn as nn\nfrom basicsr.utils.registry import ARCH_REGISTRY\n\n\ndef conv3x3(inplanes, outplanes, stride=1):\n    \"\"\"A simple wrapper for 3x3 convolution with padding.\n\n    Args:\n        inplanes (int): Channel number of inputs.\n        outplanes (int): Channel number of outputs.\n        stride (int): Stride in convolution. Default: 1.\n    \"\"\"\n    return nn.Conv2d(inplanes, outplanes, kernel_size=3, stride=stride, padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n    \"\"\"Basic residual block used in the ResNetArcFace architecture.\n\n    Args:\n        inplanes (int): Channel number of inputs.\n        planes (int): Channel number of outputs.\n        stride (int): Stride in convolution. Default: 1.\n        downsample (nn.Module): The downsample module. Default: None.\n    \"\"\"\n    expansion = 1  # output channel expansion ratio\n\n    def __init__(self, inplanes, planes, stride=1, downsample=None):\n        super(BasicBlock, self).__init__()\n        self.conv1 = conv3x3(inplanes, planes, stride)\n        self.bn1 = nn.BatchNorm2d(planes)\n        self.relu = nn.ReLU(inplace=True)\n        self.conv2 = conv3x3(planes, planes)\n        self.bn2 = nn.BatchNorm2d(planes)\n        self.downsample = downsample\n        self.stride = stride\n\n    def forward(self, x):\n        residual = x\n\n        out = self.conv1(x)\n        out = self.bn1(out)\n        out = self.relu(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n\n        if self.downsample is not None:\n            residual = self.downsample(x)\n\n        out += residual\n        out = self.relu(out)\n\n        return out\n\n\nclass IRBlock(nn.Module):\n    \"\"\"Improved residual block (IR Block) used in the ResNetArcFace architecture.\n\n    Args:\n        inplanes (int): Channel number of inputs.\n        planes (int): Channel number of outputs.\n        stride (int): Stride in convolution. Default: 1.\n        downsample (nn.Module): The downsample module. Default: None.\n        use_se (bool): Whether use the SEBlock (squeeze and excitation block). Default: True.\n    \"\"\"\n    expansion = 1  # output channel expansion ratio\n\n    def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True):\n        super(IRBlock, self).__init__()\n        self.bn0 = nn.BatchNorm2d(inplanes)\n        self.conv1 = conv3x3(inplanes, inplanes)\n        self.bn1 = nn.BatchNorm2d(inplanes)\n        self.prelu = nn.PReLU()\n        self.conv2 = conv3x3(inplanes, planes, stride)\n        self.bn2 = nn.BatchNorm2d(planes)\n        self.downsample = downsample\n        self.stride = stride\n        self.use_se = use_se\n        if self.use_se:\n            self.se = SEBlock(planes)\n\n    def forward(self, x):\n        residual = x\n        out = self.bn0(x)\n        out = self.conv1(out)\n        out = self.bn1(out)\n        out = self.prelu(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n        if self.use_se:\n            out = self.se(out)\n\n        if self.downsample is not None:\n            residual = self.downsample(x)\n\n        out += residual\n        out = self.prelu(out)\n\n        return out\n\n\nclass Bottleneck(nn.Module):\n    \"\"\"Bottleneck block used in the ResNetArcFace architecture.\n\n    Args:\n        inplanes (int): Channel number of inputs.\n        planes (int): Channel number of outputs.\n        stride (int): Stride in convolution. Default: 1.\n        downsample (nn.Module): The downsample module. Default: None.\n    \"\"\"\n    expansion = 4  # output channel expansion ratio\n\n    def __init__(self, inplanes, planes, stride=1, downsample=None):\n        super(Bottleneck, self).__init__()\n        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(planes)\n        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n        self.bn2 = nn.BatchNorm2d(planes)\n        self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)\n        self.bn3 = nn.BatchNorm2d(planes * self.expansion)\n        self.relu = nn.ReLU(inplace=True)\n        self.downsample = downsample\n        self.stride = stride\n\n    def forward(self, x):\n        residual = x\n\n        out = self.conv1(x)\n        out = self.bn1(out)\n        out = self.relu(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n        out = self.relu(out)\n\n        out = self.conv3(out)\n        out = self.bn3(out)\n\n        if self.downsample is not None:\n            residual = self.downsample(x)\n\n        out += residual\n        out = self.relu(out)\n\n        return out\n\n\nclass SEBlock(nn.Module):\n    \"\"\"The squeeze-and-excitation block (SEBlock) used in the IRBlock.\n\n    Args:\n        channel (int): Channel number of inputs.\n        reduction (int): Channel reduction ration. Default: 16.\n    \"\"\"\n\n    def __init__(self, channel, reduction=16):\n        super(SEBlock, self).__init__()\n        self.avg_pool = nn.AdaptiveAvgPool2d(1)  # pool to 1x1 without spatial information\n        self.fc = nn.Sequential(\n            nn.Linear(channel, channel // reduction), nn.PReLU(), nn.Linear(channel // reduction, channel),\n            nn.Sigmoid())\n\n    def forward(self, x):\n        b, c, _, _ = x.size()\n        y = self.avg_pool(x).view(b, c)\n        y = self.fc(y).view(b, c, 1, 1)\n        return x * y\n\n\n@ARCH_REGISTRY.register()\nclass ResNetArcFace(nn.Module):\n    \"\"\"ArcFace with ResNet architectures.\n\n    Ref: ArcFace: Additive Angular Margin Loss for Deep Face Recognition.\n\n    Args:\n        block (str): Block used in the ArcFace architecture.\n        layers (tuple(int)): Block numbers in each layer.\n        use_se (bool): Whether use the SEBlock (squeeze and excitation block). Default: True.\n    \"\"\"\n\n    def __init__(self, block, layers, use_se=True):\n        if block == 'IRBlock':\n            block = IRBlock\n        self.inplanes = 64\n        self.use_se = use_se\n        super(ResNetArcFace, self).__init__()\n\n        self.conv1 = nn.Conv2d(1, 64, kernel_size=3, padding=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(64)\n        self.prelu = nn.PReLU()\n        self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)\n        self.layer1 = self._make_layer(block, 64, layers[0])\n        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n        self.bn4 = nn.BatchNorm2d(512)\n        self.dropout = nn.Dropout()\n        self.fc5 = nn.Linear(512 * 8 * 8, 512)\n        self.bn5 = nn.BatchNorm1d(512)\n\n        # initialization\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                nn.init.xavier_normal_(m.weight)\n            elif isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d):\n                nn.init.constant_(m.weight, 1)\n                nn.init.constant_(m.bias, 0)\n            elif isinstance(m, nn.Linear):\n                nn.init.xavier_normal_(m.weight)\n                nn.init.constant_(m.bias, 0)\n\n    def _make_layer(self, block, planes, num_blocks, stride=1):\n        downsample = None\n        if stride != 1 or self.inplanes != planes * block.expansion:\n            downsample = nn.Sequential(\n                nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False),\n                nn.BatchNorm2d(planes * block.expansion),\n            )\n        layers = []\n        layers.append(block(self.inplanes, planes, stride, downsample, use_se=self.use_se))\n        self.inplanes = planes\n        for _ in range(1, num_blocks):\n            layers.append(block(self.inplanes, planes, use_se=self.use_se))\n\n        return nn.Sequential(*layers)\n\n    def forward(self, x):\n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.prelu(x)\n        x = self.maxpool(x)\n\n        x = self.layer1(x)\n        x = self.layer2(x)\n        x = self.layer3(x)\n        x = self.layer4(x)\n        x = self.bn4(x)\n        x = self.dropout(x)\n        x = x.view(x.size(0), -1)\n        x = self.fc5(x)\n        x = self.bn5(x)\n\n        return x\n"
  },
  {
    "path": "gfpgan/archs/gfpgan_bilinear_arch.py",
    "content": "import math\nimport random\nimport torch\nfrom basicsr.utils.registry import ARCH_REGISTRY\nfrom torch import nn\n\nfrom .gfpganv1_arch import ResUpBlock\nfrom .stylegan2_bilinear_arch import (ConvLayer, EqualConv2d, EqualLinear, ResBlock, ScaledLeakyReLU,\n                                      StyleGAN2GeneratorBilinear)\n\n\nclass StyleGAN2GeneratorBilinearSFT(StyleGAN2GeneratorBilinear):\n    \"\"\"StyleGAN2 Generator with SFT modulation (Spatial Feature Transform).\n\n    It is the bilinear version. It does not use the complicated UpFirDnSmooth function that is not friendly for\n    deployment. It can be easily converted to the clean version: StyleGAN2GeneratorCSFT.\n\n    Args:\n        out_size (int): The spatial size of outputs.\n        num_style_feat (int): Channel number of style features. Default: 512.\n        num_mlp (int): Layer number of MLP style layers. Default: 8.\n        channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.\n        lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01.\n        narrow (float): The narrow ratio for channels. Default: 1.\n        sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.\n    \"\"\"\n\n    def __init__(self,\n                 out_size,\n                 num_style_feat=512,\n                 num_mlp=8,\n                 channel_multiplier=2,\n                 lr_mlp=0.01,\n                 narrow=1,\n                 sft_half=False):\n        super(StyleGAN2GeneratorBilinearSFT, self).__init__(\n            out_size,\n            num_style_feat=num_style_feat,\n            num_mlp=num_mlp,\n            channel_multiplier=channel_multiplier,\n            lr_mlp=lr_mlp,\n            narrow=narrow)\n        self.sft_half = sft_half\n\n    def forward(self,\n                styles,\n                conditions,\n                input_is_latent=False,\n                noise=None,\n                randomize_noise=True,\n                truncation=1,\n                truncation_latent=None,\n                inject_index=None,\n                return_latents=False):\n        \"\"\"Forward function for StyleGAN2GeneratorBilinearSFT.\n\n        Args:\n            styles (list[Tensor]): Sample codes of styles.\n            conditions (list[Tensor]): SFT conditions to generators.\n            input_is_latent (bool): Whether input is latent style. Default: False.\n            noise (Tensor | None): Input noise or None. Default: None.\n            randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.\n            truncation (float): The truncation ratio. Default: 1.\n            truncation_latent (Tensor | None): The truncation latent tensor. Default: None.\n            inject_index (int | None): The injection index for mixing noise. Default: None.\n            return_latents (bool): Whether to return style latents. Default: False.\n        \"\"\"\n        # style codes -> latents with Style MLP layer\n        if not input_is_latent:\n            styles = [self.style_mlp(s) for s in styles]\n        # noises\n        if noise is None:\n            if randomize_noise:\n                noise = [None] * self.num_layers  # for each style conv layer\n            else:  # use the stored noise\n                noise = [getattr(self.noises, f'noise{i}') for i in range(self.num_layers)]\n        # style truncation\n        if truncation < 1:\n            style_truncation = []\n            for style in styles:\n                style_truncation.append(truncation_latent + truncation * (style - truncation_latent))\n            styles = style_truncation\n        # get style latents with injection\n        if len(styles) == 1:\n            inject_index = self.num_latent\n\n            if styles[0].ndim < 3:\n                # repeat latent code for all the layers\n                latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)\n            else:  # used for encoder with different latent code for each layer\n                latent = styles[0]\n        elif len(styles) == 2:  # mixing noises\n            if inject_index is None:\n                inject_index = random.randint(1, self.num_latent - 1)\n            latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1)\n            latent2 = styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1)\n            latent = torch.cat([latent1, latent2], 1)\n\n        # main generation\n        out = self.constant_input(latent.shape[0])\n        out = self.style_conv1(out, latent[:, 0], noise=noise[0])\n        skip = self.to_rgb1(out, latent[:, 1])\n\n        i = 1\n        for conv1, conv2, noise1, noise2, to_rgb in zip(self.style_convs[::2], self.style_convs[1::2], noise[1::2],\n                                                        noise[2::2], self.to_rgbs):\n            out = conv1(out, latent[:, i], noise=noise1)\n\n            # the conditions may have fewer levels\n            if i < len(conditions):\n                # SFT part to combine the conditions\n                if self.sft_half:  # only apply SFT to half of the channels\n                    out_same, out_sft = torch.split(out, int(out.size(1) // 2), dim=1)\n                    out_sft = out_sft * conditions[i - 1] + conditions[i]\n                    out = torch.cat([out_same, out_sft], dim=1)\n                else:  # apply SFT to all the channels\n                    out = out * conditions[i - 1] + conditions[i]\n\n            out = conv2(out, latent[:, i + 1], noise=noise2)\n            skip = to_rgb(out, latent[:, i + 2], skip)  # feature back to the rgb space\n            i += 2\n\n        image = skip\n\n        if return_latents:\n            return image, latent\n        else:\n            return image, None\n\n\n@ARCH_REGISTRY.register()\nclass GFPGANBilinear(nn.Module):\n    \"\"\"The GFPGAN architecture: Unet + StyleGAN2 decoder with SFT.\n\n    It is the bilinear version and it does not use the complicated UpFirDnSmooth function that is not friendly for\n    deployment. It can be easily converted to the clean version: GFPGANv1Clean.\n\n\n    Ref: GFP-GAN: Towards Real-World Blind Face Restoration with Generative Facial Prior.\n\n    Args:\n        out_size (int): The spatial size of outputs.\n        num_style_feat (int): Channel number of style features. Default: 512.\n        channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.\n        decoder_load_path (str): The path to the pre-trained decoder model (usually, the StyleGAN2). Default: None.\n        fix_decoder (bool): Whether to fix the decoder. Default: True.\n\n        num_mlp (int): Layer number of MLP style layers. Default: 8.\n        lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01.\n        input_is_latent (bool): Whether input is latent style. Default: False.\n        different_w (bool): Whether to use different latent w for different layers. Default: False.\n        narrow (float): The narrow ratio for channels. Default: 1.\n        sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.\n    \"\"\"\n\n    def __init__(\n            self,\n            out_size,\n            num_style_feat=512,\n            channel_multiplier=1,\n            decoder_load_path=None,\n            fix_decoder=True,\n            # for stylegan decoder\n            num_mlp=8,\n            lr_mlp=0.01,\n            input_is_latent=False,\n            different_w=False,\n            narrow=1,\n            sft_half=False):\n\n        super(GFPGANBilinear, self).__init__()\n        self.input_is_latent = input_is_latent\n        self.different_w = different_w\n        self.num_style_feat = num_style_feat\n\n        unet_narrow = narrow * 0.5  # by default, use a half of input channels\n        channels = {\n            '4': int(512 * unet_narrow),\n            '8': int(512 * unet_narrow),\n            '16': int(512 * unet_narrow),\n            '32': int(512 * unet_narrow),\n            '64': int(256 * channel_multiplier * unet_narrow),\n            '128': int(128 * channel_multiplier * unet_narrow),\n            '256': int(64 * channel_multiplier * unet_narrow),\n            '512': int(32 * channel_multiplier * unet_narrow),\n            '1024': int(16 * channel_multiplier * unet_narrow)\n        }\n\n        self.log_size = int(math.log(out_size, 2))\n        first_out_size = 2**(int(math.log(out_size, 2)))\n\n        self.conv_body_first = ConvLayer(3, channels[f'{first_out_size}'], 1, bias=True, activate=True)\n\n        # downsample\n        in_channels = channels[f'{first_out_size}']\n        self.conv_body_down = nn.ModuleList()\n        for i in range(self.log_size, 2, -1):\n            out_channels = channels[f'{2**(i - 1)}']\n            self.conv_body_down.append(ResBlock(in_channels, out_channels))\n            in_channels = out_channels\n\n        self.final_conv = ConvLayer(in_channels, channels['4'], 3, bias=True, activate=True)\n\n        # upsample\n        in_channels = channels['4']\n        self.conv_body_up = nn.ModuleList()\n        for i in range(3, self.log_size + 1):\n            out_channels = channels[f'{2**i}']\n            self.conv_body_up.append(ResUpBlock(in_channels, out_channels))\n            in_channels = out_channels\n\n        # to RGB\n        self.toRGB = nn.ModuleList()\n        for i in range(3, self.log_size + 1):\n            self.toRGB.append(EqualConv2d(channels[f'{2**i}'], 3, 1, stride=1, padding=0, bias=True, bias_init_val=0))\n\n        if different_w:\n            linear_out_channel = (int(math.log(out_size, 2)) * 2 - 2) * num_style_feat\n        else:\n            linear_out_channel = num_style_feat\n\n        self.final_linear = EqualLinear(\n            channels['4'] * 4 * 4, linear_out_channel, bias=True, bias_init_val=0, lr_mul=1, activation=None)\n\n        # the decoder: stylegan2 generator with SFT modulations\n        self.stylegan_decoder = StyleGAN2GeneratorBilinearSFT(\n            out_size=out_size,\n            num_style_feat=num_style_feat,\n            num_mlp=num_mlp,\n            channel_multiplier=channel_multiplier,\n            lr_mlp=lr_mlp,\n            narrow=narrow,\n            sft_half=sft_half)\n\n        # load pre-trained stylegan2 model if necessary\n        if decoder_load_path:\n            self.stylegan_decoder.load_state_dict(\n                torch.load(decoder_load_path, map_location=lambda storage, loc: storage)['params_ema'])\n        # fix decoder without updating params\n        if fix_decoder:\n            for _, param in self.stylegan_decoder.named_parameters():\n                param.requires_grad = False\n\n        # for SFT modulations (scale and shift)\n        self.condition_scale = nn.ModuleList()\n        self.condition_shift = nn.ModuleList()\n        for i in range(3, self.log_size + 1):\n            out_channels = channels[f'{2**i}']\n            if sft_half:\n                sft_out_channels = out_channels\n            else:\n                sft_out_channels = out_channels * 2\n            self.condition_scale.append(\n                nn.Sequential(\n                    EqualConv2d(out_channels, out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0),\n                    ScaledLeakyReLU(0.2),\n                    EqualConv2d(out_channels, sft_out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=1)))\n            self.condition_shift.append(\n                nn.Sequential(\n                    EqualConv2d(out_channels, out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0),\n                    ScaledLeakyReLU(0.2),\n                    EqualConv2d(out_channels, sft_out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0)))\n\n    def forward(self, x, return_latents=False, return_rgb=True, randomize_noise=True):\n        \"\"\"Forward function for GFPGANBilinear.\n\n        Args:\n            x (Tensor): Input images.\n            return_latents (bool): Whether to return style latents. Default: False.\n            return_rgb (bool): Whether return intermediate rgb images. Default: True.\n            randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.\n        \"\"\"\n        conditions = []\n        unet_skips = []\n        out_rgbs = []\n\n        # encoder\n        feat = self.conv_body_first(x)\n        for i in range(self.log_size - 2):\n            feat = self.conv_body_down[i](feat)\n            unet_skips.insert(0, feat)\n\n        feat = self.final_conv(feat)\n\n        # style code\n        style_code = self.final_linear(feat.view(feat.size(0), -1))\n        if self.different_w:\n            style_code = style_code.view(style_code.size(0), -1, self.num_style_feat)\n\n        # decode\n        for i in range(self.log_size - 2):\n            # add unet skip\n            feat = feat + unet_skips[i]\n            # ResUpLayer\n            feat = self.conv_body_up[i](feat)\n            # generate scale and shift for SFT layers\n            scale = self.condition_scale[i](feat)\n            conditions.append(scale.clone())\n            shift = self.condition_shift[i](feat)\n            conditions.append(shift.clone())\n            # generate rgb images\n            if return_rgb:\n                out_rgbs.append(self.toRGB[i](feat))\n\n        # decoder\n        image, _ = self.stylegan_decoder([style_code],\n                                         conditions,\n                                         return_latents=return_latents,\n                                         input_is_latent=self.input_is_latent,\n                                         randomize_noise=randomize_noise)\n\n        return image, out_rgbs\n"
  },
  {
    "path": "gfpgan/archs/gfpganv1_arch.py",
    "content": "import math\nimport random\nimport torch\nfrom basicsr.archs.stylegan2_arch import (ConvLayer, EqualConv2d, EqualLinear, ResBlock, ScaledLeakyReLU,\n                                          StyleGAN2Generator)\nfrom basicsr.ops.fused_act import FusedLeakyReLU\nfrom basicsr.utils.registry import ARCH_REGISTRY\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\nclass StyleGAN2GeneratorSFT(StyleGAN2Generator):\n    \"\"\"StyleGAN2 Generator with SFT modulation (Spatial Feature Transform).\n\n    Args:\n        out_size (int): The spatial size of outputs.\n        num_style_feat (int): Channel number of style features. Default: 512.\n        num_mlp (int): Layer number of MLP style layers. Default: 8.\n        channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.\n        resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. A cross production will be\n            applied to extent 1D resample kernel to 2D resample kernel. Default: (1, 3, 3, 1).\n        lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01.\n        narrow (float): The narrow ratio for channels. Default: 1.\n        sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.\n    \"\"\"\n\n    def __init__(self,\n                 out_size,\n                 num_style_feat=512,\n                 num_mlp=8,\n                 channel_multiplier=2,\n                 resample_kernel=(1, 3, 3, 1),\n                 lr_mlp=0.01,\n                 narrow=1,\n                 sft_half=False):\n        super(StyleGAN2GeneratorSFT, self).__init__(\n            out_size,\n            num_style_feat=num_style_feat,\n            num_mlp=num_mlp,\n            channel_multiplier=channel_multiplier,\n            resample_kernel=resample_kernel,\n            lr_mlp=lr_mlp,\n            narrow=narrow)\n        self.sft_half = sft_half\n\n    def forward(self,\n                styles,\n                conditions,\n                input_is_latent=False,\n                noise=None,\n                randomize_noise=True,\n                truncation=1,\n                truncation_latent=None,\n                inject_index=None,\n                return_latents=False):\n        \"\"\"Forward function for StyleGAN2GeneratorSFT.\n\n        Args:\n            styles (list[Tensor]): Sample codes of styles.\n            conditions (list[Tensor]): SFT conditions to generators.\n            input_is_latent (bool): Whether input is latent style. Default: False.\n            noise (Tensor | None): Input noise or None. Default: None.\n            randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.\n            truncation (float): The truncation ratio. Default: 1.\n            truncation_latent (Tensor | None): The truncation latent tensor. Default: None.\n            inject_index (int | None): The injection index for mixing noise. Default: None.\n            return_latents (bool): Whether to return style latents. Default: False.\n        \"\"\"\n        # style codes -> latents with Style MLP layer\n        if not input_is_latent:\n            styles = [self.style_mlp(s) for s in styles]\n        # noises\n        if noise is None:\n            if randomize_noise:\n                noise = [None] * self.num_layers  # for each style conv layer\n            else:  # use the stored noise\n                noise = [getattr(self.noises, f'noise{i}') for i in range(self.num_layers)]\n        # style truncation\n        if truncation < 1:\n            style_truncation = []\n            for style in styles:\n                style_truncation.append(truncation_latent + truncation * (style - truncation_latent))\n            styles = style_truncation\n        # get style latents with injection\n        if len(styles) == 1:\n            inject_index = self.num_latent\n\n            if styles[0].ndim < 3:\n                # repeat latent code for all the layers\n                latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)\n            else:  # used for encoder with different latent code for each layer\n                latent = styles[0]\n        elif len(styles) == 2:  # mixing noises\n            if inject_index is None:\n                inject_index = random.randint(1, self.num_latent - 1)\n            latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1)\n            latent2 = styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1)\n            latent = torch.cat([latent1, latent2], 1)\n\n        # main generation\n        out = self.constant_input(latent.shape[0])\n        out = self.style_conv1(out, latent[:, 0], noise=noise[0])\n        skip = self.to_rgb1(out, latent[:, 1])\n\n        i = 1\n        for conv1, conv2, noise1, noise2, to_rgb in zip(self.style_convs[::2], self.style_convs[1::2], noise[1::2],\n                                                        noise[2::2], self.to_rgbs):\n            out = conv1(out, latent[:, i], noise=noise1)\n\n            # the conditions may have fewer levels\n            if i < len(conditions):\n                # SFT part to combine the conditions\n                if self.sft_half:  # only apply SFT to half of the channels\n                    out_same, out_sft = torch.split(out, int(out.size(1) // 2), dim=1)\n                    out_sft = out_sft * conditions[i - 1] + conditions[i]\n                    out = torch.cat([out_same, out_sft], dim=1)\n                else:  # apply SFT to all the channels\n                    out = out * conditions[i - 1] + conditions[i]\n\n            out = conv2(out, latent[:, i + 1], noise=noise2)\n            skip = to_rgb(out, latent[:, i + 2], skip)  # feature back to the rgb space\n            i += 2\n\n        image = skip\n\n        if return_latents:\n            return image, latent\n        else:\n            return image, None\n\n\nclass ConvUpLayer(nn.Module):\n    \"\"\"Convolutional upsampling layer. It uses bilinear upsampler + Conv.\n\n    Args:\n        in_channels (int): Channel number of the input.\n        out_channels (int): Channel number of the output.\n        kernel_size (int): Size of the convolving kernel.\n        stride (int): Stride of the convolution. Default: 1\n        padding (int): Zero-padding added to both sides of the input. Default: 0.\n        bias (bool): If ``True``, adds a learnable bias to the output. Default: ``True``.\n        bias_init_val (float): Bias initialized value. Default: 0.\n        activate (bool): Whether use activateion. Default: True.\n    \"\"\"\n\n    def __init__(self,\n                 in_channels,\n                 out_channels,\n                 kernel_size,\n                 stride=1,\n                 padding=0,\n                 bias=True,\n                 bias_init_val=0,\n                 activate=True):\n        super(ConvUpLayer, self).__init__()\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.kernel_size = kernel_size\n        self.stride = stride\n        self.padding = padding\n        # self.scale is used to scale the convolution weights, which is related to the common initializations.\n        self.scale = 1 / math.sqrt(in_channels * kernel_size**2)\n\n        self.weight = nn.Parameter(torch.randn(out_channels, in_channels, kernel_size, kernel_size))\n\n        if bias and not activate:\n            self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val))\n        else:\n            self.register_parameter('bias', None)\n\n        # activation\n        if activate:\n            if bias:\n                self.activation = FusedLeakyReLU(out_channels)\n            else:\n                self.activation = ScaledLeakyReLU(0.2)\n        else:\n            self.activation = None\n\n    def forward(self, x):\n        # bilinear upsample\n        out = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)\n        # conv\n        out = F.conv2d(\n            out,\n            self.weight * self.scale,\n            bias=self.bias,\n            stride=self.stride,\n            padding=self.padding,\n        )\n        # activation\n        if self.activation is not None:\n            out = self.activation(out)\n        return out\n\n\nclass ResUpBlock(nn.Module):\n    \"\"\"Residual block with upsampling.\n\n    Args:\n        in_channels (int): Channel number of the input.\n        out_channels (int): Channel number of the output.\n    \"\"\"\n\n    def __init__(self, in_channels, out_channels):\n        super(ResUpBlock, self).__init__()\n\n        self.conv1 = ConvLayer(in_channels, in_channels, 3, bias=True, activate=True)\n        self.conv2 = ConvUpLayer(in_channels, out_channels, 3, stride=1, padding=1, bias=True, activate=True)\n        self.skip = ConvUpLayer(in_channels, out_channels, 1, bias=False, activate=False)\n\n    def forward(self, x):\n        out = self.conv1(x)\n        out = self.conv2(out)\n        skip = self.skip(x)\n        out = (out + skip) / math.sqrt(2)\n        return out\n\n\n@ARCH_REGISTRY.register()\nclass GFPGANv1(nn.Module):\n    \"\"\"The GFPGAN architecture: Unet + StyleGAN2 decoder with SFT.\n\n    Ref: GFP-GAN: Towards Real-World Blind Face Restoration with Generative Facial Prior.\n\n    Args:\n        out_size (int): The spatial size of outputs.\n        num_style_feat (int): Channel number of style features. Default: 512.\n        channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.\n        resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. A cross production will be\n            applied to extent 1D resample kernel to 2D resample kernel. Default: (1, 3, 3, 1).\n        decoder_load_path (str): The path to the pre-trained decoder model (usually, the StyleGAN2). Default: None.\n        fix_decoder (bool): Whether to fix the decoder. Default: True.\n\n        num_mlp (int): Layer number of MLP style layers. Default: 8.\n        lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01.\n        input_is_latent (bool): Whether input is latent style. Default: False.\n        different_w (bool): Whether to use different latent w for different layers. Default: False.\n        narrow (float): The narrow ratio for channels. Default: 1.\n        sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.\n    \"\"\"\n\n    def __init__(\n            self,\n            out_size,\n            num_style_feat=512,\n            channel_multiplier=1,\n            resample_kernel=(1, 3, 3, 1),\n            decoder_load_path=None,\n            fix_decoder=True,\n            # for stylegan decoder\n            num_mlp=8,\n            lr_mlp=0.01,\n            input_is_latent=False,\n            different_w=False,\n            narrow=1,\n            sft_half=False):\n\n        super(GFPGANv1, self).__init__()\n        self.input_is_latent = input_is_latent\n        self.different_w = different_w\n        self.num_style_feat = num_style_feat\n\n        unet_narrow = narrow * 0.5  # by default, use a half of input channels\n        channels = {\n            '4': int(512 * unet_narrow),\n            '8': int(512 * unet_narrow),\n            '16': int(512 * unet_narrow),\n            '32': int(512 * unet_narrow),\n            '64': int(256 * channel_multiplier * unet_narrow),\n            '128': int(128 * channel_multiplier * unet_narrow),\n            '256': int(64 * channel_multiplier * unet_narrow),\n            '512': int(32 * channel_multiplier * unet_narrow),\n            '1024': int(16 * channel_multiplier * unet_narrow)\n        }\n\n        self.log_size = int(math.log(out_size, 2))\n        first_out_size = 2**(int(math.log(out_size, 2)))\n\n        self.conv_body_first = ConvLayer(3, channels[f'{first_out_size}'], 1, bias=True, activate=True)\n\n        # downsample\n        in_channels = channels[f'{first_out_size}']\n        self.conv_body_down = nn.ModuleList()\n        for i in range(self.log_size, 2, -1):\n            out_channels = channels[f'{2**(i - 1)}']\n            self.conv_body_down.append(ResBlock(in_channels, out_channels, resample_kernel))\n            in_channels = out_channels\n\n        self.final_conv = ConvLayer(in_channels, channels['4'], 3, bias=True, activate=True)\n\n        # upsample\n        in_channels = channels['4']\n        self.conv_body_up = nn.ModuleList()\n        for i in range(3, self.log_size + 1):\n            out_channels = channels[f'{2**i}']\n            self.conv_body_up.append(ResUpBlock(in_channels, out_channels))\n            in_channels = out_channels\n\n        # to RGB\n        self.toRGB = nn.ModuleList()\n        for i in range(3, self.log_size + 1):\n            self.toRGB.append(EqualConv2d(channels[f'{2**i}'], 3, 1, stride=1, padding=0, bias=True, bias_init_val=0))\n\n        if different_w:\n            linear_out_channel = (int(math.log(out_size, 2)) * 2 - 2) * num_style_feat\n        else:\n            linear_out_channel = num_style_feat\n\n        self.final_linear = EqualLinear(\n            channels['4'] * 4 * 4, linear_out_channel, bias=True, bias_init_val=0, lr_mul=1, activation=None)\n\n        # the decoder: stylegan2 generator with SFT modulations\n        self.stylegan_decoder = StyleGAN2GeneratorSFT(\n            out_size=out_size,\n            num_style_feat=num_style_feat,\n            num_mlp=num_mlp,\n            channel_multiplier=channel_multiplier,\n            resample_kernel=resample_kernel,\n            lr_mlp=lr_mlp,\n            narrow=narrow,\n            sft_half=sft_half)\n\n        # load pre-trained stylegan2 model if necessary\n        if decoder_load_path:\n            self.stylegan_decoder.load_state_dict(\n                torch.load(decoder_load_path, map_location=lambda storage, loc: storage)['params_ema'])\n        # fix decoder without updating params\n        if fix_decoder:\n            for _, param in self.stylegan_decoder.named_parameters():\n                param.requires_grad = False\n\n        # for SFT modulations (scale and shift)\n        self.condition_scale = nn.ModuleList()\n        self.condition_shift = nn.ModuleList()\n        for i in range(3, self.log_size + 1):\n            out_channels = channels[f'{2**i}']\n            if sft_half:\n                sft_out_channels = out_channels\n            else:\n                sft_out_channels = out_channels * 2\n            self.condition_scale.append(\n                nn.Sequential(\n                    EqualConv2d(out_channels, out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0),\n                    ScaledLeakyReLU(0.2),\n                    EqualConv2d(out_channels, sft_out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=1)))\n            self.condition_shift.append(\n                nn.Sequential(\n                    EqualConv2d(out_channels, out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0),\n                    ScaledLeakyReLU(0.2),\n                    EqualConv2d(out_channels, sft_out_channels, 3, stride=1, padding=1, bias=True, bias_init_val=0)))\n\n    def forward(self, x, return_latents=False, return_rgb=True, randomize_noise=True, **kwargs):\n        \"\"\"Forward function for GFPGANv1.\n\n        Args:\n            x (Tensor): Input images.\n            return_latents (bool): Whether to return style latents. Default: False.\n            return_rgb (bool): Whether return intermediate rgb images. Default: True.\n            randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.\n        \"\"\"\n        conditions = []\n        unet_skips = []\n        out_rgbs = []\n\n        # encoder\n        feat = self.conv_body_first(x)\n        for i in range(self.log_size - 2):\n            feat = self.conv_body_down[i](feat)\n            unet_skips.insert(0, feat)\n\n        feat = self.final_conv(feat)\n\n        # style code\n        style_code = self.final_linear(feat.view(feat.size(0), -1))\n        if self.different_w:\n            style_code = style_code.view(style_code.size(0), -1, self.num_style_feat)\n\n        # decode\n        for i in range(self.log_size - 2):\n            # add unet skip\n            feat = feat + unet_skips[i]\n            # ResUpLayer\n            feat = self.conv_body_up[i](feat)\n            # generate scale and shift for SFT layers\n            scale = self.condition_scale[i](feat)\n            conditions.append(scale.clone())\n            shift = self.condition_shift[i](feat)\n            conditions.append(shift.clone())\n            # generate rgb images\n            if return_rgb:\n                out_rgbs.append(self.toRGB[i](feat))\n\n        # decoder\n        image, _ = self.stylegan_decoder([style_code],\n                                         conditions,\n                                         return_latents=return_latents,\n                                         input_is_latent=self.input_is_latent,\n                                         randomize_noise=randomize_noise)\n\n        return image, out_rgbs\n\n\n@ARCH_REGISTRY.register()\nclass FacialComponentDiscriminator(nn.Module):\n    \"\"\"Facial component (eyes, mouth, noise) discriminator used in GFPGAN.\n    \"\"\"\n\n    def __init__(self):\n        super(FacialComponentDiscriminator, self).__init__()\n        # It now uses a VGG-style architectrue with fixed model size\n        self.conv1 = ConvLayer(3, 64, 3, downsample=False, resample_kernel=(1, 3, 3, 1), bias=True, activate=True)\n        self.conv2 = ConvLayer(64, 128, 3, downsample=True, resample_kernel=(1, 3, 3, 1), bias=True, activate=True)\n        self.conv3 = ConvLayer(128, 128, 3, downsample=False, resample_kernel=(1, 3, 3, 1), bias=True, activate=True)\n        self.conv4 = ConvLayer(128, 256, 3, downsample=True, resample_kernel=(1, 3, 3, 1), bias=True, activate=True)\n        self.conv5 = ConvLayer(256, 256, 3, downsample=False, resample_kernel=(1, 3, 3, 1), bias=True, activate=True)\n        self.final_conv = ConvLayer(256, 1, 3, bias=True, activate=False)\n\n    def forward(self, x, return_feats=False, **kwargs):\n        \"\"\"Forward function for FacialComponentDiscriminator.\n\n        Args:\n            x (Tensor): Input images.\n            return_feats (bool): Whether to return intermediate features. Default: False.\n        \"\"\"\n        feat = self.conv1(x)\n        feat = self.conv3(self.conv2(feat))\n        rlt_feats = []\n        if return_feats:\n            rlt_feats.append(feat.clone())\n        feat = self.conv5(self.conv4(feat))\n        if return_feats:\n            rlt_feats.append(feat.clone())\n        out = self.final_conv(feat)\n\n        if return_feats:\n            return out, rlt_feats\n        else:\n            return out, None\n"
  },
  {
    "path": "gfpgan/archs/gfpganv1_clean_arch.py",
    "content": "import math\nimport random\nimport torch\nfrom basicsr.utils.registry import ARCH_REGISTRY\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom .stylegan2_clean_arch import StyleGAN2GeneratorClean\n\n\nclass StyleGAN2GeneratorCSFT(StyleGAN2GeneratorClean):\n    \"\"\"StyleGAN2 Generator with SFT modulation (Spatial Feature Transform).\n\n    It is the clean version without custom compiled CUDA extensions used in StyleGAN2.\n\n    Args:\n        out_size (int): The spatial size of outputs.\n        num_style_feat (int): Channel number of style features. Default: 512.\n        num_mlp (int): Layer number of MLP style layers. Default: 8.\n        channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.\n        narrow (float): The narrow ratio for channels. Default: 1.\n        sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.\n    \"\"\"\n\n    def __init__(self, out_size, num_style_feat=512, num_mlp=8, channel_multiplier=2, narrow=1, sft_half=False):\n        super(StyleGAN2GeneratorCSFT, self).__init__(\n            out_size,\n            num_style_feat=num_style_feat,\n            num_mlp=num_mlp,\n            channel_multiplier=channel_multiplier,\n            narrow=narrow)\n        self.sft_half = sft_half\n\n    def forward(self,\n                styles,\n                conditions,\n                input_is_latent=False,\n                noise=None,\n                randomize_noise=True,\n                truncation=1,\n                truncation_latent=None,\n                inject_index=None,\n                return_latents=False):\n        \"\"\"Forward function for StyleGAN2GeneratorCSFT.\n\n        Args:\n            styles (list[Tensor]): Sample codes of styles.\n            conditions (list[Tensor]): SFT conditions to generators.\n            input_is_latent (bool): Whether input is latent style. Default: False.\n            noise (Tensor | None): Input noise or None. Default: None.\n            randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.\n            truncation (float): The truncation ratio. Default: 1.\n            truncation_latent (Tensor | None): The truncation latent tensor. Default: None.\n            inject_index (int | None): The injection index for mixing noise. Default: None.\n            return_latents (bool): Whether to return style latents. Default: False.\n        \"\"\"\n        # style codes -> latents with Style MLP layer\n        if not input_is_latent:\n            styles = [self.style_mlp(s) for s in styles]\n        # noises\n        if noise is None:\n            if randomize_noise:\n                noise = [None] * self.num_layers  # for each style conv layer\n            else:  # use the stored noise\n                noise = [getattr(self.noises, f'noise{i}') for i in range(self.num_layers)]\n        # style truncation\n        if truncation < 1:\n            style_truncation = []\n            for style in styles:\n                style_truncation.append(truncation_latent + truncation * (style - truncation_latent))\n            styles = style_truncation\n        # get style latents with injection\n        if len(styles) == 1:\n            inject_index = self.num_latent\n\n            if styles[0].ndim < 3:\n                # repeat latent code for all the layers\n                latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)\n            else:  # used for encoder with different latent code for each layer\n                latent = styles[0]\n        elif len(styles) == 2:  # mixing noises\n            if inject_index is None:\n                inject_index = random.randint(1, self.num_latent - 1)\n            latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1)\n            latent2 = styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1)\n            latent = torch.cat([latent1, latent2], 1)\n\n        # main generation\n        out = self.constant_input(latent.shape[0])\n        out = self.style_conv1(out, latent[:, 0], noise=noise[0])\n        skip = self.to_rgb1(out, latent[:, 1])\n\n        i = 1\n        for conv1, conv2, noise1, noise2, to_rgb in zip(self.style_convs[::2], self.style_convs[1::2], noise[1::2],\n                                                        noise[2::2], self.to_rgbs):\n            out = conv1(out, latent[:, i], noise=noise1)\n\n            # the conditions may have fewer levels\n            if i < len(conditions):\n                # SFT part to combine the conditions\n                if self.sft_half:  # only apply SFT to half of the channels\n                    out_same, out_sft = torch.split(out, int(out.size(1) // 2), dim=1)\n                    out_sft = out_sft * conditions[i - 1] + conditions[i]\n                    out = torch.cat([out_same, out_sft], dim=1)\n                else:  # apply SFT to all the channels\n                    out = out * conditions[i - 1] + conditions[i]\n\n            out = conv2(out, latent[:, i + 1], noise=noise2)\n            skip = to_rgb(out, latent[:, i + 2], skip)  # feature back to the rgb space\n            i += 2\n\n        image = skip\n\n        if return_latents:\n            return image, latent\n        else:\n            return image, None\n\n\nclass ResBlock(nn.Module):\n    \"\"\"Residual block with bilinear upsampling/downsampling.\n\n    Args:\n        in_channels (int): Channel number of the input.\n        out_channels (int): Channel number of the output.\n        mode (str): Upsampling/downsampling mode. Options: down | up. Default: down.\n    \"\"\"\n\n    def __init__(self, in_channels, out_channels, mode='down'):\n        super(ResBlock, self).__init__()\n\n        self.conv1 = nn.Conv2d(in_channels, in_channels, 3, 1, 1)\n        self.conv2 = nn.Conv2d(in_channels, out_channels, 3, 1, 1)\n        self.skip = nn.Conv2d(in_channels, out_channels, 1, bias=False)\n        if mode == 'down':\n            self.scale_factor = 0.5\n        elif mode == 'up':\n            self.scale_factor = 2\n\n    def forward(self, x):\n        out = F.leaky_relu_(self.conv1(x), negative_slope=0.2)\n        # upsample/downsample\n        out = F.interpolate(out, scale_factor=self.scale_factor, mode='bilinear', align_corners=False)\n        out = F.leaky_relu_(self.conv2(out), negative_slope=0.2)\n        # skip\n        x = F.interpolate(x, scale_factor=self.scale_factor, mode='bilinear', align_corners=False)\n        skip = self.skip(x)\n        out = out + skip\n        return out\n\n\n@ARCH_REGISTRY.register()\nclass GFPGANv1Clean(nn.Module):\n    \"\"\"The GFPGAN architecture: Unet + StyleGAN2 decoder with SFT.\n\n    It is the clean version without custom compiled CUDA extensions used in StyleGAN2.\n\n    Ref: GFP-GAN: Towards Real-World Blind Face Restoration with Generative Facial Prior.\n\n    Args:\n        out_size (int): The spatial size of outputs.\n        num_style_feat (int): Channel number of style features. Default: 512.\n        channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.\n        decoder_load_path (str): The path to the pre-trained decoder model (usually, the StyleGAN2). Default: None.\n        fix_decoder (bool): Whether to fix the decoder. Default: True.\n\n        num_mlp (int): Layer number of MLP style layers. Default: 8.\n        input_is_latent (bool): Whether input is latent style. Default: False.\n        different_w (bool): Whether to use different latent w for different layers. Default: False.\n        narrow (float): The narrow ratio for channels. Default: 1.\n        sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.\n    \"\"\"\n\n    def __init__(\n            self,\n            out_size,\n            num_style_feat=512,\n            channel_multiplier=1,\n            decoder_load_path=None,\n            fix_decoder=True,\n            # for stylegan decoder\n            num_mlp=8,\n            input_is_latent=False,\n            different_w=False,\n            narrow=1,\n            sft_half=False):\n\n        super(GFPGANv1Clean, self).__init__()\n        self.input_is_latent = input_is_latent\n        self.different_w = different_w\n        self.num_style_feat = num_style_feat\n\n        unet_narrow = narrow * 0.5  # by default, use a half of input channels\n        channels = {\n            '4': int(512 * unet_narrow),\n            '8': int(512 * unet_narrow),\n            '16': int(512 * unet_narrow),\n            '32': int(512 * unet_narrow),\n            '64': int(256 * channel_multiplier * unet_narrow),\n            '128': int(128 * channel_multiplier * unet_narrow),\n            '256': int(64 * channel_multiplier * unet_narrow),\n            '512': int(32 * channel_multiplier * unet_narrow),\n            '1024': int(16 * channel_multiplier * unet_narrow)\n        }\n\n        self.log_size = int(math.log(out_size, 2))\n        first_out_size = 2**(int(math.log(out_size, 2)))\n\n        self.conv_body_first = nn.Conv2d(3, channels[f'{first_out_size}'], 1)\n\n        # downsample\n        in_channels = channels[f'{first_out_size}']\n        self.conv_body_down = nn.ModuleList()\n        for i in range(self.log_size, 2, -1):\n            out_channels = channels[f'{2**(i - 1)}']\n            self.conv_body_down.append(ResBlock(in_channels, out_channels, mode='down'))\n            in_channels = out_channels\n\n        self.final_conv = nn.Conv2d(in_channels, channels['4'], 3, 1, 1)\n\n        # upsample\n        in_channels = channels['4']\n        self.conv_body_up = nn.ModuleList()\n        for i in range(3, self.log_size + 1):\n            out_channels = channels[f'{2**i}']\n            self.conv_body_up.append(ResBlock(in_channels, out_channels, mode='up'))\n            in_channels = out_channels\n\n        # to RGB\n        self.toRGB = nn.ModuleList()\n        for i in range(3, self.log_size + 1):\n            self.toRGB.append(nn.Conv2d(channels[f'{2**i}'], 3, 1))\n\n        if different_w:\n            linear_out_channel = (int(math.log(out_size, 2)) * 2 - 2) * num_style_feat\n        else:\n            linear_out_channel = num_style_feat\n\n        self.final_linear = nn.Linear(channels['4'] * 4 * 4, linear_out_channel)\n\n        # the decoder: stylegan2 generator with SFT modulations\n        self.stylegan_decoder = StyleGAN2GeneratorCSFT(\n            out_size=out_size,\n            num_style_feat=num_style_feat,\n            num_mlp=num_mlp,\n            channel_multiplier=channel_multiplier,\n            narrow=narrow,\n            sft_half=sft_half)\n\n        # load pre-trained stylegan2 model if necessary\n        if decoder_load_path:\n            self.stylegan_decoder.load_state_dict(\n                torch.load(decoder_load_path, map_location=lambda storage, loc: storage)['params_ema'])\n        # fix decoder without updating params\n        if fix_decoder:\n            for _, param in self.stylegan_decoder.named_parameters():\n                param.requires_grad = False\n\n        # for SFT modulations (scale and shift)\n        self.condition_scale = nn.ModuleList()\n        self.condition_shift = nn.ModuleList()\n        for i in range(3, self.log_size + 1):\n            out_channels = channels[f'{2**i}']\n            if sft_half:\n                sft_out_channels = out_channels\n            else:\n                sft_out_channels = out_channels * 2\n            self.condition_scale.append(\n                nn.Sequential(\n                    nn.Conv2d(out_channels, out_channels, 3, 1, 1), nn.LeakyReLU(0.2, True),\n                    nn.Conv2d(out_channels, sft_out_channels, 3, 1, 1)))\n            self.condition_shift.append(\n                nn.Sequential(\n                    nn.Conv2d(out_channels, out_channels, 3, 1, 1), nn.LeakyReLU(0.2, True),\n                    nn.Conv2d(out_channels, sft_out_channels, 3, 1, 1)))\n\n    def forward(self, x, return_latents=False, return_rgb=True, randomize_noise=True, **kwargs):\n        \"\"\"Forward function for GFPGANv1Clean.\n\n        Args:\n            x (Tensor): Input images.\n            return_latents (bool): Whether to return style latents. Default: False.\n            return_rgb (bool): Whether return intermediate rgb images. Default: True.\n            randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.\n        \"\"\"\n        conditions = []\n        unet_skips = []\n        out_rgbs = []\n\n        # encoder\n        feat = F.leaky_relu_(self.conv_body_first(x), negative_slope=0.2)\n        for i in range(self.log_size - 2):\n            feat = self.conv_body_down[i](feat)\n            unet_skips.insert(0, feat)\n        feat = F.leaky_relu_(self.final_conv(feat), negative_slope=0.2)\n\n        # style code\n        style_code = self.final_linear(feat.view(feat.size(0), -1))\n        if self.different_w:\n            style_code = style_code.view(style_code.size(0), -1, self.num_style_feat)\n\n        # decode\n        for i in range(self.log_size - 2):\n            # add unet skip\n            feat = feat + unet_skips[i]\n            # ResUpLayer\n            feat = self.conv_body_up[i](feat)\n            # generate scale and shift for SFT layers\n            scale = self.condition_scale[i](feat)\n            conditions.append(scale.clone())\n            shift = self.condition_shift[i](feat)\n            conditions.append(shift.clone())\n            # generate rgb images\n            if return_rgb:\n                out_rgbs.append(self.toRGB[i](feat))\n\n        # decoder\n        image, _ = self.stylegan_decoder([style_code],\n                                         conditions,\n                                         return_latents=return_latents,\n                                         input_is_latent=self.input_is_latent,\n                                         randomize_noise=randomize_noise)\n\n        return image, out_rgbs\n"
  },
  {
    "path": "gfpgan/archs/restoreformer_arch.py",
    "content": "\"\"\"Modified from https://github.com/wzhouxiff/RestoreFormer\n\"\"\"\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass VectorQuantizer(nn.Module):\n    \"\"\"\n    see https://github.com/MishaLaskin/vqvae/blob/d761a999e2267766400dc646d82d3ac3657771d4/models/quantizer.py\n    ____________________________________________\n    Discretization bottleneck part of the VQ-VAE.\n    Inputs:\n    - n_e : number of embeddings\n    - e_dim : dimension of embedding\n    - beta : commitment cost used in loss term, beta * ||z_e(x)-sg[e]||^2\n    _____________________________________________\n    \"\"\"\n\n    def __init__(self, n_e, e_dim, beta):\n        super(VectorQuantizer, self).__init__()\n        self.n_e = n_e\n        self.e_dim = e_dim\n        self.beta = beta\n\n        self.embedding = nn.Embedding(self.n_e, self.e_dim)\n        self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)\n\n    def forward(self, z):\n        \"\"\"\n        Inputs the output of the encoder network z and maps it to a discrete\n        one-hot vector that is the index of the closest embedding vector e_j\n        z (continuous) -> z_q (discrete)\n        z.shape = (batch, channel, height, width)\n        quantization pipeline:\n            1. get encoder input (B,C,H,W)\n            2. flatten input to (B*H*W,C)\n        \"\"\"\n        # reshape z -> (batch, height, width, channel) and flatten\n        z = z.permute(0, 2, 3, 1).contiguous()\n        z_flattened = z.view(-1, self.e_dim)\n        # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z\n\n        d = torch.sum(z_flattened ** 2, dim=1, keepdim=True) + \\\n            torch.sum(self.embedding.weight**2, dim=1) - 2 * \\\n            torch.matmul(z_flattened, self.embedding.weight.t())\n\n        # could possible replace this here\n        # #\\start...\n        # find closest encodings\n\n        min_value, min_encoding_indices = torch.min(d, dim=1)\n\n        min_encoding_indices = min_encoding_indices.unsqueeze(1)\n\n        min_encodings = torch.zeros(min_encoding_indices.shape[0], self.n_e).to(z)\n        min_encodings.scatter_(1, min_encoding_indices, 1)\n\n        # dtype min encodings: torch.float32\n        # min_encodings shape: torch.Size([2048, 512])\n        # min_encoding_indices.shape: torch.Size([2048, 1])\n\n        # get quantized latent vectors\n        z_q = torch.matmul(min_encodings, self.embedding.weight).view(z.shape)\n        # .........\\end\n\n        # with:\n        # .........\\start\n        # min_encoding_indices = torch.argmin(d, dim=1)\n        # z_q = self.embedding(min_encoding_indices)\n        # ......\\end......... (TODO)\n\n        # compute loss for embedding\n        loss = torch.mean((z_q.detach() - z)**2) + self.beta * torch.mean((z_q - z.detach())**2)\n\n        # preserve gradients\n        z_q = z + (z_q - z).detach()\n\n        # perplexity\n\n        e_mean = torch.mean(min_encodings, dim=0)\n        perplexity = torch.exp(-torch.sum(e_mean * torch.log(e_mean + 1e-10)))\n\n        # reshape back to match original input shape\n        z_q = z_q.permute(0, 3, 1, 2).contiguous()\n\n        return z_q, loss, (perplexity, min_encodings, min_encoding_indices, d)\n\n    def get_codebook_entry(self, indices, shape):\n        # shape specifying (batch, height, width, channel)\n        # TODO: check for more easy handling with nn.Embedding\n        min_encodings = torch.zeros(indices.shape[0], self.n_e).to(indices)\n        min_encodings.scatter_(1, indices[:, None], 1)\n\n        # get quantized latent vectors\n        z_q = torch.matmul(min_encodings.float(), self.embedding.weight)\n\n        if shape is not None:\n            z_q = z_q.view(shape)\n\n            # reshape back to match original input shape\n            z_q = z_q.permute(0, 3, 1, 2).contiguous()\n\n        return z_q\n\n\n# pytorch_diffusion + derived encoder decoder\ndef nonlinearity(x):\n    # swish\n    return x * torch.sigmoid(x)\n\n\ndef Normalize(in_channels):\n    return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)\n\n\nclass Upsample(nn.Module):\n\n    def __init__(self, in_channels, with_conv):\n        super().__init__()\n        self.with_conv = with_conv\n        if self.with_conv:\n            self.conv = torch.nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)\n\n    def forward(self, x):\n        x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode='nearest')\n        if self.with_conv:\n            x = self.conv(x)\n        return x\n\n\nclass Downsample(nn.Module):\n\n    def __init__(self, in_channels, with_conv):\n        super().__init__()\n        self.with_conv = with_conv\n        if self.with_conv:\n            # no asymmetric padding in torch conv, must do it ourselves\n            self.conv = torch.nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)\n\n    def forward(self, x):\n        if self.with_conv:\n            pad = (0, 1, 0, 1)\n            x = torch.nn.functional.pad(x, pad, mode='constant', value=0)\n            x = self.conv(x)\n        else:\n            x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)\n        return x\n\n\nclass ResnetBlock(nn.Module):\n\n    def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False, dropout, temb_channels=512):\n        super().__init__()\n        self.in_channels = in_channels\n        out_channels = in_channels if out_channels is None else out_channels\n        self.out_channels = out_channels\n        self.use_conv_shortcut = conv_shortcut\n\n        self.norm1 = Normalize(in_channels)\n        self.conv1 = torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)\n        if temb_channels > 0:\n            self.temb_proj = torch.nn.Linear(temb_channels, out_channels)\n        self.norm2 = Normalize(out_channels)\n        self.dropout = torch.nn.Dropout(dropout)\n        self.conv2 = torch.nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)\n        if self.in_channels != self.out_channels:\n            if self.use_conv_shortcut:\n                self.conv_shortcut = torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)\n            else:\n                self.nin_shortcut = torch.nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)\n\n    def forward(self, x, temb):\n        h = x\n        h = self.norm1(h)\n        h = nonlinearity(h)\n        h = self.conv1(h)\n\n        if temb is not None:\n            h = h + self.temb_proj(nonlinearity(temb))[:, :, None, None]\n\n        h = self.norm2(h)\n        h = nonlinearity(h)\n        h = self.dropout(h)\n        h = self.conv2(h)\n\n        if self.in_channels != self.out_channels:\n            if self.use_conv_shortcut:\n                x = self.conv_shortcut(x)\n            else:\n                x = self.nin_shortcut(x)\n\n        return x + h\n\n\nclass MultiHeadAttnBlock(nn.Module):\n\n    def __init__(self, in_channels, head_size=1):\n        super().__init__()\n        self.in_channels = in_channels\n        self.head_size = head_size\n        self.att_size = in_channels // head_size\n        assert (in_channels % head_size == 0), 'The size of head should be divided by the number of channels.'\n\n        self.norm1 = Normalize(in_channels)\n        self.norm2 = Normalize(in_channels)\n\n        self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)\n        self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)\n        self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)\n        self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)\n        self.num = 0\n\n    def forward(self, x, y=None):\n        h_ = x\n        h_ = self.norm1(h_)\n        if y is None:\n            y = h_\n        else:\n            y = self.norm2(y)\n\n        q = self.q(y)\n        k = self.k(h_)\n        v = self.v(h_)\n\n        # compute attention\n        b, c, h, w = q.shape\n        q = q.reshape(b, self.head_size, self.att_size, h * w)\n        q = q.permute(0, 3, 1, 2)  # b, hw, head, att\n\n        k = k.reshape(b, self.head_size, self.att_size, h * w)\n        k = k.permute(0, 3, 1, 2)\n\n        v = v.reshape(b, self.head_size, self.att_size, h * w)\n        v = v.permute(0, 3, 1, 2)\n\n        q = q.transpose(1, 2)\n        v = v.transpose(1, 2)\n        k = k.transpose(1, 2).transpose(2, 3)\n\n        scale = int(self.att_size)**(-0.5)\n        q.mul_(scale)\n        w_ = torch.matmul(q, k)\n        w_ = F.softmax(w_, dim=3)\n\n        w_ = w_.matmul(v)\n\n        w_ = w_.transpose(1, 2).contiguous()  # [b, h*w, head, att]\n        w_ = w_.view(b, h, w, -1)\n        w_ = w_.permute(0, 3, 1, 2)\n\n        w_ = self.proj_out(w_)\n\n        return x + w_\n\n\nclass MultiHeadEncoder(nn.Module):\n\n    def __init__(self,\n                 ch,\n                 out_ch,\n                 ch_mult=(1, 2, 4, 8),\n                 num_res_blocks=2,\n                 attn_resolutions=(16, ),\n                 dropout=0.0,\n                 resamp_with_conv=True,\n                 in_channels=3,\n                 resolution=512,\n                 z_channels=256,\n                 double_z=True,\n                 enable_mid=True,\n                 head_size=1,\n                 **ignore_kwargs):\n        super().__init__()\n        self.ch = ch\n        self.temb_ch = 0\n        self.num_resolutions = len(ch_mult)\n        self.num_res_blocks = num_res_blocks\n        self.resolution = resolution\n        self.in_channels = in_channels\n        self.enable_mid = enable_mid\n\n        # downsampling\n        self.conv_in = torch.nn.Conv2d(in_channels, self.ch, kernel_size=3, stride=1, padding=1)\n\n        curr_res = resolution\n        in_ch_mult = (1, ) + tuple(ch_mult)\n        self.down = nn.ModuleList()\n        for i_level in range(self.num_resolutions):\n            block = nn.ModuleList()\n            attn = nn.ModuleList()\n            block_in = ch * in_ch_mult[i_level]\n            block_out = ch * ch_mult[i_level]\n            for i_block in range(self.num_res_blocks):\n                block.append(\n                    ResnetBlock(\n                        in_channels=block_in, out_channels=block_out, temb_channels=self.temb_ch, dropout=dropout))\n                block_in = block_out\n                if curr_res in attn_resolutions:\n                    attn.append(MultiHeadAttnBlock(block_in, head_size))\n            down = nn.Module()\n            down.block = block\n            down.attn = attn\n            if i_level != self.num_resolutions - 1:\n                down.downsample = Downsample(block_in, resamp_with_conv)\n                curr_res = curr_res // 2\n            self.down.append(down)\n\n        # middle\n        if self.enable_mid:\n            self.mid = nn.Module()\n            self.mid.block_1 = ResnetBlock(\n                in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout)\n            self.mid.attn_1 = MultiHeadAttnBlock(block_in, head_size)\n            self.mid.block_2 = ResnetBlock(\n                in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout)\n\n        # end\n        self.norm_out = Normalize(block_in)\n        self.conv_out = torch.nn.Conv2d(\n            block_in, 2 * z_channels if double_z else z_channels, kernel_size=3, stride=1, padding=1)\n\n    def forward(self, x):\n        hs = {}\n        # timestep embedding\n        temb = None\n\n        # downsampling\n        h = self.conv_in(x)\n        hs['in'] = h\n        for i_level in range(self.num_resolutions):\n            for i_block in range(self.num_res_blocks):\n                h = self.down[i_level].block[i_block](h, temb)\n                if len(self.down[i_level].attn) > 0:\n                    h = self.down[i_level].attn[i_block](h)\n\n            if i_level != self.num_resolutions - 1:\n                # hs.append(h)\n                hs['block_' + str(i_level)] = h\n                h = self.down[i_level].downsample(h)\n\n        # middle\n        # h = hs[-1]\n        if self.enable_mid:\n            h = self.mid.block_1(h, temb)\n            hs['block_' + str(i_level) + '_atten'] = h\n            h = self.mid.attn_1(h)\n            h = self.mid.block_2(h, temb)\n            hs['mid_atten'] = h\n\n        # end\n        h = self.norm_out(h)\n        h = nonlinearity(h)\n        h = self.conv_out(h)\n        # hs.append(h)\n        hs['out'] = h\n\n        return hs\n\n\nclass MultiHeadDecoder(nn.Module):\n\n    def __init__(self,\n                 ch,\n                 out_ch,\n                 ch_mult=(1, 2, 4, 8),\n                 num_res_blocks=2,\n                 attn_resolutions=(16, ),\n                 dropout=0.0,\n                 resamp_with_conv=True,\n                 in_channels=3,\n                 resolution=512,\n                 z_channels=256,\n                 give_pre_end=False,\n                 enable_mid=True,\n                 head_size=1,\n                 **ignorekwargs):\n        super().__init__()\n        self.ch = ch\n        self.temb_ch = 0\n        self.num_resolutions = len(ch_mult)\n        self.num_res_blocks = num_res_blocks\n        self.resolution = resolution\n        self.in_channels = in_channels\n        self.give_pre_end = give_pre_end\n        self.enable_mid = enable_mid\n\n        # compute in_ch_mult, block_in and curr_res at lowest res\n        block_in = ch * ch_mult[self.num_resolutions - 1]\n        curr_res = resolution // 2**(self.num_resolutions - 1)\n        self.z_shape = (1, z_channels, curr_res, curr_res)\n        print('Working with z of shape {} = {} dimensions.'.format(self.z_shape, np.prod(self.z_shape)))\n\n        # z to block_in\n        self.conv_in = torch.nn.Conv2d(z_channels, block_in, kernel_size=3, stride=1, padding=1)\n\n        # middle\n        if self.enable_mid:\n            self.mid = nn.Module()\n            self.mid.block_1 = ResnetBlock(\n                in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout)\n            self.mid.attn_1 = MultiHeadAttnBlock(block_in, head_size)\n            self.mid.block_2 = ResnetBlock(\n                in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout)\n\n        # upsampling\n        self.up = nn.ModuleList()\n        for i_level in reversed(range(self.num_resolutions)):\n            block = nn.ModuleList()\n            attn = nn.ModuleList()\n            block_out = ch * ch_mult[i_level]\n            for i_block in range(self.num_res_blocks + 1):\n                block.append(\n                    ResnetBlock(\n                        in_channels=block_in, out_channels=block_out, temb_channels=self.temb_ch, dropout=dropout))\n                block_in = block_out\n                if curr_res in attn_resolutions:\n                    attn.append(MultiHeadAttnBlock(block_in, head_size))\n            up = nn.Module()\n            up.block = block\n            up.attn = attn\n            if i_level != 0:\n                up.upsample = Upsample(block_in, resamp_with_conv)\n                curr_res = curr_res * 2\n            self.up.insert(0, up)  # prepend to get consistent order\n\n        # end\n        self.norm_out = Normalize(block_in)\n        self.conv_out = torch.nn.Conv2d(block_in, out_ch, kernel_size=3, stride=1, padding=1)\n\n    def forward(self, z):\n        # assert z.shape[1:] == self.z_shape[1:]\n        self.last_z_shape = z.shape\n\n        # timestep embedding\n        temb = None\n\n        # z to block_in\n        h = self.conv_in(z)\n\n        # middle\n        if self.enable_mid:\n            h = self.mid.block_1(h, temb)\n            h = self.mid.attn_1(h)\n            h = self.mid.block_2(h, temb)\n\n        # upsampling\n        for i_level in reversed(range(self.num_resolutions)):\n            for i_block in range(self.num_res_blocks + 1):\n                h = self.up[i_level].block[i_block](h, temb)\n                if len(self.up[i_level].attn) > 0:\n                    h = self.up[i_level].attn[i_block](h)\n            if i_level != 0:\n                h = self.up[i_level].upsample(h)\n\n        # end\n        if self.give_pre_end:\n            return h\n\n        h = self.norm_out(h)\n        h = nonlinearity(h)\n        h = self.conv_out(h)\n        return h\n\n\nclass MultiHeadDecoderTransformer(nn.Module):\n\n    def __init__(self,\n                 ch,\n                 out_ch,\n                 ch_mult=(1, 2, 4, 8),\n                 num_res_blocks=2,\n                 attn_resolutions=(16, ),\n                 dropout=0.0,\n                 resamp_with_conv=True,\n                 in_channels=3,\n                 resolution=512,\n                 z_channels=256,\n                 give_pre_end=False,\n                 enable_mid=True,\n                 head_size=1,\n                 **ignorekwargs):\n        super().__init__()\n        self.ch = ch\n        self.temb_ch = 0\n        self.num_resolutions = len(ch_mult)\n        self.num_res_blocks = num_res_blocks\n        self.resolution = resolution\n        self.in_channels = in_channels\n        self.give_pre_end = give_pre_end\n        self.enable_mid = enable_mid\n\n        # compute in_ch_mult, block_in and curr_res at lowest res\n        block_in = ch * ch_mult[self.num_resolutions - 1]\n        curr_res = resolution // 2**(self.num_resolutions - 1)\n        self.z_shape = (1, z_channels, curr_res, curr_res)\n        print('Working with z of shape {} = {} dimensions.'.format(self.z_shape, np.prod(self.z_shape)))\n\n        # z to block_in\n        self.conv_in = torch.nn.Conv2d(z_channels, block_in, kernel_size=3, stride=1, padding=1)\n\n        # middle\n        if self.enable_mid:\n            self.mid = nn.Module()\n            self.mid.block_1 = ResnetBlock(\n                in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout)\n            self.mid.attn_1 = MultiHeadAttnBlock(block_in, head_size)\n            self.mid.block_2 = ResnetBlock(\n                in_channels=block_in, out_channels=block_in, temb_channels=self.temb_ch, dropout=dropout)\n\n        # upsampling\n        self.up = nn.ModuleList()\n        for i_level in reversed(range(self.num_resolutions)):\n            block = nn.ModuleList()\n            attn = nn.ModuleList()\n            block_out = ch * ch_mult[i_level]\n            for i_block in range(self.num_res_blocks + 1):\n                block.append(\n                    ResnetBlock(\n                        in_channels=block_in, out_channels=block_out, temb_channels=self.temb_ch, dropout=dropout))\n                block_in = block_out\n                if curr_res in attn_resolutions:\n                    attn.append(MultiHeadAttnBlock(block_in, head_size))\n            up = nn.Module()\n            up.block = block\n            up.attn = attn\n            if i_level != 0:\n                up.upsample = Upsample(block_in, resamp_with_conv)\n                curr_res = curr_res * 2\n            self.up.insert(0, up)  # prepend to get consistent order\n\n        # end\n        self.norm_out = Normalize(block_in)\n        self.conv_out = torch.nn.Conv2d(block_in, out_ch, kernel_size=3, stride=1, padding=1)\n\n    def forward(self, z, hs):\n        # assert z.shape[1:] == self.z_shape[1:]\n        # self.last_z_shape = z.shape\n\n        # timestep embedding\n        temb = None\n\n        # z to block_in\n        h = self.conv_in(z)\n\n        # middle\n        if self.enable_mid:\n            h = self.mid.block_1(h, temb)\n            h = self.mid.attn_1(h, hs['mid_atten'])\n            h = self.mid.block_2(h, temb)\n\n        # upsampling\n        for i_level in reversed(range(self.num_resolutions)):\n            for i_block in range(self.num_res_blocks + 1):\n                h = self.up[i_level].block[i_block](h, temb)\n                if len(self.up[i_level].attn) > 0:\n                    h = self.up[i_level].attn[i_block](h, hs['block_' + str(i_level) + '_atten'])\n                    # hfeature = h.clone()\n            if i_level != 0:\n                h = self.up[i_level].upsample(h)\n\n        # end\n        if self.give_pre_end:\n            return h\n\n        h = self.norm_out(h)\n        h = nonlinearity(h)\n        h = self.conv_out(h)\n        return h\n\n\nclass RestoreFormer(nn.Module):\n\n    def __init__(self,\n                 n_embed=1024,\n                 embed_dim=256,\n                 ch=64,\n                 out_ch=3,\n                 ch_mult=(1, 2, 2, 4, 4, 8),\n                 num_res_blocks=2,\n                 attn_resolutions=(16, ),\n                 dropout=0.0,\n                 in_channels=3,\n                 resolution=512,\n                 z_channels=256,\n                 double_z=False,\n                 enable_mid=True,\n                 fix_decoder=False,\n                 fix_codebook=True,\n                 fix_encoder=False,\n                 head_size=8):\n        super(RestoreFormer, self).__init__()\n\n        self.encoder = MultiHeadEncoder(\n            ch=ch,\n            out_ch=out_ch,\n            ch_mult=ch_mult,\n            num_res_blocks=num_res_blocks,\n            attn_resolutions=attn_resolutions,\n            dropout=dropout,\n            in_channels=in_channels,\n            resolution=resolution,\n            z_channels=z_channels,\n            double_z=double_z,\n            enable_mid=enable_mid,\n            head_size=head_size)\n        self.decoder = MultiHeadDecoderTransformer(\n            ch=ch,\n            out_ch=out_ch,\n            ch_mult=ch_mult,\n            num_res_blocks=num_res_blocks,\n            attn_resolutions=attn_resolutions,\n            dropout=dropout,\n            in_channels=in_channels,\n            resolution=resolution,\n            z_channels=z_channels,\n            enable_mid=enable_mid,\n            head_size=head_size)\n\n        self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25)\n\n        self.quant_conv = torch.nn.Conv2d(z_channels, embed_dim, 1)\n        self.post_quant_conv = torch.nn.Conv2d(embed_dim, z_channels, 1)\n\n        if fix_decoder:\n            for _, param in self.decoder.named_parameters():\n                param.requires_grad = False\n            for _, param in self.post_quant_conv.named_parameters():\n                param.requires_grad = False\n            for _, param in self.quantize.named_parameters():\n                param.requires_grad = False\n        elif fix_codebook:\n            for _, param in self.quantize.named_parameters():\n                param.requires_grad = False\n\n        if fix_encoder:\n            for _, param in self.encoder.named_parameters():\n                param.requires_grad = False\n\n    def encode(self, x):\n\n        hs = self.encoder(x)\n        h = self.quant_conv(hs['out'])\n        quant, emb_loss, info = self.quantize(h)\n        return quant, emb_loss, info, hs\n\n    def decode(self, quant, hs):\n        quant = self.post_quant_conv(quant)\n        dec = self.decoder(quant, hs)\n\n        return dec\n\n    def forward(self, input, **kwargs):\n        quant, diff, info, hs = self.encode(input)\n        dec = self.decode(quant, hs)\n\n        return dec, None\n"
  },
  {
    "path": "gfpgan/archs/stylegan2_bilinear_arch.py",
    "content": "import math\nimport random\nimport torch\nfrom basicsr.ops.fused_act import FusedLeakyReLU, fused_leaky_relu\nfrom basicsr.utils.registry import ARCH_REGISTRY\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\nclass NormStyleCode(nn.Module):\n\n    def forward(self, x):\n        \"\"\"Normalize the style codes.\n\n        Args:\n            x (Tensor): Style codes with shape (b, c).\n\n        Returns:\n            Tensor: Normalized tensor.\n        \"\"\"\n        return x * torch.rsqrt(torch.mean(x**2, dim=1, keepdim=True) + 1e-8)\n\n\nclass EqualLinear(nn.Module):\n    \"\"\"Equalized Linear as StyleGAN2.\n\n    Args:\n        in_channels (int): Size of each sample.\n        out_channels (int): Size of each output sample.\n        bias (bool): If set to ``False``, the layer will not learn an additive\n            bias. Default: ``True``.\n        bias_init_val (float): Bias initialized value. Default: 0.\n        lr_mul (float): Learning rate multiplier. Default: 1.\n        activation (None | str): The activation after ``linear`` operation.\n            Supported: 'fused_lrelu', None. Default: None.\n    \"\"\"\n\n    def __init__(self, in_channels, out_channels, bias=True, bias_init_val=0, lr_mul=1, activation=None):\n        super(EqualLinear, self).__init__()\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.lr_mul = lr_mul\n        self.activation = activation\n        if self.activation not in ['fused_lrelu', None]:\n            raise ValueError(f'Wrong activation value in EqualLinear: {activation}'\n                             \"Supported ones are: ['fused_lrelu', None].\")\n        self.scale = (1 / math.sqrt(in_channels)) * lr_mul\n\n        self.weight = nn.Parameter(torch.randn(out_channels, in_channels).div_(lr_mul))\n        if bias:\n            self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val))\n        else:\n            self.register_parameter('bias', None)\n\n    def forward(self, x):\n        if self.bias is None:\n            bias = None\n        else:\n            bias = self.bias * self.lr_mul\n        if self.activation == 'fused_lrelu':\n            out = F.linear(x, self.weight * self.scale)\n            out = fused_leaky_relu(out, bias)\n        else:\n            out = F.linear(x, self.weight * self.scale, bias=bias)\n        return out\n\n    def __repr__(self):\n        return (f'{self.__class__.__name__}(in_channels={self.in_channels}, '\n                f'out_channels={self.out_channels}, bias={self.bias is not None})')\n\n\nclass ModulatedConv2d(nn.Module):\n    \"\"\"Modulated Conv2d used in StyleGAN2.\n\n    There is no bias in ModulatedConv2d.\n\n    Args:\n        in_channels (int): Channel number of the input.\n        out_channels (int): Channel number of the output.\n        kernel_size (int): Size of the convolving kernel.\n        num_style_feat (int): Channel number of style features.\n        demodulate (bool): Whether to demodulate in the conv layer.\n            Default: True.\n        sample_mode (str | None): Indicating 'upsample', 'downsample' or None.\n            Default: None.\n        eps (float): A value added to the denominator for numerical stability.\n            Default: 1e-8.\n    \"\"\"\n\n    def __init__(self,\n                 in_channels,\n                 out_channels,\n                 kernel_size,\n                 num_style_feat,\n                 demodulate=True,\n                 sample_mode=None,\n                 eps=1e-8,\n                 interpolation_mode='bilinear'):\n        super(ModulatedConv2d, self).__init__()\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.kernel_size = kernel_size\n        self.demodulate = demodulate\n        self.sample_mode = sample_mode\n        self.eps = eps\n        self.interpolation_mode = interpolation_mode\n        if self.interpolation_mode == 'nearest':\n            self.align_corners = None\n        else:\n            self.align_corners = False\n\n        self.scale = 1 / math.sqrt(in_channels * kernel_size**2)\n        # modulation inside each modulated conv\n        self.modulation = EqualLinear(\n            num_style_feat, in_channels, bias=True, bias_init_val=1, lr_mul=1, activation=None)\n\n        self.weight = nn.Parameter(torch.randn(1, out_channels, in_channels, kernel_size, kernel_size))\n        self.padding = kernel_size // 2\n\n    def forward(self, x, style):\n        \"\"\"Forward function.\n\n        Args:\n            x (Tensor): Tensor with shape (b, c, h, w).\n            style (Tensor): Tensor with shape (b, num_style_feat).\n\n        Returns:\n            Tensor: Modulated tensor after convolution.\n        \"\"\"\n        b, c, h, w = x.shape  # c = c_in\n        # weight modulation\n        style = self.modulation(style).view(b, 1, c, 1, 1)\n        # self.weight: (1, c_out, c_in, k, k); style: (b, 1, c, 1, 1)\n        weight = self.scale * self.weight * style  # (b, c_out, c_in, k, k)\n\n        if self.demodulate:\n            demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + self.eps)\n            weight = weight * demod.view(b, self.out_channels, 1, 1, 1)\n\n        weight = weight.view(b * self.out_channels, c, self.kernel_size, self.kernel_size)\n\n        if self.sample_mode == 'upsample':\n            x = F.interpolate(x, scale_factor=2, mode=self.interpolation_mode, align_corners=self.align_corners)\n        elif self.sample_mode == 'downsample':\n            x = F.interpolate(x, scale_factor=0.5, mode=self.interpolation_mode, align_corners=self.align_corners)\n\n        b, c, h, w = x.shape\n        x = x.view(1, b * c, h, w)\n        # weight: (b*c_out, c_in, k, k), groups=b\n        out = F.conv2d(x, weight, padding=self.padding, groups=b)\n        out = out.view(b, self.out_channels, *out.shape[2:4])\n\n        return out\n\n    def __repr__(self):\n        return (f'{self.__class__.__name__}(in_channels={self.in_channels}, '\n                f'out_channels={self.out_channels}, '\n                f'kernel_size={self.kernel_size}, '\n                f'demodulate={self.demodulate}, sample_mode={self.sample_mode})')\n\n\nclass StyleConv(nn.Module):\n    \"\"\"Style conv.\n\n    Args:\n        in_channels (int): Channel number of the input.\n        out_channels (int): Channel number of the output.\n        kernel_size (int): Size of the convolving kernel.\n        num_style_feat (int): Channel number of style features.\n        demodulate (bool): Whether demodulate in the conv layer. Default: True.\n        sample_mode (str | None): Indicating 'upsample', 'downsample' or None.\n            Default: None.\n    \"\"\"\n\n    def __init__(self,\n                 in_channels,\n                 out_channels,\n                 kernel_size,\n                 num_style_feat,\n                 demodulate=True,\n                 sample_mode=None,\n                 interpolation_mode='bilinear'):\n        super(StyleConv, self).__init__()\n        self.modulated_conv = ModulatedConv2d(\n            in_channels,\n            out_channels,\n            kernel_size,\n            num_style_feat,\n            demodulate=demodulate,\n            sample_mode=sample_mode,\n            interpolation_mode=interpolation_mode)\n        self.weight = nn.Parameter(torch.zeros(1))  # for noise injection\n        self.activate = FusedLeakyReLU(out_channels)\n\n    def forward(self, x, style, noise=None):\n        # modulate\n        out = self.modulated_conv(x, style)\n        # noise injection\n        if noise is None:\n            b, _, h, w = out.shape\n            noise = out.new_empty(b, 1, h, w).normal_()\n        out = out + self.weight * noise\n        # activation (with bias)\n        out = self.activate(out)\n        return out\n\n\nclass ToRGB(nn.Module):\n    \"\"\"To RGB from features.\n\n    Args:\n        in_channels (int): Channel number of input.\n        num_style_feat (int): Channel number of style features.\n        upsample (bool): Whether to upsample. Default: True.\n    \"\"\"\n\n    def __init__(self, in_channels, num_style_feat, upsample=True, interpolation_mode='bilinear'):\n        super(ToRGB, self).__init__()\n        self.upsample = upsample\n        self.interpolation_mode = interpolation_mode\n        if self.interpolation_mode == 'nearest':\n            self.align_corners = None\n        else:\n            self.align_corners = False\n        self.modulated_conv = ModulatedConv2d(\n            in_channels,\n            3,\n            kernel_size=1,\n            num_style_feat=num_style_feat,\n            demodulate=False,\n            sample_mode=None,\n            interpolation_mode=interpolation_mode)\n        self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1))\n\n    def forward(self, x, style, skip=None):\n        \"\"\"Forward function.\n\n        Args:\n            x (Tensor): Feature tensor with shape (b, c, h, w).\n            style (Tensor): Tensor with shape (b, num_style_feat).\n            skip (Tensor): Base/skip tensor. Default: None.\n\n        Returns:\n            Tensor: RGB images.\n        \"\"\"\n        out = self.modulated_conv(x, style)\n        out = out + self.bias\n        if skip is not None:\n            if self.upsample:\n                skip = F.interpolate(\n                    skip, scale_factor=2, mode=self.interpolation_mode, align_corners=self.align_corners)\n            out = out + skip\n        return out\n\n\nclass ConstantInput(nn.Module):\n    \"\"\"Constant input.\n\n    Args:\n        num_channel (int): Channel number of constant input.\n        size (int): Spatial size of constant input.\n    \"\"\"\n\n    def __init__(self, num_channel, size):\n        super(ConstantInput, self).__init__()\n        self.weight = nn.Parameter(torch.randn(1, num_channel, size, size))\n\n    def forward(self, batch):\n        out = self.weight.repeat(batch, 1, 1, 1)\n        return out\n\n\n@ARCH_REGISTRY.register()\nclass StyleGAN2GeneratorBilinear(nn.Module):\n    \"\"\"StyleGAN2 Generator.\n\n    Args:\n        out_size (int): The spatial size of outputs.\n        num_style_feat (int): Channel number of style features. Default: 512.\n        num_mlp (int): Layer number of MLP style layers. Default: 8.\n        channel_multiplier (int): Channel multiplier for large networks of\n            StyleGAN2. Default: 2.\n        lr_mlp (float): Learning rate multiplier for mlp layers. Default: 0.01.\n        narrow (float): Narrow ratio for channels. Default: 1.0.\n    \"\"\"\n\n    def __init__(self,\n                 out_size,\n                 num_style_feat=512,\n                 num_mlp=8,\n                 channel_multiplier=2,\n                 lr_mlp=0.01,\n                 narrow=1,\n                 interpolation_mode='bilinear'):\n        super(StyleGAN2GeneratorBilinear, self).__init__()\n        # Style MLP layers\n        self.num_style_feat = num_style_feat\n        style_mlp_layers = [NormStyleCode()]\n        for i in range(num_mlp):\n            style_mlp_layers.append(\n                EqualLinear(\n                    num_style_feat, num_style_feat, bias=True, bias_init_val=0, lr_mul=lr_mlp,\n                    activation='fused_lrelu'))\n        self.style_mlp = nn.Sequential(*style_mlp_layers)\n\n        channels = {\n            '4': int(512 * narrow),\n            '8': int(512 * narrow),\n            '16': int(512 * narrow),\n            '32': int(512 * narrow),\n            '64': int(256 * channel_multiplier * narrow),\n            '128': int(128 * channel_multiplier * narrow),\n            '256': int(64 * channel_multiplier * narrow),\n            '512': int(32 * channel_multiplier * narrow),\n            '1024': int(16 * channel_multiplier * narrow)\n        }\n        self.channels = channels\n\n        self.constant_input = ConstantInput(channels['4'], size=4)\n        self.style_conv1 = StyleConv(\n            channels['4'],\n            channels['4'],\n            kernel_size=3,\n            num_style_feat=num_style_feat,\n            demodulate=True,\n            sample_mode=None,\n            interpolation_mode=interpolation_mode)\n        self.to_rgb1 = ToRGB(channels['4'], num_style_feat, upsample=False, interpolation_mode=interpolation_mode)\n\n        self.log_size = int(math.log(out_size, 2))\n        self.num_layers = (self.log_size - 2) * 2 + 1\n        self.num_latent = self.log_size * 2 - 2\n\n        self.style_convs = nn.ModuleList()\n        self.to_rgbs = nn.ModuleList()\n        self.noises = nn.Module()\n\n        in_channels = channels['4']\n        # noise\n        for layer_idx in range(self.num_layers):\n            resolution = 2**((layer_idx + 5) // 2)\n            shape = [1, 1, resolution, resolution]\n            self.noises.register_buffer(f'noise{layer_idx}', torch.randn(*shape))\n        # style convs and to_rgbs\n        for i in range(3, self.log_size + 1):\n            out_channels = channels[f'{2**i}']\n            self.style_convs.append(\n                StyleConv(\n                    in_channels,\n                    out_channels,\n                    kernel_size=3,\n                    num_style_feat=num_style_feat,\n                    demodulate=True,\n                    sample_mode='upsample',\n                    interpolation_mode=interpolation_mode))\n            self.style_convs.append(\n                StyleConv(\n                    out_channels,\n                    out_channels,\n                    kernel_size=3,\n                    num_style_feat=num_style_feat,\n                    demodulate=True,\n                    sample_mode=None,\n                    interpolation_mode=interpolation_mode))\n            self.to_rgbs.append(\n                ToRGB(out_channels, num_style_feat, upsample=True, interpolation_mode=interpolation_mode))\n            in_channels = out_channels\n\n    def make_noise(self):\n        \"\"\"Make noise for noise injection.\"\"\"\n        device = self.constant_input.weight.device\n        noises = [torch.randn(1, 1, 4, 4, device=device)]\n\n        for i in range(3, self.log_size + 1):\n            for _ in range(2):\n                noises.append(torch.randn(1, 1, 2**i, 2**i, device=device))\n\n        return noises\n\n    def get_latent(self, x):\n        return self.style_mlp(x)\n\n    def mean_latent(self, num_latent):\n        latent_in = torch.randn(num_latent, self.num_style_feat, device=self.constant_input.weight.device)\n        latent = self.style_mlp(latent_in).mean(0, keepdim=True)\n        return latent\n\n    def forward(self,\n                styles,\n                input_is_latent=False,\n                noise=None,\n                randomize_noise=True,\n                truncation=1,\n                truncation_latent=None,\n                inject_index=None,\n                return_latents=False):\n        \"\"\"Forward function for StyleGAN2Generator.\n\n        Args:\n            styles (list[Tensor]): Sample codes of styles.\n            input_is_latent (bool): Whether input is latent style.\n                Default: False.\n            noise (Tensor | None): Input noise or None. Default: None.\n            randomize_noise (bool): Randomize noise, used when 'noise' is\n                False. Default: True.\n            truncation (float): TODO. Default: 1.\n            truncation_latent (Tensor | None): TODO. Default: None.\n            inject_index (int | None): The injection index for mixing noise.\n                Default: None.\n            return_latents (bool): Whether to return style latents.\n                Default: False.\n        \"\"\"\n        # style codes -> latents with Style MLP layer\n        if not input_is_latent:\n            styles = [self.style_mlp(s) for s in styles]\n        # noises\n        if noise is None:\n            if randomize_noise:\n                noise = [None] * self.num_layers  # for each style conv layer\n            else:  # use the stored noise\n                noise = [getattr(self.noises, f'noise{i}') for i in range(self.num_layers)]\n        # style truncation\n        if truncation < 1:\n            style_truncation = []\n            for style in styles:\n                style_truncation.append(truncation_latent + truncation * (style - truncation_latent))\n            styles = style_truncation\n        # get style latent with injection\n        if len(styles) == 1:\n            inject_index = self.num_latent\n\n            if styles[0].ndim < 3:\n                # repeat latent code for all the layers\n                latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)\n            else:  # used for encoder with different latent code for each layer\n                latent = styles[0]\n        elif len(styles) == 2:  # mixing noises\n            if inject_index is None:\n                inject_index = random.randint(1, self.num_latent - 1)\n            latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1)\n            latent2 = styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1)\n            latent = torch.cat([latent1, latent2], 1)\n\n        # main generation\n        out = self.constant_input(latent.shape[0])\n        out = self.style_conv1(out, latent[:, 0], noise=noise[0])\n        skip = self.to_rgb1(out, latent[:, 1])\n\n        i = 1\n        for conv1, conv2, noise1, noise2, to_rgb in zip(self.style_convs[::2], self.style_convs[1::2], noise[1::2],\n                                                        noise[2::2], self.to_rgbs):\n            out = conv1(out, latent[:, i], noise=noise1)\n            out = conv2(out, latent[:, i + 1], noise=noise2)\n            skip = to_rgb(out, latent[:, i + 2], skip)\n            i += 2\n\n        image = skip\n\n        if return_latents:\n            return image, latent\n        else:\n            return image, None\n\n\nclass ScaledLeakyReLU(nn.Module):\n    \"\"\"Scaled LeakyReLU.\n\n    Args:\n        negative_slope (float): Negative slope. Default: 0.2.\n    \"\"\"\n\n    def __init__(self, negative_slope=0.2):\n        super(ScaledLeakyReLU, self).__init__()\n        self.negative_slope = negative_slope\n\n    def forward(self, x):\n        out = F.leaky_relu(x, negative_slope=self.negative_slope)\n        return out * math.sqrt(2)\n\n\nclass EqualConv2d(nn.Module):\n    \"\"\"Equalized Linear as StyleGAN2.\n\n    Args:\n        in_channels (int): Channel number of the input.\n        out_channels (int): Channel number of the output.\n        kernel_size (int): Size of the convolving kernel.\n        stride (int): Stride of the convolution. Default: 1\n        padding (int): Zero-padding added to both sides of the input.\n            Default: 0.\n        bias (bool): If ``True``, adds a learnable bias to the output.\n            Default: ``True``.\n        bias_init_val (float): Bias initialized value. Default: 0.\n    \"\"\"\n\n    def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, bias=True, bias_init_val=0):\n        super(EqualConv2d, self).__init__()\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.kernel_size = kernel_size\n        self.stride = stride\n        self.padding = padding\n        self.scale = 1 / math.sqrt(in_channels * kernel_size**2)\n\n        self.weight = nn.Parameter(torch.randn(out_channels, in_channels, kernel_size, kernel_size))\n        if bias:\n            self.bias = nn.Parameter(torch.zeros(out_channels).fill_(bias_init_val))\n        else:\n            self.register_parameter('bias', None)\n\n    def forward(self, x):\n        out = F.conv2d(\n            x,\n            self.weight * self.scale,\n            bias=self.bias,\n            stride=self.stride,\n            padding=self.padding,\n        )\n\n        return out\n\n    def __repr__(self):\n        return (f'{self.__class__.__name__}(in_channels={self.in_channels}, '\n                f'out_channels={self.out_channels}, '\n                f'kernel_size={self.kernel_size},'\n                f' stride={self.stride}, padding={self.padding}, '\n                f'bias={self.bias is not None})')\n\n\nclass ConvLayer(nn.Sequential):\n    \"\"\"Conv Layer used in StyleGAN2 Discriminator.\n\n    Args:\n        in_channels (int): Channel number of the input.\n        out_channels (int): Channel number of the output.\n        kernel_size (int): Kernel size.\n        downsample (bool): Whether downsample by a factor of 2.\n            Default: False.\n        bias (bool): Whether with bias. Default: True.\n        activate (bool): Whether use activateion. Default: True.\n    \"\"\"\n\n    def __init__(self,\n                 in_channels,\n                 out_channels,\n                 kernel_size,\n                 downsample=False,\n                 bias=True,\n                 activate=True,\n                 interpolation_mode='bilinear'):\n        layers = []\n        self.interpolation_mode = interpolation_mode\n        # downsample\n        if downsample:\n            if self.interpolation_mode == 'nearest':\n                self.align_corners = None\n            else:\n                self.align_corners = False\n\n            layers.append(\n                torch.nn.Upsample(scale_factor=0.5, mode=interpolation_mode, align_corners=self.align_corners))\n        stride = 1\n        self.padding = kernel_size // 2\n        # conv\n        layers.append(\n            EqualConv2d(\n                in_channels, out_channels, kernel_size, stride=stride, padding=self.padding, bias=bias\n                and not activate))\n        # activation\n        if activate:\n            if bias:\n                layers.append(FusedLeakyReLU(out_channels))\n            else:\n                layers.append(ScaledLeakyReLU(0.2))\n\n        super(ConvLayer, self).__init__(*layers)\n\n\nclass ResBlock(nn.Module):\n    \"\"\"Residual block used in StyleGAN2 Discriminator.\n\n    Args:\n        in_channels (int): Channel number of the input.\n        out_channels (int): Channel number of the output.\n    \"\"\"\n\n    def __init__(self, in_channels, out_channels, interpolation_mode='bilinear'):\n        super(ResBlock, self).__init__()\n\n        self.conv1 = ConvLayer(in_channels, in_channels, 3, bias=True, activate=True)\n        self.conv2 = ConvLayer(\n            in_channels,\n            out_channels,\n            3,\n            downsample=True,\n            interpolation_mode=interpolation_mode,\n            bias=True,\n            activate=True)\n        self.skip = ConvLayer(\n            in_channels,\n            out_channels,\n            1,\n            downsample=True,\n            interpolation_mode=interpolation_mode,\n            bias=False,\n            activate=False)\n\n    def forward(self, x):\n        out = self.conv1(x)\n        out = self.conv2(out)\n        skip = self.skip(x)\n        out = (out + skip) / math.sqrt(2)\n        return out\n"
  },
  {
    "path": "gfpgan/archs/stylegan2_clean_arch.py",
    "content": "import math\nimport random\nimport torch\nfrom basicsr.archs.arch_util import default_init_weights\nfrom basicsr.utils.registry import ARCH_REGISTRY\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\nclass NormStyleCode(nn.Module):\n\n    def forward(self, x):\n        \"\"\"Normalize the style codes.\n\n        Args:\n            x (Tensor): Style codes with shape (b, c).\n\n        Returns:\n            Tensor: Normalized tensor.\n        \"\"\"\n        return x * torch.rsqrt(torch.mean(x**2, dim=1, keepdim=True) + 1e-8)\n\n\nclass ModulatedConv2d(nn.Module):\n    \"\"\"Modulated Conv2d used in StyleGAN2.\n\n    There is no bias in ModulatedConv2d.\n\n    Args:\n        in_channels (int): Channel number of the input.\n        out_channels (int): Channel number of the output.\n        kernel_size (int): Size of the convolving kernel.\n        num_style_feat (int): Channel number of style features.\n        demodulate (bool): Whether to demodulate in the conv layer. Default: True.\n        sample_mode (str | None): Indicating 'upsample', 'downsample' or None. Default: None.\n        eps (float): A value added to the denominator for numerical stability. Default: 1e-8.\n    \"\"\"\n\n    def __init__(self,\n                 in_channels,\n                 out_channels,\n                 kernel_size,\n                 num_style_feat,\n                 demodulate=True,\n                 sample_mode=None,\n                 eps=1e-8):\n        super(ModulatedConv2d, self).__init__()\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.kernel_size = kernel_size\n        self.demodulate = demodulate\n        self.sample_mode = sample_mode\n        self.eps = eps\n\n        # modulation inside each modulated conv\n        self.modulation = nn.Linear(num_style_feat, in_channels, bias=True)\n        # initialization\n        default_init_weights(self.modulation, scale=1, bias_fill=1, a=0, mode='fan_in', nonlinearity='linear')\n\n        self.weight = nn.Parameter(\n            torch.randn(1, out_channels, in_channels, kernel_size, kernel_size) /\n            math.sqrt(in_channels * kernel_size**2))\n        self.padding = kernel_size // 2\n\n    def forward(self, x, style):\n        \"\"\"Forward function.\n\n        Args:\n            x (Tensor): Tensor with shape (b, c, h, w).\n            style (Tensor): Tensor with shape (b, num_style_feat).\n\n        Returns:\n            Tensor: Modulated tensor after convolution.\n        \"\"\"\n        b, c, h, w = x.shape  # c = c_in\n        # weight modulation\n        style = self.modulation(style).view(b, 1, c, 1, 1)\n        # self.weight: (1, c_out, c_in, k, k); style: (b, 1, c, 1, 1)\n        weight = self.weight * style  # (b, c_out, c_in, k, k)\n\n        if self.demodulate:\n            demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + self.eps)\n            weight = weight * demod.view(b, self.out_channels, 1, 1, 1)\n\n        weight = weight.view(b * self.out_channels, c, self.kernel_size, self.kernel_size)\n\n        # upsample or downsample if necessary\n        if self.sample_mode == 'upsample':\n            x = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)\n        elif self.sample_mode == 'downsample':\n            x = F.interpolate(x, scale_factor=0.5, mode='bilinear', align_corners=False)\n\n        b, c, h, w = x.shape\n        x = x.view(1, b * c, h, w)\n        # weight: (b*c_out, c_in, k, k), groups=b\n        out = F.conv2d(x, weight, padding=self.padding, groups=b)\n        out = out.view(b, self.out_channels, *out.shape[2:4])\n\n        return out\n\n    def __repr__(self):\n        return (f'{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, '\n                f'kernel_size={self.kernel_size}, demodulate={self.demodulate}, sample_mode={self.sample_mode})')\n\n\nclass StyleConv(nn.Module):\n    \"\"\"Style conv used in StyleGAN2.\n\n    Args:\n        in_channels (int): Channel number of the input.\n        out_channels (int): Channel number of the output.\n        kernel_size (int): Size of the convolving kernel.\n        num_style_feat (int): Channel number of style features.\n        demodulate (bool): Whether demodulate in the conv layer. Default: True.\n        sample_mode (str | None): Indicating 'upsample', 'downsample' or None. Default: None.\n    \"\"\"\n\n    def __init__(self, in_channels, out_channels, kernel_size, num_style_feat, demodulate=True, sample_mode=None):\n        super(StyleConv, self).__init__()\n        self.modulated_conv = ModulatedConv2d(\n            in_channels, out_channels, kernel_size, num_style_feat, demodulate=demodulate, sample_mode=sample_mode)\n        self.weight = nn.Parameter(torch.zeros(1))  # for noise injection\n        self.bias = nn.Parameter(torch.zeros(1, out_channels, 1, 1))\n        self.activate = nn.LeakyReLU(negative_slope=0.2, inplace=True)\n\n    def forward(self, x, style, noise=None):\n        # modulate\n        out = self.modulated_conv(x, style) * 2**0.5  # for conversion\n        # noise injection\n        if noise is None:\n            b, _, h, w = out.shape\n            noise = out.new_empty(b, 1, h, w).normal_()\n        out = out + self.weight * noise\n        # add bias\n        out = out + self.bias\n        # activation\n        out = self.activate(out)\n        return out\n\n\nclass ToRGB(nn.Module):\n    \"\"\"To RGB (image space) from features.\n\n    Args:\n        in_channels (int): Channel number of input.\n        num_style_feat (int): Channel number of style features.\n        upsample (bool): Whether to upsample. Default: True.\n    \"\"\"\n\n    def __init__(self, in_channels, num_style_feat, upsample=True):\n        super(ToRGB, self).__init__()\n        self.upsample = upsample\n        self.modulated_conv = ModulatedConv2d(\n            in_channels, 3, kernel_size=1, num_style_feat=num_style_feat, demodulate=False, sample_mode=None)\n        self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1))\n\n    def forward(self, x, style, skip=None):\n        \"\"\"Forward function.\n\n        Args:\n            x (Tensor): Feature tensor with shape (b, c, h, w).\n            style (Tensor): Tensor with shape (b, num_style_feat).\n            skip (Tensor): Base/skip tensor. Default: None.\n\n        Returns:\n            Tensor: RGB images.\n        \"\"\"\n        out = self.modulated_conv(x, style)\n        out = out + self.bias\n        if skip is not None:\n            if self.upsample:\n                skip = F.interpolate(skip, scale_factor=2, mode='bilinear', align_corners=False)\n            out = out + skip\n        return out\n\n\nclass ConstantInput(nn.Module):\n    \"\"\"Constant input.\n\n    Args:\n        num_channel (int): Channel number of constant input.\n        size (int): Spatial size of constant input.\n    \"\"\"\n\n    def __init__(self, num_channel, size):\n        super(ConstantInput, self).__init__()\n        self.weight = nn.Parameter(torch.randn(1, num_channel, size, size))\n\n    def forward(self, batch):\n        out = self.weight.repeat(batch, 1, 1, 1)\n        return out\n\n\n@ARCH_REGISTRY.register()\nclass StyleGAN2GeneratorClean(nn.Module):\n    \"\"\"Clean version of StyleGAN2 Generator.\n\n    Args:\n        out_size (int): The spatial size of outputs.\n        num_style_feat (int): Channel number of style features. Default: 512.\n        num_mlp (int): Layer number of MLP style layers. Default: 8.\n        channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.\n        narrow (float): Narrow ratio for channels. Default: 1.0.\n    \"\"\"\n\n    def __init__(self, out_size, num_style_feat=512, num_mlp=8, channel_multiplier=2, narrow=1):\n        super(StyleGAN2GeneratorClean, self).__init__()\n        # Style MLP layers\n        self.num_style_feat = num_style_feat\n        style_mlp_layers = [NormStyleCode()]\n        for i in range(num_mlp):\n            style_mlp_layers.extend(\n                [nn.Linear(num_style_feat, num_style_feat, bias=True),\n                 nn.LeakyReLU(negative_slope=0.2, inplace=True)])\n        self.style_mlp = nn.Sequential(*style_mlp_layers)\n        # initialization\n        default_init_weights(self.style_mlp, scale=1, bias_fill=0, a=0.2, mode='fan_in', nonlinearity='leaky_relu')\n\n        # channel list\n        channels = {\n            '4': int(512 * narrow),\n            '8': int(512 * narrow),\n            '16': int(512 * narrow),\n            '32': int(512 * narrow),\n            '64': int(256 * channel_multiplier * narrow),\n            '128': int(128 * channel_multiplier * narrow),\n            '256': int(64 * channel_multiplier * narrow),\n            '512': int(32 * channel_multiplier * narrow),\n            '1024': int(16 * channel_multiplier * narrow)\n        }\n        self.channels = channels\n\n        self.constant_input = ConstantInput(channels['4'], size=4)\n        self.style_conv1 = StyleConv(\n            channels['4'],\n            channels['4'],\n            kernel_size=3,\n            num_style_feat=num_style_feat,\n            demodulate=True,\n            sample_mode=None)\n        self.to_rgb1 = ToRGB(channels['4'], num_style_feat, upsample=False)\n\n        self.log_size = int(math.log(out_size, 2))\n        self.num_layers = (self.log_size - 2) * 2 + 1\n        self.num_latent = self.log_size * 2 - 2\n\n        self.style_convs = nn.ModuleList()\n        self.to_rgbs = nn.ModuleList()\n        self.noises = nn.Module()\n\n        in_channels = channels['4']\n        # noise\n        for layer_idx in range(self.num_layers):\n            resolution = 2**((layer_idx + 5) // 2)\n            shape = [1, 1, resolution, resolution]\n            self.noises.register_buffer(f'noise{layer_idx}', torch.randn(*shape))\n        # style convs and to_rgbs\n        for i in range(3, self.log_size + 1):\n            out_channels = channels[f'{2**i}']\n            self.style_convs.append(\n                StyleConv(\n                    in_channels,\n                    out_channels,\n                    kernel_size=3,\n                    num_style_feat=num_style_feat,\n                    demodulate=True,\n                    sample_mode='upsample'))\n            self.style_convs.append(\n                StyleConv(\n                    out_channels,\n                    out_channels,\n                    kernel_size=3,\n                    num_style_feat=num_style_feat,\n                    demodulate=True,\n                    sample_mode=None))\n            self.to_rgbs.append(ToRGB(out_channels, num_style_feat, upsample=True))\n            in_channels = out_channels\n\n    def make_noise(self):\n        \"\"\"Make noise for noise injection.\"\"\"\n        device = self.constant_input.weight.device\n        noises = [torch.randn(1, 1, 4, 4, device=device)]\n\n        for i in range(3, self.log_size + 1):\n            for _ in range(2):\n                noises.append(torch.randn(1, 1, 2**i, 2**i, device=device))\n\n        return noises\n\n    def get_latent(self, x):\n        return self.style_mlp(x)\n\n    def mean_latent(self, num_latent):\n        latent_in = torch.randn(num_latent, self.num_style_feat, device=self.constant_input.weight.device)\n        latent = self.style_mlp(latent_in).mean(0, keepdim=True)\n        return latent\n\n    def forward(self,\n                styles,\n                input_is_latent=False,\n                noise=None,\n                randomize_noise=True,\n                truncation=1,\n                truncation_latent=None,\n                inject_index=None,\n                return_latents=False):\n        \"\"\"Forward function for StyleGAN2GeneratorClean.\n\n        Args:\n            styles (list[Tensor]): Sample codes of styles.\n            input_is_latent (bool): Whether input is latent style. Default: False.\n            noise (Tensor | None): Input noise or None. Default: None.\n            randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.\n            truncation (float): The truncation ratio. Default: 1.\n            truncation_latent (Tensor | None): The truncation latent tensor. Default: None.\n            inject_index (int | None): The injection index for mixing noise. Default: None.\n            return_latents (bool): Whether to return style latents. Default: False.\n        \"\"\"\n        # style codes -> latents with Style MLP layer\n        if not input_is_latent:\n            styles = [self.style_mlp(s) for s in styles]\n        # noises\n        if noise is None:\n            if randomize_noise:\n                noise = [None] * self.num_layers  # for each style conv layer\n            else:  # use the stored noise\n                noise = [getattr(self.noises, f'noise{i}') for i in range(self.num_layers)]\n        # style truncation\n        if truncation < 1:\n            style_truncation = []\n            for style in styles:\n                style_truncation.append(truncation_latent + truncation * (style - truncation_latent))\n            styles = style_truncation\n        # get style latents with injection\n        if len(styles) == 1:\n            inject_index = self.num_latent\n\n            if styles[0].ndim < 3:\n                # repeat latent code for all the layers\n                latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)\n            else:  # used for encoder with different latent code for each layer\n                latent = styles[0]\n        elif len(styles) == 2:  # mixing noises\n            if inject_index is None:\n                inject_index = random.randint(1, self.num_latent - 1)\n            latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1)\n            latent2 = styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1)\n            latent = torch.cat([latent1, latent2], 1)\n\n        # main generation\n        out = self.constant_input(latent.shape[0])\n        out = self.style_conv1(out, latent[:, 0], noise=noise[0])\n        skip = self.to_rgb1(out, latent[:, 1])\n\n        i = 1\n        for conv1, conv2, noise1, noise2, to_rgb in zip(self.style_convs[::2], self.style_convs[1::2], noise[1::2],\n                                                        noise[2::2], self.to_rgbs):\n            out = conv1(out, latent[:, i], noise=noise1)\n            out = conv2(out, latent[:, i + 1], noise=noise2)\n            skip = to_rgb(out, latent[:, i + 2], skip)  # feature back to the rgb space\n            i += 2\n\n        image = skip\n\n        if return_latents:\n            return image, latent\n        else:\n            return image, None\n"
  },
  {
    "path": "gfpgan/data/__init__.py",
    "content": "import importlib\nfrom basicsr.utils import scandir\nfrom os import path as osp\n\n# automatically scan and import dataset modules for registry\n# scan all the files that end with '_dataset.py' under the data folder\ndata_folder = osp.dirname(osp.abspath(__file__))\ndataset_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(data_folder) if v.endswith('_dataset.py')]\n# import all the dataset modules\n_dataset_modules = [importlib.import_module(f'gfpgan.data.{file_name}') for file_name in dataset_filenames]\n"
  },
  {
    "path": "gfpgan/data/ffhq_degradation_dataset.py",
    "content": "import cv2\nimport math\nimport numpy as np\nimport os.path as osp\nimport torch\nimport torch.utils.data as data\nfrom basicsr.data import degradations as degradations\nfrom basicsr.data.data_util import paths_from_folder\nfrom basicsr.data.transforms import augment\nfrom basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor\nfrom basicsr.utils.registry import DATASET_REGISTRY\nfrom torchvision.transforms.functional import (adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation,\n                                               normalize)\n\n\n@DATASET_REGISTRY.register()\nclass FFHQDegradationDataset(data.Dataset):\n    \"\"\"FFHQ dataset for GFPGAN.\n\n    It reads high resolution images, and then generate low-quality (LQ) images on-the-fly.\n\n    Args:\n        opt (dict): Config for train datasets. It contains the following keys:\n            dataroot_gt (str): Data root path for gt.\n            io_backend (dict): IO backend type and other kwarg.\n            mean (list | tuple): Image mean.\n            std (list | tuple): Image std.\n            use_hflip (bool): Whether to horizontally flip.\n            Please see more options in the codes.\n    \"\"\"\n\n    def __init__(self, opt):\n        super(FFHQDegradationDataset, self).__init__()\n        self.opt = opt\n        # file client (io backend)\n        self.file_client = None\n        self.io_backend_opt = opt['io_backend']\n\n        self.gt_folder = opt['dataroot_gt']\n        self.mean = opt['mean']\n        self.std = opt['std']\n        self.out_size = opt['out_size']\n\n        self.crop_components = opt.get('crop_components', False)  # facial components\n        self.eye_enlarge_ratio = opt.get('eye_enlarge_ratio', 1)  # whether enlarge eye regions\n\n        if self.crop_components:\n            # load component list from a pre-process pth files\n            self.components_list = torch.load(opt.get('component_path'))\n\n        # file client (lmdb io backend)\n        if self.io_backend_opt['type'] == 'lmdb':\n            self.io_backend_opt['db_paths'] = self.gt_folder\n            if not self.gt_folder.endswith('.lmdb'):\n                raise ValueError(f\"'dataroot_gt' should end with '.lmdb', but received {self.gt_folder}\")\n            with open(osp.join(self.gt_folder, 'meta_info.txt')) as fin:\n                self.paths = [line.split('.')[0] for line in fin]\n        else:\n            # disk backend: scan file list from a folder\n            self.paths = paths_from_folder(self.gt_folder)\n\n        # degradation configurations\n        self.blur_kernel_size = opt['blur_kernel_size']\n        self.kernel_list = opt['kernel_list']\n        self.kernel_prob = opt['kernel_prob']\n        self.blur_sigma = opt['blur_sigma']\n        self.downsample_range = opt['downsample_range']\n        self.noise_range = opt['noise_range']\n        self.jpeg_range = opt['jpeg_range']\n\n        # color jitter\n        self.color_jitter_prob = opt.get('color_jitter_prob')\n        self.color_jitter_pt_prob = opt.get('color_jitter_pt_prob')\n        self.color_jitter_shift = opt.get('color_jitter_shift', 20)\n        # to gray\n        self.gray_prob = opt.get('gray_prob')\n\n        logger = get_root_logger()\n        logger.info(f'Blur: blur_kernel_size {self.blur_kernel_size}, sigma: [{\", \".join(map(str, self.blur_sigma))}]')\n        logger.info(f'Downsample: downsample_range [{\", \".join(map(str, self.downsample_range))}]')\n        logger.info(f'Noise: [{\", \".join(map(str, self.noise_range))}]')\n        logger.info(f'JPEG compression: [{\", \".join(map(str, self.jpeg_range))}]')\n\n        if self.color_jitter_prob is not None:\n            logger.info(f'Use random color jitter. Prob: {self.color_jitter_prob}, shift: {self.color_jitter_shift}')\n        if self.gray_prob is not None:\n            logger.info(f'Use random gray. Prob: {self.gray_prob}')\n        self.color_jitter_shift /= 255.\n\n    @staticmethod\n    def color_jitter(img, shift):\n        \"\"\"jitter color: randomly jitter the RGB values, in numpy formats\"\"\"\n        jitter_val = np.random.uniform(-shift, shift, 3).astype(np.float32)\n        img = img + jitter_val\n        img = np.clip(img, 0, 1)\n        return img\n\n    @staticmethod\n    def color_jitter_pt(img, brightness, contrast, saturation, hue):\n        \"\"\"jitter color: randomly jitter the brightness, contrast, saturation, and hue, in torch Tensor formats\"\"\"\n        fn_idx = torch.randperm(4)\n        for fn_id in fn_idx:\n            if fn_id == 0 and brightness is not None:\n                brightness_factor = torch.tensor(1.0).uniform_(brightness[0], brightness[1]).item()\n                img = adjust_brightness(img, brightness_factor)\n\n            if fn_id == 1 and contrast is not None:\n                contrast_factor = torch.tensor(1.0).uniform_(contrast[0], contrast[1]).item()\n                img = adjust_contrast(img, contrast_factor)\n\n            if fn_id == 2 and saturation is not None:\n                saturation_factor = torch.tensor(1.0).uniform_(saturation[0], saturation[1]).item()\n                img = adjust_saturation(img, saturation_factor)\n\n            if fn_id == 3 and hue is not None:\n                hue_factor = torch.tensor(1.0).uniform_(hue[0], hue[1]).item()\n                img = adjust_hue(img, hue_factor)\n        return img\n\n    def get_component_coordinates(self, index, status):\n        \"\"\"Get facial component (left_eye, right_eye, mouth) coordinates from a pre-loaded pth file\"\"\"\n        components_bbox = self.components_list[f'{index:08d}']\n        if status[0]:  # hflip\n            # exchange right and left eye\n            tmp = components_bbox['left_eye']\n            components_bbox['left_eye'] = components_bbox['right_eye']\n            components_bbox['right_eye'] = tmp\n            # modify the width coordinate\n            components_bbox['left_eye'][0] = self.out_size - components_bbox['left_eye'][0]\n            components_bbox['right_eye'][0] = self.out_size - components_bbox['right_eye'][0]\n            components_bbox['mouth'][0] = self.out_size - components_bbox['mouth'][0]\n\n        # get coordinates\n        locations = []\n        for part in ['left_eye', 'right_eye', 'mouth']:\n            mean = components_bbox[part][0:2]\n            half_len = components_bbox[part][2]\n            if 'eye' in part:\n                half_len *= self.eye_enlarge_ratio\n            loc = np.hstack((mean - half_len + 1, mean + half_len))\n            loc = torch.from_numpy(loc).float()\n            locations.append(loc)\n        return locations\n\n    def __getitem__(self, index):\n        if self.file_client is None:\n            self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt)\n\n        # load gt image\n        # Shape: (h, w, c); channel order: BGR; image range: [0, 1], float32.\n        gt_path = self.paths[index]\n        img_bytes = self.file_client.get(gt_path)\n        img_gt = imfrombytes(img_bytes, float32=True)\n\n        # random horizontal flip\n        img_gt, status = augment(img_gt, hflip=self.opt['use_hflip'], rotation=False, return_status=True)\n        h, w, _ = img_gt.shape\n\n        # get facial component coordinates\n        if self.crop_components:\n            locations = self.get_component_coordinates(index, status)\n            loc_left_eye, loc_right_eye, loc_mouth = locations\n\n        # ------------------------ generate lq image ------------------------ #\n        # blur\n        kernel = degradations.random_mixed_kernels(\n            self.kernel_list,\n            self.kernel_prob,\n            self.blur_kernel_size,\n            self.blur_sigma,\n            self.blur_sigma, [-math.pi, math.pi],\n            noise_range=None)\n        img_lq = cv2.filter2D(img_gt, -1, kernel)\n        # downsample\n        scale = np.random.uniform(self.downsample_range[0], self.downsample_range[1])\n        img_lq = cv2.resize(img_lq, (int(w // scale), int(h // scale)), interpolation=cv2.INTER_LINEAR)\n        # noise\n        if self.noise_range is not None:\n            img_lq = degradations.random_add_gaussian_noise(img_lq, self.noise_range)\n        # jpeg compression\n        if self.jpeg_range is not None:\n            img_lq = degradations.random_add_jpg_compression(img_lq, self.jpeg_range)\n\n        # resize to original size\n        img_lq = cv2.resize(img_lq, (w, h), interpolation=cv2.INTER_LINEAR)\n\n        # random color jitter (only for lq)\n        if self.color_jitter_prob is not None and (np.random.uniform() < self.color_jitter_prob):\n            img_lq = self.color_jitter(img_lq, self.color_jitter_shift)\n        # random to gray (only for lq)\n        if self.gray_prob and np.random.uniform() < self.gray_prob:\n            img_lq = cv2.cvtColor(img_lq, cv2.COLOR_BGR2GRAY)\n            img_lq = np.tile(img_lq[:, :, None], [1, 1, 3])\n            if self.opt.get('gt_gray'):  # whether convert GT to gray images\n                img_gt = cv2.cvtColor(img_gt, cv2.COLOR_BGR2GRAY)\n                img_gt = np.tile(img_gt[:, :, None], [1, 1, 3])  # repeat the color channels\n\n        # BGR to RGB, HWC to CHW, numpy to tensor\n        img_gt, img_lq = img2tensor([img_gt, img_lq], bgr2rgb=True, float32=True)\n\n        # random color jitter (pytorch version) (only for lq)\n        if self.color_jitter_pt_prob is not None and (np.random.uniform() < self.color_jitter_pt_prob):\n            brightness = self.opt.get('brightness', (0.5, 1.5))\n            contrast = self.opt.get('contrast', (0.5, 1.5))\n            saturation = self.opt.get('saturation', (0, 1.5))\n            hue = self.opt.get('hue', (-0.1, 0.1))\n            img_lq = self.color_jitter_pt(img_lq, brightness, contrast, saturation, hue)\n\n        # round and clip\n        img_lq = torch.clamp((img_lq * 255.0).round(), 0, 255) / 255.\n\n        # normalize\n        normalize(img_gt, self.mean, self.std, inplace=True)\n        normalize(img_lq, self.mean, self.std, inplace=True)\n\n        if self.crop_components:\n            return_dict = {\n                'lq': img_lq,\n                'gt': img_gt,\n                'gt_path': gt_path,\n                'loc_left_eye': loc_left_eye,\n                'loc_right_eye': loc_right_eye,\n                'loc_mouth': loc_mouth\n            }\n            return return_dict\n        else:\n            return {'lq': img_lq, 'gt': img_gt, 'gt_path': gt_path}\n\n    def __len__(self):\n        return len(self.paths)\n"
  },
  {
    "path": "gfpgan/models/__init__.py",
    "content": "import importlib\nfrom basicsr.utils import scandir\nfrom os import path as osp\n\n# automatically scan and import model modules for registry\n# scan all the files that end with '_model.py' under the model folder\nmodel_folder = osp.dirname(osp.abspath(__file__))\nmodel_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(model_folder) if v.endswith('_model.py')]\n# import all the model modules\n_model_modules = [importlib.import_module(f'gfpgan.models.{file_name}') for file_name in model_filenames]\n"
  },
  {
    "path": "gfpgan/models/gfpgan_model.py",
    "content": "import math\nimport os.path as osp\nimport torch\nfrom basicsr.archs import build_network\nfrom basicsr.losses import build_loss\nfrom basicsr.losses.gan_loss import r1_penalty\nfrom basicsr.metrics import calculate_metric\nfrom basicsr.models.base_model import BaseModel\nfrom basicsr.utils import get_root_logger, imwrite, tensor2img\nfrom basicsr.utils.registry import MODEL_REGISTRY\nfrom collections import OrderedDict\nfrom torch.nn import functional as F\nfrom torchvision.ops import roi_align\nfrom tqdm import tqdm\n\n\n@MODEL_REGISTRY.register()\nclass GFPGANModel(BaseModel):\n    \"\"\"The GFPGAN model for Towards real-world blind face restoratin with generative facial prior\"\"\"\n\n    def __init__(self, opt):\n        super(GFPGANModel, self).__init__(opt)\n        self.idx = 0  # it is used for saving data for check\n\n        # define network\n        self.net_g = build_network(opt['network_g'])\n        self.net_g = self.model_to_device(self.net_g)\n        self.print_network(self.net_g)\n\n        # load pretrained model\n        load_path = self.opt['path'].get('pretrain_network_g', None)\n        if load_path is not None:\n            param_key = self.opt['path'].get('param_key_g', 'params')\n            self.load_network(self.net_g, load_path, self.opt['path'].get('strict_load_g', True), param_key)\n\n        self.log_size = int(math.log(self.opt['network_g']['out_size'], 2))\n\n        if self.is_train:\n            self.init_training_settings()\n\n    def init_training_settings(self):\n        train_opt = self.opt['train']\n\n        # ----------- define net_d ----------- #\n        self.net_d = build_network(self.opt['network_d'])\n        self.net_d = self.model_to_device(self.net_d)\n        self.print_network(self.net_d)\n        # load pretrained model\n        load_path = self.opt['path'].get('pretrain_network_d', None)\n        if load_path is not None:\n            self.load_network(self.net_d, load_path, self.opt['path'].get('strict_load_d', True))\n\n        # ----------- define net_g with Exponential Moving Average (EMA) ----------- #\n        # net_g_ema only used for testing on one GPU and saving. There is no need to wrap with DistributedDataParallel\n        self.net_g_ema = build_network(self.opt['network_g']).to(self.device)\n        # load pretrained model\n        load_path = self.opt['path'].get('pretrain_network_g', None)\n        if load_path is not None:\n            self.load_network(self.net_g_ema, load_path, self.opt['path'].get('strict_load_g', True), 'params_ema')\n        else:\n            self.model_ema(0)  # copy net_g weight\n\n        self.net_g.train()\n        self.net_d.train()\n        self.net_g_ema.eval()\n\n        # ----------- facial component networks ----------- #\n        if ('network_d_left_eye' in self.opt and 'network_d_right_eye' in self.opt and 'network_d_mouth' in self.opt):\n            self.use_facial_disc = True\n        else:\n            self.use_facial_disc = False\n\n        if self.use_facial_disc:\n            # left eye\n            self.net_d_left_eye = build_network(self.opt['network_d_left_eye'])\n            self.net_d_left_eye = self.model_to_device(self.net_d_left_eye)\n            self.print_network(self.net_d_left_eye)\n            load_path = self.opt['path'].get('pretrain_network_d_left_eye')\n            if load_path is not None:\n                self.load_network(self.net_d_left_eye, load_path, True, 'params')\n            # right eye\n            self.net_d_right_eye = build_network(self.opt['network_d_right_eye'])\n            self.net_d_right_eye = self.model_to_device(self.net_d_right_eye)\n            self.print_network(self.net_d_right_eye)\n            load_path = self.opt['path'].get('pretrain_network_d_right_eye')\n            if load_path is not None:\n                self.load_network(self.net_d_right_eye, load_path, True, 'params')\n            # mouth\n            self.net_d_mouth = build_network(self.opt['network_d_mouth'])\n            self.net_d_mouth = self.model_to_device(self.net_d_mouth)\n            self.print_network(self.net_d_mouth)\n            load_path = self.opt['path'].get('pretrain_network_d_mouth')\n            if load_path is not None:\n                self.load_network(self.net_d_mouth, load_path, True, 'params')\n\n            self.net_d_left_eye.train()\n            self.net_d_right_eye.train()\n            self.net_d_mouth.train()\n\n            # ----------- define facial component gan loss ----------- #\n            self.cri_component = build_loss(train_opt['gan_component_opt']).to(self.device)\n\n        # ----------- define losses ----------- #\n        # pixel loss\n        if train_opt.get('pixel_opt'):\n            self.cri_pix = build_loss(train_opt['pixel_opt']).to(self.device)\n        else:\n            self.cri_pix = None\n\n        # perceptual loss\n        if train_opt.get('perceptual_opt'):\n            self.cri_perceptual = build_loss(train_opt['perceptual_opt']).to(self.device)\n        else:\n            self.cri_perceptual = None\n\n        # L1 loss is used in pyramid loss, component style loss and identity loss\n        self.cri_l1 = build_loss(train_opt['L1_opt']).to(self.device)\n\n        # gan loss (wgan)\n        self.cri_gan = build_loss(train_opt['gan_opt']).to(self.device)\n\n        # ----------- define identity loss ----------- #\n        if 'network_identity' in self.opt:\n            self.use_identity = True\n        else:\n            self.use_identity = False\n\n        if self.use_identity:\n            # define identity network\n            self.network_identity = build_network(self.opt['network_identity'])\n            self.network_identity = self.model_to_device(self.network_identity)\n            self.print_network(self.network_identity)\n            load_path = self.opt['path'].get('pretrain_network_identity')\n            if load_path is not None:\n                self.load_network(self.network_identity, load_path, True, None)\n            self.network_identity.eval()\n            for param in self.network_identity.parameters():\n                param.requires_grad = False\n\n        # regularization weights\n        self.r1_reg_weight = train_opt['r1_reg_weight']  # for discriminator\n        self.net_d_iters = train_opt.get('net_d_iters', 1)\n        self.net_d_init_iters = train_opt.get('net_d_init_iters', 0)\n        self.net_d_reg_every = train_opt['net_d_reg_every']\n\n        # set up optimizers and schedulers\n        self.setup_optimizers()\n        self.setup_schedulers()\n\n    def setup_optimizers(self):\n        train_opt = self.opt['train']\n\n        # ----------- optimizer g ----------- #\n        net_g_reg_ratio = 1\n        normal_params = []\n        for _, param in self.net_g.named_parameters():\n            normal_params.append(param)\n        optim_params_g = [{  # add normal params first\n            'params': normal_params,\n            'lr': train_opt['optim_g']['lr']\n        }]\n        optim_type = train_opt['optim_g'].pop('type')\n        lr = train_opt['optim_g']['lr'] * net_g_reg_ratio\n        betas = (0**net_g_reg_ratio, 0.99**net_g_reg_ratio)\n        self.optimizer_g = self.get_optimizer(optim_type, optim_params_g, lr, betas=betas)\n        self.optimizers.append(self.optimizer_g)\n\n        # ----------- optimizer d ----------- #\n        net_d_reg_ratio = self.net_d_reg_every / (self.net_d_reg_every + 1)\n        normal_params = []\n        for _, param in self.net_d.named_parameters():\n            normal_params.append(param)\n        optim_params_d = [{  # add normal params first\n            'params': normal_params,\n            'lr': train_opt['optim_d']['lr']\n        }]\n        optim_type = train_opt['optim_d'].pop('type')\n        lr = train_opt['optim_d']['lr'] * net_d_reg_ratio\n        betas = (0**net_d_reg_ratio, 0.99**net_d_reg_ratio)\n        self.optimizer_d = self.get_optimizer(optim_type, optim_params_d, lr, betas=betas)\n        self.optimizers.append(self.optimizer_d)\n\n        # ----------- optimizers for facial component networks ----------- #\n        if self.use_facial_disc:\n            # setup optimizers for facial component discriminators\n            optim_type = train_opt['optim_component'].pop('type')\n            lr = train_opt['optim_component']['lr']\n            # left eye\n            self.optimizer_d_left_eye = self.get_optimizer(\n                optim_type, self.net_d_left_eye.parameters(), lr, betas=(0.9, 0.99))\n            self.optimizers.append(self.optimizer_d_left_eye)\n            # right eye\n            self.optimizer_d_right_eye = self.get_optimizer(\n                optim_type, self.net_d_right_eye.parameters(), lr, betas=(0.9, 0.99))\n            self.optimizers.append(self.optimizer_d_right_eye)\n            # mouth\n            self.optimizer_d_mouth = self.get_optimizer(\n                optim_type, self.net_d_mouth.parameters(), lr, betas=(0.9, 0.99))\n            self.optimizers.append(self.optimizer_d_mouth)\n\n    def feed_data(self, data):\n        self.lq = data['lq'].to(self.device)\n        if 'gt' in data:\n            self.gt = data['gt'].to(self.device)\n\n        if 'loc_left_eye' in data:\n            # get facial component locations, shape (batch, 4)\n            self.loc_left_eyes = data['loc_left_eye']\n            self.loc_right_eyes = data['loc_right_eye']\n            self.loc_mouths = data['loc_mouth']\n\n        # uncomment to check data\n        # import torchvision\n        # if self.opt['rank'] == 0:\n        #     import os\n        #     os.makedirs('tmp/gt', exist_ok=True)\n        #     os.makedirs('tmp/lq', exist_ok=True)\n        #     print(self.idx)\n        #     torchvision.utils.save_image(\n        #         self.gt, f'tmp/gt/gt_{self.idx}.png', nrow=4, padding=2, normalize=True, range=(-1, 1))\n        #     torchvision.utils.save_image(\n        #         self.lq, f'tmp/lq/lq{self.idx}.png', nrow=4, padding=2, normalize=True, range=(-1, 1))\n        #     self.idx = self.idx + 1\n\n    def construct_img_pyramid(self):\n        \"\"\"Construct image pyramid for intermediate restoration loss\"\"\"\n        pyramid_gt = [self.gt]\n        down_img = self.gt\n        for _ in range(0, self.log_size - 3):\n            down_img = F.interpolate(down_img, scale_factor=0.5, mode='bilinear', align_corners=False)\n            pyramid_gt.insert(0, down_img)\n        return pyramid_gt\n\n    def get_roi_regions(self, eye_out_size=80, mouth_out_size=120):\n        face_ratio = int(self.opt['network_g']['out_size'] / 512)\n        eye_out_size *= face_ratio\n        mouth_out_size *= face_ratio\n\n        rois_eyes = []\n        rois_mouths = []\n        for b in range(self.loc_left_eyes.size(0)):  # loop for batch size\n            # left eye and right eye\n            img_inds = self.loc_left_eyes.new_full((2, 1), b)\n            bbox = torch.stack([self.loc_left_eyes[b, :], self.loc_right_eyes[b, :]], dim=0)  # shape: (2, 4)\n            rois = torch.cat([img_inds, bbox], dim=-1)  # shape: (2, 5)\n            rois_eyes.append(rois)\n            # mouse\n            img_inds = self.loc_left_eyes.new_full((1, 1), b)\n            rois = torch.cat([img_inds, self.loc_mouths[b:b + 1, :]], dim=-1)  # shape: (1, 5)\n            rois_mouths.append(rois)\n\n        rois_eyes = torch.cat(rois_eyes, 0).to(self.device)\n        rois_mouths = torch.cat(rois_mouths, 0).to(self.device)\n\n        # real images\n        all_eyes = roi_align(self.gt, boxes=rois_eyes, output_size=eye_out_size) * face_ratio\n        self.left_eyes_gt = all_eyes[0::2, :, :, :]\n        self.right_eyes_gt = all_eyes[1::2, :, :, :]\n        self.mouths_gt = roi_align(self.gt, boxes=rois_mouths, output_size=mouth_out_size) * face_ratio\n        # output\n        all_eyes = roi_align(self.output, boxes=rois_eyes, output_size=eye_out_size) * face_ratio\n        self.left_eyes = all_eyes[0::2, :, :, :]\n        self.right_eyes = all_eyes[1::2, :, :, :]\n        self.mouths = roi_align(self.output, boxes=rois_mouths, output_size=mouth_out_size) * face_ratio\n\n    def _gram_mat(self, x):\n        \"\"\"Calculate Gram matrix.\n\n        Args:\n            x (torch.Tensor): Tensor with shape of (n, c, h, w).\n\n        Returns:\n            torch.Tensor: Gram matrix.\n        \"\"\"\n        n, c, h, w = x.size()\n        features = x.view(n, c, w * h)\n        features_t = features.transpose(1, 2)\n        gram = features.bmm(features_t) / (c * h * w)\n        return gram\n\n    def gray_resize_for_identity(self, out, size=128):\n        out_gray = (0.2989 * out[:, 0, :, :] + 0.5870 * out[:, 1, :, :] + 0.1140 * out[:, 2, :, :])\n        out_gray = out_gray.unsqueeze(1)\n        out_gray = F.interpolate(out_gray, (size, size), mode='bilinear', align_corners=False)\n        return out_gray\n\n    def optimize_parameters(self, current_iter):\n        # optimize net_g\n        for p in self.net_d.parameters():\n            p.requires_grad = False\n        self.optimizer_g.zero_grad()\n\n        # do not update facial component net_d\n        if self.use_facial_disc:\n            for p in self.net_d_left_eye.parameters():\n                p.requires_grad = False\n            for p in self.net_d_right_eye.parameters():\n                p.requires_grad = False\n            for p in self.net_d_mouth.parameters():\n                p.requires_grad = False\n\n        # image pyramid loss weight\n        pyramid_loss_weight = self.opt['train'].get('pyramid_loss_weight', 0)\n        if pyramid_loss_weight > 0 and current_iter > self.opt['train'].get('remove_pyramid_loss', float('inf')):\n            pyramid_loss_weight = 1e-12  # very small weight to avoid unused param error\n        if pyramid_loss_weight > 0:\n            self.output, out_rgbs = self.net_g(self.lq, return_rgb=True)\n            pyramid_gt = self.construct_img_pyramid()\n        else:\n            self.output, out_rgbs = self.net_g(self.lq, return_rgb=False)\n\n        # get roi-align regions\n        if self.use_facial_disc:\n            self.get_roi_regions(eye_out_size=80, mouth_out_size=120)\n\n        l_g_total = 0\n        loss_dict = OrderedDict()\n        if (current_iter % self.net_d_iters == 0 and current_iter > self.net_d_init_iters):\n            # pixel loss\n            if self.cri_pix:\n                l_g_pix = self.cri_pix(self.output, self.gt)\n                l_g_total += l_g_pix\n                loss_dict['l_g_pix'] = l_g_pix\n\n            # image pyramid loss\n            if pyramid_loss_weight > 0:\n                for i in range(0, self.log_size - 2):\n                    l_pyramid = self.cri_l1(out_rgbs[i], pyramid_gt[i]) * pyramid_loss_weight\n                    l_g_total += l_pyramid\n                    loss_dict[f'l_p_{2**(i+3)}'] = l_pyramid\n\n            # perceptual loss\n            if self.cri_perceptual:\n                l_g_percep, l_g_style = self.cri_perceptual(self.output, self.gt)\n                if l_g_percep is not None:\n                    l_g_total += l_g_percep\n                    loss_dict['l_g_percep'] = l_g_percep\n                if l_g_style is not None:\n                    l_g_total += l_g_style\n                    loss_dict['l_g_style'] = l_g_style\n\n            # gan loss\n            fake_g_pred = self.net_d(self.output)\n            l_g_gan = self.cri_gan(fake_g_pred, True, is_disc=False)\n            l_g_total += l_g_gan\n            loss_dict['l_g_gan'] = l_g_gan\n\n            # facial component loss\n            if self.use_facial_disc:\n                # left eye\n                fake_left_eye, fake_left_eye_feats = self.net_d_left_eye(self.left_eyes, return_feats=True)\n                l_g_gan = self.cri_component(fake_left_eye, True, is_disc=False)\n                l_g_total += l_g_gan\n                loss_dict['l_g_gan_left_eye'] = l_g_gan\n                # right eye\n                fake_right_eye, fake_right_eye_feats = self.net_d_right_eye(self.right_eyes, return_feats=True)\n                l_g_gan = self.cri_component(fake_right_eye, True, is_disc=False)\n                l_g_total += l_g_gan\n                loss_dict['l_g_gan_right_eye'] = l_g_gan\n                # mouth\n                fake_mouth, fake_mouth_feats = self.net_d_mouth(self.mouths, return_feats=True)\n                l_g_gan = self.cri_component(fake_mouth, True, is_disc=False)\n                l_g_total += l_g_gan\n                loss_dict['l_g_gan_mouth'] = l_g_gan\n\n                if self.opt['train'].get('comp_style_weight', 0) > 0:\n                    # get gt feat\n                    _, real_left_eye_feats = self.net_d_left_eye(self.left_eyes_gt, return_feats=True)\n                    _, real_right_eye_feats = self.net_d_right_eye(self.right_eyes_gt, return_feats=True)\n                    _, real_mouth_feats = self.net_d_mouth(self.mouths_gt, return_feats=True)\n\n                    def _comp_style(feat, feat_gt, criterion):\n                        return criterion(self._gram_mat(feat[0]), self._gram_mat(\n                            feat_gt[0].detach())) * 0.5 + criterion(\n                                self._gram_mat(feat[1]), self._gram_mat(feat_gt[1].detach()))\n\n                    # facial component style loss\n                    comp_style_loss = 0\n                    comp_style_loss += _comp_style(fake_left_eye_feats, real_left_eye_feats, self.cri_l1)\n                    comp_style_loss += _comp_style(fake_right_eye_feats, real_right_eye_feats, self.cri_l1)\n                    comp_style_loss += _comp_style(fake_mouth_feats, real_mouth_feats, self.cri_l1)\n                    comp_style_loss = comp_style_loss * self.opt['train']['comp_style_weight']\n                    l_g_total += comp_style_loss\n                    loss_dict['l_g_comp_style_loss'] = comp_style_loss\n\n            # identity loss\n            if self.use_identity:\n                identity_weight = self.opt['train']['identity_weight']\n                # get gray images and resize\n                out_gray = self.gray_resize_for_identity(self.output)\n                gt_gray = self.gray_resize_for_identity(self.gt)\n\n                identity_gt = self.network_identity(gt_gray).detach()\n                identity_out = self.network_identity(out_gray)\n                l_identity = self.cri_l1(identity_out, identity_gt) * identity_weight\n                l_g_total += l_identity\n                loss_dict['l_identity'] = l_identity\n\n            l_g_total.backward()\n            self.optimizer_g.step()\n\n        # EMA\n        self.model_ema(decay=0.5**(32 / (10 * 1000)))\n\n        # ----------- optimize net_d ----------- #\n        for p in self.net_d.parameters():\n            p.requires_grad = True\n        self.optimizer_d.zero_grad()\n        if self.use_facial_disc:\n            for p in self.net_d_left_eye.parameters():\n                p.requires_grad = True\n            for p in self.net_d_right_eye.parameters():\n                p.requires_grad = True\n            for p in self.net_d_mouth.parameters():\n                p.requires_grad = True\n            self.optimizer_d_left_eye.zero_grad()\n            self.optimizer_d_right_eye.zero_grad()\n            self.optimizer_d_mouth.zero_grad()\n\n        fake_d_pred = self.net_d(self.output.detach())\n        real_d_pred = self.net_d(self.gt)\n        l_d = self.cri_gan(real_d_pred, True, is_disc=True) + self.cri_gan(fake_d_pred, False, is_disc=True)\n        loss_dict['l_d'] = l_d\n        # In WGAN, real_score should be positive and fake_score should be negative\n        loss_dict['real_score'] = real_d_pred.detach().mean()\n        loss_dict['fake_score'] = fake_d_pred.detach().mean()\n        l_d.backward()\n\n        # regularization loss\n        if current_iter % self.net_d_reg_every == 0:\n            self.gt.requires_grad = True\n            real_pred = self.net_d(self.gt)\n            l_d_r1 = r1_penalty(real_pred, self.gt)\n            l_d_r1 = (self.r1_reg_weight / 2 * l_d_r1 * self.net_d_reg_every + 0 * real_pred[0])\n            loss_dict['l_d_r1'] = l_d_r1.detach().mean()\n            l_d_r1.backward()\n\n        self.optimizer_d.step()\n\n        # optimize facial component discriminators\n        if self.use_facial_disc:\n            # left eye\n            fake_d_pred, _ = self.net_d_left_eye(self.left_eyes.detach())\n            real_d_pred, _ = self.net_d_left_eye(self.left_eyes_gt)\n            l_d_left_eye = self.cri_component(\n                real_d_pred, True, is_disc=True) + self.cri_gan(\n                    fake_d_pred, False, is_disc=True)\n            loss_dict['l_d_left_eye'] = l_d_left_eye\n            l_d_left_eye.backward()\n            # right eye\n            fake_d_pred, _ = self.net_d_right_eye(self.right_eyes.detach())\n            real_d_pred, _ = self.net_d_right_eye(self.right_eyes_gt)\n            l_d_right_eye = self.cri_component(\n                real_d_pred, True, is_disc=True) + self.cri_gan(\n                    fake_d_pred, False, is_disc=True)\n            loss_dict['l_d_right_eye'] = l_d_right_eye\n            l_d_right_eye.backward()\n            # mouth\n            fake_d_pred, _ = self.net_d_mouth(self.mouths.detach())\n            real_d_pred, _ = self.net_d_mouth(self.mouths_gt)\n            l_d_mouth = self.cri_component(\n                real_d_pred, True, is_disc=True) + self.cri_gan(\n                    fake_d_pred, False, is_disc=True)\n            loss_dict['l_d_mouth'] = l_d_mouth\n            l_d_mouth.backward()\n\n            self.optimizer_d_left_eye.step()\n            self.optimizer_d_right_eye.step()\n            self.optimizer_d_mouth.step()\n\n        self.log_dict = self.reduce_loss_dict(loss_dict)\n\n    def test(self):\n        with torch.no_grad():\n            if hasattr(self, 'net_g_ema'):\n                self.net_g_ema.eval()\n                self.output, _ = self.net_g_ema(self.lq)\n            else:\n                logger = get_root_logger()\n                logger.warning('Do not have self.net_g_ema, use self.net_g.')\n                self.net_g.eval()\n                self.output, _ = self.net_g(self.lq)\n                self.net_g.train()\n\n    def dist_validation(self, dataloader, current_iter, tb_logger, save_img):\n        if self.opt['rank'] == 0:\n            self.nondist_validation(dataloader, current_iter, tb_logger, save_img)\n\n    def nondist_validation(self, dataloader, current_iter, tb_logger, save_img):\n        dataset_name = dataloader.dataset.opt['name']\n        with_metrics = self.opt['val'].get('metrics') is not None\n        use_pbar = self.opt['val'].get('pbar', False)\n\n        if with_metrics:\n            if not hasattr(self, 'metric_results'):  # only execute in the first run\n                self.metric_results = {metric: 0 for metric in self.opt['val']['metrics'].keys()}\n            # initialize the best metric results for each dataset_name (supporting multiple validation datasets)\n            self._initialize_best_metric_results(dataset_name)\n            # zero self.metric_results\n            self.metric_results = {metric: 0 for metric in self.metric_results}\n\n        metric_data = dict()\n        if use_pbar:\n            pbar = tqdm(total=len(dataloader), unit='image')\n\n        for idx, val_data in enumerate(dataloader):\n            img_name = osp.splitext(osp.basename(val_data['lq_path'][0]))[0]\n            self.feed_data(val_data)\n            self.test()\n\n            sr_img = tensor2img(self.output.detach().cpu(), min_max=(-1, 1))\n            metric_data['img'] = sr_img\n            if hasattr(self, 'gt'):\n                gt_img = tensor2img(self.gt.detach().cpu(), min_max=(-1, 1))\n                metric_data['img2'] = gt_img\n                del self.gt\n\n            # tentative for out of GPU memory\n            del self.lq\n            del self.output\n            torch.cuda.empty_cache()\n\n            if save_img:\n                if self.opt['is_train']:\n                    save_img_path = osp.join(self.opt['path']['visualization'], img_name,\n                                             f'{img_name}_{current_iter}.png')\n                else:\n                    if self.opt['val']['suffix']:\n                        save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,\n                                                 f'{img_name}_{self.opt[\"val\"][\"suffix\"]}.png')\n                    else:\n                        save_img_path = osp.join(self.opt['path']['visualization'], dataset_name,\n                                                 f'{img_name}_{self.opt[\"name\"]}.png')\n                imwrite(sr_img, save_img_path)\n\n            if with_metrics:\n                # calculate metrics\n                for name, opt_ in self.opt['val']['metrics'].items():\n                    self.metric_results[name] += calculate_metric(metric_data, opt_)\n            if use_pbar:\n                pbar.update(1)\n                pbar.set_description(f'Test {img_name}')\n        if use_pbar:\n            pbar.close()\n\n        if with_metrics:\n            for metric in self.metric_results.keys():\n                self.metric_results[metric] /= (idx + 1)\n                # update the best metric result\n                self._update_best_metric_result(dataset_name, metric, self.metric_results[metric], current_iter)\n\n            self._log_validation_metric_values(current_iter, dataset_name, tb_logger)\n\n    def _log_validation_metric_values(self, current_iter, dataset_name, tb_logger):\n        log_str = f'Validation {dataset_name}\\n'\n        for metric, value in self.metric_results.items():\n            log_str += f'\\t # {metric}: {value:.4f}'\n            if hasattr(self, 'best_metric_results'):\n                log_str += (f'\\tBest: {self.best_metric_results[dataset_name][metric][\"val\"]:.4f} @ '\n                            f'{self.best_metric_results[dataset_name][metric][\"iter\"]} iter')\n            log_str += '\\n'\n\n        logger = get_root_logger()\n        logger.info(log_str)\n        if tb_logger:\n            for metric, value in self.metric_results.items():\n                tb_logger.add_scalar(f'metrics/{dataset_name}/{metric}', value, current_iter)\n\n    def save(self, epoch, current_iter):\n        # save net_g and net_d\n        self.save_network([self.net_g, self.net_g_ema], 'net_g', current_iter, param_key=['params', 'params_ema'])\n        self.save_network(self.net_d, 'net_d', current_iter)\n        # save component discriminators\n        if self.use_facial_disc:\n            self.save_network(self.net_d_left_eye, 'net_d_left_eye', current_iter)\n            self.save_network(self.net_d_right_eye, 'net_d_right_eye', current_iter)\n            self.save_network(self.net_d_mouth, 'net_d_mouth', current_iter)\n        # save training state\n        self.save_training_state(epoch, current_iter)\n"
  },
  {
    "path": "gfpgan/train.py",
    "content": "# flake8: noqa\nimport os.path as osp\nfrom basicsr.train import train_pipeline\n\nimport gfpgan.archs\nimport gfpgan.data\nimport gfpgan.models\n\nif __name__ == '__main__':\n    root_path = osp.abspath(osp.join(__file__, osp.pardir, osp.pardir))\n    train_pipeline(root_path)\n"
  },
  {
    "path": "gfpgan/utils.py",
    "content": "import cv2\nimport os\nimport torch\nfrom basicsr.utils import img2tensor, tensor2img\nfrom basicsr.utils.download_util import load_file_from_url\nfrom facexlib.utils.face_restoration_helper import FaceRestoreHelper\nfrom torchvision.transforms.functional import normalize\n\nfrom gfpgan.archs.gfpgan_bilinear_arch import GFPGANBilinear\nfrom gfpgan.archs.gfpganv1_arch import GFPGANv1\nfrom gfpgan.archs.gfpganv1_clean_arch import GFPGANv1Clean\n\nROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\nclass GFPGANer():\n    \"\"\"Helper for restoration with GFPGAN.\n\n    It will detect and crop faces, and then resize the faces to 512x512.\n    GFPGAN is used to restored the resized faces.\n    The background is upsampled with the bg_upsampler.\n    Finally, the faces will be pasted back to the upsample background image.\n\n    Args:\n        model_path (str): The path to the GFPGAN model. It can be urls (will first download it automatically).\n        upscale (float): The upscale of the final output. Default: 2.\n        arch (str): The GFPGAN architecture. Option: clean | original. Default: clean.\n        channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.\n        bg_upsampler (nn.Module): The upsampler for the background. Default: None.\n    \"\"\"\n\n    def __init__(self, model_path, upscale=2, arch='clean', channel_multiplier=2, bg_upsampler=None, device=None):\n        self.upscale = upscale\n        self.bg_upsampler = bg_upsampler\n\n        # initialize model\n        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if device is None else device\n        # initialize the GFP-GAN\n        if arch == 'clean':\n            self.gfpgan = GFPGANv1Clean(\n                out_size=512,\n                num_style_feat=512,\n                channel_multiplier=channel_multiplier,\n                decoder_load_path=None,\n                fix_decoder=False,\n                num_mlp=8,\n                input_is_latent=True,\n                different_w=True,\n                narrow=1,\n                sft_half=True)\n        elif arch == 'bilinear':\n            self.gfpgan = GFPGANBilinear(\n                out_size=512,\n                num_style_feat=512,\n                channel_multiplier=channel_multiplier,\n                decoder_load_path=None,\n                fix_decoder=False,\n                num_mlp=8,\n                input_is_latent=True,\n                different_w=True,\n                narrow=1,\n                sft_half=True)\n        elif arch == 'original':\n            self.gfpgan = GFPGANv1(\n                out_size=512,\n                num_style_feat=512,\n                channel_multiplier=channel_multiplier,\n                decoder_load_path=None,\n                fix_decoder=True,\n                num_mlp=8,\n                input_is_latent=True,\n                different_w=True,\n                narrow=1,\n                sft_half=True)\n        elif arch == 'RestoreFormer':\n            from gfpgan.archs.restoreformer_arch import RestoreFormer\n            self.gfpgan = RestoreFormer()\n        # initialize face helper\n        self.face_helper = FaceRestoreHelper(\n            upscale,\n            face_size=512,\n            crop_ratio=(1, 1),\n            det_model='retinaface_resnet50',\n            save_ext='png',\n            use_parse=True,\n            device=self.device,\n            model_rootpath='gfpgan/weights')\n\n        if model_path.startswith('https://'):\n            model_path = load_file_from_url(\n                url=model_path, model_dir=os.path.join(ROOT_DIR, 'gfpgan/weights'), progress=True, file_name=None)\n        loadnet = torch.load(model_path)\n        if 'params_ema' in loadnet:\n            keyname = 'params_ema'\n        else:\n            keyname = 'params'\n        self.gfpgan.load_state_dict(loadnet[keyname], strict=True)\n        self.gfpgan.eval()\n        self.gfpgan = self.gfpgan.to(self.device)\n\n    @torch.no_grad()\n    def enhance(self, img, has_aligned=False, only_center_face=False, paste_back=True, weight=0.5):\n        self.face_helper.clean_all()\n\n        if has_aligned:  # the inputs are already aligned\n            img = cv2.resize(img, (512, 512))\n            self.face_helper.cropped_faces = [img]\n        else:\n            self.face_helper.read_image(img)\n            # get face landmarks for each face\n            self.face_helper.get_face_landmarks_5(only_center_face=only_center_face, eye_dist_threshold=5)\n            # eye_dist_threshold=5: skip faces whose eye distance is smaller than 5 pixels\n            # TODO: even with eye_dist_threshold, it will still introduce wrong detections and restorations.\n            # align and warp each face\n            self.face_helper.align_warp_face()\n\n        # face restoration\n        for cropped_face in self.face_helper.cropped_faces:\n            # prepare data\n            cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True)\n            normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)\n            cropped_face_t = cropped_face_t.unsqueeze(0).to(self.device)\n\n            try:\n                output = self.gfpgan(cropped_face_t, return_rgb=False, weight=weight)[0]\n                # convert to image\n                restored_face = tensor2img(output.squeeze(0), rgb2bgr=True, min_max=(-1, 1))\n            except RuntimeError as error:\n                print(f'\\tFailed inference for GFPGAN: {error}.')\n                restored_face = cropped_face\n\n            restored_face = restored_face.astype('uint8')\n            self.face_helper.add_restored_face(restored_face)\n\n        if not has_aligned and paste_back:\n            # upsample the background\n            if self.bg_upsampler is not None:\n                # Now only support RealESRGAN for upsampling background\n                bg_img = self.bg_upsampler.enhance(img, outscale=self.upscale)[0]\n            else:\n                bg_img = None\n\n            self.face_helper.get_inverse_affine(None)\n            # paste each restored face to the input image\n            restored_img = self.face_helper.paste_faces_to_input_image(upsample_img=bg_img)\n            return self.face_helper.cropped_faces, self.face_helper.restored_faces, restored_img\n        else:\n            return self.face_helper.cropped_faces, self.face_helper.restored_faces, None\n"
  },
  {
    "path": "gfpgan/weights/README.md",
    "content": "# Weights\n\nPut the downloaded weights to this folder.\n"
  },
  {
    "path": "inference_gfpgan.py",
    "content": "import argparse\nimport cv2\nimport glob\nimport numpy as np\nimport os\nimport torch\nfrom basicsr.utils import imwrite\n\nfrom gfpgan import GFPGANer\n\n\ndef main():\n    \"\"\"Inference demo for GFPGAN (for users).\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        '-i',\n        '--input',\n        type=str,\n        default='inputs/whole_imgs',\n        help='Input image or folder. Default: inputs/whole_imgs')\n    parser.add_argument('-o', '--output', type=str, default='results', help='Output folder. Default: results')\n    # we use version to select models, which is more user-friendly\n    parser.add_argument(\n        '-v', '--version', type=str, default='1.3', help='GFPGAN model version. Option: 1 | 1.2 | 1.3. Default: 1.3')\n    parser.add_argument(\n        '-s', '--upscale', type=int, default=2, help='The final upsampling scale of the image. Default: 2')\n\n    parser.add_argument(\n        '--bg_upsampler', type=str, default='realesrgan', help='background upsampler. Default: realesrgan')\n    parser.add_argument(\n        '--bg_tile',\n        type=int,\n        default=400,\n        help='Tile size for background sampler, 0 for no tile during testing. Default: 400')\n    parser.add_argument('--suffix', type=str, default=None, help='Suffix of the restored faces')\n    parser.add_argument('--only_center_face', action='store_true', help='Only restore the center face')\n    parser.add_argument('--aligned', action='store_true', help='Input are aligned faces')\n    parser.add_argument(\n        '--ext',\n        type=str,\n        default='auto',\n        help='Image extension. Options: auto | jpg | png, auto means using the same extension as inputs. Default: auto')\n    parser.add_argument('-w', '--weight', type=float, default=0.5, help='Adjustable weights.')\n    args = parser.parse_args()\n\n    args = parser.parse_args()\n\n    # ------------------------ input & output ------------------------\n    if args.input.endswith('/'):\n        args.input = args.input[:-1]\n    if os.path.isfile(args.input):\n        img_list = [args.input]\n    else:\n        img_list = sorted(glob.glob(os.path.join(args.input, '*')))\n\n    os.makedirs(args.output, exist_ok=True)\n\n    # ------------------------ set up background upsampler ------------------------\n    if args.bg_upsampler == 'realesrgan':\n        if not torch.cuda.is_available():  # CPU\n            import warnings\n            warnings.warn('The unoptimized RealESRGAN is slow on CPU. We do not use it. '\n                          'If you really want to use it, please modify the corresponding codes.')\n            bg_upsampler = None\n        else:\n            from basicsr.archs.rrdbnet_arch import RRDBNet\n            from realesrgan import RealESRGANer\n            model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)\n            bg_upsampler = RealESRGANer(\n                scale=2,\n                model_path='https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth',\n                model=model,\n                tile=args.bg_tile,\n                tile_pad=10,\n                pre_pad=0,\n                half=True)  # need to set False in CPU mode\n    else:\n        bg_upsampler = None\n\n    # ------------------------ set up GFPGAN restorer ------------------------\n    if args.version == '1':\n        arch = 'original'\n        channel_multiplier = 1\n        model_name = 'GFPGANv1'\n        url = 'https://github.com/TencentARC/GFPGAN/releases/download/v0.1.0/GFPGANv1.pth'\n    elif args.version == '1.2':\n        arch = 'clean'\n        channel_multiplier = 2\n        model_name = 'GFPGANCleanv1-NoCE-C2'\n        url = 'https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth'\n    elif args.version == '1.3':\n        arch = 'clean'\n        channel_multiplier = 2\n        model_name = 'GFPGANv1.3'\n        url = 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth'\n    elif args.version == '1.4':\n        arch = 'clean'\n        channel_multiplier = 2\n        model_name = 'GFPGANv1.4'\n        url = 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth'\n    elif args.version == 'RestoreFormer':\n        arch = 'RestoreFormer'\n        channel_multiplier = 2\n        model_name = 'RestoreFormer'\n        url = 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth'\n    else:\n        raise ValueError(f'Wrong model version {args.version}.')\n\n    # determine model paths\n    model_path = os.path.join('experiments/pretrained_models', model_name + '.pth')\n    if not os.path.isfile(model_path):\n        model_path = os.path.join('gfpgan/weights', model_name + '.pth')\n    if not os.path.isfile(model_path):\n        # download pre-trained models from url\n        model_path = url\n\n    restorer = GFPGANer(\n        model_path=model_path,\n        upscale=args.upscale,\n        arch=arch,\n        channel_multiplier=channel_multiplier,\n        bg_upsampler=bg_upsampler)\n\n    # ------------------------ restore ------------------------\n    for img_path in img_list:\n        # read image\n        img_name = os.path.basename(img_path)\n        print(f'Processing {img_name} ...')\n        basename, ext = os.path.splitext(img_name)\n        input_img = cv2.imread(img_path, cv2.IMREAD_COLOR)\n\n        # restore faces and background if necessary\n        cropped_faces, restored_faces, restored_img = restorer.enhance(\n            input_img,\n            has_aligned=args.aligned,\n            only_center_face=args.only_center_face,\n            paste_back=True,\n            weight=args.weight)\n\n        # save faces\n        for idx, (cropped_face, restored_face) in enumerate(zip(cropped_faces, restored_faces)):\n            # save cropped face\n            save_crop_path = os.path.join(args.output, 'cropped_faces', f'{basename}_{idx:02d}.png')\n            imwrite(cropped_face, save_crop_path)\n            # save restored face\n            if args.suffix is not None:\n                save_face_name = f'{basename}_{idx:02d}_{args.suffix}.png'\n            else:\n                save_face_name = f'{basename}_{idx:02d}.png'\n            save_restore_path = os.path.join(args.output, 'restored_faces', save_face_name)\n            imwrite(restored_face, save_restore_path)\n            # save comparison image\n            cmp_img = np.concatenate((cropped_face, restored_face), axis=1)\n            imwrite(cmp_img, os.path.join(args.output, 'cmp', f'{basename}_{idx:02d}.png'))\n\n        # save restored img\n        if restored_img is not None:\n            if args.ext == 'auto':\n                extension = ext[1:]\n            else:\n                extension = args.ext\n\n            if args.suffix is not None:\n                save_restore_path = os.path.join(args.output, 'restored_imgs', f'{basename}_{args.suffix}.{extension}')\n            else:\n                save_restore_path = os.path.join(args.output, 'restored_imgs', f'{basename}.{extension}')\n            imwrite(restored_img, save_restore_path)\n\n    print(f'Results are in the [{args.output}] folder.')\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "options/train_gfpgan_v1.yml",
    "content": "# general settings\nname: train_GFPGANv1_512\nmodel_type: GFPGANModel\nnum_gpu: auto  # officially, we use 4 GPUs\nmanual_seed: 0\n\n# dataset and data loader settings\ndatasets:\n  train:\n    name: FFHQ\n    type: FFHQDegradationDataset\n    # dataroot_gt: datasets/ffhq/ffhq_512.lmdb\n    dataroot_gt: datasets/ffhq/ffhq_512\n    io_backend:\n      # type: lmdb\n      type: disk\n\n    use_hflip: true\n    mean: [0.5, 0.5, 0.5]\n    std: [0.5, 0.5, 0.5]\n    out_size: 512\n\n    blur_kernel_size: 41\n    kernel_list: ['iso', 'aniso']\n    kernel_prob: [0.5, 0.5]\n    blur_sigma: [0.1, 10]\n    downsample_range: [0.8, 8]\n    noise_range: [0, 20]\n    jpeg_range: [60, 100]\n\n    # color jitter and gray\n    color_jitter_prob: 0.3\n    color_jitter_shift: 20\n    color_jitter_pt_prob: 0.3\n    gray_prob: 0.01\n\n    # If you do not want colorization, please set\n    # color_jitter_prob: ~\n    # color_jitter_pt_prob: ~\n    # gray_prob: 0.01\n    # gt_gray: True\n\n    crop_components: true\n    component_path: experiments/pretrained_models/FFHQ_eye_mouth_landmarks_512.pth\n    eye_enlarge_ratio: 1.4\n\n    # data loader\n    use_shuffle: true\n    num_worker_per_gpu: 6\n    batch_size_per_gpu: 3\n    dataset_enlarge_ratio: 1\n    prefetch_mode: ~\n\n  val:\n    # Please modify accordingly to use your own validation\n    # Or comment the val block if do not need validation during training\n    name: validation\n    type: PairedImageDataset\n    dataroot_lq: datasets/faces/validation/input\n    dataroot_gt: datasets/faces/validation/reference\n    io_backend:\n      type: disk\n    mean: [0.5, 0.5, 0.5]\n    std: [0.5, 0.5, 0.5]\n    scale: 1\n\n# network structures\nnetwork_g:\n  type: GFPGANv1\n  out_size: 512\n  num_style_feat: 512\n  channel_multiplier: 1\n  resample_kernel: [1, 3, 3, 1]\n  decoder_load_path: experiments/pretrained_models/StyleGAN2_512_Cmul1_FFHQ_B12G4_scratch_800k.pth\n  fix_decoder: true\n  num_mlp: 8\n  lr_mlp: 0.01\n  input_is_latent: true\n  different_w: true\n  narrow: 1\n  sft_half: true\n\nnetwork_d:\n  type: StyleGAN2Discriminator\n  out_size: 512\n  channel_multiplier: 1\n  resample_kernel: [1, 3, 3, 1]\n\nnetwork_d_left_eye:\n  type: FacialComponentDiscriminator\n\nnetwork_d_right_eye:\n  type: FacialComponentDiscriminator\n\nnetwork_d_mouth:\n  type: FacialComponentDiscriminator\n\nnetwork_identity:\n  type: ResNetArcFace\n  block: IRBlock\n  layers: [2, 2, 2, 2]\n  use_se: False\n\n# path\npath:\n  pretrain_network_g: ~\n  param_key_g: params_ema\n  strict_load_g: ~\n  pretrain_network_d: ~\n  pretrain_network_d_left_eye: ~\n  pretrain_network_d_right_eye: ~\n  pretrain_network_d_mouth: ~\n  pretrain_network_identity: experiments/pretrained_models/arcface_resnet18.pth\n  # resume\n  resume_state: ~\n  ignore_resume_networks: ['network_identity']\n\n# training settings\ntrain:\n  optim_g:\n    type: Adam\n    lr: !!float 2e-3\n  optim_d:\n    type: Adam\n    lr: !!float 2e-3\n  optim_component:\n    type: Adam\n    lr: !!float 2e-3\n\n  scheduler:\n    type: MultiStepLR\n    milestones: [600000, 700000]\n    gamma: 0.5\n\n  total_iter: 800000\n  warmup_iter: -1  # no warm up\n\n  # losses\n  # pixel loss\n  pixel_opt:\n    type: L1Loss\n    loss_weight: !!float 1e-1\n    reduction: mean\n  # L1 loss used in pyramid loss, component style loss and identity loss\n  L1_opt:\n    type: L1Loss\n    loss_weight: 1\n    reduction: mean\n\n  # image pyramid loss\n  pyramid_loss_weight: 1\n  remove_pyramid_loss: 50000\n  # perceptual loss (content and style losses)\n  perceptual_opt:\n    type: PerceptualLoss\n    layer_weights:\n      # before relu\n      'conv1_2': 0.1\n      'conv2_2': 0.1\n      'conv3_4': 1\n      'conv4_4': 1\n      'conv5_4': 1\n    vgg_type: vgg19\n    use_input_norm: true\n    perceptual_weight: !!float 1\n    style_weight: 50\n    range_norm: true\n    criterion: l1\n  # gan loss\n  gan_opt:\n    type: GANLoss\n    gan_type: wgan_softplus\n    loss_weight: !!float 1e-1\n  # r1 regularization for discriminator\n  r1_reg_weight: 10\n  # facial component loss\n  gan_component_opt:\n    type: GANLoss\n    gan_type: vanilla\n    real_label_val: 1.0\n    fake_label_val: 0.0\n    loss_weight: !!float 1\n  comp_style_weight: 200\n  # identity loss\n  identity_weight: 10\n\n  net_d_iters: 1\n  net_d_init_iters: 0\n  net_d_reg_every: 16\n\n# validation settings\nval:\n  val_freq: !!float 5e3\n  save_img: true\n\n  metrics:\n    psnr: # metric name\n      type: calculate_psnr\n      crop_border: 0\n      test_y_channel: false\n\n# logging settings\nlogger:\n  print_freq: 100\n  save_checkpoint_freq: !!float 5e3\n  use_tb_logger: true\n  wandb:\n    project: ~\n    resume_id: ~\n\n# dist training settings\ndist_params:\n  backend: nccl\n  port: 29500\n\nfind_unused_parameters: true\n"
  },
  {
    "path": "options/train_gfpgan_v1_simple.yml",
    "content": "# general settings\nname: train_GFPGANv1_512_simple\nmodel_type: GFPGANModel\nnum_gpu: auto  # officially, we use 4 GPUs\nmanual_seed: 0\n\n# dataset and data loader settings\ndatasets:\n  train:\n    name: FFHQ\n    type: FFHQDegradationDataset\n    # dataroot_gt: datasets/ffhq/ffhq_512.lmdb\n    dataroot_gt: datasets/ffhq/ffhq_512\n    io_backend:\n      # type: lmdb\n      type: disk\n\n    use_hflip: true\n    mean: [0.5, 0.5, 0.5]\n    std: [0.5, 0.5, 0.5]\n    out_size: 512\n\n    blur_kernel_size: 41\n    kernel_list: ['iso', 'aniso']\n    kernel_prob: [0.5, 0.5]\n    blur_sigma: [0.1, 10]\n    downsample_range: [0.8, 8]\n    noise_range: [0, 20]\n    jpeg_range: [60, 100]\n\n    # color jitter and gray\n    color_jitter_prob: 0.3\n    color_jitter_shift: 20\n    color_jitter_pt_prob: 0.3\n    gray_prob: 0.01\n\n    # If you do not want colorization, please set\n    # color_jitter_prob: ~\n    # color_jitter_pt_prob: ~\n    # gray_prob: 0.01\n    # gt_gray: True\n\n    # data loader\n    use_shuffle: true\n    num_worker_per_gpu: 6\n    batch_size_per_gpu: 3\n    dataset_enlarge_ratio: 1\n    prefetch_mode: ~\n\n  val:\n    # Please modify accordingly to use your own validation\n    # Or comment the val block if do not need validation during training\n    name: validation\n    type: PairedImageDataset\n    dataroot_lq: datasets/faces/validation/input\n    dataroot_gt: datasets/faces/validation/reference\n    io_backend:\n      type: disk\n    mean: [0.5, 0.5, 0.5]\n    std: [0.5, 0.5, 0.5]\n    scale: 1\n\n# network structures\nnetwork_g:\n  type: GFPGANv1\n  out_size: 512\n  num_style_feat: 512\n  channel_multiplier: 1\n  resample_kernel: [1, 3, 3, 1]\n  decoder_load_path: experiments/pretrained_models/StyleGAN2_512_Cmul1_FFHQ_B12G4_scratch_800k.pth\n  fix_decoder: true\n  num_mlp: 8\n  lr_mlp: 0.01\n  input_is_latent: true\n  different_w: true\n  narrow: 1\n  sft_half: true\n\nnetwork_d:\n  type: StyleGAN2Discriminator\n  out_size: 512\n  channel_multiplier: 1\n  resample_kernel: [1, 3, 3, 1]\n\n\n# path\npath:\n  pretrain_network_g: ~\n  param_key_g: params_ema\n  strict_load_g: ~\n  pretrain_network_d: ~\n  resume_state: ~\n\n# training settings\ntrain:\n  optim_g:\n    type: Adam\n    lr: !!float 2e-3\n  optim_d:\n    type: Adam\n    lr: !!float 2e-3\n  optim_component:\n    type: Adam\n    lr: !!float 2e-3\n\n  scheduler:\n    type: MultiStepLR\n    milestones: [600000, 700000]\n    gamma: 0.5\n\n  total_iter: 800000\n  warmup_iter: -1  # no warm up\n\n  # losses\n  # pixel loss\n  pixel_opt:\n    type: L1Loss\n    loss_weight: !!float 1e-1\n    reduction: mean\n  # L1 loss used in pyramid loss, component style loss and identity loss\n  L1_opt:\n    type: L1Loss\n    loss_weight: 1\n    reduction: mean\n\n  # image pyramid loss\n  pyramid_loss_weight: 1\n  remove_pyramid_loss: 50000\n  # perceptual loss (content and style losses)\n  perceptual_opt:\n    type: PerceptualLoss\n    layer_weights:\n      # before relu\n      'conv1_2': 0.1\n      'conv2_2': 0.1\n      'conv3_4': 1\n      'conv4_4': 1\n      'conv5_4': 1\n    vgg_type: vgg19\n    use_input_norm: true\n    perceptual_weight: !!float 1\n    style_weight: 50\n    range_norm: true\n    criterion: l1\n  # gan loss\n  gan_opt:\n    type: GANLoss\n    gan_type: wgan_softplus\n    loss_weight: !!float 1e-1\n  # r1 regularization for discriminator\n  r1_reg_weight: 10\n\n  net_d_iters: 1\n  net_d_init_iters: 0\n  net_d_reg_every: 16\n\n# validation settings\nval:\n  val_freq: !!float 5e3\n  save_img: true\n\n  metrics:\n    psnr: # metric name\n      type: calculate_psnr\n      crop_border: 0\n      test_y_channel: false\n\n# logging settings\nlogger:\n  print_freq: 100\n  save_checkpoint_freq: !!float 5e3\n  use_tb_logger: true\n  wandb:\n    project: ~\n    resume_id: ~\n\n# dist training settings\ndist_params:\n  backend: nccl\n  port: 29500\n\nfind_unused_parameters: true\n"
  },
  {
    "path": "requirements.txt",
    "content": "basicsr>=1.4.2\nfacexlib>=0.2.5\nlmdb\nnumpy\nopencv-python\npyyaml\nscipy\ntb-nightly\ntorch>=1.7\ntorchvision\ntqdm\nyapf\n"
  },
  {
    "path": "scripts/convert_gfpganv_to_clean.py",
    "content": "import argparse\nimport math\nimport torch\n\nfrom gfpgan.archs.gfpganv1_clean_arch import GFPGANv1Clean\n\n\ndef modify_checkpoint(checkpoint_bilinear, checkpoint_clean):\n    for ori_k, ori_v in checkpoint_bilinear.items():\n        if 'stylegan_decoder' in ori_k:\n            if 'style_mlp' in ori_k:  # style_mlp_layers\n                lr_mul = 0.01\n                prefix, name, idx, var = ori_k.split('.')\n                idx = (int(idx) * 2) - 1\n                crt_k = f'{prefix}.{name}.{idx}.{var}'\n                if var == 'weight':\n                    _, c_in = ori_v.size()\n                    scale = (1 / math.sqrt(c_in)) * lr_mul\n                    crt_v = ori_v * scale * 2**0.5\n                else:\n                    crt_v = ori_v * lr_mul * 2**0.5\n                checkpoint_clean[crt_k] = crt_v\n            elif 'modulation' in ori_k:  # modulation in StyleConv\n                lr_mul = 1\n                crt_k = ori_k\n                var = ori_k.split('.')[-1]\n                if var == 'weight':\n                    _, c_in = ori_v.size()\n                    scale = (1 / math.sqrt(c_in)) * lr_mul\n                    crt_v = ori_v * scale\n                else:\n                    crt_v = ori_v * lr_mul\n                checkpoint_clean[crt_k] = crt_v\n            elif 'style_conv' in ori_k:\n                # StyleConv in style_conv1 and style_convs\n                if 'activate' in ori_k:  # FusedLeakyReLU\n                    # eg. style_conv1.activate.bias\n                    # eg. style_convs.13.activate.bias\n                    split_rlt = ori_k.split('.')\n                    if len(split_rlt) == 4:\n                        prefix, name, _, var = split_rlt\n                        crt_k = f'{prefix}.{name}.{var}'\n                    elif len(split_rlt) == 5:\n                        prefix, name, idx, _, var = split_rlt\n                        crt_k = f'{prefix}.{name}.{idx}.{var}'\n                    crt_v = ori_v * 2**0.5  # 2**0.5 used in FusedLeakyReLU\n                    c = crt_v.size(0)\n                    checkpoint_clean[crt_k] = crt_v.view(1, c, 1, 1)\n                elif 'modulated_conv' in ori_k:\n                    # eg. style_conv1.modulated_conv.weight\n                    # eg. style_convs.13.modulated_conv.weight\n                    _, c_out, c_in, k1, k2 = ori_v.size()\n                    scale = 1 / math.sqrt(c_in * k1 * k2)\n                    crt_k = ori_k\n                    checkpoint_clean[crt_k] = ori_v * scale\n                elif 'weight' in ori_k:\n                    crt_k = ori_k\n                    checkpoint_clean[crt_k] = ori_v * 2**0.5\n            elif 'to_rgb' in ori_k:  # StyleConv in to_rgb1 and to_rgbs\n                if 'modulated_conv' in ori_k:\n                    # eg. to_rgb1.modulated_conv.weight\n                    # eg. to_rgbs.5.modulated_conv.weight\n                    _, c_out, c_in, k1, k2 = ori_v.size()\n                    scale = 1 / math.sqrt(c_in * k1 * k2)\n                    crt_k = ori_k\n                    checkpoint_clean[crt_k] = ori_v * scale\n                else:\n                    crt_k = ori_k\n                    checkpoint_clean[crt_k] = ori_v\n            else:\n                crt_k = ori_k\n                checkpoint_clean[crt_k] = ori_v\n            # end of 'stylegan_decoder'\n        elif 'conv_body_first' in ori_k or 'final_conv' in ori_k:\n            # key name\n            name, _, var = ori_k.split('.')\n            crt_k = f'{name}.{var}'\n            # weight and bias\n            if var == 'weight':\n                c_out, c_in, k1, k2 = ori_v.size()\n                scale = 1 / math.sqrt(c_in * k1 * k2)\n                checkpoint_clean[crt_k] = ori_v * scale * 2**0.5\n            else:\n                checkpoint_clean[crt_k] = ori_v * 2**0.5\n        elif 'conv_body' in ori_k:\n            if 'conv_body_up' in ori_k:\n                ori_k = ori_k.replace('conv2.weight', 'conv2.1.weight')\n                ori_k = ori_k.replace('skip.weight', 'skip.1.weight')\n            name1, idx1, name2, _, var = ori_k.split('.')\n            crt_k = f'{name1}.{idx1}.{name2}.{var}'\n            if name2 == 'skip':\n                c_out, c_in, k1, k2 = ori_v.size()\n                scale = 1 / math.sqrt(c_in * k1 * k2)\n                checkpoint_clean[crt_k] = ori_v * scale / 2**0.5\n            else:\n                if var == 'weight':\n                    c_out, c_in, k1, k2 = ori_v.size()\n                    scale = 1 / math.sqrt(c_in * k1 * k2)\n                    checkpoint_clean[crt_k] = ori_v * scale\n                else:\n                    checkpoint_clean[crt_k] = ori_v\n                if 'conv1' in ori_k:\n                    checkpoint_clean[crt_k] *= 2**0.5\n        elif 'toRGB' in ori_k:\n            crt_k = ori_k\n            if 'weight' in ori_k:\n                c_out, c_in, k1, k2 = ori_v.size()\n                scale = 1 / math.sqrt(c_in * k1 * k2)\n                checkpoint_clean[crt_k] = ori_v * scale\n            else:\n                checkpoint_clean[crt_k] = ori_v\n        elif 'final_linear' in ori_k:\n            crt_k = ori_k\n            if 'weight' in ori_k:\n                _, c_in = ori_v.size()\n                scale = 1 / math.sqrt(c_in)\n                checkpoint_clean[crt_k] = ori_v * scale\n            else:\n                checkpoint_clean[crt_k] = ori_v\n        elif 'condition' in ori_k:\n            crt_k = ori_k\n            if '0.weight' in ori_k:\n                c_out, c_in, k1, k2 = ori_v.size()\n                scale = 1 / math.sqrt(c_in * k1 * k2)\n                checkpoint_clean[crt_k] = ori_v * scale * 2**0.5\n            elif '0.bias' in ori_k:\n                checkpoint_clean[crt_k] = ori_v * 2**0.5\n            elif '2.weight' in ori_k:\n                c_out, c_in, k1, k2 = ori_v.size()\n                scale = 1 / math.sqrt(c_in * k1 * k2)\n                checkpoint_clean[crt_k] = ori_v * scale\n            elif '2.bias' in ori_k:\n                checkpoint_clean[crt_k] = ori_v\n\n    return checkpoint_clean\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--ori_path', type=str, help='Path to the original model')\n    parser.add_argument('--narrow', type=float, default=1)\n    parser.add_argument('--channel_multiplier', type=float, default=2)\n    parser.add_argument('--save_path', type=str)\n    args = parser.parse_args()\n\n    ori_ckpt = torch.load(args.ori_path)['params_ema']\n\n    net = GFPGANv1Clean(\n        512,\n        num_style_feat=512,\n        channel_multiplier=args.channel_multiplier,\n        decoder_load_path=None,\n        fix_decoder=False,\n        # for stylegan decoder\n        num_mlp=8,\n        input_is_latent=True,\n        different_w=True,\n        narrow=args.narrow,\n        sft_half=True)\n    crt_ckpt = net.state_dict()\n\n    crt_ckpt = modify_checkpoint(ori_ckpt, crt_ckpt)\n    print(f'Save to {args.save_path}.')\n    torch.save(dict(params_ema=crt_ckpt), args.save_path, _use_new_zipfile_serialization=False)\n"
  },
  {
    "path": "scripts/parse_landmark.py",
    "content": "import cv2\nimport json\nimport numpy as np\nimport os\nimport torch\nfrom basicsr.utils import FileClient, imfrombytes\nfrom collections import OrderedDict\n\n# ---------------------------- This script is used to parse facial landmarks ------------------------------------- #\n# Configurations\nsave_img = False\nscale = 0.5  # 0.5 for official FFHQ (512x512), 1 for others\nenlarge_ratio = 1.4  # only for eyes\njson_path = 'ffhq-dataset-v2.json'\nface_path = 'datasets/ffhq/ffhq_512.lmdb'\nsave_path = './FFHQ_eye_mouth_landmarks_512.pth'\n\nprint('Load JSON metadata...')\n# use the official json file in FFHQ dataset\nwith open(json_path, 'rb') as f:\n    json_data = json.load(f, object_pairs_hook=OrderedDict)\n\nprint('Open LMDB file...')\n# read ffhq images\nfile_client = FileClient('lmdb', db_paths=face_path)\nwith open(os.path.join(face_path, 'meta_info.txt')) as fin:\n    paths = [line.split('.')[0] for line in fin]\n\nsave_dict = {}\n\nfor item_idx, item in enumerate(json_data.values()):\n    print(f'\\r{item_idx} / {len(json_data)}, {item[\"image\"][\"file_path\"]} ', end='', flush=True)\n\n    # parse landmarks\n    lm = np.array(item['image']['face_landmarks'])\n    lm = lm * scale\n\n    item_dict = {}\n    # get image\n    if save_img:\n        img_bytes = file_client.get(paths[item_idx])\n        img = imfrombytes(img_bytes, float32=True)\n\n    # get landmarks for each component\n    map_left_eye = list(range(36, 42))\n    map_right_eye = list(range(42, 48))\n    map_mouth = list(range(48, 68))\n\n    # eye_left\n    mean_left_eye = np.mean(lm[map_left_eye], 0)  # (x, y)\n    half_len_left_eye = np.max((np.max(np.max(lm[map_left_eye], 0) - np.min(lm[map_left_eye], 0)) / 2, 16))\n    item_dict['left_eye'] = [mean_left_eye[0], mean_left_eye[1], half_len_left_eye]\n    # mean_left_eye[0] = 512 - mean_left_eye[0]  # for testing flip\n    half_len_left_eye *= enlarge_ratio\n    loc_left_eye = np.hstack((mean_left_eye - half_len_left_eye + 1, mean_left_eye + half_len_left_eye)).astype(int)\n    if save_img:\n        eye_left_img = img[loc_left_eye[1]:loc_left_eye[3], loc_left_eye[0]:loc_left_eye[2], :]\n        cv2.imwrite(f'tmp/{item_idx:08d}_eye_left.png', eye_left_img * 255)\n\n    # eye_right\n    mean_right_eye = np.mean(lm[map_right_eye], 0)\n    half_len_right_eye = np.max((np.max(np.max(lm[map_right_eye], 0) - np.min(lm[map_right_eye], 0)) / 2, 16))\n    item_dict['right_eye'] = [mean_right_eye[0], mean_right_eye[1], half_len_right_eye]\n    # mean_right_eye[0] = 512 - mean_right_eye[0]  # # for testing flip\n    half_len_right_eye *= enlarge_ratio\n    loc_right_eye = np.hstack(\n        (mean_right_eye - half_len_right_eye + 1, mean_right_eye + half_len_right_eye)).astype(int)\n    if save_img:\n        eye_right_img = img[loc_right_eye[1]:loc_right_eye[3], loc_right_eye[0]:loc_right_eye[2], :]\n        cv2.imwrite(f'tmp/{item_idx:08d}_eye_right.png', eye_right_img * 255)\n\n    # mouth\n    mean_mouth = np.mean(lm[map_mouth], 0)\n    half_len_mouth = np.max((np.max(np.max(lm[map_mouth], 0) - np.min(lm[map_mouth], 0)) / 2, 16))\n    item_dict['mouth'] = [mean_mouth[0], mean_mouth[1], half_len_mouth]\n    # mean_mouth[0] = 512 - mean_mouth[0]  # for testing flip\n    loc_mouth = np.hstack((mean_mouth - half_len_mouth + 1, mean_mouth + half_len_mouth)).astype(int)\n    if save_img:\n        mouth_img = img[loc_mouth[1]:loc_mouth[3], loc_mouth[0]:loc_mouth[2], :]\n        cv2.imwrite(f'tmp/{item_idx:08d}_mouth.png', mouth_img * 255)\n\n    save_dict[f'{item_idx:08d}'] = item_dict\n\nprint('Save...')\ntorch.save(save_dict, save_path)\n"
  },
  {
    "path": "setup.cfg",
    "content": "[flake8]\nignore =\n    # line break before binary operator (W503)\n    W503,\n    # line break after binary operator (W504)\n    W504,\nmax-line-length=120\n\n[yapf]\nbased_on_style = pep8\ncolumn_limit = 120\nblank_line_before_nested_class_or_def = true\nsplit_before_expression_after_opening_paren = true\n\n[isort]\nline_length = 120\nmulti_line_output = 0\nknown_standard_library = pkg_resources,setuptools\nknown_first_party = gfpgan\nknown_third_party = basicsr,cv2,facexlib,numpy,pytest,torch,torchvision,tqdm,yaml\nno_lines_before = STDLIB,LOCALFOLDER\ndefault_section = THIRDPARTY\n\n[codespell]\nskip = .git,./docs/build\ncount =\nquiet-level = 3\n\n[aliases]\ntest=pytest\n\n[tool:pytest]\naddopts=tests/\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/env python\n\nfrom setuptools import find_packages, setup\n\nimport os\nimport subprocess\nimport time\n\nversion_file = 'gfpgan/version.py'\n\n\ndef readme():\n    with open('README.md', encoding='utf-8') as f:\n        content = f.read()\n    return content\n\n\ndef get_git_hash():\n\n    def _minimal_ext_cmd(cmd):\n        # construct minimal environment\n        env = {}\n        for k in ['SYSTEMROOT', 'PATH', 'HOME']:\n            v = os.environ.get(k)\n            if v is not None:\n                env[k] = v\n        # LANGUAGE is used on win32\n        env['LANGUAGE'] = 'C'\n        env['LANG'] = 'C'\n        env['LC_ALL'] = 'C'\n        out = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=env).communicate()[0]\n        return out\n\n    try:\n        out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])\n        sha = out.strip().decode('ascii')\n    except OSError:\n        sha = 'unknown'\n\n    return sha\n\n\ndef get_hash():\n    if os.path.exists('.git'):\n        sha = get_git_hash()[:7]\n    else:\n        sha = 'unknown'\n\n    return sha\n\n\ndef write_version_py():\n    content = \"\"\"# GENERATED VERSION FILE\n# TIME: {}\n__version__ = '{}'\n__gitsha__ = '{}'\nversion_info = ({})\n\"\"\"\n    sha = get_hash()\n    with open('VERSION', 'r') as f:\n        SHORT_VERSION = f.read().strip()\n    VERSION_INFO = ', '.join([x if x.isdigit() else f'\"{x}\"' for x in SHORT_VERSION.split('.')])\n\n    version_file_str = content.format(time.asctime(), SHORT_VERSION, sha, VERSION_INFO)\n    with open(version_file, 'w') as f:\n        f.write(version_file_str)\n\n\ndef get_version():\n    with open(version_file, 'r') as f:\n        exec(compile(f.read(), version_file, 'exec'))\n    return locals()['__version__']\n\n\ndef get_requirements(filename='requirements.txt'):\n    here = os.path.dirname(os.path.realpath(__file__))\n    with open(os.path.join(here, filename), 'r') as f:\n        requires = [line.replace('\\n', '') for line in f.readlines()]\n    return requires\n\n\nif __name__ == '__main__':\n    write_version_py()\n    setup(\n        name='gfpgan',\n        version=get_version(),\n        description='GFPGAN aims at developing Practical Algorithms for Real-world Face Restoration',\n        long_description=readme(),\n        long_description_content_type='text/markdown',\n        author='Xintao Wang',\n        author_email='xintao.wang@outlook.com',\n        keywords='computer vision, pytorch, image restoration, super-resolution, face restoration, gan, gfpgan',\n        url='https://github.com/TencentARC/GFPGAN',\n        include_package_data=True,\n        packages=find_packages(exclude=('options', 'datasets', 'experiments', 'results', 'tb_logger', 'wandb')),\n        classifiers=[\n            'Development Status :: 4 - Beta',\n            'License :: OSI Approved :: Apache Software License',\n            'Operating System :: OS Independent',\n            'Programming Language :: Python :: 3',\n            'Programming Language :: Python :: 3.7',\n            'Programming Language :: Python :: 3.8',\n        ],\n        license='Apache License Version 2.0',\n        setup_requires=['cython', 'numpy'],\n        install_requires=get_requirements(),\n        zip_safe=False)\n"
  },
  {
    "path": "tests/data/ffhq_gt.lmdb/meta_info.txt",
    "content": "00000000.png (512,512,3) 1\n"
  },
  {
    "path": "tests/data/test_ffhq_degradation_dataset.yml",
    "content": "name: UnitTest\ntype: FFHQDegradationDataset\ndataroot_gt: tests/data/gt\nio_backend:\n  type: disk\n\nuse_hflip: true\nmean: [0.5, 0.5, 0.5]\nstd: [0.5, 0.5, 0.5]\nout_size: 512\n\nblur_kernel_size: 41\nkernel_list: ['iso', 'aniso']\nkernel_prob: [0.5, 0.5]\nblur_sigma: [0.1, 10]\ndownsample_range: [0.8, 8]\nnoise_range: [0, 20]\njpeg_range: [60, 100]\n\n# color jitter and gray\ncolor_jitter_prob: 1\ncolor_jitter_shift: 20\ncolor_jitter_pt_prob: 1\ngray_prob: 1\n"
  },
  {
    "path": "tests/data/test_gfpgan_model.yml",
    "content": "num_gpu: 1\nmanual_seed: 0\nis_train: True\ndist: False\n\n# network structures\nnetwork_g:\n  type: GFPGANv1\n  out_size: 512\n  num_style_feat: 512\n  channel_multiplier: 1\n  resample_kernel: [1, 3, 3, 1]\n  decoder_load_path: ~\n  fix_decoder: true\n  num_mlp: 8\n  lr_mlp: 0.01\n  input_is_latent: true\n  different_w: true\n  narrow: 0.5\n  sft_half: true\n\nnetwork_d:\n  type: StyleGAN2Discriminator\n  out_size: 512\n  channel_multiplier: 1\n  resample_kernel: [1, 3, 3, 1]\n\nnetwork_d_left_eye:\n  type: FacialComponentDiscriminator\n\nnetwork_d_right_eye:\n  type: FacialComponentDiscriminator\n\nnetwork_d_mouth:\n  type: FacialComponentDiscriminator\n\nnetwork_identity:\n  type: ResNetArcFace\n  block: IRBlock\n  layers: [2, 2, 2, 2]\n  use_se: False\n\n# path\npath:\n  pretrain_network_g: ~\n  param_key_g: params_ema\n  strict_load_g: ~\n  pretrain_network_d: ~\n  pretrain_network_d_left_eye: ~\n  pretrain_network_d_right_eye: ~\n  pretrain_network_d_mouth: ~\n  pretrain_network_identity: ~\n  # resume\n  resume_state: ~\n  ignore_resume_networks: ['network_identity']\n\n# training settings\ntrain:\n  optim_g:\n    type: Adam\n    lr: !!float 2e-3\n  optim_d:\n    type: Adam\n    lr: !!float 2e-3\n  optim_component:\n    type: Adam\n    lr: !!float 2e-3\n\n  scheduler:\n    type: MultiStepLR\n    milestones: [600000, 700000]\n    gamma: 0.5\n\n  total_iter: 800000\n  warmup_iter: -1  # no warm up\n\n  # losses\n  # pixel loss\n  pixel_opt:\n    type: L1Loss\n    loss_weight: !!float 1e-1\n    reduction: mean\n  # L1 loss used in pyramid loss, component style loss and identity loss\n  L1_opt:\n    type: L1Loss\n    loss_weight: 1\n    reduction: mean\n\n  # image pyramid loss\n  pyramid_loss_weight: 1\n  remove_pyramid_loss: 50000\n  # perceptual loss (content and style losses)\n  perceptual_opt:\n    type: PerceptualLoss\n    layer_weights:\n      # before relu\n      'conv1_2': 0.1\n      'conv2_2': 0.1\n      'conv3_4': 1\n      'conv4_4': 1\n      'conv5_4': 1\n    vgg_type: vgg19\n    use_input_norm: true\n    perceptual_weight: !!float 1\n    style_weight: 50\n    range_norm: true\n    criterion: l1\n  # gan loss\n  gan_opt:\n    type: GANLoss\n    gan_type: wgan_softplus\n    loss_weight: !!float 1e-1\n  # r1 regularization for discriminator\n  r1_reg_weight: 10\n  # facial component loss\n  gan_component_opt:\n    type: GANLoss\n    gan_type: vanilla\n    real_label_val: 1.0\n    fake_label_val: 0.0\n    loss_weight: !!float 1\n  comp_style_weight: 200\n  # identity loss\n  identity_weight: 10\n\n  net_d_iters: 1\n  net_d_init_iters: 0\n  net_d_reg_every: 1\n\n# validation settings\nval:\n  val_freq: !!float 5e3\n  save_img: True\n  use_pbar: True\n\n  metrics:\n    psnr: # metric name\n      type: calculate_psnr\n      crop_border: 0\n      test_y_channel: false\n"
  },
  {
    "path": "tests/test_arcface_arch.py",
    "content": "import torch\n\nfrom gfpgan.archs.arcface_arch import BasicBlock, Bottleneck, ResNetArcFace\n\n\ndef test_resnetarcface():\n    \"\"\"Test arch: ResNetArcFace.\"\"\"\n\n    # model init and forward (gpu)\n    if torch.cuda.is_available():\n        net = ResNetArcFace(block='IRBlock', layers=(2, 2, 2, 2), use_se=True).cuda().eval()\n        img = torch.rand((1, 1, 128, 128), dtype=torch.float32).cuda()\n        output = net(img)\n        assert output.shape == (1, 512)\n\n        # -------------------- without SE block ----------------------- #\n        net = ResNetArcFace(block='IRBlock', layers=(2, 2, 2, 2), use_se=False).cuda().eval()\n        output = net(img)\n        assert output.shape == (1, 512)\n\n\ndef test_basicblock():\n    \"\"\"Test the BasicBlock in arcface_arch\"\"\"\n    block = BasicBlock(1, 3, stride=1, downsample=None).cuda()\n    img = torch.rand((1, 1, 12, 12), dtype=torch.float32).cuda()\n    output = block(img)\n    assert output.shape == (1, 3, 12, 12)\n\n    # ----------------- use the downsmaple module--------------- #\n    downsample = torch.nn.UpsamplingNearest2d(scale_factor=0.5).cuda()\n    block = BasicBlock(1, 3, stride=2, downsample=downsample).cuda()\n    img = torch.rand((1, 1, 12, 12), dtype=torch.float32).cuda()\n    output = block(img)\n    assert output.shape == (1, 3, 6, 6)\n\n\ndef test_bottleneck():\n    \"\"\"Test the Bottleneck in arcface_arch\"\"\"\n    block = Bottleneck(1, 1, stride=1, downsample=None).cuda()\n    img = torch.rand((1, 1, 12, 12), dtype=torch.float32).cuda()\n    output = block(img)\n    assert output.shape == (1, 4, 12, 12)\n\n    # ----------------- use the downsmaple module--------------- #\n    downsample = torch.nn.UpsamplingNearest2d(scale_factor=0.5).cuda()\n    block = Bottleneck(1, 1, stride=2, downsample=downsample).cuda()\n    img = torch.rand((1, 1, 12, 12), dtype=torch.float32).cuda()\n    output = block(img)\n    assert output.shape == (1, 4, 6, 6)\n"
  },
  {
    "path": "tests/test_ffhq_degradation_dataset.py",
    "content": "import pytest\nimport yaml\n\nfrom gfpgan.data.ffhq_degradation_dataset import FFHQDegradationDataset\n\n\ndef test_ffhq_degradation_dataset():\n\n    with open('tests/data/test_ffhq_degradation_dataset.yml', mode='r') as f:\n        opt = yaml.load(f, Loader=yaml.FullLoader)\n\n    dataset = FFHQDegradationDataset(opt)\n    assert dataset.io_backend_opt['type'] == 'disk'  # io backend\n    assert len(dataset) == 1  # whether to read correct meta info\n    assert dataset.kernel_list == ['iso', 'aniso']  # correct initialization the degradation configurations\n    assert dataset.color_jitter_prob == 1\n\n    # test __getitem__\n    result = dataset.__getitem__(0)\n    # check returned keys\n    expected_keys = ['gt', 'lq', 'gt_path']\n    assert set(expected_keys).issubset(set(result.keys()))\n    # check shape and contents\n    assert result['gt'].shape == (3, 512, 512)\n    assert result['lq'].shape == (3, 512, 512)\n    assert result['gt_path'] == 'tests/data/gt/00000000.png'\n\n    # ------------------ test with probability = 0 -------------------- #\n    opt['color_jitter_prob'] = 0\n    opt['color_jitter_pt_prob'] = 0\n    opt['gray_prob'] = 0\n    opt['io_backend'] = dict(type='disk')\n    dataset = FFHQDegradationDataset(opt)\n    assert dataset.io_backend_opt['type'] == 'disk'  # io backend\n    assert len(dataset) == 1  # whether to read correct meta info\n    assert dataset.kernel_list == ['iso', 'aniso']  # correct initialization the degradation configurations\n    assert dataset.color_jitter_prob == 0\n\n    # test __getitem__\n    result = dataset.__getitem__(0)\n    # check returned keys\n    expected_keys = ['gt', 'lq', 'gt_path']\n    assert set(expected_keys).issubset(set(result.keys()))\n    # check shape and contents\n    assert result['gt'].shape == (3, 512, 512)\n    assert result['lq'].shape == (3, 512, 512)\n    assert result['gt_path'] == 'tests/data/gt/00000000.png'\n\n    # ------------------ test lmdb backend -------------------- #\n    opt['dataroot_gt'] = 'tests/data/ffhq_gt.lmdb'\n    opt['io_backend'] = dict(type='lmdb')\n\n    dataset = FFHQDegradationDataset(opt)\n    assert dataset.io_backend_opt['type'] == 'lmdb'  # io backend\n    assert len(dataset) == 1  # whether to read correct meta info\n    assert dataset.kernel_list == ['iso', 'aniso']  # correct initialization the degradation configurations\n    assert dataset.color_jitter_prob == 0\n\n    # test __getitem__\n    result = dataset.__getitem__(0)\n    # check returned keys\n    expected_keys = ['gt', 'lq', 'gt_path']\n    assert set(expected_keys).issubset(set(result.keys()))\n    # check shape and contents\n    assert result['gt'].shape == (3, 512, 512)\n    assert result['lq'].shape == (3, 512, 512)\n    assert result['gt_path'] == '00000000'\n\n    # ------------------ test with crop_components -------------------- #\n    opt['crop_components'] = True\n    opt['component_path'] = 'tests/data/test_eye_mouth_landmarks.pth'\n    opt['eye_enlarge_ratio'] = 1.4\n    opt['gt_gray'] = True\n    opt['io_backend'] = dict(type='lmdb')\n\n    dataset = FFHQDegradationDataset(opt)\n    assert dataset.crop_components is True\n\n    # test __getitem__\n    result = dataset.__getitem__(0)\n    # check returned keys\n    expected_keys = ['gt', 'lq', 'gt_path', 'loc_left_eye', 'loc_right_eye', 'loc_mouth']\n    assert set(expected_keys).issubset(set(result.keys()))\n    # check shape and contents\n    assert result['gt'].shape == (3, 512, 512)\n    assert result['lq'].shape == (3, 512, 512)\n    assert result['gt_path'] == '00000000'\n    assert result['loc_left_eye'].shape == (4, )\n    assert result['loc_right_eye'].shape == (4, )\n    assert result['loc_mouth'].shape == (4, )\n\n    # ------------------ lmdb backend should have paths ends with lmdb -------------------- #\n    with pytest.raises(ValueError):\n        opt['dataroot_gt'] = 'tests/data/gt'\n        opt['io_backend'] = dict(type='lmdb')\n        dataset = FFHQDegradationDataset(opt)\n"
  },
  {
    "path": "tests/test_gfpgan_arch.py",
    "content": "import torch\n\nfrom gfpgan.archs.gfpganv1_arch import FacialComponentDiscriminator, GFPGANv1, StyleGAN2GeneratorSFT\nfrom gfpgan.archs.gfpganv1_clean_arch import GFPGANv1Clean, StyleGAN2GeneratorCSFT\n\n\ndef test_stylegan2generatorsft():\n    \"\"\"Test arch: StyleGAN2GeneratorSFT.\"\"\"\n\n    # model init and forward (gpu)\n    if torch.cuda.is_available():\n        net = StyleGAN2GeneratorSFT(\n            out_size=32,\n            num_style_feat=512,\n            num_mlp=8,\n            channel_multiplier=1,\n            resample_kernel=(1, 3, 3, 1),\n            lr_mlp=0.01,\n            narrow=1,\n            sft_half=False).cuda().eval()\n        style = torch.rand((1, 512), dtype=torch.float32).cuda()\n        condition1 = torch.rand((1, 512, 8, 8), dtype=torch.float32).cuda()\n        condition2 = torch.rand((1, 512, 16, 16), dtype=torch.float32).cuda()\n        condition3 = torch.rand((1, 512, 32, 32), dtype=torch.float32).cuda()\n        conditions = [condition1, condition1, condition2, condition2, condition3, condition3]\n        output = net([style], conditions)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert output[1] is None\n\n        # -------------------- with return_latents ----------------------- #\n        output = net([style], conditions, return_latents=True)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert len(output[1]) == 1\n        # check latent\n        assert output[1][0].shape == (8, 512)\n\n        # -------------------- with randomize_noise = False ----------------------- #\n        output = net([style], conditions, randomize_noise=False)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert output[1] is None\n\n        # -------------------- with truncation = 0.5 and mixing----------------------- #\n        output = net([style, style], conditions, truncation=0.5, truncation_latent=style)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert output[1] is None\n\n\ndef test_gfpganv1():\n    \"\"\"Test arch: GFPGANv1.\"\"\"\n\n    # model init and forward (gpu)\n    if torch.cuda.is_available():\n        net = GFPGANv1(\n            out_size=32,\n            num_style_feat=512,\n            channel_multiplier=1,\n            resample_kernel=(1, 3, 3, 1),\n            decoder_load_path=None,\n            fix_decoder=True,\n            # for stylegan decoder\n            num_mlp=8,\n            lr_mlp=0.01,\n            input_is_latent=False,\n            different_w=False,\n            narrow=1,\n            sft_half=True).cuda().eval()\n        img = torch.rand((1, 3, 32, 32), dtype=torch.float32).cuda()\n        output = net(img)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert len(output[1]) == 3\n        # check out_rgbs for intermediate loss\n        assert output[1][0].shape == (1, 3, 8, 8)\n        assert output[1][1].shape == (1, 3, 16, 16)\n        assert output[1][2].shape == (1, 3, 32, 32)\n\n        # -------------------- with different_w = True ----------------------- #\n        net = GFPGANv1(\n            out_size=32,\n            num_style_feat=512,\n            channel_multiplier=1,\n            resample_kernel=(1, 3, 3, 1),\n            decoder_load_path=None,\n            fix_decoder=True,\n            # for stylegan decoder\n            num_mlp=8,\n            lr_mlp=0.01,\n            input_is_latent=False,\n            different_w=True,\n            narrow=1,\n            sft_half=True).cuda().eval()\n        img = torch.rand((1, 3, 32, 32), dtype=torch.float32).cuda()\n        output = net(img)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert len(output[1]) == 3\n        # check out_rgbs for intermediate loss\n        assert output[1][0].shape == (1, 3, 8, 8)\n        assert output[1][1].shape == (1, 3, 16, 16)\n        assert output[1][2].shape == (1, 3, 32, 32)\n\n\ndef test_facialcomponentdiscriminator():\n    \"\"\"Test arch: FacialComponentDiscriminator.\"\"\"\n\n    # model init and forward (gpu)\n    if torch.cuda.is_available():\n        net = FacialComponentDiscriminator().cuda().eval()\n        img = torch.rand((1, 3, 32, 32), dtype=torch.float32).cuda()\n        output = net(img)\n        assert len(output) == 2\n        assert output[0].shape == (1, 1, 8, 8)\n        assert output[1] is None\n\n        # -------------------- return intermediate features ----------------------- #\n        output = net(img, return_feats=True)\n        assert len(output) == 2\n        assert output[0].shape == (1, 1, 8, 8)\n        assert len(output[1]) == 2\n        assert output[1][0].shape == (1, 128, 16, 16)\n        assert output[1][1].shape == (1, 256, 8, 8)\n\n\ndef test_stylegan2generatorcsft():\n    \"\"\"Test arch: StyleGAN2GeneratorCSFT.\"\"\"\n\n    # model init and forward (gpu)\n    if torch.cuda.is_available():\n        net = StyleGAN2GeneratorCSFT(\n            out_size=32, num_style_feat=512, num_mlp=8, channel_multiplier=1, narrow=1, sft_half=False).cuda().eval()\n        style = torch.rand((1, 512), dtype=torch.float32).cuda()\n        condition1 = torch.rand((1, 512, 8, 8), dtype=torch.float32).cuda()\n        condition2 = torch.rand((1, 512, 16, 16), dtype=torch.float32).cuda()\n        condition3 = torch.rand((1, 512, 32, 32), dtype=torch.float32).cuda()\n        conditions = [condition1, condition1, condition2, condition2, condition3, condition3]\n        output = net([style], conditions)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert output[1] is None\n\n        # -------------------- with return_latents ----------------------- #\n        output = net([style], conditions, return_latents=True)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert len(output[1]) == 1\n        # check latent\n        assert output[1][0].shape == (8, 512)\n\n        # -------------------- with randomize_noise = False ----------------------- #\n        output = net([style], conditions, randomize_noise=False)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert output[1] is None\n\n        # -------------------- with truncation = 0.5 and mixing----------------------- #\n        output = net([style, style], conditions, truncation=0.5, truncation_latent=style)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert output[1] is None\n\n\ndef test_gfpganv1clean():\n    \"\"\"Test arch: GFPGANv1Clean.\"\"\"\n\n    # model init and forward (gpu)\n    if torch.cuda.is_available():\n        net = GFPGANv1Clean(\n            out_size=32,\n            num_style_feat=512,\n            channel_multiplier=1,\n            decoder_load_path=None,\n            fix_decoder=True,\n            # for stylegan decoder\n            num_mlp=8,\n            input_is_latent=False,\n            different_w=False,\n            narrow=1,\n            sft_half=True).cuda().eval()\n\n        img = torch.rand((1, 3, 32, 32), dtype=torch.float32).cuda()\n        output = net(img)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert len(output[1]) == 3\n        # check out_rgbs for intermediate loss\n        assert output[1][0].shape == (1, 3, 8, 8)\n        assert output[1][1].shape == (1, 3, 16, 16)\n        assert output[1][2].shape == (1, 3, 32, 32)\n\n        # -------------------- with different_w = True ----------------------- #\n        net = GFPGANv1Clean(\n            out_size=32,\n            num_style_feat=512,\n            channel_multiplier=1,\n            decoder_load_path=None,\n            fix_decoder=True,\n            # for stylegan decoder\n            num_mlp=8,\n            input_is_latent=False,\n            different_w=True,\n            narrow=1,\n            sft_half=True).cuda().eval()\n        img = torch.rand((1, 3, 32, 32), dtype=torch.float32).cuda()\n        output = net(img)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert len(output[1]) == 3\n        # check out_rgbs for intermediate loss\n        assert output[1][0].shape == (1, 3, 8, 8)\n        assert output[1][1].shape == (1, 3, 16, 16)\n        assert output[1][2].shape == (1, 3, 32, 32)\n"
  },
  {
    "path": "tests/test_gfpgan_model.py",
    "content": "import tempfile\nimport torch\nimport yaml\nfrom basicsr.archs.stylegan2_arch import StyleGAN2Discriminator\nfrom basicsr.data.paired_image_dataset import PairedImageDataset\nfrom basicsr.losses.losses import GANLoss, L1Loss, PerceptualLoss\n\nfrom gfpgan.archs.arcface_arch import ResNetArcFace\nfrom gfpgan.archs.gfpganv1_arch import FacialComponentDiscriminator, GFPGANv1\nfrom gfpgan.models.gfpgan_model import GFPGANModel\n\n\ndef test_gfpgan_model():\n    with open('tests/data/test_gfpgan_model.yml', mode='r') as f:\n        opt = yaml.load(f, Loader=yaml.FullLoader)\n\n    # build model\n    model = GFPGANModel(opt)\n    # test attributes\n    assert model.__class__.__name__ == 'GFPGANModel'\n    assert isinstance(model.net_g, GFPGANv1)  # generator\n    assert isinstance(model.net_d, StyleGAN2Discriminator)  # discriminator\n    # facial component discriminators\n    assert isinstance(model.net_d_left_eye, FacialComponentDiscriminator)\n    assert isinstance(model.net_d_right_eye, FacialComponentDiscriminator)\n    assert isinstance(model.net_d_mouth, FacialComponentDiscriminator)\n    # identity network\n    assert isinstance(model.network_identity, ResNetArcFace)\n    # losses\n    assert isinstance(model.cri_pix, L1Loss)\n    assert isinstance(model.cri_perceptual, PerceptualLoss)\n    assert isinstance(model.cri_gan, GANLoss)\n    assert isinstance(model.cri_l1, L1Loss)\n    # optimizer\n    assert isinstance(model.optimizers[0], torch.optim.Adam)\n    assert isinstance(model.optimizers[1], torch.optim.Adam)\n\n    # prepare data\n    gt = torch.rand((1, 3, 512, 512), dtype=torch.float32)\n    lq = torch.rand((1, 3, 512, 512), dtype=torch.float32)\n    loc_left_eye = torch.rand((1, 4), dtype=torch.float32)\n    loc_right_eye = torch.rand((1, 4), dtype=torch.float32)\n    loc_mouth = torch.rand((1, 4), dtype=torch.float32)\n    data = dict(gt=gt, lq=lq, loc_left_eye=loc_left_eye, loc_right_eye=loc_right_eye, loc_mouth=loc_mouth)\n    model.feed_data(data)\n    # check data shape\n    assert model.lq.shape == (1, 3, 512, 512)\n    assert model.gt.shape == (1, 3, 512, 512)\n    assert model.loc_left_eyes.shape == (1, 4)\n    assert model.loc_right_eyes.shape == (1, 4)\n    assert model.loc_mouths.shape == (1, 4)\n\n    # ----------------- test optimize_parameters -------------------- #\n    model.feed_data(data)\n    model.optimize_parameters(1)\n    assert model.output.shape == (1, 3, 512, 512)\n    assert isinstance(model.log_dict, dict)\n    # check returned keys\n    expected_keys = [\n        'l_g_pix', 'l_g_percep', 'l_g_style', 'l_g_gan', 'l_g_gan_left_eye', 'l_g_gan_right_eye', 'l_g_gan_mouth',\n        'l_g_comp_style_loss', 'l_identity', 'l_d', 'real_score', 'fake_score', 'l_d_r1', 'l_d_left_eye',\n        'l_d_right_eye', 'l_d_mouth'\n    ]\n    assert set(expected_keys).issubset(set(model.log_dict.keys()))\n\n    # ----------------- remove pyramid_loss_weight-------------------- #\n    model.feed_data(data)\n    model.optimize_parameters(100000)  # large than remove_pyramid_loss = 50000\n    assert model.output.shape == (1, 3, 512, 512)\n    assert isinstance(model.log_dict, dict)\n    # check returned keys\n    expected_keys = [\n        'l_g_pix', 'l_g_percep', 'l_g_style', 'l_g_gan', 'l_g_gan_left_eye', 'l_g_gan_right_eye', 'l_g_gan_mouth',\n        'l_g_comp_style_loss', 'l_identity', 'l_d', 'real_score', 'fake_score', 'l_d_r1', 'l_d_left_eye',\n        'l_d_right_eye', 'l_d_mouth'\n    ]\n    assert set(expected_keys).issubset(set(model.log_dict.keys()))\n\n    # ----------------- test save -------------------- #\n    with tempfile.TemporaryDirectory() as tmpdir:\n        model.opt['path']['models'] = tmpdir\n        model.opt['path']['training_states'] = tmpdir\n        model.save(0, 1)\n\n    # ----------------- test the test function -------------------- #\n    model.test()\n    assert model.output.shape == (1, 3, 512, 512)\n    # delete net_g_ema\n    model.__delattr__('net_g_ema')\n    model.test()\n    assert model.output.shape == (1, 3, 512, 512)\n    assert model.net_g.training is True  # should back to training mode after testing\n\n    # ----------------- test nondist_validation -------------------- #\n    # construct dataloader\n    dataset_opt = dict(\n        name='Demo',\n        dataroot_gt='tests/data/gt',\n        dataroot_lq='tests/data/gt',\n        io_backend=dict(type='disk'),\n        scale=4,\n        phase='val')\n    dataset = PairedImageDataset(dataset_opt)\n    dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=1, shuffle=False, num_workers=0)\n    assert model.is_train is True\n    with tempfile.TemporaryDirectory() as tmpdir:\n        model.opt['path']['visualization'] = tmpdir\n        model.nondist_validation(dataloader, 1, None, save_img=True)\n        assert model.is_train is True\n        # check metric_results\n        assert 'psnr' in model.metric_results\n        assert isinstance(model.metric_results['psnr'], float)\n\n    # validation\n    with tempfile.TemporaryDirectory() as tmpdir:\n        model.opt['is_train'] = False\n        model.opt['val']['suffix'] = 'test'\n        model.opt['path']['visualization'] = tmpdir\n        model.opt['val']['pbar'] = True\n        model.nondist_validation(dataloader, 1, None, save_img=True)\n        # check metric_results\n        assert 'psnr' in model.metric_results\n        assert isinstance(model.metric_results['psnr'], float)\n\n        # if opt['val']['suffix'] is None\n        model.opt['val']['suffix'] = None\n        model.opt['name'] = 'demo'\n        model.opt['path']['visualization'] = tmpdir\n        model.nondist_validation(dataloader, 1, None, save_img=True)\n        # check metric_results\n        assert 'psnr' in model.metric_results\n        assert isinstance(model.metric_results['psnr'], float)\n"
  },
  {
    "path": "tests/test_stylegan2_clean_arch.py",
    "content": "import torch\n\nfrom gfpgan.archs.stylegan2_clean_arch import StyleGAN2GeneratorClean\n\n\ndef test_stylegan2generatorclean():\n    \"\"\"Test arch: StyleGAN2GeneratorClean.\"\"\"\n\n    # model init and forward (gpu)\n    if torch.cuda.is_available():\n        net = StyleGAN2GeneratorClean(\n            out_size=32, num_style_feat=512, num_mlp=8, channel_multiplier=1, narrow=0.5).cuda().eval()\n        style = torch.rand((1, 512), dtype=torch.float32).cuda()\n        output = net([style], input_is_latent=False)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert output[1] is None\n\n        # -------------------- with return_latents ----------------------- #\n        output = net([style], input_is_latent=True, return_latents=True)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert len(output[1]) == 1\n        # check latent\n        assert output[1][0].shape == (8, 512)\n\n        # -------------------- with randomize_noise = False ----------------------- #\n        output = net([style], randomize_noise=False)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert output[1] is None\n\n        # -------------------- with truncation = 0.5 and mixing----------------------- #\n        output = net([style, style], truncation=0.5, truncation_latent=style)\n        assert output[0].shape == (1, 3, 32, 32)\n        assert output[1] is None\n\n        # ------------------ test make_noise ----------------------- #\n        out = net.make_noise()\n        assert len(out) == 7\n        assert out[0].shape == (1, 1, 4, 4)\n        assert out[1].shape == (1, 1, 8, 8)\n        assert out[2].shape == (1, 1, 8, 8)\n        assert out[3].shape == (1, 1, 16, 16)\n        assert out[4].shape == (1, 1, 16, 16)\n        assert out[5].shape == (1, 1, 32, 32)\n        assert out[6].shape == (1, 1, 32, 32)\n\n        # ------------------ test get_latent ----------------------- #\n        out = net.get_latent(style)\n        assert out.shape == (1, 512)\n\n        # ------------------ test mean_latent ----------------------- #\n        out = net.mean_latent(2)\n        assert out.shape == (1, 512)\n"
  },
  {
    "path": "tests/test_utils.py",
    "content": "import cv2\nfrom facexlib.utils.face_restoration_helper import FaceRestoreHelper\n\nfrom gfpgan.archs.gfpganv1_arch import GFPGANv1\nfrom gfpgan.archs.gfpganv1_clean_arch import GFPGANv1Clean\nfrom gfpgan.utils import GFPGANer\n\n\ndef test_gfpganer():\n    # initialize with the clean model\n    restorer = GFPGANer(\n        model_path='experiments/pretrained_models/GFPGANCleanv1-NoCE-C2.pth',\n        upscale=2,\n        arch='clean',\n        channel_multiplier=2,\n        bg_upsampler=None)\n    # test attribute\n    assert isinstance(restorer.gfpgan, GFPGANv1Clean)\n    assert isinstance(restorer.face_helper, FaceRestoreHelper)\n\n    # initialize with the original model\n    restorer = GFPGANer(\n        model_path='experiments/pretrained_models/GFPGANv1.pth',\n        upscale=2,\n        arch='original',\n        channel_multiplier=1,\n        bg_upsampler=None)\n    # test attribute\n    assert isinstance(restorer.gfpgan, GFPGANv1)\n    assert isinstance(restorer.face_helper, FaceRestoreHelper)\n\n    # ------------------ test enhance ---------------- #\n    img = cv2.imread('tests/data/gt/00000000.png', cv2.IMREAD_COLOR)\n    result = restorer.enhance(img, has_aligned=False, paste_back=True)\n    assert result[0][0].shape == (512, 512, 3)\n    assert result[1][0].shape == (512, 512, 3)\n    assert result[2].shape == (1024, 1024, 3)\n\n    # with has_aligned=True\n    result = restorer.enhance(img, has_aligned=True, paste_back=False)\n    assert result[0][0].shape == (512, 512, 3)\n    assert result[1][0].shape == (512, 512, 3)\n    assert result[2] is None\n"
  }
]