[
  {
    "path": ".gitignore",
    "content": "# Neural Doodle\nvgg19_conv.pkl.bz2\n\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\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\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n#Ipython Notebook\n.ipynb_checkpoints\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<http://www.gnu.org/licenses/>.\n\n"
  },
  {
    "path": "README.rst",
    "content": "Neural Doodle\n=============\n\n.. image:: docs/Workflow.gif\n\nUse a deep neural network to borrow the skills of real artists and turn your two-bit doodles into masterpieces! This project is an implementation of `Semantic Style Transfer <http://arxiv.org/abs/1603.01768>`_ (Champandard, 2016), based on the `Neural Patches <http://arxiv.org/abs/1601.04589>`_ algorithm (Li, 2016). Read more about the motivation in this `in-depth article <https://nucl.ai/blog/neural-doodles/>`_ and watch this `workflow video <https://www.youtube.com/watch?v=fu2fzx4w3mI>`_ for inspiration.\n\nThe ``doodle.py`` script generates a new image by using one, two, three or four images as inputs depending what you're trying to do: the original style and its annotation, and a target content image (optional) with its annotation (a.k.a. your doodle). The algorithm extracts annotated patches from the style image, and incrementally transfers them over to the target image based on how closely they match.\n\n**NOTE**: Making a ``#NeuralDoodle`` is a skill. The parameters in the script were adjusted to work well by default and with the examples below. For new images, you may need to adjust values and modify on your input data too. It takes practice, but you can reach almost photo-realistic results if you iterate! (`Ask for advice here or see examples <https://github.com/alexjc/neural-doodle/issues?q=label%3Aadvice>`_.)\n\n1. `Examples & Usage <#1-examples--usage>`_\n2. `Installation <#2-installation--setup>`_\n3. `Troubleshooting <#3-troubleshooting-problems>`_\n4. `Frequent Questions <#4-frequent-questions>`_\n\n**IMPORTANT**: This project is possible thanks to the `nucl.ai Conference <http://events.nucl.ai/>`_ on Creative AI, **July 18-20**. Join us in **Vienna**!\n\n|Python Version| |License Type| |Project Stars|\n\n----\n\n.. image:: docs/Landscape_example.png\n\n1. Examples & Usage\n===================\n\nThe main script is called ``doodle.py``, which you can run with Python 3.4+ (see setup below).  The ``--device`` argument that lets you specify which GPU or CPU to use. For the samples above, here are the performance results:\n\n* **GPU Rendering** — Assuming you have CUDA setup and enough on-board RAM, the process should complete in 3 to 8 minutes, even with twice the iteration count.\n* **CPU Rendering** — This will take hours and hours, even up to 12h on older hardware. To match quality it'd take twice the time. Do multiple runs in parallel!\n\nThe default is to use ``cpu``, if you have NVIDIA card setup with CUDA already try ``gpu0``. On the CPU, you can also set environment variable to ``OMP_NUM_THREADS=4``, but we've found the speed improvements to be minimal.\n\n1.a) Image Analogy\n------------------\n\nThe algorithm is built for style transfer, but can also generate image analogies that we call a ``#NeuralDoodle``; use the hashtag if you post your images!  Example files are included in the ``#/samples/`` folder. Execute with these commands:\n\n.. code:: bash\n\n    # Synthesize a coastline as if painted by Monet. This uses \"*_sem.png\" masks for both images.\n    python3 doodle.py --style samples/Monet.jpg --output samples/Coastline.png \\\n                      --device=cpu --iterations=40\n\n    # Generate a scene around a lake in the style of a Renoir painting.\n    python3 doodle.py --style samples/Renoir.jpg --output samples/Landscape.png \\\n                      --device=gpu0 --iterations=80\n\nNotice the Renoir results look a little better than the Monet. Some rotational variations of the source image could improve the quality of the arch outline in particular.\n\n\n1.b) Style Transfer\n-------------------\n\nIf you want to transfer the style given a source style with annotations, and a target content image with annotations, you can use the following command lines.  In all cases, the semantic map is loaded and used if it's found under the ``*_sem.png`` filename that matches the input file.\n\n.. code:: bash\n\n    # Synthesize a portrait of Seth Johnson like a Gogh portrait. This uses \"*_sem.png\" masks for both images.\n    python3 doodle.py --style samples/Gogh.jpg --content samples/Seth.png \\\n                      --output SethAsGogh.png --device=cpu --phases=4 --iterations=40\n\n    # Generate what a photo of Vincent van Gogh would look like, using Seth's portrait as reference.\n    python3 doodle.py --style samples/Seth.jpg --content samples/Gogh.png \\\n                      --output GoghAsSeth.png --device=gpu0 --phases=4 --iterations=80\n\nTo perform regular style transfer without semantic annotations, simply delete or rename the files with the semantic maps.  The photo is originally by `Seth Johnson <http://sethjohnson.tumblr.com/post/655063019/this-was-a-project-for-an-art-history-class-turns>`_, and the concept for this style transfer by `Kyle McDonald <https://twitter.com/kcimc>`_.\n\n.. image:: docs/Portraits_example.jpg\n\n\n1.c) Texture Synthesis\n----------------------\n\nFor synthesizing bitmap textures, you only need an input style without anotations and without target output.  In this case, you simply specify one input style image and the output file as follows:\n\n.. code:: bash\n\n    # First synthesis uses a darker noise pattern as seed.\n    python3 doodle.py --style samples/Wall.jpg --output Wall.png\\\n                      --seed=noise --seed-range=0:128 --iterations=50 --phases=3\n\n    # Second synthesis uses a lighter noise pattern as seed.\n    python3 doodle.py --style samples/Wall.jpg --output Wall.png\\\n                      --seed=noise --seed-range=192:255 --iterations=50 --phases=3\n\nYou can also control the output resolution using ``--output-size=512x512`` parameter—which also depends on the memory you have available. By default the size will be the same as the style image.\n\n.. image:: docs/Textures_example.jpg\n\n\n1.d) Script Parameters\n----------------------\n\nYou can configure the algorithm using the following parameters. Type ``python3 doodle.py --help`` for the full list of options, or see the source code.\n\n* ``--style-weight=50.0`` — Weight of style relative to content.\n* ``--style-layers=3_1,4_1`` — The layers to match style patches.\n* ``--semantic-weight=1.0`` — Global weight of semantics vs. features.\n* ``--smoothness=1.0`` — Weight of image smoothing scheme.\n* ``--seed=noise`` — Seed image path, \"noise\" or \"content\".\n* ``--print-every=10`` — How often to log statistics to stdout.\n* ``--save-every=10`` — How frequently to save PNG into `frames`.\n\n\n2. Installation & Setup\n=======================\n\n.. image:: docs/DockerConsole.gif\n\n2.a) Using Docker Image (recommended)\n-------------------------------------\n\nThe easiest way to get up-and-running is to `install Docker <https://www.docker.com/>`_. Then, you should be able to downloand and run the pre-built image using the ``docker`` command line tool.  Find out more about the ``alexjc/neural-doodle`` image on its `Docker Hub <https://hub.docker.com/r/alexjc/neural-doodle/>`_ page.\n\nThe easiest way to run the script from the docker image is to setup an easy access command called `doodle`. This will automatically:\n\n* Mount the ``frames`` folder from current directory into the instance for visualization.\n* Expose the ``samples`` folder from the current directory so the script can access files!\n\nThis is how you can do it in your terminal console on OSX or Linux:\n\n.. code:: bash\n\n    # Setup the alias. Put this in your .bash_rc or .zshrc file so it's available at startup.\n    alias doodle=\"docker run -v $(pwd)/samples:/nd/samples -v $(pwd)/frames:/nd/frames \\\n                             -it alexjc/neural-doodle\"\n    \n    # Now run any of the examples above using this alias, without the `.py` extension.\n    doodle --help\n\nIf you want to run on your NVIDIA GPU, you can instead use the image ``alexjc/neural-doodle:gpu`` which comes with CUDA and CUDNN pre-installed in the image.  See the scripts in ``docker/*.sh`` for how to setup your host machine. (advanced)\n\n\n2.b) Manual Installation (optional)\n-----------------------------------\n\nThis project requires Python 3.4+ and you'll also need ``numpy`` and ``scipy`` (numerical computing libraries) as well as ``python3-dev`` installed system-wide.  If you want more detailed instructions, follow these:\n\n1. `Linux Installation of Lasagne <https://github.com/Lasagne/Lasagne/wiki/From-Zero-to-Lasagne-on-Ubuntu-14.04>`_ **(intermediate)**\n2. `Mac OSX Installation of Lasagne <http://deeplearning.net/software/theano/install.html#mac-os>`_ **(advanced)**\n3. `Windows Installation of Lasagne <https://github.com/Lasagne/Lasagne/wiki/From-Zero-to-Lasagne-on-Windows-7-%2864-bit%29>`_ **(expert)**\n\nAfterward fetching the repository, you can run the following commands from your terminal to setup a local environment:\n\n.. code:: bash\n\n    # Create a local environment for Python 3.x to install dependencies here.\n    python3 -m venv pyvenv --system-site-packages\n\n    # If you're using bash, make this the active version of Python.\n    source pyvenv/bin/activate\n\n    # Setup the required dependencies simply using the PIP module.\n    python3 -m pip install --ignore-installed -r requirements.txt\n\nAfter this, you should have ``scikit-image``, ``theano`` and ``lasagne`` installed in your virtual environment.  You'll also need to download this `pre-trained neural network <https://github.com/alexjc/neural-doodle/releases/download/v0.0/vgg19_conv.pkl.bz2>`_ (VGG19, 80Mb) and put it in the same folder as the script to run. Once you're done you can just delete the ``#/pyvenv/`` folder.\n\n.. image:: docs/Coastline_example.png\n\n\n3. Troubleshooting Problems\n===========================\n\nIt's running out of GPU Ram, throwing ``MemoryError``. Help!\n------------------------------------------------------------\n\nYou'll need a good NVIDIA card with CUDA to run this software on GPU, ideally 2Gb / 4Gb or better still, 8Gb to 12Gb for larger resolutions.  The code does work on CPU by default, so use that as fallback since you likely have more system RAM!\n\nTo improve memory consumption, you can also install NVIDIA's ``cudnn`` library version 3.0 or 4.0. This allows convolutional neural networks to run faster and save space in GPU RAM.\n\n**FIX:** Use ``--device=cpu`` to use main system memory.\n\n\nHow much GPU is being used? It doesn't seem very fast...\n--------------------------------------------------------\n\nFirst make sure CUDA is installed correctly and environment variables are set, then reinstall ``theano``.  If everything is setup correctly, the GPU should be used regularly as the gradient calculations are offloaded. If you run NVIDIA's monitoring tool it looks something like this:\n\n.. code:: bash\n    # gpu   pwr  temp    sm   mem   enc   dec  mclk  pclk\n    # Idx     W     C     %     %     %     %   MHz   MHz\n        0    88    63    50    25     0     0  3004  1252\n        0    60    63     0     1     0     0  3004  1252\n        0    75    63    19     9     0     0  3004  1252\n        0    59    63     0     1     0     0  3004  1240\n        0    62    63    16     3     0     0  3004  1240\n        0    63    64     2     1     0     0  3004  1252\n        0    66    63    26     4     0     0  3004  1252 \n\nThe third column is the utilitazition of compute resources, and the fourth column is the use of memory.  If memory is under-used you can increase resolution!  If compute is under allocated too you can try running multiple scripts in parallel!\n\n**FIX:** Run ``nvidia-smi dmon`` and check the ``sm`` column.\n\n\nCan't install or Unable to find pgen, not compiling formal grammar.\n-------------------------------------------------------------------\n\nThere's a Python extension compiler called Cython, and it's missing or inproperly installed. Try getting it directly from the system package manager rather than PIP.\n\n*FIX:* ``sudo apt-get install cython3``\n\n\nNotImplementedError: AbstractConv2d theano optimization failed.\n---------------------------------------------------------------\n\nThis happens when you're running without a GPU, and the CPU libraries were not found (e.g. ``libblas``).  The neural network expressions cannot be evaluated by Theano and it's raising an exception.\n\n**FIX:** ``sudo apt-get install libblas-dev libopenblas-dev``\n\n\nTypeError: max_pool_2d() got an unexpected keyword argument 'mode'\n------------------------------------------------------------------\n\nYou need to install Lasagne and Theano directly from the versions specified in ``requirements.txt``, rather than from the PIP versions.  These alternatives are older and don't have the required features.\n\n**FIX:** ``python3 -m pip install -r requirements.txt``\n\n\nValueError: unknown locale: UTF-8\n---------------------------------\n\nIt seems your terminal is misconfigured and not compatible with the way Python treats locales. You may need to change this in your ``.bash_rc`` or other startup script. Alternatively, this command will fix it once for this shell instance.\n\n**FIX:** ``export LC_ALL=en_US.UTF-8``\n\n\nERROR: The optimization diverged and NaNs were encountered.\n-----------------------------------------------------------\n\nIt's possible there's a platform bug in the underlying libraries or compiler, which has been reported on MacOS El Capitan.  It's not clear how to fix it, but you can try to disable optimizations to prevent the bug. (See `Issue #8 <https://github.com/alexjc/neural-doodle/issues/8>`_.)\n\n**FIX:** Use ``--safe-mode`` flag to disable optimizations.\n\n\n4. Frequent Questions\n=====================\n\nQ: When will this be possible in realtime? I want it as filter!\n---------------------------------------------------------------\n\nRelated algorithms have shown this is possible in realtime—if you're willing to accept slightly lower quality:\n\n* `Texture Networks: Feed-forward Synthesis of Textures and Stylized Images <http://arxiv.org/abs/1603.03417>`_\n* `Perceptual Losses for Real-Time Style Transfer and Super-Resolution <http://arxiv.org/abs/1603.08155>`_\n* `Precomputed Real-Time Texture Synthesis with Markovian Generative Adversarial Networks <http://arxiv.org/abs/1604.04382>`_\n\nThis project is not designed for real-time use, the focus is on quality.  The code in this repository is ideal for training realtime capable networks. \n\nQ: Is there an application for this? I want to download it!\n-----------------------------------------------------------\n\nThere are many online services that provide basic style transfer with neural networks. We run `@DeepForger <https://deepforger.com/>`_, a Twitter & Facebook bot with web interface, that can take your requests too.  It takes time to make forgeries, so there's a queue... be patient!\n\n\n----\n\n|Python Version| |License Type| |Project Stars|\n\n.. |Python Version| image:: http://aigamedev.github.io/scikit-neuralnetwork/badge_python.svg\n    :target: https://www.python.org/\n\n.. |License Type| image:: https://img.shields.io/badge/license-AGPL-blue.svg\n    :target: https://github.com/alexjc/neural-doodle/blob/master/LICENSE\n\n.. |Project Stars| image:: https://img.shields.io/github/stars/alexjc/neural-doodle.svg?style=flat\n    :target: https://github.com/alexjc/neural-doodle/stargazers\n"
  },
  {
    "path": "docker/install-cuda-drivers-ubuntu-14.04.sh",
    "content": "#!/usr/bin/env bash\n\n# Install dependencies\napt-get update\napt-get install --assume-yes                      \\\n    \"linux-source\"                                \\\n    \"linux-headers-$(uname --kernel-release)\"     \\\n    \"linux-image-extra-$(uname --kernel-release)\" \\\n    \"build-essential\"                             \\\n    \"wget\"\n\n# Install NVIDIA CUDA with NVIDIA GPU drivers\nCUDA_REPOSITORY=\"cuda-repo-ubuntu1404_7.5-18_amd64.deb\"\nCUDA_REPOSITORY_URL=\"http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1404/x86_64\"\n\nwget --directory-prefix=\"/tmp/\" --continue \"$CUDA_REPOSITORY_URL/$CUDA_REPOSITORY\"\ndpkg --install \"/tmp/$CUDA_REPOSITORY\"\napt-get update\napt-get install \"cuda\"\n\nrm --interactive \"/tmp/$CUDA_REPOSITORY\"\n"
  },
  {
    "path": "docker/install-nvidia-docker-ubuntu-14.04.sh",
    "content": "#!/usr/bin/env bash\n\n# Install dependencies\napt-get update\napt-get install --assume-yes \"wget\"\n\n# Install Docker Engine\nwget --quiet --output-document=\"-\" \"https://get.docker.com\" | sh\nusermod --append --groups=\"docker\" \"$SUDO_USER\"\n\n# Install an NVIDIA Docker wrapper\nNVIDIA_DOCKER=\"nvidia-docker_1.0.0.beta.2-1_amd64.deb\"\nNVIDIA_DOCKER_URL=\"https://github.com/NVIDIA/nvidia-docker/releases/download/v1.0.0-beta.2\"\n\nwget --directory-prefix=\"/tmp/\" --continue \"$NVIDIA_DOCKER_URL/$NVIDIA_DOCKER\"\ndpkg --install \"/tmp/$NVIDIA_DOCKER\"\nrm --interactive \"/tmp/$NVIDIA_DOCKER\"\n\nnvidia-docker volume setup\n"
  },
  {
    "path": "docker-cpu.df",
    "content": "FROM ubuntu:14.04\n\n# Install dependencies\nRUN apt-get -qq update           &&  \\\n    apt-get -qq install --assume-yes \\\n        \"build-essential\"           \\\n        \"cmake\"                     \\\n        \"git\"                       \\\n        \"wget\"                      \\\n        \"libopenjpeg2\"              \\\n        \"libopenblas-dev\"           \\\n        \"liblapack-dev\"             \\\n        \"libjpeg-dev\"               \\\n        \"libtiff5-dev\"              \\\n        \"zlib1g-dev\"                \\\n        \"libfreetype6-dev\"          \\\n        \"liblcms2-dev\"              \\\n        \"libwebp-dev\"               \\\n        \"gfortran\"                  \\\n        \"pkg-config\"                \\\n        \"python3\"                   \\\n        \"python3-dev\"               \\\n        \"python3-pip\"               \\\n        \"python3-numpy\"             \\\n        \"python3-scipy\"             \\\n        \"python3-six\"               \\\n        \"python3-networkx\"       &&  \\\n    rm -rf /var/lib/apt/lists/*  &&  \\\n    python3 -m pip install \"cython\"\n\n# Install requirements before copying project files\nWORKDIR /nd\nCOPY requirements.txt .\nRUN python3 -m pip install -r \"requirements.txt\"\n\n# Copy only required project files\nCOPY doodle.py .\n\n# Get a pre-trained neural network (VGG19)\nRUN wget -q \"https://github.com/alexjc/neural-doodle/releases/download/v0.0/vgg19_conv.pkl.bz2\"\n\n# Set an entrypoint to the main doodle.py script\nENTRYPOINT [\"python3\", \"doodle.py\", \"--device=cpu\"]\n"
  },
  {
    "path": "docker-gpu.df",
    "content": "FROM nvidia/cuda:7.5-cudnn4-devel\n\n# Install dependencies\nRUN apt-get -qq update            && \\\n    apt-get -qq install --assume-yes \\\n        \"module-init-tools\"         \\\n        \"build-essential\"           \\\n        \"cmake\"                     \\\n        \"git\"                       \\\n        \"wget\"                      \\\n        \"libopenjpeg2\"              \\\n        \"libopenblas-dev\"           \\\n        \"liblapack-dev\"             \\\n        \"libjpeg-dev\"               \\\n        \"libtiff5-dev\"              \\\n        \"zlib1g-dev\"                \\\n        \"libfreetype6-dev\"          \\\n        \"liblcms2-dev\"              \\\n        \"libwebp-dev\"               \\\n        \"gfortran\"                  \\\n        \"pkg-config\"\t\t    \\\n        \"python3\"                   \\\n        \"python3-dev\"               \\\n        \"python3-pip\"               \\\n        \"python3-numpy\"             \\\n        \"python3-scipy\"             \\\n        \"python3-matplotlib\"        \\\n        \"python3-six\"               \\\n        \"python3-networkx\"          \\\n        \"python3-tk\"             &&  \\\n    rm -rf /var/lib/apt/lists/*  &&  \\\n    python3 -m pip -q install \"cython\"\n\n# Install requirements before copying project files\nWORKDIR /nd\nCOPY requirements.txt .\nRUN python3 -m pip -q install -r \"requirements.txt\"\n\n# Copy only required project files\nCOPY doodle.py .\n\n# Get a pre-trained neural network (VGG19)\nRUN wget -q \"https://github.com/alexjc/neural-doodle/releases/download/v0.0/vgg19_conv.pkl.bz2\"\n\n# Set an entrypoint to the main doodle.py script\nENTRYPOINT [\"python3\", \"doodle.py\", \"--device=gpu\"]\n"
  },
  {
    "path": "doodle.py",
    "content": "#!/usr/bin/env python3\n#\n# Neural Doodle!\n# Copyright (c) 2016, Alex J. Champandard.\n#\n# Research and Development sponsored by the nucl.ai Conference!\n#   http://events.nucl.ai/\n#   July 18-20, 2016 in Vienna/Austria.\n#\n\nimport os\nimport sys\nimport bz2\nimport math\nimport time\nimport pickle\nimport argparse\nimport itertools\nimport collections\n\n\n# Configure all options first so we can custom load other libraries (Theano) based on device specified by user.\nparser = argparse.ArgumentParser(description='Generate a new image by applying style onto a content image.',\n                                 formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nadd_arg = parser.add_argument\n\nadd_arg('--content',        default=None, type=str,         help='Content image path as optimization target.')\nadd_arg('--content-weight', default=10.0, type=float,       help='Weight of content relative to style.')\nadd_arg('--content-layers', default='4_2', type=str,        help='The layer with which to match content.')\nadd_arg('--style',          default=None, type=str,         help='Style image path to extract patches.')\nadd_arg('--style-weight',   default=25.0, type=float,       help='Weight of style relative to content.')\nadd_arg('--style-layers',   default='3_1,4_1', type=str,    help='The layers to match style patches.')\nadd_arg('--semantic-ext',   default='_sem.png', type=str,   help='File extension for the semantic maps.')\nadd_arg('--semantic-weight', default=10.0, type=float,      help='Global weight of semantics vs. features.')\nadd_arg('--output',         default='output.png', type=str, help='Output image path to save once done.')\nadd_arg('--output-size',    default=None, type=str,         help='Size of the output image, e.g. 512x512.')\nadd_arg('--phases',         default=3, type=int,            help='Number of image scales to process in phases.')\nadd_arg('--slices',         default=2, type=int,            help='Split patches up into this number of batches.')\nadd_arg('--cache',          default=0, type=int,            help='Whether to compute matches only once.')\nadd_arg('--smoothness',     default=1E+0, type=float,       help='Weight of image smoothing scheme.')\nadd_arg('--variety',        default=0.0, type=float,        help='Bias toward selecting diverse patches, e.g. 0.5.')\nadd_arg('--seed',           default='noise', type=str,      help='Seed image path, \"noise\" or \"content\".')\nadd_arg('--seed-range',     default='16:240', type=str,     help='Random colors chosen in range, e.g. 0:255.')\nadd_arg('--iterations',     default=100, type=int,          help='Number of iterations to run each resolution.')\nadd_arg('--device',         default='cpu', type=str,        help='Index of the GPU number to use, for theano.')\nadd_arg('--print-every',    default=10, type=int,           help='How often to log statistics to stdout.')\nadd_arg('--save-every',     default=10, type=int,           help='How frequently to save PNG into `frames`.')\nargs = parser.parse_args()\n\n\n#----------------------------------------------------------------------------------------------------------------------\n\n# Color coded output helps visualize the information a little better, plus looks cool!\nclass ansi:\n    BOLD = '\\033[1;97m'\n    WHITE = '\\033[0;97m'\n    YELLOW = '\\033[0;33m'\n    YELLOW_B = '\\033[0;33m'\n    RED = '\\033[0;31m'\n    RED_B = '\\033[1;31m'\n    BLUE = '\\033[0;94m'\n    BLUE_B = '\\033[1;94m'\n    CYAN = '\\033[0;36m'\n    CYAN_B = '\\033[1;36m'\n    ENDC = '\\033[0m'\n    \ndef error(message, *lines):\n    string = \"\\n{}ERROR: \" + message + \"{}\\n\" + \"\\n\".join(lines) + \"{}\\n\"\n    print(string.format(ansi.RED_B, ansi.RED, ansi.ENDC))\n    sys.exit(-1)\n\nprint('{}Neural Doodle for semantic style transfer.{}'.format(ansi.CYAN_B, ansi.ENDC))\n\n# Load the underlying deep learning libraries based on the device specified.  If you specify THEANO_FLAGS manually,\n# the code assumes you know what you are doing and they are not overriden!\nos.environ.setdefault('THEANO_FLAGS', 'floatX=float32,device={},force_device=True,'\\\n                                      'print_active_device=False'.format(args.device))\n\n# Scientific & Imaging Libraries\nimport numpy as np\nimport scipy.optimize, scipy.ndimage, scipy.misc\nimport PIL\n\n# Numeric Computing (GPU)\nimport theano\nimport theano.tensor as T\nimport theano.tensor.nnet.neighbours\n\n# Support ansi colors in Windows too.\nif sys.platform == 'win32':\n    import colorama\n\n# Deep Learning Framework\nimport lasagne\nfrom lasagne.layers import Conv2DLayer as ConvLayer, Pool2DLayer as PoolLayer\nfrom lasagne.layers import InputLayer, ConcatLayer\n\nprint('{}  - Using device `{}` for processing the images.{}'.format(ansi.CYAN, theano.config.device, ansi.ENDC))\n\n\n#----------------------------------------------------------------------------------------------------------------------\n# Convolutional Neural Network\n#----------------------------------------------------------------------------------------------------------------------\nclass Model(object):\n    \"\"\"Store all the data related to the neural network (aka. \"model\"). This is currently based on VGG19.\n    \"\"\"\n\n    def __init__(self):\n        self.pixel_mean = np.array([103.939, 116.779, 123.680], dtype=np.float32).reshape((3,1,1))\n\n        self.setup_model()\n        self.load_data()\n\n    def setup_model(self, input=None):\n        \"\"\"Use lasagne to create a network of convolution layers, first using VGG19 as the framework\n        and then adding augmentations for Semantic Style Transfer.\n        \"\"\"\n        net, self.channels = {}, {}\n\n        # Primary network for the main image. These are convolution only, and stop at layer 4_2 (rest unused).\n        net['img']     = input or InputLayer((None, 3, None, None))\n        net['conv1_1'] = ConvLayer(net['img'],     64, 3, pad=1)\n        net['conv1_2'] = ConvLayer(net['conv1_1'], 64, 3, pad=1)\n        net['pool1']   = PoolLayer(net['conv1_2'], 2, mode='average_exc_pad')\n        net['conv2_1'] = ConvLayer(net['pool1'],   128, 3, pad=1)\n        net['conv2_2'] = ConvLayer(net['conv2_1'], 128, 3, pad=1)\n        net['pool2']   = PoolLayer(net['conv2_2'], 2, mode='average_exc_pad')\n        net['conv3_1'] = ConvLayer(net['pool2'],   256, 3, pad=1)\n        net['conv3_2'] = ConvLayer(net['conv3_1'], 256, 3, pad=1)\n        net['conv3_3'] = ConvLayer(net['conv3_2'], 256, 3, pad=1)\n        net['conv3_4'] = ConvLayer(net['conv3_3'], 256, 3, pad=1)\n        net['pool3']   = PoolLayer(net['conv3_4'], 2, mode='average_exc_pad')\n        net['conv4_1'] = ConvLayer(net['pool3'],   512, 3, pad=1)\n        net['conv4_2'] = ConvLayer(net['conv4_1'], 512, 3, pad=1)\n        net['conv4_3'] = ConvLayer(net['conv4_2'], 512, 3, pad=1)\n        net['conv4_4'] = ConvLayer(net['conv4_3'], 512, 3, pad=1)\n        net['pool4']   = PoolLayer(net['conv4_4'], 2, mode='average_exc_pad')\n        net['conv5_1'] = ConvLayer(net['pool4'],   512, 3, pad=1)\n        net['conv5_2'] = ConvLayer(net['conv5_1'], 512, 3, pad=1)\n        net['conv5_3'] = ConvLayer(net['conv5_2'], 512, 3, pad=1)\n        net['conv5_4'] = ConvLayer(net['conv5_3'], 512, 3, pad=1)\n        net['main']    = net['conv5_4']\n\n        # Auxiliary network for the semantic layers, and the nearest neighbors calculations.\n        net['map'] = InputLayer((1, 1, None, None))\n        for j, i in itertools.product(range(5), range(4)):\n            if j < 2 and i > 1: continue\n            suffix = '%i_%i' % (j+1, i+1)\n\n            if i == 0:\n                net['map%i'%(j+1)] = PoolLayer(net['map'], 2**j, mode='average_exc_pad')\n            self.channels[suffix] = net['conv'+suffix].num_filters\n            \n            if args.semantic_weight > 0.0:\n                net['sem'+suffix] = ConcatLayer([net['conv'+suffix], net['map%i'%(j+1)]])\n            else:\n                net['sem'+suffix] = net['conv'+suffix]\n\n            net['dup'+suffix] = InputLayer(net['sem'+suffix].output_shape)\n            net['nn'+suffix] = ConvLayer(net['dup'+suffix], 1, 3, b=None, pad=0, flip_filters=False)\n\n        self.network = net\n\n    def load_data(self):\n        \"\"\"Open the serialized parameters from a pre-trained network, and load them into the model created.\n        \"\"\"\n        vgg19_file = os.path.join(os.path.dirname(__file__), 'vgg19_conv.pkl.bz2')\n        if not os.path.exists(vgg19_file):\n            error(\"Model file with pre-trained convolution layers not found. Download here...\",\n                  \"https://github.com/alexjc/neural-doodle/releases/download/v0.0/vgg19_conv.pkl.bz2\")\n\n        data = pickle.load(bz2.open(vgg19_file, 'rb'))\n        params = lasagne.layers.get_all_param_values(self.network['main'])\n        lasagne.layers.set_all_param_values(self.network['main'], data[:len(params)])\n\n    def setup(self, layers):\n        \"\"\"Setup the inputs and outputs, knowing the layers that are required by the optimization algorithm.\n        \"\"\"\n        self.tensor_img = T.tensor4()\n        self.tensor_map = T.tensor4()\n        tensor_inputs = {self.network['img']: self.tensor_img, self.network['map']: self.tensor_map}\n        outputs = lasagne.layers.get_output([self.network[l] for l in layers], tensor_inputs)\n        self.tensor_outputs = {k: v for k, v in zip(layers, outputs)}\n\n    def get_outputs(self, type, layers):\n        \"\"\"Fetch the output tensors for the network layers.\n        \"\"\"\n        return [self.tensor_outputs[type+l] for l in layers]\n\n    def prepare_image(self, image):\n        \"\"\"Given an image loaded from disk, turn it into a representation compatible with the model.\n        The format is (b,c,y,x) with batch=1 for a single image, channels=3 for RGB, and y,x matching\n        the resolution.\n        \"\"\"\n        image = np.swapaxes(np.swapaxes(image, 1, 2), 0, 1)[::-1, :, :]\n        image = image.astype(np.float32) - self.pixel_mean\n        return image[np.newaxis]\n\n    def finalize_image(self, image, resolution):\n        \"\"\"Based on the output of the neural network, convert it into an image format that can be saved\n        to disk -- shuffling dimensions as appropriate.\n        \"\"\"\n        image = np.swapaxes(np.swapaxes(image[::-1], 0, 1), 1, 2)\n        image = np.clip(image, 0, 255).astype('uint8')\n        return scipy.misc.imresize(image, resolution, interp='bicubic')\n\n\n#----------------------------------------------------------------------------------------------------------------------\n# Semantic Style Transfer\n#----------------------------------------------------------------------------------------------------------------------\nclass NeuralGenerator(object):\n    \"\"\"This is the main part of the application that generates an image using optimization and LBFGS.\n    The images will be processed at increasing resolutions in the run() method.\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Constructor sets up global variables, loads and validates files, then builds the model.\n        \"\"\"\n        self.start_time = time.time()\n        self.style_cache = {}\n        self.style_layers = args.style_layers.split(',')\n        self.content_layers = args.content_layers.split(',')\n        self.used_layers = self.style_layers + self.content_layers\n\n        # Prepare file output and load files specified as input.\n        if args.save_every is not None:\n            os.makedirs('frames', exist_ok=True)\n        if args.output is not None and os.path.isfile(args.output):\n            os.remove(args.output)\n\n        print(ansi.CYAN, end='')\n        target = args.content or args.output\n        self.content_img_original, self.content_map_original = self.load_images('content', target)\n        self.style_img_original, self.style_map_original = self.load_images('style', args.style)\n\n        if self.content_map_original is None and self.content_img_original is None:\n            print(\"  - No content files found; result depends on seed only.\")\n        print(ansi.ENDC, end='')\n\n        # Display some useful errors if the user's input can't be undrestood.\n        if self.style_img_original is None:\n            error(\"Couldn't find style image as expected.\",\n                  \"  - Try making sure `{}` exists and is a valid image.\".format(args.style))\n\n        if self.content_map_original is not None and self.style_map_original is None:\n            basename, _ = os.path.splitext(args.style)\n            error(\"Expecting a semantic map for the input style image too.\",\n                  \"  - Try creating the file `{}_sem.png` with your annotations.\".format(basename))\n\n        if self.style_map_original is not None and self.content_map_original is None:\n            basename, _ = os.path.splitext(target)\n            error(\"Expecting a semantic map for the input content image too.\",\n                  \"  - Try creating the file `{}_sem.png` with your annotations.\".format(basename))\n\n        if self.content_map_original is None:\n            if self.content_img_original is None and args.output_size:\n                shape = tuple([int(i) for i in args.output_size.split('x')])\n            else:\n                shape = self.style_img_original.shape[:2]\n\n            self.content_map_original = np.zeros(shape+(3,))\n            args.semantic_weight = 0.0\n\n        if self.style_map_original is None:\n            self.style_map_original = np.zeros(self.style_img_original.shape[:2]+(3,))\n            args.semantic_weight = 0.0\n\n        if self.content_img_original is None:\n            self.content_img_original = np.zeros(self.content_map_original.shape[:2]+(3,))\n            args.content_weight = 0.0\n\n        if self.content_map_original.shape[2] != self.style_map_original.shape[2]:\n            error(\"Mismatch in number of channels for style and content semantic map.\",\n                  \"  - Make sure both images are RGB, RGBA, or L.\")\n\n        # Finalize the parameters based on what we loaded, then create the model.\n        args.semantic_weight = math.sqrt(9.0 / args.semantic_weight) if args.semantic_weight else 0.0\n        self.model = Model()\n\n\n    #------------------------------------------------------------------------------------------------------------------\n    # Helper Functions\n    #------------------------------------------------------------------------------------------------------------------\n\n    def load_images(self, name, filename):\n        \"\"\"If the image and map files exist, load them. Otherwise they'll be set to default values later.\n        \"\"\"\n        basename, _ = os.path.splitext(filename)\n        mapname = basename + args.semantic_ext\n        img = scipy.ndimage.imread(filename, mode='RGB') if os.path.exists(filename) else None\n        map = scipy.ndimage.imread(mapname) if os.path.exists(mapname) and args.semantic_weight > 0.0 else None\n\n        if img is not None: print('  - Loading `{}` for {} data.'.format(filename, name))\n        if map is not None: print('  - Adding `{}` as semantic map.'.format(mapname))\n\n        if img is not None and map is not None and img.shape[:2] != map.shape[:2]:\n            error(\"The {} image and its semantic map have different resolutions. Either:\".format(name),\n                  \"  - Resize {} to {}, or\\n  - Resize {} to {}.\"\\\n                  .format(filename, map.shape[1::-1], mapname, img.shape[1::-1]))\n        return img, map\n\n    def compile(self, arguments, function):\n        \"\"\"Build a Theano function that will run the specified expression on the GPU.\n        \"\"\"\n        return theano.function(list(arguments), function, on_unused_input='ignore')\n\n    def compute_norms(self, backend, layer, array):\n        ni = backend.sqrt(backend.sum(array[:,:self.model.channels[layer]] ** 2.0, axis=(1,), keepdims=True))\n        ns = backend.sqrt(backend.sum(array[:,self.model.channels[layer]:] ** 2.0, axis=(1,), keepdims=True))\n        return [ni] + [ns]\n\n    def normalize_components(self, layer, array, norms):\n        if args.style_weight > 0.0:\n            array[:,:self.model.channels[layer]] /= (norms[0] * 3.0)\n        if args.semantic_weight > 0.0:\n            array[:,self.model.channels[layer]:] /= (norms[1] * args.semantic_weight)\n\n\n    #------------------------------------------------------------------------------------------------------------------\n    # Initialization & Setup\n    #------------------------------------------------------------------------------------------------------------------\n\n    def rescale_image(self, img, scale):\n        \"\"\"Re-implementing skimage.transform.scale without the extra dependency. Saves a lot of space and hassle!\n        \"\"\"\n        output = scipy.misc.toimage(img, cmin=0.0, cmax=255)\n        output.thumbnail((int(output.size[0]*scale), int(output.size[1]*scale)), PIL.Image.ANTIALIAS)\n        return np.asarray(output)\n\n    def prepare_content(self, scale=1.0):\n        \"\"\"Called each phase of the optimization, rescale the original content image and its map to use as inputs.\n        \"\"\"\n        content_img = self.rescale_image(self.content_img_original, scale)\n        self.content_img = self.model.prepare_image(content_img)\n\n        content_map = self.rescale_image(self.content_map_original, scale)\n        self.content_map = content_map.transpose((2, 0, 1))[np.newaxis].astype(np.float32)\n\n    def prepare_style(self, scale=1.0):\n        \"\"\"Called each phase of the optimization, process the style image according to the scale, then run it\n        through the model to extract intermediate outputs (e.g. sem4_1) and turn them into patches.\n        \"\"\"\n        style_img = self.rescale_image(self.style_img_original, scale)\n        self.style_img = self.model.prepare_image(style_img)\n\n        style_map = self.rescale_image(self.style_map_original, scale)\n        self.style_map = style_map.transpose((2, 0, 1))[np.newaxis].astype(np.float32)\n\n        # Compile a function to run on the GPU to extract patches for all layers at once.\n        layer_outputs = zip(self.style_layers, self.model.get_outputs('sem', self.style_layers))\n        extractor = self.compile([self.model.tensor_img, self.model.tensor_map], self.do_extract_patches(layer_outputs))\n        result = extractor(self.style_img, self.style_map)\n\n        # Store all the style patches layer by layer, resized to match slice size and cast to 16-bit for size. \n        self.style_data = {}\n        for layer, *data in zip(self.style_layers, result[0::3], result[1::3], result[2::3]):\n            patches = data[0]\n            l = self.model.network['nn'+layer]\n            l.num_filters = patches.shape[0] // args.slices\n            self.style_data[layer] = [d[:l.num_filters*args.slices].astype(np.float16) for d in data]\\\n                                   + [np.zeros((patches.shape[0],), dtype=np.float16)]\n            print('  - Style layer {}: {} patches in {:,}kb.'.format(layer, patches.shape, patches.size//1000))\n\n    def prepare_optimization(self):\n        \"\"\"Optimization requires a function to compute the error (aka. loss) which is done in multiple components.\n        Here we compile a function to run on the GPU that returns all components separately.\n        \"\"\"\n\n        # Feed-forward calculation only, returns the result of the convolution post-activation \n        self.compute_features = self.compile([self.model.tensor_img, self.model.tensor_map],\n                                             self.model.get_outputs('sem', self.style_layers))\n\n        # Patch matching calculation that uses only pre-calculated features and a slice of the patches.\n        \n        self.matcher_tensors = {l: lasagne.utils.shared_empty(dim=4) for l in self.style_layers}\n        self.matcher_history = {l: T.vector() for l in self.style_layers} \n        self.matcher_inputs = {self.model.network['dup'+l]: self.matcher_tensors[l] for l in self.style_layers}\n        nn_layers = [self.model.network['nn'+l] for l in self.style_layers]\n        self.matcher_outputs = dict(zip(self.style_layers, lasagne.layers.get_output(nn_layers, self.matcher_inputs)))\n\n        self.compute_matches = {l: self.compile([self.matcher_history[l]], self.do_match_patches(l))\\\n                                                for l in self.style_layers}\n\n        self.tensor_matches = [T.tensor4() for l in self.style_layers]\n        # Build a list of Theano expressions that, once summed up, compute the total error.\n        self.losses = self.content_loss() + self.total_variation_loss() + self.style_loss()\n        # Let Theano automatically compute the gradient of the error, used by LBFGS to update image pixels.\n        grad = T.grad(sum([l[-1] for l in self.losses]), self.model.tensor_img)\n        # Create a single function that returns the gradient and the individual errors components.\n        self.compute_grad_and_losses = theano.function(\n                                                [self.model.tensor_img, self.model.tensor_map] + self.tensor_matches,\n                                                [grad] + [l[-1] for l in self.losses], on_unused_input='ignore')\n\n\n    #------------------------------------------------------------------------------------------------------------------\n    # Theano Computation\n    #------------------------------------------------------------------------------------------------------------------\n\n    def do_extract_patches(self, layers, size=3, stride=1):\n        \"\"\"This function builds a Theano expression that will get compiled an run on the GPU. It extracts 3x3 patches\n        from the intermediate outputs in the model.\n        \"\"\"\n        results = []\n        for l, f in layers:\n            # Use a Theano helper function to extract \"neighbors\" of specific size, seems a bit slower than doing\n            # it manually but much simpler!\n            patches = theano.tensor.nnet.neighbours.images2neibs(f, (size, size), (stride, stride), mode='valid')\n            # Make sure the patches are in the shape required to insert them into the model as another layer.\n            patches = patches.reshape((-1, patches.shape[0] // f.shape[1], size, size)).dimshuffle((1, 0, 2, 3))\n            # Calculate the magnitude that we'll use for normalization at runtime, then store...\n            results.extend([patches] + self.compute_norms(T, l, patches))\n        return results\n\n    def do_match_patches(self, layer):\n        # Use node in the model to compute the result of the normalized cross-correlation, using results from the\n        # nearest-neighbor layers called 'nn3_1' and 'nn4_1'.\n        dist = self.matcher_outputs[layer]\n        dist = dist.reshape((dist.shape[1], -1))\n        # Compute the score of each patch, taking into account statistics from previous iteration. This equalizes\n        # the chances of the patches being selected when the user requests more variety.\n        offset = self.matcher_history[layer].reshape((-1, 1))\n        scores = (dist - offset * args.variety)\n        # Pick the best style patches for each patch in the current image, the result is an array of indices.\n        # Also return the maximum value along both axis, used to compare slices and add patch variety.\n        return [scores.argmax(axis=0), scores.max(axis=0), dist.max(axis=1)]\n\n\n    #------------------------------------------------------------------------------------------------------------------\n    # Error/Loss Functions\n    #------------------------------------------------------------------------------------------------------------------\n\n    def content_loss(self):\n        \"\"\"Return a list of Theano expressions for the error function, measuring how different the current image is\n        from the reference content that was loaded.\n        \"\"\"\n\n        content_loss = []\n        if args.content_weight == 0.0:\n            return content_loss\n\n        # First extract all the features we need from the model, these results after convolution.\n        extractor = theano.function([self.model.tensor_img], self.model.get_outputs('conv', self.content_layers))\n        result = extractor(self.content_img)\n\n        # Build a list of loss components that compute the mean squared error by comparing current result to desired.\n        for l, ref in zip(self.content_layers, result):\n            layer = self.model.tensor_outputs['conv'+l]\n            loss = T.mean((layer - ref) ** 2.0)\n            content_loss.append(('content', l, args.content_weight * loss))\n            print('  - Content layer conv{}: {} features in {:,}kb.'.format(l, ref.shape[1], ref.size//1000))\n        return content_loss\n\n    def style_loss(self):\n        \"\"\"Returns a list of loss components as Theano expressions. Finds the best style patch for each patch in the\n        current image using normalized cross-correlation, then computes the mean squared error for all patches.\n        \"\"\"\n        style_loss = []\n        if args.style_weight == 0.0:\n            return style_loss\n\n        # Extract the patches from the current image, as well as their magnitude.\n        result = self.do_extract_patches(zip(self.style_layers, self.model.get_outputs('conv', self.style_layers)))\n\n        # Multiple style layers are optimized separately, usually conv3_1 and conv4_1 — semantic data not used here.\n        for l, matches, patches in zip(self.style_layers, self.tensor_matches, result[0::3]):\n            # Compute the mean squared error between the current patch and the best matching style patch.\n            # Ignore the last channels (from semantic map) so errors returned are indicative of image only.\n            loss = T.mean((patches - matches[:,:self.model.channels[l]]) ** 2.0)\n            style_loss.append(('style', l, args.style_weight * loss))\n        return style_loss\n\n    def total_variation_loss(self):\n        \"\"\"Return a loss component as Theano expression for the smoothness prior on the result image.\n        \"\"\"\n        x = self.model.tensor_img\n        loss = (((x[:,:,:-1,:-1] - x[:,:,1:,:-1])**2 + (x[:,:,:-1,:-1] - x[:,:,:-1,1:])**2)**1.25).mean()\n        return [('smooth', 'img', args.smoothness * loss)]\n\n\n    #------------------------------------------------------------------------------------------------------------------\n    # Optimization Loop\n    #------------------------------------------------------------------------------------------------------------------\n\n    def iterate_batches(self, *arrays, batch_size):\n        \"\"\"Break down the data in arrays batch by batch and return them as a generator.\n        \"\"\" \n        total_size = arrays[0].shape[0]\n        indices = np.arange(total_size)\n        for index in range(0, total_size, batch_size):\n            excerpt = indices[index:index + batch_size]\n            yield excerpt, [a[excerpt] for a in arrays]\n\n    def evaluate_slices(self, f, l):\n        if args.cache and l in self.style_cache:\n            return self.style_cache[l]\n\n        layer, data = self.model.network['nn'+l], self.style_data[l]\n        history = data[-1]\n\n        best_idx, best_val = None, 0.0\n        for idx, (bp, bi, bs, bh) in self.iterate_batches(*data, batch_size=layer.num_filters):\n            weights = bp.astype(np.float32)\n            self.normalize_components(l, weights, (bi, bs))\n            layer.W.set_value(weights)\n\n            cur_idx, cur_val, cur_match = self.compute_matches[l](history[idx])\n            if best_idx is None:\n                best_idx, best_val = cur_idx, cur_val\n            else:\n                i = np.where(cur_val > best_val)\n                best_idx[i] = idx[cur_idx[i]]\n                best_val[i] = cur_val[i]\n\n            history[idx] = cur_match\n\n        if args.cache:\n            self.style_cache[l] = best_idx\n        return best_idx\n\n    def evaluate(self, Xn):\n        \"\"\"Callback for the L-BFGS optimization that computes the loss and gradients on the GPU.\n        \"\"\"\n        # Adjust the representation to be compatible with the model before computing results.\n        current_img = Xn.reshape(self.content_img.shape).astype(np.float32) - self.model.pixel_mean\n        current_features = self.compute_features(current_img, self.content_map)\n\n        # Iterate through each of the style layers one by one, computing best matches.\n        current_best = []\n        for l, f in zip(self.style_layers, current_features):\n            self.normalize_components(l, f, self.compute_norms(np, l, f))\n            self.matcher_tensors[l].set_value(f)\n\n            # Compute best matching patches this style layer, going through all slices.\n            warmup = bool(args.variety > 0.0 and self.iteration == 0)\n            for _ in range(2 if warmup else 1):\n                best_idx = self.evaluate_slices(f, l)\n\n            patches = self.style_data[l][0]\n            current_best.append(patches[best_idx].astype(np.float32))\n\n        grads, *losses = self.compute_grad_and_losses(current_img, self.content_map, *current_best)\n        if np.isnan(grads).any():\n            raise OverflowError(\"Optimization diverged; try using a different device or parameters.\")\n\n        # Use magnitude of gradients as an estimate for overall quality.\n        self.error = self.error * 0.9 + 0.1 * min(np.abs(grads).max(), 255.0)\n        loss = sum(losses)\n\n        # Dump the image to disk if requested by the user.\n        if args.save_every and self.frame % args.save_every == 0:\n            frame = Xn.reshape(self.content_img.shape[1:])\n            resolution = self.content_img_original.shape\n            image = scipy.misc.toimage(self.model.finalize_image(frame, resolution), cmin=0, cmax=255)\n            image.save('frames/%04d.png'%self.frame)\n\n        # Print more information to the console every few iterations.\n        if args.print_every and self.frame % args.print_every == 0:\n            print('{:>3}   {}loss{} {:8.2e} '.format(self.frame, ansi.BOLD, ansi.ENDC, loss / 1000.0), end='')\n            category = ''\n            for v, l in zip(losses, self.losses):\n                if l[0] == 'smooth':\n                    continue\n                if l[0] != category:\n                    print('  {}{}{}'.format(ansi.BOLD, l[0], ansi.ENDC), end='')\n                    category = l[0]\n                print(' {}{}{} {:8.2e} '.format(ansi.BOLD, l[1], ansi.ENDC, v / 1000.0), end='')\n\n            current_time = time.time()\n            quality = 100.0 - 100.0 * np.sqrt(self.error / 255.0)\n            print('  {}quality{} {: >4.1f}% '.format(ansi.BOLD, ansi.ENDC, quality), end='')\n            print('  {}time{} {:3.1f}s '.format(ansi.BOLD, ansi.ENDC, current_time - self.iter_time), flush=True)\n            self.iter_time = current_time\n\n        # Update counters and timers.\n        self.frame += 1\n        self.iteration += 1\n\n        # Return the data in the right format for L-BFGS.\n        return loss, np.array(grads).flatten().astype(np.float64)\n\n    def run(self):\n        \"\"\"The main entry point for the application, runs through multiple phases at increasing resolutions.\n        \"\"\"\n        self.frame, Xn = 0, None\n        for i in range(args.phases):\n            self.error = 255.0\n            scale = 1.0 / 2.0 ** (args.phases - 1 - i)\n\n            shape = self.content_img_original.shape\n            print('\\n{}Phase #{}: resolution {}x{}  scale {}{}'\\\n                    .format(ansi.BLUE_B, i, int(shape[1]*scale), int(shape[0]*scale), scale, ansi.BLUE))\n\n            # Precompute all necessary data for the various layers, put patches in place into augmented network.\n            self.model.setup(layers=['sem'+l for l in self.style_layers] + ['conv'+l for l in self.content_layers])\n            self.prepare_content(scale)\n            self.prepare_style(scale)\n\n            # Now setup the model with the new data, ready for the optimization loop.\n            self.model.setup(layers=['sem'+l for l in self.style_layers] + ['conv'+l for l in self.used_layers])\n            self.prepare_optimization()\n            print('{}'.format(ansi.ENDC))\n\n            # Setup the seed for the optimization as specified by the user.\n            shape = self.content_img.shape[2:]\n            if args.seed == 'content':\n                Xn = self.content_img[0] + self.model.pixel_mean\n            if args.seed == 'noise':\n                bounds = [int(i) for i in args.seed_range.split(':')]\n                Xn = np.random.uniform(bounds[0], bounds[1], shape + (3,)).astype(np.float32)\n            if args.seed == 'previous':\n                Xn = scipy.misc.imresize(Xn[0], shape, interp='bicubic')\n                Xn = Xn.transpose((2, 0, 1))[np.newaxis]\n            if os.path.exists(args.seed):\n                seed_image = scipy.ndimage.imread(args.seed, mode='RGB')\n                seed_image = scipy.misc.imresize(seed_image, shape, interp='bicubic')\n                self.seed_image = self.model.prepare_image(seed_image)\n                Xn = self.seed_image[0] + self.model.pixel_mean\n            if Xn is None:\n                error(\"Seed for optimization was not found. You can either...\",\n                      \"  - Set the `--seed` to `content` or `noise`.\", \"  - Specify `--seed` as a valid filename.\")\n\n            # Optimization algorithm needs min and max bounds to prevent divergence.\n            data_bounds = np.zeros((np.product(Xn.shape), 2), dtype=np.float64)\n            data_bounds[:] = (0.0, 255.0)\n\n            self.iter_time, self.iteration, interrupt = time.time(), 0, False\n            try:\n                Xn, Vn, info = scipy.optimize.fmin_l_bfgs_b(\n                                self.evaluate,\n                                Xn.astype(np.float64).flatten(),\n                                bounds=data_bounds,\n                                factr=0.0, pgtol=0.0,            # Disable automatic termination, set low threshold.\n                                m=5,                             # Maximum correlations kept in memory by algorithm.\n                                maxfun=args.iterations-1,        # Limit number of calls to evaluate().\n                                iprint=-1)                       # Handle our own logging of information.\n            except OverflowError:\n                error(\"The optimization diverged and NaNs were encountered.\",\n                      \"  - Try using a different `--device` or change the parameters.\",\n                      \"  - Make sure libraries are updated to work around platform bugs.\")\n            except KeyboardInterrupt:\n                interrupt = True\n\n            args.seed = 'previous'\n            resolution = self.content_img.shape\n            Xn = Xn.reshape(resolution)\n\n            output = self.model.finalize_image(Xn[0], self.content_img_original.shape)\n            scipy.misc.toimage(output, cmin=0, cmax=255).save(args.output)\n            if interrupt: break\n\n        status = \"finished in\" if not interrupt else \"interrupted at\"\n        print('\\n{}Optimization {} {:3.1f}s, average pixel error {:3.1f}!{}\\n'\\\n              .format(ansi.CYAN, status, time.time() - self.start_time, self.error, ansi.ENDC))\n\n\nif __name__ == \"__main__\":\n    generator = NeuralGenerator()\n    generator.run()\n"
  },
  {
    "path": "requirements.txt",
    "content": "colorama\npillow>=3.2.0\nTheano>=0.8.1\ngit+https://github.com/Lasagne/Lasagne.git@0440814#egg=Lasagne==0.2-dev\n"
  }
]