[
  {
    "path": ".github/ISSUE_TEMPLATE/1_bug_report.md",
    "content": "---\nname: \"\\U0001F41B Bug report\"\nabout: Report a bug, crash or some misbehavior\ntitle: ''\nlabels: 'bug'\nassignees: ''\n---\n<!--- Provide a general summary of the issue in the title above -->\n\n## Context\n<!--- Please provide context, as this streamlines the debugging process. Mark the correct cases and follow the instructions. -->\n- [ ] I have installed this repo manually and the issue occurred on this commit:\n<!--- Get the current commit hash either from the first printout of the program or by executing the following command: 'git rev-parse --short HEAD' -->\n- [ ] I have installed this repo via `PIP` and the issue occurred on version: <!--- Get the current version number by executing the following command: 'pip show pytorchyolo' -->\n- [ ] The issue occurred when using the following .cfg model:\n    - [ ] `yolov3`\n    - [ ] `yolov3-tiny`\n    - [ ] `CUSTOM`\n\n## Necessary Checks\n<!--- Please ensure, you have completed the following checks. This helps to give insight into the issue and prevent already resolved issues. -->\n- [ ] The issue occurred on the newest version\n<!--- If installed manually, run: 'git pull && poetry install'  -->\n<!--- If installed via PIP, run: 'pip install --upgrade pytorchyolo' -->\n- [ ] I couldn't find a similar issue here on this project's github repo\n- [ ] If the issue is CUDA related (CUDA error), I have tested and provided the traceback also when CUDA is turned off <!--- For linux, rerun your steps with the prefix CUDA_VISIBLE_DEVICES=\"\" -->\n- [ ] I have provided all tracebacks or printouts in ```Text Form``` <!--- This makes it easier to search for errors. -->\n- [ ] In case, the issue occurred on a custom .cfg model, I have provided the model down below\n\n## Expected behavior\n<!--- Describe what you expected to happen -->\n\n## Current behavior\n<!--- Describe what actually happened instead of the expected behavior -->\n\n## Steps to Reproduce\n<!--- An unambiguous set of steps to reproduce this bug. -->\n<!--- Code-snippets, screenshots ot other details are welcome if needed. -->\n1.\n2.\n3.\n...\n\n## Possible Solution\n<!--- If you already have an idea, you can suggest a fix/reason for the bug. This is not obligatory. -->\n\n<!--- Please remove the following block, if this does not apply to you issue. -->\n### Custom `.cfg`\n<!--- Please paste your custom .cfg model below. -->\n<details><summary>Custom .cfg</summary>\n<p>\n<!--- YOUR CUSTOM .CFG HERE -->\n</p>\n</details>\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/2_need_help.md",
    "content": "---\nname: \"⁉️ Need help?\"\nabout: \"Get help with using or improving our software\"\ntitle: ''\nlabels: ''\nassignees: ''\n---\n\n## What I'm trying to do\n<!--- Please describe what you're trying to do so we know what your problem is about. -->\n\n## What I've tried\n<!--- If you tell us, what you already tried or what documentation you already read, we are able to help you better by not pointing to information you already know. -->\n\n## Additional context\n<!--- If there's more to say, feel free to do so :) -->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/3_feature_request.md",
    "content": "---\nname: \"\\U0001F680 Feature request\"\nabout: Suggest an idea for this project\nlabels: 'enhancement'\n---\n\n<!--\nThank you for suggesting an idea to make us better.\n\nPlease fill in as much of the template below as you're able.\n-->\n\n## Is your feature request related to a problem? Please describe.\n<!-- Please describe the problem you are trying to solve. -->\n\n## Describe the solution you'd like\n<!-- Please describe the desired behavior. -->\n\n## Describe alternatives you've considered\n<!-- Please describe alternative solutions or features you have considered. -->\n<!-- This is not strictly necessary but helps all of us get a different point-of-view -->\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where the package manifests are located.\n# Please see the documentation for all configuration options:\n# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates\n\nversion: 2\nupdates:\n  - package-ecosystem: \"pip\" # See documentation for possible values\n    directory: \"/\" # Location of package manifests\n    schedule:\n      interval: \"daily\"\n"
  },
  {
    "path": ".github/pull_request_template.md",
    "content": "## Proposed changes\n<!--- Describe your changes and why they are necessary. -->\n\n## Related issues\n<!--- Mention (link) related issues. -->\n<!--- If you suggest a new feature, please discuss it in an issue first. -->\n<!--- If fixing a bug, there should be an issue describing it with steps to reproduce -->\n\n## Necessary checks\n- [ ] Update poetry package version [semantically](https://semver.org/)\n- [ ] Write documentation\n- [ ] Create issues for future work\n- [ ] Test on your machine\n"
  },
  {
    "path": ".github/workflows/main.yml",
    "content": "name: CI\n\non: [pull_request, workflow_dispatch]\n\njobs:\n  main:\n    runs-on: ${{ matrix.os }}\n    strategy:\n        matrix:\n            os: [ubuntu-22.04, ubuntu-20.04, windows-latest]\n    steps:\n      - uses: actions/checkout@v2\n\n      - name: Set up Python\n        uses: actions/setup-python@v1\n        with:\n          python-version: 3.8\n\n      - name: Upgrade pip\n        run: python3 -m pip install --upgrade pip\n      \n      - name: Install Poetry\n        run: pip3 install poetry --user\n\n      - name: Install Dependencies\n        run: poetry install\n\n      # Prints the help pages of all scripts to see if the imports etc. work\n      - name: Test the help pages\n        run: |\n          poetry run yolo-train -h\n          poetry run yolo-test -h\n          poetry run yolo-detect -h\n\n      - name: Demo Training\n        run: poetry run yolo-train --data config/custom.data  --model config/yolov3.cfg --epochs 30\n\n      - name: Demo Evaluate\n        run: poetry run yolo-test --data config/custom.data  --model config/yolov3.cfg --weights checkpoints/yolov3_ckpt_29.pth\n\n      - name: Demo Detect\n        run: poetry run yolo-detect --batch_size 2 --weights checkpoints/yolov3_ckpt_29.pth\n\n  linter:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n\n      - name: Flake8\n        uses: TrueBrain/actions-flake8@master\n        with:\n          only_warn: 1\n          max_line_length: 150\n          path: pytorchyolo\n"
  },
  {
    "path": ".gitignore",
    "content": "\n.DS_Store\nbuild\n.git\n*.egg-info\ndist\noutput/\ndata/*\nbackup\nweights/*.weights\nweights/*.conv.*\n__pycache__\ncheckpoints/\n\n.vscode/\nlogs/\n\n.python-version\n"
  },
  {
    "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": "# PyTorch YOLO\nA minimal PyTorch implementation of YOLOv3, with support for training, inference and evaluation.\n\nYOLOv4 and YOLOv7 weights are also compatible with this implementation.\n\n[![CI](https://github.com/eriklindernoren/PyTorch-YOLOv3/actions/workflows/main.yml/badge.svg)](https://github.com/eriklindernoren/PyTorch-YOLOv3/actions/workflows/main.yml) [![PyPI pyversions](https://img.shields.io/pypi/pyversions/pytorchyolo.svg)](https://pypi.python.org/pypi/pytorchyolo/) [![PyPI license](https://img.shields.io/pypi/l/pytorchyolo.svg)](LICENSE)\n\n## Installation\n### Installing from source\n\nFor normal training and evaluation we recommend installing the package from source using a poetry virtual environment.\n\n```bash\ngit clone https://github.com/eriklindernoren/PyTorch-YOLOv3\ncd PyTorch-YOLOv3/\npip3 install poetry --user\npoetry install\n```\n\nYou need to join the virtual environment by running `poetry shell` in this directory before running any of the following commands without the `poetry run` prefix.\nAlso have a look at the other installing method, if you want to use the commands everywhere without opening a poetry-shell.\n\n#### Download pretrained weights\n\n```bash\n./weights/download_weights.sh\n```\n\n#### Download COCO\n\n```bash\n./data/get_coco_dataset.sh\n```\n\n### Install via pip\n\nThis installation method is recommended, if you want to use this package as a dependency in another python project.\nThis method only includes the code, is less isolated and may conflict with other packages.\nWeights and the COCO dataset need to be downloaded as stated above.\nSee __API__ for further information regarding the packages API.\nIt also enables the CLI tools `yolo-detect`, `yolo-train`, and `yolo-test` everywhere without any additional commands.\n\n```bash\npip3 install pytorchyolo --user\n```\n\n## Test\nEvaluates the model on COCO test dataset.\nTo download this dataset as well as weights, see above.\n\n```bash\npoetry run yolo-test --weights weights/yolov3.weights\n```\n\n| Model                   | mAP (min. 50 IoU) |\n| ----------------------- |:-----------------:|\n| YOLOv3 608 (paper)      | 57.9              |\n| YOLOv3 608 (this impl.) | 57.3              |\n| YOLOv3 416 (paper)      | 55.3              |\n| YOLOv3 416 (this impl.) | 55.5              |\n\n## Inference\nUses pretrained weights to make predictions on images. Below table displays the inference times when using as inputs images scaled to 256x256. The ResNet backbone measurements are taken from the YOLOv3 paper. The Darknet-53 measurement marked shows the inference time of this implementation on my 1080ti card.\n\n| Backbone                | GPU      | FPS      |\n| ----------------------- |:--------:|:--------:|\n| ResNet-101              | Titan X  | 53       |\n| ResNet-152              | Titan X  | 37       |\n| Darknet-53 (paper)      | Titan X  | 76       |\n| Darknet-53 (this impl.) | 1080ti   | 74       |\n\n```bash\npoetry run yolo-detect --images data/samples/\n```\n\n<p align=\"center\"><img src=\"https://github.com/eriklindernoren/PyTorch-YOLOv3/raw/master/assets/giraffe.png\" width=\"480\"\\></p>\n<p align=\"center\"><img src=\"https://github.com/eriklindernoren/PyTorch-YOLOv3/raw/master/assets/dog.png\" width=\"480\"\\></p>\n<p align=\"center\"><img src=\"https://github.com/eriklindernoren/PyTorch-YOLOv3/raw/master/assets/traffic.png\" width=\"480\"\\></p>\n<p align=\"center\"><img src=\"https://github.com/eriklindernoren/PyTorch-YOLOv3/raw/master/assets/messi.png\" width=\"480\"\\></p>\n\n## Train\nFor argument descriptions have a look at `poetry run yolo-train --help`\n\n#### Example (COCO)\nTo train on COCO using a Darknet-53 backend pretrained on ImageNet run:\n\n```bash\npoetry run yolo-train --data config/coco.data  --pretrained_weights weights/darknet53.conv.74\n```\n\n#### Tensorboard\nTrack training progress in Tensorboard:\n* Initialize training\n* Run the command below\n* Go to http://localhost:6006/\n\n```bash\npoetry run tensorboard --logdir='logs' --port=6006\n```\n\nStoring the logs on a slow drive possibly leads to a significant training speed decrease.\n\nYou can adjust the log directory using `--logdir <path>` when running `tensorboard` and `yolo-train`.\n\n## Train on Custom Dataset\n\n#### Custom model\nRun the commands below to create a custom model definition, replacing `<num-classes>` with the number of classes in your dataset.\n\n```bash\ncd config \n./create_custom_model.sh <num-classes>  # Will create custom model 'yolov3-custom.cfg'\n```\n\n#### Classes\nAdd class names to `data/custom/classes.names`. This file should have one row per class name.\n\n#### Image Folder\nMove the images of your dataset to `data/custom/images/`.\n\n#### Annotation Folder\nMove your annotations to `data/custom/labels/`. The dataloader expects that the annotation file corresponding to the image `data/custom/images/train.jpg` has the path `data/custom/labels/train.txt`. Each row in the annotation file should define one bounding box, using the syntax `label_idx x_center y_center width height`. The coordinates should be scaled `[0, 1]`, and the `label_idx` should be zero-indexed and correspond to the row number of the class name in `data/custom/classes.names`.\n\n#### Define Train and Validation Sets\nIn `data/custom/train.txt` and `data/custom/valid.txt`, add paths to images that will be used as train and validation data respectively.\n\n#### Train\nTo train on the custom dataset run:\n\n```bash\npoetry run yolo-train --model config/yolov3-custom.cfg --data config/custom.data\n```\n\nAdd `--pretrained_weights weights/darknet53.conv.74` to train using a backend pretrained on ImageNet.\n\n\n## API\n\nYou are able to import the modules of this repo in your own project if you install the pip package `pytorchyolo`.\n\nAn example prediction call from a simple OpenCV python script would look like this:\n\n```python\nimport cv2\nfrom pytorchyolo import detect, models\n\n# Load the YOLO model\nmodel = models.load_model(\n  \"<PATH_TO_YOUR_CONFIG_FOLDER>/yolov3.cfg\",\n  \"<PATH_TO_YOUR_WEIGHTS_FOLDER>/yolov3.weights\")\n\n# Load the image as a numpy array\nimg = cv2.imread(\"<PATH_TO_YOUR_IMAGE>\")\n\n# Convert OpenCV bgr to rgb\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n# Runs the YOLO model on the image\nboxes = detect.detect_image(model, img)\n\nprint(boxes)\n# Output will be a numpy array in the following format:\n# [[x1, y1, x2, y2, confidence, class]]\n```\n\nFor more advanced usage look at the method's doc strings.\n\n## Credit\n\n### YOLOv3: An Incremental Improvement\n_Joseph Redmon, Ali Farhadi_ <br>\n\n**Abstract** <br>\nWe present some updates to YOLO! We made a bunch\nof little design changes to make it better. We also trained\nthis new network that’s pretty swell. It’s a little bigger than\nlast time but more accurate. It’s still fast though, don’t\nworry. At 320 × 320 YOLOv3 runs in 22 ms at 28.2 mAP,\nas accurate as SSD but three times faster. When we look\nat the old .5 IOU mAP detection metric YOLOv3 is quite\ngood. It achieves 57.9 AP50 in 51 ms on a Titan X, compared\nto 57.5 AP50 in 198 ms by RetinaNet, similar performance\nbut 3.8× faster. As always, all the code is online at\nhttps://pjreddie.com/yolo/.\n\n[[Paper]](https://pjreddie.com/media/files/papers/YOLOv3.pdf) [[Project Webpage]](https://pjreddie.com/darknet/yolo/) [[Authors' Implementation]](https://github.com/pjreddie/darknet)\n\n```\n@article{yolov3,\n  title={YOLOv3: An Incremental Improvement},\n  author={Redmon, Joseph and Farhadi, Ali},\n  journal = {arXiv},\n  year={2018}\n}\n```\n\n## Other\n\n### YOEO — You Only Encode Once\n\n[YOEO](https://github.com/bit-bots/YOEO) extends this repo with the ability to train an additional semantic segmentation decoder. The lightweight example model is mainly targeted towards embedded real-time applications.\n"
  },
  {
    "path": "config/coco.data",
    "content": "classes= 80\ntrain=data/coco/trainvalno5k.txt\nvalid=data/coco/5k.txt\nnames=data/coco.names\nbackup=backup/\neval=coco\n"
  },
  {
    "path": "config/create_custom_model.sh",
    "content": "#!/bin/bash\n\nNUM_CLASSES=$1\n\necho \"\n[net]\n# Testing\n#batch=1\n#subdivisions=1\n# Training\nbatch=16\nsubdivisions=1\nwidth=416\nheight=416\nchannels=3\nmomentum=0.9\ndecay=0.0005\nangle=0\nsaturation = 1.5\nexposure = 1.5\nhue=.1\n\nlearning_rate=0.001\nburn_in=1000\nmax_batches = 500200\npolicy=steps\nsteps=400000,450000\nscales=.1,.1\n\n[convolutional]\nbatch_normalize=1\nfilters=32\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n# Downsample\n\n[convolutional]\nbatch_normalize=1\nfilters=64\nsize=3\nstride=2\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=32\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=64\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n# Downsample\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=3\nstride=2\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=64\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=64\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n# Downsample\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=2\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n# Downsample\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=2\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n# Downsample\n\n[convolutional]\nbatch_normalize=1\nfilters=1024\nsize=3\nstride=2\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=1024\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=1024\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=1024\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=1024\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n######################\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=1024\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=1024\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=1024\nactivation=leaky\n\n[convolutional]\nsize=1\nstride=1\npad=1\nfilters=$(expr 3 \\* $(expr $NUM_CLASSES \\+ 5))\nactivation=linear\n\n\n[yolo]\nmask = 6,7,8\nanchors = 10,13,  16,30,  33,23,  30,61,  62,45,  59,119,  116,90,  156,198,  373,326\nclasses=$NUM_CLASSES\nnum=9\njitter=.3\nignore_thresh = .7\ntruth_thresh = 1\nrandom=1\n\n\n[route]\nlayers = -4\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[upsample]\nstride=2\n\n[route]\nlayers = -1, 61\n\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=512\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=512\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=512\nactivation=leaky\n\n[convolutional]\nsize=1\nstride=1\npad=1\nfilters=$(expr 3 \\* $(expr $NUM_CLASSES \\+ 5))\nactivation=linear\n\n\n[yolo]\nmask = 3,4,5\nanchors = 10,13,  16,30,  33,23,  30,61,  62,45,  59,119,  116,90,  156,198,  373,326\nclasses=$NUM_CLASSES\nnum=9\njitter=.3\nignore_thresh = .7\ntruth_thresh = 1\nrandom=1\n\n\n\n[route]\nlayers = -4\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[upsample]\nstride=2\n\n[route]\nlayers = -1, 36\n\n\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=256\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=256\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=256\nactivation=leaky\n\n[convolutional]\nsize=1\nstride=1\npad=1\nfilters=$(expr 3 \\* $(expr $NUM_CLASSES \\+ 5))\nactivation=linear\n\n\n[yolo]\nmask = 0,1,2\nanchors = 10,13,  16,30,  33,23,  30,61,  62,45,  59,119,  116,90,  156,198,  373,326\nclasses=$NUM_CLASSES\nnum=9\njitter=.3\nignore_thresh = .7\ntruth_thresh = 1\nrandom=1\n\" >> yolov3-custom.cfg\n"
  },
  {
    "path": "config/custom.data",
    "content": "classes= 1\ntrain=data/custom/train.txt\nvalid=data/custom/valid.txt\nnames=data/custom/classes.names\n"
  },
  {
    "path": "config/yolov3-tiny.cfg",
    "content": "[net]\n# Testing\n#batch=1\n#subdivisions=1\n# Training\nbatch=64\nsubdivisions=2\nwidth=416\nheight=416\nchannels=3\nmomentum=0.9\ndecay=0.0005\nangle=0\nsaturation = 1.5\nexposure = 1.5\nhue=.1\n\nlearning_rate=0.0001\nburn_in=1000\nmax_batches = 500200\npolicy=steps\nsteps=400000,450000\nscales=.1,.1\n\n# 0\n[convolutional]\nbatch_normalize=1\nfilters=16\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n# 1\n[maxpool]\nsize=2\nstride=2\n\n# 2\n[convolutional]\nbatch_normalize=1\nfilters=32\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n# 3\n[maxpool]\nsize=2\nstride=2\n\n# 4\n[convolutional]\nbatch_normalize=1\nfilters=64\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n# 5\n[maxpool]\nsize=2\nstride=2\n\n# 6\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n# 7\n[maxpool]\nsize=2\nstride=2\n\n# 8\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n# 9\n[maxpool]\nsize=2\nstride=2\n\n# 10\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n# 11\n[maxpool]\nsize=2\nstride=1\n\n# 12\n[convolutional]\nbatch_normalize=1\nfilters=1024\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n###########\n\n# 13\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n# 14\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n# 15\n[convolutional]\nsize=1\nstride=1\npad=1\nfilters=255\nactivation=linear\n\n\n\n# 16\n[yolo]\nmask = 3,4,5\nanchors = 10,14,  23,27,  37,58,  81,82,  135,169,  344,319\nclasses=80\nnum=6\njitter=.3\nignore_thresh = .7\ntruth_thresh = 1\nrandom=1\n\n# 17\n[route]\nlayers = -4\n\n# 18\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n# 19\n[upsample]\nstride=2\n\n# 20\n[route]\nlayers = -1, 8\n\n# 21\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n# 22\n[convolutional]\nsize=1\nstride=1\npad=1\nfilters=255\nactivation=linear\n\n# 23\n[yolo]\nmask = 1,2,3\nanchors = 10,14,  23,27,  37,58,  81,82,  135,169,  344,319\nclasses=80\nnum=6\njitter=.3\nignore_thresh = .7\ntruth_thresh = 1\nrandom=1\n"
  },
  {
    "path": "config/yolov3.cfg",
    "content": "[net]\n# Testing\n#batch=1\n#subdivisions=1\n# Training\nbatch=16\nsubdivisions=1\nwidth=416\nheight=416\nchannels=3\nmomentum=0.9\ndecay=0.0005\nangle=0\nsaturation = 1.5\nexposure = 1.5\nhue=.1\n\nlearning_rate=0.0001\nburn_in=1000\nmax_batches = 500200\npolicy=steps\nsteps=400000,450000\nscales=.1,.1\n\n[convolutional]\nbatch_normalize=1\nfilters=32\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n# Downsample\n\n[convolutional]\nbatch_normalize=1\nfilters=64\nsize=3\nstride=2\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=32\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=64\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n# Downsample\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=3\nstride=2\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=64\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=64\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n# Downsample\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=2\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n# Downsample\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=2\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n# Downsample\n\n[convolutional]\nbatch_normalize=1\nfilters=1024\nsize=3\nstride=2\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=1024\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=1024\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=1024\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=1024\nsize=3\nstride=1\npad=1\nactivation=leaky\n\n[shortcut]\nfrom=-3\nactivation=linear\n\n######################\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=1024\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=1024\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=512\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=1024\nactivation=leaky\n\n[convolutional]\nsize=1\nstride=1\npad=1\nfilters=255\nactivation=linear\n\n\n[yolo]\nmask = 6,7,8\nanchors = 10,13,  16,30,  33,23,  30,61,  62,45,  59,119,  116,90,  156,198,  373,326\nclasses=80\nnum=9\njitter=.3\nignore_thresh = .7\ntruth_thresh = 1\nrandom=1\n\n\n[route]\nlayers = -4\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[upsample]\nstride=2\n\n[route]\nlayers = -1, 61\n\n\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=512\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=512\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=256\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=512\nactivation=leaky\n\n[convolutional]\nsize=1\nstride=1\npad=1\nfilters=255\nactivation=linear\n\n\n[yolo]\nmask = 3,4,5\nanchors = 10,13,  16,30,  33,23,  30,61,  62,45,  59,119,  116,90,  156,198,  373,326\nclasses=80\nnum=9\njitter=.3\nignore_thresh = .7\ntruth_thresh = 1\nrandom=1\n\n\n\n[route]\nlayers = -4\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[upsample]\nstride=2\n\n[route]\nlayers = -1, 36\n\n\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=256\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=256\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nfilters=128\nsize=1\nstride=1\npad=1\nactivation=leaky\n\n[convolutional]\nbatch_normalize=1\nsize=3\nstride=1\npad=1\nfilters=256\nactivation=leaky\n\n[convolutional]\nsize=1\nstride=1\npad=1\nfilters=255\nactivation=linear\n\n\n[yolo]\nmask = 0,1,2\nanchors = 10,13,  16,30,  33,23,  30,61,  62,45,  59,119,  116,90,  156,198,  373,326\nclasses=80\nnum=9\njitter=.3\nignore_thresh = .7\ntruth_thresh = 1\nrandom=1\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[tool.poetry]\nname = \"PyTorchYolo\"\nversion = \"1.8.0\"\nreadme = \"README.md\"\nrepository = \"https://github.com/eriklindernoren/PyTorch-YOLOv3\"\ndescription = \"Minimal PyTorch implementation of YOLO\"\nauthors = [\"Florian Vahl <git@flova.de>\", \"Erik Linder-Noren <eriklindernoren@gmail.com>\"]\nlicense = \"GPL-3.0\"\n\n[tool.poetry.dependencies]\npython = \">=3.8,<4.0\"\ntorch = \">=1.10.1, < 1.13.0\"\ntorchvision = \">=0.13.1\"\nmatplotlib = \"^3.3.3\"\ntensorboard = \"^2.10.0\"\nterminaltables = \"^3.1.0\"\nPillow = \"^9.1.0\"\ntqdm = \"^4.64.1\"\nurllib3 =  [\n    {version = \"<=1.22\", python = \">=3.8,<3.9\"},\n    {version = \"^1.23\", python = \">=3.9\"}\n] # Temp pin because of crash issue\nscipy = [\n    {version = \"<=1.6\", python = \">=3.8,<3.9\"},\n    {version = \"^1.9\", python = \">=3.9,<4.0\"}\n]\nimgaug = \"^0.4.0\"\ntorchsummary = \"^1.5.1\"\nnumpy = \"^1.23.4\"\n\n[tool.poetry.dev-dependencies]\nprofilehooks = \"^1.12.0\"\n\n[build-system]\nrequires = [\"poetry-core>=1.0.0\"]\nbuild-backend = \"poetry.core.masonry.api\"\n\n[tool.poetry.scripts]\nyolo-detect = \"pytorchyolo.detect:run\"\nyolo-train = \"pytorchyolo.train:run\"\nyolo-test = \"pytorchyolo.test:run\"\n"
  },
  {
    "path": "pytorchyolo/__init__.py",
    "content": ""
  },
  {
    "path": "pytorchyolo/detect.py",
    "content": "#! /usr/bin/env python3\n\nfrom __future__ import division\n\nimport os\nimport argparse\nimport tqdm\nimport random\nimport numpy as np\n\nfrom PIL import Image\n\nimport torch\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\n\nfrom pytorchyolo.models import load_model\nfrom pytorchyolo.utils.utils import load_classes, rescale_boxes, non_max_suppression, print_environment_info\nfrom pytorchyolo.utils.datasets import ImageFolder\nfrom pytorchyolo.utils.transforms import Resize, DEFAULT_TRANSFORMS\n\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom matplotlib.ticker import NullLocator\n\n\ndef detect_directory(model_path, weights_path, img_path, classes, output_path,\n                     batch_size=8, img_size=416, n_cpu=8, conf_thres=0.5, nms_thres=0.5):\n    \"\"\"Detects objects on all images in specified directory and saves output images with drawn detections.\n\n    :param model_path: Path to model definition file (.cfg)\n    :type model_path: str\n    :param weights_path: Path to weights or checkpoint file (.weights or .pth)\n    :type weights_path: str\n    :param img_path: Path to directory with images to inference\n    :type img_path: str\n    :param classes: List of class names\n    :type classes: [str]\n    :param output_path: Path to output directory\n    :type output_path: str\n    :param batch_size: Size of each image batch, defaults to 8\n    :type batch_size: int, optional\n    :param img_size: Size of each image dimension for yolo, defaults to 416\n    :type img_size: int, optional\n    :param n_cpu: Number of cpu threads to use during batch generation, defaults to 8\n    :type n_cpu: int, optional\n    :param conf_thres: Object confidence threshold, defaults to 0.5\n    :type conf_thres: float, optional\n    :param nms_thres: IOU threshold for non-maximum suppression, defaults to 0.5\n    :type nms_thres: float, optional\n    \"\"\"\n    dataloader = _create_data_loader(img_path, batch_size, img_size, n_cpu)\n    model = load_model(model_path, weights_path)\n    img_detections, imgs = detect(\n        model,\n        dataloader,\n        output_path,\n        conf_thres,\n        nms_thres)\n    _draw_and_save_output_images(\n        img_detections, imgs, img_size, output_path, classes)\n\n    print(f\"---- Detections were saved to: '{output_path}' ----\")\n\n\ndef detect_image(model, image, img_size=416, conf_thres=0.5, nms_thres=0.5):\n    \"\"\"Inferences one image with model.\n\n    :param model: Model for inference\n    :type model: models.Darknet\n    :param image: Image to inference\n    :type image: nd.array\n    :param img_size: Size of each image dimension for yolo, defaults to 416\n    :type img_size: int, optional\n    :param conf_thres: Object confidence threshold, defaults to 0.5\n    :type conf_thres: float, optional\n    :param nms_thres: IOU threshold for non-maximum suppression, defaults to 0.5\n    :type nms_thres: float, optional\n    :return: Detections on image with each detection in the format: [x1, y1, x2, y2, confidence, class]\n    :rtype: nd.array\n    \"\"\"\n    model.eval()  # Set model to evaluation mode\n\n    # Configure input\n    input_img = transforms.Compose([\n        DEFAULT_TRANSFORMS,\n        Resize(img_size)])(\n            (image, np.zeros((1, 5))))[0].unsqueeze(0)\n\n    if torch.cuda.is_available():\n        input_img = input_img.to(\"cuda\")\n\n    # Get detections\n    with torch.no_grad():\n        detections = model(input_img)\n        detections = non_max_suppression(detections, conf_thres, nms_thres)\n        detections = rescale_boxes(detections[0], img_size, image.shape[:2])\n    return detections.numpy()\n\n\ndef detect(model, dataloader, output_path, conf_thres, nms_thres):\n    \"\"\"Inferences images with model.\n\n    :param model: Model for inference\n    :type model: models.Darknet\n    :param dataloader: Dataloader provides the batches of images to inference\n    :type dataloader: DataLoader\n    :param output_path: Path to output directory\n    :type output_path: str\n    :param conf_thres: Object confidence threshold, defaults to 0.5\n    :type conf_thres: float, optional\n    :param nms_thres: IOU threshold for non-maximum suppression, defaults to 0.5\n    :type nms_thres: float, optional\n    :return: List of detections. The coordinates are given for the padded image that is provided by the dataloader.\n        Use `utils.rescale_boxes` to transform them into the desired input image coordinate system before its transformed by the dataloader),\n        List of input image paths\n    :rtype: [Tensor], [str]\n    \"\"\"\n    # Create output directory, if missing\n    os.makedirs(output_path, exist_ok=True)\n\n    model.eval()  # Set model to evaluation mode\n\n    Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor\n\n    img_detections = []  # Stores detections for each image index\n    imgs = []  # Stores image paths\n\n    for (img_paths, input_imgs) in tqdm.tqdm(dataloader, desc=\"Detecting\"):\n        # Configure input\n        input_imgs = Variable(input_imgs.type(Tensor))\n\n        # Get detections\n        with torch.no_grad():\n            detections = model(input_imgs)\n            detections = non_max_suppression(detections, conf_thres, nms_thres)\n\n        # Store image and detections\n        img_detections.extend(detections)\n        imgs.extend(img_paths)\n    return img_detections, imgs\n\n\ndef _draw_and_save_output_images(img_detections, imgs, img_size, output_path, classes):\n    \"\"\"Draws detections in output images and stores them.\n\n    :param img_detections: List of detections\n    :type img_detections: [Tensor]\n    :param imgs: List of paths to image files\n    :type imgs: [str]\n    :param img_size: Size of each image dimension for yolo\n    :type img_size: int\n    :param output_path: Path of output directory\n    :type output_path: str\n    :param classes: List of class names\n    :type classes: [str]\n    \"\"\"\n\n    # Iterate through images and save plot of detections\n    for (image_path, detections) in zip(imgs, img_detections):\n        print(f\"Image {image_path}:\")\n        _draw_and_save_output_image(\n            image_path, detections, img_size, output_path, classes)\n\n\ndef _draw_and_save_output_image(image_path, detections, img_size, output_path, classes):\n    \"\"\"Draws detections in output image and stores this.\n\n    :param image_path: Path to input image\n    :type image_path: str\n    :param detections: List of detections on image\n    :type detections: [Tensor]\n    :param img_size: Size of each image dimension for yolo\n    :type img_size: int\n    :param output_path: Path of output directory\n    :type output_path: str\n    :param classes: List of class names\n    :type classes: [str]\n    \"\"\"\n    # Create plot\n    img = np.array(Image.open(image_path))\n    plt.figure()\n    fig, ax = plt.subplots(1)\n    ax.imshow(img)\n    # Rescale boxes to original image\n    detections = rescale_boxes(detections, img_size, img.shape[:2])\n    unique_labels = detections[:, -1].cpu().unique()\n    n_cls_preds = len(unique_labels)\n    # Bounding-box colors\n    cmap = plt.get_cmap(\"tab20b\")\n    colors = [cmap(i) for i in np.linspace(0, 1, n_cls_preds)]\n    bbox_colors = random.sample(colors, n_cls_preds)\n    for x1, y1, x2, y2, conf, cls_pred in detections:\n\n        print(f\"\\t+ Label: {classes[int(cls_pred)]} | Confidence: {conf.item():0.4f}\")\n\n        box_w = x2 - x1\n        box_h = y2 - y1\n\n        color = bbox_colors[int(np.where(unique_labels == int(cls_pred))[0])]\n        # Create a Rectangle patch\n        bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor=\"none\")\n        # Add the bbox to the plot\n        ax.add_patch(bbox)\n        # Add label\n        plt.text(\n            x1,\n            y1,\n            s=f\"{classes[int(cls_pred)]}: {conf:.2f}\",\n            color=\"white\",\n            verticalalignment=\"top\",\n            bbox={\"color\": color, \"pad\": 0})\n\n    # Save generated image with detections\n    plt.axis(\"off\")\n    plt.gca().xaxis.set_major_locator(NullLocator())\n    plt.gca().yaxis.set_major_locator(NullLocator())\n    filename = os.path.basename(image_path).split(\".\")[0]\n    output_path = os.path.join(output_path, f\"{filename}.png\")\n    plt.savefig(output_path, bbox_inches=\"tight\", pad_inches=0.0)\n    plt.close()\n\n\ndef _create_data_loader(img_path, batch_size, img_size, n_cpu):\n    \"\"\"Creates a DataLoader for inferencing.\n\n    :param img_path: Path to file containing all paths to validation images.\n    :type img_path: str\n    :param batch_size: Size of each image batch\n    :type batch_size: int\n    :param img_size: Size of each image dimension for yolo\n    :type img_size: int\n    :param n_cpu: Number of cpu threads to use during batch generation\n    :type n_cpu: int\n    :return: Returns DataLoader\n    :rtype: DataLoader\n    \"\"\"\n    dataset = ImageFolder(\n        img_path,\n        transform=transforms.Compose([DEFAULT_TRANSFORMS, Resize(img_size)]))\n    dataloader = DataLoader(\n        dataset,\n        batch_size=batch_size,\n        shuffle=False,\n        num_workers=n_cpu,\n        pin_memory=True)\n    return dataloader\n\n\ndef run():\n    print_environment_info()\n    parser = argparse.ArgumentParser(description=\"Detect objects on images.\")\n    parser.add_argument(\"-m\", \"--model\", type=str, default=\"config/yolov3.cfg\", help=\"Path to model definition file (.cfg)\")\n    parser.add_argument(\"-w\", \"--weights\", type=str, default=\"weights/yolov3.weights\", help=\"Path to weights or checkpoint file (.weights or .pth)\")\n    parser.add_argument(\"-i\", \"--images\", type=str, default=\"data/samples\", help=\"Path to directory with images to inference\")\n    parser.add_argument(\"-c\", \"--classes\", type=str, default=\"data/coco.names\", help=\"Path to classes label file (.names)\")\n    parser.add_argument(\"-o\", \"--output\", type=str, default=\"output\", help=\"Path to output directory\")\n    parser.add_argument(\"-b\", \"--batch_size\", type=int, default=1, help=\"Size of each image batch\")\n    parser.add_argument(\"--img_size\", type=int, default=416, help=\"Size of each image dimension for yolo\")\n    parser.add_argument(\"--n_cpu\", type=int, default=8, help=\"Number of cpu threads to use during batch generation\")\n    parser.add_argument(\"--conf_thres\", type=float, default=0.5, help=\"Object confidence threshold\")\n    parser.add_argument(\"--nms_thres\", type=float, default=0.4, help=\"IOU threshold for non-maximum suppression\")\n    args = parser.parse_args()\n    print(f\"Command line arguments: {args}\")\n\n    # Extract class names from file\n    classes = load_classes(args.classes)  # List of class names\n\n    detect_directory(\n        args.model,\n        args.weights,\n        args.images,\n        classes,\n        args.output,\n        batch_size=args.batch_size,\n        img_size=args.img_size,\n        n_cpu=args.n_cpu,\n        conf_thres=args.conf_thres,\n        nms_thres=args.nms_thres)\n\n\nif __name__ == '__main__':\n    run()\n"
  },
  {
    "path": "pytorchyolo/models.py",
    "content": "from __future__ import division\n\nimport os\nfrom itertools import chain\nfrom typing import List, Tuple\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom pytorchyolo.utils.parse_config import parse_model_config\nfrom pytorchyolo.utils.utils import weights_init_normal\n\n\ndef create_modules(module_defs: List[dict]) -> Tuple[dict, nn.ModuleList]:\n    \"\"\"\n    Constructs module list of layer blocks from module configuration in module_defs\n\n    :param module_defs: List of dictionaries with module definitions\n    :return: Hyperparameters and pytorch module list\n    \"\"\"\n    hyperparams = module_defs.pop(0)\n    hyperparams.update({\n        'batch': int(hyperparams['batch']),\n        'subdivisions': int(hyperparams['subdivisions']),\n        'width': int(hyperparams['width']),\n        'height': int(hyperparams['height']),\n        'channels': int(hyperparams['channels']),\n        'optimizer': hyperparams.get('optimizer'),\n        'momentum': float(hyperparams['momentum']),\n        'decay': float(hyperparams['decay']),\n        'learning_rate': float(hyperparams['learning_rate']),\n        'burn_in': int(hyperparams['burn_in']),\n        'max_batches': int(hyperparams['max_batches']),\n        'policy': hyperparams['policy'],\n        'lr_steps': list(zip(map(int,   hyperparams[\"steps\"].split(\",\")),\n                             map(float, hyperparams[\"scales\"].split(\",\"))))\n    })\n    assert hyperparams[\"height\"] == hyperparams[\"width\"], \\\n        \"Height and width should be equal! Non square images are padded with zeros.\"\n    output_filters = [hyperparams[\"channels\"]]\n    module_list = nn.ModuleList()\n    for module_i, module_def in enumerate(module_defs):\n        modules = nn.Sequential()\n\n        if module_def[\"type\"] == \"convolutional\":\n            bn = int(module_def[\"batch_normalize\"])\n            filters = int(module_def[\"filters\"])\n            kernel_size = int(module_def[\"size\"])\n            pad = (kernel_size - 1) // 2\n            modules.add_module(\n                f\"conv_{module_i}\",\n                nn.Conv2d(\n                    in_channels=output_filters[-1],\n                    out_channels=filters,\n                    kernel_size=kernel_size,\n                    stride=int(module_def[\"stride\"]),\n                    padding=pad,\n                    bias=not bn,\n                ),\n            )\n            if bn:\n                modules.add_module(f\"batch_norm_{module_i}\",\n                                   nn.BatchNorm2d(filters, momentum=0.1, eps=1e-5))\n            if module_def[\"activation\"] == \"leaky\":\n                modules.add_module(f\"leaky_{module_i}\", nn.LeakyReLU(0.1))\n            elif module_def[\"activation\"] == \"mish\":\n                modules.add_module(f\"mish_{module_i}\", nn.Mish())\n            elif module_def[\"activation\"] == \"logistic\":\n                modules.add_module(f\"sigmoid_{module_i}\", nn.Sigmoid())\n            elif module_def[\"activation\"] == \"swish\":\n                modules.add_module(f\"swish_{module_i}\", nn.SiLU())\n\n        elif module_def[\"type\"] == \"maxpool\":\n            kernel_size = int(module_def[\"size\"])\n            stride = int(module_def[\"stride\"])\n            if kernel_size == 2 and stride == 1:\n                modules.add_module(f\"_debug_padding_{module_i}\", nn.ZeroPad2d((0, 1, 0, 1)))\n            maxpool = nn.MaxPool2d(kernel_size=kernel_size, stride=stride,\n                                   padding=int((kernel_size - 1) // 2))\n            modules.add_module(f\"maxpool_{module_i}\", maxpool)\n\n        elif module_def[\"type\"] == \"upsample\":\n            upsample = Upsample(scale_factor=int(module_def[\"stride\"]), mode=\"nearest\")\n            modules.add_module(f\"upsample_{module_i}\", upsample)\n\n        elif module_def[\"type\"] == \"route\":\n            layers = [int(x) for x in module_def[\"layers\"].split(\",\")]\n            filters = sum([output_filters[1:][i] for i in layers]) // int(module_def.get(\"groups\", 1))\n            modules.add_module(f\"route_{module_i}\", nn.Sequential())\n\n        elif module_def[\"type\"] == \"shortcut\":\n            filters = output_filters[1:][int(module_def[\"from\"])]\n            modules.add_module(f\"shortcut_{module_i}\", nn.Sequential())\n\n        elif module_def[\"type\"] == \"yolo\":\n            anchor_idxs = [int(x) for x in module_def[\"mask\"].split(\",\")]\n            # Extract anchors\n            anchors = [int(x) for x in module_def[\"anchors\"].split(\",\")]\n            anchors = [(anchors[i], anchors[i + 1]) for i in range(0, len(anchors), 2)]\n            anchors = [anchors[i] for i in anchor_idxs]\n            num_classes = int(module_def[\"classes\"])\n            new_coords = bool(module_def.get(\"new_coords\", False))\n            # Define detection layer\n            yolo_layer = YOLOLayer(anchors, num_classes, new_coords)\n            modules.add_module(f\"yolo_{module_i}\", yolo_layer)\n        # Register module list and number of output filters\n        module_list.append(modules)\n        output_filters.append(filters)\n\n    return hyperparams, module_list\n\n\nclass Upsample(nn.Module):\n    \"\"\" nn.Upsample is deprecated \"\"\"\n\n    def __init__(self, scale_factor, mode: str = \"nearest\"):\n        super(Upsample, self).__init__()\n        self.scale_factor = scale_factor\n        self.mode = mode\n\n    def forward(self, x):\n        x = F.interpolate(x, scale_factor=self.scale_factor, mode=self.mode)\n        return x\n\n\nclass YOLOLayer(nn.Module):\n    \"\"\"Detection layer\"\"\"\n\n    def __init__(self, anchors: List[Tuple[int, int]], num_classes: int, new_coords: bool):\n        \"\"\"\n        Create a YOLO layer\n\n        :param anchors: List of anchors\n        :param num_classes: Number of classes\n        :param new_coords: Whether to use the new coordinate format from YOLO V7\n        \"\"\"\n        super(YOLOLayer, self).__init__()\n        self.num_anchors = len(anchors)\n        self.num_classes = num_classes\n        self.new_coords = new_coords\n        self.mse_loss = nn.MSELoss()\n        self.bce_loss = nn.BCELoss()\n        self.no = num_classes + 5  # number of outputs per anchor\n        self.grid = torch.zeros(1)  # TODO\n\n        anchors = torch.tensor(list(chain(*anchors))).float().view(-1, 2)\n        self.register_buffer('anchors', anchors)\n        self.register_buffer(\n            'anchor_grid', anchors.clone().view(1, -1, 1, 1, 2))\n        self.stride = None\n\n    def forward(self, x: torch.Tensor, img_size: int) -> torch.Tensor:\n        \"\"\"\n        Forward pass of the YOLO layer\n\n        :param x: Input tensor\n        :param img_size: Size of the input image\n        \"\"\"\n        stride = img_size // x.size(2)\n        self.stride = stride\n        bs, _, ny, nx = x.shape  # x(bs,255,20,20) to x(bs,3,20,20,85)\n        x = x.view(bs, self.num_anchors, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()\n\n        if not self.training:  # inference\n            if self.grid.shape[2:4] != x.shape[2:4]:\n                self.grid = self._make_grid(nx, ny).to(x.device)\n\n            if self.new_coords:\n                x[..., 0:2] = (x[..., 0:2] + self.grid) * stride  # xy\n                x[..., 2:4] = x[..., 2:4] ** 2 * (4 * self.anchor_grid) # wh\n            else:\n                x[..., 0:2] = (x[..., 0:2].sigmoid() + self.grid) * stride  # xy\n                x[..., 2:4] = torch.exp(x[..., 2:4]) * self.anchor_grid # wh\n                x[..., 4:] = x[..., 4:].sigmoid() # conf, cls\n            x = x.view(bs, -1, self.no)\n\n        return x\n\n    @staticmethod\n    def _make_grid(nx: int = 20, ny: int = 20) -> torch.Tensor:\n        \"\"\"\n        Create a grid of (x, y) coordinates\n\n        :param nx: Number of x coordinates\n        :param ny: Number of y coordinates\n        \"\"\"\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 Darknet(nn.Module):\n    \"\"\"YOLOv3 object detection model\"\"\"\n\n    def __init__(self, config_path):\n        super(Darknet, self).__init__()\n        self.module_defs = parse_model_config(config_path)\n        self.hyperparams, self.module_list = create_modules(self.module_defs)\n        self.yolo_layers = [layer[0]\n                            for layer in self.module_list if isinstance(layer[0], YOLOLayer)]\n        self.seen = 0\n        self.header_info = np.array([0, 0, 0, self.seen, 0], dtype=np.int32)\n\n    def forward(self, x):\n        img_size = x.size(2)\n        layer_outputs, yolo_outputs = [], []\n        for i, (module_def, module) in enumerate(zip(self.module_defs, self.module_list)):\n            if module_def[\"type\"] in [\"convolutional\", \"upsample\", \"maxpool\"]:\n                x = module(x)\n            elif module_def[\"type\"] == \"route\":\n                combined_outputs = torch.cat([layer_outputs[int(layer_i)] for layer_i in module_def[\"layers\"].split(\",\")], 1)\n                group_size = combined_outputs.shape[1] // int(module_def.get(\"groups\", 1))\n                group_id = int(module_def.get(\"group_id\", 0))\n                x = combined_outputs[:, group_size * group_id : group_size * (group_id + 1)] # Slice groupings used by yolo v4\n            elif module_def[\"type\"] == \"shortcut\":\n                layer_i = int(module_def[\"from\"])\n                x = layer_outputs[-1] + layer_outputs[layer_i]\n            elif module_def[\"type\"] == \"yolo\":\n                x = module[0](x, img_size)\n                yolo_outputs.append(x)\n            layer_outputs.append(x)\n        return yolo_outputs if self.training else torch.cat(yolo_outputs, 1)\n\n    def load_darknet_weights(self, weights_path):\n        \"\"\"Parses and loads the weights stored in 'weights_path'\"\"\"\n\n        # Open the weights file\n        with open(weights_path, \"rb\") as f:\n            # First five are header values\n            header = np.fromfile(f, dtype=np.int32, count=5)\n            self.header_info = header  # Needed to write header when saving weights\n            self.seen = header[3]  # number of images seen during training\n            weights = np.fromfile(f, dtype=np.float32)  # The rest are weights\n\n        # Establish cutoff for loading backbone weights\n        cutoff = None\n        # If the weights file has a cutoff, we can find out about it by looking at the filename\n        # examples: darknet53.conv.74 -> cutoff is 74\n        filename = os.path.basename(weights_path)\n        if \".conv.\" in filename:\n            try:\n                cutoff = int(filename.split(\".\")[-1])  # use last part of filename\n            except ValueError:\n                pass\n\n        ptr = 0\n        for i, (module_def, module) in enumerate(zip(self.module_defs, self.module_list)):\n            if i == cutoff:\n                break\n            if module_def[\"type\"] == \"convolutional\":\n                conv_layer = module[0]\n                if module_def[\"batch_normalize\"]:\n                    # Load BN bias, weights, running mean and running variance\n                    bn_layer = module[1]\n                    num_b = bn_layer.bias.numel()  # Number of biases\n                    # Bias\n                    bn_b = torch.from_numpy(\n                        weights[ptr: ptr + num_b]).view_as(bn_layer.bias)\n                    bn_layer.bias.data.copy_(bn_b)\n                    ptr += num_b\n                    # Weight\n                    bn_w = torch.from_numpy(\n                        weights[ptr: ptr + num_b]).view_as(bn_layer.weight)\n                    bn_layer.weight.data.copy_(bn_w)\n                    ptr += num_b\n                    # Running Mean\n                    bn_rm = torch.from_numpy(\n                        weights[ptr: ptr + num_b]).view_as(bn_layer.running_mean)\n                    bn_layer.running_mean.data.copy_(bn_rm)\n                    ptr += num_b\n                    # Running Var\n                    bn_rv = torch.from_numpy(\n                        weights[ptr: ptr + num_b]).view_as(bn_layer.running_var)\n                    bn_layer.running_var.data.copy_(bn_rv)\n                    ptr += num_b\n                else:\n                    # Load conv. bias\n                    num_b = conv_layer.bias.numel()\n                    conv_b = torch.from_numpy(\n                        weights[ptr: ptr + num_b]).view_as(conv_layer.bias)\n                    conv_layer.bias.data.copy_(conv_b)\n                    ptr += num_b\n                # Load conv. weights\n                num_w = conv_layer.weight.numel()\n                conv_w = torch.from_numpy(\n                    weights[ptr: ptr + num_w]).view_as(conv_layer.weight)\n                conv_layer.weight.data.copy_(conv_w)\n                ptr += num_w\n\n    def save_darknet_weights(self, path, cutoff=-1):\n        \"\"\"\n            @:param path    - path of the new weights file\n            @:param cutoff  - save layers between 0 and cutoff (cutoff = -1 -> all are saved)\n        \"\"\"\n        fp = open(path, \"wb\")\n        self.header_info[3] = self.seen\n        self.header_info.tofile(fp)\n\n        # Iterate through layers\n        for i, (module_def, module) in enumerate(zip(self.module_defs[:cutoff], self.module_list[:cutoff])):\n            if module_def[\"type\"] == \"convolutional\":\n                conv_layer = module[0]\n                # If batch norm, load bn first\n                if module_def[\"batch_normalize\"]:\n                    bn_layer = module[1]\n                    bn_layer.bias.data.cpu().numpy().tofile(fp)\n                    bn_layer.weight.data.cpu().numpy().tofile(fp)\n                    bn_layer.running_mean.data.cpu().numpy().tofile(fp)\n                    bn_layer.running_var.data.cpu().numpy().tofile(fp)\n                # Load conv bias\n                else:\n                    conv_layer.bias.data.cpu().numpy().tofile(fp)\n                # Load conv weights\n                conv_layer.weight.data.cpu().numpy().tofile(fp)\n\n        fp.close()\n\n\ndef load_model(model_path, weights_path=None):\n    \"\"\"Loads the yolo model from file.\n\n    :param model_path: Path to model definition file (.cfg)\n    :type model_path: str\n    :param weights_path: Path to weights or checkpoint file (.weights or .pth)\n    :type weights_path: str\n    :return: Returns model\n    :rtype: Darknet\n    \"\"\"\n    device = torch.device(\"cuda\" if torch.cuda.is_available()\n                          else \"cpu\")  # Select device for inference\n    model = Darknet(model_path).to(device)\n\n    model.apply(weights_init_normal)\n\n    # If pretrained weights are specified, start from checkpoint or weight file\n    if weights_path:\n        if weights_path.endswith(\".pth\"):\n            # Load checkpoint weights\n            model.load_state_dict(torch.load(weights_path, map_location=device))\n        else:\n            # Load darknet weights\n            model.load_darknet_weights(weights_path)\n    return model\n"
  },
  {
    "path": "pytorchyolo/test.py",
    "content": "#! /usr/bin/env python3\n\nfrom __future__ import division\n\nimport argparse\nimport tqdm\nimport numpy as np\n\nfrom terminaltables import AsciiTable\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\n\nfrom pytorchyolo.models import load_model\nfrom pytorchyolo.utils.utils import load_classes, ap_per_class, get_batch_statistics, non_max_suppression, to_cpu, xywh2xyxy, print_environment_info\nfrom pytorchyolo.utils.datasets import ListDataset\nfrom pytorchyolo.utils.transforms import DEFAULT_TRANSFORMS\nfrom pytorchyolo.utils.parse_config import parse_data_config\n\n\ndef evaluate_model_file(model_path, weights_path, img_path, class_names, batch_size=8, img_size=416,\n                        n_cpu=8, iou_thres=0.5, conf_thres=0.5, nms_thres=0.5, verbose=True):\n    \"\"\"Evaluate model on validation dataset.\n\n    :param model_path: Path to model definition file (.cfg)\n    :type model_path: str\n    :param weights_path: Path to weights or checkpoint file (.weights or .pth)\n    :type weights_path: str\n    :param img_path: Path to file containing all paths to validation images.\n    :type img_path: str\n    :param class_names: List of class names\n    :type class_names: [str]\n    :param batch_size: Size of each image batch, defaults to 8\n    :type batch_size: int, optional\n    :param img_size: Size of each image dimension for yolo, defaults to 416\n    :type img_size: int, optional\n    :param n_cpu: Number of cpu threads to use during batch generation, defaults to 8\n    :type n_cpu: int, optional\n    :param iou_thres: IOU threshold required to qualify as detected, defaults to 0.5\n    :type iou_thres: float, optional\n    :param conf_thres: Object confidence threshold, defaults to 0.5\n    :type conf_thres: float, optional\n    :param nms_thres: IOU threshold for non-maximum suppression, defaults to 0.5\n    :type nms_thres: float, optional\n    :param verbose: If True, prints stats of model, defaults to True\n    :type verbose: bool, optional\n    :return: Returns precision, recall, AP, f1, ap_class\n    \"\"\"\n    dataloader = _create_validation_data_loader(\n        img_path, batch_size, img_size, n_cpu)\n    model = load_model(model_path, weights_path)\n    metrics_output = _evaluate(\n        model,\n        dataloader,\n        class_names,\n        img_size,\n        iou_thres,\n        conf_thres,\n        nms_thres,\n        verbose)\n    return metrics_output\n\n\ndef print_eval_stats(metrics_output, class_names, verbose):\n    if metrics_output is not None:\n        precision, recall, AP, f1, ap_class = metrics_output\n        if verbose:\n            # Prints class AP and mean AP\n            ap_table = [[\"Index\", \"Class\", \"AP\"]]\n            for i, c in enumerate(ap_class):\n                ap_table += [[c, class_names[c], \"%.5f\" % AP[i]]]\n            print(AsciiTable(ap_table).table)\n        print(f\"---- mAP {AP.mean():.5f} ----\")\n    else:\n        print(\"---- mAP not measured (no detections found by model) ----\")\n\n\ndef _evaluate(model, dataloader, class_names, img_size, iou_thres, conf_thres, nms_thres, verbose):\n    \"\"\"Evaluate model on validation dataset.\n\n    :param model: Model to evaluate\n    :type model: models.Darknet\n    :param dataloader: Dataloader provides the batches of images with targets\n    :type dataloader: DataLoader\n    :param class_names: List of class names\n    :type class_names: [str]\n    :param img_size: Size of each image dimension for yolo\n    :type img_size: int\n    :param iou_thres: IOU threshold required to qualify as detected\n    :type iou_thres: float\n    :param conf_thres: Object confidence threshold\n    :type conf_thres: float\n    :param nms_thres: IOU threshold for non-maximum suppression\n    :type nms_thres: float\n    :param verbose: If True, prints stats of model\n    :type verbose: bool\n    :return: Returns precision, recall, AP, f1, ap_class\n    \"\"\"\n    model.eval()  # Set model to evaluation mode\n\n    Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor\n\n    labels = []\n    sample_metrics = []  # List of tuples (TP, confs, pred)\n    for _, imgs, targets in tqdm.tqdm(dataloader, desc=\"Validating\"):\n        # Extract labels\n        labels += targets[:, 1].tolist()\n        # Rescale target\n        targets[:, 2:] = xywh2xyxy(targets[:, 2:])\n        targets[:, 2:] *= img_size\n\n        imgs = Variable(imgs.type(Tensor), requires_grad=False)\n\n        with torch.no_grad():\n            outputs = model(imgs)\n            outputs = non_max_suppression(outputs, conf_thres=conf_thres, iou_thres=nms_thres)\n\n        sample_metrics += get_batch_statistics(outputs, targets, iou_threshold=iou_thres)\n\n    if len(sample_metrics) == 0:  # No detections over whole validation set.\n        print(\"---- No detections over whole validation set ----\")\n        return None\n\n    # Concatenate sample statistics\n    true_positives, pred_scores, pred_labels = [\n        np.concatenate(x, 0) for x in list(zip(*sample_metrics))]\n    metrics_output = ap_per_class(\n        true_positives, pred_scores, pred_labels, labels)\n\n    print_eval_stats(metrics_output, class_names, verbose)\n\n    return metrics_output\n\n\ndef _create_validation_data_loader(img_path, batch_size, img_size, n_cpu):\n    \"\"\"\n    Creates a DataLoader for validation.\n\n    :param img_path: Path to file containing all paths to validation images.\n    :type img_path: str\n    :param batch_size: Size of each image batch\n    :type batch_size: int\n    :param img_size: Size of each image dimension for yolo\n    :type img_size: int\n    :param n_cpu: Number of cpu threads to use during batch generation\n    :type n_cpu: int\n    :return: Returns DataLoader\n    :rtype: DataLoader\n    \"\"\"\n    dataset = ListDataset(img_path, img_size=img_size, multiscale=False, transform=DEFAULT_TRANSFORMS)\n    dataloader = DataLoader(\n        dataset,\n        batch_size=batch_size,\n        shuffle=False,\n        num_workers=n_cpu,\n        pin_memory=True,\n        collate_fn=dataset.collate_fn)\n    return dataloader\n\n\ndef run():\n    print_environment_info()\n    parser = argparse.ArgumentParser(description=\"Evaluate validation data.\")\n    parser.add_argument(\"-m\", \"--model\", type=str, default=\"config/yolov3.cfg\", help=\"Path to model definition file (.cfg)\")\n    parser.add_argument(\"-w\", \"--weights\", type=str, default=\"weights/yolov3.weights\", help=\"Path to weights or checkpoint file (.weights or .pth)\")\n    parser.add_argument(\"-d\", \"--data\", type=str, default=\"config/coco.data\", help=\"Path to data config file (.data)\")\n    parser.add_argument(\"-b\", \"--batch_size\", type=int, default=8, help=\"Size of each image batch\")\n    parser.add_argument(\"-v\", \"--verbose\", action='store_true', help=\"Makes the validation more verbose\")\n    parser.add_argument(\"--img_size\", type=int, default=416, help=\"Size of each image dimension for yolo\")\n    parser.add_argument(\"--n_cpu\", type=int, default=8, help=\"Number of cpu threads to use during batch generation\")\n    parser.add_argument(\"--iou_thres\", type=float, default=0.5, help=\"IOU threshold required to qualify as detected\")\n    parser.add_argument(\"--conf_thres\", type=float, default=0.01, help=\"Object confidence threshold\")\n    parser.add_argument(\"--nms_thres\", type=float, default=0.4, help=\"IOU threshold for non-maximum suppression\")\n    args = parser.parse_args()\n    print(f\"Command line arguments: {args}\")\n\n    # Load configuration from data file\n    data_config = parse_data_config(args.data)\n    # Path to file containing all images for validation\n    valid_path = data_config[\"valid\"]\n    class_names = load_classes(data_config[\"names\"])  # List of class names\n\n    precision, recall, AP, f1, ap_class = evaluate_model_file(\n        args.model,\n        args.weights,\n        valid_path,\n        class_names,\n        batch_size=args.batch_size,\n        img_size=args.img_size,\n        n_cpu=args.n_cpu,\n        iou_thres=args.iou_thres,\n        conf_thres=args.conf_thres,\n        nms_thres=args.nms_thres,\n        verbose=True)\n\n\nif __name__ == \"__main__\":\n    run()\n"
  },
  {
    "path": "pytorchyolo/train.py",
    "content": "#! /usr/bin/env python3\n\nfrom __future__ import division\n\nimport os\nimport argparse\nimport tqdm\n\nimport torch\nfrom torch.utils.data import DataLoader\nimport torch.optim as optim\n\nfrom pytorchyolo.models import load_model\nfrom pytorchyolo.utils.logger import Logger\nfrom pytorchyolo.utils.utils import to_cpu, load_classes, print_environment_info, provide_determinism, worker_seed_set\nfrom pytorchyolo.utils.datasets import ListDataset\nfrom pytorchyolo.utils.augmentations import AUGMENTATION_TRANSFORMS\n#from pytorchyolo.utils.transforms import DEFAULT_TRANSFORMS\nfrom pytorchyolo.utils.parse_config import parse_data_config\nfrom pytorchyolo.utils.loss import compute_loss\nfrom pytorchyolo.test import _evaluate, _create_validation_data_loader\n\nfrom terminaltables import AsciiTable\n\nfrom torchsummary import summary\n\n\ndef _create_data_loader(img_path, batch_size, img_size, n_cpu, multiscale_training=False):\n    \"\"\"Creates a DataLoader for training.\n\n    :param img_path: Path to file containing all paths to training images.\n    :type img_path: str\n    :param batch_size: Size of each image batch\n    :type batch_size: int\n    :param img_size: Size of each image dimension for yolo\n    :type img_size: int\n    :param n_cpu: Number of cpu threads to use during batch generation\n    :type n_cpu: int\n    :param multiscale_training: Scale images to different sizes randomly\n    :type multiscale_training: bool\n    :return: Returns DataLoader\n    :rtype: DataLoader\n    \"\"\"\n    dataset = ListDataset(\n        img_path,\n        img_size=img_size,\n        multiscale=multiscale_training,\n        transform=AUGMENTATION_TRANSFORMS)\n    dataloader = DataLoader(\n        dataset,\n        batch_size=batch_size,\n        shuffle=True,\n        num_workers=n_cpu,\n        pin_memory=True,\n        collate_fn=dataset.collate_fn,\n        worker_init_fn=worker_seed_set)\n    return dataloader\n\n\ndef run():\n    print_environment_info()\n    parser = argparse.ArgumentParser(description=\"Trains the YOLO model.\")\n    parser.add_argument(\"-m\", \"--model\", type=str, default=\"config/yolov3.cfg\", help=\"Path to model definition file (.cfg)\")\n    parser.add_argument(\"-d\", \"--data\", type=str, default=\"config/coco.data\", help=\"Path to data config file (.data)\")\n    parser.add_argument(\"-e\", \"--epochs\", type=int, default=300, help=\"Number of epochs\")\n    parser.add_argument(\"-v\", \"--verbose\", action='store_true', help=\"Makes the training more verbose\")\n    parser.add_argument(\"--n_cpu\", type=int, default=8, help=\"Number of cpu threads to use during batch generation\")\n    parser.add_argument(\"--pretrained_weights\", type=str, help=\"Path to checkpoint file (.weights or .pth). Starts training from checkpoint model\")\n    parser.add_argument(\"--checkpoint_interval\", type=int, default=1, help=\"Interval of epochs between saving model weights\")\n    parser.add_argument(\"--evaluation_interval\", type=int, default=1, help=\"Interval of epochs between evaluations on validation set\")\n    parser.add_argument(\"--multiscale_training\", action=\"store_true\", help=\"Allow multi-scale training\")\n    parser.add_argument(\"--iou_thres\", type=float, default=0.5, help=\"Evaluation: IOU threshold required to qualify as detected\")\n    parser.add_argument(\"--conf_thres\", type=float, default=0.1, help=\"Evaluation: Object confidence threshold\")\n    parser.add_argument(\"--nms_thres\", type=float, default=0.5, help=\"Evaluation: IOU threshold for non-maximum suppression\")\n    parser.add_argument(\"--logdir\", type=str, default=\"logs\", help=\"Directory for training log files (e.g. for TensorBoard)\")\n    parser.add_argument(\"--seed\", type=int, default=-1, help=\"Makes results reproducable. Set -1 to disable.\")\n    args = parser.parse_args()\n    print(f\"Command line arguments: {args}\")\n\n    if args.seed != -1:\n        provide_determinism(args.seed)\n\n    logger = Logger(args.logdir)  # Tensorboard logger\n\n    # Create output directories if missing\n    os.makedirs(\"output\", exist_ok=True)\n    os.makedirs(\"checkpoints\", exist_ok=True)\n\n    # Get data configuration\n    data_config = parse_data_config(args.data)\n    train_path = data_config[\"train\"]\n    valid_path = data_config[\"valid\"]\n    class_names = load_classes(data_config[\"names\"])\n    device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n    # ############\n    # Create model\n    # ############\n\n    model = load_model(args.model, args.pretrained_weights)\n\n    # Print model\n    if args.verbose:\n        summary(model, input_size=(3, model.hyperparams['height'], model.hyperparams['height']))\n\n    mini_batch_size = model.hyperparams['batch'] // model.hyperparams['subdivisions']\n\n    # #################\n    # Create Dataloader\n    # #################\n\n    # Load training dataloader\n    dataloader = _create_data_loader(\n        train_path,\n        mini_batch_size,\n        model.hyperparams['height'],\n        args.n_cpu,\n        args.multiscale_training)\n\n    # Load validation dataloader\n    validation_dataloader = _create_validation_data_loader(\n        valid_path,\n        mini_batch_size,\n        model.hyperparams['height'],\n        args.n_cpu)\n\n    # ################\n    # Create optimizer\n    # ################\n\n    params = [p for p in model.parameters() if p.requires_grad]\n\n    if (model.hyperparams['optimizer'] in [None, \"adam\"]):\n        optimizer = optim.Adam(\n            params,\n            lr=model.hyperparams['learning_rate'],\n            weight_decay=model.hyperparams['decay'],\n        )\n    elif (model.hyperparams['optimizer'] == \"sgd\"):\n        optimizer = optim.SGD(\n            params,\n            lr=model.hyperparams['learning_rate'],\n            weight_decay=model.hyperparams['decay'],\n            momentum=model.hyperparams['momentum'])\n    else:\n        print(\"Unknown optimizer. Please choose between (adam, sgd).\")\n\n    # skip epoch zero, because then the calculations for when to evaluate/checkpoint makes more intuitive sense\n    # e.g. when you stop after 30 epochs and evaluate every 10 epochs then the evaluations happen after: 10,20,30\n    # instead of: 0, 10, 20\n    for epoch in range(1, args.epochs+1):\n\n        print(\"\\n---- Training Model ----\")\n\n        model.train()  # Set model to training mode\n\n        for batch_i, (_, imgs, targets) in enumerate(tqdm.tqdm(dataloader, desc=f\"Training Epoch {epoch}\")):\n            batches_done = len(dataloader) * epoch + batch_i\n\n            imgs = imgs.to(device, non_blocking=True)\n            targets = targets.to(device)\n\n            outputs = model(imgs)\n\n            loss, loss_components = compute_loss(outputs, targets, model)\n\n            loss.backward()\n\n            ###############\n            # Run optimizer\n            ###############\n\n            if batches_done % model.hyperparams['subdivisions'] == 0:\n                # Adapt learning rate\n                # Get learning rate defined in cfg\n                lr = model.hyperparams['learning_rate']\n                if batches_done < model.hyperparams['burn_in']:\n                    # Burn in\n                    lr *= (batches_done / model.hyperparams['burn_in'])\n                else:\n                    # Set and parse the learning rate to the steps defined in the cfg\n                    for threshold, value in model.hyperparams['lr_steps']:\n                        if batches_done > threshold:\n                            lr *= value\n                # Log the learning rate\n                logger.scalar_summary(\"train/learning_rate\", lr, batches_done)\n                # Set learning rate\n                for g in optimizer.param_groups:\n                    g['lr'] = lr\n\n                # Run optimizer\n                optimizer.step()\n                # Reset gradients\n                optimizer.zero_grad()\n\n            # ############\n            # Log progress\n            # ############\n            if args.verbose:\n                print(AsciiTable(\n                    [\n                        [\"Type\", \"Value\"],\n                        [\"IoU loss\", float(loss_components[0])],\n                        [\"Object loss\", float(loss_components[1])],\n                        [\"Class loss\", float(loss_components[2])],\n                        [\"Loss\", float(loss_components[3])],\n                        [\"Batch loss\", to_cpu(loss).item()],\n                    ]).table)\n\n            # Tensorboard logging\n            tensorboard_log = [\n                (\"train/iou_loss\", float(loss_components[0])),\n                (\"train/obj_loss\", float(loss_components[1])),\n                (\"train/class_loss\", float(loss_components[2])),\n                (\"train/loss\", to_cpu(loss).item())]\n            logger.list_of_scalars_summary(tensorboard_log, batches_done)\n\n            model.seen += imgs.size(0)\n\n        # #############\n        # Save progress\n        # #############\n\n        # Save model to checkpoint file\n        if epoch % args.checkpoint_interval == 0:\n            checkpoint_path = f\"checkpoints/yolov3_ckpt_{epoch}.pth\"\n            print(f\"---- Saving checkpoint to: '{checkpoint_path}' ----\")\n            torch.save(model.state_dict(), checkpoint_path)\n\n        # ########\n        # Evaluate\n        # ########\n\n        if epoch % args.evaluation_interval == 0:\n            print(\"\\n---- Evaluating Model ----\")\n            # Evaluate the model on the validation set\n            metrics_output = _evaluate(\n                model,\n                validation_dataloader,\n                class_names,\n                img_size=model.hyperparams['height'],\n                iou_thres=args.iou_thres,\n                conf_thres=args.conf_thres,\n                nms_thres=args.nms_thres,\n                verbose=args.verbose\n            )\n\n            if metrics_output is not None:\n                precision, recall, AP, f1, ap_class = metrics_output\n                evaluation_metrics = [\n                    (\"validation/precision\", precision.mean()),\n                    (\"validation/recall\", recall.mean()),\n                    (\"validation/mAP\", AP.mean()),\n                    (\"validation/f1\", f1.mean())]\n                logger.list_of_scalars_summary(evaluation_metrics, epoch)\n\n\nif __name__ == \"__main__\":\n    run()\n"
  },
  {
    "path": "pytorchyolo/utils/__init__.py",
    "content": ""
  },
  {
    "path": "pytorchyolo/utils/augmentations.py",
    "content": "import imgaug.augmenters as iaa\nfrom torchvision import transforms\nfrom pytorchyolo.utils.transforms import ToTensor, PadSquare, RelativeLabels, AbsoluteLabels, ImgAug\n\n\nclass DefaultAug(ImgAug):\n    def __init__(self, ):\n        self.augmentations = iaa.Sequential([\n            iaa.Sharpen((0.0, 0.1)),\n            iaa.Affine(rotate=(-0, 0), translate_percent=(-0.1, 0.1), scale=(0.8, 1.5)),\n            iaa.AddToBrightness((-60, 40)),\n            iaa.AddToHue((-10, 10)),\n            iaa.Fliplr(0.5),\n        ])\n\n\nclass StrongAug(ImgAug):\n    def __init__(self, ):\n        self.augmentations = iaa.Sequential([\n            iaa.Dropout([0.0, 0.01]),\n            iaa.Sharpen((0.0, 0.1)),\n            iaa.Affine(rotate=(-10, 10), translate_percent=(-0.1, 0.1), scale=(0.8, 1.5)),\n            iaa.AddToBrightness((-60, 40)),\n            iaa.AddToHue((-20, 20)),\n            iaa.Fliplr(0.5),\n        ])\n\n\nAUGMENTATION_TRANSFORMS = transforms.Compose([\n    AbsoluteLabels(),\n    DefaultAug(),\n    PadSquare(),\n    RelativeLabels(),\n    ToTensor(),\n])\n"
  },
  {
    "path": "pytorchyolo/utils/datasets.py",
    "content": "from torch.utils.data import Dataset\nimport torch.nn.functional as F\nimport torch\nimport glob\nimport random\nimport os\nimport warnings\nimport numpy as np\nfrom PIL import Image\nfrom PIL import ImageFile\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\ndef pad_to_square(img, pad_value):\n    c, h, w = img.shape\n    dim_diff = np.abs(h - w)\n    # (upper / left) padding and (lower / right) padding\n    pad1, pad2 = dim_diff // 2, dim_diff - dim_diff // 2\n    # Determine padding\n    pad = (0, 0, pad1, pad2) if h <= w else (pad1, pad2, 0, 0)\n    # Add padding\n    img = F.pad(img, pad, \"constant\", value=pad_value)\n\n    return img, pad\n\n\ndef resize(image, size):\n    image = F.interpolate(image.unsqueeze(0), size=size, mode=\"nearest\").squeeze(0)\n    return image\n\n\nclass ImageFolder(Dataset):\n    def __init__(self, folder_path, transform=None):\n        self.files = sorted(glob.glob(\"%s/*.*\" % folder_path))\n        self.transform = transform\n\n    def __getitem__(self, index):\n\n        img_path = self.files[index % len(self.files)]\n        img = np.array(\n            Image.open(img_path).convert('RGB'),\n            dtype=np.uint8)\n\n        # Label Placeholder\n        boxes = np.zeros((1, 5))\n\n        # Apply transforms\n        if self.transform:\n            img, _ = self.transform((img, boxes))\n\n        return img_path, img\n\n    def __len__(self):\n        return len(self.files)\n\n\nclass ListDataset(Dataset):\n    def __init__(self, list_path, img_size=416, multiscale=True, transform=None):\n        with open(list_path, \"r\") as file:\n            self.img_files = file.readlines()\n\n        self.label_files = []\n        for path in self.img_files:\n            image_dir = os.path.dirname(path)\n            label_dir = \"labels\".join(image_dir.rsplit(\"images\", 1))\n            assert label_dir != image_dir, \\\n                f\"Image path must contain a folder named 'images'! \\n'{image_dir}'\"\n            label_file = os.path.join(label_dir, os.path.basename(path))\n            label_file = os.path.splitext(label_file)[0] + '.txt'\n            self.label_files.append(label_file)\n\n        self.img_size = img_size\n        self.max_objects = 100\n        self.multiscale = multiscale\n        self.min_size = self.img_size - 3 * 32\n        self.max_size = self.img_size + 3 * 32\n        self.batch_count = 0\n        self.transform = transform\n\n    def __getitem__(self, index):\n\n        # ---------\n        #  Image\n        # ---------\n        try:\n\n            img_path = self.img_files[index % len(self.img_files)].rstrip()\n\n            img = np.array(Image.open(img_path).convert('RGB'), dtype=np.uint8)\n        except Exception:\n            print(f\"Could not read image '{img_path}'.\")\n            return\n\n        # ---------\n        #  Label\n        # ---------\n        try:\n            label_path = self.label_files[index % len(self.img_files)].rstrip()\n\n            # Ignore warning if file is empty\n            with warnings.catch_warnings():\n                warnings.simplefilter(\"ignore\")\n                boxes = np.loadtxt(label_path).reshape(-1, 5)\n        except Exception:\n            print(f\"Could not read label '{label_path}'.\")\n            return\n\n        # -----------\n        #  Transform\n        # -----------\n        if self.transform:\n            try:\n                img, bb_targets = self.transform((img, boxes))\n            except Exception:\n                print(\"Could not apply transform.\")\n                return\n\n        return img_path, img, bb_targets\n\n    def collate_fn(self, batch):\n        self.batch_count += 1\n\n        # Drop invalid images\n        batch = [data for data in batch if data is not None]\n\n        paths, imgs, bb_targets = list(zip(*batch))\n\n        # Selects new image size every tenth batch\n        if self.multiscale and self.batch_count % 10 == 0:\n            self.img_size = random.choice(\n                range(self.min_size, self.max_size + 1, 32))\n\n        # Resize images to input shape\n        imgs = torch.stack([resize(img, self.img_size) for img in imgs])\n\n        # Add sample index to targets\n        for i, boxes in enumerate(bb_targets):\n            boxes[:, 0] = i\n        bb_targets = torch.cat(bb_targets, 0)\n\n        return paths, imgs, bb_targets\n\n    def __len__(self):\n        return len(self.img_files)\n"
  },
  {
    "path": "pytorchyolo/utils/logger.py",
    "content": "import os\nimport datetime\nfrom torch.utils.tensorboard import SummaryWriter\n\n\nclass Logger(object):\n    def __init__(self, log_dir, log_hist=True):\n        \"\"\"Create a summary writer logging to log_dir.\"\"\"\n        if log_hist:    # Check a new folder for each log should be dreated\n            log_dir = os.path.join(\n                log_dir,\n                datetime.datetime.now().strftime(\"%Y_%m_%d__%H_%M_%S\"))\n        self.writer = SummaryWriter(log_dir)\n\n    def scalar_summary(self, tag, value, step):\n        \"\"\"Log a scalar variable.\"\"\"\n        self.writer.add_scalar(tag, value, step)\n\n    def list_of_scalars_summary(self, tag_value_pairs, step):\n        \"\"\"Log scalar variables.\"\"\"\n        for tag, value in tag_value_pairs:\n            self.writer.add_scalar(tag, value, step)\n"
  },
  {
    "path": "pytorchyolo/utils/loss.py",
    "content": "import math\n\nimport torch\nimport torch.nn as nn\n\nfrom .utils import to_cpu\n\n# This new loss function is based on https://github.com/ultralytics/yolov3/blob/master/utils/loss.py\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 compute_loss(predictions, targets, model):\n    # Check which device was used\n    device = targets.device\n\n    # Add placeholder varables for the different losses\n    lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)\n\n    # Build yolo targets\n    tcls, tbox, indices, anchors = build_targets(predictions, targets, model)  # targets\n\n    # Define different loss functions classification\n    BCEcls = nn.BCEWithLogitsLoss(\n        pos_weight=torch.tensor([1.0], device=device))\n    BCEobj = nn.BCEWithLogitsLoss(\n        pos_weight=torch.tensor([1.0], device=device))\n\n    # Calculate losses for each yolo layer\n    for layer_index, layer_predictions in enumerate(predictions):\n        # Get image ids, anchors, grid index i and j for each target in the current yolo layer\n        b, anchor, grid_j, grid_i = indices[layer_index]\n        # Build empty object target tensor with the same shape as the object prediction\n        tobj = torch.zeros_like(layer_predictions[..., 0], device=device)  # target obj\n        # Get the number of targets for this layer.\n        # Each target is a label box with some scaling and the association of an anchor box.\n        # Label boxes may be associated to 0 or multiple anchors. So they are multiple times or not at all in the targets.\n        num_targets = b.shape[0]\n        # Check if there are targets for this batch\n        if num_targets:\n            # Load the corresponding values from the predictions for each of the targets\n            ps = layer_predictions[b, anchor, grid_j, grid_i]\n\n            # Regression of the box\n            # Apply sigmoid to xy offset predictions in each cell that has a target\n            pxy = ps[:, :2].sigmoid()\n            # Apply exponent to wh predictions and multiply with the anchor box that matched best with the label for each cell that has a target\n            pwh = torch.exp(ps[:, 2:4]) * anchors[layer_index]\n            # Build box out of xy and wh\n            pbox = torch.cat((pxy, pwh), 1)\n            # Calculate CIoU or GIoU for each target with the predicted box for its cell + anchor\n            iou = bbox_iou(pbox.T, tbox[layer_index], x1y1x2y2=False, CIoU=True)\n            # We want to minimize our loss so we and the best possible IoU is 1 so we take 1 - IoU and reduce it with a mean\n            lbox += (1.0 - iou).mean()  # iou loss\n\n            # Classification of the objectness\n            # Fill our empty object target tensor with the IoU we just calculated for each target at the targets position\n            tobj[b, anchor, grid_j, grid_i] = iou.detach().clamp(0).type(tobj.dtype)  # Use cells with iou > 0 as object targets\n\n            # Classification of the class\n            # Check if we need to do a classification (number of classes > 1)\n            if ps.size(1) - 5 > 1:\n                # Hot one class encoding\n                t = torch.zeros_like(ps[:, 5:], device=device)  # targets\n                t[range(num_targets), tcls[layer_index]] = 1\n                # Use the tensor to calculate the BCE loss\n                lcls += BCEcls(ps[:, 5:], t)  # BCE\n\n        # Classification of the objectness the sequel\n        # Calculate the BCE loss between the on the fly generated target and the network prediction\n        lobj += BCEobj(layer_predictions[..., 4], tobj) # obj loss\n\n    lbox *= 0.05\n    lobj *= 1.0\n    lcls *= 0.5\n\n    # Merge losses\n    loss = lbox + lobj + lcls\n\n    return loss, to_cpu(torch.cat((lbox, lobj, lcls, loss)))\n\n\ndef build_targets(p, targets, model):\n    # Build targets for compute_loss(), input targets(image,class,x,y,w,h)\n    na, nt = 3, targets.shape[0]  # number of anchors, targets #TODO\n    tcls, tbox, indices, anch = [], [], [], []\n    gain = torch.ones(7, device=targets.device)  # normalized to gridspace gain\n    # Make a tensor that iterates 0-2 for 3 anchors and repeat that as many times as we have target boxes\n    ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt)\n    # Copy target boxes anchor size times and append an anchor index to each copy the anchor index is also expressed by the new first dimension\n    targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2)\n\n    for i, yolo_layer in enumerate(model.yolo_layers):\n        # Scale anchors by the yolo grid cell size so that an anchor with the size of the cell would result in 1\n        anchors = yolo_layer.anchors / yolo_layer.stride\n        # Add the number of yolo cells in this layer the gain tensor\n        # The gain tensor matches the collums of our targets (img id, class, x, y, w, h, anchor id)\n        gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]]  # xyxy gain\n        # Scale targets by the number of yolo layer cells, they are now in the yolo cell coordinate system\n        t = targets * gain\n        # Check if we have targets\n        if nt:\n            # Calculate ration between anchor and target box for both width and height\n            r = t[:, :, 4:6] / anchors[:, None]\n            # Select the ratios that have the highest divergence in any axis and check if the ratio is less than 4\n            j = torch.max(r, 1. / r).max(2)[0] < 4  # compare #TODO\n            # Only use targets that have the correct ratios for their anchors\n            # That means we only keep ones that have a matching anchor and we loose the anchor dimension\n            # The anchor id is still saved in the 7th value of each target\n            t = t[j]\n        else:\n            t = targets[0]\n\n        # Extract image id in batch and class id\n        b, c = t[:, :2].long().T\n        # We isolate the target cell associations.\n        # x, y, w, h are allready in the cell coordinate system meaning an x = 1.2 would be 1.2 times cellwidth\n        gxy = t[:, 2:4]\n        gwh = t[:, 4:6]  # grid wh\n        # Cast to int to get an cell index e.g. 1.2 gets associated to cell 1\n        gij = gxy.long()\n        # Isolate x and y index dimensions\n        gi, gj = gij.T  # grid xy indices\n\n        # Convert anchor indexes to int\n        a = t[:, 6].long()\n        # Add target tensors for this yolo layer to the output lists\n        # Add to index list and limit index range to prevent out of bounds\n        indices.append((b, a, gj.clamp_(0, gain[3].long() - 1), gi.clamp_(0, gain[2].long() - 1)))\n        # Add to target box list and convert box coordinates from global grid coordinates to local offsets in the grid cell\n        tbox.append(torch.cat((gxy - gij, gwh), 1))  # box\n        # Add correct anchor for each target to the list\n        anch.append(anchors[a])\n        # Add class for each target to the list\n        tcls.append(c)\n\n    return tcls, tbox, indices, anch\n"
  },
  {
    "path": "pytorchyolo/utils/parse_config.py",
    "content": "\n\ndef parse_model_config(path):\n    \"\"\"Parses the yolo-v3 layer configuration file and returns module definitions\"\"\"\n    file = open(path, 'r')\n    lines = file.read().split('\\n')\n    lines = [x for x in lines if x and not x.startswith('#')]\n    lines = [x.rstrip().lstrip() for x in lines]  # get rid of fringe whitespaces\n    module_defs = []\n    for line in lines:\n        if line.startswith('['):  # This marks the start of a new block\n            module_defs.append({})\n            module_defs[-1]['type'] = line[1:-1].rstrip()\n            if module_defs[-1]['type'] == 'convolutional':\n                module_defs[-1]['batch_normalize'] = 0\n        else:\n            key, value = line.split(\"=\")\n            value = value.strip()\n            module_defs[-1][key.rstrip()] = value.strip()\n\n    return module_defs\n\n\ndef parse_data_config(path):\n    \"\"\"Parses the data configuration file\"\"\"\n    options = dict()\n    options['gpus'] = '0,1,2,3'\n    options['num_workers'] = '10'\n    with open(path, 'r') as fp:\n        lines = fp.readlines()\n    for line in lines:\n        line = line.strip()\n        if line == '' or line.startswith('#'):\n            continue\n        key, value = line.split('=')\n        options[key.strip()] = value.strip()\n    return options\n"
  },
  {
    "path": "pytorchyolo/utils/transforms.py",
    "content": "import torch\nimport torch.nn.functional as F\nimport numpy as np\n\nimport imgaug.augmenters as iaa\nfrom imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage\n\nfrom .utils import xywh2xyxy_np\nimport torchvision.transforms as transforms\n\n\nclass ImgAug(object):\n    def __init__(self, augmentations=[]):\n        self.augmentations = augmentations\n\n    def __call__(self, data):\n        # Unpack data\n        img, boxes = data\n\n        # Convert xywh to xyxy\n        boxes = np.array(boxes)\n        boxes[:, 1:] = xywh2xyxy_np(boxes[:, 1:])\n\n        # Convert bounding boxes to imgaug\n        bounding_boxes = BoundingBoxesOnImage(\n            [BoundingBox(*box[1:], label=box[0]) for box in boxes],\n            shape=img.shape)\n\n        # Apply augmentations\n        img, bounding_boxes = self.augmentations(\n            image=img,\n            bounding_boxes=bounding_boxes)\n\n        # Clip out of image boxes\n        bounding_boxes = bounding_boxes.clip_out_of_image()\n\n        # Convert bounding boxes back to numpy\n        boxes = np.zeros((len(bounding_boxes), 5))\n        for box_idx, box in enumerate(bounding_boxes):\n            # Extract coordinates for unpadded + unscaled image\n            x1 = box.x1\n            y1 = box.y1\n            x2 = box.x2\n            y2 = box.y2\n\n            # Returns (x, y, w, h)\n            boxes[box_idx, 0] = box.label\n            boxes[box_idx, 1] = ((x1 + x2) / 2)\n            boxes[box_idx, 2] = ((y1 + y2) / 2)\n            boxes[box_idx, 3] = (x2 - x1)\n            boxes[box_idx, 4] = (y2 - y1)\n\n        return img, boxes\n\n\nclass RelativeLabels(object):\n    def __init__(self, ):\n        pass\n\n    def __call__(self, data):\n        img, boxes = data\n        h, w, _ = img.shape\n        boxes[:, [1, 3]] /= w\n        boxes[:, [2, 4]] /= h\n        return img, boxes\n\n\nclass AbsoluteLabels(object):\n    def __init__(self, ):\n        pass\n\n    def __call__(self, data):\n        img, boxes = data\n        h, w, _ = img.shape\n        boxes[:, [1, 3]] *= w\n        boxes[:, [2, 4]] *= h\n        return img, boxes\n\n\nclass PadSquare(ImgAug):\n    def __init__(self, ):\n        self.augmentations = iaa.Sequential([\n            iaa.PadToAspectRatio(\n                1.0,\n                position=\"center-center\").to_deterministic()\n        ])\n\n\nclass ToTensor(object):\n    def __init__(self, ):\n        pass\n\n    def __call__(self, data):\n        img, boxes = data\n        # Extract image as PyTorch tensor\n        img = transforms.ToTensor()(img)\n\n        bb_targets = torch.zeros((len(boxes), 6))\n        bb_targets[:, 1:] = transforms.ToTensor()(boxes)\n\n        return img, bb_targets\n\n\nclass Resize(object):\n    def __init__(self, size):\n        self.size = size\n\n    def __call__(self, data):\n        img, boxes = data\n        img = F.interpolate(img.unsqueeze(0), size=self.size, mode=\"nearest\").squeeze(0)\n        return img, boxes\n\n\nDEFAULT_TRANSFORMS = transforms.Compose([\n    AbsoluteLabels(),\n    PadSquare(),\n    RelativeLabels(),\n    ToTensor(),\n])\n"
  },
  {
    "path": "pytorchyolo/utils/utils.py",
    "content": "from __future__ import division\n\nimport time\nimport platform\nimport tqdm\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport numpy as np\nimport subprocess\nimport random\nimport imgaug as ia\n\n\ndef provide_determinism(seed=42):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n    ia.seed(seed)\n\n    torch.backends.cudnn.benchmark = False\n    torch.backends.cudnn.deterministic = True\n\n\ndef worker_seed_set(worker_id):\n    # See for details of numpy:\n    # https://github.com/pytorch/pytorch/issues/5059#issuecomment-817392562\n    # See for details of random:\n    # https://pytorch.org/docs/stable/notes/randomness.html#dataloader\n\n    # NumPy\n    uint64_seed = torch.initial_seed()\n    ss = np.random.SeedSequence([uint64_seed])\n    np.random.seed(ss.generate_state(4))\n\n    # random\n    worker_seed = torch.initial_seed() % 2**32\n    random.seed(worker_seed)\n\n\ndef to_cpu(tensor):\n    return tensor.detach().cpu()\n\n\ndef load_classes(path):\n    \"\"\"\n    Loads class labels at 'path'\n    \"\"\"\n    with open(path, \"r\") as fp:\n        names = fp.read().splitlines()\n    return names\n\n\ndef weights_init_normal(m):\n    classname = m.__class__.__name__\n    if classname.find(\"Conv\") != -1:\n        nn.init.normal_(m.weight.data, 0.0, 0.02)\n    elif classname.find(\"BatchNorm2d\") != -1:\n        nn.init.normal_(m.weight.data, 1.0, 0.02)\n        nn.init.constant_(m.bias.data, 0.0)\n\n\ndef rescale_boxes(boxes, current_dim, original_shape):\n    \"\"\"\n    Rescales bounding boxes to the original shape\n    \"\"\"\n    orig_h, orig_w = original_shape\n\n    # The amount of padding that was added\n    pad_x = max(orig_h - orig_w, 0) * (current_dim / max(original_shape))\n    pad_y = max(orig_w - orig_h, 0) * (current_dim / max(original_shape))\n\n    # Image height and width after padding is removed\n    unpad_h = current_dim - pad_y\n    unpad_w = current_dim - pad_x\n\n    # Rescale bounding boxes to dimension of original image\n    boxes[:, 0] = ((boxes[:, 0] - pad_x // 2) / unpad_w) * orig_w\n    boxes[:, 1] = ((boxes[:, 1] - pad_y // 2) / unpad_h) * orig_h\n    boxes[:, 2] = ((boxes[:, 2] - pad_x // 2) / unpad_w) * orig_w\n    boxes[:, 3] = ((boxes[:, 3] - pad_y // 2) / unpad_h) * orig_h\n    return boxes\n\n\ndef xywh2xyxy(x):\n    y = x.new(x.shape)\n    y[..., 0] = x[..., 0] - x[..., 2] / 2\n    y[..., 1] = x[..., 1] - x[..., 3] / 2\n    y[..., 2] = x[..., 0] + x[..., 2] / 2\n    y[..., 3] = x[..., 1] + x[..., 3] / 2\n    return y\n\n\ndef xywh2xyxy_np(x):\n    y = np.zeros_like(x)\n    y[..., 0] = x[..., 0] - x[..., 2] / 2\n    y[..., 1] = x[..., 1] - x[..., 3] / 2\n    y[..., 2] = x[..., 0] + x[..., 2] / 2\n    y[..., 3] = x[..., 1] + x[..., 3] / 2\n    return y\n\n\ndef ap_per_class(tp, conf, pred_cls, target_cls):\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 (list).\n        conf:  Objectness value from 0-1 (list).\n        pred_cls: Predicted object classes (list).\n        target_cls: True object classes (list).\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    ap, p, r = [], [], []\n    for c in tqdm.tqdm(unique_classes, desc=\"Computing AP\"):\n        i = pred_cls == c\n        n_gt = (target_cls == c).sum()  # Number of ground truth objects\n        n_p = i.sum()  # Number of predicted objects\n\n        if n_p == 0 and n_gt == 0:\n            continue\n        elif n_p == 0 or n_gt == 0:\n            ap.append(0)\n            r.append(0)\n            p.append(0)\n        else:\n            # Accumulate FPs and TPs\n            fpc = (1 - tp[i]).cumsum()\n            tpc = (tp[i]).cumsum()\n\n            # Recall\n            recall_curve = tpc / (n_gt + 1e-16)\n            r.append(recall_curve[-1])\n\n            # Precision\n            precision_curve = tpc / (tpc + fpc)\n            p.append(precision_curve[-1])\n\n            # AP from recall-precision curve\n            ap.append(compute_ap(recall_curve, precision_curve))\n\n    # Compute F1 score (harmonic mean of precision and recall)\n    p, r, ap = np.array(p), np.array(r), np.array(ap)\n    f1 = 2 * p * r / (p + r + 1e-16)\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    Code originally from https://github.com/rbgirshick/py-faster-rcnn.\n\n    # Arguments\n        recall:    The recall curve (list).\n        precision: The precision curve (list).\n    # Returns\n        The average precision as computed in py-faster-rcnn.\n    \"\"\"\n    # correct AP calculation\n    # first append sentinel values at the end\n    mrec = np.concatenate(([0.0], recall, [1.0]))\n    mpre = np.concatenate(([0.0], precision, [0.0]))\n\n    # compute the precision envelope\n    for i in range(mpre.size - 1, 0, -1):\n        mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n    # to calculate area under PR curve, look for points\n    # where X axis (recall) changes value\n    i = np.where(mrec[1:] != mrec[:-1])[0]\n\n    # and sum (\\Delta recall) * prec\n    ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n    return ap\n\n\ndef get_batch_statistics(outputs, targets, iou_threshold):\n    \"\"\" Compute true positives, predicted scores and predicted labels per sample \"\"\"\n    batch_metrics = []\n    for sample_i in range(len(outputs)):\n\n        if outputs[sample_i] is None:\n            continue\n\n        output = outputs[sample_i]\n        pred_boxes = output[:, :4]\n        pred_scores = output[:, 4]\n        pred_labels = output[:, -1]\n\n        true_positives = np.zeros(pred_boxes.shape[0])\n\n        annotations = targets[targets[:, 0] == sample_i][:, 1:]\n        target_labels = annotations[:, 0] if len(annotations) else []\n        if len(annotations):\n            detected_boxes = []\n            target_boxes = annotations[:, 1:]\n\n            for pred_i, (pred_box, pred_label) in enumerate(zip(pred_boxes, pred_labels)):\n\n                # If targets are found break\n                if len(detected_boxes) == len(annotations):\n                    break\n\n                # Ignore if label is not one of the target labels\n                if pred_label not in target_labels:\n                    continue\n\n                # Filter target_boxes by pred_label so that we only match against boxes of our own label\n                filtered_target_position, filtered_targets = zip(*filter(lambda x: target_labels[x[0]] == pred_label, enumerate(target_boxes)))\n\n                # Find the best matching target for our predicted box\n                iou, box_filtered_index = bbox_iou(pred_box.unsqueeze(0), torch.stack(filtered_targets)).max(0)\n\n                # Remap the index in the list of filtered targets for that label to the index in the list with all targets.\n                box_index = filtered_target_position[box_filtered_index]\n\n                # Check if the iou is above the min treshold and i\n                if iou >= iou_threshold and box_index not in detected_boxes:\n                    true_positives[pred_i] = 1\n                    detected_boxes += [box_index]\n        batch_metrics.append([true_positives, pred_scores, pred_labels])\n    return batch_metrics\n\n\ndef bbox_wh_iou(wh1, wh2):\n    wh2 = wh2.t()\n    w1, h1 = wh1[0], wh1[1]\n    w2, h2 = wh2[0], wh2[1]\n    inter_area = torch.min(w1, w2) * torch.min(h1, h2)\n    union_area = (w1 * h1 + 1e-16) + w2 * h2 - inter_area\n    return inter_area / union_area\n\n\ndef bbox_iou(box1, box2, x1y1x2y2=True):\n    \"\"\"\n    Returns the IoU of two bounding boxes\n    \"\"\"\n    if not x1y1x2y2:\n        # Transform from center and width to exact coordinates\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    else:\n        # Get the coordinates of bounding boxes\n        b1_x1, b1_y1, b1_x2, b1_y2 = \\\n            box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]\n        b2_x1, b2_y1, b2_x2, b2_y2 = \\\n            box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]\n\n    # get the corrdinates of the intersection rectangle\n    inter_rect_x1 = torch.max(b1_x1, b2_x1)\n    inter_rect_y1 = torch.max(b1_y1, b2_y1)\n    inter_rect_x2 = torch.min(b1_x2, b2_x2)\n    inter_rect_y2 = torch.min(b1_y2, b2_y2)\n    # Intersection area\n    inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1 + 1, min=0) * torch.clamp(\n        inter_rect_y2 - inter_rect_y1 + 1, min=0\n    )\n    # Union Area\n    b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1)\n    b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1)\n\n    iou = inter_area / (b1_area + b2_area - inter_area + 1e-16)\n\n    return 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 non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None):\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] - 5  # number of classes\n\n    # Settings\n    # (pixels) minimum and maximum box width and height\n    max_wh = 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 = 1.0  # seconds to quit after\n    multi_label = nc > 1  # multiple labels per box (adds 0.5ms/img)\n\n    t = time.time()\n    output = [torch.zeros((0, 6), device=\"cpu\")] * prediction.shape[0]\n\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[x[..., 4] > conf_thres]  # confidence\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)[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        # 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            # sort by confidence\n            x = x[x[:, 4].argsort(descending=True)[:max_nms]]\n\n        # Batched NMS\n        c = x[:, 5:6] * max_wh  # classes\n        # boxes (offset by class), scores\n        boxes, scores = x[:, :4] + c, x[:, 4]\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\n        output[xi] = to_cpu(x[i])\n\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 print_environment_info():\n    \"\"\"\n    Prints infos about the environment and the system.\n    This should help when people make issues containg the printout.\n    \"\"\"\n\n    print(\"Environment information:\")\n\n    # Print OS information\n    print(f\"System: {platform.system()} {platform.release()}\")\n\n    # Print poetry package version\n    try:\n        print(f\"Current Version: {subprocess.check_output(['poetry', 'version'], stderr=subprocess.DEVNULL).decode('ascii').strip()}\")\n    except (subprocess.CalledProcessError, FileNotFoundError):\n        print(\"Not using the poetry package\")\n\n    # Print commit hash if possible\n    try:\n        print(f\"Current Commit Hash: {subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], stderr=subprocess.DEVNULL).decode('ascii').strip()}\")\n    except (subprocess.CalledProcessError, FileNotFoundError):\n        print(\"No git or repo found\")\n"
  },
  {
    "path": "weights/download_weights.sh",
    "content": "#!/bin/bash\n# Download weights for vanilla YOLOv3\nwget -c \"https://pjreddie.com/media/files/yolov3.weights\" --header \"Referer: pjreddie.com\"\n# # Download weights for tiny YOLOv3\nwget -c \"https://pjreddie.com/media/files/yolov3-tiny.weights\" --header \"Referer: pjreddie.com\"\n# Download weights for backbone network\nwget -c \"https://pjreddie.com/media/files/darknet53.conv.74\" --header \"Referer: pjreddie.com\"\n"
  }
]