[
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://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 General Public License is a free, copyleft license for\nsoftware and other kinds of works.\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,\nthe GNU General Public License is 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.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\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  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\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 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. Use with the GNU Affero General Public License.\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 Affero 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 special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe 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 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 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 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 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 General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\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 GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Video-Auto-Wipe\nIf you are interested in AIGC application tools, you can learn a bit about it on [this blog](https://www.seeprettyface.com/).<br />\n--------------------------------------------------------------------------------------------------<br /><br />\n\nErase the fixed-pattern content you don't want to see in your video. This project shares a model for subtitle removal and demonstrates the effectiveness of erasing content with easily recognizable patterns, such as subtitles, logos, and animated icons.<br /><br />\n\n# 效果预览\n## 1. 字幕擦除\n![Image text](https://github.com/a312863063/Video-Auto-Wipe/blob/main/pics/de-text/detext_9_ko.JPG)<br/>\n<p align=\"center\"><a href='http://www.seeprettyface.com/mp4/video-inpainting/detext_06.mp4' target='_blank'>查看视频</a></p><br/>\n&emsp;&emsp;字幕擦除模型的功能是模型自动感知到视频中字幕的位置然后进行擦除，感知字幕的方法为具有统一样式的文字区域被视作字幕。<br/>\n<br/><br/>\n\n## 2. 图标擦除\n![Image text](https://github.com/a312863063/Video-Auto-Wipe/blob/main/pics/de-logo/delogo_4.JPG)<br/>\n<p align=\"center\"><a href='http://www.seeprettyface.com/mp4/video-inpainting/delogo_04.mp4' target='_blank'>查看视频</a></p><br/>\n&emsp;&emsp;图标擦除模型的功能是模型自动感知到视频中图标的位置然后进行擦除，感知图标的方法为在时域上静止不动的像素块被视作图标。<br/>\n<br/><br/>\n\n## 3. 动态图标擦除\n![Image text](https://github.com/a312863063/Video-Auto-Wipe/blob/main/pics/de-dynamic-logo/de-dynamic-logo_1.JPG)<br/>\n<p align=\"center\"><a href='http://www.seeprettyface.com/mp4/video-inpainting/de_dynamic_logo.mp4' target='_blank'>查看视频</a></p><br/>\n&emsp;&emsp;动态图标擦除模型的功能是模型自动感知到视频中动态图标的位置然后进行擦除，感知动态图标的方法为在时域上闪烁出现或动态移动的固定像素块被视作动态图标。<br/>\n<br/><br/>\n\n# 使用方法\n### 1.环境配置\n&emsp;&emsp;torch>1.0<br/>\n&emsp;&emsp;其他的缺什么依赖就pip install xxx，需要的东西不多<br/><br/>\n\n### 2.运行方法\n&emsp;&emsp;下载预训练文件放在pretrained-weight文件夹里。<br/>\n&emsp;&emsp;&emsp;&emsp;预训练模型下载地址：链接：https://pan.baidu.com/s/1JN9-8Glw_ozOrSMgBIyHOw 提取码：px0s <br/> <br/>\n&emsp;&emsp;更多的输入样例下载地址：https://pan.baidu.com/s/1_tzmvIoEQi3h_24-ieZJ_Q 提取码：cnqf <br/><br/>\n&emsp;&emsp;运行```python demo.py```。<br/><br/><br/><br/>\n\n# 训练方法\n## 训练数据\n### 背景数据制作\n&emsp;&emsp;1.基于搜集的300余部高清电影制作了2,709部电影片段数据集；<br/>\n&emsp;&emsp;&emsp;&emsp;下载地址：https://pan.baidu.com/s/1CIgJmFmx5iR2JfgAyjVaeg  提取码：xb7o <br/><br/>\n&emsp;&emsp;2.基于搜集的40余部综艺节目制作了864部综艺片段数据集；<br/>\n&emsp;&emsp;&emsp;&emsp;下载地址：https://pan.baidu.com/s/1lJk6IIWlwxknAie0LlGYOg  提取码：9rd4 <br/><br/>\n\n### 前景数据制作\n&emsp;&emsp;1.字幕擦除：利用ImageDraw库生成随机样式、字体的文字，并模拟其变换；<br/>\n&emsp;&emsp;2.图标擦除：利用ImageDraw库生成随机的像素区块，并模拟时域一致性（固定在视频中的某一个区域）；<br/>\n&emsp;&emsp;3.动态图标擦除：利用PR软件制作闪烁、跳跃等字幕的动态特效，模拟动态图标的场景。<br/>\n<br/>\n### 训练过程\n&emsp;&emsp;第1步. 针对特定任务的时域感知训练，即让模型能感知到需被擦除的前景数据；<br/>\n&emsp;&emsp;第2步. 融合进擦除模型，进行端到端的微调训练。<br/>\n<br/><br/><br/>\n\n# 后续计划\n![Image text](https://github.com/a312863063/Video-Auto-Wipe/blob/main/pics/undo.png)<br/>\n&emsp;&emsp;后续我想实现广告、人物和敏感内容擦除等方向。填补技术效果已经不错了，难点在于感知。图标感知可以利用区域一致性实现，字幕感知可以利用模式一致性实现。人物感知要如何实现？广告感知要如何实现？这种设计不能有缺漏，估计得<b>结合数据本身的规律</b>去做才行。。\n<br/><br/>\n"
  },
  {
    "path": "core/spectral_norm.py",
    "content": "\"\"\"\nSpectral Normalization from https://arxiv.org/abs/1802.05957\n\"\"\"\nimport torch\nfrom torch.nn.functional import normalize\n\n\nclass SpectralNorm(object):\n    # Invariant before and after each forward call:\n    #   u = normalize(W @ v)\n    # NB: At initialization, this invariant is not enforced\n\n    _version = 1\n    # At version 1:\n    #   made  `W` not a buffer,\n    #   added `v` as a buffer, and\n    #   made eval mode use `W = u @ W_orig @ v` rather than the stored `W`.\n\n    def __init__(self, name='weight', n_power_iterations=1, dim=0, eps=1e-12):\n        self.name = name\n        self.dim = dim\n        if n_power_iterations <= 0:\n            raise ValueError('Expected n_power_iterations to be positive, but '\n                             'got n_power_iterations={}'.format(n_power_iterations))\n        self.n_power_iterations = n_power_iterations\n        self.eps = eps\n\n    def reshape_weight_to_matrix(self, weight):\n        weight_mat = weight\n        if self.dim != 0:\n            # permute dim to front\n            weight_mat = weight_mat.permute(self.dim,\n                                            *[d for d in range(weight_mat.dim()) if d != self.dim])\n        height = weight_mat.size(0)\n        return weight_mat.reshape(height, -1)\n\n    def compute_weight(self, module, do_power_iteration):\n        # NB: If `do_power_iteration` is set, the `u` and `v` vectors are\n        #     updated in power iteration **in-place**. This is very important\n        #     because in `DataParallel` forward, the vectors (being buffers) are\n        #     broadcast from the parallelized module to each module replica,\n        #     which is a new module object created on the fly. And each replica\n        #     runs its own spectral norm power iteration. So simply assigning\n        #     the updated vectors to the module this function runs on will cause\n        #     the update to be lost forever. And the next time the parallelized\n        #     module is replicated, the same randomly initialized vectors are\n        #     broadcast and used!\n        #\n        #     Therefore, to make the change propagate back, we rely on two\n        #     important behaviors (also enforced via tests):\n        #       1. `DataParallel` doesn't clone storage if the broadcast tensor\n        #          is already on correct device; and it makes sure that the\n        #          parallelized module is already on `device[0]`.\n        #       2. If the out tensor in `out=` kwarg has correct shape, it will\n        #          just fill in the values.\n        #     Therefore, since the same power iteration is performed on all\n        #     devices, simply updating the tensors in-place will make sure that\n        #     the module replica on `device[0]` will update the _u vector on the\n        #     parallized module (by shared storage).\n        #\n        #    However, after we update `u` and `v` in-place, we need to **clone**\n        #    them before using them to normalize the weight. This is to support\n        #    backproping through two forward passes, e.g., the common pattern in\n        #    GAN training: loss = D(real) - D(fake). Otherwise, engine will\n        #    complain that variables needed to do backward for the first forward\n        #    (i.e., the `u` and `v` vectors) are changed in the second forward.\n        weight = getattr(module, self.name + '_orig')\n        u = getattr(module, self.name + '_u')\n        v = getattr(module, self.name + '_v')\n        weight_mat = self.reshape_weight_to_matrix(weight)\n\n        if do_power_iteration:\n            with torch.no_grad():\n                for _ in range(self.n_power_iterations):\n                    # Spectral norm of weight equals to `u^T W v`, where `u` and `v`\n                    # are the first left and right singular vectors.\n                    # This power iteration produces approximations of `u` and `v`.\n                    v = normalize(torch.mv(weight_mat.t(), u), dim=0, eps=self.eps, out=v)\n                    u = normalize(torch.mv(weight_mat, v), dim=0, eps=self.eps, out=u)\n                if self.n_power_iterations > 0:\n                    # See above on why we need to clone\n                    u = u.clone()\n                    v = v.clone()\n\n        sigma = torch.dot(u, torch.mv(weight_mat, v))\n        weight = weight / sigma\n        return weight\n\n    def remove(self, module):\n        with torch.no_grad():\n            weight = self.compute_weight(module, do_power_iteration=False)\n        delattr(module, self.name)\n        delattr(module, self.name + '_u')\n        delattr(module, self.name + '_v')\n        delattr(module, self.name + '_orig')\n        module.register_parameter(self.name, torch.nn.Parameter(weight.detach()))\n\n    def __call__(self, module, inputs):\n        setattr(module, self.name, self.compute_weight(module, do_power_iteration=module.training))\n\n    def _solve_v_and_rescale(self, weight_mat, u, target_sigma):\n        # Tries to returns a vector `v` s.t. `u = normalize(W @ v)`\n        # (the invariant at top of this class) and `u @ W @ v = sigma`.\n        # This uses pinverse in case W^T W is not invertible.\n        v = torch.chain_matmul(weight_mat.t().mm(weight_mat).pinverse(), weight_mat.t(), u.unsqueeze(1)).squeeze(1)\n        return v.mul_(target_sigma / torch.dot(u, torch.mv(weight_mat, v)))\n\n    @staticmethod\n    def apply(module, name, n_power_iterations, dim, eps):\n        for k, hook in module._forward_pre_hooks.items():\n            if isinstance(hook, SpectralNorm) and hook.name == name:\n                raise RuntimeError(\"Cannot register two spectral_norm hooks on \"\n                                   \"the same parameter {}\".format(name))\n\n        fn = SpectralNorm(name, n_power_iterations, dim, eps)\n        weight = module._parameters[name]\n\n        with torch.no_grad():\n            weight_mat = fn.reshape_weight_to_matrix(weight)\n\n            h, w = weight_mat.size()\n            # randomly initialize `u` and `v`\n            u = normalize(weight.new_empty(h).normal_(0, 1), dim=0, eps=fn.eps)\n            v = normalize(weight.new_empty(w).normal_(0, 1), dim=0, eps=fn.eps)\n\n        delattr(module, fn.name)\n        module.register_parameter(fn.name + \"_orig\", weight)\n        # We still need to assign weight back as fn.name because all sorts of\n        # things may assume that it exists, e.g., when initializing weights.\n        # However, we can't directly assign as it could be an nn.Parameter and\n        # gets added as a parameter. Instead, we register weight.data as a plain\n        # attribute.\n        setattr(module, fn.name, weight.data)\n        module.register_buffer(fn.name + \"_u\", u)\n        module.register_buffer(fn.name + \"_v\", v)\n\n        module.register_forward_pre_hook(fn)\n\n        module._register_state_dict_hook(SpectralNormStateDictHook(fn))\n        module._register_load_state_dict_pre_hook(SpectralNormLoadStateDictPreHook(fn))\n        return fn\n\n\n# This is a top level class because Py2 pickle doesn't like inner class nor an\n# instancemethod.\nclass SpectralNormLoadStateDictPreHook(object):\n    # See docstring of SpectralNorm._version on the changes to spectral_norm.\n    def __init__(self, fn):\n        self.fn = fn\n\n    # For state_dict with version None, (assuming that it has gone through at\n    # least one training forward), we have\n    #\n    #    u = normalize(W_orig @ v)\n    #    W = W_orig / sigma, where sigma = u @ W_orig @ v\n    #\n    # To compute `v`, we solve `W_orig @ x = u`, and let\n    #    v = x / (u @ W_orig @ x) * (W / W_orig).\n    def __call__(self, state_dict, prefix, local_metadata, strict,\n                 missing_keys, unexpected_keys, error_msgs):\n        fn = self.fn\n        version = local_metadata.get('spectral_norm', {}).get(fn.name + '.version', None)\n        if version is None or version < 1:\n            with torch.no_grad():\n                weight_orig = state_dict[prefix + fn.name + '_orig']\n                # weight = state_dict.pop(prefix + fn.name)\n                # sigma = (weight_orig / weight).mean()\n                weight_mat = fn.reshape_weight_to_matrix(weight_orig)\n                u = state_dict[prefix + fn.name + '_u']\n                # v = fn._solve_v_and_rescale(weight_mat, u, sigma)\n                # state_dict[prefix + fn.name + '_v'] = v\n\n\n# This is a top level class because Py2 pickle doesn't like inner class nor an\n# instancemethod.\nclass SpectralNormStateDictHook(object):\n    # See docstring of SpectralNorm._version on the changes to spectral_norm.\n    def __init__(self, fn):\n        self.fn = fn\n\n    def __call__(self, module, state_dict, prefix, local_metadata):\n        if 'spectral_norm' not in local_metadata:\n            local_metadata['spectral_norm'] = {}\n        key = self.fn.name + '.version'\n        if key in local_metadata['spectral_norm']:\n            raise RuntimeError(\"Unexpected key in metadata['spectral_norm']: {}\".format(key))\n        local_metadata['spectral_norm'][key] = self.fn._version\n\n\ndef spectral_norm(module, name='weight', n_power_iterations=1, eps=1e-12, dim=None):\n    r\"\"\"Applies spectral normalization to a parameter in the given module.\n\n    .. math::\n        \\mathbf{W}_{SN} = \\dfrac{\\mathbf{W}}{\\sigma(\\mathbf{W})},\n        \\sigma(\\mathbf{W}) = \\max_{\\mathbf{h}: \\mathbf{h} \\ne 0} \\dfrac{\\|\\mathbf{W} \\mathbf{h}\\|_2}{\\|\\mathbf{h}\\|_2}\n\n    Spectral normalization stabilizes the training of discriminators (critics)\n    in Generative Adversarial Networks (GANs) by rescaling the weight tensor\n    with spectral norm :math:`\\sigma` of the weight matrix calculated using\n    power iteration method. If the dimension of the weight tensor is greater\n    than 2, it is reshaped to 2D in power iteration method to get spectral\n    norm. This is implemented via a hook that calculates spectral norm and\n    rescales weight before every :meth:`~Module.forward` call.\n\n    See `Spectral Normalization for Generative Adversarial Networks`_ .\n\n    .. _`Spectral Normalization for Generative Adversarial Networks`: https://arxiv.org/abs/1802.05957\n\n    Args:\n        module (nn.Module): containing module\n        name (str, optional): name of weight parameter\n        n_power_iterations (int, optional): number of power iterations to\n            calculate spectral norm\n        eps (float, optional): epsilon for numerical stability in\n            calculating norms\n        dim (int, optional): dimension corresponding to number of outputs,\n            the default is ``0``, except for modules that are instances of\n            ConvTranspose{1,2,3}d, when it is ``1``\n\n    Returns:\n        The original module with the spectral norm hook\n\n    Example::\n\n        >>> m = spectral_norm(nn.Linear(20, 40))\n        >>> m\n        Linear(in_features=20, out_features=40, bias=True)\n        >>> m.weight_u.size()\n        torch.Size([40])\n\n    \"\"\"\n    if dim is None:\n        if isinstance(module, (torch.nn.ConvTranspose1d,\n                               torch.nn.ConvTranspose2d,\n                               torch.nn.ConvTranspose3d)):\n            dim = 1\n        else:\n            dim = 0\n    SpectralNorm.apply(module, name, n_power_iterations, dim, eps)\n    return module\n\n\ndef remove_spectral_norm(module, name='weight'):\n    r\"\"\"Removes the spectral normalization reparameterization from a module.\n\n    Args:\n        module (Module): containing module\n        name (str, optional): name of weight parameter\n\n    Example:\n        >>> m = spectral_norm(nn.Linear(40, 10))\n        >>> remove_spectral_norm(m)\n    \"\"\"\n    for k, hook in module._forward_pre_hooks.items():\n        if isinstance(hook, SpectralNorm) and hook.name == name:\n            hook.remove(module)\n            del module._forward_pre_hooks[k]\n            return module\n\n    raise ValueError(\"spectral_norm of '{}' not found in {}\".format(\n        name, module))\n\n\ndef use_spectral_norm(module, use_sn=False):\n    if use_sn:\n        return spectral_norm(module)\n    return module"
  },
  {
    "path": "core/utils.py",
    "content": "import matplotlib.patches as patches\nfrom matplotlib.path import Path\nimport os\nimport sys\nimport io\nimport cv2\nimport time\nimport argparse\nimport shutil\nimport random\nimport zipfile\nfrom glob import glob\nimport math\nimport numpy as np\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nfrom PIL import Image, ImageOps, ImageDraw, ImageFilter\n\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torch.distributed as dist\n\nimport matplotlib\nfrom matplotlib import pyplot as plt\nmatplotlib.use('agg')\n\n\n# #####################################################\n# #####################################################\n\nclass ZipReader(object):\n    file_dict = dict()\n\n    def __init__(self):\n        super(ZipReader, self).__init__()\n\n    @staticmethod\n    def build_file_dict(path):\n        file_dict = ZipReader.file_dict\n        if path in file_dict:\n            return file_dict[path]\n        else:\n            file_handle = zipfile.ZipFile(path, 'r')\n            file_dict[path] = file_handle\n            return file_dict[path]\n\n    @staticmethod\n    def imread(path, idx):\n        zfile = ZipReader.build_file_dict(path)\n        znames = zfile.namelist()\n        znames.sort()\n        data = zfile.read(znames[idx])\n        im = Image.open(io.BytesIO(data))\n        return im\n\n# ###########################################################################\n# ###########################################################################\n\n\nclass GroupRandomHorizontalFlip(object):\n    \"\"\"Randomly horizontally flips the given PIL.Image with a probability of 0.5\n    \"\"\"\n\n    def __init__(self, is_flow=False):\n        self.is_flow = is_flow\n\n    def __call__(self, img_group, is_flow=False):\n        v = random.random()\n        if v < 0.5:\n            ret = [img.transpose(Image.FLIP_LEFT_RIGHT) for img in img_group]\n            if self.is_flow:\n                for i in range(0, len(ret), 2):\n                    # invert flow pixel values when flipping\n                    ret[i] = ImageOps.invert(ret[i])\n            return ret\n        else:\n            return img_group\n\n\nclass Stack(object):\n    def __init__(self, roll=False):\n        self.roll = roll\n\n    def __call__(self, img_group):\n        for i in range(len(img_group)):\n            if img_group[i].ndim==3:\n                img_group[i] = Image.fromarray(cv2.cvtColor(img_group[i], cv2.COLOR_BGR2RGB))\n            elif img_group[i].ndim==2:\n                img_group[i] = Image.fromarray(img_group[i])\n\n        mode = img_group[0].mode\n        if mode == '1':\n            img_group = [img.convert('L') for img in img_group]\n            mode = 'L'\n        if mode == 'L':\n            return np.stack([np.expand_dims(x, 2) for x in img_group], axis=2)\n        elif mode == 'RGB':\n            if self.roll:\n                return np.stack([np.array(x)[:, :, ::-1] for x in img_group], axis=2)\n            else:\n                return np.stack(img_group, axis=2)\n        else:\n            raise NotImplementedError(f\"Image mode {mode}\")\n\n\nclass ToTorchFormatTensor(object):\n    \"\"\" Converts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255]\n    to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] \"\"\"\n\n    def __init__(self, div=True):\n        self.div = div\n\n    def __call__(self, pic):\n        if isinstance(pic, np.ndarray):\n            # numpy img: [L, C, H, W]\n            img = torch.from_numpy(pic).permute(2, 3, 0, 1).contiguous()\n        else:\n            # handle PIL Image\n            img = torch.ByteTensor(\n                torch.ByteStorage.from_buffer(pic.tobytes()))\n            img = img.view(pic.size[1], pic.size[0], len(pic.mode))\n            # put it from HWC to CHW format\n            # yikes, this transpose takes 80% of the loading time/CPU\n            img = img.transpose(0, 1).transpose(0, 2).contiguous()\n        img = img.float().div(255) if self.div else img.float()\n        return img\n\n\n# ##########################################\n# ##########################################\n\ndef create_random_shape_with_random_motion(video_length, imageHeight=240, imageWidth=432):\n    # get a random shape\n    height = random.randint(imageHeight//3, imageHeight-1)\n    width = random.randint(imageWidth//3, imageWidth-1)\n    edge_num = random.randint(6, 8)\n    ratio = random.randint(6, 8)/10\n    region = get_random_shape(\n        edge_num=edge_num, ratio=ratio, height=height, width=width)\n    region_width, region_height = region.size\n    # get random position\n    x, y = random.randint(\n        0, imageHeight-region_height), random.randint(0, imageWidth-region_width)\n    velocity = get_random_velocity(max_speed=3)\n    m = Image.fromarray(np.zeros((imageHeight, imageWidth)).astype(np.uint8))\n    m.paste(region, (y, x, y+region.size[0], x+region.size[1]))\n    masks = [m.convert('L')]\n    # return fixed masks\n    if random.uniform(0, 1) > 0.5:\n        return masks*video_length\n    # return moving masks\n    for _ in range(video_length-1):\n        x, y, velocity = random_move_control_points(\n            x, y, imageHeight, imageWidth, velocity, region.size, maxLineAcceleration=(3, 0.5), maxInitSpeed=3)\n        m = Image.fromarray(\n            np.zeros((imageHeight, imageWidth)).astype(np.uint8))\n        m.paste(region, (y, x, y+region.size[0], x+region.size[1]))\n        masks.append(m.convert('L'))\n    return masks\n\n\ndef get_random_shape(edge_num=9, ratio=0.7, width=432, height=240):\n    '''\n      There is the initial point and 3 points per cubic bezier curve. \n      Thus, the curve will only pass though n points, which will be the sharp edges.\n      The other 2 modify the shape of the bezier curve.\n      edge_num, Number of possibly sharp edges\n      points_num, number of points in the Path\n      ratio, (0, 1) magnitude of the perturbation from the unit circle, \n    '''\n    points_num = edge_num*3 + 1\n    angles = np.linspace(0, 2*np.pi, points_num)\n    codes = np.full(points_num, Path.CURVE4)\n    codes[0] = Path.MOVETO\n    # Using this instad of Path.CLOSEPOLY avoids an innecessary straight line\n    verts = np.stack((np.cos(angles), np.sin(angles))).T * \\\n        (2*ratio*np.random.random(points_num)+1-ratio)[:, None]\n    verts[-1, :] = verts[0, :]\n    path = Path(verts, codes)\n    # draw paths into images\n    fig = plt.figure()\n    ax = fig.add_subplot(111)\n    patch = patches.PathPatch(path, facecolor='black', lw=2)\n    ax.add_patch(patch)\n    ax.set_xlim(np.min(verts)*1.1, np.max(verts)*1.1)\n    ax.set_ylim(np.min(verts)*1.1, np.max(verts)*1.1)\n    ax.axis('off')  # removes the axis to leave only the shape\n    fig.canvas.draw()\n    # convert plt images into numpy images\n    data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)\n    data = data.reshape((fig.canvas.get_width_height()[::-1] + (3,)))\n    plt.close(fig)\n    # postprocess\n    data = cv2.resize(data, (width, height))[:, :, 0]\n    data = (1 - np.array(data > 0).astype(np.uint8))*255\n    corrdinates = np.where(data > 0)\n    xmin, xmax, ymin, ymax = np.min(corrdinates[0]), np.max(\n        corrdinates[0]), np.min(corrdinates[1]), np.max(corrdinates[1])\n    region = Image.fromarray(data).crop((ymin, xmin, ymax, xmax))\n    return region\n\n\ndef random_accelerate(velocity, maxAcceleration, dist='uniform'):\n    speed, angle = velocity\n    d_speed, d_angle = maxAcceleration\n    if dist == 'uniform':\n        speed += np.random.uniform(-d_speed, d_speed)\n        angle += np.random.uniform(-d_angle, d_angle)\n    elif dist == 'guassian':\n        speed += np.random.normal(0, d_speed / 2)\n        angle += np.random.normal(0, d_angle / 2)\n    else:\n        raise NotImplementedError(\n            f'Distribution type {dist} is not supported.')\n    return (speed, angle)\n\n\ndef get_random_velocity(max_speed=3, dist='uniform'):\n    if dist == 'uniform':\n        speed = np.random.uniform(max_speed)\n    elif dist == 'guassian':\n        speed = np.abs(np.random.normal(0, max_speed / 2))\n    else:\n        raise NotImplementedError(\n            f'Distribution type {dist} is not supported.')\n    angle = np.random.uniform(0, 2 * np.pi)\n    return (speed, angle)\n\n\ndef random_move_control_points(X, Y, imageHeight, imageWidth, lineVelocity, region_size, maxLineAcceleration=(3, 0.5), maxInitSpeed=3):\n    region_width, region_height = region_size\n    speed, angle = lineVelocity\n    X += int(speed * np.cos(angle))\n    Y += int(speed * np.sin(angle))\n    lineVelocity = random_accelerate(\n        lineVelocity, maxLineAcceleration, dist='guassian')\n    if ((X > imageHeight - region_height) or (X < 0) or (Y > imageWidth - region_width) or (Y < 0)):\n        lineVelocity = get_random_velocity(maxInitSpeed, dist='guassian')\n    new_X = np.clip(X, 0, imageHeight - region_height)\n    new_Y = np.clip(Y, 0, imageWidth - region_width)\n    return new_X, new_Y, lineVelocity\n\n\n\n# ##############################################\n# ##############################################\n\nif __name__ == '__main__':\n\n    trials = 10\n    for _ in range(trials):\n        video_length = 10\n        # The returned masks are either stationary (50%) or moving (50%)\n        masks = create_random_shape_with_random_motion(\n            video_length, imageHeight=240, imageWidth=432)\n        print(np.array(masks[0]).shape)\n\n        for m in masks:\n            cv2.imshow('mask', np.array(m))\n            cv2.waitKey(500)\n\n"
  },
  {
    "path": "demo.py",
    "content": "# -*- coding: utf-8 -*-\n'''\nCopyright: Copyright(c) 2018, seeprettyface.com, BUPT_GWY contributes the model.\nThanks to STTN provider: https://github.com/researchmm/STTN\nAuthor: BUPT_GWY\nContact: a312863063@126.com\n'''\nimport cv2\nimport numpy as np\nimport importlib\nimport argparse\nimport sys\nimport torch\nimport os\nfrom torchvision import transforms\n\n# My libs\nfrom core.utils import Stack, ToTorchFormatTensor\n\nparser = argparse.ArgumentParser(description=\"STTN\")\n\nparser.add_argument(\"-t\", \"--task\", type=str, help='CHOOSE THE TASK：delogo or detext', default='detext')\nparser.add_argument(\"-v\", \"--video\", type=str, default='input/detext_examples/chinese1.mp4')\nparser.add_argument(\"-m\", \"--mask\",  type=str, default='input/detext_examples/mask/chinese1_mask.png')\nparser.add_argument(\"-r\", \"--result\",  type=str, default='result/')\nparser.add_argument(\"-d\", \"--dual\",  type=bool, default=False, help='Whether to display the original video in the final video')\nparser.add_argument(\"-w\", \"--weight\",   type=str, default='pretrained_weight/detext_trial.pth')\n\nparser.add_argument(\"--model\", type=str, default='auto-sttn')\nparser.add_argument(\"-g\", \"--gap\",   type=int, default=200, help='set it higher and get result better')\nparser.add_argument(\"-l\", \"--ref_length\",   type=int, default=5)\nparser.add_argument(\"-n\", \"--neighbor_stride\",   type=int, default=5)\n\nargs = parser.parse_args()\n\n_to_tensors = transforms.Compose([\n    Stack(),\n    ToTorchFormatTensor()])\n\ndef read_frame_info_from_video(vname):\n    reader = cv2.VideoCapture(vname)\n    if not reader.isOpened():\n        print(\"fail to open video in {}\".format(args.input))\n        sys.exit(1)\n    frame_info = {}\n    frame_info['W_ori'] = int(reader.get(cv2.CAP_PROP_FRAME_WIDTH) + 0.5)\n    frame_info['H_ori'] = int(reader.get(cv2.CAP_PROP_FRAME_HEIGHT) + 0.5)\n    frame_info['fps'] = reader.get(cv2.CAP_PROP_FPS)\n    frame_info['len'] = int(reader.get(cv2.CAP_PROP_FRAME_COUNT) + 0.5)\n    return reader, frame_info\n\ndef read_mask(path):\n    img = cv2.imread(path, 0)\n    ret, img = cv2.threshold(img, 127, 1, cv2.THRESH_BINARY)\n    img = img[:, :, None]\n    return img\n\n# sample reference frames from the whole video\ndef get_ref_index(neighbor_ids, length):\n    ref_index = []\n    for i in range(0, length, args.ref_length):\n        if not i in neighbor_ids:\n            ref_index.append(i)\n    return ref_index\n\ndef pre_process(task):\n    print('Task: ', task)\n    device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n    net = importlib.import_module('model.' + args.model)\n    model = net.InpaintGenerator().to(device)\n    data = torch.load(args.weight, map_location=device)\n    model.load_state_dict(data['netG'])\n    model.eval()\n    print('Loading weight from: {}'.format(args.weight))\n\n    # prepare dataset, encode all frames into deep space\n    reader, frame_info = read_frame_info_from_video(args.video)\n    if not os.path.exists(args.result):\n        os.makedirs(args.result)\n    video_base_name = os.path.join(args.result, os.path.basename(args.video).rsplit('.', 1)[0])\n    video_name = f\"{video_base_name}_{task}.mp4\"\n    video_H = frame_info['H_ori'] if not args.dual else frame_info['H_ori'] * 2\n    writer = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*\"mp4v\"), frame_info['fps'], (frame_info['W_ori'], video_H))\n    print('Loading video from: {}'.format(args.video))\n    print('Loading mask from: {}'.format(args.mask))\n    print('--------------------------------------')\n\n    clip_gap = args.gap  # processing how many frames during one period\n    rec_time = frame_info['len'] // clip_gap if frame_info['len'] % clip_gap == 0 else frame_info['len'] // clip_gap + 1\n    mask = read_mask(args.mask)\n    return clip_gap, device, frame_info, mask, model, reader, rec_time, video_name, writer\n\ndef process(frames, model, device, w, h):\n    video_length = len(frames)\n    feats = _to_tensors(frames).unsqueeze(0) * 2 - 1\n\n    feats = feats.to(device)\n    comp_frames = [None] * video_length\n\n    with torch.no_grad():\n        feats = model.encoder(feats.view(video_length, 3, h, w))\n        _, c, feat_h, feat_w = feats.size()\n        feats = feats.view(1, video_length, c, feat_h, feat_w)\n\n    # completing holes by spatial-temporal transformers\n    for f in range(0, video_length, args.neighbor_stride):\n        neighbor_ids = [i for i in range(max(0, f - args.neighbor_stride), min(video_length, f + args.neighbor_stride + 1))]\n        ref_ids = get_ref_index(neighbor_ids, video_length)\n        with torch.no_grad():\n            pred_feat = model.infer(\n                feats[0, neighbor_ids + ref_ids, :, :, :])\n            pred_img = torch.tanh(model.decoder(\n                pred_feat[:len(neighbor_ids), :, :, :])).detach()\n            pred_img = (pred_img + 1) / 2\n            pred_img = pred_img.cpu().permute(0, 2, 3, 1).numpy() * 255\n            for i in range(len(neighbor_ids)):\n                idx = neighbor_ids[i]\n                img = np.array(pred_img[i]).astype(\n                    np.uint8)\n                if comp_frames[idx] is None:\n                    comp_frames[idx] = img\n                else:\n                    comp_frames[idx] = comp_frames[idx].astype(\n                        np.float32) * 0.5 + img.astype(np.float32) * 0.5\n    return comp_frames\n\ndef get_inpaint_mode_for_detext(H, h, mask):  # get inpaint segment\n    mode = []\n    to_H = from_H = H   # the subtitles are usually underneath\n    while from_H != 0:\n        if to_H - h < 0:\n            from_H = 0\n            to_H = h\n        else:\n            from_H = to_H - h\n        if not np.all(mask[from_H:to_H, :] == 0) and np.sum(mask[from_H:to_H, :]) > 10:\n            if to_H != H:\n                move = 0\n                while to_H + move < H and not np.all(mask[to_H+move, :] == 0):\n                    move += 1\n                if to_H + move < H and move < h:\n                    to_H += move\n                    from_H += move\n            mode.append((from_H, to_H))\n        to_H -= h\n    return mode\n\ndef main():  # detext\n    # set up models\n    w, h = 640, 120\n    clip_gap, device, frame_info, mask, model, reader, rec_time, video_name, writer = pre_process(args.task)\n\n    split_h = int(frame_info['W_ori'] * 3 / 16)\n    mode = get_inpaint_mode_for_detext(frame_info['H_ori'], split_h, mask)\n\n    for i in range(rec_time):\n        start_f = i * clip_gap\n        end_f = min((i + 1) * clip_gap, frame_info['len'])\n        print('Processing:', start_f+1, '-', end_f, ' / Total:', frame_info['len'])\n\n        frames_hr = []\n        frames = {}\n        comps = {}\n        for k in range(len(mode)):\n            frames[k] = []\n        for j in range(start_f, end_f):\n            success, image = reader.read()\n            frames_hr.append(image)\n            for k in range(len(mode)):\n                image_crop = image[mode[k][0]:mode[k][1], :, :]\n                image_resize = cv2.resize(image_crop, (w, h))\n                frames[k].append(image_resize)\n\n        for k in range(len(mode)):\n            comps[k] = process(frames[k], model, device, w, h)\n\n        if mode is not []:\n            for j in range(end_f - start_f):\n                frame_ori = frames_hr[j].copy()\n                frame = frames_hr[j]\n                for k in range(len(mode)):\n                    comp = cv2.resize(comps[k][j], (frame_info['W_ori'], split_h))\n                    comp = cv2.cvtColor(np.array(comp).astype(np.uint8), cv2.COLOR_BGR2RGB)\n                    mask_area = mask[mode[k][0]:mode[k][1], :]\n                    frame[mode[k][0]:mode[k][1], :, :] = mask_area * comp + (1 - mask_area) * frame[mode[k][0]:mode[k][1], :, :]\n                if args.dual:\n                    frame = np.vstack([frame_ori, frame])\n                writer.write(frame)\n\n    writer.release()\n    print('--------------------------------------')\n    print('Finish in {}'.format(video_name))\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "model/auto-sttn.py",
    "content": "''' Spatial-Temporal Transformer Networks\n'''\nimport numpy as np\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models as models\nfrom core.spectral_norm import spectral_norm as _spectral_norm\n\nclass BaseNetwork(nn.Module):\n    def __init__(self):\n        super(BaseNetwork, self).__init__()\n\n    def print_network(self):\n        if isinstance(self, list):\n            self = self[0]\n        num_params = 0\n        for param in self.parameters():\n            num_params += param.numel()\n        print('Network [%s] was created. Total number of parameters: %.1f million. '\n              'To see the architecture, do print(network).' % (type(self).__name__, num_params / 1000000))\n\n    def init_weights(self, init_type='normal', gain=0.02):\n        '''\n        initialize network's weights\n        init_type: normal | xavier | kaiming | orthogonal\n        https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/9451e70673400885567d08a9e97ade2524c700d0/models/networks.py#L39\n        '''\n        def init_func(m):\n            classname = m.__class__.__name__\n            if classname.find('InstanceNorm2d') != -1:\n                if hasattr(m, 'weight') and m.weight is not None:\n                    nn.init.constant_(m.weight.data, 1.0)\n                if hasattr(m, 'bias') and m.bias is not None:\n                    nn.init.constant_(m.bias.data, 0.0)\n            elif hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n                if init_type == 'normal':\n                    nn.init.normal_(m.weight.data, 0.0, gain)\n                elif init_type == 'xavier':\n                    nn.init.xavier_normal_(m.weight.data, gain=gain)\n                elif init_type == 'xavier_uniform':\n                    nn.init.xavier_uniform_(m.weight.data, gain=1.0)\n                elif init_type == 'kaiming':\n                    nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n                elif init_type == 'orthogonal':\n                    nn.init.orthogonal_(m.weight.data, gain=gain)\n                elif init_type == 'none':  # uses pytorch's default init method\n                    m.reset_parameters()\n                else:\n                    raise NotImplementedError(\n                        'initialization method [%s] is not implemented' % init_type)\n                if hasattr(m, 'bias') and m.bias is not None:\n                    nn.init.constant_(m.bias.data, 0.0)\n\n        self.apply(init_func)\n\n        # propagate to children\n        for m in self.children():\n            if hasattr(m, 'init_weights'):\n                m.init_weights(init_type, gain)\n\n\nclass InpaintGenerator(BaseNetwork):\n    def __init__(self, init_weights=True):\n        super(InpaintGenerator, self).__init__()\n        channel = 256\n        stack_num = 8\n        patchsize = [(80, 15), (32, 6), (10, 5), (5, 3)]\n        blocks = []\n        for _ in range(stack_num):\n            blocks.append(TransformerBlock(patchsize, hidden=channel))\n        self.transformer = nn.Sequential(*blocks)\n\n        self.encoder = nn.Sequential(\n            nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(128, channel, kernel_size=3, stride=1, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n        )\n\n        # decoder: decode frames from features\n        self.decoder = nn.Sequential(\n            deconv(channel, 128, kernel_size=3, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(128, 64, kernel_size=3, stride=1, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            deconv(64, 64, kernel_size=3, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(64, 3, kernel_size=3, stride=1, padding=1)\n        )\n\n        if init_weights:\n            self.init_weights()\n\n    def forward(self, masked_frames):\n        # extracting features\n        b, t, c, h, w = masked_frames.size()\n        enc_feat = self.encoder(masked_frames.view(b*t, c, h, w))\n        _, c, h, w = enc_feat.size()\n        enc_feat = self.transformer(\n            {'x': enc_feat, 'b': b, 'c': c})['x']\n        output = self.decoder(enc_feat)\n        output = torch.tanh(output)\n        return output\n\n    def infer(self, feat):\n        t, c, _, _ = feat.size()\n        enc_feat = self.transformer(\n            {'x': feat, 'b': 1, 'c': c})['x']\n        return enc_feat\n\n\nclass deconv(nn.Module):\n    def __init__(self, input_channel, output_channel, kernel_size=3, padding=0):\n        super().__init__()\n        self.conv = nn.Conv2d(input_channel, output_channel,\n                              kernel_size=kernel_size, stride=1, padding=padding)\n\n    def forward(self, x):\n        x = F.interpolate(x, scale_factor=2, mode='bilinear',\n                          align_corners=True)\n        return self.conv(x)\n\n\n# #############################################################################\n# ############################# Transformer  ##################################\n# #############################################################################\n\n\nclass Attention(nn.Module):\n    \"\"\"\n    Compute 'Scaled Dot Product Attention\n    \"\"\"\n\n    def forward(self, query, key, value):\n        scores = torch.matmul(query, key.transpose(-2, -1)\n                              ) / math.sqrt(query.size(-1))\n        p_attn = F.softmax(scores, dim=-1)\n        p_val = torch.matmul(p_attn, value)\n        return p_val, p_attn\n\n\nclass MultiHeadedAttention(nn.Module):\n    \"\"\"\n    Take in model size and number of heads.\n    \"\"\"\n\n    def __init__(self, patchsize, d_model):\n        super().__init__()\n        self.patchsize = patchsize\n        self.query_embedding = nn.Conv2d(\n            d_model, d_model, kernel_size=1, padding=0)\n        self.value_embedding = nn.Conv2d(\n            d_model, d_model, kernel_size=1, padding=0)\n        self.key_embedding = nn.Conv2d(\n            d_model, d_model, kernel_size=1, padding=0)\n        self.output_linear = nn.Sequential(\n            nn.Conv2d(d_model, d_model, kernel_size=3, padding=1),\n            nn.LeakyReLU(0.2, inplace=True))\n        self.attention = Attention()\n\n    def forward(self, x, b, c):\n        bt, _, h, w = x.size()\n        t = bt // b\n        d_k = c // len(self.patchsize)\n        output = []\n        _query = self.query_embedding(x)\n        _key = self.key_embedding(x)\n        _value = self.value_embedding(x)\n        for (width, height), query, key, value in zip(self.patchsize,\n                                                      torch.chunk(_query, len(self.patchsize), dim=1), torch.chunk(\n                                                          _key, len(self.patchsize), dim=1),\n                                                      torch.chunk(_value, len(self.patchsize), dim=1)):\n            out_w, out_h = w // width, h // height\n\n            # 1) embedding and reshape\n            query = query.view(b, t, d_k, out_h, height, out_w, width)\n            query = query.permute(0, 1, 3, 5, 2, 4, 6).contiguous().view(\n                b,  t*out_h*out_w, d_k*height*width)\n            key = key.view(b, t, d_k, out_h, height, out_w, width)\n            key = key.permute(0, 1, 3, 5, 2, 4, 6).contiguous().view(\n                b,  t*out_h*out_w, d_k*height*width)\n            value = value.view(b, t, d_k, out_h, height, out_w, width)\n            value = value.permute(0, 1, 3, 5, 2, 4, 6).contiguous().view(\n                b,  t*out_h*out_w, d_k*height*width)\n            '''\n            # 2) Apply attention on all the projected vectors in batch.\n            tmp1 = []\n            for q,k,v in zip(torch.chunk(query, b, dim=0), torch.chunk(key, b, dim=0), torch.chunk(value, b, dim=0)):\n                y, _ = self.attention(q.unsqueeze(0), k.unsqueeze(0), v.unsqueeze(0))\n                tmp1.append(y)\n            y = torch.cat(tmp1,1)\n            '''\n            y, _ = self.attention(query, key, value)\n            # 3) \"Concat\" using a view and apply a final linear.\n            y = y.view(b, t, out_h, out_w, d_k, height, width)\n            y = y.permute(0, 1, 4, 2, 5, 3, 6).contiguous().view(bt, d_k, h, w)\n            output.append(y)\n        output = torch.cat(output, 1)\n        x = self.output_linear(output)\n        return x\n\n\n# Standard 2 layerd FFN of transformer\nclass FeedForward(nn.Module):\n    def __init__(self, d_model):\n        super(FeedForward, self).__init__()\n        # We set d_ff as a default to 2048\n        self.conv = nn.Sequential(\n            nn.Conv2d(d_model, d_model, kernel_size=3, padding=2, dilation=2),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(d_model, d_model, kernel_size=3, padding=1),\n            nn.LeakyReLU(0.2, inplace=True))\n\n    def forward(self, x):\n        x = self.conv(x)\n        return x\n\n\nclass TransformerBlock(nn.Module):\n    \"\"\"\n    Transformer = MultiHead_Attention + Feed_Forward with sublayer connection\n    \"\"\"\n\n    def __init__(self, patchsize, hidden=128):\n        super().__init__()\n        self.attention = MultiHeadedAttention(patchsize, d_model=hidden)\n        self.feed_forward = FeedForward(hidden)\n\n    def forward(self, x):\n        x, b, c = x['x'], x['b'], x['c']\n        x = x + self.attention(x, b, c)\n        x = x + self.feed_forward(x)\n        return {'x': x, 'b': b, 'c': c}\n\n\n# ######################################################################\n# ######################################################################\n\n\nclass Discriminator(BaseNetwork):\n    def __init__(self, in_channels=3, use_sigmoid=False, use_spectral_norm=True, init_weights=True):\n        super(Discriminator, self).__init__()\n        self.use_sigmoid = use_sigmoid\n        nf = 64\n\n        self.conv = nn.Sequential(\n            spectral_norm(nn.Conv3d(in_channels=in_channels, out_channels=nf*1, kernel_size=(3, 5, 5), stride=(1, 2, 2),\n                                    padding=1, bias=not use_spectral_norm), use_spectral_norm),\n            # nn.InstanceNorm2d(64, track_running_stats=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            spectral_norm(nn.Conv3d(nf*1, nf*2, kernel_size=(3, 5, 5), stride=(1, 2, 2),\n                                    padding=(1, 2, 2), bias=not use_spectral_norm), use_spectral_norm),\n            # nn.InstanceNorm2d(128, track_running_stats=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            spectral_norm(nn.Conv3d(nf * 2, nf * 4, kernel_size=(3, 5, 5), stride=(1, 2, 2),\n                                    padding=(1, 2, 2), bias=not use_spectral_norm), use_spectral_norm),\n            # nn.InstanceNorm2d(256, track_running_stats=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            spectral_norm(nn.Conv3d(nf * 4, nf * 4, kernel_size=(3, 5, 5), stride=(1, 2, 2),\n                                    padding=(1, 2, 2), bias=not use_spectral_norm), use_spectral_norm),\n            # nn.InstanceNorm2d(256, track_running_stats=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            spectral_norm(nn.Conv3d(nf * 4, nf * 4, kernel_size=(3, 5, 5), stride=(1, 2, 2),\n                                    padding=(1, 2, 2), bias=not use_spectral_norm), use_spectral_norm),\n            # nn.InstanceNorm2d(256, track_running_stats=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv3d(nf * 4, nf * 4, kernel_size=(3, 5, 5),\n                      stride=(1, 2, 2), padding=(1, 2, 2))\n        )\n\n        if init_weights:\n            self.init_weights()\n\n    def forward(self, xs):\n        # T, C, H, W = xs.shape\n        xs_t = torch.transpose(xs, 0, 1)\n        xs_t = xs_t.unsqueeze(0)  # B, C, T, H, W\n        feat = self.conv(xs_t)\n        if self.use_sigmoid:\n            feat = torch.sigmoid(feat)\n        out = torch.transpose(feat, 1, 2)  # B, T, C, H, W\n        return out\n\n\ndef spectral_norm(module, mode=True):\n    if mode:\n        return _spectral_norm(module)\n    return module\n"
  },
  {
    "path": "model/vis.py",
    "content": "''' Spatial-Temporal Transformer Networks\n'''\nimport numpy as np\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models as models\nfrom core.spectral_norm import spectral_norm as _spectral_norm\n\n\nclass BaseNetwork(nn.Module):\n    def __init__(self):\n        super(BaseNetwork, self).__init__()\n\n    def print_network(self):\n        if isinstance(self, list):\n            self = self[0]\n        num_params = 0\n        for param in self.parameters():\n            num_params += param.numel()\n        print('Network [%s] was created. Total number of parameters: %.1f million. '\n              'To see the architecture, do print(network).' % (type(self).__name__, num_params / 1000000))\n\n    def init_weights(self, init_type='normal', gain=0.02):\n        '''\n        initialize network's weights\n        init_type: normal | xavier | kaiming | orthogonal\n        https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/9451e70673400885567d08a9e97ade2524c700d0/models/networks.py#L39\n        '''\n        def init_func(m):\n            classname = m.__class__.__name__\n            if classname.find('InstanceNorm2d') != -1:\n                if hasattr(m, 'weight') and m.weight is not None:\n                    nn.init.constant_(m.weight.data, 1.0)\n                if hasattr(m, 'bias') and m.bias is not None:\n                    nn.init.constant_(m.bias.data, 0.0)\n            elif hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n                if init_type == 'normal':\n                    nn.init.normal_(m.weight.data, 0.0, gain)\n                elif init_type == 'xavier':\n                    nn.init.xavier_normal_(m.weight.data, gain=gain)\n                elif init_type == 'xavier_uniform':\n                    nn.init.xavier_uniform_(m.weight.data, gain=1.0)\n                elif init_type == 'kaiming':\n                    nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n                elif init_type == 'orthogonal':\n                    nn.init.orthogonal_(m.weight.data, gain=gain)\n                elif init_type == 'none':  # uses pytorch's default init method\n                    m.reset_parameters()\n                else:\n                    raise NotImplementedError(\n                        'initialization method [%s] is not implemented' % init_type)\n                if hasattr(m, 'bias') and m.bias is not None:\n                    nn.init.constant_(m.bias.data, 0.0)\n\n        self.apply(init_func)\n\n        # propagate to children\n        for m in self.children():\n            if hasattr(m, 'init_weights'):\n                m.init_weights(init_type, gain)\n\n\nclass InpaintGenerator(BaseNetwork):\n    def __init__(self, init_weights=True):  # 1046\n        super(InpaintGenerator, self).__init__()\n        channel = 256\n        stack_num = 8\n        patchsize = [(108, 60), (36, 20), (18, 10), (9, 5)]\n        blocks = []\n        for _ in range(stack_num):\n            blocks.append(TransformerBlock(patchsize, hidden=channel))\n        self.transformer = nn.Sequential(*blocks)\n\n        self.encoder = nn.Sequential(\n            nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(128, channel, kernel_size=3, stride=1, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n        )\n\n        # decoder: decode image from features\n        self.decoder = nn.Sequential(\n            deconv(channel, 128, kernel_size=3, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(128, 64, kernel_size=3, stride=1, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            deconv(64, 64, kernel_size=3, padding=1),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(64, 3, kernel_size=3, stride=1, padding=1)\n        )\n\n        if init_weights:\n            self.init_weights()\n\n    def forward(self, masked_frames, masks):\n        # extracting features\n        b, t, c, h, w = masked_frames.size()\n        masks = masks.view(b*t, 1, h, w)\n        enc_feat = self.encoder(masked_frames.view(b*t, c, h, w))\n        _, c, h, w = enc_feat.size()\n        masks = F.interpolate(masks, scale_factor=1.0/4)\n        enc_feat = self.transformer(\n            {'x': enc_feat, 'm': masks, 'b': b, 'c': c})['x']\n        output = self.decoder(enc_feat)\n        output = torch.tanh(output)\n        return output\n\n    def infer(self, feat, masks):\n        t, c, h, w = masks.size()\n        masks = masks.view(t, c, h, w)\n        masks = F.interpolate(masks, scale_factor=1.0/4)\n        t, c, _, _ = feat.size()\n        output = self.transformer({'x': feat, 'm': masks, 'b': 1, 'c': c})\n        enc_feat = output['x']\n        attn = output['attn']\n        mm = output['smm']\n        return enc_feat, attn, mm\n\n\nclass deconv(nn.Module):\n    def __init__(self, input_channel, output_channel, kernel_size=3, padding=0):\n        super().__init__()\n        self.conv = nn.Conv2d(input_channel, output_channel,\n                              kernel_size=kernel_size, stride=1, padding=padding)\n\n    def forward(self, x):\n        x = F.interpolate(x, scale_factor=2, mode='bilinear',\n                          align_corners=True)\n        return self.conv(x)\n\n\n# ##################################################\n# ################## Transformer ####################\n\n\nclass Attention(nn.Module):\n    \"\"\"\n    Compute 'Scaled Dot Product Attention\n    \"\"\"\n\n    def forward(self, query, key, value, m):\n        scores = torch.matmul(query, key.transpose(-2, -1)\n                              ) / math.sqrt(query.size(-1))\n        scores.masked_fill(m, -1e9)\n        p_attn = F.softmax(scores, dim=-1)\n        p_val = torch.matmul(p_attn, value)\n        return p_val, p_attn\n\n\nclass MultiHeadedAttention(nn.Module):\n    \"\"\"\n    Take in model size and number of heads.\n    \"\"\"\n\n    def __init__(self, patchsize, d_model):\n        super().__init__()\n        self.patchsize = patchsize\n        self.query_embedding = nn.Conv2d(\n            d_model, d_model, kernel_size=1, padding=0)\n        self.value_embedding = nn.Conv2d(\n            d_model, d_model, kernel_size=1, padding=0)\n        self.key_embedding = nn.Conv2d(\n            d_model, d_model, kernel_size=1, padding=0)\n        self.output_linear = nn.Sequential(\n            nn.Conv2d(d_model, d_model, kernel_size=3, padding=1),\n            nn.LeakyReLU(0.2, inplace=True))\n        self.attention = Attention()\n\n    def forward(self, x, m, b, c):\n        bt, _, h, w = x.size()\n        t = bt // b\n        d_k = c // len(self.patchsize)\n        output = []\n        _query = self.query_embedding(x)\n        _key = self.key_embedding(x)\n        _value = self.value_embedding(x)\n        for (width, height), query, key, value in zip(self.patchsize,\n                                                      torch.chunk(_query, len(self.patchsize), dim=1), torch.chunk(\n                                                          _key, len(self.patchsize), dim=1),\n                                                      torch.chunk(_value, len(self.patchsize), dim=1)):\n            out_w, out_h = w // width, h // height\n            mm = m.view(b, t, 1, out_h, height, out_w, width)\n            mm = mm.permute(0, 1, 3, 5, 2, 4, 6).contiguous().view(\n                b,  t*out_h*out_w, height*width)\n            mm = (mm.mean(-1) > 0.5).unsqueeze(1).repeat(1, t*out_h*out_w, 1)\n            # 1) embedding and reshape\n            query = query.view(b, t, d_k, out_h, height, out_w, width)\n            query = query.permute(0, 1, 3, 5, 2, 4, 6).contiguous().view(\n                b,  t*out_h*out_w, d_k*height*width)\n            key = key.view(b, t, d_k, out_h, height, out_w, width)\n            key = key.permute(0, 1, 3, 5, 2, 4, 6).contiguous().view(\n                b,  t*out_h*out_w, d_k*height*width)\n            value = value.view(b, t, d_k, out_h, height, out_w, width)\n            value = value.permute(0, 1, 3, 5, 2, 4, 6).contiguous().view(\n                b,  t*out_h*out_w, d_k*height*width)\n            '''\n            # 2) Apply attention on all the projected vectors in batch.\n            tmp1 = []\n            for q,k,v in zip(torch.chunk(query, b, dim=0), torch.chunk(key, b, dim=0), torch.chunk(value, b, dim=0)):\n                y, _ = self.attention(q.unsqueeze(0), k.unsqueeze(0), v.unsqueeze(0))\n                tmp1.append(y)\n            y = torch.cat(tmp1,1)\n            '''\n            y, attn = self.attention(query, key, value, mm)\n\n            # return attention value for visualization \n            # here we return the attention value of patchsize=18 \n            if width == 18:\n                select_attn = attn.view(t, out_h*out_w, t, out_h, out_w)[0]\n                # mm, [b, thw, thw]\n                select_mm = mm[0].view(t*out_h*out_w, t, out_h, out_w)[0]\n\n            # 3) \"Concat\" using a view and apply a final linear.\n            y = y.view(b, t, out_h, out_w, d_k, height, width)\n            y = y.permute(0, 1, 4, 2, 5, 3, 6).contiguous().view(bt, d_k, h, w)\n            output.append(y)\n        output = torch.cat(output, 1)\n        x = self.output_linear(output)\n        return x, select_attn, select_mm\n\n\n# Standard 2 layerd FFN of transformer\nclass FeedForward(nn.Module):\n    def __init__(self, d_model):\n        super(FeedForward, self).__init__()\n        # We set d_ff as a default to 2048\n        self.conv = nn.Sequential(\n            nn.Conv2d(d_model, d_model, kernel_size=3, padding=2, dilation=2),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv2d(d_model, d_model, kernel_size=3, padding=1),\n            nn.LeakyReLU(0.2, inplace=True))\n\n    def forward(self, x):\n        x = self.conv(x)\n        return x\n\n\nclass TransformerBlock(nn.Module):\n    \"\"\"\n    Transformer = MultiHead_Attention + Feed_Forward with sublayer connection\n    \"\"\"\n\n    def __init__(self, patchsize, hidden=128):\n        super().__init__()\n        self.attention = MultiHeadedAttention(patchsize, d_model=hidden)\n        self.feed_forward = FeedForward(hidden)\n\n    def forward(self, x):\n        x, m, b, c = x['x'], x['m'], x['b'], x['c']\n        val, attn, mm = self.attention(x, m, b, c)\n        x = x + val\n        x = x + self.feed_forward(x)\n        return {'x': x, 'm': m, 'b': b, 'c': c, 'attn': attn, 'smm': mm}\n\n\n# ######################################################################\n# ######################################################################\n\n\nclass Discriminator(BaseNetwork):\n    def __init__(self, in_channels=3, use_sigmoid=False, use_spectral_norm=True, init_weights=True):\n        super(Discriminator, self).__init__()\n        self.use_sigmoid = use_sigmoid\n        nf = 64\n\n        self.conv = nn.Sequential(\n            spectral_norm(nn.Conv3d(in_channels=in_channels, out_channels=nf*1, kernel_size=(3, 5, 5), stride=(1, 2, 2),\n                                    padding=1, bias=not use_spectral_norm), use_spectral_norm),\n            # nn.InstanceNorm2d(64, track_running_stats=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            spectral_norm(nn.Conv3d(nf*1, nf*2, kernel_size=(3, 5, 5), stride=(1, 2, 2),\n                                    padding=(1, 2, 2), bias=not use_spectral_norm), use_spectral_norm),\n            # nn.InstanceNorm2d(128, track_running_stats=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            spectral_norm(nn.Conv3d(nf * 2, nf * 4, kernel_size=(3, 5, 5), stride=(1, 2, 2),\n                                    padding=(1, 2, 2), bias=not use_spectral_norm), use_spectral_norm),\n            # nn.InstanceNorm2d(256, track_running_stats=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            spectral_norm(nn.Conv3d(nf * 4, nf * 4, kernel_size=(3, 5, 5), stride=(1, 2, 2),\n                                    padding=(1, 2, 2), bias=not use_spectral_norm), use_spectral_norm),\n            # nn.InstanceNorm2d(256, track_running_stats=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            spectral_norm(nn.Conv3d(nf * 4, nf * 4, kernel_size=(3, 5, 5), stride=(1, 2, 2),\n                                    padding=(1, 2, 2), bias=not use_spectral_norm), use_spectral_norm),\n            # nn.InstanceNorm2d(256, track_running_stats=False),\n            nn.LeakyReLU(0.2, inplace=True),\n            nn.Conv3d(nf * 4, nf * 4, kernel_size=(3, 5, 5),\n                      stride=(1, 2, 2), padding=(1, 2, 2))\n        )\n\n        if init_weights:\n            self.init_weights()\n\n    def forward(self, xs):\n        # T, C, H, W = xs.shape\n        xs_t = torch.transpose(xs, 0, 1)\n        xs_t = xs_t.unsqueeze(0)  # B, C, T, H, W\n        feat = self.conv(xs_t)\n        if self.use_sigmoid:\n            feat = torch.sigmoid(feat)\n        out = torch.transpose(feat, 1, 2)  # B, T, C, H, W\n        return out\n\n\ndef spectral_norm(module, mode=True):\n    if mode:\n        return _spectral_norm(module)\n    return module\n"
  },
  {
    "path": "pics/de-watermark/1",
    "content": "\n"
  },
  {
    "path": "pretrained_weight/download_weights.txt",
    "content": "模型下载地址：\n  链接：https://pan.baidu.com/s/1JN9-8Glw_ozOrSMgBIyHOw \n  提取码：px0s \n\n\n"
  }
]