b3h-young123 commited on
Commit
7cc2d87
·
verified ·
1 Parent(s): 514504e

Add files using upload-large-folder tool

Browse files
Files changed (35) hide show
  1. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/.gitattributes +31 -0
  2. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/.gitignore +144 -0
  3. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/README.md +13 -0
  4. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/app.py +766 -0
  5. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/a01.jpg +3 -0
  6. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/a02.jpg +3 -0
  7. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/a03.jpg +3 -0
  8. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/a04.jpg +3 -0
  9. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b01.jpg +3 -0
  10. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b02.jpg +3 -0
  11. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b03.jpg +3 -0
  12. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b04.jpg +3 -0
  13. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b05.jpg +3 -0
  14. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b06.jpg +3 -0
  15. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b07.jpg +3 -0
  16. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b08.jpg +3 -0
  17. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b09.jpg +3 -0
  18. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b10.jpg +3 -0
  19. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b11.jpg +3 -0
  20. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/bus.jpg +3 -0
  21. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c01.jpg +3 -0
  22. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c02.jpg +3 -0
  23. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c03.jpg +3 -0
  24. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c04.jpg +3 -0
  25. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c05.jpg +3 -0
  26. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c06.jpg +3 -0
  27. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c07.jpg +3 -0
  28. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c08.jpg +3 -0
  29. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c09.jpg +3 -0
  30. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c10.jpg +3 -0
  31. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/zidane.jpg +3 -0
  32. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/packages.txt +3 -0
  33. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/requirements.txt +24 -0
  34. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/utils/dataops.py +127 -0
  35. Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/webui.bat +72 -0
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/.gitattributes ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.npy filter=lfs diff=lfs merge=lfs -text
13
+ *.npz filter=lfs diff=lfs merge=lfs -text
14
+ *.onnx filter=lfs diff=lfs merge=lfs -text
15
+ *.ot filter=lfs diff=lfs merge=lfs -text
16
+ *.parquet filter=lfs diff=lfs merge=lfs -text
17
+ *.pickle filter=lfs diff=lfs merge=lfs -text
18
+ *.pkl filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pt filter=lfs diff=lfs merge=lfs -text
21
+ *.pth filter=lfs diff=lfs merge=lfs -text
22
+ *.rar filter=lfs diff=lfs merge=lfs -text
23
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
25
+ *.tflite filter=lfs diff=lfs merge=lfs -text
26
+ *.tgz filter=lfs diff=lfs merge=lfs -text
27
+ *.wasm filter=lfs diff=lfs merge=lfs -text
28
+ *.xz filter=lfs diff=lfs merge=lfs -text
29
+ *.zip filter=lfs diff=lfs merge=lfs -text
30
+ *.zst filter=lfs diff=lfs merge=lfs -text
31
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/.gitignore ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ignored folders
2
+ datasets/*
3
+ experiments/*
4
+ results/*
5
+ tb_logger/*
6
+ wandb/*
7
+ tmp/*
8
+
9
+ version.py
10
+
11
+ # Byte-compiled / optimized / DLL files
12
+ __pycache__/
13
+ *.py[cod]
14
+ *$py.class
15
+
16
+ # C extensions
17
+ *.so
18
+
19
+ # Distribution / packaging
20
+ .Python
21
+ build/
22
+ develop-eggs/
23
+ dist/
24
+ downloads/
25
+ eggs/
26
+ .eggs/
27
+ lib/
28
+ lib64/
29
+ parts/
30
+ sdist/
31
+ var/
32
+ wheels/
33
+ pip-wheel-metadata/
34
+ share/python-wheels/
35
+ *.egg-info/
36
+ .installed.cfg
37
+ *.egg
38
+ MANIFEST
39
+
40
+ # PyInstaller
41
+ # Usually these files are written by a python script from a template
42
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
43
+ *.manifest
44
+ *.spec
45
+
46
+ # Installer logs
47
+ pip-log.txt
48
+ pip-delete-this-directory.txt
49
+
50
+ # Unit test / coverage reports
51
+ htmlcov/
52
+ .tox/
53
+ .nox/
54
+ .coverage
55
+ .coverage.*
56
+ .cache
57
+ nosetests.xml
58
+ coverage.xml
59
+ *.cover
60
+ *.py,cover
61
+ .hypothesis/
62
+ .pytest_cache/
63
+
64
+ # Translations
65
+ *.mo
66
+ *.pot
67
+
68
+ # Django stuff:
69
+ *.log
70
+ local_settings.py
71
+ db.sqlite3
72
+ db.sqlite3-journal
73
+
74
+ # Flask stuff:
75
+ instance/
76
+ .webassets-cache
77
+
78
+ # Scrapy stuff:
79
+ .scrapy
80
+
81
+ # Sphinx documentation
82
+ docs/_build/
83
+
84
+ # PyBuilder
85
+ target/
86
+
87
+ # Jupyter Notebook
88
+ .ipynb_checkpoints
89
+
90
+ # IPython
91
+ profile_default/
92
+ ipython_config.py
93
+
94
+ # pyenv
95
+ .python-version
96
+
97
+ # pipenv
98
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
99
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
100
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
101
+ # install all needed dependencies.
102
+ #Pipfile.lock
103
+
104
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
105
+ __pypackages__/
106
+
107
+ # Celery stuff
108
+ celerybeat-schedule
109
+ celerybeat.pid
110
+
111
+ # SageMath parsed files
112
+ *.sage.py
113
+
114
+ # Environments
115
+ .env
116
+ .venv
117
+ env/
118
+ venv/
119
+ ENV/
120
+ env.bak/
121
+ venv.bak/
122
+
123
+ # Spyder project settings
124
+ .spyderproject
125
+ .spyproject
126
+
127
+ # Rope project settings
128
+ .ropeproject
129
+
130
+ # mkdocs documentation
131
+ /site
132
+
133
+ # mypy
134
+ .mypy_cache/
135
+ .dmypy.json
136
+ dmypy.json
137
+
138
+ # Pyre type checker
139
+ .pyre/
140
+ .vs
141
+ output
142
+ weights
143
+ .jpg
144
+ .png
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Image Face Upscale Restoration-GFPGAN-RestoreFormerPlusPlus-CodeFormer
3
+ emoji: 📈
4
+ colorFrom: blue
5
+ colorTo: gray
6
+ sdk: gradio
7
+ sdk_version: 5.15.0
8
+ app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/app.py ADDED
@@ -0,0 +1,766 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gc
3
+ import re
4
+ import cv2
5
+ import numpy as np
6
+ import gradio as gr
7
+ import torch
8
+ import traceback
9
+ from collections import defaultdict
10
+ from facexlib.utils.misc import download_from_url
11
+ from basicsr.utils.realesrganer import RealESRGANer
12
+
13
+
14
+ # Define URLs and their corresponding local storage paths
15
+ face_models = {
16
+ "GFPGANv1.4.pth" : ["https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth",
17
+ "https://github.com/TencentARC/GFPGAN/",
18
+ """GFPGAN: Towards Real-World Blind Face Restoration and Upscalling of the image with a Generative Facial Prior.
19
+ GFPGAN aims at developing a Practical Algorithm for Real-world Face Restoration.
20
+ It leverages rich and diverse priors encapsulated in a pretrained face GAN (e.g., StyleGAN2) for blind face restoration."""],
21
+
22
+ "RestoreFormer++.ckpt": ["https://github.com/wzhouxiff/RestoreFormerPlusPlus/releases/download/v1.0.0/RestoreFormer++.ckpt",
23
+ "https://github.com/wzhouxiff/RestoreFormerPlusPlus",
24
+ """RestoreFormer++: Towards Real-World Blind Face Restoration from Undegraded Key-Value Pairs.
25
+ RestoreFormer++ is an extension of RestoreFormer. It proposes to restore a degraded face image with both fidelity and \
26
+ realness by using the powerful fully-spacial attention mechanisms to model the abundant contextual information in the face and \
27
+ its interplay with reconstruction-oriented high-quality priors."""],
28
+
29
+ "CodeFormer.pth" : ["https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth",
30
+ "https://github.com/sczhou/CodeFormer",
31
+ """CodeFormer: Towards Robust Blind Face Restoration with Codebook Lookup Transformer (NeurIPS 2022).
32
+ CodeFormer is a Transformer-based model designed to tackle the challenging problem of blind face restoration, where inputs are often severely degraded.
33
+ By framing face restoration as a code prediction task, this approach ensures both improved mapping from degraded inputs to outputs and the generation of visually rich, high-quality faces.
34
+ """],
35
+
36
+ "GPEN-BFR-512.pth" : ["https://huggingface.co/akhaliq/GPEN-BFR-512/resolve/main/GPEN-BFR-512.pth",
37
+ "https://github.com/yangxy/GPEN",
38
+ """GPEN: GAN Prior Embedded Network for Blind Face Restoration in the Wild.
39
+ GPEN addresses blind face restoration (BFR) by embedding a GAN into a U-shaped DNN, combining GAN’s ability to generate high-quality images with DNN’s feature extraction.
40
+ This design reconstructs global structure, fine details, and backgrounds from degraded inputs.
41
+ Simple yet effective, GPEN outperforms state-of-the-art methods, delivering realistic results even for severely degraded images."""],
42
+
43
+ "GPEN-BFR-1024.pt" : ["https://www.modelscope.cn/models/iic/cv_gpen_image-portrait-enhancement-hires/resolve/master/pytorch_model.pt",
44
+ "https://www.modelscope.cn/models/iic/cv_gpen_image-portrait-enhancement-hires/files",
45
+ """The same as GPEN but for 1024 resolution."""],
46
+
47
+ "GPEN-BFR-2048.pt" : ["https://www.modelscope.cn/models/iic/cv_gpen_image-portrait-enhancement-hires/resolve/master/pytorch_model-2048.pt",
48
+ "https://www.modelscope.cn/models/iic/cv_gpen_image-portrait-enhancement-hires/files",
49
+ """The same as GPEN but for 2048 resolution."""],
50
+
51
+ # legacy model
52
+ "GFPGANv1.3.pth" : ["https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth",
53
+ "https://github.com/TencentARC/GFPGAN/", "The same as GFPGAN but legacy model"],
54
+ "GFPGANv1.2.pth" : ["https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.2.pth",
55
+ "https://github.com/TencentARC/GFPGAN/", "The same as GFPGAN but legacy model"],
56
+ "RestoreFormer.ckpt": ["https://github.com/wzhouxiff/RestoreFormerPlusPlus/releases/download/v1.0.0/RestoreFormer.ckpt",
57
+ "https://github.com/wzhouxiff/RestoreFormerPlusPlus", "The same as RestoreFormer++ but legacy model"],
58
+ }
59
+ upscale_models = {
60
+ # SRVGGNet
61
+ "realesr-general-x4v3.pth": ["https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth",
62
+ "https://github.com/xinntao/Real-ESRGAN/releases/tag/v0.3.0",
63
+ """add realesr-general-x4v3 and realesr-general-wdn-x4v3. They are very tiny models for general scenes, and they may more robust. But as they are tiny models, their performance may be limited."""],
64
+
65
+ "realesr-animevideov3.pth": ["https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth",
66
+ "https://github.com/xinntao/Real-ESRGAN/releases/tag/v0.2.5.0",
67
+ """update the RealESRGAN AnimeVideo-v3 model, which can achieve better results with a faster inference speed."""],
68
+
69
+ "4xLSDIRCompact.pth": ["https://github.com/Phhofm/models/releases/download/4xLSDIRCompact/4xLSDIRCompact.pth",
70
+ "https://github.com/Phhofm/models/releases/tag/4xLSDIRCompact",
71
+ """Upscale small good quality photos to 4x their size. This is my first ever released self-trained sisr upscaling model."""],
72
+
73
+ "4xLSDIRCompactC.pth": ["https://github.com/Phhofm/models/releases/download/4xLSDIRCompactC/4xLSDIRCompactC.pth",
74
+ "https://github.com/Phhofm/models/releases/tag/4xLSDIRCompactC",
75
+ """4x photo upscaler that handler jpg compression. Trying to extend my previous model to be able to handle compression (JPG 100-30) by manually altering the training dataset, since 4xLSDIRCompact cant handle compression. Use this instead of 4xLSDIRCompact if your photo has compression (like an image from the web)."""],
76
+
77
+ "4xLSDIRCompactR.pth": ["https://github.com/Phhofm/models/releases/download/4xLSDIRCompactC/4xLSDIRCompactR.pth",
78
+ "https://github.com/Phhofm/models/releases/tag/4xLSDIRCompactC",
79
+ """4x photo uspcaler that handles jpg compression, noise and slight. Extending my last 4xLSDIRCompact model to Real-ESRGAN, meaning trained on synthetic data instead to handle more kinds of degradations, it should be able to handle compression, noise, and slight blur."""],
80
+
81
+ "4xLSDIRCompactN.pth": ["https://github.com/Phhofm/models/releases/download/4xLSDIRCompact3/4xLSDIRCompactC3.pth",
82
+ "https://github.com/Phhofm/models/releases/tag/4xLSDIRCompact3",
83
+ """Upscale good quality input photos to x4 their size. The original 4xLSDIRCompact a bit more trained, cannot handle degradation.
84
+ I am releasing the Series 3 from my 4xLSDIRCompact models. In general my suggestion is, if you have good quality input images use 4xLSDIRCompactN3, otherwise try 4xLSDIRCompactC3 which will be able to handle jpg compression and a bit of blur, or then 4xLSDIRCompactCR3, which is an interpolation between C3 and R3 to be able to handle a bit of noise additionally."""],
85
+
86
+ "4xLSDIRCompactC3.pth": ["https://github.com/Phhofm/models/releases/download/4xLSDIRCompact3/4xLSDIRCompactC3.pth",
87
+ "https://github.com/Phhofm/models/releases/tag/4xLSDIRCompact3",
88
+ """Upscale compressed photos to x4 their size. Able to handle JPG compression (30-100).
89
+ I am releasing the Series 3 from my 4xLSDIRCompact models. In general my suggestion is, if you have good quality input images use 4xLSDIRCompactN3, otherwise try 4xLSDIRCompactC3 which will be able to handle jpg compression and a bit of blur, or then 4xLSDIRCompactCR3, which is an interpolation between C3 and R3 to be able to handle a bit of noise additionally."""],
90
+
91
+ "4xLSDIRCompactR3.pth": ["https://github.com/Phhofm/models/releases/download/4xLSDIRCompact3/4xLSDIRCompactR3.pth",
92
+ "https://github.com/Phhofm/models/releases/tag/4xLSDIRCompact3",
93
+ """Upscale (degraded) photos to x4 their size. Trained on synthetic data, meant to handle more degradations.
94
+ I am releasing the Series 3 from my 4xLSDIRCompact models. In general my suggestion is, if you have good quality input images use 4xLSDIRCompactN3, otherwise try 4xLSDIRCompactC3 which will be able to handle jpg compression and a bit of blur, or then 4xLSDIRCompactCR3, which is an interpolation between C3 and R3 to be able to handle a bit of noise additionally."""],
95
+
96
+ "4xLSDIRCompactCR3.pth": ["https://github.com/Phhofm/models/releases/download/4xLSDIRCompact3/4xLSDIRCompactCR3.pth",
97
+ "https://github.com/Phhofm/models/releases/tag/4xLSDIRCompact3",
98
+ """I am releasing the Series 3 from my 4xLSDIRCompact models. In general my suggestion is, if you have good quality input images use 4xLSDIRCompactN3, otherwise try 4xLSDIRCompactC3 which will be able to handle jpg compression and a bit of blur, or then 4xLSDIRCompactCR3, which is an interpolation between C3 and R3 to be able to handle a bit of noise additionally."""],
99
+
100
+ "2xParimgCompact.pth": ["https://github.com/Phhofm/models/releases/download/2xParimgCompact/2xParimgCompact.pth",
101
+ "https://github.com/Phhofm/models/releases/tag/2xParimgCompact",
102
+ """A 2x photo upscaling compact model based on Microsoft's ImagePairs. This was one of the earliest models I started training and finished it now for release. As can be seen in the examples, this model will affect colors."""],
103
+
104
+ "1xExposureCorrection_compact.pth": ["https://github.com/Phhofm/models/releases/download/1xExposureCorrection_compact/1xExposureCorrection_compact.pth",
105
+ "https://github.com/Phhofm/models/releases/tag/1xExposureCorrection_compact",
106
+ """This model is meant as an experiment to see if compact can be used to train on photos to exposure correct those using the pixel, perceptual, color, color and ldl losses. There is no brightness loss. Still it seems to kinda work."""],
107
+
108
+ "1xUnderExposureCorrection_compact.pth": ["https://github.com/Phhofm/models/releases/download/1xExposureCorrection_compact/1xUnderExposureCorrection_compact.pth",
109
+ "https://github.com/Phhofm/models/releases/tag/1xExposureCorrection_compact",
110
+ """This model is meant as an experiment to see if compact can be used to train on underexposed images to exposure correct those using the pixel, perceptual, color, color and ldl losses. There is no brightness loss. Still it seems to kinda work."""],
111
+
112
+ "1xOverExposureCorrection_compact.pth": ["https://github.com/Phhofm/models/releases/download/1xExposureCorrection_compact/1xOverExposureCorrection_compact.pth",
113
+ "https://github.com/Phhofm/models/releases/tag/1xExposureCorrection_compact",
114
+ """This model is meant as an experiment to see if compact can be used to train on overexposed images to exposure correct those using the pixel, perceptual, color, color and ldl losses. There is no brightness loss. Still it seems to kinda work."""],
115
+
116
+ # RRDBNet
117
+ "RealESRGAN_x4plus_anime_6B.pth": ["https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",
118
+ "https://github.com/xinntao/Real-ESRGAN/releases/tag/v0.2.2.4",
119
+ """We add RealESRGAN_x4plus_anime_6B.pth, which is optimized for anime images with much smaller model size. More details and comparisons with waifu2x are in anime_model.md"""],
120
+
121
+ "RealESRGAN_x2plus.pth" : ["https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth",
122
+ "https://github.com/xinntao/Real-ESRGAN/releases/tag/v0.2.1",
123
+ """Add RealESRGAN_x2plus.pth model"""],
124
+
125
+ "RealESRNet_x4plus.pth" : ["https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth",
126
+ "https://github.com/xinntao/Real-ESRGAN/releases/tag/v0.1.1",
127
+ """This release is mainly for storing pre-trained models and executable files."""],
128
+
129
+ "RealESRGAN_x4plus.pth" : ["https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
130
+ "https://github.com/xinntao/Real-ESRGAN/releases/tag/v0.1.0",
131
+ """This release is mainly for storing pre-trained models and executable files."""],
132
+
133
+ # ESRGAN(oldRRDB)
134
+ "4x-AnimeSharp.pth": ["https://huggingface.co/utnah/esrgan/resolve/main/4x-AnimeSharp.pth?download=true",
135
+ "https://openmodeldb.info/models/4x-AnimeSharp",
136
+ """Interpolation between 4x-UltraSharp and 4x-TextSharp-v0.5. Works amazingly on anime. It also upscales text, but it's far better with anime content."""],
137
+
138
+ "4x_IllustrationJaNai_V1_ESRGAN_135k.pth": ["https://drive.google.com/uc?export=download&confirm=1&id=1qpioSqBkB_IkSBhEAewSSNFt6qgkBimP",
139
+ "https://openmodeldb.info/models/4x-IllustrationJaNai-V1-DAT2",
140
+ """Purpose: Illustrations, digital art, manga covers
141
+ Model for color images including manga covers and color illustrations, digital art, visual novel art, artbooks, and more.
142
+ DAT2 version is the highest quality version but also the slowest. See the ESRGAN version for faster performance."""],
143
+
144
+ "2x-sudo-RealESRGAN.pth": ["https://objectstorage.us-phoenix-1.oraclecloud.com/n/ax6ygfvpvzka/b/open-modeldb-files/o/2x-sudo-RealESRGAN.pth",
145
+ "https://openmodeldb.info/models/2x-sudo-RealESRGAN",
146
+ """Pretrained: Pretrained_Model_G: RealESRGAN_x4plus_anime_6B.pth / RealESRGAN_x4plus_anime_6B.pth (sudo_RealESRGAN2x_3.332.758_G.pth)
147
+ Tried to make the best 2x model there is for drawings. I think i archived that.
148
+ And yes, it is nearly 3.8 million iterations (probably a record nobody will beat here), took me nearly half a year to train.
149
+ It can happen that in one edge is a noisy pattern in edges. You can use padding/crop for that.
150
+ I aimed for perceptual quality without zooming in like 400%. Since RealESRGAN is 4x, I downscaled these images with bicubic."""],
151
+
152
+ "2x-sudo-RealESRGAN-Dropout.pth": ["https://objectstorage.us-phoenix-1.oraclecloud.com/n/ax6ygfvpvzka/b/open-modeldb-files/o/2x-sudo-RealESRGAN-Dropout.pth",
153
+ "https://openmodeldb.info/models/2x-sudo-RealESRGAN-Dropout",
154
+ """Pretrained: Pretrained_Model_G: RealESRGAN_x4plus_anime_6B.pth / RealESRGAN_x4plus_anime_6B.pth (sudo_RealESRGAN2x_3.332.758_G.pth)
155
+ Tried to make the best 2x model there is for drawings. I think i archived that.
156
+ And yes, it is nearly 3.8 million iterations (probably a record nobody will beat here), took me nearly half a year to train.
157
+ It can happen that in one edge is a noisy pattern in edges. You can use padding/crop for that.
158
+ I aimed for perceptual quality without zooming in like 400%. Since RealESRGAN is 4x, I downscaled these images with bicubic."""],
159
+
160
+ "4xNomos2_otf_esrgan.pth": ["https://github.com/Phhofm/models/releases/download/4xNomos2_otf_esrgan/4xNomos2_otf_esrgan.pth",
161
+ "https://github.com/Phhofm/models/releases/tag/4xNomos2_otf_esrgan",
162
+ """Purpose: Restoration, 4x ESRGAN model for photography, trained using the Real-ESRGAN otf degradation pipeline."""],
163
+
164
+ "4xNomosWebPhoto_esrgan.pth": ["https://github.com/Phhofm/models/releases/download/4xNomosWebPhoto_esrgan/4xNomosWebPhoto_esrgan.pth",
165
+ "https://github.com/Phhofm/models/releases/tag/4xNomosWebPhoto_esrgan",
166
+ """Purpose: Restoration, 4x ESRGAN model for photography, trained with realistic noise, lens blur, jpg and webp re-compression.
167
+ ESRGAN version of 4xNomosWebPhoto_RealPLKSR, trained on the same dataset and in the same way."""],
168
+
169
+ # DATNet
170
+ "4xNomos8kDAT.pth" : ["https://github.com/Phhofm/models/releases/download/4xNomos8kDAT/4xNomos8kDAT.pth",
171
+ "https://openmodeldb.info/models/4x-Nomos8kDAT",
172
+ """A 4x photo upscaler with otf jpg compression, blur and resize, trained on musl's Nomos8k_sfw dataset for realisic sr, this time based on the DAT arch, as a finetune on the official 4x DAT model."""],
173
+
174
+ "4x-DWTP-DS-dat2-v3.pth" : ["https://objectstorage.us-phoenix-1.oraclecloud.com/n/ax6ygfvpvzka/b/open-modeldb-files/o/4x-DWTP-DS-dat2-v3.pth",
175
+ "https://openmodeldb.info/models/4x-DWTP-DS-dat2-v3",
176
+ """DAT descreenton model, designed to reduce discrepancies on tiles due to too much loss of the first version, while getting rid of the removal of paper texture"""],
177
+
178
+ "4xBHI_dat2_real.pth" : ["https://github.com/Phhofm/models/releases/download/4xBHI_dat2_real/4xBHI_dat2_real.pth",
179
+ "https://github.com/Phhofm/models/releases/tag/4xBHI_dat2_real",
180
+ """Purpose: 4x upscaling images. Handles realistic noise, some realistic blur, and webp and jpg (re)compression.
181
+ Description: 4x dat2 upscaling model for web and realistic images. It handles realistic noise, some realistic blur, and webp and jpg (re)compression. Trained on my BHI dataset (390'035 training tiles) with degraded LR subset."""],
182
+
183
+ "4xBHI_dat2_otf.pth" : ["https://github.com/Phhofm/models/releases/download/4xBHI_dat2_otf/4xBHI_dat2_otf.pth",
184
+ "https://github.com/Phhofm/models/releases/tag/4xBHI_dat2_otf",
185
+ """Purpose: 4x upscaling images, handles noise and jpg compression
186
+ Description: 4x dat2 upscaling model, trained with the real-esrgan otf pipeline on my bhi dataset. Handles noise and compression."""],
187
+
188
+ "4xBHI_dat2_multiblur.pth" : ["https://github.com/Phhofm/models/releases/download/4xBHI_dat2_multiblurjpg/4xBHI_dat2_multiblur.pth",
189
+ "https://github.com/Phhofm/models/releases/tag/4xBHI_dat2_multiblurjpg",
190
+ """Purpose: 4x upscaling images, handles jpg compression
191
+ Description: 4x dat2 upscaling model, trained with down_up,linear, cubic_mitchell, lanczos, gauss and box scaling algos, some average, gaussian and anisotropic blurs and jpg compression. Trained on my BHI sisr dataset."""],
192
+
193
+ "4xBHI_dat2_multiblurjpg.pth" : ["https://github.com/Phhofm/models/releases/download/4xBHI_dat2_multiblurjpg/4xBHI_dat2_multiblurjpg.pth",
194
+ "https://github.com/Phhofm/models/releases/tag/4xBHI_dat2_multiblurjpg",
195
+ """Purpose: 4x upscaling images, handles jpg compression
196
+ Description: 4x dat2 upscaling model, trained with down_up,linear, cubic_mitchell, lanczos, gauss and box scaling algos, some average, gaussian and anisotropic blurs and jpg compression. Trained on my BHI sisr dataset."""],
197
+
198
+ "4x_IllustrationJaNai_V1_DAT2_190k.pth": ["https://drive.google.com/uc?export=download&confirm=1&id=1qpioSqBkB_IkSBhEAewSSNFt6qgkBimP",
199
+ "https://openmodeldb.info/models/4x-IllustrationJaNai-V1-DAT2",
200
+ """Purpose: Illustrations, digital art, manga covers
201
+ Model for color images including manga covers and color illustrations, digital art, visual novel art, artbooks, and more.
202
+ DAT2 version is the highest quality version but also the slowest. See the ESRGAN version for faster performance."""],
203
+
204
+ # HAT
205
+ "4xNomos8kSCHAT-L.pth" : ["https://github.com/Phhofm/models/releases/download/4xNomos8kSCHAT/4xNomos8kSCHAT-L.pth",
206
+ "https://openmodeldb.info/models/4x-Nomos8kSCHAT-L",
207
+ """4x photo upscaler with otf jpg compression and blur, trained on musl's Nomos8k_sfw dataset for realisic sr. Since this is a big model, upscaling might take a while."""],
208
+
209
+ "4xNomos8kSCHAT-S.pth" : ["https://github.com/Phhofm/models/releases/download/4xNomos8kSCHAT/4xNomos8kSCHAT-S.pth",
210
+ "https://openmodeldb.info/models/4x-Nomos8kSCHAT-S",
211
+ """4x photo upscaler with otf jpg compression and blur, trained on musl's Nomos8k_sfw dataset for realisic sr. HAT-S version/model."""],
212
+
213
+ "4xNomos8kHAT-L_otf.pth": ["https://github.com/Phhofm/models/releases/download/4xNomos8kHAT-L_otf/4xNomos8kHAT-L_otf.pth",
214
+ "https://openmodeldb.info/models/4x-Nomos8kHAT-L-otf",
215
+ """4x photo upscaler trained with otf"""],
216
+
217
+ # RealPLKSR_dysample
218
+ "4xHFA2k_ludvae_realplksr_dysample.pth": ["https://github.com/Phhofm/models/releases/download/4xHFA2k_ludvae_realplksr_dysample/4xHFA2k_ludvae_realplksr_dysample.pth",
219
+ "https://openmodeldb.info/models/4x-HFA2k-ludvae-realplksr-dysample",
220
+ """A Dysample RealPLKSR 4x upscaling model for anime single-image resolution."""],
221
+
222
+ "4xArtFaces_realplksr_dysample.pth" : ["https://github.com/Phhofm/models/releases/download/4xArtFaces_realplksr_dysample/4xArtFaces_realplksr_dysample.pth",
223
+ "https://openmodeldb.info/models/4x-ArtFaces-realplksr-dysample",
224
+ """A Dysample RealPLKSR 4x upscaling model for art / painted faces."""],
225
+
226
+ "4x-PBRify_RPLKSRd_V3.pth" : ["https://github.com/Kim2091/Kim2091-Models/releases/download/4x-PBRify_RPLKSRd_V3/4x-PBRify_RPLKSRd_V3.pth", "https://openmodeldb.info/models/4x-PBRify-RPLKSRd-V3",
227
+ """This model is roughly 8x faster than the current DAT2 model, while being higher quality. It produces far more natural detail, resolves lines and edges more smoothly, and cleans up compression artifacts better."""],
228
+
229
+ "4xNomos2_realplksr_dysample.pth" : ["https://github.com/Phhofm/models/releases/download/4xNomos2_realplksr_dysample/4xNomos2_realplksr_dysample.pth",
230
+ "https://openmodeldb.info/models/4x-Nomos2-realplksr-dysample",
231
+ """Description: A Dysample RealPLKSR 4x upscaling model that was trained with / handles jpg compression down to 70 on the Nomosv2 dataset, preserves DoF.
232
+ This model affects / saturate colors, which can be counteracted a bit by using wavelet color fix, as used in these examples."""],
233
+
234
+ # RealPLKSR
235
+ "2x-AnimeSharpV2_RPLKSR_Sharp.pth": ["https://github.com/Kim2091/Kim2091-Models/releases/download/2x-AnimeSharpV2_Set/2x-AnimeSharpV2_RPLKSR_Sharp.pth",
236
+ "https://openmodeldb.info/models/2x-AnimeSharpV2-RPLKSR-Sharp",
237
+ """Kim2091: This is my first anime model in years. Hopefully you guys can find a good use-case for it.
238
+ RealPLKSR (Higher quality, slower) Sharp: For heavily degraded sources. Sharp models have issues depth of field but are best at removing artifacts
239
+ """],
240
+
241
+ "2x-AnimeSharpV2_RPLKSR_Soft.pth" : ["https://github.com/Kim2091/Kim2091-Models/releases/download/2x-AnimeSharpV2_Set/2x-AnimeSharpV2_RPLKSR_Soft.pth",
242
+ "https://openmodeldb.info/models/2x-AnimeSharpV2-RPLKSR-Soft",
243
+ """Kim2091: This is my first anime model in years. Hopefully you guys can find a good use-case for it.
244
+ RealPLKSR (Higher quality, slower) Soft: For cleaner sources. Soft models preserve depth of field but may not remove other artifacts as well"""],
245
+
246
+ "4xPurePhoto-RealPLSKR.pth" : ["https://github.com/starinspace/StarinspaceUpscale/releases/download/Models/4xPurePhoto-RealPLSKR.pth",
247
+ "https://openmodeldb.info/models/4x-PurePhoto-RealPLSKR",
248
+ """Skilled in working with cats, hair, parties, and creating clear images.
249
+ Also proficient in resizing photos and enlarging large, sharp images.
250
+ Can effectively improve images from small sizes as well (300px at smallest on one side, depending on the subject).
251
+ Experienced in experimenting with techniques like upscaling with this model twice and \
252
+ then reducing it by 50% to enhance details, especially in features like hair or animals."""],
253
+
254
+ "2x_Text2HD_v.1-RealPLKSR.pth" : ["https://github.com/starinspace/StarinspaceUpscale/releases/download/Models/2x_Text2HD_v.1-RealPLKSR.pth",
255
+ "https://openmodeldb.info/models/2x-Text2HD-v-1",
256
+ """Purpose: Upscale text in very low quality to normal quality.
257
+ The upscale model is specifically designed to enhance lower-quality text images, \
258
+ improving their clarity and readability by upscaling them by 2x.
259
+ It excels at processing moderately sized text, effectively transforming it into high-quality, legible scans.
260
+ However, the model may encounter challenges when dealing with very small text, \
261
+ as its performance is optimized for text of a certain minimum size. For best results, \
262
+ input images should contain text that is not excessively small."""],
263
+
264
+ "2xVHS2HD-RealPLKSR.pth" : ["https://github.com/starinspace/StarinspaceUpscale/releases/download/Models/2xVHS2HD-RealPLKSR.pth",
265
+ "https://openmodeldb.info/models/2x-VHS2HD",
266
+ """An advanced VHS recording model designed to enhance video quality by reducing artifacts such as haloing, ghosting, and noise patterns.
267
+ Optimized primarily for PAL resolution (NTSC might work good as well)."""],
268
+
269
+ "4xNomosWebPhoto_RealPLKSR.pth" : ["https://github.com/Phhofm/models/releases/download/4xNomosWebPhoto_RealPLKSR/4xNomosWebPhoto_RealPLKSR.pth",
270
+ "https://openmodeldb.info/models/4x-NomosWebPhoto-RealPLKSR",
271
+ """4x RealPLKSR model for photography, trained with realistic noise, lens blur, jpg and webp re-compression."""],
272
+
273
+ # "4xNomos2_hq_drct-l.pth" : ["https://github.com/Phhofm/models/releases/download/4xNomos2_hq_drct-l/4xNomos2_hq_drct-l.pth",
274
+ # "https://github.com/Phhofm/models/releases/tag/4xNomos2_hq_drct-l",
275
+ # """An drct-l 4x upscaling model, similiar to the 4xNomos2_hq_atd, 4xNomos2_hq_dat2 and 4xNomos2_hq_mosr models, trained and for usage on non-degraded input to give good quality output.
276
+ # """],
277
+
278
+ # "4xNomos2_hq_atd.pth" : ["https://github.com/Phhofm/models/releases/download/4xNomos2_hq_atd/4xNomos2_hq_atd.pth",
279
+ # "https://github.com/Phhofm/models/releases/tag/4xNomos2_hq_atd",
280
+ # """An atd 4x upscaling model, similiar to the 4xNomos2_hq_dat2 or 4xNomos2_hq_mosr models, trained and for usage on non-degraded input to give good quality output.
281
+ # """]
282
+ }
283
+
284
+ example_list = ["images/a01.jpg", "images/a02.jpg", "images/a03.jpg", "images/a04.jpg", "images/bus.jpg", "images/zidane.jpg",
285
+ "images/b01.jpg", "images/b02.jpg", "images/b03.jpg", "images/b04.jpg", "images/b05.jpg", "images/b06.jpg",
286
+ "images/b07.jpg", "images/b08.jpg", "images/b09.jpg", "images/b10.jpg", "images/b11.jpg", "images/c01.jpg",
287
+ "images/c02.jpg", "images/c03.jpg", "images/c04.jpg", "images/c05.jpg", "images/c06.jpg", "images/c07.jpg",
288
+ "images/c08.jpg", "images/c09.jpg", "images/c10.jpg"]
289
+
290
+ def get_model_type(model_name):
291
+ # Define model type mappings based on key parts of the model names
292
+ model_type = "other"
293
+ if any(value in model_name.lower() for value in ("4x-animesharp.pth", "sudo-realesrgan")):
294
+ model_type = "ESRGAN"
295
+ elif any(value in model_name.lower() for value in ("realesrgan", "realesrnet")):
296
+ model_type = "RRDB"
297
+ elif any(value in model_name.lower() for value in ("realesr", "exposurecorrection", "parimgcompact", "lsdircompact")):
298
+ model_type = "SRVGG"
299
+ elif "esrgan" in model_name.lower():
300
+ model_type = "ESRGAN"
301
+ elif "dat" in model_name.lower():
302
+ model_type = "DAT"
303
+ elif "hat" in model_name.lower():
304
+ model_type = "HAT"
305
+ elif ("realplksr" in model_name.lower() and "dysample" in model_name.lower()) or "rplksrd" in model_name.lower():
306
+ model_type = "RealPLKSR_dysample"
307
+ elif any(value in model_name.lower() for value in ("realplksr", "rplksr", "realplskr")):
308
+ model_type = "RealPLKSR"
309
+ elif "drct-l" in model_name.lower():
310
+ model_type = "DRCT-L"
311
+ elif "atd" in model_name.lower():
312
+ model_type = "ATD"
313
+ return f"{model_type}, {model_name}"
314
+
315
+ typed_upscale_models = {get_model_type(key): value[0] for key, value in upscale_models.items()}
316
+
317
+
318
+ class Upscale:
319
+ def inference(self, img, face_restoration, upscale_model, scale: float, face_detection, face_detection_threshold: any, face_detection_only_center: bool, outputWithModelName: bool):
320
+ print(img)
321
+ print(face_restoration, upscale_model, scale)
322
+ try:
323
+ self.scale = scale
324
+ self.img_name = os.path.basename(str(img))
325
+ self.basename, self.extension = os.path.splitext(self.img_name)
326
+
327
+ img = cv2.imdecode(np.fromfile(img, np.uint8), cv2.IMREAD_UNCHANGED) # numpy.ndarray
328
+
329
+ self.img_mode = "RGBA" if len(img.shape) == 3 and img.shape[2] == 4 else None
330
+ if len(img.shape) == 2: # for gray inputs
331
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
332
+
333
+ self.h_input, self.w_input = img.shape[0:2]
334
+
335
+ if face_restoration:
336
+ download_from_url(face_models[face_restoration][0], face_restoration, os.path.join("weights", "face"))
337
+
338
+ modelInUse = ""
339
+ upscale_type = None
340
+ if upscale_model:
341
+ upscale_type, upscale_model = upscale_model.split(", ", 1)
342
+ download_from_url(upscale_models[upscale_model][0], upscale_model, os.path.join("weights", "upscale"))
343
+ modelInUse = f"_{os.path.splitext(upscale_model)[0]}"
344
+
345
+ self.netscale = 1 if any(sub in upscale_model for sub in ("x1", "1x")) else (2 if any(sub in upscale_model for sub in ("x2", "2x")) else 4)
346
+ loadnet = None
347
+ model = None
348
+ is_auto_split_upscale = True
349
+ half = True if torch.cuda.is_available() else False
350
+ if upscale_type:
351
+ from basicsr.archs.rrdbnet_arch import RRDBNet
352
+ # background enhancer with upscale model
353
+ if any(value == upscale_type for value in ("SRVGG", "RRDB", "ESRGAN")):
354
+ loadnet_origin = torch.load(os.path.join("weights", "upscale", upscale_model), map_location=torch.device('cpu'), weights_only=True)
355
+ if 'params_ema' in loadnet_origin or 'params' in loadnet_origin:
356
+ loadnet_origin = loadnet_origin['params_ema'] if 'params_ema' in loadnet_origin else loadnet_origin['params']
357
+ if upscale_type == "SRVGG":
358
+ from basicsr.archs.srvgg_arch import SRVGGNetCompact
359
+ body_max_num = self.find_max_numbers(loadnet_origin, "body")
360
+ num_feat = loadnet_origin["body.0.weight"].shape[0]
361
+ num_in_ch = loadnet_origin["body.0.weight"].shape[1]
362
+ num_conv = body_max_num // 2 - 1 #16 if any(value in upscale_model for value in ("animevideov3", "ExposureCorrection", "ParimgCompact", "LSDIRCompact")) else 32
363
+ model = SRVGGNetCompact(num_in_ch=num_in_ch, num_out_ch=3, num_feat=num_feat, num_conv=num_conv, upscale=self.netscale, act_type='prelu')
364
+ elif upscale_type == "RRDB" or upscale_type == "ESRGAN":
365
+ if upscale_type == "RRDB":
366
+ num_block = 1 + self.find_max_numbers(loadnet_origin, "body")
367
+ num_feat = loadnet_origin["conv_first.weight"].shape[0]
368
+ else:
369
+ num_block = self.find_max_numbers(loadnet_origin, "model.1.sub")
370
+ num_feat = loadnet_origin["model.0.weight"].shape[0]
371
+ model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=num_feat, num_block=num_block, num_grow_ch=32, scale=self.netscale, is_real_esrgan=upscale_type == "RRDB")
372
+ elif upscale_type == "DAT":
373
+ from basicsr.archs.dat_arch import DAT
374
+ half = False
375
+ expansion_factor = 2. if "dat2" in upscale_model.lower() else 4.
376
+ model = DAT(img_size=64, in_chans=3, embed_dim=180, split_size=[8,32], depth=[6,6,6,6,6,6], num_heads=[6,6,6,6,6,6], expansion_factor=expansion_factor, upscale=self.netscale)
377
+ # # Speculate on the parameters.
378
+ # loadnet_origin = torch.load(os.path.join("weights", "upscale", upscale_model), map_location=torch.device('cpu'), weights_only=True)
379
+ # inferred_params = self.infer_parameters_from_state_dict_for_dat(loadnet_origin, self.netscale)
380
+ # for param, value in inferred_params.items():
381
+ # print(f"{param}: {value}")
382
+ elif upscale_type == "HAT":
383
+ half = False
384
+ from basicsr.archs.hat_arch import HAT
385
+ # The parameters are derived from the XPixelGroup project files: HAT-L_SRx4_ImageNet-pretrain.yml and HAT-S_SRx4.yml.
386
+ # https://github.com/XPixelGroup/HAT/tree/main/options/test
387
+ if "hat-l" in upscale_model.lower():
388
+ window_size = 16
389
+ compress_ratio = 3
390
+ squeeze_factor = 30
391
+ depths = [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
392
+ embed_dim = 180
393
+ num_heads = [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
394
+ mlp_ratio = 2
395
+ upsampler = "pixelshuffle"
396
+ elif "hat-s" in upscale_model.lower():
397
+ window_size = 16
398
+ compress_ratio = 24
399
+ squeeze_factor = 24
400
+ depths = [6, 6, 6, 6, 6, 6]
401
+ embed_dim = 144
402
+ num_heads = [6, 6, 6, 6, 6, 6]
403
+ mlp_ratio = 2
404
+ upsampler = "pixelshuffle"
405
+ model = HAT(img_size=64, patch_size=1, in_chans=3, embed_dim=embed_dim, depths=depths, num_heads=num_heads, window_size=window_size, compress_ratio=compress_ratio,
406
+ squeeze_factor=squeeze_factor, conv_scale=0.01, overlap_ratio=0.5, mlp_ratio=mlp_ratio, upsampler=upsampler, upscale=self.netscale,)
407
+ elif "RealPLKSR" in upscale_type:
408
+ from basicsr.archs.realplksr_arch import realplksr
409
+ if upscale_type == "RealPLKSR_dysample":
410
+ model = realplksr(dim=64, n_blocks=28, kernel_size=17, split_ratio=0.25, upscaling_factor=self.netscale, dysample=True)
411
+ elif upscale_type == "RealPLKSR":
412
+ half = False if "RealPLSKR" in upscale_model else half
413
+ model = realplksr(dim=64, n_blocks=28, kernel_size=17, split_ratio=0.25, upscaling_factor=self.netscale)
414
+
415
+ self.upsampler = None
416
+ if loadnet:
417
+ self.upsampler = RealESRGANer(scale=self.netscale, loadnet=loadnet, model=model, tile=0, tile_pad=10, pre_pad=0, half=half)
418
+ elif model:
419
+ self.upsampler = RealESRGANer(scale=self.netscale, model_path=os.path.join("weights", "upscale", upscale_model), model=model, tile=0, tile_pad=10, pre_pad=0, half=half)
420
+ elif upscale_model:
421
+ self.upsampler = None
422
+ import PIL
423
+ from image_gen_aux import UpscaleWithModel
424
+ class UpscaleWithModel_Gfpgan(UpscaleWithModel):
425
+ def cv2pil(self, image):
426
+ ''' OpenCV type -> PIL type
427
+ https://qiita.com/derodero24/items/f22c22b22451609908ee
428
+ '''
429
+ new_image = image.copy()
430
+ if new_image.ndim == 2: # Grayscale
431
+ pass
432
+ elif new_image.shape[2] == 3: # Color
433
+ new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB)
434
+ elif new_image.shape[2] == 4: # Transparency
435
+ new_image = cv2.cvtColor(new_image, cv2.COLOR_BGRA2RGBA)
436
+ new_image = PIL.Image.fromarray(new_image)
437
+ return new_image
438
+
439
+ def pil2cv(self, image):
440
+ ''' PIL type -> OpenCV type
441
+ https://qiita.com/derodero24/items/f22c22b22451609908ee
442
+ '''
443
+ new_image = np.array(image, dtype=np.uint8)
444
+ if new_image.ndim == 2: # Grayscale
445
+ pass
446
+ elif new_image.shape[2] == 3: # Color
447
+ new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
448
+ elif new_image.shape[2] == 4: # Transparency
449
+ new_image = cv2.cvtColor(new_image, cv2.COLOR_RGBA2BGRA)
450
+ return new_image
451
+
452
+ def enhance(self_, img, outscale=None):
453
+ # img: numpy
454
+ h_input, w_input = img.shape[0:2]
455
+ pil_img = self.cv2pil(img)
456
+ pil_img = self_.__call__(pil_img)
457
+ cv_image = self.pil2cv(pil_img)
458
+ if outscale is not None and outscale != float(self.netscale):
459
+ interpolation = cv2.INTER_AREA if outscale < float(self.netscale) else cv2.INTER_LANCZOS4
460
+ cv_image = cv2.resize(
461
+ cv_image, (
462
+ int(w_input * outscale),
463
+ int(h_input * outscale),
464
+ ), interpolation=interpolation)
465
+ return cv_image, None
466
+
467
+ device = "cuda" if torch.cuda.is_available() else "cpu"
468
+ upscaler = UpscaleWithModel.from_pretrained(os.path.join("weights", "upscale", upscale_model)).to(device)
469
+ upscaler.__class__ = UpscaleWithModel_Gfpgan
470
+ self.upsampler = upscaler
471
+ self.face_enhancer = None
472
+
473
+ resolution = 512
474
+ if face_restoration:
475
+ modelInUse = f"_{os.path.splitext(face_restoration)[0]}" + modelInUse
476
+ from gfpgan.utils import GFPGANer
477
+ model_rootpath = os.path.join("weights", "face")
478
+ model_path = os.path.join(model_rootpath, face_restoration)
479
+ channel_multiplier = None
480
+
481
+ if face_restoration and face_restoration.startswith("GFPGANv1."):
482
+ arch = "clean"
483
+ channel_multiplier = 2
484
+ elif face_restoration and face_restoration.startswith("RestoreFormer"):
485
+ arch = "RestoreFormer++" if face_restoration.startswith("RestoreFormer++") else "RestoreFormer"
486
+ elif face_restoration == 'CodeFormer.pth':
487
+ arch = "CodeFormer"
488
+ elif face_restoration.startswith("GPEN-BFR-"):
489
+ arch = "GPEN"
490
+ channel_multiplier = 2
491
+ if "1024" in face_restoration:
492
+ arch = "GPEN-1024"
493
+ resolution = 1024
494
+ elif "2048" in face_restoration:
495
+ arch = "GPEN-2048"
496
+ resolution = 2048
497
+
498
+ self.face_enhancer = GFPGANer(model_path=model_path, upscale=self.scale, arch=arch, channel_multiplier=channel_multiplier, model_rootpath=model_rootpath, det_model=face_detection, resolution=resolution)
499
+
500
+ files = []
501
+ if not outputWithModelName:
502
+ modelInUse = ""
503
+
504
+ try:
505
+ bg_upsample_img = None
506
+ if self.upsampler and hasattr(self.upsampler, "enhance"):
507
+ from utils.dataops import auto_split_upscale
508
+ bg_upsample_img, _ = auto_split_upscale(img, self.upsampler.enhance, self.scale) if is_auto_split_upscale else self.upsampler.enhance(img, outscale=self.scale)
509
+
510
+ if self.face_enhancer:
511
+ cropped_faces, restored_aligned, bg_upsample_img = self.face_enhancer.enhance(img, has_aligned=False, only_center_face=face_detection_only_center, paste_back=True, bg_upsample_img=bg_upsample_img, eye_dist_threshold=face_detection_threshold)
512
+ # save faces
513
+ if cropped_faces and restored_aligned:
514
+ for idx, (cropped_face, restored_face) in enumerate(zip(cropped_faces, restored_aligned)):
515
+ # save cropped face
516
+ save_crop_path = f"output/{self.basename}{idx:02d}_cropped_faces{modelInUse}.png"
517
+ self.imwriteUTF8(save_crop_path, cropped_face)
518
+ # save restored face
519
+ save_restore_path = f"output/{self.basename}{idx:02d}_restored_faces{modelInUse}.png"
520
+ self.imwriteUTF8(save_restore_path, restored_face)
521
+ # save comparison image
522
+ save_cmp_path = f"output/{self.basename}{idx:02d}_cmp{modelInUse}.png"
523
+ cmp_img = np.concatenate((cropped_face, restored_face), axis=1)
524
+ self.imwriteUTF8(save_cmp_path, cmp_img)
525
+
526
+ files.append(save_crop_path)
527
+ files.append(save_restore_path)
528
+ files.append(save_cmp_path)
529
+
530
+ restored_img = bg_upsample_img
531
+ except RuntimeError as error:
532
+ print(traceback.format_exc())
533
+ print('Error', error)
534
+ finally:
535
+ if self.face_enhancer:
536
+ self.face_enhancer._cleanup()
537
+ else:
538
+ # Free GPU memory and clean up resources
539
+ torch.cuda.empty_cache()
540
+ gc.collect()
541
+
542
+ if not self.extension:
543
+ self.extension = ".png" if self.img_mode == "RGBA" else ".jpg" # RGBA images should be saved in png format
544
+ save_path = f"output/{self.basename}{modelInUse}{self.extension}"
545
+ self.imwriteUTF8(save_path, restored_img)
546
+
547
+ restored_img = cv2.cvtColor(restored_img, cv2.COLOR_BGR2RGB)
548
+ files.append(save_path)
549
+ return files, files
550
+ except Exception as error:
551
+ print(traceback.format_exc())
552
+ print("global exception", error)
553
+ return None, None
554
+
555
+ def find_max_numbers(self, state_dict, findkeys):
556
+ if isinstance(findkeys, str):
557
+ findkeys = [findkeys]
558
+ max_values = defaultdict(lambda: None)
559
+ patterns = {findkey: re.compile(rf"^{re.escape(findkey)}\.(\d+)\.") for findkey in findkeys}
560
+
561
+ for key in state_dict:
562
+ for findkey, pattern in patterns.items():
563
+ if match := pattern.match(key):
564
+ num = int(match.group(1))
565
+ max_values[findkey] = max(num, max_values[findkey] if max_values[findkey] is not None else num)
566
+
567
+ return tuple(max_values[findkey] for findkey in findkeys) if len(findkeys) > 1 else max_values[findkeys[0]]
568
+
569
+ def infer_parameters_from_state_dict_for_dat(self, state_dict, upscale=4):
570
+ if "params" in state_dict:
571
+ state_dict = state_dict["params"]
572
+ elif "params_ema" in state_dict:
573
+ state_dict = state_dict["params_ema"]
574
+
575
+ inferred_params = {}
576
+
577
+ # Speculate on the depth.
578
+ depth = {}
579
+ for key in state_dict.keys():
580
+ if "blocks" in key:
581
+ layer = int(key.split(".")[1])
582
+ block = int(key.split(".")[3])
583
+ depth[layer] = max(depth.get(layer, 0), block + 1)
584
+ inferred_params["depth"] = [depth[layer] for layer in sorted(depth.keys())]
585
+
586
+ # Speculate on the number of num_heads per layer.
587
+ # ex.
588
+ # layers.0.blocks.1.attn.temperature: torch.Size([6, 1, 1])
589
+ # layers.5.blocks.5.attn.temperature: torch.Size([6, 1, 1])
590
+ # The shape of temperature is [num_heads, 1, 1].
591
+ num_heads = []
592
+ for layer in range(len(inferred_params["depth"])):
593
+ for block in range(inferred_params["depth"][layer]):
594
+ key = f"layers.{layer}.blocks.{block}.attn.temperature"
595
+ if key in state_dict:
596
+ num_heads_layer = state_dict[key].shape[0]
597
+ num_heads.append(num_heads_layer)
598
+ break
599
+
600
+ inferred_params["num_heads"] = num_heads
601
+
602
+ # Speculate on embed_dim.
603
+ # ex. layers.0.blocks.0.attn.qkv.weight: torch.Size([540, 180])
604
+ for key in state_dict.keys():
605
+ if "attn.qkv.weight" in key:
606
+ qkv_weight = state_dict[key]
607
+ embed_dim = qkv_weight.shape[1] # Note: The in_features of qkv corresponds to embed_dim.
608
+ inferred_params["embed_dim"] = embed_dim
609
+ break
610
+
611
+ # Speculate on split_size.
612
+ # ex.
613
+ # layers.0.blocks.0.attn.attns.0.rpe_biases: torch.Size([945, 2])
614
+ # layers.0.blocks.0.attn.attns.0.relative_position_index: torch.Size([256, 256])
615
+ # layers.0.blocks.2.attn.attn_mask_0: torch.Size([16, 256, 256])
616
+ # layers.0.blocks.2.attn.attn_mask_1: torch.Size([16, 256, 256])
617
+ for key in state_dict.keys():
618
+ if "relative_position_index" in key:
619
+ relative_position_size = state_dict[key].shape[0]
620
+ # Determine split_size[0] and split_size[1] based on the provided data.
621
+ split_size_0, split_size_1 = 8, relative_position_size // 8 # 256 = 8 * 32
622
+ inferred_params["split_size"] = [split_size_0, split_size_1]
623
+ break
624
+
625
+ # Speculate on the expansion_factor.
626
+ # ex.
627
+ # layers.0.blocks.0.ffn.fc1.weight: torch.Size([360, 180])
628
+ # layers.5.blocks.5.ffn.fc1.weight: torch.Size([360, 180])
629
+ if "embed_dim" in inferred_params:
630
+ for key in state_dict.keys():
631
+ if "ffn.fc1.weight" in key:
632
+ fc1_weight = state_dict[key]
633
+ expansion_factor = fc1_weight.shape[0] // inferred_params["embed_dim"]
634
+ inferred_params["expansion_factor"] = expansion_factor
635
+ break
636
+
637
+ inferred_params["img_size"] = 64
638
+ inferred_params["in_chans"] = 3 # Assume an RGB image.
639
+
640
+ for key in state_dict.keys():
641
+ print(f"{key}: {state_dict[key].shape}")
642
+
643
+ return inferred_params
644
+
645
+
646
+ def imwriteUTF8(self, save_path, image): # `cv2.imwrite` does not support writing files to UTF-8 file paths.
647
+ img_name = os.path.basename(save_path)
648
+ _, extension = os.path.splitext(img_name)
649
+ is_success, im_buf_arr = cv2.imencode(extension, image)
650
+ if (is_success): im_buf_arr.tofile(save_path)
651
+
652
+
653
+ def main():
654
+ if torch.cuda.is_available():
655
+ torch.cuda.set_per_process_memory_fraction(0.975, device='cuda:0')
656
+ # set torch options to avoid get black image for RTX16xx card
657
+ # https://github.com/CompVis/stable-diffusion/issues/69#issuecomment-1260722801
658
+ torch.backends.cudnn.enabled = True
659
+ torch.backends.cudnn.benchmark = True
660
+ # Ensure the target directory exists
661
+ os.makedirs('output', exist_ok=True)
662
+
663
+ title = "Image Upscaling & Restoration using GFPGAN / RestoreFormerPlusPlus / CodeFormer / GPEN Algorithm"
664
+ description = r"""
665
+ <a href='https://github.com/TencentARC/GFPGAN' target='_blank'><b>GFPGAN: Towards Real-World Blind Face Restoration and Upscalling of the image with a Generative Facial Prior</b></a>. <br>
666
+ <a href='https://github.com/wzhouxiff/RestoreFormerPlusPlus' target='_blank'><b>RestoreFormer++: Towards Real-World Blind Face Restoration from Undegraded Key-Value Pairs</b></a>. <br>
667
+ <a href='https://github.com/sczhou/CodeFormer' target='_blank'><b>CodeFormer: Towards Robust Blind Face Restoration with Codebook Lookup Transformer (NeurIPS 2022)</b></a>. <br>
668
+ <a href='https://github.com/yangxy/GPEN' target='_blank'><b>GPEN: GAN Prior Embedded Network for Blind Face Restoration in the Wild</b></a>. <br>
669
+ <br>
670
+ Practically, the aforementioned algorithm is used to restore your **old photos** or improve **AI-generated faces**.<br>
671
+ To use it, simply just upload the concerned image.<br>
672
+ """
673
+ article = r"""
674
+ [![download](https://img.shields.io/github/downloads/TencentARC/GFPGAN/total.svg)](https://github.com/TencentARC/GFPGAN/releases)
675
+ [![GitHub Stars](https://img.shields.io/github/stars/TencentARC/GFPGAN?style=social)](https://github.com/TencentARC/GFPGAN)
676
+ [![arXiv](https://img.shields.io/badge/arXiv-Paper-<COLOR>.svg)](https://arxiv.org/abs/2101.04061)
677
+ """
678
+
679
+ upscale = Upscale()
680
+
681
+ rows = []
682
+ tmptype = None
683
+ upscale_model_tables = []
684
+ for key, _ in typed_upscale_models.items():
685
+ upscale_type, upscale_model = key.split(", ", 1)
686
+ if tmptype and tmptype != upscale_type:#RRDB ESRGAN
687
+ speed = "Fast" if tmptype == "SRVGG" else ("Slow" if any(value == tmptype for value in ("DAT", "HAT")) else "Normal")
688
+ upscale_model_header = f"| Upscale Model | Info, Type: {tmptype}, Model execution speed: {speed} | Download URL |\n|------------|------|--------------|"
689
+ upscale_model_tables.append(upscale_model_header + "\n" + "\n".join(rows))
690
+ rows.clear()
691
+ tmptype = upscale_type
692
+ value = upscale_models[upscale_model]
693
+ row = f"| [{upscale_model}]({value[1]}) | " + value[2].replace("\n", "<br>") + " | [download]({value[0]}) |"
694
+ rows.append(row)
695
+ upscale_model_header = f"| Upscale Model Name | Info, Type: {tmptype}, Model execution speed: {speed} | Download URL |\n|------------|------|--------------|"
696
+ upscale_model_tables.append(upscale_model_header + "\n" + "\n".join(rows))
697
+
698
+ with gr.Blocks(title = title) as demo:
699
+ gr.Markdown(value=f"<h1 style=\"text-align:center;\">{title}</h1><br>{description}")
700
+ with gr.Row():
701
+ with gr.Column(variant ="panel"):
702
+ input_image = gr.Image(type="filepath", label="Input", format="png")
703
+ face_model = gr.Dropdown(list(face_models.keys())+[None], type="value", value='GFPGANv1.4.pth', label='Face Restoration version', info="Face Restoration and RealESR can be freely combined in different ways, or one can be set to \"None\" to use only the other model. Face Restoration is primarily used for face restoration in real-life images, while RealESR serves as a background restoration model.")
704
+ upscale_model = gr.Dropdown(list(typed_upscale_models.keys())+[None], type="value", value='SRVGG, realesr-general-x4v3.pth', label='UpScale version')
705
+ upscale_scale = gr.Number(label="Rescaling factor", value=4)
706
+ face_detection = gr.Dropdown(["retinaface_resnet50", "YOLOv5l", "YOLOv5n"], type="value", value="retinaface_resnet50", label="Face Detection type")
707
+ face_detection_threshold = gr.Number(label="Face eye dist threshold", value=10, info="A threshold to filter out faces with too small an eye distance (e.g., side faces).")
708
+ face_detection_only_center = gr.Checkbox(value=False, label="Face detection only center", info="If set to True, only the face closest to the center of the image will be kept.")
709
+ with_model_name = gr.Checkbox(label="Output image files name with model name", value=True)
710
+ with gr.Row():
711
+ submit = gr.Button(value="Submit", variant="primary", size="lg")
712
+ clear = gr.ClearButton(
713
+ components=[
714
+ input_image,
715
+ face_model,
716
+ upscale_model,
717
+ upscale_scale,
718
+ face_detection,
719
+ face_detection_threshold,
720
+ face_detection_only_center,
721
+ with_model_name,
722
+ ], variant="secondary", size="lg",)
723
+ with gr.Column(variant="panel"):
724
+ gallerys = gr.Gallery(type="filepath", label="Output (The whole image)", format="png")
725
+ outputs = gr.File(label="Download the output image")
726
+ with gr.Row(variant="panel"):
727
+ # Generate output array
728
+ output_arr = []
729
+ for file_name in example_list:
730
+ output_arr.append([file_name,])
731
+ gr.Examples(output_arr, inputs=[input_image,], examples_per_page=20)
732
+ with gr.Row(variant="panel"):
733
+ # Convert to Markdown table
734
+ header = "| Face Model Name | Info | Download URL |\n|------------|------|--------------|"
735
+ rows = [
736
+ f"| [{key}]({value[1]}) | " + value[2].replace("\n", "<br>") + f" | [download]({value[0]}) |"
737
+ for key, value in face_models.items()
738
+ ]
739
+ markdown_table = header + "\n" + "\n".join(rows)
740
+ gr.Markdown(value=markdown_table)
741
+
742
+ for table in upscale_model_tables:
743
+ with gr.Row(variant="panel"):
744
+ gr.Markdown(value=table)
745
+
746
+ submit.click(
747
+ upscale.inference,
748
+ inputs=[
749
+ input_image,
750
+ face_model,
751
+ upscale_model,
752
+ upscale_scale,
753
+ face_detection,
754
+ face_detection_threshold,
755
+ face_detection_only_center,
756
+ with_model_name,
757
+ ],
758
+ outputs=[gallerys, outputs],
759
+ )
760
+
761
+ demo.queue(default_concurrency_limit=1)
762
+ demo.launch(inbrowser=True)
763
+
764
+
765
+ if __name__ == "__main__":
766
+ main()
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/a01.jpg ADDED

Git LFS Details

  • SHA256: 87f937d80fe59ea4a8c95047d1b0cc0913939863ad2e40d0662413dbb060b5c6
  • Pointer size: 130 Bytes
  • Size of remote file: 65.9 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/a02.jpg ADDED

Git LFS Details

  • SHA256: 6dcf966dddecc2653e5fe4dd55c85a7fced7d8bf623a2ba98152550d81e5a962
  • Pointer size: 130 Bytes
  • Size of remote file: 46 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/a03.jpg ADDED

Git LFS Details

  • SHA256: a5fb1d821abae9f1468a82052d3c445f9bd35c20c480d55b8cb9e33e82e812a9
  • Pointer size: 130 Bytes
  • Size of remote file: 78.3 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/a04.jpg ADDED

Git LFS Details

  • SHA256: 9bfd88ab744acaed9791e96f3d0976e07ecaab02b57b4bab4d49e677c40e5cd3
  • Pointer size: 131 Bytes
  • Size of remote file: 128 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b01.jpg ADDED

Git LFS Details

  • SHA256: b4075ba07149206b97f0e822534ea9378433dc6872f606ba5f142a53b99a0e58
  • Pointer size: 130 Bytes
  • Size of remote file: 32.8 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b02.jpg ADDED

Git LFS Details

  • SHA256: f696cae2afbeea134aff5c26236d5314662ba1d155e62f3ff949dccd3d22519b
  • Pointer size: 130 Bytes
  • Size of remote file: 26.5 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b03.jpg ADDED

Git LFS Details

  • SHA256: 9968af5909bfc759de4e959c24edc69308859be1fcc7926f41df79bee19a55bc
  • Pointer size: 130 Bytes
  • Size of remote file: 30.3 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b04.jpg ADDED

Git LFS Details

  • SHA256: 362346c87d61692127a46a40988d5ab1345b0656f9627e2c75002cbc8ebf03ab
  • Pointer size: 130 Bytes
  • Size of remote file: 88.6 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b05.jpg ADDED

Git LFS Details

  • SHA256: 90424f8a204cd1039ca0efc42a86d785bc684f47276b4dd56d3f40103e9f4e64
  • Pointer size: 130 Bytes
  • Size of remote file: 54.5 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b06.jpg ADDED

Git LFS Details

  • SHA256: 8a42b0b4157edf27a987449e538641756129740d85175e94cc61ed14c2cfe10e
  • Pointer size: 129 Bytes
  • Size of remote file: 8.32 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b07.jpg ADDED

Git LFS Details

  • SHA256: 77db13032029b8daf1592d8580c3cacefd730492032c2ffd0d05f139decf83db
  • Pointer size: 130 Bytes
  • Size of remote file: 27 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b08.jpg ADDED

Git LFS Details

  • SHA256: bcdac7fce85d4624632e6dd59e4f520731f6cf1d7004fabb627923d157e84b41
  • Pointer size: 130 Bytes
  • Size of remote file: 26.5 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b09.jpg ADDED

Git LFS Details

  • SHA256: 4b0beb4ed78c9b1555861cd7ed4bcb0ba878c1983c6dbf7a80d1f602653d8142
  • Pointer size: 130 Bytes
  • Size of remote file: 33.8 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b10.jpg ADDED

Git LFS Details

  • SHA256: 222fd9c2215f5d703685a6435d375afbacc700a0140973b86e05c56e25960337
  • Pointer size: 130 Bytes
  • Size of remote file: 20.3 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/b11.jpg ADDED

Git LFS Details

  • SHA256: 2e3801a73384531afcf22a794cb0cd008e3a72b125ced2fe7dfaf8e8e7c43c4d
  • Pointer size: 130 Bytes
  • Size of remote file: 33.6 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/bus.jpg ADDED

Git LFS Details

  • SHA256: 33b198a1d2839bb9ac4c65d61f9e852196793cae9a0781360859425f6022b69c
  • Pointer size: 131 Bytes
  • Size of remote file: 487 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c01.jpg ADDED

Git LFS Details

  • SHA256: 35b479d3f7ef6566467d9eedc2638ea5d8e875f9322b712a1d71c98e485a69d3
  • Pointer size: 130 Bytes
  • Size of remote file: 40.3 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c02.jpg ADDED

Git LFS Details

  • SHA256: 17b9bc4e0b877cc75bad0478643ccba7772613787590ef3c32ee2ffe03c9f77d
  • Pointer size: 130 Bytes
  • Size of remote file: 62.7 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c03.jpg ADDED

Git LFS Details

  • SHA256: fef184d6f5c70f204ae0b5aa7ad365b08d94770de6b00c5f57e0a6184970047a
  • Pointer size: 130 Bytes
  • Size of remote file: 62.8 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c04.jpg ADDED

Git LFS Details

  • SHA256: 97e1db8acb5e39225b4f54cb6ebf02fc7208c8de57019f6219a46813471a8b45
  • Pointer size: 130 Bytes
  • Size of remote file: 42.6 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c05.jpg ADDED

Git LFS Details

  • SHA256: 60b4ee29e8f5f9ded96d5743f9c69d8054833c8b2ad4758768507459548a9398
  • Pointer size: 131 Bytes
  • Size of remote file: 117 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c06.jpg ADDED

Git LFS Details

  • SHA256: 85760e49958229e4c24e2fd66c55f2c6fe7907baead385802b93fdc0a873c81f
  • Pointer size: 130 Bytes
  • Size of remote file: 63.9 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c07.jpg ADDED

Git LFS Details

  • SHA256: 141a538476039df8a1d2d0562d584df969c19ac3e533aa3a475d9c862f126f5f
  • Pointer size: 130 Bytes
  • Size of remote file: 56 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c08.jpg ADDED

Git LFS Details

  • SHA256: 0f29cba0630f60b108fe1c49a2686a7315bd5e18e048588c4756b3856158bcf0
  • Pointer size: 130 Bytes
  • Size of remote file: 37.5 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c09.jpg ADDED

Git LFS Details

  • SHA256: c86def0cc5ab1a10d0c65f4112f6fbed5981925739fa6ad1f3225db4e38d659d
  • Pointer size: 131 Bytes
  • Size of remote file: 277 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/c10.jpg ADDED

Git LFS Details

  • SHA256: 509e5bb9d0af907ce134e8027c21df73f7568c6eb0bd572a959216604f129dd3
  • Pointer size: 131 Bytes
  • Size of remote file: 260 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/images/zidane.jpg ADDED

Git LFS Details

  • SHA256: 356dad2107bb0254e4e4a81bc1d9c7140043e88569d546e5b404b19bffa77d0a
  • Pointer size: 131 Bytes
  • Size of remote file: 169 kB
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/packages.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ffmpeg
2
+ libsm6
3
+ libxext6
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/requirements.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu124
2
+
3
+ gradio==5.15.0
4
+
5
+ basicsr @ git+https://github.com/avan06/BasicSR
6
+ facexlib @ git+https://github.com/avan06/facexlib
7
+ gfpgan @ git+https://github.com/avan06/GFPGAN
8
+
9
+ numpy
10
+ opencv-python
11
+
12
+ torch==2.5.0+cu124; sys_platform != 'darwin'
13
+ torchvision==0.20.0+cu124; sys_platform != 'darwin'
14
+ torch==2.5.0; sys_platform == 'darwin'
15
+ torchvision==0.20.0; sys_platform == 'darwin'
16
+
17
+ scipy
18
+ tqdm
19
+ lmdb
20
+ pyyaml
21
+ yapf
22
+
23
+ image_gen_aux @ git+https://github.com/huggingface/image_gen_aux
24
+ gdown # supports downloading the large file from Google Drive
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/utils/dataops.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # The file source is from the [ESRGAN](https://github.com/xinntao/ESRGAN) project
4
+ # forked by authors [joeyballentine](https://github.com/joeyballentine/ESRGAN) and [BlueAmulet](https://github.com/BlueAmulet/ESRGAN).
5
+
6
+ import gc
7
+
8
+ import numpy as np
9
+ import torch
10
+
11
+
12
+ def bgr_to_rgb(image: torch.Tensor) -> torch.Tensor:
13
+ # flip image channels
14
+ # https://github.com/pytorch/pytorch/issues/229
15
+ out: torch.Tensor = image.flip(-3)
16
+ # out: torch.Tensor = image[[2, 1, 0], :, :] #RGB to BGR #may be faster
17
+ return out
18
+
19
+
20
+ def rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:
21
+ # same operation as bgr_to_rgb(), flip image channels
22
+ return bgr_to_rgb(image)
23
+
24
+
25
+ def bgra_to_rgba(image: torch.Tensor) -> torch.Tensor:
26
+ out: torch.Tensor = image[[2, 1, 0, 3], :, :]
27
+ return out
28
+
29
+
30
+ def rgba_to_bgra(image: torch.Tensor) -> torch.Tensor:
31
+ # same operation as bgra_to_rgba(), flip image channels
32
+ return bgra_to_rgba(image)
33
+
34
+
35
+ def auto_split_upscale(
36
+ lr_img: np.ndarray,
37
+ upscale_function,
38
+ scale: int = 4,
39
+ overlap: int = 32,
40
+ max_depth: int = None,
41
+ current_depth: int = 1,
42
+ ):
43
+ # Attempt to upscale if unknown depth or if reached known max depth
44
+ if max_depth is None or max_depth == current_depth:
45
+ try:
46
+ print(f"auto_split_upscale, current depth: {current_depth}")
47
+ result, _ = upscale_function(lr_img, scale)
48
+ return result, current_depth
49
+ except RuntimeError as e:
50
+ # Check to see if its actually the CUDA out of memory error
51
+ if "CUDA" in str(e):
52
+ # Collect garbage (clear VRAM)
53
+ torch.cuda.empty_cache()
54
+ gc.collect()
55
+ # Re-raise the exception if not an OOM error
56
+ else:
57
+ raise RuntimeError(e)
58
+ finally:
59
+ # Free GPU memory and clean up resources
60
+ torch.cuda.empty_cache()
61
+ gc.collect()
62
+
63
+ h, w, c = lr_img.shape
64
+
65
+ # Split image into 4ths
66
+ top_left = lr_img[: h // 2 + overlap, : w // 2 + overlap, :]
67
+ top_right = lr_img[: h // 2 + overlap, w // 2 - overlap :, :]
68
+ bottom_left = lr_img[h // 2 - overlap :, : w // 2 + overlap, :]
69
+ bottom_right = lr_img[h // 2 - overlap :, w // 2 - overlap :, :]
70
+
71
+ # Recursively upscale the quadrants
72
+ # After we go through the top left quadrant, we know the maximum depth and no longer need to test for out-of-memory
73
+ top_left_rlt, depth = auto_split_upscale(
74
+ top_left,
75
+ upscale_function,
76
+ scale=scale,
77
+ overlap=overlap,
78
+ max_depth=max_depth,
79
+ current_depth=current_depth + 1,
80
+ )
81
+ top_right_rlt, _ = auto_split_upscale(
82
+ top_right,
83
+ upscale_function,
84
+ scale=scale,
85
+ overlap=overlap,
86
+ max_depth=depth,
87
+ current_depth=current_depth + 1,
88
+ )
89
+ bottom_left_rlt, _ = auto_split_upscale(
90
+ bottom_left,
91
+ upscale_function,
92
+ scale=scale,
93
+ overlap=overlap,
94
+ max_depth=depth,
95
+ current_depth=current_depth + 1,
96
+ )
97
+ bottom_right_rlt, _ = auto_split_upscale(
98
+ bottom_right,
99
+ upscale_function,
100
+ scale=scale,
101
+ overlap=overlap,
102
+ max_depth=depth,
103
+ current_depth=current_depth + 1,
104
+ )
105
+
106
+ # Define output shape
107
+ out_h = h * scale
108
+ out_w = w * scale
109
+
110
+ # Create blank output image
111
+ output_img = np.zeros((out_h, out_w, c), np.uint8)
112
+
113
+ # Fill output image with tiles, cropping out the overlaps
114
+ output_img[: out_h // 2, : out_w // 2, :] = top_left_rlt[
115
+ : out_h // 2, : out_w // 2, :
116
+ ]
117
+ output_img[: out_h // 2, -out_w // 2 :, :] = top_right_rlt[
118
+ : out_h // 2, -out_w // 2 :, :
119
+ ]
120
+ output_img[-out_h // 2 :, : out_w // 2, :] = bottom_left_rlt[
121
+ -out_h // 2 :, : out_w // 2, :
122
+ ]
123
+ output_img[-out_h // 2 :, -out_w // 2 :, :] = bottom_right_rlt[
124
+ -out_h // 2 :, -out_w // 2 :, :
125
+ ]
126
+
127
+ return output_img, depth
Image_Face_Upscale_Restoration-GFPGAN-RestoreFormer-CodeFormer-GPEN/webui.bat ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+
3
+ :: The source of the webui.bat file is stable-diffusion-webui
4
+
5
+ if not defined PYTHON (set PYTHON=python)
6
+ if not defined VENV_DIR (set "VENV_DIR=%~dp0%venv")
7
+
8
+ mkdir tmp 2>NUL
9
+
10
+ %PYTHON% -c "" >tmp/stdout.txt 2>tmp/stderr.txt
11
+ if %ERRORLEVEL% == 0 goto :check_pip
12
+ echo Couldn't launch python
13
+ goto :show_stdout_stderr
14
+
15
+ :check_pip
16
+ %PYTHON% -mpip --help >tmp/stdout.txt 2>tmp/stderr.txt
17
+ if %ERRORLEVEL% == 0 goto :start_venv
18
+ if "%PIP_INSTALLER_LOCATION%" == "" goto :show_stdout_stderr
19
+ %PYTHON% "%PIP_INSTALLER_LOCATION%" >tmp/stdout.txt 2>tmp/stderr.txt
20
+ if %ERRORLEVEL% == 0 goto :start_venv
21
+ echo Couldn't install pip
22
+ goto :show_stdout_stderr
23
+
24
+ :start_venv
25
+ if ["%VENV_DIR%"] == ["-"] goto :skip_venv
26
+ if ["%SKIP_VENV%"] == ["1"] goto :skip_venv
27
+
28
+ dir "%VENV_DIR%\Scripts\Python.exe" >tmp/stdout.txt 2>tmp/stderr.txt
29
+ if %ERRORLEVEL% == 0 goto :activate_venv
30
+
31
+ for /f "delims=" %%i in ('CALL %PYTHON% -c "import sys; print(sys.executable)"') do set PYTHON_FULLNAME="%%i"
32
+ echo Creating venv in directory %VENV_DIR% using python %PYTHON_FULLNAME%
33
+ %PYTHON_FULLNAME% -m venv "%VENV_DIR%" >tmp/stdout.txt 2>tmp/stderr.txt
34
+ if %ERRORLEVEL% == 0 goto :activate_venv
35
+ echo Unable to create venv in directory "%VENV_DIR%"
36
+ goto :show_stdout_stderr
37
+
38
+ :activate_venv
39
+ set PYTHON="%VENV_DIR%\Scripts\Python.exe"
40
+ echo venv %PYTHON%
41
+
42
+ :skip_venv
43
+ goto :launch
44
+
45
+ :launch
46
+ %PYTHON% app.py %COMMANDLINE_ARGS% %*
47
+ pause
48
+ exit /b
49
+
50
+ :show_stdout_stderr
51
+
52
+ echo.
53
+ echo exit code: %errorlevel%
54
+
55
+ for /f %%i in ("tmp\stdout.txt") do set size=%%~zi
56
+ if %size% equ 0 goto :show_stderr
57
+ echo.
58
+ echo stdout:
59
+ type tmp\stdout.txt
60
+
61
+ :show_stderr
62
+ for /f %%i in ("tmp\stderr.txt") do set size=%%~zi
63
+ if %size% equ 0 goto :show_stderr
64
+ echo.
65
+ echo stderr:
66
+ type tmp\stderr.txt
67
+
68
+ :endofscript
69
+
70
+ echo.
71
+ echo Launch unsuccessful. Exiting.
72
+ pause