Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
HolyWu committed Aug 16, 2021
1 parent b60aa47 commit e37c7d8
Show file tree
Hide file tree
Showing 13 changed files with 853 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitattributes
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
138 changes: 138 additions & 0 deletions .gitignore
@@ -0,0 +1,138 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/
27 changes: 27 additions & 0 deletions README.md
@@ -0,0 +1,27 @@
# Real-ESRGAN
Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data

Ported from https://github.com/xinntao/Real-ESRGAN


## Dependencies
- [NumPy](https://numpy.org/install)
- [PyTorch](https://pytorch.org/get-started), preferably with CUDA. Note that `torchvision` and `torchaudio` are not required and hence can be omitted from the command.
- [VapourSynth](http://www.vapoursynth.com/)


## Installation
```
pip install --upgrade vsrealesrgan
python -m vsrealesrgan
```


## Usage
```python
from vsrealesrgan import RealESRGAN

ret = RealESRGAN(clip)
```

See `__init__.py` for the description of the parameters.
3 changes: 3 additions & 0 deletions pyproject.toml
@@ -0,0 +1,3 @@
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
27 changes: 27 additions & 0 deletions setup.cfg
@@ -0,0 +1,27 @@
[metadata]
name = vsrealesrgan
version = 1.0.0
author = HolyWu
description = RealESRGAN function for VapourSynth
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/HolyWu/vs-realesrgan
classifiers =
License :: OSI Approved :: BSD License
Operating System :: OS Independent
Programming Language :: Python :: 3
Programming Language :: Python :: 3 :: Only
Topic :: Multimedia :: Video

[options]
zip_safe = False
packages = find:
python_requires = >=3.6
install_requires =
numpy
requests
torch
tqdm

[options.package_data]
* = *.pth
Empty file.
Empty file.
75 changes: 75 additions & 0 deletions vsrealesrgan/__init__.py
@@ -0,0 +1,75 @@
import numpy as np
import os
import torch
import vapoursynth as vs
from .utils import RealESRGANer


def RealESRGAN(clip: vs.VideoNode, scale: int=2, tile: int=0, tile_pad: int=10, pre_pad: int=0, half: bool=False, device_type: str='cuda', device_index: int=0) -> vs.VideoNode:
'''
Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data
Parameters:
clip: Clip to process. Only planar format with float sample type of 32 bit depth is supported.
scale: Upsample scale factor of the network. Must be 2 or 4.
tile: Tile size, 0 for no tile.
tile_pad: Tile padding.
pre_pad: Pre padding size at each border.
half: Use half precision.
device_type: Device type on which the tensor is allocated. Must be 'cuda' or 'cpu'.
device_index: Device ordinal for the device type.
'''
if not isinstance(clip, vs.VideoNode):
raise vs.Error('RealESRGAN: this is not a clip')

if clip.format.id != vs.RGBS:
raise vs.Error('RealESRGAN: only RGBS format is supported')

if scale not in [2, 4]:
raise vs.Error('RealESRGAN: scale must be 2 or 4')

device_type = device_type.lower()

if device_type not in ['cuda', 'cpu']:
raise vs.Error("RealESRGAN: device_type must be 'cuda' or 'cpu'")

if device_type == 'cuda' and not torch.cuda.is_available():
raise vs.Error('RealESRGAN: CUDA is not available')

device = torch.device(device_type, device_index)
if device_type == 'cuda':
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True

model_path = os.path.join(os.path.dirname(__file__), f'RealESRGAN_x{scale}plus.pth')

upsampler = RealESRGANer(device, scale, model_path, tile, tile_pad, pre_pad, half)

new_clip = clip.std.BlankClip(width=clip.width * scale, height=clip.height * scale)

def realesrgan(n: int, f: vs.VideoFrame) -> vs.VideoFrame:
img = frame_to_tensor(f[0])
img = upsampler.enhance(img)
return tensor_to_frame(img, f[1])

return new_clip.std.ModifyFrame(clips=[clip, new_clip], selector=realesrgan)


def frame_to_tensor(f: vs.VideoFrame) -> torch.Tensor:
arr = np.stack([np.asarray(f.get_read_array(plane)) for plane in range(f.format.num_planes)])
return torch.from_numpy(arr).unsqueeze(0)


def tensor_to_frame(t: torch.Tensor, f: vs.VideoFrame) -> vs.VideoFrame:
arr = t.data.squeeze().cpu().numpy()
fout = f.copy()
for plane in range(fout.format.num_planes):
np.copyto(np.asarray(fout.get_write_array(plane)), arr[plane, :, :])
return fout
16 changes: 16 additions & 0 deletions vsrealesrgan/__main__.py
@@ -0,0 +1,16 @@
import os.path
import requests
from tqdm import tqdm

def download_model(url: str) -> None:
filename = url.split('/')[-1]
r = requests.get(url, stream=True)
with open(os.path.join(os.path.dirname(__file__), filename), 'wb') as f:
with tqdm(unit='B', unit_scale=True, unit_divisor=1024, miniters=1, desc=filename, total=int(r.headers.get('content-length', 0))) as pbar:
for chunk in r.iter_content(chunk_size=4096):
f.write(chunk)
pbar.update(len(chunk))

if __name__ == '__main__':
download_model('https://github.com/HolyWu/vs-realesrgan/releases/download/model/RealESRGAN_x2plus.pth')
download_model('https://github.com/HolyWu/vs-realesrgan/releases/download/model/RealESRGAN_x4plus.pth')

0 comments on commit e37c7d8

Please sign in to comment.