[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\r\n__pycache__/\r\n*.py[cod]\r\n*$py.class"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Material Map Generator\n\nEasily create AI generated Normal maps, Displacement maps, and Roughness maps.\n\n|Input|Output|Output|Output|\n|:-:|:-:|:-:|:-:|\n|Diffuse Texture|Normal Map|Displacement Map|Roughness Map|\n|<img src=\"./input/example.png\" width=\"128\" height=\"128\">|<img src=\"./output/example_Normal.png\" width=\"128\" height=\"128\">|<img src=\"./output/example_Displacement.png\" width=\"128\" height=\"128\">|<img src=\"./output/example_Roughness.png\" width=\"128\" height=\"128\">|\n\nBefore you begin, make sure you have numpy, opencv-python, and pytorch installed (`pip install torch --index-url https://download.pytorch.org/whl/cu117`).\n\nTo run, put images in the `input` folder, and type `python generate.py`. Output images will then be placed in the `output` folder, with the type of map appended to the file name.\n\nTo run on CPU instead of GPU (not recommended) use the `--cpu` flag.\n\nIf you run out of VRAM while generating the maps, try decreasing the tile size by using the `--tile_size` flag. `--tile size 512` is the default. You can also increase this if your GPU has a lot of VRAM.\n\nTo avoid seams and other artifacts that can be created, there are 3 optional flags included: `--seamless`, `--mirror`, and `--replicate` for creating different kinds of seamlessness or padding.\n\nTo create material maps in the format used by Ishiiruka Dolphin, use the `--ishiiruka` flag. These can then be converted using Ishiiruka's texture tool. If you want to skip having to use the texture tool, you can use the `--ishiiruka_texture_tool` flag instead, and it will generate the textures in that format instead.\n\nThanks to Xinntao for the ESRGAN architecture used to train these models. The included models are lighter than regular ones and therefore require less VRAM to process the images with.\n"
  },
  {
    "path": "generate.py",
    "content": "import argparse\r\nimport os\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport torch\r\nimport sys\r\n\r\nimport utils.imgops as ops\r\nimport utils.architecture.architecture as arch\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--input', default='input', help='Input folder')\r\nparser.add_argument('--output', default='output', help='Output folder')\r\nparser.add_argument('--reverse', help='Reverse Order', action=\"store_true\")\r\nparser.add_argument('--tile_size', default=512,\r\n                    help='Tile size for splitting', type=int)\r\nparser.add_argument('--seamless', action='store_true',\r\n                    help='Seamless upscaling')\r\nparser.add_argument('--mirror', action='store_true',\r\n                    help='Mirrored seamless upscaling')\r\nparser.add_argument('--replicate', action='store_true',\r\n                    help='Replicate edge pixels for padding')\r\nparser.add_argument('--cpu', action='store_true',\r\n                    help='Use CPU instead of CUDA')\r\nparser.add_argument('--ishiiruka', action='store_true',\r\n                    help='Save textures in the format used in Ishiiruka Dolphin material map texture packs')\r\nparser.add_argument('--ishiiruka_texture_encoder', action='store_true',\r\n                    help='Save textures in the format used by Ishiiruka Dolphin\\'s Texture Encoder tool')\r\nargs = parser.parse_args()\r\n\r\nif not os.path.exists(args.input):\r\n    print('Error: Folder [{:s}] does not exist.'.format(args.input))\r\n    sys.exit(1)\r\nelif os.path.isfile(args.input):\r\n    print('Error: Folder [{:s}] is a file.'.format(args.input))\r\n    sys.exit(1)\r\nelif os.path.isfile(args.output):\r\n    print('Error: Folder [{:s}] is a file.'.format(args.output))\r\n    sys.exit(1)\r\nelif not os.path.exists(args.output):\r\n    os.mkdir(args.output)\r\n\r\ndevice = torch.device('cpu' if args.cpu else 'cuda')\r\n\r\ninput_folder = os.path.normpath(args.input)\r\noutput_folder = os.path.normpath(args.output)\r\n\r\nNORMAL_MAP_MODEL = 'utils/models/1x_NormalMapGenerator-CX-Lite_200000_G.pth'\r\nOTHER_MAP_MODEL = 'utils/models/1x_FrankenMapGenerator-CX-Lite_215000_G.pth'\r\n\r\ndef process(img, model):\r\n    img = img * 1. / np.iinfo(img.dtype).max\r\n    img = img[:, :, [2, 1, 0]]\r\n    img = torch.from_numpy(np.transpose(img, (2, 0, 1))).float()\r\n    img_LR = img.unsqueeze(0)\r\n    img_LR = img_LR.to(device)\r\n\r\n    output = model(img_LR).data.squeeze(\r\n        0).float().cpu().clamp_(0, 1).numpy()\r\n    output = output[[2, 1, 0], :, :]\r\n    output = np.transpose(output, (1, 2, 0))\r\n    output = (output * 255.).round()\r\n    return output\r\n\r\ndef load_model(model_path):\r\n    global device\r\n    state_dict = torch.load(model_path)\r\n    model = arch.RRDB_Net(3, 3, 32, 12, gc=32, upscale=1, norm_type=None, act_type='leakyrelu',\r\n                            mode='CNA', res_scale=1, upsample_mode='upconv')\r\n    model.load_state_dict(state_dict, strict=True)\r\n    del state_dict\r\n    model.eval()\r\n    for k, v in model.named_parameters():\r\n        v.requires_grad = False\r\n    return model.to(device)\r\n\r\nimages=[]\r\nfor root, _, files in os.walk(input_folder):\r\n    for file in sorted(files, reverse=args.reverse):\r\n        if file.split('.')[-1].lower() in ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'tga']:\r\n            images.append(os.path.join(root, file))\r\nmodels = [\r\n    # NORMAL MAP\r\n    load_model(NORMAL_MAP_MODEL), \r\n    # ROUGHNESS/DISPLACEMENT MAPS\r\n    load_model(OTHER_MAP_MODEL)\r\n    ]\r\nfor idx, path in enumerate(images, 1):\r\n    base = os.path.splitext(os.path.relpath(path, input_folder))[0]\r\n    output_dir = os.path.dirname(os.path.join(output_folder, base))\r\n    os.makedirs(output_dir, exist_ok=True)\r\n    print(idx, base)\r\n    # read image\r\n    try: \r\n        img = cv2.imread(path, cv2.cv2.IMREAD_COLOR)\r\n    except:\r\n        img = cv2.imread(path, cv2.IMREAD_COLOR)\r\n        \r\n    # Seamless modes\r\n    if args.seamless:\r\n        img = cv2.copyMakeBorder(img, 16, 16, 16, 16, cv2.BORDER_WRAP)\r\n    elif args.mirror:\r\n        img = cv2.copyMakeBorder(img, 16, 16, 16, 16, cv2.BORDER_REFLECT_101)\r\n    elif args.replicate:\r\n        img = cv2.copyMakeBorder(img, 16, 16, 16, 16, cv2.BORDER_REPLICATE)\r\n\r\n    img_height, img_width = img.shape[:2]\r\n\r\n    # Whether or not to perform the split/merge action\r\n    do_split = img_height > args.tile_size or img_width > args.tile_size\r\n\r\n    if do_split:\r\n        rlts = ops.esrgan_launcher_split_merge(img, process, models, scale_factor=1, tile_size=args.tile_size)\r\n    else:\r\n        rlts = [process(img, model) for model in models]\r\n\r\n    if args.seamless or args.mirror or args.replicate:\r\n        rlts = [ops.crop_seamless(rlt) for rlt in rlts]\r\n\r\n    normal_map = rlts[0]\r\n    roughness = rlts[1][:, :, 1]\r\n    displacement = rlts[1][:, :, 0]\r\n\r\n    if args.ishiiruka_texture_encoder:\r\n        r = 255 - roughness\r\n        g = normal_map[:, :, 1]\r\n        b = displacement\r\n        a = normal_map[:, :, 2]\r\n        output = cv2.merge((b, g, r, a))\r\n        cv2.imwrite(os.path.join(output_folder, '{:s}.mat.png'.format(base)), output)\r\n    else:\r\n        normal_name = '{:s}.nrm.png'.format(base) if args.ishiiruka else '{:s}_Normal.png'.format(base)\r\n        cv2.imwrite(os.path.join(output_folder, normal_name), normal_map)\r\n\r\n        rough_name = '{:s}.spec.png'.format(base) if args.ishiiruka else '{:s}_Roughness.png'.format(base)\r\n        rough_img = 255 - roughness if args.ishiiruka else roughness\r\n        cv2.imwrite(os.path.join(output_folder, rough_name), rough_img)\r\n\r\n        displ_name = '{:s}.bump.png'.format(base) if args.ishiiruka else '{:s}_Displacement.png'.format(base)\r\n        cv2.imwrite(os.path.join(output_folder, displ_name), displacement)\r\n"
  },
  {
    "path": "utils/architecture/architecture.py",
    "content": "import math\nimport torch.nn as nn\nimport utils.architecture.block as B\n\n####################\n# Generator\n####################\n\nclass RRDB_Net(nn.Module):\n    def __init__(self, in_nc, out_nc, nf, nb, gc=32, upscale=4, norm_type=None, act_type='leakyrelu', \\\n            mode='CNA', res_scale=1, upsample_mode='upconv'):\n        super(RRDB_Net, self).__init__()\n        n_upscale = int(math.log(upscale, 2))\n        if upscale == 3:\n            n_upscale = 1\n\n        fea_conv = B.conv_block(in_nc, nf, kernel_size=3, norm_type=None, act_type=None)\n        rb_blocks = [B.RRDB(nf, kernel_size=3, gc=32, stride=1, bias=True, pad_type='zero', \\\n            norm_type=norm_type, act_type=act_type, mode='CNA') for _ in range(nb)]\n        LR_conv = B.conv_block(nf, nf, kernel_size=3, norm_type=norm_type, act_type=None, mode=mode)\n\n        if upsample_mode == 'upconv':\n            upsample_block = B.upconv_blcok\n        elif upsample_mode == 'pixelshuffle':\n            upsample_block = B.pixelshuffle_block\n        else:\n            raise NotImplementedError('upsample mode [%s] is not found' % upsample_mode)\n        if upscale == 3:\n            upsampler = upsample_block(nf, nf, 3, act_type=act_type)\n        else:\n            upsampler = [upsample_block(nf, nf, act_type=act_type) for _ in range(n_upscale)]\n        HR_conv0 = B.conv_block(nf, nf, kernel_size=3, norm_type=None, act_type=act_type)\n        HR_conv1 = B.conv_block(nf, out_nc, kernel_size=3, norm_type=None, act_type=None)\n\n        self.model = B.sequential(fea_conv, B.ShortcutBlock(B.sequential(*rb_blocks, LR_conv)),\\\n            *upsampler, HR_conv0, HR_conv1)\n\n    def forward(self, x):\n        x = self.model(x)\n        return x"
  },
  {
    "path": "utils/architecture/block.py",
    "content": "from collections import OrderedDict\nimport torch\nimport torch.nn as nn\n\n####################\n# Basic blocks\n####################\n\n\ndef act(act_type, inplace=True, neg_slope=0.2, n_prelu=1):\n    # helper selecting activation\n    # neg_slope: for leakyrelu and init of prelu\n    # n_prelu: for p_relu num_parameters\n    act_type = act_type.lower()\n    if act_type == 'relu':\n        layer = nn.ReLU(inplace)\n    elif act_type == 'leakyrelu':\n        layer = nn.LeakyReLU(neg_slope, inplace)\n    elif act_type == 'prelu':\n        layer = nn.PReLU(num_parameters=n_prelu, init=neg_slope)\n    else:\n        raise NotImplementedError('activation layer [{:s}] is not found'.format(act_type))\n    return layer\n\n\ndef norm(norm_type, nc):\n    # helper selecting normalization layer\n    norm_type = norm_type.lower()\n    if norm_type == 'batch':\n        layer = nn.BatchNorm2d(nc, affine=True)\n    elif norm_type == 'instance':\n        layer = nn.InstanceNorm2d(nc, affine=False)\n    else:\n        raise NotImplementedError('normalization layer [{:s}] is not found'.format(norm_type))\n    return layer\n\n\ndef pad(pad_type, padding):\n    # helper selecting padding layer\n    # if padding is 'zero', do by conv layers\n    pad_type = pad_type.lower()\n    if padding == 0:\n        return None\n    if pad_type == 'reflect':\n        layer = nn.ReflectionPad2d(padding)\n    elif pad_type == 'replicate':\n        layer = nn.ReplicationPad2d(padding)\n    else:\n        raise NotImplementedError('padding layer [{:s}] is not implemented'.format(pad_type))\n    return layer\n\n\ndef get_valid_padding(kernel_size, dilation):\n    kernel_size = kernel_size + (kernel_size - 1) * (dilation - 1)\n    padding = (kernel_size - 1) // 2\n    return padding\n\n\nclass ConcatBlock(nn.Module):\n    # Concat the output of a submodule to its input\n    def __init__(self, submodule):\n        super(ConcatBlock, self).__init__()\n        self.sub = submodule\n\n    def forward(self, x):\n        output = torch.cat((x, self.sub(x)), dim=1)\n        return output\n\n    def __repr__(self):\n        tmpstr = 'Identity .. \\n|'\n        modstr = self.sub.__repr__().replace('\\n', '\\n|')\n        tmpstr = tmpstr + modstr\n        return tmpstr\n\n\nclass ShortcutBlock(nn.Module):\n    #Elementwise sum the output of a submodule to its input\n    def __init__(self, submodule):\n        super(ShortcutBlock, self).__init__()\n        self.sub = submodule\n\n    def forward(self, x):\n        output = x + self.sub(x)\n        return output\n\n    def __repr__(self):\n        tmpstr = 'Identity + \\n|'\n        modstr = self.sub.__repr__().replace('\\n', '\\n|')\n        tmpstr = tmpstr + modstr\n        return tmpstr\n\n\nclass ShortcutBlockSPSR(nn.Module):\n    #Elementwise sum the output of a submodule to its input\n    def __init__(self, submodule):\n        super(ShortcutBlockSPSR, self).__init__()\n        self.sub = submodule\n\n    def forward(self, x):\n        return x, self.sub\n\n    def __repr__(self):\n        tmpstr = 'Identity + \\n|'\n        modstr = self.sub.__repr__().replace('\\n', '\\n|')\n        tmpstr = tmpstr + modstr\n        return tmpstr\n\n\ndef sequential(*args):\n    # Flatten Sequential. It unwraps nn.Sequential.\n    if len(args) == 1:\n        if isinstance(args[0], OrderedDict):\n            raise NotImplementedError('sequential does not support OrderedDict input.')\n        return args[0]  # No sequential is needed.\n    modules = []\n    for module in args:\n        if isinstance(module, nn.Sequential):\n            for submodule in module.children():\n                modules.append(submodule)\n        elif isinstance(module, nn.Module):\n            modules.append(module)\n    return nn.Sequential(*modules)\n\n\ndef conv_block(in_nc, out_nc, kernel_size, stride=1, dilation=1, groups=1, bias=True, \\\n               pad_type='zero', norm_type=None, act_type='relu', mode='CNA'):\n    '''\n    Conv layer with padding, normalization, activation\n    mode: CNA --> Conv -> Norm -> Act\n        NAC --> Norm -> Act --> Conv (Identity Mappings in Deep Residual Networks, ECCV16)\n    '''\n    assert mode in ['CNA', 'NAC', 'CNAC'], 'Wrong conv mode [{:s}]'.format(mode)\n    padding = get_valid_padding(kernel_size, dilation)\n    p = pad(pad_type, padding) if pad_type and pad_type != 'zero' else None\n    padding = padding if pad_type == 'zero' else 0\n\n    c = nn.Conv2d(in_nc, out_nc, kernel_size=kernel_size, stride=stride, padding=padding, \\\n            dilation=dilation, bias=bias, groups=groups)\n    a = act(act_type) if act_type else None\n    if 'CNA' in mode:\n        n = norm(norm_type, out_nc) if norm_type else None\n        return sequential(p, c, n, a)\n    elif mode == 'NAC':\n        if norm_type is None and act_type is not None:\n            a = act(act_type, inplace=False)\n            # Important!\n            # input----ReLU(inplace)----Conv--+----output\n            #        |________________________|\n            # inplace ReLU will modify the input, therefore wrong output\n        n = norm(norm_type, in_nc) if norm_type else None\n        return sequential(n, a, p, c)\n\n\n####################\n# Useful blocks\n####################\n\n\nclass ResNetBlock(nn.Module):\n    '''\n    ResNet Block, 3-3 style\n    with extra residual scaling used in EDSR\n    (Enhanced Deep Residual Networks for Single Image Super-Resolution, CVPRW 17)\n    '''\n\n    def __init__(self, in_nc, mid_nc, out_nc, kernel_size=3, stride=1, dilation=1, groups=1, \\\n            bias=True, pad_type='zero', norm_type=None, act_type='relu', mode='CNA', res_scale=1):\n        super(ResNetBlock, self).__init__()\n        conv0 = conv_block(in_nc, mid_nc, kernel_size, stride, dilation, groups, bias, pad_type, \\\n            norm_type, act_type, mode)\n        if mode == 'CNA':\n            act_type = None\n        if mode == 'CNAC':  # Residual path: |-CNAC-|\n            act_type = None\n            norm_type = None\n        conv1 = conv_block(mid_nc, out_nc, kernel_size, stride, dilation, groups, bias, pad_type, \\\n            norm_type, act_type, mode)\n        # if in_nc != out_nc:\n        #     self.project = conv_block(in_nc, out_nc, 1, stride, dilation, 1, bias, pad_type, \\\n        #         None, None)\n        #     print('Need a projecter in ResNetBlock.')\n        # else:\n        #     self.project = lambda x:x\n        self.res = sequential(conv0, conv1)\n        self.res_scale = res_scale\n\n    def forward(self, x):\n        res = self.res(x).mul(self.res_scale)\n        return x + res\n\n\nclass ResidualDenseBlock_5C(nn.Module):\n    '''\n    Residual Dense Block\n    style: 5 convs\n    The core module of paper: (Residual Dense Network for Image Super-Resolution, CVPR 18)\n    '''\n\n    def __init__(self, nc, kernel_size=3, gc=32, stride=1, bias=True, pad_type='zero', \\\n            norm_type=None, act_type='leakyrelu', mode='CNA'):\n        super(ResidualDenseBlock_5C, self).__init__()\n        # gc: growth channel, i.e. intermediate channels\n        self.conv1 = conv_block(nc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, \\\n            norm_type=norm_type, act_type=act_type, mode=mode)\n        self.conv2 = conv_block(nc+gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, \\\n            norm_type=norm_type, act_type=act_type, mode=mode)\n        self.conv3 = conv_block(nc+2*gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, \\\n            norm_type=norm_type, act_type=act_type, mode=mode)\n        self.conv4 = conv_block(nc+3*gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, \\\n            norm_type=norm_type, act_type=act_type, mode=mode)\n        if mode == 'CNA':\n            last_act = None\n        else:\n            last_act = act_type\n        self.conv5 = conv_block(nc+4*gc, nc, 3, stride, bias=bias, pad_type=pad_type, \\\n            norm_type=norm_type, act_type=last_act, mode=mode)\n\n    def forward(self, x):\n        x1 = self.conv1(x)\n        x2 = self.conv2(torch.cat((x, x1), 1))\n        x3 = self.conv3(torch.cat((x, x1, x2), 1))\n        x4 = self.conv4(torch.cat((x, x1, x2, x3), 1))\n        x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))\n        return x5.mul(0.2) + x\n\n\nclass RRDB(nn.Module):\n    '''\n    Residual in Residual Dense Block\n    (ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks)\n    '''\n\n    def __init__(self, nc, kernel_size=3, gc=32, stride=1, bias=True, pad_type='zero', \\\n            norm_type=None, act_type='leakyrelu', mode='CNA'):\n        super(RRDB, self).__init__()\n        self.RDB1 = ResidualDenseBlock_5C(nc, kernel_size, gc, stride, bias, pad_type, \\\n            norm_type, act_type, mode)\n        self.RDB2 = ResidualDenseBlock_5C(nc, kernel_size, gc, stride, bias, pad_type, \\\n            norm_type, act_type, mode)\n        self.RDB3 = ResidualDenseBlock_5C(nc, kernel_size, gc, stride, bias, pad_type, \\\n            norm_type, act_type, mode)\n\n    def forward(self, x):\n        out = self.RDB1(x)\n        out = self.RDB2(out)\n        out = self.RDB3(out)\n        return out.mul(0.2) + x\n\n\n####################\n# Upsampler\n####################\n\n\ndef pixelshuffle_block(in_nc, out_nc, upscale_factor=2, kernel_size=3, stride=1, bias=True, \\\n                        pad_type='zero', norm_type=None, act_type='relu'):\n    '''\n    Pixel shuffle layer\n    (Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional\n    Neural Network, CVPR17)\n    '''\n    conv = conv_block(in_nc, out_nc * (upscale_factor ** 2), kernel_size, stride, bias=bias, \\\n                        pad_type=pad_type, norm_type=None, act_type=None)\n    pixel_shuffle = nn.PixelShuffle(upscale_factor)\n\n    n = norm(norm_type, out_nc) if norm_type else None\n    a = act(act_type) if act_type else None\n    return sequential(conv, pixel_shuffle, n, a)\n\n\ndef upconv_blcok(in_nc, out_nc, upscale_factor=2, kernel_size=3, stride=1, bias=True, \\\n                pad_type='zero', norm_type=None, act_type='relu', mode='nearest'):\n    # Up conv\n    # described in https://distill.pub/2016/deconv-checkerboard/\n    upsample = nn.Upsample(scale_factor=upscale_factor, mode=mode)\n    conv = conv_block(in_nc, out_nc, kernel_size, stride, bias=bias, \\\n                        pad_type=pad_type, norm_type=norm_type, act_type=act_type)\n    return sequential(upsample, conv)\n"
  },
  {
    "path": "utils/imgops.py",
    "content": "import numpy as np\r\nimport math\r\n\r\ndef crop_seamless(img):\r\n    img_height, img_width = img.shape[:2]\r\n    y, x = 16, 16\r\n    h, w = img_height - 32, img_width - 32\r\n    img = img[y:y+h, x:x+w]\r\n    return img\r\n\r\n# from https://github.com/ata4/esrgan-launcher/blob/master/upscale.py\r\ndef esrgan_launcher_split_merge(input_image, upscale_function, models, scale_factor=4, tile_size=512, tile_padding=0.125):\r\n    width, height, depth = input_image.shape\r\n    output_width = width * scale_factor\r\n    output_height = height * scale_factor\r\n    output_shape = (output_width, output_height, depth)\r\n\r\n    # start with black image\r\n    output_images = [np.zeros(output_shape, np.uint8) for i in range(len(models))]\r\n\r\n    tile_padding = math.ceil(tile_size * tile_padding)\r\n    tile_size = math.ceil(tile_size / scale_factor)\r\n\r\n    tiles_x = math.ceil(width / tile_size)\r\n    tiles_y = math.ceil(height / tile_size)\r\n\r\n    for y in range(tiles_y):\r\n        for x in range(tiles_x):\r\n            # extract tile from input image\r\n            ofs_x = x * tile_size\r\n            ofs_y = y * tile_size\r\n\r\n            # input tile area on total image\r\n            input_start_x = ofs_x\r\n            input_end_x = min(ofs_x + tile_size, width)\r\n\r\n            input_start_y = ofs_y\r\n            input_end_y = min(ofs_y + tile_size, height)\r\n\r\n            # input tile area on total image with padding\r\n            input_start_x_pad = max(input_start_x - tile_padding, 0)\r\n            input_end_x_pad = min(input_end_x + tile_padding, width)\r\n\r\n            input_start_y_pad = max(input_start_y - tile_padding, 0)\r\n            input_end_y_pad = min(input_end_y + tile_padding, height)\r\n\r\n            # input tile dimensions\r\n            input_tile_width = input_end_x - input_start_x\r\n            input_tile_height = input_end_y - input_start_y\r\n\r\n            input_tile = input_image[input_start_x_pad:input_end_x_pad, input_start_y_pad:input_end_y_pad]\r\n\r\n            for idx, model in enumerate(models):\r\n\r\n                # upscale tile\r\n                output_tile = upscale_function(input_tile, model)\r\n\r\n                # output tile area on total image\r\n                output_start_x = input_start_x * scale_factor\r\n                output_end_x = input_end_x * scale_factor\r\n\r\n                output_start_y = input_start_y * scale_factor\r\n                output_end_y = input_end_y * scale_factor\r\n\r\n                # output tile area without padding\r\n                output_start_x_tile = (input_start_x - input_start_x_pad) * scale_factor\r\n                output_end_x_tile = output_start_x_tile + input_tile_width * scale_factor\r\n\r\n                output_start_y_tile = (input_start_y - input_start_y_pad) * scale_factor\r\n                output_end_y_tile = output_start_y_tile + input_tile_height * scale_factor\r\n\r\n                # put tile into output image\r\n                output_images[idx][output_start_x:output_end_x, output_start_y:output_end_y] = \\\r\n                    output_tile[output_start_x_tile:output_end_x_tile, output_start_y_tile:output_end_y_tile]\r\n\r\n    return output_images"
  }
]