[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# dotenv\n.env\n\n# virtualenv\n.venv\nvenv/\nENV/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n\nmodel.ckpt*\ncheckpoint\n"
  },
  {
    "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": "MANIFEST.in",
    "content": "include README.md LICENSE\n"
  },
  {
    "path": "README.md",
    "content": "# Time Domain Neural Audio Style Transfer\n\nNIPS2017 \"Time Domain Neural Audio Style Transfer\" code repository  \nhttps://arxiv.org/abs/1711.11160  \nParag K. Mital  \n  \nPresented at [https://nips2017creativity.github.io](https://nips2017creativity.github.io)\n\nColab: https://colab.research.google.com/drive/18_DckMGM-fsSthIqZI9sOAlY6I3plDLD\n\n# Introduction\n\n  A recently published method for audio style transfer has shown how to extend the process of image style transfer to audio.  This method synthesizes audio \"content\" and \"style\" independently using the magnitudes of a short time Fourier transform, shallow convolutional networks with randomly initialized filters, and iterative phase reconstruction with Griffin-Lim.  In this work, we explore whether it is possible to directly optimize a time domain audio signal, removing the process of phase reconstruction and opening up possibilities for real-time applications and higher quality syntheses.  We explore a variety of style transfer processes on neural networks that operate directly on time domain audio signals and demonstrate one such network capable of audio stylization.\n\n# Installation\n\nPython 3.4+ required (Magenta is required for NSynth and WaveNet models only; but I was unable to stylize audio using these models).\n\n# Code\n\nThe `models` folder shows three different modules, `timedomain` shows how to combine the different input features described in the paper, including `real`, `imaginary`, and `magnitudes` and `phases` of a discrete timedomain transform for performing time-domain audio style transfer.  Have a look at the `input_features` argument for specifying different input features to use for the time domain style transfer algorithm.   \n\nThe `uylanov` module includes the approach by Ulyanov et al.  \n\nFinally, the `nsynth` module includes the NSynth Autoencoder, showing how to use the encoder or the decoder as approaches to audio stylization, though I was unable to perform any successful stylization using this approach.\n\n# Usage\n\nYou can use any of the modules in the models folder, `timedomain`, `uylanov`, or `nsynth` from the command line like so:\n\n```\npython models/timedomain.py\nusage: timedomain.py [-h] -s STYLE -c CONTENT -o OUTPUT [-m MODE]\n```\n\nThese take paths to the style or content files or paths (when mode is 'batch'), e.g.:\n\n```\npython models/timedomain.py -s /path/to/style.wav -c /path/to/content.wav -o /path/to/output.wav\n```\n\nor:\n\n```\npython models/timedomain.py -s /path/to/style/wavs/folder -c /path/to/content/wavs/folder -o /path/to/output/wavs/folder -m batch\n```\n\n# Audio Samples\n\nThis repository also includes audio samples from Robert Thomas (`target/male-talking.wav`), music by [Robert Thomas](http://robertthomassound.com/) and [Franky Redente](https://soundcloud.com/franky80y) (`corpus/robthomas*`), samples and music by [John Tejada](http://www.paletterecordings.com/) and [Reggie Watts](http://reggiewatts.com/) (`corpus/johntejada*`, `target/beat-box*`, `target/male-singing.wav`, `target/female-singing.wav`), and one voice sample by [Ashwin Vaswani](https://www.ashwinvaswani.com/) (`target/male-taal.wav`).  These clips were generously contributed to this work by their authors and are *licensed under a Creative Commons Attribution-NonCommercial 4.0 International License*.  That means these clips are not for commercial usage.  Further, any sharing of these clips must contain attribution to their authors, and must be shared under the same license.\n\n# Example Outputs\n\nThe folder `examples` includes syntheses using the `models/timedomain` module and the original Ulyanov network in `models/uylanov`, and were created using the script in the root of the repo, `search.py`.\n`\n"
  },
  {
    "path": "audio_style_transfer/__init__.py",
    "content": ""
  },
  {
    "path": "audio_style_transfer/__version__.py",
    "content": "VERSION = (1, 0, 0)\n\n__version__ = '.'.join(map(str, VERSION))\n"
  },
  {
    "path": "audio_style_transfer/models/__init__.py",
    "content": ""
  },
  {
    "path": "audio_style_transfer/models/nsynth.py",
    "content": "\"\"\"NSynth & WaveNet Audio Style Transfer.\"\"\"\nimport os\nimport glob\nimport librosa\nimport argparse\nimport numpy as np\nimport tensorflow as tf\nfrom magenta.models.nsynth.wavenet import masked\nfrom magenta.models.nsynth.utils import mu_law, inv_mu_law_numpy\nfrom audio_style_transfer import utils\n\n\ndef compute_wavenet_encoder_features(content, style):\n    ae_hop_length = 512\n    ae_bottleneck_width = 16\n    ae_num_stages = 10\n    ae_num_layers = 30\n    ae_filter_length = 3\n    ae_width = 128\n    # Encode the source with 8-bit Mu-Law.\n    n_frames = content.shape[0]\n    n_samples = content.shape[1]\n    content_tf = np.ascontiguousarray(content)\n    style_tf = np.ascontiguousarray(style)\n    g = tf.Graph()\n    content_features = []\n    style_features = []\n    layers = []\n    with g.as_default(), g.device('/cpu:0'), tf.Session() as sess:\n        x = tf.placeholder('float32', [n_frames, n_samples], name=\"x\")\n        x_quantized = mu_law(x)\n        x_scaled = tf.cast(x_quantized, tf.float32) / 128.0\n        x_scaled = tf.expand_dims(x_scaled, 2)\n        en = masked.conv1d(\n            x_scaled,\n            causal=False,\n            num_filters=ae_width,\n            filter_length=ae_filter_length,\n            name='ae_startconv')\n        for num_layer in range(ae_num_layers):\n            dilation = 2**(num_layer % ae_num_stages)\n            d = tf.nn.relu(en)\n            d = masked.conv1d(\n                d,\n                causal=False,\n                num_filters=ae_width,\n                filter_length=ae_filter_length,\n                dilation=dilation,\n                name='ae_dilatedconv_%d' % (num_layer + 1))\n            d = tf.nn.relu(d)\n            en += masked.conv1d(\n                d,\n                num_filters=ae_width,\n                filter_length=1,\n                name='ae_res_%d' % (num_layer + 1))\n            layers.append(en)\n        en = masked.conv1d(\n            en,\n            num_filters=ae_bottleneck_width,\n            filter_length=1,\n            name='ae_bottleneck')\n        en = masked.pool1d(en, ae_hop_length, name='ae_pool', mode='avg')\n        saver = tf.train.Saver()\n        saver.restore(sess, './model.ckpt-200000')\n        content_features = sess.run(layers, feed_dict={x: content_tf})\n        styles = sess.run(layers, feed_dict={x: style_tf})\n        for i, style_feature in enumerate(styles):\n            n_features = np.prod(layers[i].shape.as_list()[-1])\n            features = np.reshape(style_feature, (-1, n_features))\n            style_gram = np.matmul(features.T, features) / (n_samples *\n                                                            n_frames)\n            style_features.append(style_gram)\n    return content_features, style_features\n\n\ndef compute_wavenet_encoder_stylization(n_samples,\n                                        n_frames,\n                                        content_features,\n                                        style_features,\n                                        alpha=1e-4,\n                                        learning_rate=1e-3,\n                                        iterations=100):\n    ae_style_layers = [1, 5]\n    ae_num_layers = 30\n    ae_num_stages = 10\n    ae_filter_length = 3\n    ae_width = 128\n    layers = []\n    with tf.Graph().as_default() as g, g.device('/cpu:0'), tf.Session() as sess:\n        x = tf.placeholder(\n            name=\"x\", shape=(n_frames, n_samples, 1), dtype=tf.float32)\n        en = masked.conv1d(\n            x,\n            causal=False,\n            num_filters=ae_width,\n            filter_length=ae_filter_length,\n            name='ae_startconv')\n        for num_layer in range(ae_num_layers):\n            dilation = 2**(num_layer % ae_num_stages)\n            d = tf.nn.relu(en)\n            d = masked.conv1d(\n                d,\n                causal=False,\n                num_filters=ae_width,\n                filter_length=ae_filter_length,\n                dilation=dilation,\n                name='ae_dilatedconv_%d' % (num_layer + 1))\n            d = tf.nn.relu(d)\n            en += masked.conv1d(\n                d,\n                num_filters=ae_width,\n                filter_length=1,\n                name='ae_res_%d' % (num_layer + 1))\n            layer_i = tf.identity(en, name='layer_{}'.format(num_layer))\n            layers.append(layer_i)\n        saver = tf.train.Saver()\n        saver.restore(sess, './model.ckpt-200000')\n        sess.run(tf.initialize_all_variables())\n        frozen_graph_def = tf.graph_util.convert_variables_to_constants(\n            sess, sess.graph_def, [en.name.replace(':0', '')] +\n            ['layer_{}'.format(i) for i in range(ae_num_layers)])\n    with tf.Graph().as_default() as g, g.device('/cpu:0'), tf.Session() as sess:\n        x = tf.Variable(\n            np.random.randn(n_frames, n_samples, 1).astype(np.float32))\n        tf.import_graph_def(frozen_graph_def, input_map={'x:0': x})\n        content_loss = np.float32(0.0)\n        style_loss = np.float32(0.0)\n        for num_layer in ae_style_layers:\n            layer_i = g.get_tensor_by_name(name='import/layer_%d:0' %\n                                           (num_layer))\n            content_loss = content_loss + alpha * 2 * tf.nn.l2_loss(\n                layer_i - content_features[num_layer])\n            n_features = layer_i.shape.as_list()[-1]\n            features = tf.reshape(layer_i, (-1, n_features))\n            gram = tf.matmul(tf.transpose(features), features) / (n_frames *\n                                                                  n_samples)\n            style_loss = style_loss + 2 * tf.nn.l2_loss(gram - style_features[\n                num_layer])\n        loss = content_loss + style_loss\n        # Optimization\n        print('Started optimization.')\n        opt = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)\n        var_list = tf.trainable_variables()\n        print(var_list)\n        sess.run(tf.initialize_all_variables())\n        for i in range(iterations):\n            s, c, layer, _ = sess.run([style_loss, content_loss, loss, opt])\n            print(i, '- Style:', s, 'Content:', c, end='\\r')\n        result = x.eval()\n        result = inv_mu_law_numpy(result[..., 0] / result.max() * 128.0)\n    return result\n\n\ndef compute_wavenet_decoder_features(content, style):\n    num_stages = 10\n    num_layers = 30\n    filter_length = 3\n    width = 512\n    skip_width = 256\n    # Encode the source with 8-bit Mu-Law.\n    n_frames = content.shape[0]\n    n_samples = content.shape[1]\n    content_tf = np.ascontiguousarray(content)\n    style_tf = np.ascontiguousarray(style)\n    g = tf.Graph()\n    content_features = []\n    style_features = []\n    layers = []\n    with g.as_default(), g.device('/cpu:0'), tf.Session() as sess:\n        x = tf.placeholder('float32', [n_frames, n_samples], name=\"x\")\n        x_quantized = mu_law(x)\n        x_scaled = tf.cast(x_quantized, tf.float32) / 128.0\n        x_scaled = tf.expand_dims(x_scaled, 2)\n        layer = x_scaled\n        layer = masked.conv1d(\n            layer, num_filters=width, filter_length=filter_length, name='startconv')\n\n        # Set up skip connections.\n        s = masked.conv1d(\n            layer, num_filters=skip_width, filter_length=1, name='skip_start')\n\n        # Residual blocks with skip connections.\n        for i in range(num_layers):\n            dilation = 2**(i % num_stages)\n            d = masked.conv1d(\n                layer,\n                num_filters=2 * width,\n                filter_length=filter_length,\n                dilation=dilation,\n                name='dilatedconv_%d' % (i + 1))\n            assert d.get_shape().as_list()[2] % 2 == 0\n            m = d.get_shape().as_list()[2] // 2\n            d_sigmoid = tf.sigmoid(d[:, :, :m])\n            d_tanh = tf.tanh(d[:, :, m:])\n            d = d_sigmoid * d_tanh\n\n            layer += masked.conv1d(\n                d, num_filters=width, filter_length=1, name='res_%d' % (i + 1))\n            s += masked.conv1d(\n                d,\n                num_filters=skip_width,\n                filter_length=1,\n                name='skip_%d' % (i + 1))\n            layers.append(s)\n\n        saver = tf.train.Saver()\n        saver.restore(sess, './model.ckpt-200000')\n        content_features = sess.run(layers, feed_dict={x: content_tf})\n        styles = sess.run(layers, feed_dict={x: style_tf})\n        for i, style_feature in enumerate(styles):\n            n_features = np.prod(layers[i].shape.as_list()[-1])\n            features = np.reshape(style_feature, (-1, n_features))\n            style_gram = np.matmul(features.T, features) / (n_samples *\n                                                            n_frames)\n            style_features.append(style_gram)\n    return content_features, style_features\n\n\ndef compute_wavenet_decoder_stylization(n_samples,\n                                        n_frames,\n                                        content_features,\n                                        style_features,\n                                        alpha=1e-4,\n                                        learning_rate=1e-3,\n                                        iterations=100):\n\n    style_layers = [1, 5]\n    num_stages = 10\n    num_layers = 30\n    filter_length = 3\n    width = 512\n    skip_width = 256\n    layers = []\n    with tf.Graph().as_default() as g, g.device('/cpu:0'), tf.Session() as sess:\n        x = tf.placeholder(\n            name=\"x\", shape=(n_frames, n_samples, 1), dtype=tf.float32)\n        layer = x\n        layer = masked.conv1d(\n            layer, num_filters=width, filter_length=filter_length, name='startconv')\n\n        # Set up skip connections.\n        s = masked.conv1d(\n            layer, num_filters=skip_width, filter_length=1, name='skip_start')\n\n        # Residual blocks with skip connections.\n        for i in range(num_layers):\n            dilation = 2**(i % num_stages)\n            d = masked.conv1d(\n                layer,\n                num_filters=2 * width,\n                filter_length=filter_length,\n                dilation=dilation,\n                name='dilatedconv_%d' % (i + 1))\n            assert d.get_shape().as_list()[2] % 2 == 0\n            m = d.get_shape().as_list()[2] // 2\n            d_sigmoid = tf.sigmoid(d[:, :, :m])\n            d_tanh = tf.tanh(d[:, :, m:])\n            d = d_sigmoid * d_tanh\n\n            layer += masked.conv1d(\n                d, num_filters=width, filter_length=1, name='res_%d' % (i + 1))\n            s += masked.conv1d(\n                d,\n                num_filters=skip_width,\n                filter_length=1,\n                name='skip_%d' % (i + 1))\n            layer_i = tf.identity(s, name='layer_{}'.format(num_layers))\n            layers.append(layer_i)\n        saver = tf.train.Saver()\n        saver.restore(sess, './model.ckpt-200000')\n        sess.run(tf.initialize_all_variables())\n        frozen_graph_def = tf.graph_util.convert_variables_to_constants(\n            sess, sess.graph_def, [s.name.replace(':0', '')] +\n            ['layer_{}'.format(i) for i in range(num_layers)])\n\n    with tf.Graph().as_default() as g, g.device('/cpu:0'), tf.Session() as sess:\n        x = tf.Variable(\n            np.random.randn(n_frames, n_samples, 1).astype(np.float32))\n        tf.import_graph_def(frozen_graph_def, input_map={'x:0': x})\n        content_loss = np.float32(0.0)\n        style_loss = np.float32(0.0)\n        for num_layer in style_layers:\n            layer_i = g.get_tensor_by_name(name='import/layer_%d:0' %\n                                           (num_layer))\n            content_loss = content_loss + alpha * 2 * tf.nn.l2_loss(\n                layer_i - content_features[num_layer])\n            n_features = layer_i.shape.as_list()[-1]\n            features = tf.reshape(layer_i, (-1, n_features))\n            gram = tf.matmul(tf.transpose(features), features) / (n_frames *\n                                                                  n_samples)\n            style_loss = style_loss + 2 * tf.nn.l2_loss(gram - style_features[\n                num_layer])\n        loss = content_loss + style_loss\n        # Optimization\n        print('Started optimization.')\n        opt = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)\n        var_list = tf.trainable_variables()\n        print(var_list)\n        sess.run(tf.initialize_all_variables())\n        for i in range(iterations):\n            s, c, _ = sess.run([style_loss, content_loss, opt])\n            print(i, '- Style:', s, 'Content:', c, end='\\r')\n        result = x.eval()\n        result = inv_mu_law_numpy(result[..., 0] / result.max() * 128.0)\n\n    return result\n\n\ndef run(content_fname,\n        style_fname,\n        output_path,\n        model,\n        iterations=100,\n        sr=16000,\n        hop_size=512,\n        frame_size=2048,\n        alpha=1e-3):\n\n    content, fs = librosa.load(content_fname, sr=sr)\n    style, fs = librosa.load(style_fname, sr=sr)\n    n_samples = (min(content.shape[0], style.shape[0]) // 512) * 512\n    content = utils.chop(content[:n_samples], hop_size, frame_size)\n    style = utils.chop(style[:n_samples], hop_size, frame_size)\n\n    if model == 'encoder':\n        content_features, style_features = compute_wavenet_encoder_features(\n            content=content, style=style)\n        result = compute_wavenet_encoder_stylization(\n            n_frames=content_features[0].shape[0],\n            n_samples=frame_size,\n            alpha=alpha,\n            content_features=content_features,\n            style_features=style_features,\n            iterations=iterations)\n    elif model == 'decoder':\n        content_features, style_features = compute_wavenet_decoder_features(\n            content=content, style=style)\n        result = compute_wavenet_decoder_stylization(\n            n_frames=content_features[0].shape[0],\n            n_samples=frame_size,\n            alpha=alpha,\n            content_features=content_features,\n            style_features=style_features,\n            iterations=iterations)\n    else:\n        raise ValueError('Unsupported model type: {}.'.format(model))\n\n    x = utils.unchop(result, hop_size, frame_size)\n    librosa.output.write_wav('prelimiter.wav', x, sr)\n\n    limited = utils.limiter(x)\n    output_fname = '{}/{}+{}.wav'.format(output_path,\n                                         content_fname.split('/')[-1],\n                                         style_fname.split('/')[-1])\n    librosa.output.write_wav(output_fname, limited, sr=sr)\n\n\ndef batch(content_path, style_path, output_path, model):\n    content_files = glob.glob('{}/*.wav'.format(content_path))\n    style_files = glob.glob('{}/*.wav'.format(style_path))\n    for content_fname in content_files:\n        for style_fname in style_files:\n            output_fname = '{}/{}+{}.wav'.format(output_path,\n                                                 content_fname.split('/')[-1],\n                                                 style_fname.split('/')[-1])\n            if os.path.exists(output_fname):\n                continue\n            run(content_fname, style_fname, output_fname, model)\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        '-s', '--style', help='style file(s) location', required=True)\n    parser.add_argument(\n        '-c', '--content', help='content file(s) location', required=True)\n    parser.add_argument('-o', '--output', help='output path', required=True)\n    parser.add_argument(\n        '-m',\n        '--model',\n        help='model type: [encoder], or decoder',\n        default='encoder')\n    parser.add_argument(\n        '-t',\n        '--type',\n        help='mode for training [single] (point to files) or batch (point to path)',\n        default='single')\n\n    args = vars(parser.parse_args())\n    if args['model'] == 'single':\n        run(args['content'], args['style'], args['output'], args['model'])\n    else:\n        batch(args['content'], args['style'], args['output'], args['model'])\n"
  },
  {
    "path": "audio_style_transfer/models/timedomain.py",
    "content": "\"\"\"NIPS2017 \"Time Domain Neural Audio Style Transfer\" code repository\nParag K. Mital\n\"\"\"\nimport tensorflow as tf\nimport librosa\nimport numpy as np\nfrom scipy.signal import hann\nfrom audio_style_transfer import utils\nimport argparse\nimport glob\nimport os\n\n\ndef chop(signal, hop_size=256, frame_size=512):\n    n_hops = len(signal) // hop_size\n    s = []\n    hann_win = hann(frame_size)\n    for hop_i in range(n_hops):\n        frame = signal[(hop_i * hop_size):(hop_i * hop_size + frame_size)]\n        frame = np.pad(frame, (0, frame_size - len(frame)), 'constant')\n        frame *= hann_win\n        s.append(frame)\n    s = np.array(s)\n    return s\n\n\ndef unchop(frames, hop_size=256, frame_size=512):\n    signal = np.zeros((frames.shape[0] * hop_size + frame_size,))\n    for hop_i, frame in enumerate(frames):\n        signal[(hop_i * hop_size):(hop_i * hop_size + frame_size)] += frame\n    return signal\n\n\ndef dft_np(signal, hop_size=256, fft_size=512):\n    s = chop(signal, hop_size, fft_size)\n    N = s.shape[-1]\n    k = np.reshape(\n        np.linspace(0.0, 2 * np.pi / N * (N // 2), N // 2), [1, N // 2])\n    x = np.reshape(np.linspace(0.0, N - 1, N), [N, 1])\n    freqs = np.dot(x, k)\n    real = np.dot(s, np.cos(freqs)) * (2.0 / N)\n    imag = np.dot(s, np.sin(freqs)) * (2.0 / N)\n    return real, imag\n\n\ndef idft_np(re, im, hop_size=256, fft_size=512):\n    N = re.shape[1] * 2\n    k = np.reshape(\n        np.linspace(0.0, 2 * np.pi / N * (N // 2), N // 2), [N // 2, 1])\n    x = np.reshape(np.linspace(0.0, N - 1, N), [1, N])\n    freqs = np.dot(k, x)\n    signal = np.zeros((re.shape[0] * hop_size + fft_size,))\n    recon = np.dot(re, np.cos(freqs)) + np.dot(im, np.sin(freqs))\n    for hop_i, frame in enumerate(recon):\n        signal[(hop_i * hop_size):(hop_i * hop_size + fft_size)] += frame\n    return signal\n\n\ndef unwrap(x):\n    return np.unwrap(x).astype(np.float32)\n\n\ndef instance_norm(x, epsilon=1e-5):\n    \"\"\"Instance Normalization.\n\n    See Ulyanov, D., Vedaldi, A., & Lempitsky, V. (2016).\n    Instance Normalization: The Missing Ingredient for Fast Stylization,\n    Retrieved from http://arxiv.org/abs/1607.08022\n\n    Parameters\n    ----------\n    x : TYPE\n        Description\n    epsilon : float, optional\n        Description\n    \"\"\"\n    with tf.variable_scope('instance_norm'):\n        mean, var = tf.nn.moments(x, [1, 2], keep_dims=True)\n        scale = tf.get_variable(\n            name='scale',\n            shape=[x.get_shape()[-1]],\n            initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02))\n        offset = tf.get_variable(\n            name='offset',\n            shape=[x.get_shape()[-1]],\n            initializer=tf.constant_initializer(0.0))\n        out = scale * tf.div(x - mean, tf.sqrt(var + epsilon)) + offset\n        return out\n\n\ndef compute_inputs(x, freqs, n_fft, n_frames, input_features, norm=False):\n    if norm:\n        norm_fn = instance_norm\n    else:\n        def norm_fn(x):\n            return x\n    freqs_tf = tf.constant(freqs, name=\"freqs\", dtype='float32')\n    inputs = {}\n    with tf.variable_scope('real'):\n        inputs['real'] = norm_fn(tf.reshape(\n            tf.matmul(x, tf.cos(freqs_tf)), [1, 1, n_frames, n_fft // 2]))\n    with tf.variable_scope('imag'):\n        inputs['imag'] = norm_fn(tf.reshape(\n            tf.matmul(x, tf.sin(freqs_tf)), [1, 1, n_frames, n_fft // 2]))\n    with tf.variable_scope('mags'):\n        inputs['mags'] = norm_fn(tf.reshape(\n            tf.sqrt(\n                tf.maximum(1e-15, inputs['real'] * inputs['real'] + inputs[\n                    'imag'] * inputs['imag'])), [1, 1, n_frames, n_fft // 2]))\n    with tf.variable_scope('phase'):\n        inputs['phase'] = norm_fn(tf.atan2(inputs['imag'], inputs['real']))\n    with tf.variable_scope('unwrapped'):\n        inputs['unwrapped'] = tf.py_func(\n            unwrap, [inputs['phase']], tf.float32)\n    with tf.variable_scope('unwrapped_difference'):\n        inputs['unwrapped_difference'] = (tf.slice(\n                inputs['unwrapped'],\n                [0, 0, 0, 1], [-1, -1, -1, n_fft // 2 - 1]) -\n            tf.slice(\n                inputs['unwrapped'],\n                [0, 0, 0, 0], [-1, -1, -1, n_fft // 2 - 1]))\n    if 'unwrapped_difference' in input_features:\n        for k, v in input_features:\n            if k is not 'unwrapped_difference':\n                inputs[k] = tf.slice(\n                        v, [0, 0, 0, 0], [-1, -1, -1, n_fft // 2 - 1])\n    net = tf.concat([inputs[i] for i in input_features], 1)\n    return inputs, net\n\n\ndef compute_features(content,\n                     style,\n                     input_features,\n                     norm=False,\n                     stride=1,\n                     n_layers=1,\n                     n_filters=4096,\n                     n_fft=1024,\n                     k_h=1,\n                     k_w=11):\n    n_frames = content.shape[0]\n    n_samples = content.shape[1]\n    content_tf = np.ascontiguousarray(content)\n    style_tf = np.ascontiguousarray(style)\n    g = tf.Graph()\n    kernels = []\n    content_features = []\n    style_features = []\n    config_proto = tf.ConfigProto()\n    config_proto.gpu_options.allow_growth = True\n    with g.as_default(), g.device('/cpu:0'), tf.Session(config=config_proto) as sess:\n        x = tf.placeholder('float32', [n_frames, n_samples], name=\"x\")\n        p = np.reshape(\n            np.linspace(0.0, n_samples - 1, n_samples), [n_samples, 1])\n        k = np.reshape(\n            np.linspace(0.0, 2 * np.pi / n_fft * (n_fft // 2), n_fft // 2),\n            [1, n_fft // 2])\n        freqs = np.dot(p, k)\n        inputs, net = compute_inputs(x, freqs, n_fft, n_frames, input_features, norm)\n        sess.run(tf.initialize_all_variables())\n        content_feature = net.eval(feed_dict={x: content_tf})\n        content_features.append(content_feature)\n        style_feature = inputs['mags'].eval(feed_dict={x: style_tf})\n        features = np.reshape(style_feature, (-1, n_fft // 2))\n        style_gram = np.matmul(features.T, features) / (n_frames)\n        style_features.append(style_gram)\n        for layer_i in range(n_layers):\n            if layer_i == 0:\n                std = np.sqrt(2) * np.sqrt(2.0 / (\n                    (n_fft / 2 + n_filters) * k_w))\n                kernel = np.random.randn(k_h, k_w, n_fft // 2, n_filters) * std\n            else:\n                std = np.sqrt(2) * np.sqrt(2.0 / (\n                    (n_filters + n_filters) * k_w))\n                kernel = np.random.randn(1, k_w, n_filters, n_filters) * std\n            kernels.append(kernel)\n            kernel_tf = tf.constant(\n                kernel, name=\"kernel{}\".format(layer_i), dtype='float32')\n            conv = tf.nn.conv2d(\n                net,\n                kernel_tf,\n                strides=[1, stride, stride, 1],\n                padding=\"VALID\",\n                name=\"conv{}\".format(layer_i))\n            net = tf.nn.relu(conv)\n            content_feature = net.eval(feed_dict={x: content_tf})\n            content_features.append(content_feature)\n            style_feature = net.eval(feed_dict={x: style_tf})\n            features = np.reshape(style_feature, (-1, n_filters))\n            style_gram = np.matmul(features.T, features) / (n_frames)\n            style_features.append(style_gram)\n    return content_features, style_features, kernels, freqs\n\n\ndef compute_stylization(kernels,\n                        n_samples,\n                        n_frames,\n                        content_features,\n                        style_gram,\n                        freqs,\n                        input_features,\n                        norm=False,\n                        stride=1,\n                        n_layers=1,\n                        n_fft=1024,\n                        alpha=1e-4,\n                        learning_rate=1e-3,\n                        iterations=100,\n                        optimizer='bfgs'):\n    result = None\n    with tf.Graph().as_default():\n        x = tf.Variable(\n            np.random.randn(n_frames, n_samples).astype(np.float32) * 1e-3,\n            name=\"x\")\n        inputs, net = compute_inputs(x, freqs, n_fft, n_frames, input_features, norm)\n        content_loss = alpha * 2 * tf.nn.l2_loss(net - content_features[0])\n        feats = tf.reshape(inputs['mags'], (-1, n_fft // 2))\n        gram = tf.matmul(tf.transpose(feats), feats) / (n_frames)\n        style_loss = 2 * tf.nn.l2_loss(gram - style_gram[0])\n        for layer_i in range(n_layers):\n            kernel_tf = tf.constant(\n                kernels[layer_i],\n                name=\"kernel{}\".format(layer_i),\n                dtype='float32')\n            conv = tf.nn.conv2d(\n                net,\n                kernel_tf,\n                strides=[1, stride, stride, 1],\n                padding=\"VALID\",\n                name=\"conv{}\".format(layer_i))\n            net = tf.nn.relu(conv)\n            content_loss = content_loss + \\\n                alpha * 2 * tf.nn.l2_loss(net - content_features[layer_i + 1])\n            _, height, width, number = map(lambda i: i.value, net.get_shape())\n            feats = tf.reshape(net, (-1, number))\n            gram = tf.matmul(tf.transpose(feats), feats) / (n_frames)\n            style_loss = style_loss + 2 * tf.nn.l2_loss(gram - style_gram[\n                layer_i + 1])\n        loss = content_loss + style_loss\n        if optimizer == 'bfgs':\n            opt = tf.contrib.opt.ScipyOptimizerInterface(\n                loss, method='L-BFGS-B', options={'maxiter': iterations})\n            # Optimization\n            with tf.Session() as sess:\n                sess.run(tf.initialize_all_variables())\n                print('Started optimization.')\n                opt.minimize(sess)\n                result = x.eval()\n        else:\n            opt = tf.train.AdamOptimizer(\n                learning_rate=learning_rate).minimize(loss)\n            # Optimization\n            with tf.Session() as sess:\n                sess.run(tf.initialize_all_variables())\n                print('Started optimization.')\n                for i in range(iterations):\n                    s, c, l, _ = sess.run([style_loss, content_loss, loss, opt])\n                    print('Style:', s, 'Content:', c, end='\\r')\n                result = x.eval()\n    return result\n\n\ndef run(content_fname,\n        style_fname,\n        output_fname,\n        norm=False,\n        input_features=['real', 'imag', 'mags'],\n        n_fft=4096,\n        n_layers=1,\n        n_filters=4096,\n        hop_length=256,\n        alpha=0.05,\n        k_w=15,\n        k_h=3,\n        optimizer='bfgs',\n        stride=1,\n        iterations=300,\n        sr=22050):\n\n    frame_size = n_fft // 2\n\n    audio, fs = librosa.load(content_fname, sr=sr)\n    content = chop(audio, hop_size=hop_length, frame_size=frame_size)\n    audio, fs = librosa.load(style_fname, sr=sr)\n    style = chop(audio, hop_size=hop_length, frame_size=frame_size)\n\n    n_frames = min(content.shape[0], style.shape[0])\n    n_samples = min(content.shape[1], style.shape[1])\n    content = content[:n_frames, :n_samples]\n    style = style[:n_frames, :n_samples]\n\n    content_features, style_gram, kernels, freqs = compute_features(\n        content=content,\n        style=style,\n        input_features=input_features,\n        norm=norm,\n        stride=stride,\n        n_fft=n_fft,\n        n_layers=n_layers,\n        n_filters=n_filters,\n        k_w=k_w,\n        k_h=k_h)\n\n    result = compute_stylization(\n        kernels=kernels,\n        freqs=freqs,\n        input_features=input_features,\n        norm=norm,\n        n_samples=n_samples,\n        n_frames=n_frames,\n        n_fft=n_fft,\n        content_features=content_features,\n        style_gram=style_gram,\n        stride=stride,\n        n_layers=n_layers,\n        alpha=alpha,\n        optimizer=optimizer,\n        iterations=iterations)\n\n    s = unchop(result, hop_size=hop_length, frame_size=frame_size)\n    librosa.output.write_wav(output_fname, s, sr=sr)\n    s = utils.limiter(s)\n    librosa.output.write_wav(output_fname + '.limiter.wav', s, sr=sr)\n\n\ndef batch(content_path, style_path, output_path, model):\n    content_files = glob.glob('{}/*.wav'.format(content_path))\n    style_files = glob.glob('{}/*.wav'.format(style_path))\n    for content_fname in content_files:\n        for style_fname in style_files:\n            output_fname = '{}/{}+{}.wav'.format(output_path,\n                                                 content_fname.split('/')[-1],\n                                                 style_fname.split('/')[-1])\n            if os.path.exists(output_fname):\n                continue\n            run(content_fname, style_fname, output_fname, model)\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-s', '--style', help='style file', required=True)\n    parser.add_argument('-c', '--content', help='content file', required=True)\n    parser.add_argument('-o', '--output', help='output file', required=True)\n    parser.add_argument(\n        '-m',\n        '--mode',\n        help='mode for training [single] or batch',\n        default='single')\n\n    args = vars(parser.parse_args())\n    if args['mode'] == 'single':\n        run(args['content'], args['style'], args['output'])\n    else:\n        batch(args['content'], args['style'], args['output'])\n"
  },
  {
    "path": "audio_style_transfer/models/uylanov.py",
    "content": "\"\"\"NIPS2017 \"Time Domain Neural Audio Style Transfer\" code repository\nParag K. Mital\n\"\"\"\nimport tensorflow as tf\nimport librosa\nimport numpy as np\nimport argparse\nimport glob\nimport os\nfrom audio_style_transfer import utils\n\n\ndef read_audio_spectum(filename, n_fft=2048, hop_length=512, sr=22050):\n    x, sr = librosa.load(filename, sr=sr)\n    S = librosa.stft(x, n_fft, hop_length)\n    S = np.log1p(np.abs(S)).T\n    return S, sr\n\n\ndef compute_features(content,\n                     style,\n                     stride=1,\n                     n_layers=1,\n                     n_filters=4096,\n                     k_h=1,\n                     k_w=11):\n    n_frames = content.shape[0]\n    n_samples = content.shape[1]\n    content_tf = np.ascontiguousarray(content)\n    style_tf = np.ascontiguousarray(style)\n    g = tf.Graph()\n    kernels = []\n    layers = []\n    content_features = []\n    style_features = []\n    with g.as_default(), g.device('/cpu:0'), tf.Session():\n        x = tf.placeholder('float32', [None, n_samples], name=\"x\")\n        net = tf.reshape(x, [1, 1, -1, n_samples])\n        for layer_i in range(n_layers):\n            if layer_i == 0:\n                std = np.sqrt(2) * np.sqrt(2.0 / ((n_frames + n_filters) * k_w))\n                kernel = np.random.randn(k_h, k_w, n_samples, n_filters) * std\n            else:\n                std = np.sqrt(2) * np.sqrt(2.0 / (\n                    (n_filters + n_filters) * k_w))\n                kernel = np.random.randn(k_h, k_w, n_filters, n_filters) * std\n            kernels.append(kernel)\n            kernel_tf = tf.constant(\n                kernel, name=\"kernel{}\".format(layer_i), dtype='float32')\n            conv = tf.nn.conv2d(\n                net,\n                kernel_tf,\n                strides=[1, stride, stride, 1],\n                padding=\"VALID\",\n                name=\"conv{}\".format(layer_i))\n            net = tf.nn.relu(conv)\n            layers.append(net)\n            content_feature = net.eval(feed_dict={x: content_tf})\n            content_features.append(content_feature)\n            style_feature = net.eval(feed_dict={x: style_tf})\n            features = np.reshape(style_feature, (-1, n_filters))\n            style_gram = np.matmul(features.T, features) / n_frames\n            style_features.append(style_gram)\n    return content_features, style_features, kernels\n\n\ndef compute_stylization(kernels,\n                        n_samples,\n                        n_frames,\n                        content_features,\n                        style_features,\n                        stride=1,\n                        n_layers=1,\n                        alpha=1e-4,\n                        learning_rate=1e-3,\n                        iterations=100):\n    result = None\n    with tf.Graph().as_default():\n        x = tf.Variable(\n            np.random.randn(1, 1, n_frames, n_samples).astype(np.float32) *\n            1e-3,\n            name=\"x\")\n        net = x\n        content_loss = 0\n        style_loss = 0\n        for layer_i in range(n_layers):\n            kernel_tf = tf.constant(\n                kernels[layer_i],\n                name=\"kernel{}\".format(layer_i),\n                dtype='float32')\n            conv = tf.nn.conv2d(\n                net,\n                kernel_tf,\n                strides=[1, stride, stride, 1],\n                padding=\"VALID\",\n                name=\"conv{}\".format(layer_i))\n            net = tf.nn.relu(conv)\n            content_loss = content_loss + \\\n                alpha * 2 * tf.nn.l2_loss(net - content_features[layer_i])\n            _, height, width, number = map(lambda i: i.value, net.get_shape())\n            feats = tf.reshape(net, (-1, number))\n            gram = tf.matmul(tf.transpose(feats), feats) / n_frames\n            style_loss = style_loss + 2 * tf.nn.l2_loss(gram - style_features[\n                layer_i])\n        loss = content_loss + style_loss\n        opt = tf.contrib.opt.ScipyOptimizerInterface(\n            loss, method='L-BFGS-B', options={'maxiter': iterations})\n        # Optimization\n        with tf.Session() as sess:\n            sess.run(tf.initialize_all_variables())\n            print('Started optimization.')\n            opt.minimize(sess)\n            print('Final loss:', loss.eval())\n            result = x.eval()\n    return result\n\n\ndef run(content_fname,\n        style_fname,\n        output_fname,\n        n_fft=2048,\n        hop_length=256,\n        alpha=0.02,\n        n_layers=1,\n        n_filters=8192,\n        k_w=15,\n        stride=1,\n        iterations=300,\n        phase_iterations=500,\n        sr=22050,\n        signal_length=1,  # second\n        block_length=1024):\n\n    content, sr = read_audio_spectum(\n        content_fname, n_fft=n_fft, hop_length=hop_length, sr=sr)\n    style, sr = read_audio_spectum(\n        style_fname, n_fft=n_fft, hop_length=hop_length, sr=sr)\n\n    n_frames = min(content.shape[0], style.shape[0])\n    n_samples = content.shape[1]\n    content = content[:n_frames, :]\n    style = style[:n_frames, :]\n\n    content_features, style_features, kernels = compute_features(\n        content=content,\n        style=style,\n        stride=stride,\n        n_layers=n_layers,\n        n_filters=n_filters,\n        k_w=k_w)\n\n    result = compute_stylization(\n        kernels=kernels,\n        n_samples=n_samples,\n        n_frames=n_frames,\n        content_features=content_features,\n        style_features=style_features,\n        stride=stride,\n        n_layers=n_layers,\n        alpha=alpha,\n        iterations=iterations)\n\n    mags = np.zeros_like(content.T)\n    mags[:, :n_frames] = np.exp(result[0, 0].T) - 1\n\n    p = 2 * np.pi * np.random.random_sample(mags.shape) - np.pi\n    for i in range(phase_iterations):\n        S = mags * np.exp(1j * p)\n        x = librosa.istft(S, hop_length)\n        p = np.angle(librosa.stft(x, n_fft, hop_length))\n\n    librosa.output.write_wav('prelimiter.wav', x, sr)\n    limited = utils.limiter(x)\n    librosa.output.write_wav(output_fname, limited, sr)\n\n\ndef batch(content_path, style_path, output_path):\n    content_files = glob.glob('{}/*.wav'.format(content_path))\n    style_files = glob.glob('{}/*.wav'.format(style_path))\n    for content_filename in content_files:\n        for style_filename in style_files:\n            output_filename = '{}/{}+{}.wav'.format(\n                output_path,\n                content_filename.split('/')[-1], style_filename.split('/')[-1])\n            if os.path.exists(output_filename):\n                continue\n            run(content_filename, style_filename, output_filename)\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-s', '--style', help='style file', required=True)\n    parser.add_argument('-c', '--content', help='content file', required=True)\n    parser.add_argument('-o', '--output', help='output file', required=True)\n    parser.add_argument(\n        '-m',\n        '--mode',\n        help='mode for training [single] or batch',\n        default='single')\n\n    args = vars(parser.parse_args())\n    if args['mode'] == 'single':\n        run(args['content'], args['style'], args['output'])\n    else:\n        batch(args['content'], args['style'], args['output'])\n"
  },
  {
    "path": "audio_style_transfer/utils.py",
    "content": "\"\"\"NIPS2017 \"Time Domain Neural Audio Style Transfer\" code repository\nParag K. Mital\n\"\"\"\nimport glob\nimport numpy as np\nfrom scipy.signal import hann\nimport librosa\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport os\n\n\ndef limiter(signal,\n            delay=40,\n            threshold=0.9,\n            release_coeff=0.9995,\n            attack_coeff=0.9):\n\n    delay_index = 0\n    envelope = 0\n    gain = 1\n    delay = delay\n    delay_line = np.zeros(delay)\n    release_coeff = release_coeff\n    attack_coeff = attack_coeff\n    threshold = threshold\n\n    for idx, sample in enumerate(signal):\n        delay_line[delay_index] = sample\n        delay_index = (delay_index + 1) % delay\n\n        # calculate an envelope of the signal\n        envelope = max(np.abs(sample), envelope * release_coeff)\n\n        if envelope > threshold:\n            target_gain = threshold / envelope\n        else:\n            target_gain = 1.0\n\n        # have gain go towards a desired limiter gain\n        gain = (gain * attack_coeff + target_gain * (1 - attack_coeff))\n\n        # limit the delayed signal\n        signal[idx] = delay_line[delay_index] * gain\n    return signal\n\n\ndef chop(signal, hop_size=256, frame_size=512):\n    n_hops = len(signal) // hop_size\n    frames = []\n    hann_win = hann(frame_size)\n    for hop_i in range(n_hops):\n        frame = signal[(hop_i * hop_size):(hop_i * hop_size + frame_size)]\n        frame = np.pad(frame, (0, frame_size - len(frame)), 'constant')\n        frame *= hann_win\n        frames.append(frame)\n    frames = np.array(frames)\n    return frames\n\n\ndef unchop(frames, hop_size=256, frame_size=512):\n    signal = np.zeros((frames.shape[0] * hop_size + frame_size,))\n    for hop_i, frame in enumerate(frames):\n        signal[(hop_i * hop_size):(hop_i * hop_size + frame_size)] += frame\n    return signal\n\n\ndef matrix_dft(V):\n    N = len(V)\n    w = np.exp(-2j * np.pi / N)\n    col = np.vander([w], N, True)\n    W = np.vander(col.flatten(), N, True) / np.sqrt(N)\n    return np.dot(W, V)\n\n\ndef dft_np(signal, hop_size=256, fft_size=512):\n    s = chop(signal, hop_size, fft_size)\n    N = s.shape[-1]\n    k = np.reshape(\n        np.linspace(0.0, 2 * np.pi / N * (N // 2), N // 2), [1, N // 2])\n    x = np.reshape(np.linspace(0.0, N - 1, N), [N, 1])\n    freqs = np.dot(x, k)\n    real = np.dot(s, np.cos(freqs)) * (2.0 / N)\n    imag = np.dot(s, np.sin(freqs)) * (2.0 / N)\n    return real, imag\n\n\ndef idft_np(re, im, hop_size=256, fft_size=512):\n    N = re.shape[1] * 2\n    k = np.reshape(\n        np.linspace(0.0, 2 * np.pi / N * (N // 2), N // 2), [N // 2, 1])\n    x = np.reshape(np.linspace(0.0, N - 1, N), [1, N])\n    freqs = np.dot(k, x)\n    signal = np.zeros((re.shape[0] * hop_size + fft_size,))\n    recon = np.dot(re, np.cos(freqs)) + np.dot(im, np.sin(freqs))\n    for hop_i, frame in enumerate(recon):\n        signal[(hop_i * hop_size):(hop_i * hop_size + fft_size)] += frame\n    return signal\n\n\ndef rainbowgram(path,\n                ax,\n                peak=70.0,\n                use_cqt=False,\n                n_fft=1024,\n                hop_length=256,\n                sr=22050,\n                over_sample=4,\n                res_factor=0.8,\n                octaves=5,\n                notes_per_octave=10):\n    audio = librosa.load(path, sr=sr)[0]\n    if use_cqt:\n        C = librosa.cqt(audio,\n                        sr=sr,\n                        hop_length=hop_length,\n                        bins_per_octave=int(notes_per_octave * over_sample),\n                        n_bins=int(octaves * notes_per_octave * over_sample),\n                        filter_scale=res_factor,\n                        fmin=librosa.note_to_hz('C2'))\n    else:\n        C = librosa.stft(\n            audio,\n            n_fft=n_fft,\n            win_length=n_fft,\n            hop_length=hop_length,\n            center=True)\n    mag, phase = librosa.core.magphase(C)\n    phase_angle = np.angle(phase)\n    phase_unwrapped = np.unwrap(phase_angle)\n    dphase = phase_unwrapped[:, 1:] - phase_unwrapped[:, :-1]\n    dphase = np.concatenate([phase_unwrapped[:, 0:1], dphase], axis=1) / np.pi\n    mag = (librosa.logamplitude(\n        mag**2, amin=1e-13, top_db=peak, ref_power=np.max) / peak) + 1\n    cdict = {\n        'red': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),\n        'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),\n        'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),\n        'alpha': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0))\n    }\n    my_mask = matplotlib.colors.LinearSegmentedColormap('MyMask', cdict)\n    plt.register_cmap(cmap=my_mask)\n    ax.matshow(dphase[::-1, :], cmap=plt.cm.rainbow)\n    ax.matshow(mag[::-1, :], cmap=my_mask)\n\n\ndef rainbowgrams(list_of_paths,\n                 saveto=None,\n                 rows=2,\n                 cols=4,\n                 col_labels=[],\n                 row_labels=[],\n                 use_cqt=True,\n                 figsize=(15, 20),\n                 peak=70.0):\n    \"\"\"Build a CQT rowsXcols.\n    \"\"\"\n    N = len(list_of_paths)\n    assert N == rows * cols\n    fig, axes = plt.subplots(\n        rows, cols, sharex=True, sharey=True, figsize=figsize)\n    fig.subplots_adjust(left=0.05, right=0.95, wspace=0.05, hspace=0.1)\n    #       fig = plt.figure(figsize=(18, N * 1.25))\n    for i, path in enumerate(list_of_paths):\n        row = int(i / cols)\n        col = i % cols\n        if rows == 1 and cols == 1:\n            ax = axes\n        elif rows == 1:\n            ax = axes[col]\n        elif cols == 1:\n            ax = axes[row]\n        else:\n            ax = axes[row, col]\n        rainbowgram(path, ax, peak, use_cqt)\n        ax.set_axis_bgcolor('white')\n        ax.set_xticks([])\n        ax.set_yticks([])\n        if col == 0 and row_labels:\n            ax.set_ylabel(row_labels[row])\n        if row == rows - 1 and col_labels:\n            ax.set_xlabel(col_labels[col])\n    if saveto is not None:\n        fig.savefig(filename='{}.png'.format(saveto))\n\n\ndef plot_rainbowgrams():\n    for root in ['target', 'corpus', 'results']:\n        files = glob.glob('{}/**/*.wav'.format(root), recursive=True)\n        for f in files:\n            fname = '{}.png'.format(f)\n            if not os.path.exists(fname):\n                rainbowgrams(\n                    [f],\n                    saveto=fname,\n                    figsize=(20, 5),\n                    rows=1,\n                    cols=1)\n                plt.close('all')\n"
  },
  {
    "path": "environment.yml",
    "content": "name: tdnast\nchannels:\n  - defaults\ndependencies:\n  - _libgcc_mutex=0.1=main\n  - _openmp_mutex=4.5=1_gnu\n  - _tflow_select=2.1.0=gpu\n  - absl-py=0.15.0=pyhd3eb1b0_0\n  - astor=0.8.1=py37h06a4308_0\n  - blas=1.0=mkl\n  - brotli=1.0.9=he6710b0_2\n  - c-ares=1.18.1=h7f8727e_0\n  - ca-certificates=2022.3.29=h06a4308_0\n  - cached-property=1.5.2=py_0\n  - certifi=2021.10.8=py37h06a4308_2\n  - cudatoolkit=10.0.130=0\n  - cudnn=7.6.5=cuda10.0_0\n  - cupti=10.0.130=0\n  - cycler=0.11.0=pyhd3eb1b0_0\n  - dbus=1.13.18=hb2f20db_0\n  - expat=2.4.4=h295c915_0\n  - fontconfig=2.13.1=h6c09931_0\n  - fonttools=4.25.0=pyhd3eb1b0_0\n  - freetype=2.11.0=h70c0345_0\n  - gast=0.2.2=py37_0\n  - giflib=5.2.1=h7b6447c_0\n  - glib=2.69.1=h4ff587b_1\n  - google-pasta=0.2.0=pyhd3eb1b0_0\n  - grpcio=1.42.0=py37hce63b2e_0\n  - gst-plugins-base=1.14.0=h8213a91_2\n  - gstreamer=1.14.0=h28cd5cc_2\n  - h5py=3.6.0=py37ha0f2276_0\n  - hdf5=1.10.6=hb1b8bf9_0\n  - icu=58.2=he6710b0_3\n  - importlib-metadata=4.11.3=py37h06a4308_0\n  - intel-openmp=2021.4.0=h06a4308_3561\n  - jpeg=9d=h7f8727e_0\n  - keras-applications=1.0.8=py_1\n  - keras-preprocessing=1.1.2=pyhd3eb1b0_0\n  - kiwisolver=1.3.2=py37h295c915_0\n  - lcms2=2.12=h3be6417_0\n  - ld_impl_linux-64=2.35.1=h7274673_9\n  - libffi=3.3=he6710b0_2\n  - libgcc-ng=9.3.0=h5101ec6_17\n  - libgfortran-ng=7.5.0=ha8ba4b0_17\n  - libgfortran4=7.5.0=ha8ba4b0_17\n  - libgomp=9.3.0=h5101ec6_17\n  - libpng=1.6.37=hbc83047_0\n  - libprotobuf=3.19.1=h4ff587b_0\n  - libstdcxx-ng=9.3.0=hd4cf53a_17\n  - libtiff=4.2.0=h85742a9_0\n  - libuuid=1.0.3=h7f8727e_2\n  - libwebp=1.2.2=h55f646e_0\n  - libwebp-base=1.2.2=h7f8727e_0\n  - libxcb=1.14=h7b6447c_0\n  - libxml2=2.9.12=h03d6c58_0\n  - lz4-c=1.9.3=h295c915_1\n  - markdown=3.3.4=py37h06a4308_0\n  - matplotlib=3.5.1=py37h06a4308_1\n  - matplotlib-base=3.5.1=py37ha18d171_1\n  - mkl=2021.4.0=h06a4308_640\n  - mkl-service=2.4.0=py37h7f8727e_0\n  - mkl_fft=1.3.1=py37hd3c417c_0\n  - mkl_random=1.2.2=py37h51133e4_0\n  - munkres=1.1.4=py_0\n  - ncurses=6.3=h7f8727e_2\n  - numpy=1.21.2=py37h20f2e39_0\n  - numpy-base=1.21.2=py37h79a1101_0\n  - openssl=1.1.1n=h7f8727e_0\n  - opt_einsum=3.3.0=pyhd3eb1b0_1\n  - packaging=21.3=pyhd3eb1b0_0\n  - pcre=8.45=h295c915_0\n  - pillow=9.0.1=py37h22f2fdc_0\n  - pip=21.2.2=py37h06a4308_0\n  - protobuf=3.19.1=py37h295c915_0\n  - pyparsing=3.0.4=pyhd3eb1b0_0\n  - pyqt=5.9.2=py37h05f1152_2\n  - python=3.7.13=h12debd9_0\n  - python-dateutil=2.8.2=pyhd3eb1b0_0\n  - qt=5.9.7=h5867ecd_1\n  - readline=8.1.2=h7f8727e_1\n  - scipy=1.7.3=py37hc147768_0\n  - setuptools=58.0.4=py37h06a4308_0\n  - sip=4.19.8=py37hf484d3e_0\n  - six=1.16.0=pyhd3eb1b0_1\n  - sqlite=3.38.2=hc218d9a_0\n  - tensorboard=1.15.0=pyhb230dea_0\n  - tensorflow=1.15.0=gpu_py37h0f0df58_0\n  - tensorflow-base=1.15.0=gpu_py37h9dcbed7_0\n  - tensorflow-estimator=1.15.1=pyh2649769_0\n  - tensorflow-gpu=1.15.0=h0d30ee6_0\n  - termcolor=1.1.0=py37h06a4308_1\n  - tk=8.6.11=h1ccaba5_0\n  - tornado=6.1=py37h27cfd23_0\n  - typing_extensions=4.1.1=pyh06a4308_0\n  - webencodings=0.5.1=py37_1\n  - werkzeug=0.16.1=py_0\n  - wheel=0.37.1=pyhd3eb1b0_0\n  - wrapt=1.13.3=py37h7f8727e_2\n  - xz=5.2.5=h7b6447c_0\n  - zipp=3.7.0=pyhd3eb1b0_0\n  - zlib=1.2.11=h7f8727e_4\n  - zstd=1.4.9=haebb681_0\n  - pip:\n    - audioread==2.1.9\n    - cffi==1.15.0\n    - decorator==5.1.1\n    - joblib==1.1.0\n    - librosa==0.7.2\n    - llvmlite==0.31.0\n    - numba==0.48.0\n    - pycparser==2.21\n    - resampy==0.2.2\n    - scikit-learn==1.0.2\n    - soundfile==0.10.3.post1\n    - threadpoolctl==3.1.0\nprefix: /home/pkmital/anaconda3/envs/tdnast\n"
  },
  {
    "path": "nips_2017.sty",
    "content": "% partial rewrite of the LaTeX2e package for submissions to the\n% Conference on Neural Information Processing Systems (NIPS):\n%\n% - uses more LaTeX conventions\n% - line numbers at submission time replaced with aligned numbers from\n%   lineno package\n% - \\nipsfinalcopy replaced with [final] package option\n% - automatically loads times package for authors\n% - loads natbib automatically; this can be suppressed with the\n%   [nonatbib] package option\n% - adds foot line to first page identifying the conference\n%\n% Roman Garnett (garnett@wustl.edu) and the many authors of\n% nips15submit_e.sty, including MK and drstrip@sandia\n%\n% last revision: March 2017\n\n\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{nips_2017}[2017/03/20 NIPS 2017 submission/camera-ready style file]\n\n% declare final option, which creates camera-ready copy\n\\newif\\if@nipsfinal\\@nipsfinalfalse\n\\DeclareOption{final}{\n  \\@nipsfinaltrue\n}\n\n% declare nonatbib option, which does not load natbib in case of\n% package clash (users can pass options to natbib via\n% \\PassOptionsToPackage)\n\\newif\\if@natbib\\@natbibtrue\n\\DeclareOption{nonatbib}{\n  \\@natbibfalse\n}\n\n\\ProcessOptions\\relax\n\n% fonts\n\\renewcommand{\\rmdefault}{ptm}\n\\renewcommand{\\sfdefault}{phv}\n\n% change this every year for notice string at bottom\n\\newcommand{\\@nipsordinal}{31st}\n\\newcommand{\\@nipsyear}{2017}\n\\newcommand{\\@nipslocation}{Long Beach, CA, USA}\n\n% handle tweaks for camera-ready copy vs. submission copy\n\\if@nipsfinal\n  \\newcommand{\\@noticestring}{%\n    \\@nipsordinal\\/ Conference on Neural Information Processing Systems\n    (NIPS \\@nipsyear), \\@nipslocation.%\n  }\n\\else\n  \\newcommand{\\@noticestring}{%\n    Submitted to \\@nipsordinal\\/ Conference on Neural Information\n    Processing Systems (NIPS \\@nipsyear). Do not distribute.%\n  }\n\n  % line numbers for submission\n  \\RequirePackage{lineno}\n  \\linenumbers\n\n  % fix incompatibilities between lineno and amsmath, if required, by\n  % transparently wrapping linenomath environments around amsmath\n  % environments\n  \\AtBeginDocument{%\n    \\@ifpackageloaded{amsmath}{%\n      \\newcommand*\\patchAmsMathEnvironmentForLineno[1]{%\n        \\expandafter\\let\\csname old#1\\expandafter\\endcsname\\csname #1\\endcsname\n        \\expandafter\\let\\csname oldend#1\\expandafter\\endcsname\\csname end#1\\endcsname\n        \\renewenvironment{#1}%\n          {\\linenomath\\csname old#1\\endcsname}%\n          {\\csname oldend#1\\endcsname\\endlinenomath}%\n      }%\n      \\newcommand*\\patchBothAmsMathEnvironmentsForLineno[1]{%\n        \\patchAmsMathEnvironmentForLineno{#1}%\n        \\patchAmsMathEnvironmentForLineno{#1*}%\n      }%\n      \\patchBothAmsMathEnvironmentsForLineno{equation}%\n      \\patchBothAmsMathEnvironmentsForLineno{align}%\n      \\patchBothAmsMathEnvironmentsForLineno{flalign}%\n      \\patchBothAmsMathEnvironmentsForLineno{alignat}%\n      \\patchBothAmsMathEnvironmentsForLineno{gather}%\n      \\patchBothAmsMathEnvironmentsForLineno{multline}%\n    }{}\n  }\n\\fi\n\n% load natbib unless told otherwise\n\\if@natbib\n  \\RequirePackage{natbib}\n\\fi\n\n% set page geometry\n\\usepackage[verbose=true,letterpaper]{geometry}\n\\AtBeginDocument{\n  \\newgeometry{\n    textheight=9in,\n    textwidth=5.5in,\n    top=1in,\n    headheight=12pt,\n    headsep=25pt,\n    footskip=30pt\n  }\n  \\@ifpackageloaded{fullpage}\n    {\\PackageWarning{nips_2016}{fullpage package not allowed! Overwriting formatting.}}\n    {}\n}\n\n\\widowpenalty=10000\n\\clubpenalty=10000\n\\flushbottom\n\\sloppy\n\n% font sizes with reduced leading\n\\renewcommand{\\normalsize}{%\n  \\@setfontsize\\normalsize\\@xpt\\@xipt\n  \\abovedisplayskip      7\\p@ \\@plus 2\\p@ \\@minus 5\\p@\n  \\abovedisplayshortskip \\z@ \\@plus 3\\p@\n  \\belowdisplayskip      \\abovedisplayskip\n  \\belowdisplayshortskip 4\\p@ \\@plus 3\\p@ \\@minus 3\\p@\n}\n\\normalsize\n\\renewcommand{\\small}{%\n  \\@setfontsize\\small\\@ixpt\\@xpt\n  \\abovedisplayskip      6\\p@ \\@plus 1.5\\p@ \\@minus 4\\p@\n  \\abovedisplayshortskip \\z@  \\@plus 2\\p@\n  \\belowdisplayskip      \\abovedisplayskip\n  \\belowdisplayshortskip 3\\p@ \\@plus 2\\p@   \\@minus 2\\p@\n}\n\\renewcommand{\\footnotesize}{\\@setfontsize\\footnotesize\\@ixpt\\@xpt}\n\\renewcommand{\\scriptsize}{\\@setfontsize\\scriptsize\\@viipt\\@viiipt}\n\\renewcommand{\\tiny}{\\@setfontsize\\tiny\\@vipt\\@viipt}\n\\renewcommand{\\large}{\\@setfontsize\\large\\@xiipt{14}}\n\\renewcommand{\\Large}{\\@setfontsize\\Large\\@xivpt{16}}\n\\renewcommand{\\LARGE}{\\@setfontsize\\LARGE\\@xviipt{20}}\n\\renewcommand{\\huge}{\\@setfontsize\\huge\\@xxpt{23}}\n\\renewcommand{\\Huge}{\\@setfontsize\\Huge\\@xxvpt{28}}\n\n% sections with less space\n\\providecommand{\\section}{}\n\\renewcommand{\\section}{%\n  \\@startsection{section}{1}{\\z@}%\n                {-2.0ex \\@plus -0.5ex \\@minus -0.2ex}%\n                { 1.5ex \\@plus  0.3ex \\@minus  0.2ex}%\n                {\\large\\bf\\raggedright}%\n}\n\\providecommand{\\subsection}{}\n\\renewcommand{\\subsection}{%\n  \\@startsection{subsection}{2}{\\z@}%\n                {-1.8ex \\@plus -0.5ex \\@minus -0.2ex}%\n                { 0.8ex \\@plus  0.2ex}%\n                {\\normalsize\\bf\\raggedright}%\n}\n\\providecommand{\\subsubsection}{}\n\\renewcommand{\\subsubsection}{%\n  \\@startsection{subsubsection}{3}{\\z@}%\n                {-1.5ex \\@plus -0.5ex \\@minus -0.2ex}%\n                { 0.5ex \\@plus  0.2ex}%\n                {\\normalsize\\bf\\raggedright}%\n}\n\\providecommand{\\paragraph}{}\n\\renewcommand{\\paragraph}{%\n  \\@startsection{paragraph}{4}{\\z@}%\n                {1.5ex \\@plus 0.5ex \\@minus 0.2ex}%\n                {-1em}%\n                {\\normalsize\\bf}%\n}\n\\providecommand{\\subparagraph}{}\n\\renewcommand{\\subparagraph}{%\n  \\@startsection{subparagraph}{5}{\\z@}%\n                {1.5ex \\@plus 0.5ex \\@minus 0.2ex}%\n                {-1em}%\n                {\\normalsize\\bf}%\n}\n\\providecommand{\\subsubsubsection}{}\n\\renewcommand{\\subsubsubsection}{%\n  \\vskip5pt{\\noindent\\normalsize\\rm\\raggedright}%\n}\n\n% float placement\n\\renewcommand{\\topfraction      }{0.85}\n\\renewcommand{\\bottomfraction   }{0.4}\n\\renewcommand{\\textfraction     }{0.1}\n\\renewcommand{\\floatpagefraction}{0.7}\n\n\\newlength{\\@nipsabovecaptionskip}\\setlength{\\@nipsabovecaptionskip}{7\\p@}\n\\newlength{\\@nipsbelowcaptionskip}\\setlength{\\@nipsbelowcaptionskip}{\\z@}\n\n\\setlength{\\abovecaptionskip}{\\@nipsabovecaptionskip}\n\\setlength{\\belowcaptionskip}{\\@nipsbelowcaptionskip}\n\n% swap above/belowcaptionskip lengths for tables\n\\renewenvironment{table}\n  {\\setlength{\\abovecaptionskip}{\\@nipsbelowcaptionskip}%\n   \\setlength{\\belowcaptionskip}{\\@nipsabovecaptionskip}%\n   \\@float{table}}\n  {\\end@float}\n\n% footnote formatting\n\\setlength{\\footnotesep }{6.65\\p@}\n\\setlength{\\skip\\footins}{9\\p@ \\@plus 4\\p@ \\@minus 2\\p@}\n\\renewcommand{\\footnoterule}{\\kern-3\\p@ \\hrule width 12pc \\kern 2.6\\p@}\n\\setcounter{footnote}{0}\n\n% paragraph formatting\n\\setlength{\\parindent}{\\z@}\n\\setlength{\\parskip  }{5.5\\p@}\n\n% list formatting\n\\setlength{\\topsep       }{4\\p@ \\@plus 1\\p@   \\@minus 2\\p@}\n\\setlength{\\partopsep    }{1\\p@ \\@plus 0.5\\p@ \\@minus 0.5\\p@}\n\\setlength{\\itemsep      }{2\\p@ \\@plus 1\\p@   \\@minus 0.5\\p@}\n\\setlength{\\parsep       }{2\\p@ \\@plus 1\\p@   \\@minus 0.5\\p@}\n\\setlength{\\leftmargin   }{3pc}\n\\setlength{\\leftmargini  }{\\leftmargin}\n\\setlength{\\leftmarginii }{2em}\n\\setlength{\\leftmarginiii}{1.5em}\n\\setlength{\\leftmarginiv }{1.0em}\n\\setlength{\\leftmarginv  }{0.5em}\n\\def\\@listi  {\\leftmargin\\leftmargini}\n\\def\\@listii {\\leftmargin\\leftmarginii\n              \\labelwidth\\leftmarginii\n              \\advance\\labelwidth-\\labelsep\n              \\topsep  2\\p@ \\@plus 1\\p@    \\@minus 0.5\\p@\n              \\parsep  1\\p@ \\@plus 0.5\\p@ \\@minus 0.5\\p@\n              \\itemsep \\parsep}\n\\def\\@listiii{\\leftmargin\\leftmarginiii\n              \\labelwidth\\leftmarginiii\n              \\advance\\labelwidth-\\labelsep\n              \\topsep    1\\p@ \\@plus 0.5\\p@ \\@minus 0.5\\p@\n              \\parsep    \\z@\n              \\partopsep 0.5\\p@ \\@plus 0\\p@ \\@minus 0.5\\p@\n              \\itemsep \\topsep}\n\\def\\@listiv {\\leftmargin\\leftmarginiv\n              \\labelwidth\\leftmarginiv\n              \\advance\\labelwidth-\\labelsep}\n\\def\\@listv  {\\leftmargin\\leftmarginv\n              \\labelwidth\\leftmarginv\n              \\advance\\labelwidth-\\labelsep}\n\\def\\@listvi {\\leftmargin\\leftmarginvi\n              \\labelwidth\\leftmarginvi\n              \\advance\\labelwidth-\\labelsep}\n\n% create title\n\\providecommand{\\maketitle}{}\n\\renewcommand{\\maketitle}{%\n  \\par\n  \\begingroup\n    \\renewcommand{\\thefootnote}{\\fnsymbol{footnote}}\n    % for perfect author name centering\n    \\renewcommand{\\@makefnmark}{\\hbox to \\z@{$^{\\@thefnmark}$\\hss}}\n    % The footnote-mark was overlapping the footnote-text,\n    % added the following to fix this problem               (MK)\n    \\long\\def\\@makefntext##1{%\n      \\parindent 1em\\noindent\n      \\hbox to 1.8em{\\hss $\\m@th ^{\\@thefnmark}$}##1\n    }\n    \\thispagestyle{empty}\n    \\@maketitle\n    \\@thanks\n    \\@notice\n  \\endgroup\n  \\let\\maketitle\\relax\n  \\let\\thanks\\relax\n}\n\n% rules for title box at top of first page\n\\newcommand{\\@toptitlebar}{\n  \\hrule height 4\\p@\n  \\vskip 0.25in\n  \\vskip -\\parskip%\n}\n\\newcommand{\\@bottomtitlebar}{\n  \\vskip 0.29in\n  \\vskip -\\parskip\n  \\hrule height 1\\p@\n  \\vskip 0.09in%\n}\n\n% create title (includes both anonymized and non-anonymized versions)\n\\providecommand{\\@maketitle}{}\n\\renewcommand{\\@maketitle}{%\n  \\vbox{%\n    \\hsize\\textwidth\n    \\linewidth\\hsize\n    \\vskip 0.1in\n    \\@toptitlebar\n    \\centering\n    {\\LARGE\\bf \\@title\\par}\n    \\@bottomtitlebar\n    \\if@nipsfinal\n      \\def\\And{%\n        \\end{tabular}\\hfil\\linebreak[0]\\hfil%\n        \\begin{tabular}[t]{c}\\bf\\rule{\\z@}{24\\p@}\\ignorespaces%\n      }\n      \\def\\AND{%\n        \\end{tabular}\\hfil\\linebreak[4]\\hfil%\n        \\begin{tabular}[t]{c}\\bf\\rule{\\z@}{24\\p@}\\ignorespaces%\n      }\n      \\begin{tabular}[t]{c}\\bf\\rule{\\z@}{24\\p@}\\@author\\end{tabular}%\n    \\else\n      \\begin{tabular}[t]{c}\\bf\\rule{\\z@}{24\\p@}\n        Anonymous Author(s) \\\\\n        Affiliation \\\\\n        Address \\\\\n        \\texttt{email} \\\\\n      \\end{tabular}%\n    \\fi\n    \\vskip 0.3in \\@minus 0.1in\n  }\n}\n\n% add conference notice to bottom of first page\n\\newcommand{\\ftype@noticebox}{8}\n\\newcommand{\\@notice}{%\n  % give a bit of extra room back to authors on first page\n  \\enlargethispage{2\\baselineskip}%\n  \\@float{noticebox}[b]%\n    \\footnotesize\\@noticestring%\n  \\end@float%\n}\n\n% abstract styling\n\\renewenvironment{abstract}%\n{%\n  \\vskip 0.075in%\n  \\centerline%\n  {\\large\\bf Abstract}%\n  \\vspace{0.5ex}%\n  \\begin{quote}%\n}\n{\n  \\par%\n  \\end{quote}%\n  \\vskip 1ex%\n}\n\n\\endinput\n\n"
  },
  {
    "path": "paper.tex",
    "content": "\\documentclass{article}\n\n% if you need to pass options to natbib, use, e.g.:\n% \\PassOptionsToPackage{numbers, compress}{natbib}\n% before loading nips_2017\n%\n% to avoid loading the natbib package, add option nonatbib:\n% \\usepackage[nonatbib]{nips_2017}\n\n%\\usepackage{nips_2017}\n\n% to compile a camera-ready version, add the [final] option, e.g.:\n\\usepackage[final,nonatbib]{nips_2017}\n\n\\usepackage[utf8]{inputenc} % allow utf-8 input\n\\usepackage[T1]{fontenc}    % use 8-bit T1 fonts\n\\usepackage{hyperref}       % hyperlinks\n\\usepackage{url}            % simple URL typesetting\n\\usepackage{booktabs}       % professional-quality tables\n\\usepackage{amsfonts}       % blackboard math symbols\n\\usepackage{nicefrac}       % compact symbols for 1/2, etc.\n\\usepackage{microtype}      % microtypography\n\\usepackage{graphicx}\n\\usepackage{caption}\n\\usepackage{subcaption}\n\n\\title{Time Domain Neural Audio Style Transfer}\n\n% The \\author macro works with any number of authors. There are two\n% commands used to separate the names and addresses of multiple\n% authors: \\And and \\AND.\n%\n% Using \\And between authors leaves it to LaTeX to determine where to\n% break the lines. Using \\AND forces a line break at that point. So,\n% if LaTeX puts 3 of 4 authors names on the first line, and the last\n% on the second line, try using \\AND instead of \\And before the third\n% author name.\n\n\\author{\n  Parag K. Mital\\\\\n  Kadenze, Inc.\\thanks{http://kadenze.com}\\\\\n  \\texttt{parag@kadenze.com} \\\\\n  %% examples of more authors\n  %% \\And\n  %% Coauthor \\\\\n  %% Affiliation \\\\\n  %% Address \\\\\n  %% \\texttt{email} \\\\\n  %% \\AND\n  %% Coauthor \\\\\n  %% Affiliation \\\\\n  %% Address \\\\\n  %% \\texttt{email} \\\\\n  %% \\And\n  %% Coauthor \\\\\n  %% Affiliation \\\\\n  %% Address \\\\\n  %% \\texttt{email} \\\\\n  %% \\And\n  %% Coauthor \\\\\n  %% Affiliation \\\\\n  %% Address \\\\\n  %% \\texttt{email} \\\\\n}\n\n\\begin{document}\n% \\nipsfinalcopy is no longer used\n\n\\maketitle\n\n\\begin{abstract}\n  A recently published method for audio style transfer has shown how to extend the process of image style transfer to audio.  This method synthesizes audio \"content\" and \"style\" independently using the magnitudes of a short time Fourier transform, shallow convolutional networks with randomly initialized filters, and iterative phase reconstruction with Griffin-Lim.  In this work, we explore whether it is possible to directly optimize a time domain audio signal, removing the process of phase reconstruction and opening up possibilities for real-time applications and higher quality syntheses.  We explore a variety of style transfer processes on neural networks that operate directly on time domain audio signals and demonstrate one such network capable of audio stylization.\n\\end{abstract}\n\n\\section{Introduction}\n\n% Style transfer \\cite{} is a method for optimizing a randomly initialized image to have the appearance of the content and style of two separate images.  It works by finding the raw activations of a so-called \"content\" image and optimizing a noise image to resemble the same activations while for \"style\", it looks at the kernel activations of any given layer and optimizes for these.  The original work by Gatys et al. demonstrated this technique using activations from pre-trained VGG deep convolutional networks, though recent techniques in texture synthesis \\cite{} show that similar results are possible with randomly initialized shallow convolutional networks.\n\nAudio style transfer \\cite{Ulyanov2016} attempts to extend the technique of image style transfer \\cite{Gatys} to the domain of audio, allowing \"content\" and \"style\" to be independently manipulated.  Ulyanov et al. demonstrates the process using the magnitudes of a short time Fourier transform representation of an audio signal as the input to a shallow untrained neural network, following similar work in image style transfer \\cite{Ulyanov2016b}, storing the activations of the content and Gram activations of the style.  A noisy input short time magnitude spectra is then optimized such that its activations through the same network resemble the target content and style magnitude's activations.  The optimized magnitudes are then inverted back to an audio signal using an iterative Griffin-lim phase reconstruction process \\cite{Griffin1984}.\n\nUsing phase reconstruction ultimately means the stylization process is not modeling the audio signal's fine temporal characteristics contained in its phase information.  For instance, if a particular content or style audio source were to contain information about vibrato or the spatial movement or position of the audio source, this would likely be lost in a magnitude-only representation.  Further, by relying on phase reconstruction, some error during the phase reconstruction is likely to happen, and developing real-time applications are also more difficult \\cite{Wyse2017}, though not impossible \\cite{Prusa2017}.  In any case, any networks which discard phase information, such as \\cite{Wyse2017}, which build on Ulyanov's approach, or recent audio networks such as \\cite{Hershey2016} will still require phase reconstruction for stylization/synthesis applications.\n\nRather than approach stylization/synthesis via phase reconstruction, this work attempts to directly optimize a raw audio signal.  Recent work in Neural Audio Synthesis has shown it is possible to take as input a raw audio signal and apply blending of musical notes in a neural embedding space on a trained WaveNet autoencoder \\cite{Engel2017}.  Though their work is capable of synthesizing raw audio from its embedding space, there is no separation of content and style using this approach, and thus they cannot be independently manipulated.  However, to date, it is not clear whether this network's encoder or decoder could be used for audio stylization using the approach of Ulyanov/Gatys.\n\nTo understand better whether it is possible to perform audio stylization in the time domain, we investigate a variety of networks which take a time domain audio signal as input to their network: using the real and imaginary components of a Discrete Fourier Transform (DFT); using the magnitude and unwrapped phase differential components of a DFT; using combinations of real, imaginary, magnitude, and phase components; using the activations of a pre-trained WaveNet decoder \\cite{Oord2016b,Engel2017}; and using the activations of a pre-trained NSynth encoder \\cite{Engel2017}.  We then apply audio stylization similarly to Ulyanov using a variety of parameters and report our results.\n\n% \\section{Related Work}\n\n% There have been a few investigations of audio style transfer employing magnitude representations, such as Ulyanov's original work and a follow-up work employing VGG \\cite{Wyse2017}.  These models discard the phase information in favor of phase reconstruction.  As well, there have been further developments in neural networks capable of large scale audio classification such as \\cite{Hershey2016}, though these are trained on magnitude representations and would also require phase reconstruction as part of a stylization process.  Perhaps most closely aligned is the work of NSynth \\cite{Engel2017}, whose work is capable of taking as input a raw audio signal and allows for applications such as the blending of musical notes in a neural embedding space.  Though their work is capable of synthesizing raw audio from its embedding space, there is no separation of content and style, and thus they cannot be independently manipulated.\n\n% Speech synthesis techniques\n%TacoTron demonstrated a technique using ...\n%In a similar vein, WaveNet, ...\n%NSynth incorporates a WaveNet decoder and includes an additional encoder, allowing one to encode a time domain audio signal using the encoding part of the network with 16 channels at 125x compression, and use these as biases during the WaveNet decoding.  The embedding space is capable of linearly mixing instruments in its embedding space, though has yet to be explored as a network for audio stylization where content and style are indepenently manipulated.\n\n% SampleRNN\n\n% Soundnet\n\n% VGG (Lonce Wyse, https://arxiv.org/pdf/1706.09559.pdf);\n\n% Zdenek Pruska\n\n% Other networks exploring audio include VGGish, built on the AudioSet dataset.  This network, like Ulyanov's original implementation, however does not operate on the raw time domain signal and would require phase reconstruction.  However, it does afford a potentially richer representation than a shallow convolutional network, as its embedding space was trained with the knowledge of many semantic classes of sounds.\n\n% CycleGAN (https://gauthamzz.github.io/2017/09/23/AudioStyleTransfer/)\n\n\n\\section{Experiments}\n\nWe explore a variety of computational graphs which use as their first operation a discrete Fourier transform in order to project an audio signal into its real and imaginary components.  We then explore manipulations on these components, including directly applying convolutional layers, or undergoing an additional transformation of the typical magnitude and phase components, as well as combinations of each these components.  For representing phase, we also explored using the original phase, the phase differential, and the unwrapped phase differentials.  From here, we apply the same techniques for stylization as described in \\cite{Ulyanov2016}, except we no longer have to optimize a noisy magnitude input, and can instead optimize a time domain signal.  We also explore combinations of using content/style layers following the initial projections and after fully connected layers.\n\nWe also explore two pre-trained networks: a pre-trained WaveNet decoder, and the encoder portion of an NSynth network as provided by Magenta \\cite{Engel2017}, and look at the activations of each of these networks at different layers, much like the original image style networks did with VGG.  We also include Ulyanov's original network as a baseline, and report our results as seen through spectrograms and through listening.  Our code is also available online\\footnote{https://github.com/pkmital/neural-audio-style-transfer}\\footnote{Further details are described in the Supplementary Materials}.\n\n\\section{Results}\n\nOnly one network was capable of producing meaningful audio reconstruction through a stylization process where both the style and content appeared to be retained: including the real, imaginary, and magnitude information as concatenated features in height and using a kernel size 3 height convolutional filter.  This process also includes a content layer which includes the concatenated features before any linear layer, and a style layer which is simply the magnitudes, and then uses a content and style layer following each nonlinearity.  This network produces distinctly different stylizations to Ulyanov's original network, despite having similar parameters, often including quicker and busier temporal changes in content and style.  The stylization also tends to produce what seems like higher fidelity syntheses, especially in lower frequencies, despite having the same sample rate.  Lastly, this approach also tends to produce much less noise than Ulyanov's approach, most likely due to errors in the phase reconstruction/lack of phase representation.\n\nEvery other combination of input manipulations we tried tended towards a white noise signal and did not appear to drop in loss.  The only other network that appeared to produce something recognizable, though with considerable noise was using the magnitude and unwrapped phase differential information with a kernel size 2 height convolutional filter.  We could not manage to stylize any meaningful sounding synthesis using the activations in a WaveNet decoder or NSynth encoder.\n\n% VGGish, AudioSet; VGG equivalent for audio, but uses a log-mel spectrogram.\n\n\\section{Discussion and Conclusion}\n\nThis work explores neural audio style transfer of a time domain audio signal.  Of these networks, only two produced any meaningful results: the magnitude and unwrapped phase network, which produced distinctly noisier syntheses, and the real, imaginary, and magnitude network which was capable of resembling both the content and style sources in a similar quality to Ulyanov's original approach, though with interesting differences.  It was especially surprising that we were unable to stylize with NSynth's encoder or decoder, though this is perhaps to due to the limited number of combinations of layers and possible activations we explored, and is worth exploring more in the future.\n\n% Style transfer, like deep dream and its predecessor works in visualizing gradient activations, through exploration have the potential to enable us to understand representations created by neural networks.  Through synthesis, and exploring the representations at each level of a neural network, we can start to gain insights into what sorts of representations if any are created by a network.  However, to date, very few explorations of audio networks for the purpose of dreaming or stylization have been done.\n\n%End to end learning, http://www.mirlab.org/conference_papers/International_Conference/ICASSP\\%202014/papers/p7014-dieleman.pdf - spectrums still do better than raw audio.\n\n\\small\n% Generated by IEEEtran.bst, version: 1.14 (2015/08/26)\n\\begin{thebibliography}{1}\n\\providecommand{\\url}[1]{#1}\n\\csname url@samestyle\\endcsname\n\\providecommand{\\newblock}{\\relax}\n\\providecommand{\\bibinfo}[2]{#2}\n\\providecommand{\\BIBentrySTDinterwordspacing}{\\spaceskip=0pt\\relax}\n\\providecommand{\\BIBentryALTinterwordstretchfactor}{4}\n\\providecommand{\\BIBentryALTinterwordspacing}{\\spaceskip=\\fontdimen2\\font plus\n\\BIBentryALTinterwordstretchfactor\\fontdimen3\\font minus\n  \\fontdimen4\\font\\relax}\n\\providecommand{\\BIBforeignlanguage}[2]{{%\n\\expandafter\\ifx\\csname l@#1\\endcsname\\relax\n\\typeout{** WARNING: IEEEtran.bst: No hyphenation pattern has been}%\n\\typeout{** loaded for the language `#1'. Using the pattern for}%\n\\typeout{** the default language instead.}%\n\\else\n\\language=\\csname l@#1\\endcsname\n\\fi\n#2}}\n\\providecommand{\\BIBdecl}{\\relax}\n\\BIBdecl\n\n\\bibitem{Ulyanov2016}\nD.~Ulyanov and V.~Lebedev, ``{Audio texture synthesis and style transfer},''\n  2016.\n\n\\bibitem{Gatys}\nL.~A. Gatys, A.~S. Ecker, M.~Bethge, and C.~V. Sep, ``{A Neural Algorithm of\n  Artistic Style},'' \\emph{Arxiv}, p. 211839, 2015.\n\n\\bibitem{Ulyanov2016b}\n\\BIBentryALTinterwordspacing\nD.~Ulyanov, V.~Lebedev, A.~Vedaldi, and V.~Lempitsky, ``{Texture Networks:\n  Feed-forward Synthesis of Textures and Stylized Images},'' 2016. [Online].\n  Available: \\url{http://arxiv.org/abs/1603.03417}\n\\BIBentrySTDinterwordspacing\n\n\\bibitem{Griffin1984}\nD.~W. Griffin and J.~S. Lim, ``{Signal Estimation from Modified Short-Time\n  Fourier Transform},'' \\emph{IEEE Transactions on Acoustics, Speech, and\n  Signal Processing}, vol.~32, no.~2, pp. 236--243, 1984.\n\n\\bibitem{Wyse2017}\n\\BIBentryALTinterwordspacing\nL.~Wyse, ``{Audio Spectrogram Representations for Processing with Convolutional\n  Neural Networks},'' in \\emph{Proceedings of the First International Workshop\n  on Deep Learning and Music joint with IJCNN}, vol.~1, no.~1, 2017, pp.\n  37--41. [Online]. Available: \\url{http://arxiv.org/abs/1706.09559}\n\\BIBentrySTDinterwordspacing\n\n\\bibitem{Prusa2017}\nZ.~Prů{\\v{s}}a and P.~Rajmic, ``{Toward High-Quality Real-Time Signal\n  Reconstruction from STFT Magnitude},'' \\emph{IEEE Signal Processing Letters},\n  vol.~24, no.~6, pp. 892--896, 2017.\n\n\\bibitem{Hershey2016}\n\\BIBentryALTinterwordspacing\nS.~Hershey, S.~Chaudhuri, D.~P.~W. Ellis, J.~F. Gemmeke, A.~Jansen, C.~Moore,\n  M.~Plakal, D.~Platt, R.~A. Saurous, B.~Seybold, M.~Slaney, R.~J. Weiss,\n  K.~Wilson, R.~C. Moore, M.~Plakal, D.~Platt, R.~A. Saurous, B.~Seybold,\n  M.~Slaney, R.~J. Weiss, and K.~Wilson, ``{CNN Architectures for Large-Scale\n  Audio Classification},'' \\emph{International Conference on Acoustics, Speech\n  and Signal Processing (ICASSP)}, pp. 4--8, 2016. [Online]. Available:\n  \\url{http://arxiv.org/abs/1609.09430}\n\\BIBentrySTDinterwordspacing\n\n\\bibitem{Engel2017}\n\\BIBentryALTinterwordspacing\nJ.~Engel, C.~Resnick, A.~Roberts, S.~Dieleman, D.~Eck, K.~Simonyan, and\n  M.~Norouzi, ``{Neural Audio Synthesis of Musical Notes with WaveNet\n  Autoencoders},'' in \\emph{Proceedings of the 34th International Conference on\n  Machine Learning}, 2017. [Online]. Available:\n  \\url{http://arxiv.org/abs/1704.01279}\n\\BIBentrySTDinterwordspacing\n\n\\bibitem{Oord2016b}\n\\BIBentryALTinterwordspacing\nA.~van~den Oord, S.~Dieleman, H.~Zen, K.~Simonyan, O.~Vinyals, A.~Graves,\n  N.~Kalchbrenner, A.~Senior, and K.~Kavukcuoglu, ``{WaveNet: A Generative\n  Model for Raw Audio},'' \\emph{arxiv}, pp. 1--15, 2016. [Online]. Available:\n  \\url{http://arxiv.org/abs/1609.03499}\n\\BIBentrySTDinterwordspacing\n\n\\end{thebibliography}\n\n\\begin{figure}\n\\centering\n\\includegraphics[width=1\\linewidth]{synthesis}\n\\caption{Example synthesis optimizing audio directly with both the source content and style audible.}\n\\end{figure}\n\\end{document}\n\n"
  },
  {
    "path": "search.py",
    "content": "\"\"\"NIPS2017 \"Time Domain Neural Audio Style Transfer\" code repository\nParag K. Mital\n\"\"\"\nimport os\nimport glob\nimport numpy as np\nfrom audio_style_transfer.models import timedomain, uylanov\n\n\ndef get_path(model, output_path, content_filename, style_filename):\n    output_dir = os.path.join(output_path, model)\n    if not os.path.exists(output_dir):\n        os.makedirs(output_dir)\n    output_filename = '{}/{}/{}+{}'.format(output_path, model,\n                                           content_filename.split('/')[-1],\n                                           style_filename.split('/')[-1])\n    return output_filename\n\n\ndef params():\n    n_fft = [2048, 4096, 8196]\n    n_layers = [1, 2, 4]\n    n_filters = [128, 2048, 4096]\n    hop_length = [128, 256, 512]\n    alpha = [0.1, 0.01, 0.005]\n    k_w = [4, 8, 12]\n    norm = [True, False]\n    input_features = [['mags'], ['mags', 'phase'], ['real', 'imag'], ['real', 'imag', 'mags']]\n    return locals()\n\n\ndef batch(content_path, style_path, output_path, run_timedomain=True, run_uylanov=False):\n    content_files = glob.glob('{}/*.wav'.format(content_path))\n    style_files = glob.glob('{}/*.wav'.format(style_path))\n    content_filename = np.random.choice(content_files)\n    style_filename = np.random.choice(style_files)\n    alpha = np.random.choice(params()['alpha'])\n    n_fft = np.random.choice(params()['n_fft'])\n    n_layers = np.random.choice(params()['n_layers'])\n    n_filters = np.random.choice(params()['n_filters'])\n    hop_length = np.random.choice(params()['hop_length'])\n    norm = np.random.choice(params()['norm'])\n    k_w = np.random.choice(params()['k_w'])\n\n    # Run the Time Domain Model\n    if run_timedomain:\n        for f in params()['input_features']:\n            fname = get_path('timedomain/input_features={}'.format(\",\".join(f)),\n                             output_path, content_filename, style_filename)\n            output_filename = ('{},n_fft={},n_layers={},n_filters={},norm={},'\n                               'hop_length={},alpha={},k_w={}.wav'.format(\n                                   fname, n_fft, n_layers, n_filters, norm,\n                                   hop_length, alpha, k_w))\n            print(output_filename)\n            if not os.path.exists(output_filename):\n                timedomain.run(content_fname=content_filename,\n                               style_fname=style_filename,\n                               output_fname=output_filename,\n                               n_fft=n_fft,\n                               n_layers=n_layers,\n                               n_filters=n_filters,\n                               hop_length=hop_length,\n                               alpha=alpha,\n                               norm=norm,\n                               k_w=k_w)\n\n    if run_uylanov:\n        # Run Original Uylanov Model\n        fname = get_path('uylanov', output_path, content_filename, style_filename)\n        output_filename = ('{},n_fft={},n_layers={},n_filters={},'\n                           'hop_length={},alpha={},k_w={}.wav'.format(\n                               fname, n_fft, n_layers, n_filters, hop_length, alpha,\n                               k_w))\n        print(output_filename)\n        if not os.path.exists(output_filename):\n            uylanov.run(content_filename,\n                        style_filename,\n                        output_filename,\n                        n_fft=n_fft,\n                        n_layers=n_layers,\n                        n_filters=n_filters,\n                        hop_length=hop_length,\n                        alpha=alpha,\n                        k_w=k_w)\n\n    # These only produce noise so they are commented\n    # # Run NSynth Encoder Model\n    # output_filename = get_path('nsynth-encoder', output_path, content_filename,\n    #                            style_filename)\n    # output_filename = ('{},n_fft={},n_layers={},n_filters={},'\n    #                    'hop_length={},alpha={},k_w={}.wav'.format(\n    #                        fname, n_fft, n_layers, n_filters, hop_length, alpha, k_w))\n    # if not os.path.exists(output_filename):\n    #     nsynth.run(content_filename,\n    #                style_filename,\n    #                output_filename,\n    #                model='encoder',\n    #                n_fft=n_fft,\n    #                n_layers=n_layers,\n    #                n_filters=n_filters,\n    #                hop_length=hop_length,\n    #                alpha=alpha,\n    #                k_w=k_w)\n    # # Run NSynth Decoder Model\n    # output_filename = get_path('wavenet-decoder', output_path, content_filename,\n    #                            style_filename)\n    # output_filename = ('{},n_fft={},n_layers={},n_filters={},'\n    #                    'hop_length={},alpha={},k_w={}.wav'.format(\n    #                        fname, n_fft, n_layers, n_filters, hop_length, alpha, k_w))\n    # if not os.path.exists(output_filename):\n    #     nsynth.run(content_filename,\n    #                style_filename,\n    #                output_filename,\n    #                model='decoder',\n    #                n_fft=n_fft,\n    #                n_layers=n_layers,\n    #                n_filters=n_filters,\n    #                hop_length=hop_length,\n    #                alpha=alpha,\n    #                k_w=k_w)\n\n\nif __name__ == '__main__':\n    content_path = './target'\n    style_path = './corpus'\n    output_path = './results'\n    batch(content_path, style_path, output_path)\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Note: To use the 'upload' functionality of this file, you must:\n#   $ pip install twine\n\nimport io\nimport os\nimport sys\nfrom shutil import rmtree\n\nfrom setuptools import find_packages, setup, Command\n\n# Package meta-data.\nNAME = 'audio_style_transfer'\nDESCRIPTION = 'Exploring Audio Style Transfer'\nURL = 'https://github.com/pkmital/time-domain-neural-audio-style-transfer'\nEMAIL = 'parag@pkmital.com'\nAUTHOR = 'Parag Mital'\n\n# What packages are required for this module to be executed?\nREQUIRED = [\n    # 'tensorflow-gpu<2.0.0', 'librosa<0.8.0',\n    # 'magenta'\n]\n\n# The rest you shouldn't have to touch too much :)\n# ------------------------------------------------\n# Except, perhaps the License and Trove Classifiers!\n# If you do change the License, remember to change the Trove Classifier for that!\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n# Import the README and use it as the long-description.\n# Note: this will only work if 'README.rst' is present in your MANIFEST.in file!\nwith io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:\n    long_description = '\\n' + f.read()\n\n# Load the package's __version__.py module as a dictionary.\nabout = {}\nwith open(os.path.join(here, NAME, '__version__.py')) as f:\n    exec(f.read(), about)\n\n\nclass UploadCommand(Command):\n    \"\"\"Support setup.py upload.\"\"\"\n\n    description = 'Build and publish the package.'\n    user_options = []\n\n    @staticmethod\n    def status(s):\n        \"\"\"Prints things in bold.\"\"\"\n        print('\\033[1m{0}\\033[0m'.format(s))\n\n    def initialize_options(self):\n        pass\n\n    def finalize_options(self):\n        pass\n\n    def run(self):\n        try:\n            self.status('Removing previous builds…')\n            rmtree(os.path.join(here, 'dist'))\n        except OSError:\n            pass\n\n        self.status('Building Source and Wheel (universal) distribution…')\n        os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))\n\n        self.status('Uploading the package to PyPi via Twine…')\n        os.system('twine upload dist/*')\n\n        sys.exit()\n\n\n# Where the magic happens:\nsetup(\n    name=NAME,\n    version=about['__version__'],\n    description=DESCRIPTION,\n    long_description=long_description,\n    author=AUTHOR,\n    author_email=EMAIL,\n    url=URL,\n    packages=find_packages(exclude=('tests',)),\n    # If your package is a single module, use this instead of 'packages':\n    # py_modules=['mypackage'],\n\n    # entry_points={\n    #     'console_scripts': ['mycli=mymodule:cli'],\n    # },\n    install_requires=REQUIRED,\n    include_package_data=True,\n    license='MIT',\n    classifiers=[\n        # Trove classifiers\n        # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers\n        'License :: OSI Approved :: MIT License',\n        'Programming Language :: Python',\n        'Programming Language :: Python :: 2.6',\n        'Programming Language :: Python :: 2.7',\n        'Programming Language :: Python :: 3',\n        'Programming Language :: Python :: 3.3',\n        'Programming Language :: Python :: 3.4',\n        'Programming Language :: Python :: 3.5',\n        'Programming Language :: Python :: 3.6',\n        'Programming Language :: Python :: Implementation :: CPython',\n        'Programming Language :: Python :: Implementation :: PyPy'\n    ],\n    # $ setup.py publish support.\n    cmdclass={\n        'upload': UploadCommand,\n    },\n)\n"
  },
  {
    "path": "sounds/corpus/README.md",
    "content": "These clips were generously contributed to this work by their authors and are licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. That means these clips are not for commercial usage. Further, any sharing of these clips must contain attribution to their authors, and must be shared under the same license.\n"
  },
  {
    "path": "sounds/examples/timedomain/README.md",
    "content": "\n# Audio Samples\n\nThis repository also includes audio samples from Robert Thomas (`target/male-talking.wav`), music by [Robert Thomas](http://robertthomassound.com/) and [Franky Redente](https://soundcloud.com/franky80y) (`corpus/robthomas*`), samples and music by [John Tejada](http://www.paletterecordings.com/) and [Reggie Watts](http://reggiewatts.com/) (`corpus/johntejada*`, `target/beat-box*`, `target/male-singing.wav`, `target/female-singing.wav`), and one voice sample by [Ashwin Vaswani](https://www.ashwinvaswani.com/) (`target/male-taal.wav`).  These clips were generously contributed to this work by their authors and are *licensed under a Creative Commons Attribution-NonCommercial 4.0 International License*.  That means these clips are not for commercial usage.  Further, any sharing of these clips must contain attribution to their authors, and must be shared under the same license.\n"
  },
  {
    "path": "sounds/examples/uylanov/README.md",
    "content": "\n# Audio Samples\n\nThis repository also includes audio samples from Robert Thomas (`target/male-talking.wav`), music by [Robert Thomas](http://robertthomassound.com/) and [Franky Redente](https://soundcloud.com/franky80y) (`corpus/robthomas*`), samples and music by [John Tejada](http://www.paletterecordings.com/) and [Reggie Watts](http://reggiewatts.com/) (`corpus/johntejada*`, `target/beat-box*`, `target/male-singing.wav`, `target/female-singing.wav`), and one voice sample by [Ashwin Vaswani](https://www.ashwinvaswani.com/) (`target/male-taal.wav`).  These clips were generously contributed to this work by their authors and are *licensed under a Creative Commons Attribution-NonCommercial 4.0 International License*.  That means these clips are not for commercial usage.  Further, any sharing of these clips must contain attribution to their authors, and must be shared under the same license.\n"
  },
  {
    "path": "style-transfer.bib",
    "content": "sc{Ulyanov2016,\nauthor = {Ulyanov, Dmitry and Lebedev, Vadim},\ntitle = {{Audio texture synthesis and style transfer}},\nurldate = {November 3, 2017},\nyear = {2016}\n}\n@inproceedings{Wyse2017,\nabstract = {One of the decisions that arise when designing a neural network for any application is how the data should be represented in order to be presented to, and possibly generated by, a neural network. For audio, the choice is less obvious than it seems to be for visual images, and a variety of representations have been used for different applications including the raw digitized sample stream, hand-crafted features, machine discovered features, MFCCs and variants that include deltas, and a variety of spectral representations. This paper reviews some of these representations and issues that arise, focusing particularly on spectrograms for generating audio using neural networks for style transfer.},\narchivePrefix = {arXiv},\narxivId = {1706.09559},\nauthor = {Wyse, L.},\nbooktitle = {Proceedings of the First International Workshop on Deep Learning and Music joint with IJCNN},\neprint = {1706.09559},\nfile = {:Users/pkmital/Documents/PDFs/Wyse/Wyse - 2017 - Audio Spectrogram Representations for Processing with Convolutional Neural Networks.pdf:pdf},\nkeywords = {data representation,sound synthesis,spectrograms,style transfer},\nnumber = {1},\npages = {37--41},\ntitle = {{Audio Spectrogram Representations for Processing with Convolutional Neural Networks}},\nurl = {http://arxiv.org/abs/1706.09559},\nvolume = {1},\nyear = {2017}\n}\n@article{Ustyuzhaninov2016,\nabstract = {Here we demonstrate that the feature space of random shallow convolutional neural networks (CNNs) can serve as a surprisingly good model of natural textures. Patches from the same texture are consistently classified as being more similar then patches from different textures. Samples synthesized from the model capture spatial correlations on scales much larger then the receptive field size, and sometimes even rival or surpass the perceptual quality of state of the art texture models (but show less variability). The current state of the art in parametric texture synthesis relies on the multi-layer feature space of deep CNNs that were trained on natural images. Our finding suggests that such optimized multi-layer feature spaces are not imperative for texture modeling. Instead, much simpler shallow and convolutional networks can serve as the basis for novel texture synthesis algorithms.},\narchivePrefix = {arXiv},\narxivId = {1606.00021},\nauthor = {Ustyuzhaninov, Ivan and Brendel, Wieland and Gatys, Leon A. and Bethge, Matthias},\neprint = {1606.00021},\nfile = {:Users/pkmital/Documents/PDFs/Ustyuzhaninov et al/Ustyuzhaninov et al. - 2016 - Texture Synthesis Using Shallow Convolutional Networks with Random Filters.pdf:pdf},\njournal = {Arxiv},\npages = {1--9},\ntitle = {{Texture Synthesis Using Shallow Convolutional Networks with Random Filters}},\nurl = {http://arxiv.org/abs/1606.00021},\nyear = {2016}\n}\n@article{Gatys,\narchivePrefix = {arXiv},\narxivId = {arXiv:1508.06576v2},\nauthor = {Gatys, Leon A and Ecker, Alexander S and Bethge, Matthias and Sep, C V},\neprint = {arXiv:1508.06576v2},\nfile = {:Users/pkmital/Documents/PDFs/Gatys et al/Gatys et al. - 2015 - A Neural Algorithm of Artistic Style.pdf:pdf},\njournal = {Arxiv},\npages = {211839},\ntitle = {{A Neural Algorithm of Artistic Style}},\nyear = {2015}\n}\n@article{Prusa2017,\nauthor = {Prů{\\v{s}}a, Zden{\\v{e}}k and Rajmic, Pavel},\ndoi = {10.1109/LSP.2017.2696970},\nfile = {:Users/pkmital/Documents/PDFs/Prů{\\v{s}}a, Rajmic/Prů{\\v{s}}a, Rajmic - 2017 - Toward High-Quality Real-Time Signal Reconstruction from STFT Magnitude.pdf:pdf},\nissn = {10709908},\njournal = {IEEE Signal Processing Letters},\nkeywords = {Phase reconstruction,real-time,short-time Fourier transform (STFT),spectrogram,time-frequency},\nmendeley-groups = {nips-2017-audio-style},\nnumber = {6},\npages = {892--896},\ntitle = {{Toward High-Quality Real-Time Signal Reconstruction from STFT Magnitude}},\nvolume = {24},\nyear = {2017}\n}\n@article{Griffin1984,\nauthor = {Griffin, Daniel W and Lim, Jae S},\nfile = {:Users/pkmital/Documents/PDFs/Griffin, Lim/Griffin, Lim - 1984 - Signal Estimation from Modified Short-Time Fourier Transform.pdf:pdf},\njournal = {IEEE Transactions on Acoustics, Speech, and Signal Processing},\nmendeley-groups = {nips-2017-audio-style},\nnumber = {2},\npages = {236--243},\ntitle = {{Signal Estimation from Modified Short-Time Fourier Transform}},\nvolume = {32},\nyear = {1984}\n}\n@inproceedings{Engel2017,\nabstract = {Generative models in vision have seen rapid progress due to algorithmic improvements and the availability of high-quality image datasets. In this paper, we offer contributions in both these areas to enable similar progress in audio modeling. First, we detail a powerful new WaveNet-style autoencoder model that conditions an autoregressive decoder on temporal codes learned from the raw audio waveform. Second, we introduce NSynth, a large-scale and high-quality dataset of musical notes that is an order of magnitude larger than comparable public datasets. Using NSynth, we demonstrate improved qualitative and quantitative performance of the WaveNet autoencoder over a well-tuned spectral autoencoder baseline. Finally, we show that the model learns a manifold of embeddings that allows for morphing between instruments, meaningfully interpolating in timbre to create new types of sounds that are realistic and expressive.},\narchivePrefix = {arXiv},\narxivId = {1704.01279},\nauthor = {Engel, Jesse and Resnick, Cinjon and Roberts, Adam and Dieleman, Sander and Eck, Douglas and Simonyan, Karen and Norouzi, Mohammad},\nbooktitle = {Proceedings of the 34th International Conference on Machine Learning},\neprint = {1704.01279},\nfile = {:Users/pkmital/Documents/PDFs/Engel et al/Engel et al. - 2017 - Neural Audio Synthesis of Musical Notes with WaveNet Autoencoders(2).pdf:pdf},\nmendeley-groups = {nips-2017-audio-style},\ntitle = {{Neural Audio Synthesis of Musical Notes with WaveNet Autoencoders}},\nurl = {http://arxiv.org/abs/1704.01279},\nyear = {2017}\n}\n@article{Oord2016b,\nabstract = {This paper introduces WaveNet, a deep neural network for generating raw audio waveforms. The model is fully probabilistic and autoregressive, with the predictive distribution for each audio sample conditioned on all previous ones; nonetheless we show that it can be efficiently trained on data with tens of thousands of samples per second of audio. When applied to text-to-speech, it yields state-of-the-art performance, with human listeners rating it as significantly more natural sounding than the best parametric and concatenative systems for both English and Mandarin. A single WaveNet can capture the characteristics of many different speakers with equal fidelity, and can switch between them by conditioning on the speaker identity. When trained to model music, we find that it generates novel and often highly realistic musical fragments. We also show that it can be employed as a discriminative model, returning promising results for phoneme recognition.},\narchivePrefix = {arXiv},\narxivId = {1609.03499},\nauthor = {van den Oord, Aaron and Dieleman, Sander and Zen, Heiga and Simonyan, Karen and Vinyals, Oriol and Graves, Alex and Kalchbrenner, Nal and Senior, Andrew and Kavukcuoglu, Koray},\neprint = {1609.03499},\nfile = {:Users/pkmital/Documents/PDFs/Oord et al/Oord et al. - 2016 - WaveNet A Generative Model for Raw Audio.pdf:pdf},\njournal = {arxiv},\nmendeley-groups = {Neural Audio},\npages = {1--15},\ntitle = {{WaveNet: A Generative Model for Raw Audio}},\nurl = {http://arxiv.org/abs/1609.03499},\nyear = {2016}\n}\n@article{Hershey2016,\nabstract = {Convolutional Neural Networks (CNNs) have proven very effective in image classification and show promise for audio. We use various CNN architectures to classify the soundtracks of a dataset of 70M training videos (5.24 million hours) with 30,871 video-level labels. We examine fully connected Deep Neural Networks (DNNs), AlexNet [1], VGG [2], Inception [3], and ResNet [4]. We investigate varying the size of both training set and label vocabulary, finding that analogs of the CNNs used in image classification do well on our audio classification task, and larger training and label sets help up to a point. A model using embeddings from these classifiers does much better than raw features on the Audio Set [5] Acoustic Event Detection (AED) classification task.},\narchivePrefix = {arXiv},\narxivId = {1609.09430},\nauthor = {Hershey, Shawn and Chaudhuri, Sourish and Ellis, Daniel P. W. and Gemmeke, Jort F. and Jansen, Aren and Moore, Channing and Plakal, Manoj and Platt, Devin and Saurous, Rif A. and Seybold, Bryan and Slaney, Malcolm and Weiss, Ron J. and Wilson, Kevin and Moore, R. Channing and Plakal, Manoj and Platt, Devin and Saurous, Rif A. and Seybold, Bryan and Slaney, Malcolm and Weiss, Ron J. and Wilson, Kevin},\neprint = {1609.09430},\nfile = {:Users/pkmital/Documents/PDFs/Hershey et al/Hershey et al. - 2016 - CNN Architectures for Large-Scale Audio Classification.pdf:pdf},\nisbn = {9781509041176},\njournal = {International Conference on Acoustics, Speech and Signal Processing (ICASSP)},\nmendeley-groups = {Embodied Cognition,nips-2017-audio-style},\npages = {4--8},\ntitle = {{CNN Architectures for Large-Scale Audio Classification}},\nurl = {http://arxiv.org/abs/1609.09430},\nyear = {2016}\n}\n@article{Ulyanov2016b,\nabstract = {Gatys et al. recently demonstrated that deep networks can generate beautiful textures and stylized images from a single texture example. However, their methods requires a slow and memory-consuming optimization process. We propose here an alternative approach that moves the computational burden to a learning stage. Given a single example of a texture, our approach trains compact feed-forward convolutional networks to generate multiple samples of the same texture of arbitrary size and to transfer artistic style from a given image to any other image. The resulting networks are remarkably light-weight and can generate textures of quality comparable to Gatys{\\~{}}et{\\~{}}al., but hundreds of times faster. More generally, our approach highlights the power and flexibility of generative feed-forward models trained with complex and expressive loss functions.},\narchivePrefix = {arXiv},\narxivId = {1603.03417},\nauthor = {Ulyanov, Dmitry and Lebedev, Vadim and Vedaldi, Andrea and Lempitsky, Victor},\neprint = {1603.03417},\nfile = {:Users/pkmital/Documents/PDFs/Ulyanov et al/Ulyanov et al. - 2016 - Texture Networks Feed-forward Synthesis of Textures and Stylized Images.pdf:pdf},\nisbn = {9781510829008},\nissn = {1938-7228},\nmendeley-groups = {nips-2017-audio-style},\ntitle = {{Texture Networks: Feed-forward Synthesis of Textures and Stylized Images}},\nurl = {http://arxiv.org/abs/1603.03417},\nyear = {2016}\n}\n\n"
  }
]