[
  {
    "path": "LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU 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 <http://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<http://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<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Yolov5 Face Detection\n\n## Description\nThe project is a wrap over [yolov5-face](https://github.com/deepcam-cn/yolov5-face) repo. Made simple portable interface for model import and inference. Model detects faces on images and returns bounding boxes and coordinates of 5 facial keypoints, which can be used for face alignment.\n## Installation\n```bash\npip install -r requirements.txt\n```\n## Usage example\n```python\nfrom face_detector import YoloDetector\nimport numpy as np\nfrom PIL import Image\n\nmodel = YoloDetector(target_size=720, device=\"cuda:0\", min_face=90)\norgimg = np.array(Image.open('test_image.jpg'))\nbboxes,points = model.predict(orgimg)\n```\nYou can also pass several images packed in a list to get multi-image predictions:\n```python\nbboxes,points = model.predict([image1,image2])\n```\nYou can align faces, using `align` class method for predicted keypoints. May be useful in conjunction with facial recognition neural network to increase accuracy:\n```python\ncrops = model.align(orgimg, points[0])\n```\nIf you want to use model class outside root folder, export it into you PYTHONPATH:\n```bash\nexport PYTHONPATH=\"${PYTHONPATH}:/path/to/yoloface/project/\"\n```\nor the same from python:\n```python\nimport sys\nsys.path.append(\"/path/to/yoloface/project/\")\n```\n## Other pretrained models\nYou can use any model from [yolov5-face](https://github.com/deepcam-cn/yolov5-face#pretrained-models) repo. Default models are saved as entire torch module and are bound to the specific classes and the exact directory structure used when the model was saved by authors. To make model portable and run it via my interface you must save it as pytorch state_dict and put new weights in `weights/` folder. Example below:\n```python\nmodel = torch.load('weights/yolov5m-face.pt', map_location='cpu')['model']\ntorch.save(model.state_dict(),'path/to/project/weights/yolov5m_state_dict.pt')\n```\nThen when creating YoloDetector class object, pass new model name and corresponding yaml config from `models/` folder as class arguments.\nExample below:\n```python\nmodel = YoloFace(weights_name='yolov5m_state_dict.pt',config_name='yolov5m.yaml',target_size=720)\n```\n\n## Result example\n<img src=\"/results/result_example.jpg\" width=\"600\"/>\n\n## Citiation\nThanks [deepcam-cn](https://github.com/deepcam-cn/yolov5-face) for pretrained models.\n"
  },
  {
    "path": "face_detector.py",
    "content": "import joblib\nimport os\nimport sys\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport cv2\nimport copy\nimport scipy\nimport pathlib\nimport warnings\n\nfrom math import sqrt\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(\"__file__\"), '..')))\nfrom models.common import Conv\nfrom models.yolo import Model\nfrom utils.datasets import letterbox\nfrom utils.preprocess_utils import align_faces\nfrom utils.general import check_img_size, non_max_suppression_face, \\\n    scale_coords,scale_coords_landmarks,filter_boxes\n\nclass YoloDetector:\n    def __init__(self, weights_name='yolov5n_state_dict.pt', config_name='yolov5n.yaml', device='cuda:0', min_face=100, target_size=None, frontal=False):\n            \"\"\"\n            weights_name: name of file with network weights in weights/ folder.\n            config_name: name of .yaml config with network configuration from models/ folder.\n            device : pytorch device. Use 'cuda:0', 'cuda:1', e.t.c to use gpu or 'cpu' to use cpu.\n            min_face : minimal face size in pixels.\n            target_size : target size of smaller image axis (choose lower for faster work). e.g. 480, 720, 1080. Choose None for original resolution.\n            frontal : if True tries to filter nonfrontal faces by keypoints location. CURRENTRLY UNSUPPORTED.\n            \"\"\"\n            self._class_path = pathlib.Path(__file__).parent.absolute()#os.path.dirname(inspect.getfile(self.__class__))\n            self.device = device\n            self.target_size = target_size\n            self.min_face = min_face\n            self.frontal = frontal\n            if self.frontal:\n                print('Currently unavailable')\n                # self.anti_profile = joblib.load(os.path.join(self._class_path, 'models/anti_profile/anti_profile_xgb_new.pkl'))\n            self.detector = self.init_detector(weights_name,config_name)\n\n    def init_detector(self,weights_name,config_name):\n        print(self.device)\n        model_path = os.path.join(self._class_path,'weights/',weights_name)\n        print(model_path)\n        config_path = os.path.join(self._class_path,'models/',config_name)\n        state_dict = torch.load(model_path)\n        detector = Model(cfg=config_path)\n        detector.load_state_dict(state_dict)\n        detector = detector.to(self.device).float().eval()\n        for m in detector.modules():\n            if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:\n                m.inplace = True  # pytorch 1.7.0 compatibility\n            elif type(m) is Conv:\n                m._non_persistent_buffers_set = set()  # pytorch 1.6.0 compatibility\n        return detector\n    \n    def _preprocess(self,imgs):\n        \"\"\"\n            Preprocessing image before passing through the network. Resize and conversion to torch tensor.\n        \"\"\"\n        pp_imgs = []\n        for img in imgs:\n            h0, w0 = img.shape[:2]  # orig hw\n            if self.target_size:\n                r = self.target_size / min(h0, w0)  # resize image to img_size\n                if r < 1:  \n                    img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=cv2.INTER_LINEAR)\n\n            imgsz = check_img_size(max(img.shape[:2]), s=self.detector.stride.max())  # check img_size\n            img = letterbox(img, new_shape=imgsz)[0]\n            pp_imgs.append(img)\n        pp_imgs = np.array(pp_imgs)\n        pp_imgs = pp_imgs.transpose(0, 3, 1, 2)\n        pp_imgs = torch.from_numpy(pp_imgs).to(self.device)\n        pp_imgs = pp_imgs.float()  # uint8 to fp16/32\n        pp_imgs /= 255.0  # 0 - 255 to 0.0 - 1.0\n        return pp_imgs\n        \n    def _postprocess(self, imgs, origimgs, pred, conf_thres, iou_thres):\n        \"\"\"\n            Postprocessing of raw pytorch model output.\n            Returns:\n                bboxes: list of arrays with 4 coordinates of bounding boxes with format x1,y1,x2,y2.\n                points: list of arrays with coordinates of 5 facial keypoints (eyes, nose, lips corners).\n        \"\"\"\n        bboxes = [[] for i in range(len(origimgs))]\n        landmarks = [[] for i in range(len(origimgs))]\n        \n        pred = non_max_suppression_face(pred, conf_thres, iou_thres)\n        \n        for i in range(len(origimgs)):\n            img_shape = origimgs[i].shape\n            h,w = img_shape[:2]\n            gn = torch.tensor(img_shape)[[1, 0, 1, 0]]  # normalization gain whwh\n            gn_lks = torch.tensor(img_shape)[[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]]  # normalization gain landmarks\n            det = pred[i].cpu()\n            scaled_bboxes = scale_coords(imgs[i].shape[1:], det[:, :4], img_shape).round()\n            scaled_cords = scale_coords_landmarks(imgs[i].shape[1:], det[:, 5:15], img_shape).round()\n\n            for j in range(det.size()[0]):\n                box = (det[j, :4].view(1, 4) / gn).view(-1).tolist()\n                box = list(map(int,[box[0]*w,box[1]*h,box[2]*w,box[3]*h]))\n                if box[3] - box[1] < self.min_face:\n                    continue\n                lm = (det[j, 5:15].view(1, 10) / gn_lks).view(-1).tolist()\n                lm = list(map(int,[i*w if j%2==0 else i*h for j,i in enumerate(lm)]))\n                lm = [lm[i:i+2] for i in range(0,len(lm),2)]\n                bboxes[i].append(box)\n                landmarks[i].append(lm)\n        return bboxes, landmarks\n\n    def get_frontal_predict(self, box, points):\n        '''\n            Make a decision whether face is frontal by keypoints.\n            Returns:\n                True if face is frontal, False otherwise.\n        '''\n        cur_points = points.astype('int')\n        x1, y1, x2, y2 = box[0:4]\n        w = x2-x1\n        h = y2-y1\n        diag = sqrt(w**2+h**2)\n        dist = scipy.spatial.distance.pdist(cur_points)/diag\n        predict = self.anti_profile.predict(dist.reshape(1, -1))[0]\n        if predict == 0:\n            return True\n        else:\n            return False\n    def align(self, img, points):\n        '''\n            Align faces, found on images.\n            Params:\n                img: Single image, used in predict method.\n                points: list of keypoints, produced in predict method.\n            Returns:\n                crops: list of croped and aligned faces of shape (112,112,3).\n        '''\n        crops = [align_faces(img,landmark=np.array(i)) for i in points]\n        return crops\n\n    def predict(self, imgs, conf_thres = 0.3, iou_thres = 0.5):\n        '''\n            Get bbox coordinates and keypoints of faces on original image.\n            Params:\n                imgs: image or list of images to detect faces on\n                conf_thres: confidence threshold for each prediction\n                iou_thres: threshold for NMS (filtering of intersecting bboxes)\n            Returns:\n                bboxes: list of arrays with 4 coordinates of bounding boxes with format x1,y1,x2,y2.\n                points: list of arrays with coordinates of 5 facial keypoints (eyes, nose, lips corners).\n        '''\n        one_by_one = False\n        # Pass input images through face detector\n        if type(imgs) != list:\n            images = [imgs]\n        else:\n            images = imgs\n            one_by_one = False\n            shapes = {arr.shape for arr in images}\n            if len(shapes) != 1:\n                one_by_one = True\n                warnings.warn(f\"Can't use batch predict due to different shapes of input images. Using one by one strategy.\")\n        origimgs = copy.deepcopy(images)\n        \n        \n        if one_by_one:\n            images = [self._preprocess([img]) for img in images]\n            bboxes = [[] for i in range(len(origimgs))]\n            points = [[] for i in range(len(origimgs))]\n            for num, img in enumerate(images):\n                with torch.inference_mode(): # change this with torch.no_grad() for pytorch <1.8 compatibility\n                    single_pred = self.detector(img)[0]\n                    print(single_pred.shape)\n                bb, pt = self._postprocess(img, [origimgs[num]], single_pred, conf_thres, iou_thres)\n                #print(bb)\n                bboxes[num] = bb[0]\n                points[num] = pt[0]\n        else:\n            images = self._preprocess(images)\n            with torch.inference_mode(): # change this with torch.no_grad() for pytorch <1.8 compatibility\n                pred = self.detector(images)[0]\n            bboxes, points = self._postprocess(images, origimgs, pred, conf_thres, iou_thres)\n\n        return bboxes, points\n\n    def __call__(self,*args):\n        return self.predict(*args)\n\nif __name__=='__main__':\n    a = YoloDetector()\n"
  },
  {
    "path": "models/__init__.py",
    "content": ""
  },
  {
    "path": "models/common.py",
    "content": "# This file contains modules common to various models\n\nimport math\n\nimport numpy as np\nimport requests\nimport torch\nimport torch.nn as nn\nfrom PIL import Image, ImageDraw\n\nfrom utils.datasets import letterbox\nfrom utils.general import non_max_suppression, make_divisible, scale_coords, xyxy2xywh\nfrom utils.plots import color_list\n\ndef autopad(k, p=None):  # kernel, padding\n    # Pad to 'same'\n    if p is None:\n        p = k // 2 if isinstance(k, int) else [x // 2 for x in k]  # auto-pad\n    return p\n\ndef channel_shuffle(x, groups):\n    batchsize, num_channels, height, width = x.data.size()\n    channels_per_group = num_channels // groups\n\n    # reshape\n    x = x.view(batchsize, groups, channels_per_group, height, width)\n    x = torch.transpose(x, 1, 2).contiguous()\n\n    # flatten\n    x = x.view(batchsize, -1, height, width)\n    return x\n\ndef DWConv(c1, c2, k=1, s=1, act=True):\n    # Depthwise convolution\n    return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)\n\nclass Conv(nn.Module):\n    # Standard convolution\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups\n        super(Conv, self).__init__()\n        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)\n        self.bn = nn.BatchNorm2d(c2)\n        self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())\n        #self.act = self.act = nn.LeakyReLU(0.1, inplace=True) if act is True else (act if isinstance(act, nn.Module) else nn.Identity())\n\n    def forward(self, x):\n        return self.act(self.bn(self.conv(x)))\n\n    def fuseforward(self, x):\n        return self.act(self.conv(x))\n\nclass StemBlock(nn.Module):\n    def __init__(self, c1, c2, k=3, s=2, p=None, g=1, act=True):\n        super(StemBlock, self).__init__()\n        self.stem_1 = Conv(c1, c2, k, s, p, g, act)\n        self.stem_2a = Conv(c2, c2 // 2, 1, 1, 0)\n        self.stem_2b = Conv(c2 // 2, c2, 3, 2, 1)\n        self.stem_2p = nn.MaxPool2d(kernel_size=2,stride=2,ceil_mode=True)\n        self.stem_3 = Conv(c2 * 2, c2, 1, 1, 0)\n\n    def forward(self, x):\n        stem_1_out  = self.stem_1(x)\n        stem_2a_out = self.stem_2a(stem_1_out)\n        stem_2b_out = self.stem_2b(stem_2a_out)\n        stem_2p_out = self.stem_2p(stem_1_out)\n        out = self.stem_3(torch.cat((stem_2b_out,stem_2p_out),1))\n        return out\n\nclass Bottleneck(nn.Module):\n    # Standard bottleneck\n    def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, shortcut, groups, expansion\n        super(Bottleneck, self).__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c_, c2, 3, 1, g=g)\n        self.add = shortcut and c1 == c2\n\n    def forward(self, x):\n        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))\n\nclass BottleneckCSP(nn.Module):\n    # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super(BottleneckCSP, self).__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)\n        self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)\n        self.cv4 = Conv(2 * c_, c2, 1, 1)\n        self.bn = nn.BatchNorm2d(2 * c_)  # applied to cat(cv2, cv3)\n        self.act = nn.LeakyReLU(0.1, inplace=True)\n        self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])\n\n    def forward(self, x):\n        y1 = self.cv3(self.m(self.cv1(x)))\n        y2 = self.cv2(x)\n        return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))\n\n\nclass C3(nn.Module):\n    # CSP Bottleneck with 3 convolutions\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super(C3, self).__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c1, c_, 1, 1)\n        self.cv3 = Conv(2 * c_, c2, 1)  # act=FReLU(c2)\n        self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])\n\n    def forward(self, x):\n        return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))\n\nclass ShuffleV2Block(nn.Module):\n    def __init__(self, inp, oup, stride):\n        super(ShuffleV2Block, self).__init__()\n\n        if not (1 <= stride <= 3):\n            raise ValueError('illegal stride value')\n        self.stride = stride\n\n        branch_features = oup // 2\n        assert (self.stride != 1) or (inp == branch_features << 1)\n\n        if self.stride > 1:\n            self.branch1 = nn.Sequential(\n                self.depthwise_conv(inp, inp, kernel_size=3, stride=self.stride, padding=1),\n                nn.BatchNorm2d(inp),\n                nn.Conv2d(inp, branch_features, kernel_size=1, stride=1, padding=0, bias=False),\n                nn.BatchNorm2d(branch_features),\n                nn.SiLU(),\n            )\n        else:\n            self.branch1 = nn.Sequential()\n\n        self.branch2 = nn.Sequential(\n            nn.Conv2d(inp if (self.stride > 1) else branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False),\n            nn.BatchNorm2d(branch_features),\n            nn.SiLU(),\n            self.depthwise_conv(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1),\n            nn.BatchNorm2d(branch_features),\n            nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False),\n            nn.BatchNorm2d(branch_features),\n            nn.SiLU(),\n        )\n\n    @staticmethod\n    def depthwise_conv(i, o, kernel_size, stride=1, padding=0, bias=False):\n        return nn.Conv2d(i, o, kernel_size, stride, padding, bias=bias, groups=i)\n\n    def forward(self, x):\n        if self.stride == 1:\n            x1, x2 = x.chunk(2, dim=1)\n            out = torch.cat((x1, self.branch2(x2)), dim=1)\n        else:\n            out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)\n        out = channel_shuffle(out, 2)\n        return out\n\nclass SPP(nn.Module):\n    # Spatial pyramid pooling layer used in YOLOv3-SPP\n    def __init__(self, c1, c2, k=(5, 9, 13)):\n        super(SPP, self).__init__()\n        c_ = c1 // 2  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)\n        self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])\n\n    def forward(self, x):\n        x = self.cv1(x)\n        return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))\n\n\nclass Focus(nn.Module):\n    # Focus wh information into c-space\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups\n        super(Focus, self).__init__()\n        self.conv = Conv(c1 * 4, c2, k, s, p, g, act)\n        # self.contract = Contract(gain=2)\n\n    def forward(self, x):  # x(b,c,w,h) -> y(b,4c,w/2,h/2)\n        return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))\n        # return self.conv(self.contract(x))\n\n\nclass Contract(nn.Module):\n    # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)\n    def __init__(self, gain=2):\n        super().__init__()\n        self.gain = gain\n\n    def forward(self, x):\n        N, C, H, W = x.size()  # assert (H / s == 0) and (W / s == 0), 'Indivisible gain'\n        s = self.gain\n        x = x.view(N, C, H // s, s, W // s, s)  # x(1,64,40,2,40,2)\n        x = x.permute(0, 3, 5, 1, 2, 4).contiguous()  # x(1,2,2,64,40,40)\n        return x.view(N, C * s * s, H // s, W // s)  # x(1,256,40,40)\n\n\nclass Expand(nn.Module):\n    # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)\n    def __init__(self, gain=2):\n        super().__init__()\n        self.gain = gain\n\n    def forward(self, x):\n        N, C, H, W = x.size()  # assert C / s ** 2 == 0, 'Indivisible gain'\n        s = self.gain\n        x = x.view(N, s, s, C // s ** 2, H, W)  # x(1,2,2,16,80,80)\n        x = x.permute(0, 3, 4, 1, 5, 2).contiguous()  # x(1,16,80,2,80,2)\n        return x.view(N, C // s ** 2, H * s, W * s)  # x(1,16,160,160)\n\n\nclass Concat(nn.Module):\n    # Concatenate a list of tensors along dimension\n    def __init__(self, dimension=1):\n        super(Concat, self).__init__()\n        self.d = dimension\n\n    def forward(self, x):\n        return torch.cat(x, self.d)\n\n\nclass NMS(nn.Module):\n    # Non-Maximum Suppression (NMS) module\n    conf = 0.25  # confidence threshold\n    iou = 0.45  # IoU threshold\n    classes = None  # (optional list) filter by class\n\n    def __init__(self):\n        super(NMS, self).__init__()\n\n    def forward(self, x):\n        return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes)\n\nclass autoShape(nn.Module):\n    # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS\n    img_size = 640  # inference size (pixels)\n    conf = 0.25  # NMS confidence threshold\n    iou = 0.45  # NMS IoU threshold\n    classes = None  # (optional list) filter by class\n\n    def __init__(self, model):\n        super(autoShape, self).__init__()\n        self.model = model.eval()\n\n    def autoshape(self):\n        print('autoShape already enabled, skipping... ')  # model already converted to model.autoshape()\n        return self\n\n    def forward(self, imgs, size=640, augment=False, profile=False):\n        # Inference from various sources. For height=720, width=1280, RGB images example inputs are:\n        #   filename:   imgs = 'data/samples/zidane.jpg'\n        #   URI:             = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg'\n        #   OpenCV:          = cv2.imread('image.jpg')[:,:,::-1]  # HWC BGR to RGB x(720,1280,3)\n        #   PIL:             = Image.open('image.jpg')  # HWC x(720,1280,3)\n        #   numpy:           = np.zeros((720,1280,3))  # HWC\n        #   torch:           = torch.zeros(16,3,720,1280)  # BCHW\n        #   multiple:        = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...]  # list of images\n\n        p = next(self.model.parameters())  # for device and type\n        if isinstance(imgs, torch.Tensor):  # torch\n            return self.model(imgs.to(p.device).type_as(p), augment, profile)  # inference\n\n        # Pre-process\n        n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs])  # number of images, list of images\n        shape0, shape1 = [], []  # image and inference shapes\n        for i, im in enumerate(imgs):\n            if isinstance(im, str):  # filename or uri\n                im = Image.open(requests.get(im, stream=True).raw if im.startswith('http') else im)  # open\n            im = np.array(im)  # to numpy\n            if im.shape[0] < 5:  # image in CHW\n                im = im.transpose((1, 2, 0))  # reverse dataloader .transpose(2, 0, 1)\n            im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3)  # enforce 3ch input\n            s = im.shape[:2]  # HWC\n            shape0.append(s)  # image shape\n            g = (size / max(s))  # gain\n            shape1.append([y * g for y in s])\n            imgs[i] = im  # update\n        shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)]  # inference shape\n        x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs]  # pad\n        x = np.stack(x, 0) if n > 1 else x[0][None]  # stack\n        x = np.ascontiguousarray(x.transpose((0, 3, 1, 2)))  # BHWC to BCHW\n        x = torch.from_numpy(x).to(p.device).type_as(p) / 255.  # uint8 to fp16/32\n\n        # Inference\n        with torch.no_grad():\n            y = self.model(x, augment, profile)[0]  # forward\n        y = non_max_suppression(y, conf_thres=self.conf, iou_thres=self.iou, classes=self.classes)  # NMS\n\n        # Post-process\n        for i in range(n):\n            scale_coords(shape1, y[i][:, :4], shape0[i])\n\n        return Detections(imgs, y, self.names)\n\n\nclass Detections:\n    # detections class for YOLOv5 inference results\n    def __init__(self, imgs, pred, names=None):\n        super(Detections, self).__init__()\n        d = pred[0].device  # device\n        gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs]  # normalizations\n        self.imgs = imgs  # list of images as numpy arrays\n        self.pred = pred  # list of tensors pred[0] = (xyxy, conf, cls)\n        self.names = names  # class names\n        self.xyxy = pred  # xyxy pixels\n        self.xywh = [xyxy2xywh(x) for x in pred]  # xywh pixels\n        self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)]  # xyxy normalized\n        self.xywhn = [x / g for x, g in zip(self.xywh, gn)]  # xywh normalized\n        self.n = len(self.pred)\n\n    def display(self, pprint=False, show=False, save=False, render=False):\n        colors = color_list()\n        for i, (img, pred) in enumerate(zip(self.imgs, self.pred)):\n            str = f'Image {i + 1}/{len(self.pred)}: {img.shape[0]}x{img.shape[1]} '\n            if pred is not None:\n                for c in pred[:, -1].unique():\n                    n = (pred[:, -1] == c).sum()  # detections per class\n                    str += f'{n} {self.names[int(c)]}s, '  # add to string\n                if show or save or render:\n                    img = Image.fromarray(img.astype(np.uint8)) if isinstance(img, np.ndarray) else img  # from np\n                    for *box, conf, cls in pred:  # xyxy, confidence, class\n                        # str += '%s %.2f, ' % (names[int(cls)], conf)  # label\n                        ImageDraw.Draw(img).rectangle(box, width=4, outline=colors[int(cls) % 10])  # plot\n            if pprint:\n                print(str)\n            if show:\n                img.show(f'Image {i}')  # show\n            if save:\n                f = f'results{i}.jpg'\n                str += f\"saved to '{f}'\"\n                img.save(f)  # save\n            if render:\n                self.imgs[i] = np.asarray(img)\n\n    def print(self):\n        self.display(pprint=True)  # print results\n\n    def show(self):\n        self.display(show=True)  # show results\n\n    def save(self):\n        self.display(save=True)  # save results\n\n    def render(self):\n        self.display(render=True)  # render results\n        return self.imgs\n\n    def __len__(self):\n        return self.n\n\n    def tolist(self):\n        # return a list of Detections objects, i.e. 'for result in results.tolist():'\n        x = [Detections([self.imgs[i]], [self.pred[i]], self.names) for i in range(self.n)]\n        for d in x:\n            for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:\n                setattr(d, k, getattr(d, k)[0])  # pop out of list\n        return x\n\n\nclass Classify(nn.Module):\n    # Classification head, i.e. x(b,c1,20,20) to x(b,c2)\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1):  # ch_in, ch_out, kernel, stride, padding, groups\n        super(Classify, self).__init__()\n        self.aap = nn.AdaptiveAvgPool2d(1)  # to x(b,c1,1,1)\n        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g)  # to x(b,c2,1,1)\n        self.flat = nn.Flatten()\n\n    def forward(self, x):\n        z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1)  # cat if list\n        return self.flat(self.conv(z))  # flatten to x(b,c2)\n"
  },
  {
    "path": "models/experimental.py",
    "content": "# This file contains experimental modules\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom models.common import Conv, DWConv\nfrom utils.google_utils import attempt_download\n\n\nclass CrossConv(nn.Module):\n    # Cross Convolution Downsample\n    def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):\n        # ch_in, ch_out, kernel, stride, groups, expansion, shortcut\n        super(CrossConv, self).__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, (1, k), (1, s))\n        self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)\n        self.add = shortcut and c1 == c2\n\n    def forward(self, x):\n        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))\n\n\nclass Sum(nn.Module):\n    # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070\n    def __init__(self, n, weight=False):  # n: number of inputs\n        super(Sum, self).__init__()\n        self.weight = weight  # apply weights boolean\n        self.iter = range(n - 1)  # iter object\n        if weight:\n            self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True)  # layer weights\n\n    def forward(self, x):\n        y = x[0]  # no weight\n        if self.weight:\n            w = torch.sigmoid(self.w) * 2\n            for i in self.iter:\n                y = y + x[i + 1] * w[i]\n        else:\n            for i in self.iter:\n                y = y + x[i + 1]\n        return y\n\n\nclass GhostConv(nn.Module):\n    # Ghost Convolution https://github.com/huawei-noah/ghostnet\n    def __init__(self, c1, c2, k=1, s=1, g=1, act=True):  # ch_in, ch_out, kernel, stride, groups\n        super(GhostConv, self).__init__()\n        c_ = c2 // 2  # hidden channels\n        self.cv1 = Conv(c1, c_, k, s, None, g, act)\n        self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)\n\n    def forward(self, x):\n        y = self.cv1(x)\n        return torch.cat([y, self.cv2(y)], 1)\n\n\nclass GhostBottleneck(nn.Module):\n    # Ghost Bottleneck https://github.com/huawei-noah/ghostnet\n    def __init__(self, c1, c2, k, s):\n        super(GhostBottleneck, self).__init__()\n        c_ = c2 // 2\n        self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1),  # pw\n                                  DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(),  # dw\n                                  GhostConv(c_, c2, 1, 1, act=False))  # pw-linear\n        self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),\n                                      Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()\n\n    def forward(self, x):\n        return self.conv(x) + self.shortcut(x)\n\n\nclass MixConv2d(nn.Module):\n    # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595\n    def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):\n        super(MixConv2d, self).__init__()\n        groups = len(k)\n        if equal_ch:  # equal c_ per group\n            i = torch.linspace(0, groups - 1E-6, c2).floor()  # c2 indices\n            c_ = [(i == g).sum() for g in range(groups)]  # intermediate channels\n        else:  # equal weight.numel() per group\n            b = [c2] + [0] * groups\n            a = np.eye(groups + 1, groups, k=-1)\n            a -= np.roll(a, 1, axis=1)\n            a *= np.array(k) ** 2\n            a[0] = 1\n            c_ = np.linalg.lstsq(a, b, rcond=None)[0].round()  # solve for equal weight indices, ax = b\n\n        self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])\n        self.bn = nn.BatchNorm2d(c2)\n        self.act = nn.LeakyReLU(0.1, inplace=True)\n\n    def forward(self, x):\n        return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))\n\n\nclass Ensemble(nn.ModuleList):\n    # Ensemble of models\n    def __init__(self):\n        super(Ensemble, self).__init__()\n\n    def forward(self, x, augment=False):\n        y = []\n        for module in self:\n            y.append(module(x, augment)[0])\n        # y = torch.stack(y).max(0)[0]  # max ensemble\n        # y = torch.stack(y).mean(0)  # mean ensemble\n        y = torch.cat(y, 1)  # nms ensemble\n        return y, None  # inference, train output\n\n\ndef attempt_load(weights, map_location=None):\n    # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a\n    model = Ensemble()\n    for w in weights if isinstance(weights, list) else [weights]:\n        attempt_download(w)\n        model.append(torch.load(w, map_location=map_location)['model'].float().fuse().eval())  # load FP32 model\n\n    # Compatibility updates\n    for m in model.modules():\n        if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:\n            m.inplace = True  # pytorch 1.7.0 compatibility\n        elif type(m) is Conv:\n            m._non_persistent_buffers_set = set()  # pytorch 1.6.0 compatibility\n\n    if len(model) == 1:\n        return model[-1]  # return model\n    else:\n        print('Ensemble created with %s\\n' % weights)\n        for k in ['names', 'stride']:\n            setattr(model, k, getattr(model[-1], k))\n        return model  # return ensemble\n"
  },
  {
    "path": "models/export.py",
    "content": "\"\"\"Exports a YOLOv5 *.pt model to ONNX and TorchScript formats\n\nUsage:\n    $ export PYTHONPATH=\"$PWD\" && python models/export.py --weights ./weights/yolov5s.pt --img 640 --batch 1\n\"\"\"\n\nimport argparse\nimport sys\nimport time\n\nsys.path.append('./')  # to run '$ python *.py' files in subdirectories\n\nimport torch\nimport torch.nn as nn\n\nfrom yoloface.models.experimental import attempt_load\nfrom yoloface.models.common import Conv\nfrom yoloface.utils.activations import Hardswish, SiLU\nfrom yoloface.utils.general import set_logging, check_img_size\nimport onnx\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')  # from yolov5/models/\n    parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size')  # height, width\n    parser.add_argument('--batch-size', type=int, default=1, help='batch size')\n    opt = parser.parse_args()\n    opt.img_size *= 2 if len(opt.img_size) == 1 else 1  # expand\n    print(opt)\n    set_logging()\n    t = time.time()\n\n    # Load PyTorch model\n    model = attempt_load(opt.weights, map_location=torch.device('cpu'))  # load FP32 model\n    model.eval()\n    labels = model.names\n\n    # Checks\n    gs = int(max(model.stride))  # grid size (max stride)\n    opt.img_size = [check_img_size(x, gs) for x in opt.img_size]  # verify img_size are gs-multiples\n\n    # Input\n    img = torch.zeros(opt.batch_size, 3, *opt.img_size)  # image size(1,3,320,192) iDetection\n\n    # Update model\n    for k, m in model.named_modules():\n        m._non_persistent_buffers_set = set()  # pytorch 1.6.0 compatibility\n        if isinstance(m, Conv):  # assign export-friendly activations\n            if isinstance(m.act, nn.Hardswish):\n                m.act = Hardswish()\n            elif isinstance(m.act, nn.SiLU):\n                m.act = SiLU()\n        # elif isinstance(m, models.yolo.Detect):\n        #     m.forward = m.forward_export  # assign forward (optional)\n    model.model[-1].export = True  # set Detect() layer export=True\n    y = model(img)  # dry run\n\n    # ONNX export\n    print('\\nStarting ONNX export with onnx %s...' % onnx.__version__)\n    f = opt.weights.replace('.pt', '.onnx')  # filename\n    model.fuse()  # only for ONNX\n    torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['data'],\n                      output_names=['stride_' + str(int(x)) for x in model.stride])\n\n    # Checks\n    onnx_model = onnx.load(f)  # load onnx model\n    onnx.checker.check_model(onnx_model)  # check onnx model\n    # print(onnx.helper.printable_graph(onnx_model.graph))  # print a human readable model\n    print('ONNX export success, saved as %s' % f)\n    # Finish\n    print('\\nExport complete (%.2fs). Visualize with https://github.com/lutzroeder/netron.' % (time.time() - t))\n"
  },
  {
    "path": "models/yolo.py",
    "content": "import argparse\nimport logging\nimport math\nimport sys\nfrom copy import deepcopy\nfrom pathlib import Path\n\nimport torch\nimport torch.nn as nn\n\nsys.path.append('./')  # to run '$ python *.py' files in subdirectories\nlogger = logging.getLogger(__name__)\n\nfrom models.common import Conv, Bottleneck, SPP, DWConv, Focus, BottleneckCSP, C3, ShuffleV2Block, Concat, NMS, autoShape, StemBlock\nfrom models.experimental import MixConv2d, CrossConv\nfrom utils.autoanchor import check_anchor_order\nfrom utils.general import make_divisible, check_file, set_logging\nfrom utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \\\n    select_device, copy_attr\n\ntry:\n    import thop  # for FLOPS computation\nexcept ImportError:\n    thop = None\n\n\nclass Detect(nn.Module):\n    stride = None  # strides computed during build\n    export = False  # onnx export\n\n    def __init__(self, nc=80, anchors=(), ch=()):  # detection layer\n        super(Detect, self).__init__()\n        self.nc = nc  # number of classes\n        #self.no = nc + 5  # number of outputs per anchor\n        self.no = nc + 5 + 10  # number of outputs per anchor\n\n        self.nl = len(anchors)  # number of detection layers\n        self.na = len(anchors[0]) // 2  # number of anchors\n        self.grid = [torch.zeros(1)] * self.nl  # init grid\n        a = torch.tensor(anchors).float().view(self.nl, -1, 2)\n        self.register_buffer('anchors', a)  # shape(nl,na,2)\n        self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2))  # shape(nl,1,na,1,1,2)\n        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)  # output conv\n\n    def forward(self, x):\n        # x = x.copy()  # for profiling\n        z = []  # inference output\n       # self.training |= self.export\n        if self.export:\n            for i in range(self.nl):\n                x[i] = self.m[i](x[i])\n            return x\n        for i in range(self.nl):\n            x[i] = self.m[i](x[i])  # conv\n            bs, _, ny, nx = x[i].shape  # x(bs,255,20,20) to x(bs,3,20,20,85)\n            x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()\n\n            if not self.training:  # inference\n                if self.grid[i].shape[2:4] != x[i].shape[2:4]:\n                    self.grid[i] = self._make_grid(nx, ny).to(x[i].device)\n\n                y = torch.full_like(x[i], 0)\n                y[..., [0,1,2,3,4,15]] = x[i][..., [0,1,2,3,4,15]].sigmoid()\n                y[..., 5:15] = x[i][..., 5:15]\n                #y = x[i].sigmoid()\n\n                y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i]  # xy\n                y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]  # wh\n\n                #y[..., 5:15] = y[..., 5:15] * 8 - 4\n                y[..., 5:7]   = y[..., 5:7] *   self.anchor_grid[i] + self.grid[i].to(x[i].device) * self.stride[i] # landmark x1 y1\n                y[..., 7:9]   = y[..., 7:9] *   self.anchor_grid[i] + self.grid[i].to(x[i].device) * self.stride[i]# landmark x2 y2\n                y[..., 9:11]  = y[..., 9:11] *  self.anchor_grid[i] + self.grid[i].to(x[i].device) * self.stride[i]# landmark x3 y3\n                y[..., 11:13] = y[..., 11:13] * self.anchor_grid[i] + self.grid[i].to(x[i].device) * self.stride[i]# landmark x4 y4\n                y[..., 13:15] = y[..., 13:15] * self.anchor_grid[i] + self.grid[i].to(x[i].device) * self.stride[i]# landmark x5 y5\n\n                #y[..., 5:7] = (y[..., 5:7] * 2 -1) * self.anchor_grid[i]  # landmark x1 y1\n                #y[..., 7:9] = (y[..., 7:9] * 2 -1) * self.anchor_grid[i]  # landmark x2 y2\n                #y[..., 9:11] = (y[..., 9:11] * 2 -1) * self.anchor_grid[i]  # landmark x3 y3\n                #y[..., 11:13] = (y[..., 11:13] * 2 -1) * self.anchor_grid[i]  # landmark x4 y4\n                #y[..., 13:15] = (y[..., 13:15] * 2 -1) * self.anchor_grid[i]  # landmark x5 y5\n\n                z.append(y.view(bs, -1, self.no))\n\n        return x if self.training else (torch.cat(z, 1), x)\n\n    @staticmethod\n    def _make_grid(nx=20, ny=20):\n        yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)], indexing='ij')\n        return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()\n\n\nclass Model(nn.Module):\n    def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None):  # model, input channels, number of classes\n        super(Model, self).__init__()\n        if isinstance(cfg, dict):\n            self.yaml = cfg  # model dict\n        else:  # is *.yaml\n            import yaml  # for torch hub\n            self.yaml_file = Path(cfg).name\n            with open(cfg) as f:\n                self.yaml = yaml.load(f, Loader=yaml.FullLoader)  # model dict\n\n        # Define model\n        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels\n        if nc and nc != self.yaml['nc']:\n            logger.info('Overriding model.yaml nc=%g with nc=%g' % (self.yaml['nc'], nc))\n            self.yaml['nc'] = nc  # override yaml value\n        self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch])  # model, savelist\n        self.names = [str(i) for i in range(self.yaml['nc'])]  # default names\n        # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])\n\n        # Build strides, anchors\n        m = self.model[-1]  # Detect()\n        if isinstance(m, Detect):\n            s = 128  # 2x min stride\n            m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))])  # forward\n            m.anchors /= m.stride.view(-1, 1, 1)\n            check_anchor_order(m)\n            self.stride = m.stride\n            self._initialize_biases()  # only run once\n            # print('Strides: %s' % m.stride.tolist())\n\n        # Init weights, biases\n        initialize_weights(self)\n        self.info()\n        logger.info('')\n\n    def forward(self, x, augment=False, profile=False):\n        if augment:\n            img_size = x.shape[-2:]  # height, width\n            s = [1, 0.83, 0.67]  # scales\n            f = [None, 3, None]  # flips (2-ud, 3-lr)\n            y = []  # outputs\n            for si, fi in zip(s, f):\n                xi = scale_img(x.flip(fi) if fi else x, si)\n                yi = self.forward_once(xi)[0]  # forward\n                # cv2.imwrite('img%g.jpg' % s, 255 * xi[0].numpy().transpose((1, 2, 0))[:, :, ::-1])  # save\n                yi[..., :4] /= si  # de-scale\n                if fi == 2:\n                    yi[..., 1] = img_size[0] - yi[..., 1]  # de-flip ud\n                elif fi == 3:\n                    yi[..., 0] = img_size[1] - yi[..., 0]  # de-flip lr\n                y.append(yi)\n            return torch.cat(y, 1), None  # augmented inference, train\n        else:\n            return self.forward_once(x, profile)  # single-scale inference, train\n\n    def forward_once(self, x, profile=False):\n        y, dt = [], []  # outputs\n        for m in self.model:\n            if m.f != -1:  # if not from previous layer\n                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers\n\n            if profile:\n                o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 if thop else 0  # FLOPS\n                t = time_synchronized()\n                for _ in range(10):\n                    _ = m(x)\n                dt.append((time_synchronized() - t) * 100)\n                print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))\n\n            x = m(x)  # run\n            y.append(x if m.i in self.save else None)  # save output\n\n        if profile:\n            print('%.1fms total' % sum(dt))\n        return x\n\n    def _initialize_biases(self, cf=None):  # initialize biases into Detect(), cf is class frequency\n        # https://arxiv.org/abs/1708.02002 section 3.3\n        # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n        m = self.model[-1]  # Detect() module\n        for mi, s in zip(m.m, m.stride):  # from\n            b = mi.bias.view(m.na, -1)  # conv.bias(255) to (3,85)\n            b.data[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)\n            b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum())  # cls\n            mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n    def _print_biases(self):\n        m = self.model[-1]  # Detect() module\n        for mi in m.m:  # from\n            b = mi.bias.detach().view(m.na, -1).T  # conv.bias(255) to (3,85)\n            print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))\n\n    # def _print_weights(self):\n    #     for m in self.model.modules():\n    #         if type(m) is Bottleneck:\n    #             print('%10.3g' % (m.w.detach().sigmoid() * 2))  # shortcut weights\n\n    def fuse(self):  # fuse model Conv2d() + BatchNorm2d() layers\n        print('Fusing layers... ')\n        for m in self.model.modules():\n            if type(m) is Conv and hasattr(m, 'bn'):\n                m.conv = fuse_conv_and_bn(m.conv, m.bn)  # update conv\n                delattr(m, 'bn')  # remove batchnorm\n                m.forward = m.fuseforward  # update forward\n        self.info()\n        return self\n\n    def nms(self, mode=True):  # add or remove NMS module\n        present = type(self.model[-1]) is NMS  # last layer is NMS\n        if mode and not present:\n            print('Adding NMS... ')\n            m = NMS()  # module\n            m.f = -1  # from\n            m.i = self.model[-1].i + 1  # index\n            self.model.add_module(name='%s' % m.i, module=m)  # add\n            self.eval()\n        elif not mode and present:\n            print('Removing NMS... ')\n            self.model = self.model[:-1]  # remove\n        return self\n\n    def autoshape(self):  # add autoShape module\n        print('Adding autoShape... ')\n        m = autoShape(self)  # wrap model\n        copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=())  # copy attributes\n        return m\n\n    def info(self, verbose=False, img_size=640):  # print model information\n        model_info(self, verbose, img_size)\n\n\ndef parse_model(d, ch):  # model_dict, input_channels(3)\n    # logger.info('\\n%3s%18s%3s%10s  %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))\n    anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']\n    na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors  # number of anchors\n    no = na * (nc + 5)  # number of outputs = anchors * (classes + 5)\n\n    layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out\n    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args\n        m = eval(m) if isinstance(m, str) else m  # eval strings\n        for j, a in enumerate(args):\n            try:\n                args[j] = eval(a) if isinstance(a, str) else a  # eval strings\n            except:\n                pass\n\n        n = max(round(n * gd), 1) if n > 1 else n  # depth gain\n        if m in [Conv, Bottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3, ShuffleV2Block, StemBlock]:\n            c1, c2 = ch[f], args[0]\n\n            # Normal\n            # if i > 0 and args[0] != no:  # channel expansion factor\n            #     ex = 1.75  # exponential (default 2.0)\n            #     e = math.log(c2 / ch[1]) / math.log(2)\n            #     c2 = int(ch[1] * ex ** e)\n            # if m != Focus:\n\n            c2 = make_divisible(c2 * gw, 8) if c2 != no else c2\n\n            # Experimental\n            # if i > 0 and args[0] != no:  # channel expansion factor\n            #     ex = 1 + gw  # exponential (default 2.0)\n            #     ch1 = 32  # ch[1]\n            #     e = math.log(c2 / ch1) / math.log(2)  # level 1-n\n            #     c2 = int(ch1 * ex ** e)\n            # if m != Focus:\n            #     c2 = make_divisible(c2, 8) if c2 != no else c2\n\n            args = [c1, c2, *args[1:]]\n            if m in [BottleneckCSP, C3]:\n                args.insert(2, n)\n                n = 1\n        elif m is nn.BatchNorm2d:\n            args = [ch[f]]\n        elif m is Concat:\n            c2 = sum([ch[-1 if x == -1 else x + 1] for x in f])\n        elif m is Detect:\n            args.append([ch[x + 1] for x in f])\n            if isinstance(args[1], int):  # number of anchors\n                args[1] = [list(range(args[1] * 2))] * len(f)\n        else:\n            c2 = ch[f]\n\n        m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args)  # module\n        t = str(m)[8:-2].replace('__main__.', '')  # module type\n        np = sum([x.numel() for x in m_.parameters()])  # number params\n        m_.i, m_.f, m_.type, m_.np = i, f, t, np  # attach index, 'from' index, type, number params\n        # logger.info('%3s%18s%3s%10.0f  %-40s%-30s' % (i, f, n, np, t, args))  # print\n        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist\n        layers.append(m_)\n        ch.append(c2)\n    return nn.Sequential(*layers), sorted(save)\n\n\nfrom thop import profile\nfrom thop import clever_format\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')\n    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n    opt = parser.parse_args()\n    opt.cfg = check_file(opt.cfg)  # check file\n    set_logging()\n    device = select_device(opt.device)\n    \n    # Create model\n    model = Model(opt.cfg).to(device)\n    stride = model.stride.max()\n    if stride == 32:\n        input = torch.Tensor(1, 3, 480, 640).to(device)\n    else:\n        input = torch.Tensor(1, 3, 512, 640).to(device)\n    model.train()\n    # print(model)\n    flops, params = profile(model, inputs=(input, ))\n    flops, params = clever_format([flops, params], \"%.3f\")\n    print('Flops:', flops, ',Params:' ,params)\n"
  },
  {
    "path": "models/yolov5-0.5.yaml",
    "content": "# parameters\nnc: 1  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 0.5  # layer channel multiple\n\n# anchors\nanchors:\n  - [4,5,  8,10,  13,16]  # P3/8\n  - [23,29,  43,55,  73,105]  # P4/16\n  - [146,217,  231,300,  335,433]  # P5/32\n\n# YOLOv5 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, StemBlock, [32, 3, 2]],    # 0-P2/4\n   [-1, 1, ShuffleV2Block, [128, 2]], # 1-P3/8\n   [-1, 3, ShuffleV2Block, [128, 1]], # 2\n   [-1, 1, ShuffleV2Block, [256, 2]], # 3-P4/16\n   [-1, 7, ShuffleV2Block, [256, 1]], # 4\n   [-1, 1, ShuffleV2Block, [512, 2]], # 5-P5/32\n   [-1, 3, ShuffleV2Block, [512, 1]], # 6\n  ]\n\n# YOLOv5 head\nhead:\n  [[-1, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, C3, [128, False]],  # 10\n\n   [-1, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 2], 1, Concat, [1]],  # cat backbone P3\n   [-1, 1, C3, [128, False]],  # 14 (P3/8-small)\n\n   [-1, 1, Conv, [128, 3, 2]],\n   [[-1, 11], 1, Concat, [1]],  # cat head P4\n   [-1, 1, C3, [128, False]],  # 17 (P4/16-medium)\n\n   [-1, 1, Conv, [128, 3, 2]],\n   [[-1, 7], 1, Concat, [1]],  # cat head P5\n   [-1, 1, C3, [128, False]],  # 20 (P5/32-large)\n\n   [[14, 17, 20], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n          \n"
  },
  {
    "path": "models/yolov5l.yaml",
    "content": "# parameters\nnc: 1  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\n\n# anchors\nanchors:\n  - [4,5,  8,10,  13,16]  # P3/8\n  - [23,29,  43,55,  73,105]  # P4/16\n  - [146,217,  231,300,  335,433]  # P5/32\n\n# YOLOv5 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, StemBlock, [64, 3, 2]],  # 0-P1/2\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],      # 2-P3/8\n   [-1, 9, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],      # 4-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],     # 6-P5/32\n   [-1, 1, SPP, [1024, [3,5,7]]],\n   [-1, 3, C3, [1024, False]],      # 8\n  ]\n\n# YOLOv5 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 5], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 12\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 3], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 16 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 13], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 19 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 9], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 22 (P5/32-large)\n\n   [[16, 19, 22], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "models/yolov5l6.yaml",
    "content": "# parameters\nnc: 1  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\n\n# anchors\nanchors:\n  - [6,7,  9,11,  13,16]  # P3/8\n  - [18,23,  26,33,  37,47]  # P4/16\n  - [54,67,  77,104,  112,154]  # P5/32\n  - [174,238,  258,355,  445,568]  # P6/64\n\n# YOLOv5 backbone\nbackbone:\n  # [from, number, module, args]\n  [ [ -1, 1, StemBlock, [ 64, 3, 2 ] ],  # 0-P1/2\n    [ -1, 3, C3, [ 128 ] ],\n    [ -1, 1, Conv, [ 256, 3, 2 ] ],  # 2-P3/8\n    [ -1, 9, C3, [ 256 ] ],\n    [ -1, 1, Conv, [ 512, 3, 2 ] ],  # 4-P4/16\n    [ -1, 9, C3, [ 512 ] ],\n    [ -1, 1, Conv, [ 768, 3, 2 ] ],  # 6-P5/32\n    [ -1, 3, C3, [ 768 ] ],\n    [ -1, 1, Conv, [ 1024, 3, 2 ] ],  # 8-P6/64\n    [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],\n    [ -1, 3, C3, [ 1024, False ] ],  # 10\n  ]\n\n# YOLOv5 head\nhead:\n  [ [ -1, 1, Conv, [ 768, 1, 1 ] ],\n    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],\n    [ [ -1, 7 ], 1, Concat, [ 1 ] ],  # cat backbone P5\n    [ -1, 3, C3, [ 768, False ] ],  # 14\n\n    [ -1, 1, Conv, [ 512, 1, 1 ] ],\n    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],\n    [ [ -1, 5 ], 1, Concat, [ 1 ] ],  # cat backbone P4\n    [ -1, 3, C3, [ 512, False ] ],  # 18\n\n    [ -1, 1, Conv, [ 256, 1, 1 ] ],\n    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],\n    [ [ -1, 3 ], 1, Concat, [ 1 ] ],  # cat backbone P3\n    [ -1, 3, C3, [ 256, False ] ],  # 22 (P3/8-small)\n\n    [ -1, 1, Conv, [ 256, 3, 2 ] ],\n    [ [ -1, 19 ], 1, Concat, [ 1 ] ],  # cat head P4\n    [ -1, 3, C3, [ 512, False ] ],  # 25 (P4/16-medium)\n\n    [ -1, 1, Conv, [ 512, 3, 2 ] ],\n    [ [ -1, 15 ], 1, Concat, [ 1 ] ],  # cat head P5\n    [ -1, 3, C3, [ 768, False ] ],  # 28 (P5/32-large)\n\n    [ -1, 1, Conv, [ 768, 3, 2 ] ],\n    [ [ -1, 11 ], 1, Concat, [ 1 ] ],  # cat head P6\n    [ -1, 3, C3, [ 1024, False ] ],  # 31 (P6/64-xlarge)\n\n    [ [ 22, 25, 28, 31 ], 1, Detect, [ nc, anchors ] ],  # Detect(P3, P4, P5, P6)\n  ]\n\n"
  },
  {
    "path": "models/yolov5m.yaml",
    "content": "# parameters\nnc: 1  # number of classes\ndepth_multiple: 0.67  # model depth multiple\nwidth_multiple: 0.75  # layer channel multiple\n\n# anchors\nanchors:\n  - [4,5,  8,10,  13,16]  # P3/8\n  - [23,29,  43,55,  73,105]  # P4/16\n  - [146,217,  231,300,  335,433]  # P5/32\n\n# YOLOv5 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, StemBlock, [64, 3, 2]],  # 0-P1/2\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],      # 2-P3/8\n   [-1, 9, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],      # 4-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],     # 6-P5/32\n   [-1, 1, SPP, [1024, [3,5,7]]],\n   [-1, 3, C3, [1024, False]],      # 8\n  ]\n\n# YOLOv5 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 5], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 12\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 3], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 16 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 13], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 19 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 9], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 22 (P5/32-large)\n\n   [[16, 19, 22], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "models/yolov5m6.yaml",
    "content": "# parameters\nnc: 1  # number of classes\ndepth_multiple: 0.67  # model depth multiple\nwidth_multiple: 0.75  # layer channel multiple\n\n# anchors\nanchors:\n  - [6,7,  9,11,  13,16]  # P3/8\n  - [18,23,  26,33,  37,47]  # P4/16\n  - [54,67,  77,104,  112,154]  # P5/32\n  - [174,238,  258,355,  445,568]  # P6/64\n\n# YOLOv5 backbone\nbackbone:\n  # [from, number, module, args]\n  [ [ -1, 1, StemBlock, [ 64, 3, 2 ] ],  # 0-P1/2\n    [ -1, 3, C3, [ 128 ] ],\n    [ -1, 1, Conv, [ 256, 3, 2 ] ],  # 2-P3/8\n    [ -1, 9, C3, [ 256 ] ],\n    [ -1, 1, Conv, [ 512, 3, 2 ] ],  # 4-P4/16\n    [ -1, 9, C3, [ 512 ] ],\n    [ -1, 1, Conv, [ 768, 3, 2 ] ],  # 6-P5/32\n    [ -1, 3, C3, [ 768 ] ],\n    [ -1, 1, Conv, [ 1024, 3, 2 ] ],  # 8-P6/64\n    [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],\n    [ -1, 3, C3, [ 1024, False ] ],  # 10\n  ]\n\n# YOLOv5 head\nhead:\n  [ [ -1, 1, Conv, [ 768, 1, 1 ] ],\n    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],\n    [ [ -1, 7 ], 1, Concat, [ 1 ] ],  # cat backbone P5\n    [ -1, 3, C3, [ 768, False ] ],  # 14\n\n    [ -1, 1, Conv, [ 512, 1, 1 ] ],\n    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],\n    [ [ -1, 5 ], 1, Concat, [ 1 ] ],  # cat backbone P4\n    [ -1, 3, C3, [ 512, False ] ],  # 18\n\n    [ -1, 1, Conv, [ 256, 1, 1 ] ],\n    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],\n    [ [ -1, 3 ], 1, Concat, [ 1 ] ],  # cat backbone P3\n    [ -1, 3, C3, [ 256, False ] ],  # 22 (P3/8-small)\n\n    [ -1, 1, Conv, [ 256, 3, 2 ] ],\n    [ [ -1, 19 ], 1, Concat, [ 1 ] ],  # cat head P4\n    [ -1, 3, C3, [ 512, False ] ],  # 25 (P4/16-medium)\n\n    [ -1, 1, Conv, [ 512, 3, 2 ] ],\n    [ [ -1, 15 ], 1, Concat, [ 1 ] ],  # cat head P5\n    [ -1, 3, C3, [ 768, False ] ],  # 28 (P5/32-large)\n\n    [ -1, 1, Conv, [ 768, 3, 2 ] ],\n    [ [ -1, 11 ], 1, Concat, [ 1 ] ],  # cat head P6\n    [ -1, 3, C3, [ 1024, False ] ],  # 31 (P6/64-xlarge)\n\n    [ [ 22, 25, 28, 31 ], 1, Detect, [ nc, anchors ] ],  # Detect(P3, P4, P5, P6)\n  ]\n\n"
  },
  {
    "path": "models/yolov5n.yaml",
    "content": "# parameters\nnc: 1  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\n\n# anchors\nanchors:\n  - [4,5,  8,10,  13,16]  # P3/8\n  - [23,29,  43,55,  73,105]  # P4/16\n  - [146,217,  231,300,  335,433]  # P5/32\n\n# YOLOv5 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, StemBlock, [32, 3, 2]],    # 0-P2/4\n   [-1, 1, ShuffleV2Block, [128, 2]], # 1-P3/8\n   [-1, 3, ShuffleV2Block, [128, 1]], # 2\n   [-1, 1, ShuffleV2Block, [256, 2]], # 3-P4/16\n   [-1, 7, ShuffleV2Block, [256, 1]], # 4\n   [-1, 1, ShuffleV2Block, [512, 2]], # 5-P5/32\n   [-1, 3, ShuffleV2Block, [512, 1]], # 6\n  ]\n\n# YOLOv5 head\nhead:\n  [[-1, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, C3, [128, False]],  # 10\n\n   [-1, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 2], 1, Concat, [1]],  # cat backbone P3\n   [-1, 1, C3, [128, False]],  # 14 (P3/8-small)\n\n   [-1, 1, Conv, [128, 3, 2]],\n   [[-1, 11], 1, Concat, [1]],  # cat head P4\n   [-1, 1, C3, [128, False]],  # 17 (P4/16-medium)\n\n   [-1, 1, Conv, [128, 3, 2]],\n   [[-1, 7], 1, Concat, [1]],  # cat head P5\n   [-1, 1, C3, [128, False]],  # 20 (P5/32-large)\n\n   [[14, 17, 20], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n          \n"
  },
  {
    "path": "models/yolov5n6.yaml",
    "content": "# parameters\nnc: 1  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\n\n# anchors\nanchors:\n  - [6,7,  9,11,  13,16]  # P3/8\n  - [18,23,  26,33,  37,47]  # P4/16\n  - [54,67,  77,104,  112,154]  # P5/32\n  - [174,238,  258,355,  445,568]  # P6/64\n\n# YOLOv5 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, StemBlock, [32, 3, 2]],    # 0-P2/4\n   [-1, 1, ShuffleV2Block, [128, 2]], # 1-P3/8\n   [-1, 3, ShuffleV2Block, [128, 1]], # 2\n   [-1, 1, ShuffleV2Block, [256, 2]], # 3-P4/16\n   [-1, 7, ShuffleV2Block, [256, 1]], # 4\n   [-1, 1, ShuffleV2Block, [384, 2]], # 5-P5/32\n   [-1, 3, ShuffleV2Block, [384, 1]], # 6\n   [-1, 1, ShuffleV2Block, [512, 2]], # 7-P6/64\n   [-1, 3, ShuffleV2Block, [512, 1]], # 8\n  ]\n\n# YOLOv5 head\nhead:\n  [[-1, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P5\n   [-1, 1, C3, [128, False]],  # 12\n\n   [-1, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, C3, [128, False]],  # 16 (P4/8-small)\n\n   [-1, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 2], 1, Concat, [1]],  # cat backbone P3\n   [-1, 1, C3, [128, False]],  # 20 (P3/8-small)\n\n   [-1, 1, Conv, [128, 3, 2]],\n   [[-1, 17], 1, Concat, [1]],  # cat head P4\n   [-1, 1, C3, [128, False]],  # 23 (P4/16-medium)\n\n   [-1, 1, Conv, [128, 3, 2]],\n   [[-1, 13], 1, Concat, [1]],  # cat head P5\n   [-1, 1, C3, [128, False]],  # 26 (P5/32-large)\n\n   [-1, 1, Conv, [128, 3, 2]],\n   [[-1, 9], 1, Concat, [1]],  # cat head P6\n   [-1, 1, C3, [128, False]],  # 29 (P6/64-large)\n\n   [[20, 23, 26, 29], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n          \n"
  },
  {
    "path": "models/yolov5s.yaml",
    "content": "# parameters\nnc: 1  # number of classes\ndepth_multiple: 0.33  # model depth multiple\nwidth_multiple: 0.35  # layer channel multiple\n\n# anchors\nanchors:\n  - [4,5,  8,10,  13,16]  # P3/8\n  - [23,29,  43,55,  73,105]  # P4/16\n  - [146,217,  231,300,  335,433]  # P5/32\n\n# YOLOv5 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, StemBlock, [64, 3, 2]],  # 0-P1/2\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],      # 2-P3/8\n   [-1, 9, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],      # 4-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],     # 6-P5/32\n   [-1, 1, SPP, [1024, [3,5,7]]],\n   [-1, 3, C3, [1024, False]],      # 8\n  ]\n\n# YOLOv5 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 5], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 12\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 3], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 16 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 13], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 19 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 9], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 22 (P5/32-large)\n\n   [[16, 19, 22], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "models/yolov5s6.yaml",
    "content": "# parameters\nnc: 1  # number of classes\ndepth_multiple: 0.33  # model depth multiple\nwidth_multiple: 0.50  # layer channel multiple\n\n# anchors\nanchors:\n  - [6,7,  9,11,  13,16]  # P3/8\n  - [18,23,  26,33,  37,47]  # P4/16\n  - [54,67,  77,104,  112,154]  # P5/32\n  - [174,238,  258,355,  445,568]  # P6/64\n\n# YOLOv5 backbone\nbackbone:\n  # [from, number, module, args]\n  [ [ -1, 1, StemBlock, [ 64, 3, 2 ] ],  # 0-P1/2\n    [ -1, 3, C3, [ 128 ] ],\n    [ -1, 1, Conv, [ 256, 3, 2 ] ],  # 2-P3/8\n    [ -1, 9, C3, [ 256 ] ],\n    [ -1, 1, Conv, [ 512, 3, 2 ] ],  # 4-P4/16\n    [ -1, 9, C3, [ 512 ] ],\n    [ -1, 1, Conv, [ 768, 3, 2 ] ],  # 6-P5/32\n    [ -1, 3, C3, [ 768 ] ],\n    [ -1, 1, Conv, [ 1024, 3, 2 ] ],  # 8-P6/64\n    [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ],\n    [ -1, 3, C3, [ 1024, False ] ],  # 10\n  ]\n\n# YOLOv5 head\nhead:\n  [ [ -1, 1, Conv, [ 768, 1, 1 ] ],\n    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],\n    [ [ -1, 7 ], 1, Concat, [ 1 ] ],  # cat backbone P5\n    [ -1, 3, C3, [ 768, False ] ],  # 14\n\n    [ -1, 1, Conv, [ 512, 1, 1 ] ],\n    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],\n    [ [ -1, 5 ], 1, Concat, [ 1 ] ],  # cat backbone P4\n    [ -1, 3, C3, [ 512, False ] ],  # 18\n\n    [ -1, 1, Conv, [ 256, 1, 1 ] ],\n    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],\n    [ [ -1, 3 ], 1, Concat, [ 1 ] ],  # cat backbone P3\n    [ -1, 3, C3, [ 256, False ] ],  # 22 (P3/8-small)\n\n    [ -1, 1, Conv, [ 256, 3, 2 ] ],\n    [ [ -1, 19 ], 1, Concat, [ 1 ] ],  # cat head P4\n    [ -1, 3, C3, [ 512, False ] ],  # 25 (P4/16-medium)\n\n    [ -1, 1, Conv, [ 512, 3, 2 ] ],\n    [ [ -1, 15 ], 1, Concat, [ 1 ] ],  # cat head P5\n    [ -1, 3, C3, [ 768, False ] ],  # 28 (P5/32-large)\n\n    [ -1, 1, Conv, [ 768, 3, 2 ] ],\n    [ [ -1, 11 ], 1, Concat, [ 1 ] ],  # cat head P6\n    [ -1, 3, C3, [ 1024, False ] ],  # 31 (P6/64-xlarge)\n\n    [ [ 22, 25, 28, 31 ], 1, Detect, [ nc, anchors ] ],  # Detect(P3, P4, P5, P6)\n  ]\n\n"
  },
  {
    "path": "requirements.txt",
    "content": "joblib==1.2.0\nmatplotlib==3.5.1\nnumpy==1.22.4\nonnx==1.12.0\nopencv_python==4.6.0.66\npandas==1.4.2\nPillow==9.3.0\nPyYAML==6.0\nrequests==2.27.1\nscipy==1.7.3\nseaborn==0.11.2\nsetuptools==61.2.0\nthop==0.1.1.post2207130030\ntorch==1.12.1+cu116\ntorchvision==0.13.1+cu116\ntqdm==4.64.0\nwandb==0.13.6\n"
  },
  {
    "path": "utils/__init__.py",
    "content": ""
  },
  {
    "path": "utils/activations.py",
    "content": "# Activation functions\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n# SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------\nclass SiLU(nn.Module):  # export-friendly version of nn.SiLU()\n    @staticmethod\n    def forward(x):\n        return x * torch.sigmoid(x)\n\n\nclass Hardswish(nn.Module):  # export-friendly version of nn.Hardswish()\n    @staticmethod\n    def forward(x):\n        # return x * F.hardsigmoid(x)  # for torchscript and CoreML\n        return x * F.hardtanh(x + 3, 0., 6.) / 6.  # for torchscript, CoreML and ONNX\n\n\nclass MemoryEfficientSwish(nn.Module):\n    class F(torch.autograd.Function):\n        @staticmethod\n        def forward(ctx, x):\n            ctx.save_for_backward(x)\n            return x * torch.sigmoid(x)\n\n        @staticmethod\n        def backward(ctx, grad_output):\n            x = ctx.saved_tensors[0]\n            sx = torch.sigmoid(x)\n            return grad_output * (sx * (1 + x * (1 - sx)))\n\n    def forward(self, x):\n        return self.F.apply(x)\n\n\n# Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------\nclass Mish(nn.Module):\n    @staticmethod\n    def forward(x):\n        return x * F.softplus(x).tanh()\n\n\nclass MemoryEfficientMish(nn.Module):\n    class F(torch.autograd.Function):\n        @staticmethod\n        def forward(ctx, x):\n            ctx.save_for_backward(x)\n            return x.mul(torch.tanh(F.softplus(x)))  # x * tanh(ln(1 + exp(x)))\n\n        @staticmethod\n        def backward(ctx, grad_output):\n            x = ctx.saved_tensors[0]\n            sx = torch.sigmoid(x)\n            fx = F.softplus(x).tanh()\n            return grad_output * (fx + x * sx * (1 - fx * fx))\n\n    def forward(self, x):\n        return self.F.apply(x)\n\n\n# FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------\nclass FReLU(nn.Module):\n    def __init__(self, c1, k=3):  # ch_in, kernel\n        super().__init__()\n        self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)\n        self.bn = nn.BatchNorm2d(c1)\n\n    def forward(self, x):\n        return torch.max(x, self.bn(self.conv(x)))\n"
  },
  {
    "path": "utils/autoanchor.py",
    "content": "# Auto-anchor utils\n\nimport numpy as np\nimport torch\nimport yaml\nfrom scipy.cluster.vq import kmeans\nfrom tqdm import tqdm\n\nfrom utils.general import colorstr\n\n\ndef check_anchor_order(m):\n    # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary\n    a = m.anchor_grid.prod(-1).view(-1)  # anchor area\n    da = a[-1] - a[0]  # delta a\n    ds = m.stride[-1] - m.stride[0]  # delta s\n    if da.sign() != ds.sign():  # same order\n        print('Reversing anchor order')\n        m.anchors[:] = m.anchors.flip(0)\n        m.anchor_grid[:] = m.anchor_grid.flip(0)\n\n\ndef check_anchors(dataset, model, thr=4.0, imgsz=640):\n    # Check anchor fit to data, recompute if necessary\n    prefix = colorstr('autoanchor: ')\n    print(f'\\n{prefix}Analyzing anchors... ', end='')\n    m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1]  # Detect()\n    shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)\n    scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1))  # augment scale\n    wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float()  # wh\n\n    def metric(k):  # compute metric\n        r = wh[:, None] / k[None]\n        x = torch.min(r, 1. / r).min(2)[0]  # ratio metric\n        best = x.max(1)[0]  # best_x\n        aat = (x > 1. / thr).float().sum(1).mean()  # anchors above threshold\n        bpr = (best > 1. / thr).float().mean()  # best possible recall\n        return bpr, aat\n\n    bpr, aat = metric(m.anchor_grid.clone().cpu().view(-1, 2))\n    print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')\n    if bpr < 0.98:  # threshold to recompute\n        print('. Attempting to improve anchors, please wait...')\n        na = m.anchor_grid.numel() // 2  # number of anchors\n        new_anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)\n        new_bpr = metric(new_anchors.reshape(-1, 2))[0]\n        if new_bpr > bpr:  # replace anchors\n            new_anchors = torch.tensor(new_anchors, device=m.anchors.device).type_as(m.anchors)\n            m.anchor_grid[:] = new_anchors.clone().view_as(m.anchor_grid)  # for inference\n            m.anchors[:] = new_anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1)  # loss\n            check_anchor_order(m)\n            print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')\n        else:\n            print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')\n    print('')  # newline\n\n\ndef kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):\n    \"\"\" Creates kmeans-evolved anchors from training dataset\n\n        Arguments:\n            path: path to dataset *.yaml, or a loaded dataset\n            n: number of anchors\n            img_size: image size used for training\n            thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0\n            gen: generations to evolve anchors using genetic algorithm\n            verbose: print all results\n\n        Return:\n            k: kmeans evolved anchors\n\n        Usage:\n            from utils.autoanchor import *; _ = kmean_anchors()\n    \"\"\"\n    thr = 1. / thr\n    prefix = colorstr('autoanchor: ')\n\n    def metric(k, wh):  # compute metrics\n        r = wh[:, None] / k[None]\n        x = torch.min(r, 1. / r).min(2)[0]  # ratio metric\n        # x = wh_iou(wh, torch.tensor(k))  # iou metric\n        return x, x.max(1)[0]  # x, best_x\n\n    def anchor_fitness(k):  # mutation fitness\n        _, best = metric(torch.tensor(k, dtype=torch.float32), wh)\n        return (best * (best > thr).float()).mean()  # fitness\n\n    def print_results(k):\n        k = k[np.argsort(k.prod(1))]  # sort small to large\n        x, best = metric(k, wh0)\n        bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n  # best possible recall, anch > thr\n        print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')\n        print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '\n              f'past_thr={x[x > thr].mean():.3f}-mean: ', end='')\n        for i, x in enumerate(k):\n            print('%i,%i' % (round(x[0]), round(x[1])), end=',  ' if i < len(k) - 1 else '\\n')  # use in *.cfg\n        return k\n\n    if isinstance(path, str):  # *.yaml file\n        with open(path) as f:\n            data_dict = yaml.load(f, Loader=yaml.SafeLoader)  # model dict\n        from utils.datasets import LoadImagesAndLabels\n        dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)\n    else:\n        dataset = path  # dataset\n\n    # Get label wh\n    shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)\n    wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)])  # wh\n\n    # Filter\n    i = (wh0 < 3.0).any(1).sum()\n    if i:\n        print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')\n    wh = wh0[(wh0 >= 2.0).any(1)]  # filter > 2 pixels\n    # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1)  # multiply by random scale 0-1\n\n    # Kmeans calculation\n    print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')\n    s = wh.std(0)  # sigmas for whitening\n    k, dist = kmeans(wh / s, n, iter=30)  # points, mean distance\n    k *= s\n    wh = torch.tensor(wh, dtype=torch.float32)  # filtered\n    wh0 = torch.tensor(wh0, dtype=torch.float32)  # unfiltered\n    k = print_results(k)\n\n    # Plot\n    # k, d = [None] * 20, [None] * 20\n    # for i in tqdm(range(1, 21)):\n    #     k[i-1], d[i-1] = kmeans(wh / s, i)  # points, mean distance\n    # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)\n    # ax = ax.ravel()\n    # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')\n    # fig, ax = plt.subplots(1, 2, figsize=(14, 7))  # plot wh\n    # ax[0].hist(wh[wh[:, 0]<100, 0],400)\n    # ax[1].hist(wh[wh[:, 1]<100, 1],400)\n    # fig.savefig('wh.png', dpi=200)\n\n    # Evolve\n    npr = np.random\n    f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1  # fitness, generations, mutation prob, sigma\n    pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:')  # progress bar\n    for _ in pbar:\n        v = np.ones(sh)\n        while (v == 1).all():  # mutate until a change occurs (prevent duplicates)\n            v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)\n        kg = (k.copy() * v).clip(min=2.0)\n        fg = anchor_fitness(kg)\n        if fg > f:\n            f, k = fg, kg.copy()\n            pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'\n            if verbose:\n                print_results(k)\n\n    return print_results(k)\n"
  },
  {
    "path": "utils/aws/__init__.py",
    "content": ""
  },
  {
    "path": "utils/aws/mime.sh",
    "content": "# AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/\n# This script will run on every instance restart, not only on first start\n# --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA ---\n\nContent-Type: multipart/mixed; boundary=\"//\"\nMIME-Version: 1.0\n\n--//\nContent-Type: text/cloud-config; charset=\"us-ascii\"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment; filename=\"cloud-config.txt\"\n\n#cloud-config\ncloud_final_modules:\n- [scripts-user, always]\n\n--//\nContent-Type: text/x-shellscript; charset=\"us-ascii\"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment; filename=\"userdata.txt\"\n\n#!/bin/bash\n# --- paste contents of userdata.sh here ---\n--//\n"
  },
  {
    "path": "utils/aws/resume.py",
    "content": "# Resume all interrupted trainings in yolov5/ dir including DDP trainings\n# Usage: $ python utils/aws/resume.py\n\nimport os\nimport sys\nfrom pathlib import Path\n\nimport torch\nimport yaml\n\nsys.path.append('./')  # to run '$ python *.py' files in subdirectories\n\nport = 0  # --master_port\npath = Path('').resolve()\nfor last in path.rglob('*/**/last.pt'):\n    ckpt = torch.load(last)\n    if ckpt['optimizer'] is None:\n        continue\n\n    # Load opt.yaml\n    with open(last.parent.parent / 'opt.yaml') as f:\n        opt = yaml.load(f, Loader=yaml.SafeLoader)\n\n    # Get device count\n    d = opt['device'].split(',')  # devices\n    nd = len(d)  # number of devices\n    ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1)  # distributed data parallel\n\n    if ddp:  # multi-GPU\n        port += 1\n        cmd = f'python -m torch.distributed.launch --nproc_per_node {nd} --master_port {port} train.py --resume {last}'\n    else:  # single-GPU\n        cmd = f'python train.py --resume {last}'\n\n    cmd += ' > /dev/null 2>&1 &'  # redirect output to dev/null and run in daemon thread\n    print(cmd)\n    os.system(cmd)\n"
  },
  {
    "path": "utils/aws/userdata.sh",
    "content": "#!/bin/bash\n# AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html\n# This script will run only once on first instance start (for a re-start script see mime.sh)\n# /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir\n# Use >300 GB SSD\n\ncd home/ubuntu\nif [ ! -d yolov5 ]; then\n  echo \"Running first-time script.\" # install dependencies, download COCO, pull Docker\n  git clone https://github.com/ultralytics/yolov5 && sudo chmod -R 777 yolov5\n  cd yolov5\n  bash data/scripts/get_coco.sh && echo \"Data done.\" &\n  sudo docker pull ultralytics/yolov5:latest && echo \"Docker done.\" &\n  python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo \"Requirements done.\" &\n  wait && echo \"All tasks done.\" # finish background tasks\nelse\n  echo \"Running re-start script.\" # resume interrupted runs\n  i=0\n  list=$(sudo docker ps -qa) # container list i.e. $'one\\ntwo\\nthree\\nfour'\n  while IFS= read -r id; do\n    ((i++))\n    echo \"restarting container $i: $id\"\n    sudo docker start $id\n    # sudo docker exec -it $id python train.py --resume # single-GPU\n    sudo docker exec -d $id python utils/aws/resume.py # multi-scenario\n  done <<<\"$list\"\nfi\n"
  },
  {
    "path": "utils/datasets.py",
    "content": "# Dataset utils and dataloaders\n\nimport glob\nimport logging\nimport math\nimport os\nimport random\nimport shutil\nimport time\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom threading import Thread\n\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom PIL import Image, ExifTags\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\n\nfrom utils.general import xyxy2xywh, xywh2xyxy, xywhn2xyxy, clean_str\nfrom utils.torch_utils import torch_distributed_zero_first\n\n# Parameters\nhelp_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'\nimg_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng']  # acceptable image suffixes\nvid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv']  # acceptable video suffixes\nlogger = logging.getLogger(__name__)\n\n# Get orientation exif tag\nfor orientation in ExifTags.TAGS.keys():\n    if ExifTags.TAGS[orientation] == 'Orientation':\n        break\n\n\ndef get_hash(files):\n    # Returns a single hash value of a list of files\n    return sum(os.path.getsize(f) for f in files if os.path.isfile(f))\n\n\ndef exif_size(img):\n    # Returns exif-corrected PIL size\n    s = img.size  # (width, height)\n    try:\n        rotation = dict(img._getexif().items())[orientation]\n        if rotation == 6:  # rotation 270\n            s = (s[1], s[0])\n        elif rotation == 8:  # rotation 90\n            s = (s[1], s[0])\n    except:\n        pass\n\n    return s\n\n\ndef create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,\n                      rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''):\n    # Make sure only the first process in DDP process the dataset first, and the following others can use the cache\n    with torch_distributed_zero_first(rank):\n        dataset = LoadImagesAndLabels(path, imgsz, batch_size,\n                                      augment=augment,  # augment images\n                                      hyp=hyp,  # augmentation hyperparameters\n                                      rect=rect,  # rectangular training\n                                      cache_images=cache,\n                                      single_cls=opt.single_cls,\n                                      stride=int(stride),\n                                      pad=pad,\n                                      image_weights=image_weights,\n                                      prefix=prefix)\n\n    batch_size = min(batch_size, len(dataset))\n    nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers])  # number of workers\n    sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None\n    loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader\n    # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()\n    dataloader = loader(dataset,\n                        batch_size=batch_size,\n                        num_workers=nw,\n                        sampler=sampler,\n                        pin_memory=True,\n                        collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)\n    return dataloader, dataset\n\n\nclass InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):\n    \"\"\" Dataloader that reuses workers\n\n    Uses same syntax as vanilla DataLoader\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))\n        self.iterator = super().__iter__()\n\n    def __len__(self):\n        return len(self.batch_sampler.sampler)\n\n    def __iter__(self):\n        for i in range(len(self)):\n            yield next(self.iterator)\n\n\nclass _RepeatSampler(object):\n    \"\"\" Sampler that repeats forever\n\n    Args:\n        sampler (Sampler)\n    \"\"\"\n\n    def __init__(self, sampler):\n        self.sampler = sampler\n\n    def __iter__(self):\n        while True:\n            yield from iter(self.sampler)\n\n\nclass LoadImages:  # for inference\n    def __init__(self, path, img_size=640):\n        p = str(Path(path))  # os-agnostic\n        p = os.path.abspath(p)  # absolute path\n        if '*' in p:\n            files = sorted(glob.glob(p, recursive=True))  # glob\n        elif os.path.isdir(p):\n            files = sorted(glob.glob(os.path.join(p, '*.*')))  # dir\n        elif os.path.isfile(p):\n            files = [p]  # files\n        else:\n            raise Exception(f'ERROR: {p} does not exist')\n\n        images = [x for x in files if x.split('.')[-1].lower() in img_formats]\n        videos = [x for x in files if x.split('.')[-1].lower() in vid_formats]\n        ni, nv = len(images), len(videos)\n\n        self.img_size = img_size\n        self.files = images + videos\n        self.nf = ni + nv  # number of files\n        self.video_flag = [False] * ni + [True] * nv\n        self.mode = 'image'\n        if any(videos):\n            self.new_video(videos[0])  # new video\n        else:\n            self.cap = None\n        assert self.nf > 0, f'No images or videos found in {p}. ' \\\n                            f'Supported formats are:\\nimages: {img_formats}\\nvideos: {vid_formats}'\n\n    def __iter__(self):\n        self.count = 0\n        return self\n\n    def __next__(self):\n        if self.count == self.nf:\n            raise StopIteration\n        path = self.files[self.count]\n\n        if self.video_flag[self.count]:\n            # Read video\n            self.mode = 'video'\n            ret_val, img0 = self.cap.read()\n            if not ret_val:\n                self.count += 1\n                self.cap.release()\n                if self.count == self.nf:  # last video\n                    raise StopIteration\n                else:\n                    path = self.files[self.count]\n                    self.new_video(path)\n                    ret_val, img0 = self.cap.read()\n\n            self.frame += 1\n            print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.nframes}) {path}: ', end='')\n\n        else:\n            # Read image\n            self.count += 1\n            img0 = cv2.imread(path)  # BGR\n            assert img0 is not None, 'Image Not Found ' + path\n            print(f'image {self.count}/{self.nf} {path}: ', end='')\n\n        # Padded resize\n        img = letterbox(img0, new_shape=self.img_size)[0]\n\n        # Convert\n        img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416\n        img = np.ascontiguousarray(img)\n\n        return path, img, img0, self.cap\n\n    def new_video(self, path):\n        self.frame = 0\n        self.cap = cv2.VideoCapture(path)\n        self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n    def __len__(self):\n        return self.nf  # number of files\n\n\nclass LoadWebcam:  # for inference\n    def __init__(self, pipe='0', img_size=640):\n        self.img_size = img_size\n\n        if pipe.isnumeric():\n            pipe = eval(pipe)  # local camera\n        # pipe = 'rtsp://192.168.1.64/1'  # IP camera\n        # pipe = 'rtsp://username:password@192.168.1.64/1'  # IP camera with login\n        # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg'  # IP golf camera\n\n        self.pipe = pipe\n        self.cap = cv2.VideoCapture(pipe)  # video capture object\n        self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3)  # set buffer size\n\n    def __iter__(self):\n        self.count = -1\n        return self\n\n    def __next__(self):\n        self.count += 1\n        if cv2.waitKey(1) == ord('q'):  # q to quit\n            self.cap.release()\n            cv2.destroyAllWindows()\n            raise StopIteration\n\n        # Read frame\n        if self.pipe == 0:  # local camera\n            ret_val, img0 = self.cap.read()\n            img0 = cv2.flip(img0, 1)  # flip left-right\n        else:  # IP camera\n            n = 0\n            while True:\n                n += 1\n                self.cap.grab()\n                if n % 30 == 0:  # skip frames\n                    ret_val, img0 = self.cap.retrieve()\n                    if ret_val:\n                        break\n\n        # Print\n        assert ret_val, f'Camera Error {self.pipe}'\n        img_path = 'webcam.jpg'\n        print(f'webcam {self.count}: ', end='')\n\n        # Padded resize\n        img = letterbox(img0, new_shape=self.img_size)[0]\n\n        # Convert\n        img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416\n        img = np.ascontiguousarray(img)\n\n        return img_path, img, img0, None\n\n    def __len__(self):\n        return 0\n\n\nclass LoadStreams:  # multiple IP or RTSP cameras\n    def __init__(self, sources='streams.txt', img_size=640):\n        self.mode = 'stream'\n        self.img_size = img_size\n\n        if os.path.isfile(sources):\n            with open(sources, 'r') as f:\n                sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]\n        else:\n            sources = [sources]\n\n        n = len(sources)\n        self.imgs = [None] * n\n        self.sources = [clean_str(x) for x in sources]  # clean source names for later\n        for i, s in enumerate(sources):\n            # Start the thread to read frames from the video stream\n            print(f'{i + 1}/{n}: {s}... ', end='')\n            cap = cv2.VideoCapture(eval(s) if s.isnumeric() else s)\n            assert cap.isOpened(), f'Failed to open {s}'\n            w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n            h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n            fps = cap.get(cv2.CAP_PROP_FPS) % 100\n            _, self.imgs[i] = cap.read()  # guarantee first frame\n            thread = Thread(target=self.update, args=([i, cap]), daemon=True)\n            print(f' success ({w}x{h} at {fps:.2f} FPS).')\n            thread.start()\n        print('')  # newline\n\n        # check for common shapes\n        s = np.stack([letterbox(x, new_shape=self.img_size)[0].shape for x in self.imgs], 0)  # inference shapes\n        self.rect = np.unique(s, axis=0).shape[0] == 1  # rect inference if all shapes equal\n        if not self.rect:\n            print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')\n\n    def update(self, index, cap):\n        # Read next stream frame in a daemon thread\n        n = 0\n        while cap.isOpened():\n            n += 1\n            # _, self.imgs[index] = cap.read()\n            cap.grab()\n            if n == 4:  # read every 4th frame\n                _, self.imgs[index] = cap.retrieve()\n                n = 0\n            time.sleep(0.01)  # wait time\n\n    def __iter__(self):\n        self.count = -1\n        return self\n\n    def __next__(self):\n        self.count += 1\n        img0 = self.imgs.copy()\n        if cv2.waitKey(1) == ord('q'):  # q to quit\n            cv2.destroyAllWindows()\n            raise StopIteration\n\n        # Letterbox\n        img = [letterbox(x, new_shape=self.img_size, auto=self.rect)[0] for x in img0]\n\n        # Stack\n        img = np.stack(img, 0)\n\n        # Convert\n        img = img[:, :, :, ::-1].transpose(0, 3, 1, 2)  # BGR to RGB, to bsx3x416x416\n        img = np.ascontiguousarray(img)\n\n        return self.sources, img, img0, None\n\n    def __len__(self):\n        return 0  # 1E12 frames = 32 streams at 30 FPS for 30 years\n\n\ndef img2label_paths(img_paths):\n    # Define label paths as a function of image paths\n    sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep  # /images/, /labels/ substrings\n    return [x.replace(sa, sb, 1).replace('.' + x.split('.')[-1], '.txt') for x in img_paths]\n\n\nclass LoadImagesAndLabels(Dataset):  # for training/testing\n    def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,\n                 cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):\n        self.img_size = img_size\n        self.augment = augment\n        self.hyp = hyp\n        self.image_weights = image_weights\n        self.rect = False if image_weights else rect\n        self.mosaic = self.augment and not self.rect  # load 4 images at a time into a mosaic (only during training)\n        self.mosaic_border = [-img_size // 2, -img_size // 2]\n        self.stride = stride\n\n        try:\n            f = []  # image files\n            for p in path if isinstance(path, list) else [path]:\n                p = Path(p)  # os-agnostic\n                if p.is_dir():  # dir\n                    f += glob.glob(str(p / '**' / '*.*'), recursive=True)\n                elif p.is_file():  # file\n                    with open(p, 'r') as t:\n                        t = t.read().strip().splitlines()\n                        parent = str(p.parent) + os.sep\n                        f += [x.replace('./', parent) if x.startswith('./') else x for x in t]  # local to global path\n                else:\n                    raise Exception(f'{prefix}{p} does not exist')\n            self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats])\n            assert self.img_files, f'{prefix}No images found'\n        except Exception as e:\n            raise Exception(f'{prefix}Error loading data from {path}: {e}\\nSee {help_url}')\n\n        # Check cache\n        self.label_files = img2label_paths(self.img_files)  # labels\n        cache_path = Path(self.label_files[0]).parent.with_suffix('.cache')  # cached labels\n        if cache_path.is_file():\n            cache = torch.load(cache_path)  # load\n            if cache['hash'] != get_hash(self.label_files + self.img_files) or 'results' not in cache:  # changed\n                cache = self.cache_labels(cache_path, prefix)  # re-cache\n        else:\n            cache = self.cache_labels(cache_path, prefix)  # cache\n\n        # Display cache\n        [nf, nm, ne, nc, n] = cache.pop('results')  # found, missing, empty, corrupted, total\n        desc = f\"Scanning '{cache_path}' for images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted\"\n        tqdm(None, desc=prefix + desc, total=n, initial=n)\n        assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}'\n\n        # Read cache\n        cache.pop('hash')  # remove hash\n        labels, shapes = zip(*cache.values())\n        self.labels = list(labels)\n        self.shapes = np.array(shapes, dtype=np.float64)\n        self.img_files = list(cache.keys())  # update\n        self.label_files = img2label_paths(cache.keys())  # update\n        if single_cls:\n            for x in self.labels:\n                x[:, 0] = 0\n\n        n = len(shapes)  # number of images\n        bi = np.floor(np.arange(n) / batch_size).astype(np.int)  # batch index\n        nb = bi[-1] + 1  # number of batches\n        self.batch = bi  # batch index of image\n        self.n = n\n        self.indices = range(n)\n\n        # Rectangular Training\n        if self.rect:\n            # Sort by aspect ratio\n            s = self.shapes  # wh\n            ar = s[:, 1] / s[:, 0]  # aspect ratio\n            irect = ar.argsort()\n            self.img_files = [self.img_files[i] for i in irect]\n            self.label_files = [self.label_files[i] for i in irect]\n            self.labels = [self.labels[i] for i in irect]\n            self.shapes = s[irect]  # wh\n            ar = ar[irect]\n\n            # Set training image shapes\n            shapes = [[1, 1]] * nb\n            for i in range(nb):\n                ari = ar[bi == i]\n                mini, maxi = ari.min(), ari.max()\n                if maxi < 1:\n                    shapes[i] = [maxi, 1]\n                elif mini > 1:\n                    shapes[i] = [1, 1 / mini]\n\n            self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride\n\n        # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)\n        self.imgs = [None] * n\n        if cache_images:\n            gb = 0  # Gigabytes of cached images\n            self.img_hw0, self.img_hw = [None] * n, [None] * n\n            results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))  # 8 threads\n            pbar = tqdm(enumerate(results), total=n)\n            for i, x in pbar:\n                self.imgs[i], self.img_hw0[i], self.img_hw[i] = x  # img, hw_original, hw_resized = load_image(self, i)\n                gb += self.imgs[i].nbytes\n                pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)'\n\n    def cache_labels(self, path=Path('./labels.cache'), prefix=''):\n        # Cache dataset labels, check images and read shapes\n        x = {}  # dict\n        nm, nf, ne, nc = 0, 0, 0, 0  # number missing, found, empty, duplicate\n        pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files))\n        for i, (im_file, lb_file) in enumerate(pbar):\n            try:\n                # verify images\n                im = Image.open(im_file)\n                im.verify()  # PIL verify\n                shape = exif_size(im)  # image size\n                assert (shape[0] > 9) & (shape[1] > 9), 'image size <10 pixels'\n\n                # verify labels\n                if os.path.isfile(lb_file):\n                    nf += 1  # label found\n                    with open(lb_file, 'r') as f:\n                        l = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)  # labels\n                    if len(l):\n                        assert l.shape[1] == 5, 'labels require 5 columns each'\n                        assert (l >= 0).all(), 'negative labels'\n                        assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'\n                        assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'\n                    else:\n                        ne += 1  # label empty\n                        l = np.zeros((0, 5), dtype=np.float32)\n                else:\n                    nm += 1  # label missing\n                    l = np.zeros((0, 5), dtype=np.float32)\n                x[im_file] = [l, shape]\n            except Exception as e:\n                nc += 1\n                print(f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}')\n\n            pbar.desc = f\"{prefix}Scanning '{path.parent / path.stem}' for images and labels... \" \\\n                        f\"{nf} found, {nm} missing, {ne} empty, {nc} corrupted\"\n\n        if nf == 0:\n            print(f'{prefix}WARNING: No labels found in {path}. See {help_url}')\n\n        x['hash'] = get_hash(self.label_files + self.img_files)\n        x['results'] = [nf, nm, ne, nc, i + 1]\n        torch.save(x, path)  # save for next time\n        logging.info(f'{prefix}New cache created: {path}')\n        return x\n\n    def __len__(self):\n        return len(self.img_files)\n\n    # def __iter__(self):\n    #     self.count = -1\n    #     print('ran dataset iter')\n    #     #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)\n    #     return self\n\n    def __getitem__(self, index):\n        index = self.indices[index]  # linear, shuffled, or image_weights\n\n        hyp = self.hyp\n        mosaic = self.mosaic and random.random() < hyp['mosaic']\n        if mosaic:\n            # Load mosaic\n            img, labels = load_mosaic(self, index)\n            shapes = None\n\n            # MixUp https://arxiv.org/pdf/1710.09412.pdf\n            if random.random() < hyp['mixup']:\n                img2, labels2 = load_mosaic(self, random.randint(0, self.n - 1))\n                r = np.random.beta(8.0, 8.0)  # mixup ratio, alpha=beta=8.0\n                img = (img * r + img2 * (1 - r)).astype(np.uint8)\n                labels = np.concatenate((labels, labels2), 0)\n\n        else:\n            # Load image\n            img, (h0, w0), (h, w) = load_image(self, index)\n\n            # Letterbox\n            shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size  # final letterboxed shape\n            img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)\n            shapes = (h0, w0), ((h / h0, w / w0), pad)  # for COCO mAP rescaling\n\n            labels = self.labels[index].copy()\n            if labels.size:  # normalized xywh to pixel xyxy format\n                labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])\n\n        if self.augment:\n            # Augment imagespace\n            if not mosaic:\n                img, labels = random_perspective(img, labels,\n                                                 degrees=hyp['degrees'],\n                                                 translate=hyp['translate'],\n                                                 scale=hyp['scale'],\n                                                 shear=hyp['shear'],\n                                                 perspective=hyp['perspective'])\n\n            # Augment colorspace\n            augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])\n\n            # Apply cutouts\n            # if random.random() < 0.9:\n            #     labels = cutout(img, labels)\n\n        nL = len(labels)  # number of labels\n        if nL:\n            labels[:, 1:5] = xyxy2xywh(labels[:, 1:5])  # convert xyxy to xywh\n            labels[:, [2, 4]] /= img.shape[0]  # normalized height 0-1\n            labels[:, [1, 3]] /= img.shape[1]  # normalized width 0-1\n\n        if self.augment:\n            # flip up-down\n            if random.random() < hyp['flipud']:\n                img = np.flipud(img)\n                if nL:\n                    labels[:, 2] = 1 - labels[:, 2]\n\n            # flip left-right\n            if random.random() < hyp['fliplr']:\n                img = np.fliplr(img)\n                if nL:\n                    labels[:, 1] = 1 - labels[:, 1]\n\n        labels_out = torch.zeros((nL, 6))\n        if nL:\n            labels_out[:, 1:] = torch.from_numpy(labels)\n\n        # Convert\n        img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416\n        img = np.ascontiguousarray(img)\n\n        return torch.from_numpy(img), labels_out, self.img_files[index], shapes\n\n    @staticmethod\n    def collate_fn(batch):\n        img, label, path, shapes = zip(*batch)  # transposed\n        for i, l in enumerate(label):\n            l[:, 0] = i  # add target image index for build_targets()\n        return torch.stack(img, 0), torch.cat(label, 0), path, shapes\n\n    @staticmethod\n    def collate_fn4(batch):\n        img, label, path, shapes = zip(*batch)  # transposed\n        n = len(shapes) // 4\n        img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]\n\n        ho = torch.tensor([[0., 0, 0, 1, 0, 0]])\n        wo = torch.tensor([[0., 0, 1, 0, 0, 0]])\n        s = torch.tensor([[1, 1, .5, .5, .5, .5]])  # scale\n        for i in range(n):  # zidane torch.zeros(16,3,720,1280)  # BCHW\n            i *= 4\n            if random.random() < 0.5:\n                im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[\n                    0].type(img[i].type())\n                l = label[i]\n            else:\n                im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)\n                l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s\n            img4.append(im)\n            label4.append(l)\n\n        for i, l in enumerate(label4):\n            l[:, 0] = i  # add target image index for build_targets()\n\n        return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4\n\n\n# Ancillary functions --------------------------------------------------------------------------------------------------\ndef load_image(self, index):\n    # loads 1 image from dataset, returns img, original hw, resized hw\n    img = self.imgs[index]\n    if img is None:  # not cached\n        path = self.img_files[index]\n        img = cv2.imread(path)  # BGR\n        assert img is not None, 'Image Not Found ' + path\n        h0, w0 = img.shape[:2]  # orig hw\n        r = self.img_size / max(h0, w0)  # resize image to img_size\n        if r != 1:  # always resize down, only resize up if training with augmentation\n            interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR\n            img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)\n        return img, (h0, w0), img.shape[:2]  # img, hw_original, hw_resized\n    else:\n        return self.imgs[index], self.img_hw0[index], self.img_hw[index]  # img, hw_original, hw_resized\n\n\ndef augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):\n    r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1  # random gains\n    hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))\n    dtype = img.dtype  # uint8\n\n    x = np.arange(0, 256, dtype=np.int16)\n    lut_hue = ((x * r[0]) % 180).astype(dtype)\n    lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)\n    lut_val = np.clip(x * r[2], 0, 255).astype(dtype)\n\n    img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)\n    cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img)  # no return needed\n\n    # Histogram equalization\n    # if random.random() < 0.2:\n    #     for i in range(3):\n    #         img[:, :, i] = cv2.equalizeHist(img[:, :, i])\n\n\ndef load_mosaic(self, index):\n    # loads images in a 4-mosaic\n\n    labels4 = []\n    s = self.img_size\n    yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border]  # mosaic center x, y\n    indices = [index] + [self.indices[random.randint(0, self.n - 1)] for _ in range(3)]  # 3 additional image indices\n    for i, index in enumerate(indices):\n        # Load image\n        img, _, (h, w) = load_image(self, index)\n\n        # place img in img4\n        if i == 0:  # top left\n            img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n            x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc  # xmin, ymin, xmax, ymax (large image)\n            x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h  # xmin, ymin, xmax, ymax (small image)\n        elif i == 1:  # top right\n            x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc\n            x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h\n        elif i == 2:  # bottom left\n            x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)\n            x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)\n        elif i == 3:  # bottom right\n            x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)\n            x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)\n\n        img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]  # img4[ymin:ymax, xmin:xmax]\n        padw = x1a - x1b\n        padh = y1a - y1b\n\n        # Labels\n        labels = self.labels[index].copy()\n        if labels.size:\n            labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh)  # normalized xywh to pixel xyxy format\n        labels4.append(labels)\n\n    # Concat/clip labels\n    if len(labels4):\n        labels4 = np.concatenate(labels4, 0)\n        np.clip(labels4[:, 1:], 0, 2 * s, out=labels4[:, 1:])  # use with random_perspective\n        # img4, labels4 = replicate(img4, labels4)  # replicate\n\n    # Augment\n    img4, labels4 = random_perspective(img4, labels4,\n                                       degrees=self.hyp['degrees'],\n                                       translate=self.hyp['translate'],\n                                       scale=self.hyp['scale'],\n                                       shear=self.hyp['shear'],\n                                       perspective=self.hyp['perspective'],\n                                       border=self.mosaic_border)  # border to remove\n\n    return img4, labels4\n\n\ndef load_mosaic9(self, index):\n    # loads images in a 9-mosaic\n\n    labels9 = []\n    s = self.img_size\n    indices = [index] + [self.indices[random.randint(0, self.n - 1)] for _ in range(8)]  # 8 additional image indices\n    for i, index in enumerate(indices):\n        # Load image\n        img, _, (h, w) = load_image(self, index)\n\n        # place img in img9\n        if i == 0:  # center\n            img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n            h0, w0 = h, w\n            c = s, s, s + w, s + h  # xmin, ymin, xmax, ymax (base) coordinates\n        elif i == 1:  # top\n            c = s, s - h, s + w, s\n        elif i == 2:  # top right\n            c = s + wp, s - h, s + wp + w, s\n        elif i == 3:  # right\n            c = s + w0, s, s + w0 + w, s + h\n        elif i == 4:  # bottom right\n            c = s + w0, s + hp, s + w0 + w, s + hp + h\n        elif i == 5:  # bottom\n            c = s + w0 - w, s + h0, s + w0, s + h0 + h\n        elif i == 6:  # bottom left\n            c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h\n        elif i == 7:  # left\n            c = s - w, s + h0 - h, s, s + h0\n        elif i == 8:  # top left\n            c = s - w, s + h0 - hp - h, s, s + h0 - hp\n\n        padx, pady = c[:2]\n        x1, y1, x2, y2 = [max(x, 0) for x in c]  # allocate coords\n\n        # Labels\n        labels = self.labels[index].copy()\n        if labels.size:\n            labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady)  # normalized xywh to pixel xyxy format\n        labels9.append(labels)\n\n        # Image\n        img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:]  # img9[ymin:ymax, xmin:xmax]\n        hp, wp = h, w  # height, width previous\n\n    # Offset\n    yc, xc = [int(random.uniform(0, s)) for x in self.mosaic_border]  # mosaic center x, y\n    img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]\n\n    # Concat/clip labels\n    if len(labels9):\n        labels9 = np.concatenate(labels9, 0)\n        labels9[:, [1, 3]] -= xc\n        labels9[:, [2, 4]] -= yc\n\n        np.clip(labels9[:, 1:], 0, 2 * s, out=labels9[:, 1:])  # use with random_perspective\n        # img9, labels9 = replicate(img9, labels9)  # replicate\n\n    # Augment\n    img9, labels9 = random_perspective(img9, labels9,\n                                       degrees=self.hyp['degrees'],\n                                       translate=self.hyp['translate'],\n                                       scale=self.hyp['scale'],\n                                       shear=self.hyp['shear'],\n                                       perspective=self.hyp['perspective'],\n                                       border=self.mosaic_border)  # border to remove\n\n    return img9, labels9\n\n\ndef replicate(img, labels):\n    # Replicate labels\n    h, w = img.shape[:2]\n    boxes = labels[:, 1:].astype(int)\n    x1, y1, x2, y2 = boxes.T\n    s = ((x2 - x1) + (y2 - y1)) / 2  # side length (pixels)\n    for i in s.argsort()[:round(s.size * 0.5)]:  # smallest indices\n        x1b, y1b, x2b, y2b = boxes[i]\n        bh, bw = y2b - y1b, x2b - x1b\n        yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw))  # offset x, y\n        x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]\n        img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]  # img4[ymin:ymax, xmin:xmax]\n        labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)\n\n    return img, labels\n\n\ndef letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True):\n    # Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232\n    shape = img.shape[:2]  # current shape [height, width]\n    if isinstance(new_shape, int):\n        new_shape = (new_shape, new_shape)\n\n    # Scale ratio (new / old)\n    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n    if not scaleup:  # only scale down, do not scale up (for better test mAP)\n        r = min(r, 1.0)\n\n    # Compute padding\n    ratio = r, r  # width, height ratios\n    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding\n    if auto:  # minimum rectangle\n        dw, dh = np.mod(dw, 64), np.mod(dh, 64)  # wh padding\n    elif scaleFill:  # stretch\n        dw, dh = 0.0, 0.0\n        new_unpad = (new_shape[1], new_shape[0])\n        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios\n\n    dw /= 2  # divide padding into 2 sides\n    dh /= 2\n\n    if shape[::-1] != new_unpad:  # resize\n        img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)\n    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n    img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border\n    return img, ratio, (dw, dh)\n\n\ndef random_perspective(img, targets=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0, border=(0, 0)):\n    # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))\n    # targets = [cls, xyxy]\n\n    height = img.shape[0] + border[0] * 2  # shape(h,w,c)\n    width = img.shape[1] + border[1] * 2\n\n    # Center\n    C = np.eye(3)\n    C[0, 2] = -img.shape[1] / 2  # x translation (pixels)\n    C[1, 2] = -img.shape[0] / 2  # y translation (pixels)\n\n    # Perspective\n    P = np.eye(3)\n    P[2, 0] = random.uniform(-perspective, perspective)  # x perspective (about y)\n    P[2, 1] = random.uniform(-perspective, perspective)  # y perspective (about x)\n\n    # Rotation and Scale\n    R = np.eye(3)\n    a = random.uniform(-degrees, degrees)\n    # a += random.choice([-180, -90, 0, 90])  # add 90deg rotations to small rotations\n    s = random.uniform(1 - scale, 1 + scale)\n    # s = 2 ** random.uniform(-scale, scale)\n    R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)\n\n    # Shear\n    S = np.eye(3)\n    S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # x shear (deg)\n    S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # y shear (deg)\n\n    # Translation\n    T = np.eye(3)\n    T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width  # x translation (pixels)\n    T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height  # y translation (pixels)\n\n    # Combined rotation matrix\n    M = T @ S @ R @ P @ C  # order of operations (right to left) is IMPORTANT\n    if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():  # image changed\n        if perspective:\n            img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))\n        else:  # affine\n            img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))\n\n    # Visualize\n    # import matplotlib.pyplot as plt\n    # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()\n    # ax[0].imshow(img[:, :, ::-1])  # base\n    # ax[1].imshow(img2[:, :, ::-1])  # warped\n\n    # Transform label coordinates\n    n = len(targets)\n    if n:\n        # warp points\n        xy = np.ones((n * 4, 3))\n        xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2)  # x1y1, x2y2, x1y2, x2y1\n        xy = xy @ M.T  # transform\n        if perspective:\n            xy = (xy[:, :2] / xy[:, 2:3]).reshape(n, 8)  # rescale\n        else:  # affine\n            xy = xy[:, :2].reshape(n, 8)\n\n        # create new boxes\n        x = xy[:, [0, 2, 4, 6]]\n        y = xy[:, [1, 3, 5, 7]]\n        xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T\n\n        # # apply angle-based reduction of bounding boxes\n        # radians = a * math.pi / 180\n        # reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5\n        # x = (xy[:, 2] + xy[:, 0]) / 2\n        # y = (xy[:, 3] + xy[:, 1]) / 2\n        # w = (xy[:, 2] - xy[:, 0]) * reduction\n        # h = (xy[:, 3] - xy[:, 1]) * reduction\n        # xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T\n\n        # clip boxes\n        xy[:, [0, 2]] = xy[:, [0, 2]].clip(0, width)\n        xy[:, [1, 3]] = xy[:, [1, 3]].clip(0, height)\n\n        # filter candidates\n        i = box_candidates(box1=targets[:, 1:5].T * s, box2=xy.T)\n        targets = targets[i]\n        targets[:, 1:5] = xy[i]\n\n    return img, targets\n\n\ndef box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16):  # box1(4,n), box2(4,n)\n    # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio\n    w1, h1 = box1[2] - box1[0], box1[3] - box1[1]\n    w2, h2 = box2[2] - box2[0], box2[3] - box2[1]\n    ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps))  # aspect ratio\n    return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr)  # candidates\n\n\ndef cutout(image, labels):\n    # Applies image cutout augmentation https://arxiv.org/abs/1708.04552\n    h, w = image.shape[:2]\n\n    def bbox_ioa(box1, box2):\n        # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2\n        box2 = box2.transpose()\n\n        # Get the coordinates of bounding boxes\n        b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]\n        b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]\n\n        # Intersection area\n        inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \\\n                     (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)\n\n        # box2 area\n        box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16\n\n        # Intersection over box2 area\n        return inter_area / box2_area\n\n    # create random masks\n    scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16  # image size fraction\n    for s in scales:\n        mask_h = random.randint(1, int(h * s))\n        mask_w = random.randint(1, int(w * s))\n\n        # box\n        xmin = max(0, random.randint(0, w) - mask_w // 2)\n        ymin = max(0, random.randint(0, h) - mask_h // 2)\n        xmax = min(w, xmin + mask_w)\n        ymax = min(h, ymin + mask_h)\n\n        # apply random color mask\n        image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]\n\n        # return unobscured labels\n        if len(labels) and s > 0.03:\n            box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)\n            ioa = bbox_ioa(box, labels[:, 1:5])  # intersection over area\n            labels = labels[ioa < 0.60]  # remove >60% obscured labels\n\n    return labels\n\n\ndef create_folder(path='./new'):\n    # Create folder\n    if os.path.exists(path):\n        shutil.rmtree(path)  # delete output folder\n    os.makedirs(path)  # make new output folder\n\n\ndef flatten_recursive(path='../coco128'):\n    # Flatten a recursive directory by bringing all files to top level\n    new_path = Path(path + '_flat')\n    create_folder(new_path)\n    for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):\n        shutil.copyfile(file, new_path / Path(file).name)\n\n\ndef extract_boxes(path='../coco128/'):  # from utils.datasets import *; extract_boxes('../coco128')\n    # Convert detection dataset into classification dataset, with one directory per class\n\n    path = Path(path)  # images dir\n    shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None  # remove existing\n    files = list(path.rglob('*.*'))\n    n = len(files)  # number of files\n    for im_file in tqdm(files, total=n):\n        if im_file.suffix[1:] in img_formats:\n            # image\n            im = cv2.imread(str(im_file))[..., ::-1]  # BGR to RGB\n            h, w = im.shape[:2]\n\n            # labels\n            lb_file = Path(img2label_paths([str(im_file)])[0])\n            if Path(lb_file).exists():\n                with open(lb_file, 'r') as f:\n                    lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)  # labels\n\n                for j, x in enumerate(lb):\n                    c = int(x[0])  # class\n                    f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg'  # new filename\n                    if not f.parent.is_dir():\n                        f.parent.mkdir(parents=True)\n\n                    b = x[1:] * [w, h, w, h]  # box\n                    # b[2:] = b[2:].max()  # rectangle to square\n                    b[2:] = b[2:] * 1.2 + 3  # pad\n                    b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)\n\n                    b[[0, 2]] = np.clip(b[[0, 2]], 0, w)  # clip boxes outside of image\n                    b[[1, 3]] = np.clip(b[[1, 3]], 0, h)\n                    assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'\n\n\ndef autosplit(path='../coco128', weights=(0.9, 0.1, 0.0)):  # from utils.datasets import *; autosplit('../coco128')\n    \"\"\" Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files\n    # Arguments\n        path:       Path to images directory\n        weights:    Train, val, test weights (list)\n    \"\"\"\n    path = Path(path)  # images dir\n    files = list(path.rglob('*.*'))\n    n = len(files)  # number of files\n    indices = random.choices([0, 1, 2], weights=weights, k=n)  # assign each image to a split\n    txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt']  # 3 txt files\n    [(path / x).unlink() for x in txt if (path / x).exists()]  # remove existing\n    for i, img in tqdm(zip(indices, files), total=n):\n        if img.suffix[1:] in img_formats:\n            with open(path / txt[i], 'a') as f:\n                f.write(str(img) + '\\n')  # add image to txt file\n"
  },
  {
    "path": "utils/face_datasets.py",
    "content": "import glob\nimport logging\nimport math\nimport os\nimport random\nimport shutil\nimport time\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom threading import Thread\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image, ExifTags\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\n\nfrom utils.general import xyxy2xywh, xywh2xyxy, clean_str\nfrom utils.torch_utils import torch_distributed_zero_first\n\n\n# Parameters\nhelp_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'\nimg_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng']  # acceptable image suffixes\nvid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv']  # acceptable video suffixes\nlogger = logging.getLogger(__name__)\n\n# Get orientation exif tag\nfor orientation in ExifTags.TAGS.keys():\n    if ExifTags.TAGS[orientation] == 'Orientation':\n        break\n\ndef get_hash(files):\n    # Returns a single hash value of a list of files\n    return sum(os.path.getsize(f) for f in files if os.path.isfile(f))\n\ndef img2label_paths(img_paths):\n    # Define label paths as a function of image paths\n    sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep  # /images/, /labels/ substrings\n    return [x.replace(sa, sb, 1).replace('.' + x.split('.')[-1], '.txt') for x in img_paths]\n\ndef exif_size(img):\n    # Returns exif-corrected PIL size\n    s = img.size  # (width, height)\n    try:\n        rotation = dict(img._getexif().items())[orientation]\n        if rotation == 6:  # rotation 270\n            s = (s[1], s[0])\n        elif rotation == 8:  # rotation 90\n            s = (s[1], s[0])\n    except:\n        pass\n\n    return s\n\ndef create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,\n                      rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''):\n    # Make sure only the first process in DDP process the dataset first, and the following others can use the cache\n    with torch_distributed_zero_first(rank):\n        dataset = LoadFaceImagesAndLabels(path, imgsz, batch_size,\n                                      augment=augment,  # augment images\n                                      hyp=hyp,  # augmentation hyperparameters\n                                      rect=rect,  # rectangular training\n                                      cache_images=cache,\n                                      single_cls=opt.single_cls,\n                                      stride=int(stride),\n                                      pad=pad,\n                                      image_weights=image_weights,\n                                    )\n\n    batch_size = min(batch_size, len(dataset))\n    nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers])  # number of workers\n    sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None\n    loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader\n    # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()\n    dataloader = loader(dataset,\n                        batch_size=batch_size,\n                        num_workers=nw,\n                        sampler=sampler,\n                        pin_memory=True,\n                        collate_fn=LoadFaceImagesAndLabels.collate_fn4 if quad else LoadFaceImagesAndLabels.collate_fn)\n    return dataloader, dataset\nclass InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):\n    \"\"\" Dataloader that reuses workers\n\n    Uses same syntax as vanilla DataLoader\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))\n        self.iterator = super().__iter__()\n\n    def __len__(self):\n        return len(self.batch_sampler.sampler)\n\n    def __iter__(self):\n        for i in range(len(self)):\n            yield next(self.iterator)\nclass _RepeatSampler(object):\n    \"\"\" Sampler that repeats forever\n\n    Args:\n        sampler (Sampler)\n    \"\"\"\n\n    def __init__(self, sampler):\n        self.sampler = sampler\n\n    def __iter__(self):\n        while True:\n            yield from iter(self.sampler)\n\nclass LoadFaceImagesAndLabels(Dataset):  # for training/testing\n    def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,\n                 cache_images=False, single_cls=False, stride=32, pad=0.0, rank=-1):\n        self.img_size = img_size\n        self.augment = augment\n        self.hyp = hyp\n        self.image_weights = image_weights\n        self.rect = False if image_weights else rect\n        self.mosaic = self.augment and not self.rect  # load 4 images at a time into a mosaic (only during training)\n        self.mosaic_border = [-img_size // 2, -img_size // 2]\n        self.stride = stride\n\n        try:\n            f = []  # image files\n            for p in path if isinstance(path, list) else [path]:\n                p = Path(p)  # os-agnostic\n                if p.is_dir():  # dir\n                    f += glob.glob(str(p / '**' / '*.*'), recursive=True)\n                elif p.is_file():  # file\n                    with open(p, 'r') as t:\n                        t = t.read().strip().splitlines()\n                        parent = str(p.parent) + os.sep\n                        f += [x.replace('./', parent) if x.startswith('./') else x for x in t]  # local to global path\n                else:\n                    raise Exception('%s does not exist' % p)\n            self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats])\n            assert self.img_files, 'No images found'\n        except Exception as e:\n            raise Exception('Error loading data from %s: %s\\nSee %s' % (path, e, help_url))\n\n        # Check cache\n        self.label_files = img2label_paths(self.img_files)  # labels\n        cache_path = Path(self.label_files[0]).parent.with_suffix('.cache')  # cached labels\n        if cache_path.is_file():\n            cache = torch.load(cache_path)  # load\n            if cache['hash'] != get_hash(self.label_files + self.img_files) or 'results' not in cache:  # changed\n                cache = self.cache_labels(cache_path)  # re-cache\n        else:\n            cache = self.cache_labels(cache_path)  # cache\n\n        # Display cache\n        [nf, nm, ne, nc, n] = cache.pop('results')  # found, missing, empty, corrupted, total\n        desc = f\"Scanning '{cache_path}' for images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted\"\n        tqdm(None, desc=desc, total=n, initial=n)\n        assert nf > 0 or not augment, f'No labels found in {cache_path}. Can not train without labels. See {help_url}'\n\n        # Read cache\n        cache.pop('hash')  # remove hash\n        labels, shapes = zip(*cache.values())\n        self.labels = list(labels)\n        self.shapes = np.array(shapes, dtype=np.float64)\n        self.img_files = list(cache.keys())  # update\n        self.label_files = img2label_paths(cache.keys())  # update\n        if single_cls:\n            for x in self.labels:\n                x[:, 0] = 0\n\n        n = len(shapes)  # number of images\n        bi = np.floor(np.arange(n) / batch_size).astype(np.int)  # batch index\n        nb = bi[-1] + 1  # number of batches\n        self.batch = bi  # batch index of image\n        self.n = n\n        self.indices = range(n)\n\n        # Rectangular Training\n        if self.rect:\n            # Sort by aspect ratio\n            s = self.shapes  # wh\n            ar = s[:, 1] / s[:, 0]  # aspect ratio\n            irect = ar.argsort()\n            self.img_files = [self.img_files[i] for i in irect]\n            self.label_files = [self.label_files[i] for i in irect]\n            self.labels = [self.labels[i] for i in irect]\n            self.shapes = s[irect]  # wh\n            ar = ar[irect]\n\n            # Set training image shapes\n            shapes = [[1, 1]] * nb\n            for i in range(nb):\n                ari = ar[bi == i]\n                mini, maxi = ari.min(), ari.max()\n                if maxi < 1:\n                    shapes[i] = [maxi, 1]\n                elif mini > 1:\n                    shapes[i] = [1, 1 / mini]\n\n            self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride\n\n        # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)\n        self.imgs = [None] * n\n        if cache_images:\n            gb = 0  # Gigabytes of cached images\n            self.img_hw0, self.img_hw = [None] * n, [None] * n\n            results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))  # 8 threads\n            pbar = tqdm(enumerate(results), total=n)\n            for i, x in pbar:\n                self.imgs[i], self.img_hw0[i], self.img_hw[i] = x  # img, hw_original, hw_resized = load_image(self, i)\n                gb += self.imgs[i].nbytes\n                pbar.desc = 'Caching images (%.1fGB)' % (gb / 1E9)\n\n    def cache_labels(self, path=Path('./labels.cache')):\n        # Cache dataset labels, check images and read shapes\n        x = {}  # dict\n        nm, nf, ne, nc = 0, 0, 0, 0  # number missing, found, empty, duplicate\n        pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files))\n        for i, (im_file, lb_file) in enumerate(pbar):\n            try:\n                # verify images\n                im = Image.open(im_file)\n                im.verify()  # PIL verify\n                shape = exif_size(im)  # image size\n                assert (shape[0] > 9) & (shape[1] > 9), 'image size <10 pixels'\n\n                # verify labels\n                if os.path.isfile(lb_file):\n                    nf += 1  # label found\n                    with open(lb_file, 'r') as f:\n                        l = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)  # labels\n                    if len(l):\n                        assert l.shape[1] == 15, 'labels require 15 columns each'\n                        assert (l >= -1).all(), 'negative labels'\n                        assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'\n                        assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'\n                    else:\n                        ne += 1  # label empty\n                        l = np.zeros((0, 15), dtype=np.float32)\n                else:\n                    nm += 1  # label missing\n                    l = np.zeros((0, 15), dtype=np.float32)\n                x[im_file] = [l, shape]\n            except Exception as e:\n                nc += 1\n                print('WARNING: Ignoring corrupted image and/or label %s: %s' % (im_file, e))\n\n            pbar.desc = f\"Scanning '{path.parent / path.stem}' for images and labels... \" \\\n                        f\"{nf} found, {nm} missing, {ne} empty, {nc} corrupted\"\n\n        if nf == 0:\n            print(f'WARNING: No labels found in {path}. See {help_url}')\n\n        x['hash'] = get_hash(self.label_files + self.img_files)\n        x['results'] = [nf, nm, ne, nc, i + 1]\n        torch.save(x, path)  # save for next time\n        logging.info(f\"New cache created: {path}\")\n        return x\n\n    def __len__(self):\n        return len(self.img_files)\n\n    # def __iter__(self):\n    #     self.count = -1\n    #     print('ran dataset iter')\n    #     #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)\n    #     return self\n\n    def __getitem__(self, index):\n        index = self.indices[index]  # linear, shuffled, or image_weights\n\n        hyp = self.hyp\n        mosaic = self.mosaic and random.random() < hyp['mosaic']\n        if mosaic:\n            # Load mosaic\n            img, labels = load_mosaic_face(self, index)\n            shapes = None\n\n            # MixUp https://arxiv.org/pdf/1710.09412.pdf\n            if random.random() < hyp['mixup']:\n                img2, labels2 = load_mosaic_face(self, random.randint(0, self.n - 1))\n                r = np.random.beta(8.0, 8.0)  # mixup ratio, alpha=beta=8.0\n                img = (img * r + img2 * (1 - r)).astype(np.uint8)\n                labels = np.concatenate((labels, labels2), 0)\n\n        else:\n            # Load image\n            img, (h0, w0), (h, w) = load_image(self, index)\n\n            # Letterbox\n            shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size  # final letterboxed shape\n            img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)\n            shapes = (h0, w0), ((h / h0, w / w0), pad)  # for COCO mAP rescaling\n\n            # Load labels\n            labels = []\n            x = self.labels[index]\n            if x.size > 0:\n                # Normalized xywh to pixel xyxy format\n                labels = x.copy()\n                labels[:, 1] = ratio[0] * w * (x[:, 1] - x[:, 3] / 2) + pad[0]  # pad width\n                labels[:, 2] = ratio[1] * h * (x[:, 2] - x[:, 4] / 2) + pad[1]  # pad height\n                labels[:, 3] = ratio[0] * w * (x[:, 1] + x[:, 3] / 2) + pad[0]\n                labels[:, 4] = ratio[1] * h * (x[:, 2] + x[:, 4] / 2) + pad[1]\n\n                #labels[:, 5] = ratio[0] * w * x[:, 5] + pad[0]  # pad width\n                labels[:, 5] = np.array(x[:, 5] > 0, dtype=np.int32) * (ratio[0] * w * x[:, 5] + pad[0]) + (\n                    np.array(x[:, 5] > 0, dtype=np.int32) - 1)\n                labels[:, 6] = np.array(x[:, 6] > 0, dtype=np.int32) * (ratio[1] * h * x[:, 6] + pad[1]) + (\n                    np.array(x[:, 6] > 0, dtype=np.int32) - 1)\n                labels[:, 7] = np.array(x[:, 7] > 0, dtype=np.int32) * (ratio[0] * w * x[:, 7] + pad[0]) + (\n                    np.array(x[:, 7] > 0, dtype=np.int32) - 1)\n                labels[:, 8] = np.array(x[:, 8] > 0, dtype=np.int32) * (ratio[1] * h * x[:, 8] + pad[1]) + (\n                    np.array(x[:, 8] > 0, dtype=np.int32) - 1)\n                labels[:, 9] = np.array(x[:, 5] > 0, dtype=np.int32) * (ratio[0] * w * x[:, 9] + pad[0]) + (\n                    np.array(x[:, 9] > 0, dtype=np.int32) - 1)\n                labels[:, 10] = np.array(x[:, 5] > 0, dtype=np.int32) * (ratio[1] * h * x[:, 10] + pad[1]) + (\n                    np.array(x[:, 10] > 0, dtype=np.int32) - 1)\n                labels[:, 11] = np.array(x[:, 11] > 0, dtype=np.int32) * (ratio[0] * w * x[:, 11] + pad[0]) + (\n                    np.array(x[:, 11] > 0, dtype=np.int32) - 1)\n                labels[:, 12] = np.array(x[:, 12] > 0, dtype=np.int32) * (ratio[1] * h * x[:, 12] + pad[1]) + (\n                    np.array(x[:, 12] > 0, dtype=np.int32) - 1)\n                labels[:, 13] = np.array(x[:, 13] > 0, dtype=np.int32) * (ratio[0] * w * x[:, 13] + pad[0]) + (\n                    np.array(x[:, 13] > 0, dtype=np.int32) - 1)\n                labels[:, 14] = np.array(x[:, 14] > 0, dtype=np.int32) * (ratio[1] * h * x[:, 14] + pad[1]) + (\n                    np.array(x[:, 14] > 0, dtype=np.int32) - 1)\n\n        if self.augment:\n            # Augment imagespace\n            if not mosaic:\n                img, labels = random_perspective(img, labels,\n                                                 degrees=hyp['degrees'],\n                                                 translate=hyp['translate'],\n                                                 scale=hyp['scale'],\n                                                 shear=hyp['shear'],\n                                                 perspective=hyp['perspective'])\n\n            # Augment colorspace\n            augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])\n\n            # Apply cutouts\n            # if random.random() < 0.9:\n            #     labels = cutout(img, labels)\n\n        nL = len(labels)  # number of labels\n        if nL:\n            labels[:, 1:5] = xyxy2xywh(labels[:, 1:5])  # convert xyxy to xywh\n            labels[:, [2, 4]] /= img.shape[0]  # normalized height 0-1\n            labels[:, [1, 3]] /= img.shape[1]  # normalized width 0-1\n\n            labels[:, [5, 7, 9, 11, 13]] /= img.shape[1]  # normalized landmark x 0-1\n            labels[:, [5, 7, 9, 11, 13]] = np.where(labels[:, [5, 7, 9, 11, 13]] < 0, -1, labels[:, [5, 7, 9, 11, 13]])\n            labels[:, [6, 8, 10, 12, 14]] /= img.shape[0]  # normalized landmark y 0-1\n            labels[:, [6, 8, 10, 12, 14]] = np.where(labels[:, [6, 8, 10, 12, 14]] < 0, -1, labels[:, [6, 8, 10, 12, 14]])\n\n        if self.augment:\n            # flip up-down\n            if random.random() < hyp['flipud']:\n                img = np.flipud(img)\n                if nL:\n                    labels[:, 2] = 1 - labels[:, 2]\n\n                    labels[:, 6] = np.where(labels[:,6] < 0, -1, 1 - labels[:, 6])\n                    labels[:, 8] = np.where(labels[:, 8] < 0, -1, 1 - labels[:, 8])\n                    labels[:, 10] = np.where(labels[:, 10] < 0, -1, 1 - labels[:, 10])\n                    labels[:, 12] = np.where(labels[:, 12] < 0, -1, 1 - labels[:, 12])\n                    labels[:, 14] = np.where(labels[:, 14] < 0, -1, 1 - labels[:, 14])\n\n            # flip left-right\n            if random.random() < hyp['fliplr']:\n                img = np.fliplr(img)\n                if nL:\n                    labels[:, 1] = 1 - labels[:, 1]\n\n                    labels[:, 5] = np.where(labels[:, 5] < 0, -1, 1 - labels[:, 5])\n                    labels[:, 7] = np.where(labels[:, 7] < 0, -1, 1 - labels[:, 7])\n                    labels[:, 9] = np.where(labels[:, 9] < 0, -1, 1 - labels[:, 9])\n                    labels[:, 11] = np.where(labels[:, 11] < 0, -1, 1 - labels[:, 11])\n                    labels[:, 13] = np.where(labels[:, 13] < 0, -1, 1 - labels[:, 13])\n\n                    #左右镜像的时候，左眼、右眼，　左嘴角、右嘴角无法区分, 应该交换位置，便于网络学习\n                    eye_left = np.copy(labels[:, [5, 6]])\n                    mouth_left = np.copy(labels[:, [11, 12]])\n                    labels[:, [5, 6]] = labels[:, [7, 8]]\n                    labels[:, [7, 8]] = eye_left\n                    labels[:, [11, 12]] = labels[:, [13, 14]]\n                    labels[:, [13, 14]] = mouth_left\n\n        labels_out = torch.zeros((nL, 16))\n        if nL:\n            labels_out[:, 1:] = torch.from_numpy(labels)\n            #showlabels(img, labels[:, 1:5], labels[:, 5:15])\n\n        # Convert\n        img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416\n        img = np.ascontiguousarray(img)\n        #print(index, '   --- labels_out: ', labels_out)\n        #if nL:\n            #print( ' : landmarks : ', torch.max(labels_out[:, 5:15]), '  ---   ', torch.min(labels_out[:, 5:15]))\n        return torch.from_numpy(img), labels_out, self.img_files[index], shapes\n\n    @staticmethod\n    def collate_fn(batch):\n        img, label, path, shapes = zip(*batch)  # transposed\n        for i, l in enumerate(label):\n            l[:, 0] = i  # add target image index for build_targets()\n        return torch.stack(img, 0), torch.cat(label, 0), path, shapes\n\n\ndef showlabels(img, boxs, landmarks):\n    for box in boxs:\n        x,y,w,h = box[0] * img.shape[1], box[1] * img.shape[0], box[2] * img.shape[1], box[3] * img.shape[0]\n        #cv2.rectangle(image, (x,y), (x+w,y+h), (0,255,0), 2)\n        cv2.rectangle(img, (int(x - w/2), int(y - h/2)), (int(x + w/2), int(y + h/2)), (0, 255, 0), 2)\n\n    for landmark in landmarks:\n        #cv2.circle(img,(60,60),30,(0,0,255))\n        for i in range(5):\n            cv2.circle(img, (int(landmark[2*i] * img.shape[1]), int(landmark[2*i+1]*img.shape[0])), 3 ,(0,0,255), -1)\n    cv2.imshow('test', img)\n    cv2.waitKey(0)\n\n\ndef load_mosaic_face(self, index):\n    # loads images in a mosaic\n    labels4 = []\n    s = self.img_size\n    yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border]  # mosaic center x, y\n    indices = [index] + [self.indices[random.randint(0, self.n - 1)] for _ in range(3)]  # 3 additional image indices\n    for i, index in enumerate(indices):\n        # Load image\n        img, _, (h, w) = load_image(self, index)\n\n        # place img in img4\n        if i == 0:  # top left\n            img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n            x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc  # xmin, ymin, xmax, ymax (large image)\n            x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h  # xmin, ymin, xmax, ymax (small image)\n        elif i == 1:  # top right\n            x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc\n            x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h\n        elif i == 2:  # bottom left\n            x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)\n            x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)\n        elif i == 3:  # bottom right\n            x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)\n            x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)\n\n        img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]  # img4[ymin:ymax, xmin:xmax]\n        padw = x1a - x1b\n        padh = y1a - y1b\n\n        # Labels\n        x = self.labels[index]\n        labels = x.copy()\n        if x.size > 0:  # Normalized xywh to pixel xyxy format\n            #box, x1,y1,x2,y2\n            labels[:, 1] = w * (x[:, 1] - x[:, 3] / 2) + padw\n            labels[:, 2] = h * (x[:, 2] - x[:, 4] / 2) + padh\n            labels[:, 3] = w * (x[:, 1] + x[:, 3] / 2) + padw\n            labels[:, 4] = h * (x[:, 2] + x[:, 4] / 2) + padh\n            #10 landmarks\n\n            labels[:, 5] = np.array(x[:, 5] > 0, dtype=np.int32) * (w * x[:, 5] + padw) + (np.array(x[:, 5] > 0, dtype=np.int32) - 1)\n            labels[:, 6] = np.array(x[:, 6] > 0, dtype=np.int32) * (h * x[:, 6] + padh) + (np.array(x[:, 6] > 0, dtype=np.int32) - 1)\n            labels[:, 7] = np.array(x[:, 7] > 0, dtype=np.int32) * (w * x[:, 7] + padw) + (np.array(x[:, 7] > 0, dtype=np.int32) - 1)\n            labels[:, 8] = np.array(x[:, 8] > 0, dtype=np.int32) * (h * x[:, 8] + padh) + (np.array(x[:, 8] > 0, dtype=np.int32) - 1)\n            labels[:, 9] = np.array(x[:, 9] > 0, dtype=np.int32) * (w * x[:, 9] + padw) + (np.array(x[:, 9] > 0, dtype=np.int32) - 1)\n            labels[:, 10] = np.array(x[:, 10] > 0, dtype=np.int32) * (h * x[:, 10] + padh) + (np.array(x[:, 10] > 0, dtype=np.int32) - 1)\n            labels[:, 11] = np.array(x[:, 11] > 0, dtype=np.int32) * (w * x[:, 11] + padw) + (np.array(x[:, 11] > 0, dtype=np.int32) - 1)\n            labels[:, 12] = np.array(x[:, 12] > 0, dtype=np.int32) * (h * x[:, 12] + padh) + (np.array(x[:, 12] > 0, dtype=np.int32) - 1)\n            labels[:, 13] = np.array(x[:, 13] > 0, dtype=np.int32) * (w * x[:, 13] + padw) + (np.array(x[:, 13] > 0, dtype=np.int32) - 1)\n            labels[:, 14] = np.array(x[:, 14] > 0, dtype=np.int32) * (h * x[:, 14] + padh) + (np.array(x[:, 14] > 0, dtype=np.int32) - 1)\n        labels4.append(labels)\n\n    # Concat/clip labels\n    if len(labels4):\n        labels4 = np.concatenate(labels4, 0)\n        np.clip(labels4[:, 1:5], 0, 2 * s, out=labels4[:, 1:5])  # use with random_perspective\n        # img4, labels4 = replicate(img4, labels4)  # replicate\n\n        #landmarks\n        labels4[:, 5:] = np.where(labels4[:, 5:] < 0, -1, labels4[:, 5:])\n        labels4[:, 5:] = np.where(labels4[:, 5:] > 2 * s, -1, labels4[:, 5:])\n\n        labels4[:, 5] = np.where(labels4[:, 6] == -1, -1, labels4[:, 5])\n        labels4[:, 6] = np.where(labels4[:, 5] == -1, -1, labels4[:, 6])\n\n        labels4[:, 7] = np.where(labels4[:, 8] == -1, -1, labels4[:, 7])\n        labels4[:, 8] = np.where(labels4[:, 7] == -1, -1, labels4[:, 8])\n\n        labels4[:, 9] = np.where(labels4[:, 10] == -1, -1, labels4[:, 9])\n        labels4[:, 10] = np.where(labels4[:, 9] == -1, -1, labels4[:, 10])\n\n        labels4[:, 11] = np.where(labels4[:, 12] == -1, -1, labels4[:, 11])\n        labels4[:, 12] = np.where(labels4[:, 11] == -1, -1, labels4[:, 12])\n\n        labels4[:, 13] = np.where(labels4[:, 14] == -1, -1, labels4[:, 13])\n        labels4[:, 14] = np.where(labels4[:, 13] == -1, -1, labels4[:, 14])\n\n    # Augment\n    img4, labels4 = random_perspective(img4, labels4,\n                                       degrees=self.hyp['degrees'],\n                                       translate=self.hyp['translate'],\n                                       scale=self.hyp['scale'],\n                                       shear=self.hyp['shear'],\n                                       perspective=self.hyp['perspective'],\n                                       border=self.mosaic_border)  # border to remove\n    return img4, labels4\n\n\n# Ancillary functions --------------------------------------------------------------------------------------------------\ndef load_image(self, index):\n    # loads 1 image from dataset, returns img, original hw, resized hw\n    img = self.imgs[index]\n    if img is None:  # not cached\n        path = self.img_files[index]\n        img = cv2.imread(path)  # BGR\n        assert img is not None, 'Image Not Found ' + path\n        h0, w0 = img.shape[:2]  # orig hw\n        r = self.img_size / max(h0, w0)  # resize image to img_size\n        if r != 1:  # always resize down, only resize up if training with augmentation\n            interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR\n            img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)\n        return img, (h0, w0), img.shape[:2]  # img, hw_original, hw_resized\n    else:\n        return self.imgs[index], self.img_hw0[index], self.img_hw[index]  # img, hw_original, hw_resized\n\n\ndef augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):\n    r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1  # random gains\n    hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))\n    dtype = img.dtype  # uint8\n\n    x = np.arange(0, 256, dtype=np.int16)\n    lut_hue = ((x * r[0]) % 180).astype(dtype)\n    lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)\n    lut_val = np.clip(x * r[2], 0, 255).astype(dtype)\n\n    img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)\n    cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img)  # no return needed\n\n    # Histogram equalization\n    # if random.random() < 0.2:\n    #     for i in range(3):\n    #         img[:, :, i] = cv2.equalizeHist(img[:, :, i])\n\ndef replicate(img, labels):\n    # Replicate labels\n    h, w = img.shape[:2]\n    boxes = labels[:, 1:].astype(int)\n    x1, y1, x2, y2 = boxes.T\n    s = ((x2 - x1) + (y2 - y1)) / 2  # side length (pixels)\n    for i in s.argsort()[:round(s.size * 0.5)]:  # smallest indices\n        x1b, y1b, x2b, y2b = boxes[i]\n        bh, bw = y2b - y1b, x2b - x1b\n        yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw))  # offset x, y\n        x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]\n        img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]  # img4[ymin:ymax, xmin:xmax]\n        labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)\n\n    return img, labels\n\n\ndef letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True):\n    # Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232\n    shape = img.shape[:2]  # current shape [height, width]\n    if isinstance(new_shape, int):\n        new_shape = (new_shape, new_shape)\n\n    # Scale ratio (new / old)\n    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n    if not scaleup:  # only scale down, do not scale up (for better test mAP)\n        r = min(r, 1.0)\n\n    # Compute padding\n    ratio = r, r  # width, height ratios\n    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding\n    if auto:  # minimum rectangle\n        dw, dh = np.mod(dw, 64), np.mod(dh, 64)  # wh padding\n    elif scaleFill:  # stretch\n        dw, dh = 0.0, 0.0\n        new_unpad = (new_shape[1], new_shape[0])\n        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios\n\n    dw /= 2  # divide padding into 2 sides\n    dh /= 2\n\n    if shape[::-1] != new_unpad:  # resize\n        img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)\n    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n    img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border\n    return img, ratio, (dw, dh)\n\n\ndef random_perspective(img, targets=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0, border=(0, 0)):\n    # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))\n    # targets = [cls, xyxy]\n\n    height = img.shape[0] + border[0] * 2  # shape(h,w,c)\n    width = img.shape[1] + border[1] * 2\n\n    # Center\n    C = np.eye(3)\n    C[0, 2] = -img.shape[1] / 2  # x translation (pixels)\n    C[1, 2] = -img.shape[0] / 2  # y translation (pixels)\n\n    # Perspective\n    P = np.eye(3)\n    P[2, 0] = random.uniform(-perspective, perspective)  # x perspective (about y)\n    P[2, 1] = random.uniform(-perspective, perspective)  # y perspective (about x)\n\n    # Rotation and Scale\n    R = np.eye(3)\n    a = random.uniform(-degrees, degrees)\n    # a += random.choice([-180, -90, 0, 90])  # add 90deg rotations to small rotations\n    s = random.uniform(1 - scale, 1 + scale)\n    # s = 2 ** random.uniform(-scale, scale)\n    R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)\n\n    # Shear\n    S = np.eye(3)\n    S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # x shear (deg)\n    S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # y shear (deg)\n\n    # Translation\n    T = np.eye(3)\n    T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width  # x translation (pixels)\n    T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height  # y translation (pixels)\n\n    # Combined rotation matrix\n    M = T @ S @ R @ P @ C  # order of operations (right to left) is IMPORTANT\n    if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():  # image changed\n        if perspective:\n            img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))\n        else:  # affine\n            img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))\n\n    # Visualize\n    # import matplotlib.pyplot as plt\n    # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()\n    # ax[0].imshow(img[:, :, ::-1])  # base\n    # ax[1].imshow(img2[:, :, ::-1])  # warped\n\n    # Transform label coordinates\n    n = len(targets)\n    if n:\n        # warp points\n        #xy = np.ones((n * 4, 3))\n        xy = np.ones((n * 9, 3))\n        xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]].reshape(n * 9, 2)  # x1y1, x2y2, x1y2, x2y1\n        xy = xy @ M.T  # transform\n        if perspective:\n            xy = (xy[:, :2] / xy[:, 2:3]).reshape(n, 18)  # rescale\n        else:  # affine\n            xy = xy[:, :2].reshape(n, 18)\n\n        # create new boxes\n        x = xy[:, [0, 2, 4, 6]]\n        y = xy[:, [1, 3, 5, 7]]\n\n        landmarks = xy[:, [8, 9, 10, 11, 12, 13, 14, 15, 16, 17]]\n        mask = np.array(targets[:, 5:] > 0, dtype=np.int32)\n        landmarks = landmarks * mask\n        landmarks = landmarks + mask - 1\n\n        landmarks = np.where(landmarks < 0, -1, landmarks)\n        landmarks[:, [0, 2, 4, 6, 8]] = np.where(landmarks[:, [0, 2, 4, 6, 8]] > width, -1, landmarks[:, [0, 2, 4, 6, 8]])\n        landmarks[:, [1, 3, 5, 7, 9]] = np.where(landmarks[:, [1, 3, 5, 7, 9]] > height, -1,landmarks[:, [1, 3, 5, 7, 9]])\n\n        landmarks[:, 0] = np.where(landmarks[:, 1] == -1, -1, landmarks[:, 0])\n        landmarks[:, 1] = np.where(landmarks[:, 0] == -1, -1, landmarks[:, 1])\n\n        landmarks[:, 2] = np.where(landmarks[:, 3] == -1, -1, landmarks[:, 2])\n        landmarks[:, 3] = np.where(landmarks[:, 2] == -1, -1, landmarks[:, 3])\n\n        landmarks[:, 4] = np.where(landmarks[:, 5] == -1, -1, landmarks[:, 4])\n        landmarks[:, 5] = np.where(landmarks[:, 4] == -1, -1, landmarks[:, 5])\n\n        landmarks[:, 6] = np.where(landmarks[:, 7] == -1, -1, landmarks[:, 6])\n        landmarks[:, 7] = np.where(landmarks[:, 6] == -1, -1, landmarks[:, 7])\n\n        landmarks[:, 8] = np.where(landmarks[:, 9] == -1, -1, landmarks[:, 8])\n        landmarks[:, 9] = np.where(landmarks[:, 8] == -1, -1, landmarks[:, 9])\n\n        targets[:,5:] = landmarks\n\n        xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T\n\n        # # apply angle-based reduction of bounding boxes\n        # radians = a * math.pi / 180\n        # reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5\n        # x = (xy[:, 2] + xy[:, 0]) / 2\n        # y = (xy[:, 3] + xy[:, 1]) / 2\n        # w = (xy[:, 2] - xy[:, 0]) * reduction\n        # h = (xy[:, 3] - xy[:, 1]) * reduction\n        # xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T\n\n        # clip boxes\n        xy[:, [0, 2]] = xy[:, [0, 2]].clip(0, width)\n        xy[:, [1, 3]] = xy[:, [1, 3]].clip(0, height)\n\n        # filter candidates\n        i = box_candidates(box1=targets[:, 1:5].T * s, box2=xy.T)\n        targets = targets[i]\n        targets[:, 1:5] = xy[i]\n\n    return img, targets\n\n\ndef box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1):  # box1(4,n), box2(4,n)\n    # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio\n    w1, h1 = box1[2] - box1[0], box1[3] - box1[1]\n    w2, h2 = box2[2] - box2[0], box2[3] - box2[1]\n    ar = np.maximum(w2 / (h2 + 1e-16), h2 / (w2 + 1e-16))  # aspect ratio\n    return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + 1e-16) > area_thr) & (ar < ar_thr)  # candidates\n\n\ndef cutout(image, labels):\n    # Applies image cutout augmentation https://arxiv.org/abs/1708.04552\n    h, w = image.shape[:2]\n\n    def bbox_ioa(box1, box2):\n        # Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2\n        box2 = box2.transpose()\n\n        # Get the coordinates of bounding boxes\n        b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]\n        b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]\n\n        # Intersection area\n        inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \\\n                     (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)\n\n        # box2 area\n        box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16\n\n        # Intersection over box2 area\n        return inter_area / box2_area\n\n    # create random masks\n    scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16  # image size fraction\n    for s in scales:\n        mask_h = random.randint(1, int(h * s))\n        mask_w = random.randint(1, int(w * s))\n\n        # box\n        xmin = max(0, random.randint(0, w) - mask_w // 2)\n        ymin = max(0, random.randint(0, h) - mask_h // 2)\n        xmax = min(w, xmin + mask_w)\n        ymax = min(h, ymin + mask_h)\n\n        # apply random color mask\n        image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]\n\n        # return unobscured labels\n        if len(labels) and s > 0.03:\n            box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)\n            ioa = bbox_ioa(box, labels[:, 1:5])  # intersection over area\n            labels = labels[ioa < 0.60]  # remove >60% obscured labels\n\n    return labels\n\n\ndef create_folder(path='./new'):\n    # Create folder\n    if os.path.exists(path):\n        shutil.rmtree(path)  # delete output folder\n    os.makedirs(path)  # make new output folder\n\n\ndef flatten_recursive(path='../coco128'):\n    # Flatten a recursive directory by bringing all files to top level\n    new_path = Path(path + '_flat')\n    create_folder(new_path)\n    for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):\n        shutil.copyfile(file, new_path / Path(file).name)\n\n\ndef extract_boxes(path='../coco128/'):  # from utils.datasets import *; extract_boxes('../coco128')\n    # Convert detection dataset into classification dataset, with one directory per class\n\n    path = Path(path)  # images dir\n    shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None  # remove existing\n    files = list(path.rglob('*.*'))\n    n = len(files)  # number of files\n    for im_file in tqdm(files, total=n):\n        if im_file.suffix[1:] in img_formats:\n            # image\n            im = cv2.imread(str(im_file))[..., ::-1]  # BGR to RGB\n            h, w = im.shape[:2]\n\n            # labels\n            lb_file = Path(img2label_paths([str(im_file)])[0])\n            if Path(lb_file).exists():\n                with open(lb_file, 'r') as f:\n                    lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)  # labels\n\n                for j, x in enumerate(lb):\n                    c = int(x[0])  # class\n                    f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg'  # new filename\n                    if not f.parent.is_dir():\n                        f.parent.mkdir(parents=True)\n\n                    b = x[1:] * [w, h, w, h]  # box\n                    # b[2:] = b[2:].max()  # rectangle to square\n                    b[2:] = b[2:] * 1.2 + 3  # pad\n                    b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)\n\n                    b[[0, 2]] = np.clip(b[[0, 2]], 0, w)  # clip boxes outside of image\n                    b[[1, 3]] = np.clip(b[[1, 3]], 0, h)\n                    assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'\n\n\ndef autosplit(path='../coco128', weights=(0.9, 0.1, 0.0)):  # from utils.datasets import *; autosplit('../coco128')\n    \"\"\" Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files\n    # Arguments\n        path:       Path to images directory\n        weights:    Train, val, test weights (list)\n    \"\"\"\n    path = Path(path)  # images dir\n    files = list(path.rglob('*.*'))\n    n = len(files)  # number of files\n    indices = random.choices([0, 1, 2], weights=weights, k=n)  # assign each image to a split\n    txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt']  # 3 txt files\n    [(path / x).unlink() for x in txt if (path / x).exists()]  # remove existing\n    for i, img in tqdm(zip(indices, files), total=n):\n        if img.suffix[1:] in img_formats:\n            with open(path / txt[i], 'a') as f:\n                f.write(str(img) + '\\n')  # add image to txt file\n"
  },
  {
    "path": "utils/general.py",
    "content": "# General utils\n\nimport glob\nimport logging\nimport math\nimport os\nimport random\nimport re\nimport subprocess\nimport time\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport torch\nimport torchvision\nimport yaml\n\nfrom utils.google_utils import gsutil_getsize\nfrom utils.metrics import fitness\nfrom utils.torch_utils import init_torch_seeds\n\n# Settings\ntorch.set_printoptions(linewidth=320, precision=5, profile='long')\nnp.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format})  # format short g, %precision=5\ncv2.setNumThreads(0)  # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)\nos.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8))  # NumExpr max threads\n\n\ndef set_logging(rank=-1):\n    logging.basicConfig(\n        format=\"%(message)s\",\n        level=logging.INFO if rank in [-1, 0] else logging.WARN)\n\n\ndef init_seeds(seed=0):\n    # Initialize random number generator (RNG) seeds\n    random.seed(seed)\n    np.random.seed(seed)\n    init_torch_seeds(seed)\n\n\ndef get_latest_run(search_dir='.'):\n    # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)\n    last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)\n    return max(last_list, key=os.path.getctime) if last_list else ''\n\n\ndef check_online():\n    # Check internet connectivity\n    import socket\n    try:\n        socket.create_connection((\"1.1.1.1\", 53))  # check host accesability\n        return True\n    except OSError:\n        return False\n\n\ndef check_git_status():\n    # Recommend 'git pull' if code is out of date\n    print(colorstr('github: '), end='')\n    try:\n        assert Path('.git').exists(), 'skipping check (not a git repository)'\n        assert not Path('/workspace').exists(), 'skipping check (Docker image)'  # not Path('/.dockerenv').exists()\n        assert check_online(), 'skipping check (offline)'\n\n        cmd = 'git fetch && git config --get remote.origin.url'  # github repo url\n        url = subprocess.check_output(cmd, shell=True).decode()[:-1]\n        cmd = 'git rev-list $(git rev-parse --abbrev-ref HEAD)..origin/master --count'  # commits behind\n        n = int(subprocess.check_output(cmd, shell=True))\n        if n > 0:\n            print(f\"⚠️ WARNING: code is out of date by {n} {'commits' if n > 1 else 'commmit'}. \"\n                  f\"Use 'git pull' to update or 'git clone {url}' to download latest.\")\n        else:\n            print(f'up to date with {url} ✅')\n    except Exception as e:\n        print(e)\n\n\ndef check_requirements(file='requirements.txt'):\n    # Check installed dependencies meet requirements\n    import pkg_resources\n    requirements = pkg_resources.parse_requirements(Path(file).open())\n    requirements = [x.name + ''.join(*x.specs) if len(x.specs) else x.name for x in requirements]\n    pkg_resources.require(requirements)  # DistributionNotFound or VersionConflict exception if requirements not met\n\n\ndef check_img_size(img_size, s=32):\n    # Verify img_size is a multiple of stride s\n    new_size = make_divisible(img_size, int(s))  # ceil gs-multiple\n    if new_size != img_size:\n        print('WARNING: --img-size %g must be multiple of max stride %g, updating to %g' % (img_size, s, new_size))\n    return new_size\n\n\ndef check_file(file):\n    # Search for file if not found\n    if os.path.isfile(file) or file == '':\n        return file\n    else:\n        files = glob.glob('./**/' + file, recursive=True)  # find file\n        assert len(files), 'File Not Found: %s' % file  # assert file was found\n        assert len(files) == 1, \"Multiple files match '%s', specify exact path: %s\" % (file, files)  # assert unique\n        return files[0]  # return file\n\n\ndef check_dataset(dict):\n    # Download dataset if not found locally\n    val, s = dict.get('val'), dict.get('download')\n    if val and len(val):\n        val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])]  # val path\n        if not all(x.exists() for x in val):\n            print('\\nWARNING: Dataset not found, nonexistent paths: %s' % [str(x) for x in val if not x.exists()])\n            if s and len(s):  # download script\n                print('Downloading %s ...' % s)\n                if s.startswith('http') and s.endswith('.zip'):  # URL\n                    f = Path(s).name  # filename\n                    torch.hub.download_url_to_file(s, f)\n                    r = os.system('unzip -q %s -d ../ && rm %s' % (f, f))  # unzip\n                else:  # bash script\n                    r = os.system(s)\n                print('Dataset autodownload %s\\n' % ('success' if r == 0 else 'failure'))  # analyze return value\n            else:\n                raise Exception('Dataset not found.')\n\n\ndef make_divisible(x, divisor):\n    # Returns x evenly divisible by divisor\n    return math.ceil(x / divisor) * divisor\n\n\ndef clean_str(s):\n    # Cleans a string by replacing special characters with underscore _\n    return re.sub(pattern=\"[|@#!¡·$€%&()=?¿^*;:,¨´><+]\", repl=\"_\", string=s)\n\n\ndef one_cycle(y1=0.0, y2=1.0, steps=100):\n    # lambda function for sinusoidal ramp from y1 to y2\n    return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1\n\n\ndef colorstr(*input):\n    # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e.  colorstr('blue', 'hello world')\n    *args, string = input if len(input) > 1 else ('blue', 'bold', input[0])  # color arguments, string\n    colors = {'black': '\\033[30m',  # basic colors\n              'red': '\\033[31m',\n              'green': '\\033[32m',\n              'yellow': '\\033[33m',\n              'blue': '\\033[34m',\n              'magenta': '\\033[35m',\n              'cyan': '\\033[36m',\n              'white': '\\033[37m',\n              'bright_black': '\\033[90m',  # bright colors\n              'bright_red': '\\033[91m',\n              'bright_green': '\\033[92m',\n              'bright_yellow': '\\033[93m',\n              'bright_blue': '\\033[94m',\n              'bright_magenta': '\\033[95m',\n              'bright_cyan': '\\033[96m',\n              'bright_white': '\\033[97m',\n              'end': '\\033[0m',  # misc\n              'bold': '\\033[1m',\n              'underline': '\\033[4m'}\n    return ''.join(colors[x] for x in args) + f'{string}' + colors['end']\n\n\ndef labels_to_class_weights(labels, nc=80):\n    # Get class weights (inverse frequency) from training labels\n    if labels[0] is None:  # no labels loaded\n        return torch.Tensor()\n\n    labels = np.concatenate(labels, 0)  # labels.shape = (866643, 5) for COCO\n    classes = labels[:, 0].astype(np.int)  # labels = [class xywh]\n    weights = np.bincount(classes, minlength=nc)  # occurrences per class\n\n    # Prepend gridpoint count (for uCE training)\n    # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum()  # gridpoints per image\n    # weights = np.hstack([gpi * len(labels)  - weights.sum() * 9, weights * 9]) ** 0.5  # prepend gridpoints to start\n\n    weights[weights == 0] = 1  # replace empty bins with 1\n    weights = 1 / weights  # number of targets per class\n    weights /= weights.sum()  # normalize\n    return torch.from_numpy(weights)\n\n\ndef labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):\n    # Produces image weights based on class_weights and image contents\n    class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels])\n    image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)\n    # index = random.choices(range(n), weights=image_weights, k=1)  # weight image sample\n    return image_weights\n\n\ndef coco80_to_coco91_class():  # converts 80-index (val2014) to 91-index (paper)\n    # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/\n    # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\\n')\n    # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\\n')\n    # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)]  # darknet to coco\n    # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)]  # coco to darknet\n    x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,\n         35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,\n         64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]\n    return x\n\n\ndef xyxy2xywh(x):\n    # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = (x[:, 0] + x[:, 2]) / 2  # x center\n    y[:, 1] = (x[:, 1] + x[:, 3]) / 2  # y center\n    y[:, 2] = x[:, 2] - x[:, 0]  # width\n    y[:, 3] = x[:, 3] - x[:, 1]  # height\n    return y\n\n\ndef xywh2xyxy(x):\n    # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = x[:, 0] - x[:, 2] / 2  # top left x\n    y[:, 1] = x[:, 1] - x[:, 3] / 2  # top left y\n    y[:, 2] = x[:, 0] + x[:, 2] / 2  # bottom right x\n    y[:, 3] = x[:, 1] + x[:, 3] / 2  # bottom right y\n    return y\n\n\ndef xywhn2xyxy(x, w=640, h=640, padw=32, padh=32):\n    # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw  # top left x\n    y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh  # top left y\n    y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw  # bottom right x\n    y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh  # bottom right y\n    return y\n\n\ndef scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):\n    # Rescale coords (xyxy) from img1_shape to img0_shape\n    if ratio_pad is None:  # calculate from img0_shape\n        gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])  # gain  = old / new\n        pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2  # wh padding\n    else:\n        gain = ratio_pad[0][0]\n        pad = ratio_pad[1]\n\n    coords[:, [0, 2]] -= pad[0]  # x padding\n    coords[:, [1, 3]] -= pad[1]  # y padding\n    coords[:, :4] /= gain\n    clip_coords(coords, img0_shape)\n    return coords\n\n\ndef clip_coords(boxes, img_shape):\n    # Clip bounding xyxy bounding boxes to image shape (height, width)\n    boxes[:, 0].clamp_(0, img_shape[1])  # x1\n    boxes[:, 1].clamp_(0, img_shape[0])  # y1\n    boxes[:, 2].clamp_(0, img_shape[1])  # x2\n    boxes[:, 3].clamp_(0, img_shape[0])  # y2\n\n\ndef bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-9):\n    # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4\n    box2 = box2.T\n\n    # Get the coordinates of bounding boxes\n    if x1y1x2y2:  # x1, y1, x2, y2 = box1\n        b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]\n        b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]\n    else:  # transform from xywh to xyxy\n        b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2\n        b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2\n        b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2\n        b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2\n\n    # Intersection area\n    inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \\\n            (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)\n\n    # Union Area\n    w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps\n    w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps\n    union = w1 * h1 + w2 * h2 - inter + eps\n\n    iou = inter / union\n    if GIoU or DIoU or CIoU:\n        # convex (smallest enclosing box) width\n        cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1)\n        ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1)  # convex height\n        if CIoU or DIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1\n            c2 = cw ** 2 + ch ** 2 + eps  # convex diagonal squared\n            rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +\n                    (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4  # center distance squared\n            if DIoU:\n                return iou - rho2 / c2  # DIoU\n            elif CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47\n                v = (4 / math.pi ** 2) * \\\n                    torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)\n                with torch.no_grad():\n                    alpha = v / ((1 + eps) - iou + v)\n                return iou - (rho2 / c2 + v * alpha)  # CIoU\n        else:  # GIoU https://arxiv.org/pdf/1902.09630.pdf\n            c_area = cw * ch + eps  # convex area\n            return iou - (c_area - union) / c_area  # GIoU\n    else:\n        return iou  # IoU\n\n\ndef box_iou(box1, box2):\n    # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\n    \"\"\"\n    Return intersection-over-union (Jaccard index) of boxes.\n    Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n    Arguments:\n        box1 (Tensor[N, 4])\n        box2 (Tensor[M, 4])\n    Returns:\n        iou (Tensor[N, M]): the NxM matrix containing the pairwise\n            IoU values for every element in boxes1 and boxes2\n    \"\"\"\n\n    def box_area(box):\n        # box = 4xn\n        return (box[2] - box[0]) * (box[3] - box[1])\n\n    area1 = box_area(box1.T)\n    area2 = box_area(box2.T)\n\n    # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\n    inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) -\n             torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)\n    # iou = inter / (area1 + area2 - inter)\n    return inter / (area1[:, None] + area2 - inter)\n\n\ndef wh_iou(wh1, wh2):\n    # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2\n    wh1 = wh1[:, None]  # [N,1,2]\n    wh2 = wh2[None]  # [1,M,2]\n    inter = torch.min(wh1, wh2).prod(2)  # [N,M]\n    # iou = inter / (area1 + area2 - inter)\n    return inter / (wh1.prod(2) + wh2.prod(2) - inter)\n\ndef jaccard_diou(box_a, box_b, iscrowd:bool=False):\n    use_batch = True\n    if box_a.dim() == 2:\n        use_batch = False\n        box_a = box_a[None, ...]\n        box_b = box_b[None, ...]\n\n    inter = intersect(box_a, box_b)\n    area_a = ((box_a[:, :, 2]-box_a[:, :, 0]) *\n              (box_a[:, :, 3]-box_a[:, :, 1])).unsqueeze(2).expand_as(inter)  # [A,B]\n    area_b = ((box_b[:, :, 2]-box_b[:, :, 0]) *\n              (box_b[:, :, 3]-box_b[:, :, 1])).unsqueeze(1).expand_as(inter)  # [A,B]\n    union = area_a + area_b - inter\n    x1 = ((box_a[:, :, 2]+box_a[:, :, 0]) / 2).unsqueeze(2).expand_as(inter)\n    y1 = ((box_a[:, :, 3]+box_a[:, :, 1]) / 2).unsqueeze(2).expand_as(inter)\n    x2 = ((box_b[:, :, 2]+box_b[:, :, 0]) / 2).unsqueeze(1).expand_as(inter)\n    y2 = ((box_b[:, :, 3]+box_b[:, :, 1]) / 2).unsqueeze(1).expand_as(inter)\n\n    t1 = box_a[:, :, 1].unsqueeze(2).expand_as(inter)\n    b1 = box_a[:, :, 3].unsqueeze(2).expand_as(inter)\n    l1 = box_a[:, :, 0].unsqueeze(2).expand_as(inter)\n    r1 = box_a[:, :, 2].unsqueeze(2).expand_as(inter)\n\n    t2 = box_b[:, :, 1].unsqueeze(1).expand_as(inter)\n    b2 = box_b[:, :, 3].unsqueeze(1).expand_as(inter)\n    l2 = box_b[:, :, 0].unsqueeze(1).expand_as(inter)\n    r2 = box_b[:, :, 2].unsqueeze(1).expand_as(inter)\n\n    cr = torch.max(r1, r2)\n    cl = torch.min(l1, l2)\n    ct = torch.min(t1, t2)\n    cb = torch.max(b1, b2)\n    D = (((x2 - x1)**2 + (y2 - y1)**2) / ((cr-cl)**2 + (cb-ct)**2 + 1e-7))\n    out = inter / area_a if iscrowd else inter / (union + 1e-7) - D ** 0.7\n    return out if use_batch else out.squeeze(0)\n\n\ndef non_max_suppression_face(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, labels=()):\n    \"\"\"Performs Non-Maximum Suppression (NMS) on inference results\n    Returns:\n         detections with shape: nx6 (x1, y1, x2, y2, conf, cls)\n    \"\"\"\n\n    nc = prediction.shape[2] - 15  # number of classes\n    xc = prediction[..., 4] > conf_thres  # candidates\n\n    # Settings\n    min_wh, max_wh = 2, 4096  # (pixels) minimum and maximum box width and height\n    time_limit = 10.0  # seconds to quit after\n    redundant = True  # require redundant detections\n    multi_label = nc > 1  # multiple labels per box (adds 0.5ms/img)\n    merge = False  # use merge-NMS\n\n    t = time.time()\n    output = [torch.zeros((0, 16), device=prediction.device)] * prediction.shape[0]\n    for xi, x in enumerate(prediction):  # image index, image inference\n        # Apply constraints\n        # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0  # width-height\n        x = x[xc[xi]]  # confidence\n\n        # Cat apriori labels if autolabelling\n        if labels and len(labels[xi]):\n            l = labels[xi]\n            v = torch.zeros((len(l), nc + 15), device=x.device)\n            v[:, :4] = l[:, 1:5]  # box\n            v[:, 4] = 1.0  # conf\n            v[range(len(l)), l[:, 0].long() + 15] = 1.0  # cls\n            x = torch.cat((x, v), 0)\n\n        # If none remain process next image\n        if not x.shape[0]:\n            continue\n\n        # Compute conf\n        x[:, 15:] *= x[:, 4:5]  # conf = obj_conf * cls_conf\n\n        # Box (center x, center y, width, height) to (x1, y1, x2, y2)\n        box = xywh2xyxy(x[:, :4])\n\n        # Detections matrix nx6 (xyxy, conf, landmarks, cls)\n        if multi_label:\n            i, j = (x[:, 15:] > conf_thres).nonzero(as_tuple=False).T\n            x = torch.cat((box[i], x[i, j + 15, None], x[:, 5:15] ,j[:, None].float()), 1)\n        else:  # best class only\n            conf, j = x[:, 15:].max(1, keepdim=True)\n            x = torch.cat((box, conf, x[:, 5:15], j.float()), 1)[conf.view(-1) > conf_thres]\n\n        # Filter by class\n        if classes is not None:\n            x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\n\n        # If none remain process next image\n        n = x.shape[0]  # number of boxes\n        if not n:\n            continue\n\n        # Batched NMS\n        c = x[:, 15:16] * (0 if agnostic else max_wh)  # classes\n        boxes, scores = x[:, :4] + c, x[:, 4]  # boxes (offset by class), scores\n        i = torchvision.ops.nms(boxes, scores, iou_thres)  # NMS\n        #if i.shape[0] > max_det:  # limit detections\n        #    i = i[:max_det]\n        if merge and (1 < n < 3E3):  # Merge NMS (boxes merged using weighted mean)\n            # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\n            iou = box_iou(boxes[i], boxes) > iou_thres  # iou matrix\n            weights = iou * scores[None]  # box weights\n            x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True)  # merged boxes\n            if redundant:\n                i = i[iou.sum(1) > 1]  # require redundancy\n\n        output[xi] = x[i]\n        if (time.time() - t) > time_limit:\n            break  # time limit exceeded\n\n    return output\n\n\ndef non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, labels=()):\n    \"\"\"Performs Non-Maximum Suppression (NMS) on inference results\n\n    Returns:\n         detections with shape: nx6 (x1, y1, x2, y2, conf, cls)\n    \"\"\"\n\n    nc = prediction.shape[2] - 5  # number of classes\n    xc = prediction[..., 4] > conf_thres  # candidates\n\n    # Settings\n    # (pixels) minimum and maximum box width and height\n    min_wh, max_wh = 2, 4096\n    #max_det = 300  # maximum number of detections per image\n    #max_nms = 30000  # maximum number of boxes into torchvision.ops.nms()\n    time_limit = 10.0  # seconds to quit after\n    redundant = True  # require redundant detections\n    multi_label = nc > 1  # multiple labels per box (adds 0.5ms/img)\n    merge = False  # use merge-NMS\n\n    t = time.time()\n    output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]\n    for xi, x in enumerate(prediction):  # image index, image inference\n        # Apply constraints\n        # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0  # width-height\n        x = x[xc[xi]]  # confidence\n\n        # Cat apriori labels if autolabelling\n        if labels and len(labels[xi]):\n            l = labels[xi]\n            v = torch.zeros((len(l), nc + 5), device=x.device)\n            v[:, :4] = l[:, 1:5]  # box\n            v[:, 4] = 1.0  # conf\n            v[range(len(l)), l[:, 0].long() + 5] = 1.0  # cls\n            x = torch.cat((x, v), 0)\n\n        # If none remain process next image\n        if not x.shape[0]:\n            continue\n\n        # Compute conf\n        x[:, 5:] *= x[:, 4:5]  # conf = obj_conf * cls_conf\n\n        # Box (center x, center y, width, height) to (x1, y1, x2, y2)\n        box = xywh2xyxy(x[:, :4])\n\n        # Detections matrix nx6 (xyxy, conf, cls)\n        if multi_label:\n            i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T\n            x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)\n        else:  # best class only\n            conf, j = x[:, 5:].max(1, keepdim=True)\n            x = torch.cat((box, conf, j.float()), 1)[\n                conf.view(-1) > conf_thres]\n\n        # Filter by class\n        if classes is not None:\n            x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\n\n        # Apply finite constraint\n        # if not torch.isfinite(x).all():\n        #     x = x[torch.isfinite(x).all(1)]\n\n        # Check shape\n        n = x.shape[0]  # number of boxes\n        if not n:  # no boxes\n            continue\n        #elif n > max_nms:  # excess boxes\n        #    x = x[x[:, 4].argsort(descending=True)[:max_nms]]  # sort by confidence\n        x = x[x[:, 4].argsort(descending=True)]  # sort by confidence\n\n        # Batched NMS\n        c = x[:, 5:6] * (0 if agnostic else max_wh)  # classes\n        boxes, scores = x[:, :4] + c, x[:, 4]  # boxes (offset by class), scores\n        i = torchvision.ops.nms(boxes, scores, iou_thres)  # NMS\n        #if i.shape[0] > max_det:  # limit detections\n        #    i = i[:max_det]\n        if merge and (1 < n < 3E3):  # Merge NMS (boxes merged using weighted mean)\n            # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\n            iou = box_iou(boxes[i], boxes) > iou_thres  # iou matrix\n            weights = iou * scores[None]  # box weights\n            x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True)  # merged boxes\n            if redundant:\n                i = i[iou.sum(1) > 1]  # require redundancy\n\n        output[xi] = x[i]\n        if (time.time() - t) > time_limit:\n            print(f'WARNING: NMS time limit {time_limit}s exceeded')\n            break  # time limit exceeded\n\n    return output\n\n\ndef strip_optimizer(f='weights/best.pt', s=''):  # from utils.general import *; strip_optimizer()\n    # Strip optimizer from 'f' to finalize training, optionally save as 's'\n    x = torch.load(f, map_location=torch.device('cpu'))\n    for key in 'optimizer', 'training_results', 'wandb_id':\n        x[key] = None\n    x['epoch'] = -1\n    x['model'].half()  # to FP16\n    for p in x['model'].parameters():\n        p.requires_grad = False\n    torch.save(x, s or f)\n    mb = os.path.getsize(s or f) / 1E6  # filesize\n    print('Optimizer stripped from %s,%s %.1fMB' % (f, (' saved as %s,' % s) if s else '', mb))\n\n\ndef print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''):\n    # Print mutation results to evolve.txt (for use with train.py --evolve)\n    a = '%10s' * len(hyp) % tuple(hyp.keys())  # hyperparam keys\n    b = '%10.3g' * len(hyp) % tuple(hyp.values())  # hyperparam values\n    c = '%10.4g' * len(results) % results  # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)\n    print('\\n%s\\n%s\\nEvolved fitness: %s\\n' % (a, b, c))\n\n    if bucket:\n        url = 'gs://%s/evolve.txt' % bucket\n        if gsutil_getsize(url) > (os.path.getsize('evolve.txt') if os.path.exists('evolve.txt') else 0):\n            os.system('gsutil cp %s .' % url)  # download evolve.txt if larger than local\n\n    with open('evolve.txt', 'a') as f:  # append result\n        f.write(c + b + '\\n')\n    x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0)  # load unique rows\n    x = x[np.argsort(-fitness(x))]  # sort\n    np.savetxt('evolve.txt', x, '%10.3g')  # save sort by fitness\n\n    # Save yaml\n    for i, k in enumerate(hyp.keys()):\n        hyp[k] = float(x[0, i + 7])\n    with open(yaml_file, 'w') as f:\n        results = tuple(x[0, :7])\n        c = '%10.4g' * len(results) % results  # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)\n        f.write('# Hyperparameter Evolution Results\\n# Generations: %g\\n# Metrics: ' % len(x) + c + '\\n\\n')\n        yaml.dump(hyp, f, sort_keys=False)\n\n    if bucket:\n        os.system('gsutil cp evolve.txt %s gs://%s' % (yaml_file, bucket))  # upload\n\n\ndef apply_classifier(x, model, img, im0):\n    # applies a second stage classifier to yolo outputs\n    im0 = [im0] if isinstance(im0, np.ndarray) else im0\n    for i, d in enumerate(x):  # per image\n        if d is not None and len(d):\n            d = d.clone()\n\n            # Reshape and pad cutouts\n            b = xyxy2xywh(d[:, :4])  # boxes\n            b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1)  # rectangle to square\n            b[:, 2:] = b[:, 2:] * 1.3 + 30  # pad\n            d[:, :4] = xywh2xyxy(b).long()\n\n            # Rescale boxes from img_size to im0 size\n            scale_coords(img.shape[2:], d[:, :4], im0[i].shape)\n\n            # Classes\n            pred_cls1 = d[:, 5].long()\n            ims = []\n            for j, a in enumerate(d):  # per item\n                cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]\n                im = cv2.resize(cutout, (224, 224))  # BGR\n                # cv2.imwrite('test%i.jpg' % j, cutout)\n\n                # BGR to RGB, to 3x416x416\n                im = im[:, :, ::-1].transpose(2, 0, 1)\n                im = np.ascontiguousarray(\n                    im, dtype=np.float32)  # uint8 to float32\n                im /= 255.0  # 0 - 255 to 0.0 - 1.0\n                ims.append(im)\n\n            pred_cls2 = model(torch.Tensor(ims).to(d.device)\n                              ).argmax(1)  # classifier prediction\n            # retain matching class detections\n            x[i] = x[i][pred_cls1 == pred_cls2]\n\n    return x\n\n\ndef increment_path(path, exist_ok=True, sep=''):\n    # Increment path, i.e. runs/exp --> runs/exp{sep}0, runs/exp{sep}1 etc.\n    path = Path(path)  # os-agnostic\n    if (path.exists() and exist_ok) or (not path.exists()):\n        return str(path)\n    else:\n        dirs = glob.glob(f\"{path}{sep}*\")  # similar paths\n        matches = [re.search(rf\"%s{sep}(\\d+)\" % path.stem, d) for d in dirs]\n        i = [int(m.groups()[0]) for m in matches if m]  # indices\n        n = max(i) + 1 if i else 2  # increment number\n        return f\"{path}{sep}{n}\"  # update path\ndef filter_boxes(boxes, min_size):\n    \"\"\" Remove all boxes with any side smaller than min_size \"\"\"\n    ws = boxes[:, 2] - boxes[:, 0] + 1\n    hs = boxes[:, 3] - boxes[:, 1] + 1\n    keep = np.where((hs >= min_size))[0]\n#         keep = np.where((ws >= min_size) & (hs >= min_size))[0]\n    return keep\ndef scale_coords_landmarks(img1_shape, coords, img0_shape, ratio_pad=None):\n    # Rescale coords (xyxy) from img1_shape to img0_shape\n    if ratio_pad is None:  # calculate from img0_shape\n        gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])  # gain  = old / new\n        pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2  # wh padding\n    else:\n        gain = ratio_pad[0][0]\n        pad = ratio_pad[1]\n\n    coords[:, [0, 2, 4, 6, 8]] -= pad[0]  # x padding\n    coords[:, [1, 3, 5, 7, 9]] -= pad[1]  # y padding\n    coords[:, :10] /= gain\n    #clip_coords(coords, img0_shape)\n    coords[:, 0].clamp_(0, img0_shape[1])  # x1\n    coords[:, 1].clamp_(0, img0_shape[0])  # y1\n    coords[:, 2].clamp_(0, img0_shape[1])  # x2\n    coords[:, 3].clamp_(0, img0_shape[0])  # y2\n    coords[:, 4].clamp_(0, img0_shape[1])  # x3\n    coords[:, 5].clamp_(0, img0_shape[0])  # y3\n    coords[:, 6].clamp_(0, img0_shape[1])  # x4\n    coords[:, 7].clamp_(0, img0_shape[0])  # y4\n    coords[:, 8].clamp_(0, img0_shape[1])  # x5\n    coords[:, 9].clamp_(0, img0_shape[0])  # y5\n    return coords"
  },
  {
    "path": "utils/google_app_engine/Dockerfile",
    "content": "FROM gcr.io/google-appengine/python\n\n# Create a virtualenv for dependencies. This isolates these packages from\n# system-level packages.\n# Use -p python3 or -p python3.7 to select python version. Default is version 2.\nRUN virtualenv /env -p python3\n\n# Setting these environment variables are the same as running\n# source /env/bin/activate.\nENV VIRTUAL_ENV /env\nENV PATH /env/bin:$PATH\n\nRUN apt-get update && apt-get install -y python-opencv\n\n# Copy the application's requirements.txt and run pip to install all\n# dependencies into the virtualenv.\nADD requirements.txt /app/requirements.txt\nRUN pip install -r /app/requirements.txt\n\n# Add the application source code.\nADD . /app\n\n# Run a WSGI server to serve the application. gunicorn must be declared as\n# a dependency in requirements.txt.\nCMD gunicorn -b :$PORT main:app\n"
  },
  {
    "path": "utils/google_app_engine/additional_requirements.txt",
    "content": "# add these requirements in your app on top of the existing ones\npip==18.1\nFlask==1.0.2\ngunicorn==19.9.0\n"
  },
  {
    "path": "utils/google_app_engine/app.yaml",
    "content": "runtime: custom\nenv: flex\n\nservice: yolov5app\n\nliveness_check:\n  initial_delay_sec: 600\n\nmanual_scaling:\n  instances: 1\nresources:\n  cpu: 1\n  memory_gb: 4\n  disk_size_gb: 20"
  },
  {
    "path": "utils/google_utils.py",
    "content": "# Google utils: https://cloud.google.com/storage/docs/reference/libraries\n\nimport os\nimport platform\nimport subprocess\nimport time\nfrom pathlib import Path\n\nimport requests\nimport torch\n\n\ndef gsutil_getsize(url=''):\n    # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du\n    s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')\n    return eval(s.split(' ')[0]) if len(s) else 0  # bytes\n\n\ndef attempt_download(file, repo='ultralytics/yolov5'):\n    # Attempt file download if does not exist\n    file = Path(str(file).strip().replace(\"'\", '').lower())\n\n    if not file.exists():\n        try:\n            response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json()  # github api\n            assets = [x['name'] for x in response['assets']]  # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]\n            tag = response['tag_name']  # i.e. 'v1.0'\n        except:  # fallback plan\n            assets = ['yolov5.pt', 'yolov5.pt', 'yolov5l.pt', 'yolov5x.pt']\n            tag = subprocess.check_output('git tag', shell=True).decode('utf-8').split('\\n')[-2]\n\n        name = file.name\n        if name in assets:\n            msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'\n            redundant = False  # second download option\n            try:  # GitHub\n                url = f'https://github.com/{repo}/releases/download/{tag}/{name}'\n                print(f'Downloading {url} to {file}...')\n                torch.hub.download_url_to_file(url, file)\n                assert file.exists() and file.stat().st_size > 1E6  # check\n            except Exception as e:  # GCP\n                print(f'Download error: {e}')\n                assert redundant, 'No secondary mirror'\n                url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'\n                print(f'Downloading {url} to {file}...')\n                os.system(f'curl -L {url} -o {file}')  # torch.hub.download_url_to_file(url, weights)\n            finally:\n                if not file.exists() or file.stat().st_size < 1E6:  # check\n                    file.unlink(missing_ok=True)  # remove partial downloads\n                    print(f'ERROR: Download failure: {msg}')\n                print('')\n                return\n\n\ndef gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):\n    # Downloads a file from Google Drive. from yolov5.utils.google_utils import *; gdrive_download()\n    t = time.time()\n    file = Path(file)\n    cookie = Path('cookie')  # gdrive cookie\n    print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')\n    file.unlink(missing_ok=True)  # remove existing file\n    cookie.unlink(missing_ok=True)  # remove existing cookie\n\n    # Attempt file download\n    out = \"NUL\" if platform.system() == \"Windows\" else \"/dev/null\"\n    os.system(f'curl -c ./cookie -s -L \"drive.google.com/uc?export=download&id={id}\" > {out}')\n    if os.path.exists('cookie'):  # large file\n        s = f'curl -Lb ./cookie \"drive.google.com/uc?export=download&confirm={get_token()}&id={id}\" -o {file}'\n    else:  # small file\n        s = f'curl -s -L -o {file} \"drive.google.com/uc?export=download&id={id}\"'\n    r = os.system(s)  # execute, capture return\n    cookie.unlink(missing_ok=True)  # remove existing cookie\n\n    # Error check\n    if r != 0:\n        file.unlink(missing_ok=True)  # remove partial\n        print('Download error ')  # raise Exception('Download error')\n        return r\n\n    # Unzip if archive\n    if file.suffix == '.zip':\n        print('unzipping... ', end='')\n        os.system(f'unzip -q {file}')  # unzip\n        file.unlink()  # remove zip to free space\n\n    print(f'Done ({time.time() - t:.1f}s)')\n    return r\n\n\ndef get_token(cookie=\"./cookie\"):\n    with open(cookie) as f:\n        for line in f:\n            if \"download\" in line:\n                return line.split()[-1]\n    return \"\"\n\n# def upload_blob(bucket_name, source_file_name, destination_blob_name):\n#     # Uploads a file to a bucket\n#     # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python\n#\n#     storage_client = storage.Client()\n#     bucket = storage_client.get_bucket(bucket_name)\n#     blob = bucket.blob(destination_blob_name)\n#\n#     blob.upload_from_filename(source_file_name)\n#\n#     print('File {} uploaded to {}.'.format(\n#         source_file_name,\n#         destination_blob_name))\n#\n#\n# def download_blob(bucket_name, source_blob_name, destination_file_name):\n#     # Uploads a blob from a bucket\n#     storage_client = storage.Client()\n#     bucket = storage_client.get_bucket(bucket_name)\n#     blob = bucket.blob(source_blob_name)\n#\n#     blob.download_to_filename(destination_file_name)\n#\n#     print('Blob {} downloaded to {}.'.format(\n#         source_blob_name,\n#         destination_file_name))\n"
  },
  {
    "path": "utils/infer_utils.py",
    "content": "import torch\n\n\n\ndef decode_infer(output, stride):\n    # logging.info(torch.tensor(output.shape[0]))\n    # logging.info(output.shape)\n    # # bz is batch-size\n    # bz = tuple(torch.tensor(output.shape[0]))\n    # gridsize = tuple(torch.tensor(output.shape[-1]))\n    # logging.info(gridsize)\n    sh = torch.tensor(output.shape)\n    bz = sh[0]\n    gridsize = sh[-1]\n\n    output = output.permute(0, 2, 3, 1)\n    output = output.view(bz, gridsize, gridsize, self.gt_per_grid, 5+self.numclass)\n    x1y1, x2y2, conf, prob = torch.split(\n        output, [2, 2, 1, self.numclass], dim=4)\n\n    shiftx = torch.arange(0, gridsize, dtype=torch.float32)\n    shifty = torch.arange(0, gridsize, dtype=torch.float32)\n    shifty, shiftx = torch.meshgrid([shiftx, shifty], indexing='ij')\n    shiftx = shiftx.unsqueeze(-1).repeat(bz, 1, 1, self.gt_per_grid)\n    shifty = shifty.unsqueeze(-1).repeat(bz, 1, 1, self.gt_per_grid)\n\n    xy_grid = torch.stack([shiftx, shifty], dim=4).cuda()\n    x1y1 = (xy_grid+0.5-torch.exp(x1y1))*stride\n    x2y2 = (xy_grid+0.5+torch.exp(x2y2))*stride\n\n    xyxy = torch.cat((x1y1, x2y2), dim=4)\n    conf = torch.sigmoid(conf)\n    prob = torch.sigmoid(prob)\n    output = torch.cat((xyxy, conf, prob), 4)\n    output = output.view(bz, -1, 5+self.numclass)\n    return output\n"
  },
  {
    "path": "utils/loss.py",
    "content": "# Loss functions\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom utils.general import bbox_iou\nfrom utils.torch_utils import is_parallel\n\n\ndef smooth_BCE(eps=0.1):  # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441\n    # return positive, negative label smoothing BCE targets\n    return 1.0 - 0.5 * eps, 0.5 * eps\n\n\nclass BCEBlurWithLogitsLoss(nn.Module):\n    # BCEwithLogitLoss() with reduced missing label effects.\n    def __init__(self, alpha=0.05):\n        super(BCEBlurWithLogitsLoss, self).__init__()\n        self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none')  # must be nn.BCEWithLogitsLoss()\n        self.alpha = alpha\n\n    def forward(self, pred, true):\n        loss = self.loss_fcn(pred, true)\n        pred = torch.sigmoid(pred)  # prob from logits\n        dx = pred - true  # reduce only missing label effects\n        # dx = (pred - true).abs()  # reduce missing label and false label effects\n        alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))\n        loss *= alpha_factor\n        return loss.mean()\n\n\nclass FocalLoss(nn.Module):\n    # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)\n    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):\n        super(FocalLoss, self).__init__()\n        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()\n        self.gamma = gamma\n        self.alpha = alpha\n        self.reduction = loss_fcn.reduction\n        self.loss_fcn.reduction = 'none'  # required to apply FL to each element\n\n    def forward(self, pred, true):\n        loss = self.loss_fcn(pred, true)\n        # p_t = torch.exp(-loss)\n        # loss *= self.alpha * (1.000001 - p_t) ** self.gamma  # non-zero power for gradient stability\n\n        # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py\n        pred_prob = torch.sigmoid(pred)  # prob from logits\n        p_t = true * pred_prob + (1 - true) * (1 - pred_prob)\n        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)\n        modulating_factor = (1.0 - p_t) ** self.gamma\n        loss *= alpha_factor * modulating_factor\n\n        if self.reduction == 'mean':\n            return loss.mean()\n        elif self.reduction == 'sum':\n            return loss.sum()\n        else:  # 'none'\n            return loss\n\n\nclass QFocalLoss(nn.Module):\n    # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)\n    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):\n        super(QFocalLoss, self).__init__()\n        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()\n        self.gamma = gamma\n        self.alpha = alpha\n        self.reduction = loss_fcn.reduction\n        self.loss_fcn.reduction = 'none'  # required to apply FL to each element\n\n    def forward(self, pred, true):\n        loss = self.loss_fcn(pred, true)\n\n        pred_prob = torch.sigmoid(pred)  # prob from logits\n        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)\n        modulating_factor = torch.abs(true - pred_prob) ** self.gamma\n        loss *= alpha_factor * modulating_factor\n\n        if self.reduction == 'mean':\n            return loss.mean()\n        elif self.reduction == 'sum':\n            return loss.sum()\n        else:  # 'none'\n            return loss\n\nclass WingLoss(nn.Module):\n    def __init__(self, w=10, e=2):\n        super(WingLoss, self).__init__()\n        # https://arxiv.org/pdf/1711.06753v4.pdf   Figure 5\n        self.w = w\n        self.e = e\n        self.C = self.w - self.w * np.log(1 + self.w / self.e)\n\n    def forward(self, x, t, sigma=1):\n        weight = torch.ones_like(t)\n        weight[torch.where(t==-1)] = 0\n        diff = weight * (x - t)\n        abs_diff = diff.abs()\n        flag = (abs_diff.data < self.w).float()\n        y = flag * self.w * torch.log(1 + abs_diff / self.e) + (1 - flag) * (abs_diff - self.C)\n        return y.sum()\n\nclass LandmarksLoss(nn.Module):\n    # BCEwithLogitLoss() with reduced missing label effects.\n    def __init__(self, alpha=1.0):\n        super(LandmarksLoss, self).__init__()\n        self.loss_fcn = WingLoss()#nn.SmoothL1Loss(reduction='sum')\n        self.alpha = alpha\n\n    def forward(self, pred, truel, mask):\n        loss = self.loss_fcn(pred*mask, truel*mask)\n        return loss / (torch.sum(mask) + 10e-14)\n\n\ndef compute_loss(p, targets, model):  # predictions, targets, model\n    device = targets.device\n    lcls, lbox, lobj, lmark = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)\n    tcls, tbox, indices, anchors, tlandmarks, lmks_mask = build_targets(p, targets, model)  # targets\n    h = model.hyp  # hyperparameters\n\n    # Define criteria\n    BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))  # weight=model.class_weights)\n    BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))\n\n    landmarks_loss = LandmarksLoss(1.0)\n\n    # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3\n    cp, cn = smooth_BCE(eps=0.0)\n\n    # Focal loss\n    g = h['fl_gamma']  # focal loss gamma\n    if g > 0:\n        BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)\n\n    # Losses\n    nt = 0  # number of targets\n    no = len(p)  # number of outputs\n    balance = [4.0, 1.0, 0.4] if no == 3 else [4.0, 1.0, 0.4, 0.1]  # P3-5 or P3-6\n    for i, pi in enumerate(p):  # layer index, layer predictions\n        b, a, gj, gi = indices[i]  # image, anchor, gridy, gridx\n        tobj = torch.zeros_like(pi[..., 0], device=device)  # target obj\n\n        n = b.shape[0]  # number of targets\n        if n:\n            nt += n  # cumulative targets\n            ps = pi[b, a, gj, gi]  # prediction subset corresponding to targets\n\n            # Regression\n            pxy = ps[:, :2].sigmoid() * 2. - 0.5\n            pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]\n            pbox = torch.cat((pxy, pwh), 1)  # predicted box\n            iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True)  # iou(prediction, target)\n            lbox += (1.0 - iou).mean()  # iou loss\n\n            # Objectness\n            tobj[b, a, gj, gi] = (1.0 - model.gr) + model.gr * iou.detach().clamp(0).type(tobj.dtype)  # iou ratio\n\n            # Classification\n            if model.nc > 1:  # cls loss (only if multiple classes)\n                t = torch.full_like(ps[:, 15:], cn, device=device)  # targets\n                t[range(n), tcls[i]] = cp\n                lcls += BCEcls(ps[:, 15:], t)  # BCE\n\n            # Append targets to text file\n            # with open('targets.txt', 'a') as file:\n            #     [file.write('%11.5g ' * 4 % tuple(x) + '\\n') for x in torch.cat((txy[i], twh[i]), 1)]\n\n            #landmarks loss\n            #plandmarks = ps[:,5:15].sigmoid() * 8. - 4.\n            plandmarks = ps[:,5:15]\n\n            plandmarks[:, 0:2] = plandmarks[:, 0:2] * anchors[i]\n            plandmarks[:, 2:4] = plandmarks[:, 2:4] * anchors[i]\n            plandmarks[:, 4:6] = plandmarks[:, 4:6] * anchors[i]\n            plandmarks[:, 6:8] = plandmarks[:, 6:8] * anchors[i]\n            plandmarks[:, 8:10] = plandmarks[:,8:10] * anchors[i]\n\n            lmark += landmarks_loss(plandmarks, tlandmarks[i], lmks_mask[i])\n\n\n        lobj += BCEobj(pi[..., 4], tobj) * balance[i]  # obj loss\n\n    s = 3 / no  # output count scaling\n    lbox *= h['box'] * s\n    lobj *= h['obj'] * s * (1.4 if no == 4 else 1.)\n    lcls *= h['cls'] * s\n    lmark *= h['landmark'] * s\n\n    bs = tobj.shape[0]  # batch size\n\n    loss = lbox + lobj + lcls + lmark\n    return loss * bs, torch.cat((lbox, lobj, lcls, lmark, loss)).detach()\n\n\ndef build_targets(p, targets, model):\n    # Build targets for compute_loss(), input targets(image,class,x,y,w,h)\n    det = model.module.model[-1] if is_parallel(model) else model.model[-1]  # Detect() module\n    na, nt = det.na, targets.shape[0]  # number of anchors, targets\n    tcls, tbox, indices, anch, landmarks, lmks_mask = [], [], [], [], [], []\n    #gain = torch.ones(7, device=targets.device)  # normalized to gridspace gain\n    gain = torch.ones(17, device=targets.device)\n    ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt)  # same as .repeat_interleave(nt)\n    targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2)  # append anchor indices\n\n    g = 0.5  # bias\n    off = torch.tensor([[0, 0],\n                        [1, 0], [0, 1], [-1, 0], [0, -1],  # j,k,l,m\n                        # [1, 1], [1, -1], [-1, 1], [-1, -1],  # jk,jm,lk,lm\n                        ], device=targets.device).float() * g  # offsets\n\n    for i in range(det.nl):\n        anchors = det.anchors[i]\n        gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]]  # xyxy gain\n        #landmarks 10\n        gain[6:16] = torch.tensor(p[i].shape)[[3, 2, 3, 2, 3, 2, 3, 2, 3, 2]]  # xyxy gain\n\n        # Match targets to anchors\n        t = targets * gain\n        if nt:\n            # Matches\n            r = t[:, :, 4:6] / anchors[:, None]  # wh ratio\n            j = torch.max(r, 1. / r).max(2)[0] < model.hyp['anchor_t']  # compare\n            # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t']  # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))\n            t = t[j]  # filter\n\n            # Offsets\n            gxy = t[:, 2:4]  # grid xy\n            gxi = gain[[2, 3]] - gxy  # inverse\n            j, k = ((gxy % 1. < g) & (gxy > 1.)).T\n            l, m = ((gxi % 1. < g) & (gxi > 1.)).T\n            j = torch.stack((torch.ones_like(j), j, k, l, m))\n            t = t.repeat((5, 1, 1))[j]\n            offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]\n        else:\n            t = targets[0]\n            offsets = 0\n\n        # Define\n        b, c = t[:, :2].long().T  # image, class\n        gxy = t[:, 2:4]  # grid xy\n        gwh = t[:, 4:6]  # grid wh\n        gij = (gxy - offsets).long()\n        gi, gj = gij.T  # grid xy indices\n\n        # Append\n        a = t[:, 16].long()  # anchor indices\n        indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1)))  # image, anchor, grid indices\n        tbox.append(torch.cat((gxy - gij, gwh), 1))  # box\n        anch.append(anchors[a])  # anchors\n        tcls.append(c)  # class\n\n        #landmarks\n        lks = t[:,6:16]\n        #lks_mask = lks > 0\n        #lks_mask = lks_mask.float()\n        lks_mask = torch.where(lks < 0, torch.full_like(lks, 0.), torch.full_like(lks, 1.0))\n\n        #应该是关键点的坐标除以anch的宽高才对，便于模型学习。使用gwh会导致不同关键点的编码不同，没有统一的参考标准\n\n        lks[:, [0, 1]] = (lks[:, [0, 1]] - gij)\n        lks[:, [2, 3]] = (lks[:, [2, 3]] - gij)\n        lks[:, [4, 5]] = (lks[:, [4, 5]] - gij)\n        lks[:, [6, 7]] = (lks[:, [6, 7]] - gij)\n        lks[:, [8, 9]] = (lks[:, [8, 9]] - gij)\n\n        '''\n        #anch_w = torch.ones(5, device=targets.device).fill_(anchors[0][0])\n        #anch_wh = torch.ones(5, device=targets.device)\n        anch_f_0 = (a == 0).unsqueeze(1).repeat(1, 5)\n        anch_f_1 = (a == 1).unsqueeze(1).repeat(1, 5)\n        anch_f_2 = (a == 2).unsqueeze(1).repeat(1, 5)\n        lks[:, [0, 2, 4, 6, 8]] = torch.where(anch_f_0, lks[:, [0, 2, 4, 6, 8]] / anchors[0][0], lks[:, [0, 2, 4, 6, 8]])\n        lks[:, [0, 2, 4, 6, 8]] = torch.where(anch_f_1, lks[:, [0, 2, 4, 6, 8]] / anchors[1][0], lks[:, [0, 2, 4, 6, 8]])\n        lks[:, [0, 2, 4, 6, 8]] = torch.where(anch_f_2, lks[:, [0, 2, 4, 6, 8]] / anchors[2][0], lks[:, [0, 2, 4, 6, 8]])\n\n        lks[:, [1, 3, 5, 7, 9]] = torch.where(anch_f_0, lks[:, [1, 3, 5, 7, 9]] / anchors[0][1], lks[:, [1, 3, 5, 7, 9]])\n        lks[:, [1, 3, 5, 7, 9]] = torch.where(anch_f_1, lks[:, [1, 3, 5, 7, 9]] / anchors[1][1], lks[:, [1, 3, 5, 7, 9]])\n        lks[:, [1, 3, 5, 7, 9]] = torch.where(anch_f_2, lks[:, [1, 3, 5, 7, 9]] / anchors[2][1], lks[:, [1, 3, 5, 7, 9]])\n\n        #new_lks = lks[lks_mask>0]\n        #print('new_lks:   min --- ', torch.min(new_lks), '  max --- ', torch.max(new_lks))\n        \n        lks_mask_1 = torch.where(lks < -3, torch.full_like(lks, 0.), torch.full_like(lks, 1.0))\n        lks_mask_2 = torch.where(lks > 3, torch.full_like(lks, 0.), torch.full_like(lks, 1.0))\n\n        lks_mask_new = lks_mask * lks_mask_1 * lks_mask_2\n        lks_mask_new[:, 0] = lks_mask_new[:, 0] * lks_mask_new[:, 1]\n        lks_mask_new[:, 1] = lks_mask_new[:, 0] * lks_mask_new[:, 1]\n        lks_mask_new[:, 2] = lks_mask_new[:, 2] * lks_mask_new[:, 3]\n        lks_mask_new[:, 3] = lks_mask_new[:, 2] * lks_mask_new[:, 3]\n        lks_mask_new[:, 4] = lks_mask_new[:, 4] * lks_mask_new[:, 5]\n        lks_mask_new[:, 5] = lks_mask_new[:, 4] * lks_mask_new[:, 5]\n        lks_mask_new[:, 6] = lks_mask_new[:, 6] * lks_mask_new[:, 7]\n        lks_mask_new[:, 7] = lks_mask_new[:, 6] * lks_mask_new[:, 7]\n        lks_mask_new[:, 8] = lks_mask_new[:, 8] * lks_mask_new[:, 9]\n        lks_mask_new[:, 9] = lks_mask_new[:, 8] * lks_mask_new[:, 9]\n        '''\n        lks_mask_new = lks_mask\n        lmks_mask.append(lks_mask_new)\n        landmarks.append(lks)\n        #print('lks: ',  lks.size())\n\n    return tcls, tbox, indices, anch, landmarks, lmks_mask\n"
  },
  {
    "path": "utils/metrics.py",
    "content": "# Model validation metrics\n\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\n\nfrom . import general\n\n\ndef fitness(x):\n    # Model fitness as a weighted combination of metrics\n    w = [0.0, 0.0, 0.1, 0.9]  # weights for [P, R, mAP@0.5, mAP@0.5:0.95]\n    return (x[:, :4] * w).sum(1)\n\n\ndef ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='precision-recall_curve.png', names=[]):\n    \"\"\" Compute the average precision, given the recall and precision curves.\n    Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.\n    # Arguments\n        tp:  True positives (nparray, nx1 or nx10).\n        conf:  Objectness value from 0-1 (nparray).\n        pred_cls:  Predicted object classes (nparray).\n        target_cls:  True object classes (nparray).\n        plot:  Plot precision-recall curve at mAP@0.5\n        save_dir:  Plot save directory\n    # Returns\n        The average precision as computed in py-faster-rcnn.\n    \"\"\"\n\n    # Sort by objectness\n    i = np.argsort(-conf)\n    tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]\n\n    # Find unique classes\n    unique_classes = np.unique(target_cls)\n\n    # Create Precision-Recall curve and compute AP for each class\n    px, py = np.linspace(0, 1, 1000), []  # for plotting\n    pr_score = 0.1  # score to evaluate P and R https://github.com/ultralytics/yolov3/issues/898\n    s = [unique_classes.shape[0], tp.shape[1]]  # number class, number iou thresholds (i.e. 10 for mAP0.5...0.95)\n    ap, p, r = np.zeros(s), np.zeros(s), np.zeros(s)\n    for ci, c in enumerate(unique_classes):\n        i = pred_cls == c\n        n_l = (target_cls == c).sum()  # number of labels\n        n_p = i.sum()  # number of predictions\n\n        if n_p == 0 or n_l == 0:\n            continue\n        else:\n            # Accumulate FPs and TPs\n            fpc = (1 - tp[i]).cumsum(0)\n            tpc = tp[i].cumsum(0)\n\n            # Recall\n            recall = tpc / (n_l + 1e-16)  # recall curve\n            r[ci] = np.interp(-pr_score, -conf[i], recall[:, 0])  # r at pr_score, negative x, xp because xp decreases\n\n            # Precision\n            precision = tpc / (tpc + fpc)  # precision curve\n            p[ci] = np.interp(-pr_score, -conf[i], precision[:, 0])  # p at pr_score\n\n            # AP from recall-precision curve\n            for j in range(tp.shape[1]):\n                ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])\n                if plot and (j == 0):\n                    py.append(np.interp(px, mrec, mpre))  # precision at mAP@0.5\n\n    # Compute F1 score (harmonic mean of precision and recall)\n    f1 = 2 * p * r / (p + r + 1e-16)\n\n    if plot:\n        plot_pr_curve(px, py, ap, save_dir, names)\n\n    return p, r, ap, f1, unique_classes.astype('int32')\n\n\ndef compute_ap(recall, precision):\n    \"\"\" Compute the average precision, given the recall and precision curves\n    # Arguments\n        recall:    The recall curve (list)\n        precision: The precision curve (list)\n    # Returns\n        Average precision, precision curve, recall curve\n    \"\"\"\n\n    # Append sentinel values to beginning and end\n    mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01]))\n    mpre = np.concatenate(([1.], precision, [0.]))\n\n    # Compute the precision envelope\n    mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))\n\n    # Integrate area under curve\n    method = 'interp'  # methods: 'continuous', 'interp'\n    if method == 'interp':\n        x = np.linspace(0, 1, 101)  # 101-point interp (COCO)\n        ap = np.trapz(np.interp(x, mrec, mpre), x)  # integrate\n    else:  # 'continuous'\n        i = np.where(mrec[1:] != mrec[:-1])[0]  # points where x axis (recall) changes\n        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])  # area under curve\n\n    return ap, mpre, mrec\n\n\nclass ConfusionMatrix:\n    # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix\n    def __init__(self, nc, conf=0.25, iou_thres=0.45):\n        self.matrix = np.zeros((nc + 1, nc + 1))\n        self.nc = nc  # number of classes\n        self.conf = conf\n        self.iou_thres = iou_thres\n\n    def process_batch(self, detections, labels):\n        \"\"\"\n        Return intersection-over-union (Jaccard index) of boxes.\n        Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n        Arguments:\n            detections (Array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (Array[M, 5]), class, x1, y1, x2, y2\n        Returns:\n            None, updates confusion matrix accordingly\n        \"\"\"\n        detections = detections[detections[:, 4] > self.conf]\n        gt_classes = labels[:, 0].int()\n        detection_classes = detections[:, 5].int()\n        iou = general.box_iou(labels[:, 1:], detections[:, :4])\n\n        x = torch.where(iou > self.iou_thres)\n        if x[0].shape[0]:\n            matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()\n            if x[0].shape[0] > 1:\n                matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n        else:\n            matches = np.zeros((0, 3))\n\n        n = matches.shape[0] > 0\n        m0, m1, _ = matches.transpose().astype(np.int16)\n        for i, gc in enumerate(gt_classes):\n            j = m0 == i\n            if n and sum(j) == 1:\n                self.matrix[gc, detection_classes[m1[j]]] += 1  # correct\n            else:\n                self.matrix[gc, self.nc] += 1  # background FP\n\n        if n:\n            for i, dc in enumerate(detection_classes):\n                if not any(m1 == i):\n                    self.matrix[self.nc, dc] += 1  # background FN\n\n    def matrix(self):\n        return self.matrix\n\n    def plot(self, save_dir='', names=()):\n        try:\n            import seaborn as sn\n\n            array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6)  # normalize\n            array[array < 0.005] = np.nan  # don't annotate (would appear as 0.00)\n\n            fig = plt.figure(figsize=(12, 9), tight_layout=True)\n            sn.set(font_scale=1.0 if self.nc < 50 else 0.8)  # for label size\n            labels = (0 < len(names) < 99) and len(names) == self.nc  # apply names to ticklabels\n            sn.heatmap(array, annot=self.nc < 30, annot_kws={\"size\": 8}, cmap='Blues', fmt='.2f', square=True,\n                       xticklabels=names + ['background FN'] if labels else \"auto\",\n                       yticklabels=names + ['background FP'] if labels else \"auto\").set_facecolor((1, 1, 1))\n            fig.axes[0].set_xlabel('True')\n            fig.axes[0].set_ylabel('Predicted')\n            fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)\n        except Exception as e:\n            pass\n\n    def print(self):\n        for i in range(self.nc + 1):\n            print(' '.join(map(str, self.matrix[i])))\n\n\n# Plots ----------------------------------------------------------------------------------------------------------------\n\ndef plot_pr_curve(px, py, ap, save_dir='.', names=()):\n    fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)\n    py = np.stack(py, axis=1)\n\n    if 0 < len(names) < 21:  # show mAP in legend if < 10 classes\n        for i, y in enumerate(py.T):\n            ax.plot(px, y, linewidth=1, label=f'{names[i]} %.3f' % ap[i, 0])  # plot(recall, precision)\n    else:\n        ax.plot(px, py, linewidth=1, color='grey')  # plot(recall, precision)\n\n    ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())\n    ax.set_xlabel('Recall')\n    ax.set_ylabel('Precision')\n    ax.set_xlim(0, 1)\n    ax.set_ylim(0, 1)\n    plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n    fig.savefig(Path(save_dir) / 'precision_recall_curve.png', dpi=250)\n"
  },
  {
    "path": "utils/plots.py",
    "content": "# Plotting utils\n\nimport glob\nimport math\nimport os\nimport random\nfrom copy import copy\nfrom pathlib import Path\n\nimport cv2\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport torch\nimport yaml\nfrom PIL import Image, ImageDraw\nfrom scipy.signal import butter, filtfilt\n\nfrom utils.general import xywh2xyxy, xyxy2xywh\nfrom utils.metrics import fitness\n\n# Settings\nmatplotlib.rc('font', **{'size': 11})\nmatplotlib.use('Agg')  # for writing to files only\n\n\ndef color_list():\n    # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb\n    def hex2rgb(h):\n        return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))\n\n    return [hex2rgb(h) for h in plt.rcParams['axes.prop_cycle'].by_key()['color']]\n\n\ndef hist2d(x, y, n=100):\n    # 2d histogram used in labels.png and evolve.png\n    xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)\n    hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))\n    xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)\n    yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)\n    return np.log(hist[xidx, yidx])\n\n\ndef butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):\n    # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy\n    def butter_lowpass(cutoff, fs, order):\n        nyq = 0.5 * fs\n        normal_cutoff = cutoff / nyq\n        return butter(order, normal_cutoff, btype='low', analog=False)\n\n    b, a = butter_lowpass(cutoff, fs, order=order)\n    return filtfilt(b, a, data)  # forward-backward filter\n\n\ndef plot_one_box(x, img, color=None, label=None, line_thickness=None):\n    # Plots one bounding box on image img\n    tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1  # line/font thickness\n    color = color or [random.randint(0, 255) for _ in range(3)]\n    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))\n    cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)\n    if label:\n        tf = max(tl - 1, 1)  # font thickness\n        t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]\n        c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3\n        cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)  # filled\n        cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)\n\n\ndef plot_wh_methods():  # from utils.plots import *; plot_wh_methods()\n    # Compares the two methods for width-height anchor multiplication\n    # https://github.com/ultralytics/yolov3/issues/168\n    x = np.arange(-4.0, 4.0, .1)\n    ya = np.exp(x)\n    yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2\n\n    fig = plt.figure(figsize=(6, 3), tight_layout=True)\n    plt.plot(x, ya, '.-', label='YOLOv3')\n    plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2')\n    plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6')\n    plt.xlim(left=-4, right=4)\n    plt.ylim(bottom=0, top=6)\n    plt.xlabel('input')\n    plt.ylabel('output')\n    plt.grid()\n    plt.legend()\n    fig.savefig('comparison.png', dpi=200)\n\n\ndef output_to_target(output):\n    # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]\n    targets = []\n    for i, o in enumerate(output):\n        for *box, conf, cls in o.cpu().numpy():\n            targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])\n    return np.array(targets)\n\n\ndef plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):\n    # Plot image grid with labels\n\n    if isinstance(images, torch.Tensor):\n        images = images.cpu().float().numpy()\n    if isinstance(targets, torch.Tensor):\n        targets = targets.cpu().numpy()\n\n    # un-normalise\n    if np.max(images[0]) <= 1:\n        images *= 255\n\n    tl = 3  # line thickness\n    tf = max(tl - 1, 1)  # font thickness\n    bs, _, h, w = images.shape  # batch size, _, height, width\n    bs = min(bs, max_subplots)  # limit plot images\n    ns = np.ceil(bs ** 0.5)  # number of subplots (square)\n\n    # Check if we should resize\n    scale_factor = max_size / max(h, w)\n    if scale_factor < 1:\n        h = math.ceil(scale_factor * h)\n        w = math.ceil(scale_factor * w)\n\n    # colors = color_list()  # list of colors\n    mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8)  # init\n    for i, img in enumerate(images):\n        if i == max_subplots:  # if last batch has fewer images than we expect\n            break\n\n        block_x = int(w * (i // ns))\n        block_y = int(h * (i % ns))\n\n        img = img.transpose(1, 2, 0)\n        if scale_factor < 1:\n            img = cv2.resize(img, (w, h))\n\n        mosaic[block_y:block_y + h, block_x:block_x + w, :] = img\n        if len(targets) > 0:\n            image_targets = targets[targets[:, 0] == i]\n            boxes = xywh2xyxy(image_targets[:, 2:6]).T\n            classes = image_targets[:, 1].astype('int')\n            labels = image_targets.shape[1] == 6  # labels if no conf column\n            conf = None if labels else image_targets[:, 6]  # check for confidence presence (label vs pred)\n\n            if boxes.shape[1]:\n                if boxes.max() <= 1.01:  # if normalized with tolerance 0.01\n                    boxes[[0, 2]] *= w  # scale to pixels\n                    boxes[[1, 3]] *= h\n                elif scale_factor < 1:  # absolute coords need scale if image scales\n                    boxes *= scale_factor\n            boxes[[0, 2]] += block_x\n            boxes[[1, 3]] += block_y\n            for j, box in enumerate(boxes.T):\n                cls = int(classes[j])\n                # color = colors[cls % len(colors)]\n                cls = names[cls] if names else cls\n                if labels or conf[j] > 0.25:  # 0.25 conf thresh\n                    label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])\n                    plot_one_box(box, mosaic, label=label, color=None, line_thickness=tl)\n\n        # Draw image filename labels\n        if paths:\n            label = Path(paths[i]).name[:40]  # trim to 40 char\n            t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]\n            cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,\n                        lineType=cv2.LINE_AA)\n\n        # Image border\n        cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)\n\n    if fname:\n        r = min(1280. / max(h, w) / ns, 1.0)  # ratio to limit image size\n        mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)\n        # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB))  # cv2 save\n        Image.fromarray(mosaic).save(fname)  # PIL save\n    return mosaic\n\n\ndef plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):\n    # Plot LR simulating training for full epochs\n    optimizer, scheduler = copy(optimizer), copy(scheduler)  # do not modify originals\n    y = []\n    for _ in range(epochs):\n        scheduler.step()\n        y.append(optimizer.param_groups[0]['lr'])\n    plt.plot(y, '.-', label='LR')\n    plt.xlabel('epoch')\n    plt.ylabel('LR')\n    plt.grid()\n    plt.xlim(0, epochs)\n    plt.ylim(0)\n    plt.savefig(Path(save_dir) / 'LR.png', dpi=200)\n    plt.close()\n\n\ndef plot_test_txt():  # from utils.plots import *; plot_test()\n    # Plot test.txt histograms\n    x = np.loadtxt('test.txt', dtype=np.float32)\n    box = xyxy2xywh(x[:, :4])\n    cx, cy = box[:, 0], box[:, 1]\n\n    fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)\n    ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)\n    ax.set_aspect('equal')\n    plt.savefig('hist2d.png', dpi=300)\n\n    fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)\n    ax[0].hist(cx, bins=600)\n    ax[1].hist(cy, bins=600)\n    plt.savefig('hist1d.png', dpi=200)\n\n\ndef plot_targets_txt():  # from utils.plots import *; plot_targets_txt()\n    # Plot targets.txt histograms\n    x = np.loadtxt('targets.txt', dtype=np.float32).T\n    s = ['x targets', 'y targets', 'width targets', 'height targets']\n    fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)\n    ax = ax.ravel()\n    for i in range(4):\n        ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))\n        ax[i].legend()\n        ax[i].set_title(s[i])\n    plt.savefig('targets.jpg', dpi=200)\n\n\ndef plot_study_txt(path='study/', x=None):  # from utils.plots import *; plot_study_txt()\n    # Plot study.txt generated by test.py\n    fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)\n    ax = ax.ravel()\n\n    fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)\n    for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s', 'yolov5m', 'yolov5l', 'yolov5x']]:\n        y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T\n        x = np.arange(y.shape[1]) if x is None else np.array(x)\n        s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']\n        for i in range(7):\n            ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)\n            ax[i].set_title(s[i])\n\n        j = y[3].argmax() + 1\n        ax2.plot(y[6, :j], y[3, :j] * 1E2, '.-', linewidth=2, markersize=8,\n                 label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))\n\n    ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],\n             'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')\n\n    ax2.grid()\n    ax2.set_yticks(np.arange(30, 60, 5))\n    ax2.set_xlim(0, 30)\n    ax2.set_ylim(29, 51)\n    ax2.set_xlabel('GPU Speed (ms/img)')\n    ax2.set_ylabel('COCO AP val')\n    ax2.legend(loc='lower right')\n    plt.savefig('test_study.png', dpi=300)\n\n\ndef plot_labels(labels, save_dir=Path(''), loggers=None):\n    # plot dataset labels\n    print('Plotting labels... ')\n    c, b = labels[:, 0], labels[:, 1:5].transpose()  # classes, boxes\n    nc = int(c.max() + 1)  # number of classes\n    colors = color_list()\n    x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])\n\n    # seaborn correlogram\n    sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))\n    plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)\n    plt.close()\n\n    # matplotlib labels\n    matplotlib.use('svg')  # faster\n    ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()\n    ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)\n    ax[0].set_xlabel('classes')\n    sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)\n    sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)\n\n    # rectangles\n    labels[:, 1:3] = 0.5  # center\n    labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000\n    img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)\n    # for cls, *box in labels[:1000]:\n    #     ImageDraw.Draw(img).rectangle(box, width=1, outline=colors[int(cls) % 10])  # plot\n    ax[1].imshow(img)\n    ax[1].axis('off')\n\n    for a in [0, 1, 2, 3]:\n        for s in ['top', 'right', 'left', 'bottom']:\n            ax[a].spines[s].set_visible(False)\n\n    plt.savefig(save_dir / 'labels.jpg', dpi=200)\n    matplotlib.use('Agg')\n    plt.close()\n\n    # loggers\n    for k, v in loggers.items() or {}:\n        if k == 'wandb' and v:\n            v.log({\"Labels\": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]})\n\n\ndef plot_evolution(yaml_file='data/hyp.finetune.yaml'):  # from utils.plots import *; plot_evolution()\n    # Plot hyperparameter evolution results in evolve.txt\n    with open(yaml_file) as f:\n        hyp = yaml.load(f, Loader=yaml.SafeLoader)\n    x = np.loadtxt('evolve.txt', ndmin=2)\n    f = fitness(x)\n    # weights = (f - f.min()) ** 2  # for weighted results\n    plt.figure(figsize=(10, 12), tight_layout=True)\n    matplotlib.rc('font', **{'size': 8})\n    for i, (k, v) in enumerate(hyp.items()):\n        y = x[:, i + 7]\n        # mu = (y * weights).sum() / weights.sum()  # best weighted result\n        mu = y[f.argmax()]  # best single result\n        plt.subplot(6, 5, i + 1)\n        plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')\n        plt.plot(mu, f.max(), 'k+', markersize=15)\n        plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9})  # limit to 40 characters\n        if i % 5 != 0:\n            plt.yticks([])\n        print('%15s: %.3g' % (k, mu))\n    plt.savefig('evolve.png', dpi=200)\n    print('\\nPlot saved as evolve.png')\n\n\ndef profile_idetection(start=0, stop=0, labels=(), save_dir=''):\n    # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()\n    ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()\n    s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']\n    files = list(Path(save_dir).glob('frames*.txt'))\n    for fi, f in enumerate(files):\n        try:\n            results = np.loadtxt(f, ndmin=2).T[:, 90:-30]  # clip first and last rows\n            n = results.shape[1]  # number of rows\n            x = np.arange(start, min(stop, n) if stop else n)\n            results = results[:, x]\n            t = (results[0] - results[0].min())  # set t0=0s\n            results[0] = x\n            for i, a in enumerate(ax):\n                if i < len(results):\n                    label = labels[fi] if len(labels) else f.stem.replace('frames_', '')\n                    a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)\n                    a.set_title(s[i])\n                    a.set_xlabel('time (s)')\n                    # if fi == len(files) - 1:\n                    #     a.set_ylim(bottom=0)\n                    for side in ['top', 'right']:\n                        a.spines[side].set_visible(False)\n                else:\n                    a.remove()\n        except Exception as e:\n            print('Warning: Plotting error for %s; %s' % (f, e))\n\n    ax[1].legend()\n    plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)\n\n\ndef plot_results_overlay(start=0, stop=0):  # from utils.plots import *; plot_results_overlay()\n    # Plot training 'results*.txt', overlaying train and val losses\n    s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95']  # legends\n    t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1']  # titles\n    for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):\n        results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T\n        n = results.shape[1]  # number of rows\n        x = range(start, min(stop, n) if stop else n)\n        fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)\n        ax = ax.ravel()\n        for i in range(5):\n            for j in [i, i + 5]:\n                y = results[j, x]\n                ax[i].plot(x, y, marker='.', label=s[j])\n                # y_smooth = butter_lowpass_filtfilt(y)\n                # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])\n\n            ax[i].set_title(t[i])\n            ax[i].legend()\n            ax[i].set_ylabel(f) if i == 0 else None  # add filename\n        fig.savefig(f.replace('.txt', '.png'), dpi=200)\n\n\ndef plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):\n    # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')\n    fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)\n    ax = ax.ravel()\n    s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',\n         'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']\n    if bucket:\n        # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]\n        files = ['results%g.txt' % x for x in id]\n        c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)\n        os.system(c)\n    else:\n        files = list(Path(save_dir).glob('results*.txt'))\n    assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)\n    for fi, f in enumerate(files):\n        try:\n            results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T\n            n = results.shape[1]  # number of rows\n            x = range(start, min(stop, n) if stop else n)\n            for i in range(10):\n                y = results[i, x]\n                if i in [0, 1, 2, 5, 6, 7]:\n                    y[y == 0] = np.nan  # don't show zero loss values\n                    # y /= y[0]  # normalize\n                label = labels[fi] if len(labels) else f.stem\n                ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)\n                ax[i].set_title(s[i])\n                # if i in [5, 6, 7]:  # share train and val loss y axes\n                #     ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])\n        except Exception as e:\n            print('Warning: Plotting error for %s; %s' % (f, e))\n\n    ax[1].legend()\n    fig.savefig(Path(save_dir) / 'results.png', dpi=200)\n"
  },
  {
    "path": "utils/preprocess_utils.py",
    "content": "import numpy as np\nimport cv2\ndef align_faces(img, bbox=None, landmark=None, **kwargs):\n    M = None\n    # Do alignment using landmark points\n    if landmark is not None:\n        src = np.array([\n          [30.2946, 51.6963],\n          [65.5318, 51.5014],\n          [48.0252, 71.7366],\n          [33.5493, 92.3655],\n          [62.7299, 92.2041] ], dtype=np.float32 )\n        src[:,0] += 8.0\n        dst = landmark.astype(np.float32)\n        M = cv2.estimateAffine2D(dst,src)[0]\n        warped = cv2.warpAffine(img,M,(112,112), borderValue = 0.0)\n        return warped\n    \n    # If no landmark points available, do alignment using bounding box. If no bounding box available use center crop\n    if M is None:\n        x1,y1,x2,y2,_ = bbox\n        ret = img[y1:y2,x1:x2]\n        ret = cv2.resize(ret, (112,112))\n        return ret\ndef face_distance(vec1,vec2):\n    return np.dot(vec1, vec2.T)\n"
  },
  {
    "path": "utils/torch_utils.py",
    "content": "# PyTorch utils\n\nimport logging\nimport math\nimport os\nimport subprocess\nimport time\nfrom contextlib import contextmanager\nfrom copy import deepcopy\nfrom pathlib import Path\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\n\ntry:\n    import thop  # for FLOPS computation\nexcept ImportError:\n    thop = None\nlogger = logging.getLogger(__name__)\n\n\n@contextmanager\ndef torch_distributed_zero_first(local_rank: int):\n    \"\"\"\n    Decorator to make all processes in distributed training wait for each local_master to do something.\n    \"\"\"\n    if local_rank not in [-1, 0]:\n        torch.distributed.barrier()\n    yield\n    if local_rank == 0:\n        torch.distributed.barrier()\n\n\ndef init_torch_seeds(seed=0):\n    # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html\n    torch.manual_seed(seed)\n    if seed == 0:  # slower, more reproducible\n        cudnn.benchmark, cudnn.deterministic = False, True\n    else:  # faster, less reproducible\n        cudnn.benchmark, cudnn.deterministic = True, False\n\n\ndef git_describe():\n    # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe\n    if Path('.git').exists():\n        return subprocess.check_output('git describe --tags --long --always', shell=True).decode('utf-8')[:-1]\n    else:\n        return ''\n\n\ndef select_device(device='', batch_size=None):\n    # device = 'cpu' or '0' or '0,1,2,3'\n    s = f'YOLOv5 {git_describe()} torch {torch.__version__} '  # string\n    cpu = device.lower() == 'cpu'\n    if cpu:\n        os.environ['CUDA_VISIBLE_DEVICES'] = '-1'  # force torch.cuda.is_available() = False\n    elif device:  # non-cpu device requested\n        os.environ['CUDA_VISIBLE_DEVICES'] = device  # set environment variable\n        assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested'  # check availability\n\n    cuda = not cpu and torch.cuda.is_available()\n    if cuda:\n        n = torch.cuda.device_count()\n        if n > 1 and batch_size:  # check that batch_size is compatible with device_count\n            assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'\n        space = ' ' * len(s)\n        for i, d in enumerate(device.split(',') if device else range(n)):\n            p = torch.cuda.get_device_properties(i)\n            s += f\"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\\n\"  # bytes to MB\n    else:\n        s += 'CPU\\n'\n\n    logger.info(s)  # skip a line\n    return torch.device('cuda:0' if cuda else 'cpu')\n\n\ndef time_synchronized():\n    # pytorch-accurate time\n    if torch.cuda.is_available():\n        torch.cuda.synchronize()\n    return time.time()\n\n\ndef profile(x, ops, n=100, device=None):\n    # profile a pytorch module or list of modules. Example usage:\n    #     x = torch.randn(16, 3, 640, 640)  # input\n    #     m1 = lambda x: x * torch.sigmoid(x)\n    #     m2 = nn.SiLU()\n    #     profile(x, [m1, m2], n=100)  # profile speed over 100 iterations\n\n    device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n    x = x.to(device)\n    x.requires_grad = True\n    print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '')\n    print(f\"\\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}\")\n    for m in ops if isinstance(ops, list) else [ops]:\n        m = m.to(device) if hasattr(m, 'to') else m  # device\n        m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m  # type\n        dtf, dtb, t = 0., 0., [0., 0., 0.]  # dt forward, backward\n        try:\n            flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2  # GFLOPS\n        except:\n            flops = 0\n\n        for _ in range(n):\n            t[0] = time_synchronized()\n            y = m(x)\n            t[1] = time_synchronized()\n            try:\n                _ = y.sum().backward()\n                t[2] = time_synchronized()\n            except:  # no backward method\n                t[2] = float('nan')\n            dtf += (t[1] - t[0]) * 1000 / n  # ms per op forward\n            dtb += (t[2] - t[1]) * 1000 / n  # ms per op backward\n\n        s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'\n        s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'\n        p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0  # parameters\n        print(f'{p:12.4g}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}')\n\n\ndef is_parallel(model):\n    return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)\n\n\ndef intersect_dicts(da, db, exclude=()):\n    # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values\n    return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}\n\n\ndef initialize_weights(model):\n    for m in model.modules():\n        t = type(m)\n        if t is nn.Conv2d:\n            pass  # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n        elif t is nn.BatchNorm2d:\n            m.eps = 1e-3\n            m.momentum = 0.03\n        elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:\n            m.inplace = True\n\n\ndef find_modules(model, mclass=nn.Conv2d):\n    # Finds layer indices matching module class 'mclass'\n    return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]\n\n\ndef sparsity(model):\n    # Return global model sparsity\n    a, b = 0., 0.\n    for p in model.parameters():\n        a += p.numel()\n        b += (p == 0).sum()\n    return b / a\n\n\ndef prune(model, amount=0.3):\n    # Prune model to requested global sparsity\n    import torch.nn.utils.prune as prune\n    print('Pruning model... ', end='')\n    for name, m in model.named_modules():\n        if isinstance(m, nn.Conv2d):\n            prune.l1_unstructured(m, name='weight', amount=amount)  # prune\n            prune.remove(m, 'weight')  # make permanent\n    print(' %.3g global sparsity' % sparsity(model))\n\n\ndef fuse_conv_and_bn(conv, bn):\n    # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/\n    fusedconv = nn.Conv2d(conv.in_channels,\n                          conv.out_channels,\n                          kernel_size=conv.kernel_size,\n                          stride=conv.stride,\n                          padding=conv.padding,\n                          groups=conv.groups,\n                          bias=True).requires_grad_(False).to(conv.weight.device)\n\n    # prepare filters\n    w_conv = conv.weight.clone().view(conv.out_channels, -1)\n    w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))\n    fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size()))\n\n    # prepare spatial bias\n    b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias\n    b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))\n    fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)\n\n    return fusedconv\n\n\ndef model_info(model, verbose=False, img_size=640):\n    # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]\n    n_p = sum(x.numel() for x in model.parameters())  # number parameters\n    n_g = sum(x.numel() for x in model.parameters() if x.requires_grad)  # number gradients\n    if verbose:\n        print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))\n        for i, (name, p) in enumerate(model.named_parameters()):\n            name = name.replace('module_list.', '')\n            print('%5g %40s %9s %12g %20s %10.3g %10.3g' %\n                  (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))\n\n    try:  # FLOPS\n        from thop import profile\n        stride = int(model.stride.max()) if hasattr(model, 'stride') else 32\n        img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device)  # input\n        flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2  # stride GFLOPS\n        img_size = img_size if isinstance(img_size, list) else [img_size, img_size]  # expand if int/float\n        fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride)  # 640x640 GFLOPS\n    except (ImportError, Exception):\n        fs = ''\n\n    logger.info(f\"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}\")\n\n\ndef load_classifier(name='resnet101', n=2):\n    # Loads a pretrained model reshaped to n-class output\n    model = torchvision.models.__dict__[name](pretrained=True)\n\n    # ResNet model properties\n    # input_size = [3, 224, 224]\n    # input_space = 'RGB'\n    # input_range = [0, 1]\n    # mean = [0.485, 0.456, 0.406]\n    # std = [0.229, 0.224, 0.225]\n\n    # Reshape output to n classes\n    filters = model.fc.weight.shape[1]\n    model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)\n    model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)\n    model.fc.out_features = n\n    return model\n\n\ndef scale_img(img, ratio=1.0, same_shape=False, gs=32):  # img(16,3,256,416)\n    # scales img(bs,3,y,x) by ratio constrained to gs-multiple\n    if ratio == 1.0:\n        return img\n    else:\n        h, w = img.shape[2:]\n        s = (int(h * ratio), int(w * ratio))  # new size\n        img = F.interpolate(img, size=s, mode='bilinear', align_corners=False)  # resize\n        if not same_shape:  # pad/crop img\n            h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]\n        return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447)  # value = imagenet mean\n\n\ndef copy_attr(a, b, include=(), exclude=()):\n    # Copy attributes from b to a, options to only include [...] and to exclude [...]\n    for k, v in b.__dict__.items():\n        if (len(include) and k not in include) or k.startswith('_') or k in exclude:\n            continue\n        else:\n            setattr(a, k, v)\n\n\nclass ModelEMA:\n    \"\"\" Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models\n    Keep a moving average of everything in the model state_dict (parameters and buffers).\n    This is intended to allow functionality like\n    https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage\n    A smoothed version of the weights is necessary for some training schemes to perform well.\n    This class is sensitive where it is initialized in the sequence of model init,\n    GPU assignment and distributed training wrappers.\n    \"\"\"\n\n    def __init__(self, model, decay=0.9999, updates=0):\n        # Create EMA\n        self.ema = deepcopy(model.module if is_parallel(model) else model).eval()  # FP32 EMA\n        # if next(model.parameters()).device.type != 'cpu':\n        #     self.ema.half()  # FP16 EMA\n        self.updates = updates  # number of EMA updates\n        self.decay = lambda x: decay * (1 - math.exp(-x / 2000))  # decay exponential ramp (to help early epochs)\n        for p in self.ema.parameters():\n            p.requires_grad_(False)\n\n    def update(self, model):\n        # Update EMA parameters\n        with torch.no_grad():\n            self.updates += 1\n            d = self.decay(self.updates)\n\n            msd = model.module.state_dict() if is_parallel(model) else model.state_dict()  # model state_dict\n            for k, v in self.ema.state_dict().items():\n                if v.dtype.is_floating_point:\n                    v *= d\n                    v += (1. - d) * msd[k].detach()\n\n    def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):\n        # Update EMA attributes\n        copy_attr(self.ema, model, include, exclude)\n"
  },
  {
    "path": "utils/wandb_logging/__init__.py",
    "content": ""
  },
  {
    "path": "utils/wandb_logging/log_dataset.py",
    "content": "import argparse\n\nimport yaml\n\nfrom wandb_utils import WandbLogger\n\nWANDB_ARTIFACT_PREFIX = 'wandb-artifact://'\n\n\ndef create_dataset_artifact(opt):\n    with open(opt.data) as f:\n        data = yaml.load(f, Loader=yaml.SafeLoader)  # data dict\n    logger = WandbLogger(opt, '', None, data, job_type='Dataset Creation')\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')\n    parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')\n    parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project')\n    opt = parser.parse_args()\n    opt.resume = False  # Explicitly disallow resume check for dataset upload job\n\n    create_dataset_artifact(opt)\n"
  },
  {
    "path": "utils/wandb_logging/wandb_utils.py",
    "content": "import json\nimport sys\nfrom pathlib import Path\n\nimport torch\nimport yaml\nfrom tqdm import tqdm\n\nsys.path.append(str(Path(__file__).parent.parent.parent))  # add utils/ to path\nfrom utils.datasets import LoadImagesAndLabels\nfrom utils.datasets import img2label_paths\nfrom utils.general import colorstr, xywh2xyxy, check_dataset\n\ntry:\n    import wandb\n    from wandb import init, finish\nexcept ImportError:\n    wandb = None\n\nWANDB_ARTIFACT_PREFIX = 'wandb-artifact://'\n\n\ndef remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX):\n    return from_string[len(prefix):]\n\n\ndef check_wandb_config_file(data_config_file):\n    wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1))  # updated data.yaml path\n    if Path(wandb_config).is_file():\n        return wandb_config\n    return data_config_file\n\n\ndef get_run_info(run_path):\n    run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX))\n    run_id = run_path.stem\n    project = run_path.parent.stem\n    model_artifact_name = 'run_' + run_id + '_model'\n    return run_id, project, model_artifact_name\n\n\ndef check_wandb_resume(opt):\n    process_wandb_config_ddp_mode(opt) if opt.global_rank not in [-1, 0] else None\n    if isinstance(opt.resume, str):\n        if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):\n            if opt.global_rank not in [-1, 0]:  # For resuming DDP runs\n                run_id, project, model_artifact_name = get_run_info(opt.resume)\n                api = wandb.Api()\n                artifact = api.artifact(project + '/' + model_artifact_name + ':latest')\n                modeldir = artifact.download()\n                opt.weights = str(Path(modeldir) / \"last.pt\")\n            return True\n    return None\n\n\ndef process_wandb_config_ddp_mode(opt):\n    with open(opt.data) as f:\n        data_dict = yaml.load(f, Loader=yaml.SafeLoader)  # data dict\n    train_dir, val_dir = None, None\n    if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX):\n        api = wandb.Api()\n        train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias)\n        train_dir = train_artifact.download()\n        train_path = Path(train_dir) / 'data/images/'\n        data_dict['train'] = str(train_path)\n\n    if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX):\n        api = wandb.Api()\n        val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias)\n        val_dir = val_artifact.download()\n        val_path = Path(val_dir) / 'data/images/'\n        data_dict['val'] = str(val_path)\n    if train_dir or val_dir:\n        ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml')\n        with open(ddp_data_path, 'w') as f:\n            yaml.dump(data_dict, f)\n        opt.data = ddp_data_path\n\n\nclass WandbLogger():\n    def __init__(self, opt, name, run_id, data_dict, job_type='Training'):\n        # Pre-training routine --\n        self.job_type = job_type\n        self.wandb, self.wandb_run, self.data_dict = wandb, None if not wandb else wandb.run, data_dict\n        # It's more elegant to stick to 1 wandb.init call, but useful config data is overwritten in the WandbLogger's wandb.init call\n        if isinstance(opt.resume, str):  # checks resume from artifact\n            if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):\n                run_id, project, model_artifact_name = get_run_info(opt.resume)\n                model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name\n                assert wandb, 'install wandb to resume wandb runs'\n                # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config\n                self.wandb_run = wandb.init(id=run_id, project=project, resume='allow')\n                opt.resume = model_artifact_name\n        elif self.wandb:\n            self.wandb_run = wandb.init(config=opt,\n                                        resume=\"allow\",\n                                        project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,\n                                        name=name,\n                                        job_type=job_type,\n                                        id=run_id) if not wandb.run else wandb.run\n        if self.wandb_run:\n            if self.job_type == 'Training':\n                if not opt.resume:\n                    wandb_data_dict = self.check_and_upload_dataset(opt) if opt.upload_dataset else data_dict\n                    # Info useful for resuming from artifacts\n                    self.wandb_run.config.opt = vars(opt)\n                    self.wandb_run.config.data_dict = wandb_data_dict\n                self.data_dict = self.setup_training(opt, data_dict)\n            if self.job_type == 'Dataset Creation':\n                self.data_dict = self.check_and_upload_dataset(opt)\n        else:\n            prefix = colorstr('wandb: ')\n            print(f\"{prefix}Install Weights & Biases for YOLOv5 logging with 'pip install wandb' (recommended)\")\n\n    def check_and_upload_dataset(self, opt):\n        assert wandb, 'Install wandb to upload dataset'\n        check_dataset(self.data_dict)\n        config_path = self.log_dataset_artifact(opt.data,\n                                                opt.single_cls,\n                                                'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem)\n        print(\"Created dataset config file \", config_path)\n        with open(config_path) as f:\n            wandb_data_dict = yaml.load(f, Loader=yaml.SafeLoader)\n        return wandb_data_dict\n\n    def setup_training(self, opt, data_dict):\n        self.log_dict, self.current_epoch, self.log_imgs = {}, 0, 16  # Logging Constants\n        self.bbox_interval = opt.bbox_interval\n        if isinstance(opt.resume, str):\n            modeldir, _ = self.download_model_artifact(opt)\n            if modeldir:\n                self.weights = Path(modeldir) / \"last.pt\"\n                config = self.wandb_run.config\n                opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str(\n                    self.weights), config.save_period, config.total_batch_size, config.bbox_interval, config.epochs, \\\n                                                                                                       config.opt['hyp']\n            data_dict = dict(self.wandb_run.config.data_dict)  # eliminates the need for config file to resume\n        if 'val_artifact' not in self.__dict__:  # If --upload_dataset is set, use the existing artifact, don't download\n            self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'),\n                                                                                           opt.artifact_alias)\n            self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'),\n                                                                                       opt.artifact_alias)\n            self.result_artifact, self.result_table, self.val_table, self.weights = None, None, None, None\n            if self.train_artifact_path is not None:\n                train_path = Path(self.train_artifact_path) / 'data/images/'\n                data_dict['train'] = str(train_path)\n            if self.val_artifact_path is not None:\n                val_path = Path(self.val_artifact_path) / 'data/images/'\n                data_dict['val'] = str(val_path)\n                self.val_table = self.val_artifact.get(\"val\")\n                self.map_val_table_path()\n        if self.val_artifact is not None:\n            self.result_artifact = wandb.Artifact(\"run_\" + wandb.run.id + \"_progress\", \"evaluation\")\n            self.result_table = wandb.Table([\"epoch\", \"id\", \"prediction\", \"avg_confidence\"])\n        if opt.bbox_interval == -1:\n            self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1\n        return data_dict\n\n    def download_dataset_artifact(self, path, alias):\n        if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):\n            dataset_artifact = wandb.use_artifact(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + \":\" + alias)\n            assert dataset_artifact is not None, \"'Error: W&B dataset artifact doesn\\'t exist'\"\n            datadir = dataset_artifact.download()\n            return datadir, dataset_artifact\n        return None, None\n\n    def download_model_artifact(self, opt):\n        if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):\n            model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + \":latest\")\n            assert model_artifact is not None, 'Error: W&B model artifact doesn\\'t exist'\n            modeldir = model_artifact.download()\n            epochs_trained = model_artifact.metadata.get('epochs_trained')\n            total_epochs = model_artifact.metadata.get('total_epochs')\n            assert epochs_trained < total_epochs, 'training to %g epochs is finished, nothing to resume.' % (\n                total_epochs)\n            return modeldir, model_artifact\n        return None, None\n\n    def log_model(self, path, opt, epoch, fitness_score, best_model=False):\n        model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={\n            'original_url': str(path),\n            'epochs_trained': epoch + 1,\n            'save period': opt.save_period,\n            'project': opt.project,\n            'total_epochs': opt.epochs,\n            'fitness_score': fitness_score\n        })\n        model_artifact.add_file(str(path / 'last.pt'), name='last.pt')\n        wandb.log_artifact(model_artifact,\n                           aliases=['latest', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])\n        print(\"Saving model artifact on epoch \", epoch + 1)\n\n    def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):\n        with open(data_file) as f:\n            data = yaml.load(f, Loader=yaml.SafeLoader)  # data dict\n        nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names'])\n        names = {k: v for k, v in enumerate(names)}  # to index dictionary\n        self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(\n            data['train']), names, name='train') if data.get('train') else None\n        self.val_artifact = self.create_dataset_table(LoadImagesAndLabels(\n            data['val']), names, name='val') if data.get('val') else None\n        if data.get('train'):\n            data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train')\n        if data.get('val'):\n            data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val')\n        path = data_file if overwrite_config else '_wandb.'.join(data_file.rsplit('.', 1))  # updated data.yaml path\n        data.pop('download', None)\n        with open(path, 'w') as f:\n            yaml.dump(data, f)\n\n        if self.job_type == 'Training':  # builds correct artifact pipeline graph\n            self.wandb_run.use_artifact(self.val_artifact)\n            self.wandb_run.use_artifact(self.train_artifact)\n            self.val_artifact.wait()\n            self.val_table = self.val_artifact.get('val')\n            self.map_val_table_path()\n        else:\n            self.wandb_run.log_artifact(self.train_artifact)\n            self.wandb_run.log_artifact(self.val_artifact)\n        return path\n\n    def map_val_table_path(self):\n        self.val_table_map = {}\n        print(\"Mapping dataset\")\n        for i, data in enumerate(tqdm(self.val_table.data)):\n            self.val_table_map[data[3]] = data[0]\n\n    def create_dataset_table(self, dataset, class_to_id, name='dataset'):\n        # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging\n        artifact = wandb.Artifact(name=name, type=\"dataset\")\n        img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None\n        img_files = tqdm(dataset.img_files) if not img_files else img_files\n        for img_file in img_files:\n            if Path(img_file).is_dir():\n                artifact.add_dir(img_file, name='data/images')\n                labels_path = 'labels'.join(dataset.path.rsplit('images', 1))\n                artifact.add_dir(labels_path, name='data/labels')\n            else:\n                artifact.add_file(img_file, name='data/images/' + Path(img_file).name)\n                label_file = Path(img2label_paths([img_file])[0])\n                artifact.add_file(str(label_file),\n                                  name='data/labels/' + label_file.name) if label_file.exists() else None\n        table = wandb.Table(columns=[\"id\", \"train_image\", \"Classes\", \"name\"])\n        class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])\n        for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)):\n            height, width = shapes[0]\n            labels[:, 2:] = (xywh2xyxy(labels[:, 2:].view(-1, 4))) * torch.Tensor([width, height, width, height])\n            box_data, img_classes = [], {}\n            for cls, *xyxy in labels[:, 1:].tolist():\n                cls = int(cls)\n                box_data.append({\"position\": {\"minX\": xyxy[0], \"minY\": xyxy[1], \"maxX\": xyxy[2], \"maxY\": xyxy[3]},\n                                 \"class_id\": cls,\n                                 \"box_caption\": \"%s\" % (class_to_id[cls]),\n                                 \"scores\": {\"acc\": 1},\n                                 \"domain\": \"pixel\"})\n                img_classes[cls] = class_to_id[cls]\n            boxes = {\"ground_truth\": {\"box_data\": box_data, \"class_labels\": class_to_id}}  # inference-space\n            table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), json.dumps(img_classes),\n                           Path(paths).name)\n        artifact.add(table, name)\n        return artifact\n\n    def log_training_progress(self, predn, path, names):\n        if self.val_table and self.result_table:\n            class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])\n            box_data = []\n            total_conf = 0\n            for *xyxy, conf, cls in predn.tolist():\n                if conf >= 0.25:\n                    box_data.append(\n                        {\"position\": {\"minX\": xyxy[0], \"minY\": xyxy[1], \"maxX\": xyxy[2], \"maxY\": xyxy[3]},\n                         \"class_id\": int(cls),\n                         \"box_caption\": \"%s %.3f\" % (names[cls], conf),\n                         \"scores\": {\"class_score\": conf},\n                         \"domain\": \"pixel\"})\n                    total_conf = total_conf + conf\n            boxes = {\"predictions\": {\"box_data\": box_data, \"class_labels\": names}}  # inference-space\n            id = self.val_table_map[Path(path).name]\n            self.result_table.add_data(self.current_epoch,\n                                       id,\n                                       wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set),\n                                       total_conf / max(1, len(box_data))\n                                       )\n\n    def log(self, log_dict):\n        if self.wandb_run:\n            for key, value in log_dict.items():\n                self.log_dict[key] = value\n\n    def end_epoch(self, best_result=False):\n        if self.wandb_run:\n            wandb.log(self.log_dict)\n            self.log_dict = {}\n            if self.result_artifact:\n                train_results = wandb.JoinedTable(self.val_table, self.result_table, \"id\")\n                self.result_artifact.add(train_results, 'result')\n                wandb.log_artifact(self.result_artifact, aliases=['latest', 'epoch ' + str(self.current_epoch),\n                                                                  ('best' if best_result else '')])\n                self.result_table = wandb.Table([\"epoch\", \"id\", \"prediction\", \"avg_confidence\"])\n                self.result_artifact = wandb.Artifact(\"run_\" + wandb.run.id + \"_progress\", \"evaluation\")\n\n    def finish_run(self):\n        if self.wandb_run:\n            if self.log_dict:\n                wandb.log(self.log_dict)\n            wandb.run.finish()\n"
  },
  {
    "path": "weights/download_weights.sh",
    "content": "#!/bin/bash\n# Download latest models from https://github.com/ultralytics/yolov5/releases\n# Usage:\n#    $ bash weights/download_weights.sh\n\npython3 - <<EOF\nfrom utils.google_utils import attempt_download\n\nfor x in ['s', 'm', 'l', 'x']:\n    attempt_download(f'yolov5{x}.pt')\n\nEOF\n"
  }
]