[
  {
    "path": ".gitignore",
    "content": "*.pyc\n*.pyo\n*.pyd\n.DS_Store\n.idea\nweights\nbuild/\n*.egg-info/\ngradio_cached_examples"
  },
  {
    "path": "Inference.py",
    "content": "import argparse\r\nfrom fastsam import FastSAM, FastSAMPrompt \r\nimport ast\r\nimport torch\r\nfrom PIL import Image\r\nfrom utils.tools import convert_box_xywh_to_xyxy\r\n\r\n\r\ndef parse_args():\r\n    parser = argparse.ArgumentParser()\r\n    parser.add_argument(\r\n        \"--model_path\", type=str, default=\"./weights/FastSAM.pt\", help=\"model\"\r\n    )\r\n    parser.add_argument(\r\n        \"--img_path\", type=str, default=\"./images/dogs.jpg\", help=\"path to image file\"\r\n    )\r\n    parser.add_argument(\"--imgsz\", type=int, default=1024, help=\"image size\")\r\n    parser.add_argument(\r\n        \"--iou\",\r\n        type=float,\r\n        default=0.9,\r\n        help=\"iou threshold for filtering the annotations\",\r\n    )\r\n    parser.add_argument(\r\n        \"--text_prompt\", type=str, default=None, help='use text prompt eg: \"a dog\"'\r\n    )\r\n    parser.add_argument(\r\n        \"--conf\", type=float, default=0.4, help=\"object confidence threshold\"\r\n    )\r\n    parser.add_argument(\r\n        \"--output\", type=str, default=\"./output/\", help=\"image save path\"\r\n    )\r\n    parser.add_argument(\r\n        \"--randomcolor\", type=bool, default=True, help=\"mask random color\"\r\n    )\r\n    parser.add_argument(\r\n        \"--point_prompt\", type=str, default=\"[[0,0]]\", help=\"[[x1,y1],[x2,y2]]\"\r\n    )\r\n    parser.add_argument(\r\n        \"--point_label\",\r\n        type=str,\r\n        default=\"[0]\",\r\n        help=\"[1,0] 0:background, 1:foreground\",\r\n    )\r\n    parser.add_argument(\"--box_prompt\", type=str, default=\"[[0,0,0,0]]\", help=\"[[x,y,w,h],[x2,y2,w2,h2]] support multiple boxes\")\r\n    parser.add_argument(\r\n        \"--better_quality\",\r\n        type=str,\r\n        default=False,\r\n        help=\"better quality using morphologyEx\",\r\n    )\r\n    device = torch.device(\r\n        \"cuda\"\r\n        if torch.cuda.is_available()\r\n        else \"mps\"\r\n        if torch.backends.mps.is_available()\r\n        else \"cpu\"\r\n    )\r\n    parser.add_argument(\r\n        \"--device\", type=str, default=device, help=\"cuda:[0,1,2,3,4] or cpu\"\r\n    )\r\n    parser.add_argument(\r\n        \"--retina\",\r\n        type=bool,\r\n        default=True,\r\n        help=\"draw high-resolution segmentation masks\",\r\n    )\r\n    parser.add_argument(\r\n        \"--withContours\", type=bool, default=False, help=\"draw the edges of the masks\"\r\n    )\r\n    return parser.parse_args()\r\n\r\n\r\ndef main(args):\r\n    # load model\r\n    model = FastSAM(args.model_path)\r\n    args.point_prompt = ast.literal_eval(args.point_prompt)\r\n    args.box_prompt = convert_box_xywh_to_xyxy(ast.literal_eval(args.box_prompt))\r\n    args.point_label = ast.literal_eval(args.point_label)\r\n    input = Image.open(args.img_path)\r\n    input = input.convert(\"RGB\")\r\n    everything_results = model(\r\n        input,\r\n        device=args.device,\r\n        retina_masks=args.retina,\r\n        imgsz=args.imgsz,\r\n        conf=args.conf,\r\n        iou=args.iou    \r\n        )\r\n    bboxes = None\r\n    points = None\r\n    point_label = None\r\n    prompt_process = FastSAMPrompt(input, everything_results, device=args.device)\r\n    if args.box_prompt[0][2] != 0 and args.box_prompt[0][3] != 0:\r\n            ann = prompt_process.box_prompt(bboxes=args.box_prompt)\r\n            bboxes = args.box_prompt\r\n    elif args.text_prompt != None:\r\n        ann = prompt_process.text_prompt(text=args.text_prompt)\r\n    elif args.point_prompt[0] != [0, 0]:\r\n        ann = prompt_process.point_prompt(\r\n            points=args.point_prompt, pointlabel=args.point_label\r\n        )\r\n        points = args.point_prompt\r\n        point_label = args.point_label\r\n    else:\r\n        ann = prompt_process.everything_prompt()\r\n    prompt_process.plot(\r\n        annotations=ann,\r\n        output_path=args.output+args.img_path.split(\"/\")[-1],\r\n        bboxes = bboxes,\r\n        points = points,\r\n        point_label = point_label,\r\n        withContours=args.withContours,\r\n        better_quality=args.better_quality,\r\n    )\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    args = parse_args()\r\n    main(args)\r\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "MORE_USAGES.md",
    "content": "# MORE_USAGES\n\n\n\n### Everything mode\nUse --imgsz to change different input sizes.\n\n```shell\npython Inference.py --model_path ./weights/FastSAM.pt \\\n                    --img_path ./images/dogs.jpg \\\n                    --imgsz 720 \\\n```\n![everything mode](assets/more_usages/everything_mode.png)\n\n\n\n### Use more points\np\n```shell\npython Inference.py --model_path ./weights/FastSAM.pt \\\n                    --img_path ./images/dogs.jpg \\\n                    --point_prompt \"[[520,360],[620,300],[520,300],[620,360]]\" \\\n                    --point_label \"[1,0,1,0]\"\n```\n![points prompt](assets/more_usages/more_points.png)\n### draw mask edge\nUse `--withContours True` to draw the edge of the mask.\n\nWhen `--better_quality True` is set, the edge will be more smooth.\n\n```shell\npython Inference.py --model_path ./weights/FastSAM.pt \\\n                    --img_path ./images/dogs.jpg \\\n                    --point_prompt \"[[620,360]]\" \\\n                    --point_label \"[1]\" \\\n                    --withContours True \\\n                    --better_quality True\n```\n\n![Draw Edge](assets/more_usages/draw_edge.png)\n### use box prompt\nUse `--box_prompt [x,y,w,h]` to specify the bounding box of the foreground object\n```shell\npython Inference.py --model_path ./weights/FastSAM.pt \\\n                    --img_path ./images/dogs.jpg \\\n                    --box_prompt \"[[570,200,230,400]]\"\n```\n![box prompt](assets/more_usages/box_prompt.png)\n\n### use text prompt\nUse `--text_prompt \"text\"` to specify the text prompt\n```shell\npython Inference.py --model_path ./weights/FastSAM.pt \\\n                    --img_path ./images/cat.jpg \\\n                    --text_prompt \"cat\" \\\n                    --better_quality True \\\n                    --withContours True \n```\n![text prompt](assets/more_usages/text_prompt_cat.png)\n"
  },
  {
    "path": "README.md",
    "content": "![](assets/logo.png)\r\n\r\n# Fast Segment Anything\r\n\r\n[[`📕Paper`](https://arxiv.org/pdf/2306.12156.pdf)] [[`🤗HuggingFace Demo`](https://huggingface.co/spaces/An-619/FastSAM)] [[`Colab demo`](https://colab.research.google.com/drive/1oX14f6IneGGw612WgVlAiy91UHwFAvr9?usp=sharing)] [[`Replicate demo & API`](https://replicate.com/casia-iva-lab/fastsam)] [~~[`OpenXLab Demo`](https://openxlab.org.cn/apps/detail/zxair/FastSAM)~~] [[`Model Zoo`](#model-checkpoints)] [[`BibTeX`](#citing-fastsam)] [[`Video Demo`](https://youtu.be/yHNPyqazYYU)]\r\n\r\n![FastSAM Speed](assets/head_fig.png)\r\n\r\nThe **Fast Segment Anything Model(FastSAM)** is a CNN Segment Anything Model trained using only 2% of the SA-1B dataset published by SAM authors. FastSAM achieves comparable performance with\r\nthe SAM method at **50× higher run-time speed**.\r\n\r\n![FastSAM design](assets/Overview.png)\r\n\r\n**🍇 Updates**\r\n- **`2024/6/25`** The edge jaggies issue has been slightly improved [#231](https://github.com/CASIA-IVA-Lab/FastSAM/pull/231), and the strategy has also been synchronized to the ultralytics project[#13939](https://github.com/ultralytics/ultralytics/pull/13939),[#13912](https://github.com/ultralytics/ultralytics/pull/13912). The [huggingface demo](https://huggingface.co/spaces/An-619/FastSAM) is updated.\r\n- **`2023/11/28`** Recommendation: [Semantic FastSAM](https://github.com/KBH00/Semantic-Fast-SAM), which add the semantic class labels to FastSAM. Thanks to [KBH00](https://github.com/KBH00/Semantic-Fast-SAM) for this valuable contribution.\r\n- **`2023/09/11`** Release  [Training and Validation Code](https://github.com/CASIA-IVA-Lab/FastSAM/releases).\r\n- **`2023/08/17`** Release  [OpenXLab Demo](https://openxlab.org.cn/apps/detail/zxair/FastSAM). Thanks to OpenXLab Team for help.\r\n- **`2023/07/06`** Added to [Ultralytics (YOLOv8) Model Hub](https://docs.ultralytics.com/models/fast-sam/). Thanks to [Ultralytics](https://github.com/ultralytics/ultralytics) for help 🌹.\r\n- **`2023/06/29`** Support [text mode](https://huggingface.co/spaces/An-619/FastSAM) in HuggingFace Space. Thanks a lot to [gaoxinge](https://github.com/gaoxinge) for help 🌹.\r\n- **`2023/06/29`** Release [FastSAM_Awesome_TensorRT](https://github.com/ChuRuaNh0/FastSam_Awsome_TensorRT). Thanks a lot to [ChuRuaNh0](https://github.com/ChuRuaNh0) for providing the TensorRT model of FastSAM 🌹.\r\n- **`2023/06/26`** Release [FastSAM Replicate Online Demo](https://replicate.com/casia-iva-lab/fastsam). Thanks a lot to [Chenxi](https://chenxwh.github.io/) for providing this nice demo 🌹.\r\n- **`2023/06/26`** Support [points mode](https://huggingface.co/spaces/An-619/FastSAM) in HuggingFace Space. Better and faster interaction will come soon!\r\n- **`2023/06/24`** Thanks a lot to [Grounding-SAM](https://github.com/IDEA-Research/Grounded-Segment-Anything) for Combining Grounding-DINO with FastSAM in [Grounded-FastSAM](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM) 🌹.\r\n\r\n## Installation\r\n\r\nClone the repository locally:\r\n\r\n```shell\r\ngit clone https://github.com/CASIA-IVA-Lab/FastSAM.git\r\n```\r\n\r\nCreate the conda env. The code requires `python>=3.7`, as well as `pytorch>=1.7` and `torchvision>=0.8`. Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install both PyTorch and TorchVision dependencies. Installing both PyTorch and TorchVision with CUDA support is strongly recommended.\r\n\r\n```shell\r\nconda create -n FastSAM python=3.9\r\nconda activate FastSAM\r\n```\r\n\r\nInstall the packages:\r\n\r\n```shell\r\ncd FastSAM\r\npip install -r requirements.txt\r\n```\r\n\r\nInstall CLIP(Required if the text prompt is being tested.):\r\n\r\n```shell\r\npip install git+https://github.com/openai/CLIP.git\r\n```\r\n\r\n## <a name=\"GettingStarted\"></a> Getting Started\r\n\r\n\r\nFirst download a [model checkpoint](#model-checkpoints).\r\n\r\nThen, you can run the scripts to try the everything mode and three prompt modes.\r\n\r\n```shell\r\n# Everything mode\r\npython Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg\r\n```\r\n\r\n```shell\r\n# Text prompt\r\npython Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg  --text_prompt \"the yellow dog\"\r\n```\r\n\r\n```shell\r\n# Box prompt (xywh)\r\npython Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg --box_prompt \"[[570,200,230,400]]\"\r\n```\r\n\r\n```shell\r\n# Points prompt\r\npython Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg  --point_prompt \"[[520,360],[620,300]]\" --point_label \"[1,0]\"\r\n```\r\n\r\nYou can use the following code to generate all masks and visualize the results.\r\n```shell\r\nfrom fastsam import FastSAM, FastSAMPrompt\r\n\r\nmodel = FastSAM('./weights/FastSAM.pt')\r\nIMAGE_PATH = './images/dogs.jpg'\r\nDEVICE = 'cpu'\r\neverything_results = model(IMAGE_PATH, device=DEVICE, retina_masks=True, imgsz=1024, conf=0.4, iou=0.9,)\r\nprompt_process = FastSAMPrompt(IMAGE_PATH, everything_results, device=DEVICE)\r\n\r\n# everything prompt\r\nann = prompt_process.everything_prompt()\r\n\r\nprompt_process.plot(annotations=ann,output_path='./output/dog.jpg',)\r\n\r\n```\r\nFor point/box/text mode prompts, use:\r\n```\r\n# bbox default shape [0,0,0,0] -> [x1,y1,x2,y2]\r\nann = prompt_process.box_prompt(bboxes=[[200, 200, 300, 300]])\r\n\r\n# text prompt\r\nann = prompt_process.text_prompt(text='a photo of a dog')\r\n\r\n# point prompt\r\n# points default [[0,0]] [[x1,y1],[x2,y2]]\r\n# point_label default [0] [1,0] 0:background, 1:foreground\r\nann = prompt_process.point_prompt(points=[[620, 360]], pointlabel=[1])\r\n\r\nprompt_process.plot(annotations=ann,output_path='./output/dog.jpg',)\r\n\r\n```\r\n\r\nYou are also welcomed to try our Colab demo: [FastSAM_example.ipynb](https://colab.research.google.com/drive/1oX14f6IneGGw612WgVlAiy91UHwFAvr9?usp=sharing).\r\n\r\n\r\n\r\n## Different Inference Options\r\n\r\nWe provide various options for different purposes, details are in [MORE_USAGES.md](MORE_USAGES.md).\r\n\r\n## Training or Validation\r\nTraining from scratch or validation: [Training and Validation Code](https://github.com/CASIA-IVA-Lab/FastSAM/releases).\r\n\r\n## Web demo\r\n\r\n### Gradio demo\r\n\r\n- We also provide a UI for testing our method that is built with gradio. You can upload a custom image, select the mode and set the parameters, click the segment button, and get a satisfactory segmentation result. Currently, the UI supports interaction with the 'Everything mode' and 'points mode'. We plan to add support for additional modes in the future. Running the following command in a terminal will launch the demo:\r\n\r\n```\r\n# Download the pre-trained model in \"./weights/FastSAM.pt\"\r\npython app_gradio.py\r\n```\r\n\r\n- This demo is also hosted on [HuggingFace Space](https://huggingface.co/spaces/An-619/FastSAM).\r\n\r\n![HF_Everyhting](assets/hf_everything_mode.png) ![HF_Points](assets/hf_points_mode.png)\r\n\r\n### Replicate demo\r\n\r\n- [Replicate demo](https://replicate.com/casia-iva-lab/fastsam) has supported all modes, you can experience points/box/text mode.\r\n\r\n![Replicate-1](assets/replicate-1.png) ![Replicate-2](assets/replicate-2.png) ![Replicate-3](assets/replicate-3.png)\r\n\r\n## <a name=\"Models\"></a>Model Checkpoints\r\n\r\nTwo model versions of the model are available with different sizes. Click the links below to download the checkpoint for the corresponding model type.\r\n\r\n- **`default` or `FastSAM`: [YOLOv8x based Segment Anything Model](https://drive.google.com/file/d/1m1sjY4ihXBU1fZXdQ-Xdj-mDltW-2Rqv/view?usp=sharing) | [Baidu Cloud (pwd: 0000).](https://pan.baidu.com/s/18KzBmOTENjByoWWR17zdiQ?pwd=0000)**\r\n- `FastSAM-s`: [YOLOv8s based Segment Anything Model.](https://drive.google.com/file/d/10XmSj6mmpmRb8NhXbtiuO9cTTBwR_9SV/view?usp=sharing)\r\n\r\n## Results\r\n\r\nAll result were tested on a single NVIDIA GeForce RTX 3090.\r\n\r\n### 1. Inference time\r\n\r\nRunning Speed under Different Point Prompt Numbers(ms).\r\n| method | params | 1 | 10 | 100 | E(16x16) | E(32x32\\*) | E(64x64) |\r\n|:------------------:|:--------:|:-----:|:-----:|:-----:|:----------:|:-----------:|:----------:|\r\n| SAM-H | 0.6G | 446 | 464 | 627 | 852 | 2099 | 6972 |\r\n| SAM-B | 136M | 110 | 125 | 230 | 432 | 1383 | 5417 |\r\n| FastSAM | 68M | 40 |40 | 40 | 40 | 40 | 40 |\r\n\r\n### 2. Memory usage\r\n\r\n|  Dataset  | Method  | GPU Memory (MB) |\r\n| :-------: | :-----: | :-------------: |\r\n| COCO 2017 | FastSAM |      2608       |\r\n| COCO 2017 |  SAM-H  |      7060       |\r\n| COCO 2017 |  SAM-B  |      4670       |\r\n\r\n### 3. Zero-shot Transfer Experiments\r\n\r\n#### Edge Detection\r\n\r\nTest on the BSDB500 dataset.\r\n|method | year| ODS | OIS | AP | R50 |\r\n|:----------:|:-------:|:--------:|:--------:|:------:|:-----:|\r\n| HED | 2015| .788 | .808 | .840 | .923 |\r\n| SAM | 2023| .768 | .786 | .794 | .928 |\r\n| FastSAM | 2023| .750 | .790 | .793 | .903 |\r\n\r\n#### Object Proposals\r\n\r\n##### COCO\r\n\r\n|  method   | AR10 | AR100 | AR1000 | AUC  |\r\n| :-------: | :--: | :---: | :-----: | :--: |\r\n| SAM-H E64 | 15.5 | 45.6  |   67.7 | 32.1 |\r\n| SAM-H E32 | 18.5 | 49.5  |   62.5 | 33.7 |\r\n| SAM-B E32 | 11.4 | 39.6  |   59.1 | 27.3 |\r\n|  FastSAM  | 15.7 | 47.3  |   63.7 | 32.2 |\r\n\r\n##### LVIS\r\n\r\nbbox AR@1000\r\n| method | all | small | med. | large |\r\n|:---------------:|:-----:|:------:|:-----:|:------:|\r\n| ViTDet-H | 65.0 | 53.2 | 83.3 | 91.2 |\r\nzero-shot transfer methods\r\n| SAM-H E64 | 52.1 | 36.6 | 75.1 | 88.2 |\r\n| SAM-H E32 | 50.3 | 33.1 | 76.2 | 89.8 |\r\n| SAM-B E32 | 45.0 | 29.3 | 68.7 | 80.6 |\r\n| FastSAM | 57.1 | 44.3 | 77.1 | 85.3 |\r\n\r\n#### Instance Segmentation On COCO 2017\r\n\r\n|  method  |  AP  | APS  | APM  | APL  |\r\n| :------: | :--: | :--: | :--: | :--: |\r\n| ViTDet-H | .510 | .320 | .543 | .689 |\r\n|   SAM    | .465 | .308 | .510 | .617 |\r\n| FastSAM  | .379 | .239 | .434 | .500 |\r\n\r\n### 4. Performance Visualization\r\n\r\nSeveral segmentation results:\r\n\r\n#### Natural Images\r\n\r\n![Natural Images](assets/eightpic.png)\r\n\r\n#### Text to Mask\r\n\r\n![Text to Mask](assets/dog_clip.png)\r\n\r\n### 5.Downstream tasks\r\n\r\nThe results of several downstream tasks to show the effectiveness.\r\n\r\n#### Anomaly Detection\r\n\r\n![Anomaly Detection](assets/anomaly.png)\r\n\r\n#### Salient Object Detection\r\n\r\n![Salient Object Detection](assets/salient.png)\r\n\r\n#### Building Extracting\r\n\r\n![Building Detection](assets/building.png)\r\n\r\n## License\r\n\r\nThe model is licensed under the [Apache 2.0 license](LICENSE).\r\n\r\n## Acknowledgement\r\n\r\n- [Segment Anything](https://segment-anything.com/) provides the SA-1B dataset and the base codes.\r\n- [YOLOv8](https://github.com/ultralytics/ultralytics) provides codes and pre-trained models.\r\n- [YOLACT](https://arxiv.org/abs/2112.10003) provides powerful instance segmentation method.\r\n- [Grounded-Segment-Anything](https://huggingface.co/spaces/yizhangliu/Grounded-Segment-Anything) provides a useful web demo template.\r\n\r\n## Contributors\r\n\r\nOur project wouldn't be possible without the contributions of these amazing people! Thank you all for making this project better.\r\n\r\n\r\n<a href=\"https://github.com/CASIA-IVA-Lab/FastSAM/graphs/contributors\">\r\n  <img src=\"https://contrib.rocks/image?repo=CASIA-IVA-Lab/FastSAM\" />\r\n</a>\r\n\r\n\r\n## Citing FastSAM\r\n\r\nIf you find this project useful for your research, please consider citing the following BibTeX entry.\r\n\r\n```\r\n@misc{zhao2023fast,\r\n      title={Fast Segment Anything},\r\n      author={Xu Zhao and Wenchao Ding and Yongqi An and Yinglong Du and Tao Yu and Min Li and Ming Tang and Jinqiao Wang},\r\n      year={2023},\r\n      eprint={2306.12156},\r\n      archivePrefix={arXiv},\r\n      primaryClass={cs.CV}\r\n}\r\n```\r\n\r\n[![Star History Chart](https://api.star-history.com/svg?repos=CASIA-IVA-Lab/FastSAM&type=Date)](https://star-history.com/#CASIA-IVA-Lab/FastSAM&Date)\r\n"
  },
  {
    "path": "app_gradio.py",
    "content": "from ultralytics import YOLO\nimport gradio as gr\nimport torch\nfrom utils.tools_gradio import fast_process\nfrom utils.tools import format_results, box_prompt, point_prompt, text_prompt\nfrom PIL import ImageDraw\nimport numpy as np\n\n# Load the pre-trained model\nmodel = YOLO('./weights/FastSAM.pt')\n\ndevice = torch.device(\n    \"cuda\"\n    if torch.cuda.is_available()\n    else \"mps\"\n    if torch.backends.mps.is_available()\n    else \"cpu\"\n)\n\n# Description\ntitle = \"<center><strong><font size='8'>🏃 Fast Segment Anything 🤗</font></strong></center>\"\n\nnews = \"\"\" # 📖 News\n        🔥 2023/07/14: Add a \"wider result\" button in text mode (Thanks for [gaoxinge](https://github.com/CASIA-IVA-Lab/FastSAM/pull/95)).\n\n        🔥 2023/06/29: Support the text mode (Thanks for [gaoxinge](https://github.com/CASIA-IVA-Lab/FastSAM/pull/47)).\n\n        🔥 2023/06/26: Support the points mode. (Better and faster interaction will come soon!)\n\n        🔥 2023/06/24: Add the 'Advanced options\" in Everything mode to get a more detailed adjustment.        \n        \"\"\"  \n\ndescription_e = \"\"\"This is a demo on Github project 🏃 [Fast Segment Anything Model](https://github.com/CASIA-IVA-Lab/FastSAM). Welcome to give a star ⭐️ to it.\n                \n                🎯 Upload an Image, segment it with Fast Segment Anything (Everything mode). The other modes will come soon.\n                \n                ⌛️ It takes about 6~ seconds to generate segment results. The concurrency_count of queue is 1, please wait for a moment when it is crowded.\n                \n                🚀 To get faster results, you can use a smaller input size and leave high_visual_quality unchecked.\n                \n                📣 You can also obtain the segmentation results of any Image through this Colab: [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1oX14f6IneGGw612WgVlAiy91UHwFAvr9?usp=sharing)\n                \n                😚 A huge thanks goes out to the @HuggingFace Team for supporting us with GPU grant.\n                \n                🏠 Check out our [Model Card 🏃](https://huggingface.co/An-619/FastSAM)\n                \n              \"\"\"\n\ndescription_p = \"\"\" # 🎯 Instructions for points mode\n                This is a demo on Github project 🏃 [Fast Segment Anything Model](https://github.com/CASIA-IVA-Lab/FastSAM). Welcome to give a star ⭐️ to it.\n                \n                1. Upload an image or choose an example.\n                \n                2. Choose the point label ('Add mask' means a positive point. 'Remove' Area means a negative point that is not segmented).\n                \n                3. Add points one by one on the image.\n                \n                4. Click the 'Segment with points prompt' button to get the segmentation results.\n                \n                **5. If you get Error, click the 'Clear points' button and try again may help.**\n                \n              \"\"\"\n\nexamples = [[\"examples/sa_8776.jpg\"], [\"examples/sa_414.jpg\"], [\"examples/sa_1309.jpg\"], [\"examples/sa_11025.jpg\"],\n            [\"examples/sa_561.jpg\"], [\"examples/sa_192.jpg\"], [\"examples/sa_10039.jpg\"], [\"examples/sa_862.jpg\"]]\n\ndefault_example = examples[0]\n\ncss = \"h1 { text-align: center } .about { text-align: justify; padding-left: 10%; padding-right: 10%; }\"\n\n\ndef segment_everything(\n    input,\n    input_size=1024, \n    iou_threshold=0.7,\n    conf_threshold=0.25,\n    better_quality=False,\n    withContours=True,\n    use_retina=True,\n    text=\"\",\n    wider=False,\n    mask_random_color=True,\n):\n    input_size = int(input_size)  # 确保 imgsz 是整数\n    # Thanks for the suggestion by hysts in HuggingFace.\n    w, h = input.size\n    scale = input_size / max(w, h)\n    new_w = int(w * scale)\n    new_h = int(h * scale)\n    input = input.resize((new_w, new_h))\n\n    results = model(input,\n                    device=device,\n                    retina_masks=True,\n                    iou=iou_threshold,\n                    conf=conf_threshold,\n                    imgsz=input_size,)\n\n    if len(text) > 0:\n        results = format_results(results[0], 0)\n        annotations, _ = text_prompt(results, text, input, device=device, wider=wider)\n        annotations = np.array([annotations])\n    else:\n        annotations = results[0].masks.data\n    \n    fig = fast_process(annotations=annotations,\n                       image=input,\n                       device=device,\n                       scale=(1024 // input_size),\n                       better_quality=better_quality,\n                       mask_random_color=mask_random_color,\n                       bbox=None,\n                       use_retina=use_retina,\n                       withContours=withContours,)\n    return fig\n\n\ndef segment_with_points(\n    input,\n    input_size=1024, \n    iou_threshold=0.7,\n    conf_threshold=0.25,\n    better_quality=False,\n    withContours=True,\n    use_retina=True,\n    mask_random_color=True,\n):\n    global global_points\n    global global_point_label\n    \n    input_size = int(input_size)  # 确保 imgsz 是整数\n    # Thanks for the suggestion by hysts in HuggingFace.\n    w, h = input.size\n    scale = input_size / max(w, h)\n    new_w = int(w * scale)\n    new_h = int(h * scale)\n    input = input.resize((new_w, new_h))\n    \n    scaled_points = [[int(x * scale) for x in point] for point in global_points]\n\n    results = model(input,\n                    device=device,\n                    retina_masks=True,\n                    iou=iou_threshold,\n                    conf=conf_threshold,\n                    imgsz=input_size,)\n    \n    results = format_results(results[0], 0)\n    annotations, _ = point_prompt(results, scaled_points, global_point_label, new_h, new_w)\n    annotations = np.array([annotations])\n\n    fig = fast_process(annotations=annotations,\n                       image=input,\n                       device=device,\n                       scale=(1024 // input_size),\n                       better_quality=better_quality,\n                       mask_random_color=mask_random_color,\n                       bbox=None,\n                       use_retina=use_retina,\n                       withContours=withContours,)\n\n    global_points = []\n    global_point_label = []\n    return fig, None\n\n\ndef get_points_with_draw(image, label, evt: gr.SelectData):\n    global global_points\n    global global_point_label\n\n    x, y = evt.index[0], evt.index[1]\n    point_radius, point_color = 15, (255, 255, 0) if label == 'Add Mask' else (255, 0, 255)\n    global_points.append([x, y])\n    global_point_label.append(1 if label == 'Add Mask' else 0)\n    \n    print(x, y, label == 'Add Mask')\n    \n    # 创建一个可以在图像上绘图的对象\n    draw = ImageDraw.Draw(image)\n    draw.ellipse([(x - point_radius, y - point_radius), (x + point_radius, y + point_radius)], fill=point_color)\n    return image\n\n\ncond_img_e = gr.Image(label=\"Input\", value=default_example[0], type='pil')\ncond_img_p = gr.Image(label=\"Input with points\", value=default_example[0], type='pil')\ncond_img_t = gr.Image(label=\"Input with text\", value=\"examples/dogs.jpg\", type='pil')\n\nsegm_img_e = gr.Image(label=\"Segmented Image\", interactive=False, type='pil')\nsegm_img_p = gr.Image(label=\"Segmented Image with points\", interactive=False, type='pil')\nsegm_img_t = gr.Image(label=\"Segmented Image with text\", interactive=False, type='pil')\n\nglobal_points = []\nglobal_point_label = []\n\ninput_size_slider = gr.components.Slider(minimum=512,\n                                         maximum=1024,\n                                         value=1024,\n                                         step=64,\n                                         label='Input_size',\n                                         info='Our model was trained on a size of 1024')\n\nwith gr.Blocks(css=css, title='Fast Segment Anything') as demo:\n    with gr.Row():\n        with gr.Column(scale=1):\n            # Title\n            gr.Markdown(title)\n\n        with gr.Column(scale=1):\n            # News\n            gr.Markdown(news)\n\n    with gr.Tab(\"Everything mode\"):\n        # Images\n        with gr.Row(variant=\"panel\"):\n            with gr.Column(scale=1):\n                cond_img_e.render()\n\n            with gr.Column(scale=1):\n                segm_img_e.render()\n\n        # Submit & Clear\n        with gr.Row():\n            with gr.Column():\n                input_size_slider.render()\n\n                with gr.Row():\n                    contour_check = gr.Checkbox(value=True, label='withContours', info='draw the edges of the masks')\n\n                    with gr.Column():\n                        segment_btn_e = gr.Button(\"Segment Everything\", variant='primary')\n                        clear_btn_e = gr.Button(\"Clear\", variant=\"secondary\")\n\n                gr.Markdown(\"Try some of the examples below ⬇️\")\n                gr.Examples(examples=examples,\n                            inputs=[cond_img_e],\n                            outputs=segm_img_e,\n                            fn=segment_everything,\n                            cache_examples=True,\n                            examples_per_page=4)\n\n            with gr.Column():\n                with gr.Accordion(\"Advanced options\", open=False):\n                    iou_threshold = gr.Slider(0.1, 0.9, 0.7, step=0.1, label='iou', info='iou threshold for filtering the annotations')\n                    conf_threshold = gr.Slider(0.1, 0.9, 0.25, step=0.05, label='conf', info='object confidence threshold')\n                    with gr.Row():\n                        mor_check = gr.Checkbox(value=False, label='better_visual_quality', info='better quality using morphologyEx')\n                        with gr.Column():\n                            retina_check = gr.Checkbox(value=True, label='use_retina', info='draw high-resolution segmentation masks')\n\n                # Description\n                gr.Markdown(description_e)\n\n    segment_btn_e.click(segment_everything,\n                        inputs=[\n                            cond_img_e,\n                            input_size_slider,\n                            iou_threshold,\n                            conf_threshold,\n                            mor_check,\n                            contour_check,\n                            retina_check,\n                        ],\n                        outputs=segm_img_e)\n\n    with gr.Tab(\"Points mode\"):\n        # Images\n        with gr.Row(variant=\"panel\"):\n            with gr.Column(scale=1):\n                cond_img_p.render()\n\n            with gr.Column(scale=1):\n                segm_img_p.render()\n                \n        # Submit & Clear\n        with gr.Row():\n            with gr.Column():\n                with gr.Row():\n                    add_or_remove = gr.Radio([\"Add Mask\", \"Remove Area\"], value=\"Add Mask\", label=\"Point_label (foreground/background)\")\n\n                    with gr.Column():\n                        segment_btn_p = gr.Button(\"Segment with points prompt\", variant='primary')\n                        clear_btn_p = gr.Button(\"Clear points\", variant='secondary')\n\n                gr.Markdown(\"Try some of the examples below ⬇️\")\n                gr.Examples(examples=examples,\n                            inputs=[cond_img_p],\n                            # outputs=segm_img_p,\n                            # fn=segment_with_points,\n                            # cache_examples=True,\n                            examples_per_page=4)\n\n            with gr.Column():\n                # Description\n                gr.Markdown(description_p)\n\n    cond_img_p.select(get_points_with_draw, [cond_img_p, add_or_remove], cond_img_p)\n\n    segment_btn_p.click(segment_with_points,\n                        inputs=[cond_img_p],\n                        outputs=[segm_img_p, cond_img_p])\n\n    with gr.Tab(\"Text mode\"):\n        # Images\n        with gr.Row(variant=\"panel\"):\n            with gr.Column(scale=1):\n                cond_img_t.render()\n\n            with gr.Column(scale=1):\n                segm_img_t.render()\n\n        # Submit & Clear\n        with gr.Row():\n            with gr.Column():\n                input_size_slider_t = gr.components.Slider(minimum=512,\n                                                           maximum=1024,\n                                                           value=1024,\n                                                           step=64,\n                                                           label='Input_size',\n                                                           info='Our model was trained on a size of 1024')\n                with gr.Row():\n                    with gr.Column():\n                        contour_check = gr.Checkbox(value=True, label='withContours', info='draw the edges of the masks')\n                        text_box = gr.Textbox(label=\"text prompt\", value=\"a black dog\")\n\n                    with gr.Column():\n                        segment_btn_t = gr.Button(\"Segment with text\", variant='primary')\n                        clear_btn_t = gr.Button(\"Clear\", variant=\"secondary\")\n\n                gr.Markdown(\"Try some of the examples below ⬇️\")\n                gr.Examples(examples=[[\"examples/dogs.jpg\"]] + examples,\n                            inputs=[cond_img_e],\n                            # outputs=segm_img_e,\n                            # fn=segment_everything,\n                            # cache_examples=True,\n                            examples_per_page=4)\n\n            with gr.Column():\n                with gr.Accordion(\"Advanced options\", open=False):\n                    iou_threshold = gr.Slider(0.1, 0.9, 0.7, step=0.1, label='iou', info='iou threshold for filtering the annotations')\n                    conf_threshold = gr.Slider(0.1, 0.9, 0.25, step=0.05, label='conf', info='object confidence threshold')\n                    with gr.Row():\n                        mor_check = gr.Checkbox(value=False, label='better_visual_quality', info='better quality using morphologyEx')\n                        retina_check = gr.Checkbox(value=True, label='use_retina', info='draw high-resolution segmentation masks')\n                        wider_check = gr.Checkbox(value=False, label='wider', info='wider result')\n\n                # Description\n                gr.Markdown(description_e)\n    \n    segment_btn_t.click(segment_everything,\n                        inputs=[\n                            cond_img_t,\n                            input_size_slider_t,\n                            iou_threshold,\n                            conf_threshold,\n                            mor_check,\n                            contour_check,\n                            retina_check,\n                            text_box,\n                            wider_check,\n                        ],\n                        outputs=segm_img_t)\n\n    def clear():\n        return None, None\n    \n    def clear_text():\n        return None, None, None\n\n    clear_btn_e.click(clear, outputs=[cond_img_e, segm_img_e])\n    clear_btn_p.click(clear, outputs=[cond_img_p, segm_img_p])\n    clear_btn_t.click(clear_text, outputs=[cond_img_p, segm_img_p, text_box])\n\ndemo.queue()\ndemo.launch()\n"
  },
  {
    "path": "cog.yaml",
    "content": "# Configuration for Cog ⚙️\n# Reference: https://github.com/replicate/cog/blob/main/docs/yaml.md\n# Thanks for chenxwh.\n\nbuild:\n  # set to true if your model requires a GPU\n  gpu: true\n  cuda: \"11.7\"\n  system_packages:\n    - \"libgl1-mesa-glx\"\n    - \"libglib2.0-0\"\n  python_version: \"3.8\"\n  python_packages:\n    - \"matplotlib==3.7.1\"\n    - \"opencv-python==4.7.0.72\"\n    - \"Pillow==9.5.0\"\n    - \"PyYAML==6.0\"\n    - \"requests==2.31.0\"\n    - \"scipy==1.10.1\"\n    - \"torch==2.0.1\"\n    - \"torchvision==0.15.2\"\n    - \"tqdm==4.65.0\"\n    - \"pandas==2.0.2\"\n    - \"seaborn==0.12.0\"\n    - \"ultralytics==8.0.121\"\n    - git+https://github.com/openai/CLIP.git\npredict: \"predict.py:Predictor\"\n"
  },
  {
    "path": "fastsam/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .model import FastSAM\nfrom .predict import FastSAMPredictor\nfrom .prompt import FastSAMPrompt\n# from .val import FastSAMValidator\nfrom .decoder import FastSAMDecoder\n\n__all__ = 'FastSAMPredictor', 'FastSAM', 'FastSAMPrompt', 'FastSAMDecoder'\n"
  },
  {
    "path": "fastsam/decoder.py",
    "content": "from .model import FastSAM\nimport numpy as np\nfrom PIL import Image\nfrom typing import Optional, List, Tuple, Union\n\n\nclass FastSAMDecoder:\n    def __init__(\n        self,\n        model: FastSAM,\n        device: str='cpu',\n        conf: float=0.4, \n        iou: float=0.9,\n        imgsz: int=1024,\n        retina_masks: bool=True,\n        ):\n        self.model = model\n        self.device = device\n        self.retina_masks = retina_masks\n        self.imgsz = imgsz\n        self.conf = conf\n        self.iou = iou\n        self.image = None\n        self.image_embedding = None\n        \n    def run_encoder(self, image):\n        if isinstance(image,str):\n            image =  np.array(Image.open(image))\n        self.image = image\n        image_embedding = self.model(\n            self.image, \n            device=self.device, \n            retina_masks=self.retina_masks, \n            imgsz=self.imgsz, \n            conf=self.conf, \n            iou=self.iou\n            )\n        return image_embedding[0].numpy()\n\n    def run_decoder(\n            self,\n            image_embedding, \n            point_prompt: Optional[np.ndarray]=None,\n            point_label: Optional[np.ndarray]=None,\n            box_prompt: Optional[np.ndarray]=None,\n            text_prompt: Optional[str]=None,\n            )->np.ndarray:\n        self.image_embedding = image_embedding\n        if point_prompt is not None:\n            ann = self.point_prompt(points=point_prompt, pointlabel=point_label)\n            return ann\n        elif box_prompt is not None:\n            ann = self.box_prompt(bbox=box_prompt)\n            return ann\n        elif text_prompt is not None:\n            ann = self.text_prompt(text=text_prompt)\n            return ann\n        else:\n            return None\n\n    def box_prompt(self, bbox):\n        assert (bbox[2] != 0 and bbox[3] != 0)\n        masks = self.image_embedding.masks.data\n        target_height = self.image.shape[0]\n        target_width = self.image.shape[1]\n        h = masks.shape[1]\n        w = masks.shape[2]\n        if h != target_height or w != target_width:\n            bbox = [\n                int(bbox[0] * w / target_width),\n                int(bbox[1] * h / target_height),\n                int(bbox[2] * w / target_width),\n                int(bbox[3] * h / target_height), ]\n        bbox[0] = round(bbox[0]) if round(bbox[0]) > 0 else 0\n        bbox[1] = round(bbox[1]) if round(bbox[1]) > 0 else 0\n        bbox[2] = round(bbox[2]) if round(bbox[2]) < w else w\n        bbox[3] = round(bbox[3]) if round(bbox[3]) < h else h\n\n        # IoUs = torch.zeros(len(masks), dtype=torch.float32)\n        bbox_area = (bbox[3] - bbox[1]) * (bbox[2] - bbox[0])\n\n        masks_area = np.sum(masks[:, bbox[1]:bbox[3], bbox[0]:bbox[2]], axis=(1, 2))\n        orig_masks_area = np.sum(masks, axis=(1, 2))\n\n        union = bbox_area + orig_masks_area - masks_area\n        IoUs = masks_area / union\n        max_iou_index = np.argmax(IoUs)\n\n        return np.array([masks[max_iou_index].cpu().numpy()])\n\n    def point_prompt(self, points, pointlabel):  # numpy \n\n        masks = self._format_results(self.image_embedding[0], 0)\n        target_height = self.image.shape[0]\n        target_width = self.image.shape[1]\n        h = masks[0]['segmentation'].shape[0]\n        w = masks[0]['segmentation'].shape[1]\n        if h != target_height or w != target_width:\n            points = [[int(point[0] * w / target_width), int(point[1] * h / target_height)] for point in points]\n        onemask = np.zeros((h, w))\n        masks = sorted(masks, key=lambda x: x['area'], reverse=True)\n        for i, annotation in enumerate(masks):\n            if type(annotation) == dict:\n                mask = annotation['segmentation']\n            else:\n                mask = annotation\n            for i, point in enumerate(points):\n                if mask[point[1], point[0]] == 1 and pointlabel[i] == 1:\n                    onemask[mask] = 1\n                if mask[point[1], point[0]] == 1 and pointlabel[i] == 0:\n                    onemask[mask] = 0\n        onemask = onemask >= 1\n        return np.array([onemask])\n    \n    def _format_results(self, result, filter=0):\n        annotations = []\n        n = len(result.masks.data)\n        for i in range(n):\n            annotation = {}\n            mask = result.masks.data[i] == 1.0\n\n            if np.sum(mask) < filter:\n                continue\n            annotation['id'] = i\n            annotation['segmentation'] = mask\n            annotation['bbox'] = result.boxes.data[i]\n            annotation['score'] = result.boxes.conf[i]\n            annotation['area'] = annotation['segmentation'].sum()\n            annotations.append(annotation)\n        return annotations\n"
  },
  {
    "path": "fastsam/model.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nFastSAM model interface.\n\nUsage - Predict:\n    from ultralytics import FastSAM\n\n    model = FastSAM('last.pt')\n    results = model.predict('ultralytics/assets/bus.jpg')\n\"\"\"\n\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.engine.exporter import Exporter\nfrom ultralytics.yolo.engine.model import YOLO\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, ROOT, is_git_dir\nfrom ultralytics.yolo.utils.checks import check_imgsz\n\nfrom ultralytics.yolo.utils.torch_utils import model_info, smart_inference_mode\nfrom .predict import FastSAMPredictor\n\n\nclass FastSAM(YOLO):\n\n    @smart_inference_mode()\n    def predict(self, source=None, stream=False, **kwargs):\n        \"\"\"\n        Perform prediction using the YOLO model.\n\n        Args:\n            source (str | int | PIL | np.ndarray): The source of the image to make predictions on.\n                          Accepts all source types accepted by the YOLO model.\n            stream (bool): Whether to stream the predictions or not. Defaults to False.\n            **kwargs : Additional keyword arguments passed to the predictor.\n                       Check the 'configuration' section in the documentation for all available options.\n\n        Returns:\n            (List[ultralytics.yolo.engine.results.Results]): The prediction results.\n        \"\"\"\n        if source is None:\n            source = ROOT / 'assets' if is_git_dir() else 'https://ultralytics.com/images/bus.jpg'\n            LOGGER.warning(f\"WARNING ⚠️ 'source' is missing. Using 'source={source}'.\")\n        overrides = self.overrides.copy()\n        overrides['conf'] = 0.25\n        overrides.update(kwargs)  # prefer kwargs\n        overrides['mode'] = kwargs.get('mode', 'predict')\n        assert overrides['mode'] in ['track', 'predict']\n        overrides['save'] = kwargs.get('save', False)  # do not save by default if called in Python\n        self.predictor = FastSAMPredictor(overrides=overrides)\n        self.predictor.setup_model(model=self.model, verbose=False)\n        try:\n            return self.predictor(source, stream=stream)\n        except Exception as e:\n            return None\n\n    def train(self, **kwargs):\n        \"\"\"Function trains models but raises an error as FastSAM models do not support training.\"\"\"\n        raise NotImplementedError(\"Currently, the training codes are on the way.\")\n\n    def val(self, **kwargs):\n        \"\"\"Run validation given dataset.\"\"\"\n        overrides = dict(task='segment', mode='val')\n        overrides.update(kwargs)  # prefer kwargs\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.imgsz = check_imgsz(args.imgsz, max_dim=1)\n        validator = FastSAM(args=args)\n        validator(model=self.model)\n        self.metrics = validator.metrics\n        return validator.metrics\n\n    @smart_inference_mode()\n    def export(self, **kwargs):\n        \"\"\"\n        Export model.\n\n        Args:\n            **kwargs : Any other args accepted by the predictors. To see all args check 'configuration' section in docs\n        \"\"\"\n        overrides = dict(task='detect')\n        overrides.update(kwargs)\n        overrides['mode'] = 'export'\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.task = self.task\n        if args.imgsz == DEFAULT_CFG.imgsz:\n            args.imgsz = self.model.args['imgsz']  # use trained imgsz unless custom value is passed\n        if args.batch == DEFAULT_CFG.batch:\n            args.batch = 1  # default to 1 if not modified\n        return Exporter(overrides=args)(model=self.model)\n\n    def info(self, detailed=False, verbose=True):\n        \"\"\"\n        Logs model info.\n\n        Args:\n            detailed (bool): Show detailed information about model.\n            verbose (bool): Controls verbosity.\n        \"\"\"\n        return model_info(self.model, detailed=detailed, verbose=verbose, imgsz=640)\n\n    def __call__(self, source=None, stream=False, **kwargs):\n        \"\"\"Calls the 'predict' function with given arguments to perform object detection.\"\"\"\n        return self.predict(source, stream, **kwargs)\n\n    def __getattr__(self, attr):\n        \"\"\"Raises error if object has no requested attribute.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n"
  },
  {
    "path": "fastsam/predict.py",
    "content": "import torch\n\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import DEFAULT_CFG, ops\nfrom ultralytics.yolo.v8.detect.predict import DetectionPredictor\nfrom .utils import bbox_iou\n\nclass FastSAMPredictor(DetectionPredictor):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        super().__init__(cfg, overrides, _callbacks)\n        self.args.task = 'segment'\n\n    def postprocess(self, preds, img, orig_imgs):\n        \"\"\"TODO: filter by classes.\"\"\"\n        p = ops.non_max_suppression(preds[0],\n                                    self.args.conf,\n                                    self.args.iou,\n                                    agnostic=self.args.agnostic_nms,\n                                    max_det=self.args.max_det,\n                                    nc=len(self.model.names),\n                                    classes=self.args.classes)\n\n        results = []\n        if len(p) == 0 or len(p[0]) == 0:\n            print(\"No object detected.\")\n            return results\n\n        full_box = torch.zeros_like(p[0][0])\n        full_box[2], full_box[3], full_box[4], full_box[6:] = img.shape[3], img.shape[2], 1.0, 1.0\n        full_box = full_box.view(1, -1)\n        critical_iou_index = bbox_iou(full_box[0][:4], p[0][:, :4], iou_thres=0.9, image_shape=img.shape[2:])\n        if critical_iou_index.numel() != 0:\n            full_box[0][4] = p[0][critical_iou_index][:,4]\n            full_box[0][6:] = p[0][critical_iou_index][:,6:]\n            p[0][critical_iou_index] = full_box\n        \n        proto = preds[1][-1] if len(preds[1]) == 3 else preds[1]  # second output is len 3 if pt, but only 1 if exported\n        for i, pred in enumerate(p):\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            if not len(pred):  # save empty boxes\n                results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6]))\n                continue\n            if self.args.retina_masks:\n                if not isinstance(orig_imgs, torch.Tensor):\n                    pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)\n                masks = ops.process_mask_native(proto[i], pred[:, 6:], pred[:, :4], orig_img.shape[:2])  # HWC\n            else:\n                masks = ops.process_mask(proto[i], pred[:, 6:], pred[:, :4], img.shape[2:], upsample=True)  # HWC\n                if not isinstance(orig_imgs, torch.Tensor):\n                    pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)\n            results.append(\n                Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6], masks=masks))\n        return results\n"
  },
  {
    "path": "fastsam/prompt.py",
    "content": "import os\nimport sys\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom .utils import image_to_np_ndarray\nfrom PIL import Image\n\n\nclass FastSAMPrompt:\n\n    def __init__(self, image, results, device='cuda'):\n        if isinstance(image, str) or isinstance(image, Image.Image):\n            image = image_to_np_ndarray(image)\n        self.device = device\n        self.results = results\n        self.img = image\n    \n    def _segment_image(self, image, bbox):\n        if isinstance(image, Image.Image):\n            image_array = np.array(image)\n        else:\n            image_array = image\n        segmented_image_array = np.zeros_like(image_array)\n        x1, y1, x2, y2 = bbox\n        segmented_image_array[y1:y2, x1:x2] = image_array[y1:y2, x1:x2]\n        segmented_image = Image.fromarray(segmented_image_array)\n        black_image = Image.new('RGB', image.size, (255, 255, 255))\n        # transparency_mask = np.zeros_like((), dtype=np.uint8)\n        transparency_mask = np.zeros((image_array.shape[0], image_array.shape[1]), dtype=np.uint8)\n        transparency_mask[y1:y2, x1:x2] = 255\n        transparency_mask_image = Image.fromarray(transparency_mask, mode='L')\n        black_image.paste(segmented_image, mask=transparency_mask_image)\n        return black_image\n\n    def _format_results(self, result, filter=0):\n        annotations = []\n        n = len(result.masks.data)\n        for i in range(n):\n            annotation = {}\n            mask = result.masks.data[i] == 1.0\n\n            if torch.sum(mask) < filter:\n                continue\n            annotation['id'] = i\n            annotation['segmentation'] = mask.cpu().numpy()\n            annotation['bbox'] = result.boxes.data[i]\n            annotation['score'] = result.boxes.conf[i]\n            annotation['area'] = annotation['segmentation'].sum()\n            annotations.append(annotation)\n        return annotations\n\n    def filter_masks(annotations):  # filte the overlap mask\n        annotations.sort(key=lambda x: x['area'], reverse=True)\n        to_remove = set()\n        for i in range(0, len(annotations)):\n            a = annotations[i]\n            for j in range(i + 1, len(annotations)):\n                b = annotations[j]\n                if i != j and j not in to_remove:\n                    # check if\n                    if b['area'] < a['area']:\n                        if (a['segmentation'] & b['segmentation']).sum() / b['segmentation'].sum() > 0.8:\n                            to_remove.add(j)\n\n        return [a for i, a in enumerate(annotations) if i not in to_remove], to_remove\n\n    def _get_bbox_from_mask(self, mask):\n        mask = mask.astype(np.uint8)\n        contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n        x1, y1, w, h = cv2.boundingRect(contours[0])\n        x2, y2 = x1 + w, y1 + h\n        if len(contours) > 1:\n            for b in contours:\n                x_t, y_t, w_t, h_t = cv2.boundingRect(b)\n                # Merge multiple bounding boxes into one.\n                x1 = min(x1, x_t)\n                y1 = min(y1, y_t)\n                x2 = max(x2, x_t + w_t)\n                y2 = max(y2, y_t + h_t)\n            h = y2 - y1\n            w = x2 - x1\n        return [x1, y1, x2, y2]\n\n    def plot_to_result(self,\n             annotations,\n             bboxes=None,\n             points=None,\n             point_label=None,\n             mask_random_color=True,\n             better_quality=True,\n             retina=False,\n             withContours=True) -> np.ndarray:\n        if isinstance(annotations[0], dict):\n            annotations = [annotation['segmentation'] for annotation in annotations]\n        image = self.img\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        original_h = image.shape[0]\n        original_w = image.shape[1]\n        if sys.platform == \"darwin\":\n            plt.switch_backend(\"TkAgg\")\n        plt.figure(figsize=(original_w / 100, original_h / 100))\n        # Add subplot with no margin.\n        plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\n        plt.margins(0, 0)\n        plt.gca().xaxis.set_major_locator(plt.NullLocator())\n        plt.gca().yaxis.set_major_locator(plt.NullLocator())\n\n        plt.imshow(image)\n        if better_quality:\n            if isinstance(annotations[0], torch.Tensor):\n                annotations = np.array(annotations.cpu())\n            for i, mask in enumerate(annotations):\n                mask = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))\n                annotations[i] = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_OPEN, np.ones((8, 8), np.uint8))\n        if self.device == 'cpu':\n            annotations = np.array(annotations)\n            self.fast_show_mask(\n                annotations,\n                plt.gca(),\n                random_color=mask_random_color,\n                bboxes=bboxes,\n                points=points,\n                pointlabel=point_label,\n                retinamask=retina,\n                target_height=original_h,\n                target_width=original_w,\n            )\n        else:\n            if isinstance(annotations[0], np.ndarray):\n                annotations = torch.from_numpy(annotations)\n            self.fast_show_mask_gpu(\n                annotations,\n                plt.gca(),\n                random_color=mask_random_color,\n                bboxes=bboxes,\n                points=points,\n                pointlabel=point_label,\n                retinamask=retina,\n                target_height=original_h,\n                target_width=original_w,\n            )\n        if isinstance(annotations, torch.Tensor):\n            annotations = annotations.cpu().numpy()\n        if withContours:\n            contour_all = []\n            temp = np.zeros((original_h, original_w, 1))\n            for i, mask in enumerate(annotations):\n                if type(mask) == dict:\n                    mask = mask['segmentation']\n                annotation = mask.astype(np.uint8)\n                if not retina:\n                    annotation = cv2.resize(\n                        annotation,\n                        (original_w, original_h),\n                        interpolation=cv2.INTER_NEAREST,\n                    )\n                contours, hierarchy = cv2.findContours(annotation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n                for contour in contours:\n                    contour_all.append(contour)\n            cv2.drawContours(temp, contour_all, -1, (255, 255, 255), 2)\n            color = np.array([0 / 255, 0 / 255, 255 / 255, 0.8])\n            contour_mask = temp / 255 * color.reshape(1, 1, -1)\n            plt.imshow(contour_mask)\n\n        plt.axis('off')\n        fig = plt.gcf()\n        plt.draw()\n\n        try:\n            buf = fig.canvas.tostring_rgb()\n        except AttributeError:\n            fig.canvas.draw()\n            buf = fig.canvas.tostring_rgb()\n        cols, rows = fig.canvas.get_width_height()\n        img_array = np.frombuffer(buf, dtype=np.uint8).reshape(rows, cols, 3)\n        result = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)\n        plt.close()\n        return result\n            \n    # Remark for refactoring: IMO a function should do one thing only, storing the image and plotting should be seperated and do not necessarily need to be class functions but standalone utility functions that the user can chain in his scripts to have more fine-grained control. \n    def plot(self,\n             annotations,\n             output_path,\n             bboxes=None,\n             points=None,\n             point_label=None,\n             mask_random_color=True,\n             better_quality=True,\n             retina=False,\n             withContours=True):\n        if len(annotations) == 0:\n            return None\n        result = self.plot_to_result(\n            annotations, \n            bboxes, \n            points, \n            point_label, \n            mask_random_color,\n            better_quality, \n            retina, \n            withContours,\n        )\n\n        path = os.path.dirname(os.path.abspath(output_path))\n        if not os.path.exists(path):\n            os.makedirs(path)\n        result = result[:, :, ::-1]\n        cv2.imwrite(output_path, result)\n     \n    #   CPU post process\n    def fast_show_mask(\n        self,\n        annotation,\n        ax,\n        random_color=False,\n        bboxes=None,\n        points=None,\n        pointlabel=None,\n        retinamask=True,\n        target_height=960,\n        target_width=960,\n    ):\n        msak_sum = annotation.shape[0]\n        height = annotation.shape[1]\n        weight = annotation.shape[2]\n        #Sort annotations based on area.\n        areas = np.sum(annotation, axis=(1, 2))\n        sorted_indices = np.argsort(areas)\n        annotation = annotation[sorted_indices]\n\n        index = (annotation != 0).argmax(axis=0)\n        if random_color:\n            color = np.random.random((msak_sum, 1, 1, 3))\n        else:\n            color = np.ones((msak_sum, 1, 1, 3)) * np.array([30 / 255, 144 / 255, 255 / 255])\n        transparency = np.ones((msak_sum, 1, 1, 1)) * 0.6\n        visual = np.concatenate([color, transparency], axis=-1)\n        mask_image = np.expand_dims(annotation, -1) * visual\n\n        show = np.zeros((height, weight, 4))\n        h_indices, w_indices = np.meshgrid(np.arange(height), np.arange(weight), indexing='ij')\n        indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))\n        # Use vectorized indexing to update the values of 'show'.\n        show[h_indices, w_indices, :] = mask_image[indices]\n        if bboxes is not None:\n            for bbox in bboxes:\n                x1, y1, x2, y2 = bbox\n                ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor='b', linewidth=1))\n        # draw point\n        if points is not None:\n            plt.scatter(\n                [point[0] for i, point in enumerate(points) if pointlabel[i] == 1],\n                [point[1] for i, point in enumerate(points) if pointlabel[i] == 1],\n                s=20,\n                c='y',\n            )\n            plt.scatter(\n                [point[0] for i, point in enumerate(points) if pointlabel[i] == 0],\n                [point[1] for i, point in enumerate(points) if pointlabel[i] == 0],\n                s=20,\n                c='m',\n            )\n\n        if not retinamask:\n            show = cv2.resize(show, (target_width, target_height), interpolation=cv2.INTER_NEAREST)\n        ax.imshow(show)\n\n    def fast_show_mask_gpu(\n        self,\n        annotation,\n        ax,\n        random_color=False,\n        bboxes=None,\n        points=None,\n        pointlabel=None,\n        retinamask=True,\n        target_height=960,\n        target_width=960,\n    ):\n        msak_sum = annotation.shape[0]\n        height = annotation.shape[1]\n        weight = annotation.shape[2]\n        areas = torch.sum(annotation, dim=(1, 2))\n        sorted_indices = torch.argsort(areas, descending=False)\n        annotation = annotation[sorted_indices]\n        # Find the index of the first non-zero value at each position.\n        index = (annotation != 0).to(torch.long).argmax(dim=0)\n        if random_color:\n            color = torch.rand((msak_sum, 1, 1, 3)).to(annotation.device)\n        else:\n            color = torch.ones((msak_sum, 1, 1, 3)).to(annotation.device) * torch.tensor([\n                30 / 255, 144 / 255, 255 / 255]).to(annotation.device)\n        transparency = torch.ones((msak_sum, 1, 1, 1)).to(annotation.device) * 0.6\n        visual = torch.cat([color, transparency], dim=-1)\n        mask_image = torch.unsqueeze(annotation, -1) * visual\n        # Select data according to the index. The index indicates which batch's data to choose at each position, converting the mask_image into a single batch form.\n        show = torch.zeros((height, weight, 4)).to(annotation.device)\n        try:\n            h_indices, w_indices = torch.meshgrid(torch.arange(height), torch.arange(weight), indexing='ij')\n        except:\n            h_indices, w_indices = torch.meshgrid(torch.arange(height), torch.arange(weight))\n        indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))\n        # Use vectorized indexing to update the values of 'show'.\n        show[h_indices, w_indices, :] = mask_image[indices]\n        show_cpu = show.cpu().numpy()\n        if bboxes is not None:\n            for bbox in bboxes:\n                x1, y1, x2, y2 = bbox\n                ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor='b', linewidth=1))\n        # draw point\n        if points is not None:\n            plt.scatter(\n                [point[0] for i, point in enumerate(points) if pointlabel[i] == 1],\n                [point[1] for i, point in enumerate(points) if pointlabel[i] == 1],\n                s=20,\n                c='y',\n            )\n            plt.scatter(\n                [point[0] for i, point in enumerate(points) if pointlabel[i] == 0],\n                [point[1] for i, point in enumerate(points) if pointlabel[i] == 0],\n                s=20,\n                c='m',\n            )\n        if not retinamask:\n            show_cpu = cv2.resize(show_cpu, (target_width, target_height), interpolation=cv2.INTER_NEAREST)\n        ax.imshow(show_cpu)\n\n    # clip\n    @torch.no_grad()\n    def retrieve(self, model, preprocess, elements, search_text: str, device) -> int:\n        preprocessed_images = [preprocess(image).to(device) for image in elements]\n        try:\n           import clip  # for linear_assignment\n    \n        except (ImportError, AssertionError, AttributeError):\n           from ultralytics.yolo.utils.checks import check_requirements\n    \n           check_requirements('git+https://github.com/openai/CLIP.git')  # required before installing lap from source\n           import clip\n\n\n        tokenized_text = clip.tokenize([search_text]).to(device)\n        stacked_images = torch.stack(preprocessed_images)\n        image_features = model.encode_image(stacked_images)\n        text_features = model.encode_text(tokenized_text)\n        image_features /= image_features.norm(dim=-1, keepdim=True)\n        text_features /= text_features.norm(dim=-1, keepdim=True)\n        probs = 100.0 * image_features @ text_features.T\n        return probs[:, 0].softmax(dim=0)\n\n    def _crop_image(self, format_results):\n\n        image = Image.fromarray(cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB))\n        ori_w, ori_h = image.size\n        annotations = format_results\n        mask_h, mask_w = annotations[0]['segmentation'].shape\n        if ori_w != mask_w or ori_h != mask_h:\n            image = image.resize((mask_w, mask_h))\n        cropped_boxes = []\n        cropped_images = []\n        not_crop = []\n        filter_id = []\n        # annotations, _ = filter_masks(annotations)\n        # filter_id = list(_)\n        for _, mask in enumerate(annotations):\n            if np.sum(mask['segmentation']) <= 100:\n                filter_id.append(_)\n                continue\n            bbox = self._get_bbox_from_mask(mask['segmentation'])  # mask 的 bbox\n            cropped_boxes.append(self._segment_image(image, bbox))  \n            # cropped_boxes.append(segment_image(image,mask[\"segmentation\"]))\n            cropped_images.append(bbox)  # Save the bounding box of the cropped image.\n\n        return cropped_boxes, cropped_images, not_crop, filter_id, annotations\n\n    def box_prompt(self, bbox=None, bboxes=None):\n        if self.results == None:\n            return []\n        assert bbox or bboxes\n        if bboxes is None:\n            bboxes = [bbox]\n        max_iou_index = []\n        for bbox in bboxes:\n            assert (bbox[2] != 0 and bbox[3] != 0)\n            masks = self.results[0].masks.data\n            target_height = self.img.shape[0]\n            target_width = self.img.shape[1]\n            h = masks.shape[1]\n            w = masks.shape[2]\n            if h != target_height or w != target_width:\n                bbox = [\n                    int(bbox[0] * w / target_width),\n                    int(bbox[1] * h / target_height),\n                    int(bbox[2] * w / target_width),\n                    int(bbox[3] * h / target_height), ]\n            bbox[0] = round(bbox[0]) if round(bbox[0]) > 0 else 0\n            bbox[1] = round(bbox[1]) if round(bbox[1]) > 0 else 0\n            bbox[2] = round(bbox[2]) if round(bbox[2]) < w else w\n            bbox[3] = round(bbox[3]) if round(bbox[3]) < h else h\n\n            # IoUs = torch.zeros(len(masks), dtype=torch.float32)\n            bbox_area = (bbox[3] - bbox[1]) * (bbox[2] - bbox[0])\n\n            masks_area = torch.sum(masks[:, bbox[1]:bbox[3], bbox[0]:bbox[2]], dim=(1, 2))\n            orig_masks_area = torch.sum(masks, dim=(1, 2))\n\n            union = bbox_area + orig_masks_area - masks_area\n            IoUs = masks_area / union\n            max_iou_index.append(int(torch.argmax(IoUs)))\n        max_iou_index = list(set(max_iou_index))\n        return np.array(masks[max_iou_index].cpu().numpy())\n\n    def point_prompt(self, points, pointlabel):  # numpy \n        if self.results == None:\n            return []\n        masks = self._format_results(self.results[0], 0)\n        target_height = self.img.shape[0]\n        target_width = self.img.shape[1]\n        h = masks[0]['segmentation'].shape[0]\n        w = masks[0]['segmentation'].shape[1]\n        if h != target_height or w != target_width:\n            points = [[int(point[0] * w / target_width), int(point[1] * h / target_height)] for point in points]\n        onemask = np.zeros((h, w))\n        masks = sorted(masks, key=lambda x: x['area'], reverse=True)\n        for i, annotation in enumerate(masks):\n            if type(annotation) == dict:\n                mask = annotation['segmentation']\n            else:\n                mask = annotation\n            for i, point in enumerate(points):\n                if mask[point[1], point[0]] == 1 and pointlabel[i] == 1:\n                    onemask[mask] = 1\n                if mask[point[1], point[0]] == 1 and pointlabel[i] == 0:\n                    onemask[mask] = 0\n        onemask = onemask >= 1\n        return np.array([onemask])\n\n    def text_prompt(self, text):\n        if self.results == None:\n            return []\n        format_results = self._format_results(self.results[0], 0)\n        cropped_boxes, cropped_images, not_crop, filter_id, annotations = self._crop_image(format_results)\n        clip_model, preprocess = clip.load('ViT-B/32', device=self.device)\n        scores = self.retrieve(clip_model, preprocess, cropped_boxes, text, device=self.device)\n        max_idx = scores.argsort()\n        max_idx = max_idx[-1]\n        max_idx += sum(np.array(filter_id) <= int(max_idx))\n        return np.array([annotations[max_idx]['segmentation']])\n\n    def everything_prompt(self):\n        if self.results == None:\n            return []\n        return self.results[0].masks.data\n        \n"
  },
  {
    "path": "fastsam/utils.py",
    "content": "import numpy as np\nimport torch\nfrom PIL import Image\n\n\ndef adjust_bboxes_to_image_border(boxes, image_shape, threshold=20):\n    '''Adjust bounding boxes to stick to image border if they are within a certain threshold.\n    Args:\n    boxes: (n, 4)\n    image_shape: (height, width)\n    threshold: pixel threshold\n    Returns:\n    adjusted_boxes: adjusted bounding boxes\n    '''\n\n    # Image dimensions\n    h, w = image_shape\n\n    # Adjust boxes\n    boxes[:, 0] = torch.where(boxes[:, 0] < threshold, torch.tensor(\n        0, dtype=torch.float, device=boxes.device), boxes[:, 0])  # x1\n    boxes[:, 1] = torch.where(boxes[:, 1] < threshold, torch.tensor(\n        0, dtype=torch.float, device=boxes.device), boxes[:, 1])  # y1\n    boxes[:, 2] = torch.where(boxes[:, 2] > w - threshold, torch.tensor(\n        w, dtype=torch.float, device=boxes.device), boxes[:, 2])  # x2\n    boxes[:, 3] = torch.where(boxes[:, 3] > h - threshold, torch.tensor(\n        h, dtype=torch.float, device=boxes.device), boxes[:, 3])  # y2\n\n    return boxes\n\n\n\ndef convert_box_xywh_to_xyxy(box):\n    x1 = box[0]\n    y1 = box[1]\n    x2 = box[0] + box[2]\n    y2 = box[1] + box[3]\n    return [x1, y1, x2, y2]\n\n\ndef bbox_iou(box1, boxes, iou_thres=0.9, image_shape=(640, 640), raw_output=False):\n    '''Compute the Intersection-Over-Union of a bounding box with respect to an array of other bounding boxes.\n    Args:\n    box1: (4, )\n    boxes: (n, 4)\n    Returns:\n    high_iou_indices: Indices of boxes with IoU > thres\n    '''\n    boxes = adjust_bboxes_to_image_border(boxes, image_shape)\n    # obtain coordinates for intersections\n    x1 = torch.max(box1[0], boxes[:, 0])\n    y1 = torch.max(box1[1], boxes[:, 1])\n    x2 = torch.min(box1[2], boxes[:, 2])\n    y2 = torch.min(box1[3], boxes[:, 3])\n\n    # compute the area of intersection\n    intersection = (x2 - x1).clamp(0) * (y2 - y1).clamp(0)\n\n    # compute the area of both individual boxes\n    box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])\n    box2_area = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])\n\n    # compute the area of union\n    union = box1_area + box2_area - intersection\n\n    # compute the IoU\n    iou = intersection / union  # Should be shape (n, )\n    if raw_output:\n        if iou.numel() == 0:\n            return 0\n        return iou\n\n    # get indices of boxes with IoU > thres\n    high_iou_indices = torch.nonzero(iou > iou_thres).flatten()\n\n    return high_iou_indices\n\n\ndef image_to_np_ndarray(image):\n    if type(image) is str:\n        return np.array(Image.open(image))\n    elif issubclass(type(image), Image.Image):\n        return np.array(image)\n    elif type(image) is np.ndarray:\n        return image\n    return None\n"
  },
  {
    "path": "predict.py",
    "content": "# Prediction interface for Cog ⚙️\n# https://github.com/replicate/cog/blob/main/docs/python.md\n# Thanks for chenxwh.\n\nimport argparse\nimport cv2\nimport shutil\nimport ast\nfrom cog import BasePredictor, Input, Path\nfrom ultralytics import YOLO\nfrom utils.tools import *\n\n\nclass Predictor(BasePredictor):\n    def setup(self):\n        \"\"\"Load the model into memory to make running multiple predictions efficient\"\"\"\n        self.models = {k: YOLO(f\"{k}.pt\") for k in [\"FastSAM-s\", \"FastSAM-x\"]}\n\n    def predict(\n        self,\n        input_image: Path = Input(description=\"Input image\"),\n        model_name: str = Input(\n            description=\"choose a model\",\n            choices=[\"FastSAM-x\", \"FastSAM-s\"],\n            default=\"FastSAM-x\",\n        ),\n        iou: float = Input(\n            description=\"iou threshold for filtering the annotations\", default=0.7\n        ),\n        text_prompt: str = Input(\n            description='use text prompt eg: \"a black dog\"', default=None\n        ),\n        conf: float = Input(description=\"object confidence threshold\", default=0.25),\n        retina: bool = Input(\n            description=\"draw high-resolution segmentation masks\", default=True\n        ),\n        box_prompt: str = Input(default=\"[0,0,0,0]\", description=\"[x,y,w,h]\"),\n        point_prompt: str = Input(default=\"[[0,0]]\", description=\"[[x1,y1],[x2,y2]]\"),\n        point_label: str = Input(default=\"[0]\", description=\"[1,0] 0:background, 1:foreground\"),\n        withContours: bool = Input(\n            description=\"draw the edges of the masks\", default=False\n        ),\n        better_quality: bool = Input(\n            description=\"better quality using morphologyEx\", default=False\n        ),\n    ) -> Path:\n        \"\"\"Run a single prediction on the model\"\"\"\n\n        # default params\n\n        out_path = \"output\"\n        if os.path.exists(out_path):\n            shutil.rmtree(out_path)\n        os.makedirs(out_path, exist_ok=True)\n\n        device = torch.device(\n            \"cuda\"\n            if torch.cuda.is_available()\n            else \"mps\"\n            if torch.backends.mps.is_available()\n            else \"cpu\"\n        )\n        \n        args = argparse.Namespace(\n            better_quality=better_quality,\n            box_prompt=box_prompt,\n            conf=conf,\n            device=device,\n            img_path=str(input_image),\n            imgsz=1024,\n            iou=iou,\n            model_path=\"FastSAM-x.pt\",\n            output=out_path,\n            point_label=point_label,\n            point_prompt=point_prompt,\n            randomcolor=True,\n            retina=retina,\n            text_prompt=text_prompt,\n            withContours=withContours,\n        )\n        args.point_prompt = ast.literal_eval(args.point_prompt)\n        args.box_prompt = ast.literal_eval(args.box_prompt)\n        args.point_label = ast.literal_eval(args.point_label)\n\n        model = self.models[model_name]\n\n        results = model(\n            str(input_image),\n            imgsz=args.imgsz,\n            device=args.device,\n            retina_masks=args.retina,\n            iou=args.iou,\n            conf=args.conf,\n            max_det=100,\n        )\n\n        if args.box_prompt[2] != 0 and args.box_prompt[3] != 0:\n            annotations = prompt(results, args, box=True)\n            annotations = np.array([annotations])\n            fast_process(\n                annotations=annotations,\n                args=args,\n                mask_random_color=args.randomcolor,\n                bbox=convert_box_xywh_to_xyxy(args.box_prompt),\n            )\n\n        elif args.text_prompt != None:\n            results = format_results(results[0], 0)\n            annotations = prompt(results, args, text=True)\n            annotations = np.array([annotations])\n            fast_process(\n                annotations=annotations, args=args, mask_random_color=args.randomcolor\n            )\n\n        elif args.point_prompt[0] != [0, 0]:\n            results = format_results(results[0], 0)\n            annotations = prompt(results, args, point=True)\n            # list to numpy\n            annotations = np.array([annotations])\n            fast_process(\n                annotations=annotations,\n                args=args,\n                mask_random_color=args.randomcolor,\n                points=args.point_prompt,\n            )\n\n        else:\n            fast_process(\n                annotations=results[0].masks.data,\n                args=args,\n                mask_random_color=args.randomcolor,\n            )\n\n        out = \"/tmp.out.png\"\n        shutil.copy(os.path.join(out_path, os.listdir(out_path)[0]), out)\n\n        return Path(out)\n\n\ndef prompt(results, args, box=None, point=None, text=None):\n    ori_img = cv2.imread(args.img_path)\n    ori_h = ori_img.shape[0]\n    ori_w = ori_img.shape[1]\n    if box:\n        mask, idx = box_prompt(\n            results[0].masks.data,\n            convert_box_xywh_to_xyxy(args.box_prompt),\n            ori_h,\n            ori_w,\n        )\n    elif point:\n        mask, idx = point_prompt(\n            results, args.point_prompt, args.point_label, ori_h, ori_w\n        )\n    elif text:\n        mask, idx = text_prompt(results, args.text_prompt, args.img_path, args.device)\n    else:\n        return None\n    return mask\n"
  },
  {
    "path": "requirements.txt",
    "content": "# Base-----------------------------------\r\nmatplotlib>=3.2.2\r\nopencv-python>=4.6.0\r\nPillow>=7.1.2\r\nPyYAML>=5.3.1\r\nrequests>=2.23.0\r\nscipy>=1.4.1\r\ntorch>=1.7.0\r\ntorchvision>=0.8.1\r\ntqdm>=4.64.0\r\n\r\npandas>=1.1.4\r\nseaborn>=0.11.0\r\n\r\ngradio==3.35.2\r\n\r\n# Ultralytics-----------------------------------\r\n# ultralytics == 8.0.120\r\n\r\n"
  },
  {
    "path": "segpredict.py",
    "content": "from fastsam import FastSAM, FastSAMPrompt\nimport torch \n\nmodel = FastSAM('FastSAM.pt')\nIMAGE_PATH = './images/dogs.jpg'\nDEVICE = torch.device(\n    \"cuda\"\n    if torch.cuda.is_available()\n    else \"mps\"\n    if torch.backends.mps.is_available()\n    else \"cpu\"\n)\neverything_results = model(\n    IMAGE_PATH,\n    device=DEVICE,\n    retina_masks=True,\n    imgsz=1024,\n    conf=0.4,\n    iou=0.9,\n)\nprompt_process = FastSAMPrompt(IMAGE_PATH, everything_results, device=DEVICE)\n\n# # everything prompt\nann = prompt_process.everything_prompt()\n\n# # bbox prompt\n# # bbox default shape [0,0,0,0] -> [x1,y1,x2,y2]\n# bboxes default shape [[0,0,0,0]] -> [[x1,y1,x2,y2]]\n# ann = prompt_process.box_prompt(bbox=[200, 200, 300, 300])\n# ann = prompt_process.box_prompt(bboxes=[[200, 200, 300, 300], [500, 500, 600, 600]])\n\n# # text prompt\n# ann = prompt_process.text_prompt(text='a photo of a dog')\n\n# # point prompt\n# # points default [[0,0]] [[x1,y1],[x2,y2]]\n# # point_label default [0] [1,0] 0:background, 1:foreground\n# ann = prompt_process.point_prompt(points=[[620, 360]], pointlabel=[1])\n\n# point prompt\n# points default [[0,0]] [[x1,y1],[x2,y2]]\n# point_label default [0] [1,0] 0:background, 1:foreground\nann = prompt_process.point_prompt(points=[[620, 360]], pointlabel=[1])\n\nprompt_process.plot(\n    annotations=ann,\n    output='./output/',\n    mask_random_color=True,\n    better_quality=True,\n    retina=False,\n    withContours=True,\n)\n"
  },
  {
    "path": "setup.py",
    "content": "# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom setuptools import find_packages, setup\n\nREQUIREMENTS = [i.strip() for i in open(\"requirements.txt\").readlines()]\nREQUIREMENTS += [\n    \"CLIP @ git+https://github.com/openai/CLIP.git@a1d071733d7111c9c014f024669f959182114e33#egg=CLIP\"\n]\n\nsetup(\n    name=\"fastsam\",\n    version=\"0.1.1\",\n    install_requires=REQUIREMENTS,\n    packages=[\"fastsam\", \"fastsam_tools\"],\n    package_dir= {\n        \"fastsam\": \"fastsam\",\n        \"fastsam_tools\": \"utils\",\n    },\n    url=\"https://github.com/CASIA-IVA-Lab/FastSAM\"\n)\n"
  },
  {
    "path": "ultralytics/.pre-commit-config.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Pre-commit hooks. For more information see https://github.com/pre-commit/pre-commit-hooks/blob/main/README.md\n\nexclude: 'docs/'\n# Define bot property if installed via https://github.com/marketplace/pre-commit-ci\nci:\n  autofix_prs: true\n  autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions'\n  autoupdate_schedule: monthly\n  # submodules: true\n\nrepos:\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v4.4.0\n    hooks:\n      - id: end-of-file-fixer\n      - id: trailing-whitespace\n      - id: check-case-conflict\n      # - id: check-yaml\n      - id: check-docstring-first\n      - id: double-quote-string-fixer\n      - id: detect-private-key\n\n  - repo: https://github.com/asottile/pyupgrade\n    rev: v3.4.0\n    hooks:\n      - id: pyupgrade\n        name: Upgrade code\n\n  - repo: https://github.com/PyCQA/isort\n    rev: 5.12.0\n    hooks:\n      - id: isort\n        name: Sort imports\n\n  - repo: https://github.com/google/yapf\n    rev: v0.33.0\n    hooks:\n      - id: yapf\n        name: YAPF formatting\n\n  - repo: https://github.com/executablebooks/mdformat\n    rev: 0.7.16\n    hooks:\n      - id: mdformat\n        name: MD formatting\n        additional_dependencies:\n          - mdformat-gfm\n          - mdformat-black\n        # exclude: \"README.md|README.zh-CN.md|CONTRIBUTING.md\"\n\n  - repo: https://github.com/PyCQA/flake8\n    rev: 6.0.0\n    hooks:\n      - id: flake8\n        name: PEP8\n\n  - repo: https://github.com/codespell-project/codespell\n    rev: v2.2.4\n    hooks:\n      - id: codespell\n        args:\n          - --ignore-words-list=crate,nd,strack,dota\n\n#  - repo: https://github.com/asottile/yesqa\n#    rev: v1.4.0\n#    hooks:\n#      - id: yesqa\n\n#  - repo: https://github.com/asottile/dead\n#    rev: v1.5.0\n#    hooks:\n#    -   id: dead\n"
  },
  {
    "path": "ultralytics/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n__version__ = '8.0.120'\n\nfrom ultralytics.hub import start\nfrom ultralytics.vit.rtdetr import RTDETR\nfrom ultralytics.vit.sam import SAM\nfrom ultralytics.yolo.engine.model import YOLO\nfrom ultralytics.yolo.nas import NAS\nfrom ultralytics.yolo.utils.checks import check_yolo as checks\n\n__all__ = '__version__', 'YOLO', 'NAS', 'SAM', 'RTDETR', 'checks', 'start'  # allow simpler import\n"
  },
  {
    "path": "ultralytics/datasets/Argoverse.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ by Argo AI\n# Example usage: yolo train data=Argoverse.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── Argoverse  ← downloads here (31.3 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/Argoverse  # dataset root dir\ntrain: Argoverse-1.1/images/train/  # train images (relative to 'path') 39384 images\nval: Argoverse-1.1/images/val/  # val images (relative to 'path') 15062 images\ntest: Argoverse-1.1/images/test/  # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  4: bus\n  5: truck\n  6: traffic_light\n  7: stop_sign\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  import json\n  from tqdm import tqdm\n  from ultralytics.yolo.utils.downloads import download\n  from pathlib import Path\n\n  def argoverse2yolo(set):\n      labels = {}\n      a = json.load(open(set, \"rb\"))\n      for annot in tqdm(a['annotations'], desc=f\"Converting {set} to YOLOv5 format...\"):\n          img_id = annot['image_id']\n          img_name = a['images'][img_id]['name']\n          img_label_name = f'{img_name[:-3]}txt'\n\n          cls = annot['category_id']  # instance class id\n          x_center, y_center, width, height = annot['bbox']\n          x_center = (x_center + width / 2) / 1920.0  # offset and scale\n          y_center = (y_center + height / 2) / 1200.0  # offset and scale\n          width /= 1920.0  # scale\n          height /= 1200.0  # scale\n\n          img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']]\n          if not img_dir.exists():\n              img_dir.mkdir(parents=True, exist_ok=True)\n\n          k = str(img_dir / img_label_name)\n          if k not in labels:\n              labels[k] = []\n          labels[k].append(f\"{cls} {x_center} {y_center} {width} {height}\\n\")\n\n      for k in labels:\n          with open(k, \"w\") as f:\n              f.writelines(labels[k])\n\n\n  # Download\n  dir = Path(yaml['path'])  # dataset root dir\n  urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip']\n  download(urls, dir=dir)\n\n  # Convert\n  annotations_dir = 'Argoverse-HD/annotations/'\n  (dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images')  # rename 'tracking' to 'images'\n  for d in \"train.json\", \"val.json\":\n      argoverse2yolo(dir / annotations_dir / d)  # convert VisDrone annotations to YOLO labels\n"
  },
  {
    "path": "ultralytics/datasets/GlobalWheat2020.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Global Wheat 2020 dataset http://www.global-wheat.com/ by University of Saskatchewan\n# Example usage: yolo train data=GlobalWheat2020.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── GlobalWheat2020  ← downloads here (7.0 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/GlobalWheat2020  # dataset root dir\ntrain: # train images (relative to 'path') 3422 images\n  - images/arvalis_1\n  - images/arvalis_2\n  - images/arvalis_3\n  - images/ethz_1\n  - images/rres_1\n  - images/inrae_1\n  - images/usask_1\nval: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1)\n  - images/ethz_1\ntest: # test images (optional) 1276 images\n  - images/utokyo_1\n  - images/utokyo_2\n  - images/nau_1\n  - images/uq_1\n\n# Classes\nnames:\n  0: wheat_head\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  from ultralytics.yolo.utils.downloads import download\n  from pathlib import Path\n\n  # Download\n  dir = Path(yaml['path'])  # dataset root dir\n  urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',\n          'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip']\n  download(urls, dir=dir)\n\n  # Make Directories\n  for p in 'annotations', 'images', 'labels':\n      (dir / p).mkdir(parents=True, exist_ok=True)\n\n  # Move\n  for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \\\n           'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':\n      (dir / 'global-wheat-codalab-official' / p).rename(dir / 'images' / p)  # move to /images\n      f = (dir / 'global-wheat-codalab-official' / p).with_suffix('.json')  # json file\n      if f.exists():\n          f.rename((dir / 'annotations' / p).with_suffix('.json'))  # move to /annotations\n"
  },
  {
    "path": "ultralytics/datasets/ImageNet.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# ImageNet-1k dataset https://www.image-net.org/index.php by Stanford University\n# Simplified class names from https://github.com/anishathalye/imagenet-simple-labels\n# Example usage: yolo train task=classify data=imagenet\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── imagenet  ← downloads here (144 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/imagenet  # dataset root dir\ntrain: train  # train images (relative to 'path') 1281167 images\nval: val  # val images (relative to 'path') 50000 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: tench\n  1: goldfish\n  2: great white shark\n  3: tiger shark\n  4: hammerhead shark\n  5: electric ray\n  6: stingray\n  7: cock\n  8: hen\n  9: ostrich\n  10: brambling\n  11: goldfinch\n  12: house finch\n  13: junco\n  14: indigo bunting\n  15: American robin\n  16: bulbul\n  17: jay\n  18: magpie\n  19: chickadee\n  20: American dipper\n  21: kite\n  22: bald eagle\n  23: vulture\n  24: great grey owl\n  25: fire salamander\n  26: smooth newt\n  27: newt\n  28: spotted salamander\n  29: axolotl\n  30: American bullfrog\n  31: tree frog\n  32: tailed frog\n  33: loggerhead sea turtle\n  34: leatherback sea turtle\n  35: mud turtle\n  36: terrapin\n  37: box turtle\n  38: banded gecko\n  39: green iguana\n  40: Carolina anole\n  41: desert grassland whiptail lizard\n  42: agama\n  43: frilled-necked lizard\n  44: alligator lizard\n  45: Gila monster\n  46: European green lizard\n  47: chameleon\n  48: Komodo dragon\n  49: Nile crocodile\n  50: American alligator\n  51: triceratops\n  52: worm snake\n  53: ring-necked snake\n  54: eastern hog-nosed snake\n  55: smooth green snake\n  56: kingsnake\n  57: garter snake\n  58: water snake\n  59: vine snake\n  60: night snake\n  61: boa constrictor\n  62: African rock python\n  63: Indian cobra\n  64: green mamba\n  65: sea snake\n  66: Saharan horned viper\n  67: eastern diamondback rattlesnake\n  68: sidewinder\n  69: trilobite\n  70: harvestman\n  71: scorpion\n  72: yellow garden spider\n  73: barn spider\n  74: European garden spider\n  75: southern black widow\n  76: tarantula\n  77: wolf spider\n  78: tick\n  79: centipede\n  80: black grouse\n  81: ptarmigan\n  82: ruffed grouse\n  83: prairie grouse\n  84: peacock\n  85: quail\n  86: partridge\n  87: grey parrot\n  88: macaw\n  89: sulphur-crested cockatoo\n  90: lorikeet\n  91: coucal\n  92: bee eater\n  93: hornbill\n  94: hummingbird\n  95: jacamar\n  96: toucan\n  97: duck\n  98: red-breasted merganser\n  99: goose\n  100: black swan\n  101: tusker\n  102: echidna\n  103: platypus\n  104: wallaby\n  105: koala\n  106: wombat\n  107: jellyfish\n  108: sea anemone\n  109: brain coral\n  110: flatworm\n  111: nematode\n  112: conch\n  113: snail\n  114: slug\n  115: sea slug\n  116: chiton\n  117: chambered nautilus\n  118: Dungeness crab\n  119: rock crab\n  120: fiddler crab\n  121: red king crab\n  122: American lobster\n  123: spiny lobster\n  124: crayfish\n  125: hermit crab\n  126: isopod\n  127: white stork\n  128: black stork\n  129: spoonbill\n  130: flamingo\n  131: little blue heron\n  132: great egret\n  133: bittern\n  134: crane (bird)\n  135: limpkin\n  136: common gallinule\n  137: American coot\n  138: bustard\n  139: ruddy turnstone\n  140: dunlin\n  141: common redshank\n  142: dowitcher\n  143: oystercatcher\n  144: pelican\n  145: king penguin\n  146: albatross\n  147: grey whale\n  148: killer whale\n  149: dugong\n  150: sea lion\n  151: Chihuahua\n  152: Japanese Chin\n  153: Maltese\n  154: Pekingese\n  155: Shih Tzu\n  156: King Charles Spaniel\n  157: Papillon\n  158: toy terrier\n  159: Rhodesian Ridgeback\n  160: Afghan Hound\n  161: Basset Hound\n  162: Beagle\n  163: Bloodhound\n  164: Bluetick Coonhound\n  165: Black and Tan Coonhound\n  166: Treeing Walker Coonhound\n  167: English foxhound\n  168: Redbone Coonhound\n  169: borzoi\n  170: Irish Wolfhound\n  171: Italian Greyhound\n  172: Whippet\n  173: Ibizan Hound\n  174: Norwegian Elkhound\n  175: Otterhound\n  176: Saluki\n  177: Scottish Deerhound\n  178: Weimaraner\n  179: Staffordshire Bull Terrier\n  180: American Staffordshire Terrier\n  181: Bedlington Terrier\n  182: Border Terrier\n  183: Kerry Blue Terrier\n  184: Irish Terrier\n  185: Norfolk Terrier\n  186: Norwich Terrier\n  187: Yorkshire Terrier\n  188: Wire Fox Terrier\n  189: Lakeland Terrier\n  190: Sealyham Terrier\n  191: Airedale Terrier\n  192: Cairn Terrier\n  193: Australian Terrier\n  194: Dandie Dinmont Terrier\n  195: Boston Terrier\n  196: Miniature Schnauzer\n  197: Giant Schnauzer\n  198: Standard Schnauzer\n  199: Scottish Terrier\n  200: Tibetan Terrier\n  201: Australian Silky Terrier\n  202: Soft-coated Wheaten Terrier\n  203: West Highland White Terrier\n  204: Lhasa Apso\n  205: Flat-Coated Retriever\n  206: Curly-coated Retriever\n  207: Golden Retriever\n  208: Labrador Retriever\n  209: Chesapeake Bay Retriever\n  210: German Shorthaired Pointer\n  211: Vizsla\n  212: English Setter\n  213: Irish Setter\n  214: Gordon Setter\n  215: Brittany\n  216: Clumber Spaniel\n  217: English Springer Spaniel\n  218: Welsh Springer Spaniel\n  219: Cocker Spaniels\n  220: Sussex Spaniel\n  221: Irish Water Spaniel\n  222: Kuvasz\n  223: Schipperke\n  224: Groenendael\n  225: Malinois\n  226: Briard\n  227: Australian Kelpie\n  228: Komondor\n  229: Old English Sheepdog\n  230: Shetland Sheepdog\n  231: collie\n  232: Border Collie\n  233: Bouvier des Flandres\n  234: Rottweiler\n  235: German Shepherd Dog\n  236: Dobermann\n  237: Miniature Pinscher\n  238: Greater Swiss Mountain Dog\n  239: Bernese Mountain Dog\n  240: Appenzeller Sennenhund\n  241: Entlebucher Sennenhund\n  242: Boxer\n  243: Bullmastiff\n  244: Tibetan Mastiff\n  245: French Bulldog\n  246: Great Dane\n  247: St. Bernard\n  248: husky\n  249: Alaskan Malamute\n  250: Siberian Husky\n  251: Dalmatian\n  252: Affenpinscher\n  253: Basenji\n  254: pug\n  255: Leonberger\n  256: Newfoundland\n  257: Pyrenean Mountain Dog\n  258: Samoyed\n  259: Pomeranian\n  260: Chow Chow\n  261: Keeshond\n  262: Griffon Bruxellois\n  263: Pembroke Welsh Corgi\n  264: Cardigan Welsh Corgi\n  265: Toy Poodle\n  266: Miniature Poodle\n  267: Standard Poodle\n  268: Mexican hairless dog\n  269: grey wolf\n  270: Alaskan tundra wolf\n  271: red wolf\n  272: coyote\n  273: dingo\n  274: dhole\n  275: African wild dog\n  276: hyena\n  277: red fox\n  278: kit fox\n  279: Arctic fox\n  280: grey fox\n  281: tabby cat\n  282: tiger cat\n  283: Persian cat\n  284: Siamese cat\n  285: Egyptian Mau\n  286: cougar\n  287: lynx\n  288: leopard\n  289: snow leopard\n  290: jaguar\n  291: lion\n  292: tiger\n  293: cheetah\n  294: brown bear\n  295: American black bear\n  296: polar bear\n  297: sloth bear\n  298: mongoose\n  299: meerkat\n  300: tiger beetle\n  301: ladybug\n  302: ground beetle\n  303: longhorn beetle\n  304: leaf beetle\n  305: dung beetle\n  306: rhinoceros beetle\n  307: weevil\n  308: fly\n  309: bee\n  310: ant\n  311: grasshopper\n  312: cricket\n  313: stick insect\n  314: cockroach\n  315: mantis\n  316: cicada\n  317: leafhopper\n  318: lacewing\n  319: dragonfly\n  320: damselfly\n  321: red admiral\n  322: ringlet\n  323: monarch butterfly\n  324: small white\n  325: sulphur butterfly\n  326: gossamer-winged butterfly\n  327: starfish\n  328: sea urchin\n  329: sea cucumber\n  330: cottontail rabbit\n  331: hare\n  332: Angora rabbit\n  333: hamster\n  334: porcupine\n  335: fox squirrel\n  336: marmot\n  337: beaver\n  338: guinea pig\n  339: common sorrel\n  340: zebra\n  341: pig\n  342: wild boar\n  343: warthog\n  344: hippopotamus\n  345: ox\n  346: water buffalo\n  347: bison\n  348: ram\n  349: bighorn sheep\n  350: Alpine ibex\n  351: hartebeest\n  352: impala\n  353: gazelle\n  354: dromedary\n  355: llama\n  356: weasel\n  357: mink\n  358: European polecat\n  359: black-footed ferret\n  360: otter\n  361: skunk\n  362: badger\n  363: armadillo\n  364: three-toed sloth\n  365: orangutan\n  366: gorilla\n  367: chimpanzee\n  368: gibbon\n  369: siamang\n  370: guenon\n  371: patas monkey\n  372: baboon\n  373: macaque\n  374: langur\n  375: black-and-white colobus\n  376: proboscis monkey\n  377: marmoset\n  378: white-headed capuchin\n  379: howler monkey\n  380: titi\n  381: Geoffroy's spider monkey\n  382: common squirrel monkey\n  383: ring-tailed lemur\n  384: indri\n  385: Asian elephant\n  386: African bush elephant\n  387: red panda\n  388: giant panda\n  389: snoek\n  390: eel\n  391: coho salmon\n  392: rock beauty\n  393: clownfish\n  394: sturgeon\n  395: garfish\n  396: lionfish\n  397: pufferfish\n  398: abacus\n  399: abaya\n  400: academic gown\n  401: accordion\n  402: acoustic guitar\n  403: aircraft carrier\n  404: airliner\n  405: airship\n  406: altar\n  407: ambulance\n  408: amphibious vehicle\n  409: analog clock\n  410: apiary\n  411: apron\n  412: waste container\n  413: assault rifle\n  414: backpack\n  415: bakery\n  416: balance beam\n  417: balloon\n  418: ballpoint pen\n  419: Band-Aid\n  420: banjo\n  421: baluster\n  422: barbell\n  423: barber chair\n  424: barbershop\n  425: barn\n  426: barometer\n  427: barrel\n  428: wheelbarrow\n  429: baseball\n  430: basketball\n  431: bassinet\n  432: bassoon\n  433: swimming cap\n  434: bath towel\n  435: bathtub\n  436: station wagon\n  437: lighthouse\n  438: beaker\n  439: military cap\n  440: beer bottle\n  441: beer glass\n  442: bell-cot\n  443: bib\n  444: tandem bicycle\n  445: bikini\n  446: ring binder\n  447: binoculars\n  448: birdhouse\n  449: boathouse\n  450: bobsleigh\n  451: bolo tie\n  452: poke bonnet\n  453: bookcase\n  454: bookstore\n  455: bottle cap\n  456: bow\n  457: bow tie\n  458: brass\n  459: bra\n  460: breakwater\n  461: breastplate\n  462: broom\n  463: bucket\n  464: buckle\n  465: bulletproof vest\n  466: high-speed train\n  467: butcher shop\n  468: taxicab\n  469: cauldron\n  470: candle\n  471: cannon\n  472: canoe\n  473: can opener\n  474: cardigan\n  475: car mirror\n  476: carousel\n  477: tool kit\n  478: carton\n  479: car wheel\n  480: automated teller machine\n  481: cassette\n  482: cassette player\n  483: castle\n  484: catamaran\n  485: CD player\n  486: cello\n  487: mobile phone\n  488: chain\n  489: chain-link fence\n  490: chain mail\n  491: chainsaw\n  492: chest\n  493: chiffonier\n  494: chime\n  495: china cabinet\n  496: Christmas stocking\n  497: church\n  498: movie theater\n  499: cleaver\n  500: cliff dwelling\n  501: cloak\n  502: clogs\n  503: cocktail shaker\n  504: coffee mug\n  505: coffeemaker\n  506: coil\n  507: combination lock\n  508: computer keyboard\n  509: confectionery store\n  510: container ship\n  511: convertible\n  512: corkscrew\n  513: cornet\n  514: cowboy boot\n  515: cowboy hat\n  516: cradle\n  517: crane (machine)\n  518: crash helmet\n  519: crate\n  520: infant bed\n  521: Crock Pot\n  522: croquet ball\n  523: crutch\n  524: cuirass\n  525: dam\n  526: desk\n  527: desktop computer\n  528: rotary dial telephone\n  529: diaper\n  530: digital clock\n  531: digital watch\n  532: dining table\n  533: dishcloth\n  534: dishwasher\n  535: disc brake\n  536: dock\n  537: dog sled\n  538: dome\n  539: doormat\n  540: drilling rig\n  541: drum\n  542: drumstick\n  543: dumbbell\n  544: Dutch oven\n  545: electric fan\n  546: electric guitar\n  547: electric locomotive\n  548: entertainment center\n  549: envelope\n  550: espresso machine\n  551: face powder\n  552: feather boa\n  553: filing cabinet\n  554: fireboat\n  555: fire engine\n  556: fire screen sheet\n  557: flagpole\n  558: flute\n  559: folding chair\n  560: football helmet\n  561: forklift\n  562: fountain\n  563: fountain pen\n  564: four-poster bed\n  565: freight car\n  566: French horn\n  567: frying pan\n  568: fur coat\n  569: garbage truck\n  570: gas mask\n  571: gas pump\n  572: goblet\n  573: go-kart\n  574: golf ball\n  575: golf cart\n  576: gondola\n  577: gong\n  578: gown\n  579: grand piano\n  580: greenhouse\n  581: grille\n  582: grocery store\n  583: guillotine\n  584: barrette\n  585: hair spray\n  586: half-track\n  587: hammer\n  588: hamper\n  589: hair dryer\n  590: hand-held computer\n  591: handkerchief\n  592: hard disk drive\n  593: harmonica\n  594: harp\n  595: harvester\n  596: hatchet\n  597: holster\n  598: home theater\n  599: honeycomb\n  600: hook\n  601: hoop skirt\n  602: horizontal bar\n  603: horse-drawn vehicle\n  604: hourglass\n  605: iPod\n  606: clothes iron\n  607: jack-o'-lantern\n  608: jeans\n  609: jeep\n  610: T-shirt\n  611: jigsaw puzzle\n  612: pulled rickshaw\n  613: joystick\n  614: kimono\n  615: knee pad\n  616: knot\n  617: lab coat\n  618: ladle\n  619: lampshade\n  620: laptop computer\n  621: lawn mower\n  622: lens cap\n  623: paper knife\n  624: library\n  625: lifeboat\n  626: lighter\n  627: limousine\n  628: ocean liner\n  629: lipstick\n  630: slip-on shoe\n  631: lotion\n  632: speaker\n  633: loupe\n  634: sawmill\n  635: magnetic compass\n  636: mail bag\n  637: mailbox\n  638: tights\n  639: tank suit\n  640: manhole cover\n  641: maraca\n  642: marimba\n  643: mask\n  644: match\n  645: maypole\n  646: maze\n  647: measuring cup\n  648: medicine chest\n  649: megalith\n  650: microphone\n  651: microwave oven\n  652: military uniform\n  653: milk can\n  654: minibus\n  655: miniskirt\n  656: minivan\n  657: missile\n  658: mitten\n  659: mixing bowl\n  660: mobile home\n  661: Model T\n  662: modem\n  663: monastery\n  664: monitor\n  665: moped\n  666: mortar\n  667: square academic cap\n  668: mosque\n  669: mosquito net\n  670: scooter\n  671: mountain bike\n  672: tent\n  673: computer mouse\n  674: mousetrap\n  675: moving van\n  676: muzzle\n  677: nail\n  678: neck brace\n  679: necklace\n  680: nipple\n  681: notebook computer\n  682: obelisk\n  683: oboe\n  684: ocarina\n  685: odometer\n  686: oil filter\n  687: organ\n  688: oscilloscope\n  689: overskirt\n  690: bullock cart\n  691: oxygen mask\n  692: packet\n  693: paddle\n  694: paddle wheel\n  695: padlock\n  696: paintbrush\n  697: pajamas\n  698: palace\n  699: pan flute\n  700: paper towel\n  701: parachute\n  702: parallel bars\n  703: park bench\n  704: parking meter\n  705: passenger car\n  706: patio\n  707: payphone\n  708: pedestal\n  709: pencil case\n  710: pencil sharpener\n  711: perfume\n  712: Petri dish\n  713: photocopier\n  714: plectrum\n  715: Pickelhaube\n  716: picket fence\n  717: pickup truck\n  718: pier\n  719: piggy bank\n  720: pill bottle\n  721: pillow\n  722: ping-pong ball\n  723: pinwheel\n  724: pirate ship\n  725: pitcher\n  726: hand plane\n  727: planetarium\n  728: plastic bag\n  729: plate rack\n  730: plow\n  731: plunger\n  732: Polaroid camera\n  733: pole\n  734: police van\n  735: poncho\n  736: billiard table\n  737: soda bottle\n  738: pot\n  739: potter's wheel\n  740: power drill\n  741: prayer rug\n  742: printer\n  743: prison\n  744: projectile\n  745: projector\n  746: hockey puck\n  747: punching bag\n  748: purse\n  749: quill\n  750: quilt\n  751: race car\n  752: racket\n  753: radiator\n  754: radio\n  755: radio telescope\n  756: rain barrel\n  757: recreational vehicle\n  758: reel\n  759: reflex camera\n  760: refrigerator\n  761: remote control\n  762: restaurant\n  763: revolver\n  764: rifle\n  765: rocking chair\n  766: rotisserie\n  767: eraser\n  768: rugby ball\n  769: ruler\n  770: running shoe\n  771: safe\n  772: safety pin\n  773: salt shaker\n  774: sandal\n  775: sarong\n  776: saxophone\n  777: scabbard\n  778: weighing scale\n  779: school bus\n  780: schooner\n  781: scoreboard\n  782: CRT screen\n  783: screw\n  784: screwdriver\n  785: seat belt\n  786: sewing machine\n  787: shield\n  788: shoe store\n  789: shoji\n  790: shopping basket\n  791: shopping cart\n  792: shovel\n  793: shower cap\n  794: shower curtain\n  795: ski\n  796: ski mask\n  797: sleeping bag\n  798: slide rule\n  799: sliding door\n  800: slot machine\n  801: snorkel\n  802: snowmobile\n  803: snowplow\n  804: soap dispenser\n  805: soccer ball\n  806: sock\n  807: solar thermal collector\n  808: sombrero\n  809: soup bowl\n  810: space bar\n  811: space heater\n  812: space shuttle\n  813: spatula\n  814: motorboat\n  815: spider web\n  816: spindle\n  817: sports car\n  818: spotlight\n  819: stage\n  820: steam locomotive\n  821: through arch bridge\n  822: steel drum\n  823: stethoscope\n  824: scarf\n  825: stone wall\n  826: stopwatch\n  827: stove\n  828: strainer\n  829: tram\n  830: stretcher\n  831: couch\n  832: stupa\n  833: submarine\n  834: suit\n  835: sundial\n  836: sunglass\n  837: sunglasses\n  838: sunscreen\n  839: suspension bridge\n  840: mop\n  841: sweatshirt\n  842: swimsuit\n  843: swing\n  844: switch\n  845: syringe\n  846: table lamp\n  847: tank\n  848: tape player\n  849: teapot\n  850: teddy bear\n  851: television\n  852: tennis ball\n  853: thatched roof\n  854: front curtain\n  855: thimble\n  856: threshing machine\n  857: throne\n  858: tile roof\n  859: toaster\n  860: tobacco shop\n  861: toilet seat\n  862: torch\n  863: totem pole\n  864: tow truck\n  865: toy store\n  866: tractor\n  867: semi-trailer truck\n  868: tray\n  869: trench coat\n  870: tricycle\n  871: trimaran\n  872: tripod\n  873: triumphal arch\n  874: trolleybus\n  875: trombone\n  876: tub\n  877: turnstile\n  878: typewriter keyboard\n  879: umbrella\n  880: unicycle\n  881: upright piano\n  882: vacuum cleaner\n  883: vase\n  884: vault\n  885: velvet\n  886: vending machine\n  887: vestment\n  888: viaduct\n  889: violin\n  890: volleyball\n  891: waffle iron\n  892: wall clock\n  893: wallet\n  894: wardrobe\n  895: military aircraft\n  896: sink\n  897: washing machine\n  898: water bottle\n  899: water jug\n  900: water tower\n  901: whiskey jug\n  902: whistle\n  903: wig\n  904: window screen\n  905: window shade\n  906: Windsor tie\n  907: wine bottle\n  908: wing\n  909: wok\n  910: wooden spoon\n  911: wool\n  912: split-rail fence\n  913: shipwreck\n  914: yawl\n  915: yurt\n  916: website\n  917: comic book\n  918: crossword\n  919: traffic sign\n  920: traffic light\n  921: dust jacket\n  922: menu\n  923: plate\n  924: guacamole\n  925: consomme\n  926: hot pot\n  927: trifle\n  928: ice cream\n  929: ice pop\n  930: baguette\n  931: bagel\n  932: pretzel\n  933: cheeseburger\n  934: hot dog\n  935: mashed potato\n  936: cabbage\n  937: broccoli\n  938: cauliflower\n  939: zucchini\n  940: spaghetti squash\n  941: acorn squash\n  942: butternut squash\n  943: cucumber\n  944: artichoke\n  945: bell pepper\n  946: cardoon\n  947: mushroom\n  948: Granny Smith\n  949: strawberry\n  950: orange\n  951: lemon\n  952: fig\n  953: pineapple\n  954: banana\n  955: jackfruit\n  956: custard apple\n  957: pomegranate\n  958: hay\n  959: carbonara\n  960: chocolate syrup\n  961: dough\n  962: meatloaf\n  963: pizza\n  964: pot pie\n  965: burrito\n  966: red wine\n  967: espresso\n  968: cup\n  969: eggnog\n  970: alp\n  971: bubble\n  972: cliff\n  973: coral reef\n  974: geyser\n  975: lakeshore\n  976: promontory\n  977: shoal\n  978: seashore\n  979: valley\n  980: volcano\n  981: baseball player\n  982: bridegroom\n  983: scuba diver\n  984: rapeseed\n  985: daisy\n  986: yellow lady's slipper\n  987: corn\n  988: acorn\n  989: rose hip\n  990: horse chestnut seed\n  991: coral fungus\n  992: agaric\n  993: gyromitra\n  994: stinkhorn mushroom\n  995: earth star\n  996: hen-of-the-woods\n  997: bolete\n  998: ear\n  999: toilet paper\n\n# Imagenet class codes to human-readable names\nmap:\n  n01440764: tench\n  n01443537: goldfish\n  n01484850: great_white_shark\n  n01491361: tiger_shark\n  n01494475: hammerhead\n  n01496331: electric_ray\n  n01498041: stingray\n  n01514668: cock\n  n01514859: hen\n  n01518878: ostrich\n  n01530575: brambling\n  n01531178: goldfinch\n  n01532829: house_finch\n  n01534433: junco\n  n01537544: indigo_bunting\n  n01558993: robin\n  n01560419: bulbul\n  n01580077: jay\n  n01582220: magpie\n  n01592084: chickadee\n  n01601694: water_ouzel\n  n01608432: kite\n  n01614925: bald_eagle\n  n01616318: vulture\n  n01622779: great_grey_owl\n  n01629819: European_fire_salamander\n  n01630670: common_newt\n  n01631663: eft\n  n01632458: spotted_salamander\n  n01632777: axolotl\n  n01641577: bullfrog\n  n01644373: tree_frog\n  n01644900: tailed_frog\n  n01664065: loggerhead\n  n01665541: leatherback_turtle\n  n01667114: mud_turtle\n  n01667778: terrapin\n  n01669191: box_turtle\n  n01675722: banded_gecko\n  n01677366: common_iguana\n  n01682714: American_chameleon\n  n01685808: whiptail\n  n01687978: agama\n  n01688243: frilled_lizard\n  n01689811: alligator_lizard\n  n01692333: Gila_monster\n  n01693334: green_lizard\n  n01694178: African_chameleon\n  n01695060: Komodo_dragon\n  n01697457: African_crocodile\n  n01698640: American_alligator\n  n01704323: triceratops\n  n01728572: thunder_snake\n  n01728920: ringneck_snake\n  n01729322: hognose_snake\n  n01729977: green_snake\n  n01734418: king_snake\n  n01735189: garter_snake\n  n01737021: water_snake\n  n01739381: vine_snake\n  n01740131: night_snake\n  n01742172: boa_constrictor\n  n01744401: rock_python\n  n01748264: Indian_cobra\n  n01749939: green_mamba\n  n01751748: sea_snake\n  n01753488: horned_viper\n  n01755581: diamondback\n  n01756291: sidewinder\n  n01768244: trilobite\n  n01770081: harvestman\n  n01770393: scorpion\n  n01773157: black_and_gold_garden_spider\n  n01773549: barn_spider\n  n01773797: garden_spider\n  n01774384: black_widow\n  n01774750: tarantula\n  n01775062: wolf_spider\n  n01776313: tick\n  n01784675: centipede\n  n01795545: black_grouse\n  n01796340: ptarmigan\n  n01797886: ruffed_grouse\n  n01798484: prairie_chicken\n  n01806143: peacock\n  n01806567: quail\n  n01807496: partridge\n  n01817953: African_grey\n  n01818515: macaw\n  n01819313: sulphur-crested_cockatoo\n  n01820546: lorikeet\n  n01824575: coucal\n  n01828970: bee_eater\n  n01829413: hornbill\n  n01833805: hummingbird\n  n01843065: jacamar\n  n01843383: toucan\n  n01847000: drake\n  n01855032: red-breasted_merganser\n  n01855672: goose\n  n01860187: black_swan\n  n01871265: tusker\n  n01872401: echidna\n  n01873310: platypus\n  n01877812: wallaby\n  n01882714: koala\n  n01883070: wombat\n  n01910747: jellyfish\n  n01914609: sea_anemone\n  n01917289: brain_coral\n  n01924916: flatworm\n  n01930112: nematode\n  n01943899: conch\n  n01944390: snail\n  n01945685: slug\n  n01950731: sea_slug\n  n01955084: chiton\n  n01968897: chambered_nautilus\n  n01978287: Dungeness_crab\n  n01978455: rock_crab\n  n01980166: fiddler_crab\n  n01981276: king_crab\n  n01983481: American_lobster\n  n01984695: spiny_lobster\n  n01985128: crayfish\n  n01986214: hermit_crab\n  n01990800: isopod\n  n02002556: white_stork\n  n02002724: black_stork\n  n02006656: spoonbill\n  n02007558: flamingo\n  n02009229: little_blue_heron\n  n02009912: American_egret\n  n02011460: bittern\n  n02012849: crane_(bird)\n  n02013706: limpkin\n  n02017213: European_gallinule\n  n02018207: American_coot\n  n02018795: bustard\n  n02025239: ruddy_turnstone\n  n02027492: red-backed_sandpiper\n  n02028035: redshank\n  n02033041: dowitcher\n  n02037110: oystercatcher\n  n02051845: pelican\n  n02056570: king_penguin\n  n02058221: albatross\n  n02066245: grey_whale\n  n02071294: killer_whale\n  n02074367: dugong\n  n02077923: sea_lion\n  n02085620: Chihuahua\n  n02085782: Japanese_spaniel\n  n02085936: Maltese_dog\n  n02086079: Pekinese\n  n02086240: Shih-Tzu\n  n02086646: Blenheim_spaniel\n  n02086910: papillon\n  n02087046: toy_terrier\n  n02087394: Rhodesian_ridgeback\n  n02088094: Afghan_hound\n  n02088238: basset\n  n02088364: beagle\n  n02088466: bloodhound\n  n02088632: bluetick\n  n02089078: black-and-tan_coonhound\n  n02089867: Walker_hound\n  n02089973: English_foxhound\n  n02090379: redbone\n  n02090622: borzoi\n  n02090721: Irish_wolfhound\n  n02091032: Italian_greyhound\n  n02091134: whippet\n  n02091244: Ibizan_hound\n  n02091467: Norwegian_elkhound\n  n02091635: otterhound\n  n02091831: Saluki\n  n02092002: Scottish_deerhound\n  n02092339: Weimaraner\n  n02093256: Staffordshire_bullterrier\n  n02093428: American_Staffordshire_terrier\n  n02093647: Bedlington_terrier\n  n02093754: Border_terrier\n  n02093859: Kerry_blue_terrier\n  n02093991: Irish_terrier\n  n02094114: Norfolk_terrier\n  n02094258: Norwich_terrier\n  n02094433: Yorkshire_terrier\n  n02095314: wire-haired_fox_terrier\n  n02095570: Lakeland_terrier\n  n02095889: Sealyham_terrier\n  n02096051: Airedale\n  n02096177: cairn\n  n02096294: Australian_terrier\n  n02096437: Dandie_Dinmont\n  n02096585: Boston_bull\n  n02097047: miniature_schnauzer\n  n02097130: giant_schnauzer\n  n02097209: standard_schnauzer\n  n02097298: Scotch_terrier\n  n02097474: Tibetan_terrier\n  n02097658: silky_terrier\n  n02098105: soft-coated_wheaten_terrier\n  n02098286: West_Highland_white_terrier\n  n02098413: Lhasa\n  n02099267: flat-coated_retriever\n  n02099429: curly-coated_retriever\n  n02099601: golden_retriever\n  n02099712: Labrador_retriever\n  n02099849: Chesapeake_Bay_retriever\n  n02100236: German_short-haired_pointer\n  n02100583: vizsla\n  n02100735: English_setter\n  n02100877: Irish_setter\n  n02101006: Gordon_setter\n  n02101388: Brittany_spaniel\n  n02101556: clumber\n  n02102040: English_springer\n  n02102177: Welsh_springer_spaniel\n  n02102318: cocker_spaniel\n  n02102480: Sussex_spaniel\n  n02102973: Irish_water_spaniel\n  n02104029: kuvasz\n  n02104365: schipperke\n  n02105056: groenendael\n  n02105162: malinois\n  n02105251: briard\n  n02105412: kelpie\n  n02105505: komondor\n  n02105641: Old_English_sheepdog\n  n02105855: Shetland_sheepdog\n  n02106030: collie\n  n02106166: Border_collie\n  n02106382: Bouvier_des_Flandres\n  n02106550: Rottweiler\n  n02106662: German_shepherd\n  n02107142: Doberman\n  n02107312: miniature_pinscher\n  n02107574: Greater_Swiss_Mountain_dog\n  n02107683: Bernese_mountain_dog\n  n02107908: Appenzeller\n  n02108000: EntleBucher\n  n02108089: boxer\n  n02108422: bull_mastiff\n  n02108551: Tibetan_mastiff\n  n02108915: French_bulldog\n  n02109047: Great_Dane\n  n02109525: Saint_Bernard\n  n02109961: Eskimo_dog\n  n02110063: malamute\n  n02110185: Siberian_husky\n  n02110341: dalmatian\n  n02110627: affenpinscher\n  n02110806: basenji\n  n02110958: pug\n  n02111129: Leonberg\n  n02111277: Newfoundland\n  n02111500: Great_Pyrenees\n  n02111889: Samoyed\n  n02112018: Pomeranian\n  n02112137: chow\n  n02112350: keeshond\n  n02112706: Brabancon_griffon\n  n02113023: Pembroke\n  n02113186: Cardigan\n  n02113624: toy_poodle\n  n02113712: miniature_poodle\n  n02113799: standard_poodle\n  n02113978: Mexican_hairless\n  n02114367: timber_wolf\n  n02114548: white_wolf\n  n02114712: red_wolf\n  n02114855: coyote\n  n02115641: dingo\n  n02115913: dhole\n  n02116738: African_hunting_dog\n  n02117135: hyena\n  n02119022: red_fox\n  n02119789: kit_fox\n  n02120079: Arctic_fox\n  n02120505: grey_fox\n  n02123045: tabby\n  n02123159: tiger_cat\n  n02123394: Persian_cat\n  n02123597: Siamese_cat\n  n02124075: Egyptian_cat\n  n02125311: cougar\n  n02127052: lynx\n  n02128385: leopard\n  n02128757: snow_leopard\n  n02128925: jaguar\n  n02129165: lion\n  n02129604: tiger\n  n02130308: cheetah\n  n02132136: brown_bear\n  n02133161: American_black_bear\n  n02134084: ice_bear\n  n02134418: sloth_bear\n  n02137549: mongoose\n  n02138441: meerkat\n  n02165105: tiger_beetle\n  n02165456: ladybug\n  n02167151: ground_beetle\n  n02168699: long-horned_beetle\n  n02169497: leaf_beetle\n  n02172182: dung_beetle\n  n02174001: rhinoceros_beetle\n  n02177972: weevil\n  n02190166: fly\n  n02206856: bee\n  n02219486: ant\n  n02226429: grasshopper\n  n02229544: cricket\n  n02231487: walking_stick\n  n02233338: cockroach\n  n02236044: mantis\n  n02256656: cicada\n  n02259212: leafhopper\n  n02264363: lacewing\n  n02268443: dragonfly\n  n02268853: damselfly\n  n02276258: admiral\n  n02277742: ringlet\n  n02279972: monarch\n  n02280649: cabbage_butterfly\n  n02281406: sulphur_butterfly\n  n02281787: lycaenid\n  n02317335: starfish\n  n02319095: sea_urchin\n  n02321529: sea_cucumber\n  n02325366: wood_rabbit\n  n02326432: hare\n  n02328150: Angora\n  n02342885: hamster\n  n02346627: porcupine\n  n02356798: fox_squirrel\n  n02361337: marmot\n  n02363005: beaver\n  n02364673: guinea_pig\n  n02389026: sorrel\n  n02391049: zebra\n  n02395406: hog\n  n02396427: wild_boar\n  n02397096: warthog\n  n02398521: hippopotamus\n  n02403003: ox\n  n02408429: water_buffalo\n  n02410509: bison\n  n02412080: ram\n  n02415577: bighorn\n  n02417914: ibex\n  n02422106: hartebeest\n  n02422699: impala\n  n02423022: gazelle\n  n02437312: Arabian_camel\n  n02437616: llama\n  n02441942: weasel\n  n02442845: mink\n  n02443114: polecat\n  n02443484: black-footed_ferret\n  n02444819: otter\n  n02445715: skunk\n  n02447366: badger\n  n02454379: armadillo\n  n02457408: three-toed_sloth\n  n02480495: orangutan\n  n02480855: gorilla\n  n02481823: chimpanzee\n  n02483362: gibbon\n  n02483708: siamang\n  n02484975: guenon\n  n02486261: patas\n  n02486410: baboon\n  n02487347: macaque\n  n02488291: langur\n  n02488702: colobus\n  n02489166: proboscis_monkey\n  n02490219: marmoset\n  n02492035: capuchin\n  n02492660: howler_monkey\n  n02493509: titi\n  n02493793: spider_monkey\n  n02494079: squirrel_monkey\n  n02497673: Madagascar_cat\n  n02500267: indri\n  n02504013: Indian_elephant\n  n02504458: African_elephant\n  n02509815: lesser_panda\n  n02510455: giant_panda\n  n02514041: barracouta\n  n02526121: eel\n  n02536864: coho\n  n02606052: rock_beauty\n  n02607072: anemone_fish\n  n02640242: sturgeon\n  n02641379: gar\n  n02643566: lionfish\n  n02655020: puffer\n  n02666196: abacus\n  n02667093: abaya\n  n02669723: academic_gown\n  n02672831: accordion\n  n02676566: acoustic_guitar\n  n02687172: aircraft_carrier\n  n02690373: airliner\n  n02692877: airship\n  n02699494: altar\n  n02701002: ambulance\n  n02704792: amphibian\n  n02708093: analog_clock\n  n02727426: apiary\n  n02730930: apron\n  n02747177: ashcan\n  n02749479: assault_rifle\n  n02769748: backpack\n  n02776631: bakery\n  n02777292: balance_beam\n  n02782093: balloon\n  n02783161: ballpoint\n  n02786058: Band_Aid\n  n02787622: banjo\n  n02788148: bannister\n  n02790996: barbell\n  n02791124: barber_chair\n  n02791270: barbershop\n  n02793495: barn\n  n02794156: barometer\n  n02795169: barrel\n  n02797295: barrow\n  n02799071: baseball\n  n02802426: basketball\n  n02804414: bassinet\n  n02804610: bassoon\n  n02807133: bathing_cap\n  n02808304: bath_towel\n  n02808440: bathtub\n  n02814533: beach_wagon\n  n02814860: beacon\n  n02815834: beaker\n  n02817516: bearskin\n  n02823428: beer_bottle\n  n02823750: beer_glass\n  n02825657: bell_cote\n  n02834397: bib\n  n02835271: bicycle-built-for-two\n  n02837789: bikini\n  n02840245: binder\n  n02841315: binoculars\n  n02843684: birdhouse\n  n02859443: boathouse\n  n02860847: bobsled\n  n02865351: bolo_tie\n  n02869837: bonnet\n  n02870880: bookcase\n  n02871525: bookshop\n  n02877765: bottlecap\n  n02879718: bow\n  n02883205: bow_tie\n  n02892201: brass\n  n02892767: brassiere\n  n02894605: breakwater\n  n02895154: breastplate\n  n02906734: broom\n  n02909870: bucket\n  n02910353: buckle\n  n02916936: bulletproof_vest\n  n02917067: bullet_train\n  n02927161: butcher_shop\n  n02930766: cab\n  n02939185: caldron\n  n02948072: candle\n  n02950826: cannon\n  n02951358: canoe\n  n02951585: can_opener\n  n02963159: cardigan\n  n02965783: car_mirror\n  n02966193: carousel\n  n02966687: carpenter's_kit\n  n02971356: carton\n  n02974003: car_wheel\n  n02977058: cash_machine\n  n02978881: cassette\n  n02979186: cassette_player\n  n02980441: castle\n  n02981792: catamaran\n  n02988304: CD_player\n  n02992211: cello\n  n02992529: cellular_telephone\n  n02999410: chain\n  n03000134: chainlink_fence\n  n03000247: chain_mail\n  n03000684: chain_saw\n  n03014705: chest\n  n03016953: chiffonier\n  n03017168: chime\n  n03018349: china_cabinet\n  n03026506: Christmas_stocking\n  n03028079: church\n  n03032252: cinema\n  n03041632: cleaver\n  n03042490: cliff_dwelling\n  n03045698: cloak\n  n03047690: clog\n  n03062245: cocktail_shaker\n  n03063599: coffee_mug\n  n03063689: coffeepot\n  n03065424: coil\n  n03075370: combination_lock\n  n03085013: computer_keyboard\n  n03089624: confectionery\n  n03095699: container_ship\n  n03100240: convertible\n  n03109150: corkscrew\n  n03110669: cornet\n  n03124043: cowboy_boot\n  n03124170: cowboy_hat\n  n03125729: cradle\n  n03126707: crane_(machine)\n  n03127747: crash_helmet\n  n03127925: crate\n  n03131574: crib\n  n03133878: Crock_Pot\n  n03134739: croquet_ball\n  n03141823: crutch\n  n03146219: cuirass\n  n03160309: dam\n  n03179701: desk\n  n03180011: desktop_computer\n  n03187595: dial_telephone\n  n03188531: diaper\n  n03196217: digital_clock\n  n03197337: digital_watch\n  n03201208: dining_table\n  n03207743: dishrag\n  n03207941: dishwasher\n  n03208938: disk_brake\n  n03216828: dock\n  n03218198: dogsled\n  n03220513: dome\n  n03223299: doormat\n  n03240683: drilling_platform\n  n03249569: drum\n  n03250847: drumstick\n  n03255030: dumbbell\n  n03259280: Dutch_oven\n  n03271574: electric_fan\n  n03272010: electric_guitar\n  n03272562: electric_locomotive\n  n03290653: entertainment_center\n  n03291819: envelope\n  n03297495: espresso_maker\n  n03314780: face_powder\n  n03325584: feather_boa\n  n03337140: file\n  n03344393: fireboat\n  n03345487: fire_engine\n  n03347037: fire_screen\n  n03355925: flagpole\n  n03372029: flute\n  n03376595: folding_chair\n  n03379051: football_helmet\n  n03384352: forklift\n  n03388043: fountain\n  n03388183: fountain_pen\n  n03388549: four-poster\n  n03393912: freight_car\n  n03394916: French_horn\n  n03400231: frying_pan\n  n03404251: fur_coat\n  n03417042: garbage_truck\n  n03424325: gasmask\n  n03425413: gas_pump\n  n03443371: goblet\n  n03444034: go-kart\n  n03445777: golf_ball\n  n03445924: golfcart\n  n03447447: gondola\n  n03447721: gong\n  n03450230: gown\n  n03452741: grand_piano\n  n03457902: greenhouse\n  n03459775: grille\n  n03461385: grocery_store\n  n03467068: guillotine\n  n03476684: hair_slide\n  n03476991: hair_spray\n  n03478589: half_track\n  n03481172: hammer\n  n03482405: hamper\n  n03483316: hand_blower\n  n03485407: hand-held_computer\n  n03485794: handkerchief\n  n03492542: hard_disc\n  n03494278: harmonica\n  n03495258: harp\n  n03496892: harvester\n  n03498962: hatchet\n  n03527444: holster\n  n03529860: home_theater\n  n03530642: honeycomb\n  n03532672: hook\n  n03534580: hoopskirt\n  n03535780: horizontal_bar\n  n03538406: horse_cart\n  n03544143: hourglass\n  n03584254: iPod\n  n03584829: iron\n  n03590841: jack-o'-lantern\n  n03594734: jean\n  n03594945: jeep\n  n03595614: jersey\n  n03598930: jigsaw_puzzle\n  n03599486: jinrikisha\n  n03602883: joystick\n  n03617480: kimono\n  n03623198: knee_pad\n  n03627232: knot\n  n03630383: lab_coat\n  n03633091: ladle\n  n03637318: lampshade\n  n03642806: laptop\n  n03649909: lawn_mower\n  n03657121: lens_cap\n  n03658185: letter_opener\n  n03661043: library\n  n03662601: lifeboat\n  n03666591: lighter\n  n03670208: limousine\n  n03673027: liner\n  n03676483: lipstick\n  n03680355: Loafer\n  n03690938: lotion\n  n03691459: loudspeaker\n  n03692522: loupe\n  n03697007: lumbermill\n  n03706229: magnetic_compass\n  n03709823: mailbag\n  n03710193: mailbox\n  n03710637: maillot_(tights)\n  n03710721: maillot_(tank_suit)\n  n03717622: manhole_cover\n  n03720891: maraca\n  n03721384: marimba\n  n03724870: mask\n  n03729826: matchstick\n  n03733131: maypole\n  n03733281: maze\n  n03733805: measuring_cup\n  n03742115: medicine_chest\n  n03743016: megalith\n  n03759954: microphone\n  n03761084: microwave\n  n03763968: military_uniform\n  n03764736: milk_can\n  n03769881: minibus\n  n03770439: miniskirt\n  n03770679: minivan\n  n03773504: missile\n  n03775071: mitten\n  n03775546: mixing_bowl\n  n03776460: mobile_home\n  n03777568: Model_T\n  n03777754: modem\n  n03781244: monastery\n  n03782006: monitor\n  n03785016: moped\n  n03786901: mortar\n  n03787032: mortarboard\n  n03788195: mosque\n  n03788365: mosquito_net\n  n03791053: motor_scooter\n  n03792782: mountain_bike\n  n03792972: mountain_tent\n  n03793489: mouse\n  n03794056: mousetrap\n  n03796401: moving_van\n  n03803284: muzzle\n  n03804744: nail\n  n03814639: neck_brace\n  n03814906: necklace\n  n03825788: nipple\n  n03832673: notebook\n  n03837869: obelisk\n  n03838899: oboe\n  n03840681: ocarina\n  n03841143: odometer\n  n03843555: oil_filter\n  n03854065: organ\n  n03857828: oscilloscope\n  n03866082: overskirt\n  n03868242: oxcart\n  n03868863: oxygen_mask\n  n03871628: packet\n  n03873416: paddle\n  n03874293: paddlewheel\n  n03874599: padlock\n  n03876231: paintbrush\n  n03877472: pajama\n  n03877845: palace\n  n03884397: panpipe\n  n03887697: paper_towel\n  n03888257: parachute\n  n03888605: parallel_bars\n  n03891251: park_bench\n  n03891332: parking_meter\n  n03895866: passenger_car\n  n03899768: patio\n  n03902125: pay-phone\n  n03903868: pedestal\n  n03908618: pencil_box\n  n03908714: pencil_sharpener\n  n03916031: perfume\n  n03920288: Petri_dish\n  n03924679: photocopier\n  n03929660: pick\n  n03929855: pickelhaube\n  n03930313: picket_fence\n  n03930630: pickup\n  n03933933: pier\n  n03935335: piggy_bank\n  n03937543: pill_bottle\n  n03938244: pillow\n  n03942813: ping-pong_ball\n  n03944341: pinwheel\n  n03947888: pirate\n  n03950228: pitcher\n  n03954731: plane\n  n03956157: planetarium\n  n03958227: plastic_bag\n  n03961711: plate_rack\n  n03967562: plow\n  n03970156: plunger\n  n03976467: Polaroid_camera\n  n03976657: pole\n  n03977966: police_van\n  n03980874: poncho\n  n03982430: pool_table\n  n03983396: pop_bottle\n  n03991062: pot\n  n03992509: potter's_wheel\n  n03995372: power_drill\n  n03998194: prayer_rug\n  n04004767: printer\n  n04005630: prison\n  n04008634: projectile\n  n04009552: projector\n  n04019541: puck\n  n04023962: punching_bag\n  n04026417: purse\n  n04033901: quill\n  n04033995: quilt\n  n04037443: racer\n  n04039381: racket\n  n04040759: radiator\n  n04041544: radio\n  n04044716: radio_telescope\n  n04049303: rain_barrel\n  n04065272: recreational_vehicle\n  n04067472: reel\n  n04069434: reflex_camera\n  n04070727: refrigerator\n  n04074963: remote_control\n  n04081281: restaurant\n  n04086273: revolver\n  n04090263: rifle\n  n04099969: rocking_chair\n  n04111531: rotisserie\n  n04116512: rubber_eraser\n  n04118538: rugby_ball\n  n04118776: rule\n  n04120489: running_shoe\n  n04125021: safe\n  n04127249: safety_pin\n  n04131690: saltshaker\n  n04133789: sandal\n  n04136333: sarong\n  n04141076: sax\n  n04141327: scabbard\n  n04141975: scale\n  n04146614: school_bus\n  n04147183: schooner\n  n04149813: scoreboard\n  n04152593: screen\n  n04153751: screw\n  n04154565: screwdriver\n  n04162706: seat_belt\n  n04179913: sewing_machine\n  n04192698: shield\n  n04200800: shoe_shop\n  n04201297: shoji\n  n04204238: shopping_basket\n  n04204347: shopping_cart\n  n04208210: shovel\n  n04209133: shower_cap\n  n04209239: shower_curtain\n  n04228054: ski\n  n04229816: ski_mask\n  n04235860: sleeping_bag\n  n04238763: slide_rule\n  n04239074: sliding_door\n  n04243546: slot\n  n04251144: snorkel\n  n04252077: snowmobile\n  n04252225: snowplow\n  n04254120: soap_dispenser\n  n04254680: soccer_ball\n  n04254777: sock\n  n04258138: solar_dish\n  n04259630: sombrero\n  n04263257: soup_bowl\n  n04264628: space_bar\n  n04265275: space_heater\n  n04266014: space_shuttle\n  n04270147: spatula\n  n04273569: speedboat\n  n04275548: spider_web\n  n04277352: spindle\n  n04285008: sports_car\n  n04286575: spotlight\n  n04296562: stage\n  n04310018: steam_locomotive\n  n04311004: steel_arch_bridge\n  n04311174: steel_drum\n  n04317175: stethoscope\n  n04325704: stole\n  n04326547: stone_wall\n  n04328186: stopwatch\n  n04330267: stove\n  n04332243: strainer\n  n04335435: streetcar\n  n04336792: stretcher\n  n04344873: studio_couch\n  n04346328: stupa\n  n04347754: submarine\n  n04350905: suit\n  n04355338: sundial\n  n04355933: sunglass\n  n04356056: sunglasses\n  n04357314: sunscreen\n  n04366367: suspension_bridge\n  n04367480: swab\n  n04370456: sweatshirt\n  n04371430: swimming_trunks\n  n04371774: swing\n  n04372370: switch\n  n04376876: syringe\n  n04380533: table_lamp\n  n04389033: tank\n  n04392985: tape_player\n  n04398044: teapot\n  n04399382: teddy\n  n04404412: television\n  n04409515: tennis_ball\n  n04417672: thatch\n  n04418357: theater_curtain\n  n04423845: thimble\n  n04428191: thresher\n  n04429376: throne\n  n04435653: tile_roof\n  n04442312: toaster\n  n04443257: tobacco_shop\n  n04447861: toilet_seat\n  n04456115: torch\n  n04458633: totem_pole\n  n04461696: tow_truck\n  n04462240: toyshop\n  n04465501: tractor\n  n04467665: trailer_truck\n  n04476259: tray\n  n04479046: trench_coat\n  n04482393: tricycle\n  n04483307: trimaran\n  n04485082: tripod\n  n04486054: triumphal_arch\n  n04487081: trolleybus\n  n04487394: trombone\n  n04493381: tub\n  n04501370: turnstile\n  n04505470: typewriter_keyboard\n  n04507155: umbrella\n  n04509417: unicycle\n  n04515003: upright\n  n04517823: vacuum\n  n04522168: vase\n  n04523525: vault\n  n04525038: velvet\n  n04525305: vending_machine\n  n04532106: vestment\n  n04532670: viaduct\n  n04536866: violin\n  n04540053: volleyball\n  n04542943: waffle_iron\n  n04548280: wall_clock\n  n04548362: wallet\n  n04550184: wardrobe\n  n04552348: warplane\n  n04553703: washbasin\n  n04554684: washer\n  n04557648: water_bottle\n  n04560804: water_jug\n  n04562935: water_tower\n  n04579145: whiskey_jug\n  n04579432: whistle\n  n04584207: wig\n  n04589890: window_screen\n  n04590129: window_shade\n  n04591157: Windsor_tie\n  n04591713: wine_bottle\n  n04592741: wing\n  n04596742: wok\n  n04597913: wooden_spoon\n  n04599235: wool\n  n04604644: worm_fence\n  n04606251: wreck\n  n04612504: yawl\n  n04613696: yurt\n  n06359193: web_site\n  n06596364: comic_book\n  n06785654: crossword_puzzle\n  n06794110: street_sign\n  n06874185: traffic_light\n  n07248320: book_jacket\n  n07565083: menu\n  n07579787: plate\n  n07583066: guacamole\n  n07584110: consomme\n  n07590611: hot_pot\n  n07613480: trifle\n  n07614500: ice_cream\n  n07615774: ice_lolly\n  n07684084: French_loaf\n  n07693725: bagel\n  n07695742: pretzel\n  n07697313: cheeseburger\n  n07697537: hotdog\n  n07711569: mashed_potato\n  n07714571: head_cabbage\n  n07714990: broccoli\n  n07715103: cauliflower\n  n07716358: zucchini\n  n07716906: spaghetti_squash\n  n07717410: acorn_squash\n  n07717556: butternut_squash\n  n07718472: cucumber\n  n07718747: artichoke\n  n07720875: bell_pepper\n  n07730033: cardoon\n  n07734744: mushroom\n  n07742313: Granny_Smith\n  n07745940: strawberry\n  n07747607: orange\n  n07749582: lemon\n  n07753113: fig\n  n07753275: pineapple\n  n07753592: banana\n  n07754684: jackfruit\n  n07760859: custard_apple\n  n07768694: pomegranate\n  n07802026: hay\n  n07831146: carbonara\n  n07836838: chocolate_sauce\n  n07860988: dough\n  n07871810: meat_loaf\n  n07873807: pizza\n  n07875152: potpie\n  n07880968: burrito\n  n07892512: red_wine\n  n07920052: espresso\n  n07930864: cup\n  n07932039: eggnog\n  n09193705: alp\n  n09229709: bubble\n  n09246464: cliff\n  n09256479: coral_reef\n  n09288635: geyser\n  n09332890: lakeside\n  n09399592: promontory\n  n09421951: sandbar\n  n09428293: seashore\n  n09468604: valley\n  n09472597: volcano\n  n09835506: ballplayer\n  n10148035: groom\n  n10565667: scuba_diver\n  n11879895: rapeseed\n  n11939491: daisy\n  n12057211: yellow_lady's_slipper\n  n12144580: corn\n  n12267677: acorn\n  n12620546: hip\n  n12768682: buckeye\n  n12985857: coral_fungus\n  n12998815: agaric\n  n13037406: gyromitra\n  n13040303: stinkhorn\n  n13044778: earthstar\n  n13052670: hen-of-the-woods\n  n13054560: bolete\n  n13133613: ear\n  n15075141: toilet_tissue\n\n\n# Download script/URL (optional)\ndownload: yolo/data/scripts/get_imagenet.sh\n"
  },
  {
    "path": "ultralytics/datasets/Objects365.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Objects365 dataset https://www.objects365.org/ by Megvii\n# Example usage: yolo train data=Objects365.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── Objects365  ← downloads here (712 GB = 367G data + 345G zips)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/Objects365  # dataset root dir\ntrain: images/train  # train images (relative to 'path') 1742289 images\nval: images/val # val images (relative to 'path') 80000 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: Person\n  1: Sneakers\n  2: Chair\n  3: Other Shoes\n  4: Hat\n  5: Car\n  6: Lamp\n  7: Glasses\n  8: Bottle\n  9: Desk\n  10: Cup\n  11: Street Lights\n  12: Cabinet/shelf\n  13: Handbag/Satchel\n  14: Bracelet\n  15: Plate\n  16: Picture/Frame\n  17: Helmet\n  18: Book\n  19: Gloves\n  20: Storage box\n  21: Boat\n  22: Leather Shoes\n  23: Flower\n  24: Bench\n  25: Potted Plant\n  26: Bowl/Basin\n  27: Flag\n  28: Pillow\n  29: Boots\n  30: Vase\n  31: Microphone\n  32: Necklace\n  33: Ring\n  34: SUV\n  35: Wine Glass\n  36: Belt\n  37: Monitor/TV\n  38: Backpack\n  39: Umbrella\n  40: Traffic Light\n  41: Speaker\n  42: Watch\n  43: Tie\n  44: Trash bin Can\n  45: Slippers\n  46: Bicycle\n  47: Stool\n  48: Barrel/bucket\n  49: Van\n  50: Couch\n  51: Sandals\n  52: Basket\n  53: Drum\n  54: Pen/Pencil\n  55: Bus\n  56: Wild Bird\n  57: High Heels\n  58: Motorcycle\n  59: Guitar\n  60: Carpet\n  61: Cell Phone\n  62: Bread\n  63: Camera\n  64: Canned\n  65: Truck\n  66: Traffic cone\n  67: Cymbal\n  68: Lifesaver\n  69: Towel\n  70: Stuffed Toy\n  71: Candle\n  72: Sailboat\n  73: Laptop\n  74: Awning\n  75: Bed\n  76: Faucet\n  77: Tent\n  78: Horse\n  79: Mirror\n  80: Power outlet\n  81: Sink\n  82: Apple\n  83: Air Conditioner\n  84: Knife\n  85: Hockey Stick\n  86: Paddle\n  87: Pickup Truck\n  88: Fork\n  89: Traffic Sign\n  90: Balloon\n  91: Tripod\n  92: Dog\n  93: Spoon\n  94: Clock\n  95: Pot\n  96: Cow\n  97: Cake\n  98: Dinning Table\n  99: Sheep\n  100: Hanger\n  101: Blackboard/Whiteboard\n  102: Napkin\n  103: Other Fish\n  104: Orange/Tangerine\n  105: Toiletry\n  106: Keyboard\n  107: Tomato\n  108: Lantern\n  109: Machinery Vehicle\n  110: Fan\n  111: Green Vegetables\n  112: Banana\n  113: Baseball Glove\n  114: Airplane\n  115: Mouse\n  116: Train\n  117: Pumpkin\n  118: Soccer\n  119: Skiboard\n  120: Luggage\n  121: Nightstand\n  122: Tea pot\n  123: Telephone\n  124: Trolley\n  125: Head Phone\n  126: Sports Car\n  127: Stop Sign\n  128: Dessert\n  129: Scooter\n  130: Stroller\n  131: Crane\n  132: Remote\n  133: Refrigerator\n  134: Oven\n  135: Lemon\n  136: Duck\n  137: Baseball Bat\n  138: Surveillance Camera\n  139: Cat\n  140: Jug\n  141: Broccoli\n  142: Piano\n  143: Pizza\n  144: Elephant\n  145: Skateboard\n  146: Surfboard\n  147: Gun\n  148: Skating and Skiing shoes\n  149: Gas stove\n  150: Donut\n  151: Bow Tie\n  152: Carrot\n  153: Toilet\n  154: Kite\n  155: Strawberry\n  156: Other Balls\n  157: Shovel\n  158: Pepper\n  159: Computer Box\n  160: Toilet Paper\n  161: Cleaning Products\n  162: Chopsticks\n  163: Microwave\n  164: Pigeon\n  165: Baseball\n  166: Cutting/chopping Board\n  167: Coffee Table\n  168: Side Table\n  169: Scissors\n  170: Marker\n  171: Pie\n  172: Ladder\n  173: Snowboard\n  174: Cookies\n  175: Radiator\n  176: Fire Hydrant\n  177: Basketball\n  178: Zebra\n  179: Grape\n  180: Giraffe\n  181: Potato\n  182: Sausage\n  183: Tricycle\n  184: Violin\n  185: Egg\n  186: Fire Extinguisher\n  187: Candy\n  188: Fire Truck\n  189: Billiards\n  190: Converter\n  191: Bathtub\n  192: Wheelchair\n  193: Golf Club\n  194: Briefcase\n  195: Cucumber\n  196: Cigar/Cigarette\n  197: Paint Brush\n  198: Pear\n  199: Heavy Truck\n  200: Hamburger\n  201: Extractor\n  202: Extension Cord\n  203: Tong\n  204: Tennis Racket\n  205: Folder\n  206: American Football\n  207: earphone\n  208: Mask\n  209: Kettle\n  210: Tennis\n  211: Ship\n  212: Swing\n  213: Coffee Machine\n  214: Slide\n  215: Carriage\n  216: Onion\n  217: Green beans\n  218: Projector\n  219: Frisbee\n  220: Washing Machine/Drying Machine\n  221: Chicken\n  222: Printer\n  223: Watermelon\n  224: Saxophone\n  225: Tissue\n  226: Toothbrush\n  227: Ice cream\n  228: Hot-air balloon\n  229: Cello\n  230: French Fries\n  231: Scale\n  232: Trophy\n  233: Cabbage\n  234: Hot dog\n  235: Blender\n  236: Peach\n  237: Rice\n  238: Wallet/Purse\n  239: Volleyball\n  240: Deer\n  241: Goose\n  242: Tape\n  243: Tablet\n  244: Cosmetics\n  245: Trumpet\n  246: Pineapple\n  247: Golf Ball\n  248: Ambulance\n  249: Parking meter\n  250: Mango\n  251: Key\n  252: Hurdle\n  253: Fishing Rod\n  254: Medal\n  255: Flute\n  256: Brush\n  257: Penguin\n  258: Megaphone\n  259: Corn\n  260: Lettuce\n  261: Garlic\n  262: Swan\n  263: Helicopter\n  264: Green Onion\n  265: Sandwich\n  266: Nuts\n  267: Speed Limit Sign\n  268: Induction Cooker\n  269: Broom\n  270: Trombone\n  271: Plum\n  272: Rickshaw\n  273: Goldfish\n  274: Kiwi fruit\n  275: Router/modem\n  276: Poker Card\n  277: Toaster\n  278: Shrimp\n  279: Sushi\n  280: Cheese\n  281: Notepaper\n  282: Cherry\n  283: Pliers\n  284: CD\n  285: Pasta\n  286: Hammer\n  287: Cue\n  288: Avocado\n  289: Hamimelon\n  290: Flask\n  291: Mushroom\n  292: Screwdriver\n  293: Soap\n  294: Recorder\n  295: Bear\n  296: Eggplant\n  297: Board Eraser\n  298: Coconut\n  299: Tape Measure/Ruler\n  300: Pig\n  301: Showerhead\n  302: Globe\n  303: Chips\n  304: Steak\n  305: Crosswalk Sign\n  306: Stapler\n  307: Camel\n  308: Formula 1\n  309: Pomegranate\n  310: Dishwasher\n  311: Crab\n  312: Hoverboard\n  313: Meat ball\n  314: Rice Cooker\n  315: Tuba\n  316: Calculator\n  317: Papaya\n  318: Antelope\n  319: Parrot\n  320: Seal\n  321: Butterfly\n  322: Dumbbell\n  323: Donkey\n  324: Lion\n  325: Urinal\n  326: Dolphin\n  327: Electric Drill\n  328: Hair Dryer\n  329: Egg tart\n  330: Jellyfish\n  331: Treadmill\n  332: Lighter\n  333: Grapefruit\n  334: Game board\n  335: Mop\n  336: Radish\n  337: Baozi\n  338: Target\n  339: French\n  340: Spring Rolls\n  341: Monkey\n  342: Rabbit\n  343: Pencil Case\n  344: Yak\n  345: Red Cabbage\n  346: Binoculars\n  347: Asparagus\n  348: Barbell\n  349: Scallop\n  350: Noddles\n  351: Comb\n  352: Dumpling\n  353: Oyster\n  354: Table Tennis paddle\n  355: Cosmetics Brush/Eyeliner Pencil\n  356: Chainsaw\n  357: Eraser\n  358: Lobster\n  359: Durian\n  360: Okra\n  361: Lipstick\n  362: Cosmetics Mirror\n  363: Curling\n  364: Table Tennis\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  from tqdm import tqdm\n\n  from ultralytics.yolo.utils.checks import check_requirements\n  from ultralytics.yolo.utils.downloads import download\n  from ultralytics.yolo.utils.ops import xyxy2xywhn\n\n  import numpy as np\n  from pathlib import Path\n\n  check_requirements(('pycocotools>=2.0',))\n  from pycocotools.coco import COCO\n\n  # Make Directories\n  dir = Path(yaml['path'])  # dataset root dir\n  for p in 'images', 'labels':\n      (dir / p).mkdir(parents=True, exist_ok=True)\n      for q in 'train', 'val':\n          (dir / p / q).mkdir(parents=True, exist_ok=True)\n\n  # Train, Val Splits\n  for split, patches in [('train', 50 + 1), ('val', 43 + 1)]:\n      print(f\"Processing {split} in {patches} patches ...\")\n      images, labels = dir / 'images' / split, dir / 'labels' / split\n\n      # Download\n      url = f\"https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/{split}/\"\n      if split == 'train':\n          download([f'{url}zhiyuan_objv2_{split}.tar.gz'], dir=dir)  # annotations json\n          download([f'{url}patch{i}.tar.gz' for i in range(patches)], dir=images, curl=True, threads=8)\n      elif split == 'val':\n          download([f'{url}zhiyuan_objv2_{split}.json'], dir=dir)  # annotations json\n          download([f'{url}images/v1/patch{i}.tar.gz' for i in range(15 + 1)], dir=images, curl=True, threads=8)\n          download([f'{url}images/v2/patch{i}.tar.gz' for i in range(16, patches)], dir=images, curl=True, threads=8)\n\n      # Move\n      for f in tqdm(images.rglob('*.jpg'), desc=f'Moving {split} images'):\n          f.rename(images / f.name)  # move to /images/{split}\n\n      # Labels\n      coco = COCO(dir / f'zhiyuan_objv2_{split}.json')\n      names = [x[\"name\"] for x in coco.loadCats(coco.getCatIds())]\n      for cid, cat in enumerate(names):\n          catIds = coco.getCatIds(catNms=[cat])\n          imgIds = coco.getImgIds(catIds=catIds)\n          for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'):\n              width, height = im[\"width\"], im[\"height\"]\n              path = Path(im[\"file_name\"])  # image filename\n              try:\n                  with open(labels / path.with_suffix('.txt').name, 'a') as file:\n                      annIds = coco.getAnnIds(imgIds=im[\"id\"], catIds=catIds, iscrowd=None)\n                      for a in coco.loadAnns(annIds):\n                          x, y, w, h = a['bbox']  # bounding box in xywh (xy top-left corner)\n                          xyxy = np.array([x, y, x + w, y + h])[None]  # pixels(1,4)\n                          x, y, w, h = xyxy2xywhn(xyxy, w=width, h=height, clip=True)[0]  # normalized and clipped\n                          file.write(f\"{cid} {x:.5f} {y:.5f} {w:.5f} {h:.5f}\\n\")\n              except Exception as e:\n                  print(e)\n"
  },
  {
    "path": "ultralytics/datasets/SKU-110K.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 by Trax Retail\n# Example usage: yolo train data=SKU-110K.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── SKU-110K  ← downloads here (13.6 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/SKU-110K  # dataset root dir\ntrain: train.txt  # train images (relative to 'path')  8219 images\nval: val.txt  # val images (relative to 'path')  588 images\ntest: test.txt  # test images (optional)  2936 images\n\n# Classes\nnames:\n  0: object\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  import shutil\n  from pathlib import Path\n\n  import numpy as np\n  import pandas as pd\n  from tqdm import tqdm\n\n  from ultralytics.yolo.utils.downloads import download\n  from ultralytics.yolo.utils.ops import xyxy2xywh\n\n  # Download\n  dir = Path(yaml['path'])  # dataset root dir\n  parent = Path(dir.parent)  # download dir\n  urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz']\n  download(urls, dir=parent)\n\n  # Rename directories\n  if dir.exists():\n      shutil.rmtree(dir)\n  (parent / 'SKU110K_fixed').rename(dir)  # rename dir\n  (dir / 'labels').mkdir(parents=True, exist_ok=True)  # create labels dir\n\n  # Convert labels\n  names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height'  # column names\n  for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv':\n      x = pd.read_csv(dir / 'annotations' / d, names=names).values  # annotations\n      images, unique_images = x[:, 0], np.unique(x[:, 0])\n      with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f:\n          f.writelines(f'./images/{s}\\n' for s in unique_images)\n      for im in tqdm(unique_images, desc=f'Converting {dir / d}'):\n          cls = 0  # single-class dataset\n          with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f:\n              for r in x[images == im]:\n                  w, h = r[6], r[7]  # image width, height\n                  xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0]  # instance\n                  f.write(f\"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\\n\")  # write label\n"
  },
  {
    "path": "ultralytics/datasets/VOC.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC by University of Oxford\n# Example usage: yolo train data=VOC.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── VOC  ← downloads here (2.8 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/VOC\ntrain: # train images (relative to 'path')  16551 images\n  - images/train2012\n  - images/train2007\n  - images/val2012\n  - images/val2007\nval: # val images (relative to 'path')  4952 images\n  - images/test2007\ntest: # test images (optional)\n  - images/test2007\n\n# Classes\nnames:\n  0: aeroplane\n  1: bicycle\n  2: bird\n  3: boat\n  4: bottle\n  5: bus\n  6: car\n  7: cat\n  8: chair\n  9: cow\n  10: diningtable\n  11: dog\n  12: horse\n  13: motorbike\n  14: person\n  15: pottedplant\n  16: sheep\n  17: sofa\n  18: train\n  19: tvmonitor\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  import xml.etree.ElementTree as ET\n\n  from tqdm import tqdm\n  from ultralytics.yolo.utils.downloads import download\n  from pathlib import Path\n\n  def convert_label(path, lb_path, year, image_id):\n      def convert_box(size, box):\n          dw, dh = 1. / size[0], 1. / size[1]\n          x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2]\n          return x * dw, y * dh, w * dw, h * dh\n\n      in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml')\n      out_file = open(lb_path, 'w')\n      tree = ET.parse(in_file)\n      root = tree.getroot()\n      size = root.find('size')\n      w = int(size.find('width').text)\n      h = int(size.find('height').text)\n\n      names = list(yaml['names'].values())  # names list\n      for obj in root.iter('object'):\n          cls = obj.find('name').text\n          if cls in names and int(obj.find('difficult').text) != 1:\n              xmlbox = obj.find('bndbox')\n              bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')])\n              cls_id = names.index(cls)  # class id\n              out_file.write(\" \".join([str(a) for a in (cls_id, *bb)]) + '\\n')\n\n\n  # Download\n  dir = Path(yaml['path'])  # dataset root dir\n  url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'\n  urls = [f'{url}VOCtrainval_06-Nov-2007.zip',  # 446MB, 5012 images\n          f'{url}VOCtest_06-Nov-2007.zip',  # 438MB, 4953 images\n          f'{url}VOCtrainval_11-May-2012.zip']  # 1.95GB, 17126 images\n  download(urls, dir=dir / 'images', curl=True, threads=3)\n\n  # Convert\n  path = dir / 'images/VOCdevkit'\n  for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'):\n      imgs_path = dir / 'images' / f'{image_set}{year}'\n      lbs_path = dir / 'labels' / f'{image_set}{year}'\n      imgs_path.mkdir(exist_ok=True, parents=True)\n      lbs_path.mkdir(exist_ok=True, parents=True)\n\n      with open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt') as f:\n          image_ids = f.read().strip().split()\n      for id in tqdm(image_ids, desc=f'{image_set}{year}'):\n          f = path / f'VOC{year}/JPEGImages/{id}.jpg'  # old img path\n          lb_path = (lbs_path / f.name).with_suffix('.txt')  # new label path\n          f.rename(imgs_path / f.name)  # move image\n          convert_label(path, lb_path, year, id)  # convert labels to YOLO format\n"
  },
  {
    "path": "ultralytics/datasets/VisDrone.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset by Tianjin University\n# Example usage: yolo train data=VisDrone.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── VisDrone  ← downloads here (2.3 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/VisDrone  # dataset root dir\ntrain: VisDrone2019-DET-train/images  # train images (relative to 'path')  6471 images\nval: VisDrone2019-DET-val/images  # val images (relative to 'path')  548 images\ntest: VisDrone2019-DET-test-dev/images  # test images (optional)  1610 images\n\n# Classes\nnames:\n  0: pedestrian\n  1: people\n  2: bicycle\n  3: car\n  4: van\n  5: truck\n  6: tricycle\n  7: awning-tricycle\n  8: bus\n  9: motor\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  import os\n  from pathlib import Path\n\n  from ultralytics.yolo.utils.downloads import download\n\n  def visdrone2yolo(dir):\n      from PIL import Image\n      from tqdm import tqdm\n\n      def convert_box(size, box):\n          # Convert VisDrone box to YOLO xywh box\n          dw = 1. / size[0]\n          dh = 1. / size[1]\n          return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh\n\n      (dir / 'labels').mkdir(parents=True, exist_ok=True)  # make labels directory\n      pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')\n      for f in pbar:\n          img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size\n          lines = []\n          with open(f, 'r') as file:  # read annotation.txt\n              for row in [x.split(',') for x in file.read().strip().splitlines()]:\n                  if row[4] == '0':  # VisDrone 'ignored regions' class 0\n                      continue\n                  cls = int(row[5]) - 1\n                  box = convert_box(img_size, tuple(map(int, row[:4])))\n                  lines.append(f\"{cls} {' '.join(f'{x:.6f}' for x in box)}\\n\")\n                  with open(str(f).replace(f'{os.sep}annotations{os.sep}', f'{os.sep}labels{os.sep}'), 'w') as fl:\n                      fl.writelines(lines)  # write label.txt\n\n\n  # Download\n  dir = Path(yaml['path'])  # dataset root dir\n  urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip',\n          'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip',\n          'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip',\n          'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip']\n  download(urls, dir=dir, curl=True, threads=4)\n\n  # Convert\n  for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':\n      visdrone2yolo(dir / d)  # convert VisDrone annotations to YOLO labels\n"
  },
  {
    "path": "ultralytics/datasets/coco-pose.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO 2017 dataset http://cocodataset.org by Microsoft\n# Example usage: yolo train data=coco-pose.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco-pose  ← downloads here (20.1 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco-pose  # dataset root dir\ntrain: train2017.txt  # train images (relative to 'path') 118287 images\nval: val2017.txt  # val images (relative to 'path') 5000 images\ntest: test-dev2017.txt  # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794\n\n# Keypoints\nkpt_shape: [17, 3]  # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)\nflip_idx: [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]\n\n# Classes\nnames:\n  0: person\n\n# Download script/URL (optional)\ndownload: |\n  from ultralytics.yolo.utils.downloads import download\n  from pathlib import Path\n\n  # Download labels\n  dir = Path(yaml['path'])  # dataset root dir\n  url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'\n  urls = [url + 'coco2017labels-pose.zip']  # labels\n  download(urls, dir=dir.parent)\n  # Download data\n  urls = ['http://images.cocodataset.org/zips/train2017.zip',  # 19G, 118k images\n          'http://images.cocodataset.org/zips/val2017.zip',  # 1G, 5k images\n          'http://images.cocodataset.org/zips/test2017.zip']  # 7G, 41k images (optional)\n  download(urls, dir=dir / 'images', threads=3)\n"
  },
  {
    "path": "ultralytics/datasets/coco.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO 2017 dataset http://cocodataset.org by Microsoft\n# Example usage: yolo train data=coco.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco  ← downloads here (20.1 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco  # dataset root dir\ntrain: train2017.txt  # train images (relative to 'path') 118287 images\nval: val2017.txt  # val images (relative to 'path') 5000 images\ntest: test-dev2017.txt  # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  4: airplane\n  5: bus\n  6: train\n  7: truck\n  8: boat\n  9: traffic light\n  10: fire hydrant\n  11: stop sign\n  12: parking meter\n  13: bench\n  14: bird\n  15: cat\n  16: dog\n  17: horse\n  18: sheep\n  19: cow\n  20: elephant\n  21: bear\n  22: zebra\n  23: giraffe\n  24: backpack\n  25: umbrella\n  26: handbag\n  27: tie\n  28: suitcase\n  29: frisbee\n  30: skis\n  31: snowboard\n  32: sports ball\n  33: kite\n  34: baseball bat\n  35: baseball glove\n  36: skateboard\n  37: surfboard\n  38: tennis racket\n  39: bottle\n  40: wine glass\n  41: cup\n  42: fork\n  43: knife\n  44: spoon\n  45: bowl\n  46: banana\n  47: apple\n  48: sandwich\n  49: orange\n  50: broccoli\n  51: carrot\n  52: hot dog\n  53: pizza\n  54: donut\n  55: cake\n  56: chair\n  57: couch\n  58: potted plant\n  59: bed\n  60: dining table\n  61: toilet\n  62: tv\n  63: laptop\n  64: mouse\n  65: remote\n  66: keyboard\n  67: cell phone\n  68: microwave\n  69: oven\n  70: toaster\n  71: sink\n  72: refrigerator\n  73: book\n  74: clock\n  75: vase\n  76: scissors\n  77: teddy bear\n  78: hair drier\n  79: toothbrush\n\n\n# Download script/URL (optional)\ndownload: |\n  from ultralytics.yolo.utils.downloads import download\n  from pathlib import Path\n\n  # Download labels\n  segments = True  # segment or box labels\n  dir = Path(yaml['path'])  # dataset root dir\n  url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'\n  urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')]  # labels\n  download(urls, dir=dir.parent)\n  # Download data\n  urls = ['http://images.cocodataset.org/zips/train2017.zip',  # 19G, 118k images\n          'http://images.cocodataset.org/zips/val2017.zip',  # 1G, 5k images\n          'http://images.cocodataset.org/zips/test2017.zip']  # 7G, 41k images (optional)\n  download(urls, dir=dir / 'images', threads=3)\n"
  },
  {
    "path": "ultralytics/datasets/coco128-seg.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO128-seg dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics\n# Example usage: yolo train data=coco128.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco128-seg  ← downloads here (7 MB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco128-seg  # dataset root dir\ntrain: images/train2017  # train images (relative to 'path') 128 images\nval: images/train2017  # val images (relative to 'path') 128 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  4: airplane\n  5: bus\n  6: train\n  7: truck\n  8: boat\n  9: traffic light\n  10: fire hydrant\n  11: stop sign\n  12: parking meter\n  13: bench\n  14: bird\n  15: cat\n  16: dog\n  17: horse\n  18: sheep\n  19: cow\n  20: elephant\n  21: bear\n  22: zebra\n  23: giraffe\n  24: backpack\n  25: umbrella\n  26: handbag\n  27: tie\n  28: suitcase\n  29: frisbee\n  30: skis\n  31: snowboard\n  32: sports ball\n  33: kite\n  34: baseball bat\n  35: baseball glove\n  36: skateboard\n  37: surfboard\n  38: tennis racket\n  39: bottle\n  40: wine glass\n  41: cup\n  42: fork\n  43: knife\n  44: spoon\n  45: bowl\n  46: banana\n  47: apple\n  48: sandwich\n  49: orange\n  50: broccoli\n  51: carrot\n  52: hot dog\n  53: pizza\n  54: donut\n  55: cake\n  56: chair\n  57: couch\n  58: potted plant\n  59: bed\n  60: dining table\n  61: toilet\n  62: tv\n  63: laptop\n  64: mouse\n  65: remote\n  66: keyboard\n  67: cell phone\n  68: microwave\n  69: oven\n  70: toaster\n  71: sink\n  72: refrigerator\n  73: book\n  74: clock\n  75: vase\n  76: scissors\n  77: teddy bear\n  78: hair drier\n  79: toothbrush\n\n\n# Download script/URL (optional)\ndownload: https://ultralytics.com/assets/coco128-seg.zip\n"
  },
  {
    "path": "ultralytics/datasets/coco128.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics\n# Example usage: yolo train data=coco128.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco128  ← downloads here (7 MB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco128  # dataset root dir\ntrain: images/train2017  # train images (relative to 'path') 128 images\nval: images/train2017  # val images (relative to 'path') 128 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  4: airplane\n  5: bus\n  6: train\n  7: truck\n  8: boat\n  9: traffic light\n  10: fire hydrant\n  11: stop sign\n  12: parking meter\n  13: bench\n  14: bird\n  15: cat\n  16: dog\n  17: horse\n  18: sheep\n  19: cow\n  20: elephant\n  21: bear\n  22: zebra\n  23: giraffe\n  24: backpack\n  25: umbrella\n  26: handbag\n  27: tie\n  28: suitcase\n  29: frisbee\n  30: skis\n  31: snowboard\n  32: sports ball\n  33: kite\n  34: baseball bat\n  35: baseball glove\n  36: skateboard\n  37: surfboard\n  38: tennis racket\n  39: bottle\n  40: wine glass\n  41: cup\n  42: fork\n  43: knife\n  44: spoon\n  45: bowl\n  46: banana\n  47: apple\n  48: sandwich\n  49: orange\n  50: broccoli\n  51: carrot\n  52: hot dog\n  53: pizza\n  54: donut\n  55: cake\n  56: chair\n  57: couch\n  58: potted plant\n  59: bed\n  60: dining table\n  61: toilet\n  62: tv\n  63: laptop\n  64: mouse\n  65: remote\n  66: keyboard\n  67: cell phone\n  68: microwave\n  69: oven\n  70: toaster\n  71: sink\n  72: refrigerator\n  73: book\n  74: clock\n  75: vase\n  76: scissors\n  77: teddy bear\n  78: hair drier\n  79: toothbrush\n\n\n# Download script/URL (optional)\ndownload: https://ultralytics.com/assets/coco128.zip\n"
  },
  {
    "path": "ultralytics/datasets/coco8-pose.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO8-pose dataset (first 8 images from COCO train2017) by Ultralytics\n# Example usage: yolo train data=coco8-pose.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco8-pose  ← downloads here (1 MB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco8-pose  # dataset root dir\ntrain: images/train  # train images (relative to 'path') 4 images\nval: images/val  # val images (relative to 'path') 4 images\ntest:  # test images (optional)\n\n# Keypoints\nkpt_shape: [17, 3]  # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)\nflip_idx: [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]\n\n# Classes\nnames:\n  0: person\n\n# Download script/URL (optional)\ndownload: https://ultralytics.com/assets/coco8-pose.zip\n"
  },
  {
    "path": "ultralytics/datasets/coco8-seg.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO8-seg dataset (first 8 images from COCO train2017) by Ultralytics\n# Example usage: yolo train data=coco8-seg.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco8-seg  ← downloads here (1 MB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco8-seg  # dataset root dir\ntrain: images/train  # train images (relative to 'path') 4 images\nval: images/val  # val images (relative to 'path') 4 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  4: airplane\n  5: bus\n  6: train\n  7: truck\n  8: boat\n  9: traffic light\n  10: fire hydrant\n  11: stop sign\n  12: parking meter\n  13: bench\n  14: bird\n  15: cat\n  16: dog\n  17: horse\n  18: sheep\n  19: cow\n  20: elephant\n  21: bear\n  22: zebra\n  23: giraffe\n  24: backpack\n  25: umbrella\n  26: handbag\n  27: tie\n  28: suitcase\n  29: frisbee\n  30: skis\n  31: snowboard\n  32: sports ball\n  33: kite\n  34: baseball bat\n  35: baseball glove\n  36: skateboard\n  37: surfboard\n  38: tennis racket\n  39: bottle\n  40: wine glass\n  41: cup\n  42: fork\n  43: knife\n  44: spoon\n  45: bowl\n  46: banana\n  47: apple\n  48: sandwich\n  49: orange\n  50: broccoli\n  51: carrot\n  52: hot dog\n  53: pizza\n  54: donut\n  55: cake\n  56: chair\n  57: couch\n  58: potted plant\n  59: bed\n  60: dining table\n  61: toilet\n  62: tv\n  63: laptop\n  64: mouse\n  65: remote\n  66: keyboard\n  67: cell phone\n  68: microwave\n  69: oven\n  70: toaster\n  71: sink\n  72: refrigerator\n  73: book\n  74: clock\n  75: vase\n  76: scissors\n  77: teddy bear\n  78: hair drier\n  79: toothbrush\n\n\n# Download script/URL (optional)\ndownload: https://ultralytics.com/assets/coco8-seg.zip\n"
  },
  {
    "path": "ultralytics/datasets/coco8.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO8 dataset (first 8 images from COCO train2017) by Ultralytics\n# Example usage: yolo train data=coco8.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco8  ← downloads here (1 MB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco8  # dataset root dir\ntrain: images/train  # train images (relative to 'path') 4 images\nval: images/val  # val images (relative to 'path') 4 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  4: airplane\n  5: bus\n  6: train\n  7: truck\n  8: boat\n  9: traffic light\n  10: fire hydrant\n  11: stop sign\n  12: parking meter\n  13: bench\n  14: bird\n  15: cat\n  16: dog\n  17: horse\n  18: sheep\n  19: cow\n  20: elephant\n  21: bear\n  22: zebra\n  23: giraffe\n  24: backpack\n  25: umbrella\n  26: handbag\n  27: tie\n  28: suitcase\n  29: frisbee\n  30: skis\n  31: snowboard\n  32: sports ball\n  33: kite\n  34: baseball bat\n  35: baseball glove\n  36: skateboard\n  37: surfboard\n  38: tennis racket\n  39: bottle\n  40: wine glass\n  41: cup\n  42: fork\n  43: knife\n  44: spoon\n  45: bowl\n  46: banana\n  47: apple\n  48: sandwich\n  49: orange\n  50: broccoli\n  51: carrot\n  52: hot dog\n  53: pizza\n  54: donut\n  55: cake\n  56: chair\n  57: couch\n  58: potted plant\n  59: bed\n  60: dining table\n  61: toilet\n  62: tv\n  63: laptop\n  64: mouse\n  65: remote\n  66: keyboard\n  67: cell phone\n  68: microwave\n  69: oven\n  70: toaster\n  71: sink\n  72: refrigerator\n  73: book\n  74: clock\n  75: vase\n  76: scissors\n  77: teddy bear\n  78: hair drier\n  79: toothbrush\n\n\n# Download script/URL (optional)\ndownload: https://ultralytics.com/assets/coco8.zip\n"
  },
  {
    "path": "ultralytics/datasets/xView.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# DIUx xView 2018 Challenge https://challenge.xviewdataset.org by U.S. National Geospatial-Intelligence Agency (NGA)\n# --------  DOWNLOAD DATA MANUALLY and jar xf val_images.zip to 'datasets/xView' before running train command!  --------\n# Example usage: yolo train data=xView.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── xView  ← downloads here (20.7 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/xView  # dataset root dir\ntrain: images/autosplit_train.txt  # train images (relative to 'path') 90% of 847 train images\nval: images/autosplit_val.txt  # train images (relative to 'path') 10% of 847 train images\n\n# Classes\nnames:\n  0: Fixed-wing Aircraft\n  1: Small Aircraft\n  2: Cargo Plane\n  3: Helicopter\n  4: Passenger Vehicle\n  5: Small Car\n  6: Bus\n  7: Pickup Truck\n  8: Utility Truck\n  9: Truck\n  10: Cargo Truck\n  11: Truck w/Box\n  12: Truck Tractor\n  13: Trailer\n  14: Truck w/Flatbed\n  15: Truck w/Liquid\n  16: Crane Truck\n  17: Railway Vehicle\n  18: Passenger Car\n  19: Cargo Car\n  20: Flat Car\n  21: Tank car\n  22: Locomotive\n  23: Maritime Vessel\n  24: Motorboat\n  25: Sailboat\n  26: Tugboat\n  27: Barge\n  28: Fishing Vessel\n  29: Ferry\n  30: Yacht\n  31: Container Ship\n  32: Oil Tanker\n  33: Engineering Vehicle\n  34: Tower crane\n  35: Container Crane\n  36: Reach Stacker\n  37: Straddle Carrier\n  38: Mobile Crane\n  39: Dump Truck\n  40: Haul Truck\n  41: Scraper/Tractor\n  42: Front loader/Bulldozer\n  43: Excavator\n  44: Cement Mixer\n  45: Ground Grader\n  46: Hut/Tent\n  47: Shed\n  48: Building\n  49: Aircraft Hangar\n  50: Damaged Building\n  51: Facility\n  52: Construction Site\n  53: Vehicle Lot\n  54: Helipad\n  55: Storage Tank\n  56: Shipping container lot\n  57: Shipping Container\n  58: Pylon\n  59: Tower\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  import json\n  import os\n  from pathlib import Path\n\n  import numpy as np\n  from PIL import Image\n  from tqdm import tqdm\n\n  from ultralytics.yolo.data.dataloaders.v5loader import autosplit\n  from ultralytics.yolo.utils.ops import xyxy2xywhn\n\n\n  def convert_labels(fname=Path('xView/xView_train.geojson')):\n      # Convert xView geoJSON labels to YOLO format\n      path = fname.parent\n      with open(fname) as f:\n          print(f'Loading {fname}...')\n          data = json.load(f)\n\n      # Make dirs\n      labels = Path(path / 'labels' / 'train')\n      os.system(f'rm -rf {labels}')\n      labels.mkdir(parents=True, exist_ok=True)\n\n      # xView classes 11-94 to 0-59\n      xview_class2index = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, -1, 9, 10, 11,\n                           12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, 23, 24, 25, -1, 26, 27, -1, 28, -1,\n                           29, 30, 31, 32, 33, 34, 35, 36, 37, -1, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, 46,\n                           47, 48, 49, -1, 50, 51, -1, 52, -1, -1, -1, 53, 54, -1, 55, -1, -1, 56, -1, 57, -1, 58, 59]\n\n      shapes = {}\n      for feature in tqdm(data['features'], desc=f'Converting {fname}'):\n          p = feature['properties']\n          if p['bounds_imcoords']:\n              id = p['image_id']\n              file = path / 'train_images' / id\n              if file.exists():  # 1395.tif missing\n                  try:\n                      box = np.array([int(num) for num in p['bounds_imcoords'].split(\",\")])\n                      assert box.shape[0] == 4, f'incorrect box shape {box.shape[0]}'\n                      cls = p['type_id']\n                      cls = xview_class2index[int(cls)]  # xView class to 0-60\n                      assert 59 >= cls >= 0, f'incorrect class index {cls}'\n\n                      # Write YOLO label\n                      if id not in shapes:\n                          shapes[id] = Image.open(file).size\n                      box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True)\n                      with open((labels / id).with_suffix('.txt'), 'a') as f:\n                          f.write(f\"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\\n\")  # write label.txt\n                  except Exception as e:\n                      print(f'WARNING: skipping one label for {file}: {e}')\n\n\n  # Download manually from https://challenge.xviewdataset.org\n  dir = Path(yaml['path'])  # dataset root dir\n  # urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip',  # train labels\n  #         'https://d307kc0mrhucc3.cloudfront.net/train_images.zip',  # 15G, 847 train images\n  #         'https://d307kc0mrhucc3.cloudfront.net/val_images.zip']  # 5G, 282 val images (no labels)\n  # download(urls, dir=dir)\n\n  # Convert labels\n  convert_labels(dir / 'xView_train.geojson')\n\n  # Move images\n  images = Path(dir / 'images')\n  images.mkdir(parents=True, exist_ok=True)\n  Path(dir / 'train_images').rename(dir / 'images' / 'train')\n  Path(dir / 'val_images').rename(dir / 'images' / 'val')\n\n  # Split\n  autosplit(dir / 'images' / 'train')\n"
  },
  {
    "path": "ultralytics/hub/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport requests\n\nfrom ultralytics.hub.auth import Auth\nfrom ultralytics.hub.utils import PREFIX\nfrom ultralytics.yolo.data.utils import HUBDatasetStats\nfrom ultralytics.yolo.utils import LOGGER, SETTINGS, USER_CONFIG_DIR, yaml_save\n\n\ndef login(api_key=''):\n    \"\"\"\n    Log in to the Ultralytics HUB API using the provided API key.\n\n    Args:\n        api_key (str, optional): May be an API key or a combination API key and model ID, i.e. key_id\n\n    Example:\n        from ultralytics import hub\n        hub.login('API_KEY')\n    \"\"\"\n    Auth(api_key, verbose=True)\n\n\ndef logout():\n    \"\"\"\n    Log out of Ultralytics HUB by removing the API key from the settings file. To log in again, use 'yolo hub login'.\n\n    Example:\n        from ultralytics import hub\n        hub.logout()\n    \"\"\"\n    SETTINGS['api_key'] = ''\n    yaml_save(USER_CONFIG_DIR / 'settings.yaml', SETTINGS)\n    LOGGER.info(f\"{PREFIX}logged out ✅. To log in again, use 'yolo hub login'.\")\n\n\ndef start(key=''):\n    \"\"\"\n    Start training models with Ultralytics HUB (DEPRECATED).\n\n    Args:\n        key (str, optional): A string containing either the API key and model ID combination (apikey_modelid),\n                               or the full model URL (https://hub.ultralytics.com/models/apikey_modelid).\n    \"\"\"\n    api_key, model_id = key.split('_')\n    LOGGER.warning(f\"\"\"\nWARNING ⚠️ ultralytics.start() is deprecated after 8.0.60. Updated usage to train Ultralytics HUB models is:\n\nfrom ultralytics import YOLO, hub\n\nhub.login('{api_key}')\nmodel = YOLO('https://hub.ultralytics.com/models/{model_id}')\nmodel.train()\"\"\")\n\n\ndef reset_model(model_id=''):\n    \"\"\"Reset a trained model to an untrained state.\"\"\"\n    r = requests.post('https://api.ultralytics.com/model-reset', json={'apiKey': Auth().api_key, 'modelId': model_id})\n    if r.status_code == 200:\n        LOGGER.info(f'{PREFIX}Model reset successfully')\n        return\n    LOGGER.warning(f'{PREFIX}Model reset failure {r.status_code} {r.reason}')\n\n\ndef export_fmts_hub():\n    \"\"\"Returns a list of HUB-supported export formats.\"\"\"\n    from ultralytics.yolo.engine.exporter import export_formats\n    return list(export_formats()['Argument'][1:]) + ['ultralytics_tflite', 'ultralytics_coreml']\n\n\ndef export_model(model_id='', format='torchscript'):\n    \"\"\"Export a model to all formats.\"\"\"\n    assert format in export_fmts_hub(), f\"Unsupported export format '{format}', valid formats are {export_fmts_hub()}\"\n    r = requests.post(f'https://api.ultralytics.com/v1/models/{model_id}/export',\n                      json={'format': format},\n                      headers={'x-api-key': Auth().api_key})\n    assert r.status_code == 200, f'{PREFIX}{format} export failure {r.status_code} {r.reason}'\n    LOGGER.info(f'{PREFIX}{format} export started ✅')\n\n\ndef get_export(model_id='', format='torchscript'):\n    \"\"\"Get an exported model dictionary with download URL.\"\"\"\n    assert format in export_fmts_hub(), f\"Unsupported export format '{format}', valid formats are {export_fmts_hub()}\"\n    r = requests.post('https://api.ultralytics.com/get-export',\n                      json={\n                          'apiKey': Auth().api_key,\n                          'modelId': model_id,\n                          'format': format})\n    assert r.status_code == 200, f'{PREFIX}{format} get_export failure {r.status_code} {r.reason}'\n    return r.json()\n\n\ndef check_dataset(path='', task='detect'):\n    \"\"\"\n    Function for error-checking HUB dataset Zip file before upload. It checks a dataset for errors before it is\n    uploaded to the HUB. Usage examples are given below.\n\n    Args:\n        path (str, optional): Path to data.zip (with data.yaml inside data.zip). Defaults to ''.\n        task (str, optional): Dataset task. Options are 'detect', 'segment', 'pose', 'classify'. Defaults to 'detect'.\n\n    Example:\n        ```python\n        from ultralytics.hub import check_dataset\n\n        check_dataset('path/to/coco8.zip', task='detect')  # detect dataset\n        check_dataset('path/to/coco8-seg.zip', task='segment')  # segment dataset\n        check_dataset('path/to/coco8-pose.zip', task='pose')  # pose dataset\n        ```\n    \"\"\"\n    HUBDatasetStats(path=path, task=task).get_json()\n    LOGGER.info('Checks completed correctly ✅. Upload this dataset to https://hub.ultralytics.com/datasets/.')\n\n\nif __name__ == '__main__':\n    start()\n"
  },
  {
    "path": "ultralytics/hub/auth.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport requests\n\nfrom ultralytics.hub.utils import HUB_API_ROOT, PREFIX, request_with_credentials\nfrom ultralytics.yolo.utils import LOGGER, SETTINGS, emojis, is_colab, set_settings\n\nAPI_KEY_URL = 'https://hub.ultralytics.com/settings?tab=api+keys'\n\n\nclass Auth:\n    id_token = api_key = model_key = False\n\n    def __init__(self, api_key='', verbose=False):\n        \"\"\"\n        Initialize the Auth class with an optional API key.\n\n        Args:\n            api_key (str, optional): May be an API key or a combination API key and model ID, i.e. key_id\n        \"\"\"\n        # Split the input API key in case it contains a combined key_model and keep only the API key part\n        api_key = api_key.split('_')[0]\n\n        # Set API key attribute as value passed or SETTINGS API key if none passed\n        self.api_key = api_key or SETTINGS.get('api_key', '')\n\n        # If an API key is provided\n        if self.api_key:\n            # If the provided API key matches the API key in the SETTINGS\n            if self.api_key == SETTINGS.get('api_key'):\n                # Log that the user is already logged in\n                if verbose:\n                    LOGGER.info(f'{PREFIX}Authenticated ✅')\n                return\n            else:\n                # Attempt to authenticate with the provided API key\n                success = self.authenticate()\n        # If the API key is not provided and the environment is a Google Colab notebook\n        elif is_colab():\n            # Attempt to authenticate using browser cookies\n            success = self.auth_with_cookies()\n        else:\n            # Request an API key\n            success = self.request_api_key()\n\n        # Update SETTINGS with the new API key after successful authentication\n        if success:\n            set_settings({'api_key': self.api_key})\n            # Log that the new login was successful\n            if verbose:\n                LOGGER.info(f'{PREFIX}New authentication successful ✅')\n        elif verbose:\n            LOGGER.info(f'{PREFIX}Retrieve API key from {API_KEY_URL}')\n\n    def request_api_key(self, max_attempts=3):\n        \"\"\"\n        Prompt the user to input their API key. Returns the model ID.\n        \"\"\"\n        import getpass\n        for attempts in range(max_attempts):\n            LOGGER.info(f'{PREFIX}Login. Attempt {attempts + 1} of {max_attempts}')\n            input_key = getpass.getpass(f'Enter API key from {API_KEY_URL} ')\n            self.api_key = input_key.split('_')[0]  # remove model id if present\n            if self.authenticate():\n                return True\n        raise ConnectionError(emojis(f'{PREFIX}Failed to authenticate ❌'))\n\n    def authenticate(self) -> bool:\n        \"\"\"\n        Attempt to authenticate with the server using either id_token or API key.\n\n        Returns:\n            bool: True if authentication is successful, False otherwise.\n        \"\"\"\n        try:\n            header = self.get_auth_header()\n            if header:\n                r = requests.post(f'{HUB_API_ROOT}/v1/auth', headers=header)\n                if not r.json().get('success', False):\n                    raise ConnectionError('Unable to authenticate.')\n                return True\n            raise ConnectionError('User has not authenticated locally.')\n        except ConnectionError:\n            self.id_token = self.api_key = False  # reset invalid\n            LOGGER.warning(f'{PREFIX}Invalid API key ⚠️')\n            return False\n\n    def auth_with_cookies(self) -> bool:\n        \"\"\"\n        Attempt to fetch authentication via cookies and set id_token.\n        User must be logged in to HUB and running in a supported browser.\n\n        Returns:\n            bool: True if authentication is successful, False otherwise.\n        \"\"\"\n        if not is_colab():\n            return False  # Currently only works with Colab\n        try:\n            authn = request_with_credentials(f'{HUB_API_ROOT}/v1/auth/auto')\n            if authn.get('success', False):\n                self.id_token = authn.get('data', {}).get('idToken', None)\n                self.authenticate()\n                return True\n            raise ConnectionError('Unable to fetch browser authentication details.')\n        except ConnectionError:\n            self.id_token = False  # reset invalid\n            return False\n\n    def get_auth_header(self):\n        \"\"\"\n        Get the authentication header for making API requests.\n\n        Returns:\n            (dict): The authentication header if id_token or API key is set, None otherwise.\n        \"\"\"\n        if self.id_token:\n            return {'authorization': f'Bearer {self.id_token}'}\n        elif self.api_key:\n            return {'x-api-key': self.api_key}\n        else:\n            return None\n\n    def get_state(self) -> bool:\n        \"\"\"\n        Get the authentication state.\n\n        Returns:\n            bool: True if either id_token or API key is set, False otherwise.\n        \"\"\"\n        return self.id_token or self.api_key\n\n    def set_api_key(self, key: str):\n        \"\"\"\n        Set the API key for authentication.\n\n        Args:\n            key (str): The API key string.\n        \"\"\"\n        self.api_key = key\n"
  },
  {
    "path": "ultralytics/hub/session.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nimport signal\nimport sys\nfrom pathlib import Path\nfrom time import sleep\n\nimport requests\n\nfrom ultralytics.hub.utils import HUB_API_ROOT, PREFIX, smart_request\nfrom ultralytics.yolo.utils import LOGGER, __version__, checks, emojis, is_colab, threaded\nfrom ultralytics.yolo.utils.errors import HUBModelError\n\nAGENT_NAME = f'python-{__version__}-colab' if is_colab() else f'python-{__version__}-local'\n\n\nclass HUBTrainingSession:\n    \"\"\"\n    HUB training session for Ultralytics HUB YOLO models. Handles model initialization, heartbeats, and checkpointing.\n\n    Args:\n        url (str): Model identifier used to initialize the HUB training session.\n\n    Attributes:\n        agent_id (str): Identifier for the instance communicating with the server.\n        model_id (str): Identifier for the YOLOv5 model being trained.\n        model_url (str): URL for the model in Ultralytics HUB.\n        api_url (str): API URL for the model in Ultralytics HUB.\n        auth_header (Dict): Authentication header for the Ultralytics HUB API requests.\n        rate_limits (Dict): Rate limits for different API calls (in seconds).\n        timers (Dict): Timers for rate limiting.\n        metrics_queue (Dict): Queue for the model's metrics.\n        model (Dict): Model data fetched from Ultralytics HUB.\n        alive (bool): Indicates if the heartbeat loop is active.\n    \"\"\"\n\n    def __init__(self, url):\n        \"\"\"\n        Initialize the HUBTrainingSession with the provided model identifier.\n\n        Args:\n            url (str): Model identifier used to initialize the HUB training session.\n                         It can be a URL string or a model key with specific format.\n\n        Raises:\n            ValueError: If the provided model identifier is invalid.\n            ConnectionError: If connecting with global API key is not supported.\n        \"\"\"\n\n        from ultralytics.hub.auth import Auth\n\n        # Parse input\n        if url.startswith('https://hub.ultralytics.com/models/'):\n            url = url.split('https://hub.ultralytics.com/models/')[-1]\n        if [len(x) for x in url.split('_')] == [42, 20]:\n            key, model_id = url.split('_')\n        elif len(url) == 20:\n            key, model_id = '', url\n        else:\n            raise HUBModelError(f\"model='{url}' not found. Check format is correct, i.e. \"\n                                f\"model='https://hub.ultralytics.com/models/MODEL_ID' and try again.\")\n\n        # Authorize\n        auth = Auth(key)\n        self.agent_id = None  # identifies which instance is communicating with server\n        self.model_id = model_id\n        self.model_url = f'https://hub.ultralytics.com/models/{model_id}'\n        self.api_url = f'{HUB_API_ROOT}/v1/models/{model_id}'\n        self.auth_header = auth.get_auth_header()\n        self.rate_limits = {'metrics': 3.0, 'ckpt': 900.0, 'heartbeat': 300.0}  # rate limits (seconds)\n        self.timers = {}  # rate limit timers (seconds)\n        self.metrics_queue = {}  # metrics queue\n        self.model = self._get_model()\n        self.alive = True\n        self._start_heartbeat()  # start heartbeats\n        self._register_signal_handlers()\n        LOGGER.info(f'{PREFIX}View model at {self.model_url} 🚀')\n\n    def _register_signal_handlers(self):\n        \"\"\"Register signal handlers for SIGTERM and SIGINT signals to gracefully handle termination.\"\"\"\n        signal.signal(signal.SIGTERM, self._handle_signal)\n        signal.signal(signal.SIGINT, self._handle_signal)\n\n    def _handle_signal(self, signum, frame):\n        \"\"\"\n        Handle kill signals and prevent heartbeats from being sent on Colab after termination.\n        This method does not use frame, it is included as it is passed by signal.\n        \"\"\"\n        if self.alive is True:\n            LOGGER.info(f'{PREFIX}Kill signal received! ❌')\n            self._stop_heartbeat()\n            sys.exit(signum)\n\n    def _stop_heartbeat(self):\n        \"\"\"Terminate the heartbeat loop.\"\"\"\n        self.alive = False\n\n    def upload_metrics(self):\n        \"\"\"Upload model metrics to Ultralytics HUB.\"\"\"\n        payload = {'metrics': self.metrics_queue.copy(), 'type': 'metrics'}\n        smart_request('post', self.api_url, json=payload, headers=self.auth_header, code=2)\n\n    def _get_model(self):\n        \"\"\"Fetch and return model data from Ultralytics HUB.\"\"\"\n        api_url = f'{HUB_API_ROOT}/v1/models/{self.model_id}'\n\n        try:\n            response = smart_request('get', api_url, headers=self.auth_header, thread=False, code=0)\n            data = response.json().get('data', None)\n\n            if data.get('status', None) == 'trained':\n                raise ValueError(emojis(f'Model is already trained and uploaded to {self.model_url} 🚀'))\n\n            if not data.get('data', None):\n                raise ValueError('Dataset may still be processing. Please wait a minute and try again.')  # RF fix\n            self.model_id = data['id']\n\n            if data['status'] == 'new':  # new model to start training\n                self.train_args = {\n                    # TODO: deprecate 'batch_size' key for 'batch' in 3Q23\n                    'batch': data['batch' if ('batch' in data) else 'batch_size'],\n                    'epochs': data['epochs'],\n                    'imgsz': data['imgsz'],\n                    'patience': data['patience'],\n                    'device': data['device'],\n                    'cache': data['cache'],\n                    'data': data['data']}\n                self.model_file = data.get('cfg') or data.get('weights')  # cfg for pretrained=False\n                self.model_file = checks.check_yolov5u_filename(self.model_file, verbose=False)  # YOLOv5->YOLOv5u\n            elif data['status'] == 'training':  # existing model to resume training\n                self.train_args = {'data': data['data'], 'resume': True}\n                self.model_file = data['resume']\n\n            return data\n        except requests.exceptions.ConnectionError as e:\n            raise ConnectionRefusedError('ERROR: The HUB server is not online. Please try again later.') from e\n        except Exception:\n            raise\n\n    def upload_model(self, epoch, weights, is_best=False, map=0.0, final=False):\n        \"\"\"\n        Upload a model checkpoint to Ultralytics HUB.\n\n        Args:\n            epoch (int): The current training epoch.\n            weights (str): Path to the model weights file.\n            is_best (bool): Indicates if the current model is the best one so far.\n            map (float): Mean average precision of the model.\n            final (bool): Indicates if the model is the final model after training.\n        \"\"\"\n        if Path(weights).is_file():\n            with open(weights, 'rb') as f:\n                file = f.read()\n        else:\n            LOGGER.warning(f'{PREFIX}WARNING ⚠️ Model upload issue. Missing model {weights}.')\n            file = None\n        url = f'{self.api_url}/upload'\n        # url = 'http://httpbin.org/post'  # for debug\n        data = {'epoch': epoch}\n        if final:\n            data.update({'type': 'final', 'map': map})\n            smart_request('post',\n                          url,\n                          data=data,\n                          files={'best.pt': file},\n                          headers=self.auth_header,\n                          retry=10,\n                          timeout=3600,\n                          thread=False,\n                          progress=True,\n                          code=4)\n        else:\n            data.update({'type': 'epoch', 'isBest': bool(is_best)})\n            smart_request('post', url, data=data, files={'last.pt': file}, headers=self.auth_header, code=3)\n\n    @threaded\n    def _start_heartbeat(self):\n        \"\"\"Begin a threaded heartbeat loop to report the agent's status to Ultralytics HUB.\"\"\"\n        while self.alive:\n            r = smart_request('post',\n                              f'{HUB_API_ROOT}/v1/agent/heartbeat/models/{self.model_id}',\n                              json={\n                                  'agent': AGENT_NAME,\n                                  'agentId': self.agent_id},\n                              headers=self.auth_header,\n                              retry=0,\n                              code=5,\n                              thread=False)  # already in a thread\n            self.agent_id = r.json().get('data', {}).get('agentId', None)\n            sleep(self.rate_limits['heartbeat'])\n"
  },
  {
    "path": "ultralytics/hub/utils.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nimport platform\nimport random\nimport sys\nimport threading\nimport time\nfrom pathlib import Path\n\nimport requests\nfrom tqdm import tqdm\n\nfrom ultralytics.yolo.utils import (ENVIRONMENT, LOGGER, ONLINE, RANK, SETTINGS, TESTS_RUNNING, TQDM_BAR_FORMAT,\n                                    TryExcept, __version__, colorstr, get_git_origin_url, is_colab, is_git_dir,\n                                    is_pip_package)\n\nPREFIX = colorstr('Ultralytics HUB: ')\nHELP_MSG = 'If this issue persists please visit https://github.com/ultralytics/hub/issues for assistance.'\nHUB_API_ROOT = os.environ.get('ULTRALYTICS_HUB_API', 'https://api.ultralytics.com')\n\n\ndef request_with_credentials(url: str) -> any:\n    \"\"\"\n    Make an AJAX request with cookies attached in a Google Colab environment.\n\n    Args:\n        url (str): The URL to make the request to.\n\n    Returns:\n        (any): The response data from the AJAX request.\n\n    Raises:\n        OSError: If the function is not run in a Google Colab environment.\n    \"\"\"\n    if not is_colab():\n        raise OSError('request_with_credentials() must run in a Colab environment')\n    from google.colab import output  # noqa\n    from IPython import display  # noqa\n    display.display(\n        display.Javascript(\"\"\"\n            window._hub_tmp = new Promise((resolve, reject) => {\n                const timeout = setTimeout(() => reject(\"Failed authenticating existing browser session\"), 5000)\n                fetch(\"%s\", {\n                    method: 'POST',\n                    credentials: 'include'\n                })\n                    .then((response) => resolve(response.json()))\n                    .then((json) => {\n                    clearTimeout(timeout);\n                    }).catch((err) => {\n                    clearTimeout(timeout);\n                    reject(err);\n                });\n            });\n            \"\"\" % url))\n    return output.eval_js('_hub_tmp')\n\n\ndef requests_with_progress(method, url, **kwargs):\n    \"\"\"\n    Make an HTTP request using the specified method and URL, with an optional progress bar.\n\n    Args:\n        method (str): The HTTP method to use (e.g. 'GET', 'POST').\n        url (str): The URL to send the request to.\n        **kwargs (dict): Additional keyword arguments to pass to the underlying `requests.request` function.\n\n    Returns:\n        (requests.Response): The response object from the HTTP request.\n\n    Note:\n        If 'progress' is set to True, the progress bar will display the download progress\n        for responses with a known content length.\n    \"\"\"\n    progress = kwargs.pop('progress', False)\n    if not progress:\n        return requests.request(method, url, **kwargs)\n    response = requests.request(method, url, stream=True, **kwargs)\n    total = int(response.headers.get('content-length', 0))  # total size\n    pbar = tqdm(total=total, unit='B', unit_scale=True, unit_divisor=1024, bar_format=TQDM_BAR_FORMAT)\n    for data in response.iter_content(chunk_size=1024):\n        pbar.update(len(data))\n    pbar.close()\n    return response\n\n\ndef smart_request(method, url, retry=3, timeout=30, thread=True, code=-1, verbose=True, progress=False, **kwargs):\n    \"\"\"\n    Makes an HTTP request using the 'requests' library, with exponential backoff retries up to a specified timeout.\n\n    Args:\n        method (str): The HTTP method to use for the request. Choices are 'post' and 'get'.\n        url (str): The URL to make the request to.\n        retry (int, optional): Number of retries to attempt before giving up. Default is 3.\n        timeout (int, optional): Timeout in seconds after which the function will give up retrying. Default is 30.\n        thread (bool, optional): Whether to execute the request in a separate daemon thread. Default is True.\n        code (int, optional): An identifier for the request, used for logging purposes. Default is -1.\n        verbose (bool, optional): A flag to determine whether to print out to console or not. Default is True.\n        progress (bool, optional): Whether to show a progress bar during the request. Default is False.\n        **kwargs (dict): Keyword arguments to be passed to the requests function specified in method.\n\n    Returns:\n        (requests.Response): The HTTP response object. If the request is executed in a separate thread, returns None.\n    \"\"\"\n    retry_codes = (408, 500)  # retry only these codes\n\n    @TryExcept(verbose=verbose)\n    def func(func_method, func_url, **func_kwargs):\n        \"\"\"Make HTTP requests with retries and timeouts, with optional progress tracking.\"\"\"\n        r = None  # response\n        t0 = time.time()  # initial time for timer\n        for i in range(retry + 1):\n            if (time.time() - t0) > timeout:\n                break\n            r = requests_with_progress(func_method, func_url, **func_kwargs)  # i.e. get(url, data, json, files)\n            if r.status_code < 300:  # return codes in the 2xx range are generally considered \"good\" or \"successful\"\n                break\n            try:\n                m = r.json().get('message', 'No JSON message.')\n            except AttributeError:\n                m = 'Unable to read JSON.'\n            if i == 0:\n                if r.status_code in retry_codes:\n                    m += f' Retrying {retry}x for {timeout}s.' if retry else ''\n                elif r.status_code == 429:  # rate limit\n                    h = r.headers  # response headers\n                    m = f\"Rate limit reached ({h['X-RateLimit-Remaining']}/{h['X-RateLimit-Limit']}). \" \\\n                        f\"Please retry after {h['Retry-After']}s.\"\n                if verbose:\n                    LOGGER.warning(f'{PREFIX}{m} {HELP_MSG} ({r.status_code} #{code})')\n                if r.status_code not in retry_codes:\n                    return r\n            time.sleep(2 ** i)  # exponential standoff\n        return r\n\n    args = method, url\n    kwargs['progress'] = progress\n    if thread:\n        threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True).start()\n    else:\n        return func(*args, **kwargs)\n\n\nclass Events:\n    \"\"\"\n    A class for collecting anonymous event analytics. Event analytics are enabled when sync=True in settings and\n    disabled when sync=False. Run 'yolo settings' to see and update settings YAML file.\n\n    Attributes:\n        url (str): The URL to send anonymous events.\n        rate_limit (float): The rate limit in seconds for sending events.\n        metadata (dict): A dictionary containing metadata about the environment.\n        enabled (bool): A flag to enable or disable Events based on certain conditions.\n    \"\"\"\n\n    url = 'https://www.google-analytics.com/mp/collect?measurement_id=G-X8NCJYTQXM&api_secret=QLQrATrNSwGRFRLE-cbHJw'\n\n    def __init__(self):\n        \"\"\"\n        Initializes the Events object with default values for events, rate_limit, and metadata.\n        \"\"\"\n        self.events = []  # events list\n        self.rate_limit = 60.0  # rate limit (seconds)\n        self.t = 0.0  # rate limit timer (seconds)\n        self.metadata = {\n            'cli': Path(sys.argv[0]).name == 'yolo',\n            'install': 'git' if is_git_dir() else 'pip' if is_pip_package() else 'other',\n            'python': '.'.join(platform.python_version_tuple()[:2]),  # i.e. 3.10\n            'version': __version__,\n            'env': ENVIRONMENT,\n            'session_id': round(random.random() * 1E15),\n            'engagement_time_msec': 1000}\n        self.enabled = \\\n            SETTINGS['sync'] and \\\n            RANK in (-1, 0) and \\\n            not TESTS_RUNNING and \\\n            ONLINE and \\\n            (is_pip_package() or get_git_origin_url() == 'https://github.com/ultralytics/ultralytics.git')\n\n    def __call__(self, cfg):\n        \"\"\"\n        Attempts to add a new event to the events list and send events if the rate limit is reached.\n\n        Args:\n            cfg (IterableSimpleNamespace): The configuration object containing mode and task information.\n        \"\"\"\n        if not self.enabled:\n            # Events disabled, do nothing\n            return\n\n        # Attempt to add to events\n        if len(self.events) < 25:  # Events list limited to 25 events (drop any events past this)\n            params = {**self.metadata, **{'task': cfg.task}}\n            if cfg.mode == 'export':\n                params['format'] = cfg.format\n            self.events.append({'name': cfg.mode, 'params': params})\n\n        # Check rate limit\n        t = time.time()\n        if (t - self.t) < self.rate_limit:\n            # Time is under rate limiter, wait to send\n            return\n\n        # Time is over rate limiter, send now\n        data = {'client_id': SETTINGS['uuid'], 'events': self.events}  # SHA-256 anonymized UUID hash and events list\n\n        # POST equivalent to requests.post(self.url, json=data)\n        smart_request('post', self.url, json=data, retry=0, verbose=False)\n\n        # Reset events and rate limit timer\n        self.events = []\n        self.t = t\n\n\n# Run below code on hub/utils init -------------------------------------------------------------------------------------\nevents = Events()\n"
  },
  {
    "path": "ultralytics/models/README.md",
    "content": "## Models\n\nWelcome to the Ultralytics Models directory! Here you will find a wide variety of pre-configured model configuration\nfiles (`*.yaml`s) that can be used to create custom YOLO models. The models in this directory have been expertly crafted\nand fine-tuned by the Ultralytics team to provide the best performance for a wide range of object detection and image\nsegmentation tasks.\n\nThese model configurations cover a wide range of scenarios, from simple object detection to more complex tasks like\ninstance segmentation and object tracking. They are also designed to run efficiently on a variety of hardware platforms,\nfrom CPUs to GPUs. Whether you are a seasoned machine learning practitioner or just getting started with YOLO, this\ndirectory provides a great starting point for your custom model development needs.\n\nTo get started, simply browse through the models in this directory and find one that best suits your needs. Once you've\nselected a model, you can use the provided `*.yaml` file to train and deploy your custom YOLO model with ease. See full\ndetails at the Ultralytics [Docs](https://docs.ultralytics.com/models), and if you need help or have any questions, feel free\nto reach out to the Ultralytics team for support. So, don't wait, start creating your custom YOLO model now!\n\n### Usage\n\nModel `*.yaml` files may be used directly in the Command Line Interface (CLI) with a `yolo` command:\n\n```bash\nyolo task=detect mode=train model=yolov8n.yaml data=coco128.yaml epochs=100\n```\n\nThey may also be used directly in a Python environment, and accepts the same\n[arguments](https://docs.ultralytics.com/usage/cfg/) as in the CLI example above:\n\n```python\nfrom ultralytics import YOLO\n\nmodel = YOLO(\"model.yaml\")  # build a YOLOv8n model from scratch\n# YOLO(\"model.pt\")  use pre-trained model if available\nmodel.info()  # display model information\nmodel.train(data=\"coco128.yaml\", epochs=100)  # train the model\n```\n\n## Pre-trained Model Architectures\n\nUltralytics supports many model architectures. Visit https://docs.ultralytics.com/models to view detailed information\nand usage. Any of these models can be used by loading their configs or pretrained checkpoints if available.\n\n## Contributing New Models\n\nIf you've developed a new model architecture or have improvements for existing models that you'd like to contribute to the Ultralytics community, please submit your contribution in a new Pull Request. For more details, visit our [Contributing Guide](https://docs.ultralytics.com/help/contributing).\n"
  },
  {
    "path": "ultralytics/models/rt-detr/rtdetr-l.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# RT-DETR-l object detection model with P3-P5 outputs. For details see https://docs.ultralytics.com/models/rtdetr\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n-cls.yaml' will call yolov8-cls.yaml with scale 'n'\n  # [depth, width, max_channels]\n  l: [1.00, 1.00, 1024]\n\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, HGStem, [32, 48]]  # 0-P2/4\n  - [-1, 6, HGBlock, [48, 128, 3]]  # stage 1\n\n  - [-1, 1, DWConv, [128, 3, 2, 1, False]]  # 2-P3/8\n  - [-1, 6, HGBlock, [96, 512, 3]]   # stage 2\n\n  - [-1, 1, DWConv, [512, 3, 2, 1, False]]  # 4-P3/16\n  - [-1, 6, HGBlock, [192, 1024, 5, True, False]]  # cm, c2, k, light, shortcut\n  - [-1, 6, HGBlock, [192, 1024, 5, True, True]]\n  - [-1, 6, HGBlock, [192, 1024, 5, True, True]]  # stage 3\n\n  - [-1, 1, DWConv, [1024, 3, 2, 1, False]]  # 8-P4/32\n  - [-1, 6, HGBlock, [384, 2048, 5, True, False]]  # stage 4\n\nhead:\n  - [-1, 1, Conv, [256, 1, 1, None, 1, 1, False]]  # 10 input_proj.2\n  - [-1, 1, AIFI, [1024, 8]]\n  - [-1, 1, Conv, [256, 1, 1]]   # 12, Y5, lateral_convs.0\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [7, 1, Conv, [256, 1, 1, None, 1, 1, False]]  # 14 input_proj.1\n  - [[-2, -1], 1, Concat, [1]]\n  - [-1, 3, RepC3, [256]]  # 16, fpn_blocks.0\n  - [-1, 1, Conv, [256, 1, 1]]   # 17, Y4, lateral_convs.1\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [3, 1, Conv, [256, 1, 1, None, 1, 1, False]]  # 19 input_proj.0\n  - [[-2, -1], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, RepC3, [256]]    # X3 (21), fpn_blocks.1\n\n  - [-1, 1, Conv, [256, 3, 2]]   # 22, downsample_convs.0\n  - [[-1, 17], 1, Concat, [1]]  # cat Y4\n  - [-1, 3, RepC3, [256]]    # F4 (24), pan_blocks.0\n\n  - [-1, 1, Conv, [256, 3, 2]]   # 25, downsample_convs.1\n  - [[-1, 12], 1, Concat, [1]]  # cat Y5\n  - [-1, 3, RepC3, [256]]    # F5 (27), pan_blocks.1\n\n  - [[21, 24, 27], 1, RTDETRDecoder, [nc]]  # Detect(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/rt-detr/rtdetr-x.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# RT-DETR-x object detection model with P3-P5 outputs. For details see https://docs.ultralytics.com/models/rtdetr\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n-cls.yaml' will call yolov8-cls.yaml with scale 'n'\n  # [depth, width, max_channels]\n  x: [1.00, 1.00, 2048]\n\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, HGStem, [32, 64]]  # 0-P2/4\n  - [-1, 6, HGBlock, [64, 128, 3]]  # stage 1\n\n  - [-1, 1, DWConv, [128, 3, 2, 1, False]]  # 2-P3/8\n  - [-1, 6, HGBlock, [128, 512, 3]]\n  - [-1, 6, HGBlock, [128, 512, 3, False, True]]   # 4-stage 2\n\n  - [-1, 1, DWConv, [512, 3, 2, 1, False]]  # 5-P3/16\n  - [-1, 6, HGBlock, [256, 1024, 5, True, False]]  # cm, c2, k, light, shortcut\n  - [-1, 6, HGBlock, [256, 1024, 5, True, True]]\n  - [-1, 6, HGBlock, [256, 1024, 5, True, True]]\n  - [-1, 6, HGBlock, [256, 1024, 5, True, True]]\n  - [-1, 6, HGBlock, [256, 1024, 5, True, True]]  # 10-stage 3\n\n  - [-1, 1, DWConv, [1024, 3, 2, 1, False]]  # 11-P4/32\n  - [-1, 6, HGBlock, [512, 2048, 5, True, False]]\n  - [-1, 6, HGBlock, [512, 2048, 5, True, True]]  # 13-stage 4\n\nhead:\n  - [-1, 1, Conv, [384, 1, 1, None, 1, 1, False]]  # 14 input_proj.2\n  - [-1, 1, AIFI, [2048, 8]]\n  - [-1, 1, Conv, [384, 1, 1]]   # 16, Y5, lateral_convs.0\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [10, 1, Conv, [384, 1, 1, None, 1, 1, False]]  # 18 input_proj.1\n  - [[-2, -1], 1, Concat, [1]]\n  - [-1, 3, RepC3, [384]]  # 20, fpn_blocks.0\n  - [-1, 1, Conv, [384, 1, 1]]   # 21, Y4, lateral_convs.1\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [4, 1, Conv, [384, 1, 1, None, 1, 1, False]]  # 23 input_proj.0\n  - [[-2, -1], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, RepC3, [384]]    # X3 (25), fpn_blocks.1\n\n  - [-1, 1, Conv, [384, 3, 2]]   # 26, downsample_convs.0\n  - [[-1, 21], 1, Concat, [1]]  # cat Y4\n  - [-1, 3, RepC3, [384]]    # F4 (28), pan_blocks.0\n\n  - [-1, 1, Conv, [384, 3, 2]]   # 29, downsample_convs.1\n  - [[-1, 16], 1, Concat, [1]]  # cat Y5\n  - [-1, 3, RepC3, [384]]    # F5 (31), pan_blocks.1\n\n  - [[25, 28, 31], 1, RTDETRDecoder, [nc]]  # Detect(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/v3/yolov3-spp.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv3-SPP object detection model with P3-P5 outputs. For details see https://docs.ultralytics.com/models/yolov3\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\n\n# darknet53 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [32, 3, 1]],  # 0\n   [-1, 1, Conv, [64, 3, 2]],  # 1-P1/2\n   [-1, 1, Bottleneck, [64]],\n   [-1, 1, Conv, [128, 3, 2]],  # 3-P2/4\n   [-1, 2, Bottleneck, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 5-P3/8\n   [-1, 8, Bottleneck, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 7-P4/16\n   [-1, 8, Bottleneck, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P5/32\n   [-1, 4, Bottleneck, [1024]],  # 10\n  ]\n\n# YOLOv3-SPP head\nhead:\n  [[-1, 1, Bottleneck, [1024, False]],\n   [-1, 1, SPP, [512, [5, 9, 13]]],\n   [-1, 1, Conv, [1024, 3, 1]],\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, Conv, [1024, 3, 1]],  # 15 (P5/32-large)\n\n   [-2, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, Conv, [512, 3, 1]],  # 22 (P4/16-medium)\n\n   [-2, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P3\n   [-1, 1, Bottleneck, [256, False]],\n   [-1, 2, Bottleneck, [256, False]],  # 27 (P3/8-small)\n\n   [[27, 22, 15], 1, Detect, [nc]],   # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "ultralytics/models/v3/yolov3-tiny.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv3-tiny object detection model with P4-P5 outputs. For details see https://docs.ultralytics.com/models/yolov3\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\n\n# YOLOv3-tiny backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [16, 3, 1]],  # 0\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 1-P1/2\n   [-1, 1, Conv, [32, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 3-P2/4\n   [-1, 1, Conv, [64, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 5-P3/8\n   [-1, 1, Conv, [128, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 7-P4/16\n   [-1, 1, Conv, [256, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 9-P5/32\n   [-1, 1, Conv, [512, 3, 1]],\n   [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]],  # 11\n   [-1, 1, nn.MaxPool2d, [2, 1, 0]],  # 12\n  ]\n\n# YOLOv3-tiny head\nhead:\n  [[-1, 1, Conv, [1024, 3, 1]],\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, Conv, [512, 3, 1]],  # 15 (P5/32-large)\n\n   [-2, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, Conv, [256, 3, 1]],  # 19 (P4/16-medium)\n\n   [[19, 15], 1, Detect, [nc]],  # Detect(P4, P5)\n  ]\n"
  },
  {
    "path": "ultralytics/models/v3/yolov3.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv3 object detection model with P3-P5 outputs. For details see https://docs.ultralytics.com/models/yolov3\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\n\n# darknet53 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [32, 3, 1]],  # 0\n   [-1, 1, Conv, [64, 3, 2]],  # 1-P1/2\n   [-1, 1, Bottleneck, [64]],\n   [-1, 1, Conv, [128, 3, 2]],  # 3-P2/4\n   [-1, 2, Bottleneck, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 5-P3/8\n   [-1, 8, Bottleneck, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 7-P4/16\n   [-1, 8, Bottleneck, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P5/32\n   [-1, 4, Bottleneck, [1024]],  # 10\n  ]\n\n# YOLOv3 head\nhead:\n  [[-1, 1, Bottleneck, [1024, False]],\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, Conv, [1024, 3, 1]],\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, Conv, [1024, 3, 1]],  # 15 (P5/32-large)\n\n   [-2, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, Conv, [512, 3, 1]],  # 22 (P4/16-medium)\n\n   [-2, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P3\n   [-1, 1, Bottleneck, [256, False]],\n   [-1, 2, Bottleneck, [256, False]],  # 27 (P3/8-small)\n\n   [[27, 22, 15], 1, Detect, [nc]],   # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "ultralytics/models/v5/yolov5-p6.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv5 object detection model with P3-P6 outputs. For details see https://docs.ultralytics.com/models/yolov5\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov5n-p6.yaml' will call yolov5-p6.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 1024]\n  l: [1.00, 1.00, 1024]\n  x: [1.33, 1.25, 1024]\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [768, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [768]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P6/64\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 11\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [768, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P5\n   [-1, 3, C3, [768, False]],  # 15\n\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 19\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 23 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 20], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 26 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 16], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [768, False]],  # 29 (P5/32-large)\n\n   [-1, 1, Conv, [768, 3, 2]],\n   [[-1, 12], 1, Concat, [1]],  # cat head P6\n   [-1, 3, C3, [1024, False]],  # 32 (P6/64-xlarge)\n\n   [[23, 26, 29, 32], 1, Detect, [nc]],  # Detect(P3, P4, P5, P6)\n  ]\n"
  },
  {
    "path": "ultralytics/models/v5/yolov5.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv5 object detection model with P3-P5 outputs. For details see https://docs.ultralytics.com/models/yolov5\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov5n.yaml' will call yolov5.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 1024]\n  l: [1.00, 1.00, 1024]\n  x: [1.33, 1.25, 1024]\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)\n\n   [[17, 20, 23], 1, Detect, [nc]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "ultralytics/models/v6/yolov6.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv6 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/models/yolov6\n\n# Parameters\nnc: 80  # number of classes\nactivation: nn.ReLU()  # (optional) model default activation function\nscales: # model compound scaling constants, i.e. 'model=yolov6n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 768]\n  l: [1.00, 1.00, 512]\n  x: [1.00, 1.25, 512]\n\n# YOLOv6-3.0s backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 6, Conv, [128, 3, 1]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 12, Conv, [256, 3, 1]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 18, Conv, [512, 3, 1]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 6, Conv, [1024, 3, 1]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv6-3.0s head\nhead:\n  - [-1, 1, Conv, [256, 1, 1]]\n  - [-1, 1, nn.ConvTranspose2d, [256, 2, 2, 0]]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 1, Conv, [256, 3, 1]]\n  - [-1, 9, Conv, [256, 3, 1]]  # 14\n\n  - [-1, 1, Conv, [128, 1, 1]]\n  - [-1, 1, nn.ConvTranspose2d, [128, 2, 2, 0]]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 1, Conv, [128, 3, 1]]\n  - [-1, 9, Conv, [128, 3, 1]]  # 19\n\n  - [-1, 1, Conv, [128, 3, 2]]\n  - [[-1, 15], 1, Concat, [1]]  # cat head P4\n  - [-1, 1, Conv, [256, 3, 1]]\n  - [-1, 9, Conv, [256, 3, 1]]  # 23\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 10], 1, Concat, [1]]  # cat head P5\n  - [-1, 1, Conv, [512, 3, 1]]\n  - [-1, 9, Conv, [512, 3, 1]]  # 27\n\n  - [[19, 23, 27], 1, Detect, [nc]]  # Detect(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-cls.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8-cls image classification model. For Usage examples see https://docs.ultralytics.com/tasks/classify\n\n# Parameters\nnc: 1000  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n-cls.yaml' will call yolov8-cls.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 1024]\n  l: [1.00, 1.00, 1024]\n  x: [1.00, 1.25, 1024]\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, Classify, [nc]]  # Classify\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-p2.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P2-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 768]\n  l: [1.00, 1.00, 512]\n  x: [1.00, 1.25, 512]\n\n# YOLOv8.0 backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0-p2 head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 2], 1, Concat, [1]]  # cat backbone P2\n  - [-1, 3, C2f, [128]]  # 18 (P2/4-xsmall)\n\n  - [-1, 1, Conv, [128, 3, 2]]\n  - [[-1, 15], 1, Concat, [1]]  # cat head P3\n  - [-1, 3, C2f, [256]]  # 21 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 24 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 27 (P5/32-large)\n\n  - [[18, 21, 24, 27], 1, Detect, [nc]]  # Detect(P2, P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-p6.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P3-P6 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n-p6.yaml' will call yolov8-p6.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 768]\n  l: [1.00, 1.00, 512]\n  x: [1.00, 1.25, 512]\n\n# YOLOv8.0x6 backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [768, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [768, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 9-P6/64\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 11\n\n# YOLOv8.0x6 head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 8], 1, Concat, [1]]  # cat backbone P5\n  - [-1, 3, C2, [768, False]]  # 14\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2, [512, False]]  # 17\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2, [256, False]]  # 20 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 17], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2, [512, False]]  # 23 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 14], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2, [768, False]]  # 26 (P5/32-large)\n\n  - [-1, 1, Conv, [768, 3, 2]]\n  - [[-1, 11], 1, Concat, [1]]  # cat head P6\n  - [-1, 3, C2, [1024, False]]  # 29 (P6/64-xlarge)\n\n  - [[20, 23, 26, 29], 1, Detect, [nc]]  # Detect(P3, P4, P5, P6)\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-pose-p6.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8-pose keypoints/pose estimation model. For Usage examples see https://docs.ultralytics.com/tasks/pose\n\n# Parameters\nnc: 1  # number of classes\nkpt_shape: [17, 3]  # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)\nscales: # model compound scaling constants, i.e. 'model=yolov8n-p6.yaml' will call yolov8-p6.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 768]\n  l: [1.00, 1.00, 512]\n  x: [1.00, 1.25, 512]\n\n# YOLOv8.0x6 backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [768, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [768, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 9-P6/64\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 11\n\n# YOLOv8.0x6 head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 8], 1, Concat, [1]]  # cat backbone P5\n  - [-1, 3, C2, [768, False]]  # 14\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2, [512, False]]  # 17\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2, [256, False]]  # 20 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 17], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2, [512, False]]  # 23 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 14], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2, [768, False]]  # 26 (P5/32-large)\n\n  - [-1, 1, Conv, [768, 3, 2]]\n  - [[-1, 11], 1, Concat, [1]]  # cat head P6\n  - [-1, 3, C2, [1024, False]]  # 29 (P6/64-xlarge)\n\n  - [[20, 23, 26, 29], 1, Pose, [nc, kpt_shape]]  # Pose(P3, P4, P5, P6)\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-pose.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8-pose keypoints/pose estimation model. For Usage examples see https://docs.ultralytics.com/tasks/pose\n\n# Parameters\nnc: 1  # number of classes\nkpt_shape: [17, 3]  # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)\nscales: # model compound scaling constants, i.e. 'model=yolov8n-pose.yaml' will call yolov8-pose.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 768]\n  l: [1.00, 1.00, 512]\n  x: [1.00, 1.25, 512]\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n  - [[15, 18, 21], 1, Pose, [nc, kpt_shape]]  # Pose(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-rtdetr.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]  # YOLOv8n summary: 225 layers,  3157200 parameters,  3157184 gradients,   8.9 GFLOPs\n  s: [0.33, 0.50, 1024]  # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients,  28.8 GFLOPs\n  m: [0.67, 0.75, 768]   # YOLOv8m summary: 295 layers, 25902640 parameters, 25902624 gradients,  79.3 GFLOPs\n  l: [1.00, 1.00, 512]   # YOLOv8l summary: 365 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPs\n  x: [1.00, 1.25, 512]   # YOLOv8x summary: 365 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPs\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n  - [[15, 18, 21], 1, RTDETRDecoder, [nc]]  # Detect(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-seg.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8-seg instance segmentation model. For Usage examples see https://docs.ultralytics.com/tasks/segment\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n-seg.yaml' will call yolov8-seg.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 768]\n  l: [1.00, 1.00, 512]\n  x: [1.00, 1.25, 512]\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n  - [[15, 18, 21], 1, Segment, [nc, 32, 256]]  # Segment(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]  # YOLOv8n summary: 225 layers,  3157200 parameters,  3157184 gradients,   8.9 GFLOPs\n  s: [0.33, 0.50, 1024]  # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients,  28.8 GFLOPs\n  m: [0.67, 0.75, 768]   # YOLOv8m summary: 295 layers, 25902640 parameters, 25902624 gradients,  79.3 GFLOPs\n  l: [1.00, 1.00, 512]   # YOLOv8l summary: 365 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPs\n  x: [1.00, 1.25, 512]   # YOLOv8x summary: 365 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPs\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n  - [[15, 18, 21], 1, Detect, [nc]]  # Detect(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/nn/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .tasks import (BaseModel, ClassificationModel, DetectionModel, SegmentationModel, attempt_load_one_weight,\n                    attempt_load_weights, guess_model_scale, guess_model_task, parse_model, torch_safe_load,\n                    yaml_model_load)\n\n__all__ = ('attempt_load_one_weight', 'attempt_load_weights', 'parse_model', 'yaml_model_load', 'guess_model_task',\n           'guess_model_scale', 'torch_safe_load', 'DetectionModel', 'SegmentationModel', 'ClassificationModel',\n           'BaseModel')\n"
  },
  {
    "path": "ultralytics/nn/autobackend.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport ast\nimport contextlib\nimport json\nimport platform\nimport zipfile\nfrom collections import OrderedDict, namedtuple\nfrom pathlib import Path\nfrom urllib.parse import urlparse\n\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom PIL import Image\n\nfrom ultralytics.yolo.utils import LINUX, LOGGER, ROOT, yaml_load\nfrom ultralytics.yolo.utils.checks import check_requirements, check_suffix, check_version, check_yaml\nfrom ultralytics.yolo.utils.downloads import attempt_download_asset, is_url\nfrom ultralytics.yolo.utils.ops import xywh2xyxy\n\n\ndef check_class_names(names):\n    \"\"\"Check class names. Map imagenet class codes to human-readable names if required. Convert lists to dicts.\"\"\"\n    if isinstance(names, list):  # names is a list\n        names = dict(enumerate(names))  # convert to dict\n    if isinstance(names, dict):\n        # Convert 1) string keys to int, i.e. '0' to 0, and non-string values to strings, i.e. True to 'True'\n        names = {int(k): str(v) for k, v in names.items()}\n        n = len(names)\n        if max(names.keys()) >= n:\n            raise KeyError(f'{n}-class dataset requires class indices 0-{n - 1}, but you have invalid class indices '\n                           f'{min(names.keys())}-{max(names.keys())} defined in your dataset YAML.')\n        if isinstance(names[0], str) and names[0].startswith('n0'):  # imagenet class codes, i.e. 'n01440764'\n            map = yaml_load(ROOT / 'datasets/ImageNet.yaml')['map']  # human-readable names\n            names = {k: map[v] for k, v in names.items()}\n    return names\n\n\nclass AutoBackend(nn.Module):\n\n    def __init__(self,\n                 weights='yolov8n.pt',\n                 device=torch.device('cpu'),\n                 dnn=False,\n                 data=None,\n                 fp16=False,\n                 fuse=True,\n                 verbose=True):\n        \"\"\"\n        MultiBackend class for python inference on various platforms using Ultralytics YOLO.\n\n        Args:\n            weights (str): The path to the weights file. Default: 'yolov8n.pt'\n            device (torch.device): The device to run the model on.\n            dnn (bool): Use OpenCV DNN module for inference if True, defaults to False.\n            data (str | Path | optional): Additional data.yaml file for class names.\n            fp16 (bool): If True, use half precision. Default: False\n            fuse (bool): Whether to fuse the model or not. Default: True\n            verbose (bool): Whether to run in verbose mode or not. Default: True\n\n        Supported formats and their naming conventions:\n            | Format                | Suffix           |\n            |-----------------------|------------------|\n            | PyTorch               | *.pt             |\n            | TorchScript           | *.torchscript    |\n            | ONNX Runtime          | *.onnx           |\n            | ONNX OpenCV DNN       | *.onnx dnn=True  |\n            | OpenVINO              | *.xml            |\n            | CoreML                | *.mlmodel        |\n            | TensorRT              | *.engine         |\n            | TensorFlow SavedModel | *_saved_model    |\n            | TensorFlow GraphDef   | *.pb             |\n            | TensorFlow Lite       | *.tflite         |\n            | TensorFlow Edge TPU   | *_edgetpu.tflite |\n            | PaddlePaddle          | *_paddle_model   |\n        \"\"\"\n        super().__init__()\n        w = str(weights[0] if isinstance(weights, list) else weights)\n        nn_module = isinstance(weights, torch.nn.Module)\n        pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle, triton = self._model_type(w)\n        fp16 &= pt or jit or onnx or engine or nn_module or triton  # FP16\n        nhwc = coreml or saved_model or pb or tflite or edgetpu  # BHWC formats (vs torch BCWH)\n        stride = 32  # default stride\n        model, metadata = None, None\n        cuda = torch.cuda.is_available() and device.type != 'cpu'  # use CUDA\n        if not (pt or triton or nn_module):\n            w = attempt_download_asset(w)  # download if not local\n\n        # NOTE: special case: in-memory pytorch model\n        if nn_module:\n            model = weights.to(device)\n            model = model.fuse(verbose=verbose) if fuse else model\n            if hasattr(model, 'kpt_shape'):\n                kpt_shape = model.kpt_shape  # pose-only\n            stride = max(int(model.stride.max()), 32)  # model stride\n            names = model.module.names if hasattr(model, 'module') else model.names  # get class names\n            model.half() if fp16 else model.float()\n            self.model = model  # explicitly assign for to(), cpu(), cuda(), half()\n            pt = True\n        elif pt:  # PyTorch\n            from ultralytics.nn.tasks import attempt_load_weights\n            model = attempt_load_weights(weights if isinstance(weights, list) else w,\n                                         device=device,\n                                         inplace=True,\n                                         fuse=fuse)\n            if hasattr(model, 'kpt_shape'):\n                kpt_shape = model.kpt_shape  # pose-only\n            stride = max(int(model.stride.max()), 32)  # model stride\n            names = model.module.names if hasattr(model, 'module') else model.names  # get class names\n            model.half() if fp16 else model.float()\n            self.model = model  # explicitly assign for to(), cpu(), cuda(), half()\n        elif jit:  # TorchScript\n            LOGGER.info(f'Loading {w} for TorchScript inference...')\n            extra_files = {'config.txt': ''}  # model metadata\n            model = torch.jit.load(w, _extra_files=extra_files, map_location=device)\n            model.half() if fp16 else model.float()\n            if extra_files['config.txt']:  # load metadata dict\n                metadata = json.loads(extra_files['config.txt'], object_hook=lambda x: dict(x.items()))\n        elif dnn:  # ONNX OpenCV DNN\n            LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...')\n            check_requirements('opencv-python>=4.5.4')\n            net = cv2.dnn.readNetFromONNX(w)\n        elif onnx:  # ONNX Runtime\n            LOGGER.info(f'Loading {w} for ONNX Runtime inference...')\n            check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime'))\n            import onnxruntime\n            providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']\n            session = onnxruntime.InferenceSession(w, providers=providers)\n            output_names = [x.name for x in session.get_outputs()]\n            metadata = session.get_modelmeta().custom_metadata_map  # metadata\n        elif xml:  # OpenVINO\n            LOGGER.info(f'Loading {w} for OpenVINO inference...')\n            check_requirements('openvino')  # requires openvino-dev: https://pypi.org/project/openvino-dev/\n            from openvino.runtime import Core, Layout, get_batch  # noqa\n            ie = Core()\n            w = Path(w)\n            if not w.is_file():  # if not *.xml\n                w = next(w.glob('*.xml'))  # get *.xml file from *_openvino_model dir\n            network = ie.read_model(model=str(w), weights=w.with_suffix('.bin'))\n            if network.get_parameters()[0].get_layout().empty:\n                network.get_parameters()[0].set_layout(Layout('NCHW'))\n            batch_dim = get_batch(network)\n            if batch_dim.is_static:\n                batch_size = batch_dim.get_length()\n            executable_network = ie.compile_model(network, device_name='CPU')  # device_name=\"MYRIAD\" for NCS2\n            metadata = w.parent / 'metadata.yaml'\n        elif engine:  # TensorRT\n            LOGGER.info(f'Loading {w} for TensorRT inference...')\n            try:\n                import tensorrt as trt  # noqa https://developer.nvidia.com/nvidia-tensorrt-download\n            except ImportError:\n                if LINUX:\n                    check_requirements('nvidia-tensorrt', cmds='-U --index-url https://pypi.ngc.nvidia.com')\n                import tensorrt as trt  # noqa\n            check_version(trt.__version__, '7.0.0', hard=True)  # require tensorrt>=7.0.0\n            if device.type == 'cpu':\n                device = torch.device('cuda:0')\n            Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr'))\n            logger = trt.Logger(trt.Logger.INFO)\n            # Read file\n            with open(w, 'rb') as f, trt.Runtime(logger) as runtime:\n                meta_len = int.from_bytes(f.read(4), byteorder='little')  # read metadata length\n                metadata = json.loads(f.read(meta_len).decode('utf-8'))  # read metadata\n                model = runtime.deserialize_cuda_engine(f.read())  # read engine\n            context = model.create_execution_context()\n            bindings = OrderedDict()\n            output_names = []\n            fp16 = False  # default updated below\n            dynamic = False\n            for i in range(model.num_bindings):\n                name = model.get_binding_name(i)\n                dtype = trt.nptype(model.get_binding_dtype(i))\n                if model.binding_is_input(i):\n                    if -1 in tuple(model.get_binding_shape(i)):  # dynamic\n                        dynamic = True\n                        context.set_binding_shape(i, tuple(model.get_profile_shape(0, i)[2]))\n                    if dtype == np.float16:\n                        fp16 = True\n                else:  # output\n                    output_names.append(name)\n                shape = tuple(context.get_binding_shape(i))\n                im = torch.from_numpy(np.empty(shape, dtype=dtype)).to(device)\n                bindings[name] = Binding(name, dtype, shape, im, int(im.data_ptr()))\n            binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())\n            batch_size = bindings['images'].shape[0]  # if dynamic, this is instead max batch size\n        elif coreml:  # CoreML\n            LOGGER.info(f'Loading {w} for CoreML inference...')\n            import coremltools as ct\n            model = ct.models.MLModel(w)\n            metadata = dict(model.user_defined_metadata)\n        elif saved_model:  # TF SavedModel\n            LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...')\n            import tensorflow as tf\n            keras = False  # assume TF1 saved_model\n            model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w)\n            metadata = Path(w) / 'metadata.yaml'\n        elif pb:  # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt\n            LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...')\n            import tensorflow as tf\n\n            from ultralytics.yolo.engine.exporter import gd_outputs\n\n            def wrap_frozen_graph(gd, inputs, outputs):\n                \"\"\"Wrap frozen graphs for deployment.\"\"\"\n                x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=''), [])  # wrapped\n                ge = x.graph.as_graph_element\n                return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))\n\n            gd = tf.Graph().as_graph_def()  # TF GraphDef\n            with open(w, 'rb') as f:\n                gd.ParseFromString(f.read())\n            frozen_func = wrap_frozen_graph(gd, inputs='x:0', outputs=gd_outputs(gd))\n        elif tflite or edgetpu:  # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python\n            try:  # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu\n                from tflite_runtime.interpreter import Interpreter, load_delegate\n            except ImportError:\n                import tensorflow as tf\n                Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate\n            if edgetpu:  # TF Edge TPU https://coral.ai/software/#edgetpu-runtime\n                LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...')\n                delegate = {\n                    'Linux': 'libedgetpu.so.1',\n                    'Darwin': 'libedgetpu.1.dylib',\n                    'Windows': 'edgetpu.dll'}[platform.system()]\n                interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)])\n            else:  # TFLite\n                LOGGER.info(f'Loading {w} for TensorFlow Lite inference...')\n                interpreter = Interpreter(model_path=w)  # load TFLite model\n            interpreter.allocate_tensors()  # allocate\n            input_details = interpreter.get_input_details()  # inputs\n            output_details = interpreter.get_output_details()  # outputs\n            # Load metadata\n            with contextlib.suppress(zipfile.BadZipFile):\n                with zipfile.ZipFile(w, 'r') as model:\n                    meta_file = model.namelist()[0]\n                    metadata = ast.literal_eval(model.read(meta_file).decode('utf-8'))\n        elif tfjs:  # TF.js\n            raise NotImplementedError('YOLOv8 TF.js inference is not supported')\n        elif paddle:  # PaddlePaddle\n            LOGGER.info(f'Loading {w} for PaddlePaddle inference...')\n            check_requirements('paddlepaddle-gpu' if cuda else 'paddlepaddle')\n            import paddle.inference as pdi  # noqa\n            w = Path(w)\n            if not w.is_file():  # if not *.pdmodel\n                w = next(w.rglob('*.pdmodel'))  # get *.pdmodel file from *_paddle_model dir\n            config = pdi.Config(str(w), str(w.with_suffix('.pdiparams')))\n            if cuda:\n                config.enable_use_gpu(memory_pool_init_size_mb=2048, device_id=0)\n            predictor = pdi.create_predictor(config)\n            input_handle = predictor.get_input_handle(predictor.get_input_names()[0])\n            output_names = predictor.get_output_names()\n            metadata = w.parents[1] / 'metadata.yaml'\n        elif triton:  # NVIDIA Triton Inference Server\n            LOGGER.info('Triton Inference Server not supported...')\n            '''\n            TODO:\n            check_requirements('tritonclient[all]')\n            from utils.triton import TritonRemoteModel\n            model = TritonRemoteModel(url=w)\n            nhwc = model.runtime.startswith(\"tensorflow\")\n            '''\n        else:\n            from ultralytics.yolo.engine.exporter import export_formats\n            raise TypeError(f\"model='{w}' is not a supported model format. \"\n                            'See https://docs.ultralytics.com/modes/predict for help.'\n                            f'\\n\\n{export_formats()}')\n\n        # Load external metadata YAML\n        if isinstance(metadata, (str, Path)) and Path(metadata).exists():\n            metadata = yaml_load(metadata)\n        if metadata:\n            for k, v in metadata.items():\n                if k in ('stride', 'batch'):\n                    metadata[k] = int(v)\n                elif k in ('imgsz', 'names', 'kpt_shape') and isinstance(v, str):\n                    metadata[k] = eval(v)\n            stride = metadata['stride']\n            task = metadata['task']\n            batch = metadata['batch']\n            imgsz = metadata['imgsz']\n            names = metadata['names']\n            kpt_shape = metadata.get('kpt_shape')\n        elif not (pt or triton or nn_module):\n            LOGGER.warning(f\"WARNING ⚠️ Metadata not found for 'model={weights}'\")\n\n        # Check names\n        if 'names' not in locals():  # names missing\n            names = self._apply_default_class_names(data)\n        names = check_class_names(names)\n\n        self.__dict__.update(locals())  # assign all variables to self\n\n    def forward(self, im, augment=False, visualize=False):\n        \"\"\"\n        Runs inference on the YOLOv8 MultiBackend model.\n\n        Args:\n            im (torch.Tensor): The image tensor to perform inference on.\n            augment (bool): whether to perform data augmentation during inference, defaults to False\n            visualize (bool): whether to visualize the output predictions, defaults to False\n\n        Returns:\n            (tuple): Tuple containing the raw output tensor, and processed output for visualization (if visualize=True)\n        \"\"\"\n        b, ch, h, w = im.shape  # batch, channel, height, width\n        if self.fp16 and im.dtype != torch.float16:\n            im = im.half()  # to FP16\n        if self.nhwc:\n            im = im.permute(0, 2, 3, 1)  # torch BCHW to numpy BHWC shape(1,320,192,3)\n\n        if self.pt or self.nn_module:  # PyTorch\n            y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im)\n        elif self.jit:  # TorchScript\n            y = self.model(im)\n        elif self.dnn:  # ONNX OpenCV DNN\n            im = im.cpu().numpy()  # torch to numpy\n            self.net.setInput(im)\n            y = self.net.forward()\n        elif self.onnx:  # ONNX Runtime\n            im = im.cpu().numpy()  # torch to numpy\n            y = self.session.run(self.output_names, {self.session.get_inputs()[0].name: im})\n        elif self.xml:  # OpenVINO\n            im = im.cpu().numpy()  # FP32\n            y = list(self.executable_network([im]).values())\n        elif self.engine:  # TensorRT\n            if self.dynamic and im.shape != self.bindings['images'].shape:\n                i = self.model.get_binding_index('images')\n                self.context.set_binding_shape(i, im.shape)  # reshape if dynamic\n                self.bindings['images'] = self.bindings['images']._replace(shape=im.shape)\n                for name in self.output_names:\n                    i = self.model.get_binding_index(name)\n                    self.bindings[name].data.resize_(tuple(self.context.get_binding_shape(i)))\n            s = self.bindings['images'].shape\n            assert im.shape == s, f\"input size {im.shape} {'>' if self.dynamic else 'not equal to'} max model size {s}\"\n            self.binding_addrs['images'] = int(im.data_ptr())\n            self.context.execute_v2(list(self.binding_addrs.values()))\n            y = [self.bindings[x].data for x in sorted(self.output_names)]\n        elif self.coreml:  # CoreML\n            im = im[0].cpu().numpy()\n            im_pil = Image.fromarray((im * 255).astype('uint8'))\n            # im = im.resize((192, 320), Image.ANTIALIAS)\n            y = self.model.predict({'image': im_pil})  # coordinates are xywh normalized\n            if 'confidence' in y:\n                box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]])  # xyxy pixels\n                conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)\n                y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)\n            elif len(y) == 1:  # classification model\n                y = list(y.values())\n            elif len(y) == 2:  # segmentation model\n                y = list(reversed(y.values()))  # reversed for segmentation models (pred, proto)\n        elif self.paddle:  # PaddlePaddle\n            im = im.cpu().numpy().astype(np.float32)\n            self.input_handle.copy_from_cpu(im)\n            self.predictor.run()\n            y = [self.predictor.get_output_handle(x).copy_to_cpu() for x in self.output_names]\n        elif self.triton:  # NVIDIA Triton Inference Server\n            y = self.model(im)\n        else:  # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)\n            im = im.cpu().numpy()\n            if self.saved_model:  # SavedModel\n                y = self.model(im, training=False) if self.keras else self.model(im)\n                if not isinstance(y, list):\n                    y = [y]\n            elif self.pb:  # GraphDef\n                y = self.frozen_func(x=self.tf.constant(im))\n                if len(y) == 2 and len(self.names) == 999:  # segments and names not defined\n                    ip, ib = (0, 1) if len(y[0].shape) == 4 else (1, 0)  # index of protos, boxes\n                    nc = y[ib].shape[1] - y[ip].shape[3] - 4  # y = (1, 160, 160, 32), (1, 116, 8400)\n                    self.names = {i: f'class{i}' for i in range(nc)}\n            else:  # Lite or Edge TPU\n                input = self.input_details[0]\n                int8 = input['dtype'] == np.int8  # is TFLite quantized int8 model\n                if int8:\n                    scale, zero_point = input['quantization']\n                    im = (im / scale + zero_point).astype(np.int8)  # de-scale\n                self.interpreter.set_tensor(input['index'], im)\n                self.interpreter.invoke()\n                y = []\n                for output in self.output_details:\n                    x = self.interpreter.get_tensor(output['index'])\n                    if int8:\n                        scale, zero_point = output['quantization']\n                        x = (x.astype(np.float32) - zero_point) * scale  # re-scale\n                    y.append(x)\n            # TF segment fixes: export is reversed vs ONNX export and protos are transposed\n            if len(y) == 2:  # segment with (det, proto) output order reversed\n                if len(y[1].shape) != 4:\n                    y = list(reversed(y))  # should be y = (1, 116, 8400), (1, 160, 160, 32)\n                y[1] = np.transpose(y[1], (0, 3, 1, 2))  # should be y = (1, 116, 8400), (1, 32, 160, 160)\n            y = [x if isinstance(x, np.ndarray) else x.numpy() for x in y]\n            # y[0][..., :4] *= [w, h, w, h]  # xywh normalized to pixels\n\n        # for x in y:\n        #     print(type(x), len(x)) if isinstance(x, (list, tuple)) else print(type(x), x.shape)  # debug shapes\n        if isinstance(y, (list, tuple)):\n            return self.from_numpy(y[0]) if len(y) == 1 else [self.from_numpy(x) for x in y]\n        else:\n            return self.from_numpy(y)\n\n    def from_numpy(self, x):\n        \"\"\"\n         Convert a numpy array to a tensor.\n\n         Args:\n             x (np.ndarray): The array to be converted.\n\n         Returns:\n             (torch.Tensor): The converted tensor\n         \"\"\"\n        return torch.tensor(x).to(self.device) if isinstance(x, np.ndarray) else x\n\n    def warmup(self, imgsz=(1, 3, 640, 640)):\n        \"\"\"\n        Warm up the model by running one forward pass with a dummy input.\n\n        Args:\n            imgsz (tuple): The shape of the dummy input tensor in the format (batch_size, channels, height, width)\n\n        Returns:\n            (None): This method runs the forward pass and don't return any value\n        \"\"\"\n        warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb, self.triton, self.nn_module\n        if any(warmup_types) and (self.device.type != 'cpu' or self.triton):\n            im = torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device)  # input\n            for _ in range(2 if self.jit else 1):  #\n                self.forward(im)  # warmup\n\n    @staticmethod\n    def _apply_default_class_names(data):\n        \"\"\"Applies default class names to an input YAML file or returns numerical class names.\"\"\"\n        with contextlib.suppress(Exception):\n            return yaml_load(check_yaml(data))['names']\n        return {i: f'class{i}' for i in range(999)}  # return default if above errors\n\n    @staticmethod\n    def _model_type(p='path/to/model.pt'):\n        \"\"\"\n        This function takes a path to a model file and returns the model type\n\n        Args:\n            p: path to the model file. Defaults to path/to/model.pt\n        \"\"\"\n        # Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx\n        # types = [pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle]\n        from ultralytics.yolo.engine.exporter import export_formats\n        sf = list(export_formats().Suffix)  # export suffixes\n        if not is_url(p, check=False) and not isinstance(p, str):\n            check_suffix(p, sf)  # checks\n        url = urlparse(p)  # if url may be Triton inference server\n        types = [s in Path(p).name for s in sf]\n        types[8] &= not types[9]  # tflite &= not edgetpu\n        triton = not any(types) and all([any(s in url.scheme for s in ['http', 'grpc']), url.netloc])\n        return types + [triton]\n"
  },
  {
    "path": "ultralytics/nn/autoshape.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nCommon modules\n\"\"\"\n\nfrom copy import copy\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport requests\nimport torch\nimport torch.nn as nn\nfrom PIL import Image, ImageOps\nfrom torch.cuda import amp\n\nfrom ultralytics.nn.autobackend import AutoBackend\nfrom ultralytics.yolo.data.augment import LetterBox\nfrom ultralytics.yolo.utils import LOGGER, colorstr\nfrom ultralytics.yolo.utils.files import increment_path\nfrom ultralytics.yolo.utils.ops import Profile, make_divisible, non_max_suppression, scale_boxes, xyxy2xywh\nfrom ultralytics.yolo.utils.plotting import Annotator, colors, save_one_box\nfrom ultralytics.yolo.utils.torch_utils import copy_attr, smart_inference_mode\n\n\nclass AutoShape(nn.Module):\n    \"\"\"YOLOv8 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS.\"\"\"\n    conf = 0.25  # NMS confidence threshold\n    iou = 0.45  # NMS IoU threshold\n    agnostic = False  # NMS class-agnostic\n    multi_label = False  # NMS multiple labels per box\n    classes = None  # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs\n    max_det = 1000  # maximum number of detections per image\n    amp = False  # Automatic Mixed Precision (AMP) inference\n\n    def __init__(self, model, verbose=True):\n        \"\"\"Initializes object and copies attributes from model object.\"\"\"\n        super().__init__()\n        if verbose:\n            LOGGER.info('Adding AutoShape... ')\n        copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=())  # copy attributes\n        self.dmb = isinstance(model, AutoBackend)  # DetectMultiBackend() instance\n        self.pt = not self.dmb or model.pt  # PyTorch model\n        self.model = model.eval()\n        if self.pt:\n            m = self.model.model.model[-1] if self.dmb else self.model.model[-1]  # Detect()\n            m.inplace = False  # Detect.inplace=False for safe multithread inference\n            m.export = True  # do not output loss values\n\n    def _apply(self, fn):\n        \"\"\"Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers.\"\"\"\n        self = super()._apply(fn)\n        if self.pt:\n            m = self.model.model.model[-1] if self.dmb else self.model.model[-1]  # Detect()\n            m.stride = fn(m.stride)\n            m.grid = list(map(fn, m.grid))\n            if isinstance(m.anchor_grid, list):\n                m.anchor_grid = list(map(fn, m.anchor_grid))\n        return self\n\n    @smart_inference_mode()\n    def forward(self, ims, size=640, augment=False, profile=False):\n        \"\"\"Inference from various sources. For size(height=640, width=1280), RGB images example inputs are:.\"\"\"\n        #   file:        ims = 'data/images/zidane.jpg'  # str or PosixPath\n        #   URI:             = 'https://ultralytics.com/images/zidane.jpg'\n        #   OpenCV:          = cv2.imread('image.jpg')[:,:,::-1]  # HWC BGR to RGB x(640,1280,3)\n        #   PIL:             = Image.open('image.jpg') or ImageGrab.grab()  # HWC x(640,1280,3)\n        #   numpy:           = np.zeros((640,1280,3))  # HWC\n        #   torch:           = torch.zeros(16,3,320,640)  # BCHW (scaled to size=640, 0-1 values)\n        #   multiple:        = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...]  # list of images\n\n        dt = (Profile(), Profile(), Profile())\n        with dt[0]:\n            if isinstance(size, int):  # expand\n                size = (size, size)\n            p = next(self.model.parameters()) if self.pt else torch.empty(1, device=self.model.device)  # param\n            autocast = self.amp and (p.device.type != 'cpu')  # Automatic Mixed Precision (AMP) inference\n            if isinstance(ims, torch.Tensor):  # torch\n                with amp.autocast(autocast):\n                    return self.model(ims.to(p.device).type_as(p), augment=augment)  # inference\n\n            # Preprocess\n            n, ims = (len(ims), list(ims)) if isinstance(ims, (list, tuple)) else (1, [ims])  # number, list of images\n            shape0, shape1, files = [], [], []  # image and inference shapes, filenames\n            for i, im in enumerate(ims):\n                f = f'image{i}'  # filename\n                if isinstance(im, (str, Path)):  # filename or uri\n                    im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im\n                    im = np.asarray(ImageOps.exif_transpose(im))\n                elif isinstance(im, Image.Image):  # PIL Image\n                    im, f = np.asarray(ImageOps.exif_transpose(im)), getattr(im, 'filename', f) or f\n                files.append(Path(f).with_suffix('.jpg').name)\n                if im.shape[0] < 5:  # image in CHW\n                    im = im.transpose((1, 2, 0))  # reverse dataloader .transpose(2, 0, 1)\n                im = im[..., :3] if im.ndim == 3 else cv2.cvtColor(im, cv2.COLOR_GRAY2BGR)  # enforce 3ch input\n                s = im.shape[:2]  # HWC\n                shape0.append(s)  # image shape\n                g = max(size) / max(s)  # gain\n                shape1.append([y * g for y in s])\n                ims[i] = im if im.data.contiguous else np.ascontiguousarray(im)  # update\n            shape1 = [make_divisible(x, self.stride) for x in np.array(shape1).max(0)] if self.pt else size  # inf shape\n            x = [LetterBox(shape1, auto=False)(image=im)['img'] for im in ims]  # pad\n            x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2)))  # stack and BHWC to BCHW\n            x = torch.from_numpy(x).to(p.device).type_as(p) / 255  # uint8 to fp16/32\n\n        with amp.autocast(autocast):\n            # Inference\n            with dt[1]:\n                y = self.model(x, augment=augment)  # forward\n\n            # Postprocess\n            with dt[2]:\n                y = non_max_suppression(y if self.dmb else y[0],\n                                        self.conf,\n                                        self.iou,\n                                        self.classes,\n                                        self.agnostic,\n                                        self.multi_label,\n                                        max_det=self.max_det)  # NMS\n                for i in range(n):\n                    scale_boxes(shape1, y[i][:, :4], shape0[i])\n\n            return Detections(ims, y, files, dt, self.names, x.shape)\n\n\nclass Detections:\n    \"\"\" YOLOv8 detections class for inference results\"\"\"\n\n    def __init__(self, ims, pred, files, times=(0, 0, 0), names=None, shape=None):\n        \"\"\"Initialize object attributes for YOLO detection results.\"\"\"\n        super().__init__()\n        d = pred[0].device  # device\n        gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in ims]  # normalizations\n        self.ims = ims  # list of images as numpy arrays\n        self.pred = pred  # list of tensors pred[0] = (xyxy, conf, cls)\n        self.names = names  # class names\n        self.files = files  # image filenames\n        self.times = times  # profiling times\n        self.xyxy = pred  # xyxy pixels\n        self.xywh = [xyxy2xywh(x) for x in pred]  # xywh pixels\n        self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)]  # xyxy normalized\n        self.xywhn = [x / g for x, g in zip(self.xywh, gn)]  # xywh normalized\n        self.n = len(self.pred)  # number of images (batch size)\n        self.t = tuple(x.t / self.n * 1E3 for x in times)  # timestamps (ms)\n        self.s = tuple(shape)  # inference BCHW shape\n\n    def _run(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')):\n        \"\"\"Return performance metrics and optionally cropped/save images or results.\"\"\"\n        s, crops = '', []\n        for i, (im, pred) in enumerate(zip(self.ims, self.pred)):\n            s += f'\\nimage {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} '  # string\n            if pred.shape[0]:\n                for c in pred[:, -1].unique():\n                    n = (pred[:, -1] == c).sum()  # detections per class\n                    s += f\"{n} {self.names[int(c)]}{'s' * (n > 1)}, \"  # add to string\n                s = s.rstrip(', ')\n                if show or save or render or crop:\n                    annotator = Annotator(im, example=str(self.names))\n                    for *box, conf, cls in reversed(pred):  # xyxy, confidence, class\n                        label = f'{self.names[int(cls)]} {conf:.2f}'\n                        if crop:\n                            file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None\n                            crops.append({\n                                'box': box,\n                                'conf': conf,\n                                'cls': cls,\n                                'label': label,\n                                'im': save_one_box(box, im, file=file, save=save)})\n                        else:  # all others\n                            annotator.box_label(box, label if labels else '', color=colors(cls))\n                    im = annotator.im\n            else:\n                s += '(no detections)'\n\n            im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im  # from np\n            if show:\n                im.show(self.files[i])  # show\n            if save:\n                f = self.files[i]\n                im.save(save_dir / f)  # save\n                if i == self.n - 1:\n                    LOGGER.info(f\"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}\")\n            if render:\n                self.ims[i] = np.asarray(im)\n        if pprint:\n            s = s.lstrip('\\n')\n            return f'{s}\\nSpeed: %.1fms preprocess, %.1fms inference, %.1fms NMS per image at shape {self.s}' % self.t\n        if crop:\n            if save:\n                LOGGER.info(f'Saved results to {save_dir}\\n')\n            return crops\n\n    def show(self, labels=True):\n        \"\"\"Displays YOLO results with detected bounding boxes.\"\"\"\n        self._run(show=True, labels=labels)  # show results\n\n    def save(self, labels=True, save_dir='runs/detect/exp', exist_ok=False):\n        \"\"\"Save detection results with optional labels to specified directory.\"\"\"\n        save_dir = increment_path(save_dir, exist_ok, mkdir=True)  # increment save_dir\n        self._run(save=True, labels=labels, save_dir=save_dir)  # save results\n\n    def crop(self, save=True, save_dir='runs/detect/exp', exist_ok=False):\n        \"\"\"Crops images into detections and saves them if 'save' is True.\"\"\"\n        save_dir = increment_path(save_dir, exist_ok, mkdir=True) if save else None\n        return self._run(crop=True, save=save, save_dir=save_dir)  # crop results\n\n    def render(self, labels=True):\n        \"\"\"Renders detected objects and returns images.\"\"\"\n        self._run(render=True, labels=labels)  # render results\n        return self.ims\n\n    def pandas(self):\n        \"\"\"Return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0]).\"\"\"\n        import pandas\n        new = copy(self)  # return copy\n        ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name'  # xyxy columns\n        cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name'  # xywh columns\n        for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):\n            a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)]  # update\n            setattr(new, k, [pandas.DataFrame(x, columns=c) for x in a])\n        return new\n\n    def tolist(self):\n        \"\"\"Return a list of Detections objects, i.e. 'for result in results.tolist():'.\"\"\"\n        r = range(self.n)  # iterable\n        x = [Detections([self.ims[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]\n        # for d in x:\n        #    for k in ['ims', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:\n        #        setattr(d, k, getattr(d, k)[0])  # pop out of list\n        return x\n\n    def print(self):\n        \"\"\"Print the results of the `self._run()` function.\"\"\"\n        LOGGER.info(self.__str__())\n\n    def __len__(self):  # override len(results)\n        return self.n\n\n    def __str__(self):  # override print(results)\n        return self._run(pprint=True)  # print results\n\n    def __repr__(self):\n        \"\"\"Returns a printable representation of the object.\"\"\"\n        return f'YOLOv8 {self.__class__} instance\\n' + self.__str__()\n"
  },
  {
    "path": "ultralytics/nn/modules/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nUltralytics modules. Visualize with:\n\nfrom ultralytics.nn.modules import *\nimport torch\nimport os\n\nx = torch.ones(1, 128, 40, 40)\nm = Conv(128, 128)\nf = f'{m._get_name()}.onnx'\ntorch.onnx.export(m, x, f)\nos.system(f'onnxsim {f} {f} && open {f}')\n\"\"\"\n\nfrom .block import (C1, C2, C3, C3TR, DFL, SPP, SPPF, Bottleneck, BottleneckCSP, C2f, C3Ghost, C3x, GhostBottleneck,\n                    HGBlock, HGStem, Proto, RepC3)\nfrom .conv import (CBAM, ChannelAttention, Concat, Conv, Conv2, ConvTranspose, DWConv, DWConvTranspose2d, Focus,\n                   GhostConv, LightConv, RepConv, SpatialAttention)\nfrom .head import Classify, Detect, Pose, RTDETRDecoder, Segment\nfrom .transformer import (AIFI, MLP, DeformableTransformerDecoder, DeformableTransformerDecoderLayer, LayerNorm2d,\n                          MLPBlock, MSDeformAttn, TransformerBlock, TransformerEncoderLayer, TransformerLayer)\n\n__all__ = ('Conv', 'Conv2', 'LightConv', 'RepConv', 'DWConv', 'DWConvTranspose2d', 'ConvTranspose', 'Focus',\n           'GhostConv', 'ChannelAttention', 'SpatialAttention', 'CBAM', 'Concat', 'TransformerLayer',\n           'TransformerBlock', 'MLPBlock', 'LayerNorm2d', 'DFL', 'HGBlock', 'HGStem', 'SPP', 'SPPF', 'C1', 'C2', 'C3',\n           'C2f', 'C3x', 'C3TR', 'C3Ghost', 'GhostBottleneck', 'Bottleneck', 'BottleneckCSP', 'Proto', 'Detect',\n           'Segment', 'Pose', 'Classify', 'TransformerEncoderLayer', 'RepC3', 'RTDETRDecoder', 'AIFI',\n           'DeformableTransformerDecoder', 'DeformableTransformerDecoderLayer', 'MSDeformAttn', 'MLP')\n"
  },
  {
    "path": "ultralytics/nn/modules/block.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nBlock modules\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .conv import Conv, DWConv, GhostConv, LightConv, RepConv\nfrom .transformer import TransformerBlock\n\n__all__ = ('DFL', 'HGBlock', 'HGStem', 'SPP', 'SPPF', 'C1', 'C2', 'C3', 'C2f', 'C3x', 'C3TR', 'C3Ghost',\n           'GhostBottleneck', 'Bottleneck', 'BottleneckCSP', 'Proto', 'RepC3')\n\n\nclass DFL(nn.Module):\n    \"\"\"\n    Integral module of Distribution Focal Loss (DFL).\n    Proposed in Generalized Focal Loss https://ieeexplore.ieee.org/document/9792391\n    \"\"\"\n\n    def __init__(self, c1=16):\n        \"\"\"Initialize a convolutional layer with a given number of input channels.\"\"\"\n        super().__init__()\n        self.conv = nn.Conv2d(c1, 1, 1, bias=False).requires_grad_(False)\n        x = torch.arange(c1, dtype=torch.float)\n        self.conv.weight.data[:] = nn.Parameter(x.view(1, c1, 1, 1))\n        self.c1 = c1\n\n    def forward(self, x):\n        \"\"\"Applies a transformer layer on input tensor 'x' and returns a tensor.\"\"\"\n        b, c, a = x.shape  # batch, channels, anchors\n        return self.conv(x.view(b, 4, self.c1, a).transpose(2, 1).softmax(1)).view(b, 4, a)\n        # return self.conv(x.view(b, self.c1, 4, a).softmax(1)).view(b, 4, a)\n\n\nclass Proto(nn.Module):\n    \"\"\"YOLOv8 mask Proto module for segmentation models.\"\"\"\n\n    def __init__(self, c1, c_=256, c2=32):  # ch_in, number of protos, number of masks\n        super().__init__()\n        self.cv1 = Conv(c1, c_, k=3)\n        self.upsample = nn.ConvTranspose2d(c_, c_, 2, 2, 0, bias=True)  # nn.Upsample(scale_factor=2, mode='nearest')\n        self.cv2 = Conv(c_, c_, k=3)\n        self.cv3 = Conv(c_, c2)\n\n    def forward(self, x):\n        \"\"\"Performs a forward pass through layers using an upsampled input image.\"\"\"\n        return self.cv3(self.cv2(self.upsample(self.cv1(x))))\n\n\nclass HGStem(nn.Module):\n    \"\"\"StemBlock of PPHGNetV2 with 5 convolutions and one maxpool2d.\n    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py\n    \"\"\"\n\n    def __init__(self, c1, cm, c2):\n        super().__init__()\n        self.stem1 = Conv(c1, cm, 3, 2, act=nn.ReLU())\n        self.stem2a = Conv(cm, cm // 2, 2, 1, 0, act=nn.ReLU())\n        self.stem2b = Conv(cm // 2, cm, 2, 1, 0, act=nn.ReLU())\n        self.stem3 = Conv(cm * 2, cm, 3, 2, act=nn.ReLU())\n        self.stem4 = Conv(cm, c2, 1, 1, act=nn.ReLU())\n        self.pool = nn.MaxPool2d(kernel_size=2, stride=1, padding=0, ceil_mode=True)\n\n    def forward(self, x):\n        \"\"\"Forward pass of a PPHGNetV2 backbone layer.\"\"\"\n        x = self.stem1(x)\n        x = F.pad(x, [0, 1, 0, 1])\n        x2 = self.stem2a(x)\n        x2 = F.pad(x2, [0, 1, 0, 1])\n        x2 = self.stem2b(x2)\n        x1 = self.pool(x)\n        x = torch.cat([x1, x2], dim=1)\n        x = self.stem3(x)\n        x = self.stem4(x)\n        return x\n\n\nclass HGBlock(nn.Module):\n    \"\"\"HG_Block of PPHGNetV2 with 2 convolutions and LightConv.\n    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py\n    \"\"\"\n\n    def __init__(self, c1, cm, c2, k=3, n=6, lightconv=False, shortcut=False, act=nn.ReLU()):\n        super().__init__()\n        block = LightConv if lightconv else Conv\n        self.m = nn.ModuleList(block(c1 if i == 0 else cm, cm, k=k, act=act) for i in range(n))\n        self.sc = Conv(c1 + n * cm, c2 // 2, 1, 1, act=act)  # squeeze conv\n        self.ec = Conv(c2 // 2, c2, 1, 1, act=act)  # excitation conv\n        self.add = shortcut and c1 == c2\n\n    def forward(self, x):\n        \"\"\"Forward pass of a PPHGNetV2 backbone layer.\"\"\"\n        y = [x]\n        y.extend(m(y[-1]) for m in self.m)\n        y = self.ec(self.sc(torch.cat(y, 1)))\n        return y + x if self.add else y\n\n\nclass SPP(nn.Module):\n    \"\"\"Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729.\"\"\"\n\n    def __init__(self, c1, c2, k=(5, 9, 13)):\n        \"\"\"Initialize the SPP layer with input/output channels and pooling kernel sizes.\"\"\"\n        super().__init__()\n        c_ = c1 // 2  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)\n        self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])\n\n    def forward(self, x):\n        \"\"\"Forward pass of the SPP layer, performing spatial pyramid pooling.\"\"\"\n        x = self.cv1(x)\n        return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))\n\n\nclass SPPF(nn.Module):\n    \"\"\"Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher.\"\"\"\n\n    def __init__(self, c1, c2, k=5):  # equivalent to SPP(k=(5, 9, 13))\n        super().__init__()\n        c_ = c1 // 2  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c_ * 4, c2, 1, 1)\n        self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)\n\n    def forward(self, x):\n        \"\"\"Forward pass through Ghost Convolution block.\"\"\"\n        x = self.cv1(x)\n        y1 = self.m(x)\n        y2 = self.m(y1)\n        return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))\n\n\nclass C1(nn.Module):\n    \"\"\"CSP Bottleneck with 1 convolution.\"\"\"\n\n    def __init__(self, c1, c2, n=1):  # ch_in, ch_out, number\n        super().__init__()\n        self.cv1 = Conv(c1, c2, 1, 1)\n        self.m = nn.Sequential(*(Conv(c2, c2, 3) for _ in range(n)))\n\n    def forward(self, x):\n        \"\"\"Applies cross-convolutions to input in the C3 module.\"\"\"\n        y = self.cv1(x)\n        return self.m(y) + y\n\n\nclass C2(nn.Module):\n    \"\"\"CSP Bottleneck with 2 convolutions.\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        self.c = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, 2 * self.c, 1, 1)\n        self.cv2 = Conv(2 * self.c, c2, 1)  # optional act=FReLU(c2)\n        # self.attention = ChannelAttention(2 * self.c)  # or SpatialAttention()\n        self.m = nn.Sequential(*(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n)))\n\n    def forward(self, x):\n        \"\"\"Forward pass through the CSP bottleneck with 2 convolutions.\"\"\"\n        a, b = self.cv1(x).chunk(2, 1)\n        return self.cv2(torch.cat((self.m(a), b), 1))\n\n\nclass C2f(nn.Module):\n    \"\"\"CSP Bottleneck with 2 convolutions.\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        self.c = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, 2 * self.c, 1, 1)\n        self.cv2 = Conv((2 + n) * self.c, c2, 1)  # optional act=FReLU(c2)\n        self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))\n\n    def forward(self, x):\n        \"\"\"Forward pass through C2f layer.\"\"\"\n        y = list(self.cv1(x).chunk(2, 1))\n        y.extend(m(y[-1]) for m in self.m)\n        return self.cv2(torch.cat(y, 1))\n\n    def forward_split(self, x):\n        \"\"\"Forward pass using split() instead of chunk().\"\"\"\n        y = list(self.cv1(x).split((self.c, self.c), 1))\n        y.extend(m(y[-1]) for m in self.m)\n        return self.cv2(torch.cat(y, 1))\n\n\nclass C3(nn.Module):\n    \"\"\"CSP Bottleneck with 3 convolutions.\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c1, c_, 1, 1)\n        self.cv3 = Conv(2 * c_, c2, 1)  # optional act=FReLU(c2)\n        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))\n\n    def forward(self, x):\n        \"\"\"Forward pass through the CSP bottleneck with 2 convolutions.\"\"\"\n        return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))\n\n\nclass C3x(C3):\n    \"\"\"C3 module with cross-convolutions.\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):\n        \"\"\"Initialize C3TR instance and set default parameters.\"\"\"\n        super().__init__(c1, c2, n, shortcut, g, e)\n        self.c_ = int(c2 * e)\n        self.m = nn.Sequential(*(Bottleneck(self.c_, self.c_, shortcut, g, k=((1, 3), (3, 1)), e=1) for _ in range(n)))\n\n\nclass RepC3(nn.Module):\n    \"\"\"Rep C3.\"\"\"\n\n    def __init__(self, c1, c2, n=3, e=1.0):\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c2, 1, 1)\n        self.cv2 = Conv(c1, c2, 1, 1)\n        self.m = nn.Sequential(*[RepConv(c_, c_) for _ in range(n)])\n        self.cv3 = Conv(c_, c2, 1, 1) if c_ != c2 else nn.Identity()\n\n    def forward(self, x):\n        \"\"\"Forward pass of RT-DETR neck layer.\"\"\"\n        return self.cv3(self.m(self.cv1(x)) + self.cv2(x))\n\n\nclass C3TR(C3):\n    \"\"\"C3 module with TransformerBlock().\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):\n        \"\"\"Initialize C3Ghost module with GhostBottleneck().\"\"\"\n        super().__init__(c1, c2, n, shortcut, g, e)\n        c_ = int(c2 * e)\n        self.m = TransformerBlock(c_, c_, 4, n)\n\n\nclass C3Ghost(C3):\n    \"\"\"C3 module with GhostBottleneck().\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):\n        \"\"\"Initialize 'SPP' module with various pooling sizes for spatial pyramid pooling.\"\"\"\n        super().__init__(c1, c2, n, shortcut, g, e)\n        c_ = int(c2 * e)  # hidden channels\n        self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))\n\n\nclass GhostBottleneck(nn.Module):\n    \"\"\"Ghost Bottleneck https://github.com/huawei-noah/ghostnet.\"\"\"\n\n    def __init__(self, c1, c2, k=3, s=1):  # ch_in, ch_out, kernel, stride\n        super().__init__()\n        c_ = c2 // 2\n        self.conv = nn.Sequential(\n            GhostConv(c1, c_, 1, 1),  # pw\n            DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(),  # dw\n            GhostConv(c_, c2, 1, 1, act=False))  # pw-linear\n        self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1,\n                                                                            act=False)) if s == 2 else nn.Identity()\n\n    def forward(self, x):\n        \"\"\"Applies skip connection and concatenation to input tensor.\"\"\"\n        return self.conv(x) + self.shortcut(x)\n\n\nclass Bottleneck(nn.Module):\n    \"\"\"Standard bottleneck.\"\"\"\n\n    def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5):  # ch_in, ch_out, shortcut, groups, kernels, expand\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, k[0], 1)\n        self.cv2 = Conv(c_, c2, k[1], 1, g=g)\n        self.add = shortcut and c1 == c2\n\n    def forward(self, x):\n        \"\"\"'forward()' applies the YOLOv5 FPN to input data.\"\"\"\n        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))\n\n\nclass BottleneckCSP(nn.Module):\n    \"\"\"CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks.\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)\n        self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)\n        self.cv4 = Conv(2 * c_, c2, 1, 1)\n        self.bn = nn.BatchNorm2d(2 * c_)  # applied to cat(cv2, cv3)\n        self.act = nn.SiLU()\n        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))\n\n    def forward(self, x):\n        \"\"\"Applies a CSP bottleneck with 3 convolutions.\"\"\"\n        y1 = self.cv3(self.m(self.cv1(x)))\n        y2 = self.cv2(x)\n        return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))\n"
  },
  {
    "path": "ultralytics/nn/modules/conv.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nConvolution modules\n\"\"\"\n\nimport math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\n__all__ = ('Conv', 'LightConv', 'DWConv', 'DWConvTranspose2d', 'ConvTranspose', 'Focus', 'GhostConv',\n           'ChannelAttention', 'SpatialAttention', 'CBAM', 'Concat', 'RepConv')\n\n\ndef autopad(k, p=None, d=1):  # kernel, padding, dilation\n    \"\"\"Pad to 'same' shape outputs.\"\"\"\n    if d > 1:\n        k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k]  # actual kernel-size\n    if p is None:\n        p = k // 2 if isinstance(k, int) else [x // 2 for x in k]  # auto-pad\n    return p\n\n\nclass Conv(nn.Module):\n    \"\"\"Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation).\"\"\"\n    default_act = nn.SiLU()  # default activation\n\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):\n        \"\"\"Initialize Conv layer with given arguments including activation.\"\"\"\n        super().__init__()\n        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)\n        self.bn = nn.BatchNorm2d(c2)\n        self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()\n\n    def forward(self, x):\n        \"\"\"Apply convolution, batch normalization and activation to input tensor.\"\"\"\n        return self.act(self.bn(self.conv(x)))\n\n    def forward_fuse(self, x):\n        \"\"\"Perform transposed convolution of 2D data.\"\"\"\n        return self.act(self.conv(x))\n\n\nclass Conv2(Conv):\n    \"\"\"Simplified RepConv module with Conv fusing.\"\"\"\n\n    def __init__(self, c1, c2, k=3, s=1, p=None, g=1, d=1, act=True):\n        \"\"\"Initialize Conv layer with given arguments including activation.\"\"\"\n        super().__init__(c1, c2, k, s, p, g=g, d=d, act=act)\n        self.cv2 = nn.Conv2d(c1, c2, 1, s, autopad(1, p, d), groups=g, dilation=d, bias=False)  # add 1x1 conv\n\n    def forward(self, x):\n        \"\"\"Apply convolution, batch normalization and activation to input tensor.\"\"\"\n        return self.act(self.bn(self.conv(x) + self.cv2(x)))\n\n    def fuse_convs(self):\n        \"\"\"Fuse parallel convolutions.\"\"\"\n        w = torch.zeros_like(self.conv.weight.data)\n        i = [x // 2 for x in w.shape[2:]]\n        w[:, :, i[0]:i[0] + 1, i[1]:i[1] + 1] = self.cv2.weight.data.clone()\n        self.conv.weight.data += w\n        self.__delattr__('cv2')\n\n\nclass LightConv(nn.Module):\n    \"\"\"Light convolution with args(ch_in, ch_out, kernel).\n    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py\n    \"\"\"\n\n    def __init__(self, c1, c2, k=1, act=nn.ReLU()):\n        \"\"\"Initialize Conv layer with given arguments including activation.\"\"\"\n        super().__init__()\n        self.conv1 = Conv(c1, c2, 1, act=False)\n        self.conv2 = DWConv(c2, c2, k, act=act)\n\n    def forward(self, x):\n        \"\"\"Apply 2 convolutions to input tensor.\"\"\"\n        return self.conv2(self.conv1(x))\n\n\nclass DWConv(Conv):\n    \"\"\"Depth-wise convolution.\"\"\"\n\n    def __init__(self, c1, c2, k=1, s=1, d=1, act=True):  # ch_in, ch_out, kernel, stride, dilation, activation\n        super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)\n\n\nclass DWConvTranspose2d(nn.ConvTranspose2d):\n    \"\"\"Depth-wise transpose convolution.\"\"\"\n\n    def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0):  # ch_in, ch_out, kernel, stride, padding, padding_out\n        super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))\n\n\nclass ConvTranspose(nn.Module):\n    \"\"\"Convolution transpose 2d layer.\"\"\"\n    default_act = nn.SiLU()  # default activation\n\n    def __init__(self, c1, c2, k=2, s=2, p=0, bn=True, act=True):\n        \"\"\"Initialize ConvTranspose2d layer with batch normalization and activation function.\"\"\"\n        super().__init__()\n        self.conv_transpose = nn.ConvTranspose2d(c1, c2, k, s, p, bias=not bn)\n        self.bn = nn.BatchNorm2d(c2) if bn else nn.Identity()\n        self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()\n\n    def forward(self, x):\n        \"\"\"Applies transposed convolutions, batch normalization and activation to input.\"\"\"\n        return self.act(self.bn(self.conv_transpose(x)))\n\n    def forward_fuse(self, x):\n        \"\"\"Applies activation and convolution transpose operation to input.\"\"\"\n        return self.act(self.conv_transpose(x))\n\n\nclass Focus(nn.Module):\n    \"\"\"Focus wh information into c-space.\"\"\"\n\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups\n        super().__init__()\n        self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act)\n        # self.contract = Contract(gain=2)\n\n    def forward(self, x):  # x(b,c,w,h) -> y(b,4c,w/2,h/2)\n        return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))\n        # return self.conv(self.contract(x))\n\n\nclass GhostConv(nn.Module):\n    \"\"\"Ghost Convolution https://github.com/huawei-noah/ghostnet.\"\"\"\n\n    def __init__(self, c1, c2, k=1, s=1, g=1, act=True):  # ch_in, ch_out, kernel, stride, groups\n        super().__init__()\n        c_ = c2 // 2  # hidden channels\n        self.cv1 = Conv(c1, c_, k, s, None, g, act=act)\n        self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)\n\n    def forward(self, x):\n        \"\"\"Forward propagation through a Ghost Bottleneck layer with skip connection.\"\"\"\n        y = self.cv1(x)\n        return torch.cat((y, self.cv2(y)), 1)\n\n\nclass RepConv(nn.Module):\n    \"\"\"RepConv is a basic rep-style block, including training and deploy status\n    This code is based on https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py\n    \"\"\"\n    default_act = nn.SiLU()  # default activation\n\n    def __init__(self, c1, c2, k=3, s=1, p=1, g=1, d=1, act=True, bn=False, deploy=False):\n        super().__init__()\n        assert k == 3 and p == 1\n        self.g = g\n        self.c1 = c1\n        self.c2 = c2\n        self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()\n\n        self.bn = nn.BatchNorm2d(num_features=c1) if bn and c2 == c1 and s == 1 else None\n        self.conv1 = Conv(c1, c2, k, s, p=p, g=g, act=False)\n        self.conv2 = Conv(c1, c2, 1, s, p=(p - k // 2), g=g, act=False)\n\n    def forward_fuse(self, x):\n        \"\"\"Forward process\"\"\"\n        return self.act(self.conv(x))\n\n    def forward(self, x):\n        \"\"\"Forward process\"\"\"\n        id_out = 0 if self.bn is None else self.bn(x)\n        return self.act(self.conv1(x) + self.conv2(x) + id_out)\n\n    def get_equivalent_kernel_bias(self):\n        kernel3x3, bias3x3 = self._fuse_bn_tensor(self.conv1)\n        kernel1x1, bias1x1 = self._fuse_bn_tensor(self.conv2)\n        kernelid, biasid = self._fuse_bn_tensor(self.bn)\n        return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid\n\n    def _avg_to_3x3_tensor(self, avgp):\n        channels = self.c1\n        groups = self.g\n        kernel_size = avgp.kernel_size\n        input_dim = channels // groups\n        k = torch.zeros((channels, input_dim, kernel_size, kernel_size))\n        k[np.arange(channels), np.tile(np.arange(input_dim), groups), :, :] = 1.0 / kernel_size ** 2\n        return k\n\n    def _pad_1x1_to_3x3_tensor(self, kernel1x1):\n        if kernel1x1 is None:\n            return 0\n        else:\n            return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])\n\n    def _fuse_bn_tensor(self, branch):\n        if branch is None:\n            return 0, 0\n        if isinstance(branch, Conv):\n            kernel = branch.conv.weight\n            running_mean = branch.bn.running_mean\n            running_var = branch.bn.running_var\n            gamma = branch.bn.weight\n            beta = branch.bn.bias\n            eps = branch.bn.eps\n        elif isinstance(branch, nn.BatchNorm2d):\n            if not hasattr(self, 'id_tensor'):\n                input_dim = self.c1 // self.g\n                kernel_value = np.zeros((self.c1, input_dim, 3, 3), dtype=np.float32)\n                for i in range(self.c1):\n                    kernel_value[i, i % input_dim, 1, 1] = 1\n                self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)\n            kernel = self.id_tensor\n            running_mean = branch.running_mean\n            running_var = branch.running_var\n            gamma = branch.weight\n            beta = branch.bias\n            eps = branch.eps\n        std = (running_var + eps).sqrt()\n        t = (gamma / std).reshape(-1, 1, 1, 1)\n        return kernel * t, beta - running_mean * gamma / std\n\n    def fuse_convs(self):\n        if hasattr(self, 'conv'):\n            return\n        kernel, bias = self.get_equivalent_kernel_bias()\n        self.conv = nn.Conv2d(in_channels=self.conv1.conv.in_channels,\n                              out_channels=self.conv1.conv.out_channels,\n                              kernel_size=self.conv1.conv.kernel_size,\n                              stride=self.conv1.conv.stride,\n                              padding=self.conv1.conv.padding,\n                              dilation=self.conv1.conv.dilation,\n                              groups=self.conv1.conv.groups,\n                              bias=True).requires_grad_(False)\n        self.conv.weight.data = kernel\n        self.conv.bias.data = bias\n        for para in self.parameters():\n            para.detach_()\n        self.__delattr__('conv1')\n        self.__delattr__('conv2')\n        if hasattr(self, 'nm'):\n            self.__delattr__('nm')\n        if hasattr(self, 'bn'):\n            self.__delattr__('bn')\n        if hasattr(self, 'id_tensor'):\n            self.__delattr__('id_tensor')\n\n\nclass ChannelAttention(nn.Module):\n    \"\"\"Channel-attention module https://github.com/open-mmlab/mmdetection/tree/v3.0.0rc1/configs/rtmdet.\"\"\"\n\n    def __init__(self, channels: int) -> None:\n        super().__init__()\n        self.pool = nn.AdaptiveAvgPool2d(1)\n        self.fc = nn.Conv2d(channels, channels, 1, 1, 0, bias=True)\n        self.act = nn.Sigmoid()\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        return x * self.act(self.fc(self.pool(x)))\n\n\nclass SpatialAttention(nn.Module):\n    \"\"\"Spatial-attention module.\"\"\"\n\n    def __init__(self, kernel_size=7):\n        \"\"\"Initialize Spatial-attention module with kernel size argument.\"\"\"\n        super().__init__()\n        assert kernel_size in (3, 7), 'kernel size must be 3 or 7'\n        padding = 3 if kernel_size == 7 else 1\n        self.cv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)\n        self.act = nn.Sigmoid()\n\n    def forward(self, x):\n        \"\"\"Apply channel and spatial attention on input for feature recalibration.\"\"\"\n        return x * self.act(self.cv1(torch.cat([torch.mean(x, 1, keepdim=True), torch.max(x, 1, keepdim=True)[0]], 1)))\n\n\nclass CBAM(nn.Module):\n    \"\"\"Convolutional Block Attention Module.\"\"\"\n\n    def __init__(self, c1, kernel_size=7):  # ch_in, kernels\n        super().__init__()\n        self.channel_attention = ChannelAttention(c1)\n        self.spatial_attention = SpatialAttention(kernel_size)\n\n    def forward(self, x):\n        \"\"\"Applies the forward pass through C1 module.\"\"\"\n        return self.spatial_attention(self.channel_attention(x))\n\n\nclass Concat(nn.Module):\n    \"\"\"Concatenate a list of tensors along dimension.\"\"\"\n\n    def __init__(self, dimension=1):\n        \"\"\"Concatenates a list of tensors along a specified dimension.\"\"\"\n        super().__init__()\n        self.d = dimension\n\n    def forward(self, x):\n        \"\"\"Forward pass for the YOLOv8 mask Proto module.\"\"\"\n        return torch.cat(x, self.d)\n"
  },
  {
    "path": "ultralytics/nn/modules/head.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nModel head modules\n\"\"\"\n\nimport math\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn.init import constant_, xavier_uniform_\n\nfrom ultralytics.yolo.utils.tal import dist2bbox, make_anchors\n\nfrom .block import DFL, Proto\nfrom .conv import Conv\nfrom .transformer import MLP, DeformableTransformerDecoder, DeformableTransformerDecoderLayer\nfrom .utils import bias_init_with_prob, linear_init_\n\n__all__ = 'Detect', 'Segment', 'Pose', 'Classify', 'RTDETRDecoder'\n\n\nclass Detect(nn.Module):\n    \"\"\"YOLOv8 Detect head for detection models.\"\"\"\n    dynamic = False  # force grid reconstruction\n    export = False  # export mode\n    shape = None\n    anchors = torch.empty(0)  # init\n    strides = torch.empty(0)  # init\n\n    def __init__(self, nc=80, ch=()):  # detection layer\n        super().__init__()\n        self.nc = nc  # number of classes\n        self.nl = len(ch)  # number of detection layers\n        self.reg_max = 16  # DFL channels (ch[0] // 16 to scale 4/8/12/16/20 for n/s/m/l/x)\n        self.no = nc + self.reg_max * 4  # number of outputs per anchor\n        self.stride = torch.zeros(self.nl)  # strides computed during build\n        c2, c3 = max((16, ch[0] // 4, self.reg_max * 4)), max(ch[0], self.nc)  # channels\n        self.cv2 = nn.ModuleList(\n            nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3), nn.Conv2d(c2, 4 * self.reg_max, 1)) for x in ch)\n        self.cv3 = nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch)\n        self.dfl = DFL(self.reg_max) if self.reg_max > 1 else nn.Identity()\n\n    def forward(self, x):\n        \"\"\"Concatenates and returns predicted bounding boxes and class probabilities.\"\"\"\n        shape = x[0].shape  # BCHW\n        for i in range(self.nl):\n            x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)\n        if self.training:\n            return x\n        elif self.dynamic or self.shape != shape:\n            self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors(x, self.stride, 0.5))\n            self.shape = shape\n\n        x_cat = torch.cat([xi.view(shape[0], self.no, -1) for xi in x], 2)\n        if self.export and self.format in ('saved_model', 'pb', 'tflite', 'edgetpu', 'tfjs'):  # avoid TF FlexSplitV ops\n            box = x_cat[:, :self.reg_max * 4]\n            cls = x_cat[:, self.reg_max * 4:]\n        else:\n            box, cls = x_cat.split((self.reg_max * 4, self.nc), 1)\n        dbox = dist2bbox(self.dfl(box), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides\n        y = torch.cat((dbox, cls.sigmoid()), 1)\n        return y if self.export else (y, x)\n\n    def bias_init(self):\n        \"\"\"Initialize Detect() biases, WARNING: requires stride availability.\"\"\"\n        m = self  # self.model[-1]  # Detect() module\n        # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1\n        # ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum())  # nominal class frequency\n        for a, b, s in zip(m.cv2, m.cv3, m.stride):  # from\n            a[-1].bias.data[:] = 1.0  # box\n            b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2)  # cls (.01 objects, 80 classes, 640 img)\n\n\nclass Segment(Detect):\n    \"\"\"YOLOv8 Segment head for segmentation models.\"\"\"\n\n    def __init__(self, nc=80, nm=32, npr=256, ch=()):\n        \"\"\"Initialize the YOLO model attributes such as the number of masks, prototypes, and the convolution layers.\"\"\"\n        super().__init__(nc, ch)\n        self.nm = nm  # number of masks\n        self.npr = npr  # number of protos\n        self.proto = Proto(ch[0], self.npr, self.nm)  # protos\n        self.detect = Detect.forward\n\n        c4 = max(ch[0] // 4, self.nm)\n        self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nm, 1)) for x in ch)\n\n    def forward(self, x):\n        \"\"\"Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients.\"\"\"\n        p = self.proto(x[0])  # mask protos\n        bs = p.shape[0]  # batch size\n\n        mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2)  # mask coefficients\n        x = self.detect(self, x)\n        if self.training:\n            return x, mc, p\n        return (torch.cat([x, mc], 1), p) if self.export else (torch.cat([x[0], mc], 1), (x[1], mc, p))\n\n\nclass Pose(Detect):\n    \"\"\"YOLOv8 Pose head for keypoints models.\"\"\"\n\n    def __init__(self, nc=80, kpt_shape=(17, 3), ch=()):\n        \"\"\"Initialize YOLO network with default parameters and Convolutional Layers.\"\"\"\n        super().__init__(nc, ch)\n        self.kpt_shape = kpt_shape  # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)\n        self.nk = kpt_shape[0] * kpt_shape[1]  # number of keypoints total\n        self.detect = Detect.forward\n\n        c4 = max(ch[0] // 4, self.nk)\n        self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nk, 1)) for x in ch)\n\n    def forward(self, x):\n        \"\"\"Perform forward pass through YOLO model and return predictions.\"\"\"\n        bs = x[0].shape[0]  # batch size\n        kpt = torch.cat([self.cv4[i](x[i]).view(bs, self.nk, -1) for i in range(self.nl)], -1)  # (bs, 17*3, h*w)\n        x = self.detect(self, x)\n        if self.training:\n            return x, kpt\n        pred_kpt = self.kpts_decode(bs, kpt)\n        return torch.cat([x, pred_kpt], 1) if self.export else (torch.cat([x[0], pred_kpt], 1), (x[1], kpt))\n\n    def kpts_decode(self, bs, kpts):\n        \"\"\"Decodes keypoints.\"\"\"\n        ndim = self.kpt_shape[1]\n        if self.export:  # required for TFLite export to avoid 'PLACEHOLDER_FOR_GREATER_OP_CODES' bug\n            y = kpts.view(bs, *self.kpt_shape, -1)\n            a = (y[:, :, :2] * 2.0 + (self.anchors - 0.5)) * self.strides\n            if ndim == 3:\n                a = torch.cat((a, y[:, :, 2:3].sigmoid()), 2)\n            return a.view(bs, self.nk, -1)\n        else:\n            y = kpts.clone()\n            if ndim == 3:\n                y[:, 2::3].sigmoid_()  # inplace sigmoid\n            y[:, 0::ndim] = (y[:, 0::ndim] * 2.0 + (self.anchors[0] - 0.5)) * self.strides\n            y[:, 1::ndim] = (y[:, 1::ndim] * 2.0 + (self.anchors[1] - 0.5)) * self.strides\n            return y\n\n\nclass Classify(nn.Module):\n    \"\"\"YOLOv8 classification head, i.e. x(b,c1,20,20) to x(b,c2).\"\"\"\n\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1):  # ch_in, ch_out, kernel, stride, padding, groups\n        super().__init__()\n        c_ = 1280  # efficientnet_b0 size\n        self.conv = Conv(c1, c_, k, s, p, g)\n        self.pool = nn.AdaptiveAvgPool2d(1)  # to x(b,c_,1,1)\n        self.drop = nn.Dropout(p=0.0, inplace=True)\n        self.linear = nn.Linear(c_, c2)  # to x(b,c2)\n\n    def forward(self, x):\n        \"\"\"Performs a forward pass of the YOLO model on input image data.\"\"\"\n        if isinstance(x, list):\n            x = torch.cat(x, 1)\n        x = self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))\n        return x if self.training else x.softmax(1)\n\n\nclass RTDETRDecoder(nn.Module):\n\n    def __init__(\n            self,\n            nc=80,\n            ch=(512, 1024, 2048),\n            hd=256,  # hidden dim\n            nq=300,  # num queries\n            ndp=4,  # num decoder points\n            nh=8,  # num head\n            ndl=6,  # num decoder layers\n            d_ffn=1024,  # dim of feedforward\n            dropout=0.,\n            act=nn.ReLU(),\n            eval_idx=-1,\n            # training args\n            nd=100,  # num denoising\n            label_noise_ratio=0.5,\n            box_noise_scale=1.0,\n            learnt_init_query=False):\n        super().__init__()\n        self.hidden_dim = hd\n        self.nhead = nh\n        self.nl = len(ch)  # num level\n        self.nc = nc\n        self.num_queries = nq\n        self.num_decoder_layers = ndl\n\n        # backbone feature projection\n        self.input_proj = nn.ModuleList(nn.Sequential(nn.Conv2d(x, hd, 1, bias=False), nn.BatchNorm2d(hd)) for x in ch)\n        # NOTE: simplified version but it's not consistent with .pt weights.\n        # self.input_proj = nn.ModuleList(Conv(x, hd, act=False) for x in ch)\n\n        # Transformer module\n        decoder_layer = DeformableTransformerDecoderLayer(hd, nh, d_ffn, dropout, act, self.nl, ndp)\n        self.decoder = DeformableTransformerDecoder(hd, decoder_layer, ndl, eval_idx)\n\n        # denoising part\n        self.denoising_class_embed = nn.Embedding(nc, hd)\n        self.num_denoising = nd\n        self.label_noise_ratio = label_noise_ratio\n        self.box_noise_scale = box_noise_scale\n\n        # decoder embedding\n        self.learnt_init_query = learnt_init_query\n        if learnt_init_query:\n            self.tgt_embed = nn.Embedding(nq, hd)\n        self.query_pos_head = MLP(4, 2 * hd, hd, num_layers=2)\n\n        # encoder head\n        self.enc_output = nn.Sequential(nn.Linear(hd, hd), nn.LayerNorm(hd))\n        self.enc_score_head = nn.Linear(hd, nc)\n        self.enc_bbox_head = MLP(hd, hd, 4, num_layers=3)\n\n        # decoder head\n        self.dec_score_head = nn.ModuleList([nn.Linear(hd, nc) for _ in range(ndl)])\n        self.dec_bbox_head = nn.ModuleList([MLP(hd, hd, 4, num_layers=3) for _ in range(ndl)])\n\n        self._reset_parameters()\n\n    def forward(self, x, batch=None):\n        from ultralytics.vit.utils.ops import get_cdn_group\n\n        # input projection and embedding\n        feats, shapes = self._get_encoder_input(x)\n\n        # prepare denoising training\n        dn_embed, dn_bbox, attn_mask, dn_meta = \\\n            get_cdn_group(batch,\n                          self.nc,\n                          self.num_queries,\n                          self.denoising_class_embed.weight,\n                          self.num_denoising,\n                          self.label_noise_ratio,\n                          self.box_noise_scale,\n                          self.training)\n\n        embed, refer_bbox, enc_bboxes, enc_scores = \\\n            self._get_decoder_input(feats, shapes, dn_embed, dn_bbox)\n\n        # decoder\n        dec_bboxes, dec_scores = self.decoder(embed,\n                                              refer_bbox,\n                                              feats,\n                                              shapes,\n                                              self.dec_bbox_head,\n                                              self.dec_score_head,\n                                              self.query_pos_head,\n                                              attn_mask=attn_mask)\n        if not self.training:\n            dec_scores = dec_scores.sigmoid_()\n        return dec_bboxes, dec_scores, enc_bboxes, enc_scores, dn_meta\n\n    def _generate_anchors(self, shapes, grid_size=0.05, dtype=torch.float32, device='cpu', eps=1e-2):\n        anchors = []\n        for i, (h, w) in enumerate(shapes):\n            grid_y, grid_x = torch.meshgrid(torch.arange(end=h, dtype=dtype, device=device),\n                                            torch.arange(end=w, dtype=dtype, device=device),\n                                            indexing='ij')\n            grid_xy = torch.stack([grid_x, grid_y], -1)  # (h, w, 2)\n\n            valid_WH = torch.tensor([h, w], dtype=dtype, device=device)\n            grid_xy = (grid_xy.unsqueeze(0) + 0.5) / valid_WH  # (1, h, w, 2)\n            wh = torch.ones_like(grid_xy, dtype=dtype, device=device) * grid_size * (2.0 ** i)\n            anchors.append(torch.cat([grid_xy, wh], -1).view(-1, h * w, 4))  # (1, h*w, 4)\n\n        anchors = torch.cat(anchors, 1)  # (1, h*w*nl, 4)\n        valid_mask = ((anchors > eps) * (anchors < 1 - eps)).all(-1, keepdim=True)  # 1, h*w*nl, 1\n        anchors = torch.log(anchors / (1 - anchors))\n        anchors = torch.where(valid_mask, anchors, torch.inf)\n        return anchors, valid_mask\n\n    def _get_encoder_input(self, x):\n        # get projection features\n        x = [self.input_proj[i](feat) for i, feat in enumerate(x)]\n        # get encoder inputs\n        feats = []\n        shapes = []\n        for feat in x:\n            h, w = feat.shape[2:]\n            # [b, c, h, w] -> [b, h*w, c]\n            feats.append(feat.flatten(2).permute(0, 2, 1))\n            # [nl, 2]\n            shapes.append([h, w])\n\n        # [b, h*w, c]\n        feats = torch.cat(feats, 1)\n        return feats, shapes\n\n    def _get_decoder_input(self, feats, shapes, dn_embed=None, dn_bbox=None):\n        bs = len(feats)\n        # prepare input for decoder\n        anchors, valid_mask = self._generate_anchors(shapes, dtype=feats.dtype, device=feats.device)\n        features = self.enc_output(torch.where(valid_mask, feats, 0))  # bs, h*w, 256\n\n        enc_outputs_scores = self.enc_score_head(features)  # (bs, h*w, nc)\n        # dynamic anchors + static content\n        enc_outputs_bboxes = self.enc_bbox_head(features) + anchors  # (bs, h*w, 4)\n\n        # query selection\n        # (bs, num_queries)\n        topk_ind = torch.topk(enc_outputs_scores.max(-1).values, self.num_queries, dim=1).indices.view(-1)\n        # (bs, num_queries)\n        batch_ind = torch.arange(end=bs, dtype=topk_ind.dtype).unsqueeze(-1).repeat(1, self.num_queries).view(-1)\n\n        # Unsigmoided\n        refer_bbox = enc_outputs_bboxes[batch_ind, topk_ind].view(bs, self.num_queries, -1)\n        # refer_bbox = torch.gather(enc_outputs_bboxes, 1, topk_ind.reshape(bs, self.num_queries).unsqueeze(-1).repeat(1, 1, 4))\n\n        enc_bboxes = refer_bbox.sigmoid()\n        if dn_bbox is not None:\n            refer_bbox = torch.cat([dn_bbox, refer_bbox], 1)\n        if self.training:\n            refer_bbox = refer_bbox.detach()\n        enc_scores = enc_outputs_scores[batch_ind, topk_ind].view(bs, self.num_queries, -1)\n\n        if self.learnt_init_query:\n            embeddings = self.tgt_embed.weight.unsqueeze(0).repeat(bs, 1, 1)\n        else:\n            embeddings = features[batch_ind, topk_ind].view(bs, self.num_queries, -1)\n            if self.training:\n                embeddings = embeddings.detach()\n        if dn_embed is not None:\n            embeddings = torch.cat([dn_embed, embeddings], 1)\n\n        return embeddings, refer_bbox, enc_bboxes, enc_scores\n\n    # TODO\n    def _reset_parameters(self):\n        # class and bbox head init\n        bias_cls = bias_init_with_prob(0.01) / 80 * self.nc\n        # NOTE: the weight initialization in `linear_init_` would cause NaN when training with custom datasets.\n        # linear_init_(self.enc_score_head)\n        constant_(self.enc_score_head.bias, bias_cls)\n        constant_(self.enc_bbox_head.layers[-1].weight, 0.)\n        constant_(self.enc_bbox_head.layers[-1].bias, 0.)\n        for cls_, reg_ in zip(self.dec_score_head, self.dec_bbox_head):\n            # linear_init_(cls_)\n            constant_(cls_.bias, bias_cls)\n            constant_(reg_.layers[-1].weight, 0.)\n            constant_(reg_.layers[-1].bias, 0.)\n\n        linear_init_(self.enc_output[0])\n        xavier_uniform_(self.enc_output[0].weight)\n        if self.learnt_init_query:\n            xavier_uniform_(self.tgt_embed.weight)\n        xavier_uniform_(self.query_pos_head.layers[0].weight)\n        xavier_uniform_(self.query_pos_head.layers[1].weight)\n        for layer in self.input_proj:\n            xavier_uniform_(layer[0].weight)\n"
  },
  {
    "path": "ultralytics/nn/modules/transformer.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nTransformer modules\n\"\"\"\n\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.init import constant_, xavier_uniform_\n\nfrom .conv import Conv\nfrom .utils import _get_clones, inverse_sigmoid, multi_scale_deformable_attn_pytorch\n\n__all__ = ('TransformerEncoderLayer', 'TransformerLayer', 'TransformerBlock', 'MLPBlock', 'LayerNorm2d', 'AIFI',\n           'DeformableTransformerDecoder', 'DeformableTransformerDecoderLayer', 'MSDeformAttn', 'MLP')\n\n\nclass TransformerEncoderLayer(nn.Module):\n    \"\"\"Transformer Encoder.\"\"\"\n\n    def __init__(self, c1, cm=2048, num_heads=8, dropout=0.0, act=nn.GELU(), normalize_before=False):\n        super().__init__()\n        self.ma = nn.MultiheadAttention(c1, num_heads, dropout=dropout, batch_first=True)\n        # Implementation of Feedforward model\n        self.fc1 = nn.Linear(c1, cm)\n        self.fc2 = nn.Linear(cm, c1)\n\n        self.norm1 = nn.LayerNorm(c1)\n        self.norm2 = nn.LayerNorm(c1)\n        self.dropout = nn.Dropout(dropout)\n        self.dropout1 = nn.Dropout(dropout)\n        self.dropout2 = nn.Dropout(dropout)\n\n        self.act = act\n        self.normalize_before = normalize_before\n\n    def with_pos_embed(self, tensor, pos=None):\n        \"\"\"Add position embeddings if given.\"\"\"\n        return tensor if pos is None else tensor + pos\n\n    def forward_post(self, src, src_mask=None, src_key_padding_mask=None, pos=None):\n        q = k = self.with_pos_embed(src, pos)\n        src2 = self.ma(q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0]\n        src = src + self.dropout1(src2)\n        src = self.norm1(src)\n        src2 = self.fc2(self.dropout(self.act(self.fc1(src))))\n        src = src + self.dropout2(src2)\n        src = self.norm2(src)\n        return src\n\n    def forward_pre(self, src, src_mask=None, src_key_padding_mask=None, pos=None):\n        src2 = self.norm1(src)\n        q = k = self.with_pos_embed(src2, pos)\n        src2 = self.ma(q, k, value=src2, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0]\n        src = src + self.dropout1(src2)\n        src2 = self.norm2(src)\n        src2 = self.fc2(self.dropout(self.act(self.fc1(src2))))\n        src = src + self.dropout2(src2)\n        return src\n\n    def forward(self, src, src_mask=None, src_key_padding_mask=None, pos=None):\n        \"\"\"Forward propagates the input through the encoder module.\"\"\"\n        if self.normalize_before:\n            return self.forward_pre(src, src_mask, src_key_padding_mask, pos)\n        return self.forward_post(src, src_mask, src_key_padding_mask, pos)\n\n\nclass AIFI(TransformerEncoderLayer):\n\n    def __init__(self, c1, cm=2048, num_heads=8, dropout=0, act=nn.GELU(), normalize_before=False):\n        super().__init__(c1, cm, num_heads, dropout, act, normalize_before)\n\n    def forward(self, x):\n        c, h, w = x.shape[1:]\n        pos_embed = self.build_2d_sincos_position_embedding(w, h, c)\n        # flatten [B, C, H, W] to [B, HxW, C]\n        x = super().forward(x.flatten(2).permute(0, 2, 1), pos=pos_embed.to(device=x.device, dtype=x.dtype))\n        return x.permute(0, 2, 1).view([-1, c, h, w]).contiguous()\n\n    @staticmethod\n    def build_2d_sincos_position_embedding(w, h, embed_dim=256, temperature=10000.):\n        grid_w = torch.arange(int(w), dtype=torch.float32)\n        grid_h = torch.arange(int(h), dtype=torch.float32)\n        grid_w, grid_h = torch.meshgrid(grid_w, grid_h, indexing='ij')\n        assert embed_dim % 4 == 0, \\\n            'Embed dimension must be divisible by 4 for 2D sin-cos position embedding'\n        pos_dim = embed_dim // 4\n        omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim\n        omega = 1. / (temperature ** omega)\n\n        out_w = grid_w.flatten()[..., None] @ omega[None]\n        out_h = grid_h.flatten()[..., None] @ omega[None]\n\n        return torch.concat([torch.sin(out_w), torch.cos(out_w),\n                             torch.sin(out_h), torch.cos(out_h)], axis=1)[None, :, :]\n\n\nclass TransformerLayer(nn.Module):\n    \"\"\"Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance).\"\"\"\n\n    def __init__(self, c, num_heads):\n        \"\"\"Initializes a self-attention mechanism using linear transformations and multi-head attention.\"\"\"\n        super().__init__()\n        self.q = nn.Linear(c, c, bias=False)\n        self.k = nn.Linear(c, c, bias=False)\n        self.v = nn.Linear(c, c, bias=False)\n        self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)\n        self.fc1 = nn.Linear(c, c, bias=False)\n        self.fc2 = nn.Linear(c, c, bias=False)\n\n    def forward(self, x):\n        \"\"\"Apply a transformer block to the input x and return the output.\"\"\"\n        x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x\n        x = self.fc2(self.fc1(x)) + x\n        return x\n\n\nclass TransformerBlock(nn.Module):\n    \"\"\"Vision Transformer https://arxiv.org/abs/2010.11929.\"\"\"\n\n    def __init__(self, c1, c2, num_heads, num_layers):\n        \"\"\"Initialize a Transformer module with position embedding and specified number of heads and layers.\"\"\"\n        super().__init__()\n        self.conv = None\n        if c1 != c2:\n            self.conv = Conv(c1, c2)\n        self.linear = nn.Linear(c2, c2)  # learnable position embedding\n        self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))\n        self.c2 = c2\n\n    def forward(self, x):\n        \"\"\"Forward propagates the input through the bottleneck module.\"\"\"\n        if self.conv is not None:\n            x = self.conv(x)\n        b, _, w, h = x.shape\n        p = x.flatten(2).permute(2, 0, 1)\n        return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)\n\n\nclass MLPBlock(nn.Module):\n\n    def __init__(self, embedding_dim, mlp_dim, act=nn.GELU):\n        super().__init__()\n        self.lin1 = nn.Linear(embedding_dim, mlp_dim)\n        self.lin2 = nn.Linear(mlp_dim, embedding_dim)\n        self.act = act()\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        return self.lin2(self.act(self.lin1(x)))\n\n\nclass MLP(nn.Module):\n    \"\"\" Very simple multi-layer perceptron (also called FFN)\"\"\"\n\n    def __init__(self, input_dim, hidden_dim, output_dim, num_layers):\n        super().__init__()\n        self.num_layers = num_layers\n        h = [hidden_dim] * (num_layers - 1)\n        self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))\n\n    def forward(self, x):\n        for i, layer in enumerate(self.layers):\n            x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)\n        return x\n\n\n# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa\n# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119  # noqa\nclass LayerNorm2d(nn.Module):\n\n    def __init__(self, num_channels, eps=1e-6):\n        super().__init__()\n        self.weight = nn.Parameter(torch.ones(num_channels))\n        self.bias = nn.Parameter(torch.zeros(num_channels))\n        self.eps = eps\n\n    def forward(self, x):\n        u = x.mean(1, keepdim=True)\n        s = (x - u).pow(2).mean(1, keepdim=True)\n        x = (x - u) / torch.sqrt(s + self.eps)\n        x = self.weight[:, None, None] * x + self.bias[:, None, None]\n        return x\n\n\nclass MSDeformAttn(nn.Module):\n    \"\"\"\n    Original Multi-Scale Deformable Attention Module.\n    https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/modules/ms_deform_attn.py\n    \"\"\"\n\n    def __init__(self, d_model=256, n_levels=4, n_heads=8, n_points=4):\n        super().__init__()\n        if d_model % n_heads != 0:\n            raise ValueError(f'd_model must be divisible by n_heads, but got {d_model} and {n_heads}')\n        _d_per_head = d_model // n_heads\n        # you'd better set _d_per_head to a power of 2 which is more efficient in our CUDA implementation\n        assert _d_per_head * n_heads == d_model, '`d_model` must be divisible by `n_heads`'\n\n        self.im2col_step = 64\n\n        self.d_model = d_model\n        self.n_levels = n_levels\n        self.n_heads = n_heads\n        self.n_points = n_points\n\n        self.sampling_offsets = nn.Linear(d_model, n_heads * n_levels * n_points * 2)\n        self.attention_weights = nn.Linear(d_model, n_heads * n_levels * n_points)\n        self.value_proj = nn.Linear(d_model, d_model)\n        self.output_proj = nn.Linear(d_model, d_model)\n\n        self._reset_parameters()\n\n    def _reset_parameters(self):\n        constant_(self.sampling_offsets.weight.data, 0.)\n        thetas = torch.arange(self.n_heads, dtype=torch.float32) * (2.0 * math.pi / self.n_heads)\n        grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)\n        grid_init = (grid_init / grid_init.abs().max(-1, keepdim=True)[0]).view(self.n_heads, 1, 1, 2).repeat(\n            1, self.n_levels, self.n_points, 1)\n        for i in range(self.n_points):\n            grid_init[:, :, i, :] *= i + 1\n        with torch.no_grad():\n            self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1))\n        constant_(self.attention_weights.weight.data, 0.)\n        constant_(self.attention_weights.bias.data, 0.)\n        xavier_uniform_(self.value_proj.weight.data)\n        constant_(self.value_proj.bias.data, 0.)\n        xavier_uniform_(self.output_proj.weight.data)\n        constant_(self.output_proj.bias.data, 0.)\n\n    def forward(self, query, refer_bbox, value, value_shapes, value_mask=None):\n        \"\"\"\n        https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py\n        Args:\n            query (torch.Tensor): [bs, query_length, C]\n            refer_bbox (torch.Tensor): [bs, query_length, n_levels, 2], range in [0, 1], top-left (0,0),\n                bottom-right (1, 1), including padding area\n            value (torch.Tensor): [bs, value_length, C]\n            value_shapes (List): [n_levels, 2], [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]\n            value_mask (Tensor): [bs, value_length], True for non-padding elements, False for padding elements\n\n        Returns:\n            output (Tensor): [bs, Length_{query}, C]\n        \"\"\"\n        bs, len_q = query.shape[:2]\n        len_v = value.shape[1]\n        assert sum(s[0] * s[1] for s in value_shapes) == len_v\n\n        value = self.value_proj(value)\n        if value_mask is not None:\n            value = value.masked_fill(value_mask[..., None], float(0))\n        value = value.view(bs, len_v, self.n_heads, self.d_model // self.n_heads)\n        sampling_offsets = self.sampling_offsets(query).view(bs, len_q, self.n_heads, self.n_levels, self.n_points, 2)\n        attention_weights = self.attention_weights(query).view(bs, len_q, self.n_heads, self.n_levels * self.n_points)\n        attention_weights = F.softmax(attention_weights, -1).view(bs, len_q, self.n_heads, self.n_levels, self.n_points)\n        # N, Len_q, n_heads, n_levels, n_points, 2\n        num_points = refer_bbox.shape[-1]\n        if num_points == 2:\n            offset_normalizer = torch.as_tensor(value_shapes, dtype=query.dtype, device=query.device).flip(-1)\n            add = sampling_offsets / offset_normalizer[None, None, None, :, None, :]\n            sampling_locations = refer_bbox[:, :, None, :, None, :] + add\n        elif num_points == 4:\n            add = sampling_offsets / self.n_points * refer_bbox[:, :, None, :, None, 2:] * 0.5\n            sampling_locations = refer_bbox[:, :, None, :, None, :2] + add\n        else:\n            raise ValueError(f'Last dim of reference_points must be 2 or 4, but got {num_points}.')\n        output = multi_scale_deformable_attn_pytorch(value, value_shapes, sampling_locations, attention_weights)\n        output = self.output_proj(output)\n        return output\n\n\nclass DeformableTransformerDecoderLayer(nn.Module):\n    \"\"\"\n    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py\n    https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/deformable_transformer.py\n    \"\"\"\n\n    def __init__(self, d_model=256, n_heads=8, d_ffn=1024, dropout=0., act=nn.ReLU(), n_levels=4, n_points=4):\n        super().__init__()\n\n        # self attention\n        self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)\n        self.dropout1 = nn.Dropout(dropout)\n        self.norm1 = nn.LayerNorm(d_model)\n\n        # cross attention\n        self.cross_attn = MSDeformAttn(d_model, n_levels, n_heads, n_points)\n        self.dropout2 = nn.Dropout(dropout)\n        self.norm2 = nn.LayerNorm(d_model)\n\n        # ffn\n        self.linear1 = nn.Linear(d_model, d_ffn)\n        self.act = act\n        self.dropout3 = nn.Dropout(dropout)\n        self.linear2 = nn.Linear(d_ffn, d_model)\n        self.dropout4 = nn.Dropout(dropout)\n        self.norm3 = nn.LayerNorm(d_model)\n\n    @staticmethod\n    def with_pos_embed(tensor, pos):\n        return tensor if pos is None else tensor + pos\n\n    def forward_ffn(self, tgt):\n        tgt2 = self.linear2(self.dropout3(self.act(self.linear1(tgt))))\n        tgt = tgt + self.dropout4(tgt2)\n        tgt = self.norm3(tgt)\n        return tgt\n\n    def forward(self, embed, refer_bbox, feats, shapes, padding_mask=None, attn_mask=None, query_pos=None):\n        # self attention\n        q = k = self.with_pos_embed(embed, query_pos)\n        tgt = self.self_attn(q.transpose(0, 1), k.transpose(0, 1), embed.transpose(0, 1),\n                             attn_mask=attn_mask)[0].transpose(0, 1)\n        embed = embed + self.dropout1(tgt)\n        embed = self.norm1(embed)\n\n        # cross attention\n        tgt = self.cross_attn(self.with_pos_embed(embed, query_pos), refer_bbox.unsqueeze(2), feats, shapes,\n                              padding_mask)\n        embed = embed + self.dropout2(tgt)\n        embed = self.norm2(embed)\n\n        # ffn\n        embed = self.forward_ffn(embed)\n\n        return embed\n\n\nclass DeformableTransformerDecoder(nn.Module):\n    \"\"\"\n    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py\n    \"\"\"\n\n    def __init__(self, hidden_dim, decoder_layer, num_layers, eval_idx=-1):\n        super().__init__()\n        self.layers = _get_clones(decoder_layer, num_layers)\n        self.num_layers = num_layers\n        self.hidden_dim = hidden_dim\n        self.eval_idx = eval_idx if eval_idx >= 0 else num_layers + eval_idx\n\n    def forward(\n            self,\n            embed,  # decoder embeddings\n            refer_bbox,  # anchor\n            feats,  # image features\n            shapes,  # feature shapes\n            bbox_head,\n            score_head,\n            pos_mlp,\n            attn_mask=None,\n            padding_mask=None):\n        output = embed\n        dec_bboxes = []\n        dec_cls = []\n        last_refined_bbox = None\n        refer_bbox = refer_bbox.sigmoid()\n        for i, layer in enumerate(self.layers):\n            output = layer(output, refer_bbox, feats, shapes, padding_mask, attn_mask, pos_mlp(refer_bbox))\n\n            # refine bboxes, (bs, num_queries+num_denoising, 4)\n            refined_bbox = torch.sigmoid(bbox_head[i](output) + inverse_sigmoid(refer_bbox))\n\n            if self.training:\n                dec_cls.append(score_head[i](output))\n                if i == 0:\n                    dec_bboxes.append(refined_bbox)\n                else:\n                    dec_bboxes.append(torch.sigmoid(bbox_head[i](output) + inverse_sigmoid(last_refined_bbox)))\n            elif i == self.eval_idx:\n                dec_cls.append(score_head[i](output))\n                dec_bboxes.append(refined_bbox)\n                break\n\n            last_refined_bbox = refined_bbox\n            refer_bbox = refined_bbox.detach() if self.training else refined_bbox\n\n        return torch.stack(dec_bboxes), torch.stack(dec_cls)\n"
  },
  {
    "path": "ultralytics/nn/modules/utils.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nModule utils\n\"\"\"\n\nimport copy\nimport math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.init import uniform_\n\n__all__ = 'multi_scale_deformable_attn_pytorch', 'inverse_sigmoid'\n\n\ndef _get_clones(module, n):\n    return nn.ModuleList([copy.deepcopy(module) for _ in range(n)])\n\n\ndef bias_init_with_prob(prior_prob=0.01):\n    \"\"\"initialize conv/fc bias value according to a given probability value.\"\"\"\n    return float(-np.log((1 - prior_prob) / prior_prob))  # return bias_init\n\n\ndef linear_init_(module):\n    bound = 1 / math.sqrt(module.weight.shape[0])\n    uniform_(module.weight, -bound, bound)\n    if hasattr(module, 'bias') and module.bias is not None:\n        uniform_(module.bias, -bound, bound)\n\n\ndef inverse_sigmoid(x, eps=1e-5):\n    x = x.clamp(min=0, max=1)\n    x1 = x.clamp(min=eps)\n    x2 = (1 - x).clamp(min=eps)\n    return torch.log(x1 / x2)\n\n\ndef multi_scale_deformable_attn_pytorch(value: torch.Tensor, value_spatial_shapes: torch.Tensor,\n                                        sampling_locations: torch.Tensor,\n                                        attention_weights: torch.Tensor) -> torch.Tensor:\n    \"\"\"\n    Multi-scale deformable attention.\n    https://github.com/IDEA-Research/detrex/blob/main/detrex/layers/multi_scale_deform_attn.py\n    \"\"\"\n\n    bs, _, num_heads, embed_dims = value.shape\n    _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape\n    value_list = value.split([H_ * W_ for H_, W_ in value_spatial_shapes], dim=1)\n    sampling_grids = 2 * sampling_locations - 1\n    sampling_value_list = []\n    for level, (H_, W_) in enumerate(value_spatial_shapes):\n        # bs, H_*W_, num_heads, embed_dims ->\n        # bs, H_*W_, num_heads*embed_dims ->\n        # bs, num_heads*embed_dims, H_*W_ ->\n        # bs*num_heads, embed_dims, H_, W_\n        value_l_ = (value_list[level].flatten(2).transpose(1, 2).reshape(bs * num_heads, embed_dims, H_, W_))\n        # bs, num_queries, num_heads, num_points, 2 ->\n        # bs, num_heads, num_queries, num_points, 2 ->\n        # bs*num_heads, num_queries, num_points, 2\n        sampling_grid_l_ = sampling_grids[:, :, :, level].transpose(1, 2).flatten(0, 1)\n        # bs*num_heads, embed_dims, num_queries, num_points\n        sampling_value_l_ = F.grid_sample(value_l_,\n                                          sampling_grid_l_,\n                                          mode='bilinear',\n                                          padding_mode='zeros',\n                                          align_corners=False)\n        sampling_value_list.append(sampling_value_l_)\n    # (bs, num_queries, num_heads, num_levels, num_points) ->\n    # (bs, num_heads, num_queries, num_levels, num_points) ->\n    # (bs, num_heads, 1, num_queries, num_levels*num_points)\n    attention_weights = attention_weights.transpose(1, 2).reshape(bs * num_heads, 1, num_queries,\n                                                                  num_levels * num_points)\n    output = ((torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights).sum(-1).view(\n        bs, num_heads * embed_dims, num_queries))\n    return output.transpose(1, 2).contiguous()\n"
  },
  {
    "path": "ultralytics/nn/tasks.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nfrom copy import deepcopy\nfrom pathlib import Path\n\nimport torch\nimport torch.nn as nn\n\nfrom ultralytics.nn.modules import (AIFI, C1, C2, C3, C3TR, SPP, SPPF, Bottleneck, BottleneckCSP, C2f, C3Ghost, C3x,\n                                    Classify, Concat, Conv, Conv2, ConvTranspose, Detect, DWConv, DWConvTranspose2d,\n                                    Focus, GhostBottleneck, GhostConv, HGBlock, HGStem, Pose, RepC3, RepConv,\n                                    RTDETRDecoder, Segment)\nfrom ultralytics.yolo.utils import DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, colorstr, emojis, yaml_load\nfrom ultralytics.yolo.utils.checks import check_requirements, check_suffix, check_yaml\nfrom ultralytics.yolo.utils.loss import v8ClassificationLoss, v8DetectionLoss, v8PoseLoss, v8SegmentationLoss\nfrom ultralytics.yolo.utils.plotting import feature_visualization\nfrom ultralytics.yolo.utils.torch_utils import (fuse_conv_and_bn, fuse_deconv_and_bn, initialize_weights,\n                                                intersect_dicts, make_divisible, model_info, scale_img, time_sync)\n\ntry:\n    import thop\nexcept ImportError:\n    thop = None\n\n\nclass BaseModel(nn.Module):\n    \"\"\"\n    The BaseModel class serves as a base class for all the models in the Ultralytics YOLO family.\n    \"\"\"\n\n    def forward(self, x, *args, **kwargs):\n        \"\"\"\n        Forward pass of the model on a single scale.\n        Wrapper for `_forward_once` method.\n\n        Args:\n            x (torch.Tensor | dict): The input image tensor or a dict including image tensor and gt labels.\n\n        Returns:\n            (torch.Tensor): The output of the network.\n        \"\"\"\n        if isinstance(x, dict):  # for cases of training and validating while training.\n            return self.loss(x, *args, **kwargs)\n        return self.predict(x, *args, **kwargs)\n\n    def predict(self, x, profile=False, visualize=False, augment=False):\n        \"\"\"\n        Perform a forward pass through the network.\n\n        Args:\n            x (torch.Tensor): The input tensor to the model.\n            profile (bool):  Print the computation time of each layer if True, defaults to False.\n            visualize (bool): Save the feature maps of the model if True, defaults to False.\n            augment (bool): Augment image during prediction, defaults to False.\n\n        Returns:\n            (torch.Tensor): The last output of the model.\n        \"\"\"\n        if augment:\n            return self._predict_augment(x)\n        return self._predict_once(x, profile, visualize)\n\n    def _predict_once(self, x, profile=False, visualize=False):\n        \"\"\"\n        Perform a forward pass through the network.\n\n        Args:\n            x (torch.Tensor): The input tensor to the model.\n            profile (bool):  Print the computation time of each layer if True, defaults to False.\n            visualize (bool): Save the feature maps of the model if True, defaults to False.\n\n        Returns:\n            (torch.Tensor): The last output of the model.\n        \"\"\"\n        y, dt = [], []  # outputs\n        for m in self.model:\n            if m.f != -1:  # if not from previous layer\n                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers\n            if profile:\n                self._profile_one_layer(m, x, dt)\n            x = m(x)  # run\n            y.append(x if m.i in self.save else None)  # save output\n            if visualize:\n                feature_visualization(x, m.type, m.i, save_dir=visualize)\n        return x\n\n    def _predict_augment(self, x):\n        \"\"\"Perform augmentations on input image x and return augmented inference.\"\"\"\n        LOGGER.warning(\n            f'WARNING ⚠️ {self.__class__.__name__} has not supported augment inference yet! Now using single-scale inference instead.'\n        )\n        return self._predict_once(x)\n\n    def _profile_one_layer(self, m, x, dt):\n        \"\"\"\n        Profile the computation time and FLOPs of a single layer of the model on a given input.\n        Appends the results to the provided list.\n\n        Args:\n            m (nn.Module): The layer to be profiled.\n            x (torch.Tensor): The input data to the layer.\n            dt (list): A list to store the computation time of the layer.\n\n        Returns:\n            None\n        \"\"\"\n        c = m == self.model[-1]  # is final layer, copy input as inplace fix\n        o = thop.profile(m, inputs=[x.clone() if c else x], verbose=False)[0] / 1E9 * 2 if thop else 0  # FLOPs\n        t = time_sync()\n        for _ in range(10):\n            m(x.clone() if c else x)\n        dt.append((time_sync() - t) * 100)\n        if m == self.model[0]:\n            LOGGER.info(f\"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s}  module\")\n        LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f}  {m.type}')\n        if c:\n            LOGGER.info(f\"{sum(dt):10.2f} {'-':>10s} {'-':>10s}  Total\")\n\n    def fuse(self, verbose=True):\n        \"\"\"\n        Fuse the `Conv2d()` and `BatchNorm2d()` layers of the model into a single layer, in order to improve the\n        computation efficiency.\n\n        Returns:\n            (nn.Module): The fused model is returned.\n        \"\"\"\n        if not self.is_fused():\n            for m in self.model.modules():\n                if isinstance(m, (Conv, Conv2, DWConv)) and hasattr(m, 'bn'):\n                    if isinstance(m, Conv2):\n                        m.fuse_convs()\n                    m.conv = fuse_conv_and_bn(m.conv, m.bn)  # update conv\n                    delattr(m, 'bn')  # remove batchnorm\n                    m.forward = m.forward_fuse  # update forward\n                if isinstance(m, ConvTranspose) and hasattr(m, 'bn'):\n                    m.conv_transpose = fuse_deconv_and_bn(m.conv_transpose, m.bn)\n                    delattr(m, 'bn')  # remove batchnorm\n                    m.forward = m.forward_fuse  # update forward\n                if isinstance(m, RepConv):\n                    m.fuse_convs()\n                    m.forward = m.forward_fuse  # update forward\n            self.info(verbose=verbose)\n\n        return self\n\n    def is_fused(self, thresh=10):\n        \"\"\"\n        Check if the model has less than a certain threshold of BatchNorm layers.\n\n        Args:\n            thresh (int, optional): The threshold number of BatchNorm layers. Default is 10.\n\n        Returns:\n            (bool): True if the number of BatchNorm layers in the model is less than the threshold, False otherwise.\n        \"\"\"\n        bn = tuple(v for k, v in nn.__dict__.items() if 'Norm' in k)  # normalization layers, i.e. BatchNorm2d()\n        return sum(isinstance(v, bn) for v in self.modules()) < thresh  # True if < 'thresh' BatchNorm layers in model\n\n    def info(self, detailed=False, verbose=True, imgsz=640):\n        \"\"\"\n        Prints model information\n\n        Args:\n            verbose (bool): if True, prints out the model information. Defaults to False\n            imgsz (int): the size of the image that the model will be trained on. Defaults to 640\n        \"\"\"\n        return model_info(self, detailed=detailed, verbose=verbose, imgsz=imgsz)\n\n    def _apply(self, fn):\n        \"\"\"\n        `_apply()` is a function that applies a function to all the tensors in the model that are not\n        parameters or registered buffers\n\n        Args:\n            fn: the function to apply to the model\n\n        Returns:\n            A model that is a Detect() object.\n        \"\"\"\n        self = super()._apply(fn)\n        m = self.model[-1]  # Detect()\n        if isinstance(m, (Detect, Segment)):\n            m.stride = fn(m.stride)\n            m.anchors = fn(m.anchors)\n            m.strides = fn(m.strides)\n        return self\n\n    def load(self, weights, verbose=True):\n        \"\"\"Load the weights into the model.\n\n        Args:\n            weights (dict | torch.nn.Module): The pre-trained weights to be loaded.\n            verbose (bool, optional): Whether to log the transfer progress. Defaults to True.\n        \"\"\"\n        model = weights['model'] if isinstance(weights, dict) else weights  # torchvision models are not dicts\n        csd = model.float().state_dict()  # checkpoint state_dict as FP32\n        csd = intersect_dicts(csd, self.state_dict())  # intersect\n        self.load_state_dict(csd, strict=False)  # load\n        if verbose:\n            LOGGER.info(f'Transferred {len(csd)}/{len(self.model.state_dict())} items from pretrained weights')\n\n    def loss(self, batch, preds=None):\n        \"\"\"\n        Compute loss\n\n        Args:\n            batch (dict): Batch to compute loss on\n            preds (torch.Tensor | List[torch.Tensor]): Predictions.\n        \"\"\"\n        if not hasattr(self, 'criterion'):\n            self.criterion = self.init_criterion()\n\n        preds = self.forward(batch['img']) if preds is None else preds\n        return self.criterion(preds, batch)\n\n    def init_criterion(self):\n        raise NotImplementedError('compute_loss() needs to be implemented by task heads')\n\n\nclass DetectionModel(BaseModel):\n    \"\"\"YOLOv8 detection model.\"\"\"\n\n    def __init__(self, cfg='yolov8n.yaml', ch=3, nc=None, verbose=True):  # model, input channels, number of classes\n        super().__init__()\n        self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg)  # cfg dict\n\n        # Define model\n        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels\n        if nc and nc != self.yaml['nc']:\n            LOGGER.info(f\"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}\")\n            self.yaml['nc'] = nc  # override yaml value\n        self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose)  # model, savelist\n        self.names = {i: f'{i}' for i in range(self.yaml['nc'])}  # default names dict\n        self.inplace = self.yaml.get('inplace', True)\n\n        # Build strides\n        m = self.model[-1]  # Detect()\n        if isinstance(m, (Detect, Segment, Pose)):\n            s = 256  # 2x min stride\n            m.inplace = self.inplace\n            forward = lambda x: self.forward(x)[0] if isinstance(m, (Segment, Pose)) else self.forward(x)\n            m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))])  # forward\n            self.stride = m.stride\n            m.bias_init()  # only run once\n        else:\n            self.stride = torch.Tensor([32])  # default stride for i.e. RTDETR\n\n        # Init weights, biases\n        initialize_weights(self)\n        if verbose:\n            self.info()\n            LOGGER.info('')\n\n    def _predict_augment(self, x):\n        \"\"\"Perform augmentations on input image x and return augmented inference and train outputs.\"\"\"\n        img_size = x.shape[-2:]  # height, width\n        s = [1, 0.83, 0.67]  # scales\n        f = [None, 3, None]  # flips (2-ud, 3-lr)\n        y = []  # outputs\n        for si, fi in zip(s, f):\n            xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))\n            yi = super().predict(xi)[0]  # forward\n            # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save\n            yi = self._descale_pred(yi, fi, si, img_size)\n            y.append(yi)\n        y = self._clip_augmented(y)  # clip augmented tails\n        return torch.cat(y, -1), None  # augmented inference, train\n\n    @staticmethod\n    def _descale_pred(p, flips, scale, img_size, dim=1):\n        \"\"\"De-scale predictions following augmented inference (inverse operation).\"\"\"\n        p[:, :4] /= scale  # de-scale\n        x, y, wh, cls = p.split((1, 1, 2, p.shape[dim] - 4), dim)\n        if flips == 2:\n            y = img_size[0] - y  # de-flip ud\n        elif flips == 3:\n            x = img_size[1] - x  # de-flip lr\n        return torch.cat((x, y, wh, cls), dim)\n\n    def _clip_augmented(self, y):\n        \"\"\"Clip YOLOv5 augmented inference tails.\"\"\"\n        nl = self.model[-1].nl  # number of detection layers (P3-P5)\n        g = sum(4 ** x for x in range(nl))  # grid points\n        e = 1  # exclude layer count\n        i = (y[0].shape[-1] // g) * sum(4 ** x for x in range(e))  # indices\n        y[0] = y[0][..., :-i]  # large\n        i = (y[-1].shape[-1] // g) * sum(4 ** (nl - 1 - x) for x in range(e))  # indices\n        y[-1] = y[-1][..., i:]  # small\n        return y\n\n    def init_criterion(self):\n        return v8DetectionLoss(self)\n\n\nclass SegmentationModel(DetectionModel):\n    \"\"\"YOLOv8 segmentation model.\"\"\"\n\n    def __init__(self, cfg='yolov8n-seg.yaml', ch=3, nc=None, verbose=True):\n        \"\"\"Initialize YOLOv8 segmentation model with given config and parameters.\"\"\"\n        super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)\n\n    def init_criterion(self):\n        return v8SegmentationLoss(self)\n\n    def _predict_augment(self, x):\n        \"\"\"Perform augmentations on input image x and return augmented inference.\"\"\"\n        LOGGER.warning(\n            f'WARNING ⚠️ {self.__class__.__name__} has not supported augment inference yet! Now using single-scale inference instead.'\n        )\n        return self._predict_once(x)\n\n\nclass PoseModel(DetectionModel):\n    \"\"\"YOLOv8 pose model.\"\"\"\n\n    def __init__(self, cfg='yolov8n-pose.yaml', ch=3, nc=None, data_kpt_shape=(None, None), verbose=True):\n        \"\"\"Initialize YOLOv8 Pose model.\"\"\"\n        if not isinstance(cfg, dict):\n            cfg = yaml_model_load(cfg)  # load model YAML\n        if any(data_kpt_shape) and list(data_kpt_shape) != list(cfg['kpt_shape']):\n            LOGGER.info(f\"Overriding model.yaml kpt_shape={cfg['kpt_shape']} with kpt_shape={data_kpt_shape}\")\n            cfg['kpt_shape'] = data_kpt_shape\n        super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)\n\n    def init_criterion(self):\n        return v8PoseLoss(self)\n\n    def _predict_augment(self, x):\n        \"\"\"Perform augmentations on input image x and return augmented inference.\"\"\"\n        LOGGER.warning(\n            f'WARNING ⚠️ {self.__class__.__name__} has not supported augment inference yet! Now using single-scale inference instead.'\n        )\n        return self._predict_once(x)\n\n\nclass ClassificationModel(BaseModel):\n    \"\"\"YOLOv8 classification model.\"\"\"\n\n    def __init__(self,\n                 cfg=None,\n                 model=None,\n                 ch=3,\n                 nc=None,\n                 cutoff=10,\n                 verbose=True):  # yaml, model, channels, number of classes, cutoff index, verbose flag\n        super().__init__()\n        self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg, ch, nc, verbose)\n\n    def _from_detection_model(self, model, nc=1000, cutoff=10):\n        \"\"\"Create a YOLOv5 classification model from a YOLOv5 detection model.\"\"\"\n        from ultralytics.nn.autobackend import AutoBackend\n        if isinstance(model, AutoBackend):\n            model = model.model  # unwrap DetectMultiBackend\n        model.model = model.model[:cutoff]  # backbone\n        m = model.model[-1]  # last layer\n        ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels  # ch into module\n        c = Classify(ch, nc)  # Classify()\n        c.i, c.f, c.type = m.i, m.f, 'models.common.Classify'  # index, from, type\n        model.model[-1] = c  # replace\n        self.model = model.model\n        self.stride = model.stride\n        self.save = []\n        self.nc = nc\n\n    def _from_yaml(self, cfg, ch, nc, verbose):\n        \"\"\"Set YOLOv8 model configurations and define the model architecture.\"\"\"\n        self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg)  # cfg dict\n\n        # Define model\n        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels\n        if nc and nc != self.yaml['nc']:\n            LOGGER.info(f\"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}\")\n            self.yaml['nc'] = nc  # override yaml value\n        elif not nc and not self.yaml.get('nc', None):\n            raise ValueError('nc not specified. Must specify nc in model.yaml or function arguments.')\n        self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose)  # model, savelist\n        self.stride = torch.Tensor([1])  # no stride constraints\n        self.names = {i: f'{i}' for i in range(self.yaml['nc'])}  # default names dict\n        self.info()\n\n    @staticmethod\n    def reshape_outputs(model, nc):\n        \"\"\"Update a TorchVision classification model to class count 'n' if required.\"\"\"\n        name, m = list((model.model if hasattr(model, 'model') else model).named_children())[-1]  # last module\n        if isinstance(m, Classify):  # YOLO Classify() head\n            if m.linear.out_features != nc:\n                m.linear = nn.Linear(m.linear.in_features, nc)\n        elif isinstance(m, nn.Linear):  # ResNet, EfficientNet\n            if m.out_features != nc:\n                setattr(model, name, nn.Linear(m.in_features, nc))\n        elif isinstance(m, nn.Sequential):\n            types = [type(x) for x in m]\n            if nn.Linear in types:\n                i = types.index(nn.Linear)  # nn.Linear index\n                if m[i].out_features != nc:\n                    m[i] = nn.Linear(m[i].in_features, nc)\n            elif nn.Conv2d in types:\n                i = types.index(nn.Conv2d)  # nn.Conv2d index\n                if m[i].out_channels != nc:\n                    m[i] = nn.Conv2d(m[i].in_channels, nc, m[i].kernel_size, m[i].stride, bias=m[i].bias is not None)\n\n    def init_criterion(self):\n        \"\"\"Compute the classification loss between predictions and true labels.\"\"\"\n        return v8ClassificationLoss()\n\n\nclass RTDETRDetectionModel(DetectionModel):\n\n    def __init__(self, cfg='rtdetr-l.yaml', ch=3, nc=None, verbose=True):\n        super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)\n\n    def init_criterion(self):\n        \"\"\"Compute the classification loss between predictions and true labels.\"\"\"\n        from ultralytics.vit.utils.loss import RTDETRDetectionLoss\n\n        return RTDETRDetectionLoss(nc=self.nc, use_vfl=True)\n\n    def loss(self, batch, preds=None):\n        if not hasattr(self, 'criterion'):\n            self.criterion = self.init_criterion()\n\n        img = batch['img']\n        # NOTE: preprocess gt_bbox and gt_labels to list.\n        bs = len(img)\n        batch_idx = batch['batch_idx']\n        gt_groups = [(batch_idx == i).sum().item() for i in range(bs)]\n        targets = {\n            'cls': batch['cls'].to(img.device, dtype=torch.long).view(-1),\n            'bboxes': batch['bboxes'].to(device=img.device),\n            'batch_idx': batch_idx.to(img.device, dtype=torch.long).view(-1),\n            'gt_groups': gt_groups}\n\n        preds = self.predict(img, batch=targets) if preds is None else preds\n        dec_bboxes, dec_scores, enc_bboxes, enc_scores, dn_meta = preds\n        if dn_meta is None:\n            dn_bboxes, dn_scores = None, None\n        else:\n            dn_bboxes, dec_bboxes = torch.split(dec_bboxes, dn_meta['dn_num_split'], dim=2)\n            dn_scores, dec_scores = torch.split(dec_scores, dn_meta['dn_num_split'], dim=2)\n\n        dec_bboxes = torch.cat([enc_bboxes.unsqueeze(0), dec_bboxes])  # (7, bs, 300, 4)\n        dec_scores = torch.cat([enc_scores.unsqueeze(0), dec_scores])\n\n        loss = self.criterion((dec_bboxes, dec_scores),\n                              targets,\n                              dn_bboxes=dn_bboxes,\n                              dn_scores=dn_scores,\n                              dn_meta=dn_meta)\n        # NOTE: There are like 12 losses in RTDETR, backward with all losses but only show the main three losses.\n        return sum(loss.values()), torch.as_tensor([loss[k].detach() for k in ['loss_giou', 'loss_class', 'loss_bbox']],\n                                                   device=img.device)\n\n    def predict(self, x, profile=False, visualize=False, batch=None, augment=False):\n        \"\"\"\n        Perform a forward pass through the network.\n\n        Args:\n            x (torch.Tensor): The input tensor to the model\n            profile (bool):  Print the computation time of each layer if True, defaults to False.\n            visualize (bool): Save the feature maps of the model if True, defaults to False\n            batch (dict): A dict including gt boxes and labels from dataloader.\n\n        Returns:\n            (torch.Tensor): The last output of the model.\n        \"\"\"\n        y, dt = [], []  # outputs\n        for m in self.model[:-1]:  # except the head part\n            if m.f != -1:  # if not from previous layer\n                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers\n            if profile:\n                self._profile_one_layer(m, x, dt)\n            x = m(x)  # run\n            y.append(x if m.i in self.save else None)  # save output\n            if visualize:\n                feature_visualization(x, m.type, m.i, save_dir=visualize)\n        head = self.model[-1]\n        x = head([y[j] for j in head.f], batch)  # head inference\n        return x\n\n\nclass Ensemble(nn.ModuleList):\n    \"\"\"Ensemble of models.\"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize an ensemble of models.\"\"\"\n        super().__init__()\n\n    def forward(self, x, augment=False, profile=False, visualize=False):\n        \"\"\"Function generates the YOLOv5 network's final layer.\"\"\"\n        y = [module(x, augment, profile, visualize)[0] for module in self]\n        # y = torch.stack(y).max(0)[0]  # max ensemble\n        # y = torch.stack(y).mean(0)  # mean ensemble\n        y = torch.cat(y, 2)  # nms ensemble, y shape(B, HW, C)\n        return y, None  # inference, train output\n\n\n# Functions ------------------------------------------------------------------------------------------------------------\n\n\ndef torch_safe_load(weight):\n    \"\"\"\n    This function attempts to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised,\n    it catches the error, logs a warning message, and attempts to install the missing module via the\n    check_requirements() function. After installation, the function again attempts to load the model using torch.load().\n\n    Args:\n        weight (str): The file path of the PyTorch model.\n\n    Returns:\n        (dict): The loaded PyTorch model.\n    \"\"\"\n    from ultralytics.yolo.utils.downloads import attempt_download_asset\n\n    check_suffix(file=weight, suffix='.pt')\n    file = attempt_download_asset(weight)  # search online if missing locally\n    try:\n        return torch.load(file, map_location='cpu'), file  # load\n    except ModuleNotFoundError as e:  # e.name is missing module name\n        if e.name == 'models':\n            raise TypeError(\n                emojis(f'ERROR ❌️ {weight} appears to be an Ultralytics YOLOv5 model originally trained '\n                       f'with https://github.com/ultralytics/yolov5.\\nThis model is NOT forwards compatible with '\n                       f'YOLOv8 at https://github.com/ultralytics/ultralytics.'\n                       f\"\\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to \"\n                       f\"run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'\")) from e\n        LOGGER.warning(f\"WARNING ⚠️ {weight} appears to require '{e.name}', which is not in ultralytics requirements.\"\n                       f\"\\nAutoInstall will run now for '{e.name}' but this feature will be removed in the future.\"\n                       f\"\\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to \"\n                       f\"run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'\")\n        check_requirements(e.name)  # install missing module\n\n        return torch.load(file, map_location='cpu'), file  # load\n\n\ndef attempt_load_weights(weights, device=None, inplace=True, fuse=False):\n    \"\"\"Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a.\"\"\"\n\n    ensemble = Ensemble()\n    for w in weights if isinstance(weights, list) else [weights]:\n        ckpt, w = torch_safe_load(w)  # load ckpt\n        args = {**DEFAULT_CFG_DICT, **ckpt['train_args']} if 'train_args' in ckpt else None  # combined args\n        model = (ckpt.get('ema') or ckpt['model']).to(device).float()  # FP32 model\n\n        # Model compatibility updates\n        model.args = args  # attach args to model\n        model.pt_path = w  # attach *.pt file path to model\n        model.task = guess_model_task(model)\n        if not hasattr(model, 'stride'):\n            model.stride = torch.tensor([32.])\n\n        # Append\n        ensemble.append(model.fuse().eval() if fuse and hasattr(model, 'fuse') else model.eval())  # model in eval mode\n\n    # Module compatibility updates\n    for m in ensemble.modules():\n        t = type(m)\n        if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Segment):\n            m.inplace = inplace  # torch 1.7.0 compatibility\n        elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):\n            m.recompute_scale_factor = None  # torch 1.11.0 compatibility\n\n    # Return model\n    if len(ensemble) == 1:\n        return ensemble[-1]\n\n    # Return ensemble\n    LOGGER.info(f'Ensemble created with {weights}\\n')\n    for k in 'names', 'nc', 'yaml':\n        setattr(ensemble, k, getattr(ensemble[0], k))\n    ensemble.stride = ensemble[torch.argmax(torch.tensor([m.stride.max() for m in ensemble])).int()].stride\n    assert all(ensemble[0].nc == m.nc for m in ensemble), f'Models differ in class counts {[m.nc for m in ensemble]}'\n    return ensemble\n\n\ndef attempt_load_one_weight(weight, device=None, inplace=True, fuse=False):\n    \"\"\"Loads a single model weights.\"\"\"\n    ckpt, weight = torch_safe_load(weight)  # load ckpt\n    args = {**DEFAULT_CFG_DICT, **(ckpt.get('train_args', {}))}  # combine model and default args, preferring model args\n    model = (ckpt.get('ema') or ckpt['model']).to(device).float()  # FP32 model\n\n    # Model compatibility updates\n    model.args = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS}  # attach args to model\n    model.pt_path = weight  # attach *.pt file path to model\n    model.task = guess_model_task(model)\n    if not hasattr(model, 'stride'):\n        model.stride = torch.tensor([32.])\n\n    model = model.fuse().eval() if fuse and hasattr(model, 'fuse') else model.eval()  # model in eval mode\n\n    # Module compatibility updates\n    for m in model.modules():\n        t = type(m)\n        if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Segment):\n            m.inplace = inplace  # torch 1.7.0 compatibility\n        elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):\n            m.recompute_scale_factor = None  # torch 1.11.0 compatibility\n\n    # Return model and ckpt\n    return model, ckpt\n\n\ndef parse_model(d, ch, verbose=True):  # model_dict, input_channels(3)\n    # Parse a YOLO model.yaml dictionary into a PyTorch model\n    import ast\n\n    # Args\n    max_channels = float('inf')\n    nc, act, scales = (d.get(x) for x in ('nc', 'activation', 'scales'))\n    depth, width, kpt_shape = (d.get(x, 1.0) for x in ('depth_multiple', 'width_multiple', 'kpt_shape'))\n    if scales:\n        scale = d.get('scale')\n        if not scale:\n            scale = tuple(scales.keys())[0]\n            LOGGER.warning(f\"WARNING ⚠️ no model scale passed. Assuming scale='{scale}'.\")\n        depth, width, max_channels = scales[scale]\n\n    if act:\n        Conv.default_act = eval(act)  # redefine default activation, i.e. Conv.default_act = nn.SiLU()\n        if verbose:\n            LOGGER.info(f\"{colorstr('activation:')} {act}\")  # print\n\n    if verbose:\n        LOGGER.info(f\"\\n{'':>3}{'from':>20}{'n':>3}{'params':>10}  {'module':<45}{'arguments':<30}\")\n    ch = [ch]\n    layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out\n    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args\n        m = getattr(torch.nn, m[3:]) if 'nn.' in m else globals()[m]  # get module\n        for j, a in enumerate(args):\n            if isinstance(a, str):\n                with contextlib.suppress(ValueError):\n                    args[j] = locals()[a] if a in locals() else ast.literal_eval(a)\n\n        n = n_ = max(round(n * depth), 1) if n > 1 else n  # depth gain\n        if m in (Classify, Conv, ConvTranspose, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, Focus,\n                 BottleneckCSP, C1, C2, C2f, C3, C3TR, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x, RepC3):\n            c1, c2 = ch[f], args[0]\n            if c2 != nc:  # if c2 not equal to number of classes (i.e. for Classify() output)\n                c2 = make_divisible(min(c2, max_channels) * width, 8)\n\n            args = [c1, c2, *args[1:]]\n            if m in (BottleneckCSP, C1, C2, C2f, C3, C3TR, C3Ghost, C3x, RepC3):\n                args.insert(2, n)  # number of repeats\n                n = 1\n        elif m is AIFI:\n            args = [ch[f], *args]\n        elif m in (HGStem, HGBlock):\n            c1, cm, c2 = ch[f], args[0], args[1]\n            args = [c1, cm, c2, *args[2:]]\n            if m is HGBlock:\n                args.insert(4, n)  # number of repeats\n                n = 1\n\n        elif m is nn.BatchNorm2d:\n            args = [ch[f]]\n        elif m is Concat:\n            c2 = sum(ch[x] for x in f)\n        elif m in (Detect, Segment, Pose, RTDETRDecoder):\n            args.append([ch[x] for x in f])\n            if m is Segment:\n                args[2] = make_divisible(min(args[2], max_channels) * width, 8)\n        else:\n            c2 = ch[f]\n\n        m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args)  # module\n        t = str(m)[8:-2].replace('__main__.', '')  # module type\n        m.np = sum(x.numel() for x in m_.parameters())  # number params\n        m_.i, m_.f, m_.type = i, f, t  # attach index, 'from' index, type\n        if verbose:\n            LOGGER.info(f'{i:>3}{str(f):>20}{n_:>3}{m.np:10.0f}  {t:<45}{str(args):<30}')  # print\n        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist\n        layers.append(m_)\n        if i == 0:\n            ch = []\n        ch.append(c2)\n    return nn.Sequential(*layers), sorted(save)\n\n\ndef yaml_model_load(path):\n    \"\"\"Load a YOLOv8 model from a YAML file.\"\"\"\n    import re\n\n    path = Path(path)\n    if path.stem in (f'yolov{d}{x}6' for x in 'nsmlx' for d in (5, 8)):\n        new_stem = re.sub(r'(\\d+)([nslmx])6(.+)?$', r'\\1\\2-p6\\3', path.stem)\n        LOGGER.warning(f'WARNING ⚠️ Ultralytics YOLO P6 models now use -p6 suffix. Renaming {path.stem} to {new_stem}.')\n        path = path.with_stem(new_stem)\n\n    unified_path = re.sub(r'(\\d+)([nslmx])(.+)?$', r'\\1\\3', str(path))  # i.e. yolov8x.yaml -> yolov8.yaml\n    yaml_file = check_yaml(unified_path, hard=False) or check_yaml(path)\n    d = yaml_load(yaml_file)  # model dict\n    d['scale'] = guess_model_scale(path)\n    d['yaml_file'] = str(path)\n    return d\n\n\ndef guess_model_scale(model_path):\n    \"\"\"\n    Takes a path to a YOLO model's YAML file as input and extracts the size character of the model's scale.\n    The function uses regular expression matching to find the pattern of the model scale in the YAML file name,\n    which is denoted by n, s, m, l, or x. The function returns the size character of the model scale as a string.\n\n    Args:\n        model_path (str | Path): The path to the YOLO model's YAML file.\n\n    Returns:\n        (str): The size character of the model's scale, which can be n, s, m, l, or x.\n    \"\"\"\n    with contextlib.suppress(AttributeError):\n        import re\n        return re.search(r'yolov\\d+([nslmx])', Path(model_path).stem).group(1)  # n, s, m, l, or x\n    return ''\n\n\ndef guess_model_task(model):\n    \"\"\"\n    Guess the task of a PyTorch model from its architecture or configuration.\n\n    Args:\n        model (nn.Module | dict): PyTorch model or model configuration in YAML format.\n\n    Returns:\n        (str): Task of the model ('detect', 'segment', 'classify', 'pose').\n\n    Raises:\n        SyntaxError: If the task of the model could not be determined.\n    \"\"\"\n\n    def cfg2task(cfg):\n        \"\"\"Guess from YAML dictionary.\"\"\"\n        m = cfg['head'][-1][-2].lower()  # output module name\n        if m in ('classify', 'classifier', 'cls', 'fc'):\n            return 'classify'\n        if m == 'detect':\n            return 'detect'\n        if m == 'segment':\n            return 'segment'\n        if m == 'pose':\n            return 'pose'\n\n    # Guess from model cfg\n    if isinstance(model, dict):\n        with contextlib.suppress(Exception):\n            return cfg2task(model)\n\n    # Guess from PyTorch model\n    if isinstance(model, nn.Module):  # PyTorch model\n        for x in 'model.args', 'model.model.args', 'model.model.model.args':\n            with contextlib.suppress(Exception):\n                return eval(x)['task']\n        for x in 'model.yaml', 'model.model.yaml', 'model.model.model.yaml':\n            with contextlib.suppress(Exception):\n                return cfg2task(eval(x))\n\n        for m in model.modules():\n            if isinstance(m, Detect):\n                return 'detect'\n            elif isinstance(m, Segment):\n                return 'segment'\n            elif isinstance(m, Classify):\n                return 'classify'\n            elif isinstance(m, Pose):\n                return 'pose'\n\n    # Guess from model filename\n    if isinstance(model, (str, Path)):\n        model = Path(model)\n        if '-seg' in model.stem or 'segment' in model.parts:\n            return 'segment'\n        elif '-cls' in model.stem or 'classify' in model.parts:\n            return 'classify'\n        elif '-pose' in model.stem or 'pose' in model.parts:\n            return 'pose'\n        elif 'detect' in model.parts:\n            return 'detect'\n\n    # Unable to determine task from model\n    LOGGER.warning(\"WARNING ⚠️ Unable to automatically guess model task, assuming 'task=detect'. \"\n                   \"Explicitly define task for your model, i.e. 'task=detect', 'segment', 'classify', or 'pose'.\")\n    return 'detect'  # assume detect\n"
  },
  {
    "path": "ultralytics/tracker/README.md",
    "content": "# Tracker\n\n## Supported Trackers\n\n- [x] ByteTracker\n- [x] BoT-SORT\n\n## Usage\n\n### python interface:\n\nYou can use the Python interface to track objects using the YOLO model.\n\n```python\nfrom ultralytics import YOLO\n\nmodel = YOLO(\"yolov8n.pt\")  # or a segmentation model .i.e yolov8n-seg.pt\nmodel.track(\n    source=\"video/streams\",\n    stream=True,\n    tracker=\"botsort.yaml\",  # or 'bytetrack.yaml'\n    show=True,\n)\n```\n\nYou can get the IDs of the tracked objects using the following code:\n\n```python\nfrom ultralytics import YOLO\n\nmodel = YOLO(\"yolov8n.pt\")\n\nfor result in model.track(source=\"video.mp4\"):\n    print(\n        result.boxes.id.cpu().numpy().astype(int)\n    )  # this will print the IDs of the tracked objects in the frame\n```\n\nIf you want to use the tracker with a folder of images or when you loop on the video frames, you should use the `persist` parameter to tell the model that these frames are related to each other so the IDs will be fixed for the same objects. Otherwise, the IDs will be different in each frame because in each loop, the model creates a new object for tracking, but the `persist` parameter makes it use the same object for tracking.\n\n```python\nimport cv2\nfrom ultralytics import YOLO\n\ncap = cv2.VideoCapture(\"video.mp4\")\nmodel = YOLO(\"yolov8n.pt\")\nwhile True:\n    ret, frame = cap.read()\n    if not ret:\n        break\n    results = model.track(frame, persist=True)\n    boxes = results[0].boxes.xyxy.cpu().numpy().astype(int)\n    ids = results[0].boxes.id.cpu().numpy().astype(int)\n    for box, id in zip(boxes, ids):\n        cv2.rectangle(frame, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)\n        cv2.putText(\n            frame,\n            f\"Id {id}\",\n            (box[0], box[1]),\n            cv2.FONT_HERSHEY_SIMPLEX,\n            1,\n            (0, 0, 255),\n            2,\n        )\n    cv2.imshow(\"frame\", frame)\n    if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n        break\n```\n\n## Change tracker parameters\n\nYou can change the tracker parameters by eding the `tracker.yaml` file which is located in the ultralytics/tracker/cfg folder.\n\n## Command Line Interface (CLI)\n\nYou can also use the command line interface to track objects using the YOLO model.\n\n```bash\nyolo detect track source=... tracker=...\nyolo segment track source=... tracker=...\nyolo pose track source=... tracker=...\n```\n\nBy default, trackers will use the configuration in `ultralytics/tracker/cfg`.\nWe also support using a modified tracker config file. Please refer to the tracker config files\nin `ultralytics/tracker/cfg`.<br>\n"
  },
  {
    "path": "ultralytics/tracker/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .track import register_tracker\nfrom .trackers import BOTSORT, BYTETracker\n\n__all__ = 'register_tracker', 'BOTSORT', 'BYTETracker'  # allow simpler import\n"
  },
  {
    "path": "ultralytics/tracker/cfg/botsort.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Default YOLO tracker settings for BoT-SORT tracker https://github.com/NirAharon/BoT-SORT\n\ntracker_type: botsort  # tracker type, ['botsort', 'bytetrack']\ntrack_high_thresh: 0.5  # threshold for the first association\ntrack_low_thresh: 0.1  # threshold for the second association\nnew_track_thresh: 0.6  # threshold for init new track if the detection does not match any tracks\ntrack_buffer: 30  # buffer to calculate the time when to remove tracks\nmatch_thresh: 0.8  # threshold for matching tracks\n# min_box_area: 10  # threshold for min box areas(for tracker evaluation, not used for now)\n# mot20: False  # for tracker evaluation(not used for now)\n\n# BoT-SORT settings\ncmc_method: sparseOptFlow  # method of global motion compensation\n# ReID model related thresh (not supported yet)\nproximity_thresh: 0.5\nappearance_thresh: 0.25\nwith_reid: False\n"
  },
  {
    "path": "ultralytics/tracker/cfg/bytetrack.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Default YOLO tracker settings for ByteTrack tracker https://github.com/ifzhang/ByteTrack\n\ntracker_type: bytetrack  # tracker type, ['botsort', 'bytetrack']\ntrack_high_thresh: 0.5  # threshold for the first association\ntrack_low_thresh: 0.1  # threshold for the second association\nnew_track_thresh: 0.6  # threshold for init new track if the detection does not match any tracks\ntrack_buffer: 30  # buffer to calculate the time when to remove tracks\nmatch_thresh: 0.8  # threshold for matching tracks\n# min_box_area: 10  # threshold for min box areas(for tracker evaluation, not used for now)\n# mot20: False  # for tracker evaluation(not used for now)\n"
  },
  {
    "path": "ultralytics/tracker/track.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom functools import partial\n\nimport torch\n\nfrom ultralytics.yolo.utils import IterableSimpleNamespace, yaml_load\nfrom ultralytics.yolo.utils.checks import check_yaml\n\nfrom .trackers import BOTSORT, BYTETracker\n\nTRACKER_MAP = {'bytetrack': BYTETracker, 'botsort': BOTSORT}\n\n\ndef on_predict_start(predictor, persist=False):\n    \"\"\"\n    Initialize trackers for object tracking during prediction.\n\n    Args:\n        predictor (object): The predictor object to initialize trackers for.\n        persist (bool, optional): Whether to persist the trackers if they already exist. Defaults to False.\n\n    Raises:\n        AssertionError: If the tracker_type is not 'bytetrack' or 'botsort'.\n    \"\"\"\n    if hasattr(predictor, 'trackers') and persist:\n        return\n    tracker = check_yaml(predictor.args.tracker)\n    cfg = IterableSimpleNamespace(**yaml_load(tracker))\n    assert cfg.tracker_type in ['bytetrack', 'botsort'], \\\n        f\"Only support 'bytetrack' and 'botsort' for now, but got '{cfg.tracker_type}'\"\n    trackers = []\n    for _ in range(predictor.dataset.bs):\n        tracker = TRACKER_MAP[cfg.tracker_type](args=cfg, frame_rate=30)\n        trackers.append(tracker)\n    predictor.trackers = trackers\n\n\ndef on_predict_postprocess_end(predictor):\n    \"\"\"Postprocess detected boxes and update with object tracking.\"\"\"\n    bs = predictor.dataset.bs\n    im0s = predictor.batch[1]\n    for i in range(bs):\n        det = predictor.results[i].boxes.cpu().numpy()\n        if len(det) == 0:\n            continue\n        tracks = predictor.trackers[i].update(det, im0s[i])\n        if len(tracks) == 0:\n            continue\n        idx = tracks[:, -1].astype(int)\n        predictor.results[i] = predictor.results[i][idx]\n        predictor.results[i].update(boxes=torch.as_tensor(tracks[:, :-1]))\n\n\ndef register_tracker(model, persist):\n    \"\"\"\n    Register tracking callbacks to the model for object tracking during prediction.\n\n    Args:\n        model (object): The model object to register tracking callbacks for.\n        persist (bool): Whether to persist the trackers if they already exist.\n\n    \"\"\"\n    model.add_callback('on_predict_start', partial(on_predict_start, persist=persist))\n    model.add_callback('on_predict_postprocess_end', on_predict_postprocess_end)\n"
  },
  {
    "path": "ultralytics/tracker/trackers/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .bot_sort import BOTSORT\nfrom .byte_tracker import BYTETracker\n\n__all__ = 'BOTSORT', 'BYTETracker'  # allow simpler import\n"
  },
  {
    "path": "ultralytics/tracker/trackers/basetrack.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom collections import OrderedDict\n\nimport numpy as np\n\n\nclass TrackState:\n    \"\"\"Enumeration of possible object tracking states.\"\"\"\n\n    New = 0\n    Tracked = 1\n    Lost = 2\n    Removed = 3\n\n\nclass BaseTrack:\n    \"\"\"Base class for object tracking, handling basic track attributes and operations.\"\"\"\n\n    _count = 0\n\n    track_id = 0\n    is_activated = False\n    state = TrackState.New\n\n    history = OrderedDict()\n    features = []\n    curr_feature = None\n    score = 0\n    start_frame = 0\n    frame_id = 0\n    time_since_update = 0\n\n    # Multi-camera\n    location = (np.inf, np.inf)\n\n    @property\n    def end_frame(self):\n        \"\"\"Return the last frame ID of the track.\"\"\"\n        return self.frame_id\n\n    @staticmethod\n    def next_id():\n        \"\"\"Increment and return the global track ID counter.\"\"\"\n        BaseTrack._count += 1\n        return BaseTrack._count\n\n    def activate(self, *args):\n        \"\"\"Activate the track with the provided arguments.\"\"\"\n        raise NotImplementedError\n\n    def predict(self):\n        \"\"\"Predict the next state of the track.\"\"\"\n        raise NotImplementedError\n\n    def update(self, *args, **kwargs):\n        \"\"\"Update the track with new observations.\"\"\"\n        raise NotImplementedError\n\n    def mark_lost(self):\n        \"\"\"Mark the track as lost.\"\"\"\n        self.state = TrackState.Lost\n\n    def mark_removed(self):\n        \"\"\"Mark the track as removed.\"\"\"\n        self.state = TrackState.Removed\n\n    @staticmethod\n    def reset_id():\n        \"\"\"Reset the global track ID counter.\"\"\"\n        BaseTrack._count = 0\n"
  },
  {
    "path": "ultralytics/tracker/trackers/bot_sort.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom collections import deque\n\nimport numpy as np\n\nfrom ..utils import matching\nfrom ..utils.gmc import GMC\nfrom ..utils.kalman_filter import KalmanFilterXYWH\nfrom .basetrack import TrackState\nfrom .byte_tracker import BYTETracker, STrack\n\n\nclass BOTrack(STrack):\n    shared_kalman = KalmanFilterXYWH()\n\n    def __init__(self, tlwh, score, cls, feat=None, feat_history=50):\n        \"\"\"Initialize YOLOv8 object with temporal parameters, such as feature history, alpha and current features.\"\"\"\n        super().__init__(tlwh, score, cls)\n\n        self.smooth_feat = None\n        self.curr_feat = None\n        if feat is not None:\n            self.update_features(feat)\n        self.features = deque([], maxlen=feat_history)\n        self.alpha = 0.9\n\n    def update_features(self, feat):\n        \"\"\"Update features vector and smooth it using exponential moving average.\"\"\"\n        feat /= np.linalg.norm(feat)\n        self.curr_feat = feat\n        if self.smooth_feat is None:\n            self.smooth_feat = feat\n        else:\n            self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat\n        self.features.append(feat)\n        self.smooth_feat /= np.linalg.norm(self.smooth_feat)\n\n    def predict(self):\n        \"\"\"Predicts the mean and covariance using Kalman filter.\"\"\"\n        mean_state = self.mean.copy()\n        if self.state != TrackState.Tracked:\n            mean_state[6] = 0\n            mean_state[7] = 0\n\n        self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)\n\n    def re_activate(self, new_track, frame_id, new_id=False):\n        \"\"\"Reactivates a track with updated features and optionally assigns a new ID.\"\"\"\n        if new_track.curr_feat is not None:\n            self.update_features(new_track.curr_feat)\n        super().re_activate(new_track, frame_id, new_id)\n\n    def update(self, new_track, frame_id):\n        \"\"\"Update the YOLOv8 instance with new track and frame ID.\"\"\"\n        if new_track.curr_feat is not None:\n            self.update_features(new_track.curr_feat)\n        super().update(new_track, frame_id)\n\n    @property\n    def tlwh(self):\n        \"\"\"Get current position in bounding box format `(top left x, top left y,\n        width, height)`.\n        \"\"\"\n        if self.mean is None:\n            return self._tlwh.copy()\n        ret = self.mean[:4].copy()\n        ret[:2] -= ret[2:] / 2\n        return ret\n\n    @staticmethod\n    def multi_predict(stracks):\n        \"\"\"Predicts the mean and covariance of multiple object tracks using shared Kalman filter.\"\"\"\n        if len(stracks) <= 0:\n            return\n        multi_mean = np.asarray([st.mean.copy() for st in stracks])\n        multi_covariance = np.asarray([st.covariance for st in stracks])\n        for i, st in enumerate(stracks):\n            if st.state != TrackState.Tracked:\n                multi_mean[i][6] = 0\n                multi_mean[i][7] = 0\n        multi_mean, multi_covariance = BOTrack.shared_kalman.multi_predict(multi_mean, multi_covariance)\n        for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):\n            stracks[i].mean = mean\n            stracks[i].covariance = cov\n\n    def convert_coords(self, tlwh):\n        \"\"\"Converts Top-Left-Width-Height bounding box coordinates to X-Y-Width-Height format.\"\"\"\n        return self.tlwh_to_xywh(tlwh)\n\n    @staticmethod\n    def tlwh_to_xywh(tlwh):\n        \"\"\"Convert bounding box to format `(center x, center y, width,\n        height)`.\n        \"\"\"\n        ret = np.asarray(tlwh).copy()\n        ret[:2] += ret[2:] / 2\n        return ret\n\n\nclass BOTSORT(BYTETracker):\n\n    def __init__(self, args, frame_rate=30):\n        \"\"\"Initialize YOLOv8 object with ReID module and GMC algorithm.\"\"\"\n        super().__init__(args, frame_rate)\n        # ReID module\n        self.proximity_thresh = args.proximity_thresh\n        self.appearance_thresh = args.appearance_thresh\n\n        if args.with_reid:\n            # Haven't supported BoT-SORT(reid) yet\n            self.encoder = None\n        # self.gmc = GMC(method=args.cmc_method, verbose=[args.name, args.ablation])\n        self.gmc = GMC(method=args.cmc_method)\n\n    def get_kalmanfilter(self):\n        \"\"\"Returns an instance of KalmanFilterXYWH for object tracking.\"\"\"\n        return KalmanFilterXYWH()\n\n    def init_track(self, dets, scores, cls, img=None):\n        \"\"\"Initialize track with detections, scores, and classes.\"\"\"\n        if len(dets) == 0:\n            return []\n        if self.args.with_reid and self.encoder is not None:\n            features_keep = self.encoder.inference(img, dets)\n            return [BOTrack(xyxy, s, c, f) for (xyxy, s, c, f) in zip(dets, scores, cls, features_keep)]  # detections\n        else:\n            return [BOTrack(xyxy, s, c) for (xyxy, s, c) in zip(dets, scores, cls)]  # detections\n\n    def get_dists(self, tracks, detections):\n        \"\"\"Get distances between tracks and detections using IoU and (optionally) ReID embeddings.\"\"\"\n        dists = matching.iou_distance(tracks, detections)\n        dists_mask = (dists > self.proximity_thresh)\n\n        # TODO: mot20\n        # if not self.args.mot20:\n        dists = matching.fuse_score(dists, detections)\n\n        if self.args.with_reid and self.encoder is not None:\n            emb_dists = matching.embedding_distance(tracks, detections) / 2.0\n            emb_dists[emb_dists > self.appearance_thresh] = 1.0\n            emb_dists[dists_mask] = 1.0\n            dists = np.minimum(dists, emb_dists)\n        return dists\n\n    def multi_predict(self, tracks):\n        \"\"\"Predict and track multiple objects with YOLOv8 model.\"\"\"\n        BOTrack.multi_predict(tracks)\n"
  },
  {
    "path": "ultralytics/tracker/trackers/byte_tracker.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport numpy as np\n\nfrom ..utils import matching\nfrom ..utils.kalman_filter import KalmanFilterXYAH\nfrom .basetrack import BaseTrack, TrackState\n\n\nclass STrack(BaseTrack):\n    shared_kalman = KalmanFilterXYAH()\n\n    def __init__(self, tlwh, score, cls):\n        \"\"\"wait activate.\"\"\"\n        self._tlwh = np.asarray(self.tlbr_to_tlwh(tlwh[:-1]), dtype=np.float32)\n        self.kalman_filter = None\n        self.mean, self.covariance = None, None\n        self.is_activated = False\n\n        self.score = score\n        self.tracklet_len = 0\n        self.cls = cls\n        self.idx = tlwh[-1]\n\n    def predict(self):\n        \"\"\"Predicts mean and covariance using Kalman filter.\"\"\"\n        mean_state = self.mean.copy()\n        if self.state != TrackState.Tracked:\n            mean_state[7] = 0\n        self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)\n\n    @staticmethod\n    def multi_predict(stracks):\n        \"\"\"Perform multi-object predictive tracking using Kalman filter for given stracks.\"\"\"\n        if len(stracks) <= 0:\n            return\n        multi_mean = np.asarray([st.mean.copy() for st in stracks])\n        multi_covariance = np.asarray([st.covariance for st in stracks])\n        for i, st in enumerate(stracks):\n            if st.state != TrackState.Tracked:\n                multi_mean[i][7] = 0\n        multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)\n        for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):\n            stracks[i].mean = mean\n            stracks[i].covariance = cov\n\n    @staticmethod\n    def multi_gmc(stracks, H=np.eye(2, 3)):\n        \"\"\"Update state tracks positions and covariances using a homography matrix.\"\"\"\n        if len(stracks) > 0:\n            multi_mean = np.asarray([st.mean.copy() for st in stracks])\n            multi_covariance = np.asarray([st.covariance for st in stracks])\n\n            R = H[:2, :2]\n            R8x8 = np.kron(np.eye(4, dtype=float), R)\n            t = H[:2, 2]\n\n            for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):\n                mean = R8x8.dot(mean)\n                mean[:2] += t\n                cov = R8x8.dot(cov).dot(R8x8.transpose())\n\n                stracks[i].mean = mean\n                stracks[i].covariance = cov\n\n    def activate(self, kalman_filter, frame_id):\n        \"\"\"Start a new tracklet.\"\"\"\n        self.kalman_filter = kalman_filter\n        self.track_id = self.next_id()\n        self.mean, self.covariance = self.kalman_filter.initiate(self.convert_coords(self._tlwh))\n\n        self.tracklet_len = 0\n        self.state = TrackState.Tracked\n        if frame_id == 1:\n            self.is_activated = True\n        self.frame_id = frame_id\n        self.start_frame = frame_id\n\n    def re_activate(self, new_track, frame_id, new_id=False):\n        \"\"\"Reactivates a previously lost track with a new detection.\"\"\"\n        self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance,\n                                                               self.convert_coords(new_track.tlwh))\n        self.tracklet_len = 0\n        self.state = TrackState.Tracked\n        self.is_activated = True\n        self.frame_id = frame_id\n        if new_id:\n            self.track_id = self.next_id()\n        self.score = new_track.score\n        self.cls = new_track.cls\n        self.idx = new_track.idx\n\n    def update(self, new_track, frame_id):\n        \"\"\"\n        Update a matched track\n        :type new_track: STrack\n        :type frame_id: int\n        :return:\n        \"\"\"\n        self.frame_id = frame_id\n        self.tracklet_len += 1\n\n        new_tlwh = new_track.tlwh\n        self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance,\n                                                               self.convert_coords(new_tlwh))\n        self.state = TrackState.Tracked\n        self.is_activated = True\n\n        self.score = new_track.score\n        self.cls = new_track.cls\n        self.idx = new_track.idx\n\n    def convert_coords(self, tlwh):\n        \"\"\"Convert a bounding box's top-left-width-height format to its x-y-angle-height equivalent.\"\"\"\n        return self.tlwh_to_xyah(tlwh)\n\n    @property\n    def tlwh(self):\n        \"\"\"Get current position in bounding box format `(top left x, top left y,\n        width, height)`.\n        \"\"\"\n        if self.mean is None:\n            return self._tlwh.copy()\n        ret = self.mean[:4].copy()\n        ret[2] *= ret[3]\n        ret[:2] -= ret[2:] / 2\n        return ret\n\n    @property\n    def tlbr(self):\n        \"\"\"Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,\n        `(top left, bottom right)`.\n        \"\"\"\n        ret = self.tlwh.copy()\n        ret[2:] += ret[:2]\n        return ret\n\n    @staticmethod\n    def tlwh_to_xyah(tlwh):\n        \"\"\"Convert bounding box to format `(center x, center y, aspect ratio,\n        height)`, where the aspect ratio is `width / height`.\n        \"\"\"\n        ret = np.asarray(tlwh).copy()\n        ret[:2] += ret[2:] / 2\n        ret[2] /= ret[3]\n        return ret\n\n    @staticmethod\n    def tlbr_to_tlwh(tlbr):\n        \"\"\"Converts top-left bottom-right format to top-left width height format.\"\"\"\n        ret = np.asarray(tlbr).copy()\n        ret[2:] -= ret[:2]\n        return ret\n\n    @staticmethod\n    def tlwh_to_tlbr(tlwh):\n        \"\"\"Converts tlwh bounding box format to tlbr format.\"\"\"\n        ret = np.asarray(tlwh).copy()\n        ret[2:] += ret[:2]\n        return ret\n\n    def __repr__(self):\n        \"\"\"Return a string representation of the BYTETracker object with start and end frames and track ID.\"\"\"\n        return f'OT_{self.track_id}_({self.start_frame}-{self.end_frame})'\n\n\nclass BYTETracker:\n\n    def __init__(self, args, frame_rate=30):\n        \"\"\"Initialize a YOLOv8 object to track objects with given arguments and frame rate.\"\"\"\n        self.tracked_stracks = []  # type: list[STrack]\n        self.lost_stracks = []  # type: list[STrack]\n        self.removed_stracks = []  # type: list[STrack]\n\n        self.frame_id = 0\n        self.args = args\n        self.max_time_lost = int(frame_rate / 30.0 * args.track_buffer)\n        self.kalman_filter = self.get_kalmanfilter()\n        self.reset_id()\n\n    def update(self, results, img=None):\n        \"\"\"Updates object tracker with new detections and returns tracked object bounding boxes.\"\"\"\n        self.frame_id += 1\n        activated_stracks = []\n        refind_stracks = []\n        lost_stracks = []\n        removed_stracks = []\n\n        scores = results.conf\n        bboxes = results.xyxy\n        # Add index\n        bboxes = np.concatenate([bboxes, np.arange(len(bboxes)).reshape(-1, 1)], axis=-1)\n        cls = results.cls\n\n        remain_inds = scores > self.args.track_high_thresh\n        inds_low = scores > self.args.track_low_thresh\n        inds_high = scores < self.args.track_high_thresh\n\n        inds_second = np.logical_and(inds_low, inds_high)\n        dets_second = bboxes[inds_second]\n        dets = bboxes[remain_inds]\n        scores_keep = scores[remain_inds]\n        scores_second = scores[inds_second]\n        cls_keep = cls[remain_inds]\n        cls_second = cls[inds_second]\n\n        detections = self.init_track(dets, scores_keep, cls_keep, img)\n        # Add newly detected tracklets to tracked_stracks\n        unconfirmed = []\n        tracked_stracks = []  # type: list[STrack]\n        for track in self.tracked_stracks:\n            if not track.is_activated:\n                unconfirmed.append(track)\n            else:\n                tracked_stracks.append(track)\n        # Step 2: First association, with high score detection boxes\n        strack_pool = self.joint_stracks(tracked_stracks, self.lost_stracks)\n        # Predict the current location with KF\n        self.multi_predict(strack_pool)\n        if hasattr(self, 'gmc') and img is not None:\n            warp = self.gmc.apply(img, dets)\n            STrack.multi_gmc(strack_pool, warp)\n            STrack.multi_gmc(unconfirmed, warp)\n\n        dists = self.get_dists(strack_pool, detections)\n        matches, u_track, u_detection = matching.linear_assignment(dists, thresh=self.args.match_thresh)\n\n        for itracked, idet in matches:\n            track = strack_pool[itracked]\n            det = detections[idet]\n            if track.state == TrackState.Tracked:\n                track.update(det, self.frame_id)\n                activated_stracks.append(track)\n            else:\n                track.re_activate(det, self.frame_id, new_id=False)\n                refind_stracks.append(track)\n        # Step 3: Second association, with low score detection boxes\n        # association the untrack to the low score detections\n        detections_second = self.init_track(dets_second, scores_second, cls_second, img)\n        r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]\n        # TODO\n        dists = matching.iou_distance(r_tracked_stracks, detections_second)\n        matches, u_track, u_detection_second = matching.linear_assignment(dists, thresh=0.5)\n        for itracked, idet in matches:\n            track = r_tracked_stracks[itracked]\n            det = detections_second[idet]\n            if track.state == TrackState.Tracked:\n                track.update(det, self.frame_id)\n                activated_stracks.append(track)\n            else:\n                track.re_activate(det, self.frame_id, new_id=False)\n                refind_stracks.append(track)\n\n        for it in u_track:\n            track = r_tracked_stracks[it]\n            if track.state != TrackState.Lost:\n                track.mark_lost()\n                lost_stracks.append(track)\n        # Deal with unconfirmed tracks, usually tracks with only one beginning frame\n        detections = [detections[i] for i in u_detection]\n        dists = self.get_dists(unconfirmed, detections)\n        matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)\n        for itracked, idet in matches:\n            unconfirmed[itracked].update(detections[idet], self.frame_id)\n            activated_stracks.append(unconfirmed[itracked])\n        for it in u_unconfirmed:\n            track = unconfirmed[it]\n            track.mark_removed()\n            removed_stracks.append(track)\n        # Step 4: Init new stracks\n        for inew in u_detection:\n            track = detections[inew]\n            if track.score < self.args.new_track_thresh:\n                continue\n            track.activate(self.kalman_filter, self.frame_id)\n            activated_stracks.append(track)\n        # Step 5: Update state\n        for track in self.lost_stracks:\n            if self.frame_id - track.end_frame > self.max_time_lost:\n                track.mark_removed()\n                removed_stracks.append(track)\n\n        self.tracked_stracks = [t for t in self.tracked_stracks if t.state == TrackState.Tracked]\n        self.tracked_stracks = self.joint_stracks(self.tracked_stracks, activated_stracks)\n        self.tracked_stracks = self.joint_stracks(self.tracked_stracks, refind_stracks)\n        self.lost_stracks = self.sub_stracks(self.lost_stracks, self.tracked_stracks)\n        self.lost_stracks.extend(lost_stracks)\n        self.lost_stracks = self.sub_stracks(self.lost_stracks, self.removed_stracks)\n        self.tracked_stracks, self.lost_stracks = self.remove_duplicate_stracks(self.tracked_stracks, self.lost_stracks)\n        self.removed_stracks.extend(removed_stracks)\n        if len(self.removed_stracks) > 1000:\n            self.removed_stracks = self.removed_stracks[-999:]  # clip remove stracks to 1000 maximum\n        return np.asarray(\n            [x.tlbr.tolist() + [x.track_id, x.score, x.cls, x.idx] for x in self.tracked_stracks if x.is_activated],\n            dtype=np.float32)\n\n    def get_kalmanfilter(self):\n        \"\"\"Returns a Kalman filter object for tracking bounding boxes.\"\"\"\n        return KalmanFilterXYAH()\n\n    def init_track(self, dets, scores, cls, img=None):\n        \"\"\"Initialize object tracking with detections and scores using STrack algorithm.\"\"\"\n        return [STrack(xyxy, s, c) for (xyxy, s, c) in zip(dets, scores, cls)] if len(dets) else []  # detections\n\n    def get_dists(self, tracks, detections):\n        \"\"\"Calculates the distance between tracks and detections using IOU and fuses scores.\"\"\"\n        dists = matching.iou_distance(tracks, detections)\n        # TODO: mot20\n        # if not self.args.mot20:\n        dists = matching.fuse_score(dists, detections)\n        return dists\n\n    def multi_predict(self, tracks):\n        \"\"\"Returns the predicted tracks using the YOLOv8 network.\"\"\"\n        STrack.multi_predict(tracks)\n\n    def reset_id(self):\n        \"\"\"Resets the ID counter of STrack.\"\"\"\n        STrack.reset_id()\n\n    @staticmethod\n    def joint_stracks(tlista, tlistb):\n        \"\"\"Combine two lists of stracks into a single one.\"\"\"\n        exists = {}\n        res = []\n        for t in tlista:\n            exists[t.track_id] = 1\n            res.append(t)\n        for t in tlistb:\n            tid = t.track_id\n            if not exists.get(tid, 0):\n                exists[tid] = 1\n                res.append(t)\n        return res\n\n    @staticmethod\n    def sub_stracks(tlista, tlistb):\n        \"\"\"DEPRECATED CODE in https://github.com/ultralytics/ultralytics/pull/1890/\n        stracks = {t.track_id: t for t in tlista}\n        for t in tlistb:\n            tid = t.track_id\n            if stracks.get(tid, 0):\n                del stracks[tid]\n        return list(stracks.values())\n        \"\"\"\n        track_ids_b = {t.track_id for t in tlistb}\n        return [t for t in tlista if t.track_id not in track_ids_b]\n\n    @staticmethod\n    def remove_duplicate_stracks(stracksa, stracksb):\n        \"\"\"Remove duplicate stracks with non-maximum IOU distance.\"\"\"\n        pdist = matching.iou_distance(stracksa, stracksb)\n        pairs = np.where(pdist < 0.15)\n        dupa, dupb = [], []\n        for p, q in zip(*pairs):\n            timep = stracksa[p].frame_id - stracksa[p].start_frame\n            timeq = stracksb[q].frame_id - stracksb[q].start_frame\n            if timep > timeq:\n                dupb.append(q)\n            else:\n                dupa.append(p)\n        resa = [t for i, t in enumerate(stracksa) if i not in dupa]\n        resb = [t for i, t in enumerate(stracksb) if i not in dupb]\n        return resa, resb\n"
  },
  {
    "path": "ultralytics/tracker/utils/__init__.py",
    "content": ""
  },
  {
    "path": "ultralytics/tracker/utils/gmc.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport copy\n\nimport cv2\nimport numpy as np\n\nfrom ultralytics.yolo.utils import LOGGER\n\n\nclass GMC:\n\n    def __init__(self, method='sparseOptFlow', downscale=2, verbose=None):\n        \"\"\"Initialize a video tracker with specified parameters.\"\"\"\n        super().__init__()\n\n        self.method = method\n        self.downscale = max(1, int(downscale))\n\n        if self.method == 'orb':\n            self.detector = cv2.FastFeatureDetector_create(20)\n            self.extractor = cv2.ORB_create()\n            self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING)\n\n        elif self.method == 'sift':\n            self.detector = cv2.SIFT_create(nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20)\n            self.extractor = cv2.SIFT_create(nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20)\n            self.matcher = cv2.BFMatcher(cv2.NORM_L2)\n\n        elif self.method == 'ecc':\n            number_of_iterations = 5000\n            termination_eps = 1e-6\n            self.warp_mode = cv2.MOTION_EUCLIDEAN\n            self.criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, number_of_iterations, termination_eps)\n\n        elif self.method == 'sparseOptFlow':\n            self.feature_params = dict(maxCorners=1000,\n                                       qualityLevel=0.01,\n                                       minDistance=1,\n                                       blockSize=3,\n                                       useHarrisDetector=False,\n                                       k=0.04)\n            # self.gmc_file = open('GMC_results.txt', 'w')\n\n        elif self.method in ['file', 'files']:\n            seqName = verbose[0]\n            ablation = verbose[1]\n            if ablation:\n                filePath = r'tracker/GMC_files/MOT17_ablation'\n            else:\n                filePath = r'tracker/GMC_files/MOTChallenge'\n\n            if '-FRCNN' in seqName:\n                seqName = seqName[:-6]\n            elif '-DPM' in seqName or '-SDP' in seqName:\n                seqName = seqName[:-4]\n            self.gmcFile = open(f'{filePath}/GMC-{seqName}.txt')\n\n            if self.gmcFile is None:\n                raise ValueError(f'Error: Unable to open GMC file in directory:{filePath}')\n        elif self.method in ['none', 'None']:\n            self.method = 'none'\n        else:\n            raise ValueError(f'Error: Unknown CMC method:{method}')\n\n        self.prevFrame = None\n        self.prevKeyPoints = None\n        self.prevDescriptors = None\n\n        self.initializedFirstFrame = False\n\n    def apply(self, raw_frame, detections=None):\n        \"\"\"Apply object detection on a raw frame using specified method.\"\"\"\n        if self.method in ['orb', 'sift']:\n            return self.applyFeatures(raw_frame, detections)\n        elif self.method == 'ecc':\n            return self.applyEcc(raw_frame, detections)\n        elif self.method == 'sparseOptFlow':\n            return self.applySparseOptFlow(raw_frame, detections)\n        elif self.method == 'file':\n            return self.applyFile(raw_frame, detections)\n        elif self.method == 'none':\n            return np.eye(2, 3)\n        else:\n            return np.eye(2, 3)\n\n    def applyEcc(self, raw_frame, detections=None):\n        \"\"\"Initialize.\"\"\"\n        height, width, _ = raw_frame.shape\n        frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)\n        H = np.eye(2, 3, dtype=np.float32)\n\n        # Downscale image (TODO: consider using pyramids)\n        if self.downscale > 1.0:\n            frame = cv2.GaussianBlur(frame, (3, 3), 1.5)\n            frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))\n            width = width // self.downscale\n            height = height // self.downscale\n\n        # Handle first frame\n        if not self.initializedFirstFrame:\n            # Initialize data\n            self.prevFrame = frame.copy()\n\n            # Initialization done\n            self.initializedFirstFrame = True\n\n            return H\n\n        # Run the ECC algorithm. The results are stored in warp_matrix.\n        # (cc, H) = cv2.findTransformECC(self.prevFrame, frame, H, self.warp_mode, self.criteria)\n        try:\n            (cc, H) = cv2.findTransformECC(self.prevFrame, frame, H, self.warp_mode, self.criteria, None, 1)\n        except Exception as e:\n            LOGGER.warning(f'WARNING: find transform failed. Set warp as identity {e}')\n\n        return H\n\n    def applyFeatures(self, raw_frame, detections=None):\n        \"\"\"Initialize.\"\"\"\n        height, width, _ = raw_frame.shape\n        frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)\n        H = np.eye(2, 3)\n\n        # Downscale image (TODO: consider using pyramids)\n        if self.downscale > 1.0:\n            # frame = cv2.GaussianBlur(frame, (3, 3), 1.5)\n            frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))\n            width = width // self.downscale\n            height = height // self.downscale\n\n        # Find the keypoints\n        mask = np.zeros_like(frame)\n        # mask[int(0.05 * height): int(0.95 * height), int(0.05 * width): int(0.95 * width)] = 255\n        mask[int(0.02 * height):int(0.98 * height), int(0.02 * width):int(0.98 * width)] = 255\n        if detections is not None:\n            for det in detections:\n                tlbr = (det[:4] / self.downscale).astype(np.int_)\n                mask[tlbr[1]:tlbr[3], tlbr[0]:tlbr[2]] = 0\n\n        keypoints = self.detector.detect(frame, mask)\n\n        # Compute the descriptors\n        keypoints, descriptors = self.extractor.compute(frame, keypoints)\n\n        # Handle first frame\n        if not self.initializedFirstFrame:\n            # Initialize data\n            self.prevFrame = frame.copy()\n            self.prevKeyPoints = copy.copy(keypoints)\n            self.prevDescriptors = copy.copy(descriptors)\n\n            # Initialization done\n            self.initializedFirstFrame = True\n\n            return H\n\n        # Match descriptors.\n        knnMatches = self.matcher.knnMatch(self.prevDescriptors, descriptors, 2)\n\n        # Filtered matches based on smallest spatial distance\n        matches = []\n        spatialDistances = []\n\n        maxSpatialDistance = 0.25 * np.array([width, height])\n\n        # Handle empty matches case\n        if len(knnMatches) == 0:\n            # Store to next iteration\n            self.prevFrame = frame.copy()\n            self.prevKeyPoints = copy.copy(keypoints)\n            self.prevDescriptors = copy.copy(descriptors)\n\n            return H\n\n        for m, n in knnMatches:\n            if m.distance < 0.9 * n.distance:\n                prevKeyPointLocation = self.prevKeyPoints[m.queryIdx].pt\n                currKeyPointLocation = keypoints[m.trainIdx].pt\n\n                spatialDistance = (prevKeyPointLocation[0] - currKeyPointLocation[0],\n                                   prevKeyPointLocation[1] - currKeyPointLocation[1])\n\n                if (np.abs(spatialDistance[0]) < maxSpatialDistance[0]) and \\\n                        (np.abs(spatialDistance[1]) < maxSpatialDistance[1]):\n                    spatialDistances.append(spatialDistance)\n                    matches.append(m)\n\n        meanSpatialDistances = np.mean(spatialDistances, 0)\n        stdSpatialDistances = np.std(spatialDistances, 0)\n\n        inliers = (spatialDistances - meanSpatialDistances) < 2.5 * stdSpatialDistances\n\n        goodMatches = []\n        prevPoints = []\n        currPoints = []\n        for i in range(len(matches)):\n            if inliers[i, 0] and inliers[i, 1]:\n                goodMatches.append(matches[i])\n                prevPoints.append(self.prevKeyPoints[matches[i].queryIdx].pt)\n                currPoints.append(keypoints[matches[i].trainIdx].pt)\n\n        prevPoints = np.array(prevPoints)\n        currPoints = np.array(currPoints)\n\n        # Draw the keypoint matches on the output image\n        # if False:\n        #     import matplotlib.pyplot as plt\n        #     matches_img = np.hstack((self.prevFrame, frame))\n        #     matches_img = cv2.cvtColor(matches_img, cv2.COLOR_GRAY2BGR)\n        #     W = np.size(self.prevFrame, 1)\n        #     for m in goodMatches:\n        #         prev_pt = np.array(self.prevKeyPoints[m.queryIdx].pt, dtype=np.int_)\n        #         curr_pt = np.array(keypoints[m.trainIdx].pt, dtype=np.int_)\n        #         curr_pt[0] += W\n        #         color = np.random.randint(0, 255, 3)\n        #         color = (int(color[0]), int(color[1]), int(color[2]))\n        #\n        #         matches_img = cv2.line(matches_img, prev_pt, curr_pt, tuple(color), 1, cv2.LINE_AA)\n        #         matches_img = cv2.circle(matches_img, prev_pt, 2, tuple(color), -1)\n        #         matches_img = cv2.circle(matches_img, curr_pt, 2, tuple(color), -1)\n        #\n        #     plt.figure()\n        #     plt.imshow(matches_img)\n        #     plt.show()\n\n        # Find rigid matrix\n        if (np.size(prevPoints, 0) > 4) and (np.size(prevPoints, 0) == np.size(prevPoints, 0)):\n            H, inliers = cv2.estimateAffinePartial2D(prevPoints, currPoints, cv2.RANSAC)\n\n            # Handle downscale\n            if self.downscale > 1.0:\n                H[0, 2] *= self.downscale\n                H[1, 2] *= self.downscale\n        else:\n            LOGGER.warning('WARNING: not enough matching points')\n\n        # Store to next iteration\n        self.prevFrame = frame.copy()\n        self.prevKeyPoints = copy.copy(keypoints)\n        self.prevDescriptors = copy.copy(descriptors)\n\n        return H\n\n    def applySparseOptFlow(self, raw_frame, detections=None):\n        \"\"\"Initialize.\"\"\"\n        # t0 = time.time()\n        height, width, _ = raw_frame.shape\n        frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)\n        H = np.eye(2, 3)\n\n        # Downscale image\n        if self.downscale > 1.0:\n            # frame = cv2.GaussianBlur(frame, (3, 3), 1.5)\n            frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))\n\n        # Find the keypoints\n        keypoints = cv2.goodFeaturesToTrack(frame, mask=None, **self.feature_params)\n\n        # Handle first frame\n        if not self.initializedFirstFrame:\n            # Initialize data\n            self.prevFrame = frame.copy()\n            self.prevKeyPoints = copy.copy(keypoints)\n\n            # Initialization done\n            self.initializedFirstFrame = True\n\n            return H\n\n        # Find correspondences\n        matchedKeypoints, status, err = cv2.calcOpticalFlowPyrLK(self.prevFrame, frame, self.prevKeyPoints, None)\n\n        # Leave good correspondences only\n        prevPoints = []\n        currPoints = []\n\n        for i in range(len(status)):\n            if status[i]:\n                prevPoints.append(self.prevKeyPoints[i])\n                currPoints.append(matchedKeypoints[i])\n\n        prevPoints = np.array(prevPoints)\n        currPoints = np.array(currPoints)\n\n        # Find rigid matrix\n        if (np.size(prevPoints, 0) > 4) and (np.size(prevPoints, 0) == np.size(prevPoints, 0)):\n            H, inliers = cv2.estimateAffinePartial2D(prevPoints, currPoints, cv2.RANSAC)\n\n            # Handle downscale\n            if self.downscale > 1.0:\n                H[0, 2] *= self.downscale\n                H[1, 2] *= self.downscale\n        else:\n            LOGGER.warning('WARNING: not enough matching points')\n\n        # Store to next iteration\n        self.prevFrame = frame.copy()\n        self.prevKeyPoints = copy.copy(keypoints)\n\n        # gmc_line = str(1000 * (time.time() - t0)) + \"\\t\" + str(H[0, 0]) + \"\\t\" + str(H[0, 1]) + \"\\t\" + str(\n        #     H[0, 2]) + \"\\t\" + str(H[1, 0]) + \"\\t\" + str(H[1, 1]) + \"\\t\" + str(H[1, 2]) + \"\\n\"\n        # self.gmc_file.write(gmc_line)\n\n        return H\n\n    def applyFile(self, raw_frame, detections=None):\n        \"\"\"Return the homography matrix based on the GCPs in the next line of the input GMC file.\"\"\"\n        line = self.gmcFile.readline()\n        tokens = line.split('\\t')\n        H = np.eye(2, 3, dtype=np.float_)\n        H[0, 0] = float(tokens[1])\n        H[0, 1] = float(tokens[2])\n        H[0, 2] = float(tokens[3])\n        H[1, 0] = float(tokens[4])\n        H[1, 1] = float(tokens[5])\n        H[1, 2] = float(tokens[6])\n\n        return H\n"
  },
  {
    "path": "ultralytics/tracker/utils/kalman_filter.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport numpy as np\nimport scipy.linalg\n\n# Table for the 0.95 quantile of the chi-square distribution with N degrees of freedom (contains values for N=1, ..., 9)\n# Taken from MATLAB/Octave's chi2inv function and used as Mahalanobis gating threshold.\nchi2inv95 = {1: 3.8415, 2: 5.9915, 3: 7.8147, 4: 9.4877, 5: 11.070, 6: 12.592, 7: 14.067, 8: 15.507, 9: 16.919}\n\n\nclass KalmanFilterXYAH:\n    \"\"\"\n    For bytetrack\n    A simple Kalman filter for tracking bounding boxes in image space.\n\n    The 8-dimensional state space\n\n        x, y, a, h, vx, vy, va, vh\n\n    contains the bounding box center position (x, y), aspect ratio a, height h,\n    and their respective velocities.\n\n    Object motion follows a constant velocity model. The bounding box location\n    (x, y, a, h) is taken as direct observation of the state space (linear\n    observation model).\n\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize Kalman filter model matrices with motion and observation uncertainty weights.\"\"\"\n        ndim, dt = 4, 1.\n\n        # Create Kalman filter model matrices.\n        self._motion_mat = np.eye(2 * ndim, 2 * ndim)\n        for i in range(ndim):\n            self._motion_mat[i, ndim + i] = dt\n        self._update_mat = np.eye(ndim, 2 * ndim)\n\n        # Motion and observation uncertainty are chosen relative to the current\n        # state estimate. These weights control the amount of uncertainty in\n        # the model. This is a bit hacky.\n        self._std_weight_position = 1. / 20\n        self._std_weight_velocity = 1. / 160\n\n    def initiate(self, measurement):\n        \"\"\"Create track from unassociated measurement.\n\n        Parameters\n        ----------\n        measurement : ndarray\n            Bounding box coordinates (x, y, a, h) with center position (x, y),\n            aspect ratio a, and height h.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector (8 dimensional) and covariance matrix (8x8\n            dimensional) of the new track. Unobserved velocities are initialized\n            to 0 mean.\n\n        \"\"\"\n        mean_pos = measurement\n        mean_vel = np.zeros_like(mean_pos)\n        mean = np.r_[mean_pos, mean_vel]\n\n        std = [\n            2 * self._std_weight_position * measurement[3], 2 * self._std_weight_position * measurement[3], 1e-2,\n            2 * self._std_weight_position * measurement[3], 10 * self._std_weight_velocity * measurement[3],\n            10 * self._std_weight_velocity * measurement[3], 1e-5, 10 * self._std_weight_velocity * measurement[3]]\n        covariance = np.diag(np.square(std))\n        return mean, covariance\n\n    def predict(self, mean, covariance):\n        \"\"\"Run Kalman filter prediction step.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The 8 dimensional mean vector of the object state at the previous\n            time step.\n        covariance : ndarray\n            The 8x8 dimensional covariance matrix of the object state at the\n            previous time step.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector and covariance matrix of the predicted\n            state. Unobserved velocities are initialized to 0 mean.\n\n        \"\"\"\n        std_pos = [\n            self._std_weight_position * mean[3], self._std_weight_position * mean[3], 1e-2,\n            self._std_weight_position * mean[3]]\n        std_vel = [\n            self._std_weight_velocity * mean[3], self._std_weight_velocity * mean[3], 1e-5,\n            self._std_weight_velocity * mean[3]]\n        motion_cov = np.diag(np.square(np.r_[std_pos, std_vel]))\n\n        # mean = np.dot(self._motion_mat, mean)\n        mean = np.dot(mean, self._motion_mat.T)\n        covariance = np.linalg.multi_dot((self._motion_mat, covariance, self._motion_mat.T)) + motion_cov\n\n        return mean, covariance\n\n    def project(self, mean, covariance):\n        \"\"\"Project state distribution to measurement space.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The state's mean vector (8 dimensional array).\n        covariance : ndarray\n            The state's covariance matrix (8x8 dimensional).\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the projected mean and covariance matrix of the given state\n            estimate.\n\n        \"\"\"\n        std = [\n            self._std_weight_position * mean[3], self._std_weight_position * mean[3], 1e-1,\n            self._std_weight_position * mean[3]]\n        innovation_cov = np.diag(np.square(std))\n\n        mean = np.dot(self._update_mat, mean)\n        covariance = np.linalg.multi_dot((self._update_mat, covariance, self._update_mat.T))\n        return mean, covariance + innovation_cov\n\n    def multi_predict(self, mean, covariance):\n        \"\"\"Run Kalman filter prediction step (Vectorized version).\n        Parameters\n        ----------\n        mean : ndarray\n            The Nx8 dimensional mean matrix of the object states at the previous\n            time step.\n        covariance : ndarray\n            The Nx8x8 dimensional covariance matrix of the object states at the\n            previous time step.\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector and covariance matrix of the predicted\n            state. Unobserved velocities are initialized to 0 mean.\n        \"\"\"\n        std_pos = [\n            self._std_weight_position * mean[:, 3], self._std_weight_position * mean[:, 3],\n            1e-2 * np.ones_like(mean[:, 3]), self._std_weight_position * mean[:, 3]]\n        std_vel = [\n            self._std_weight_velocity * mean[:, 3], self._std_weight_velocity * mean[:, 3],\n            1e-5 * np.ones_like(mean[:, 3]), self._std_weight_velocity * mean[:, 3]]\n        sqr = np.square(np.r_[std_pos, std_vel]).T\n\n        motion_cov = [np.diag(sqr[i]) for i in range(len(mean))]\n        motion_cov = np.asarray(motion_cov)\n\n        mean = np.dot(mean, self._motion_mat.T)\n        left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2))\n        covariance = np.dot(left, self._motion_mat.T) + motion_cov\n\n        return mean, covariance\n\n    def update(self, mean, covariance, measurement):\n        \"\"\"Run Kalman filter correction step.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The predicted state's mean vector (8 dimensional).\n        covariance : ndarray\n            The state's covariance matrix (8x8 dimensional).\n        measurement : ndarray\n            The 4 dimensional measurement vector (x, y, a, h), where (x, y)\n            is the center position, a the aspect ratio, and h the height of the\n            bounding box.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the measurement-corrected state distribution.\n\n        \"\"\"\n        projected_mean, projected_cov = self.project(mean, covariance)\n\n        chol_factor, lower = scipy.linalg.cho_factor(projected_cov, lower=True, check_finite=False)\n        kalman_gain = scipy.linalg.cho_solve((chol_factor, lower),\n                                             np.dot(covariance, self._update_mat.T).T,\n                                             check_finite=False).T\n        innovation = measurement - projected_mean\n\n        new_mean = mean + np.dot(innovation, kalman_gain.T)\n        new_covariance = covariance - np.linalg.multi_dot((kalman_gain, projected_cov, kalman_gain.T))\n        return new_mean, new_covariance\n\n    def gating_distance(self, mean, covariance, measurements, only_position=False, metric='maha'):\n        \"\"\"Compute gating distance between state distribution and measurements.\n        A suitable distance threshold can be obtained from `chi2inv95`. If\n        `only_position` is False, the chi-square distribution has 4 degrees of\n        freedom, otherwise 2.\n        Parameters\n        ----------\n        mean : ndarray\n            Mean vector over the state distribution (8 dimensional).\n        covariance : ndarray\n            Covariance of the state distribution (8x8 dimensional).\n        measurements : ndarray\n            An Nx4 dimensional matrix of N measurements, each in\n            format (x, y, a, h) where (x, y) is the bounding box center\n            position, a the aspect ratio, and h the height.\n        only_position : Optional[bool]\n            If True, distance computation is done with respect to the bounding\n            box center position only.\n        Returns\n        -------\n        ndarray\n            Returns an array of length N, where the i-th element contains the\n            squared Mahalanobis distance between (mean, covariance) and\n            `measurements[i]`.\n        \"\"\"\n        mean, covariance = self.project(mean, covariance)\n        if only_position:\n            mean, covariance = mean[:2], covariance[:2, :2]\n            measurements = measurements[:, :2]\n\n        d = measurements - mean\n        if metric == 'gaussian':\n            return np.sum(d * d, axis=1)\n        elif metric == 'maha':\n            cholesky_factor = np.linalg.cholesky(covariance)\n            z = scipy.linalg.solve_triangular(cholesky_factor, d.T, lower=True, check_finite=False, overwrite_b=True)\n            return np.sum(z * z, axis=0)  # square maha\n        else:\n            raise ValueError('invalid distance metric')\n\n\nclass KalmanFilterXYWH:\n    \"\"\"\n    For BoT-SORT\n    A simple Kalman filter for tracking bounding boxes in image space.\n\n    The 8-dimensional state space\n\n        x, y, w, h, vx, vy, vw, vh\n\n    contains the bounding box center position (x, y), width w, height h,\n    and their respective velocities.\n\n    Object motion follows a constant velocity model. The bounding box location\n    (x, y, w, h) is taken as direct observation of the state space (linear\n    observation model).\n\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize Kalman filter model matrices with motion and observation uncertainties.\"\"\"\n        ndim, dt = 4, 1.\n\n        # Create Kalman filter model matrices.\n        self._motion_mat = np.eye(2 * ndim, 2 * ndim)\n        for i in range(ndim):\n            self._motion_mat[i, ndim + i] = dt\n        self._update_mat = np.eye(ndim, 2 * ndim)\n\n        # Motion and observation uncertainty are chosen relative to the current\n        # state estimate. These weights control the amount of uncertainty in\n        # the model. This is a bit hacky.\n        self._std_weight_position = 1. / 20\n        self._std_weight_velocity = 1. / 160\n\n    def initiate(self, measurement):\n        \"\"\"Create track from unassociated measurement.\n\n        Parameters\n        ----------\n        measurement : ndarray\n            Bounding box coordinates (x, y, w, h) with center position (x, y),\n            width w, and height h.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector (8 dimensional) and covariance matrix (8x8\n            dimensional) of the new track. Unobserved velocities are initialized\n            to 0 mean.\n\n        \"\"\"\n        mean_pos = measurement\n        mean_vel = np.zeros_like(mean_pos)\n        mean = np.r_[mean_pos, mean_vel]\n\n        std = [\n            2 * self._std_weight_position * measurement[2], 2 * self._std_weight_position * measurement[3],\n            2 * self._std_weight_position * measurement[2], 2 * self._std_weight_position * measurement[3],\n            10 * self._std_weight_velocity * measurement[2], 10 * self._std_weight_velocity * measurement[3],\n            10 * self._std_weight_velocity * measurement[2], 10 * self._std_weight_velocity * measurement[3]]\n        covariance = np.diag(np.square(std))\n        return mean, covariance\n\n    def predict(self, mean, covariance):\n        \"\"\"Run Kalman filter prediction step.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The 8 dimensional mean vector of the object state at the previous\n            time step.\n        covariance : ndarray\n            The 8x8 dimensional covariance matrix of the object state at the\n            previous time step.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector and covariance matrix of the predicted\n            state. Unobserved velocities are initialized to 0 mean.\n\n        \"\"\"\n        std_pos = [\n            self._std_weight_position * mean[2], self._std_weight_position * mean[3],\n            self._std_weight_position * mean[2], self._std_weight_position * mean[3]]\n        std_vel = [\n            self._std_weight_velocity * mean[2], self._std_weight_velocity * mean[3],\n            self._std_weight_velocity * mean[2], self._std_weight_velocity * mean[3]]\n        motion_cov = np.diag(np.square(np.r_[std_pos, std_vel]))\n\n        mean = np.dot(mean, self._motion_mat.T)\n        covariance = np.linalg.multi_dot((self._motion_mat, covariance, self._motion_mat.T)) + motion_cov\n\n        return mean, covariance\n\n    def project(self, mean, covariance):\n        \"\"\"Project state distribution to measurement space.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The state's mean vector (8 dimensional array).\n        covariance : ndarray\n            The state's covariance matrix (8x8 dimensional).\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the projected mean and covariance matrix of the given state\n            estimate.\n\n        \"\"\"\n        std = [\n            self._std_weight_position * mean[2], self._std_weight_position * mean[3],\n            self._std_weight_position * mean[2], self._std_weight_position * mean[3]]\n        innovation_cov = np.diag(np.square(std))\n\n        mean = np.dot(self._update_mat, mean)\n        covariance = np.linalg.multi_dot((self._update_mat, covariance, self._update_mat.T))\n        return mean, covariance + innovation_cov\n\n    def multi_predict(self, mean, covariance):\n        \"\"\"Run Kalman filter prediction step (Vectorized version).\n        Parameters\n        ----------\n        mean : ndarray\n            The Nx8 dimensional mean matrix of the object states at the previous\n            time step.\n        covariance : ndarray\n            The Nx8x8 dimensional covariance matrix of the object states at the\n            previous time step.\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector and covariance matrix of the predicted\n            state. Unobserved velocities are initialized to 0 mean.\n        \"\"\"\n        std_pos = [\n            self._std_weight_position * mean[:, 2], self._std_weight_position * mean[:, 3],\n            self._std_weight_position * mean[:, 2], self._std_weight_position * mean[:, 3]]\n        std_vel = [\n            self._std_weight_velocity * mean[:, 2], self._std_weight_velocity * mean[:, 3],\n            self._std_weight_velocity * mean[:, 2], self._std_weight_velocity * mean[:, 3]]\n        sqr = np.square(np.r_[std_pos, std_vel]).T\n\n        motion_cov = [np.diag(sqr[i]) for i in range(len(mean))]\n        motion_cov = np.asarray(motion_cov)\n\n        mean = np.dot(mean, self._motion_mat.T)\n        left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2))\n        covariance = np.dot(left, self._motion_mat.T) + motion_cov\n\n        return mean, covariance\n\n    def update(self, mean, covariance, measurement):\n        \"\"\"Run Kalman filter correction step.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The predicted state's mean vector (8 dimensional).\n        covariance : ndarray\n            The state's covariance matrix (8x8 dimensional).\n        measurement : ndarray\n            The 4 dimensional measurement vector (x, y, w, h), where (x, y)\n            is the center position, w the width, and h the height of the\n            bounding box.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the measurement-corrected state distribution.\n\n        \"\"\"\n        projected_mean, projected_cov = self.project(mean, covariance)\n\n        chol_factor, lower = scipy.linalg.cho_factor(projected_cov, lower=True, check_finite=False)\n        kalman_gain = scipy.linalg.cho_solve((chol_factor, lower),\n                                             np.dot(covariance, self._update_mat.T).T,\n                                             check_finite=False).T\n        innovation = measurement - projected_mean\n\n        new_mean = mean + np.dot(innovation, kalman_gain.T)\n        new_covariance = covariance - np.linalg.multi_dot((kalman_gain, projected_cov, kalman_gain.T))\n        return new_mean, new_covariance\n\n    def gating_distance(self, mean, covariance, measurements, only_position=False, metric='maha'):\n        \"\"\"Compute gating distance between state distribution and measurements.\n        A suitable distance threshold can be obtained from `chi2inv95`. If\n        `only_position` is False, the chi-square distribution has 4 degrees of\n        freedom, otherwise 2.\n        Parameters\n        ----------\n        mean : ndarray\n            Mean vector over the state distribution (8 dimensional).\n        covariance : ndarray\n            Covariance of the state distribution (8x8 dimensional).\n        measurements : ndarray\n            An Nx4 dimensional matrix of N measurements, each in\n            format (x, y, a, h) where (x, y) is the bounding box center\n            position, a the aspect ratio, and h the height.\n        only_position : Optional[bool]\n            If True, distance computation is done with respect to the bounding\n            box center position only.\n        Returns\n        -------\n        ndarray\n            Returns an array of length N, where the i-th element contains the\n            squared Mahalanobis distance between (mean, covariance) and\n            `measurements[i]`.\n        \"\"\"\n        mean, covariance = self.project(mean, covariance)\n        if only_position:\n            mean, covariance = mean[:2], covariance[:2, :2]\n            measurements = measurements[:, :2]\n\n        d = measurements - mean\n        if metric == 'gaussian':\n            return np.sum(d * d, axis=1)\n        elif metric == 'maha':\n            cholesky_factor = np.linalg.cholesky(covariance)\n            z = scipy.linalg.solve_triangular(cholesky_factor, d.T, lower=True, check_finite=False, overwrite_b=True)\n            return np.sum(z * z, axis=0)  # square maha\n        else:\n            raise ValueError('invalid distance metric')\n"
  },
  {
    "path": "ultralytics/tracker/utils/matching.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport numpy as np\nimport scipy\nfrom scipy.spatial.distance import cdist\n\nfrom .kalman_filter import chi2inv95\n\ntry:\n    import lap  # for linear_assignment\n\n    assert lap.__version__  # verify package is not directory\nexcept (ImportError, AssertionError, AttributeError):\n    from ultralytics.yolo.utils.checks import check_requirements\n\n    check_requirements('lap>=0.4')  # install\n    import lap\n\n\ndef merge_matches(m1, m2, shape):\n    \"\"\"Merge two sets of matches and return matched and unmatched indices.\"\"\"\n    O, P, Q = shape\n    m1 = np.asarray(m1)\n    m2 = np.asarray(m2)\n\n    M1 = scipy.sparse.coo_matrix((np.ones(len(m1)), (m1[:, 0], m1[:, 1])), shape=(O, P))\n    M2 = scipy.sparse.coo_matrix((np.ones(len(m2)), (m2[:, 0], m2[:, 1])), shape=(P, Q))\n\n    mask = M1 * M2\n    match = mask.nonzero()\n    match = list(zip(match[0], match[1]))\n    unmatched_O = tuple(set(range(O)) - {i for i, j in match})\n    unmatched_Q = tuple(set(range(Q)) - {j for i, j in match})\n\n    return match, unmatched_O, unmatched_Q\n\n\ndef _indices_to_matches(cost_matrix, indices, thresh):\n    \"\"\"_indices_to_matches: Return matched and unmatched indices given a cost matrix, indices, and a threshold.\"\"\"\n    matched_cost = cost_matrix[tuple(zip(*indices))]\n    matched_mask = (matched_cost <= thresh)\n\n    matches = indices[matched_mask]\n    unmatched_a = tuple(set(range(cost_matrix.shape[0])) - set(matches[:, 0]))\n    unmatched_b = tuple(set(range(cost_matrix.shape[1])) - set(matches[:, 1]))\n\n    return matches, unmatched_a, unmatched_b\n\n\ndef linear_assignment(cost_matrix, thresh, use_lap=True):\n    \"\"\"Linear assignment implementations with scipy and lap.lapjv.\"\"\"\n    if cost_matrix.size == 0:\n        return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))\n\n    if use_lap:\n        _, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh)\n        matches = [[ix, mx] for ix, mx in enumerate(x) if mx >= 0]\n        unmatched_a = np.where(x < 0)[0]\n        unmatched_b = np.where(y < 0)[0]\n    else:\n        # Scipy linear sum assignment is NOT working correctly, DO NOT USE\n        y, x = scipy.optimize.linear_sum_assignment(cost_matrix)  # row y, col x\n        matches = np.asarray([[i, x] for i, x in enumerate(x) if cost_matrix[i, x] <= thresh])\n        unmatched = np.ones(cost_matrix.shape)\n        for i, xi in matches:\n            unmatched[i, xi] = 0.0\n        unmatched_a = np.where(unmatched.all(1))[0]\n        unmatched_b = np.where(unmatched.all(0))[0]\n\n    return matches, unmatched_a, unmatched_b\n\n\ndef ious(atlbrs, btlbrs):\n    \"\"\"\n    Compute cost based on IoU\n    :type atlbrs: list[tlbr] | np.ndarray\n    :type atlbrs: list[tlbr] | np.ndarray\n\n    :rtype ious np.ndarray\n    \"\"\"\n    ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float32)\n    if ious.size == 0:\n        return ious\n\n    ious = bbox_ious(np.ascontiguousarray(atlbrs, dtype=np.float32), np.ascontiguousarray(btlbrs, dtype=np.float32))\n    return ious\n\n\ndef iou_distance(atracks, btracks):\n    \"\"\"\n    Compute cost based on IoU\n    :type atracks: list[STrack]\n    :type btracks: list[STrack]\n\n    :rtype cost_matrix np.ndarray\n    \"\"\"\n\n    if (len(atracks) > 0 and isinstance(atracks[0], np.ndarray)) \\\n            or (len(btracks) > 0 and isinstance(btracks[0], np.ndarray)):\n        atlbrs = atracks\n        btlbrs = btracks\n    else:\n        atlbrs = [track.tlbr for track in atracks]\n        btlbrs = [track.tlbr for track in btracks]\n    _ious = ious(atlbrs, btlbrs)\n    return 1 - _ious  # cost matrix\n\n\ndef v_iou_distance(atracks, btracks):\n    \"\"\"\n    Compute cost based on IoU\n    :type atracks: list[STrack]\n    :type btracks: list[STrack]\n\n    :rtype cost_matrix np.ndarray\n    \"\"\"\n\n    if (len(atracks) > 0 and isinstance(atracks[0], np.ndarray)) \\\n            or (len(btracks) > 0 and isinstance(btracks[0], np.ndarray)):\n        atlbrs = atracks\n        btlbrs = btracks\n    else:\n        atlbrs = [track.tlwh_to_tlbr(track.pred_bbox) for track in atracks]\n        btlbrs = [track.tlwh_to_tlbr(track.pred_bbox) for track in btracks]\n    _ious = ious(atlbrs, btlbrs)\n    return 1 - _ious  # cost matrix\n\n\ndef embedding_distance(tracks, detections, metric='cosine'):\n    \"\"\"\n    :param tracks: list[STrack]\n    :param detections: list[BaseTrack]\n    :param metric:\n    :return: cost_matrix np.ndarray\n    \"\"\"\n\n    cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float32)\n    if cost_matrix.size == 0:\n        return cost_matrix\n    det_features = np.asarray([track.curr_feat for track in detections], dtype=np.float32)\n    # for i, track in enumerate(tracks):\n    # cost_matrix[i, :] = np.maximum(0.0, cdist(track.smooth_feat.reshape(1,-1), det_features, metric))\n    track_features = np.asarray([track.smooth_feat for track in tracks], dtype=np.float32)\n    cost_matrix = np.maximum(0.0, cdist(track_features, det_features, metric))  # Normalized features\n    return cost_matrix\n\n\ndef gate_cost_matrix(kf, cost_matrix, tracks, detections, only_position=False):\n    \"\"\"Apply gating to the cost matrix based on predicted tracks and detected objects.\"\"\"\n    if cost_matrix.size == 0:\n        return cost_matrix\n    gating_dim = 2 if only_position else 4\n    gating_threshold = chi2inv95[gating_dim]\n    measurements = np.asarray([det.to_xyah() for det in detections])\n    for row, track in enumerate(tracks):\n        gating_distance = kf.gating_distance(track.mean, track.covariance, measurements, only_position)\n        cost_matrix[row, gating_distance > gating_threshold] = np.inf\n    return cost_matrix\n\n\ndef fuse_motion(kf, cost_matrix, tracks, detections, only_position=False, lambda_=0.98):\n    \"\"\"Fuse motion between tracks and detections with gating and Kalman filtering.\"\"\"\n    if cost_matrix.size == 0:\n        return cost_matrix\n    gating_dim = 2 if only_position else 4\n    gating_threshold = chi2inv95[gating_dim]\n    measurements = np.asarray([det.to_xyah() for det in detections])\n    for row, track in enumerate(tracks):\n        gating_distance = kf.gating_distance(track.mean, track.covariance, measurements, only_position, metric='maha')\n        cost_matrix[row, gating_distance > gating_threshold] = np.inf\n        cost_matrix[row] = lambda_ * cost_matrix[row] + (1 - lambda_) * gating_distance\n    return cost_matrix\n\n\ndef fuse_iou(cost_matrix, tracks, detections):\n    \"\"\"Fuses ReID and IoU similarity matrices to yield a cost matrix for object tracking.\"\"\"\n    if cost_matrix.size == 0:\n        return cost_matrix\n    reid_sim = 1 - cost_matrix\n    iou_dist = iou_distance(tracks, detections)\n    iou_sim = 1 - iou_dist\n    fuse_sim = reid_sim * (1 + iou_sim) / 2\n    # det_scores = np.array([det.score for det in detections])\n    # det_scores = np.expand_dims(det_scores, axis=0).repeat(cost_matrix.shape[0], axis=0)\n    return 1 - fuse_sim  # fuse cost\n\n\ndef fuse_score(cost_matrix, detections):\n    \"\"\"Fuses cost matrix with detection scores to produce a single similarity matrix.\"\"\"\n    if cost_matrix.size == 0:\n        return cost_matrix\n    iou_sim = 1 - cost_matrix\n    det_scores = np.array([det.score for det in detections])\n    det_scores = np.expand_dims(det_scores, axis=0).repeat(cost_matrix.shape[0], axis=0)\n    fuse_sim = iou_sim * det_scores\n    return 1 - fuse_sim  # fuse_cost\n\n\ndef bbox_ious(box1, box2, eps=1e-7):\n    \"\"\"\n    Calculate the Intersection over Union (IoU) between pairs of bounding boxes.\n\n    Args:\n        box1 (np.array): A numpy array of shape (n, 4) representing 'n' bounding boxes.\n                         Each row is in the format (x1, y1, x2, y2).\n        box2 (np.array): A numpy array of shape (m, 4) representing 'm' bounding boxes.\n                         Each row is in the format (x1, y1, x2, y2).\n        eps (float, optional): A small constant to prevent division by zero. Defaults to 1e-7.\n\n    Returns:\n        (np.array): A numpy array of shape (n, m) representing the IoU scores for each pair\n                    of bounding boxes from box1 and box2.\n\n    Note:\n        The bounding box coordinates are expected to be in the format (x1, y1, x2, y2).\n    \"\"\"\n\n    # Get the coordinates of bounding boxes\n    b1_x1, b1_y1, b1_x2, b1_y2 = box1.T\n    b2_x1, b2_y1, b2_x2, b2_y2 = box2.T\n\n    # Intersection area\n    inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * \\\n                 (np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)).clip(0)\n\n    # box2 area\n    box1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)\n    box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)\n    return inter_area / (box2_area + box1_area[:, None] - inter_area + eps)\n"
  },
  {
    "path": "ultralytics/vit/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .rtdetr import RTDETR\nfrom .sam import SAM\n\n__all__ = 'RTDETR', 'SAM'  # allow simpler import\n"
  },
  {
    "path": "ultralytics/vit/rtdetr/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .model import RTDETR\nfrom .predict import RTDETRPredictor\nfrom .val import RTDETRValidator\n\n__all__ = 'RTDETRPredictor', 'RTDETRValidator', 'RTDETR'\n"
  },
  {
    "path": "ultralytics/vit/rtdetr/model.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nRT-DETR model interface\n\"\"\"\n\nfrom pathlib import Path\n\nimport torch.nn as nn\n\nfrom ultralytics.nn.tasks import RTDETRDetectionModel, attempt_load_one_weight, yaml_model_load\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.engine.exporter import Exporter\nfrom ultralytics.yolo.utils import DEFAULT_CFG, DEFAULT_CFG_DICT, LOGGER, RANK, ROOT, is_git_dir\nfrom ultralytics.yolo.utils.checks import check_imgsz\nfrom ultralytics.yolo.utils.torch_utils import model_info, smart_inference_mode\n\nfrom .predict import RTDETRPredictor\nfrom .train import RTDETRTrainer\nfrom .val import RTDETRValidator\n\n\nclass RTDETR:\n\n    def __init__(self, model='rtdetr-l.pt') -> None:\n        if model and not model.endswith('.pt') and not model.endswith('.yaml'):\n            raise NotImplementedError('RT-DETR only supports creating from pt file or yaml file.')\n        # Load or create new YOLO model\n        self.predictor = None\n        self.ckpt = None\n        suffix = Path(model).suffix\n        if suffix == '.yaml':\n            self._new(model)\n        else:\n            self._load(model)\n\n    def _new(self, cfg: str, verbose=True):\n        cfg_dict = yaml_model_load(cfg)\n        self.cfg = cfg\n        self.task = 'detect'\n        self.model = RTDETRDetectionModel(cfg_dict, verbose=verbose)  # build model\n\n        # Below added to allow export from YAMLs\n        self.model.args = DEFAULT_CFG_DICT  # attach args to model\n        self.model.task = self.task\n\n    @smart_inference_mode()\n    def _load(self, weights: str):\n        self.model, self.ckpt = attempt_load_one_weight(weights)\n        self.model.args = DEFAULT_CFG_DICT  # attach args to model\n        self.task = self.model.args['task']\n\n    @smart_inference_mode()\n    def load(self, weights='yolov8n.pt'):\n        \"\"\"\n        Transfers parameters with matching names and shapes from 'weights' to model.\n        \"\"\"\n        if isinstance(weights, (str, Path)):\n            weights, self.ckpt = attempt_load_one_weight(weights)\n        self.model.load(weights)\n        return self\n\n    @smart_inference_mode()\n    def predict(self, source=None, stream=False, **kwargs):\n        \"\"\"\n        Perform prediction using the YOLO model.\n\n        Args:\n            source (str | int | PIL | np.ndarray): The source of the image to make predictions on.\n                          Accepts all source types accepted by the YOLO model.\n            stream (bool): Whether to stream the predictions or not. Defaults to False.\n            **kwargs : Additional keyword arguments passed to the predictor.\n                       Check the 'configuration' section in the documentation for all available options.\n\n        Returns:\n            (List[ultralytics.yolo.engine.results.Results]): The prediction results.\n        \"\"\"\n        if source is None:\n            source = ROOT / 'assets' if is_git_dir() else 'https://ultralytics.com/images/bus.jpg'\n            LOGGER.warning(f\"WARNING ⚠️ 'source' is missing. Using 'source={source}'.\")\n        overrides = dict(conf=0.25, task='detect', mode='predict')\n        overrides.update(kwargs)  # prefer kwargs\n        if not self.predictor:\n            self.predictor = RTDETRPredictor(overrides=overrides)\n            self.predictor.setup_model(model=self.model)\n        else:  # only update args if predictor is already setup\n            self.predictor.args = get_cfg(self.predictor.args, overrides)\n        return self.predictor(source, stream=stream)\n\n    def train(self, **kwargs):\n        \"\"\"\n        Trains the model on a given dataset.\n\n        Args:\n            **kwargs (Any): Any number of arguments representing the training configuration.\n        \"\"\"\n        overrides = dict(task='detect', mode='train')\n        overrides.update(kwargs)\n        overrides['deterministic'] = False\n        if not overrides.get('data'):\n            raise AttributeError(\"Dataset required but missing, i.e. pass 'data=coco128.yaml'\")\n        if overrides.get('resume'):\n            overrides['resume'] = self.ckpt_path\n        self.task = overrides.get('task') or self.task\n        self.trainer = RTDETRTrainer(overrides=overrides)\n        if not overrides.get('resume'):  # manually set model only if not resuming\n            self.trainer.model = self.trainer.get_model(weights=self.model if self.ckpt else None, cfg=self.model.yaml)\n            self.model = self.trainer.model\n        self.trainer.train()\n        # Update model and cfg after training\n        if RANK in (-1, 0):\n            self.model, _ = attempt_load_one_weight(str(self.trainer.best))\n            self.overrides = self.model.args\n            self.metrics = getattr(self.trainer.validator, 'metrics', None)  # TODO: no metrics returned by DDP\n\n    def val(self, **kwargs):\n        \"\"\"Run validation given dataset.\"\"\"\n        overrides = dict(task='detect', mode='val')\n        overrides.update(kwargs)  # prefer kwargs\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.imgsz = check_imgsz(args.imgsz, max_dim=1)\n        validator = RTDETRValidator(args=args)\n        validator(model=self.model)\n        self.metrics = validator.metrics\n        return validator.metrics\n\n    def info(self, verbose=True):\n        \"\"\"Get model info\"\"\"\n        return model_info(self.model, verbose=verbose)\n\n    def _check_is_pytorch_model(self):\n        \"\"\"\n        Raises TypeError is model is not a PyTorch model\n        \"\"\"\n        pt_str = isinstance(self.model, (str, Path)) and Path(self.model).suffix == '.pt'\n        pt_module = isinstance(self.model, nn.Module)\n        if not (pt_module or pt_str):\n            raise TypeError(f\"model='{self.model}' must be a *.pt PyTorch model, but is a different type. \"\n                            f'PyTorch models can be used to train, val, predict and export, i.e. '\n                            f\"'yolo export model=yolov8n.pt', but exported formats like ONNX, TensorRT etc. only \"\n                            f\"support 'predict' and 'val' modes, i.e. 'yolo predict model=yolov8n.onnx'.\")\n\n    def fuse(self):\n        \"\"\"Fuse PyTorch Conv2d and BatchNorm2d layers.\"\"\"\n        self._check_is_pytorch_model()\n        self.model.fuse()\n\n    @smart_inference_mode()\n    def export(self, **kwargs):\n        \"\"\"\n        Export model.\n\n        Args:\n            **kwargs : Any other args accepted by the predictors. To see all args check 'configuration' section in docs\n        \"\"\"\n        overrides = dict(task='detect')\n        overrides.update(kwargs)\n        overrides['mode'] = 'export'\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.task = self.task\n        if args.imgsz == DEFAULT_CFG.imgsz:\n            args.imgsz = self.model.args['imgsz']  # use trained imgsz unless custom value is passed\n        if args.batch == DEFAULT_CFG.batch:\n            args.batch = 1  # default to 1 if not modified\n        return Exporter(overrides=args)(model=self.model)\n\n    def __call__(self, source=None, stream=False, **kwargs):\n        \"\"\"Calls the 'predict' function with given arguments to perform object detection.\"\"\"\n        return self.predict(source, stream, **kwargs)\n\n    def __getattr__(self, attr):\n        \"\"\"Raises error if object has no requested attribute.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n"
  },
  {
    "path": "ultralytics/vit/rtdetr/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.data.augment import LetterBox\nfrom ultralytics.yolo.engine.predictor import BasePredictor\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import ops\n\n\nclass RTDETRPredictor(BasePredictor):\n\n    def postprocess(self, preds, img, orig_imgs):\n        \"\"\"Postprocess predictions and returns a list of Results objects.\"\"\"\n        bboxes, scores = preds[:2]  # (1, bs, 300, 4), (1, bs, 300, nc)\n        bboxes, scores = bboxes.squeeze_(0), scores.squeeze_(0)\n        results = []\n        for i, bbox in enumerate(bboxes):  # (300, 4)\n            bbox = ops.xywh2xyxy(bbox)\n            score, cls = scores[i].max(-1, keepdim=True)  # (300, 1)\n            idx = score.squeeze(-1) > self.args.conf  # (300, )\n            if self.args.classes is not None:\n                idx = (cls == torch.tensor(self.args.classes, device=cls.device)).any(1) & idx\n            pred = torch.cat([bbox, score, cls], dim=-1)[idx]  # filter\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            oh, ow = orig_img.shape[:2]\n            if not isinstance(orig_imgs, torch.Tensor):\n                pred[..., [0, 2]] *= ow\n                pred[..., [1, 3]] *= oh\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred))\n        return results\n\n    def pre_transform(self, im):\n        \"\"\"Pre-transform input image before inference.\n\n        Args:\n            im (List(np.ndarray)): (N, 3, h, w) for tensor, [(h, w, 3) x N] for list.\n\n        Return: A list of transformed imgs.\n        \"\"\"\n        # The size must be square(640) and scaleFilled.\n        return [LetterBox(self.imgsz, auto=False, scaleFill=True)(image=x) for x in im]\n"
  },
  {
    "path": "ultralytics/vit/rtdetr/train.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom copy import copy\n\nimport torch\n\nfrom ultralytics.nn.tasks import RTDETRDetectionModel\nfrom ultralytics.yolo.utils import DEFAULT_CFG, RANK, colorstr\nfrom ultralytics.yolo.v8.detect import DetectionTrainer\n\nfrom .val import RTDETRDataset, RTDETRValidator\n\n\nclass RTDETRTrainer(DetectionTrainer):\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Return a YOLO detection model.\"\"\"\n        model = RTDETRDetectionModel(cfg, nc=self.data['nc'], verbose=verbose and RANK == -1)\n        if weights:\n            model.load(weights)\n        return model\n\n    def build_dataset(self, img_path, mode='val', batch=None):\n        \"\"\"Build RTDETR Dataset\n\n        Args:\n            img_path (str): Path to the folder containing images.\n            mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.\n            batch (int, optional): Size of batches, this is for `rect`. Defaults to None.\n        \"\"\"\n        return RTDETRDataset(\n            img_path=img_path,\n            imgsz=self.args.imgsz,\n            batch_size=batch,\n            augment=mode == 'train',  # no augmentation\n            hyp=self.args,\n            rect=False,  # no rect\n            cache=self.args.cache or None,\n            prefix=colorstr(f'{mode}: '),\n            data=self.data)\n\n    def get_validator(self):\n        \"\"\"Returns a DetectionValidator for RTDETR model validation.\"\"\"\n        self.loss_names = 'giou_loss', 'cls_loss', 'l1_loss'\n        return RTDETRValidator(self.test_loader, save_dir=self.save_dir, args=copy(self.args))\n\n    def preprocess_batch(self, batch):\n        \"\"\"Preprocesses a batch of images by scaling and converting to float.\"\"\"\n        batch = super().preprocess_batch(batch)\n        bs = len(batch['img'])\n        batch_idx = batch['batch_idx']\n        gt_bbox, gt_class = [], []\n        for i in range(bs):\n            gt_bbox.append(batch['bboxes'][batch_idx == i].to(batch_idx.device))\n            gt_class.append(batch['cls'][batch_idx == i].to(device=batch_idx.device, dtype=torch.long))\n        return batch\n\n\ndef train(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Train and optimize RTDETR model given training data and device.\"\"\"\n    model = 'rtdetr-l.yaml'\n    data = cfg.data or 'coco128.yaml'  # or yolo.ClassificationDataset(\"mnist\")\n    device = cfg.device if cfg.device is not None else ''\n\n    # NOTE: F.grid_sample which is in rt-detr does not support deterministic=True\n    # NOTE: amp training causes nan outputs and end with error while doing bipartite graph matching\n    args = dict(model=model,\n                data=data,\n                device=device,\n                imgsz=640,\n                exist_ok=True,\n                batch=4,\n                deterministic=False,\n                amp=False)\n    trainer = RTDETRTrainer(overrides=args)\n    trainer.train()\n\n\nif __name__ == '__main__':\n    train()\n"
  },
  {
    "path": "ultralytics/vit/rtdetr/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport torch\n\nfrom ultralytics.yolo.data import YOLODataset\nfrom ultralytics.yolo.data.augment import Compose, Format, v8_transforms\nfrom ultralytics.yolo.utils import colorstr, ops\nfrom ultralytics.yolo.v8.detect import DetectionValidator\n\n__all__ = 'RTDETRValidator',  # tuple or list\n\n\n# TODO: Temporarily, RT-DETR does not need padding.\nclass RTDETRDataset(YOLODataset):\n\n    def __init__(self, *args, data=None, **kwargs):\n        super().__init__(*args, data=data, use_segments=False, use_keypoints=False, **kwargs)\n\n    # NOTE: add stretch version load_image for rtdetr mosaic\n    def load_image(self, i):\n        \"\"\"Loads 1 image from dataset index 'i', returns (im, resized hw).\"\"\"\n        im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i]\n        if im is None:  # not cached in RAM\n            if fn.exists():  # load npy\n                im = np.load(fn)\n            else:  # read image\n                im = cv2.imread(f)  # BGR\n                if im is None:\n                    raise FileNotFoundError(f'Image Not Found {f}')\n            h0, w0 = im.shape[:2]  # orig hw\n            im = cv2.resize(im, (self.imgsz, self.imgsz), interpolation=cv2.INTER_LINEAR)\n\n            # Add to buffer if training with augmentations\n            if self.augment:\n                self.ims[i], self.im_hw0[i], self.im_hw[i] = im, (h0, w0), im.shape[:2]  # im, hw_original, hw_resized\n                self.buffer.append(i)\n                if len(self.buffer) >= self.max_buffer_length:\n                    j = self.buffer.pop(0)\n                    self.ims[j], self.im_hw0[j], self.im_hw[j] = None, None, None\n\n            return im, (h0, w0), im.shape[:2]\n\n        return self.ims[i], self.im_hw0[i], self.im_hw[i]\n\n    def build_transforms(self, hyp=None):\n        \"\"\"Temporarily, only for evaluation.\"\"\"\n        if self.augment:\n            hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0\n            hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0\n            transforms = v8_transforms(self, self.imgsz, hyp, stretch=True)\n        else:\n            # transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), auto=False, scaleFill=True)])\n            transforms = Compose([])\n        transforms.append(\n            Format(bbox_format='xywh',\n                   normalize=True,\n                   return_mask=self.use_segments,\n                   return_keypoint=self.use_keypoints,\n                   batch_idx=True,\n                   mask_ratio=hyp.mask_ratio,\n                   mask_overlap=hyp.overlap_mask))\n        return transforms\n\n\nclass RTDETRValidator(DetectionValidator):\n\n    def build_dataset(self, img_path, mode='val', batch=None):\n        \"\"\"Build YOLO Dataset\n\n        Args:\n            img_path (str): Path to the folder containing images.\n            mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.\n            batch (int, optional): Size of batches, this is for `rect`. Defaults to None.\n        \"\"\"\n        return RTDETRDataset(\n            img_path=img_path,\n            imgsz=self.args.imgsz,\n            batch_size=batch,\n            augment=False,  # no augmentation\n            hyp=self.args,\n            rect=False,  # no rect\n            cache=self.args.cache or None,\n            prefix=colorstr(f'{mode}: '),\n            data=self.data)\n\n    def postprocess(self, preds):\n        \"\"\"Apply Non-maximum suppression to prediction outputs.\"\"\"\n        bboxes, scores = preds[:2]  # (1, bs, 300, 4), (1, bs, 300, nc)\n        bboxes, scores = bboxes.squeeze_(0), scores.squeeze_(0)  # (bs, 300, 4)\n        bs = len(bboxes)\n        outputs = [torch.zeros((0, 6), device=bboxes.device)] * bs\n        for i, bbox in enumerate(bboxes):  # (300, 4)\n            bbox = ops.xywh2xyxy(bbox)\n            score, cls = scores[i].max(-1)  # (300, )\n            # Do not need threshold for evaluation as only got 300 boxes here.\n            # idx = score > self.args.conf\n            pred = torch.cat([bbox, score[..., None], cls[..., None]], dim=-1)  # filter\n            # sort by confidence to correctly get internal metrics.\n            pred = pred[score.argsort(descending=True)]\n            outputs[i] = pred  # [idx]\n\n        return outputs\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Metrics.\"\"\"\n        for si, pred in enumerate(preds):\n            idx = batch['batch_idx'] == si\n            cls = batch['cls'][idx]\n            bbox = batch['bboxes'][idx]\n            nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n            shape = batch['ori_shape'][si]\n            correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            self.seen += 1\n\n            if npr == 0:\n                if nl:\n                    self.stats.append((correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))\n                    if self.args.plots:\n                        self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))\n                continue\n\n            # Predictions\n            if self.args.single_cls:\n                pred[:, 5] = 0\n            predn = pred.clone()\n            predn[..., [0, 2]] *= shape[1]  # native-space pred\n            predn[..., [1, 3]] *= shape[0]  # native-space pred\n\n            # Evaluate\n            if nl:\n                tbox = ops.xywh2xyxy(bbox)  # target boxes\n                tbox[..., [0, 2]] *= shape[1]  # native-space pred\n                tbox[..., [1, 3]] *= shape[0]  # native-space pred\n                labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                # NOTE: To get correct metrics, the inputs of `_process_batch` should always be float32 type.\n                correct_bboxes = self._process_batch(predn.float(), labelsn)\n                # TODO: maybe remove these `self.` arguments as they already are member variable\n                if self.args.plots:\n                    self.confusion_matrix.process_batch(predn, labelsn)\n            self.stats.append((correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1)))  # (conf, pcls, tcls)\n\n            # Save\n            if self.args.save_json:\n                self.pred_to_json(predn, batch['im_file'][si])\n            if self.args.save_txt:\n                file = self.save_dir / 'labels' / f'{Path(batch[\"im_file\"][si]).stem}.txt'\n                self.save_one_txt(predn, self.args.save_conf, shape, file)\n"
  },
  {
    "path": "ultralytics/vit/sam/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .build import build_sam  # noqa\nfrom .model import SAM  # noqa\nfrom .modules.prompt_predictor import PromptPredictor  # noqa\n"
  },
  {
    "path": "ultralytics/vit/sam/amg.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport math\nfrom copy import deepcopy\nfrom itertools import product\nfrom typing import Any, Dict, Generator, ItemsView, List, Tuple\n\nimport numpy as np\nimport torch\n\n\nclass MaskData:\n    \"\"\"\n    A structure for storing masks and their related data in batched format.\n    Implements basic filtering and concatenation.\n    \"\"\"\n\n    def __init__(self, **kwargs) -> None:\n        \"\"\"Initialize a MaskData object, ensuring all values are supported types.\"\"\"\n        for v in kwargs.values():\n            assert isinstance(\n                v, (list, np.ndarray, torch.Tensor)), 'MaskData only supports list, numpy arrays, and torch tensors.'\n        self._stats = dict(**kwargs)\n\n    def __setitem__(self, key: str, item: Any) -> None:\n        \"\"\"Set an item in the MaskData object, ensuring it is a supported type.\"\"\"\n        assert isinstance(\n            item, (list, np.ndarray, torch.Tensor)), 'MaskData only supports list, numpy arrays, and torch tensors.'\n        self._stats[key] = item\n\n    def __delitem__(self, key: str) -> None:\n        \"\"\"Delete an item from the MaskData object.\"\"\"\n        del self._stats[key]\n\n    def __getitem__(self, key: str) -> Any:\n        \"\"\"Get an item from the MaskData object.\"\"\"\n        return self._stats[key]\n\n    def items(self) -> ItemsView[str, Any]:\n        \"\"\"Return an ItemsView of the MaskData object.\"\"\"\n        return self._stats.items()\n\n    def filter(self, keep: torch.Tensor) -> None:\n        \"\"\"Filter the MaskData object based on the given boolean tensor.\"\"\"\n        for k, v in self._stats.items():\n            if v is None:\n                self._stats[k] = None\n            elif isinstance(v, torch.Tensor):\n                self._stats[k] = v[torch.as_tensor(keep, device=v.device)]\n            elif isinstance(v, np.ndarray):\n                self._stats[k] = v[keep.detach().cpu().numpy()]\n            elif isinstance(v, list) and keep.dtype == torch.bool:\n                self._stats[k] = [a for i, a in enumerate(v) if keep[i]]\n            elif isinstance(v, list):\n                self._stats[k] = [v[i] for i in keep]\n            else:\n                raise TypeError(f'MaskData key {k} has an unsupported type {type(v)}.')\n\n    def cat(self, new_stats: 'MaskData') -> None:\n        \"\"\"Concatenate a new MaskData object to the current one.\"\"\"\n        for k, v in new_stats.items():\n            if k not in self._stats or self._stats[k] is None:\n                self._stats[k] = deepcopy(v)\n            elif isinstance(v, torch.Tensor):\n                self._stats[k] = torch.cat([self._stats[k], v], dim=0)\n            elif isinstance(v, np.ndarray):\n                self._stats[k] = np.concatenate([self._stats[k], v], axis=0)\n            elif isinstance(v, list):\n                self._stats[k] = self._stats[k] + deepcopy(v)\n            else:\n                raise TypeError(f'MaskData key {k} has an unsupported type {type(v)}.')\n\n    def to_numpy(self) -> None:\n        \"\"\"Convert all torch tensors in the MaskData object to numpy arrays.\"\"\"\n        for k, v in self._stats.items():\n            if isinstance(v, torch.Tensor):\n                self._stats[k] = v.detach().cpu().numpy()\n\n\ndef is_box_near_crop_edge(boxes: torch.Tensor,\n                          crop_box: List[int],\n                          orig_box: List[int],\n                          atol: float = 20.0) -> torch.Tensor:\n    \"\"\"Return a boolean tensor indicating if boxes are near the crop edge.\"\"\"\n    crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)\n    orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)\n    boxes = uncrop_boxes_xyxy(boxes, crop_box).float()\n    near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)\n    near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)\n    near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)\n    return torch.any(near_crop_edge, dim=1)\n\n\ndef box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor:\n    \"\"\"Convert bounding boxes from XYXY format to XYWH format.\"\"\"\n    box_xywh = deepcopy(box_xyxy)\n    box_xywh[2] = box_xywh[2] - box_xywh[0]\n    box_xywh[3] = box_xywh[3] - box_xywh[1]\n    return box_xywh\n\n\ndef batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]:\n    \"\"\"Yield batches of data from the input arguments.\"\"\"\n    assert args and all(len(a) == len(args[0]) for a in args), 'Batched iteration must have same-size inputs.'\n    n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0)\n    for b in range(n_batches):\n        yield [arg[b * batch_size:(b + 1) * batch_size] for arg in args]\n\n\ndef mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]:\n    \"\"\"Encode masks as uncompressed RLEs in the format expected by pycocotools.\"\"\"\n    # Put in fortran order and flatten h,w\n    b, h, w = tensor.shape\n    tensor = tensor.permute(0, 2, 1).flatten(1)\n\n    # Compute change indices\n    diff = tensor[:, 1:] ^ tensor[:, :-1]\n    change_indices = diff.nonzero()\n\n    # Encode run length\n    out = []\n    for i in range(b):\n        cur_idxs = change_indices[change_indices[:, 0] == i, 1]\n        cur_idxs = torch.cat([\n            torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device),\n            cur_idxs + 1,\n            torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device), ])\n        btw_idxs = cur_idxs[1:] - cur_idxs[:-1]\n        counts = [] if tensor[i, 0] == 0 else [0]\n        counts.extend(btw_idxs.detach().cpu().tolist())\n        out.append({'size': [h, w], 'counts': counts})\n    return out\n\n\ndef rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:\n    \"\"\"Compute a binary mask from an uncompressed RLE.\"\"\"\n    h, w = rle['size']\n    mask = np.empty(h * w, dtype=bool)\n    idx = 0\n    parity = False\n    for count in rle['counts']:\n        mask[idx:idx + count] = parity\n        idx += count\n        parity ^= True\n    mask = mask.reshape(w, h)\n    return mask.transpose()  # Put in C order\n\n\ndef area_from_rle(rle: Dict[str, Any]) -> int:\n    \"\"\"Calculate the area of a mask from its uncompressed RLE.\"\"\"\n    return sum(rle['counts'][1::2])\n\n\ndef calculate_stability_score(masks: torch.Tensor, mask_threshold: float, threshold_offset: float) -> torch.Tensor:\n    \"\"\"\n    Computes the stability score for a batch of masks. The stability\n    score is the IoU between the binary masks obtained by thresholding\n    the predicted mask logits at high and low values.\n    \"\"\"\n    # One mask is always contained inside the other.\n    # Save memory by preventing unnecessary cast to torch.int64\n    intersections = ((masks > (mask_threshold + threshold_offset)).sum(-1, dtype=torch.int16).sum(-1,\n                                                                                                  dtype=torch.int32))\n    unions = ((masks > (mask_threshold - threshold_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32))\n    return intersections / unions\n\n\ndef build_point_grid(n_per_side: int) -> np.ndarray:\n    \"\"\"Generate a 2D grid of evenly spaced points in the range [0,1]x[0,1].\"\"\"\n    offset = 1 / (2 * n_per_side)\n    points_one_side = np.linspace(offset, 1 - offset, n_per_side)\n    points_x = np.tile(points_one_side[None, :], (n_per_side, 1))\n    points_y = np.tile(points_one_side[:, None], (1, n_per_side))\n    return np.stack([points_x, points_y], axis=-1).reshape(-1, 2)\n\n\ndef build_all_layer_point_grids(n_per_side: int, n_layers: int, scale_per_layer: int) -> List[np.ndarray]:\n    \"\"\"Generate point grids for all crop layers.\"\"\"\n    return [build_point_grid(int(n_per_side / (scale_per_layer ** i))) for i in range(n_layers + 1)]\n\n\ndef generate_crop_boxes(im_size: Tuple[int, ...], n_layers: int,\n                        overlap_ratio: float) -> Tuple[List[List[int]], List[int]]:\n    \"\"\"Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.\"\"\"\n    crop_boxes, layer_idxs = [], []\n    im_h, im_w = im_size\n    short_side = min(im_h, im_w)\n\n    # Original image\n    crop_boxes.append([0, 0, im_w, im_h])\n    layer_idxs.append(0)\n\n    def crop_len(orig_len, n_crops, overlap):\n        \"\"\"Crops bounding boxes to the size of the input image.\"\"\"\n        return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops))\n\n    for i_layer in range(n_layers):\n        n_crops_per_side = 2 ** (i_layer + 1)\n        overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))\n\n        crop_w = crop_len(im_w, n_crops_per_side, overlap)\n        crop_h = crop_len(im_h, n_crops_per_side, overlap)\n\n        crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)]\n        crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)]\n\n        # Crops in XYWH format\n        for x0, y0 in product(crop_box_x0, crop_box_y0):\n            box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)]\n            crop_boxes.append(box)\n            layer_idxs.append(i_layer + 1)\n\n    return crop_boxes, layer_idxs\n\n\ndef uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor:\n    \"\"\"Uncrop bounding boxes by adding the crop box offset.\"\"\"\n    x0, y0, _, _ = crop_box\n    offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device)\n    # Check if boxes has a channel dimension\n    if len(boxes.shape) == 3:\n        offset = offset.unsqueeze(1)\n    return boxes + offset\n\n\ndef uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor:\n    \"\"\"Uncrop points by adding the crop box offset.\"\"\"\n    x0, y0, _, _ = crop_box\n    offset = torch.tensor([[x0, y0]], device=points.device)\n    # Check if points has a channel dimension\n    if len(points.shape) == 3:\n        offset = offset.unsqueeze(1)\n    return points + offset\n\n\ndef uncrop_masks(masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int) -> torch.Tensor:\n    \"\"\"Uncrop masks by padding them to the original image size.\"\"\"\n    x0, y0, x1, y1 = crop_box\n    if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h:\n        return masks\n    # Coordinate transform masks\n    pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0)\n    pad = (x0, pad_x - x0, y0, pad_y - y0)\n    return torch.nn.functional.pad(masks, pad, value=0)\n\n\ndef remove_small_regions(mask: np.ndarray, area_thresh: float, mode: str) -> Tuple[np.ndarray, bool]:\n    \"\"\"Remove small disconnected regions or holes in a mask, returning the mask and a modification indicator.\"\"\"\n    import cv2  # type: ignore\n\n    assert mode in {'holes', 'islands'}\n    correct_holes = mode == 'holes'\n    working_mask = (correct_holes ^ mask).astype(np.uint8)\n    n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8)\n    sizes = stats[:, -1][1:]  # Row 0 is background label\n    small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh]\n    if not small_regions:\n        return mask, False\n    fill_labels = [0] + small_regions\n    if not correct_holes:\n        # If every region is below threshold, keep largest\n        fill_labels = [i for i in range(n_labels) if i not in fill_labels] or [int(np.argmax(sizes)) + 1]\n    mask = np.isin(regions, fill_labels)\n    return mask, True\n\n\ndef coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]:\n    \"\"\"Encode uncompressed RLE (run-length encoding) to COCO RLE format.\"\"\"\n    from pycocotools import mask as mask_utils  # type: ignore\n\n    h, w = uncompressed_rle['size']\n    rle = mask_utils.frPyObjects(uncompressed_rle, h, w)\n    rle['counts'] = rle['counts'].decode('utf-8')  # Necessary to serialize with json\n    return rle\n\n\ndef batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor:\n    \"\"\"\n    Calculates boxes in XYXY format around masks. Return [0,0,0,0] for\n    an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.\n    \"\"\"\n    # torch.max below raises an error on empty inputs, just skip in this case\n    if torch.numel(masks) == 0:\n        return torch.zeros(*masks.shape[:-2], 4, device=masks.device)\n\n    # Normalize shape to CxHxW\n    shape = masks.shape\n    h, w = shape[-2:]\n    masks = masks.flatten(0, -3) if len(shape) > 2 else masks.unsqueeze(0)\n    # Get top and bottom edges\n    in_height, _ = torch.max(masks, dim=-1)\n    in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :]\n    bottom_edges, _ = torch.max(in_height_coords, dim=-1)\n    in_height_coords = in_height_coords + h * (~in_height)\n    top_edges, _ = torch.min(in_height_coords, dim=-1)\n\n    # Get left and right edges\n    in_width, _ = torch.max(masks, dim=-2)\n    in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :]\n    right_edges, _ = torch.max(in_width_coords, dim=-1)\n    in_width_coords = in_width_coords + w * (~in_width)\n    left_edges, _ = torch.min(in_width_coords, dim=-1)\n\n    # If the mask is empty the right edge will be to the left of the left edge.\n    # Replace these boxes with [0, 0, 0, 0]\n    empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)\n    out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)\n    out = out * (~empty_filter).unsqueeze(-1)\n\n    # Return to original shape\n    return out.reshape(*shape[:-2], 4) if len(shape) > 2 else out[0]\n"
  },
  {
    "path": "ultralytics/vit/sam/autosize.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom copy import deepcopy\nfrom typing import Tuple\n\nimport numpy as np\nimport torch\nfrom torch.nn import functional as F\nfrom torchvision.transforms.functional import resize, to_pil_image  # type: ignore\n\n\nclass ResizeLongestSide:\n    \"\"\"\n    Resizes images to the longest side 'target_length', as well as provides\n    methods for resizing coordinates and boxes. Provides methods for\n    transforming both numpy array and batched torch tensors.\n    \"\"\"\n\n    def __init__(self, target_length: int) -> None:\n        self.target_length = target_length\n\n    def apply_image(self, image: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Expects a numpy array with shape HxWxC in uint8 format.\n        \"\"\"\n        target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length)\n        return np.array(resize(to_pil_image(image), target_size))\n\n    def apply_coords(self, coords: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:\n        \"\"\"\n        Expects a numpy array of length 2 in the final dimension. Requires the\n        original image size in (H, W) format.\n        \"\"\"\n        old_h, old_w = original_size\n        new_h, new_w = self.get_preprocess_shape(original_size[0], original_size[1], self.target_length)\n        coords = deepcopy(coords).astype(float)\n        coords[..., 0] = coords[..., 0] * (new_w / old_w)\n        coords[..., 1] = coords[..., 1] * (new_h / old_h)\n        return coords\n\n    def apply_boxes(self, boxes: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:\n        \"\"\"\n        Expects a numpy array shape Bx4. Requires the original image size\n        in (H, W) format.\n        \"\"\"\n        boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size)\n        return boxes.reshape(-1, 4)\n\n    def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor:\n        \"\"\"\n        Expects batched images with shape BxCxHxW and float format. This\n        transformation may not exactly match apply_image. apply_image is\n        the transformation expected by the model.\n        \"\"\"\n        # Expects an image in BCHW format. May not exactly match apply_image.\n        target_size = self.get_preprocess_shape(image.shape[2], image.shape[3], self.target_length)\n        return F.interpolate(image, target_size, mode='bilinear', align_corners=False, antialias=True)\n\n    def apply_coords_torch(self, coords: torch.Tensor, original_size: Tuple[int, ...]) -> torch.Tensor:\n        \"\"\"\n        Expects a torch tensor with length 2 in the last dimension. Requires the\n        original image size in (H, W) format.\n        \"\"\"\n        old_h, old_w = original_size\n        new_h, new_w = self.get_preprocess_shape(original_size[0], original_size[1], self.target_length)\n        coords = deepcopy(coords).to(torch.float)\n        coords[..., 0] = coords[..., 0] * (new_w / old_w)\n        coords[..., 1] = coords[..., 1] * (new_h / old_h)\n        return coords\n\n    def apply_boxes_torch(self, boxes: torch.Tensor, original_size: Tuple[int, ...]) -> torch.Tensor:\n        \"\"\"\n        Expects a torch tensor with shape Bx4. Requires the original image\n        size in (H, W) format.\n        \"\"\"\n        boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size)\n        return boxes.reshape(-1, 4)\n\n    @staticmethod\n    def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]:\n        \"\"\"\n        Compute the output size given input size and target long side length.\n        \"\"\"\n        scale = long_side_length * 1.0 / max(oldh, oldw)\n        newh, neww = oldh * scale, oldw * scale\n        neww = int(neww + 0.5)\n        newh = int(newh + 0.5)\n        return (newh, neww)\n"
  },
  {
    "path": "ultralytics/vit/sam/build.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom functools import partial\n\nimport torch\n\nfrom ...yolo.utils.downloads import attempt_download_asset\nfrom .modules.decoders import MaskDecoder\nfrom .modules.encoders import ImageEncoderViT, PromptEncoder\nfrom .modules.sam import Sam\nfrom .modules.transformer import TwoWayTransformer\n\n\ndef build_sam_vit_h(checkpoint=None):\n    \"\"\"Build and return a Segment Anything Model (SAM) h-size model.\"\"\"\n    return _build_sam(\n        encoder_embed_dim=1280,\n        encoder_depth=32,\n        encoder_num_heads=16,\n        encoder_global_attn_indexes=[7, 15, 23, 31],\n        checkpoint=checkpoint,\n    )\n\n\ndef build_sam_vit_l(checkpoint=None):\n    \"\"\"Build and return a Segment Anything Model (SAM) l-size model.\"\"\"\n    return _build_sam(\n        encoder_embed_dim=1024,\n        encoder_depth=24,\n        encoder_num_heads=16,\n        encoder_global_attn_indexes=[5, 11, 17, 23],\n        checkpoint=checkpoint,\n    )\n\n\ndef build_sam_vit_b(checkpoint=None):\n    \"\"\"Build and return a Segment Anything Model (SAM) b-size model.\"\"\"\n    return _build_sam(\n        encoder_embed_dim=768,\n        encoder_depth=12,\n        encoder_num_heads=12,\n        encoder_global_attn_indexes=[2, 5, 8, 11],\n        checkpoint=checkpoint,\n    )\n\n\ndef _build_sam(\n    encoder_embed_dim,\n    encoder_depth,\n    encoder_num_heads,\n    encoder_global_attn_indexes,\n    checkpoint=None,\n):\n    \"\"\"Builds the selected SAM model architecture.\"\"\"\n    prompt_embed_dim = 256\n    image_size = 1024\n    vit_patch_size = 16\n    image_embedding_size = image_size // vit_patch_size\n    sam = Sam(\n        image_encoder=ImageEncoderViT(\n            depth=encoder_depth,\n            embed_dim=encoder_embed_dim,\n            img_size=image_size,\n            mlp_ratio=4,\n            norm_layer=partial(torch.nn.LayerNorm, eps=1e-6),\n            num_heads=encoder_num_heads,\n            patch_size=vit_patch_size,\n            qkv_bias=True,\n            use_rel_pos=True,\n            global_attn_indexes=encoder_global_attn_indexes,\n            window_size=14,\n            out_chans=prompt_embed_dim,\n        ),\n        prompt_encoder=PromptEncoder(\n            embed_dim=prompt_embed_dim,\n            image_embedding_size=(image_embedding_size, image_embedding_size),\n            input_image_size=(image_size, image_size),\n            mask_in_chans=16,\n        ),\n        mask_decoder=MaskDecoder(\n            num_multimask_outputs=3,\n            transformer=TwoWayTransformer(\n                depth=2,\n                embedding_dim=prompt_embed_dim,\n                mlp_dim=2048,\n                num_heads=8,\n            ),\n            transformer_dim=prompt_embed_dim,\n            iou_head_depth=3,\n            iou_head_hidden_dim=256,\n        ),\n        pixel_mean=[123.675, 116.28, 103.53],\n        pixel_std=[58.395, 57.12, 57.375],\n    )\n    sam.eval()\n    if checkpoint is not None:\n        attempt_download_asset(checkpoint)\n        with open(checkpoint, 'rb') as f:\n            state_dict = torch.load(f)\n        sam.load_state_dict(state_dict)\n    return sam\n\n\nsam_model_map = {\n    # \"default\": build_sam_vit_h,\n    'sam_h.pt': build_sam_vit_h,\n    'sam_l.pt': build_sam_vit_l,\n    'sam_b.pt': build_sam_vit_b, }\n\n\ndef build_sam(ckpt='sam_b.pt'):\n    \"\"\"Build a SAM model specified by ckpt.\"\"\"\n    model_builder = None\n    for k in sam_model_map.keys():\n        if ckpt.endswith(k):\n            model_builder = sam_model_map.get(k)\n\n    if not model_builder:\n        raise FileNotFoundError(f'{ckpt} is not a supported sam model. Available models are: \\n {sam_model_map.keys()}')\n\n    return model_builder(ckpt)\n"
  },
  {
    "path": "ultralytics/vit/sam/model.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nSAM model interface\n\"\"\"\n\nfrom ultralytics.yolo.cfg import get_cfg\n\nfrom ...yolo.utils.torch_utils import model_info\nfrom .build import build_sam\nfrom .predict import Predictor\n\n\nclass SAM:\n\n    def __init__(self, model='sam_b.pt') -> None:\n        if model and not model.endswith('.pt') and not model.endswith('.pth'):\n            # Should raise AssertionError instead?\n            raise NotImplementedError('Segment anything prediction requires pre-trained checkpoint')\n        self.model = build_sam(model)\n        self.task = 'segment'  # required\n        self.predictor = None  # reuse predictor\n\n    def predict(self, source, stream=False, **kwargs):\n        \"\"\"Predicts and returns segmentation masks for given image or video source.\"\"\"\n        overrides = dict(conf=0.25, task='segment', mode='predict')\n        overrides.update(kwargs)  # prefer kwargs\n        if not self.predictor:\n            self.predictor = Predictor(overrides=overrides)\n            self.predictor.setup_model(model=self.model)\n        else:  # only update args if predictor is already setup\n            self.predictor.args = get_cfg(self.predictor.args, overrides)\n        return self.predictor(source, stream=stream)\n\n    def train(self, **kwargs):\n        \"\"\"Function trains models but raises an error as SAM models do not support training.\"\"\"\n        raise NotImplementedError(\"SAM models don't support training\")\n\n    def val(self, **kwargs):\n        \"\"\"Run validation given dataset.\"\"\"\n        raise NotImplementedError(\"SAM models don't support validation\")\n\n    def __call__(self, source=None, stream=False, **kwargs):\n        \"\"\"Calls the 'predict' function with given arguments to perform object detection.\"\"\"\n        return self.predict(source, stream, **kwargs)\n\n    def __getattr__(self, attr):\n        \"\"\"Raises error if object has no requested attribute.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n\n    def info(self, detailed=False, verbose=True):\n        \"\"\"\n        Logs model info.\n\n        Args:\n            detailed (bool): Show detailed information about model.\n            verbose (bool): Controls verbosity.\n        \"\"\"\n        return model_info(self.model, detailed=detailed, verbose=verbose)\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/decoders.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom typing import List, Tuple, Type\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom ultralytics.nn.modules import LayerNorm2d\n\n\nclass MaskDecoder(nn.Module):\n\n    def __init__(\n        self,\n        *,\n        transformer_dim: int,\n        transformer: nn.Module,\n        num_multimask_outputs: int = 3,\n        activation: Type[nn.Module] = nn.GELU,\n        iou_head_depth: int = 3,\n        iou_head_hidden_dim: int = 256,\n    ) -> None:\n        \"\"\"\n        Predicts masks given an image and prompt embeddings, using a transformer architecture.\n\n        Arguments:\n            transformer_dim (int): the channel dimension of the transformer module\n            transformer (nn.Module): the transformer used to predict masks\n            num_multimask_outputs (int): the number of masks to predict when disambiguating masks\n            activation (nn.Module): the type of activation to use when upscaling masks\n            iou_head_depth (int): the depth of the MLP used to predict mask quality\n            iou_head_hidden_dim (int): the hidden dimension of the MLP used to predict mask quality\n        \"\"\"\n        super().__init__()\n        self.transformer_dim = transformer_dim\n        self.transformer = transformer\n\n        self.num_multimask_outputs = num_multimask_outputs\n\n        self.iou_token = nn.Embedding(1, transformer_dim)\n        self.num_mask_tokens = num_multimask_outputs + 1\n        self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)\n\n        self.output_upscaling = nn.Sequential(\n            nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),\n            LayerNorm2d(transformer_dim // 4),\n            activation(),\n            nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),\n            activation(),\n        )\n        self.output_hypernetworks_mlps = nn.ModuleList([\n            MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) for _ in range(self.num_mask_tokens)])\n\n        self.iou_prediction_head = MLP(transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth)\n\n    def forward(\n        self,\n        image_embeddings: torch.Tensor,\n        image_pe: torch.Tensor,\n        sparse_prompt_embeddings: torch.Tensor,\n        dense_prompt_embeddings: torch.Tensor,\n        multimask_output: bool,\n    ) -> Tuple[torch.Tensor, torch.Tensor]:\n        \"\"\"\n        Predict masks given image and prompt embeddings.\n\n        Arguments:\n            image_embeddings (torch.Tensor): the embeddings from the image encoder\n            image_pe (torch.Tensor): positional encoding with the shape of image_embeddings\n            sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes\n            dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs\n            multimask_output (bool): Whether to return multiple masks or a single mask.\n\n        Returns:\n            torch.Tensor: batched predicted masks\n            torch.Tensor: batched predictions of mask quality\n        \"\"\"\n        masks, iou_pred = self.predict_masks(\n            image_embeddings=image_embeddings,\n            image_pe=image_pe,\n            sparse_prompt_embeddings=sparse_prompt_embeddings,\n            dense_prompt_embeddings=dense_prompt_embeddings,\n        )\n\n        # Select the correct mask or masks for output\n        mask_slice = slice(1, None) if multimask_output else slice(0, 1)\n        masks = masks[:, mask_slice, :, :]\n        iou_pred = iou_pred[:, mask_slice]\n\n        # Prepare output\n        return masks, iou_pred\n\n    def predict_masks(\n        self,\n        image_embeddings: torch.Tensor,\n        image_pe: torch.Tensor,\n        sparse_prompt_embeddings: torch.Tensor,\n        dense_prompt_embeddings: torch.Tensor,\n    ) -> Tuple[torch.Tensor, torch.Tensor]:\n        \"\"\"Predicts masks. See 'forward' for more details.\"\"\"\n        # Concatenate output tokens\n        output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)\n        output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)\n        tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)\n\n        # Expand per-image data in batch direction to be per-mask\n        src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)\n        src = src + dense_prompt_embeddings\n        pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)\n        b, c, h, w = src.shape\n\n        # Run the transformer\n        hs, src = self.transformer(src, pos_src, tokens)\n        iou_token_out = hs[:, 0, :]\n        mask_tokens_out = hs[:, 1:(1 + self.num_mask_tokens), :]\n\n        # Upscale mask embeddings and predict masks using the mask tokens\n        src = src.transpose(1, 2).view(b, c, h, w)\n        upscaled_embedding = self.output_upscaling(src)\n        hyper_in_list: List[torch.Tensor] = [\n            self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) for i in range(self.num_mask_tokens)]\n        hyper_in = torch.stack(hyper_in_list, dim=1)\n        b, c, h, w = upscaled_embedding.shape\n        masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)\n\n        # Generate mask quality predictions\n        iou_pred = self.iou_prediction_head(iou_token_out)\n\n        return masks, iou_pred\n\n\nclass MLP(nn.Module):\n    \"\"\"\n    Lightly adapted from\n    https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py\n    \"\"\"\n\n    def __init__(\n        self,\n        input_dim: int,\n        hidden_dim: int,\n        output_dim: int,\n        num_layers: int,\n        sigmoid_output: bool = False,\n    ) -> None:\n        super().__init__()\n        self.num_layers = num_layers\n        h = [hidden_dim] * (num_layers - 1)\n        self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))\n        self.sigmoid_output = sigmoid_output\n\n    def forward(self, x):\n        \"\"\"Executes feedforward within the neural network module and applies activation.\"\"\"\n        for i, layer in enumerate(self.layers):\n            x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)\n        if self.sigmoid_output:\n            x = torch.sigmoid(x)\n        return x\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/encoders.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom typing import Any, Optional, Tuple, Type\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ultralytics.nn.modules import LayerNorm2d, MLPBlock\n\n\n# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa\nclass ImageEncoderViT(nn.Module):\n\n    def __init__(\n            self,\n            img_size: int = 1024,\n            patch_size: int = 16,\n            in_chans: int = 3,\n            embed_dim: int = 768,\n            depth: int = 12,\n            num_heads: int = 12,\n            mlp_ratio: float = 4.0,\n            out_chans: int = 256,\n            qkv_bias: bool = True,\n            norm_layer: Type[nn.Module] = nn.LayerNorm,\n            act_layer: Type[nn.Module] = nn.GELU,\n            use_abs_pos: bool = True,\n            use_rel_pos: bool = False,\n            rel_pos_zero_init: bool = True,\n            window_size: int = 0,\n            global_attn_indexes: Tuple[int, ...] = (),\n    ) -> None:\n        \"\"\"\n        Args:\n            img_size (int): Input image size.\n            patch_size (int): Patch size.\n            in_chans (int): Number of input image channels.\n            embed_dim (int): Patch embedding dimension.\n            depth (int): Depth of ViT.\n            num_heads (int): Number of attention heads in each ViT block.\n            mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.\n            qkv_bias (bool): If True, add a learnable bias to query, key, value.\n            norm_layer (nn.Module): Normalization layer.\n            act_layer (nn.Module): Activation layer.\n            use_abs_pos (bool): If True, use absolute positional embeddings.\n            use_rel_pos (bool): If True, add relative positional embeddings to the attention map.\n            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.\n            window_size (int): Window size for window attention blocks.\n            global_attn_indexes (list): Indexes for blocks using global attention.\n        \"\"\"\n        super().__init__()\n        self.img_size = img_size\n\n        self.patch_embed = PatchEmbed(\n            kernel_size=(patch_size, patch_size),\n            stride=(patch_size, patch_size),\n            in_chans=in_chans,\n            embed_dim=embed_dim,\n        )\n\n        self.pos_embed: Optional[nn.Parameter] = None\n        if use_abs_pos:\n            # Initialize absolute positional embedding with pretrain image size.\n            self.pos_embed = nn.Parameter(torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim))\n\n        self.blocks = nn.ModuleList()\n        for i in range(depth):\n            block = Block(\n                dim=embed_dim,\n                num_heads=num_heads,\n                mlp_ratio=mlp_ratio,\n                qkv_bias=qkv_bias,\n                norm_layer=norm_layer,\n                act_layer=act_layer,\n                use_rel_pos=use_rel_pos,\n                rel_pos_zero_init=rel_pos_zero_init,\n                window_size=window_size if i not in global_attn_indexes else 0,\n                input_size=(img_size // patch_size, img_size // patch_size),\n            )\n            self.blocks.append(block)\n\n        self.neck = nn.Sequential(\n            nn.Conv2d(\n                embed_dim,\n                out_chans,\n                kernel_size=1,\n                bias=False,\n            ),\n            LayerNorm2d(out_chans),\n            nn.Conv2d(\n                out_chans,\n                out_chans,\n                kernel_size=3,\n                padding=1,\n                bias=False,\n            ),\n            LayerNorm2d(out_chans),\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.patch_embed(x)\n        if self.pos_embed is not None:\n            x = x + self.pos_embed\n\n        for blk in self.blocks:\n            x = blk(x)\n\n        x = self.neck(x.permute(0, 3, 1, 2))\n\n        return x\n\n\nclass PromptEncoder(nn.Module):\n\n    def __init__(\n        self,\n        embed_dim: int,\n        image_embedding_size: Tuple[int, int],\n        input_image_size: Tuple[int, int],\n        mask_in_chans: int,\n        activation: Type[nn.Module] = nn.GELU,\n    ) -> None:\n        \"\"\"\n        Encodes prompts for input to SAM's mask decoder.\n\n        Arguments:\n          embed_dim (int): The prompts' embedding dimension\n          image_embedding_size (tuple(int, int)): The spatial size of the\n            image embedding, as (H, W).\n          input_image_size (int): The padded size of the image as input\n            to the image encoder, as (H, W).\n          mask_in_chans (int): The number of hidden channels used for\n            encoding input masks.\n          activation (nn.Module): The activation to use when encoding\n            input masks.\n        \"\"\"\n        super().__init__()\n        self.embed_dim = embed_dim\n        self.input_image_size = input_image_size\n        self.image_embedding_size = image_embedding_size\n        self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)\n\n        self.num_point_embeddings: int = 4  # pos/neg point + 2 box corners\n        point_embeddings = [nn.Embedding(1, embed_dim) for _ in range(self.num_point_embeddings)]\n        self.point_embeddings = nn.ModuleList(point_embeddings)\n        self.not_a_point_embed = nn.Embedding(1, embed_dim)\n\n        self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1])\n        self.mask_downscaling = nn.Sequential(\n            nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),\n            LayerNorm2d(mask_in_chans // 4),\n            activation(),\n            nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),\n            LayerNorm2d(mask_in_chans),\n            activation(),\n            nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1),\n        )\n        self.no_mask_embed = nn.Embedding(1, embed_dim)\n\n    def get_dense_pe(self) -> torch.Tensor:\n        \"\"\"\n        Returns the positional encoding used to encode point prompts,\n        applied to a dense set of points the shape of the image encoding.\n\n        Returns:\n          torch.Tensor: Positional encoding with shape\n            1x(embed_dim)x(embedding_h)x(embedding_w)\n        \"\"\"\n        return self.pe_layer(self.image_embedding_size).unsqueeze(0)\n\n    def _embed_points(\n        self,\n        points: torch.Tensor,\n        labels: torch.Tensor,\n        pad: bool,\n    ) -> torch.Tensor:\n        \"\"\"Embeds point prompts.\"\"\"\n        points = points + 0.5  # Shift to center of pixel\n        if pad:\n            padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)\n            padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)\n            points = torch.cat([points, padding_point], dim=1)\n            labels = torch.cat([labels, padding_label], dim=1)\n        point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size)\n        point_embedding[labels == -1] = 0.0\n        point_embedding[labels == -1] += self.not_a_point_embed.weight\n        point_embedding[labels == 0] += self.point_embeddings[0].weight\n        point_embedding[labels == 1] += self.point_embeddings[1].weight\n        return point_embedding\n\n    def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:\n        \"\"\"Embeds box prompts.\"\"\"\n        boxes = boxes + 0.5  # Shift to center of pixel\n        coords = boxes.reshape(-1, 2, 2)\n        corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size)\n        corner_embedding[:, 0, :] += self.point_embeddings[2].weight\n        corner_embedding[:, 1, :] += self.point_embeddings[3].weight\n        return corner_embedding\n\n    def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:\n        \"\"\"Embeds mask inputs.\"\"\"\n        return self.mask_downscaling(masks)\n\n    def _get_batch_size(\n        self,\n        points: Optional[Tuple[torch.Tensor, torch.Tensor]],\n        boxes: Optional[torch.Tensor],\n        masks: Optional[torch.Tensor],\n    ) -> int:\n        \"\"\"\n        Gets the batch size of the output given the batch size of the input prompts.\n        \"\"\"\n        if points is not None:\n            return points[0].shape[0]\n        elif boxes is not None:\n            return boxes.shape[0]\n        elif masks is not None:\n            return masks.shape[0]\n        else:\n            return 1\n\n    def _get_device(self) -> torch.device:\n        return self.point_embeddings[0].weight.device\n\n    def forward(\n        self,\n        points: Optional[Tuple[torch.Tensor, torch.Tensor]],\n        boxes: Optional[torch.Tensor],\n        masks: Optional[torch.Tensor],\n    ) -> Tuple[torch.Tensor, torch.Tensor]:\n        \"\"\"\n        Embeds different types of prompts, returning both sparse and dense\n        embeddings.\n\n        Arguments:\n          points (tuple(torch.Tensor, torch.Tensor), None): point coordinates\n            and labels to embed.\n          boxes (torch.Tensor, None): boxes to embed\n          masks (torch.Tensor, None): masks to embed\n\n        Returns:\n          torch.Tensor: sparse embeddings for the points and boxes, with shape\n            BxNx(embed_dim), where N is determined by the number of input points\n            and boxes.\n          torch.Tensor: dense embeddings for the masks, in the shape\n            Bx(embed_dim)x(embed_H)x(embed_W)\n        \"\"\"\n        bs = self._get_batch_size(points, boxes, masks)\n        sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device())\n        if points is not None:\n            coords, labels = points\n            point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))\n            sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1)\n        if boxes is not None:\n            box_embeddings = self._embed_boxes(boxes)\n            sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)\n\n        if masks is not None:\n            dense_embeddings = self._embed_masks(masks)\n        else:\n            dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1,\n                                                                 1).expand(bs, -1, self.image_embedding_size[0],\n                                                                           self.image_embedding_size[1])\n\n        return sparse_embeddings, dense_embeddings\n\n\nclass PositionEmbeddingRandom(nn.Module):\n    \"\"\"\n    Positional encoding using random spatial frequencies.\n    \"\"\"\n\n    def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:\n        super().__init__()\n        if scale is None or scale <= 0.0:\n            scale = 1.0\n        self.register_buffer(\n            'positional_encoding_gaussian_matrix',\n            scale * torch.randn((2, num_pos_feats)),\n        )\n\n    def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:\n        \"\"\"Positionally encode points that are normalized to [0,1].\"\"\"\n        # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape\n        coords = 2 * coords - 1\n        coords = coords @ self.positional_encoding_gaussian_matrix\n        coords = 2 * np.pi * coords\n        # outputs d_1 x ... x d_n x C shape\n        return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)\n\n    def forward(self, size: Tuple[int, int]) -> torch.Tensor:\n        \"\"\"Generate positional encoding for a grid of the specified size.\"\"\"\n        h, w = size\n        device: Any = self.positional_encoding_gaussian_matrix.device\n        grid = torch.ones((h, w), device=device, dtype=torch.float32)\n        y_embed = grid.cumsum(dim=0) - 0.5\n        x_embed = grid.cumsum(dim=1) - 0.5\n        y_embed = y_embed / h\n        x_embed = x_embed / w\n\n        pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))\n        return pe.permute(2, 0, 1)  # C x H x W\n\n    def forward_with_coords(self, coords_input: torch.Tensor, image_size: Tuple[int, int]) -> torch.Tensor:\n        \"\"\"Positionally encode points that are not normalized to [0,1].\"\"\"\n        coords = coords_input.clone()\n        coords[:, :, 0] = coords[:, :, 0] / image_size[1]\n        coords[:, :, 1] = coords[:, :, 1] / image_size[0]\n        return self._pe_encoding(coords.to(torch.float))  # B x N x C\n\n\nclass Block(nn.Module):\n    \"\"\"Transformer blocks with support of window attention and residual propagation blocks\"\"\"\n\n    def __init__(\n        self,\n        dim: int,\n        num_heads: int,\n        mlp_ratio: float = 4.0,\n        qkv_bias: bool = True,\n        norm_layer: Type[nn.Module] = nn.LayerNorm,\n        act_layer: Type[nn.Module] = nn.GELU,\n        use_rel_pos: bool = False,\n        rel_pos_zero_init: bool = True,\n        window_size: int = 0,\n        input_size: Optional[Tuple[int, int]] = None,\n    ) -> None:\n        \"\"\"\n        Args:\n            dim (int): Number of input channels.\n            num_heads (int): Number of attention heads in each ViT block.\n            mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.\n            qkv_bias (bool): If True, add a learnable bias to query, key, value.\n            norm_layer (nn.Module): Normalization layer.\n            act_layer (nn.Module): Activation layer.\n            use_rel_pos (bool): If True, add relative positional embeddings to the attention map.\n            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.\n            window_size (int): Window size for window attention blocks. If it equals 0, then\n                use global attention.\n            input_size (tuple(int, int), None): Input resolution for calculating the relative\n                positional parameter size.\n        \"\"\"\n        super().__init__()\n        self.norm1 = norm_layer(dim)\n        self.attn = Attention(\n            dim,\n            num_heads=num_heads,\n            qkv_bias=qkv_bias,\n            use_rel_pos=use_rel_pos,\n            rel_pos_zero_init=rel_pos_zero_init,\n            input_size=input_size if window_size == 0 else (window_size, window_size),\n        )\n\n        self.norm2 = norm_layer(dim)\n        self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer)\n\n        self.window_size = window_size\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        shortcut = x\n        x = self.norm1(x)\n        # Window partition\n        if self.window_size > 0:\n            H, W = x.shape[1], x.shape[2]\n            x, pad_hw = window_partition(x, self.window_size)\n\n        x = self.attn(x)\n        # Reverse window partition\n        if self.window_size > 0:\n            x = window_unpartition(x, self.window_size, pad_hw, (H, W))\n\n        x = shortcut + x\n        x = x + self.mlp(self.norm2(x))\n\n        return x\n\n\nclass Attention(nn.Module):\n    \"\"\"Multi-head Attention block with relative position embeddings.\"\"\"\n\n    def __init__(\n        self,\n        dim: int,\n        num_heads: int = 8,\n        qkv_bias: bool = True,\n        use_rel_pos: bool = False,\n        rel_pos_zero_init: bool = True,\n        input_size: Optional[Tuple[int, int]] = None,\n    ) -> None:\n        \"\"\"\n        Args:\n            dim (int): Number of input channels.\n            num_heads (int): Number of attention heads.\n            qkv_bias (bool):  If True, add a learnable bias to query, key, value.\n            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.\n            input_size (tuple(int, int), None): Input resolution for calculating the relative\n                positional parameter size.\n        \"\"\"\n        super().__init__()\n        self.num_heads = num_heads\n        head_dim = dim // num_heads\n        self.scale = head_dim ** -0.5\n\n        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n        self.proj = nn.Linear(dim, dim)\n\n        self.use_rel_pos = use_rel_pos\n        if self.use_rel_pos:\n            assert (input_size is not None), 'Input size must be provided if using relative positional encoding.'\n            # initialize relative positional embeddings\n            self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))\n            self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        B, H, W, _ = x.shape\n        # qkv with shape (3, B, nHead, H * W, C)\n        qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)\n        # q, k, v with shape (B * nHead, H * W, C)\n        q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)\n\n        attn = (q * self.scale) @ k.transpose(-2, -1)\n\n        if self.use_rel_pos:\n            attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))\n\n        attn = attn.softmax(dim=-1)\n        x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)\n        x = self.proj(x)\n\n        return x\n\n\ndef window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]:\n    \"\"\"\n    Partition into non-overlapping windows with padding if needed.\n    Args:\n        x (tensor): input tokens with [B, H, W, C].\n        window_size (int): window size.\n\n    Returns:\n        windows: windows after partition with [B * num_windows, window_size, window_size, C].\n        (Hp, Wp): padded height and width before partition\n    \"\"\"\n    B, H, W, C = x.shape\n\n    pad_h = (window_size - H % window_size) % window_size\n    pad_w = (window_size - W % window_size) % window_size\n    if pad_h > 0 or pad_w > 0:\n        x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))\n    Hp, Wp = H + pad_h, W + pad_w\n\n    x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)\n    windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)\n    return windows, (Hp, Wp)\n\n\ndef window_unpartition(windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int],\n                       hw: Tuple[int, int]) -> torch.Tensor:\n    \"\"\"\n    Window unpartition into original sequences and removing padding.\n    Args:\n        windows (tensor): input tokens with [B * num_windows, window_size, window_size, C].\n        window_size (int): window size.\n        pad_hw (Tuple): padded height and width (Hp, Wp).\n        hw (Tuple): original height and width (H, W) before padding.\n\n    Returns:\n        x: unpartitioned sequences with [B, H, W, C].\n    \"\"\"\n    Hp, Wp = pad_hw\n    H, W = hw\n    B = windows.shape[0] // (Hp * Wp // window_size // window_size)\n    x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)\n    x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)\n\n    if Hp > H or Wp > W:\n        x = x[:, :H, :W, :].contiguous()\n    return x\n\n\ndef get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:\n    \"\"\"\n    Get relative positional embeddings according to the relative positions of\n        query and key sizes.\n    Args:\n        q_size (int): size of query q.\n        k_size (int): size of key k.\n        rel_pos (Tensor): relative position embeddings (L, C).\n\n    Returns:\n        Extracted positional embeddings according to relative positions.\n    \"\"\"\n    max_rel_dist = int(2 * max(q_size, k_size) - 1)\n    # Interpolate rel pos if needed.\n    if rel_pos.shape[0] != max_rel_dist:\n        # Interpolate rel pos.\n        rel_pos_resized = F.interpolate(\n            rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),\n            size=max_rel_dist,\n            mode='linear',\n        )\n        rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)\n    else:\n        rel_pos_resized = rel_pos\n\n    # Scale the coords with short length if shapes for q and k are different.\n    q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)\n    k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)\n    relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)\n\n    return rel_pos_resized[relative_coords.long()]\n\n\ndef add_decomposed_rel_pos(\n    attn: torch.Tensor,\n    q: torch.Tensor,\n    rel_pos_h: torch.Tensor,\n    rel_pos_w: torch.Tensor,\n    q_size: Tuple[int, int],\n    k_size: Tuple[int, int],\n) -> torch.Tensor:\n    \"\"\"\n    Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.\n    https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py   # noqa B950\n    Args:\n        attn (Tensor): attention map.\n        q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).\n        rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.\n        rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.\n        q_size (Tuple): spatial sequence size of query q with (q_h, q_w).\n        k_size (Tuple): spatial sequence size of key k with (k_h, k_w).\n\n    Returns:\n        attn (Tensor): attention map with added relative positional embeddings.\n    \"\"\"\n    q_h, q_w = q_size\n    k_h, k_w = k_size\n    Rh = get_rel_pos(q_h, k_h, rel_pos_h)\n    Rw = get_rel_pos(q_w, k_w, rel_pos_w)\n\n    B, _, dim = q.shape\n    r_q = q.reshape(B, q_h, q_w, dim)\n    rel_h = torch.einsum('bhwc,hkc->bhwk', r_q, Rh)\n    rel_w = torch.einsum('bhwc,wkc->bhwk', r_q, Rw)\n\n    attn = (attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]).view(\n        B, q_h * q_w, k_h * k_w)\n\n    return attn\n\n\nclass PatchEmbed(nn.Module):\n    \"\"\"\n    Image to Patch Embedding.\n    \"\"\"\n\n    def __init__(\n            self,\n            kernel_size: Tuple[int, int] = (16, 16),\n            stride: Tuple[int, int] = (16, 16),\n            padding: Tuple[int, int] = (0, 0),\n            in_chans: int = 3,\n            embed_dim: int = 768,\n    ) -> None:\n        \"\"\"\n        Args:\n            kernel_size (Tuple): kernel size of the projection layer.\n            stride (Tuple): stride of the projection layer.\n            padding (Tuple): padding size of the projection layer.\n            in_chans (int): Number of input image channels.\n            embed_dim (int): Patch embedding dimension.\n        \"\"\"\n        super().__init__()\n\n        self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding)\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.proj(x)\n        # B C H W -> B H W C\n        x = x.permute(0, 2, 3, 1)\n        return x\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/mask_generator.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport numpy as np\nimport torch\nfrom torchvision.ops.boxes import batched_nms, box_area  # type: ignore\n\nfrom ..amg import (MaskData, area_from_rle, batch_iterator, batched_mask_to_box, box_xyxy_to_xywh,\n                   build_all_layer_point_grids, calculate_stability_score, coco_encode_rle, generate_crop_boxes,\n                   is_box_near_crop_edge, mask_to_rle_pytorch, remove_small_regions, rle_to_mask, uncrop_boxes_xyxy,\n                   uncrop_masks, uncrop_points)\nfrom .prompt_predictor import PromptPredictor\nfrom .sam import Sam\n\n\nclass SamAutomaticMaskGenerator:\n\n    def __init__(\n        self,\n        model: Sam,\n        points_per_side: Optional[int] = 32,\n        points_per_batch: int = 64,\n        pred_iou_thresh: float = 0.88,\n        stability_score_thresh: float = 0.95,\n        stability_score_offset: float = 1.0,\n        box_nms_thresh: float = 0.7,\n        crop_n_layers: int = 0,\n        crop_nms_thresh: float = 0.7,\n        crop_overlap_ratio: float = 512 / 1500,\n        crop_n_points_downscale_factor: int = 1,\n        point_grids: Optional[List[np.ndarray]] = None,\n        min_mask_region_area: int = 0,\n        output_mode: str = 'binary_mask',\n    ) -> None:\n        \"\"\"\n        Using a SAM model, generates masks for the entire image.\n        Generates a grid of point prompts over the image, then filters\n        low quality and duplicate masks. The default settings are chosen\n        for SAM with a ViT-H backbone.\n\n        Arguments:\n          model (Sam): The SAM model to use for mask prediction.\n          points_per_side (int, None): The number of points to be sampled\n            along one side of the image. The total number of points is\n            points_per_side**2. If None, 'point_grids' must provide explicit\n            point sampling.\n          points_per_batch (int): Sets the number of points run simultaneously\n            by the model. Higher numbers may be faster but use more GPU memory.\n          pred_iou_thresh (float): A filtering threshold in [0,1], using the\n            model's predicted mask quality.\n          stability_score_thresh (float): A filtering threshold in [0,1], using\n            the stability of the mask under changes to the cutoff used to binarize\n            the model's mask predictions.\n          stability_score_offset (float): The amount to shift the cutoff when\n            calculated the stability score.\n          box_nms_thresh (float): The box IoU cutoff used by non-maximal\n            suppression to filter duplicate masks.\n          crop_n_layers (int): If >0, mask prediction will be run again on\n            crops of the image. Sets the number of layers to run, where each\n            layer has 2**i_layer number of image crops.\n          crop_nms_thresh (float): The box IoU cutoff used by non-maximal\n            suppression to filter duplicate masks between different crops.\n          crop_overlap_ratio (float): Sets the degree to which crops overlap.\n            In the first crop layer, crops will overlap by this fraction of\n            the image length. Later layers with more crops scale down this overlap.\n          crop_n_points_downscale_factor (int): The number of points-per-side\n            sampled in layer n is scaled down by crop_n_points_downscale_factor**n.\n          point_grids (list(np.ndarray), None): A list over explicit grids\n            of points used for sampling, normalized to [0,1]. The nth grid in the\n            list is used in the nth crop layer. Exclusive with points_per_side.\n          min_mask_region_area (int): If >0, postprocessing will be applied\n            to remove disconnected regions and holes in masks with area smaller\n            than min_mask_region_area. Requires opencv.\n          output_mode (str): The form masks are returned in. Can be 'binary_mask',\n            'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.\n            For large resolutions, 'binary_mask' may consume large amounts of\n            memory.\n        \"\"\"\n\n        assert (points_per_side is None) != (point_grids is None), \\\n            'Exactly one of points_per_side or point_grid must be provided.'\n        if points_per_side is not None:\n            self.point_grids = build_all_layer_point_grids(\n                points_per_side,\n                crop_n_layers,\n                crop_n_points_downscale_factor,\n            )\n        elif point_grids is not None:\n            self.point_grids = point_grids\n        else:\n            raise ValueError(\"Can't have both points_per_side and point_grid be None.\")\n\n        assert output_mode in {'binary_mask', 'uncompressed_rle', 'coco_rle'}, f'Unknown output_mode {output_mode}.'\n        if output_mode == 'coco_rle':\n            from pycocotools import mask as mask_utils  # type: ignore # noqa: F401\n\n        if min_mask_region_area > 0:\n            import cv2  # type: ignore # noqa: F401\n\n        self.predictor = PromptPredictor(model)\n        self.points_per_batch = points_per_batch\n        self.pred_iou_thresh = pred_iou_thresh\n        self.stability_score_thresh = stability_score_thresh\n        self.stability_score_offset = stability_score_offset\n        self.box_nms_thresh = box_nms_thresh\n        self.crop_n_layers = crop_n_layers\n        self.crop_nms_thresh = crop_nms_thresh\n        self.crop_overlap_ratio = crop_overlap_ratio\n        self.crop_n_points_downscale_factor = crop_n_points_downscale_factor\n        self.min_mask_region_area = min_mask_region_area\n        self.output_mode = output_mode\n\n    # TODO: Temporary implementation for compatibility\n    def __call__(self, image: np.ndarray, augment=False, visualize=False) -> List[Dict[str, Any]]:\n        return self.generate(image)\n\n    @torch.no_grad()\n    def generate(self, image: np.ndarray) -> List[Dict[str, Any]]:\n        \"\"\"\n        Generates masks for the given image.\n\n        Arguments:\n          image (np.ndarray): The image to generate masks for, in HWC uint8 format.\n\n        Returns:\n           list(dict(str, any)): A list over records for masks. Each record is a dict containing the following keys:\n               segmentation (dict(str, any), np.ndarray): The mask. If\n                 output_mode='binary_mask', is an array of shape HW. Otherwise,\n                 is a dictionary containing the RLE.\n               bbox (list(float)): The box around the mask, in XYWH format.\n               area (int): The area in pixels of the mask.\n               predicted_iou (float): The model's own prediction of the mask's\n                 quality. This is filtered by the pred_iou_thresh parameter.\n               point_coords (list(list(float))): The point coordinates input\n                 to the model to generate this mask.\n               stability_score (float): A measure of the mask's quality. This\n                 is filtered on using the stability_score_thresh parameter.\n               crop_box (list(float)): The crop of the image used to generate\n                 the mask, given in XYWH format.\n        \"\"\"\n\n        # Generate masks\n        mask_data = self._generate_masks(image)\n\n        # Filter small disconnected regions and holes in masks\n        if self.min_mask_region_area > 0:\n            mask_data = self.postprocess_small_regions(\n                mask_data,\n                self.min_mask_region_area,\n                max(self.box_nms_thresh, self.crop_nms_thresh),\n            )\n\n        # Encode masks\n        if self.output_mode == 'coco_rle':\n            mask_data['segmentations'] = [coco_encode_rle(rle) for rle in mask_data['rles']]\n        elif self.output_mode == 'binary_mask':\n            mask_data['segmentations'] = [rle_to_mask(rle) for rle in mask_data['rles']]\n        else:\n            mask_data['segmentations'] = mask_data['rles']\n\n        # Write mask records\n        curr_anns = []\n        for idx in range(len(mask_data['segmentations'])):\n            ann = {\n                'segmentation': mask_data['segmentations'][idx],\n                'area': area_from_rle(mask_data['rles'][idx]),\n                'bbox': box_xyxy_to_xywh(mask_data['boxes'][idx]).tolist(),\n                'predicted_iou': mask_data['iou_preds'][idx].item(),\n                'point_coords': [mask_data['points'][idx].tolist()],\n                'stability_score': mask_data['stability_score'][idx].item(),\n                'crop_box': box_xyxy_to_xywh(mask_data['crop_boxes'][idx]).tolist(), }\n            curr_anns.append(ann)\n\n        return curr_anns\n\n    def _generate_masks(self, image: np.ndarray) -> MaskData:\n        orig_size = image.shape[:2]\n        crop_boxes, layer_idxs = generate_crop_boxes(orig_size, self.crop_n_layers, self.crop_overlap_ratio)\n\n        # Iterate over image crops\n        data = MaskData()\n        for crop_box, layer_idx in zip(crop_boxes, layer_idxs):\n            crop_data = self._process_crop(image, crop_box, layer_idx, orig_size)\n            data.cat(crop_data)\n\n        # Remove duplicate masks between crops\n        if len(crop_boxes) > 1:\n            # Prefer masks from smaller crops\n            scores = 1 / box_area(data['crop_boxes'])\n            scores = scores.to(data['boxes'].device)\n            keep_by_nms = batched_nms(\n                data['boxes'].float(),\n                scores,\n                torch.zeros_like(data['boxes'][:, 0]),  # categories\n                iou_threshold=self.crop_nms_thresh,\n            )\n            data.filter(keep_by_nms)\n\n        data.to_numpy()\n        return data\n\n    def _process_crop(\n        self,\n        image: np.ndarray,\n        crop_box: List[int],\n        crop_layer_idx: int,\n        orig_size: Tuple[int, ...],\n    ) -> MaskData:\n        # Crop the image and calculate embeddings\n        x0, y0, x1, y1 = crop_box\n        cropped_im = image[y0:y1, x0:x1, :]\n        cropped_im_size = cropped_im.shape[:2]\n        self.predictor.set_image(cropped_im)\n\n        # Get points for this crop\n        points_scale = np.array(cropped_im_size)[None, ::-1]\n        points_for_image = self.point_grids[crop_layer_idx] * points_scale\n\n        # Generate masks for this crop in batches\n        data = MaskData()\n        for (points, ) in batch_iterator(self.points_per_batch, points_for_image):\n            batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size)\n            data.cat(batch_data)\n            del batch_data\n        self.predictor.reset_image()\n\n        # Remove duplicates within this crop.\n        keep_by_nms = batched_nms(\n            data['boxes'].float(),\n            data['iou_preds'],\n            torch.zeros_like(data['boxes'][:, 0]),  # categories\n            iou_threshold=self.box_nms_thresh,\n        )\n        data.filter(keep_by_nms)\n\n        # Return to the original image frame\n        data['boxes'] = uncrop_boxes_xyxy(data['boxes'], crop_box)\n        data['points'] = uncrop_points(data['points'], crop_box)\n        data['crop_boxes'] = torch.tensor([crop_box for _ in range(len(data['rles']))])\n\n        return data\n\n    def _process_batch(\n        self,\n        points: np.ndarray,\n        im_size: Tuple[int, ...],\n        crop_box: List[int],\n        orig_size: Tuple[int, ...],\n    ) -> MaskData:\n        orig_h, orig_w = orig_size\n\n        # Run model on this batch\n        transformed_points = self.predictor.transform.apply_coords(points, im_size)\n        in_points = torch.as_tensor(transformed_points, device=self.predictor.device)\n        in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device)\n        masks, iou_preds, _ = self.predictor.predict_torch(\n            in_points[:, None, :],\n            in_labels[:, None],\n            multimask_output=True,\n            return_logits=True,\n        )\n\n        # Serialize predictions and store in MaskData\n        data = MaskData(\n            masks=masks.flatten(0, 1),\n            iou_preds=iou_preds.flatten(0, 1),\n            points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)),\n        )\n        del masks\n\n        # Filter by predicted IoU\n        if self.pred_iou_thresh > 0.0:\n            keep_mask = data['iou_preds'] > self.pred_iou_thresh\n            data.filter(keep_mask)\n\n        # Calculate stability score\n        data['stability_score'] = calculate_stability_score(data['masks'], self.predictor.model.mask_threshold,\n                                                            self.stability_score_offset)\n        if self.stability_score_thresh > 0.0:\n            keep_mask = data['stability_score'] >= self.stability_score_thresh\n            data.filter(keep_mask)\n\n        # Threshold masks and calculate boxes\n        data['masks'] = data['masks'] > self.predictor.model.mask_threshold\n        data['boxes'] = batched_mask_to_box(data['masks'])\n\n        # Filter boxes that touch crop boundaries\n        keep_mask = ~is_box_near_crop_edge(data['boxes'], crop_box, [0, 0, orig_w, orig_h])\n        if not torch.all(keep_mask):\n            data.filter(keep_mask)\n\n        # Compress to RLE\n        data['masks'] = uncrop_masks(data['masks'], crop_box, orig_h, orig_w)\n        data['rles'] = mask_to_rle_pytorch(data['masks'])\n        del data['masks']\n\n        return data\n\n    @staticmethod\n    def postprocess_small_regions(mask_data: MaskData, min_area: int, nms_thresh: float) -> MaskData:\n        \"\"\"\n        Removes small disconnected regions and holes in masks, then reruns\n        box NMS to remove any new duplicates.\n\n        Edits mask_data in place.\n\n        Requires open-cv as a dependency.\n        \"\"\"\n        if len(mask_data['rles']) == 0:\n            return mask_data\n\n        # Filter small disconnected regions and holes\n        new_masks = []\n        scores = []\n        for rle in mask_data['rles']:\n            mask = rle_to_mask(rle)\n\n            mask, changed = remove_small_regions(mask, min_area, mode='holes')\n            unchanged = not changed\n            mask, changed = remove_small_regions(mask, min_area, mode='islands')\n            unchanged = unchanged and not changed\n\n            new_masks.append(torch.as_tensor(mask).unsqueeze(0))\n            # Give score=0 to changed masks and score=1 to unchanged masks\n            # so NMS will prefer ones that didn't need postprocessing\n            scores.append(float(unchanged))\n\n        # Recalculate boxes and remove any new duplicates\n        masks = torch.cat(new_masks, dim=0)\n        boxes = batched_mask_to_box(masks)\n        keep_by_nms = batched_nms(\n            boxes.float(),\n            torch.as_tensor(scores),\n            torch.zeros_like(boxes[:, 0]),  # categories\n            iou_threshold=nms_thresh,\n        )\n\n        # Only recalculate RLEs for masks that have changed\n        for i_mask in keep_by_nms:\n            if scores[i_mask] == 0.0:\n                mask_torch = masks[i_mask].unsqueeze(0)\n                mask_data['rles'][i_mask] = mask_to_rle_pytorch(mask_torch)[0]\n                mask_data['boxes'][i_mask] = boxes[i_mask]  # update res directly\n        mask_data.filter(keep_by_nms)\n\n        return mask_data\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/prompt_predictor.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom typing import Optional, Tuple\n\nimport numpy as np\nimport torch\n\nfrom ..autosize import ResizeLongestSide\nfrom .sam import Sam\n\n\nclass PromptPredictor:\n\n    def __init__(self, sam_model: Sam) -> None:\n        \"\"\"\n        Uses SAM to calculate the image embedding for an image, and then\n        allow repeated, efficient mask prediction given prompts.\n\n        Arguments:\n          sam_model (Sam): The model to use for mask prediction.\n        \"\"\"\n        super().__init__()\n        self.model = sam_model\n        self.transform = ResizeLongestSide(sam_model.image_encoder.img_size)\n        self.reset_image()\n\n    def set_image(self, image: np.ndarray, image_format: str = 'RGB') -> None:\n        \"\"\"\n        Calculates the image embeddings for the provided image, allowing\n        masks to be predicted with the 'predict' method.\n\n        Arguments:\n          image (np.ndarray): The image for calculating masks. Expects an\n            image in HWC uint8 format, with pixel values in [0, 255].\n          image_format (str): The color format of the image, in ['RGB', 'BGR'].\n        \"\"\"\n        assert image_format in {'RGB', 'BGR'}, f\"image_format must be in ['RGB', 'BGR'], is {image_format}.\"\n        if image_format != self.model.image_format:\n            image = image[..., ::-1]\n\n        # Transform the image to the form expected by the model\n        input_image = self.transform.apply_image(image)\n        input_image_torch = torch.as_tensor(input_image, device=self.device)\n        input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[None, :, :, :]\n\n        self.set_torch_image(input_image_torch, image.shape[:2])\n\n    @torch.no_grad()\n    def set_torch_image(self, transformed_image: torch.Tensor, original_image_size: Tuple[int, ...]) -> None:\n        \"\"\"\n        Calculates the image embeddings for the provided image, allowing\n        masks to be predicted with the 'predict' method. Expects the input\n        image to be already transformed to the format expected by the model.\n\n        Arguments:\n          transformed_image (torch.Tensor): The input image, with shape\n            1x3xHxW, which has been transformed with ResizeLongestSide.\n          original_image_size (tuple(int, int)): The size of the image\n            before transformation, in (H, W) format.\n        \"\"\"\n        if len(transformed_image.shape) != 4 \\\n                or transformed_image.shape[1] != 3 \\\n                or max(*transformed_image.shape[2:]) != self.model.image_encoder.img_size:\n            raise ValueError('set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}.')\n        self.reset_image()\n\n        self.original_size = original_image_size\n        self.input_size = tuple(transformed_image.shape[-2:])\n        input_image = self.model.preprocess(transformed_image)\n        self.features = self.model.image_encoder(input_image)\n        self.is_image_set = True\n\n    def predict(\n        self,\n        point_coords: Optional[np.ndarray] = None,\n        point_labels: Optional[np.ndarray] = None,\n        box: Optional[np.ndarray] = None,\n        mask_input: Optional[np.ndarray] = None,\n        multimask_output: bool = True,\n        return_logits: bool = False,\n    ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n        \"\"\"\n        Predict masks for the given input prompts, using the currently set image.\n\n        Arguments:\n          point_coords (np.ndarray, None): A Nx2 array of point prompts to the\n            model. Each point is in (X,Y) in pixels.\n          point_labels (np.ndarray, None): A length N array of labels for the\n            point prompts. 1 indicates a foreground point and 0 indicates a\n            background point.\n          box (np.ndarray, None): A length 4 array given a box prompt to the\n            model, in XYXY format.\n          mask_input (np.ndarray): A low resolution mask input to the model, typically\n            coming from a previous prediction iteration. Has form 1xHxW, where\n            for SAM, H=W=256.\n          multimask_output (bool): If true, the model will return three masks.\n            For ambiguous input prompts (such as a single click), this will often\n            produce better masks than a single prediction. If only a single\n            mask is needed, the model's predicted quality score can be used\n            to select the best mask. For non-ambiguous prompts, such as multiple\n            input prompts, multimask_output=False can give better results.\n          return_logits (bool): If true, returns un-thresholded masks logits\n            instead of a binary mask.\n\n        Returns:\n          (np.ndarray): The output masks in CxHxW format, where C is the\n            number of masks, and (H, W) is the original image size.\n          (np.ndarray): An array of length C containing the model's\n            predictions for the quality of each mask.\n          (np.ndarray): An array of shape CxHxW, where C is the number\n            of masks and H=W=256. These low resolution logits can be passed to\n            a subsequent iteration as mask input.\n        \"\"\"\n        if not self.is_image_set:\n            raise RuntimeError('An image must be set with .set_image(...) before mask prediction.')\n\n        # Transform input prompts\n        coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None\n        if point_coords is not None:\n            assert (point_labels is not None), 'point_labels must be supplied if point_coords is supplied.'\n            point_coords = self.transform.apply_coords(point_coords, self.original_size)\n            coords_torch = torch.as_tensor(point_coords, dtype=torch.float, device=self.device)\n            labels_torch = torch.as_tensor(point_labels, dtype=torch.int, device=self.device)\n            coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :]\n        if box is not None:\n            box = self.transform.apply_boxes(box, self.original_size)\n            box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device)\n            box_torch = box_torch[None, :]\n        if mask_input is not None:\n            mask_input_torch = torch.as_tensor(mask_input, dtype=torch.float, device=self.device)\n            mask_input_torch = mask_input_torch[None, :, :, :]\n\n        masks, iou_predictions, low_res_masks = self.predict_torch(\n            coords_torch,\n            labels_torch,\n            box_torch,\n            mask_input_torch,\n            multimask_output,\n            return_logits=return_logits,\n        )\n\n        masks_np = masks[0].detach().cpu().numpy()\n        iou_predictions_np = iou_predictions[0].detach().cpu().numpy()\n        low_res_masks_np = low_res_masks[0].detach().cpu().numpy()\n        return masks_np, iou_predictions_np, low_res_masks_np\n\n    @torch.no_grad()\n    def predict_torch(\n        self,\n        point_coords: Optional[torch.Tensor],\n        point_labels: Optional[torch.Tensor],\n        boxes: Optional[torch.Tensor] = None,\n        mask_input: Optional[torch.Tensor] = None,\n        multimask_output: bool = True,\n        return_logits: bool = False,\n    ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n        \"\"\"\n        Predict masks for the given input prompts, using the currently set image.\n        Input prompts are batched torch tensors and are expected to already be\n        transformed to the input frame using ResizeLongestSide.\n\n        Arguments:\n          point_coords (torch.Tensor, None): A BxNx2 array of point prompts to the\n            model. Each point is in (X,Y) in pixels.\n          point_labels (torch.Tensor, None): A BxN array of labels for the\n            point prompts. 1 indicates a foreground point and 0 indicates a\n            background point.\n          boxes (np.ndarray, None): A Bx4 array given a box prompt to the\n            model, in XYXY format.\n          mask_input (np.ndarray): A low resolution mask input to the model, typically\n            coming from a previous prediction iteration. Has form Bx1xHxW, where\n            for SAM, H=W=256. Masks returned by a previous iteration of the\n            predict method do not need further transformation.\n          multimask_output (bool): If true, the model will return three masks.\n            For ambiguous input prompts (such as a single click), this will often\n            produce better masks than a single prediction. If only a single\n            mask is needed, the model's predicted quality score can be used\n            to select the best mask. For non-ambiguous prompts, such as multiple\n            input prompts, multimask_output=False can give better results.\n          return_logits (bool): If true, returns un-thresholded masks logits\n            instead of a binary mask.\n\n        Returns:\n          (torch.Tensor): The output masks in BxCxHxW format, where C is the\n            number of masks, and (H, W) is the original image size.\n          (torch.Tensor): An array of shape BxC containing the model's\n            predictions for the quality of each mask.\n          (torch.Tensor): An array of shape BxCxHxW, where C is the number\n            of masks and H=W=256. These low res logits can be passed to\n            a subsequent iteration as mask input.\n        \"\"\"\n        if not self.is_image_set:\n            raise RuntimeError('An image must be set with .set_image(...) before mask prediction.')\n\n        points = (point_coords, point_labels) if point_coords is not None else None\n        # Embed prompts\n        sparse_embeddings, dense_embeddings = self.model.prompt_encoder(\n            points=points,\n            boxes=boxes,\n            masks=mask_input,\n        )\n\n        # Predict masks\n        low_res_masks, iou_predictions = self.model.mask_decoder(\n            image_embeddings=self.features,\n            image_pe=self.model.prompt_encoder.get_dense_pe(),\n            sparse_prompt_embeddings=sparse_embeddings,\n            dense_prompt_embeddings=dense_embeddings,\n            multimask_output=multimask_output,\n        )\n\n        # Upscale the masks to the original image resolution\n        masks = self.model.postprocess_masks(low_res_masks, self.input_size, self.original_size)\n\n        if not return_logits:\n            masks = masks > self.model.mask_threshold\n\n        return masks, iou_predictions, low_res_masks\n\n    def get_image_embedding(self) -> torch.Tensor:\n        \"\"\"\n        Returns the image embeddings for the currently set image, with\n        shape 1xCxHxW, where C is the embedding dimension and (H,W) are\n        the embedding spatial dimension of SAM (typically C=256, H=W=64).\n        \"\"\"\n        if not self.is_image_set:\n            raise RuntimeError('An image must be set with .set_image(...) to generate an embedding.')\n        assert self.features is not None, 'Features must exist if an image has been set.'\n        return self.features\n\n    @property\n    def device(self) -> torch.device:\n        return self.model.device\n\n    def reset_image(self) -> None:\n        \"\"\"Resets the currently set image.\"\"\"\n        self.is_image_set = False\n        self.features = None\n        self.orig_h = None\n        self.orig_w = None\n        self.input_h = None\n        self.input_w = None\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/sam.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom typing import Any, Dict, List, Tuple\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom .decoders import MaskDecoder\nfrom .encoders import ImageEncoderViT, PromptEncoder\n\n\nclass Sam(nn.Module):\n    mask_threshold: float = 0.0\n    image_format: str = 'RGB'\n\n    def __init__(self,\n                 image_encoder: ImageEncoderViT,\n                 prompt_encoder: PromptEncoder,\n                 mask_decoder: MaskDecoder,\n                 pixel_mean: List[float] = None,\n                 pixel_std: List[float] = None) -> None:\n        \"\"\"\n        SAM predicts object masks from an image and input prompts.\n\n        Arguments:\n          image_encoder (ImageEncoderViT): The backbone used to encode the\n            image into image embeddings that allow for efficient mask prediction.\n          prompt_encoder (PromptEncoder): Encodes various types of input prompts.\n          mask_decoder (MaskDecoder): Predicts masks from the image embeddings\n            and encoded prompts.\n          pixel_mean (list(float)): Mean values for normalizing pixels in the input image.\n          pixel_std (list(float)): Std values for normalizing pixels in the input image.\n        \"\"\"\n        if pixel_mean is None:\n            pixel_mean = [123.675, 116.28, 103.53]\n        if pixel_std is None:\n            pixel_std = [58.395, 57.12, 57.375]\n        super().__init__()\n        self.image_encoder = image_encoder\n        self.prompt_encoder = prompt_encoder\n        self.mask_decoder = mask_decoder\n        self.register_buffer('pixel_mean', torch.Tensor(pixel_mean).view(-1, 1, 1), False)\n        self.register_buffer('pixel_std', torch.Tensor(pixel_std).view(-1, 1, 1), False)\n\n    @property\n    def device(self) -> Any:\n        return self.pixel_mean.device\n\n    @torch.no_grad()\n    def forward(\n        self,\n        batched_input: List[Dict[str, Any]],\n        multimask_output: bool,\n    ) -> List[Dict[str, torch.Tensor]]:\n        \"\"\"\n        Predicts masks end-to-end from provided images and prompts.\n        If prompts are not known in advance, using SamPredictor is\n        recommended over calling the model directly.\n\n        Arguments:\n          batched_input (list(dict)): A list over input images, each a\n            dictionary with the following keys. A prompt key can be\n            excluded if it is not present.\n              'image': The image as a torch tensor in 3xHxW format,\n                already transformed for input to the model.\n              'original_size': (tuple(int, int)) The original size of\n                the image before transformation, as (H, W).\n              'point_coords': (torch.Tensor) Batched point prompts for\n                this image, with shape BxNx2. Already transformed to the\n                input frame of the model.\n              'point_labels': (torch.Tensor) Batched labels for point prompts,\n                with shape BxN.\n              'boxes': (torch.Tensor) Batched box inputs, with shape Bx4.\n                Already transformed to the input frame of the model.\n              'mask_inputs': (torch.Tensor) Batched mask inputs to the model,\n                in the form Bx1xHxW.\n          multimask_output (bool): Whether the model should predict multiple\n            disambiguating masks, or return a single mask.\n\n        Returns:\n          (list(dict)): A list over input images, where each element is\n            as dictionary with the following keys.\n              'masks': (torch.Tensor) Batched binary mask predictions,\n                with shape BxCxHxW, where B is the number of input prompts,\n                C is determined by multimask_output, and (H, W) is the\n                original size of the image.\n              'iou_predictions': (torch.Tensor) The model's predictions\n                of mask quality, in shape BxC.\n              'low_res_logits': (torch.Tensor) Low resolution logits with\n                shape BxCxHxW, where H=W=256. Can be passed as mask input\n                to subsequent iterations of prediction.\n        \"\"\"\n        input_images = torch.stack([self.preprocess(x['image']) for x in batched_input], dim=0)\n        image_embeddings = self.image_encoder(input_images)\n\n        outputs = []\n        for image_record, curr_embedding in zip(batched_input, image_embeddings):\n            if 'point_coords' in image_record:\n                points = (image_record['point_coords'], image_record['point_labels'])\n            else:\n                points = None\n            sparse_embeddings, dense_embeddings = self.prompt_encoder(\n                points=points,\n                boxes=image_record.get('boxes', None),\n                masks=image_record.get('mask_inputs', None),\n            )\n            low_res_masks, iou_predictions = self.mask_decoder(\n                image_embeddings=curr_embedding.unsqueeze(0),\n                image_pe=self.prompt_encoder.get_dense_pe(),\n                sparse_prompt_embeddings=sparse_embeddings,\n                dense_prompt_embeddings=dense_embeddings,\n                multimask_output=multimask_output,\n            )\n            masks = self.postprocess_masks(\n                low_res_masks,\n                input_size=image_record['image'].shape[-2:],\n                original_size=image_record['original_size'],\n            )\n            masks = masks > self.mask_threshold\n            outputs.append({\n                'masks': masks,\n                'iou_predictions': iou_predictions,\n                'low_res_logits': low_res_masks, })\n        return outputs\n\n    def postprocess_masks(\n        self,\n        masks: torch.Tensor,\n        input_size: Tuple[int, ...],\n        original_size: Tuple[int, ...],\n    ) -> torch.Tensor:\n        \"\"\"\n        Remove padding and upscale masks to the original image size.\n\n        Arguments:\n          masks (torch.Tensor): Batched masks from the mask_decoder,\n            in BxCxHxW format.\n          input_size (tuple(int, int)): The size of the image input to the\n            model, in (H, W) format. Used to remove padding.\n          original_size (tuple(int, int)): The original size of the image\n            before resizing for input to the model, in (H, W) format.\n\n        Returns:\n          (torch.Tensor): Batched masks in BxCxHxW format, where (H, W)\n            is given by original_size.\n        \"\"\"\n        masks = F.interpolate(\n            masks,\n            (self.image_encoder.img_size, self.image_encoder.img_size),\n            mode='bilinear',\n            align_corners=False,\n        )\n        masks = masks[..., :input_size[0], :input_size[1]]\n        masks = F.interpolate(masks, original_size, mode='bilinear', align_corners=False)\n        return masks\n\n    def preprocess(self, x: torch.Tensor) -> torch.Tensor:\n        \"\"\"Normalize pixel values and pad to a square input.\"\"\"\n        # Normalize colors\n        x = (x - self.pixel_mean) / self.pixel_std\n\n        # Pad\n        h, w = x.shape[-2:]\n        padh = self.image_encoder.img_size - h\n        padw = self.image_encoder.img_size - w\n        return F.pad(x, (0, padw, 0, padh))\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/transformer.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport math\nfrom typing import Tuple, Type\n\nimport torch\nfrom torch import Tensor, nn\n\nfrom ultralytics.nn.modules import MLPBlock\n\n\nclass TwoWayTransformer(nn.Module):\n\n    def __init__(\n        self,\n        depth: int,\n        embedding_dim: int,\n        num_heads: int,\n        mlp_dim: int,\n        activation: Type[nn.Module] = nn.ReLU,\n        attention_downsample_rate: int = 2,\n    ) -> None:\n        \"\"\"\n        A transformer decoder that attends to an input image using\n        queries whose positional embedding is supplied.\n\n        Args:\n          depth (int): number of layers in the transformer\n          embedding_dim (int): the channel dimension for the input embeddings\n          num_heads (int): the number of heads for multihead attention. Must\n            divide embedding_dim\n          mlp_dim (int): the channel dimension internal to the MLP block\n          activation (nn.Module): the activation to use in the MLP block\n        \"\"\"\n        super().__init__()\n        self.depth = depth\n        self.embedding_dim = embedding_dim\n        self.num_heads = num_heads\n        self.mlp_dim = mlp_dim\n        self.layers = nn.ModuleList()\n\n        for i in range(depth):\n            self.layers.append(\n                TwoWayAttentionBlock(\n                    embedding_dim=embedding_dim,\n                    num_heads=num_heads,\n                    mlp_dim=mlp_dim,\n                    activation=activation,\n                    attention_downsample_rate=attention_downsample_rate,\n                    skip_first_layer_pe=(i == 0),\n                ))\n\n        self.final_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)\n        self.norm_final_attn = nn.LayerNorm(embedding_dim)\n\n    def forward(\n        self,\n        image_embedding: Tensor,\n        image_pe: Tensor,\n        point_embedding: Tensor,\n    ) -> Tuple[Tensor, Tensor]:\n        \"\"\"\n        Args:\n          image_embedding (torch.Tensor): image to attend to. Should be shape\n            B x embedding_dim x h x w for any h and w.\n          image_pe (torch.Tensor): the positional encoding to add to the image. Must\n            have the same shape as image_embedding.\n          point_embedding (torch.Tensor): the embedding to add to the query points.\n            Must have shape B x N_points x embedding_dim for any N_points.\n\n        Returns:\n          torch.Tensor: the processed point_embedding\n          torch.Tensor: the processed image_embedding\n        \"\"\"\n        # BxCxHxW -> BxHWxC == B x N_image_tokens x C\n        bs, c, h, w = image_embedding.shape\n        image_embedding = image_embedding.flatten(2).permute(0, 2, 1)\n        image_pe = image_pe.flatten(2).permute(0, 2, 1)\n\n        # Prepare queries\n        queries = point_embedding\n        keys = image_embedding\n\n        # Apply transformer blocks and final layernorm\n        for layer in self.layers:\n            queries, keys = layer(\n                queries=queries,\n                keys=keys,\n                query_pe=point_embedding,\n                key_pe=image_pe,\n            )\n\n        # Apply the final attention layer from the points to the image\n        q = queries + point_embedding\n        k = keys + image_pe\n        attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)\n        queries = queries + attn_out\n        queries = self.norm_final_attn(queries)\n\n        return queries, keys\n\n\nclass TwoWayAttentionBlock(nn.Module):\n\n    def __init__(\n        self,\n        embedding_dim: int,\n        num_heads: int,\n        mlp_dim: int = 2048,\n        activation: Type[nn.Module] = nn.ReLU,\n        attention_downsample_rate: int = 2,\n        skip_first_layer_pe: bool = False,\n    ) -> None:\n        \"\"\"\n        A transformer block with four layers: (1) self-attention of sparse\n        inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp\n        block on sparse inputs, and (4) cross attention of dense inputs to sparse\n        inputs.\n\n        Arguments:\n          embedding_dim (int): the channel dimension of the embeddings\n          num_heads (int): the number of heads in the attention layers\n          mlp_dim (int): the hidden dimension of the mlp block\n          activation (nn.Module): the activation of the mlp block\n          skip_first_layer_pe (bool): skip the PE on the first layer\n        \"\"\"\n        super().__init__()\n        self.self_attn = Attention(embedding_dim, num_heads)\n        self.norm1 = nn.LayerNorm(embedding_dim)\n\n        self.cross_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)\n        self.norm2 = nn.LayerNorm(embedding_dim)\n\n        self.mlp = MLPBlock(embedding_dim, mlp_dim, activation)\n        self.norm3 = nn.LayerNorm(embedding_dim)\n\n        self.norm4 = nn.LayerNorm(embedding_dim)\n        self.cross_attn_image_to_token = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)\n\n        self.skip_first_layer_pe = skip_first_layer_pe\n\n    def forward(self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor) -> Tuple[Tensor, Tensor]:\n        \"\"\"Apply self-attention and cross-attention to queries and keys and return the processed embeddings.\"\"\"\n\n        # Self attention block\n        if self.skip_first_layer_pe:\n            queries = self.self_attn(q=queries, k=queries, v=queries)\n        else:\n            q = queries + query_pe\n            attn_out = self.self_attn(q=q, k=q, v=queries)\n            queries = queries + attn_out\n        queries = self.norm1(queries)\n\n        # Cross attention block, tokens attending to image embedding\n        q = queries + query_pe\n        k = keys + key_pe\n        attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)\n        queries = queries + attn_out\n        queries = self.norm2(queries)\n\n        # MLP block\n        mlp_out = self.mlp(queries)\n        queries = queries + mlp_out\n        queries = self.norm3(queries)\n\n        # Cross attention block, image embedding attending to tokens\n        q = queries + query_pe\n        k = keys + key_pe\n        attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)\n        keys = keys + attn_out\n        keys = self.norm4(keys)\n\n        return queries, keys\n\n\nclass Attention(nn.Module):\n    \"\"\"\n    An attention layer that allows for downscaling the size of the embedding\n    after projection to queries, keys, and values.\n    \"\"\"\n\n    def __init__(\n        self,\n        embedding_dim: int,\n        num_heads: int,\n        downsample_rate: int = 1,\n    ) -> None:\n        super().__init__()\n        self.embedding_dim = embedding_dim\n        self.internal_dim = embedding_dim // downsample_rate\n        self.num_heads = num_heads\n        assert self.internal_dim % num_heads == 0, 'num_heads must divide embedding_dim.'\n\n        self.q_proj = nn.Linear(embedding_dim, self.internal_dim)\n        self.k_proj = nn.Linear(embedding_dim, self.internal_dim)\n        self.v_proj = nn.Linear(embedding_dim, self.internal_dim)\n        self.out_proj = nn.Linear(self.internal_dim, embedding_dim)\n\n    def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:\n        \"\"\"Separate the input tensor into the specified number of attention heads.\"\"\"\n        b, n, c = x.shape\n        x = x.reshape(b, n, num_heads, c // num_heads)\n        return x.transpose(1, 2)  # B x N_heads x N_tokens x C_per_head\n\n    def _recombine_heads(self, x: Tensor) -> Tensor:\n        \"\"\"Recombine the separated attention heads into a single tensor.\"\"\"\n        b, n_heads, n_tokens, c_per_head = x.shape\n        x = x.transpose(1, 2)\n        return x.reshape(b, n_tokens, n_heads * c_per_head)  # B x N_tokens x C\n\n    def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:\n        \"\"\"Compute the attention output given the input query, key, and value tensors.\"\"\"\n\n        # Input projections\n        q = self.q_proj(q)\n        k = self.k_proj(k)\n        v = self.v_proj(v)\n\n        # Separate into heads\n        q = self._separate_heads(q, self.num_heads)\n        k = self._separate_heads(k, self.num_heads)\n        v = self._separate_heads(v, self.num_heads)\n\n        # Attention\n        _, _, _, c_per_head = q.shape\n        attn = q @ k.permute(0, 1, 3, 2)  # B x N_heads x N_tokens x N_tokens\n        attn = attn / math.sqrt(c_per_head)\n        attn = torch.softmax(attn, dim=-1)\n\n        # Get output\n        out = attn @ v\n        out = self._recombine_heads(out)\n        out = self.out_proj(out)\n\n        return out\n"
  },
  {
    "path": "ultralytics/vit/sam/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport numpy as np\nimport torch\n\nfrom ultralytics.yolo.engine.predictor import BasePredictor\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils.torch_utils import select_device\n\nfrom .modules.mask_generator import SamAutomaticMaskGenerator\n\n\nclass Predictor(BasePredictor):\n\n    def preprocess(self, im):\n        \"\"\"Prepares input image for inference.\"\"\"\n        # TODO: Only support bs=1 for now\n        # im = ResizeLongestSide(1024).apply_image(im[0])\n        # im = torch.as_tensor(im, device=self.device)\n        # im = im.permute(2, 0, 1).contiguous()[None, :, :, :]\n        return im[0]\n\n    def setup_model(self, model):\n        \"\"\"Set up YOLO model with specified thresholds and device.\"\"\"\n        device = select_device(self.args.device)\n        model.eval()\n        self.model = SamAutomaticMaskGenerator(model.to(device),\n                                               pred_iou_thresh=self.args.conf,\n                                               box_nms_thresh=self.args.iou)\n        self.device = device\n        # TODO: Temporary settings for compatibility\n        self.model.pt = False\n        self.model.triton = False\n        self.model.stride = 32\n        self.model.fp16 = False\n        self.done_warmup = True\n\n    def postprocess(self, preds, path, orig_imgs):\n        \"\"\"Postprocesses inference output predictions to create detection masks for objects.\"\"\"\n        names = dict(enumerate(list(range(len(preds)))))\n        results = []\n        # TODO\n        for i, pred in enumerate([preds]):\n            masks = torch.from_numpy(np.stack([p['segmentation'] for p in pred], axis=0))\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(Results(orig_img=orig_img, path=img_path, names=names, masks=masks))\n        return results\n\n    # def __call__(self, source=None, model=None, stream=False):\n    #     frame = cv2.imread(source)\n    #     preds = self.model.generate(frame)\n    #     return self.postprocess(preds, source, frame)\n"
  },
  {
    "path": "ultralytics/vit/utils/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n"
  },
  {
    "path": "ultralytics/vit/utils/loss.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ultralytics.vit.utils.ops import HungarianMatcher\nfrom ultralytics.yolo.utils.loss import FocalLoss, VarifocalLoss\nfrom ultralytics.yolo.utils.metrics import bbox_iou\n\n\nclass DETRLoss(nn.Module):\n\n    def __init__(self,\n                 nc=80,\n                 loss_gain=None,\n                 aux_loss=True,\n                 use_fl=True,\n                 use_vfl=False,\n                 use_uni_match=False,\n                 uni_match_ind=0):\n        \"\"\"\n        DETR loss function.\n\n        Args:\n            nc (int): The number of classes.\n            loss_gain (dict): The coefficient of loss.\n            aux_loss (bool): If 'aux_loss = True', loss at each decoder layer are to be used.\n            use_vfl (bool): Use VarifocalLoss or not.\n            use_uni_match (bool): Whether to use a fixed layer to assign labels for auxiliary branch.\n            uni_match_ind (int): The fixed indices of a layer.\n        \"\"\"\n        super().__init__()\n\n        if loss_gain is None:\n            loss_gain = {'class': 1, 'bbox': 5, 'giou': 2, 'no_object': 0.1, 'mask': 1, 'dice': 1}\n        self.nc = nc\n        self.matcher = HungarianMatcher(cost_gain={'class': 2, 'bbox': 5, 'giou': 2})\n        self.loss_gain = loss_gain\n        self.aux_loss = aux_loss\n        self.fl = FocalLoss() if use_fl else None\n        self.vfl = VarifocalLoss() if use_vfl else None\n\n        self.use_uni_match = use_uni_match\n        self.uni_match_ind = uni_match_ind\n        self.device = None\n\n    def _get_loss_class(self, pred_scores, targets, gt_scores, num_gts, postfix=''):\n        # logits: [b, query, num_classes], gt_class: list[[n, 1]]\n        name_class = f'loss_class{postfix}'\n        bs, nq = pred_scores.shape[:2]\n        # one_hot = F.one_hot(targets, self.nc + 1)[..., :-1]  # (bs, num_queries, num_classes)\n        one_hot = torch.zeros((bs, nq, self.nc + 1), dtype=torch.int64, device=targets.device)\n        one_hot.scatter_(2, targets.unsqueeze(-1), 1)\n        one_hot = one_hot[..., :-1]\n        gt_scores = gt_scores.view(bs, nq, 1) * one_hot\n\n        if self.fl:\n            if num_gts and self.vfl:\n                loss_cls = self.vfl(pred_scores, gt_scores, one_hot)\n            else:\n                loss_cls = self.fl(pred_scores, one_hot.float())\n            loss_cls /= max(num_gts, 1) / nq\n        else:\n            loss_cls = nn.BCEWithLogitsLoss(reduction='none')(pred_scores, gt_scores).mean(1).sum()  # YOLO CLS loss\n\n        return {name_class: loss_cls.squeeze() * self.loss_gain['class']}\n\n    def _get_loss_bbox(self, pred_bboxes, gt_bboxes, postfix=''):\n        # boxes: [b, query, 4], gt_bbox: list[[n, 4]]\n        name_bbox = f'loss_bbox{postfix}'\n        name_giou = f'loss_giou{postfix}'\n\n        loss = {}\n        if len(gt_bboxes) == 0:\n            loss[name_bbox] = torch.tensor(0., device=self.device)\n            loss[name_giou] = torch.tensor(0., device=self.device)\n            return loss\n\n        loss[name_bbox] = self.loss_gain['bbox'] * F.l1_loss(pred_bboxes, gt_bboxes, reduction='sum') / len(gt_bboxes)\n        loss[name_giou] = 1.0 - bbox_iou(pred_bboxes, gt_bboxes, xywh=True, GIoU=True)\n        loss[name_giou] = loss[name_giou].sum() / len(gt_bboxes)\n        loss[name_giou] = self.loss_gain['giou'] * loss[name_giou]\n        loss = {k: v.squeeze() for k, v in loss.items()}\n        return loss\n\n    def _get_loss_mask(self, masks, gt_mask, match_indices, postfix=''):\n        # masks: [b, query, h, w], gt_mask: list[[n, H, W]]\n        name_mask = f'loss_mask{postfix}'\n        name_dice = f'loss_dice{postfix}'\n\n        loss = {}\n        if sum(len(a) for a in gt_mask) == 0:\n            loss[name_mask] = torch.tensor(0., device=self.device)\n            loss[name_dice] = torch.tensor(0., device=self.device)\n            return loss\n\n        num_gts = len(gt_mask)\n        src_masks, target_masks = self._get_assigned_bboxes(masks, gt_mask, match_indices)\n        src_masks = F.interpolate(src_masks.unsqueeze(0), size=target_masks.shape[-2:], mode='bilinear')[0]\n        # TODO: torch does not have `sigmoid_focal_loss`, but it's not urgent since we don't use mask branch for now.\n        loss[name_mask] = self.loss_gain['mask'] * F.sigmoid_focal_loss(src_masks, target_masks,\n                                                                        torch.tensor([num_gts], dtype=torch.float32))\n        loss[name_dice] = self.loss_gain['dice'] * self._dice_loss(src_masks, target_masks, num_gts)\n        return loss\n\n    def _dice_loss(self, inputs, targets, num_gts):\n        inputs = F.sigmoid(inputs)\n        inputs = inputs.flatten(1)\n        targets = targets.flatten(1)\n        numerator = 2 * (inputs * targets).sum(1)\n        denominator = inputs.sum(-1) + targets.sum(-1)\n        loss = 1 - (numerator + 1) / (denominator + 1)\n        return loss.sum() / num_gts\n\n    def _get_loss_aux(self,\n                      pred_bboxes,\n                      pred_scores,\n                      gt_bboxes,\n                      gt_cls,\n                      gt_groups,\n                      match_indices=None,\n                      postfix='',\n                      masks=None,\n                      gt_mask=None):\n        \"\"\"Get auxiliary losses\"\"\"\n        # NOTE: loss class, bbox, giou, mask, dice\n        loss = torch.zeros(5 if masks is not None else 3, device=pred_bboxes.device)\n        if match_indices is None and self.use_uni_match:\n            match_indices = self.matcher(pred_bboxes[self.uni_match_ind],\n                                         pred_scores[self.uni_match_ind],\n                                         gt_bboxes,\n                                         gt_cls,\n                                         gt_groups,\n                                         masks=masks[self.uni_match_ind] if masks is not None else None,\n                                         gt_mask=gt_mask)\n        for i, (aux_bboxes, aux_scores) in enumerate(zip(pred_bboxes, pred_scores)):\n            aux_masks = masks[i] if masks is not None else None\n            loss_ = self._get_loss(aux_bboxes,\n                                   aux_scores,\n                                   gt_bboxes,\n                                   gt_cls,\n                                   gt_groups,\n                                   masks=aux_masks,\n                                   gt_mask=gt_mask,\n                                   postfix=postfix,\n                                   match_indices=match_indices)\n            loss[0] += loss_[f'loss_class{postfix}']\n            loss[1] += loss_[f'loss_bbox{postfix}']\n            loss[2] += loss_[f'loss_giou{postfix}']\n            # if masks is not None and gt_mask is not None:\n            #     loss_ = self._get_loss_mask(aux_masks, gt_mask, match_indices, postfix)\n            #     loss[3] += loss_[f'loss_mask{postfix}']\n            #     loss[4] += loss_[f'loss_dice{postfix}']\n\n        loss = {\n            f'loss_class_aux{postfix}': loss[0],\n            f'loss_bbox_aux{postfix}': loss[1],\n            f'loss_giou_aux{postfix}': loss[2]}\n        # if masks is not None and gt_mask is not None:\n        #     loss[f'loss_mask_aux{postfix}'] = loss[3]\n        #     loss[f'loss_dice_aux{postfix}'] = loss[4]\n        return loss\n\n    def _get_index(self, match_indices):\n        batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(match_indices)])\n        src_idx = torch.cat([src for (src, _) in match_indices])\n        dst_idx = torch.cat([dst for (_, dst) in match_indices])\n        return (batch_idx, src_idx), dst_idx\n\n    def _get_assigned_bboxes(self, pred_bboxes, gt_bboxes, match_indices):\n        pred_assigned = torch.cat([\n            t[I] if len(I) > 0 else torch.zeros(0, t.shape[-1], device=self.device)\n            for t, (I, _) in zip(pred_bboxes, match_indices)])\n        gt_assigned = torch.cat([\n            t[J] if len(J) > 0 else torch.zeros(0, t.shape[-1], device=self.device)\n            for t, (_, J) in zip(gt_bboxes, match_indices)])\n        return pred_assigned, gt_assigned\n\n    def _get_loss(self,\n                  pred_bboxes,\n                  pred_scores,\n                  gt_bboxes,\n                  gt_cls,\n                  gt_groups,\n                  masks=None,\n                  gt_mask=None,\n                  postfix='',\n                  match_indices=None):\n        \"\"\"Get losses\"\"\"\n        if match_indices is None:\n            match_indices = self.matcher(pred_bboxes,\n                                         pred_scores,\n                                         gt_bboxes,\n                                         gt_cls,\n                                         gt_groups,\n                                         masks=masks,\n                                         gt_mask=gt_mask)\n\n        idx, gt_idx = self._get_index(match_indices)\n        pred_bboxes, gt_bboxes = pred_bboxes[idx], gt_bboxes[gt_idx]\n\n        bs, nq = pred_scores.shape[:2]\n        targets = torch.full((bs, nq), self.nc, device=pred_scores.device, dtype=gt_cls.dtype)\n        targets[idx] = gt_cls[gt_idx]\n\n        gt_scores = torch.zeros([bs, nq], device=pred_scores.device)\n        if len(gt_bboxes):\n            gt_scores[idx] = bbox_iou(pred_bboxes.detach(), gt_bboxes, xywh=True).squeeze(-1)\n\n        loss = {}\n        loss.update(self._get_loss_class(pred_scores, targets, gt_scores, len(gt_bboxes), postfix))\n        loss.update(self._get_loss_bbox(pred_bboxes, gt_bboxes, postfix))\n        # if masks is not None and gt_mask is not None:\n        #     loss.update(self._get_loss_mask(masks, gt_mask, match_indices, postfix))\n        return loss\n\n    def forward(self, pred_bboxes, pred_scores, batch, postfix='', **kwargs):\n        \"\"\"\n        Args:\n            pred_bboxes (torch.Tensor): [l, b, query, 4]\n            pred_scores (torch.Tensor): [l, b, query, num_classes]\n            batch (dict): A dict includes:\n                gt_cls (torch.Tensor) with shape [num_gts, ],\n                gt_bboxes (torch.Tensor): [num_gts, 4],\n                gt_groups (List(int)): a list of batch size length includes the number of gts of each image.\n            postfix (str): postfix of loss name.\n        \"\"\"\n        self.device = pred_bboxes.device\n        match_indices = kwargs.get('match_indices', None)\n        gt_cls, gt_bboxes, gt_groups = batch['cls'], batch['bboxes'], batch['gt_groups']\n\n        total_loss = self._get_loss(pred_bboxes[-1],\n                                    pred_scores[-1],\n                                    gt_bboxes,\n                                    gt_cls,\n                                    gt_groups,\n                                    postfix=postfix,\n                                    match_indices=match_indices)\n\n        if self.aux_loss:\n            total_loss.update(\n                self._get_loss_aux(pred_bboxes[:-1], pred_scores[:-1], gt_bboxes, gt_cls, gt_groups, match_indices,\n                                   postfix))\n\n        return total_loss\n\n\nclass RTDETRDetectionLoss(DETRLoss):\n\n    def forward(self, preds, batch, dn_bboxes=None, dn_scores=None, dn_meta=None):\n        pred_bboxes, pred_scores = preds\n        total_loss = super().forward(pred_bboxes, pred_scores, batch)\n\n        if dn_meta is not None:\n            dn_pos_idx, dn_num_group = dn_meta['dn_pos_idx'], dn_meta['dn_num_group']\n            assert len(batch['gt_groups']) == len(dn_pos_idx)\n\n            # denoising match indices\n            match_indices = self.get_dn_match_indices(dn_pos_idx, dn_num_group, batch['gt_groups'])\n\n            # compute denoising training loss\n            dn_loss = super().forward(dn_bboxes, dn_scores, batch, postfix='_dn', match_indices=match_indices)\n            total_loss.update(dn_loss)\n        else:\n            total_loss.update({f'{k}_dn': torch.tensor(0., device=self.device) for k in total_loss.keys()})\n\n        return total_loss\n\n    @staticmethod\n    def get_dn_match_indices(dn_pos_idx, dn_num_group, gt_groups):\n        \"\"\"Get the match indices for denoising.\n\n        Args:\n            dn_pos_idx (List[torch.Tensor]): A list includes positive indices of denoising.\n            dn_num_group (int): The number of groups of denoising.\n            gt_groups (List(int)): a list of batch size length includes the number of gts of each image.\n\n        Returns:\n            dn_match_indices (List(tuple)): Matched indices.\n\n        \"\"\"\n        dn_match_indices = []\n        idx_groups = torch.as_tensor([0, *gt_groups[:-1]]).cumsum_(0)\n        for i, num_gt in enumerate(gt_groups):\n            if num_gt > 0:\n                gt_idx = torch.arange(end=num_gt, dtype=torch.int32) + idx_groups[i]\n                gt_idx = gt_idx.repeat(dn_num_group)\n                assert len(dn_pos_idx[i]) == len(gt_idx), 'Expected the same length, '\n                f'but got {len(dn_pos_idx[i])} and {len(gt_idx)} respectively.'\n                dn_match_indices.append((dn_pos_idx[i], gt_idx))\n            else:\n                dn_match_indices.append((torch.zeros([0], dtype=torch.int32), torch.zeros([0], dtype=torch.int32)))\n        return dn_match_indices\n"
  },
  {
    "path": "ultralytics/vit/utils/ops.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom scipy.optimize import linear_sum_assignment\n\nfrom ultralytics.yolo.utils.metrics import bbox_iou\nfrom ultralytics.yolo.utils.ops import xywh2xyxy, xyxy2xywh\n\n\nclass HungarianMatcher(nn.Module):\n    \"\"\"\n    A module implementing the HungarianMatcher, which is a differentiable module to solve the assignment problem in\n    an end-to-end fashion.\n\n    HungarianMatcher performs optimal assignment over predicted and ground truth bounding boxes using a cost function\n    that considers classification scores, bounding box coordinates, and optionally, mask predictions.\n\n    Attributes:\n        cost_gain (dict): Dictionary of cost coefficients for different components: 'class', 'bbox', 'giou', 'mask', and 'dice'.\n        use_fl (bool): Indicates whether to use Focal Loss for the classification cost calculation.\n        with_mask (bool): Indicates whether the model makes mask predictions.\n        num_sample_points (int): The number of sample points used in mask cost calculation.\n        alpha (float): The alpha factor in Focal Loss calculation.\n        gamma (float): The gamma factor in Focal Loss calculation.\n\n    Methods:\n        forward(pred_bboxes, pred_scores, gt_bboxes, gt_cls, gt_groups, masks=None, gt_mask=None): Computes the assignment\n        between predictions and ground truths for a batch.\n        _cost_mask(bs, num_gts, masks=None, gt_mask=None): Computes the mask cost and dice cost if masks are predicted.\n    \"\"\"\n\n    def __init__(self, cost_gain=None, use_fl=True, with_mask=False, num_sample_points=12544, alpha=0.25, gamma=2.0):\n        super().__init__()\n        if cost_gain is None:\n            cost_gain = {'class': 1, 'bbox': 5, 'giou': 2, 'mask': 1, 'dice': 1}\n        self.cost_gain = cost_gain\n        self.use_fl = use_fl\n        self.with_mask = with_mask\n        self.num_sample_points = num_sample_points\n        self.alpha = alpha\n        self.gamma = gamma\n\n    def forward(self, pred_bboxes, pred_scores, gt_bboxes, gt_cls, gt_groups, masks=None, gt_mask=None):\n        \"\"\"\n        Forward pass for HungarianMatcher. This function computes costs based on prediction and ground truth\n        (classification cost, L1 cost between boxes and GIoU cost between boxes) and finds the optimal matching\n        between predictions and ground truth based on these costs.\n\n        Args:\n            pred_bboxes (Tensor): Predicted bounding boxes with shape [batch_size, num_queries, 4].\n            pred_scores (Tensor): Predicted scores with shape [batch_size, num_queries, num_classes].\n            gt_cls (torch.Tensor): Ground truth classes with shape [num_gts, ].\n            gt_bboxes (torch.Tensor): Ground truth bounding boxes with shape [num_gts, 4].\n            gt_groups (List[int]): List of length equal to batch size, containing the number of ground truths for\n                each image.\n            masks (Tensor, optional): Predicted masks with shape [batch_size, num_queries, height, width].\n                Defaults to None.\n            gt_mask (List[Tensor], optional): List of ground truth masks, each with shape [num_masks, Height, Width].\n                Defaults to None.\n\n        Returns:\n            (List[Tuple[Tensor, Tensor]]): A list of size batch_size, each element is a tuple (index_i, index_j), where:\n                - index_i is the tensor of indices of the selected predictions (in order)\n                - index_j is the tensor of indices of the corresponding selected ground truth targets (in order)\n                For each batch element, it holds:\n                    len(index_i) = len(index_j) = min(num_queries, num_target_boxes)\n        \"\"\"\n\n        bs, nq, nc = pred_scores.shape\n\n        if sum(gt_groups) == 0:\n            return [(torch.tensor([], dtype=torch.int32), torch.tensor([], dtype=torch.int32)) for _ in range(bs)]\n\n        # We flatten to compute the cost matrices in a batch\n        # [batch_size * num_queries, num_classes]\n        pred_scores = pred_scores.detach().view(-1, nc)\n        pred_scores = F.sigmoid(pred_scores) if self.use_fl else F.softmax(pred_scores, dim=-1)\n        # [batch_size * num_queries, 4]\n        pred_bboxes = pred_bboxes.detach().view(-1, 4)\n\n        # Compute the classification cost\n        pred_scores = pred_scores[:, gt_cls]\n        if self.use_fl:\n            neg_cost_class = (1 - self.alpha) * (pred_scores ** self.gamma) * (-(1 - pred_scores + 1e-8).log())\n            pos_cost_class = self.alpha * ((1 - pred_scores) ** self.gamma) * (-(pred_scores + 1e-8).log())\n            cost_class = pos_cost_class - neg_cost_class\n        else:\n            cost_class = -pred_scores\n\n        # Compute the L1 cost between boxes\n        cost_bbox = (pred_bboxes.unsqueeze(1) - gt_bboxes.unsqueeze(0)).abs().sum(-1)  # (bs*num_queries, num_gt)\n\n        # Compute the GIoU cost between boxes, (bs*num_queries, num_gt)\n        cost_giou = 1.0 - bbox_iou(pred_bboxes.unsqueeze(1), gt_bboxes.unsqueeze(0), xywh=True, GIoU=True).squeeze(-1)\n\n        # Final cost matrix\n        C = self.cost_gain['class'] * cost_class + \\\n            self.cost_gain['bbox'] * cost_bbox + \\\n            self.cost_gain['giou'] * cost_giou\n        # Compute the mask cost and dice cost\n        if self.with_mask:\n            C += self._cost_mask(bs, gt_groups, masks, gt_mask)\n\n        C = C.view(bs, nq, -1).cpu()\n        indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(gt_groups, -1))]\n        gt_groups = torch.as_tensor([0, *gt_groups[:-1]]).cumsum_(0)\n        # (idx for queries, idx for gt)\n        return [(torch.tensor(i, dtype=torch.int32), torch.tensor(j, dtype=torch.int32) + gt_groups[k])\n                for k, (i, j) in enumerate(indices)]\n\n    def _cost_mask(self, bs, num_gts, masks=None, gt_mask=None):\n        assert masks is not None and gt_mask is not None, 'Make sure the input has `mask` and `gt_mask`'\n        # all masks share the same set of points for efficient matching\n        sample_points = torch.rand([bs, 1, self.num_sample_points, 2])\n        sample_points = 2.0 * sample_points - 1.0\n\n        out_mask = F.grid_sample(masks.detach(), sample_points, align_corners=False).squeeze(-2)\n        out_mask = out_mask.flatten(0, 1)\n\n        tgt_mask = torch.cat(gt_mask).unsqueeze(1)\n        sample_points = torch.cat([a.repeat(b, 1, 1, 1) for a, b in zip(sample_points, num_gts) if b > 0])\n        tgt_mask = F.grid_sample(tgt_mask, sample_points, align_corners=False).squeeze([1, 2])\n\n        with torch.cuda.amp.autocast(False):\n            # binary cross entropy cost\n            pos_cost_mask = F.binary_cross_entropy_with_logits(out_mask, torch.ones_like(out_mask), reduction='none')\n            neg_cost_mask = F.binary_cross_entropy_with_logits(out_mask, torch.zeros_like(out_mask), reduction='none')\n            cost_mask = torch.matmul(pos_cost_mask, tgt_mask.T) + torch.matmul(neg_cost_mask, 1 - tgt_mask.T)\n            cost_mask /= self.num_sample_points\n\n            # dice cost\n            out_mask = F.sigmoid(out_mask)\n            numerator = 2 * torch.matmul(out_mask, tgt_mask.T)\n            denominator = out_mask.sum(-1, keepdim=True) + tgt_mask.sum(-1).unsqueeze(0)\n            cost_dice = 1 - (numerator + 1) / (denominator + 1)\n\n            C = self.cost_gain['mask'] * cost_mask + self.cost_gain['dice'] * cost_dice\n        return C\n\n\ndef get_cdn_group(batch,\n                  num_classes,\n                  num_queries,\n                  class_embed,\n                  num_dn=100,\n                  cls_noise_ratio=0.5,\n                  box_noise_scale=1.0,\n                  training=False):\n    \"\"\"\n    Get contrastive denoising training group. This function creates a contrastive denoising training group with\n    positive and negative samples from the ground truths (gt). It applies noise to the class labels and bounding\n    box coordinates, and returns the modified labels, bounding boxes, attention mask and meta information.\n\n    Args:\n        batch (dict): A dict that includes 'gt_cls' (torch.Tensor with shape [num_gts, ]), 'gt_bboxes'\n            (torch.Tensor with shape [num_gts, 4]), 'gt_groups' (List(int)) which is a list of batch size length\n            indicating the number of gts of each image.\n        num_classes (int): Number of classes.\n        num_queries (int): Number of queries.\n        class_embed (torch.Tensor): Embedding weights to map class labels to embedding space.\n        num_dn (int, optional): Number of denoising. Defaults to 100.\n        cls_noise_ratio (float, optional): Noise ratio for class labels. Defaults to 0.5.\n        box_noise_scale (float, optional): Noise scale for bounding box coordinates. Defaults to 1.0.\n        training (bool, optional): If it's in training mode. Defaults to False.\n\n    Returns:\n        (Tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Dict]]): The modified class embeddings,\n            bounding boxes, attention mask and meta information for denoising. If not in training mode or 'num_dn'\n            is less than or equal to 0, the function returns None for all elements in the tuple.\n    \"\"\"\n\n    if (not training) or num_dn <= 0:\n        return None, None, None, None\n    gt_groups = batch['gt_groups']\n    total_num = sum(gt_groups)\n    max_nums = max(gt_groups)\n    if max_nums == 0:\n        return None, None, None, None\n\n    num_group = num_dn // max_nums\n    num_group = 1 if num_group == 0 else num_group\n    # pad gt to max_num of a batch\n    bs = len(gt_groups)\n    gt_cls = batch['cls']  # (bs*num, )\n    gt_bbox = batch['bboxes']  # bs*num, 4\n    b_idx = batch['batch_idx']\n\n    # each group has positive and negative queries.\n    dn_cls = gt_cls.repeat(2 * num_group)  # (2*num_group*bs*num, )\n    dn_bbox = gt_bbox.repeat(2 * num_group, 1)  # 2*num_group*bs*num, 4\n    dn_b_idx = b_idx.repeat(2 * num_group).view(-1)  # (2*num_group*bs*num, )\n\n    # positive and negative mask\n    # (bs*num*num_group, ), the second total_num*num_group part as negative samples\n    neg_idx = torch.arange(total_num * num_group, dtype=torch.long, device=gt_bbox.device) + num_group * total_num\n\n    if cls_noise_ratio > 0:\n        # half of bbox prob\n        mask = torch.rand(dn_cls.shape) < (cls_noise_ratio * 0.5)\n        idx = torch.nonzero(mask).squeeze(-1)\n        # randomly put a new one here\n        new_label = torch.randint_like(idx, 0, num_classes, dtype=dn_cls.dtype, device=dn_cls.device)\n        dn_cls[idx] = new_label\n\n    if box_noise_scale > 0:\n        known_bbox = xywh2xyxy(dn_bbox)\n\n        diff = (dn_bbox[..., 2:] * 0.5).repeat(1, 2) * box_noise_scale  # 2*num_group*bs*num, 4\n\n        rand_sign = torch.randint_like(dn_bbox, 0, 2) * 2.0 - 1.0\n        rand_part = torch.rand_like(dn_bbox)\n        rand_part[neg_idx] += 1.0\n        rand_part *= rand_sign\n        known_bbox += rand_part * diff\n        known_bbox.clip_(min=0.0, max=1.0)\n        dn_bbox = xyxy2xywh(known_bbox)\n        dn_bbox = inverse_sigmoid(dn_bbox)\n\n    # total denoising queries\n    num_dn = int(max_nums * 2 * num_group)\n    # class_embed = torch.cat([class_embed, torch.zeros([1, class_embed.shape[-1]], device=class_embed.device)])\n    dn_cls_embed = class_embed[dn_cls]  # bs*num * 2 * num_group, 256\n    padding_cls = torch.zeros(bs, num_dn, dn_cls_embed.shape[-1], device=gt_cls.device)\n    padding_bbox = torch.zeros(bs, num_dn, 4, device=gt_bbox.device)\n\n    map_indices = torch.cat([torch.tensor(range(num), dtype=torch.long) for num in gt_groups])\n    pos_idx = torch.stack([map_indices + max_nums * i for i in range(num_group)], dim=0)\n\n    map_indices = torch.cat([map_indices + max_nums * i for i in range(2 * num_group)])\n    padding_cls[(dn_b_idx, map_indices)] = dn_cls_embed\n    padding_bbox[(dn_b_idx, map_indices)] = dn_bbox\n\n    tgt_size = num_dn + num_queries\n    attn_mask = torch.zeros([tgt_size, tgt_size], dtype=torch.bool)\n    # match query cannot see the reconstruct\n    attn_mask[num_dn:, :num_dn] = True\n    # reconstruct cannot see each other\n    for i in range(num_group):\n        if i == 0:\n            attn_mask[max_nums * 2 * i:max_nums * 2 * (i + 1), max_nums * 2 * (i + 1):num_dn] = True\n        if i == num_group - 1:\n            attn_mask[max_nums * 2 * i:max_nums * 2 * (i + 1), :max_nums * i * 2] = True\n        else:\n            attn_mask[max_nums * 2 * i:max_nums * 2 * (i + 1), max_nums * 2 * (i + 1):num_dn] = True\n            attn_mask[max_nums * 2 * i:max_nums * 2 * (i + 1), :max_nums * 2 * i] = True\n    dn_meta = {\n        'dn_pos_idx': [p.reshape(-1) for p in pos_idx.cpu().split(list(gt_groups), dim=1)],\n        'dn_num_group': num_group,\n        'dn_num_split': [num_dn, num_queries]}\n\n    return padding_cls.to(class_embed.device), padding_bbox.to(class_embed.device), attn_mask.to(\n        class_embed.device), dn_meta\n\n\ndef inverse_sigmoid(x, eps=1e-6):\n    \"\"\"Inverse sigmoid function.\"\"\"\n    x = x.clip(min=0., max=1.)\n    return torch.log(x / (1 - x + eps) + eps)\n"
  },
  {
    "path": "ultralytics/yolo/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom . import v8\n\n__all__ = 'v8',  # tuple or list\n"
  },
  {
    "path": "ultralytics/yolo/cfg/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport re\nimport shutil\nimport sys\nfrom difflib import get_close_matches\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom typing import Dict, List, Union\n\nfrom ultralytics.yolo.utils import (DEFAULT_CFG, DEFAULT_CFG_DICT, DEFAULT_CFG_PATH, LOGGER, ROOT, USER_CONFIG_DIR,\n                                    IterableSimpleNamespace, __version__, checks, colorstr, deprecation_warn,\n                                    get_settings, yaml_load, yaml_print)\n\n# Define valid tasks and modes\nMODES = 'train', 'val', 'predict', 'export', 'track', 'benchmark'\nTASKS = 'detect', 'segment', 'classify', 'pose'\nTASK2DATA = {\n    'detect': 'coco128.yaml',\n    'segment': 'coco128-seg.yaml',\n    'classify': 'imagenet100',\n    'pose': 'coco8-pose.yaml'}\nTASK2MODEL = {\n    'detect': 'yolov8n.pt',\n    'segment': 'yolov8n-seg.pt',\n    'classify': 'yolov8n-cls.pt',\n    'pose': 'yolov8n-pose.pt'}\n\nCLI_HELP_MSG = \\\n    f\"\"\"\n    Arguments received: {str(['yolo'] + sys.argv[1:])}. Ultralytics 'yolo' commands use the following syntax:\n\n        yolo TASK MODE ARGS\n\n        Where   TASK (optional) is one of {TASKS}\n                MODE (required) is one of {MODES}\n                ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.\n                    See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg'\n\n    1. Train a detection model for 10 epochs with an initial learning_rate of 0.01\n        yolo train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01\n\n    2. Predict a YouTube video using a pretrained segmentation model at image size 320:\n        yolo predict model=yolov8n-seg.pt source='https://youtu.be/Zgi9g1ksQHc' imgsz=320\n\n    3. Val a pretrained detection model at batch-size 1 and image size 640:\n        yolo val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640\n\n    4. Export a YOLOv8n classification model to ONNX format at image size 224 by 128 (no TASK required)\n        yolo export model=yolov8n-cls.pt format=onnx imgsz=224,128\n\n    5. Run special commands:\n        yolo help\n        yolo checks\n        yolo version\n        yolo settings\n        yolo copy-cfg\n        yolo cfg\n\n    Docs: https://docs.ultralytics.com\n    Community: https://community.ultralytics.com\n    GitHub: https://github.com/ultralytics/ultralytics\n    \"\"\"\n\n# Define keys for arg type checks\nCFG_FLOAT_KEYS = 'warmup_epochs', 'box', 'cls', 'dfl', 'degrees', 'shear'\nCFG_FRACTION_KEYS = ('dropout', 'iou', 'lr0', 'lrf', 'momentum', 'weight_decay', 'warmup_momentum', 'warmup_bias_lr',\n                     'label_smoothing', 'hsv_h', 'hsv_s', 'hsv_v', 'translate', 'scale', 'perspective', 'flipud',\n                     'fliplr', 'mosaic', 'mixup', 'copy_paste', 'conf', 'iou', 'fraction')  # fraction floats 0.0 - 1.0\nCFG_INT_KEYS = ('epochs', 'patience', 'batch', 'workers', 'seed', 'close_mosaic', 'mask_ratio', 'max_det', 'vid_stride',\n                'line_width', 'workspace', 'nbs', 'save_period')\nCFG_BOOL_KEYS = ('save', 'exist_ok', 'verbose', 'deterministic', 'single_cls', 'rect', 'cos_lr', 'overlap_mask', 'val',\n                 'save_json', 'save_hybrid', 'half', 'dnn', 'plots', 'show', 'save_txt', 'save_conf', 'save_crop',\n                 'show_labels', 'show_conf', 'visualize', 'augment', 'agnostic_nms', 'retina_masks', 'boxes', 'keras',\n                 'optimize', 'int8', 'dynamic', 'simplify', 'nms', 'v5loader', 'profile')\n\n\ndef cfg2dict(cfg):\n    \"\"\"\n    Convert a configuration object to a dictionary, whether it is a file path, a string, or a SimpleNamespace object.\n\n    Args:\n        cfg (str | Path | SimpleNamespace): Configuration object to be converted to a dictionary.\n\n    Returns:\n        cfg (dict): Configuration object in dictionary format.\n    \"\"\"\n    if isinstance(cfg, (str, Path)):\n        cfg = yaml_load(cfg)  # load dict\n    elif isinstance(cfg, SimpleNamespace):\n        cfg = vars(cfg)  # convert to dict\n    return cfg\n\n\ndef get_cfg(cfg: Union[str, Path, Dict, SimpleNamespace] = DEFAULT_CFG_DICT, overrides: Dict = None):\n    \"\"\"\n    Load and merge configuration data from a file or dictionary.\n\n    Args:\n        cfg (str | Path | Dict | SimpleNamespace): Configuration data.\n        overrides (str | Dict | optional): Overrides in the form of a file name or a dictionary. Default is None.\n\n    Returns:\n        (SimpleNamespace): Training arguments namespace.\n    \"\"\"\n    cfg = cfg2dict(cfg)\n\n    # Merge overrides\n    if overrides:\n        overrides = cfg2dict(overrides)\n        check_cfg_mismatch(cfg, overrides)\n        cfg = {**cfg, **overrides}  # merge cfg and overrides dicts (prefer overrides)\n\n    # Special handling for numeric project/name\n    for k in 'project', 'name':\n        if k in cfg and isinstance(cfg[k], (int, float)):\n            cfg[k] = str(cfg[k])\n    if cfg.get('name') == 'model':  # assign model to 'name' arg\n        cfg['name'] = cfg.get('model', '').split('.')[0]\n        LOGGER.warning(f\"WARNING ⚠️ 'name=model' automatically updated to 'name={cfg['name']}'.\")\n\n    # Type and Value checks\n    for k, v in cfg.items():\n        if v is not None:  # None values may be from optional args\n            if k in CFG_FLOAT_KEYS and not isinstance(v, (int, float)):\n                raise TypeError(f\"'{k}={v}' is of invalid type {type(v).__name__}. \"\n                                f\"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')\")\n            elif k in CFG_FRACTION_KEYS:\n                if not isinstance(v, (int, float)):\n                    raise TypeError(f\"'{k}={v}' is of invalid type {type(v).__name__}. \"\n                                    f\"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')\")\n                if not (0.0 <= v <= 1.0):\n                    raise ValueError(f\"'{k}={v}' is an invalid value. \"\n                                     f\"Valid '{k}' values are between 0.0 and 1.0.\")\n            elif k in CFG_INT_KEYS and not isinstance(v, int):\n                raise TypeError(f\"'{k}={v}' is of invalid type {type(v).__name__}. \"\n                                f\"'{k}' must be an int (i.e. '{k}=8')\")\n            elif k in CFG_BOOL_KEYS and not isinstance(v, bool):\n                raise TypeError(f\"'{k}={v}' is of invalid type {type(v).__name__}. \"\n                                f\"'{k}' must be a bool (i.e. '{k}=True' or '{k}=False')\")\n\n    # Return instance\n    return IterableSimpleNamespace(**cfg)\n\n\ndef _handle_deprecation(custom):\n    \"\"\"\n    Hardcoded function to handle deprecated config keys\n    \"\"\"\n\n    for key in custom.copy().keys():\n        if key == 'hide_labels':\n            deprecation_warn(key, 'show_labels')\n            custom['show_labels'] = custom.pop('hide_labels') == 'False'\n        if key == 'hide_conf':\n            deprecation_warn(key, 'show_conf')\n            custom['show_conf'] = custom.pop('hide_conf') == 'False'\n        if key == 'line_thickness':\n            deprecation_warn(key, 'line_width')\n            custom['line_width'] = custom.pop('line_thickness')\n\n    return custom\n\n\ndef check_cfg_mismatch(base: Dict, custom: Dict, e=None):\n    \"\"\"\n    This function checks for any mismatched keys between a custom configuration list and a base configuration list.\n    If any mismatched keys are found, the function prints out similar keys from the base list and exits the program.\n\n    Args:\n        custom (Dict): a dictionary of custom configuration options\n        base (Dict): a dictionary of base configuration options\n    \"\"\"\n    custom = _handle_deprecation(custom)\n    base, custom = (set(x.keys()) for x in (base, custom))\n    mismatched = [x for x in custom if x not in base]\n    if mismatched:\n        string = ''\n        for x in mismatched:\n            matches = get_close_matches(x, base)  # key list\n            matches = [f'{k}={DEFAULT_CFG_DICT[k]}' if DEFAULT_CFG_DICT.get(k) is not None else k for k in matches]\n            match_str = f'Similar arguments are i.e. {matches}.' if matches else ''\n            string += f\"'{colorstr('red', 'bold', x)}' is not a valid YOLO argument. {match_str}\\n\"\n        raise SyntaxError(string + CLI_HELP_MSG) from e\n\n\ndef merge_equals_args(args: List[str]) -> List[str]:\n    \"\"\"\n    Merges arguments around isolated '=' args in a list of strings.\n    The function considers cases where the first argument ends with '=' or the second starts with '=',\n    as well as when the middle one is an equals sign.\n\n    Args:\n        args (List[str]): A list of strings where each element is an argument.\n\n    Returns:\n        List[str]: A list of strings where the arguments around isolated '=' are merged.\n    \"\"\"\n    new_args = []\n    for i, arg in enumerate(args):\n        if arg == '=' and 0 < i < len(args) - 1:  # merge ['arg', '=', 'val']\n            new_args[-1] += f'={args[i + 1]}'\n            del args[i + 1]\n        elif arg.endswith('=') and i < len(args) - 1 and '=' not in args[i + 1]:  # merge ['arg=', 'val']\n            new_args.append(f'{arg}{args[i + 1]}')\n            del args[i + 1]\n        elif arg.startswith('=') and i > 0:  # merge ['arg', '=val']\n            new_args[-1] += arg\n        else:\n            new_args.append(arg)\n    return new_args\n\n\ndef handle_yolo_hub(args: List[str]) -> None:\n    \"\"\"\n    Handle Ultralytics HUB command-line interface (CLI) commands.\n\n    This function processes Ultralytics HUB CLI commands such as login and logout.\n    It should be called when executing a script with arguments related to HUB authentication.\n\n    Args:\n        args (List[str]): A list of command line arguments\n\n    Example:\n        python my_script.py hub login your_api_key\n    \"\"\"\n    from ultralytics import hub\n\n    if args[0] == 'login':\n        key = args[1] if len(args) > 1 else ''\n        # Log in to Ultralytics HUB using the provided API key\n        hub.login(key)\n    elif args[0] == 'logout':\n        # Log out from Ultralytics HUB\n        hub.logout()\n\n\ndef handle_yolo_settings(args: List[str]) -> None:\n    \"\"\"\n    Handle YOLO settings command-line interface (CLI) commands.\n\n    This function processes YOLO settings CLI commands such as reset.\n    It should be called when executing a script with arguments related to YOLO settings management.\n\n    Args:\n        args (List[str]): A list of command line arguments for YOLO settings management.\n\n    Example:\n        python my_script.py yolo settings reset\n    \"\"\"\n    path = USER_CONFIG_DIR / 'settings.yaml'  # get SETTINGS YAML file path\n    if any(args) and args[0] == 'reset':\n        path.unlink()  # delete the settings file\n        get_settings()  # create new settings\n        LOGGER.info('Settings reset successfully')  # inform the user that settings have been reset\n    yaml_print(path)  # print the current settings\n\n\ndef entrypoint(debug=''):\n    \"\"\"\n    This function is the ultralytics package entrypoint, it's responsible for parsing the command line arguments passed\n    to the package.\n\n    This function allows for:\n    - passing mandatory YOLO args as a list of strings\n    - specifying the task to be performed, either 'detect', 'segment' or 'classify'\n    - specifying the mode, either 'train', 'val', 'test', or 'predict'\n    - running special modes like 'checks'\n    - passing overrides to the package's configuration\n\n    It uses the package's default cfg and initializes it using the passed overrides.\n    Then it calls the CLI function with the composed cfg\n    \"\"\"\n    args = (debug.split(' ') if debug else sys.argv)[1:]\n    if not args:  # no arguments passed\n        LOGGER.info(CLI_HELP_MSG)\n        return\n\n    special = {\n        'help': lambda: LOGGER.info(CLI_HELP_MSG),\n        'checks': checks.check_yolo,\n        'version': lambda: LOGGER.info(__version__),\n        'settings': lambda: handle_yolo_settings(args[1:]),\n        'cfg': lambda: yaml_print(DEFAULT_CFG_PATH),\n        'hub': lambda: handle_yolo_hub(args[1:]),\n        'login': lambda: handle_yolo_hub(args),\n        'copy-cfg': copy_default_cfg}\n    full_args_dict = {**DEFAULT_CFG_DICT, **{k: None for k in TASKS}, **{k: None for k in MODES}, **special}\n\n    # Define common mis-uses of special commands, i.e. -h, -help, --help\n    special.update({k[0]: v for k, v in special.items()})  # singular\n    special.update({k[:-1]: v for k, v in special.items() if len(k) > 1 and k.endswith('s')})  # singular\n    special = {**special, **{f'-{k}': v for k, v in special.items()}, **{f'--{k}': v for k, v in special.items()}}\n\n    overrides = {}  # basic overrides, i.e. imgsz=320\n    for a in merge_equals_args(args):  # merge spaces around '=' sign\n        if a.startswith('--'):\n            LOGGER.warning(f\"WARNING ⚠️ '{a}' does not require leading dashes '--', updating to '{a[2:]}'.\")\n            a = a[2:]\n        if a.endswith(','):\n            LOGGER.warning(f\"WARNING ⚠️ '{a}' does not require trailing comma ',', updating to '{a[:-1]}'.\")\n            a = a[:-1]\n        if '=' in a:\n            try:\n                re.sub(r' *= *', '=', a)  # remove spaces around equals sign\n                k, v = a.split('=', 1)  # split on first '=' sign\n                assert v, f\"missing '{k}' value\"\n                if k == 'cfg':  # custom.yaml passed\n                    LOGGER.info(f'Overriding {DEFAULT_CFG_PATH} with {v}')\n                    overrides = {k: val for k, val in yaml_load(checks.check_yaml(v)).items() if k != 'cfg'}\n                else:\n                    if v.lower() == 'none':\n                        v = None\n                    elif v.lower() == 'true':\n                        v = True\n                    elif v.lower() == 'false':\n                        v = False\n                    else:\n                        with contextlib.suppress(Exception):\n                            v = eval(v)\n                    overrides[k] = v\n            except (NameError, SyntaxError, ValueError, AssertionError) as e:\n                check_cfg_mismatch(full_args_dict, {a: ''}, e)\n\n        elif a in TASKS:\n            overrides['task'] = a\n        elif a in MODES:\n            overrides['mode'] = a\n        elif a.lower() in special:\n            special[a.lower()]()\n            return\n        elif a in DEFAULT_CFG_DICT and isinstance(DEFAULT_CFG_DICT[a], bool):\n            overrides[a] = True  # auto-True for default bool args, i.e. 'yolo show' sets show=True\n        elif a in DEFAULT_CFG_DICT:\n            raise SyntaxError(f\"'{colorstr('red', 'bold', a)}' is a valid YOLO argument but is missing an '=' sign \"\n                              f\"to set its value, i.e. try '{a}={DEFAULT_CFG_DICT[a]}'\\n{CLI_HELP_MSG}\")\n        else:\n            check_cfg_mismatch(full_args_dict, {a: ''})\n\n    # Check keys\n    check_cfg_mismatch(full_args_dict, overrides)\n\n    # Mode\n    mode = overrides.get('mode', None)\n    if mode is None:\n        mode = DEFAULT_CFG.mode or 'predict'\n        LOGGER.warning(f\"WARNING ⚠️ 'mode' is missing. Valid modes are {MODES}. Using default 'mode={mode}'.\")\n    elif mode not in MODES:\n        if mode not in ('checks', checks):\n            raise ValueError(f\"Invalid 'mode={mode}'. Valid modes are {MODES}.\\n{CLI_HELP_MSG}\")\n        LOGGER.warning(\"WARNING ⚠️ 'yolo mode=checks' is deprecated. Use 'yolo checks' instead.\")\n        checks.check_yolo()\n        return\n\n    # Task\n    task = overrides.pop('task', None)\n    if task:\n        if task not in TASKS:\n            raise ValueError(f\"Invalid 'task={task}'. Valid tasks are {TASKS}.\\n{CLI_HELP_MSG}\")\n        if 'model' not in overrides:\n            overrides['model'] = TASK2MODEL[task]\n\n    # Model\n    model = overrides.pop('model', DEFAULT_CFG.model)\n    if model is None:\n        model = 'yolov8n.pt'\n        LOGGER.warning(f\"WARNING ⚠️ 'model' is missing. Using default 'model={model}'.\")\n    overrides['model'] = model\n    if 'rtdetr' in model.lower():  # guess architecture\n        from ultralytics import RTDETR\n        model = RTDETR(model)  # no task argument\n    elif 'sam' in model.lower():\n        from ultralytics import SAM\n        model = SAM(model)\n    else:\n        from ultralytics import YOLO\n        model = YOLO(model, task=task)\n    if isinstance(overrides.get('pretrained'), str):\n        model.load(overrides['pretrained'])\n\n    # Task Update\n    if task != model.task:\n        if task:\n            LOGGER.warning(f\"WARNING ⚠️ conflicting 'task={task}' passed with 'task={model.task}' model. \"\n                           f\"Ignoring 'task={task}' and updating to 'task={model.task}' to match model.\")\n        task = model.task\n\n    # Mode\n    if mode in ('predict', 'track') and 'source' not in overrides:\n        overrides['source'] = DEFAULT_CFG.source or ROOT / 'assets' if (ROOT / 'assets').exists() \\\n            else 'https://ultralytics.com/images/bus.jpg'\n        LOGGER.warning(f\"WARNING ⚠️ 'source' is missing. Using default 'source={overrides['source']}'.\")\n    elif mode in ('train', 'val'):\n        if 'data' not in overrides:\n            overrides['data'] = TASK2DATA.get(task or DEFAULT_CFG.task, DEFAULT_CFG.data)\n            LOGGER.warning(f\"WARNING ⚠️ 'data' is missing. Using default 'data={overrides['data']}'.\")\n    elif mode == 'export':\n        if 'format' not in overrides:\n            overrides['format'] = DEFAULT_CFG.format or 'torchscript'\n            LOGGER.warning(f\"WARNING ⚠️ 'format' is missing. Using default 'format={overrides['format']}'.\")\n\n    # Run command in python\n    # getattr(model, mode)(**vars(get_cfg(overrides=overrides)))  # default args using default.yaml\n    getattr(model, mode)(**overrides)  # default args from model\n\n\n# Special modes --------------------------------------------------------------------------------------------------------\ndef copy_default_cfg():\n    \"\"\"Copy and create a new default configuration file with '_copy' appended to its name.\"\"\"\n    new_file = Path.cwd() / DEFAULT_CFG_PATH.name.replace('.yaml', '_copy.yaml')\n    shutil.copy2(DEFAULT_CFG_PATH, new_file)\n    LOGGER.info(f'{DEFAULT_CFG_PATH} copied to {new_file}\\n'\n                f\"Example YOLO command with this new custom cfg:\\n    yolo cfg='{new_file}' imgsz=320 batch=8\")\n\n\nif __name__ == '__main__':\n    # Example Usage: entrypoint(debug='yolo predict model=yolov8n.pt')\n    entrypoint(debug='')\n"
  },
  {
    "path": "ultralytics/yolo/cfg/default.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Default training settings and hyperparameters for medium-augmentation COCO training\n\ntask: detect  # (str) YOLO task, i.e. detect, segment, classify, pose\nmode: train  # (str) YOLO mode, i.e. train, val, predict, export, track, benchmark\n\n# Train settings -------------------------------------------------------------------------------------------------------\nmodel:  # (str, optional) path to model file, i.e. yolov8n.pt, yolov8n.yaml\ndata:  # (str, optional) path to data file, i.e. coco128.yaml\nepochs: 100  # (int) number of epochs to train for\npatience: 50  # (int) epochs to wait for no observable improvement for early stopping of training\nbatch: 16  # (int) number of images per batch (-1 for AutoBatch)\nimgsz: 640  # (int) size of input images as integer or w,h\nsave: True  # (bool) save train checkpoints and predict results\nsave_period: -1 # (int) Save checkpoint every x epochs (disabled if < 1)\ncache: False  # (bool) True/ram, disk or False. Use cache for data loading\ndevice:  # (int | str | list, optional) device to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu\nworkers: 8  # (int) number of worker threads for data loading (per RANK if DDP)\nproject:  # (str, optional) project name\nname:  # (str, optional) experiment name, results saved to 'project/name' directory\nexist_ok: False  # (bool) whether to overwrite existing experiment\npretrained: True  # (bool | str) whether to use a pretrained model (bool) or a model to load weights from (str)\noptimizer: auto  # (str) optimizer to use, choices=[SGD, Adam, Adamax, AdamW, NAdam, RAdam, RMSProp, auto]\nverbose: True  # (bool) whether to print verbose output\nseed: 0  # (int) random seed for reproducibility\ndeterministic: True  # (bool) whether to enable deterministic mode\nsingle_cls: False  # (bool) train multi-class data as single-class\nrect: False  # (bool) rectangular training if mode='train' or rectangular validation if mode='val'\ncos_lr: False  # (bool) use cosine learning rate scheduler\nclose_mosaic: 0  # (int) disable mosaic augmentation for final epochs\nresume: False  # (bool) resume training from last checkpoint\namp: True  # (bool) Automatic Mixed Precision (AMP) training, choices=[True, False], True runs AMP check\nfraction: 1.0  # (float) dataset fraction to train on (default is 1.0, all images in train set)\nprofile: False  # (bool) profile ONNX and TensorRT speeds during training for loggers\n# Segmentation\noverlap_mask: True  # (bool) masks should overlap during training (segment train only)\nmask_ratio: 4  # (int) mask downsample ratio (segment train only)\n# Classification\ndropout: 0.0  # (float) use dropout regularization (classify train only)\n\n# Val/Test settings ----------------------------------------------------------------------------------------------------\nval: True  # (bool) validate/test during training\nsplit: val  # (str) dataset split to use for validation, i.e. 'val', 'test' or 'train'\nsave_json: False  # (bool) save results to JSON file\nsave_hybrid: False  # (bool) save hybrid version of labels (labels + additional predictions)\nconf:  # (float, optional) object confidence threshold for detection (default 0.25 predict, 0.001 val)\niou: 0.7  # (float) intersection over union (IoU) threshold for NMS\nmax_det: 300  # (int) maximum number of detections per image\nhalf: False  # (bool) use half precision (FP16)\ndnn: False  # (bool) use OpenCV DNN for ONNX inference\nplots: True  # (bool) save plots during train/val\n\n# Prediction settings --------------------------------------------------------------------------------------------------\nsource:  # (str, optional) source directory for images or videos\nshow: False  # (bool) show results if possible\nsave_txt: False  # (bool) save results as .txt file\nsave_conf: False  # (bool) save results with confidence scores\nsave_crop: False  # (bool) save cropped images with results\nshow_labels: True  # (bool) show object labels in plots\nshow_conf: True  # (bool) show object confidence scores in plots\nvid_stride: 1  # (int) video frame-rate stride\nline_width:   # (int, optional) line width of the bounding boxes, auto if missing\nvisualize: False  # (bool) visualize model features\naugment: False  # (bool) apply image augmentation to prediction sources\nagnostic_nms: False  # (bool) class-agnostic NMS\nclasses:  # (int | list[int], optional) filter results by class, i.e. class=0, or class=[0,2,3]\nretina_masks: False  # (bool) use high-resolution segmentation masks\nboxes: True  # (bool) Show boxes in segmentation predictions\n\n# Export settings ------------------------------------------------------------------------------------------------------\nformat: torchscript  # (str) format to export to, choices at https://docs.ultralytics.com/modes/export/#export-formats\nkeras: False  # (bool) use Kera=s\noptimize: False  # (bool) TorchScript: optimize for mobile\nint8: False  # (bool) CoreML/TF INT8 quantization\ndynamic: False  # (bool) ONNX/TF/TensorRT: dynamic axes\nsimplify: False  # (bool) ONNX: simplify model\nopset:  # (int, optional) ONNX: opset version\nworkspace: 4  # (int) TensorRT: workspace size (GB)\nnms: False  # (bool) CoreML: add NMS\n\n# Hyperparameters ------------------------------------------------------------------------------------------------------\nlr0: 0.01  # (float) initial learning rate (i.e. SGD=1E-2, Adam=1E-3)\nlrf: 0.01  # (float) final learning rate (lr0 * lrf)\nmomentum: 0.937  # (float) SGD momentum/Adam beta1\nweight_decay: 0.0005  # (float) optimizer weight decay 5e-4\nwarmup_epochs: 3.0  # (float) warmup epochs (fractions ok)\nwarmup_momentum: 0.8  # (float) warmup initial momentum\nwarmup_bias_lr: 0.1  # (float) warmup initial bias lr\nbox: 7.5  # (float) box loss gain\ncls: 0.5  # (float) cls loss gain (scale with pixels)\ndfl: 1.5  # (float) dfl loss gain\npose: 12.0  # (float) pose loss gain\nkobj: 1.0  # (float) keypoint obj loss gain\nlabel_smoothing: 0.0  # (float) label smoothing (fraction)\nnbs: 64  # (int) nominal batch size\nhsv_h: 0.015  # (float) image HSV-Hue augmentation (fraction)\nhsv_s: 0.7  # (float) image HSV-Saturation augmentation (fraction)\nhsv_v: 0.4  # (float) image HSV-Value augmentation (fraction)\ndegrees: 0.0  # (float) image rotation (+/- deg)\ntranslate: 0.1  # (float) image translation (+/- fraction)\nscale: 0.5  # (float) image scale (+/- gain)\nshear: 0.0  # (float) image shear (+/- deg)\nperspective: 0.0  # (float) image perspective (+/- fraction), range 0-0.001\nflipud: 0.0  # (float) image flip up-down (probability)\nfliplr: 0.5  # (float) image flip left-right (probability)\nmosaic: 1.0  # (float) image mosaic (probability)\nmixup: 0.0  # (float) image mixup (probability)\ncopy_paste: 0.0  # (float) segment copy-paste (probability)\n\n# Custom config.yaml ---------------------------------------------------------------------------------------------------\ncfg:  # (str, optional) for overriding defaults.yaml\n\n# Debug, do not modify -------------------------------------------------------------------------------------------------\nv5loader: False  # (bool) use legacy YOLOv5 dataloader (deprecated)\n\n# Tracker settings ------------------------------------------------------------------------------------------------------\ntracker: botsort.yaml  # (str) tracker type, choices=[botsort.yaml, bytetrack.yaml]\n"
  },
  {
    "path": "ultralytics/yolo/data/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .base import BaseDataset\nfrom .build import build_dataloader, build_yolo_dataset, load_inference_source\nfrom .dataset import ClassificationDataset, SemanticDataset, YOLODataset\nfrom .dataset_wrappers import MixAndRectDataset\n\n__all__ = ('BaseDataset', 'ClassificationDataset', 'MixAndRectDataset', 'SemanticDataset', 'YOLODataset',\n           'build_yolo_dataset', 'build_dataloader', 'load_inference_source')\n"
  },
  {
    "path": "ultralytics/yolo/data/annotator.py",
    "content": "from pathlib import Path\n\nfrom ultralytics import YOLO\nfrom ultralytics.vit.sam import PromptPredictor, build_sam\nfrom ultralytics.yolo.utils.torch_utils import select_device\n\n\ndef auto_annotate(data, det_model='yolov8x.pt', sam_model='sam_b.pt', device='', output_dir=None):\n    \"\"\"\n    Automatically annotates images using a YOLO object detection model and a SAM segmentation model.\n    Args:\n        data (str): Path to a folder containing images to be annotated.\n        det_model (str, optional): Pre-trained YOLO detection model. Defaults to 'yolov8x.pt'.\n        sam_model (str, optional): Pre-trained SAM segmentation model. Defaults to 'sam_b.pt'.\n        device (str, optional): Device to run the models on. Defaults to an empty string (CPU or GPU, if available).\n        output_dir (str | None | optional): Directory to save the annotated results.\n            Defaults to a 'labels' folder in the same directory as 'data'.\n    \"\"\"\n    device = select_device(device)\n    det_model = YOLO(det_model)\n    sam_model = build_sam(sam_model)\n    det_model.to(device)\n    sam_model.to(device)\n\n    if not output_dir:\n        output_dir = Path(str(data)).parent / 'labels'\n    Path(output_dir).mkdir(exist_ok=True, parents=True)\n\n    prompt_predictor = PromptPredictor(sam_model)\n    det_results = det_model(data, stream=True)\n\n    for result in det_results:\n        boxes = result.boxes.xyxy  # Boxes object for bbox outputs\n        class_ids = result.boxes.cls.int().tolist()  # noqa\n        if len(class_ids):\n            prompt_predictor.set_image(result.orig_img)\n            masks, _, _ = prompt_predictor.predict_torch(\n                point_coords=None,\n                point_labels=None,\n                boxes=prompt_predictor.transform.apply_boxes_torch(boxes, result.orig_shape[:2]),\n                multimask_output=False,\n            )\n\n            result.update(masks=masks.squeeze(1))\n            segments = result.masks.xyn  # noqa\n\n            with open(str(Path(output_dir) / Path(result.path).stem) + '.txt', 'w') as f:\n                for i in range(len(segments)):\n                    s = segments[i]\n                    if len(s) == 0:\n                        continue\n                    segment = map(str, segments[i].reshape(-1).tolist())\n                    f.write(f'{class_ids[i]} ' + ' '.join(segment) + '\\n')\n"
  },
  {
    "path": "ultralytics/yolo/data/augment.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport math\nimport random\nfrom copy import deepcopy\n\nimport cv2\nimport numpy as np\nimport torch\nimport torchvision.transforms as T\n\nfrom ..utils import LOGGER, colorstr\nfrom ..utils.checks import check_version\nfrom ..utils.instance import Instances\nfrom ..utils.metrics import bbox_ioa\nfrom ..utils.ops import segment2box\nfrom .utils import polygons2masks, polygons2masks_overlap\n\nPOSE_FLIPLR_INDEX = [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]\n\n\n# TODO: we might need a BaseTransform to make all these augments be compatible with both classification and semantic\nclass BaseTransform:\n\n    def __init__(self) -> None:\n        pass\n\n    def apply_image(self, labels):\n        \"\"\"Applies image transformation to labels.\"\"\"\n        pass\n\n    def apply_instances(self, labels):\n        \"\"\"Applies transformations to input 'labels' and returns object instances.\"\"\"\n        pass\n\n    def apply_semantic(self, labels):\n        \"\"\"Applies semantic segmentation to an image.\"\"\"\n        pass\n\n    def __call__(self, labels):\n        \"\"\"Applies label transformations to an image, instances and semantic masks.\"\"\"\n        self.apply_image(labels)\n        self.apply_instances(labels)\n        self.apply_semantic(labels)\n\n\nclass Compose:\n\n    def __init__(self, transforms):\n        \"\"\"Initializes the Compose object with a list of transforms.\"\"\"\n        self.transforms = transforms\n\n    def __call__(self, data):\n        \"\"\"Applies a series of transformations to input data.\"\"\"\n        for t in self.transforms:\n            data = t(data)\n        return data\n\n    def append(self, transform):\n        \"\"\"Appends a new transform to the existing list of transforms.\"\"\"\n        self.transforms.append(transform)\n\n    def tolist(self):\n        \"\"\"Converts list of transforms to a standard Python list.\"\"\"\n        return self.transforms\n\n    def __repr__(self):\n        \"\"\"Return string representation of object.\"\"\"\n        format_string = f'{self.__class__.__name__}('\n        for t in self.transforms:\n            format_string += '\\n'\n            format_string += f'    {t}'\n        format_string += '\\n)'\n        return format_string\n\n\nclass BaseMixTransform:\n    \"\"\"This implementation is from mmyolo.\"\"\"\n\n    def __init__(self, dataset, pre_transform=None, p=0.0) -> None:\n        self.dataset = dataset\n        self.pre_transform = pre_transform\n        self.p = p\n\n    def __call__(self, labels):\n        \"\"\"Applies pre-processing transforms and mixup/mosaic transforms to labels data.\"\"\"\n        if random.uniform(0, 1) > self.p:\n            return labels\n\n        # Get index of one or three other images\n        indexes = self.get_indexes()\n        if isinstance(indexes, int):\n            indexes = [indexes]\n\n        # Get images information will be used for Mosaic or MixUp\n        mix_labels = [self.dataset.get_image_and_label(i) for i in indexes]\n\n        if self.pre_transform is not None:\n            for i, data in enumerate(mix_labels):\n                mix_labels[i] = self.pre_transform(data)\n        labels['mix_labels'] = mix_labels\n\n        # Mosaic or MixUp\n        labels = self._mix_transform(labels)\n        labels.pop('mix_labels', None)\n        return labels\n\n    def _mix_transform(self, labels):\n        \"\"\"Applies MixUp or Mosaic augmentation to the label dictionary.\"\"\"\n        raise NotImplementedError\n\n    def get_indexes(self):\n        \"\"\"Gets a list of shuffled indexes for mosaic augmentation.\"\"\"\n        raise NotImplementedError\n\n\nclass Mosaic(BaseMixTransform):\n    \"\"\"\n    Mosaic augmentation.\n\n    This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image.\n    The augmentation is applied to a dataset with a given probability.\n\n    Attributes:\n        dataset: The dataset on which the mosaic augmentation is applied.\n        imgsz (int, optional): Image size (height and width) after mosaic pipeline of a single image. Default to 640.\n        p (float, optional): Probability of applying the mosaic augmentation. Must be in the range 0-1. Default to 1.0.\n        n (int, optional): The grid size, either 4 (for 2x2) or 9 (for 3x3).\n    \"\"\"\n\n    def __init__(self, dataset, imgsz=640, p=1.0, n=4):\n        \"\"\"Initializes the object with a dataset, image size, probability, and border.\"\"\"\n        assert 0 <= p <= 1.0, f'The probability should be in range [0, 1], but got {p}.'\n        assert n in (4, 9), 'grid must be equal to 4 or 9.'\n        super().__init__(dataset=dataset, p=p)\n        self.dataset = dataset\n        self.imgsz = imgsz\n        self.border = (-imgsz // 2, -imgsz // 2)  # width, height\n        self.n = n\n\n    def get_indexes(self, buffer=True):\n        \"\"\"Return a list of random indexes from the dataset.\"\"\"\n        if buffer:  # select images from buffer\n            return random.choices(list(self.dataset.buffer), k=self.n - 1)\n        else:  # select any images\n            return [random.randint(0, len(self.dataset) - 1) for _ in range(self.n - 1)]\n\n    def _mix_transform(self, labels):\n        \"\"\"Apply mixup transformation to the input image and labels.\"\"\"\n        assert labels.get('rect_shape', None) is None, 'rect and mosaic are mutually exclusive.'\n        assert len(labels.get('mix_labels', [])), 'There are no other images for mosaic augment.'\n        return self._mosaic4(labels) if self.n == 4 else self._mosaic9(labels)\n\n    def _mosaic4(self, labels):\n        \"\"\"Create a 2x2 image mosaic.\"\"\"\n        mosaic_labels = []\n        s = self.imgsz\n        yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.border)  # mosaic center x, y\n        for i in range(4):\n            labels_patch = labels if i == 0 else labels['mix_labels'][i - 1]\n            # Load image\n            img = labels_patch['img']\n            h, w = labels_patch.pop('resized_shape')\n\n            # Place img in img4\n            if i == 0:  # top left\n                img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n                x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc  # xmin, ymin, xmax, ymax (large image)\n                x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h  # xmin, ymin, xmax, ymax (small image)\n            elif i == 1:  # top right\n                x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc\n                x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h\n            elif i == 2:  # bottom left\n                x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)\n                x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)\n            elif i == 3:  # bottom right\n                x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)\n                x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)\n\n            img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]  # img4[ymin:ymax, xmin:xmax]\n            padw = x1a - x1b\n            padh = y1a - y1b\n\n            labels_patch = self._update_labels(labels_patch, padw, padh)\n            mosaic_labels.append(labels_patch)\n        final_labels = self._cat_labels(mosaic_labels)\n        final_labels['img'] = img4\n        return final_labels\n\n    def _mosaic9(self, labels):\n        \"\"\"Create a 3x3 image mosaic.\"\"\"\n        mosaic_labels = []\n        s = self.imgsz\n        hp, wp = -1, -1  # height, width previous\n        for i in range(9):\n            labels_patch = labels if i == 0 else labels['mix_labels'][i - 1]\n            # Load image\n            img = labels_patch['img']\n            h, w = labels_patch.pop('resized_shape')\n\n            # Place img in img9\n            if i == 0:  # center\n                img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n                h0, w0 = h, w\n                c = s, s, s + w, s + h  # xmin, ymin, xmax, ymax (base) coordinates\n            elif i == 1:  # top\n                c = s, s - h, s + w, s\n            elif i == 2:  # top right\n                c = s + wp, s - h, s + wp + w, s\n            elif i == 3:  # right\n                c = s + w0, s, s + w0 + w, s + h\n            elif i == 4:  # bottom right\n                c = s + w0, s + hp, s + w0 + w, s + hp + h\n            elif i == 5:  # bottom\n                c = s + w0 - w, s + h0, s + w0, s + h0 + h\n            elif i == 6:  # bottom left\n                c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h\n            elif i == 7:  # left\n                c = s - w, s + h0 - h, s, s + h0\n            elif i == 8:  # top left\n                c = s - w, s + h0 - hp - h, s, s + h0 - hp\n\n            padw, padh = c[:2]\n            x1, y1, x2, y2 = (max(x, 0) for x in c)  # allocate coords\n\n            # Image\n            img9[y1:y2, x1:x2] = img[y1 - padh:, x1 - padw:]  # img9[ymin:ymax, xmin:xmax]\n            hp, wp = h, w  # height, width previous for next iteration\n\n            # Labels assuming imgsz*2 mosaic size\n            labels_patch = self._update_labels(labels_patch, padw + self.border[0], padh + self.border[1])\n            mosaic_labels.append(labels_patch)\n        final_labels = self._cat_labels(mosaic_labels)\n\n        final_labels['img'] = img9[-self.border[0]:self.border[0], -self.border[1]:self.border[1]]\n        return final_labels\n\n    @staticmethod\n    def _update_labels(labels, padw, padh):\n        \"\"\"Update labels.\"\"\"\n        nh, nw = labels['img'].shape[:2]\n        labels['instances'].convert_bbox(format='xyxy')\n        labels['instances'].denormalize(nw, nh)\n        labels['instances'].add_padding(padw, padh)\n        return labels\n\n    def _cat_labels(self, mosaic_labels):\n        \"\"\"Return labels with mosaic border instances clipped.\"\"\"\n        if len(mosaic_labels) == 0:\n            return {}\n        cls = []\n        instances = []\n        imgsz = self.imgsz * 2  # mosaic imgsz\n        for labels in mosaic_labels:\n            cls.append(labels['cls'])\n            instances.append(labels['instances'])\n        final_labels = {\n            'im_file': mosaic_labels[0]['im_file'],\n            'ori_shape': mosaic_labels[0]['ori_shape'],\n            'resized_shape': (imgsz, imgsz),\n            'cls': np.concatenate(cls, 0),\n            'instances': Instances.concatenate(instances, axis=0),\n            'mosaic_border': self.border}  # final_labels\n        final_labels['instances'].clip(imgsz, imgsz)\n        good = final_labels['instances'].remove_zero_area_boxes()\n        final_labels['cls'] = final_labels['cls'][good]\n        return final_labels\n\n\nclass MixUp(BaseMixTransform):\n\n    def __init__(self, dataset, pre_transform=None, p=0.0) -> None:\n        super().__init__(dataset=dataset, pre_transform=pre_transform, p=p)\n\n    def get_indexes(self):\n        \"\"\"Get a random index from the dataset.\"\"\"\n        return random.randint(0, len(self.dataset) - 1)\n\n    def _mix_transform(self, labels):\n        \"\"\"Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf.\"\"\"\n        r = np.random.beta(32.0, 32.0)  # mixup ratio, alpha=beta=32.0\n        labels2 = labels['mix_labels'][0]\n        labels['img'] = (labels['img'] * r + labels2['img'] * (1 - r)).astype(np.uint8)\n        labels['instances'] = Instances.concatenate([labels['instances'], labels2['instances']], axis=0)\n        labels['cls'] = np.concatenate([labels['cls'], labels2['cls']], 0)\n        return labels\n\n\nclass RandomPerspective:\n\n    def __init__(self,\n                 degrees=0.0,\n                 translate=0.1,\n                 scale=0.5,\n                 shear=0.0,\n                 perspective=0.0,\n                 border=(0, 0),\n                 pre_transform=None):\n        self.degrees = degrees\n        self.translate = translate\n        self.scale = scale\n        self.shear = shear\n        self.perspective = perspective\n        # Mosaic border\n        self.border = border\n        self.pre_transform = pre_transform\n\n    def affine_transform(self, img, border):\n        \"\"\"Center.\"\"\"\n        C = np.eye(3, dtype=np.float32)\n\n        C[0, 2] = -img.shape[1] / 2  # x translation (pixels)\n        C[1, 2] = -img.shape[0] / 2  # y translation (pixels)\n\n        # Perspective\n        P = np.eye(3, dtype=np.float32)\n        P[2, 0] = random.uniform(-self.perspective, self.perspective)  # x perspective (about y)\n        P[2, 1] = random.uniform(-self.perspective, self.perspective)  # y perspective (about x)\n\n        # Rotation and Scale\n        R = np.eye(3, dtype=np.float32)\n        a = random.uniform(-self.degrees, self.degrees)\n        # a += random.choice([-180, -90, 0, 90])  # add 90deg rotations to small rotations\n        s = random.uniform(1 - self.scale, 1 + self.scale)\n        # s = 2 ** random.uniform(-scale, scale)\n        R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)\n\n        # Shear\n        S = np.eye(3, dtype=np.float32)\n        S[0, 1] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180)  # x shear (deg)\n        S[1, 0] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180)  # y shear (deg)\n\n        # Translation\n        T = np.eye(3, dtype=np.float32)\n        T[0, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[0]  # x translation (pixels)\n        T[1, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[1]  # y translation (pixels)\n\n        # Combined rotation matrix\n        M = T @ S @ R @ P @ C  # order of operations (right to left) is IMPORTANT\n        # Affine image\n        if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():  # image changed\n            if self.perspective:\n                img = cv2.warpPerspective(img, M, dsize=self.size, borderValue=(114, 114, 114))\n            else:  # affine\n                img = cv2.warpAffine(img, M[:2], dsize=self.size, borderValue=(114, 114, 114))\n        return img, M, s\n\n    def apply_bboxes(self, bboxes, M):\n        \"\"\"\n        Apply affine to bboxes only.\n\n        Args:\n            bboxes (ndarray): list of bboxes, xyxy format, with shape (num_bboxes, 4).\n            M (ndarray): affine matrix.\n\n        Returns:\n            new_bboxes (ndarray): bboxes after affine, [num_bboxes, 4].\n        \"\"\"\n        n = len(bboxes)\n        if n == 0:\n            return bboxes\n\n        xy = np.ones((n * 4, 3), dtype=bboxes.dtype)\n        xy[:, :2] = bboxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(n * 4, 2)  # x1y1, x2y2, x1y2, x2y1\n        xy = xy @ M.T  # transform\n        xy = (xy[:, :2] / xy[:, 2:3] if self.perspective else xy[:, :2]).reshape(n, 8)  # perspective rescale or affine\n\n        # Create new boxes\n        x = xy[:, [0, 2, 4, 6]]\n        y = xy[:, [1, 3, 5, 7]]\n        return np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1)), dtype=bboxes.dtype).reshape(4, n).T\n\n    def apply_segments(self, segments, M):\n        \"\"\"\n        Apply affine to segments and generate new bboxes from segments.\n\n        Args:\n            segments (ndarray): list of segments, [num_samples, 500, 2].\n            M (ndarray): affine matrix.\n\n        Returns:\n            new_segments (ndarray): list of segments after affine, [num_samples, 500, 2].\n            new_bboxes (ndarray): bboxes after affine, [N, 4].\n        \"\"\"\n        n, num = segments.shape[:2]\n        if n == 0:\n            return [], segments\n\n        xy = np.ones((n * num, 3), dtype=segments.dtype)\n        segments = segments.reshape(-1, 2)\n        xy[:, :2] = segments\n        xy = xy @ M.T  # transform\n        xy = xy[:, :2] / xy[:, 2:3]\n        segments = xy.reshape(n, -1, 2)\n        bboxes = np.stack([segment2box(xy, self.size[0], self.size[1]) for xy in segments], 0)\n        return bboxes, segments\n\n    def apply_keypoints(self, keypoints, M):\n        \"\"\"\n        Apply affine to keypoints.\n\n        Args:\n            keypoints (ndarray): keypoints, [N, 17, 3].\n            M (ndarray): affine matrix.\n\n        Return:\n            new_keypoints (ndarray): keypoints after affine, [N, 17, 3].\n        \"\"\"\n        n, nkpt = keypoints.shape[:2]\n        if n == 0:\n            return keypoints\n        xy = np.ones((n * nkpt, 3), dtype=keypoints.dtype)\n        visible = keypoints[..., 2].reshape(n * nkpt, 1)\n        xy[:, :2] = keypoints[..., :2].reshape(n * nkpt, 2)\n        xy = xy @ M.T  # transform\n        xy = xy[:, :2] / xy[:, 2:3]  # perspective rescale or affine\n        out_mask = (xy[:, 0] < 0) | (xy[:, 1] < 0) | (xy[:, 0] > self.size[0]) | (xy[:, 1] > self.size[1])\n        visible[out_mask] = 0\n        return np.concatenate([xy, visible], axis=-1).reshape(n, nkpt, 3)\n\n    def __call__(self, labels):\n        \"\"\"\n        Affine images and targets.\n\n        Args:\n            labels (dict): a dict of `bboxes`, `segments`, `keypoints`.\n        \"\"\"\n        if self.pre_transform and 'mosaic_border' not in labels:\n            labels = self.pre_transform(labels)\n            labels.pop('ratio_pad')  # do not need ratio pad\n\n        img = labels['img']\n        cls = labels['cls']\n        instances = labels.pop('instances')\n        # Make sure the coord formats are right\n        instances.convert_bbox(format='xyxy')\n        instances.denormalize(*img.shape[:2][::-1])\n\n        border = labels.pop('mosaic_border', self.border)\n        self.size = img.shape[1] + border[1] * 2, img.shape[0] + border[0] * 2  # w, h\n        # M is affine matrix\n        # scale for func:`box_candidates`\n        img, M, scale = self.affine_transform(img, border)\n\n        bboxes = self.apply_bboxes(instances.bboxes, M)\n\n        segments = instances.segments\n        keypoints = instances.keypoints\n        # Update bboxes if there are segments.\n        if len(segments):\n            bboxes, segments = self.apply_segments(segments, M)\n\n        if keypoints is not None:\n            keypoints = self.apply_keypoints(keypoints, M)\n        new_instances = Instances(bboxes, segments, keypoints, bbox_format='xyxy', normalized=False)\n        # Clip\n        new_instances.clip(*self.size)\n\n        # Filter instances\n        instances.scale(scale_w=scale, scale_h=scale, bbox_only=True)\n        # Make the bboxes have the same scale with new_bboxes\n        i = self.box_candidates(box1=instances.bboxes.T,\n                                box2=new_instances.bboxes.T,\n                                area_thr=0.01 if len(segments) else 0.10)\n        labels['instances'] = new_instances[i]\n        labels['cls'] = cls[i]\n        labels['img'] = img\n        labels['resized_shape'] = img.shape[:2]\n        return labels\n\n    def box_candidates(self, box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):  # box1(4,n), box2(4,n)\n        # Compute box candidates: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio\n        w1, h1 = box1[2] - box1[0], box1[3] - box1[1]\n        w2, h2 = box2[2] - box2[0], box2[3] - box2[1]\n        ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps))  # aspect ratio\n        return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr)  # candidates\n\n\nclass RandomHSV:\n\n    def __init__(self, hgain=0.5, sgain=0.5, vgain=0.5) -> None:\n        self.hgain = hgain\n        self.sgain = sgain\n        self.vgain = vgain\n\n    def __call__(self, labels):\n        \"\"\"Applies random horizontal or vertical flip to an image with a given probability.\"\"\"\n        img = labels['img']\n        if self.hgain or self.sgain or self.vgain:\n            r = np.random.uniform(-1, 1, 3) * [self.hgain, self.sgain, self.vgain] + 1  # random gains\n            hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))\n            dtype = img.dtype  # uint8\n\n            x = np.arange(0, 256, dtype=r.dtype)\n            lut_hue = ((x * r[0]) % 180).astype(dtype)\n            lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)\n            lut_val = np.clip(x * r[2], 0, 255).astype(dtype)\n\n            im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))\n            cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=img)  # no return needed\n        return labels\n\n\nclass RandomFlip:\n\n    def __init__(self, p=0.5, direction='horizontal', flip_idx=None) -> None:\n        assert direction in ['horizontal', 'vertical'], f'Support direction `horizontal` or `vertical`, got {direction}'\n        assert 0 <= p <= 1.0\n\n        self.p = p\n        self.direction = direction\n        self.flip_idx = flip_idx\n\n    def __call__(self, labels):\n        \"\"\"Resize image and padding for detection, instance segmentation, pose.\"\"\"\n        img = labels['img']\n        instances = labels.pop('instances')\n        instances.convert_bbox(format='xywh')\n        h, w = img.shape[:2]\n        h = 1 if instances.normalized else h\n        w = 1 if instances.normalized else w\n\n        # Flip up-down\n        if self.direction == 'vertical' and random.random() < self.p:\n            img = np.flipud(img)\n            instances.flipud(h)\n        if self.direction == 'horizontal' and random.random() < self.p:\n            img = np.fliplr(img)\n            instances.fliplr(w)\n            # For keypoints\n            if self.flip_idx is not None and instances.keypoints is not None:\n                instances.keypoints = np.ascontiguousarray(instances.keypoints[:, self.flip_idx, :])\n        labels['img'] = np.ascontiguousarray(img)\n        labels['instances'] = instances\n        return labels\n\n\nclass LetterBox:\n    \"\"\"Resize image and padding for detection, instance segmentation, pose.\"\"\"\n\n    def __init__(self, new_shape=(640, 640), auto=False, scaleFill=False, scaleup=True, stride=32):\n        \"\"\"Initialize LetterBox object with specific parameters.\"\"\"\n        self.new_shape = new_shape\n        self.auto = auto\n        self.scaleFill = scaleFill\n        self.scaleup = scaleup\n        self.stride = stride\n\n    def __call__(self, labels=None, image=None):\n        \"\"\"Return updated labels and image with added border.\"\"\"\n        if labels is None:\n            labels = {}\n        img = labels.get('img') if image is None else image\n        shape = img.shape[:2]  # current shape [height, width]\n        new_shape = labels.pop('rect_shape', self.new_shape)\n        if isinstance(new_shape, int):\n            new_shape = (new_shape, new_shape)\n\n        # Scale ratio (new / old)\n        r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n        if not self.scaleup:  # only scale down, do not scale up (for better val mAP)\n            r = min(r, 1.0)\n\n        # Compute padding\n        ratio = r, r  # width, height ratios\n        new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n        dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding\n        if self.auto:  # minimum rectangle\n            dw, dh = np.mod(dw, self.stride), np.mod(dh, self.stride)  # wh padding\n        elif self.scaleFill:  # stretch\n            dw, dh = 0.0, 0.0\n            new_unpad = (new_shape[1], new_shape[0])\n            ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios\n\n        dw /= 2  # divide padding into 2 sides\n        dh /= 2\n        if labels.get('ratio_pad'):\n            labels['ratio_pad'] = (labels['ratio_pad'], (dw, dh))  # for evaluation\n\n        if shape[::-1] != new_unpad:  # resize\n            img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)\n        top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n        left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n        img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT,\n                                 value=(114, 114, 114))  # add border\n\n        if len(labels):\n            labels = self._update_labels(labels, ratio, dw, dh)\n            labels['img'] = img\n            labels['resized_shape'] = new_shape\n            return labels\n        else:\n            return img\n\n    def _update_labels(self, labels, ratio, padw, padh):\n        \"\"\"Update labels.\"\"\"\n        labels['instances'].convert_bbox(format='xyxy')\n        labels['instances'].denormalize(*labels['img'].shape[:2][::-1])\n        labels['instances'].scale(*ratio)\n        labels['instances'].add_padding(padw, padh)\n        return labels\n\n\nclass CopyPaste:\n\n    def __init__(self, p=0.5) -> None:\n        self.p = p\n\n    def __call__(self, labels):\n        \"\"\"Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy).\"\"\"\n        im = labels['img']\n        cls = labels['cls']\n        h, w = im.shape[:2]\n        instances = labels.pop('instances')\n        instances.convert_bbox(format='xyxy')\n        instances.denormalize(w, h)\n        if self.p and len(instances.segments):\n            n = len(instances)\n            _, w, _ = im.shape  # height, width, channels\n            im_new = np.zeros(im.shape, np.uint8)\n\n            # Calculate ioa first then select indexes randomly\n            ins_flip = deepcopy(instances)\n            ins_flip.fliplr(w)\n\n            ioa = bbox_ioa(ins_flip.bboxes, instances.bboxes)  # intersection over area, (N, M)\n            indexes = np.nonzero((ioa < 0.30).all(1))[0]  # (N, )\n            n = len(indexes)\n            for j in random.sample(list(indexes), k=round(self.p * n)):\n                cls = np.concatenate((cls, cls[[j]]), axis=0)\n                instances = Instances.concatenate((instances, ins_flip[[j]]), axis=0)\n                cv2.drawContours(im_new, instances.segments[[j]].astype(np.int32), -1, (1, 1, 1), cv2.FILLED)\n\n            result = cv2.flip(im, 1)  # augment segments (flip left-right)\n            i = cv2.flip(im_new, 1).astype(bool)\n            im[i] = result[i]  # cv2.imwrite('debug.jpg', im)  # debug\n\n        labels['img'] = im\n        labels['cls'] = cls\n        labels['instances'] = instances\n        return labels\n\n\nclass Albumentations:\n    # YOLOv8 Albumentations class (optional, only used if package is installed)\n    def __init__(self, p=1.0):\n        \"\"\"Initialize the transform object for YOLO bbox formatted params.\"\"\"\n        self.p = p\n        self.transform = None\n        prefix = colorstr('albumentations: ')\n        try:\n            import albumentations as A\n\n            check_version(A.__version__, '1.0.3', hard=True)  # version requirement\n\n            T = [\n                A.Blur(p=0.01),\n                A.MedianBlur(p=0.01),\n                A.ToGray(p=0.01),\n                A.CLAHE(p=0.01),\n                A.RandomBrightnessContrast(p=0.0),\n                A.RandomGamma(p=0.0),\n                A.ImageCompression(quality_lower=75, p=0.0)]  # transforms\n            self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))\n\n            LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))\n        except ImportError:  # package not installed, skip\n            pass\n        except Exception as e:\n            LOGGER.info(f'{prefix}{e}')\n\n    def __call__(self, labels):\n        \"\"\"Generates object detections and returns a dictionary with detection results.\"\"\"\n        im = labels['img']\n        cls = labels['cls']\n        if len(cls):\n            labels['instances'].convert_bbox('xywh')\n            labels['instances'].normalize(*im.shape[:2][::-1])\n            bboxes = labels['instances'].bboxes\n            # TODO: add supports of segments and keypoints\n            if self.transform and random.random() < self.p:\n                new = self.transform(image=im, bboxes=bboxes, class_labels=cls)  # transformed\n                if len(new['class_labels']) > 0:  # skip update if no bbox in new im\n                    labels['img'] = new['image']\n                    labels['cls'] = np.array(new['class_labels'])\n                    bboxes = np.array(new['bboxes'], dtype=np.float32)\n            labels['instances'].update(bboxes=bboxes)\n        return labels\n\n\n# TODO: technically this is not an augmentation, maybe we should put this to another files\nclass Format:\n\n    def __init__(self,\n                 bbox_format='xywh',\n                 normalize=True,\n                 return_mask=False,\n                 return_keypoint=False,\n                 mask_ratio=4,\n                 mask_overlap=True,\n                 batch_idx=True):\n        self.bbox_format = bbox_format\n        self.normalize = normalize\n        self.return_mask = return_mask  # set False when training detection only\n        self.return_keypoint = return_keypoint\n        self.mask_ratio = mask_ratio\n        self.mask_overlap = mask_overlap\n        self.batch_idx = batch_idx  # keep the batch indexes\n\n    def __call__(self, labels):\n        \"\"\"Return formatted image, classes, bounding boxes & keypoints to be used by 'collate_fn'.\"\"\"\n        img = labels.pop('img')\n        h, w = img.shape[:2]\n        cls = labels.pop('cls')\n        instances = labels.pop('instances')\n        instances.convert_bbox(format=self.bbox_format)\n        instances.denormalize(w, h)\n        nl = len(instances)\n\n        if self.return_mask:\n            if nl:\n                masks, instances, cls = self._format_segments(instances, cls, w, h)\n                masks = torch.from_numpy(masks)\n            else:\n                masks = torch.zeros(1 if self.mask_overlap else nl, img.shape[0] // self.mask_ratio,\n                                    img.shape[1] // self.mask_ratio)\n            labels['masks'] = masks\n        if self.normalize:\n            instances.normalize(w, h)\n        labels['img'] = self._format_img(img)\n        labels['cls'] = torch.from_numpy(cls) if nl else torch.zeros(nl)\n        labels['bboxes'] = torch.from_numpy(instances.bboxes) if nl else torch.zeros((nl, 4))\n        if self.return_keypoint:\n            labels['keypoints'] = torch.from_numpy(instances.keypoints)\n        # Then we can use collate_fn\n        if self.batch_idx:\n            labels['batch_idx'] = torch.zeros(nl)\n        return labels\n\n    def _format_img(self, img):\n        \"\"\"Format the image for YOLOv5 from Numpy array to PyTorch tensor.\"\"\"\n        if len(img.shape) < 3:\n            img = np.expand_dims(img, -1)\n        img = np.ascontiguousarray(img.transpose(2, 0, 1)[::-1])\n        img = torch.from_numpy(img)\n        return img\n\n    def _format_segments(self, instances, cls, w, h):\n        \"\"\"convert polygon points to bitmap.\"\"\"\n        segments = instances.segments\n        if self.mask_overlap:\n            masks, sorted_idx = polygons2masks_overlap((h, w), segments, downsample_ratio=self.mask_ratio)\n            masks = masks[None]  # (640, 640) -> (1, 640, 640)\n            instances = instances[sorted_idx]\n            cls = cls[sorted_idx]\n        else:\n            masks = polygons2masks((h, w), segments, color=1, downsample_ratio=self.mask_ratio)\n\n        return masks, instances, cls\n\n\ndef v8_transforms(dataset, imgsz, hyp, stretch=False):\n    \"\"\"Convert images to a size suitable for YOLOv8 training.\"\"\"\n    pre_transform = Compose([\n        Mosaic(dataset, imgsz=imgsz, p=hyp.mosaic),\n        CopyPaste(p=hyp.copy_paste),\n        RandomPerspective(\n            degrees=hyp.degrees,\n            translate=hyp.translate,\n            scale=hyp.scale,\n            shear=hyp.shear,\n            perspective=hyp.perspective,\n            pre_transform=None if stretch else LetterBox(new_shape=(imgsz, imgsz)),\n        )])\n    flip_idx = dataset.data.get('flip_idx', None)  # for keypoints augmentation\n    if dataset.use_keypoints:\n        kpt_shape = dataset.data.get('kpt_shape', None)\n        if flip_idx is None and hyp.fliplr > 0.0:\n            hyp.fliplr = 0.0\n            LOGGER.warning(\"WARNING ⚠️ No 'flip_idx' array defined in data.yaml, setting augmentation 'fliplr=0.0'\")\n        elif flip_idx and (len(flip_idx) != kpt_shape[0]):\n            raise ValueError(f'data.yaml flip_idx={flip_idx} length must be equal to kpt_shape[0]={kpt_shape[0]}')\n\n    return Compose([\n        pre_transform,\n        MixUp(dataset, pre_transform=pre_transform, p=hyp.mixup),\n        Albumentations(p=1.0),\n        RandomHSV(hgain=hyp.hsv_h, sgain=hyp.hsv_s, vgain=hyp.hsv_v),\n        RandomFlip(direction='vertical', p=hyp.flipud),\n        RandomFlip(direction='horizontal', p=hyp.fliplr, flip_idx=flip_idx)])  # transforms\n\n\n# Classification augmentations -----------------------------------------------------------------------------------------\ndef classify_transforms(size=224, mean=(0.0, 0.0, 0.0), std=(1.0, 1.0, 1.0)):  # IMAGENET_MEAN, IMAGENET_STD\n    # Transforms to apply if albumentations not installed\n    if not isinstance(size, int):\n        raise TypeError(f'classify_transforms() size {size} must be integer, not (list, tuple)')\n    if any(mean) or any(std):\n        return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(mean, std, inplace=True)])\n    else:\n        return T.Compose([CenterCrop(size), ToTensor()])\n\n\ndef hsv2colorjitter(h, s, v):\n    \"\"\"Map HSV (hue, saturation, value) jitter into ColorJitter values (brightness, contrast, saturation, hue)\"\"\"\n    return v, v, s, h\n\n\ndef classify_albumentations(\n        augment=True,\n        size=224,\n        scale=(0.08, 1.0),\n        hflip=0.5,\n        vflip=0.0,\n        hsv_h=0.015,  # image HSV-Hue augmentation (fraction)\n        hsv_s=0.7,  # image HSV-Saturation augmentation (fraction)\n        hsv_v=0.4,  # image HSV-Value augmentation (fraction)\n        mean=(0.0, 0.0, 0.0),  # IMAGENET_MEAN\n        std=(1.0, 1.0, 1.0),  # IMAGENET_STD\n        auto_aug=False,\n):\n    # YOLOv8 classification Albumentations (optional, only used if package is installed)\n    prefix = colorstr('albumentations: ')\n    try:\n        import albumentations as A\n        from albumentations.pytorch import ToTensorV2\n\n        check_version(A.__version__, '1.0.3', hard=True)  # version requirement\n        if augment:  # Resize and crop\n            T = [A.RandomResizedCrop(height=size, width=size, scale=scale)]\n            if auto_aug:\n                # TODO: implement AugMix, AutoAug & RandAug in albumentations\n                LOGGER.info(f'{prefix}auto augmentations are currently not supported')\n            else:\n                if hflip > 0:\n                    T += [A.HorizontalFlip(p=hflip)]\n                if vflip > 0:\n                    T += [A.VerticalFlip(p=vflip)]\n                if any((hsv_h, hsv_s, hsv_v)):\n                    T += [A.ColorJitter(*hsv2colorjitter(hsv_h, hsv_s, hsv_v))]  # brightness, contrast, saturation, hue\n        else:  # Use fixed crop for eval set (reproducibility)\n            T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]\n        T += [A.Normalize(mean=mean, std=std), ToTensorV2()]  # Normalize and convert to Tensor\n        LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))\n        return A.Compose(T)\n\n    except ImportError:  # package not installed, skip\n        pass\n    except Exception as e:\n        LOGGER.info(f'{prefix}{e}')\n\n\nclass ClassifyLetterBox:\n    # YOLOv8 LetterBox class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])\n    def __init__(self, size=(640, 640), auto=False, stride=32):\n        \"\"\"Resizes image and crops it to center with max dimensions 'h' and 'w'.\"\"\"\n        super().__init__()\n        self.h, self.w = (size, size) if isinstance(size, int) else size\n        self.auto = auto  # pass max size integer, automatically solve for short side using stride\n        self.stride = stride  # used with auto\n\n    def __call__(self, im):  # im = np.array HWC\n        imh, imw = im.shape[:2]\n        r = min(self.h / imh, self.w / imw)  # ratio of new/old\n        h, w = round(imh * r), round(imw * r)  # resized image\n        hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w\n        top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)\n        im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)\n        im_out[top:top + h, left:left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)\n        return im_out\n\n\nclass CenterCrop:\n    # YOLOv8 CenterCrop class for image preprocessing, i.e. T.Compose([CenterCrop(size), ToTensor()])\n    def __init__(self, size=640):\n        \"\"\"Converts an image from numpy array to PyTorch tensor.\"\"\"\n        super().__init__()\n        self.h, self.w = (size, size) if isinstance(size, int) else size\n\n    def __call__(self, im):  # im = np.array HWC\n        imh, imw = im.shape[:2]\n        m = min(imh, imw)  # min dimension\n        top, left = (imh - m) // 2, (imw - m) // 2\n        return cv2.resize(im[top:top + m, left:left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)\n\n\nclass ToTensor:\n    # YOLOv8 ToTensor class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])\n    def __init__(self, half=False):\n        \"\"\"Initialize YOLOv8 ToTensor object with optional half-precision support.\"\"\"\n        super().__init__()\n        self.half = half\n\n    def __call__(self, im):  # im = np.array HWC in BGR order\n        im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1])  # HWC to CHW -> BGR to RGB -> contiguous\n        im = torch.from_numpy(im)  # to torch\n        im = im.half() if self.half else im.float()  # uint8 to fp16/32\n        im /= 255.0  # 0-255 to 0.0-1.0\n        return im\n"
  },
  {
    "path": "ultralytics/yolo/data/base.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport glob\nimport math\nimport os\nimport random\nfrom copy import deepcopy\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom typing import Optional\n\nimport cv2\nimport numpy as np\nimport psutil\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\n\nfrom ..utils import DEFAULT_CFG, LOCAL_RANK, LOGGER, NUM_THREADS, TQDM_BAR_FORMAT\nfrom .utils import HELP_URL, IMG_FORMATS\n\n\nclass BaseDataset(Dataset):\n    \"\"\"\n    Base dataset class for loading and processing image data.\n\n    Args:\n        img_path (str): Path to the folder containing images.\n        imgsz (int, optional): Image size. Defaults to 640.\n        cache (bool, optional): Cache images to RAM or disk during training. Defaults to False.\n        augment (bool, optional): If True, data augmentation is applied. Defaults to True.\n        hyp (dict, optional): Hyperparameters to apply data augmentation. Defaults to None.\n        prefix (str, optional): Prefix to print in log messages. Defaults to ''.\n        rect (bool, optional): If True, rectangular training is used. Defaults to False.\n        batch_size (int, optional): Size of batches. Defaults to None.\n        stride (int, optional): Stride. Defaults to 32.\n        pad (float, optional): Padding. Defaults to 0.0.\n        single_cls (bool, optional): If True, single class training is used. Defaults to False.\n        classes (list): List of included classes. Default is None.\n        fraction (float): Fraction of dataset to utilize. Default is 1.0 (use all data).\n\n    Attributes:\n        im_files (list): List of image file paths.\n        labels (list): List of label data dictionaries.\n        ni (int): Number of images in the dataset.\n        ims (list): List of loaded images.\n        npy_files (list): List of numpy file paths.\n        transforms (callable): Image transformation function.\n    \"\"\"\n\n    def __init__(self,\n                 img_path,\n                 imgsz=640,\n                 cache=False,\n                 augment=True,\n                 hyp=DEFAULT_CFG,\n                 prefix='',\n                 rect=False,\n                 batch_size=16,\n                 stride=32,\n                 pad=0.5,\n                 single_cls=False,\n                 classes=None,\n                 fraction=1.0):\n        super().__init__()\n        self.img_path = img_path\n        self.imgsz = imgsz\n        self.augment = augment\n        self.single_cls = single_cls\n        self.prefix = prefix\n        self.fraction = fraction\n        self.im_files = self.get_img_files(self.img_path)\n        self.labels = self.get_labels()\n        self.update_labels(include_class=classes)  # single_cls and include_class\n        self.ni = len(self.labels)  # number of images\n        self.rect = rect\n        self.batch_size = batch_size\n        self.stride = stride\n        self.pad = pad\n        if self.rect:\n            assert self.batch_size is not None\n            self.set_rectangle()\n\n        # Buffer thread for mosaic images\n        self.buffer = []  # buffer size = batch size\n        self.max_buffer_length = min((self.ni, self.batch_size * 8, 1000)) if self.augment else 0\n\n        # Cache stuff\n        if cache == 'ram' and not self.check_cache_ram():\n            cache = False\n        self.ims, self.im_hw0, self.im_hw = [None] * self.ni, [None] * self.ni, [None] * self.ni\n        self.npy_files = [Path(f).with_suffix('.npy') for f in self.im_files]\n        if cache:\n            self.cache_images(cache)\n\n        # Transforms\n        self.transforms = self.build_transforms(hyp=hyp)\n\n    def get_img_files(self, img_path):\n        \"\"\"Read image files.\"\"\"\n        try:\n            f = []  # image files\n            for p in img_path if isinstance(img_path, list) else [img_path]:\n                p = Path(p)  # os-agnostic\n                if p.is_dir():  # dir\n                    f += glob.glob(str(p / '**' / '*.*'), recursive=True)\n                    # F = list(p.rglob('*.*'))  # pathlib\n                elif p.is_file():  # file\n                    with open(p) as t:\n                        t = t.read().strip().splitlines()\n                        parent = str(p.parent) + os.sep\n                        f += [x.replace('./', parent) if x.startswith('./') else x for x in t]  # local to global path\n                        # F += [p.parent / x.lstrip(os.sep) for x in t]  # local to global path (pathlib)\n                else:\n                    raise FileNotFoundError(f'{self.prefix}{p} does not exist')\n            im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)\n            # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS])  # pathlib\n            assert im_files, f'{self.prefix}No images found'\n        except Exception as e:\n            raise FileNotFoundError(f'{self.prefix}Error loading data from {img_path}\\n{HELP_URL}') from e\n        if self.fraction < 1:\n            im_files = im_files[:round(len(im_files) * self.fraction)]\n        return im_files\n\n    def update_labels(self, include_class: Optional[list]):\n        \"\"\"include_class, filter labels to include only these classes (optional).\"\"\"\n        include_class_array = np.array(include_class).reshape(1, -1)\n        for i in range(len(self.labels)):\n            if include_class is not None:\n                cls = self.labels[i]['cls']\n                bboxes = self.labels[i]['bboxes']\n                segments = self.labels[i]['segments']\n                keypoints = self.labels[i]['keypoints']\n                j = (cls == include_class_array).any(1)\n                self.labels[i]['cls'] = cls[j]\n                self.labels[i]['bboxes'] = bboxes[j]\n                if segments:\n                    self.labels[i]['segments'] = [segments[si] for si, idx in enumerate(j) if idx]\n                if keypoints is not None:\n                    self.labels[i]['keypoints'] = keypoints[j]\n            if self.single_cls:\n                self.labels[i]['cls'][:, 0] = 0\n\n    def load_image(self, i):\n        \"\"\"Loads 1 image from dataset index 'i', returns (im, resized hw).\"\"\"\n        im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i]\n        if im is None:  # not cached in RAM\n            if fn.exists():  # load npy\n                im = np.load(fn)\n            else:  # read image\n                im = cv2.imread(f)  # BGR\n                if im is None:\n                    raise FileNotFoundError(f'Image Not Found {f}')\n            h0, w0 = im.shape[:2]  # orig hw\n            r = self.imgsz / max(h0, w0)  # ratio\n            if r != 1:  # if sizes are not equal\n                interp = cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA\n                im = cv2.resize(im, (min(math.ceil(w0 * r), self.imgsz), min(math.ceil(h0 * r), self.imgsz)),\n                                interpolation=interp)\n\n            # Add to buffer if training with augmentations\n            if self.augment:\n                self.ims[i], self.im_hw0[i], self.im_hw[i] = im, (h0, w0), im.shape[:2]  # im, hw_original, hw_resized\n                self.buffer.append(i)\n                if len(self.buffer) >= self.max_buffer_length:\n                    j = self.buffer.pop(0)\n                    self.ims[j], self.im_hw0[j], self.im_hw[j] = None, None, None\n\n            return im, (h0, w0), im.shape[:2]\n\n        return self.ims[i], self.im_hw0[i], self.im_hw[i]\n\n    def cache_images(self, cache):\n        \"\"\"Cache images to memory or disk.\"\"\"\n        b, gb = 0, 1 << 30  # bytes of cached images, bytes per gigabytes\n        fcn = self.cache_images_to_disk if cache == 'disk' else self.load_image\n        with ThreadPool(NUM_THREADS) as pool:\n            results = pool.imap(fcn, range(self.ni))\n            pbar = tqdm(enumerate(results), total=self.ni, bar_format=TQDM_BAR_FORMAT, disable=LOCAL_RANK > 0)\n            for i, x in pbar:\n                if cache == 'disk':\n                    b += self.npy_files[i].stat().st_size\n                else:  # 'ram'\n                    self.ims[i], self.im_hw0[i], self.im_hw[i] = x  # im, hw_orig, hw_resized = load_image(self, i)\n                    b += self.ims[i].nbytes\n                pbar.desc = f'{self.prefix}Caching images ({b / gb:.1f}GB {cache})'\n            pbar.close()\n\n    def cache_images_to_disk(self, i):\n        \"\"\"Saves an image as an *.npy file for faster loading.\"\"\"\n        f = self.npy_files[i]\n        if not f.exists():\n            np.save(f.as_posix(), cv2.imread(self.im_files[i]))\n\n    def check_cache_ram(self, safety_margin=0.5):\n        \"\"\"Check image caching requirements vs available memory.\"\"\"\n        b, gb = 0, 1 << 30  # bytes of cached images, bytes per gigabytes\n        n = min(self.ni, 30)  # extrapolate from 30 random images\n        for _ in range(n):\n            im = cv2.imread(random.choice(self.im_files))  # sample image\n            ratio = self.imgsz / max(im.shape[0], im.shape[1])  # max(h, w)  # ratio\n            b += im.nbytes * ratio ** 2\n        mem_required = b * self.ni / n * (1 + safety_margin)  # GB required to cache dataset into RAM\n        mem = psutil.virtual_memory()\n        cache = mem_required < mem.available  # to cache or not to cache, that is the question\n        if not cache:\n            LOGGER.info(f'{self.prefix}{mem_required / gb:.1f}GB RAM required to cache images '\n                        f'with {int(safety_margin * 100)}% safety margin but only '\n                        f'{mem.available / gb:.1f}/{mem.total / gb:.1f}GB available, '\n                        f\"{'caching images ✅' if cache else 'not caching images ⚠️'}\")\n        return cache\n\n    def set_rectangle(self):\n        \"\"\"Sets the shape of bounding boxes for YOLO detections as rectangles.\"\"\"\n        bi = np.floor(np.arange(self.ni) / self.batch_size).astype(int)  # batch index\n        nb = bi[-1] + 1  # number of batches\n\n        s = np.array([x.pop('shape') for x in self.labels])  # hw\n        ar = s[:, 0] / s[:, 1]  # aspect ratio\n        irect = ar.argsort()\n        self.im_files = [self.im_files[i] for i in irect]\n        self.labels = [self.labels[i] for i in irect]\n        ar = ar[irect]\n\n        # Set training image shapes\n        shapes = [[1, 1]] * nb\n        for i in range(nb):\n            ari = ar[bi == i]\n            mini, maxi = ari.min(), ari.max()\n            if maxi < 1:\n                shapes[i] = [maxi, 1]\n            elif mini > 1:\n                shapes[i] = [1, 1 / mini]\n\n        self.batch_shapes = np.ceil(np.array(shapes) * self.imgsz / self.stride + self.pad).astype(int) * self.stride\n        self.batch = bi  # batch index of image\n\n    def __getitem__(self, index):\n        \"\"\"Returns transformed label information for given index.\"\"\"\n        return self.transforms(self.get_image_and_label(index))\n\n    def get_image_and_label(self, index):\n        \"\"\"Get and return label information from the dataset.\"\"\"\n        label = deepcopy(self.labels[index])  # requires deepcopy() https://github.com/ultralytics/ultralytics/pull/1948\n        label.pop('shape', None)  # shape is for rect, remove it\n        label['img'], label['ori_shape'], label['resized_shape'] = self.load_image(index)\n        label['ratio_pad'] = (label['resized_shape'][0] / label['ori_shape'][0],\n                              label['resized_shape'][1] / label['ori_shape'][1])  # for evaluation\n        if self.rect:\n            label['rect_shape'] = self.batch_shapes[self.batch[index]]\n        return self.update_labels_info(label)\n\n    def __len__(self):\n        \"\"\"Returns the length of the labels list for the dataset.\"\"\"\n        return len(self.labels)\n\n    def update_labels_info(self, label):\n        \"\"\"custom your label format here.\"\"\"\n        return label\n\n    def build_transforms(self, hyp=None):\n        \"\"\"Users can custom augmentations here\n        like:\n            if self.augment:\n                # Training transforms\n                return Compose([])\n            else:\n                # Val transforms\n                return Compose([])\n        \"\"\"\n        raise NotImplementedError\n\n    def get_labels(self):\n        \"\"\"Users can custom their own format here.\n        Make sure your output is a list with each element like below:\n            dict(\n                im_file=im_file,\n                shape=shape,  # format: (height, width)\n                cls=cls,\n                bboxes=bboxes, # xywh\n                segments=segments,  # xy\n                keypoints=keypoints, # xy\n                normalized=True, # or False\n                bbox_format=\"xyxy\",  # or xywh, ltwh\n            )\n        \"\"\"\n        raise NotImplementedError\n"
  },
  {
    "path": "ultralytics/yolo/data/build.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nimport random\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import dataloader, distributed\n\nfrom ultralytics.yolo.data.dataloaders.stream_loaders import (LOADERS, LoadImages, LoadPilAndNumpy, LoadScreenshots,\n                                                              LoadStreams, LoadTensor, SourceTypes, autocast_list)\nfrom ultralytics.yolo.data.utils import IMG_FORMATS, VID_FORMATS\nfrom ultralytics.yolo.utils.checks import check_file\n\nfrom ..utils import RANK, colorstr\nfrom .dataset import YOLODataset\nfrom .utils import PIN_MEMORY\n\n\nclass InfiniteDataLoader(dataloader.DataLoader):\n    \"\"\"Dataloader that reuses workers. Uses same syntax as vanilla DataLoader.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Dataloader that infinitely recycles workers, inherits from DataLoader.\"\"\"\n        super().__init__(*args, **kwargs)\n        object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))\n        self.iterator = super().__iter__()\n\n    def __len__(self):\n        \"\"\"Returns the length of the batch sampler's sampler.\"\"\"\n        return len(self.batch_sampler.sampler)\n\n    def __iter__(self):\n        \"\"\"Creates a sampler that repeats indefinitely.\"\"\"\n        for _ in range(len(self)):\n            yield next(self.iterator)\n\n    def reset(self):\n        \"\"\"Reset iterator.\n        This is useful when we want to modify settings of dataset while training.\n        \"\"\"\n        self.iterator = self._get_iterator()\n\n\nclass _RepeatSampler:\n    \"\"\"\n    Sampler that repeats forever.\n\n    Args:\n        sampler (Dataset.sampler): The sampler to repeat.\n    \"\"\"\n\n    def __init__(self, sampler):\n        \"\"\"Initializes an object that repeats a given sampler indefinitely.\"\"\"\n        self.sampler = sampler\n\n    def __iter__(self):\n        \"\"\"Iterates over the 'sampler' and yields its contents.\"\"\"\n        while True:\n            yield from iter(self.sampler)\n\n\ndef seed_worker(worker_id):  # noqa\n    # Set dataloader worker seed https://pytorch.org/docs/stable/notes/randomness.html#dataloader\n    worker_seed = torch.initial_seed() % 2 ** 32\n    np.random.seed(worker_seed)\n    random.seed(worker_seed)\n\n\ndef build_yolo_dataset(cfg, img_path, batch, data, mode='train', rect=False, stride=32):\n    \"\"\"Build YOLO Dataset\"\"\"\n    return YOLODataset(\n        img_path=img_path,\n        imgsz=cfg.imgsz,\n        batch_size=batch,\n        augment=mode == 'train',  # augmentation\n        hyp=cfg,  # TODO: probably add a get_hyps_from_cfg function\n        rect=cfg.rect or rect,  # rectangular batches\n        cache=cfg.cache or None,\n        single_cls=cfg.single_cls or False,\n        stride=int(stride),\n        pad=0.0 if mode == 'train' else 0.5,\n        prefix=colorstr(f'{mode}: '),\n        use_segments=cfg.task == 'segment',\n        use_keypoints=cfg.task == 'pose',\n        classes=cfg.classes,\n        data=data,\n        fraction=cfg.fraction if mode == 'train' else 1.0)\n\n\ndef build_dataloader(dataset, batch, workers, shuffle=True, rank=-1):\n    \"\"\"Return an InfiniteDataLoader or DataLoader for training or validation set.\"\"\"\n    batch = min(batch, len(dataset))\n    nd = torch.cuda.device_count()  # number of CUDA devices\n    nw = min([os.cpu_count() // max(nd, 1), batch if batch > 1 else 0, workers])  # number of workers\n    sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)\n    generator = torch.Generator()\n    generator.manual_seed(6148914691236517205 + RANK)\n    return InfiniteDataLoader(dataset=dataset,\n                              batch_size=batch,\n                              shuffle=shuffle and sampler is None,\n                              num_workers=nw,\n                              sampler=sampler,\n                              pin_memory=PIN_MEMORY,\n                              collate_fn=getattr(dataset, 'collate_fn', None),\n                              worker_init_fn=seed_worker,\n                              generator=generator)\n\n\ndef check_source(source):\n    \"\"\"Check source type and return corresponding flag values.\"\"\"\n    webcam, screenshot, from_img, in_memory, tensor = False, False, False, False, False\n    if isinstance(source, (str, int, Path)):  # int for local usb camera\n        source = str(source)\n        is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)\n        is_url = source.lower().startswith(('https://', 'http://', 'rtsp://', 'rtmp://'))\n        webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)\n        screenshot = source.lower() == 'screen'\n        if is_url and is_file:\n            source = check_file(source)  # download\n    elif isinstance(source, tuple(LOADERS)):\n        in_memory = True\n    elif isinstance(source, (list, tuple)):\n        source = autocast_list(source)  # convert all list elements to PIL or np arrays\n        from_img = True\n    elif isinstance(source, (Image.Image, np.ndarray)):\n        from_img = True\n    elif isinstance(source, torch.Tensor):\n        tensor = True\n    else:\n        raise TypeError('Unsupported image type. For supported types see https://docs.ultralytics.com/modes/predict')\n\n    return source, webcam, screenshot, from_img, in_memory, tensor\n\n\ndef load_inference_source(source=None, imgsz=640, vid_stride=1):\n    \"\"\"\n    Loads an inference source for object detection and applies necessary transformations.\n\n    Args:\n        source (str, Path, Tensor, PIL.Image, np.ndarray): The input source for inference.\n        imgsz (int, optional): The size of the image for inference. Default is 640.\n        vid_stride (int, optional): The frame interval for video sources. Default is 1.\n\n    Returns:\n        dataset (Dataset): A dataset object for the specified input source.\n    \"\"\"\n    source, webcam, screenshot, from_img, in_memory, tensor = check_source(source)\n    source_type = source.source_type if in_memory else SourceTypes(webcam, screenshot, from_img, tensor)\n\n    # Dataloader\n    if tensor:\n        dataset = LoadTensor(source)\n    elif in_memory:\n        dataset = source\n    elif webcam:\n        dataset = LoadStreams(source, imgsz=imgsz, vid_stride=vid_stride)\n    elif screenshot:\n        dataset = LoadScreenshots(source, imgsz=imgsz)\n    elif from_img:\n        dataset = LoadPilAndNumpy(source, imgsz=imgsz)\n    else:\n        dataset = LoadImages(source, imgsz=imgsz, vid_stride=vid_stride)\n\n    # Attach source types to the dataset\n    setattr(dataset, 'source_type', source_type)\n\n    return dataset\n"
  },
  {
    "path": "ultralytics/yolo/data/converter.py",
    "content": "import json\nfrom collections import defaultdict\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.files import make_dirs\n\n\ndef coco91_to_coco80_class():\n    \"\"\"Converts 91-index COCO class IDs to 80-index COCO class IDs.\n\n    Returns:\n        (list): A list of 91 class IDs where the index represents the 80-index class ID and the value is the\n            corresponding 91-index class ID.\n\n    \"\"\"\n    return [\n        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, None, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, None, 24, 25, None,\n        None, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, None, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n        51, 52, 53, 54, 55, 56, 57, 58, 59, None, 60, None, None, 61, None, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,\n        None, 73, 74, 75, 76, 77, 78, 79, None]\n\n\ndef convert_coco(labels_dir='../coco/annotations/', use_segments=False, use_keypoints=False, cls91to80=True):\n    \"\"\"Converts COCO dataset annotations to a format suitable for training YOLOv5 models.\n\n    Args:\n        labels_dir (str, optional): Path to directory containing COCO dataset annotation files.\n        use_segments (bool, optional): Whether to include segmentation masks in the output.\n        use_keypoints (bool, optional): Whether to include keypoint annotations in the output.\n        cls91to80 (bool, optional): Whether to map 91 COCO class IDs to the corresponding 80 COCO class IDs.\n\n    Raises:\n        FileNotFoundError: If the labels_dir path does not exist.\n\n    Example Usage:\n        convert_coco(labels_dir='../coco/annotations/', use_segments=True, use_keypoints=True, cls91to80=True)\n\n    Output:\n        Generates output files in the specified output directory.\n    \"\"\"\n\n    save_dir = make_dirs('yolo_labels')  # output directory\n    coco80 = coco91_to_coco80_class()\n\n    # Import json\n    for json_file in sorted(Path(labels_dir).resolve().glob('*.json')):\n        fn = Path(save_dir) / 'labels' / json_file.stem.replace('instances_', '')  # folder name\n        fn.mkdir(parents=True, exist_ok=True)\n        with open(json_file) as f:\n            data = json.load(f)\n\n        # Create image dict\n        images = {'%g' % x['id']: x for x in data['images']}\n        # Create image-annotations dict\n        imgToAnns = defaultdict(list)\n        for ann in data['annotations']:\n            imgToAnns[ann['image_id']].append(ann)\n\n        # Write labels file\n        for img_id, anns in tqdm(imgToAnns.items(), desc=f'Annotations {json_file}'):\n            img = images['%g' % img_id]\n            h, w, f = img['height'], img['width'], img['file_name']\n\n            bboxes = []\n            segments = []\n            keypoints = []\n            for ann in anns:\n                if ann['iscrowd']:\n                    continue\n                # The COCO box format is [top left x, top left y, width, height]\n                box = np.array(ann['bbox'], dtype=np.float64)\n                box[:2] += box[2:] / 2  # xy top-left corner to center\n                box[[0, 2]] /= w  # normalize x\n                box[[1, 3]] /= h  # normalize y\n                if box[2] <= 0 or box[3] <= 0:  # if w <= 0 and h <= 0\n                    continue\n\n                cls = coco80[ann['category_id'] - 1] if cls91to80 else ann['category_id'] - 1  # class\n                box = [cls] + box.tolist()\n                if box not in bboxes:\n                    bboxes.append(box)\n                if use_segments and ann.get('segmentation') is not None:\n                    if len(ann['segmentation']) == 0:\n                        segments.append([])\n                        continue\n                    if isinstance(ann['segmentation'], dict):\n                        ann['segmentation'] = rle2polygon(ann['segmentation'])\n                    if len(ann['segmentation']) > 1:\n                        s = merge_multi_segment(ann['segmentation'])\n                        s = (np.concatenate(s, axis=0) / np.array([w, h])).reshape(-1).tolist()\n                    else:\n                        s = [j for i in ann['segmentation'] for j in i]  # all segments concatenated\n                        s = (np.array(s).reshape(-1, 2) / np.array([w, h])).reshape(-1).tolist()\n                    s = [cls] + s\n                    if s not in segments:\n                        segments.append(s)\n                if use_keypoints and ann.get('keypoints') is not None:\n                    k = (np.array(ann['keypoints']).reshape(-1, 3) / np.array([w, h, 1])).reshape(-1).tolist()\n                    k = box + k\n                    keypoints.append(k)\n\n            # Write\n            with open((fn / f).with_suffix('.txt'), 'a') as file:\n                for i in range(len(bboxes)):\n                    if use_keypoints:\n                        line = *(keypoints[i]),  # cls, box, keypoints\n                    else:\n                        line = *(segments[i]\n                                 if use_segments and len(segments[i]) > 0 else bboxes[i]),  # cls, box or segments\n                    file.write(('%g ' * len(line)).rstrip() % line + '\\n')\n\n\ndef rle2polygon(segmentation):\n    \"\"\"\n    Convert Run-Length Encoding (RLE) mask to polygon coordinates.\n\n    Args:\n        segmentation (dict, list): RLE mask representation of the object segmentation.\n\n    Returns:\n        (list): A list of lists representing the polygon coordinates for each contour.\n\n    Note:\n        Requires the 'pycocotools' package to be installed.\n    \"\"\"\n    check_requirements('pycocotools')\n    from pycocotools import mask\n\n    m = mask.decode(segmentation)\n    m[m > 0] = 255\n    contours, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS)\n    polygons = []\n    for contour in contours:\n        epsilon = 0.001 * cv2.arcLength(contour, True)\n        contour_approx = cv2.approxPolyDP(contour, epsilon, True)\n        polygon = contour_approx.flatten().tolist()\n        polygons.append(polygon)\n    return polygons\n\n\ndef min_index(arr1, arr2):\n    \"\"\"\n    Find a pair of indexes with the shortest distance between two arrays of 2D points.\n\n    Args:\n        arr1 (np.array): A NumPy array of shape (N, 2) representing N 2D points.\n        arr2 (np.array): A NumPy array of shape (M, 2) representing M 2D points.\n\n    Returns:\n        (tuple): A tuple containing the indexes of the points with the shortest distance in arr1 and arr2 respectively.\n    \"\"\"\n    dis = ((arr1[:, None, :] - arr2[None, :, :]) ** 2).sum(-1)\n    return np.unravel_index(np.argmin(dis, axis=None), dis.shape)\n\n\ndef merge_multi_segment(segments):\n    \"\"\"\n    Merge multiple segments into one list by connecting the coordinates with the minimum distance between each segment.\n    This function connects these coordinates with a thin line to merge all segments into one.\n\n    Args:\n        segments (List[List]): Original segmentations in COCO's JSON file.\n                               Each element is a list of coordinates, like [segmentation1, segmentation2,...].\n\n    Returns:\n        s (List[np.ndarray]): A list of connected segments represented as NumPy arrays.\n    \"\"\"\n    s = []\n    segments = [np.array(i).reshape(-1, 2) for i in segments]\n    idx_list = [[] for _ in range(len(segments))]\n\n    # record the indexes with min distance between each segment\n    for i in range(1, len(segments)):\n        idx1, idx2 = min_index(segments[i - 1], segments[i])\n        idx_list[i - 1].append(idx1)\n        idx_list[i].append(idx2)\n\n    # use two round to connect all the segments\n    for k in range(2):\n        # forward connection\n        if k == 0:\n            for i, idx in enumerate(idx_list):\n                # middle segments have two indexes\n                # reverse the index of middle segments\n                if len(idx) == 2 and idx[0] > idx[1]:\n                    idx = idx[::-1]\n                    segments[i] = segments[i][::-1, :]\n\n                segments[i] = np.roll(segments[i], -idx[0], axis=0)\n                segments[i] = np.concatenate([segments[i], segments[i][:1]])\n                # deal with the first segment and the last one\n                if i in [0, len(idx_list) - 1]:\n                    s.append(segments[i])\n                else:\n                    idx = [0, idx[1] - idx[0]]\n                    s.append(segments[i][idx[0]:idx[1] + 1])\n\n        else:\n            for i in range(len(idx_list) - 1, -1, -1):\n                if i not in [0, len(idx_list) - 1]:\n                    idx = idx_list[i]\n                    nidx = abs(idx[1] - idx[0])\n                    s.append(segments[i][nidx:])\n    return s\n\n\ndef delete_dsstore(path='../datasets'):\n    \"\"\"Delete Apple .DS_Store files in the specified directory and its subdirectories.\"\"\"\n    from pathlib import Path\n\n    files = list(Path(path).rglob('.DS_store'))\n    print(files)\n    for f in files:\n        f.unlink()\n\n\nif __name__ == '__main__':\n    source = 'COCO'\n\n    if source == 'COCO':\n        convert_coco(\n            '../datasets/coco/annotations',  # directory with *.json\n            use_segments=False,\n            use_keypoints=True,\n            cls91to80=False)\n"
  },
  {
    "path": "ultralytics/yolo/data/dataloaders/__init__.py",
    "content": ""
  },
  {
    "path": "ultralytics/yolo/data/dataloaders/stream_loaders.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport glob\nimport math\nimport os\nimport time\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom threading import Thread\nfrom urllib.parse import urlparse\n\nimport cv2\nimport numpy as np\nimport requests\nimport torch\nfrom PIL import Image\n\nfrom ultralytics.yolo.data.utils import IMG_FORMATS, VID_FORMATS\nfrom ultralytics.yolo.utils import LOGGER, ROOT, is_colab, is_kaggle, ops\nfrom ultralytics.yolo.utils.checks import check_requirements\n\n\n@dataclass\nclass SourceTypes:\n    webcam: bool = False\n    screenshot: bool = False\n    from_img: bool = False\n    tensor: bool = False\n\n\nclass LoadStreams:\n    # YOLOv8 streamloader, i.e. `yolo predict source='rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP streams`\n    def __init__(self, sources='file.streams', imgsz=640, vid_stride=1):\n        \"\"\"Initialize instance variables and check for consistent input stream shapes.\"\"\"\n        torch.backends.cudnn.benchmark = True  # faster for fixed-size inference\n        self.mode = 'stream'\n        self.imgsz = imgsz\n        self.vid_stride = vid_stride  # video frame-rate stride\n        sources = Path(sources).read_text().rsplit() if os.path.isfile(sources) else [sources]\n        n = len(sources)\n        self.sources = [ops.clean_str(x) for x in sources]  # clean source names for later\n        self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n\n        for i, s in enumerate(sources):  # index, source\n            # Start thread to read frames from video stream\n            st = f'{i + 1}/{n}: {s}... '\n            if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'):  # if source is YouTube video\n                # YouTube format i.e. 'https://www.youtube.com/watch?v=Zgi9g1ksQHc' or 'https://youtu.be/Zgi9g1ksQHc'\n                s = get_best_youtube_url(s)\n            s = eval(s) if s.isnumeric() else s  # i.e. s = '0' local webcam\n            if s == 0 and (is_colab() or is_kaggle()):\n                raise NotImplementedError(\"'source=0' webcam not supported in Colab and Kaggle notebooks. \"\n                                          \"Try running 'source=0' in a local environment.\")\n            cap = cv2.VideoCapture(s)\n            if not cap.isOpened():\n                raise ConnectionError(f'{st}Failed to open {s}')\n            w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n            h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n            fps = cap.get(cv2.CAP_PROP_FPS)  # warning: may return 0 or nan\n            self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf')  # infinite stream fallback\n            self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30  # 30 FPS fallback\n\n            success, self.imgs[i] = cap.read()  # guarantee first frame\n            if not success or self.imgs[i] is None:\n                raise ConnectionError(f'{st}Failed to read images from {s}')\n            self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)\n            LOGGER.info(f'{st}Success ✅ ({self.frames[i]} frames of shape {w}x{h} at {self.fps[i]:.2f} FPS)')\n            self.threads[i].start()\n        LOGGER.info('')  # newline\n\n        # Check for common shapes\n        self.bs = self.__len__()\n\n    def update(self, i, cap, stream):\n        \"\"\"Read stream `i` frames in daemon thread.\"\"\"\n        n, f = 0, self.frames[i]  # frame number, frame array\n        while cap.isOpened() and n < f:\n            n += 1\n            cap.grab()  # .read() = .grab() followed by .retrieve()\n            if n % self.vid_stride == 0:\n                success, im = cap.retrieve()\n                if success:\n                    self.imgs[i] = im\n                else:\n                    LOGGER.warning('WARNING ⚠️ Video stream unresponsive, please check your IP camera connection.')\n                    self.imgs[i] = np.zeros_like(self.imgs[i])\n                    cap.open(stream)  # re-open stream if signal was lost\n            time.sleep(0.0)  # wait time\n\n    def __iter__(self):\n        \"\"\"Iterates through YOLO image feed and re-opens unresponsive streams.\"\"\"\n        self.count = -1\n        return self\n\n    def __next__(self):\n        \"\"\"Returns source paths, transformed and original images for processing YOLOv5.\"\"\"\n        self.count += 1\n        if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'):  # q to quit\n            cv2.destroyAllWindows()\n            raise StopIteration\n\n        im0 = self.imgs.copy()\n        return self.sources, im0, None, ''\n\n    def __len__(self):\n        \"\"\"Return the length of the sources object.\"\"\"\n        return len(self.sources)  # 1E12 frames = 32 streams at 30 FPS for 30 years\n\n\nclass LoadScreenshots:\n    # YOLOv8 screenshot dataloader, i.e. `yolo predict source=screen`\n    def __init__(self, source, imgsz=640):\n        \"\"\"source = [screen_number left top width height] (pixels).\"\"\"\n        check_requirements('mss')\n        import mss  # noqa\n\n        source, *params = source.split()\n        self.screen, left, top, width, height = 0, None, None, None, None  # default to full screen 0\n        if len(params) == 1:\n            self.screen = int(params[0])\n        elif len(params) == 4:\n            left, top, width, height = (int(x) for x in params)\n        elif len(params) == 5:\n            self.screen, left, top, width, height = (int(x) for x in params)\n        self.imgsz = imgsz\n        self.mode = 'stream'\n        self.frame = 0\n        self.sct = mss.mss()\n        self.bs = 1\n\n        # Parse monitor shape\n        monitor = self.sct.monitors[self.screen]\n        self.top = monitor['top'] if top is None else (monitor['top'] + top)\n        self.left = monitor['left'] if left is None else (monitor['left'] + left)\n        self.width = width or monitor['width']\n        self.height = height or monitor['height']\n        self.monitor = {'left': self.left, 'top': self.top, 'width': self.width, 'height': self.height}\n\n    def __iter__(self):\n        \"\"\"Returns an iterator of the object.\"\"\"\n        return self\n\n    def __next__(self):\n        \"\"\"mss screen capture: get raw pixels from the screen as np array.\"\"\"\n        im0 = np.array(self.sct.grab(self.monitor))[:, :, :3]  # [:, :, :3] BGRA to BGR\n        s = f'screen {self.screen} (LTWH): {self.left},{self.top},{self.width},{self.height}: '\n\n        self.frame += 1\n        return str(self.screen), im0, None, s  # screen, img, original img, im0s, s\n\n\nclass LoadImages:\n    # YOLOv8 image/video dataloader, i.e. `yolo predict source=image.jpg/vid.mp4`\n    def __init__(self, path, imgsz=640, vid_stride=1):\n        \"\"\"Initialize the Dataloader and raise FileNotFoundError if file not found.\"\"\"\n        if isinstance(path, str) and Path(path).suffix == '.txt':  # *.txt file with img/vid/dir on each line\n            path = Path(path).read_text().rsplit()\n        files = []\n        for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:\n            p = str(Path(p).absolute())  # do not use .resolve() https://github.com/ultralytics/ultralytics/issues/2912\n            if '*' in p:\n                files.extend(sorted(glob.glob(p, recursive=True)))  # glob\n            elif os.path.isdir(p):\n                files.extend(sorted(glob.glob(os.path.join(p, '*.*'))))  # dir\n            elif os.path.isfile(p):\n                files.append(p)  # files\n            else:\n                raise FileNotFoundError(f'{p} does not exist')\n\n        images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]\n        videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]\n        ni, nv = len(images), len(videos)\n\n        self.imgsz = imgsz\n        self.files = images + videos\n        self.nf = ni + nv  # number of files\n        self.video_flag = [False] * ni + [True] * nv\n        self.mode = 'image'\n        self.vid_stride = vid_stride  # video frame-rate stride\n        self.bs = 1\n        if any(videos):\n            self.orientation = None  # rotation degrees\n            self._new_video(videos[0])  # new video\n        else:\n            self.cap = None\n        if self.nf == 0:\n            raise FileNotFoundError(f'No images or videos found in {p}. '\n                                    f'Supported formats are:\\nimages: {IMG_FORMATS}\\nvideos: {VID_FORMATS}')\n\n    def __iter__(self):\n        \"\"\"Returns an iterator object for VideoStream or ImageFolder.\"\"\"\n        self.count = 0\n        return self\n\n    def __next__(self):\n        \"\"\"Return next image, path and metadata from dataset.\"\"\"\n        if self.count == self.nf:\n            raise StopIteration\n        path = self.files[self.count]\n\n        if self.video_flag[self.count]:\n            # Read video\n            self.mode = 'video'\n            for _ in range(self.vid_stride):\n                self.cap.grab()\n            success, im0 = self.cap.retrieve()\n            while not success:\n                self.count += 1\n                self.cap.release()\n                if self.count == self.nf:  # last video\n                    raise StopIteration\n                path = self.files[self.count]\n                self._new_video(path)\n                success, im0 = self.cap.read()\n\n            self.frame += 1\n            # im0 = self._cv2_rotate(im0)  # for use if cv2 autorotation is False\n            s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '\n\n        else:\n            # Read image\n            self.count += 1\n            im0 = cv2.imread(path)  # BGR\n            if im0 is None:\n                raise FileNotFoundError(f'Image Not Found {path}')\n            s = f'image {self.count}/{self.nf} {path}: '\n\n        return [path], [im0], self.cap, s\n\n    def _new_video(self, path):\n        \"\"\"Create a new video capture object.\"\"\"\n        self.frame = 0\n        self.cap = cv2.VideoCapture(path)\n        self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) / self.vid_stride)\n        if hasattr(cv2, 'CAP_PROP_ORIENTATION_META'):  # cv2<4.6.0 compatibility\n            self.orientation = int(self.cap.get(cv2.CAP_PROP_ORIENTATION_META))  # rotation degrees\n            # Disable auto-orientation due to known issues in https://github.com/ultralytics/yolov5/issues/8493\n            # self.cap.set(cv2.CAP_PROP_ORIENTATION_AUTO, 0)\n\n    def _cv2_rotate(self, im):\n        \"\"\"Rotate a cv2 video manually.\"\"\"\n        if self.orientation == 0:\n            return cv2.rotate(im, cv2.ROTATE_90_CLOCKWISE)\n        elif self.orientation == 180:\n            return cv2.rotate(im, cv2.ROTATE_90_COUNTERCLOCKWISE)\n        elif self.orientation == 90:\n            return cv2.rotate(im, cv2.ROTATE_180)\n        return im\n\n    def __len__(self):\n        \"\"\"Returns the number of files in the object.\"\"\"\n        return self.nf  # number of files\n\n\nclass LoadPilAndNumpy:\n\n    def __init__(self, im0, imgsz=640):\n        \"\"\"Initialize PIL and Numpy Dataloader.\"\"\"\n        if not isinstance(im0, list):\n            im0 = [im0]\n        self.paths = [getattr(im, 'filename', f'image{i}.jpg') for i, im in enumerate(im0)]\n        self.im0 = [self._single_check(im) for im in im0]\n        self.imgsz = imgsz\n        self.mode = 'image'\n        # Generate fake paths\n        self.bs = len(self.im0)\n\n    @staticmethod\n    def _single_check(im):\n        \"\"\"Validate and format an image to numpy array.\"\"\"\n        assert isinstance(im, (Image.Image, np.ndarray)), f'Expected PIL/np.ndarray image type, but got {type(im)}'\n        if isinstance(im, Image.Image):\n            if im.mode != 'RGB':\n                im = im.convert('RGB')\n            im = np.asarray(im)[:, :, ::-1]\n            im = np.ascontiguousarray(im)  # contiguous\n        return im\n\n    def __len__(self):\n        \"\"\"Returns the length of the 'im0' attribute.\"\"\"\n        return len(self.im0)\n\n    def __next__(self):\n        \"\"\"Returns batch paths, images, processed images, None, ''.\"\"\"\n        if self.count == 1:  # loop only once as it's batch inference\n            raise StopIteration\n        self.count += 1\n        return self.paths, self.im0, None, ''\n\n    def __iter__(self):\n        \"\"\"Enables iteration for class LoadPilAndNumpy.\"\"\"\n        self.count = 0\n        return self\n\n\nclass LoadTensor:\n\n    def __init__(self, imgs) -> None:\n        self.im0 = imgs\n        self.bs = imgs.shape[0]\n        self.mode = 'image'\n\n    def __iter__(self):\n        \"\"\"Returns an iterator object.\"\"\"\n        self.count = 0\n        return self\n\n    def __next__(self):\n        \"\"\"Return next item in the iterator.\"\"\"\n        if self.count == 1:\n            raise StopIteration\n        self.count += 1\n        return None, self.im0, None, ''  # self.paths, im, self.im0, None, ''\n\n    def __len__(self):\n        \"\"\"Returns the batch size.\"\"\"\n        return self.bs\n\n\ndef autocast_list(source):\n    \"\"\"\n    Merges a list of source of different types into a list of numpy arrays or PIL images\n    \"\"\"\n    files = []\n    for im in source:\n        if isinstance(im, (str, Path)):  # filename or uri\n            files.append(Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im))\n        elif isinstance(im, (Image.Image, np.ndarray)):  # PIL or np Image\n            files.append(im)\n        else:\n            raise TypeError(f'type {type(im).__name__} is not a supported Ultralytics prediction source type. \\n'\n                            f'See https://docs.ultralytics.com/modes/predict for supported source types.')\n\n    return files\n\n\nLOADERS = [LoadStreams, LoadPilAndNumpy, LoadImages, LoadScreenshots]\n\n\ndef get_best_youtube_url(url, use_pafy=True):\n    \"\"\"\n    Retrieves the URL of the best quality MP4 video stream from a given YouTube video.\n\n    This function uses the pafy or yt_dlp library to extract the video info from YouTube. It then finds the highest\n    quality MP4 format that has video codec but no audio codec, and returns the URL of this video stream.\n\n    Args:\n        url (str): The URL of the YouTube video.\n        use_pafy (bool): Use the pafy package, default=True, otherwise use yt_dlp package.\n\n    Returns:\n        (str): The URL of the best quality MP4 video stream, or None if no suitable stream is found.\n    \"\"\"\n    if use_pafy:\n        check_requirements(('pafy', 'youtube_dl==2020.12.2'))\n        import pafy  # noqa\n        return pafy.new(url).getbest(preftype='mp4').url\n    else:\n        check_requirements('yt-dlp')\n        import yt_dlp\n        with yt_dlp.YoutubeDL({'quiet': True}) as ydl:\n            info_dict = ydl.extract_info(url, download=False)  # extract info\n        for f in info_dict.get('formats', None):\n            if f['vcodec'] != 'none' and f['acodec'] == 'none' and f['ext'] == 'mp4':\n                return f.get('url', None)\n\n\nif __name__ == '__main__':\n    img = cv2.imread(str(ROOT / 'assets/bus.jpg'))\n    dataset = LoadPilAndNumpy(im0=img)\n    for d in dataset:\n        print(d[0])\n"
  },
  {
    "path": "ultralytics/yolo/data/dataloaders/v5augmentations.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nImage augmentation functions\n\"\"\"\n\nimport math\nimport random\n\nimport cv2\nimport numpy as np\nimport torch\nimport torchvision.transforms as T\nimport torchvision.transforms.functional as TF\n\nfrom ultralytics.yolo.utils import LOGGER, colorstr\nfrom ultralytics.yolo.utils.checks import check_version\nfrom ultralytics.yolo.utils.metrics import bbox_ioa\nfrom ultralytics.yolo.utils.ops import resample_segments, segment2box, xywhn2xyxy\n\nIMAGENET_MEAN = 0.485, 0.456, 0.406  # RGB mean\nIMAGENET_STD = 0.229, 0.224, 0.225  # RGB standard deviation\n\n\nclass Albumentations:\n    # YOLOv5 Albumentations class (optional, only used if package is installed)\n    def __init__(self, size=640):\n        \"\"\"Instantiate object with image augmentations for YOLOv5.\"\"\"\n        self.transform = None\n        prefix = colorstr('albumentations: ')\n        try:\n            import albumentations as A\n            check_version(A.__version__, '1.0.3', hard=True)  # version requirement\n\n            T = [\n                A.RandomResizedCrop(height=size, width=size, scale=(0.8, 1.0), ratio=(0.9, 1.11), p=0.0),\n                A.Blur(p=0.01),\n                A.MedianBlur(p=0.01),\n                A.ToGray(p=0.01),\n                A.CLAHE(p=0.01),\n                A.RandomBrightnessContrast(p=0.0),\n                A.RandomGamma(p=0.0),\n                A.ImageCompression(quality_lower=75, p=0.0)]  # transforms\n            self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))\n\n            LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))\n        except ImportError:  # package not installed, skip\n            pass\n        except Exception as e:\n            LOGGER.info(f'{prefix}{e}')\n\n    def __call__(self, im, labels, p=1.0):\n        \"\"\"Transforms input image and labels with probability 'p'.\"\"\"\n        if self.transform and random.random() < p:\n            new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0])  # transformed\n            im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])\n        return im, labels\n\n\ndef normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):\n    \"\"\"Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = (x - mean) / std.\"\"\"\n    return TF.normalize(x, mean, std, inplace=inplace)\n\n\ndef denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):\n    \"\"\"Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = x * std + mean.\"\"\"\n    for i in range(3):\n        x[:, i] = x[:, i] * std[i] + mean[i]\n    return x\n\n\ndef augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):\n    \"\"\"HSV color-space augmentation.\"\"\"\n    if hgain or sgain or vgain:\n        r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1  # random gains\n        hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))\n        dtype = im.dtype  # uint8\n\n        x = np.arange(0, 256, dtype=r.dtype)\n        lut_hue = ((x * r[0]) % 180).astype(dtype)\n        lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)\n        lut_val = np.clip(x * r[2], 0, 255).astype(dtype)\n\n        im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))\n        cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im)  # no return needed\n\n\ndef hist_equalize(im, clahe=True, bgr=False):\n    \"\"\"Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255.\"\"\"\n    yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)\n    if clahe:\n        c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n        yuv[:, :, 0] = c.apply(yuv[:, :, 0])\n    else:\n        yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0])  # equalize Y channel histogram\n    return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB)  # convert YUV image to RGB\n\n\ndef replicate(im, labels):\n    \"\"\"Replicate labels.\"\"\"\n    h, w = im.shape[:2]\n    boxes = labels[:, 1:].astype(int)\n    x1, y1, x2, y2 = boxes.T\n    s = ((x2 - x1) + (y2 - y1)) / 2  # side length (pixels)\n    for i in s.argsort()[:round(s.size * 0.5)]:  # smallest indices\n        x1b, y1b, x2b, y2b = boxes[i]\n        bh, bw = y2b - y1b, x2b - x1b\n        yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw))  # offset x, y\n        x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]\n        im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b]  # im4[ymin:ymax, xmin:xmax]\n        labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)\n\n    return im, labels\n\n\ndef letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):\n    \"\"\"Resize and pad image while meeting stride-multiple constraints.\"\"\"\n    shape = im.shape[:2]  # current shape [height, width]\n    if isinstance(new_shape, int):\n        new_shape = (new_shape, new_shape)\n\n    # Scale ratio (new / old)\n    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n    if not scaleup:  # only scale down, do not scale up (for better val mAP)\n        r = min(r, 1.0)\n\n    # Compute padding\n    ratio = r, r  # width, height ratios\n    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding\n    if auto:  # minimum rectangle\n        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding\n    elif scaleFill:  # stretch\n        dw, dh = 0.0, 0.0\n        new_unpad = (new_shape[1], new_shape[0])\n        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios\n\n    dw /= 2  # divide padding into 2 sides\n    dh /= 2\n\n    if shape[::-1] != new_unpad:  # resize\n        im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)\n    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n    im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border\n    return im, ratio, (dw, dh)\n\n\ndef random_perspective(im,\n                       targets=(),\n                       segments=(),\n                       degrees=10,\n                       translate=.1,\n                       scale=.1,\n                       shear=10,\n                       perspective=0.0,\n                       border=(0, 0)):\n    # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))\n    # targets = [cls, xyxy]\n\n    height = im.shape[0] + border[0] * 2  # shape(h,w,c)\n    width = im.shape[1] + border[1] * 2\n\n    # Center\n    C = np.eye(3)\n    C[0, 2] = -im.shape[1] / 2  # x translation (pixels)\n    C[1, 2] = -im.shape[0] / 2  # y translation (pixels)\n\n    # Perspective\n    P = np.eye(3)\n    P[2, 0] = random.uniform(-perspective, perspective)  # x perspective (about y)\n    P[2, 1] = random.uniform(-perspective, perspective)  # y perspective (about x)\n\n    # Rotation and Scale\n    R = np.eye(3)\n    a = random.uniform(-degrees, degrees)\n    # a += random.choice([-180, -90, 0, 90])  # add 90deg rotations to small rotations\n    s = random.uniform(1 - scale, 1 + scale)\n    # s = 2 ** random.uniform(-scale, scale)\n    R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)\n\n    # Shear\n    S = np.eye(3)\n    S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # x shear (deg)\n    S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # y shear (deg)\n\n    # Translation\n    T = np.eye(3)\n    T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width  # x translation (pixels)\n    T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height  # y translation (pixels)\n\n    # Combined rotation matrix\n    M = T @ S @ R @ P @ C  # order of operations (right to left) is IMPORTANT\n    if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():  # image changed\n        if perspective:\n            im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))\n        else:  # affine\n            im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))\n\n    # Visualize\n    # import matplotlib.pyplot as plt\n    # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()\n    # ax[0].imshow(im[:, :, ::-1])  # base\n    # ax[1].imshow(im2[:, :, ::-1])  # warped\n\n    # Transform label coordinates\n    n = len(targets)\n    if n:\n        use_segments = any(x.any() for x in segments)\n        new = np.zeros((n, 4))\n        if use_segments:  # warp segments\n            segments = resample_segments(segments)  # upsample\n            for i, segment in enumerate(segments):\n                xy = np.ones((len(segment), 3))\n                xy[:, :2] = segment\n                xy = xy @ M.T  # transform\n                xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]  # perspective rescale or affine\n\n                # Clip\n                new[i] = segment2box(xy, width, height)\n\n        else:  # warp boxes\n            xy = np.ones((n * 4, 3))\n            xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2)  # x1y1, x2y2, x1y2, x2y1\n            xy = xy @ M.T  # transform\n            xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8)  # perspective rescale or affine\n\n            # Create new boxes\n            x = xy[:, [0, 2, 4, 6]]\n            y = xy[:, [1, 3, 5, 7]]\n            new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T\n\n            # Clip\n            new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)\n            new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)\n\n        # Filter candidates\n        i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)\n        targets = targets[i]\n        targets[:, 1:5] = new[i]\n\n    return im, targets\n\n\ndef copy_paste(im, labels, segments, p=0.5):\n    \"\"\"Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy).\"\"\"\n    n = len(segments)\n    if p and n:\n        h, w, c = im.shape  # height, width, channels\n        im_new = np.zeros(im.shape, np.uint8)\n\n        # Calculate ioa first then select indexes randomly\n        boxes = np.stack([w - labels[:, 3], labels[:, 2], w - labels[:, 1], labels[:, 4]], axis=-1)  # (n, 4)\n        ioa = bbox_ioa(boxes, labels[:, 1:5])  # intersection over area\n        indexes = np.nonzero((ioa < 0.30).all(1))[0]  # (N, )\n        n = len(indexes)\n        for j in random.sample(list(indexes), k=round(p * n)):\n            l, box, s = labels[j], boxes[j], segments[j]\n            labels = np.concatenate((labels, [[l[0], *box]]), 0)\n            segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))\n            cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (1, 1, 1), cv2.FILLED)\n\n        result = cv2.flip(im, 1)  # augment segments (flip left-right)\n        i = cv2.flip(im_new, 1).astype(bool)\n        im[i] = result[i]  # cv2.imwrite('debug.jpg', im)  # debug\n\n    return im, labels, segments\n\n\ndef cutout(im, labels, p=0.5):\n    \"\"\"Applies image cutout augmentation https://arxiv.org/abs/1708.04552.\"\"\"\n    if random.random() < p:\n        h, w = im.shape[:2]\n        scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16  # image size fraction\n        for s in scales:\n            mask_h = random.randint(1, int(h * s))  # create random masks\n            mask_w = random.randint(1, int(w * s))\n\n            # Box\n            xmin = max(0, random.randint(0, w) - mask_w // 2)\n            ymin = max(0, random.randint(0, h) - mask_h // 2)\n            xmax = min(w, xmin + mask_w)\n            ymax = min(h, ymin + mask_h)\n\n            # Apply random color mask\n            im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]\n\n            # Return unobscured labels\n            if len(labels) and s > 0.03:\n                box = np.array([[xmin, ymin, xmax, ymax]], dtype=np.float32)\n                ioa = bbox_ioa(box, xywhn2xyxy(labels[:, 1:5], w, h))[0]  # intersection over area\n                labels = labels[ioa < 0.60]  # remove >60% obscured labels\n\n    return labels\n\n\ndef mixup(im, labels, im2, labels2):\n    \"\"\"Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf.\"\"\"\n    r = np.random.beta(32.0, 32.0)  # mixup ratio, alpha=beta=32.0\n    im = (im * r + im2 * (1 - r)).astype(np.uint8)\n    labels = np.concatenate((labels, labels2), 0)\n    return im, labels\n\n\ndef box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):  # box1(4,n), box2(4,n)\n    # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio\n    w1, h1 = box1[2] - box1[0], box1[3] - box1[1]\n    w2, h2 = box2[2] - box2[0], box2[3] - box2[1]\n    ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps))  # aspect ratio\n    return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr)  # candidates\n\n\ndef classify_albumentations(\n        augment=True,\n        size=224,\n        scale=(0.08, 1.0),\n        ratio=(0.75, 1.0 / 0.75),  # 0.75, 1.33\n        hflip=0.5,\n        vflip=0.0,\n        jitter=0.4,\n        mean=IMAGENET_MEAN,\n        std=IMAGENET_STD,\n        auto_aug=False):\n    # YOLOv5 classification Albumentations (optional, only used if package is installed)\n    prefix = colorstr('albumentations: ')\n    try:\n        import albumentations as A\n        from albumentations.pytorch import ToTensorV2\n        check_version(A.__version__, '1.0.3', hard=True)  # version requirement\n        if augment:  # Resize and crop\n            T = [A.RandomResizedCrop(height=size, width=size, scale=scale, ratio=ratio)]\n            if auto_aug:\n                # TODO: implement AugMix, AutoAug & RandAug in albumentation\n                LOGGER.info(f'{prefix}auto augmentations are currently not supported')\n            else:\n                if hflip > 0:\n                    T += [A.HorizontalFlip(p=hflip)]\n                if vflip > 0:\n                    T += [A.VerticalFlip(p=vflip)]\n                if jitter > 0:\n                    jitter = float(jitter)\n                    T += [A.ColorJitter(jitter, jitter, jitter, 0)]  # brightness, contrast, satuaration, 0 hue\n        else:  # Use fixed crop for eval set (reproducibility)\n            T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]\n        T += [A.Normalize(mean=mean, std=std), ToTensorV2()]  # Normalize and convert to Tensor\n        LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))\n        return A.Compose(T)\n\n    except ImportError:  # package not installed, skip\n        LOGGER.warning(f'{prefix}⚠️ not found, install with `pip install albumentations` (recommended)')\n    except Exception as e:\n        LOGGER.info(f'{prefix}{e}')\n\n\ndef classify_transforms(size=224):\n    \"\"\"Transforms to apply if albumentations not installed.\"\"\"\n    assert isinstance(size, int), f'ERROR: classify_transforms size {size} must be integer, not (list, tuple)'\n    # T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])\n    return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])\n\n\nclass LetterBox:\n    # YOLOv5 LetterBox class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])\n    def __init__(self, size=(640, 640), auto=False, stride=32):\n        \"\"\"Resizes and crops an image to a specified size for YOLOv5 preprocessing.\"\"\"\n        super().__init__()\n        self.h, self.w = (size, size) if isinstance(size, int) else size\n        self.auto = auto  # pass max size integer, automatically solve for short side using stride\n        self.stride = stride  # used with auto\n\n    def __call__(self, im):  # im = np.array HWC\n        imh, imw = im.shape[:2]\n        r = min(self.h / imh, self.w / imw)  # ratio of new/old\n        h, w = round(imh * r), round(imw * r)  # resized image\n        hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w\n        top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)\n        im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)\n        im_out[top:top + h, left:left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)\n        return im_out\n\n\nclass CenterCrop:\n    # YOLOv5 CenterCrop class for image preprocessing, i.e. T.Compose([CenterCrop(size), ToTensor()])\n    def __init__(self, size=640):\n        \"\"\"Converts input image into tensor for YOLOv5 processing.\"\"\"\n        super().__init__()\n        self.h, self.w = (size, size) if isinstance(size, int) else size\n\n    def __call__(self, im):  # im = np.array HWC\n        imh, imw = im.shape[:2]\n        m = min(imh, imw)  # min dimension\n        top, left = (imh - m) // 2, (imw - m) // 2\n        return cv2.resize(im[top:top + m, left:left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)\n\n\nclass ToTensor:\n    # YOLOv5 ToTensor class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])\n    def __init__(self, half=False):\n        \"\"\"Initialize ToTensor class for YOLOv5 image preprocessing.\"\"\"\n        super().__init__()\n        self.half = half\n\n    def __call__(self, im):  # im = np.array HWC in BGR order\n        im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1])  # HWC to CHW -> BGR to RGB -> contiguous\n        im = torch.from_numpy(im)  # to torch\n        im = im.half() if self.half else im.float()  # uint8 to fp16/32\n        im /= 255.0  # 0-255 to 0.0-1.0\n        return im\n"
  },
  {
    "path": "ultralytics/yolo/data/dataloaders/v5loader.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nDataloaders and dataset utils\n\"\"\"\n\nimport contextlib\nimport glob\nimport hashlib\nimport math\nimport os\nimport random\nimport shutil\nimport time\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom threading import Thread\nfrom urllib.parse import urlparse\n\nimport cv2\nimport numpy as np\nimport psutil\nimport torch\nimport torchvision\nfrom PIL import ExifTags, Image, ImageOps\nfrom torch.utils.data import DataLoader, Dataset, dataloader, distributed\nfrom tqdm import tqdm\n\nfrom ultralytics.yolo.utils import (DATASETS_DIR, LOGGER, NUM_THREADS, TQDM_BAR_FORMAT, is_colab, is_dir_writeable,\n                                    is_kaggle)\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.ops import clean_str, segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn\nfrom ultralytics.yolo.utils.torch_utils import torch_distributed_zero_first\n\nfrom .v5augmentations import (Albumentations, augment_hsv, classify_albumentations, classify_transforms, copy_paste,\n                              letterbox, mixup, random_perspective)\n\n# Parameters\nHELP_URL = 'See https://docs.ultralytics.com/yolov5/tutorials/train_custom_data'\nIMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp', 'pfm'  # include image suffixes\nVID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv'  # include video suffixes\nLOCAL_RANK = int(os.getenv('LOCAL_RANK', -1))  # https://pytorch.org/docs/stable/elastic/run.html\nRANK = int(os.getenv('RANK', -1))\nPIN_MEMORY = str(os.getenv('PIN_MEMORY', True)).lower() == 'true'  # global pin_memory for dataloaders\n\n# Get orientation exif tag\nfor orientation in ExifTags.TAGS.keys():\n    if ExifTags.TAGS[orientation] == 'Orientation':\n        break\n\n\ndef get_hash(paths):\n    \"\"\"Returns a single hash value of a list of paths (files or dirs).\"\"\"\n    size = sum(os.path.getsize(p) for p in paths if os.path.exists(p))  # sizes\n    h = hashlib.sha256(str(size).encode())  # hash sizes\n    h.update(''.join(paths).encode())  # hash paths\n    return h.hexdigest()  # return hash\n\n\ndef exif_size(img):\n    \"\"\"Returns exif-corrected PIL size.\"\"\"\n    s = img.size  # (width, height)\n    with contextlib.suppress(Exception):\n        rotation = dict(img._getexif().items())[orientation]\n        if rotation in [6, 8]:  # rotation 270 or 90\n            s = (s[1], s[0])\n    return s\n\n\ndef exif_transpose(image):\n    \"\"\"\n    Transpose a PIL image accordingly if it has an EXIF Orientation tag.\n    Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()\n\n    :param image: The image to transpose.\n    :return: An image.\n    \"\"\"\n    exif = image.getexif()\n    orientation = exif.get(0x0112, 1)  # default 1\n    if orientation > 1:\n        method = {\n            2: Image.FLIP_LEFT_RIGHT,\n            3: Image.ROTATE_180,\n            4: Image.FLIP_TOP_BOTTOM,\n            5: Image.TRANSPOSE,\n            6: Image.ROTATE_270,\n            7: Image.TRANSVERSE,\n            8: Image.ROTATE_90}.get(orientation)\n        if method is not None:\n            image = image.transpose(method)\n            del exif[0x0112]\n            image.info['exif'] = exif.tobytes()\n    return image\n\n\ndef seed_worker(worker_id):\n    \"\"\"Set dataloader worker seed https://pytorch.org/docs/stable/notes/randomness.html#dataloader.\"\"\"\n    worker_seed = torch.initial_seed() % 2 ** 32\n    np.random.seed(worker_seed)\n    random.seed(worker_seed)\n\n\ndef create_dataloader(path,\n                      imgsz,\n                      batch_size,\n                      stride,\n                      single_cls=False,\n                      hyp=None,\n                      augment=False,\n                      cache=False,\n                      pad=0.0,\n                      rect=False,\n                      rank=-1,\n                      workers=8,\n                      image_weights=False,\n                      close_mosaic=False,\n                      min_items=0,\n                      prefix='',\n                      shuffle=False,\n                      seed=0):\n    if rect and shuffle:\n        LOGGER.warning('WARNING ⚠️ --rect is incompatible with DataLoader shuffle, setting shuffle=False')\n        shuffle = False\n    with torch_distributed_zero_first(rank):  # init dataset *.cache only once if DDP\n        dataset = LoadImagesAndLabels(\n            path,\n            imgsz,\n            batch_size,\n            augment=augment,  # augmentation\n            hyp=hyp,  # hyperparameters\n            rect=rect,  # rectangular batches\n            cache_images=cache,\n            single_cls=single_cls,\n            stride=int(stride),\n            pad=pad,\n            image_weights=image_weights,\n            min_items=min_items,\n            prefix=prefix)\n\n    batch_size = min(batch_size, len(dataset))\n    nd = torch.cuda.device_count()  # number of CUDA devices\n    nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers])  # number of workers\n    sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)\n    loader = DataLoader if image_weights or close_mosaic else InfiniteDataLoader  # DataLoader allows attribute updates\n    generator = torch.Generator()\n    generator.manual_seed(6148914691236517205 + seed + RANK)\n    return loader(dataset,\n                  batch_size=batch_size,\n                  shuffle=shuffle and sampler is None,\n                  num_workers=nw,\n                  sampler=sampler,\n                  pin_memory=PIN_MEMORY,\n                  collate_fn=LoadImagesAndLabels.collate_fn,\n                  worker_init_fn=seed_worker,\n                  generator=generator), dataset\n\n\nclass InfiniteDataLoader(dataloader.DataLoader):\n    \"\"\"Dataloader that reuses workers\n\n    Uses same syntax as vanilla DataLoader\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Dataloader that reuses workers for same syntax as vanilla DataLoader.\"\"\"\n        super().__init__(*args, **kwargs)\n        object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))\n        self.iterator = super().__iter__()\n\n    def __len__(self):\n        \"\"\"Returns the length of batch_sampler's sampler.\"\"\"\n        return len(self.batch_sampler.sampler)\n\n    def __iter__(self):\n        \"\"\"Creates a sampler that infinitely repeats.\"\"\"\n        for _ in range(len(self)):\n            yield next(self.iterator)\n\n\nclass _RepeatSampler:\n    \"\"\"Sampler that repeats forever\n\n    Args:\n        sampler (Dataset.sampler): The sampler to repeat.\n    \"\"\"\n\n    def __init__(self, sampler):\n        \"\"\"Sampler that repeats dataset samples infinitely.\"\"\"\n        self.sampler = sampler\n\n    def __iter__(self):\n        \"\"\"Infinite loop iterating over a given sampler.\"\"\"\n        while True:\n            yield from iter(self.sampler)\n\n\nclass LoadScreenshots:\n    # YOLOv5 screenshot dataloader, i.e. `python detect.py --source \"screen 0 100 100 512 256\"`\n    def __init__(self, source, img_size=640, stride=32, auto=True, transforms=None):\n        \"\"\"source = [screen_number left top width height] (pixels).\"\"\"\n        check_requirements('mss')\n        import mss\n\n        source, *params = source.split()\n        self.screen, left, top, width, height = 0, None, None, None, None  # default to full screen 0\n        if len(params) == 1:\n            self.screen = int(params[0])\n        elif len(params) == 4:\n            left, top, width, height = (int(x) for x in params)\n        elif len(params) == 5:\n            self.screen, left, top, width, height = (int(x) for x in params)\n        self.img_size = img_size\n        self.stride = stride\n        self.transforms = transforms\n        self.auto = auto\n        self.mode = 'stream'\n        self.frame = 0\n        self.sct = mss.mss()\n\n        # Parse monitor shape\n        monitor = self.sct.monitors[self.screen]\n        self.top = monitor['top'] if top is None else (monitor['top'] + top)\n        self.left = monitor['left'] if left is None else (monitor['left'] + left)\n        self.width = width or monitor['width']\n        self.height = height or monitor['height']\n        self.monitor = {'left': self.left, 'top': self.top, 'width': self.width, 'height': self.height}\n\n    def __iter__(self):\n        \"\"\"Iterates over objects with the same structure as the monitor attribute.\"\"\"\n        return self\n\n    def __next__(self):\n        \"\"\"mss screen capture: get raw pixels from the screen as np array.\"\"\"\n        im0 = np.array(self.sct.grab(self.monitor))[:, :, :3]  # [:, :, :3] BGRA to BGR\n        s = f'screen {self.screen} (LTWH): {self.left},{self.top},{self.width},{self.height}: '\n\n        if self.transforms:\n            im = self.transforms(im0)  # transforms\n        else:\n            im = letterbox(im0, self.img_size, stride=self.stride, auto=self.auto)[0]  # padded resize\n            im = im.transpose((2, 0, 1))[::-1]  # HWC to CHW, BGR to RGB\n            im = np.ascontiguousarray(im)  # contiguous\n        self.frame += 1\n        return str(self.screen), im, im0, None, s  # screen, img, original img, im0s, s\n\n\nclass LoadImages:\n    # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`\n    def __init__(self, path, img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):\n        \"\"\"Initialize instance variables and check for valid input.\"\"\"\n        if isinstance(path, str) and Path(path).suffix == '.txt':  # *.txt file with img/vid/dir on each line\n            path = Path(path).read_text().rsplit()\n        files = []\n        for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:\n            p = str(Path(p).resolve())\n            if '*' in p:\n                files.extend(sorted(glob.glob(p, recursive=True)))  # glob\n            elif os.path.isdir(p):\n                files.extend(sorted(glob.glob(os.path.join(p, '*.*'))))  # dir\n            elif os.path.isfile(p):\n                files.append(p)  # files\n            else:\n                raise FileNotFoundError(f'{p} does not exist')\n\n        images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]\n        videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]\n        ni, nv = len(images), len(videos)\n\n        self.img_size = img_size\n        self.stride = stride\n        self.files = images + videos\n        self.nf = ni + nv  # number of files\n        self.video_flag = [False] * ni + [True] * nv\n        self.mode = 'image'\n        self.auto = auto\n        self.transforms = transforms  # optional\n        self.vid_stride = vid_stride  # video frame-rate stride\n        if any(videos):\n            self._new_video(videos[0])  # new video\n        else:\n            self.cap = None\n        assert self.nf > 0, f'No images or videos found in {p}. ' \\\n                            f'Supported formats are:\\nimages: {IMG_FORMATS}\\nvideos: {VID_FORMATS}'\n\n    def __iter__(self):\n        \"\"\"Returns an iterator object for iterating over images or videos found in a directory.\"\"\"\n        self.count = 0\n        return self\n\n    def __next__(self):\n        \"\"\"Iterator's next item, performs transformation on image and returns path, transformed image, original image, capture and size.\"\"\"\n        if self.count == self.nf:\n            raise StopIteration\n        path = self.files[self.count]\n\n        if self.video_flag[self.count]:\n            # Read video\n            self.mode = 'video'\n            for _ in range(self.vid_stride):\n                self.cap.grab()\n            ret_val, im0 = self.cap.retrieve()\n            while not ret_val:\n                self.count += 1\n                self.cap.release()\n                if self.count == self.nf:  # last video\n                    raise StopIteration\n                path = self.files[self.count]\n                self._new_video(path)\n                ret_val, im0 = self.cap.read()\n\n            self.frame += 1\n            # im0 = self._cv2_rotate(im0)  # for use if cv2 autorotation is False\n            s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '\n\n        else:\n            # Read image\n            self.count += 1\n            im0 = cv2.imread(path)  # BGR\n            assert im0 is not None, f'Image Not Found {path}'\n            s = f'image {self.count}/{self.nf} {path}: '\n\n        if self.transforms:\n            im = self.transforms(im0)  # transforms\n        else:\n            im = letterbox(im0, self.img_size, stride=self.stride, auto=self.auto)[0]  # padded resize\n            im = im.transpose((2, 0, 1))[::-1]  # HWC to CHW, BGR to RGB\n            im = np.ascontiguousarray(im)  # contiguous\n\n        return path, im, im0, self.cap, s\n\n    def _new_video(self, path):\n        \"\"\"Create a new video capture object.\"\"\"\n        self.frame = 0\n        self.cap = cv2.VideoCapture(path)\n        self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) / self.vid_stride)\n        self.orientation = int(self.cap.get(cv2.CAP_PROP_ORIENTATION_META))  # rotation degrees\n        # self.cap.set(cv2.CAP_PROP_ORIENTATION_AUTO, 0)  # disable https://github.com/ultralytics/yolov5/issues/8493\n\n    def _cv2_rotate(self, im):\n        \"\"\"Rotate a cv2 video manually.\"\"\"\n        if self.orientation == 0:\n            return cv2.rotate(im, cv2.ROTATE_90_CLOCKWISE)\n        elif self.orientation == 180:\n            return cv2.rotate(im, cv2.ROTATE_90_COUNTERCLOCKWISE)\n        elif self.orientation == 90:\n            return cv2.rotate(im, cv2.ROTATE_180)\n        return im\n\n    def __len__(self):\n        \"\"\"Returns the number of files in the class instance.\"\"\"\n        return self.nf  # number of files\n\n\nclass LoadStreams:\n    # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP streams`\n    def __init__(self, sources='file.streams', img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):\n        \"\"\"Initialize YOLO detector with optional transforms and check input shapes.\"\"\"\n        torch.backends.cudnn.benchmark = True  # faster for fixed-size inference\n        self.mode = 'stream'\n        self.img_size = img_size\n        self.stride = stride\n        self.vid_stride = vid_stride  # video frame-rate stride\n        sources = Path(sources).read_text().rsplit() if os.path.isfile(sources) else [sources]\n        n = len(sources)\n        self.sources = [clean_str(x) for x in sources]  # clean source names for later\n        self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n\n        for i, s in enumerate(sources):  # index, source\n            # Start thread to read frames from video stream\n            st = f'{i + 1}/{n}: {s}... '\n            if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'):  # if source is YouTube video\n                # YouTube format i.e. 'https://www.youtube.com/watch?v=Zgi9g1ksQHc' or 'https://youtu.be/Zgi9g1ksQHc'\n                check_requirements(('pafy', 'youtube_dl==2020.12.2'))\n                import pafy\n                s = pafy.new(s).getbest(preftype='mp4').url  # YouTube URL\n            s = eval(s) if s.isnumeric() else s  # i.e. s = '0' local webcam\n            if s == 0:\n                assert not is_colab(), '--source 0 webcam unsupported on Colab. Rerun command in a local environment.'\n                assert not is_kaggle(), '--source 0 webcam unsupported on Kaggle. Rerun command in a local environment.'\n            cap = cv2.VideoCapture(s)\n            assert cap.isOpened(), f'{st}Failed to open {s}'\n            w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n            h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n            fps = cap.get(cv2.CAP_PROP_FPS)  # warning: may return 0 or nan\n            self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf')  # infinite stream fallback\n            self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30  # 30 FPS fallback\n\n            _, self.imgs[i] = cap.read()  # guarantee first frame\n            self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)\n            LOGGER.info(f'{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)')\n            self.threads[i].start()\n        LOGGER.info('')  # newline\n\n        # Check for common shapes\n        s = np.stack([letterbox(x, img_size, stride=stride, auto=auto)[0].shape for x in self.imgs])\n        self.rect = np.unique(s, axis=0).shape[0] == 1  # rect inference if all shapes equal\n        self.auto = auto and self.rect\n        self.transforms = transforms  # optional\n        if not self.rect:\n            LOGGER.warning('WARNING ⚠️ Stream shapes differ. For optimal performance supply similarly-shaped streams.')\n\n    def update(self, i, cap, stream):\n        \"\"\"Read stream `i` frames in daemon thread.\"\"\"\n        n, f = 0, self.frames[i]  # frame number, frame array\n        while cap.isOpened() and n < f:\n            n += 1\n            cap.grab()  # .read() = .grab() followed by .retrieve()\n            if n % self.vid_stride == 0:\n                success, im = cap.retrieve()\n                if success:\n                    self.imgs[i] = im\n                else:\n                    LOGGER.warning('WARNING ⚠️ Video stream unresponsive, please check your IP camera connection.')\n                    self.imgs[i] = np.zeros_like(self.imgs[i])\n                    cap.open(stream)  # re-open stream if signal was lost\n            time.sleep(0.0)  # wait time\n\n    def __iter__(self):\n        \"\"\"Iterator that returns the class instance.\"\"\"\n        self.count = -1\n        return self\n\n    def __next__(self):\n        \"\"\"Return a tuple containing transformed and resized image data.\"\"\"\n        self.count += 1\n        if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'):  # q to quit\n            cv2.destroyAllWindows()\n            raise StopIteration\n\n        im0 = self.imgs.copy()\n        if self.transforms:\n            im = np.stack([self.transforms(x) for x in im0])  # transforms\n        else:\n            im = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0] for x in im0])  # resize\n            im = im[..., ::-1].transpose((0, 3, 1, 2))  # BGR to RGB, BHWC to BCHW\n            im = np.ascontiguousarray(im)  # contiguous\n\n        return self.sources, im, im0, None, ''\n\n    def __len__(self):\n        \"\"\"Returns the number of sources as the length of the object.\"\"\"\n        return len(self.sources)  # 1E12 frames = 32 streams at 30 FPS for 30 years\n\n\ndef img2label_paths(img_paths):\n    \"\"\"Define label paths as a function of image paths.\"\"\"\n    sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}'  # /images/, /labels/ substrings\n    return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]\n\n\nclass LoadImagesAndLabels(Dataset):\n    \"\"\"YOLOv5 train_loader/val_loader, loads images and labels for training and validation.\"\"\"\n    cache_version = 0.6  # dataset labels *.cache version\n    rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]\n\n    def __init__(self,\n                 path,\n                 img_size=640,\n                 batch_size=16,\n                 augment=False,\n                 hyp=None,\n                 rect=False,\n                 image_weights=False,\n                 cache_images=False,\n                 single_cls=False,\n                 stride=32,\n                 pad=0.0,\n                 min_items=0,\n                 prefix=''):\n        self.img_size = img_size\n        self.augment = augment\n        self.hyp = hyp\n        self.image_weights = image_weights\n        self.rect = False if image_weights else rect\n        self.mosaic = self.augment and not self.rect  # load 4 images at a time into a mosaic (only during training)\n        self.mosaic_border = [-img_size // 2, -img_size // 2]\n        self.stride = stride\n        self.path = path\n        self.albumentations = Albumentations(size=img_size) if augment else None\n\n        try:\n            f = []  # image files\n            for p in path if isinstance(path, list) else [path]:\n                p = Path(p)  # os-agnostic\n                if p.is_dir():  # dir\n                    f += glob.glob(str(p / '**' / '*.*'), recursive=True)\n                    # f = list(p.rglob('*.*'))  # pathlib\n                elif p.is_file():  # file\n                    with open(p) as t:\n                        t = t.read().strip().splitlines()\n                        parent = str(p.parent) + os.sep\n                        f += [x.replace('./', parent, 1) if x.startswith('./') else x for x in t]  # to global path\n                        # f += [p.parent / x.lstrip(os.sep) for x in t]  # to global path (pathlib)\n                else:\n                    raise FileNotFoundError(f'{prefix}{p} does not exist')\n            self.im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)\n            # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS])  # pathlib\n            assert self.im_files, f'{prefix}No images found'\n        except Exception as e:\n            raise FileNotFoundError(f'{prefix}Error loading data from {path}: {e}\\n{HELP_URL}') from e\n\n        # Check cache\n        self.label_files = img2label_paths(self.im_files)  # labels\n        cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')\n        try:\n            cache, exists = np.load(cache_path, allow_pickle=True).item(), True  # load dict\n            assert cache['version'] == self.cache_version  # matches current version\n            assert cache['hash'] == get_hash(self.label_files + self.im_files)  # identical hash\n        except (FileNotFoundError, AssertionError, AttributeError):\n            cache, exists = self.cache_labels(cache_path, prefix), False  # run cache ops\n\n        # Display cache\n        nf, nm, ne, nc, n = cache.pop('results')  # found, missing, empty, corrupt, total\n        if exists and LOCAL_RANK in (-1, 0):\n            d = f'Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt'\n            tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=TQDM_BAR_FORMAT)  # display cache results\n            if cache['msgs']:\n                LOGGER.info('\\n'.join(cache['msgs']))  # display warnings\n        assert nf > 0 or not augment, f'{prefix}No labels found in {cache_path}, can not start training. {HELP_URL}'\n\n        # Read cache\n        [cache.pop(k) for k in ('hash', 'version', 'msgs')]  # remove items\n        labels, shapes, self.segments = zip(*cache.values())\n        nl = len(np.concatenate(labels, 0))  # number of labels\n        assert nl > 0 or not augment, f'{prefix}All labels empty in {cache_path}, can not start training. {HELP_URL}'\n        self.labels = list(labels)\n        self.shapes = np.array(shapes)\n        self.im_files = list(cache.keys())  # update\n        self.label_files = img2label_paths(cache.keys())  # update\n\n        # Filter images\n        if min_items:\n            include = np.array([len(x) >= min_items for x in self.labels]).nonzero()[0].astype(int)\n            LOGGER.info(f'{prefix}{n - len(include)}/{n} images filtered from dataset')\n            self.im_files = [self.im_files[i] for i in include]\n            self.label_files = [self.label_files[i] for i in include]\n            self.labels = [self.labels[i] for i in include]\n            self.segments = [self.segments[i] for i in include]\n            self.shapes = self.shapes[include]  # wh\n\n        # Create indices\n        n = len(self.shapes)  # number of images\n        bi = np.floor(np.arange(n) / batch_size).astype(int)  # batch index\n        nb = bi[-1] + 1  # number of batches\n        self.batch = bi  # batch index of image\n        self.n = n\n        self.indices = range(n)\n\n        # Update labels\n        include_class = []  # filter labels to include only these classes (optional)\n        include_class_array = np.array(include_class).reshape(1, -1)\n        for i, (label, segment) in enumerate(zip(self.labels, self.segments)):\n            if include_class:\n                j = (label[:, 0:1] == include_class_array).any(1)\n                self.labels[i] = label[j]\n                if segment:\n                    self.segments[i] = [segment[si] for si, idx in enumerate(j) if idx]\n            if single_cls:  # single-class training, merge all classes into 0\n                self.labels[i][:, 0] = 0\n\n        # Rectangular Training\n        if self.rect:\n            # Sort by aspect ratio\n            s = self.shapes  # wh\n            ar = s[:, 1] / s[:, 0]  # aspect ratio\n            irect = ar.argsort()\n            self.im_files = [self.im_files[i] for i in irect]\n            self.label_files = [self.label_files[i] for i in irect]\n            self.labels = [self.labels[i] for i in irect]\n            self.segments = [self.segments[i] for i in irect]\n            self.shapes = s[irect]  # wh\n            ar = ar[irect]\n\n            # Set training image shapes\n            shapes = [[1, 1]] * nb\n            for i in range(nb):\n                ari = ar[bi == i]\n                mini, maxi = ari.min(), ari.max()\n                if maxi < 1:\n                    shapes[i] = [maxi, 1]\n                elif mini > 1:\n                    shapes[i] = [1, 1 / mini]\n\n            self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(int) * stride\n\n        # Cache images into RAM/disk for faster training\n        if cache_images == 'ram' and not self.check_cache_ram(prefix=prefix):\n            cache_images = False\n        self.ims = [None] * n\n        self.npy_files = [Path(f).with_suffix('.npy') for f in self.im_files]\n        if cache_images:\n            b, gb = 0, 1 << 30  # bytes of cached images, bytes per gigabytes\n            self.im_hw0, self.im_hw = [None] * n, [None] * n\n            fcn = self.cache_images_to_disk if cache_images == 'disk' else self.load_image\n            with ThreadPool(NUM_THREADS) as pool:\n                results = pool.imap(fcn, range(n))\n                pbar = tqdm(enumerate(results), total=n, bar_format=TQDM_BAR_FORMAT, disable=LOCAL_RANK > 0)\n                for i, x in pbar:\n                    if cache_images == 'disk':\n                        b += self.npy_files[i].stat().st_size\n                    else:  # 'ram'\n                        self.ims[i], self.im_hw0[i], self.im_hw[i] = x  # im, hw_orig, hw_resized = load_image(self, i)\n                        b += self.ims[i].nbytes\n                    pbar.desc = f'{prefix}Caching images ({b / gb:.1f}GB {cache_images})'\n                pbar.close()\n\n    def check_cache_ram(self, safety_margin=0.1, prefix=''):\n        \"\"\"Check image caching requirements vs available memory.\"\"\"\n        b, gb = 0, 1 << 30  # bytes of cached images, bytes per gigabytes\n        n = min(self.n, 30)  # extrapolate from 30 random images\n        for _ in range(n):\n            im = cv2.imread(random.choice(self.im_files))  # sample image\n            ratio = self.img_size / max(im.shape[0], im.shape[1])  # max(h, w)  # ratio\n            b += im.nbytes * ratio ** 2\n        mem_required = b * self.n / n  # GB required to cache dataset into RAM\n        mem = psutil.virtual_memory()\n        cache = mem_required * (1 + safety_margin) < mem.available  # to cache or not to cache, that is the question\n        if not cache:\n            LOGGER.info(f'{prefix}{mem_required / gb:.1f}GB RAM required, '\n                        f'{mem.available / gb:.1f}/{mem.total / gb:.1f}GB available, '\n                        f\"{'caching images ✅' if cache else 'not caching images ⚠️'}\")\n        return cache\n\n    def cache_labels(self, path=Path('./labels.cache'), prefix=''):\n        \"\"\"Cache labels and save as numpy file for next time.\"\"\"\n        # Cache dataset labels, check images and read shapes\n        if path.exists():\n            path.unlink()  # remove *.cache file if exists\n        x = {}  # dict\n        nm, nf, ne, nc, msgs = 0, 0, 0, 0, []  # number missing, found, empty, corrupt, messages\n        desc = f'{prefix}Scanning {path.parent / path.stem}...'\n        total = len(self.im_files)\n        with ThreadPool(NUM_THREADS) as pool:\n            results = pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix)))\n            pbar = tqdm(results, desc=desc, total=total, bar_format=TQDM_BAR_FORMAT)\n            for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:\n                nm += nm_f\n                nf += nf_f\n                ne += ne_f\n                nc += nc_f\n                if im_file:\n                    x[im_file] = [lb, shape, segments]\n                if msg:\n                    msgs.append(msg)\n                pbar.desc = f'{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt'\n            pbar.close()\n\n        if msgs:\n            LOGGER.info('\\n'.join(msgs))\n        if nf == 0:\n            LOGGER.warning(f'{prefix}WARNING ⚠️ No labels found in {path}. {HELP_URL}')\n        x['hash'] = get_hash(self.label_files + self.im_files)\n        x['results'] = nf, nm, ne, nc, len(self.im_files)\n        x['msgs'] = msgs  # warnings\n        x['version'] = self.cache_version  # cache version\n        if is_dir_writeable(path.parent):\n            np.save(str(path), x)  # save cache for next time\n            path.with_suffix('.cache.npy').rename(path)  # remove .npy suffix\n            LOGGER.info(f'{prefix}New cache created: {path}')\n        else:\n            LOGGER.warning(f'{prefix}WARNING ⚠️ Cache directory {path.parent} is not writeable')  # not writeable\n        return x\n\n    def __len__(self):\n        \"\"\"Returns the length of 'im_files' attribute.\"\"\"\n        return len(self.im_files)\n\n    def __getitem__(self, index):\n        \"\"\"Get a sample and its corresponding label, filename and shape from the dataset.\"\"\"\n        index = self.indices[index]  # linear, shuffled, or image_weights\n\n        hyp = self.hyp\n        mosaic = self.mosaic and random.random() < hyp['mosaic']\n        if mosaic:\n            # Load mosaic\n            img, labels = self.load_mosaic(index)\n            shapes = None\n\n            # MixUp augmentation\n            if random.random() < hyp['mixup']:\n                img, labels = mixup(img, labels, *self.load_mosaic(random.randint(0, self.n - 1)))\n\n        else:\n            # Load image\n            img, (h0, w0), (h, w) = self.load_image(index)\n\n            # Letterbox\n            shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size  # final letterboxed shape\n            img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)\n            shapes = (h0, w0), ((h / h0, w / w0), pad)  # for COCO mAP rescaling\n\n            labels = self.labels[index].copy()\n            if labels.size:  # normalized xywh to pixel xyxy format\n                labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])\n\n            if self.augment:\n                img, labels = random_perspective(img,\n                                                 labels,\n                                                 degrees=hyp['degrees'],\n                                                 translate=hyp['translate'],\n                                                 scale=hyp['scale'],\n                                                 shear=hyp['shear'],\n                                                 perspective=hyp['perspective'])\n\n        nl = len(labels)  # number of labels\n        if nl:\n            labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3)\n\n        if self.augment:\n            # Albumentations\n            img, labels = self.albumentations(img, labels)\n            nl = len(labels)  # update after albumentations\n\n            # HSV color-space\n            augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])\n\n            # Flip up-down\n            if random.random() < hyp['flipud']:\n                img = np.flipud(img)\n                if nl:\n                    labels[:, 2] = 1 - labels[:, 2]\n\n            # Flip left-right\n            if random.random() < hyp['fliplr']:\n                img = np.fliplr(img)\n                if nl:\n                    labels[:, 1] = 1 - labels[:, 1]\n\n            # Cutouts\n            # labels = cutout(img, labels, p=0.5)\n            # nl = len(labels)  # update after cutout\n\n        labels_out = torch.zeros((nl, 6))\n        if nl:\n            labels_out[:, 1:] = torch.from_numpy(labels)\n\n        # Convert\n        img = img.transpose((2, 0, 1))[::-1]  # HWC to CHW, BGR to RGB\n        img = np.ascontiguousarray(img)\n\n        return torch.from_numpy(img), labels_out, self.im_files[index], shapes\n\n    def load_image(self, i):\n        \"\"\"Loads 1 image from dataset index 'i', returns (im, original hw, resized hw).\"\"\"\n        im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i],\n        if im is None:  # not cached in RAM\n            if fn.exists():  # load npy\n                im = np.load(fn)\n            else:  # read image\n                im = cv2.imread(f)  # BGR\n                assert im is not None, f'Image Not Found {f}'\n            h0, w0 = im.shape[:2]  # orig hw\n            r = self.img_size / max(h0, w0)  # ratio\n            if r != 1:  # if sizes are not equal\n                interp = cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA\n                im = cv2.resize(im, (math.ceil(w0 * r), math.ceil(h0 * r)), interpolation=interp)\n            return im, (h0, w0), im.shape[:2]  # im, hw_original, hw_resized\n        return self.ims[i], self.im_hw0[i], self.im_hw[i]  # im, hw_original, hw_resized\n\n    def cache_images_to_disk(self, i):\n        \"\"\"Saves an image as an *.npy file for faster loading.\"\"\"\n        f = self.npy_files[i]\n        if not f.exists():\n            np.save(f.as_posix(), cv2.imread(self.im_files[i]))\n\n    def load_mosaic(self, index):\n        \"\"\"YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic.\"\"\"\n        labels4, segments4 = [], []\n        s = self.img_size\n        yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border)  # mosaic center x, y\n        indices = [index] + random.choices(self.indices, k=3)  # 3 additional image indices\n        random.shuffle(indices)\n        for i, index in enumerate(indices):\n            # Load image\n            img, _, (h, w) = self.load_image(index)\n\n            # Place img in img4\n            if i == 0:  # top left\n                img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n                x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc  # xmin, ymin, xmax, ymax (large image)\n                x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h  # xmin, ymin, xmax, ymax (small image)\n            elif i == 1:  # top right\n                x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc\n                x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h\n            elif i == 2:  # bottom left\n                x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)\n                x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)\n            elif i == 3:  # bottom right\n                x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)\n                x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)\n\n            img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]  # img4[ymin:ymax, xmin:xmax]\n            padw = x1a - x1b\n            padh = y1a - y1b\n\n            # Labels\n            labels, segments = self.labels[index].copy(), self.segments[index].copy()\n            if labels.size:\n                labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh)  # normalized xywh to pixel xyxy format\n                segments = [xyn2xy(x, w, h, padw, padh) for x in segments]\n            labels4.append(labels)\n            segments4.extend(segments)\n\n        # Concat/clip labels\n        labels4 = np.concatenate(labels4, 0)\n        for x in (labels4[:, 1:], *segments4):\n            np.clip(x, 0, 2 * s, out=x)  # clip when using random_perspective()\n        # img4, labels4 = replicate(img4, labels4)  # replicate\n\n        # Augment\n        img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste'])\n        img4, labels4 = random_perspective(img4,\n                                           labels4,\n                                           segments4,\n                                           degrees=self.hyp['degrees'],\n                                           translate=self.hyp['translate'],\n                                           scale=self.hyp['scale'],\n                                           shear=self.hyp['shear'],\n                                           perspective=self.hyp['perspective'],\n                                           border=self.mosaic_border)  # border to remove\n\n        return img4, labels4\n\n    def load_mosaic9(self, index):\n        \"\"\"YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic.\"\"\"\n        labels9, segments9 = [], []\n        s = self.img_size\n        indices = [index] + random.choices(self.indices, k=8)  # 8 additional image indices\n        random.shuffle(indices)\n        hp, wp = -1, -1  # height, width previous\n        for i, index in enumerate(indices):\n            # Load image\n            img, _, (h, w) = self.load_image(index)\n\n            # Place img in img9\n            if i == 0:  # center\n                img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n                h0, w0 = h, w\n                c = s, s, s + w, s + h  # xmin, ymin, xmax, ymax (base) coordinates\n            elif i == 1:  # top\n                c = s, s - h, s + w, s\n            elif i == 2:  # top right\n                c = s + wp, s - h, s + wp + w, s\n            elif i == 3:  # right\n                c = s + w0, s, s + w0 + w, s + h\n            elif i == 4:  # bottom right\n                c = s + w0, s + hp, s + w0 + w, s + hp + h\n            elif i == 5:  # bottom\n                c = s + w0 - w, s + h0, s + w0, s + h0 + h\n            elif i == 6:  # bottom left\n                c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h\n            elif i == 7:  # left\n                c = s - w, s + h0 - h, s, s + h0\n            elif i == 8:  # top left\n                c = s - w, s + h0 - hp - h, s, s + h0 - hp\n\n            padx, pady = c[:2]\n            x1, y1, x2, y2 = (max(x, 0) for x in c)  # allocate coords\n\n            # Labels\n            labels, segments = self.labels[index].copy(), self.segments[index].copy()\n            if labels.size:\n                labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady)  # normalized xywh to pixel xyxy format\n                segments = [xyn2xy(x, w, h, padx, pady) for x in segments]\n            labels9.append(labels)\n            segments9.extend(segments)\n\n            # Image\n            img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:]  # img9[ymin:ymax, xmin:xmax]\n            hp, wp = h, w  # height, width previous\n\n        # Offset\n        yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border)  # mosaic center x, y\n        img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]\n\n        # Concat/clip labels\n        labels9 = np.concatenate(labels9, 0)\n        labels9[:, [1, 3]] -= xc\n        labels9[:, [2, 4]] -= yc\n        c = np.array([xc, yc])  # centers\n        segments9 = [x - c for x in segments9]\n\n        for x in (labels9[:, 1:], *segments9):\n            np.clip(x, 0, 2 * s, out=x)  # clip when using random_perspective()\n        # img9, labels9 = replicate(img9, labels9)  # replicate\n\n        # Augment\n        img9, labels9, segments9 = copy_paste(img9, labels9, segments9, p=self.hyp['copy_paste'])\n        img9, labels9 = random_perspective(img9,\n                                           labels9,\n                                           segments9,\n                                           degrees=self.hyp['degrees'],\n                                           translate=self.hyp['translate'],\n                                           scale=self.hyp['scale'],\n                                           shear=self.hyp['shear'],\n                                           perspective=self.hyp['perspective'],\n                                           border=self.mosaic_border)  # border to remove\n\n        return img9, labels9\n\n    @staticmethod\n    def collate_fn(batch):\n        \"\"\"YOLOv8 collate function, outputs dict.\"\"\"\n        im, label, path, shapes = zip(*batch)  # transposed\n        for i, lb in enumerate(label):\n            lb[:, 0] = i  # add target image index for build_targets()\n        batch_idx, cls, bboxes = torch.cat(label, 0).split((1, 1, 4), dim=1)\n        return {\n            'ori_shape': tuple((x[0] if x else None) for x in shapes),\n            'ratio_pad': tuple((x[1] if x else None) for x in shapes),\n            'im_file': path,\n            'img': torch.stack(im, 0),\n            'cls': cls,\n            'bboxes': bboxes,\n            'batch_idx': batch_idx.view(-1)}\n\n    @staticmethod\n    def collate_fn_old(batch):\n        \"\"\"YOLOv5 original collate function.\"\"\"\n        im, label, path, shapes = zip(*batch)  # transposed\n        for i, lb in enumerate(label):\n            lb[:, 0] = i  # add target image index for build_targets()\n        return torch.stack(im, 0), torch.cat(label, 0), path, shapes\n\n\n# Ancillary functions --------------------------------------------------------------------------------------------------\ndef flatten_recursive(path=DATASETS_DIR / 'coco128'):\n    \"\"\"Flatten a recursive directory by bringing all files to top level.\"\"\"\n    new_path = Path(f'{str(path)}_flat')\n    if os.path.exists(new_path):\n        shutil.rmtree(new_path)  # delete output folder\n    os.makedirs(new_path)  # make new output folder\n    for file in tqdm(glob.glob(f'{str(Path(path))}/**/*.*', recursive=True)):\n        shutil.copyfile(file, new_path / Path(file).name)\n\n\ndef extract_boxes(path=DATASETS_DIR / 'coco128'):  # from utils.dataloaders import *; extract_boxes()\n    # Convert detection dataset into classification dataset, with one directory per class\n    path = Path(path)  # images dir\n    shutil.rmtree(path / 'classification') if (path / 'classification').is_dir() else None  # remove existing\n    files = list(path.rglob('*.*'))\n    n = len(files)  # number of files\n    for im_file in tqdm(files, total=n):\n        if im_file.suffix[1:] in IMG_FORMATS:\n            # Image\n            im = cv2.imread(str(im_file))[..., ::-1]  # BGR to RGB\n            h, w = im.shape[:2]\n\n            # Labels\n            lb_file = Path(img2label_paths([str(im_file)])[0])\n            if Path(lb_file).exists():\n                with open(lb_file) as f:\n                    lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)  # labels\n\n                for j, x in enumerate(lb):\n                    c = int(x[0])  # class\n                    f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg'  # new filename\n                    if not f.parent.is_dir():\n                        f.parent.mkdir(parents=True)\n\n                    b = x[1:] * [w, h, w, h]  # box\n                    # B[2:] = b[2:].max()  # rectangle to square\n                    b[2:] = b[2:] * 1.2 + 3  # pad\n                    b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(int)\n\n                    b[[0, 2]] = np.clip(b[[0, 2]], 0, w)  # clip boxes outside of image\n                    b[[1, 3]] = np.clip(b[[1, 3]], 0, h)\n                    assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'\n\n\ndef autosplit(path=DATASETS_DIR / 'coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):\n    \"\"\"Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files\n    Usage: from utils.dataloaders import *; autosplit()\n    Arguments\n        path:            Path to images directory\n        weights:         Train, val, test weights (list, tuple)\n        annotated_only:  Only use images with an annotated txt file\n    \"\"\"\n    path = Path(path)  # images dir\n    files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS)  # image files only\n    n = len(files)  # number of files\n    random.seed(0)  # for reproducibility\n    indices = random.choices([0, 1, 2], weights=weights, k=n)  # assign each image to a split\n\n    txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt']  # 3 txt files\n    for x in txt:\n        if (path.parent / x).exists():\n            (path.parent / x).unlink()  # remove existing\n\n    print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)\n    for i, img in tqdm(zip(indices, files), total=n):\n        if not annotated_only or Path(img2label_paths([str(img)])[0]).exists():  # check label\n            with open(path.parent / txt[i], 'a') as f:\n                f.write(f'./{img.relative_to(path.parent).as_posix()}' + '\\n')  # add image to txt file\n\n\ndef verify_image_label(args):\n    \"\"\"Verify one image-label pair.\"\"\"\n    im_file, lb_file, prefix = args\n    nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', []  # number (missing, found, empty, corrupt), message, segments\n    try:\n        # Verify images\n        im = Image.open(im_file)\n        im.verify()  # PIL verify\n        shape = exif_size(im)  # image size\n        assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'\n        assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'\n        if im.format.lower() in ('jpg', 'jpeg'):\n            with open(im_file, 'rb') as f:\n                f.seek(-2, 2)\n                if f.read() != b'\\xff\\xd9':  # corrupt JPEG\n                    ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)\n                    msg = f'{prefix}WARNING ⚠️ {im_file}: corrupt JPEG restored and saved'\n\n        # Verify labels\n        if os.path.isfile(lb_file):\n            nf = 1  # label found\n            with open(lb_file) as f:\n                lb = [x.split() for x in f.read().strip().splitlines() if len(x)]\n                if any(len(x) > 6 for x in lb):  # is segment\n                    classes = np.array([x[0] for x in lb], dtype=np.float32)\n                    segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb]  # (cls, xy1...)\n                    lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1)  # (cls, xywh)\n                lb = np.array(lb, dtype=np.float32)\n            nl = len(lb)\n            if nl:\n                assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected'\n                assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}'\n                assert (lb[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}'\n                _, i = np.unique(lb, axis=0, return_index=True)\n                if len(i) < nl:  # duplicate row check\n                    lb = lb[i]  # remove duplicates\n                    if segments:\n                        segments = [segments[x] for x in i]\n                    msg = f'{prefix}WARNING ⚠️ {im_file}: {nl - len(i)} duplicate labels removed'\n            else:\n                ne = 1  # label empty\n                lb = np.zeros((0, 5), dtype=np.float32)\n        else:\n            nm = 1  # label missing\n            lb = np.zeros((0, 5), dtype=np.float32)\n        return im_file, lb, shape, segments, nm, nf, ne, nc, msg\n    except Exception as e:\n        nc = 1\n        msg = f'{prefix}WARNING ⚠️ {im_file}: ignoring corrupt image/label: {e}'\n        return [None, None, None, None, nm, nf, ne, nc, msg]\n\n\n# Classification dataloaders -------------------------------------------------------------------------------------------\nclass ClassificationDataset(torchvision.datasets.ImageFolder):\n    \"\"\"\n    YOLOv5 Classification Dataset.\n    Arguments\n        root:  Dataset path\n        transform:  torchvision transforms, used by default\n        album_transform: Albumentations transforms, used if installed\n    \"\"\"\n\n    def __init__(self, root, augment, imgsz, cache=False):\n        \"\"\"Initialize YOLO dataset with root, augmentation, image size, and cache parameters.\"\"\"\n        super().__init__(root=root)\n        self.torch_transforms = classify_transforms(imgsz)\n        self.album_transforms = classify_albumentations(augment, imgsz) if augment else None\n        self.cache_ram = cache is True or cache == 'ram'\n        self.cache_disk = cache == 'disk'\n        self.samples = [list(x) + [Path(x[0]).with_suffix('.npy'), None] for x in self.samples]  # file, index, npy, im\n\n    def __getitem__(self, i):\n        \"\"\"Retrieves data items of 'dataset' via indices & creates InfiniteDataLoader.\"\"\"\n        f, j, fn, im = self.samples[i]  # filename, index, filename.with_suffix('.npy'), image\n        if self.cache_ram and im is None:\n            im = self.samples[i][3] = cv2.imread(f)\n        elif self.cache_disk:\n            if not fn.exists():  # load npy\n                np.save(fn.as_posix(), cv2.imread(f))\n            im = np.load(fn)\n        else:  # read image\n            im = cv2.imread(f)  # BGR\n        if self.album_transforms:\n            sample = self.album_transforms(image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB))['image']\n        else:\n            sample = self.torch_transforms(im)\n        return sample, j\n\n\ndef create_classification_dataloader(path,\n                                     imgsz=224,\n                                     batch_size=16,\n                                     augment=True,\n                                     cache=False,\n                                     rank=-1,\n                                     workers=8,\n                                     shuffle=True):\n    \"\"\"Returns Dataloader object to be used with YOLOv5 Classifier.\"\"\"\n    with torch_distributed_zero_first(rank):  # init dataset *.cache only once if DDP\n        dataset = ClassificationDataset(root=path, imgsz=imgsz, augment=augment, cache=cache)\n    batch_size = min(batch_size, len(dataset))\n    nd = torch.cuda.device_count()\n    nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers])\n    sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)\n    generator = torch.Generator()\n    generator.manual_seed(6148914691236517205 + RANK)\n    return InfiniteDataLoader(dataset,\n                              batch_size=batch_size,\n                              shuffle=shuffle and sampler is None,\n                              num_workers=nw,\n                              sampler=sampler,\n                              pin_memory=PIN_MEMORY,\n                              worker_init_fn=seed_worker,\n                              generator=generator)  # or DataLoader(persistent_workers=True)\n"
  },
  {
    "path": "ultralytics/yolo/data/dataset.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport torch\nimport torchvision\nfrom tqdm import tqdm\n\nfrom ..utils import LOCAL_RANK, NUM_THREADS, TQDM_BAR_FORMAT, is_dir_writeable\nfrom .augment import Compose, Format, Instances, LetterBox, classify_albumentations, classify_transforms, v8_transforms\nfrom .base import BaseDataset\nfrom .utils import HELP_URL, LOGGER, get_hash, img2label_paths, verify_image_label\n\n\nclass YOLODataset(BaseDataset):\n    \"\"\"\n    Dataset class for loading object detection and/or segmentation labels in YOLO format.\n\n    Args:\n        data (dict, optional): A dataset YAML dictionary. Defaults to None.\n        use_segments (bool, optional): If True, segmentation masks are used as labels. Defaults to False.\n        use_keypoints (bool, optional): If True, keypoints are used as labels. Defaults to False.\n\n    Returns:\n        (torch.utils.data.Dataset): A PyTorch dataset object that can be used for training an object detection model.\n    \"\"\"\n    cache_version = '1.0.2'  # dataset labels *.cache version, >= 1.0.0 for YOLOv8\n    rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]\n\n    def __init__(self, *args, data=None, use_segments=False, use_keypoints=False, **kwargs):\n        self.use_segments = use_segments\n        self.use_keypoints = use_keypoints\n        self.data = data\n        assert not (self.use_segments and self.use_keypoints), 'Can not use both segments and keypoints.'\n        super().__init__(*args, **kwargs)\n\n    def cache_labels(self, path=Path('./labels.cache')):\n        \"\"\"Cache dataset labels, check images and read shapes.\n        Args:\n            path (Path): path where to save the cache file (default: Path('./labels.cache')).\n        Returns:\n            (dict): labels.\n        \"\"\"\n        x = {'labels': []}\n        nm, nf, ne, nc, msgs = 0, 0, 0, 0, []  # number missing, found, empty, corrupt, messages\n        desc = f'{self.prefix}Scanning {path.parent / path.stem}...'\n        total = len(self.im_files)\n        nkpt, ndim = self.data.get('kpt_shape', (0, 0))\n        if self.use_keypoints and (nkpt <= 0 or ndim not in (2, 3)):\n            raise ValueError(\"'kpt_shape' in data.yaml missing or incorrect. Should be a list with [number of \"\n                             \"keypoints, number of dims (2 for x,y or 3 for x,y,visible)], i.e. 'kpt_shape: [17, 3]'\")\n        with ThreadPool(NUM_THREADS) as pool:\n            results = pool.imap(func=verify_image_label,\n                                iterable=zip(self.im_files, self.label_files, repeat(self.prefix),\n                                             repeat(self.use_keypoints), repeat(len(self.data['names'])), repeat(nkpt),\n                                             repeat(ndim)))\n            pbar = tqdm(results, desc=desc, total=total, bar_format=TQDM_BAR_FORMAT)\n            for im_file, lb, shape, segments, keypoint, nm_f, nf_f, ne_f, nc_f, msg in pbar:\n                nm += nm_f\n                nf += nf_f\n                ne += ne_f\n                nc += nc_f\n                if im_file:\n                    x['labels'].append(\n                        dict(\n                            im_file=im_file,\n                            shape=shape,\n                            cls=lb[:, 0:1],  # n, 1\n                            bboxes=lb[:, 1:],  # n, 4\n                            segments=segments,\n                            keypoints=keypoint,\n                            normalized=True,\n                            bbox_format='xywh'))\n                if msg:\n                    msgs.append(msg)\n                pbar.desc = f'{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt'\n            pbar.close()\n\n        if msgs:\n            LOGGER.info('\\n'.join(msgs))\n        if nf == 0:\n            LOGGER.warning(f'{self.prefix}WARNING ⚠️ No labels found in {path}. {HELP_URL}')\n        x['hash'] = get_hash(self.label_files + self.im_files)\n        x['results'] = nf, nm, ne, nc, len(self.im_files)\n        x['msgs'] = msgs  # warnings\n        x['version'] = self.cache_version  # cache version\n        if is_dir_writeable(path.parent):\n            if path.exists():\n                path.unlink()  # remove *.cache file if exists\n            np.save(str(path), x)  # save cache for next time\n            path.with_suffix('.cache.npy').rename(path)  # remove .npy suffix\n            LOGGER.info(f'{self.prefix}New cache created: {path}')\n        else:\n            LOGGER.warning(f'{self.prefix}WARNING ⚠️ Cache directory {path.parent} is not writeable, cache not saved.')\n        return x\n\n    def get_labels(self):\n        \"\"\"Returns dictionary of labels for YOLO training.\"\"\"\n        self.label_files = img2label_paths(self.im_files)\n        cache_path = Path(self.label_files[0]).parent.with_suffix('.cache')\n        try:\n            import gc\n            gc.disable()  # reduce pickle load time https://github.com/ultralytics/ultralytics/pull/1585\n            cache, exists = np.load(str(cache_path), allow_pickle=True).item(), True  # load dict\n            gc.enable()\n            assert cache['version'] == self.cache_version  # matches current version\n            assert cache['hash'] == get_hash(self.label_files + self.im_files)  # identical hash\n        except (FileNotFoundError, AssertionError, AttributeError):\n            cache, exists = self.cache_labels(cache_path), False  # run cache ops\n\n        # Display cache\n        nf, nm, ne, nc, n = cache.pop('results')  # found, missing, empty, corrupt, total\n        if exists and LOCAL_RANK in (-1, 0):\n            d = f'Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt'\n            tqdm(None, desc=self.prefix + d, total=n, initial=n, bar_format=TQDM_BAR_FORMAT)  # display cache results\n            if cache['msgs']:\n                LOGGER.info('\\n'.join(cache['msgs']))  # display warnings\n        if nf == 0:  # number of labels found\n            raise FileNotFoundError(f'{self.prefix}No labels found in {cache_path}, can not start training. {HELP_URL}')\n\n        # Read cache\n        [cache.pop(k) for k in ('hash', 'version', 'msgs')]  # remove items\n        labels = cache['labels']\n        self.im_files = [lb['im_file'] for lb in labels]  # update im_files\n\n        # Check if the dataset is all boxes or all segments\n        lengths = ((len(lb['cls']), len(lb['bboxes']), len(lb['segments'])) for lb in labels)\n        len_cls, len_boxes, len_segments = (sum(x) for x in zip(*lengths))\n        if len_segments and len_boxes != len_segments:\n            LOGGER.warning(\n                f'WARNING ⚠️ Box and segment counts should be equal, but got len(segments) = {len_segments}, '\n                f'len(boxes) = {len_boxes}. To resolve this only boxes will be used and all segments will be removed. '\n                'To avoid this please supply either a detect or segment dataset, not a detect-segment mixed dataset.')\n            for lb in labels:\n                lb['segments'] = []\n        if len_cls == 0:\n            raise ValueError(f'All labels empty in {cache_path}, can not start training without labels. {HELP_URL}')\n        return labels\n\n    # TODO: use hyp config to set all these augmentations\n    def build_transforms(self, hyp=None):\n        \"\"\"Builds and appends transforms to the list.\"\"\"\n        if self.augment:\n            hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0\n            hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0\n            transforms = v8_transforms(self, self.imgsz, hyp)\n        else:\n            transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), scaleup=False)])\n        transforms.append(\n            Format(bbox_format='xywh',\n                   normalize=True,\n                   return_mask=self.use_segments,\n                   return_keypoint=self.use_keypoints,\n                   batch_idx=True,\n                   mask_ratio=hyp.mask_ratio,\n                   mask_overlap=hyp.overlap_mask))\n        return transforms\n\n    def close_mosaic(self, hyp):\n        \"\"\"Sets mosaic, copy_paste and mixup options to 0.0 and builds transformations.\"\"\"\n        hyp.mosaic = 0.0  # set mosaic ratio=0.0\n        hyp.copy_paste = 0.0  # keep the same behavior as previous v8 close-mosaic\n        hyp.mixup = 0.0  # keep the same behavior as previous v8 close-mosaic\n        self.transforms = self.build_transforms(hyp)\n\n    def update_labels_info(self, label):\n        \"\"\"custom your label format here.\"\"\"\n        # NOTE: cls is not with bboxes now, classification and semantic segmentation need an independent cls label\n        # we can make it also support classification and semantic segmentation by add or remove some dict keys there.\n        bboxes = label.pop('bboxes')\n        segments = label.pop('segments')\n        keypoints = label.pop('keypoints', None)\n        bbox_format = label.pop('bbox_format')\n        normalized = label.pop('normalized')\n        label['instances'] = Instances(bboxes, segments, keypoints, bbox_format=bbox_format, normalized=normalized)\n        return label\n\n    @staticmethod\n    def collate_fn(batch):\n        \"\"\"Collates data samples into batches.\"\"\"\n        new_batch = {}\n        keys = batch[0].keys()\n        values = list(zip(*[list(b.values()) for b in batch]))\n        for i, k in enumerate(keys):\n            value = values[i]\n            if k == 'img':\n                value = torch.stack(value, 0)\n            if k in ['masks', 'keypoints', 'bboxes', 'cls']:\n                value = torch.cat(value, 0)\n            new_batch[k] = value\n        new_batch['batch_idx'] = list(new_batch['batch_idx'])\n        for i in range(len(new_batch['batch_idx'])):\n            new_batch['batch_idx'][i] += i  # add target image index for build_targets()\n        new_batch['batch_idx'] = torch.cat(new_batch['batch_idx'], 0)\n        return new_batch\n\n\n# Classification dataloaders -------------------------------------------------------------------------------------------\nclass ClassificationDataset(torchvision.datasets.ImageFolder):\n    \"\"\"\n    YOLO Classification Dataset.\n\n    Args:\n        root (str): Dataset path.\n\n    Attributes:\n        cache_ram (bool): True if images should be cached in RAM, False otherwise.\n        cache_disk (bool): True if images should be cached on disk, False otherwise.\n        samples (list): List of samples containing file, index, npy, and im.\n        torch_transforms (callable): torchvision transforms applied to the dataset.\n        album_transforms (callable, optional): Albumentations transforms applied to the dataset if augment is True.\n    \"\"\"\n\n    def __init__(self, root, args, augment=False, cache=False):\n        \"\"\"\n        Initialize YOLO object with root, image size, augmentations, and cache settings.\n\n        Args:\n            root (str): Dataset path.\n            args (Namespace): Argument parser containing dataset related settings.\n            augment (bool, optional): True if dataset should be augmented, False otherwise. Defaults to False.\n            cache (bool | str | optional): Cache setting, can be True, False, 'ram' or 'disk'. Defaults to False.\n        \"\"\"\n        super().__init__(root=root)\n        if augment and args.fraction < 1.0:  # reduce training fraction\n            self.samples = self.samples[:round(len(self.samples) * args.fraction)]\n        self.cache_ram = cache is True or cache == 'ram'\n        self.cache_disk = cache == 'disk'\n        self.samples = [list(x) + [Path(x[0]).with_suffix('.npy'), None] for x in self.samples]  # file, index, npy, im\n        self.torch_transforms = classify_transforms(args.imgsz)\n        self.album_transforms = classify_albumentations(\n            augment=augment,\n            size=args.imgsz,\n            scale=(1.0 - args.scale, 1.0),  # (0.08, 1.0)\n            hflip=args.fliplr,\n            vflip=args.flipud,\n            hsv_h=args.hsv_h,  # HSV-Hue augmentation (fraction)\n            hsv_s=args.hsv_s,  # HSV-Saturation augmentation (fraction)\n            hsv_v=args.hsv_v,  # HSV-Value augmentation (fraction)\n            mean=(0.0, 0.0, 0.0),  # IMAGENET_MEAN\n            std=(1.0, 1.0, 1.0),  # IMAGENET_STD\n            auto_aug=False) if augment else None\n\n    def __getitem__(self, i):\n        \"\"\"Returns subset of data and targets corresponding to given indices.\"\"\"\n        f, j, fn, im = self.samples[i]  # filename, index, filename.with_suffix('.npy'), image\n        if self.cache_ram and im is None:\n            im = self.samples[i][3] = cv2.imread(f)\n        elif self.cache_disk:\n            if not fn.exists():  # load npy\n                np.save(fn.as_posix(), cv2.imread(f))\n            im = np.load(fn)\n        else:  # read image\n            im = cv2.imread(f)  # BGR\n        if self.album_transforms:\n            sample = self.album_transforms(image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB))['image']\n        else:\n            sample = self.torch_transforms(im)\n        return {'img': sample, 'cls': j}\n\n    def __len__(self) -> int:\n        return len(self.samples)\n\n\n# TODO: support semantic segmentation\nclass SemanticDataset(BaseDataset):\n\n    def __init__(self):\n        \"\"\"Initialize a SemanticDataset object.\"\"\"\n        super().__init__()\n"
  },
  {
    "path": "ultralytics/yolo/data/dataset_wrappers.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport collections\nfrom copy import deepcopy\n\nfrom .augment import LetterBox\n\n\nclass MixAndRectDataset:\n    \"\"\"\n    A dataset class that applies mosaic and mixup transformations as well as rectangular training.\n\n    Attributes:\n        dataset: The base dataset.\n        imgsz: The size of the images in the dataset.\n    \"\"\"\n\n    def __init__(self, dataset):\n        \"\"\"\n        Args:\n            dataset (BaseDataset): The base dataset to apply transformations to.\n        \"\"\"\n        self.dataset = dataset\n        self.imgsz = dataset.imgsz\n\n    def __len__(self):\n        \"\"\"Returns the number of items in the dataset.\"\"\"\n        return len(self.dataset)\n\n    def __getitem__(self, index):\n        \"\"\"\n        Applies mosaic, mixup and rectangular training transformations to an item in the dataset.\n\n        Args:\n            index (int): Index of the item in the dataset.\n\n        Returns:\n            (dict): A dictionary containing the transformed item data.\n        \"\"\"\n        labels = deepcopy(self.dataset[index])\n        for transform in self.dataset.transforms.tolist():\n            # Mosaic and mixup\n            if hasattr(transform, 'get_indexes'):\n                indexes = transform.get_indexes(self.dataset)\n                if not isinstance(indexes, collections.abc.Sequence):\n                    indexes = [indexes]\n                labels['mix_labels'] = [deepcopy(self.dataset[index]) for index in indexes]\n            if self.dataset.rect and isinstance(transform, LetterBox):\n                transform.new_shape = self.dataset.batch_shapes[self.dataset.batch[index]]\n            labels = transform(labels)\n            if 'mix_labels' in labels:\n                labels.pop('mix_labels')\n        return labels\n"
  },
  {
    "path": "ultralytics/yolo/data/scripts/download_weights.sh",
    "content": "#!/bin/bash\n# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Download latest models from https://github.com/ultralytics/assets/releases\n# Example usage: bash ultralytics/yolo/data/scripts/download_weights.sh\n# parent\n# └── weights\n#     ├── yolov8n.pt  ← downloads here\n#     ├── yolov8s.pt\n#     └── ...\n\npython - <<EOF\nfrom ultralytics.yolo.utils.downloads import attempt_download_asset\n\nassets = [f'yolov8{size}{suffix}.pt' for size in 'nsmlx' for suffix in ('', '-cls', '-seg')]\nfor x in assets:\n    attempt_download_asset(f'weights/{x}')\n\nEOF\n"
  },
  {
    "path": "ultralytics/yolo/data/scripts/get_coco.sh",
    "content": "#!/bin/bash\n# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Download COCO 2017 dataset http://cocodataset.org\n# Example usage: bash data/scripts/get_coco.sh\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco  ← downloads here\n\n# Arguments (optional) Usage: bash data/scripts/get_coco.sh --train --val --test --segments\nif [ \"$#\" -gt 0 ]; then\n  for opt in \"$@\"; do\n    case \"${opt}\" in\n    --train) train=true ;;\n    --val) val=true ;;\n    --test) test=true ;;\n    --segments) segments=true ;;\n    --sama) sama=true ;;\n    esac\n  done\nelse\n  train=true\n  val=true\n  test=false\n  segments=false\n  sama=false\nfi\n\n# Download/unzip labels\nd='../datasets' # unzip directory\nurl=https://github.com/ultralytics/yolov5/releases/download/v1.0/\nif [ \"$segments\" == \"true\" ]; then\n  f='coco2017labels-segments.zip' # 169 MB\nelif [ \"$sama\" == \"true\" ]; then\n  f='coco2017labels-segments-sama.zip' # 199 MB https://www.sama.com/sama-coco-dataset/\nelse\n  f='coco2017labels.zip' # 46 MB\nfi\necho 'Downloading' $url$f ' ...'\ncurl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &\n\n# Download/unzip images\nd='../datasets/coco/images' # unzip directory\nurl=http://images.cocodataset.org/zips/\nif [ \"$train\" == \"true\" ]; then\n  f='train2017.zip' # 19G, 118k images\n  echo 'Downloading' $url$f '...'\n  curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &\nfi\nif [ \"$val\" == \"true\" ]; then\n  f='val2017.zip' # 1G, 5k images\n  echo 'Downloading' $url$f '...'\n  curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &\nfi\nif [ \"$test\" == \"true\" ]; then\n  f='test2017.zip' # 7G, 41k images (optional)\n  echo 'Downloading' $url$f '...'\n  curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &\nfi\nwait # finish background tasks\n"
  },
  {
    "path": "ultralytics/yolo/data/scripts/get_coco128.sh",
    "content": "#!/bin/bash\n# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Download COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017)\n# Example usage: bash data/scripts/get_coco128.sh\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco128  ← downloads here\n\n# Download/unzip images and labels\nd='../datasets' # unzip directory\nurl=https://github.com/ultralytics/yolov5/releases/download/v1.0/\nf='coco128.zip' # or 'coco128-segments.zip', 68 MB\necho 'Downloading' $url$f ' ...'\ncurl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &\n\nwait # finish background tasks\n"
  },
  {
    "path": "ultralytics/yolo/data/scripts/get_imagenet.sh",
    "content": "#!/bin/bash\n# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Download ILSVRC2012 ImageNet dataset https://image-net.org\n# Example usage: bash data/scripts/get_imagenet.sh\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── imagenet  ← downloads here\n\n# Arguments (optional) Usage: bash data/scripts/get_imagenet.sh --train --val\nif [ \"$#\" -gt 0 ]; then\n  for opt in \"$@\"; do\n    case \"${opt}\" in\n    --train) train=true ;;\n    --val) val=true ;;\n    esac\n  done\nelse\n  train=true\n  val=true\nfi\n\n# Make dir\nd='../datasets/imagenet' # unzip directory\nmkdir -p $d && cd $d\n\n# Download/unzip train\nif [ \"$train\" == \"true\" ]; then\n  wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_train.tar # download 138G, 1281167 images\n  mkdir train && mv ILSVRC2012_img_train.tar train/ && cd train\n  tar -xf ILSVRC2012_img_train.tar && rm -f ILSVRC2012_img_train.tar\n  find . -name \"*.tar\" | while read NAME; do\n    mkdir -p \"${NAME%.tar}\"\n    tar -xf \"${NAME}\" -C \"${NAME%.tar}\"\n    rm -f \"${NAME}\"\n  done\n  cd ..\nfi\n\n# Download/unzip val\nif [ \"$val\" == \"true\" ]; then\n  wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_val.tar # download 6.3G, 50000 images\n  mkdir val && mv ILSVRC2012_img_val.tar val/ && cd val && tar -xf ILSVRC2012_img_val.tar\n  wget -qO- https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh | bash # move into subdirs\nfi\n\n# Delete corrupted image (optional: PNG under JPEG name that may cause dataloaders to fail)\n# rm train/n04266014/n04266014_10835.JPEG\n\n# TFRecords (optional)\n# wget https://raw.githubusercontent.com/tensorflow/models/master/research/slim/datasets/imagenet_lsvrc_2015_synsets.txt\n"
  },
  {
    "path": "ultralytics/yolo/data/utils.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport hashlib\nimport json\nimport os\nimport subprocess\nimport time\nimport zipfile\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom tarfile import is_tarfile\n\nimport cv2\nimport numpy as np\nfrom PIL import ExifTags, Image, ImageOps\nfrom tqdm import tqdm\n\nfrom ultralytics.nn.autobackend import check_class_names\nfrom ultralytics.yolo.utils import (DATASETS_DIR, LOGGER, NUM_THREADS, ROOT, SETTINGS_YAML, clean_url, colorstr, emojis,\n                                    yaml_load)\nfrom ultralytics.yolo.utils.checks import check_file, check_font, is_ascii\nfrom ultralytics.yolo.utils.downloads import download, safe_download, unzip_file\nfrom ultralytics.yolo.utils.ops import segments2boxes\n\nHELP_URL = 'See https://docs.ultralytics.com/yolov5/tutorials/train_custom_data'\nIMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp', 'pfm'  # image suffixes\nVID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv', 'webm'  # video suffixes\nPIN_MEMORY = str(os.getenv('PIN_MEMORY', True)).lower() == 'true'  # global pin_memory for dataloaders\nIMAGENET_MEAN = 0.485, 0.456, 0.406  # RGB mean\nIMAGENET_STD = 0.229, 0.224, 0.225  # RGB standard deviation\n\n# Get orientation exif tag\nfor orientation in ExifTags.TAGS.keys():\n    if ExifTags.TAGS[orientation] == 'Orientation':\n        break\n\n\ndef img2label_paths(img_paths):\n    \"\"\"Define label paths as a function of image paths.\"\"\"\n    sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}'  # /images/, /labels/ substrings\n    return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]\n\n\ndef get_hash(paths):\n    \"\"\"Returns a single hash value of a list of paths (files or dirs).\"\"\"\n    size = sum(os.path.getsize(p) for p in paths if os.path.exists(p))  # sizes\n    h = hashlib.sha256(str(size).encode())  # hash sizes\n    h.update(''.join(paths).encode())  # hash paths\n    return h.hexdigest()  # return hash\n\n\ndef exif_size(img):\n    \"\"\"Returns exif-corrected PIL size.\"\"\"\n    s = img.size  # (width, height)\n    with contextlib.suppress(Exception):\n        rotation = dict(img._getexif().items())[orientation]\n        if rotation in [6, 8]:  # rotation 270 or 90\n            s = (s[1], s[0])\n    return s\n\n\ndef verify_image_label(args):\n    \"\"\"Verify one image-label pair.\"\"\"\n    im_file, lb_file, prefix, keypoint, num_cls, nkpt, ndim = args\n    # Number (missing, found, empty, corrupt), message, segments, keypoints\n    nm, nf, ne, nc, msg, segments, keypoints = 0, 0, 0, 0, '', [], None\n    try:\n        # Verify images\n        im = Image.open(im_file)\n        im.verify()  # PIL verify\n        shape = exif_size(im)  # image size\n        shape = (shape[1], shape[0])  # hw\n        assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'\n        assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'\n        if im.format.lower() in ('jpg', 'jpeg'):\n            with open(im_file, 'rb') as f:\n                f.seek(-2, 2)\n                if f.read() != b'\\xff\\xd9':  # corrupt JPEG\n                    ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)\n                    msg = f'{prefix}WARNING ⚠️ {im_file}: corrupt JPEG restored and saved'\n\n        # Verify labels\n        if os.path.isfile(lb_file):\n            nf = 1  # label found\n            with open(lb_file) as f:\n                lb = [x.split() for x in f.read().strip().splitlines() if len(x)]\n                if any(len(x) > 6 for x in lb) and (not keypoint):  # is segment\n                    classes = np.array([x[0] for x in lb], dtype=np.float32)\n                    segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb]  # (cls, xy1...)\n                    lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1)  # (cls, xywh)\n                lb = np.array(lb, dtype=np.float32)\n            nl = len(lb)\n            if nl:\n                if keypoint:\n                    assert lb.shape[1] == (5 + nkpt * ndim), f'labels require {(5 + nkpt * ndim)} columns each'\n                    assert (lb[:, 5::ndim] <= 1).all(), 'non-normalized or out of bounds coordinate labels'\n                    assert (lb[:, 6::ndim] <= 1).all(), 'non-normalized or out of bounds coordinate labels'\n                else:\n                    assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected'\n                    assert (lb[:, 1:] <= 1).all(), \\\n                        f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}'\n                    assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}'\n                # All labels\n                max_cls = int(lb[:, 0].max())  # max label count\n                assert max_cls <= num_cls, \\\n                    f'Label class {max_cls} exceeds dataset class count {num_cls}. ' \\\n                    f'Possible class labels are 0-{num_cls - 1}'\n                _, i = np.unique(lb, axis=0, return_index=True)\n                if len(i) < nl:  # duplicate row check\n                    lb = lb[i]  # remove duplicates\n                    if segments:\n                        segments = [segments[x] for x in i]\n                    msg = f'{prefix}WARNING ⚠️ {im_file}: {nl - len(i)} duplicate labels removed'\n            else:\n                ne = 1  # label empty\n                lb = np.zeros((0, (5 + nkpt * ndim)), dtype=np.float32) if keypoint else np.zeros(\n                    (0, 5), dtype=np.float32)\n        else:\n            nm = 1  # label missing\n            lb = np.zeros((0, (5 + nkpt * ndim)), dtype=np.float32) if keypoint else np.zeros((0, 5), dtype=np.float32)\n        if keypoint:\n            keypoints = lb[:, 5:].reshape(-1, nkpt, ndim)\n            if ndim == 2:\n                kpt_mask = np.ones(keypoints.shape[:2], dtype=np.float32)\n                kpt_mask = np.where(keypoints[..., 0] < 0, 0.0, kpt_mask)\n                kpt_mask = np.where(keypoints[..., 1] < 0, 0.0, kpt_mask)\n                keypoints = np.concatenate([keypoints, kpt_mask[..., None]], axis=-1)  # (nl, nkpt, 3)\n        lb = lb[:, :5]\n        return im_file, lb, shape, segments, keypoints, nm, nf, ne, nc, msg\n    except Exception as e:\n        nc = 1\n        msg = f'{prefix}WARNING ⚠️ {im_file}: ignoring corrupt image/label: {e}'\n        return [None, None, None, None, None, nm, nf, ne, nc, msg]\n\n\ndef polygon2mask(imgsz, polygons, color=1, downsample_ratio=1):\n    \"\"\"\n    Args:\n        imgsz (tuple): The image size.\n        polygons (list[np.ndarray]): [N, M], N is the number of polygons, M is the number of points(Be divided by 2).\n        color (int): color\n        downsample_ratio (int): downsample ratio\n    \"\"\"\n    mask = np.zeros(imgsz, dtype=np.uint8)\n    polygons = np.asarray(polygons)\n    polygons = polygons.astype(np.int32)\n    shape = polygons.shape\n    polygons = polygons.reshape(shape[0], -1, 2)\n    cv2.fillPoly(mask, polygons, color=color)\n    nh, nw = (imgsz[0] // downsample_ratio, imgsz[1] // downsample_ratio)\n    # NOTE: fillPoly firstly then resize is trying the keep the same way\n    # of loss calculation when mask-ratio=1.\n    mask = cv2.resize(mask, (nw, nh))\n    return mask\n\n\ndef polygons2masks(imgsz, polygons, color, downsample_ratio=1):\n    \"\"\"\n    Args:\n        imgsz (tuple): The image size.\n        polygons (list[np.ndarray]): each polygon is [N, M], N is number of polygons, M is number of points (M % 2 = 0)\n        color (int): color\n        downsample_ratio (int): downsample ratio\n    \"\"\"\n    masks = []\n    for si in range(len(polygons)):\n        mask = polygon2mask(imgsz, [polygons[si].reshape(-1)], color, downsample_ratio)\n        masks.append(mask)\n    return np.array(masks)\n\n\ndef polygons2masks_overlap(imgsz, segments, downsample_ratio=1):\n    \"\"\"Return a (640, 640) overlap mask.\"\"\"\n    masks = np.zeros((imgsz[0] // downsample_ratio, imgsz[1] // downsample_ratio),\n                     dtype=np.int32 if len(segments) > 255 else np.uint8)\n    areas = []\n    ms = []\n    for si in range(len(segments)):\n        mask = polygon2mask(imgsz, [segments[si].reshape(-1)], downsample_ratio=downsample_ratio, color=1)\n        ms.append(mask)\n        areas.append(mask.sum())\n    areas = np.asarray(areas)\n    index = np.argsort(-areas)\n    ms = np.array(ms)[index]\n    for i in range(len(segments)):\n        mask = ms[i] * (i + 1)\n        masks = masks + mask\n        masks = np.clip(masks, a_min=0, a_max=i + 1)\n    return masks, index\n\n\ndef check_det_dataset(dataset, autodownload=True):\n    \"\"\"Download, check and/or unzip dataset if not found locally.\"\"\"\n    data = check_file(dataset)\n\n    # Download (optional)\n    extract_dir = ''\n    if isinstance(data, (str, Path)) and (zipfile.is_zipfile(data) or is_tarfile(data)):\n        new_dir = safe_download(data, dir=DATASETS_DIR, unzip=True, delete=False, curl=False)\n        data = next((DATASETS_DIR / new_dir).rglob('*.yaml'))\n        extract_dir, autodownload = data.parent, False\n\n    # Read yaml (optional)\n    if isinstance(data, (str, Path)):\n        data = yaml_load(data, append_filename=True)  # dictionary\n\n    # Checks\n    for k in 'train', 'val':\n        if k not in data:\n            raise SyntaxError(\n                emojis(f\"{dataset} '{k}:' key missing ❌.\\n'train' and 'val' are required in all data YAMLs.\"))\n    if 'names' not in data and 'nc' not in data:\n        raise SyntaxError(emojis(f\"{dataset} key missing ❌.\\n either 'names' or 'nc' are required in all data YAMLs.\"))\n    if 'names' in data and 'nc' in data and len(data['names']) != data['nc']:\n        raise SyntaxError(emojis(f\"{dataset} 'names' length {len(data['names'])} and 'nc: {data['nc']}' must match.\"))\n    if 'names' not in data:\n        data['names'] = [f'class_{i}' for i in range(data['nc'])]\n    else:\n        data['nc'] = len(data['names'])\n\n    data['names'] = check_class_names(data['names'])\n\n    # Resolve paths\n    path = Path(extract_dir or data.get('path') or Path(data.get('yaml_file', '')).parent)  # dataset root\n\n    if not path.is_absolute():\n        path = (DATASETS_DIR / path).resolve()\n    data['path'] = path  # download scripts\n    for k in 'train', 'val', 'test':\n        if data.get(k):  # prepend path\n            if isinstance(data[k], str):\n                x = (path / data[k]).resolve()\n                if not x.exists() and data[k].startswith('../'):\n                    x = (path / data[k][3:]).resolve()\n                data[k] = str(x)\n            else:\n                data[k] = [str((path / x).resolve()) for x in data[k]]\n\n    # Parse yaml\n    train, val, test, s = (data.get(x) for x in ('train', 'val', 'test', 'download'))\n    if val:\n        val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])]  # val path\n        if not all(x.exists() for x in val):\n            name = clean_url(dataset)  # dataset name with URL auth stripped\n            m = f\"\\nDataset '{name}' images not found ⚠️, missing paths %s\" % [str(x) for x in val if not x.exists()]\n            if s and autodownload:\n                LOGGER.warning(m)\n            else:\n                m += f\"\\nNote dataset download directory is '{DATASETS_DIR}'. You can update this in '{SETTINGS_YAML}'\"\n                raise FileNotFoundError(m)\n            t = time.time()\n            if s.startswith('http') and s.endswith('.zip'):  # URL\n                safe_download(url=s, dir=DATASETS_DIR, delete=True)\n                r = None  # success\n            elif s.startswith('bash '):  # bash script\n                LOGGER.info(f'Running {s} ...')\n                r = os.system(s)\n            else:  # python script\n                r = exec(s, {'yaml': data})  # return None\n            dt = f'({round(time.time() - t, 1)}s)'\n            s = f\"success ✅ {dt}, saved to {colorstr('bold', DATASETS_DIR)}\" if r in (0, None) else f'failure {dt} ❌'\n            LOGGER.info(f'Dataset download {s}\\n')\n    check_font('Arial.ttf' if is_ascii(data['names']) else 'Arial.Unicode.ttf')  # download fonts\n\n    return data  # dictionary\n\n\ndef check_cls_dataset(dataset: str, split=''):\n    \"\"\"\n    Check a classification dataset such as Imagenet.\n\n    This function takes a `dataset` name as input and returns a dictionary containing information about the dataset.\n    If the dataset is not found, it attempts to download the dataset from the internet and save it locally.\n\n    Args:\n        dataset (str): Name of the dataset.\n        split (str, optional): Dataset split, either 'val', 'test', or ''. Defaults to ''.\n\n    Returns:\n        data (dict): A dictionary containing the following keys and values:\n            'train': Path object for the directory containing the training set of the dataset\n            'val': Path object for the directory containing the validation set of the dataset\n            'test': Path object for the directory containing the test set of the dataset\n            'nc': Number of classes in the dataset\n            'names': List of class names in the dataset\n    \"\"\"\n    data_dir = (DATASETS_DIR / dataset).resolve()\n    if not data_dir.is_dir():\n        LOGGER.info(f'\\nDataset not found ⚠️, missing path {data_dir}, attempting download...')\n        t = time.time()\n        if dataset == 'imagenet':\n            subprocess.run(f\"bash {ROOT / 'yolo/data/scripts/get_imagenet.sh'}\", shell=True, check=True)\n        else:\n            url = f'https://github.com/ultralytics/yolov5/releases/download/v1.0/{dataset}.zip'\n            download(url, dir=data_dir.parent)\n        s = f\"Dataset download success ✅ ({time.time() - t:.1f}s), saved to {colorstr('bold', data_dir)}\\n\"\n        LOGGER.info(s)\n    train_set = data_dir / 'train'\n    val_set = data_dir / 'val' if (data_dir / 'val').exists() else None  # data/test or data/val\n    test_set = data_dir / 'test' if (data_dir / 'test').exists() else None  # data/val or data/test\n    if split == 'val' and not val_set:\n        LOGGER.info(\"WARNING ⚠️ Dataset 'split=val' not found, using 'split=test' instead.\")\n    elif split == 'test' and not test_set:\n        LOGGER.info(\"WARNING ⚠️ Dataset 'split=test' not found, using 'split=val' instead.\")\n\n    nc = len([x for x in (data_dir / 'train').glob('*') if x.is_dir()])  # number of classes\n    names = [x.name for x in (data_dir / 'train').iterdir() if x.is_dir()]  # class names list\n    names = dict(enumerate(sorted(names)))\n    return {'train': train_set, 'val': val_set or test_set, 'test': test_set or val_set, 'nc': nc, 'names': names}\n\n\nclass HUBDatasetStats():\n    \"\"\"\n    Class for generating HUB dataset JSON and `-hub` dataset directory\n\n    Arguments\n        path:           Path to data.yaml or data.zip (with data.yaml inside data.zip)\n        task:           Dataset task. Options are 'detect', 'segment', 'pose', 'classify'.\n        autodownload:   Attempt to download dataset if not found locally\n\n    Usage\n        from ultralytics.yolo.data.utils import HUBDatasetStats\n        stats = HUBDatasetStats('/Users/glennjocher/Downloads/coco8.zip', task='detect')  # detect dataset\n        stats = HUBDatasetStats('/Users/glennjocher/Downloads/coco8-seg.zip', task='segment')  # segment dataset\n        stats = HUBDatasetStats('/Users/glennjocher/Downloads/coco8-pose.zip', task='pose')  # pose dataset\n        stats.get_json(save=False)\n        stats.process_images()\n    \"\"\"\n\n    def __init__(self, path='coco128.yaml', task='detect', autodownload=False):\n        \"\"\"Initialize class.\"\"\"\n        LOGGER.info(f'Starting HUB dataset checks for {path}....')\n        zipped, data_dir, yaml_path = self._unzip(Path(path))\n        try:\n            # data = yaml_load(check_yaml(yaml_path))  # data dict\n            data = check_det_dataset(yaml_path, autodownload)  # data dict\n            if zipped:\n                data['path'] = data_dir\n        except Exception as e:\n            raise Exception('error/HUB/dataset_stats/yaml_load') from e\n\n        self.hub_dir = Path(str(data['path']) + '-hub')\n        self.im_dir = self.hub_dir / 'images'\n        self.im_dir.mkdir(parents=True, exist_ok=True)  # makes /images\n        self.stats = {'nc': len(data['names']), 'names': list(data['names'].values())}  # statistics dictionary\n        self.data = data\n        self.task = task  # detect, segment, pose, classify\n\n    @staticmethod\n    def _find_yaml(dir):\n        \"\"\"Return data.yaml file.\"\"\"\n        files = list(dir.glob('*.yaml')) or list(dir.rglob('*.yaml'))  # try root level first and then recursive\n        assert files, f'No *.yaml file found in {dir}'\n        if len(files) > 1:\n            files = [f for f in files if f.stem == dir.stem]  # prefer *.yaml files that match dir name\n            assert files, f'Multiple *.yaml files found in {dir}, only 1 *.yaml file allowed'\n        assert len(files) == 1, f'Multiple *.yaml files found: {files}, only 1 *.yaml file allowed in {dir}'\n        return files[0]\n\n    def _unzip(self, path):\n        \"\"\"Unzip data.zip.\"\"\"\n        if not str(path).endswith('.zip'):  # path is data.yaml\n            return False, None, path\n        unzip_dir = unzip_file(path, path=path.parent)\n        assert unzip_dir.is_dir(), f'Error unzipping {path}, {unzip_dir} not found. ' \\\n                                   f'path/to/abc.zip MUST unzip to path/to/abc/'\n        return True, str(unzip_dir), self._find_yaml(unzip_dir)  # zipped, data_dir, yaml_path\n\n    def _hub_ops(self, f):\n        \"\"\"Saves a compressed image for HUB previews.\"\"\"\n        compress_one_image(f, self.im_dir / Path(f).name)  # save to dataset-hub\n\n    def get_json(self, save=False, verbose=False):\n        \"\"\"Return dataset JSON for Ultralytics HUB.\"\"\"\n        from ultralytics.yolo.data import YOLODataset  # ClassificationDataset\n\n        def _round(labels):\n            \"\"\"Update labels to integer class and 4 decimal place floats.\"\"\"\n            if self.task == 'detect':\n                coordinates = labels['bboxes']\n            elif self.task == 'segment':\n                coordinates = [x.flatten() for x in labels['segments']]\n            elif self.task == 'pose':\n                n = labels['keypoints'].shape[0]\n                coordinates = np.concatenate((labels['bboxes'], labels['keypoints'].reshape(n, -1)), 1)\n            else:\n                raise ValueError('Undefined dataset task.')\n            zipped = zip(labels['cls'], coordinates)\n            return [[int(c), *(round(float(x), 4) for x in points)] for c, points in zipped]\n\n        for split in 'train', 'val', 'test':\n            if self.data.get(split) is None:\n                self.stats[split] = None  # i.e. no test set\n                continue\n\n            dataset = YOLODataset(img_path=self.data[split],\n                                  data=self.data,\n                                  use_segments=self.task == 'segment',\n                                  use_keypoints=self.task == 'pose')\n            x = np.array([\n                np.bincount(label['cls'].astype(int).flatten(), minlength=self.data['nc'])\n                for label in tqdm(dataset.labels, total=len(dataset), desc='Statistics')])  # shape(128x80)\n            self.stats[split] = {\n                'instance_stats': {\n                    'total': int(x.sum()),\n                    'per_class': x.sum(0).tolist()},\n                'image_stats': {\n                    'total': len(dataset),\n                    'unlabelled': int(np.all(x == 0, 1).sum()),\n                    'per_class': (x > 0).sum(0).tolist()},\n                'labels': [{\n                    Path(k).name: _round(v)} for k, v in zip(dataset.im_files, dataset.labels)]}\n\n        # Save, print and return\n        if save:\n            stats_path = self.hub_dir / 'stats.json'\n            LOGGER.info(f'Saving {stats_path.resolve()}...')\n            with open(stats_path, 'w') as f:\n                json.dump(self.stats, f)  # save stats.json\n        if verbose:\n            LOGGER.info(json.dumps(self.stats, indent=2, sort_keys=False))\n        return self.stats\n\n    def process_images(self):\n        \"\"\"Compress images for Ultralytics HUB.\"\"\"\n        from ultralytics.yolo.data import YOLODataset  # ClassificationDataset\n\n        for split in 'train', 'val', 'test':\n            if self.data.get(split) is None:\n                continue\n            dataset = YOLODataset(img_path=self.data[split], data=self.data)\n            with ThreadPool(NUM_THREADS) as pool:\n                for _ in tqdm(pool.imap(self._hub_ops, dataset.im_files), total=len(dataset), desc=f'{split} images'):\n                    pass\n        LOGGER.info(f'Done. All images saved to {self.im_dir}')\n        return self.im_dir\n\n\ndef compress_one_image(f, f_new=None, max_dim=1920, quality=50):\n    \"\"\"\n    Compresses a single image file to reduced size while preserving its aspect ratio and quality using either the\n    Python Imaging Library (PIL) or OpenCV library. If the input image is smaller than the maximum dimension, it will\n    not be resized.\n\n    Args:\n        f (str): The path to the input image file.\n        f_new (str, optional): The path to the output image file. If not specified, the input file will be overwritten.\n        max_dim (int, optional): The maximum dimension (width or height) of the output image. Default is 1920 pixels.\n        quality (int, optional): The image compression quality as a percentage. Default is 50%.\n\n    Usage:\n        from pathlib import Path\n        from ultralytics.yolo.data.utils import compress_one_image\n        for f in Path('/Users/glennjocher/Downloads/dataset').rglob('*.jpg'):\n            compress_one_image(f)\n    \"\"\"\n    try:  # use PIL\n        im = Image.open(f)\n        r = max_dim / max(im.height, im.width)  # ratio\n        if r < 1.0:  # image too large\n            im = im.resize((int(im.width * r), int(im.height * r)))\n        im.save(f_new or f, 'JPEG', quality=quality, optimize=True)  # save\n    except Exception as e:  # use OpenCV\n        LOGGER.info(f'WARNING ⚠️ HUB ops PIL failure {f}: {e}')\n        im = cv2.imread(f)\n        im_height, im_width = im.shape[:2]\n        r = max_dim / max(im_height, im_width)  # ratio\n        if r < 1.0:  # image too large\n            im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA)\n        cv2.imwrite(str(f_new or f), im)\n\n\ndef delete_dsstore(path):\n    \"\"\"\n    Deletes all \".DS_store\" files under a specified directory.\n\n    Args:\n        path (str, optional): The directory path where the \".DS_store\" files should be deleted.\n\n    Usage:\n        from ultralytics.yolo.data.utils import delete_dsstore\n        delete_dsstore('/Users/glennjocher/Downloads/dataset')\n\n    Note:\n        \".DS_store\" files are created by the Apple operating system and contain metadata about folders and files. They\n        are hidden system files and can cause issues when transferring files between different operating systems.\n    \"\"\"\n    # Delete Apple .DS_store files\n    files = list(Path(path).rglob('.DS_store'))\n    LOGGER.info(f'Deleting *.DS_store files: {files}')\n    for f in files:\n        f.unlink()\n\n\ndef zip_directory(dir, use_zipfile_library=True):\n    \"\"\"\n    Zips a directory and saves the archive to the specified output path.\n\n    Args:\n        dir (str): The path to the directory to be zipped.\n        use_zipfile_library (bool): Whether to use zipfile library or shutil for zipping.\n\n    Usage:\n        from ultralytics.yolo.data.utils import zip_directory\n        zip_directory('/Users/glennjocher/Downloads/playground')\n\n        zip -r coco8-pose.zip coco8-pose\n    \"\"\"\n    delete_dsstore(dir)\n    if use_zipfile_library:\n        dir = Path(dir)\n        with zipfile.ZipFile(dir.with_suffix('.zip'), 'w', zipfile.ZIP_DEFLATED) as zip_file:\n            for file_path in dir.glob('**/*'):\n                if file_path.is_file():\n                    zip_file.write(file_path, file_path.relative_to(dir))\n    else:\n        import shutil\n        shutil.make_archive(dir, 'zip', dir)\n"
  },
  {
    "path": "ultralytics/yolo/engine/__init__.py",
    "content": ""
  },
  {
    "path": "ultralytics/yolo/engine/exporter.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nExport a YOLOv8 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit\n\nFormat                  | `format=argument`         | Model\n---                     | ---                       | ---\nPyTorch                 | -                         | yolov8n.pt\nTorchScript             | `torchscript`             | yolov8n.torchscript\nONNX                    | `onnx`                    | yolov8n.onnx\nOpenVINO                | `openvino`                | yolov8n_openvino_model/\nTensorRT                | `engine`                  | yolov8n.engine\nCoreML                  | `coreml`                  | yolov8n.mlmodel\nTensorFlow SavedModel   | `saved_model`             | yolov8n_saved_model/\nTensorFlow GraphDef     | `pb`                      | yolov8n.pb\nTensorFlow Lite         | `tflite`                  | yolov8n.tflite\nTensorFlow Edge TPU     | `edgetpu`                 | yolov8n_edgetpu.tflite\nTensorFlow.js           | `tfjs`                    | yolov8n_web_model/\nPaddlePaddle            | `paddle`                  | yolov8n_paddle_model/\n\nRequirements:\n    $ pip install ultralytics[export]\n\nPython:\n    from ultralytics import YOLO\n    model = YOLO('yolov8n.pt')\n    results = model.export(format='onnx')\n\nCLI:\n    $ yolo mode=export model=yolov8n.pt format=onnx\n\nInference:\n    $ yolo predict model=yolov8n.pt                 # PyTorch\n                         yolov8n.torchscript        # TorchScript\n                         yolov8n.onnx               # ONNX Runtime or OpenCV DNN with --dnn\n                         yolov8n_openvino_model     # OpenVINO\n                         yolov8n.engine             # TensorRT\n                         yolov8n.mlmodel            # CoreML (macOS-only)\n                         yolov8n_saved_model        # TensorFlow SavedModel\n                         yolov8n.pb                 # TensorFlow GraphDef\n                         yolov8n.tflite             # TensorFlow Lite\n                         yolov8n_edgetpu.tflite     # TensorFlow Edge TPU\n                         yolov8n_paddle_model       # PaddlePaddle\n\nTensorFlow.js:\n    $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example\n    $ npm install\n    $ ln -s ../../yolov5/yolov8n_web_model public/yolov8n_web_model\n    $ npm start\n\"\"\"\nimport json\nimport os\nimport platform\nimport subprocess\nimport time\nimport warnings\nfrom copy import deepcopy\nfrom pathlib import Path\n\nimport torch\n\nfrom ultralytics.nn.autobackend import check_class_names\nfrom ultralytics.nn.modules import C2f, Detect, Segment\nfrom ultralytics.nn.tasks import DetectionModel, SegmentationModel\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.utils import (DEFAULT_CFG, LINUX, LOGGER, MACOS, __version__, callbacks, colorstr,\n                                    get_default_args, yaml_save)\nfrom ultralytics.yolo.utils.checks import check_imgsz, check_requirements, check_version\nfrom ultralytics.yolo.utils.files import file_size\nfrom ultralytics.yolo.utils.ops import Profile\nfrom ultralytics.yolo.utils.torch_utils import get_latest_opset, select_device, smart_inference_mode\n\nARM64 = platform.machine() in ('arm64', 'aarch64')\n\n\ndef export_formats():\n    \"\"\"YOLOv8 export formats.\"\"\"\n    import pandas\n    x = [\n        ['PyTorch', '-', '.pt', True, True],\n        ['TorchScript', 'torchscript', '.torchscript', True, True],\n        ['ONNX', 'onnx', '.onnx', True, True],\n        ['OpenVINO', 'openvino', '_openvino_model', True, False],\n        ['TensorRT', 'engine', '.engine', False, True],\n        ['CoreML', 'coreml', '.mlmodel', True, False],\n        ['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True],\n        ['TensorFlow GraphDef', 'pb', '.pb', True, True],\n        ['TensorFlow Lite', 'tflite', '.tflite', True, False],\n        ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', True, False],\n        ['TensorFlow.js', 'tfjs', '_web_model', True, False],\n        ['PaddlePaddle', 'paddle', '_paddle_model', True, True], ]\n    return pandas.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])\n\n\ndef gd_outputs(gd):\n    \"\"\"TensorFlow GraphDef model output node names.\"\"\"\n    name_list, input_list = [], []\n    for node in gd.node:  # tensorflow.core.framework.node_def_pb2.NodeDef\n        name_list.append(node.name)\n        input_list.extend(node.input)\n    return sorted(f'{x}:0' for x in list(set(name_list) - set(input_list)) if not x.startswith('NoOp'))\n\n\ndef try_export(inner_func):\n    \"\"\"YOLOv8 export decorator, i..e @try_export.\"\"\"\n    inner_args = get_default_args(inner_func)\n\n    def outer_func(*args, **kwargs):\n        \"\"\"Export a model.\"\"\"\n        prefix = inner_args['prefix']\n        try:\n            with Profile() as dt:\n                f, model = inner_func(*args, **kwargs)\n            LOGGER.info(f'{prefix} export success ✅ {dt.t:.1f}s, saved as {f} ({file_size(f):.1f} MB)')\n            return f, model\n        except Exception as e:\n            LOGGER.info(f'{prefix} export failure ❌ {dt.t:.1f}s: {e}')\n            return None, None\n\n    return outer_func\n\n\nclass Exporter:\n    \"\"\"\n    A class for exporting a model.\n\n    Attributes:\n        args (SimpleNamespace): Configuration for the exporter.\n        save_dir (Path): Directory to save results.\n    \"\"\"\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"\n        Initializes the Exporter class.\n\n        Args:\n            cfg (str, optional): Path to a configuration file. Defaults to DEFAULT_CFG.\n            overrides (dict, optional): Configuration overrides. Defaults to None.\n            _callbacks (list, optional): List of callback functions. Defaults to None.\n        \"\"\"\n        self.args = get_cfg(cfg, overrides)\n        self.callbacks = _callbacks or callbacks.get_default_callbacks()\n        callbacks.add_integration_callbacks(self)\n\n    @smart_inference_mode()\n    def __call__(self, model=None):\n        \"\"\"Returns list of exported files/dirs after running callbacks.\"\"\"\n        self.run_callbacks('on_export_start')\n        t = time.time()\n        format = self.args.format.lower()  # to lowercase\n        if format in ('tensorrt', 'trt'):  # engine aliases\n            format = 'engine'\n        fmts = tuple(export_formats()['Argument'][1:])  # available export formats\n        flags = [x == format for x in fmts]\n        if sum(flags) != 1:\n            raise ValueError(f\"Invalid export format='{format}'. Valid formats are {fmts}\")\n        jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle = flags  # export booleans\n\n        # Load PyTorch model\n        self.device = select_device('cpu' if self.args.device is None else self.args.device)\n        if self.args.half and onnx and self.device.type == 'cpu':\n            LOGGER.warning('WARNING ⚠️ half=True only compatible with GPU export, i.e. use device=0')\n            self.args.half = False\n            assert not self.args.dynamic, 'half=True not compatible with dynamic=True, i.e. use only one.'\n\n        # Checks\n        model.names = check_class_names(model.names)\n        self.imgsz = check_imgsz(self.args.imgsz, stride=model.stride, min_dim=2)  # check image size\n        if self.args.optimize:\n            assert self.device.type == 'cpu', '--optimize not compatible with cuda devices, i.e. use --device cpu'\n        if edgetpu and not LINUX:\n            raise SystemError('Edge TPU export only supported on Linux. See https://coral.ai/docs/edgetpu/compiler/')\n\n        # Input\n        im = torch.zeros(self.args.batch, 3, *self.imgsz).to(self.device)\n        file = Path(\n            getattr(model, 'pt_path', None) or getattr(model, 'yaml_file', None) or model.yaml.get('yaml_file', ''))\n        if file.suffix == '.yaml':\n            file = Path(file.name)\n\n        # Update model\n        model = deepcopy(model).to(self.device)\n        for p in model.parameters():\n            p.requires_grad = False\n        model.eval()\n        model.float()\n        model = model.fuse()\n        for k, m in model.named_modules():\n            if isinstance(m, (Detect, Segment)):\n                m.dynamic = self.args.dynamic\n                m.export = True\n                m.format = self.args.format\n            elif isinstance(m, C2f) and not any((saved_model, pb, tflite, edgetpu, tfjs)):\n                # EdgeTPU does not support FlexSplitV while split provides cleaner ONNX graph\n                m.forward = m.forward_split\n\n        y = None\n        for _ in range(2):\n            y = model(im)  # dry runs\n        if self.args.half and (engine or onnx) and self.device.type != 'cpu':\n            im, model = im.half(), model.half()  # to FP16\n\n        # Warnings\n        warnings.filterwarnings('ignore', category=torch.jit.TracerWarning)  # suppress TracerWarning\n        warnings.filterwarnings('ignore', category=UserWarning)  # suppress shape prim::Constant missing ONNX warning\n        warnings.filterwarnings('ignore', category=DeprecationWarning)  # suppress CoreML np.bool deprecation warning\n\n        # Assign\n        self.im = im\n        self.model = model\n        self.file = file\n        self.output_shape = tuple(y.shape) if isinstance(y, torch.Tensor) else \\\n            tuple(tuple(x.shape if isinstance(x, torch.Tensor) else []) for x in y)\n        self.pretty_name = Path(self.model.yaml.get('yaml_file', self.file)).stem.replace('yolo', 'YOLO')\n        trained_on = f'trained on {Path(self.args.data).name}' if self.args.data else '(untrained)'\n        description = f'Ultralytics {self.pretty_name} model {trained_on}'\n        self.metadata = {\n            'description': description,\n            'author': 'Ultralytics',\n            'license': 'AGPL-3.0 https://ultralytics.com/license',\n            'version': __version__,\n            'stride': int(max(model.stride)),\n            'task': model.task,\n            'batch': self.args.batch,\n            'imgsz': self.imgsz,\n            'names': model.names}  # model metadata\n        if model.task == 'pose':\n            self.metadata['kpt_shape'] = model.kpt_shape\n\n        LOGGER.info(f\"\\n{colorstr('PyTorch:')} starting from {file} with input shape {tuple(im.shape)} BCHW and \"\n                    f'output shape(s) {self.output_shape} ({file_size(file):.1f} MB)')\n\n        # Exports\n        f = [''] * len(fmts)  # exported filenames\n        if jit:  # TorchScript\n            f[0], _ = self.export_torchscript()\n        if engine:  # TensorRT required before ONNX\n            f[1], _ = self.export_engine()\n        if onnx or xml:  # OpenVINO requires ONNX\n            f[2], _ = self.export_onnx()\n        if xml:  # OpenVINO\n            f[3], _ = self.export_openvino()\n        if coreml:  # CoreML\n            f[4], _ = self.export_coreml()\n        if any((saved_model, pb, tflite, edgetpu, tfjs)):  # TensorFlow formats\n            self.args.int8 |= edgetpu\n            f[5], s_model = self.export_saved_model()\n            if pb or tfjs:  # pb prerequisite to tfjs\n                f[6], _ = self.export_pb(s_model)\n            if tflite:\n                f[7], _ = self.export_tflite(s_model, nms=False, agnostic_nms=self.args.agnostic_nms)\n            if edgetpu:\n                f[8], _ = self.export_edgetpu(tflite_model=Path(f[5]) / f'{self.file.stem}_full_integer_quant.tflite')\n            if tfjs:\n                f[9], _ = self.export_tfjs()\n        if paddle:  # PaddlePaddle\n            f[10], _ = self.export_paddle()\n\n        # Finish\n        f = [str(x) for x in f if x]  # filter out '' and None\n        if any(f):\n            f = str(Path(f[-1]))\n            square = self.imgsz[0] == self.imgsz[1]\n            s = '' if square else f\"WARNING ⚠️ non-PyTorch val requires square images, 'imgsz={self.imgsz}' will not \" \\\n                                  f\"work. Use export 'imgsz={max(self.imgsz)}' if val is required.\"\n            imgsz = self.imgsz[0] if square else str(self.imgsz)[1:-1].replace(' ', '')\n            data = f'data={self.args.data}' if model.task == 'segment' and format == 'pb' else ''\n            LOGGER.info(\n                f'\\nExport complete ({time.time() - t:.1f}s)'\n                f\"\\nResults saved to {colorstr('bold', file.parent.resolve())}\"\n                f'\\nPredict:         yolo predict task={model.task} model={f} imgsz={imgsz} {data}'\n                f'\\nValidate:        yolo val task={model.task} model={f} imgsz={imgsz} data={self.args.data} {s}'\n                f'\\nVisualize:       https://netron.app')\n\n        self.run_callbacks('on_export_end')\n        return f  # return list of exported files/dirs\n\n    @try_export\n    def export_torchscript(self, prefix=colorstr('TorchScript:')):\n        \"\"\"YOLOv8 TorchScript model export.\"\"\"\n        LOGGER.info(f'\\n{prefix} starting export with torch {torch.__version__}...')\n        f = self.file.with_suffix('.torchscript')\n\n        ts = torch.jit.trace(self.model, self.im, strict=False)\n        extra_files = {'config.txt': json.dumps(self.metadata)}  # torch._C.ExtraFilesMap()\n        if self.args.optimize:  # https://pytorch.org/tutorials/recipes/mobile_interpreter.html\n            LOGGER.info(f'{prefix} optimizing for mobile...')\n            from torch.utils.mobile_optimizer import optimize_for_mobile\n            optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)\n        else:\n            ts.save(str(f), _extra_files=extra_files)\n        return f, None\n\n    @try_export\n    def export_onnx(self, prefix=colorstr('ONNX:')):\n        \"\"\"YOLOv8 ONNX export.\"\"\"\n        requirements = ['onnx>=1.12.0']\n        if self.args.simplify:\n            requirements += ['onnxsim>=0.4.17', 'onnxruntime-gpu' if torch.cuda.is_available() else 'onnxruntime']\n        check_requirements(requirements)\n        import onnx  # noqa\n\n        opset_version = self.args.opset or get_latest_opset()\n        LOGGER.info(f'\\n{prefix} starting export with onnx {onnx.__version__} opset {opset_version}...')\n        f = str(self.file.with_suffix('.onnx'))\n\n        output_names = ['output0', 'output1'] if isinstance(self.model, SegmentationModel) else ['output0']\n        dynamic = self.args.dynamic\n        if dynamic:\n            dynamic = {'images': {0: 'batch', 2: 'height', 3: 'width'}}  # shape(1,3,640,640)\n            if isinstance(self.model, SegmentationModel):\n                dynamic['output0'] = {0: 'batch', 1: 'anchors'}  # shape(1,25200,85)\n                dynamic['output1'] = {0: 'batch', 2: 'mask_height', 3: 'mask_width'}  # shape(1,32,160,160)\n            elif isinstance(self.model, DetectionModel):\n                dynamic['output0'] = {0: 'batch', 1: 'anchors'}  # shape(1,25200,85)\n\n        torch.onnx.export(\n            self.model.cpu() if dynamic else self.model,  # --dynamic only compatible with cpu\n            self.im.cpu() if dynamic else self.im,\n            f,\n            verbose=False,\n            opset_version=opset_version,\n            do_constant_folding=True,  # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False\n            input_names=['images'],\n            output_names=output_names,\n            dynamic_axes=dynamic or None)\n\n        # Checks\n        model_onnx = onnx.load(f)  # load onnx model\n        # onnx.checker.check_model(model_onnx)  # check onnx model\n\n        # Simplify\n        if self.args.simplify:\n            try:\n                import onnxsim\n\n                LOGGER.info(f'{prefix} simplifying with onnxsim {onnxsim.__version__}...')\n                # subprocess.run(f'onnxsim {f} {f}', shell=True)\n                model_onnx, check = onnxsim.simplify(model_onnx)\n                assert check, 'Simplified ONNX model could not be validated'\n            except Exception as e:\n                LOGGER.info(f'{prefix} simplifier failure: {e}')\n\n        # Metadata\n        for k, v in self.metadata.items():\n            meta = model_onnx.metadata_props.add()\n            meta.key, meta.value = k, str(v)\n\n        onnx.save(model_onnx, f)\n        return f, model_onnx\n\n    @try_export\n    def export_openvino(self, prefix=colorstr('OpenVINO:')):\n        \"\"\"YOLOv8 OpenVINO export.\"\"\"\n        check_requirements('openvino-dev>=2022.3')  # requires openvino-dev: https://pypi.org/project/openvino-dev/\n        import openvino.runtime as ov  # noqa\n        from openvino.tools import mo  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with openvino {ov.__version__}...')\n        f = str(self.file).replace(self.file.suffix, f'_openvino_model{os.sep}')\n        f_onnx = self.file.with_suffix('.onnx')\n        f_ov = str(Path(f) / self.file.with_suffix('.xml').name)\n\n        ov_model = mo.convert_model(f_onnx,\n                                    model_name=self.pretty_name,\n                                    framework='onnx',\n                                    compress_to_fp16=self.args.half)  # export\n\n        # Set RT info\n        ov_model.set_rt_info('YOLOv8', ['model_info', 'model_type'])\n        ov_model.set_rt_info(True, ['model_info', 'reverse_input_channels'])\n        ov_model.set_rt_info(114, ['model_info', 'pad_value'])\n        ov_model.set_rt_info([255.0], ['model_info', 'scale_values'])\n        ov_model.set_rt_info(self.args.iou, ['model_info', 'iou_threshold'])\n        ov_model.set_rt_info([v.replace(' ', '_') for k, v in sorted(self.model.names.items())],\n                             ['model_info', 'labels'])\n        if self.model.task != 'classify':\n            ov_model.set_rt_info('fit_to_window_letterbox', ['model_info', 'resize_type'])\n\n        ov.serialize(ov_model, f_ov)  # save\n        yaml_save(Path(f) / 'metadata.yaml', self.metadata)  # add metadata.yaml\n        return f, None\n\n    @try_export\n    def export_paddle(self, prefix=colorstr('PaddlePaddle:')):\n        \"\"\"YOLOv8 Paddle export.\"\"\"\n        check_requirements(('paddlepaddle', 'x2paddle'))\n        import x2paddle  # noqa\n        from x2paddle.convert import pytorch2paddle  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with X2Paddle {x2paddle.__version__}...')\n        f = str(self.file).replace(self.file.suffix, f'_paddle_model{os.sep}')\n\n        pytorch2paddle(module=self.model, save_dir=f, jit_type='trace', input_examples=[self.im])  # export\n        yaml_save(Path(f) / 'metadata.yaml', self.metadata)  # add metadata.yaml\n        return f, None\n\n    @try_export\n    def export_coreml(self, prefix=colorstr('CoreML:')):\n        \"\"\"YOLOv8 CoreML export.\"\"\"\n        check_requirements('coremltools>=6.0')\n        import coremltools as ct  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with coremltools {ct.__version__}...')\n        f = self.file.with_suffix('.mlmodel')\n\n        bias = [0.0, 0.0, 0.0]\n        scale = 1 / 255\n        classifier_config = None\n        if self.model.task == 'classify':\n            classifier_config = ct.ClassifierConfig(list(self.model.names.values())) if self.args.nms else None\n            model = self.model\n        elif self.model.task == 'detect':\n            model = iOSDetectModel(self.model, self.im) if self.args.nms else self.model\n        else:\n            # TODO CoreML Segment and Pose model pipelining\n            model = self.model\n\n        ts = torch.jit.trace(model.eval(), self.im, strict=False)  # TorchScript model\n        ct_model = ct.convert(ts,\n                              inputs=[ct.ImageType('image', shape=self.im.shape, scale=scale, bias=bias)],\n                              classifier_config=classifier_config)\n        bits, mode = (8, 'kmeans_lut') if self.args.int8 else (16, 'linear') if self.args.half else (32, None)\n        if bits < 32:\n            if 'kmeans' in mode:\n                check_requirements('scikit-learn')  # scikit-learn package required for k-means quantization\n            ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)\n        if self.args.nms and self.model.task == 'detect':\n            ct_model = self._pipeline_coreml(ct_model)\n\n        m = self.metadata  # metadata dict\n        ct_model.short_description = m.pop('description')\n        ct_model.author = m.pop('author')\n        ct_model.license = m.pop('license')\n        ct_model.version = m.pop('version')\n        ct_model.user_defined_metadata.update({k: str(v) for k, v in m.items()})\n        ct_model.save(str(f))\n        return f, ct_model\n\n    @try_export\n    def export_engine(self, prefix=colorstr('TensorRT:')):\n        \"\"\"YOLOv8 TensorRT export https://developer.nvidia.com/tensorrt.\"\"\"\n        assert self.im.device.type != 'cpu', \"export running on CPU but must be on GPU, i.e. use 'device=0'\"\n        try:\n            import tensorrt as trt  # noqa\n        except ImportError:\n            if LINUX:\n                check_requirements('nvidia-tensorrt', cmds='-U --index-url https://pypi.ngc.nvidia.com')\n            import tensorrt as trt  # noqa\n\n        check_version(trt.__version__, '7.0.0', hard=True)  # require tensorrt>=8.0.0\n        self.args.simplify = True\n        f_onnx, _ = self.export_onnx()\n\n        LOGGER.info(f'\\n{prefix} starting export with TensorRT {trt.__version__}...')\n        assert Path(f_onnx).exists(), f'failed to export ONNX file: {f_onnx}'\n        f = self.file.with_suffix('.engine')  # TensorRT engine file\n        logger = trt.Logger(trt.Logger.INFO)\n        if self.args.verbose:\n            logger.min_severity = trt.Logger.Severity.VERBOSE\n\n        builder = trt.Builder(logger)\n        config = builder.create_builder_config()\n        config.max_workspace_size = self.args.workspace * 1 << 30\n        # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30)  # fix TRT 8.4 deprecation notice\n\n        flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))\n        network = builder.create_network(flag)\n        parser = trt.OnnxParser(network, logger)\n        if not parser.parse_from_file(f_onnx):\n            raise RuntimeError(f'failed to load ONNX file: {f_onnx}')\n\n        inputs = [network.get_input(i) for i in range(network.num_inputs)]\n        outputs = [network.get_output(i) for i in range(network.num_outputs)]\n        for inp in inputs:\n            LOGGER.info(f'{prefix} input \"{inp.name}\" with shape{inp.shape} {inp.dtype}')\n        for out in outputs:\n            LOGGER.info(f'{prefix} output \"{out.name}\" with shape{out.shape} {out.dtype}')\n\n        if self.args.dynamic:\n            shape = self.im.shape\n            if shape[0] <= 1:\n                LOGGER.warning(f'{prefix} WARNING ⚠️ --dynamic model requires maximum --batch-size argument')\n            profile = builder.create_optimization_profile()\n            for inp in inputs:\n                profile.set_shape(inp.name, (1, *shape[1:]), (max(1, shape[0] // 2), *shape[1:]), shape)\n            config.add_optimization_profile(profile)\n\n        LOGGER.info(\n            f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and self.args.half else 32} engine as {f}')\n        if builder.platform_has_fast_fp16 and self.args.half:\n            config.set_flag(trt.BuilderFlag.FP16)\n\n        # Write file\n        with builder.build_engine(network, config) as engine, open(f, 'wb') as t:\n            # Metadata\n            meta = json.dumps(self.metadata)\n            t.write(len(meta).to_bytes(4, byteorder='little', signed=True))\n            t.write(meta.encode())\n            # Model\n            t.write(engine.serialize())\n\n        return f, None\n\n    @try_export\n    def export_saved_model(self, prefix=colorstr('TensorFlow SavedModel:')):\n        \"\"\"YOLOv8 TensorFlow SavedModel export.\"\"\"\n        try:\n            import tensorflow as tf  # noqa\n        except ImportError:\n            cuda = torch.cuda.is_available()\n            check_requirements(f\"tensorflow{'-macos' if MACOS else '-aarch64' if ARM64 else '' if cuda else '-cpu'}\")\n            import tensorflow as tf  # noqa\n        check_requirements(('onnx', 'onnx2tf>=1.7.7', 'sng4onnx>=1.0.1', 'onnxsim>=0.4.17', 'onnx_graphsurgeon>=0.3.26',\n                            'tflite_support', 'onnxruntime-gpu' if torch.cuda.is_available() else 'onnxruntime'),\n                           cmds='--extra-index-url https://pypi.ngc.nvidia.com')\n\n        LOGGER.info(f'\\n{prefix} starting export with tensorflow {tf.__version__}...')\n        f = Path(str(self.file).replace(self.file.suffix, '_saved_model'))\n        if f.is_dir():\n            import shutil\n            shutil.rmtree(f)  # delete output folder\n\n        # Export to ONNX\n        self.args.simplify = True\n        f_onnx, _ = self.export_onnx()\n\n        # Export to TF\n        int8 = '-oiqt -qt per-tensor' if self.args.int8 else ''\n        cmd = f'onnx2tf -i {f_onnx} -o {f} -nuo --non_verbose {int8}'\n        LOGGER.info(f\"\\n{prefix} running '{cmd.strip()}'\")\n        subprocess.run(cmd, shell=True)\n        yaml_save(f / 'metadata.yaml', self.metadata)  # add metadata.yaml\n\n        # Remove/rename TFLite models\n        if self.args.int8:\n            for file in f.rglob('*_dynamic_range_quant.tflite'):\n                file.rename(file.with_stem(file.stem.replace('_dynamic_range_quant', '_int8')))\n            for file in f.rglob('*_integer_quant_with_int16_act.tflite'):\n                file.unlink()  # delete extra fp16 activation TFLite files\n\n        # Add TFLite metadata\n        for file in f.rglob('*.tflite'):\n            f.unlink() if 'quant_with_int16_act.tflite' in str(f) else self._add_tflite_metadata(file)\n\n        # Load saved_model\n        keras_model = tf.saved_model.load(f, tags=None, options=None)\n\n        return str(f), keras_model\n\n    @try_export\n    def export_pb(self, keras_model, prefix=colorstr('TensorFlow GraphDef:')):\n        \"\"\"YOLOv8 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow.\"\"\"\n        import tensorflow as tf  # noqa\n        from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with tensorflow {tf.__version__}...')\n        f = self.file.with_suffix('.pb')\n\n        m = tf.function(lambda x: keras_model(x))  # full model\n        m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))\n        frozen_func = convert_variables_to_constants_v2(m)\n        frozen_func.graph.as_graph_def()\n        tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)\n        return f, None\n\n    @try_export\n    def export_tflite(self, keras_model, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):\n        \"\"\"YOLOv8 TensorFlow Lite export.\"\"\"\n        import tensorflow as tf  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with tensorflow {tf.__version__}...')\n        saved_model = Path(str(self.file).replace(self.file.suffix, '_saved_model'))\n        if self.args.int8:\n            f = saved_model / f'{self.file.stem}_int8.tflite'  # fp32 in/out\n        elif self.args.half:\n            f = saved_model / f'{self.file.stem}_float16.tflite'  # fp32 in/out\n        else:\n            f = saved_model / f'{self.file.stem}_float32.tflite'\n        return str(f), None\n\n    @try_export\n    def export_edgetpu(self, tflite_model='', prefix=colorstr('Edge TPU:')):\n        \"\"\"YOLOv8 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/.\"\"\"\n        LOGGER.warning(f'{prefix} WARNING ⚠️ Edge TPU known bug https://github.com/ultralytics/ultralytics/issues/1185')\n\n        cmd = 'edgetpu_compiler --version'\n        help_url = 'https://coral.ai/docs/edgetpu/compiler/'\n        assert LINUX, f'export only supported on Linux. See {help_url}'\n        if subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True).returncode != 0:\n            LOGGER.info(f'\\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')\n            sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0  # sudo installed on system\n            for c in (\n                    'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',\n                    'echo \"deb https://packages.cloud.google.com/apt coral-edgetpu-stable main\" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',\n                    'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):\n                subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)\n        ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]\n\n        LOGGER.info(f'\\n{prefix} starting export with Edge TPU compiler {ver}...')\n        f = str(tflite_model).replace('.tflite', '_edgetpu.tflite')  # Edge TPU model\n\n        cmd = f'edgetpu_compiler -s -d -k 10 --out_dir {Path(f).parent} {tflite_model}'\n        LOGGER.info(f\"{prefix} running '{cmd}'\")\n        subprocess.run(cmd.split(), check=True)\n        self._add_tflite_metadata(f)\n        return f, None\n\n    @try_export\n    def export_tfjs(self, prefix=colorstr('TensorFlow.js:')):\n        \"\"\"YOLOv8 TensorFlow.js export.\"\"\"\n        check_requirements('tensorflowjs')\n        import tensorflow as tf\n        import tensorflowjs as tfjs  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')\n        f = str(self.file).replace(self.file.suffix, '_web_model')  # js dir\n        f_pb = self.file.with_suffix('.pb')  # *.pb path\n\n        gd = tf.Graph().as_graph_def()  # TF GraphDef\n        with open(f_pb, 'rb') as file:\n            gd.ParseFromString(file.read())\n        outputs = ','.join(gd_outputs(gd))\n        LOGGER.info(f'\\n{prefix} output node names: {outputs}')\n\n        cmd = f'tensorflowjs_converter --input_format=tf_frozen_model --output_node_names={outputs} {f_pb} {f}'\n        subprocess.run(cmd.split(), check=True)\n\n        # f_json = Path(f) / 'model.json'  # *.json path\n        # with open(f_json, 'w') as j:  # sort JSON Identity_* in ascending order\n        #     subst = re.sub(\n        #         r'{\"outputs\": {\"Identity.?.?\": {\"name\": \"Identity.?.?\"}, '\n        #         r'\"Identity.?.?\": {\"name\": \"Identity.?.?\"}, '\n        #         r'\"Identity.?.?\": {\"name\": \"Identity.?.?\"}, '\n        #         r'\"Identity.?.?\": {\"name\": \"Identity.?.?\"}}}',\n        #         r'{\"outputs\": {\"Identity\": {\"name\": \"Identity\"}, '\n        #         r'\"Identity_1\": {\"name\": \"Identity_1\"}, '\n        #         r'\"Identity_2\": {\"name\": \"Identity_2\"}, '\n        #         r'\"Identity_3\": {\"name\": \"Identity_3\"}}}',\n        #         f_json.read_text(),\n        #     )\n        #     j.write(subst)\n        yaml_save(Path(f) / 'metadata.yaml', self.metadata)  # add metadata.yaml\n        return f, None\n\n    def _add_tflite_metadata(self, file):\n        \"\"\"Add metadata to *.tflite models per https://www.tensorflow.org/lite/models/convert/metadata.\"\"\"\n        from tflite_support import flatbuffers  # noqa\n        from tflite_support import metadata as _metadata  # noqa\n        from tflite_support import metadata_schema_py_generated as _metadata_fb  # noqa\n\n        # Create model info\n        model_meta = _metadata_fb.ModelMetadataT()\n        model_meta.name = self.metadata['description']\n        model_meta.version = self.metadata['version']\n        model_meta.author = self.metadata['author']\n        model_meta.license = self.metadata['license']\n\n        # Label file\n        tmp_file = Path(file).parent / 'temp_meta.txt'\n        with open(tmp_file, 'w') as f:\n            f.write(str(self.metadata))\n\n        label_file = _metadata_fb.AssociatedFileT()\n        label_file.name = tmp_file.name\n        label_file.type = _metadata_fb.AssociatedFileType.TENSOR_AXIS_LABELS\n\n        # Create input info\n        input_meta = _metadata_fb.TensorMetadataT()\n        input_meta.name = 'image'\n        input_meta.description = 'Input image to be detected.'\n        input_meta.content = _metadata_fb.ContentT()\n        input_meta.content.contentProperties = _metadata_fb.ImagePropertiesT()\n        input_meta.content.contentProperties.colorSpace = _metadata_fb.ColorSpaceType.RGB\n        input_meta.content.contentPropertiesType = _metadata_fb.ContentProperties.ImageProperties\n\n        # Create output info\n        output1 = _metadata_fb.TensorMetadataT()\n        output1.name = 'output'\n        output1.description = 'Coordinates of detected objects, class labels, and confidence score'\n        output1.associatedFiles = [label_file]\n        if self.model.task == 'segment':\n            output2 = _metadata_fb.TensorMetadataT()\n            output2.name = 'output'\n            output2.description = 'Mask protos'\n            output2.associatedFiles = [label_file]\n\n        # Create subgraph info\n        subgraph = _metadata_fb.SubGraphMetadataT()\n        subgraph.inputTensorMetadata = [input_meta]\n        subgraph.outputTensorMetadata = [output1, output2] if self.model.task == 'segment' else [output1]\n        model_meta.subgraphMetadata = [subgraph]\n\n        b = flatbuffers.Builder(0)\n        b.Finish(model_meta.Pack(b), _metadata.MetadataPopulator.METADATA_FILE_IDENTIFIER)\n        metadata_buf = b.Output()\n\n        populator = _metadata.MetadataPopulator.with_model_file(str(file))\n        populator.load_metadata_buffer(metadata_buf)\n        populator.load_associated_files([str(tmp_file)])\n        populator.populate()\n        tmp_file.unlink()\n\n    def _pipeline_coreml(self, model, prefix=colorstr('CoreML Pipeline:')):\n        \"\"\"YOLOv8 CoreML pipeline.\"\"\"\n        import coremltools as ct  # noqa\n\n        LOGGER.info(f'{prefix} starting pipeline with coremltools {ct.__version__}...')\n        batch_size, ch, h, w = list(self.im.shape)  # BCHW\n\n        # Output shapes\n        spec = model.get_spec()\n        out0, out1 = iter(spec.description.output)\n        if MACOS:\n            from PIL import Image\n            img = Image.new('RGB', (w, h))  # img(192 width, 320 height)\n            # img = torch.zeros((*opt.img_size, 3)).numpy()  # img size(320,192,3) iDetection\n            out = model.predict({'image': img})\n            out0_shape = out[out0.name].shape\n            out1_shape = out[out1.name].shape\n        else:  # linux and windows can not run model.predict(), get sizes from pytorch output y\n            out0_shape = self.output_shape[2], self.output_shape[1] - 4  # (3780, 80)\n            out1_shape = self.output_shape[2], 4  # (3780, 4)\n\n        # Checks\n        names = self.metadata['names']\n        nx, ny = spec.description.input[0].type.imageType.width, spec.description.input[0].type.imageType.height\n        na, nc = out0_shape\n        # na, nc = out0.type.multiArrayType.shape  # number anchors, classes\n        assert len(names) == nc, f'{len(names)} names found for nc={nc}'  # check\n\n        # Define output shapes (missing)\n        out0.type.multiArrayType.shape[:] = out0_shape  # (3780, 80)\n        out1.type.multiArrayType.shape[:] = out1_shape  # (3780, 4)\n        # spec.neuralNetwork.preprocessing[0].featureName = '0'\n\n        # Flexible input shapes\n        # from coremltools.models.neural_network import flexible_shape_utils\n        # s = [] # shapes\n        # s.append(flexible_shape_utils.NeuralNetworkImageSize(320, 192))\n        # s.append(flexible_shape_utils.NeuralNetworkImageSize(640, 384))  # (height, width)\n        # flexible_shape_utils.add_enumerated_image_sizes(spec, feature_name='image', sizes=s)\n        # r = flexible_shape_utils.NeuralNetworkImageSizeRange()  # shape ranges\n        # r.add_height_range((192, 640))\n        # r.add_width_range((192, 640))\n        # flexible_shape_utils.update_image_size_range(spec, feature_name='image', size_range=r)\n\n        # Print\n        # print(spec.description)\n\n        # Model from spec\n        model = ct.models.MLModel(spec)\n\n        # 3. Create NMS protobuf\n        nms_spec = ct.proto.Model_pb2.Model()\n        nms_spec.specificationVersion = 5\n        for i in range(2):\n            decoder_output = model._spec.description.output[i].SerializeToString()\n            nms_spec.description.input.add()\n            nms_spec.description.input[i].ParseFromString(decoder_output)\n            nms_spec.description.output.add()\n            nms_spec.description.output[i].ParseFromString(decoder_output)\n\n        nms_spec.description.output[0].name = 'confidence'\n        nms_spec.description.output[1].name = 'coordinates'\n\n        output_sizes = [nc, 4]\n        for i in range(2):\n            ma_type = nms_spec.description.output[i].type.multiArrayType\n            ma_type.shapeRange.sizeRanges.add()\n            ma_type.shapeRange.sizeRanges[0].lowerBound = 0\n            ma_type.shapeRange.sizeRanges[0].upperBound = -1\n            ma_type.shapeRange.sizeRanges.add()\n            ma_type.shapeRange.sizeRanges[1].lowerBound = output_sizes[i]\n            ma_type.shapeRange.sizeRanges[1].upperBound = output_sizes[i]\n            del ma_type.shape[:]\n\n        nms = nms_spec.nonMaximumSuppression\n        nms.confidenceInputFeatureName = out0.name  # 1x507x80\n        nms.coordinatesInputFeatureName = out1.name  # 1x507x4\n        nms.confidenceOutputFeatureName = 'confidence'\n        nms.coordinatesOutputFeatureName = 'coordinates'\n        nms.iouThresholdInputFeatureName = 'iouThreshold'\n        nms.confidenceThresholdInputFeatureName = 'confidenceThreshold'\n        nms.iouThreshold = 0.45\n        nms.confidenceThreshold = 0.25\n        nms.pickTop.perClass = True\n        nms.stringClassLabels.vector.extend(names.values())\n        nms_model = ct.models.MLModel(nms_spec)\n\n        # 4. Pipeline models together\n        pipeline = ct.models.pipeline.Pipeline(input_features=[('image', ct.models.datatypes.Array(3, ny, nx)),\n                                                               ('iouThreshold', ct.models.datatypes.Double()),\n                                                               ('confidenceThreshold', ct.models.datatypes.Double())],\n                                               output_features=['confidence', 'coordinates'])\n        pipeline.add_model(model)\n        pipeline.add_model(nms_model)\n\n        # Correct datatypes\n        pipeline.spec.description.input[0].ParseFromString(model._spec.description.input[0].SerializeToString())\n        pipeline.spec.description.output[0].ParseFromString(nms_model._spec.description.output[0].SerializeToString())\n        pipeline.spec.description.output[1].ParseFromString(nms_model._spec.description.output[1].SerializeToString())\n\n        # Update metadata\n        pipeline.spec.specificationVersion = 5\n        pipeline.spec.description.metadata.userDefined.update({\n            'IoU threshold': str(nms.iouThreshold),\n            'Confidence threshold': str(nms.confidenceThreshold)})\n\n        # Save the model\n        model = ct.models.MLModel(pipeline.spec)\n        model.input_description['image'] = 'Input image'\n        model.input_description['iouThreshold'] = f'(optional) IOU threshold override (default: {nms.iouThreshold})'\n        model.input_description['confidenceThreshold'] = \\\n            f'(optional) Confidence threshold override (default: {nms.confidenceThreshold})'\n        model.output_description['confidence'] = 'Boxes × Class confidence (see user-defined metadata \"classes\")'\n        model.output_description['coordinates'] = 'Boxes × [x, y, width, height] (relative to image size)'\n        LOGGER.info(f'{prefix} pipeline success')\n        return model\n\n    def add_callback(self, event: str, callback):\n        \"\"\"\n        Appends the given callback.\n        \"\"\"\n        self.callbacks[event].append(callback)\n\n    def run_callbacks(self, event: str):\n        \"\"\"Execute all callbacks for a given event.\"\"\"\n        for callback in self.callbacks.get(event, []):\n            callback(self)\n\n\nclass iOSDetectModel(torch.nn.Module):\n    \"\"\"Wrap an Ultralytics YOLO model for iOS export.\"\"\"\n\n    def __init__(self, model, im):\n        \"\"\"Initialize the iOSDetectModel class with a YOLO model and example image.\"\"\"\n        super().__init__()\n        b, c, h, w = im.shape  # batch, channel, height, width\n        self.model = model\n        self.nc = len(model.names)  # number of classes\n        if w == h:\n            self.normalize = 1.0 / w  # scalar\n        else:\n            self.normalize = torch.tensor([1.0 / w, 1.0 / h, 1.0 / w, 1.0 / h])  # broadcast (slower, smaller)\n\n    def forward(self, x):\n        \"\"\"Normalize predictions of object detection model with input size-dependent factors.\"\"\"\n        xywh, cls = self.model(x)[0].transpose(0, 1).split((4, self.nc), 1)\n        return cls, xywh * self.normalize  # confidence (3780, 80), coordinates (3780, 4)\n\n\ndef export(cfg=DEFAULT_CFG):\n    \"\"\"Export a YOLOv model to a specific format.\"\"\"\n    cfg.model = cfg.model or 'yolov8n.yaml'\n    cfg.format = cfg.format or 'torchscript'\n\n    from ultralytics import YOLO\n    model = YOLO(cfg.model)\n    model.export(**vars(cfg))\n\n\nif __name__ == '__main__':\n    \"\"\"\n    CLI:\n    yolo mode=export model=yolov8n.yaml format=onnx\n    \"\"\"\n    export()\n"
  },
  {
    "path": "ultralytics/yolo/engine/model.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport sys\nfrom pathlib import Path\nfrom typing import Union\n\nfrom ultralytics import yolo  # noqa\nfrom ultralytics.nn.tasks import (ClassificationModel, DetectionModel, PoseModel, SegmentationModel,\n                                  attempt_load_one_weight, guess_model_task, nn, yaml_model_load)\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.engine.exporter import Exporter\nfrom ultralytics.yolo.utils import (DEFAULT_CFG, DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, NUM_THREADS, RANK, ROOT,\n                                    callbacks, is_git_dir, yaml_load)\nfrom ultralytics.yolo.utils.checks import check_file, check_imgsz, check_pip_update_available, check_yaml\nfrom ultralytics.yolo.utils.downloads import GITHUB_ASSET_STEMS\nfrom ultralytics.yolo.utils.torch_utils import smart_inference_mode\n\n# Map head to model, trainer, validator, and predictor classes\nTASK_MAP = {\n    'classify': [\n        ClassificationModel, yolo.v8.classify.ClassificationTrainer, yolo.v8.classify.ClassificationValidator,\n        yolo.v8.classify.ClassificationPredictor],\n    'detect': [\n        DetectionModel, yolo.v8.detect.DetectionTrainer, yolo.v8.detect.DetectionValidator,\n        yolo.v8.detect.DetectionPredictor],\n    'segment': [\n        SegmentationModel, yolo.v8.segment.SegmentationTrainer, yolo.v8.segment.SegmentationValidator,\n        yolo.v8.segment.SegmentationPredictor],\n    'pose': [PoseModel, yolo.v8.pose.PoseTrainer, yolo.v8.pose.PoseValidator, yolo.v8.pose.PosePredictor]}\n\n\nclass YOLO:\n    \"\"\"\n    YOLO (You Only Look Once) object detection model.\n\n    Args:\n        model (str, Path): Path to the model file to load or create.\n        task (Any, optional): Task type for the YOLO model. Defaults to None.\n\n    Attributes:\n        predictor (Any): The predictor object.\n        model (Any): The model object.\n        trainer (Any): The trainer object.\n        task (str): The type of model task.\n        ckpt (Any): The checkpoint object if the model loaded from *.pt file.\n        cfg (str): The model configuration if loaded from *.yaml file.\n        ckpt_path (str): The checkpoint file path.\n        overrides (dict): Overrides for the trainer object.\n        metrics (Any): The data for metrics.\n\n    Methods:\n        __call__(source=None, stream=False, **kwargs):\n            Alias for the predict method.\n        _new(cfg:str, verbose:bool=True) -> None:\n            Initializes a new model and infers the task type from the model definitions.\n        _load(weights:str, task:str='') -> None:\n            Initializes a new model and infers the task type from the model head.\n        _check_is_pytorch_model() -> None:\n            Raises TypeError if the model is not a PyTorch model.\n        reset() -> None:\n            Resets the model modules.\n        info(verbose:bool=False) -> None:\n            Logs the model info.\n        fuse() -> None:\n            Fuses the model for faster inference.\n        predict(source=None, stream=False, **kwargs) -> List[ultralytics.yolo.engine.results.Results]:\n            Performs prediction using the YOLO model.\n\n    Returns:\n        list(ultralytics.yolo.engine.results.Results): The prediction results.\n    \"\"\"\n\n    def __init__(self, model: Union[str, Path] = 'yolov8n.pt', task=None) -> None:\n        \"\"\"\n        Initializes the YOLO model.\n\n        Args:\n            model (Union[str, Path], optional): Path or name of the model to load or create. Defaults to 'yolov8n.pt'.\n            task (Any, optional): Task type for the YOLO model. Defaults to None.\n        \"\"\"\n        self.callbacks = callbacks.get_default_callbacks()\n        self.predictor = None  # reuse predictor\n        self.model = None  # model object\n        self.trainer = None  # trainer object\n        self.task = None  # task type\n        self.ckpt = None  # if loaded from *.pt\n        self.cfg = None  # if loaded from *.yaml\n        self.ckpt_path = None\n        self.overrides = {}  # overrides for trainer object\n        self.metrics = None  # validation/training metrics\n        self.session = None  # HUB session\n        model = str(model).strip()  # strip spaces\n\n        # Check if Ultralytics HUB model from https://hub.ultralytics.com\n        if self.is_hub_model(model):\n            from ultralytics.hub.session import HUBTrainingSession\n            self.session = HUBTrainingSession(model)\n            model = self.session.model_file\n\n        # Load or create new YOLO model\n        suffix = Path(model).suffix\n        if not suffix and Path(model).stem in GITHUB_ASSET_STEMS:\n            model, suffix = Path(model).with_suffix('.pt'), '.pt'  # add suffix, i.e. yolov8n -> yolov8n.pt\n        if suffix == '.yaml':\n            self._new(model, task)\n        else:\n            self._load(model, task)\n\n    def __call__(self, source=None, stream=False, **kwargs):\n        \"\"\"Calls the 'predict' function with given arguments to perform object detection.\"\"\"\n        return self.predict(source, stream, **kwargs)\n\n    def __getattr__(self, attr):\n        \"\"\"Raises error if object has no requested attribute.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n\n    @staticmethod\n    def is_hub_model(model):\n        \"\"\"Check if the provided model is a HUB model.\"\"\"\n        return any((\n            model.startswith('https://hub.ultralytics.com/models/'),  # i.e. https://hub.ultralytics.com/models/MODEL_ID\n            [len(x) for x in model.split('_')] == [42, 20],  # APIKEY_MODELID\n            len(model) == 20 and not Path(model).exists() and all(x not in model for x in './\\\\')))  # MODELID\n\n    def _new(self, cfg: str, task=None, verbose=True):\n        \"\"\"\n        Initializes a new model and infers the task type from the model definitions.\n\n        Args:\n            cfg (str): model configuration file\n            task (str | None): model task\n            verbose (bool): display model info on load\n        \"\"\"\n        cfg_dict = yaml_model_load(cfg)\n        self.cfg = cfg\n        self.task = task or guess_model_task(cfg_dict)\n        self.model = TASK_MAP[self.task][0](cfg_dict, verbose=verbose and RANK == -1)  # build model\n        self.overrides['model'] = self.cfg\n\n        # Below added to allow export from yamls\n        args = {**DEFAULT_CFG_DICT, **self.overrides}  # combine model and default args, preferring model args\n        self.model.args = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS}  # attach args to model\n        self.model.task = self.task\n\n    def _load(self, weights: str, task=None):\n        \"\"\"\n        Initializes a new model and infers the task type from the model head.\n\n        Args:\n            weights (str): model checkpoint to be loaded\n            task (str | None): model task\n        \"\"\"\n        suffix = Path(weights).suffix\n        if suffix == '.pt':\n            self.model, self.ckpt = attempt_load_one_weight(weights)\n            self.task = self.model.args['task']\n            self.overrides = self.model.args = self._reset_ckpt_args(self.model.args)\n            self.ckpt_path = self.model.pt_path\n        else:\n            weights = check_file(weights)\n            self.model, self.ckpt = weights, None\n            self.task = task or guess_model_task(weights)\n            self.ckpt_path = weights\n        self.overrides['model'] = weights\n        self.overrides['task'] = self.task\n\n    def _check_is_pytorch_model(self):\n        \"\"\"\n        Raises TypeError is model is not a PyTorch model\n        \"\"\"\n        pt_str = isinstance(self.model, (str, Path)) and Path(self.model).suffix == '.pt'\n        pt_module = isinstance(self.model, nn.Module)\n        if not (pt_module or pt_str):\n            raise TypeError(f\"model='{self.model}' must be a *.pt PyTorch model, but is a different type. \"\n                            f'PyTorch models can be used to train, val, predict and export, i.e. '\n                            f\"'yolo export model=yolov8n.pt', but exported formats like ONNX, TensorRT etc. only \"\n                            f\"support 'predict' and 'val' modes, i.e. 'yolo predict model=yolov8n.onnx'.\")\n\n    @smart_inference_mode()\n    def reset_weights(self):\n        \"\"\"\n        Resets the model modules parameters to randomly initialized values, losing all training information.\n        \"\"\"\n        self._check_is_pytorch_model()\n        for m in self.model.modules():\n            if hasattr(m, 'reset_parameters'):\n                m.reset_parameters()\n        for p in self.model.parameters():\n            p.requires_grad = True\n        return self\n\n    @smart_inference_mode()\n    def load(self, weights='yolov8n.pt'):\n        \"\"\"\n        Transfers parameters with matching names and shapes from 'weights' to model.\n        \"\"\"\n        self._check_is_pytorch_model()\n        if isinstance(weights, (str, Path)):\n            weights, self.ckpt = attempt_load_one_weight(weights)\n        self.model.load(weights)\n        return self\n\n    def info(self, detailed=False, verbose=True):\n        \"\"\"\n        Logs model info.\n\n        Args:\n            detailed (bool): Show detailed information about model.\n            verbose (bool): Controls verbosity.\n        \"\"\"\n        self._check_is_pytorch_model()\n        return self.model.info(detailed=detailed, verbose=verbose)\n\n    def fuse(self):\n        \"\"\"Fuse PyTorch Conv2d and BatchNorm2d layers.\"\"\"\n        self._check_is_pytorch_model()\n        self.model.fuse()\n\n    @smart_inference_mode()\n    def predict(self, source=None, stream=False, **kwargs):\n        \"\"\"\n        Perform prediction using the YOLO model.\n\n        Args:\n            source (str | int | PIL | np.ndarray): The source of the image to make predictions on.\n                          Accepts all source types accepted by the YOLO model.\n            stream (bool): Whether to stream the predictions or not. Defaults to False.\n            **kwargs : Additional keyword arguments passed to the predictor.\n                       Check the 'configuration' section in the documentation for all available options.\n\n        Returns:\n            (List[ultralytics.yolo.engine.results.Results]): The prediction results.\n        \"\"\"\n        if source is None:\n            source = ROOT / 'assets' if is_git_dir() else 'https://ultralytics.com/images/bus.jpg'\n            LOGGER.warning(f\"WARNING ⚠️ 'source' is missing. Using 'source={source}'.\")\n        is_cli = (sys.argv[0].endswith('yolo') or sys.argv[0].endswith('ultralytics')) and any(\n            x in sys.argv for x in ('predict', 'track', 'mode=predict', 'mode=track'))\n        overrides = self.overrides.copy()\n        overrides['conf'] = 0.25\n        overrides.update(kwargs)  # prefer kwargs\n        overrides['mode'] = kwargs.get('mode', 'predict')\n        assert overrides['mode'] in ['track', 'predict']\n        if not is_cli:\n            overrides['save'] = kwargs.get('save', False)  # do not save by default if called in Python\n        if not self.predictor:\n            self.task = overrides.get('task') or self.task\n            self.predictor = TASK_MAP[self.task][3](overrides=overrides, _callbacks=self.callbacks)\n            self.predictor.setup_model(model=self.model, verbose=is_cli)\n        else:  # only update args if predictor is already setup\n            self.predictor.args = get_cfg(self.predictor.args, overrides)\n            if 'project' in overrides or 'name' in overrides:\n                self.predictor.save_dir = self.predictor.get_save_dir()\n        return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream)\n\n    def track(self, source=None, stream=False, persist=False, **kwargs):\n        \"\"\"\n        Perform object tracking on the input source using the registered trackers.\n\n        Args:\n            source (str, optional): The input source for object tracking. Can be a file path or a video stream.\n            stream (bool, optional): Whether the input source is a video stream. Defaults to False.\n            persist (bool, optional): Whether to persist the trackers if they already exist. Defaults to False.\n            **kwargs (optional): Additional keyword arguments for the tracking process.\n\n        Returns:\n            (List[ultralytics.yolo.engine.results.Results]): The tracking results.\n\n        \"\"\"\n        if not hasattr(self.predictor, 'trackers'):\n            from ultralytics.tracker import register_tracker\n            register_tracker(self, persist)\n        # ByteTrack-based method needs low confidence predictions as input\n        conf = kwargs.get('conf') or 0.1\n        kwargs['conf'] = conf\n        kwargs['mode'] = 'track'\n        return self.predict(source=source, stream=stream, **kwargs)\n\n    @smart_inference_mode()\n    def val(self, data=None, **kwargs):\n        \"\"\"\n        Validate a model on a given dataset.\n\n        Args:\n            data (str): The dataset to validate on. Accepts all formats accepted by yolo\n            **kwargs : Any other args accepted by the validators. To see all args check 'configuration' section in docs\n        \"\"\"\n        overrides = self.overrides.copy()\n        overrides['rect'] = True  # rect batches as default\n        overrides.update(kwargs)\n        overrides['mode'] = 'val'\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.data = data or args.data\n        if 'task' in overrides:\n            self.task = args.task\n        else:\n            args.task = self.task\n        if args.imgsz == DEFAULT_CFG.imgsz and not isinstance(self.model, (str, Path)):\n            args.imgsz = self.model.args['imgsz']  # use trained imgsz unless custom value is passed\n        args.imgsz = check_imgsz(args.imgsz, max_dim=1)\n\n        validator = TASK_MAP[self.task][2](args=args, _callbacks=self.callbacks)\n        validator(model=self.model)\n        self.metrics = validator.metrics\n\n        return validator.metrics\n\n    @smart_inference_mode()\n    def benchmark(self, **kwargs):\n        \"\"\"\n        Benchmark a model on all export formats.\n\n        Args:\n            **kwargs : Any other args accepted by the validators. To see all args check 'configuration' section in docs\n        \"\"\"\n        self._check_is_pytorch_model()\n        from ultralytics.yolo.utils.benchmarks import benchmark\n        overrides = self.model.args.copy()\n        overrides.update(kwargs)\n        overrides['mode'] = 'benchmark'\n        overrides = {**DEFAULT_CFG_DICT, **overrides}  # fill in missing overrides keys with defaults\n        return benchmark(model=self, imgsz=overrides['imgsz'], half=overrides['half'], device=overrides['device'])\n\n    def export(self, **kwargs):\n        \"\"\"\n        Export model.\n\n        Args:\n            **kwargs : Any other args accepted by the predictors. To see all args check 'configuration' section in docs\n        \"\"\"\n        self._check_is_pytorch_model()\n        overrides = self.overrides.copy()\n        overrides.update(kwargs)\n        overrides['mode'] = 'export'\n        if overrides.get('imgsz') is None:\n            overrides['imgsz'] = self.model.args['imgsz']  # use trained imgsz unless custom value is passed\n        if 'batch' not in kwargs:\n            overrides['batch'] = 1  # default to 1 if not modified\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.task = self.task\n        return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model)\n\n    def train(self, **kwargs):\n        \"\"\"\n        Trains the model on a given dataset.\n\n        Args:\n            **kwargs (Any): Any number of arguments representing the training configuration.\n        \"\"\"\n        self._check_is_pytorch_model()\n        if self.session:  # Ultralytics HUB session\n            if any(kwargs):\n                LOGGER.warning('WARNING ⚠️ using HUB training arguments, ignoring local training arguments.')\n            kwargs = self.session.train_args\n        check_pip_update_available()\n        overrides = self.overrides.copy()\n        if kwargs.get('cfg'):\n            LOGGER.info(f\"cfg file passed. Overriding default params with {kwargs['cfg']}.\")\n            overrides = yaml_load(check_yaml(kwargs['cfg']))\n        overrides.update(kwargs)\n        overrides['mode'] = 'train'\n        if not overrides.get('data'):\n            raise AttributeError(\"Dataset required but missing, i.e. pass 'data=coco128.yaml'\")\n        if overrides.get('resume'):\n            overrides['resume'] = self.ckpt_path\n        self.task = overrides.get('task') or self.task\n        self.trainer = TASK_MAP[self.task][1](overrides=overrides, _callbacks=self.callbacks)\n        if not overrides.get('resume'):  # manually set model only if not resuming\n            self.trainer.model = self.trainer.get_model(weights=self.model if self.ckpt else None, cfg=self.model.yaml)\n            self.model = self.trainer.model\n        self.trainer.hub_session = self.session  # attach optional HUB session\n        self.trainer.train()\n        # Update model and cfg after training\n        if RANK in (-1, 0):\n            self.model, _ = attempt_load_one_weight(str(self.trainer.best))\n            self.overrides = self.model.args\n            self.metrics = getattr(self.trainer.validator, 'metrics', None)  # TODO: no metrics returned by DDP\n\n    def to(self, device):\n        \"\"\"\n        Sends the model to the given device.\n\n        Args:\n            device (str): device\n        \"\"\"\n        self._check_is_pytorch_model()\n        self.model.to(device)\n\n    def tune(self,\n             data: str,\n             space: dict = None,\n             grace_period: int = 10,\n             gpu_per_trial: int = None,\n             max_samples: int = 10,\n             train_args: dict = None):\n        \"\"\"\n        Runs hyperparameter tuning using Ray Tune.\n\n        Args:\n            data (str): The dataset to run the tuner on.\n            space (dict, optional): The hyperparameter search space. Defaults to None.\n            grace_period (int, optional): The grace period in epochs of the ASHA scheduler. Defaults to 10.\n            gpu_per_trial (int, optional): The number of GPUs to allocate per trial. Defaults to None.\n            max_samples (int, optional): The maximum number of trials to run. Defaults to 10.\n            train_args (dict, optional): Additional arguments to pass to the `train()` method. Defaults to {}.\n\n        Returns:\n            (dict): A dictionary containing the results of the hyperparameter search.\n\n        Raises:\n            ModuleNotFoundError: If Ray Tune is not installed.\n        \"\"\"\n        if train_args is None:\n            train_args = {}\n\n        try:\n            from ultralytics.yolo.utils.tuner import (ASHAScheduler, RunConfig, WandbLoggerCallback, default_space,\n                                                      task_metric_map, tune)\n        except ImportError:\n            raise ModuleNotFoundError(\"Install Ray Tune: `pip install 'ray[tune]'`\")\n\n        try:\n            import wandb\n            from wandb import __version__  # noqa\n        except ImportError:\n            wandb = False\n\n        def _tune(config):\n            \"\"\"\n            Trains the YOLO model with the specified hyperparameters and additional arguments.\n\n            Args:\n                config (dict): A dictionary of hyperparameters to use for training.\n\n            Returns:\n                None.\n            \"\"\"\n            self._reset_callbacks()\n            config.update(train_args)\n            self.train(**config)\n\n        if not space:\n            LOGGER.warning('WARNING: search space not provided. Using default search space')\n            space = default_space\n\n        space['data'] = data\n\n        # Define the trainable function with allocated resources\n        trainable_with_resources = tune.with_resources(_tune, {'cpu': NUM_THREADS, 'gpu': gpu_per_trial or 0})\n\n        # Define the ASHA scheduler for hyperparameter search\n        asha_scheduler = ASHAScheduler(time_attr='epoch',\n                                       metric=task_metric_map[self.task],\n                                       mode='max',\n                                       max_t=train_args.get('epochs') or 100,\n                                       grace_period=grace_period,\n                                       reduction_factor=3)\n\n        # Define the callbacks for the hyperparameter search\n        tuner_callbacks = [WandbLoggerCallback(project='YOLOv8-tune')] if wandb else []\n\n        # Create the Ray Tune hyperparameter search tuner\n        tuner = tune.Tuner(trainable_with_resources,\n                           param_space=space,\n                           tune_config=tune.TuneConfig(scheduler=asha_scheduler, num_samples=max_samples),\n                           run_config=RunConfig(callbacks=tuner_callbacks, local_dir='./runs'))\n\n        # Run the hyperparameter search\n        tuner.fit()\n\n        # Return the results of the hyperparameter search\n        return tuner.get_results()\n\n    @property\n    def names(self):\n        \"\"\"Returns class names of the loaded model.\"\"\"\n        return self.model.names if hasattr(self.model, 'names') else None\n\n    @property\n    def device(self):\n        \"\"\"Returns device if PyTorch model.\"\"\"\n        return next(self.model.parameters()).device if isinstance(self.model, nn.Module) else None\n\n    @property\n    def transforms(self):\n        \"\"\"Returns transform of the loaded model.\"\"\"\n        return self.model.transforms if hasattr(self.model, 'transforms') else None\n\n    def add_callback(self, event: str, func):\n        \"\"\"Add a callback.\"\"\"\n        self.callbacks[event].append(func)\n\n    def clear_callback(self, event: str):\n        \"\"\"Clear all event callbacks.\"\"\"\n        self.callbacks[event] = []\n\n    @staticmethod\n    def _reset_ckpt_args(args):\n        \"\"\"Reset arguments when loading a PyTorch model.\"\"\"\n        include = {'imgsz', 'data', 'task', 'single_cls'}  # only remember these arguments when loading a PyTorch model\n        return {k: v for k, v in args.items() if k in include}\n\n    def _reset_callbacks(self):\n        \"\"\"Reset all registered callbacks.\"\"\"\n        for event in callbacks.default_callbacks.keys():\n            self.callbacks[event] = [callbacks.default_callbacks[event][0]]\n"
  },
  {
    "path": "ultralytics/yolo/engine/predictor.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nRun prediction on images, videos, directories, globs, YouTube, webcam, streams, etc.\n\nUsage - sources:\n    $ yolo mode=predict model=yolov8n.pt source=0                               # webcam\n                                                img.jpg                         # image\n                                                vid.mp4                         # video\n                                                screen                          # screenshot\n                                                path/                           # directory\n                                                list.txt                        # list of images\n                                                list.streams                    # list of streams\n                                                'path/*.jpg'                    # glob\n                                                'https://youtu.be/Zgi9g1ksQHc'  # YouTube\n                                                'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream\n\nUsage - formats:\n    $ yolo mode=predict model=yolov8n.pt                 # PyTorch\n                              yolov8n.torchscript        # TorchScript\n                              yolov8n.onnx               # ONNX Runtime or OpenCV DNN with dnn=True\n                              yolov8n_openvino_model     # OpenVINO\n                              yolov8n.engine             # TensorRT\n                              yolov8n.mlmodel            # CoreML (macOS-only)\n                              yolov8n_saved_model        # TensorFlow SavedModel\n                              yolov8n.pb                 # TensorFlow GraphDef\n                              yolov8n.tflite             # TensorFlow Lite\n                              yolov8n_edgetpu.tflite     # TensorFlow Edge TPU\n                              yolov8n_paddle_model       # PaddlePaddle\n\"\"\"\nimport platform\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport torch\n\nfrom ultralytics.nn.autobackend import AutoBackend\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.data import load_inference_source\nfrom ultralytics.yolo.data.augment import LetterBox, classify_transforms\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, SETTINGS, callbacks, colorstr, ops\nfrom ultralytics.yolo.utils.checks import check_imgsz, check_imshow\nfrom ultralytics.yolo.utils.files import increment_path\nfrom ultralytics.yolo.utils.torch_utils import select_device, smart_inference_mode\n\nSTREAM_WARNING = \"\"\"\n    WARNING ⚠️ stream/video/webcam/dir predict source will accumulate results in RAM unless `stream=True` is passed,\n    causing potential out-of-memory errors for large sources or long-running streams/videos.\n\n    Usage:\n        results = model(source=..., stream=True)  # generator of Results objects\n        for r in results:\n            boxes = r.boxes  # Boxes object for bbox outputs\n            masks = r.masks  # Masks object for segment masks outputs\n            probs = r.probs  # Class probabilities for classification outputs\n\"\"\"\n\n\nclass BasePredictor:\n    \"\"\"\n    BasePredictor\n\n    A base class for creating predictors.\n\n    Attributes:\n        args (SimpleNamespace): Configuration for the predictor.\n        save_dir (Path): Directory to save results.\n        done_warmup (bool): Whether the predictor has finished setup.\n        model (nn.Module): Model used for prediction.\n        data (dict): Data configuration.\n        device (torch.device): Device used for prediction.\n        dataset (Dataset): Dataset used for prediction.\n        vid_path (str): Path to video file.\n        vid_writer (cv2.VideoWriter): Video writer for saving video output.\n        data_path (str): Path to data.\n    \"\"\"\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"\n        Initializes the BasePredictor class.\n\n        Args:\n            cfg (str, optional): Path to a configuration file. Defaults to DEFAULT_CFG.\n            overrides (dict, optional): Configuration overrides. Defaults to None.\n        \"\"\"\n        self.args = get_cfg(cfg, overrides)\n        self.save_dir = self.get_save_dir()\n        if self.args.conf is None:\n            self.args.conf = 0.25  # default conf=0.25\n        self.done_warmup = False\n        if self.args.show:\n            self.args.show = check_imshow(warn=True)\n\n        # Usable if setup is done\n        self.model = None\n        self.data = self.args.data  # data_dict\n        self.imgsz = None\n        self.device = None\n        self.dataset = None\n        self.vid_path, self.vid_writer = None, None\n        self.plotted_img = None\n        self.data_path = None\n        self.source_type = None\n        self.batch = None\n        self.results = None\n        self.transforms = None\n        self.callbacks = _callbacks or callbacks.get_default_callbacks()\n        callbacks.add_integration_callbacks(self)\n\n    def get_save_dir(self):\n        project = self.args.project or Path(SETTINGS['runs_dir']) / self.args.task\n        name = self.args.name or f'{self.args.mode}'\n        return increment_path(Path(project) / name, exist_ok=self.args.exist_ok)\n\n    def preprocess(self, im):\n        \"\"\"Prepares input image before inference.\n\n        Args:\n            im (torch.Tensor | List(np.ndarray)): (N, 3, h, w) for tensor, [(h, w, 3) x N] for list.\n        \"\"\"\n        if not isinstance(im, torch.Tensor):\n            im = np.stack(self.pre_transform(im))\n            im = im[..., ::-1].transpose((0, 3, 1, 2))  # BGR to RGB, BHWC to BCHW, (n, 3, h, w)\n            im = np.ascontiguousarray(im)  # contiguous\n            im = torch.from_numpy(im)\n        # NOTE: assuming im with (b, 3, h, w) if it's a tensor\n        img = im.to(self.device)\n        img = img.half() if self.model.fp16 else img.float()  # uint8 to fp16/32\n        img /= 255  # 0 - 255 to 0.0 - 1.0\n        return img\n\n    def pre_transform(self, im):\n        \"\"\"Pre-tranform input image before inference.\n\n        Args:\n            im (List(np.ndarray)): (N, 3, h, w) for tensor, [(h, w, 3) x N] for list.\n\n        Return: A list of transformed imgs.\n        \"\"\"\n        same_shapes = all(x.shape == im[0].shape for x in im)\n        auto = same_shapes and self.model.pt\n        return [LetterBox(self.imgsz, auto=auto, stride=self.model.stride)(image=x) for x in im]\n\n    def write_results(self, idx, results, batch):\n        \"\"\"Write inference results to a file or directory.\"\"\"\n        p, im, _ = batch\n        log_string = ''\n        if len(im.shape) == 3:\n            im = im[None]  # expand for batch dim\n        self.seen += 1\n        if self.source_type.webcam or self.source_type.from_img:  # batch_size >= 1\n            log_string += f'{idx}: '\n            frame = self.dataset.count\n        else:\n            frame = getattr(self.dataset, 'frame', 0)\n        self.data_path = p\n        self.txt_path = str(self.save_dir / 'labels' / p.stem) + ('' if self.dataset.mode == 'image' else f'_{frame}')\n        log_string += '%gx%g ' % im.shape[2:]  # print string\n        result = results[idx]\n        log_string += result.verbose()\n\n        if self.args.save or self.args.show:  # Add bbox to image\n            plot_args = dict(line_width=self.args.line_width,\n                             boxes=self.args.boxes,\n                             conf=self.args.show_conf,\n                             labels=self.args.show_labels)\n            if not self.args.retina_masks:\n                plot_args['im_gpu'] = im[idx]\n            self.plotted_img = result.plot(**plot_args)\n        # Write\n        if self.args.save_txt:\n            result.save_txt(f'{self.txt_path}.txt', save_conf=self.args.save_conf)\n        if self.args.save_crop:\n            result.save_crop(save_dir=self.save_dir / 'crops', file_name=self.data_path.stem)\n\n        return log_string\n\n    def postprocess(self, preds, img, orig_imgs):\n        \"\"\"Post-processes predictions for an image and returns them.\"\"\"\n        return preds\n\n    def __call__(self, source=None, model=None, stream=False):\n        \"\"\"Performs inference on an image or stream.\"\"\"\n        self.stream = stream\n        if stream:\n            return self.stream_inference(source, model)\n        else:\n            return list(self.stream_inference(source, model))  # merge list of Result into one\n\n    def predict_cli(self, source=None, model=None):\n        \"\"\"Method used for CLI prediction. It uses always generator as outputs as not required by CLI mode.\"\"\"\n        gen = self.stream_inference(source, model)\n        for _ in gen:  # running CLI inference without accumulating any outputs (do not modify)\n            pass\n\n    def setup_source(self, source):\n        \"\"\"Sets up source and inference mode.\"\"\"\n        self.imgsz = check_imgsz(self.args.imgsz, stride=self.model.stride, min_dim=2)  # check image size\n        self.transforms = getattr(self.model.model, 'transforms', classify_transforms(\n            self.imgsz[0])) if self.args.task == 'classify' else None\n        self.dataset = load_inference_source(source=source, imgsz=self.imgsz, vid_stride=self.args.vid_stride)\n        self.source_type = self.dataset.source_type\n        if not getattr(self, 'stream', True) and (self.dataset.mode == 'stream' or  # streams\n                                                  len(self.dataset) > 1000 or  # images\n                                                  any(getattr(self.dataset, 'video_flag', [False]))):  # videos\n            LOGGER.warning(STREAM_WARNING)\n        self.vid_path, self.vid_writer = [None] * self.dataset.bs, [None] * self.dataset.bs\n\n    @smart_inference_mode()\n    def stream_inference(self, source=None, model=None):\n        \"\"\"Streams real-time inference on camera feed and saves results to file.\"\"\"\n        if self.args.verbose:\n            LOGGER.info('')\n\n        # Setup model\n        if not self.model:\n            self.setup_model(model)\n        # Setup source every time predict is called\n        self.setup_source(source if source is not None else self.args.source)\n\n        # Check if save_dir/ label file exists\n        if self.args.save or self.args.save_txt:\n            (self.save_dir / 'labels' if self.args.save_txt else self.save_dir).mkdir(parents=True, exist_ok=True)\n        # Warmup model\n        if not self.done_warmup:\n            self.model.warmup(imgsz=(1 if self.model.pt or self.model.triton else self.dataset.bs, 3, *self.imgsz))\n            self.done_warmup = True\n\n        self.seen, self.windows, self.batch, profilers = 0, [], None, (ops.Profile(), ops.Profile(), ops.Profile())\n        self.run_callbacks('on_predict_start')\n        for batch in self.dataset:\n            self.run_callbacks('on_predict_batch_start')\n            self.batch = batch\n            path, im0s, vid_cap, s = batch\n            visualize = increment_path(self.save_dir / Path(path[0]).stem,\n                                       mkdir=True) if self.args.visualize and (not self.source_type.tensor) else False\n\n            # Preprocess\n            with profilers[0]:\n                im = self.preprocess(im0s)\n\n            # Inference\n            with profilers[1]:\n                preds = self.model(im, augment=self.args.augment, visualize=visualize)\n\n            # Postprocess\n            with profilers[2]:\n                self.results = self.postprocess(preds, im, im0s)\n            self.run_callbacks('on_predict_postprocess_end')\n\n            # Visualize, save, write results\n            n = len(im0s)\n            for i in range(n):\n                self.results[i].speed = {\n                    'preprocess': profilers[0].dt * 1E3 / n,\n                    'inference': profilers[1].dt * 1E3 / n,\n                    'postprocess': profilers[2].dt * 1E3 / n}\n                if self.source_type.tensor:  # skip write, show and plot operations if input is raw tensor\n                    continue\n                p, im0 = path[i], im0s[i].copy()\n                p = Path(p)\n\n                if self.args.verbose or self.args.save or self.args.save_txt or self.args.show:\n                    s += self.write_results(i, self.results, (p, im, im0))\n                if self.args.save or self.args.save_txt:\n                    self.results[i].save_dir = self.save_dir.__str__()\n                if self.args.show and self.plotted_img is not None:\n                    self.show(p)\n                if self.args.save and self.plotted_img is not None:\n                    self.save_preds(vid_cap, i, str(self.save_dir / p.name))\n\n            self.run_callbacks('on_predict_batch_end')\n            yield from self.results\n\n            # Print time (inference-only)\n            if self.args.verbose:\n                LOGGER.info(f'{s}{profilers[1].dt * 1E3:.1f}ms')\n\n        # Release assets\n        if isinstance(self.vid_writer[-1], cv2.VideoWriter):\n            self.vid_writer[-1].release()  # release final video writer\n\n        # Print results\n        if self.args.verbose and self.seen:\n            t = tuple(x.t / self.seen * 1E3 for x in profilers)  # speeds per image\n            LOGGER.info(f'Speed: %.1fms preprocess, %.1fms inference, %.1fms postprocess per image at shape '\n                        f'{(1, 3, *self.imgsz)}' % t)\n        if self.args.save or self.args.save_txt or self.args.save_crop:\n            nl = len(list(self.save_dir.glob('labels/*.txt')))  # number of labels\n            s = f\"\\n{nl} label{'s' * (nl > 1)} saved to {self.save_dir / 'labels'}\" if self.args.save_txt else ''\n            LOGGER.info(f\"Results saved to {colorstr('bold', self.save_dir)}{s}\")\n\n        self.run_callbacks('on_predict_end')\n\n    def setup_model(self, model, verbose=True):\n        \"\"\"Initialize YOLO model with given parameters and set it to evaluation mode.\"\"\"\n        device = select_device(self.args.device, verbose=verbose)\n        model = model or self.args.model\n        self.args.half &= device.type != 'cpu'  # half precision only supported on CUDA\n        self.model = AutoBackend(model,\n                                 device=device,\n                                 dnn=self.args.dnn,\n                                 data=self.args.data,\n                                 fp16=self.args.half,\n                                 fuse=True,\n                                 verbose=verbose)\n        self.device = device\n        self.model.eval()\n\n    def show(self, p):\n        \"\"\"Display an image in a window using OpenCV imshow().\"\"\"\n        im0 = self.plotted_img\n        if platform.system() == 'Linux' and p not in self.windows:\n            self.windows.append(p)\n            cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)\n            cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])\n        cv2.imshow(str(p), im0)\n        cv2.waitKey(500 if self.batch[3].startswith('image') else 1)  # 1 millisecond\n\n    def save_preds(self, vid_cap, idx, save_path):\n        \"\"\"Save video predictions as mp4 at specified path.\"\"\"\n        im0 = self.plotted_img\n        # Save imgs\n        if self.dataset.mode == 'image':\n            cv2.imwrite(save_path, im0)\n        else:  # 'video' or 'stream'\n            if self.vid_path[idx] != save_path:  # new video\n                self.vid_path[idx] = save_path\n                if isinstance(self.vid_writer[idx], cv2.VideoWriter):\n                    self.vid_writer[idx].release()  # release previous video writer\n                if vid_cap:  # video\n                    fps = int(vid_cap.get(cv2.CAP_PROP_FPS))  # integer required, floats produce error in MP4 codec\n                    w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n                    h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n                else:  # stream\n                    fps, w, h = 30, im0.shape[1], im0.shape[0]\n                save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos\n                self.vid_writer[idx] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))\n            self.vid_writer[idx].write(im0)\n\n    def run_callbacks(self, event: str):\n        \"\"\"Runs all registered callbacks for a specific event.\"\"\"\n        for callback in self.callbacks.get(event, []):\n            callback(self)\n\n    def add_callback(self, event: str, func):\n        \"\"\"\n        Add callback\n        \"\"\"\n        self.callbacks[event].append(func)\n"
  },
  {
    "path": "ultralytics/yolo/engine/results.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nUltralytics Results, Boxes and Masks classes for handling inference results\n\nUsage: See https://docs.ultralytics.com/modes/predict/\n\"\"\"\n\nfrom copy import deepcopy\nfrom functools import lru_cache\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\n\nfrom ultralytics.yolo.data.augment import LetterBox\nfrom ultralytics.yolo.utils import LOGGER, SimpleClass, deprecation_warn, ops\nfrom ultralytics.yolo.utils.plotting import Annotator, colors, save_one_box\n\n\nclass BaseTensor(SimpleClass):\n    \"\"\"\n    Base tensor class with additional methods for easy manipulation and device handling.\n    \"\"\"\n\n    def __init__(self, data, orig_shape) -> None:\n        \"\"\"Initialize BaseTensor with data and original shape.\n\n        Args:\n            data (torch.Tensor | np.ndarray): Predictions, such as bboxes, masks and keypoints.\n            orig_shape (tuple): Original shape of image.\n        \"\"\"\n        assert isinstance(data, (torch.Tensor, np.ndarray))\n        self.data = data\n        self.orig_shape = orig_shape\n\n    @property\n    def shape(self):\n        \"\"\"Return the shape of the data tensor.\"\"\"\n        return self.data.shape\n\n    def cpu(self):\n        \"\"\"Return a copy of the tensor on CPU memory.\"\"\"\n        return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.cpu(), self.orig_shape)\n\n    def numpy(self):\n        \"\"\"Return a copy of the tensor as a numpy array.\"\"\"\n        return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.numpy(), self.orig_shape)\n\n    def cuda(self):\n        \"\"\"Return a copy of the tensor on GPU memory.\"\"\"\n        return self.__class__(torch.as_tensor(self.data).cuda(), self.orig_shape)\n\n    def to(self, *args, **kwargs):\n        \"\"\"Return a copy of the tensor with the specified device and dtype.\"\"\"\n        return self.__class__(torch.as_tensor(self.data).to(*args, **kwargs), self.orig_shape)\n\n    def __len__(self):  # override len(results)\n        \"\"\"Return the length of the data tensor.\"\"\"\n        return len(self.data)\n\n    def __getitem__(self, idx):\n        \"\"\"Return a BaseTensor with the specified index of the data tensor.\"\"\"\n        return self.__class__(self.data[idx], self.orig_shape)\n\n\nclass Results(SimpleClass):\n    \"\"\"\n    A class for storing and manipulating inference results.\n\n    Args:\n        orig_img (numpy.ndarray): The original image as a numpy array.\n        path (str): The path to the image file.\n        names (dict): A dictionary of class names.\n        boxes (torch.tensor, optional): A 2D tensor of bounding box coordinates for each detection.\n        masks (torch.tensor, optional): A 3D tensor of detection masks, where each mask is a binary image.\n        probs (torch.tensor, optional): A 1D tensor of probabilities of each class for classification task.\n        keypoints (List[List[float]], optional): A list of detected keypoints for each object.\n\n\n    Attributes:\n        orig_img (numpy.ndarray): The original image as a numpy array.\n        orig_shape (tuple): The original image shape in (height, width) format.\n        boxes (Boxes, optional): A Boxes object containing the detection bounding boxes.\n        masks (Masks, optional): A Masks object containing the detection masks.\n        probs (Probs, optional): A Probs object containing probabilities of each class for classification task.\n        names (dict): A dictionary of class names.\n        path (str): The path to the image file.\n        keypoints (Keypoints, optional): A Keypoints object containing detected keypoints for each object.\n        speed (dict): A dictionary of preprocess, inference and postprocess speeds in milliseconds per image.\n        _keys (tuple): A tuple of attribute names for non-empty attributes.\n    \"\"\"\n\n    def __init__(self, orig_img, path, names, boxes=None, masks=None, probs=None, keypoints=None) -> None:\n        \"\"\"Initialize the Results class.\"\"\"\n        self.orig_img = orig_img\n        self.orig_shape = orig_img.shape[:2]\n        self.boxes = Boxes(boxes, self.orig_shape) if boxes is not None else None  # native size boxes\n        self.masks = Masks(masks, self.orig_shape) if masks is not None else None  # native size or imgsz masks\n        self.probs = Probs(probs) if probs is not None else None\n        self.keypoints = Keypoints(keypoints, self.orig_shape) if keypoints is not None else None\n        self.speed = {'preprocess': None, 'inference': None, 'postprocess': None}  # milliseconds per image\n        self.names = names\n        self.path = path\n        self.save_dir = None\n        self._keys = ('boxes', 'masks', 'probs', 'keypoints')\n\n    def __getitem__(self, idx):\n        \"\"\"Return a Results object for the specified index.\"\"\"\n        r = self.new()\n        for k in self.keys:\n            setattr(r, k, getattr(self, k)[idx])\n        return r\n\n    def update(self, boxes=None, masks=None, probs=None):\n        \"\"\"Update the boxes, masks, and probs attributes of the Results object.\"\"\"\n        if boxes is not None:\n            self.boxes = Boxes(boxes, self.orig_shape)\n        if masks is not None:\n            self.masks = Masks(masks, self.orig_shape)\n        if probs is not None:\n            self.probs = probs\n\n    def cpu(self):\n        \"\"\"Return a copy of the Results object with all tensors on CPU memory.\"\"\"\n        r = self.new()\n        for k in self.keys:\n            setattr(r, k, getattr(self, k).cpu())\n        return r\n\n    def numpy(self):\n        \"\"\"Return a copy of the Results object with all tensors as numpy arrays.\"\"\"\n        r = self.new()\n        for k in self.keys:\n            setattr(r, k, getattr(self, k).numpy())\n        return r\n\n    def cuda(self):\n        \"\"\"Return a copy of the Results object with all tensors on GPU memory.\"\"\"\n        r = self.new()\n        for k in self.keys:\n            setattr(r, k, getattr(self, k).cuda())\n        return r\n\n    def to(self, *args, **kwargs):\n        \"\"\"Return a copy of the Results object with tensors on the specified device and dtype.\"\"\"\n        r = self.new()\n        for k in self.keys:\n            setattr(r, k, getattr(self, k).to(*args, **kwargs))\n        return r\n\n    def __len__(self):\n        \"\"\"Return the number of detections in the Results object.\"\"\"\n        for k in self.keys:\n            return len(getattr(self, k))\n\n    def new(self):\n        \"\"\"Return a new Results object with the same image, path, and names.\"\"\"\n        return Results(orig_img=self.orig_img, path=self.path, names=self.names)\n\n    @property\n    def keys(self):\n        \"\"\"Return a list of non-empty attribute names.\"\"\"\n        return [k for k in self._keys if getattr(self, k) is not None]\n\n    def plot(\n            self,\n            conf=True,\n            line_width=None,\n            font_size=None,\n            font='Arial.ttf',\n            pil=False,\n            img=None,\n            img_gpu=None,\n            kpt_line=True,\n            labels=True,\n            boxes=True,\n            masks=True,\n            probs=True,\n            **kwargs  # deprecated args TODO: remove support in 8.2\n    ):\n        \"\"\"\n        Plots the detection results on an input RGB image. Accepts a numpy array (cv2) or a PIL Image.\n\n        Args:\n            conf (bool): Whether to plot the detection confidence score.\n            line_width (float, optional): The line width of the bounding boxes. If None, it is scaled to the image size.\n            font_size (float, optional): The font size of the text. If None, it is scaled to the image size.\n            font (str): The font to use for the text.\n            pil (bool): Whether to return the image as a PIL Image.\n            img (numpy.ndarray): Plot to another image. if not, plot to original image.\n            img_gpu (torch.Tensor): Normalized image in gpu with shape (1, 3, 640, 640), for faster mask plotting.\n            kpt_line (bool): Whether to draw lines connecting keypoints.\n            labels (bool): Whether to plot the label of bounding boxes.\n            boxes (bool): Whether to plot the bounding boxes.\n            masks (bool): Whether to plot the masks.\n            probs (bool): Whether to plot classification probability\n\n        Returns:\n            (numpy.ndarray): A numpy array of the annotated image.\n        \"\"\"\n        # Deprecation warn TODO: remove in 8.2\n        if 'show_conf' in kwargs:\n            deprecation_warn('show_conf', 'conf')\n            conf = kwargs['show_conf']\n            assert type(conf) == bool, '`show_conf` should be of boolean type, i.e, show_conf=True/False'\n\n        if 'line_thickness' in kwargs:\n            deprecation_warn('line_thickness', 'line_width')\n            line_width = kwargs['line_thickness']\n            assert type(line_width) == int, '`line_width` should be of int type, i.e, line_width=3'\n\n        names = self.names\n        annotator = Annotator(deepcopy(self.orig_img if img is None else img),\n                              line_width,\n                              font_size,\n                              font,\n                              pil,\n                              example=names)\n        pred_boxes, show_boxes = self.boxes, boxes\n        pred_masks, show_masks = self.masks, masks\n        pred_probs, show_probs = self.probs, probs\n        keypoints = self.keypoints\n        if pred_masks and show_masks:\n            if img_gpu is None:\n                img = LetterBox(pred_masks.shape[1:])(image=annotator.result())\n                img_gpu = torch.as_tensor(img, dtype=torch.float16, device=pred_masks.data.device).permute(\n                    2, 0, 1).flip(0).contiguous() / 255\n            idx = pred_boxes.cls if pred_boxes else range(len(pred_masks))\n            annotator.masks(pred_masks.data, colors=[colors(x, True) for x in idx], im_gpu=img_gpu)\n\n        if pred_boxes and show_boxes:\n            for d in reversed(pred_boxes):\n                c, conf, id = int(d.cls), float(d.conf) if conf else None, None if d.id is None else int(d.id.item())\n                name = ('' if id is None else f'id:{id} ') + names[c]\n                label = (f'{name} {conf:.2f}' if conf else name) if labels else None\n                annotator.box_label(d.xyxy.squeeze(), label, color=colors(c, True))\n\n        if pred_probs is not None and show_probs:\n            text = f\"{', '.join(f'{names[j] if names else j} {pred_probs.data[j]:.2f}' for j in pred_probs.top5)}, \"\n            annotator.text((32, 32), text, txt_color=(255, 255, 255))  # TODO: allow setting colors\n\n        if keypoints is not None:\n            for k in reversed(keypoints.data):\n                annotator.kpts(k, self.orig_shape, kpt_line=kpt_line)\n\n        return annotator.result()\n\n    def verbose(self):\n        \"\"\"\n        Return log string for each task.\n        \"\"\"\n        log_string = ''\n        probs = self.probs\n        boxes = self.boxes\n        if len(self) == 0:\n            return log_string if probs is not None else f'{log_string}(no detections), '\n        if probs is not None:\n            log_string += f\"{', '.join(f'{self.names[j]} {probs.data[j]:.2f}' for j in probs.top5)}, \"\n        if boxes:\n            for c in boxes.cls.unique():\n                n = (boxes.cls == c).sum()  # detections per class\n                log_string += f\"{n} {self.names[int(c)]}{'s' * (n > 1)}, \"\n        return log_string\n\n    def save_txt(self, txt_file, save_conf=False):\n        \"\"\"\n        Save predictions into txt file.\n\n        Args:\n            txt_file (str): txt file path.\n            save_conf (bool): save confidence score or not.\n        \"\"\"\n        boxes = self.boxes\n        masks = self.masks\n        probs = self.probs\n        kpts = self.keypoints\n        texts = []\n        if probs is not None:\n            # Classify\n            [texts.append(f'{probs.data[j]:.2f} {self.names[j]}') for j in probs.top5]\n        elif boxes:\n            # Detect/segment/pose\n            for j, d in enumerate(boxes):\n                c, conf, id = int(d.cls), float(d.conf), None if d.id is None else int(d.id.item())\n                line = (c, *d.xywhn.view(-1))\n                if masks:\n                    seg = masks[j].xyn[0].copy().reshape(-1)  # reversed mask.xyn, (n,2) to (n*2)\n                    line = (c, *seg)\n                if kpts is not None:\n                    kpt = kpts[j].xyn.reshape(-1).tolist()\n                    line += (*kpt, )\n                line += (conf, ) * save_conf + (() if id is None else (id, ))\n                texts.append(('%g ' * len(line)).rstrip() % line)\n\n        if texts:\n            with open(txt_file, 'a') as f:\n                f.writelines(text + '\\n' for text in texts)\n\n    def save_crop(self, save_dir, file_name=Path('im.jpg')):\n        \"\"\"\n        Save cropped predictions to `save_dir/cls/file_name.jpg`.\n\n        Args:\n            save_dir (str | pathlib.Path): Save path.\n            file_name (str | pathlib.Path): File name.\n        \"\"\"\n        if self.probs is not None:\n            LOGGER.warning('Warning: Classify task do not support `save_crop`.')\n            return\n        if isinstance(save_dir, str):\n            save_dir = Path(save_dir)\n        if isinstance(file_name, str):\n            file_name = Path(file_name)\n        for d in self.boxes:\n            save_one_box(d.xyxy,\n                         self.orig_img.copy(),\n                         file=save_dir / self.names[int(d.cls)] / f'{file_name.stem}.jpg',\n                         BGR=True)\n\n    def pandas(self):\n        \"\"\"Convert the object to a pandas DataFrame (not yet implemented).\"\"\"\n        LOGGER.warning(\"WARNING ⚠️ 'Results.pandas' method is not yet implemented.\")\n\n    def tojson(self, normalize=False):\n        \"\"\"Convert the object to JSON format.\"\"\"\n        if self.probs is not None:\n            LOGGER.warning('Warning: Classify task do not support `tojson` yet.')\n            return\n\n        import json\n\n        # Create list of detection dictionaries\n        results = []\n        data = self.boxes.data.cpu().tolist()\n        h, w = self.orig_shape if normalize else (1, 1)\n        for i, row in enumerate(data):\n            box = {'x1': row[0] / w, 'y1': row[1] / h, 'x2': row[2] / w, 'y2': row[3] / h}\n            conf = row[4]\n            id = int(row[5])\n            name = self.names[id]\n            result = {'name': name, 'class': id, 'confidence': conf, 'box': box}\n            if self.masks:\n                x, y = self.masks.xy[i][:, 0], self.masks.xy[i][:, 1]  # numpy array\n                result['segments'] = {'x': (x / w).tolist(), 'y': (y / h).tolist()}\n            if self.keypoints is not None:\n                x, y, visible = self.keypoints[i].data[0].cpu().unbind(dim=1)  # torch Tensor\n                result['keypoints'] = {'x': (x / w).tolist(), 'y': (y / h).tolist(), 'visible': visible.tolist()}\n            results.append(result)\n\n        # Convert detections to JSON\n        return json.dumps(results, indent=2)\n\n\nclass Boxes(BaseTensor):\n    \"\"\"\n    A class for storing and manipulating detection boxes.\n\n    Args:\n        boxes (torch.Tensor | numpy.ndarray): A tensor or numpy array containing the detection boxes,\n            with shape (num_boxes, 6). The last two columns should contain confidence and class values.\n        orig_shape (tuple): Original image size, in the format (height, width).\n\n    Attributes:\n        boxes (torch.Tensor | numpy.ndarray): The detection boxes with shape (num_boxes, 6).\n        orig_shape (torch.Tensor | numpy.ndarray): Original image size, in the format (height, width).\n        is_track (bool): True if the boxes also include track IDs, False otherwise.\n\n    Properties:\n        xyxy (torch.Tensor | numpy.ndarray): The boxes in xyxy format.\n        conf (torch.Tensor | numpy.ndarray): The confidence values of the boxes.\n        cls (torch.Tensor | numpy.ndarray): The class values of the boxes.\n        id (torch.Tensor | numpy.ndarray): The track IDs of the boxes (if available).\n        xywh (torch.Tensor | numpy.ndarray): The boxes in xywh format.\n        xyxyn (torch.Tensor | numpy.ndarray): The boxes in xyxy format normalized by original image size.\n        xywhn (torch.Tensor | numpy.ndarray): The boxes in xywh format normalized by original image size.\n        data (torch.Tensor): The raw bboxes tensor\n\n    Methods:\n        cpu(): Move the object to CPU memory.\n        numpy(): Convert the object to a numpy array.\n        cuda(): Move the object to CUDA memory.\n        to(*args, **kwargs): Move the object to the specified device.\n        pandas(): Convert the object to a pandas DataFrame (not yet implemented).\n    \"\"\"\n\n    def __init__(self, boxes, orig_shape) -> None:\n        \"\"\"Initialize the Boxes class.\"\"\"\n        if boxes.ndim == 1:\n            boxes = boxes[None, :]\n        n = boxes.shape[-1]\n        assert n in (6, 7), f'expected `n` in [6, 7], but got {n}'  # xyxy, (track_id), conf, cls\n        super().__init__(boxes, orig_shape)\n        self.is_track = n == 7\n        self.orig_shape = orig_shape\n\n    @property\n    def xyxy(self):\n        \"\"\"Return the boxes in xyxy format.\"\"\"\n        return self.data[:, :4]\n\n    @property\n    def conf(self):\n        \"\"\"Return the confidence values of the boxes.\"\"\"\n        return self.data[:, -2]\n\n    @property\n    def cls(self):\n        \"\"\"Return the class values of the boxes.\"\"\"\n        return self.data[:, -1]\n\n    @property\n    def id(self):\n        \"\"\"Return the track IDs of the boxes (if available).\"\"\"\n        return self.data[:, -3] if self.is_track else None\n\n    @property\n    @lru_cache(maxsize=2)  # maxsize 1 should suffice\n    def xywh(self):\n        \"\"\"Return the boxes in xywh format.\"\"\"\n        return ops.xyxy2xywh(self.xyxy)\n\n    @property\n    @lru_cache(maxsize=2)\n    def xyxyn(self):\n        \"\"\"Return the boxes in xyxy format normalized by original image size.\"\"\"\n        xyxy = self.xyxy.clone() if isinstance(self.xyxy, torch.Tensor) else np.copy(self.xyxy)\n        xyxy[..., [0, 2]] /= self.orig_shape[1]\n        xyxy[..., [1, 3]] /= self.orig_shape[0]\n        return xyxy\n\n    @property\n    @lru_cache(maxsize=2)\n    def xywhn(self):\n        \"\"\"Return the boxes in xywh format normalized by original image size.\"\"\"\n        xywh = ops.xyxy2xywh(self.xyxy)\n        xywh[..., [0, 2]] /= self.orig_shape[1]\n        xywh[..., [1, 3]] /= self.orig_shape[0]\n        return xywh\n\n    @property\n    def boxes(self):\n        \"\"\"Return the raw bboxes tensor (deprecated).\"\"\"\n        LOGGER.warning(\"WARNING ⚠️ 'Boxes.boxes' is deprecated. Use 'Boxes.data' instead.\")\n        return self.data\n\n\nclass Masks(BaseTensor):\n    \"\"\"\n    A class for storing and manipulating detection masks.\n\n    Args:\n        masks (torch.Tensor | np.ndarray): A tensor containing the detection masks, with shape (num_masks, height, width).\n        orig_shape (tuple): Original image size, in the format (height, width).\n\n    Attributes:\n        masks (torch.Tensor | np.ndarray): A tensor containing the detection masks, with shape (num_masks, height, width).\n        orig_shape (tuple): Original image size, in the format (height, width).\n\n    Properties:\n        xy (list): A list of segments (pixels) which includes x, y segments of each detection.\n        xyn (list): A list of segments (normalized) which includes x, y segments of each detection.\n\n    Methods:\n        cpu(): Returns a copy of the masks tensor on CPU memory.\n        numpy(): Returns a copy of the masks tensor as a numpy array.\n        cuda(): Returns a copy of the masks tensor on GPU memory.\n        to(): Returns a copy of the masks tensor with the specified device and dtype.\n    \"\"\"\n\n    def __init__(self, masks, orig_shape) -> None:\n        \"\"\"Initialize the Masks class.\"\"\"\n        if masks.ndim == 2:\n            masks = masks[None, :]\n        super().__init__(masks, orig_shape)\n\n    @property\n    @lru_cache(maxsize=1)\n    def segments(self):\n        \"\"\"Return segments (deprecated; normalized).\"\"\"\n        LOGGER.warning(\"WARNING ⚠️ 'Masks.segments' is deprecated. Use 'Masks.xyn' for segments (normalized) and \"\n                       \"'Masks.xy' for segments (pixels) instead.\")\n        return self.xyn\n\n    @property\n    @lru_cache(maxsize=1)\n    def xyn(self):\n        \"\"\"Return segments (normalized).\"\"\"\n        return [\n            ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=True)\n            for x in ops.masks2segments(self.data)]\n\n    @property\n    @lru_cache(maxsize=1)\n    def xy(self):\n        \"\"\"Return segments (pixels).\"\"\"\n        return [\n            ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=False)\n            for x in ops.masks2segments(self.data)]\n\n    @property\n    def masks(self):\n        \"\"\"Return the raw masks tensor (deprecated).\"\"\"\n        LOGGER.warning(\"WARNING ⚠️ 'Masks.masks' is deprecated. Use 'Masks.data' instead.\")\n        return self.data\n\n    def pandas(self):\n        \"\"\"Convert the object to a pandas DataFrame (not yet implemented).\"\"\"\n        LOGGER.warning(\"WARNING ⚠️ 'Masks.pandas' method is not yet implemented.\")\n\n\nclass Keypoints(BaseTensor):\n    \"\"\"\n    A class for storing and manipulating detection keypoints.\n\n    Args:\n        keypoints (torch.Tensor | np.ndarray): A tensor containing the detection keypoints, with shape (num_dets, num_kpts, 2/3).\n        orig_shape (tuple): Original image size, in the format (height, width).\n\n    Attributes:\n        keypoints (torch.Tensor | np.ndarray): A tensor containing the detection keypoints, with shape (num_dets, num_kpts, 2/3).\n        orig_shape (tuple): Original image size, in the format (height, width).\n\n    Properties:\n        xy (list): A list of keypoints (pixels) which includes x, y keypoints of each detection.\n        xyn (list): A list of keypoints (normalized) which includes x, y keypoints of each detection.\n\n    Methods:\n        cpu(): Returns a copy of the keypoints tensor on CPU memory.\n        numpy(): Returns a copy of the keypoints tensor as a numpy array.\n        cuda(): Returns a copy of the keypoints tensor on GPU memory.\n        to(): Returns a copy of the keypoints tensor with the specified device and dtype.\n    \"\"\"\n\n    def __init__(self, keypoints, orig_shape) -> None:\n        if keypoints.ndim == 2:\n            keypoints = keypoints[None, :]\n        super().__init__(keypoints, orig_shape)\n        self.has_visible = self.data.shape[-1] == 3\n\n    @property\n    @lru_cache(maxsize=1)\n    def xy(self):\n        return self.data[..., :2]\n\n    @property\n    @lru_cache(maxsize=1)\n    def xyn(self):\n        xy = self.xy.clone() if isinstance(self.xy, torch.Tensor) else np.copy(self.xy)\n        xy[..., 0] /= self.orig_shape[1]\n        xy[..., 1] /= self.orig_shape[0]\n        return xy\n\n    @property\n    @lru_cache(maxsize=1)\n    def conf(self):\n        return self.data[..., 2] if self.has_visible else None\n\n\nclass Probs(BaseTensor):\n    \"\"\"\n    A class for storing and manipulating classify predictions.\n\n    Args:\n        probs (torch.Tensor | np.ndarray): A tensor containing the detection keypoints, with shape (num_class, ).\n\n    Attributes:\n        probs (torch.Tensor | np.ndarray): A tensor containing the detection keypoints, with shape (num_class).\n\n    Properties:\n        top5 (list[int]): Top 1 indice.\n        top1 (int): Top 5 indices.\n\n    Methods:\n        cpu(): Returns a copy of the probs tensor on CPU memory.\n        numpy(): Returns a copy of the probs tensor as a numpy array.\n        cuda(): Returns a copy of the probs tensor on GPU memory.\n        to(): Returns a copy of the probs tensor with the specified device and dtype.\n    \"\"\"\n\n    def __init__(self, probs, orig_shape=None) -> None:\n        super().__init__(probs, orig_shape)\n\n    @property\n    @lru_cache(maxsize=1)\n    def top5(self):\n        \"\"\"Return the indices of top 5.\"\"\"\n        return (-self.data).argsort(0)[:5].tolist()  # this way works with both torch and numpy.\n\n    @property\n    @lru_cache(maxsize=1)\n    def top1(self):\n        \"\"\"Return the indices of top 1.\"\"\"\n        return int(self.data.argmax())\n\n    @property\n    @lru_cache(maxsize=1)\n    def top5conf(self):\n        \"\"\"Return the confidences of top 5.\"\"\"\n        return self.data[self.top5]\n\n    @property\n    @lru_cache(maxsize=1)\n    def top1conf(self):\n        \"\"\"Return the confidences of top 1.\"\"\"\n        return self.data[self.top1]\n"
  },
  {
    "path": "ultralytics/yolo/engine/trainer.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nTrain a model on a dataset\n\nUsage:\n    $ yolo mode=train model=yolov8n.pt data=coco128.yaml imgsz=640 epochs=100 batch=16\n\"\"\"\nimport math\nimport os\nimport subprocess\nimport time\nfrom copy import deepcopy\nfrom datetime import datetime, timedelta\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nfrom torch import distributed as dist\nfrom torch import nn, optim\nfrom torch.cuda import amp\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom tqdm import tqdm\n\nfrom ultralytics.nn.tasks import attempt_load_one_weight, attempt_load_weights\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.data.utils import check_cls_dataset, check_det_dataset\nfrom ultralytics.yolo.utils import (DEFAULT_CFG, LOGGER, RANK, SETTINGS, TQDM_BAR_FORMAT, __version__, callbacks,\n                                    clean_url, colorstr, emojis, yaml_save)\nfrom ultralytics.yolo.utils.autobatch import check_train_batch_size\nfrom ultralytics.yolo.utils.checks import check_amp, check_file, check_imgsz, print_args\nfrom ultralytics.yolo.utils.dist import ddp_cleanup, generate_ddp_command\nfrom ultralytics.yolo.utils.files import get_latest_run, increment_path\nfrom ultralytics.yolo.utils.torch_utils import (EarlyStopping, ModelEMA, de_parallel, init_seeds, one_cycle,\n                                                select_device, strip_optimizer)\n\n\nclass BaseTrainer:\n    \"\"\"\n    BaseTrainer\n\n    A base class for creating trainers.\n\n    Attributes:\n        args (SimpleNamespace): Configuration for the trainer.\n        check_resume (method): Method to check if training should be resumed from a saved checkpoint.\n        validator (BaseValidator): Validator instance.\n        model (nn.Module): Model instance.\n        callbacks (defaultdict): Dictionary of callbacks.\n        save_dir (Path): Directory to save results.\n        wdir (Path): Directory to save weights.\n        last (Path): Path to last checkpoint.\n        best (Path): Path to best checkpoint.\n        save_period (int): Save checkpoint every x epochs (disabled if < 1).\n        batch_size (int): Batch size for training.\n        epochs (int): Number of epochs to train for.\n        start_epoch (int): Starting epoch for training.\n        device (torch.device): Device to use for training.\n        amp (bool): Flag to enable AMP (Automatic Mixed Precision).\n        scaler (amp.GradScaler): Gradient scaler for AMP.\n        data (str): Path to data.\n        trainset (torch.utils.data.Dataset): Training dataset.\n        testset (torch.utils.data.Dataset): Testing dataset.\n        ema (nn.Module): EMA (Exponential Moving Average) of the model.\n        lf (nn.Module): Loss function.\n        scheduler (torch.optim.lr_scheduler._LRScheduler): Learning rate scheduler.\n        best_fitness (float): The best fitness value achieved.\n        fitness (float): Current fitness value.\n        loss (float): Current loss value.\n        tloss (float): Total loss value.\n        loss_names (list): List of loss names.\n        csv (Path): Path to results CSV file.\n    \"\"\"\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"\n        Initializes the BaseTrainer class.\n\n        Args:\n            cfg (str, optional): Path to a configuration file. Defaults to DEFAULT_CFG.\n            overrides (dict, optional): Configuration overrides. Defaults to None.\n        \"\"\"\n        self.args = get_cfg(cfg, overrides)\n        self.device = select_device(self.args.device, self.args.batch)\n        self.check_resume()\n        self.validator = None\n        self.model = None\n        self.metrics = None\n        self.plots = {}\n        init_seeds(self.args.seed + 1 + RANK, deterministic=self.args.deterministic)\n\n        # Dirs\n        project = self.args.project or Path(SETTINGS['runs_dir']) / self.args.task\n        name = self.args.name or f'{self.args.mode}'\n        if hasattr(self.args, 'save_dir'):\n            self.save_dir = Path(self.args.save_dir)\n        else:\n            self.save_dir = Path(\n                increment_path(Path(project) / name, exist_ok=self.args.exist_ok if RANK in (-1, 0) else True))\n        self.wdir = self.save_dir / 'weights'  # weights dir\n        if RANK in (-1, 0):\n            self.wdir.mkdir(parents=True, exist_ok=True)  # make dir\n            self.args.save_dir = str(self.save_dir)\n            yaml_save(self.save_dir / 'args.yaml', vars(self.args))  # save run args\n        self.last, self.best = self.wdir / 'last.pt', self.wdir / 'best.pt'  # checkpoint paths\n        self.save_period = self.args.save_period\n\n        self.batch_size = self.args.batch\n        self.epochs = self.args.epochs\n        self.start_epoch = 0\n        if RANK == -1:\n            print_args(vars(self.args))\n\n        # Device\n        if self.device.type == 'cpu':\n            self.args.workers = 0  # faster CPU training as time dominated by inference, not dataloading\n\n        # Model and Dataset\n        self.model = self.args.model\n        try:\n            if self.args.task == 'classify':\n                self.data = check_cls_dataset(self.args.data)\n            elif self.args.data.endswith('.yaml') or self.args.task in ('detect', 'segment'):\n                self.data = check_det_dataset(self.args.data)\n                if 'yaml_file' in self.data:\n                    self.args.data = self.data['yaml_file']  # for validating 'yolo train data=url.zip' usage\n        except Exception as e:\n            raise RuntimeError(emojis(f\"Dataset '{clean_url(self.args.data)}' error ❌ {e}\")) from e\n\n        self.trainset, self.testset = self.get_dataset(self.data)\n        self.ema = None\n\n        # Optimization utils init\n        self.lf = None\n        self.scheduler = None\n\n        # Epoch level metrics\n        self.best_fitness = None\n        self.fitness = None\n        self.loss = None\n        self.tloss = None\n        self.loss_names = ['Loss']\n        self.csv = self.save_dir / 'results.csv'\n        self.plot_idx = [0, 1, 2]\n\n        # Callbacks\n        self.callbacks = _callbacks or callbacks.get_default_callbacks()\n        if RANK in (-1, 0):\n            callbacks.add_integration_callbacks(self)\n\n    def add_callback(self, event: str, callback):\n        \"\"\"\n        Appends the given callback.\n        \"\"\"\n        self.callbacks[event].append(callback)\n\n    def set_callback(self, event: str, callback):\n        \"\"\"\n        Overrides the existing callbacks with the given callback.\n        \"\"\"\n        self.callbacks[event] = [callback]\n\n    def run_callbacks(self, event: str):\n        \"\"\"Run all existing callbacks associated with a particular event.\"\"\"\n        for callback in self.callbacks.get(event, []):\n            callback(self)\n\n    def train(self):\n        \"\"\"Allow device='', device=None on Multi-GPU systems to default to device=0.\"\"\"\n        if isinstance(self.args.device, int) or self.args.device:  # i.e. device=0 or device=[0,1,2,3]\n            world_size = torch.cuda.device_count()\n        elif torch.cuda.is_available():  # i.e. device=None or device=''\n            world_size = 1  # default to device 0\n        else:  # i.e. device='cpu' or 'mps'\n            world_size = 0\n\n        # Run subprocess if DDP training, else train normally\n        if world_size > 1 and 'LOCAL_RANK' not in os.environ:\n            # Argument checks\n            if self.args.rect:\n                LOGGER.warning(\"WARNING ⚠️ 'rect=True' is incompatible with Multi-GPU training, setting rect=False\")\n                self.args.rect = False\n            # Command\n            cmd, file = generate_ddp_command(world_size, self)\n            try:\n                LOGGER.info(f'DDP command: {cmd}')\n                subprocess.run(cmd, check=True)\n            except Exception as e:\n                raise e\n            finally:\n                ddp_cleanup(self, str(file))\n        else:\n            self._do_train(world_size)\n\n    def _setup_ddp(self, world_size):\n        \"\"\"Initializes and sets the DistributedDataParallel parameters for training.\"\"\"\n        torch.cuda.set_device(RANK)\n        self.device = torch.device('cuda', RANK)\n        LOGGER.info(f'DDP info: RANK {RANK}, WORLD_SIZE {world_size}, DEVICE {self.device}')\n        os.environ['NCCL_BLOCKING_WAIT'] = '1'  # set to enforce timeout\n        dist.init_process_group('nccl' if dist.is_nccl_available() else 'gloo',\n                                timeout=timedelta(seconds=3600),\n                                rank=RANK,\n                                world_size=world_size)\n\n    def _setup_train(self, world_size):\n        \"\"\"\n        Builds dataloaders and optimizer on correct rank process.\n        \"\"\"\n        # Model\n        self.run_callbacks('on_pretrain_routine_start')\n        ckpt = self.setup_model()\n        self.model = self.model.to(self.device)\n        self.set_model_attributes()\n        # Check AMP\n        self.amp = torch.tensor(self.args.amp).to(self.device)  # True or False\n        if self.amp and RANK in (-1, 0):  # Single-GPU and DDP\n            callbacks_backup = callbacks.default_callbacks.copy()  # backup callbacks as check_amp() resets them\n            self.amp = torch.tensor(check_amp(self.model), device=self.device)\n            callbacks.default_callbacks = callbacks_backup  # restore callbacks\n        if RANK > -1 and world_size > 1:  # DDP\n            dist.broadcast(self.amp, src=0)  # broadcast the tensor from rank 0 to all other ranks (returns None)\n        self.amp = bool(self.amp)  # as boolean\n        self.scaler = amp.GradScaler(enabled=self.amp)\n        if world_size > 1:\n            self.model = DDP(self.model, device_ids=[RANK])\n        # Check imgsz\n        gs = max(int(self.model.stride.max() if hasattr(self.model, 'stride') else 32), 32)  # grid size (max stride)\n        self.args.imgsz = check_imgsz(self.args.imgsz, stride=gs, floor=gs, max_dim=1)\n        # Batch size\n        if self.batch_size == -1:\n            if RANK == -1:  # single-GPU only, estimate best batch size\n                self.args.batch = self.batch_size = check_train_batch_size(self.model, self.args.imgsz, self.amp)\n            else:\n                SyntaxError('batch=-1 to use AutoBatch is only available in Single-GPU training. '\n                            'Please pass a valid batch size value for Multi-GPU DDP training, i.e. batch=16')\n\n        # Dataloaders\n        batch_size = self.batch_size // max(world_size, 1)\n        self.train_loader = self.get_dataloader(self.trainset, batch_size=batch_size, rank=RANK, mode='train')\n        if RANK in (-1, 0):\n            self.test_loader = self.get_dataloader(self.testset, batch_size=batch_size * 2, rank=-1, mode='val')\n            self.validator = self.get_validator()\n            metric_keys = self.validator.metrics.keys + self.label_loss_items(prefix='val')\n            self.metrics = dict(zip(metric_keys, [0] * len(metric_keys)))  # TODO: init metrics for plot_results()?\n            self.ema = ModelEMA(self.model)\n            if self.args.plots and not self.args.v5loader:\n                self.plot_training_labels()\n\n        # Optimizer\n        self.accumulate = max(round(self.args.nbs / self.batch_size), 1)  # accumulate loss before optimizing\n        weight_decay = self.args.weight_decay * self.batch_size * self.accumulate / self.args.nbs  # scale weight_decay\n        iterations = math.ceil(len(self.train_loader.dataset) / max(self.batch_size, self.args.nbs)) * self.epochs\n        self.optimizer = self.build_optimizer(model=self.model,\n                                              name=self.args.optimizer,\n                                              lr=self.args.lr0,\n                                              momentum=self.args.momentum,\n                                              decay=weight_decay,\n                                              iterations=iterations)\n        # Scheduler\n        if self.args.cos_lr:\n            self.lf = one_cycle(1, self.args.lrf, self.epochs)  # cosine 1->hyp['lrf']\n        else:\n            self.lf = lambda x: (1 - x / self.epochs) * (1.0 - self.args.lrf) + self.args.lrf  # linear\n        self.scheduler = optim.lr_scheduler.LambdaLR(self.optimizer, lr_lambda=self.lf)\n        self.stopper, self.stop = EarlyStopping(patience=self.args.patience), False\n        self.resume_training(ckpt)\n        self.scheduler.last_epoch = self.start_epoch - 1  # do not move\n        self.run_callbacks('on_pretrain_routine_end')\n\n    def _do_train(self, world_size=1):\n        \"\"\"Train completed, evaluate and plot if specified by arguments.\"\"\"\n        if world_size > 1:\n            self._setup_ddp(world_size)\n\n        self._setup_train(world_size)\n\n        self.epoch_time = None\n        self.epoch_time_start = time.time()\n        self.train_time_start = time.time()\n        nb = len(self.train_loader)  # number of batches\n        nw = max(round(self.args.warmup_epochs *\n                       nb), 100) if self.args.warmup_epochs > 0 else -1  # number of warmup iterations\n        last_opt_step = -1\n        self.run_callbacks('on_train_start')\n        LOGGER.info(f'Image sizes {self.args.imgsz} train, {self.args.imgsz} val\\n'\n                    f'Using {self.train_loader.num_workers * (world_size or 1)} dataloader workers\\n'\n                    f\"Logging results to {colorstr('bold', self.save_dir)}\\n\"\n                    f'Starting training for {self.epochs} epochs...')\n        if self.args.close_mosaic:\n            base_idx = (self.epochs - self.args.close_mosaic) * nb\n            self.plot_idx.extend([base_idx, base_idx + 1, base_idx + 2])\n        epoch = self.epochs  # predefine for resume fully trained model edge cases\n        for epoch in range(self.start_epoch, self.epochs):\n            self.epoch = epoch\n            self.run_callbacks('on_train_epoch_start')\n            self.model.train()\n            if RANK != -1:\n                self.train_loader.sampler.set_epoch(epoch)\n            pbar = enumerate(self.train_loader)\n            # Update dataloader attributes (optional)\n            if epoch == (self.epochs - self.args.close_mosaic):\n                LOGGER.info('Closing dataloader mosaic')\n                if hasattr(self.train_loader.dataset, 'mosaic'):\n                    self.train_loader.dataset.mosaic = False\n                if hasattr(self.train_loader.dataset, 'close_mosaic'):\n                    self.train_loader.dataset.close_mosaic(hyp=self.args)\n                self.train_loader.reset()\n\n            if RANK in (-1, 0):\n                LOGGER.info(self.progress_string())\n                pbar = tqdm(enumerate(self.train_loader), total=nb, bar_format=TQDM_BAR_FORMAT)\n            self.tloss = None\n            self.optimizer.zero_grad()\n            for i, batch in pbar:\n                self.run_callbacks('on_train_batch_start')\n                # Warmup\n                ni = i + nb * epoch\n                if ni <= nw:\n                    xi = [0, nw]  # x interp\n                    self.accumulate = max(1, np.interp(ni, xi, [1, self.args.nbs / self.batch_size]).round())\n                    for j, x in enumerate(self.optimizer.param_groups):\n                        # Bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0\n                        x['lr'] = np.interp(\n                            ni, xi, [self.args.warmup_bias_lr if j == 0 else 0.0, x['initial_lr'] * self.lf(epoch)])\n                        if 'momentum' in x:\n                            x['momentum'] = np.interp(ni, xi, [self.args.warmup_momentum, self.args.momentum])\n\n                # Forward\n                with torch.cuda.amp.autocast(self.amp):\n                    batch = self.preprocess_batch(batch)\n                    self.loss, self.loss_items = self.model(batch)\n                    if RANK != -1:\n                        self.loss *= world_size\n                    self.tloss = (self.tloss * i + self.loss_items) / (i + 1) if self.tloss is not None \\\n                        else self.loss_items\n\n                # Backward\n                self.scaler.scale(self.loss).backward()\n\n                # Optimize - https://pytorch.org/docs/master/notes/amp_examples.html\n                if ni - last_opt_step >= self.accumulate:\n                    self.optimizer_step()\n                    last_opt_step = ni\n\n                # Log\n                mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G'  # (GB)\n                loss_len = self.tloss.shape[0] if len(self.tloss.size()) else 1\n                losses = self.tloss if loss_len > 1 else torch.unsqueeze(self.tloss, 0)\n                if RANK in (-1, 0):\n                    pbar.set_description(\n                        ('%11s' * 2 + '%11.4g' * (2 + loss_len)) %\n                        (f'{epoch + 1}/{self.epochs}', mem, *losses, batch['cls'].shape[0], batch['img'].shape[-1]))\n                    self.run_callbacks('on_batch_end')\n                    if self.args.plots and ni in self.plot_idx:\n                        self.plot_training_samples(batch, ni)\n\n                self.run_callbacks('on_train_batch_end')\n\n            self.lr = {f'lr/pg{ir}': x['lr'] for ir, x in enumerate(self.optimizer.param_groups)}  # for loggers\n\n            self.scheduler.step()\n            self.run_callbacks('on_train_epoch_end')\n\n            if RANK in (-1, 0):\n\n                # Validation\n                self.ema.update_attr(self.model, include=['yaml', 'nc', 'args', 'names', 'stride', 'class_weights'])\n                final_epoch = (epoch + 1 == self.epochs) or self.stopper.possible_stop\n\n                if self.args.val or final_epoch:\n                    self.metrics, self.fitness = self.validate()\n                self.save_metrics(metrics={**self.label_loss_items(self.tloss), **self.metrics, **self.lr})\n                self.stop = self.stopper(epoch + 1, self.fitness)\n\n                # Save model\n                if self.args.save or (epoch + 1 == self.epochs):\n                    self.save_model()\n                    self.run_callbacks('on_model_save')\n\n            tnow = time.time()\n            self.epoch_time = tnow - self.epoch_time_start\n            self.epoch_time_start = tnow\n            self.run_callbacks('on_fit_epoch_end')\n            torch.cuda.empty_cache()  # clears GPU vRAM at end of epoch, can help with out of memory errors\n\n            # Early Stopping\n            if RANK != -1:  # if DDP training\n                broadcast_list = [self.stop if RANK == 0 else None]\n                dist.broadcast_object_list(broadcast_list, 0)  # broadcast 'stop' to all ranks\n                if RANK != 0:\n                    self.stop = broadcast_list[0]\n            if self.stop:\n                break  # must break all DDP ranks\n\n        if RANK in (-1, 0):\n            # Do final val with best.pt\n            LOGGER.info(f'\\n{epoch - self.start_epoch + 1} epochs completed in '\n                        f'{(time.time() - self.train_time_start) / 3600:.3f} hours.')\n            self.final_eval()\n            if self.args.plots:\n                self.plot_metrics()\n            self.run_callbacks('on_train_end')\n        torch.cuda.empty_cache()\n        self.run_callbacks('teardown')\n\n    def save_model(self):\n        \"\"\"Save model checkpoints based on various conditions.\"\"\"\n        ckpt = {\n            'epoch': self.epoch,\n            'best_fitness': self.best_fitness,\n            'model': deepcopy(de_parallel(self.model)).half(),\n            'ema': deepcopy(self.ema.ema).half(),\n            'updates': self.ema.updates,\n            'optimizer': self.optimizer.state_dict(),\n            'train_args': vars(self.args),  # save as dict\n            'date': datetime.now().isoformat(),\n            'version': __version__}\n\n        # Use dill (if exists) to serialize the lambda functions where pickle does not do this\n        try:\n            import dill as pickle\n        except ImportError:\n            import pickle\n\n        # Save last, best and delete\n        torch.save(ckpt, self.last, pickle_module=pickle)\n        if self.best_fitness == self.fitness:\n            torch.save(ckpt, self.best, pickle_module=pickle)\n        if (self.epoch > 0) and (self.save_period > 0) and (self.epoch % self.save_period == 0):\n            torch.save(ckpt, self.wdir / f'epoch{self.epoch}.pt', pickle_module=pickle)\n        del ckpt\n\n    @staticmethod\n    def get_dataset(data):\n        \"\"\"\n        Get train, val path from data dict if it exists. Returns None if data format is not recognized.\n        \"\"\"\n        return data['train'], data.get('val') or data.get('test')\n\n    def setup_model(self):\n        \"\"\"\n        load/create/download model for any task.\n        \"\"\"\n        if isinstance(self.model, torch.nn.Module):  # if model is loaded beforehand. No setup needed\n            return\n\n        model, weights = self.model, None\n        ckpt = None\n        if str(model).endswith('.pt'):\n            weights, ckpt = attempt_load_one_weight(model)\n            cfg = ckpt['model'].yaml\n        else:\n            cfg = model\n        self.model = self.get_model(cfg=cfg, weights=weights, verbose=RANK == -1)  # calls Model(cfg, weights)\n        return ckpt\n\n    def optimizer_step(self):\n        \"\"\"Perform a single step of the training optimizer with gradient clipping and EMA update.\"\"\"\n        self.scaler.unscale_(self.optimizer)  # unscale gradients\n        torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=10.0)  # clip gradients\n        self.scaler.step(self.optimizer)\n        self.scaler.update()\n        self.optimizer.zero_grad()\n        if self.ema:\n            self.ema.update(self.model)\n\n    def preprocess_batch(self, batch):\n        \"\"\"\n        Allows custom preprocessing model inputs and ground truths depending on task type.\n        \"\"\"\n        return batch\n\n    def validate(self):\n        \"\"\"\n        Runs validation on test set using self.validator. The returned dict is expected to contain \"fitness\" key.\n        \"\"\"\n        metrics = self.validator(self)\n        fitness = metrics.pop('fitness', -self.loss.detach().cpu().numpy())  # use loss as fitness measure if not found\n        if not self.best_fitness or self.best_fitness < fitness:\n            self.best_fitness = fitness\n        return metrics, fitness\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Get model and raise NotImplementedError for loading cfg files.\"\"\"\n        raise NotImplementedError(\"This task trainer doesn't support loading cfg files\")\n\n    def get_validator(self):\n        \"\"\"Returns a NotImplementedError when the get_validator function is called.\"\"\"\n        raise NotImplementedError('get_validator function not implemented in trainer')\n\n    def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode='train'):\n        \"\"\"\n        Returns dataloader derived from torch.data.Dataloader.\n        \"\"\"\n        raise NotImplementedError('get_dataloader function not implemented in trainer')\n\n    def build_dataset(self, img_path, mode='train', batch=None):\n        \"\"\"Build dataset\"\"\"\n        raise NotImplementedError('build_dataset function not implemented in trainer')\n\n    def label_loss_items(self, loss_items=None, prefix='train'):\n        \"\"\"\n        Returns a loss dict with labelled training loss items tensor\n        \"\"\"\n        # Not needed for classification but necessary for segmentation & detection\n        return {'loss': loss_items} if loss_items is not None else ['loss']\n\n    def set_model_attributes(self):\n        \"\"\"\n        To set or update model parameters before training.\n        \"\"\"\n        self.model.names = self.data['names']\n\n    def build_targets(self, preds, targets):\n        \"\"\"Builds target tensors for training YOLO model.\"\"\"\n        pass\n\n    def progress_string(self):\n        \"\"\"Returns a string describing training progress.\"\"\"\n        return ''\n\n    # TODO: may need to put these following functions into callback\n    def plot_training_samples(self, batch, ni):\n        \"\"\"Plots training samples during YOLOv5 training.\"\"\"\n        pass\n\n    def plot_training_labels(self):\n        \"\"\"Plots training labels for YOLO model.\"\"\"\n        pass\n\n    def save_metrics(self, metrics):\n        \"\"\"Saves training metrics to a CSV file.\"\"\"\n        keys, vals = list(metrics.keys()), list(metrics.values())\n        n = len(metrics) + 1  # number of cols\n        s = '' if self.csv.exists() else (('%23s,' * n % tuple(['epoch'] + keys)).rstrip(',') + '\\n')  # header\n        with open(self.csv, 'a') as f:\n            f.write(s + ('%23.5g,' * n % tuple([self.epoch] + vals)).rstrip(',') + '\\n')\n\n    def plot_metrics(self):\n        \"\"\"Plot and display metrics visually.\"\"\"\n        pass\n\n    def on_plot(self, name, data=None):\n        \"\"\"Registers plots (e.g. to be consumed in callbacks)\"\"\"\n        self.plots[name] = {'data': data, 'timestamp': time.time()}\n\n    def final_eval(self):\n        \"\"\"Performs final evaluation and validation for object detection YOLO model.\"\"\"\n        for f in self.last, self.best:\n            if f.exists():\n                strip_optimizer(f)  # strip optimizers\n                if f is self.best:\n                    LOGGER.info(f'\\nValidating {f}...')\n                    self.metrics = self.validator(model=f)\n                    self.metrics.pop('fitness', None)\n                    self.run_callbacks('on_fit_epoch_end')\n\n    def check_resume(self):\n        \"\"\"Check if resume checkpoint exists and update arguments accordingly.\"\"\"\n        resume = self.args.resume\n        if resume:\n            try:\n                exists = isinstance(resume, (str, Path)) and Path(resume).exists()\n                last = Path(check_file(resume) if exists else get_latest_run())\n\n                # Check that resume data YAML exists, otherwise strip to force re-download of dataset\n                ckpt_args = attempt_load_weights(last).args\n                if not Path(ckpt_args['data']).exists():\n                    ckpt_args['data'] = self.args.data\n\n                self.args = get_cfg(ckpt_args)\n                self.args.model, resume = str(last), True  # reinstate\n            except Exception as e:\n                raise FileNotFoundError('Resume checkpoint not found. Please pass a valid checkpoint to resume from, '\n                                        \"i.e. 'yolo train resume model=path/to/last.pt'\") from e\n        self.resume = resume\n\n    def resume_training(self, ckpt):\n        \"\"\"Resume YOLO training from given epoch and best fitness.\"\"\"\n        if ckpt is None:\n            return\n        best_fitness = 0.0\n        start_epoch = ckpt['epoch'] + 1\n        if ckpt['optimizer'] is not None:\n            self.optimizer.load_state_dict(ckpt['optimizer'])  # optimizer\n            best_fitness = ckpt['best_fitness']\n        if self.ema and ckpt.get('ema'):\n            self.ema.ema.load_state_dict(ckpt['ema'].float().state_dict())  # EMA\n            self.ema.updates = ckpt['updates']\n        if self.resume:\n            assert start_epoch > 0, \\\n                f'{self.args.model} training to {self.epochs} epochs is finished, nothing to resume.\\n' \\\n                f\"Start a new training without resuming, i.e. 'yolo train model={self.args.model}'\"\n            LOGGER.info(\n                f'Resuming training from {self.args.model} from epoch {start_epoch + 1} to {self.epochs} total epochs')\n        if self.epochs < start_epoch:\n            LOGGER.info(\n                f\"{self.model} has been trained for {ckpt['epoch']} epochs. Fine-tuning for {self.epochs} more epochs.\")\n            self.epochs += ckpt['epoch']  # finetune additional epochs\n        self.best_fitness = best_fitness\n        self.start_epoch = start_epoch\n        if start_epoch > (self.epochs - self.args.close_mosaic):\n            LOGGER.info('Closing dataloader mosaic')\n            if hasattr(self.train_loader.dataset, 'mosaic'):\n                self.train_loader.dataset.mosaic = False\n            if hasattr(self.train_loader.dataset, 'close_mosaic'):\n                self.train_loader.dataset.close_mosaic(hyp=self.args)\n\n    def build_optimizer(self, model, name='auto', lr=0.001, momentum=0.9, decay=1e-5, iterations=1e5):\n        \"\"\"\n        Constructs an optimizer for the given model, based on the specified optimizer name, learning rate,\n        momentum, weight decay, and number of iterations.\n\n        Args:\n            model (torch.nn.Module): The model for which to build an optimizer.\n            name (str, optional): The name of the optimizer to use. If 'auto', the optimizer is selected\n                based on the number of iterations. Default: 'auto'.\n            lr (float, optional): The learning rate for the optimizer. Default: 0.001.\n            momentum (float, optional): The momentum factor for the optimizer. Default: 0.9.\n            decay (float, optional): The weight decay for the optimizer. Default: 1e-5.\n            iterations (float, optional): The number of iterations, which determines the optimizer if\n                name is 'auto'. Default: 1e5.\n\n        Returns:\n            (torch.optim.Optimizer): The constructed optimizer.\n        \"\"\"\n\n        g = [], [], []  # optimizer parameter groups\n        bn = tuple(v for k, v in nn.__dict__.items() if 'Norm' in k)  # normalization layers, i.e. BatchNorm2d()\n        if name == 'auto':\n            nc = getattr(model, 'nc', 10)  # number of classes\n            lr_fit = round(0.002 * 5 / (4 + nc), 6)  # lr0 fit equation to 6 decimal places\n            name, lr, momentum = ('SGD', 0.01, 0.9) if iterations > 10000 else ('AdamW', lr_fit, 0.9)\n            self.args.warmup_bias_lr = 0.0  # no higher than 0.01 for Adam\n\n        for module_name, module in model.named_modules():\n            for param_name, param in module.named_parameters(recurse=False):\n                fullname = f'{module_name}.{param_name}' if module_name else param_name\n                if 'bias' in fullname:  # bias (no decay)\n                    g[2].append(param)\n                elif isinstance(module, bn):  # weight (no decay)\n                    g[1].append(param)\n                else:  # weight (with decay)\n                    g[0].append(param)\n\n        if name in ('Adam', 'Adamax', 'AdamW', 'NAdam', 'RAdam'):\n            optimizer = getattr(optim, name, optim.Adam)(g[2], lr=lr, betas=(momentum, 0.999), weight_decay=0.0)\n        elif name == 'RMSProp':\n            optimizer = optim.RMSprop(g[2], lr=lr, momentum=momentum)\n        elif name == 'SGD':\n            optimizer = optim.SGD(g[2], lr=lr, momentum=momentum, nesterov=True)\n        else:\n            raise NotImplementedError(\n                f\"Optimizer '{name}' not found in list of available optimizers \"\n                f'[Adam, AdamW, NAdam, RAdam, RMSProp, SGD, auto].'\n                'To request support for addition optimizers please visit https://github.com/ultralytics/ultralytics.')\n\n        optimizer.add_param_group({'params': g[0], 'weight_decay': decay})  # add g0 with weight_decay\n        optimizer.add_param_group({'params': g[1], 'weight_decay': 0.0})  # add g1 (BatchNorm2d weights)\n        LOGGER.info(\n            f\"{colorstr('optimizer:')} {type(optimizer).__name__}(lr={lr}, momentum={momentum}) with parameter groups \"\n            f'{len(g[1])} weight(decay=0.0), {len(g[0])} weight(decay={decay}), {len(g[2])} bias(decay=0.0)')\n        return optimizer\n"
  },
  {
    "path": "ultralytics/yolo/engine/validator.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nCheck a model's accuracy on a test or val split of a dataset\n\nUsage:\n    $ yolo mode=val model=yolov8n.pt data=coco128.yaml imgsz=640\n\nUsage - formats:\n    $ yolo mode=val model=yolov8n.pt                 # PyTorch\n                          yolov8n.torchscript        # TorchScript\n                          yolov8n.onnx               # ONNX Runtime or OpenCV DNN with dnn=True\n                          yolov8n_openvino_model     # OpenVINO\n                          yolov8n.engine             # TensorRT\n                          yolov8n.mlmodel            # CoreML (macOS-only)\n                          yolov8n_saved_model        # TensorFlow SavedModel\n                          yolov8n.pb                 # TensorFlow GraphDef\n                          yolov8n.tflite             # TensorFlow Lite\n                          yolov8n_edgetpu.tflite     # TensorFlow Edge TPU\n                          yolov8n_paddle_model       # PaddlePaddle\n\"\"\"\nimport json\nimport time\nfrom pathlib import Path\n\nimport torch\nfrom tqdm import tqdm\n\nfrom ultralytics.nn.autobackend import AutoBackend\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.data.utils import check_cls_dataset, check_det_dataset\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, RANK, SETTINGS, TQDM_BAR_FORMAT, callbacks, colorstr, emojis\nfrom ultralytics.yolo.utils.checks import check_imgsz\nfrom ultralytics.yolo.utils.files import increment_path\nfrom ultralytics.yolo.utils.ops import Profile\nfrom ultralytics.yolo.utils.torch_utils import de_parallel, select_device, smart_inference_mode\n\n\nclass BaseValidator:\n    \"\"\"\n    BaseValidator\n\n    A base class for creating validators.\n\n    Attributes:\n        dataloader (DataLoader): Dataloader to use for validation.\n        pbar (tqdm): Progress bar to update during validation.\n        args (SimpleNamespace): Configuration for the validator.\n        model (nn.Module): Model to validate.\n        data (dict): Data dictionary.\n        device (torch.device): Device to use for validation.\n        batch_i (int): Current batch index.\n        training (bool): Whether the model is in training mode.\n        speed (float): Batch processing speed in seconds.\n        jdict (dict): Dictionary to store validation results.\n        save_dir (Path): Directory to save results.\n    \"\"\"\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"\n        Initializes a BaseValidator instance.\n\n        Args:\n            dataloader (torch.utils.data.DataLoader): Dataloader to be used for validation.\n            save_dir (Path): Directory to save results.\n            pbar (tqdm.tqdm): Progress bar for displaying progress.\n            args (SimpleNamespace): Configuration for the validator.\n        \"\"\"\n        self.dataloader = dataloader\n        self.pbar = pbar\n        self.args = args or get_cfg(DEFAULT_CFG)\n        self.model = None\n        self.data = None\n        self.device = None\n        self.batch_i = None\n        self.training = True\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n        self.jdict = None\n\n        project = self.args.project or Path(SETTINGS['runs_dir']) / self.args.task\n        name = self.args.name or f'{self.args.mode}'\n        self.save_dir = save_dir or increment_path(Path(project) / name,\n                                                   exist_ok=self.args.exist_ok if RANK in (-1, 0) else True)\n        (self.save_dir / 'labels' if self.args.save_txt else self.save_dir).mkdir(parents=True, exist_ok=True)\n\n        if self.args.conf is None:\n            self.args.conf = 0.001  # default conf=0.001\n\n        self.plots = {}\n        self.callbacks = _callbacks or callbacks.get_default_callbacks()\n\n    @smart_inference_mode()\n    def __call__(self, trainer=None, model=None):\n        \"\"\"\n        Supports validation of a pre-trained model if passed or a model being trained\n        if trainer is passed (trainer gets priority).\n        \"\"\"\n        self.training = trainer is not None\n        if self.training:\n            self.device = trainer.device\n            self.data = trainer.data\n            model = trainer.ema.ema or trainer.model\n            self.args.half = self.device.type != 'cpu'  # force FP16 val during training\n            model = model.half() if self.args.half else model.float()\n            self.model = model\n            self.loss = torch.zeros_like(trainer.loss_items, device=trainer.device)\n            self.args.plots = trainer.stopper.possible_stop or (trainer.epoch == trainer.epochs - 1)\n            model.eval()\n        else:\n            callbacks.add_integration_callbacks(self)\n            self.run_callbacks('on_val_start')\n            assert model is not None, 'Either trainer or model is needed for validation'\n            self.device = select_device(self.args.device, self.args.batch)\n            self.args.half &= self.device.type != 'cpu'\n            model = AutoBackend(model, device=self.device, dnn=self.args.dnn, data=self.args.data, fp16=self.args.half)\n            self.model = model\n            stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine\n            imgsz = check_imgsz(self.args.imgsz, stride=stride)\n            if engine:\n                self.args.batch = model.batch_size\n            else:\n                self.device = model.device\n                if not pt and not jit:\n                    self.args.batch = 1  # export.py models default to batch-size 1\n                    LOGGER.info(f'Forcing batch=1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models')\n\n            if isinstance(self.args.data, str) and self.args.data.endswith('.yaml'):\n                self.data = check_det_dataset(self.args.data)\n            elif self.args.task == 'classify':\n                self.data = check_cls_dataset(self.args.data, split=self.args.split)\n            else:\n                raise FileNotFoundError(emojis(f\"Dataset '{self.args.data}' for task={self.args.task} not found ❌\"))\n\n            if self.device.type == 'cpu':\n                self.args.workers = 0  # faster CPU val as time dominated by inference, not dataloading\n            if not pt:\n                self.args.rect = False\n            self.dataloader = self.dataloader or self.get_dataloader(self.data.get(self.args.split), self.args.batch)\n\n            model.eval()\n            model.warmup(imgsz=(1 if pt else self.args.batch, 3, imgsz, imgsz))  # warmup\n\n        dt = Profile(), Profile(), Profile(), Profile()\n        n_batches = len(self.dataloader)\n        desc = self.get_desc()\n        # NOTE: keeping `not self.training` in tqdm will eliminate pbar after segmentation evaluation during training,\n        # which may affect classification task since this arg is in yolov5/classify/val.py.\n        # bar = tqdm(self.dataloader, desc, n_batches, not self.training, bar_format=TQDM_BAR_FORMAT)\n        bar = tqdm(self.dataloader, desc, n_batches, bar_format=TQDM_BAR_FORMAT)\n        self.init_metrics(de_parallel(model))\n        self.jdict = []  # empty before each val\n        for batch_i, batch in enumerate(bar):\n            self.run_callbacks('on_val_batch_start')\n            self.batch_i = batch_i\n            # Preprocess\n            with dt[0]:\n                batch = self.preprocess(batch)\n\n            # Inference\n            with dt[1]:\n                preds = model(batch['img'], augment=self.args.augment)\n\n            # Loss\n            with dt[2]:\n                if self.training:\n                    self.loss += model.loss(batch, preds)[1]\n\n            # Postprocess\n            with dt[3]:\n                preds = self.postprocess(preds)\n\n            self.update_metrics(preds, batch)\n            if self.args.plots and batch_i < 3:\n                self.plot_val_samples(batch, batch_i)\n                self.plot_predictions(batch, preds, batch_i)\n\n            self.run_callbacks('on_val_batch_end')\n        stats = self.get_stats()\n        self.check_stats(stats)\n        self.speed = dict(zip(self.speed.keys(), (x.t / len(self.dataloader.dataset) * 1E3 for x in dt)))\n        self.finalize_metrics()\n        self.print_results()\n        self.run_callbacks('on_val_end')\n        if self.training:\n            model.float()\n            results = {**stats, **trainer.label_loss_items(self.loss.cpu() / len(self.dataloader), prefix='val')}\n            return {k: round(float(v), 5) for k, v in results.items()}  # return results as 5 decimal place floats\n        else:\n            LOGGER.info('Speed: %.1fms preprocess, %.1fms inference, %.1fms loss, %.1fms postprocess per image' %\n                        tuple(self.speed.values()))\n            if self.args.save_json and self.jdict:\n                with open(str(self.save_dir / 'predictions.json'), 'w') as f:\n                    LOGGER.info(f'Saving {f.name}...')\n                    json.dump(self.jdict, f)  # flatten and save\n                stats = self.eval_json(stats)  # update stats\n            if self.args.plots or self.args.save_json:\n                LOGGER.info(f\"Results saved to {colorstr('bold', self.save_dir)}\")\n            return stats\n\n    def add_callback(self, event: str, callback):\n        \"\"\"Appends the given callback.\"\"\"\n        self.callbacks[event].append(callback)\n\n    def run_callbacks(self, event: str):\n        \"\"\"Runs all callbacks associated with a specified event.\"\"\"\n        for callback in self.callbacks.get(event, []):\n            callback(self)\n\n    def get_dataloader(self, dataset_path, batch_size):\n        \"\"\"Get data loader from dataset path and batch size.\"\"\"\n        raise NotImplementedError('get_dataloader function not implemented for this validator')\n\n    def build_dataset(self, img_path):\n        \"\"\"Build dataset\"\"\"\n        raise NotImplementedError('build_dataset function not implemented in validator')\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses an input batch.\"\"\"\n        return batch\n\n    def postprocess(self, preds):\n        \"\"\"Describes and summarizes the purpose of 'postprocess()' but no details mentioned.\"\"\"\n        return preds\n\n    def init_metrics(self, model):\n        \"\"\"Initialize performance metrics for the YOLO model.\"\"\"\n        pass\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Updates metrics based on predictions and batch.\"\"\"\n        pass\n\n    def finalize_metrics(self, *args, **kwargs):\n        \"\"\"Finalizes and returns all metrics.\"\"\"\n        pass\n\n    def get_stats(self):\n        \"\"\"Returns statistics about the model's performance.\"\"\"\n        return {}\n\n    def check_stats(self, stats):\n        \"\"\"Checks statistics.\"\"\"\n        pass\n\n    def print_results(self):\n        \"\"\"Prints the results of the model's predictions.\"\"\"\n        pass\n\n    def get_desc(self):\n        \"\"\"Get description of the YOLO model.\"\"\"\n        pass\n\n    @property\n    def metric_keys(self):\n        \"\"\"Returns the metric keys used in YOLO training/validation.\"\"\"\n        return []\n\n    def on_plot(self, name, data=None):\n        \"\"\"Registers plots (e.g. to be consumed in callbacks)\"\"\"\n        self.plots[name] = {'data': data, 'timestamp': time.time()}\n\n    # TODO: may need to put these following functions into callback\n    def plot_val_samples(self, batch, ni):\n        \"\"\"Plots validation samples during training.\"\"\"\n        pass\n\n    def plot_predictions(self, batch, preds, ni):\n        \"\"\"Plots YOLO model predictions on batch images.\"\"\"\n        pass\n\n    def pred_to_json(self, preds, batch):\n        \"\"\"Convert predictions to JSON format.\"\"\"\n        pass\n\n    def eval_json(self, stats):\n        \"\"\"Evaluate and return JSON format of prediction statistics.\"\"\"\n        pass\n"
  },
  {
    "path": "ultralytics/yolo/nas/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .model import NAS\nfrom .predict import NASPredictor\nfrom .val import NASValidator\n\n__all__ = 'NASPredictor', 'NASValidator', 'NAS'\n"
  },
  {
    "path": "ultralytics/yolo/nas/model.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nYOLO-NAS model interface.\n\nUsage - Predict:\n    from ultralytics import NAS\n\n    model = NAS('yolo_nas_s')\n    results = model.predict('ultralytics/assets/bus.jpg')\n\"\"\"\n\nfrom pathlib import Path\n\nimport torch\n\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.engine.exporter import Exporter\nfrom ultralytics.yolo.utils import DEFAULT_CFG, DEFAULT_CFG_DICT, LOGGER, ROOT, is_git_dir\nfrom ultralytics.yolo.utils.checks import check_imgsz\n\nfrom ...yolo.utils.torch_utils import model_info, smart_inference_mode\nfrom .predict import NASPredictor\nfrom .val import NASValidator\n\n\nclass NAS:\n\n    def __init__(self, model='yolo_nas_s.pt') -> None:\n        # Load or create new NAS model\n        import super_gradients\n\n        self.predictor = None\n        suffix = Path(model).suffix\n        if suffix == '.pt':\n            self._load(model)\n        elif suffix == '':\n            self.model = super_gradients.training.models.get(model, pretrained_weights='coco')\n        self.task = 'detect'\n        self.model.args = DEFAULT_CFG_DICT  # attach args to model\n\n        # Standardize model\n        self.model.fuse = lambda verbose=True: self.model\n        self.model.stride = torch.tensor([32])\n        self.model.names = dict(enumerate(self.model._class_names))\n        self.model.is_fused = lambda: False  # for info()\n        self.model.yaml = {}  # for info()\n        self.model.pt_path = model  # for export()\n        self.model.task = 'detect'  # for export()\n        self.info()\n\n    @smart_inference_mode()\n    def _load(self, weights: str):\n        self.model = torch.load(weights)\n\n    @smart_inference_mode()\n    def predict(self, source=None, stream=False, **kwargs):\n        \"\"\"\n        Perform prediction using the YOLO model.\n\n        Args:\n            source (str | int | PIL | np.ndarray): The source of the image to make predictions on.\n                          Accepts all source types accepted by the YOLO model.\n            stream (bool): Whether to stream the predictions or not. Defaults to False.\n            **kwargs : Additional keyword arguments passed to the predictor.\n                       Check the 'configuration' section in the documentation for all available options.\n\n        Returns:\n            (List[ultralytics.yolo.engine.results.Results]): The prediction results.\n        \"\"\"\n        if source is None:\n            source = ROOT / 'assets' if is_git_dir() else 'https://ultralytics.com/images/bus.jpg'\n            LOGGER.warning(f\"WARNING ⚠️ 'source' is missing. Using 'source={source}'.\")\n        overrides = dict(conf=0.25, task='detect', mode='predict')\n        overrides.update(kwargs)  # prefer kwargs\n        if not self.predictor:\n            self.predictor = NASPredictor(overrides=overrides)\n            self.predictor.setup_model(model=self.model)\n        else:  # only update args if predictor is already setup\n            self.predictor.args = get_cfg(self.predictor.args, overrides)\n        return self.predictor(source, stream=stream)\n\n    def train(self, **kwargs):\n        \"\"\"Function trains models but raises an error as NAS models do not support training.\"\"\"\n        raise NotImplementedError(\"NAS models don't support training\")\n\n    def val(self, **kwargs):\n        \"\"\"Run validation given dataset.\"\"\"\n        overrides = dict(task='detect', mode='val')\n        overrides.update(kwargs)  # prefer kwargs\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.imgsz = check_imgsz(args.imgsz, max_dim=1)\n        validator = NASValidator(args=args)\n        validator(model=self.model)\n        self.metrics = validator.metrics\n        return validator.metrics\n\n    @smart_inference_mode()\n    def export(self, **kwargs):\n        \"\"\"\n        Export model.\n\n        Args:\n            **kwargs : Any other args accepted by the predictors. To see all args check 'configuration' section in docs\n        \"\"\"\n        overrides = dict(task='detect')\n        overrides.update(kwargs)\n        overrides['mode'] = 'export'\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.task = self.task\n        if args.imgsz == DEFAULT_CFG.imgsz:\n            args.imgsz = self.model.args['imgsz']  # use trained imgsz unless custom value is passed\n        if args.batch == DEFAULT_CFG.batch:\n            args.batch = 1  # default to 1 if not modified\n        return Exporter(overrides=args)(model=self.model)\n\n    def info(self, detailed=False, verbose=True):\n        \"\"\"\n        Logs model info.\n\n        Args:\n            detailed (bool): Show detailed information about model.\n            verbose (bool): Controls verbosity.\n        \"\"\"\n        return model_info(self.model, detailed=detailed, verbose=verbose, imgsz=640)\n\n    def __call__(self, source=None, stream=False, **kwargs):\n        \"\"\"Calls the 'predict' function with given arguments to perform object detection.\"\"\"\n        return self.predict(source, stream, **kwargs)\n\n    def __getattr__(self, attr):\n        \"\"\"Raises error if object has no requested attribute.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n"
  },
  {
    "path": "ultralytics/yolo/nas/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.engine.predictor import BasePredictor\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import ops\nfrom ultralytics.yolo.utils.ops import xyxy2xywh\n\n\nclass NASPredictor(BasePredictor):\n\n    def postprocess(self, preds_in, img, orig_imgs):\n        \"\"\"Postprocesses predictions and returns a list of Results objects.\"\"\"\n\n        # Cat boxes and class scores\n        boxes = xyxy2xywh(preds_in[0][0])\n        preds = torch.cat((boxes, preds_in[0][1]), -1).permute(0, 2, 1)\n\n        preds = ops.non_max_suppression(preds,\n                                        self.args.conf,\n                                        self.args.iou,\n                                        agnostic=self.args.agnostic_nms,\n                                        max_det=self.args.max_det,\n                                        classes=self.args.classes)\n\n        results = []\n        for i, pred in enumerate(preds):\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            if not isinstance(orig_imgs, torch.Tensor):\n                pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred))\n        return results\n"
  },
  {
    "path": "ultralytics/yolo/nas/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.utils import ops\nfrom ultralytics.yolo.utils.ops import xyxy2xywh\nfrom ultralytics.yolo.v8.detect import DetectionValidator\n\n__all__ = ['NASValidator']\n\n\nclass NASValidator(DetectionValidator):\n\n    def postprocess(self, preds_in):\n        \"\"\"Apply Non-maximum suppression to prediction outputs.\"\"\"\n        boxes = xyxy2xywh(preds_in[0][0])\n        preds = torch.cat((boxes, preds_in[0][1]), -1).permute(0, 2, 1)\n        return ops.non_max_suppression(preds,\n                                       self.args.conf,\n                                       self.args.iou,\n                                       labels=self.lb,\n                                       multi_label=False,\n                                       agnostic=self.args.single_cls,\n                                       max_det=self.args.max_det,\n                                       max_time_img=0.5)\n"
  },
  {
    "path": "ultralytics/yolo/utils/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport inspect\nimport logging.config\nimport os\nimport platform\nimport re\nimport subprocess\nimport sys\nimport threading\nimport urllib\nimport uuid\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom typing import Union\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport yaml\n\nfrom ultralytics import __version__\n\n# PyTorch Multi-GPU DDP Constants\nRANK = int(os.getenv('RANK', -1))\nLOCAL_RANK = int(os.getenv('LOCAL_RANK', -1))  # https://pytorch.org/docs/stable/elastic/run.html\nWORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))\n\n# Other Constants\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[2]  # YOLO\nDEFAULT_CFG_PATH = ROOT / 'yolo/cfg/default.yaml'\nNUM_THREADS = min(8, max(1, os.cpu_count() - 1))  # number of YOLOv5 multiprocessing threads\nAUTOINSTALL = str(os.getenv('YOLO_AUTOINSTALL', True)).lower() == 'true'  # global auto-install mode\nVERBOSE = str(os.getenv('YOLO_VERBOSE', True)).lower() == 'true'  # global verbose mode\nTQDM_BAR_FORMAT = '{l_bar}{bar:10}{r_bar}'  # tqdm bar format\nLOGGING_NAME = 'ultralytics'\nMACOS, LINUX, WINDOWS = (platform.system() == x for x in ['Darwin', 'Linux', 'Windows'])  # environment booleans\nHELP_MSG = \\\n    \"\"\"\n    Usage examples for running YOLOv8:\n\n    1. Install the ultralytics package:\n\n        pip install ultralytics\n\n    2. Use the Python SDK:\n\n        from ultralytics import YOLO\n\n        # Load a model\n        model = YOLO('yolov8n.yaml')  # build a new model from scratch\n        model = YOLO(\"yolov8n.pt\")  # load a pretrained model (recommended for training)\n\n        # Use the model\n        results = model.train(data=\"coco128.yaml\", epochs=3)  # train the model\n        results = model.val()  # evaluate model performance on the validation set\n        results = model('https://ultralytics.com/images/bus.jpg')  # predict on an image\n        success = model.export(format='onnx')  # export the model to ONNX format\n\n    3. Use the command line interface (CLI):\n\n        YOLOv8 'yolo' CLI commands use the following syntax:\n\n            yolo TASK MODE ARGS\n\n            Where   TASK (optional) is one of [detect, segment, classify]\n                    MODE (required) is one of [train, val, predict, export]\n                    ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.\n                        See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg'\n\n        - Train a detection model for 10 epochs with an initial learning_rate of 0.01\n            yolo detect train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01\n\n        - Predict a YouTube video using a pretrained segmentation model at image size 320:\n            yolo segment predict model=yolov8n-seg.pt source='https://youtu.be/Zgi9g1ksQHc' imgsz=320\n\n        - Val a pretrained detection model at batch-size 1 and image size 640:\n            yolo detect val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640\n\n        - Export a YOLOv8n classification model to ONNX format at image size 224 by 128 (no TASK required)\n            yolo export model=yolov8n-cls.pt format=onnx imgsz=224,128\n\n        - Run special commands:\n            yolo help\n            yolo checks\n            yolo version\n            yolo settings\n            yolo copy-cfg\n            yolo cfg\n\n    Docs: https://docs.ultralytics.com\n    Community: https://community.ultralytics.com\n    GitHub: https://github.com/ultralytics/ultralytics\n    \"\"\"\n\n# Settings\ntorch.set_printoptions(linewidth=320, precision=4, profile='default')\nnp.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format})  # format short g, %precision=5\ncv2.setNumThreads(0)  # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)\nos.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS)  # NumExpr max threads\nos.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'  # for deterministic training\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # suppress verbose TF compiler warnings in Colab\n\n\nclass SimpleClass:\n    \"\"\"\n    Ultralytics SimpleClass is a base class providing helpful string representation, error reporting, and attribute\n    access methods for easier debugging and usage.\n    \"\"\"\n\n    def __str__(self):\n        \"\"\"Return a human-readable string representation of the object.\"\"\"\n        attr = []\n        for a in dir(self):\n            v = getattr(self, a)\n            if not callable(v) and not a.startswith('_'):\n                if isinstance(v, SimpleClass):\n                    # Display only the module and class name for subclasses\n                    s = f'{a}: {v.__module__}.{v.__class__.__name__} object'\n                else:\n                    s = f'{a}: {repr(v)}'\n                attr.append(s)\n        return f'{self.__module__}.{self.__class__.__name__} object with attributes:\\n\\n' + '\\n'.join(attr)\n\n    def __repr__(self):\n        \"\"\"Return a machine-readable string representation of the object.\"\"\"\n        return self.__str__()\n\n    def __getattr__(self, attr):\n        \"\"\"Custom attribute access error message with helpful information.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n\n\nclass IterableSimpleNamespace(SimpleNamespace):\n    \"\"\"\n    Ultralytics IterableSimpleNamespace is an extension class of SimpleNamespace that adds iterable functionality and\n    enables usage with dict() and for loops.\n    \"\"\"\n\n    def __iter__(self):\n        \"\"\"Return an iterator of key-value pairs from the namespace's attributes.\"\"\"\n        return iter(vars(self).items())\n\n    def __str__(self):\n        \"\"\"Return a human-readable string representation of the object.\"\"\"\n        return '\\n'.join(f'{k}={v}' for k, v in vars(self).items())\n\n    def __getattr__(self, attr):\n        \"\"\"Custom attribute access error message with helpful information.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"\"\"\n            '{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics\n            'default.yaml' file.\\nPlease update your code with 'pip install -U ultralytics' and if necessary replace\n            {DEFAULT_CFG_PATH} with the latest version from\n            https://github.com/ultralytics/ultralytics/blob/main/ultralytics/yolo/cfg/default.yaml\n            \"\"\")\n\n    def get(self, key, default=None):\n        \"\"\"Return the value of the specified key if it exists; otherwise, return the default value.\"\"\"\n        return getattr(self, key, default)\n\n\ndef plt_settings(rcparams=None, backend='Agg'):\n    \"\"\"\n    Decorator to temporarily set rc parameters and the backend for a plotting function.\n\n    Usage:\n        decorator: @plt_settings({\"font.size\": 12})\n        context manager: with plt_settings({\"font.size\": 12}):\n\n    Args:\n        rcparams (dict): Dictionary of rc parameters to set.\n        backend (str, optional): Name of the backend to use. Defaults to 'Agg'.\n\n    Returns:\n        (Callable): Decorated function with temporarily set rc parameters and backend. This decorator can be\n            applied to any function that needs to have specific matplotlib rc parameters and backend for its execution.\n    \"\"\"\n\n    if rcparams is None:\n        rcparams = {'font.size': 11}\n\n    def decorator(func):\n        \"\"\"Decorator to apply temporary rc parameters and backend to a function.\"\"\"\n\n        def wrapper(*args, **kwargs):\n            \"\"\"Sets rc parameters and backend, calls the original function, and restores the settings.\"\"\"\n            original_backend = plt.get_backend()\n            plt.switch_backend(backend)\n\n            with plt.rc_context(rcparams):\n                result = func(*args, **kwargs)\n\n            plt.switch_backend(original_backend)\n            return result\n\n        return wrapper\n\n    return decorator\n\n\ndef set_logging(name=LOGGING_NAME, verbose=True):\n    \"\"\"Sets up logging for the given name.\"\"\"\n    rank = int(os.getenv('RANK', -1))  # rank in world for Multi-GPU trainings\n    level = logging.INFO if verbose and rank in {-1, 0} else logging.ERROR\n    logging.config.dictConfig({\n        'version': 1,\n        'disable_existing_loggers': False,\n        'formatters': {\n            name: {\n                'format': '%(message)s'}},\n        'handlers': {\n            name: {\n                'class': 'logging.StreamHandler',\n                'formatter': name,\n                'level': level}},\n        'loggers': {\n            name: {\n                'level': level,\n                'handlers': [name],\n                'propagate': False}}})\n\n\ndef emojis(string=''):\n    \"\"\"Return platform-dependent emoji-safe version of string.\"\"\"\n    return string.encode().decode('ascii', 'ignore') if WINDOWS else string\n\n\nclass EmojiFilter(logging.Filter):\n    \"\"\"\n    A custom logging filter class for removing emojis in log messages.\n\n    This filter is particularly useful for ensuring compatibility with Windows terminals\n    that may not support the display of emojis in log messages.\n    \"\"\"\n\n    def filter(self, record):\n        \"\"\"Filter logs by emoji unicode characters on windows.\"\"\"\n        record.msg = emojis(record.msg)\n        return super().filter(record)\n\n\n# Set logger\nset_logging(LOGGING_NAME, verbose=VERBOSE)  # run before defining LOGGER\nLOGGER = logging.getLogger(LOGGING_NAME)  # define globally (used in train.py, val.py, detect.py, etc.)\nif WINDOWS:  # emoji-safe logging\n    LOGGER.addFilter(EmojiFilter())\n\n\ndef yaml_save(file='data.yaml', data=None):\n    \"\"\"\n    Save YAML data to a file.\n\n    Args:\n        file (str, optional): File name. Default is 'data.yaml'.\n        data (dict): Data to save in YAML format.\n\n    Returns:\n        (None): Data is saved to the specified file.\n    \"\"\"\n    if data is None:\n        data = {}\n    file = Path(file)\n    if not file.parent.exists():\n        # Create parent directories if they don't exist\n        file.parent.mkdir(parents=True, exist_ok=True)\n\n    # Convert Path objects to strings\n    for k, v in data.items():\n        if isinstance(v, Path):\n            data[k] = str(v)\n\n    # Dump data to file in YAML format\n    with open(file, 'w') as f:\n        yaml.safe_dump(data, f, sort_keys=False, allow_unicode=True)\n\n\ndef yaml_load(file='data.yaml', append_filename=False):\n    \"\"\"\n    Load YAML data from a file.\n\n    Args:\n        file (str, optional): File name. Default is 'data.yaml'.\n        append_filename (bool): Add the YAML filename to the YAML dictionary. Default is False.\n\n    Returns:\n        (dict): YAML data and file name.\n    \"\"\"\n    with open(file, errors='ignore', encoding='utf-8') as f:\n        s = f.read()  # string\n\n        # Remove special characters\n        if not s.isprintable():\n            s = re.sub(r'[^\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\U00010000-\\U0010ffff]+', '', s)\n\n        # Add YAML filename to dict and return\n        return {**yaml.safe_load(s), 'yaml_file': str(file)} if append_filename else yaml.safe_load(s)\n\n\ndef yaml_print(yaml_file: Union[str, Path, dict]) -> None:\n    \"\"\"\n    Pretty prints a yaml file or a yaml-formatted dictionary.\n\n    Args:\n        yaml_file: The file path of the yaml file or a yaml-formatted dictionary.\n\n    Returns:\n        None\n    \"\"\"\n    yaml_dict = yaml_load(yaml_file) if isinstance(yaml_file, (str, Path)) else yaml_file\n    dump = yaml.dump(yaml_dict, sort_keys=False, allow_unicode=True)\n    LOGGER.info(f\"Printing '{colorstr('bold', 'black', yaml_file)}'\\n\\n{dump}\")\n\n\n# Default configuration\nDEFAULT_CFG_DICT = yaml_load(DEFAULT_CFG_PATH)\nfor k, v in DEFAULT_CFG_DICT.items():\n    if isinstance(v, str) and v.lower() == 'none':\n        DEFAULT_CFG_DICT[k] = None\nDEFAULT_CFG_KEYS = DEFAULT_CFG_DICT.keys()\nDEFAULT_CFG = IterableSimpleNamespace(**DEFAULT_CFG_DICT)\n\n\ndef is_colab():\n    \"\"\"\n    Check if the current script is running inside a Google Colab notebook.\n\n    Returns:\n        (bool): True if running inside a Colab notebook, False otherwise.\n    \"\"\"\n    return 'COLAB_RELEASE_TAG' in os.environ or 'COLAB_BACKEND_VERSION' in os.environ\n\n\ndef is_kaggle():\n    \"\"\"\n    Check if the current script is running inside a Kaggle kernel.\n\n    Returns:\n        (bool): True if running inside a Kaggle kernel, False otherwise.\n    \"\"\"\n    return os.environ.get('PWD') == '/kaggle/working' and os.environ.get('KAGGLE_URL_BASE') == 'https://www.kaggle.com'\n\n\ndef is_jupyter():\n    \"\"\"\n    Check if the current script is running inside a Jupyter Notebook.\n    Verified on Colab, Jupyterlab, Kaggle, Paperspace.\n\n    Returns:\n        (bool): True if running inside a Jupyter Notebook, False otherwise.\n    \"\"\"\n    with contextlib.suppress(Exception):\n        from IPython import get_ipython\n        return get_ipython() is not None\n    return False\n\n\ndef is_docker() -> bool:\n    \"\"\"\n    Determine if the script is running inside a Docker container.\n\n    Returns:\n        (bool): True if the script is running inside a Docker container, False otherwise.\n    \"\"\"\n    file = Path('/proc/self/cgroup')\n    if file.exists():\n        with open(file) as f:\n            return 'docker' in f.read()\n    else:\n        return False\n\n\ndef is_online() -> bool:\n    \"\"\"\n    Check internet connectivity by attempting to connect to a known online host.\n\n    Returns:\n        (bool): True if connection is successful, False otherwise.\n    \"\"\"\n    import socket\n\n    for host in '1.1.1.1', '8.8.8.8', '223.5.5.5':  # Cloudflare, Google, AliDNS:\n        try:\n            test_connection = socket.create_connection(address=(host, 53), timeout=2)\n        except (socket.timeout, socket.gaierror, OSError):\n            continue\n        else:\n            # If the connection was successful, close it to avoid a ResourceWarning\n            test_connection.close()\n            return True\n    return False\n\n\nONLINE = is_online()\n\n\ndef is_pip_package(filepath: str = __name__) -> bool:\n    \"\"\"\n    Determines if the file at the given filepath is part of a pip package.\n\n    Args:\n        filepath (str): The filepath to check.\n\n    Returns:\n        (bool): True if the file is part of a pip package, False otherwise.\n    \"\"\"\n    import importlib.util\n\n    # Get the spec for the module\n    spec = importlib.util.find_spec(filepath)\n\n    # Return whether the spec is not None and the origin is not None (indicating it is a package)\n    return spec is not None and spec.origin is not None\n\n\ndef is_dir_writeable(dir_path: Union[str, Path]) -> bool:\n    \"\"\"\n    Check if a directory is writeable.\n\n    Args:\n        dir_path (str | Path): The path to the directory.\n\n    Returns:\n        (bool): True if the directory is writeable, False otherwise.\n    \"\"\"\n    return os.access(str(dir_path), os.W_OK)\n\n\ndef is_pytest_running():\n    \"\"\"\n    Determines whether pytest is currently running or not.\n\n    Returns:\n        (bool): True if pytest is running, False otherwise.\n    \"\"\"\n    return ('PYTEST_CURRENT_TEST' in os.environ) or ('pytest' in sys.modules) or ('pytest' in Path(sys.argv[0]).stem)\n\n\ndef is_github_actions_ci() -> bool:\n    \"\"\"\n    Determine if the current environment is a GitHub Actions CI Python runner.\n\n    Returns:\n        (bool): True if the current environment is a GitHub Actions CI Python runner, False otherwise.\n    \"\"\"\n    return 'GITHUB_ACTIONS' in os.environ and 'RUNNER_OS' in os.environ and 'RUNNER_TOOL_CACHE' in os.environ\n\n\ndef is_git_dir():\n    \"\"\"\n    Determines whether the current file is part of a git repository.\n    If the current file is not part of a git repository, returns None.\n\n    Returns:\n        (bool): True if current file is part of a git repository.\n    \"\"\"\n    return get_git_dir() is not None\n\n\ndef get_git_dir():\n    \"\"\"\n    Determines whether the current file is part of a git repository and if so, returns the repository root directory.\n    If the current file is not part of a git repository, returns None.\n\n    Returns:\n        (Path | None): Git root directory if found or None if not found.\n    \"\"\"\n    for d in Path(__file__).parents:\n        if (d / '.git').is_dir():\n            return d\n    return None  # no .git dir found\n\n\ndef get_git_origin_url():\n    \"\"\"\n    Retrieves the origin URL of a git repository.\n\n    Returns:\n        (str | None): The origin URL of the git repository.\n    \"\"\"\n    if is_git_dir():\n        with contextlib.suppress(subprocess.CalledProcessError):\n            origin = subprocess.check_output(['git', 'config', '--get', 'remote.origin.url'])\n            return origin.decode().strip()\n    return None  # if not git dir or on error\n\n\ndef get_git_branch():\n    \"\"\"\n    Returns the current git branch name. If not in a git repository, returns None.\n\n    Returns:\n        (str | None): The current git branch name.\n    \"\"\"\n    if is_git_dir():\n        with contextlib.suppress(subprocess.CalledProcessError):\n            origin = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])\n            return origin.decode().strip()\n    return None  # if not git dir or on error\n\n\ndef get_default_args(func):\n    \"\"\"Returns a dictionary of default arguments for a function.\n\n    Args:\n        func (callable): The function to inspect.\n\n    Returns:\n        (dict): A dictionary where each key is a parameter name, and each value is the default value of that parameter.\n    \"\"\"\n    signature = inspect.signature(func)\n    return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}\n\n\ndef get_user_config_dir(sub_dir='Ultralytics'):\n    \"\"\"\n    Get the user config directory.\n\n    Args:\n        sub_dir (str): The name of the subdirectory to create.\n\n    Returns:\n        (Path): The path to the user config directory.\n    \"\"\"\n    # Return the appropriate config directory for each operating system\n    if WINDOWS:\n        path = Path.home() / 'AppData' / 'Roaming' / sub_dir\n    elif MACOS:  # macOS\n        path = Path.home() / 'Library' / 'Application Support' / sub_dir\n    elif LINUX:\n        path = Path.home() / '.config' / sub_dir\n    else:\n        raise ValueError(f'Unsupported operating system: {platform.system()}')\n\n    # GCP and AWS lambda fix, only /tmp is writeable\n    if not is_dir_writeable(str(path.parent)):\n        path = Path('/tmp') / sub_dir\n        LOGGER.warning(f\"WARNING ⚠️ user config directory is not writeable, defaulting to '{path}'.\")\n\n    # Create the subdirectory if it does not exist\n    path.mkdir(parents=True, exist_ok=True)\n\n    return path\n\n\nUSER_CONFIG_DIR = Path(os.getenv('YOLO_CONFIG_DIR', get_user_config_dir()))  # Ultralytics settings dir\nSETTINGS_YAML = USER_CONFIG_DIR / 'settings.yaml'\n\n\ndef colorstr(*input):\n    \"\"\"Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e.  colorstr('blue', 'hello world').\"\"\"\n    *args, string = input if len(input) > 1 else ('blue', 'bold', input[0])  # color arguments, string\n    colors = {\n        'black': '\\033[30m',  # basic colors\n        'red': '\\033[31m',\n        'green': '\\033[32m',\n        'yellow': '\\033[33m',\n        'blue': '\\033[34m',\n        'magenta': '\\033[35m',\n        'cyan': '\\033[36m',\n        'white': '\\033[37m',\n        'bright_black': '\\033[90m',  # bright colors\n        'bright_red': '\\033[91m',\n        'bright_green': '\\033[92m',\n        'bright_yellow': '\\033[93m',\n        'bright_blue': '\\033[94m',\n        'bright_magenta': '\\033[95m',\n        'bright_cyan': '\\033[96m',\n        'bright_white': '\\033[97m',\n        'end': '\\033[0m',  # misc\n        'bold': '\\033[1m',\n        'underline': '\\033[4m'}\n    return ''.join(colors[x] for x in args) + f'{string}' + colors['end']\n\n\nclass TryExcept(contextlib.ContextDecorator):\n    \"\"\"YOLOv8 TryExcept class. Usage: @TryExcept() decorator or 'with TryExcept():' context manager.\"\"\"\n\n    def __init__(self, msg='', verbose=True):\n        \"\"\"Initialize TryExcept class with optional message and verbosity settings.\"\"\"\n        self.msg = msg\n        self.verbose = verbose\n\n    def __enter__(self):\n        \"\"\"Executes when entering TryExcept context, initializes instance.\"\"\"\n        pass\n\n    def __exit__(self, exc_type, value, traceback):\n        \"\"\"Defines behavior when exiting a 'with' block, prints error message if necessary.\"\"\"\n        if self.verbose and value:\n            print(emojis(f\"{self.msg}{': ' if self.msg else ''}{value}\"))\n        return True\n\n\ndef threaded(func):\n    \"\"\"Multi-threads a target function and returns thread. Usage: @threaded decorator.\"\"\"\n\n    def wrapper(*args, **kwargs):\n        \"\"\"Multi-threads a given function and returns the thread.\"\"\"\n        thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)\n        thread.start()\n        return thread\n\n    return wrapper\n\n\ndef set_sentry():\n    \"\"\"\n    Initialize the Sentry SDK for error tracking and reporting. Only used if sentry_sdk package is installed and\n    sync=True in settings. Run 'yolo settings' to see and update settings YAML file.\n\n    Conditions required to send errors (ALL conditions must be met or no errors will be reported):\n        - sentry_sdk package is installed\n        - sync=True in YOLO settings\n        - pytest is not running\n        - running in a pip package installation\n        - running in a non-git directory\n        - running with rank -1 or 0\n        - online environment\n        - CLI used to run package (checked with 'yolo' as the name of the main CLI command)\n\n    The function also configures Sentry SDK to ignore KeyboardInterrupt and FileNotFoundError\n    exceptions and to exclude events with 'out of memory' in their exception message.\n\n    Additionally, the function sets custom tags and user information for Sentry events.\n    \"\"\"\n\n    def before_send(event, hint):\n        \"\"\"\n        Modify the event before sending it to Sentry based on specific exception types and messages.\n\n        Args:\n            event (dict): The event dictionary containing information about the error.\n            hint (dict): A dictionary containing additional information about the error.\n\n        Returns:\n            dict: The modified event or None if the event should not be sent to Sentry.\n        \"\"\"\n        if 'exc_info' in hint:\n            exc_type, exc_value, tb = hint['exc_info']\n            if exc_type in (KeyboardInterrupt, FileNotFoundError) \\\n                    or 'out of memory' in str(exc_value):\n                return None  # do not send event\n\n        event['tags'] = {\n            'sys_argv': sys.argv[0],\n            'sys_argv_name': Path(sys.argv[0]).name,\n            'install': 'git' if is_git_dir() else 'pip' if is_pip_package() else 'other',\n            'os': ENVIRONMENT}\n        return event\n\n    if SETTINGS['sync'] and \\\n            RANK in (-1, 0) and \\\n            Path(sys.argv[0]).name == 'yolo' and \\\n            not TESTS_RUNNING and \\\n            ONLINE and \\\n            is_pip_package() and \\\n            not is_git_dir():\n\n        # If sentry_sdk package is not installed then return and do not use Sentry\n        try:\n            import sentry_sdk  # noqa\n        except ImportError:\n            return\n\n        sentry_sdk.init(\n            dsn='https://5ff1556b71594bfea135ff0203a0d290@o4504521589325824.ingest.sentry.io/4504521592406016',\n            debug=False,\n            traces_sample_rate=1.0,\n            release=__version__,\n            environment='production',  # 'dev' or 'production'\n            before_send=before_send,\n            ignore_errors=[KeyboardInterrupt, FileNotFoundError])\n        sentry_sdk.set_user({'id': SETTINGS['uuid']})  # SHA-256 anonymized UUID hash\n\n        # Disable all sentry logging\n        for logger in 'sentry_sdk', 'sentry_sdk.errors':\n            logging.getLogger(logger).setLevel(logging.CRITICAL)\n\n\ndef get_settings(file=SETTINGS_YAML, version='0.0.3'):\n    \"\"\"\n    Loads a global Ultralytics settings YAML file or creates one with default values if it does not exist.\n\n    Args:\n        file (Path): Path to the Ultralytics settings YAML file. Defaults to 'settings.yaml' in the USER_CONFIG_DIR.\n        version (str): Settings version. If min settings version not met, new default settings will be saved.\n\n    Returns:\n        (dict): Dictionary of settings key-value pairs.\n    \"\"\"\n    import hashlib\n\n    from ultralytics.yolo.utils.checks import check_version\n    from ultralytics.yolo.utils.torch_utils import torch_distributed_zero_first\n\n    git_dir = get_git_dir()\n    root = git_dir or Path()\n    datasets_root = (root.parent if git_dir and is_dir_writeable(root.parent) else root).resolve()\n    defaults = {\n        'datasets_dir': str(datasets_root / 'datasets'),  # default datasets directory.\n        'weights_dir': str(root / 'weights'),  # default weights directory.\n        'runs_dir': str(root / 'runs'),  # default runs directory.\n        'uuid': hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(),  # SHA-256 anonymized UUID hash\n        'sync': True,  # sync analytics to help with YOLO development\n        'api_key': '',  # Ultralytics HUB API key (https://hub.ultralytics.com/)\n        'settings_version': version}  # Ultralytics settings version\n\n    with torch_distributed_zero_first(RANK):\n        if not file.exists():\n            yaml_save(file, defaults)\n        settings = yaml_load(file)\n\n        # Check that settings keys and types match defaults\n        correct = \\\n            settings \\\n            and settings.keys() == defaults.keys() \\\n            and all(type(a) == type(b) for a, b in zip(settings.values(), defaults.values())) \\\n            and check_version(settings['settings_version'], version)\n        if not correct:\n            LOGGER.warning('WARNING ⚠️ Ultralytics settings reset to defaults. This is normal and may be due to a '\n                           'recent ultralytics package update, but may have overwritten previous settings. '\n                           f\"\\nView and update settings with 'yolo settings' or at '{file}'\")\n            settings = defaults  # merge **defaults with **settings (prefer **settings)\n            yaml_save(file, settings)  # save updated defaults\n\n        return settings\n\n\ndef set_settings(kwargs, file=SETTINGS_YAML):\n    \"\"\"\n    Function that runs on a first-time ultralytics package installation to set up global settings and create necessary\n    directories.\n    \"\"\"\n    SETTINGS.update(kwargs)\n    yaml_save(file, SETTINGS)\n\n\ndef deprecation_warn(arg, new_arg, version=None):\n    \"\"\"Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument.\"\"\"\n    if not version:\n        version = float(__version__[:3]) + 0.2  # deprecate after 2nd major release\n    LOGGER.warning(f\"WARNING ⚠️ '{arg}' is deprecated and will be removed in 'ultralytics {version}' in the future. \"\n                   f\"Please use '{new_arg}' instead.\")\n\n\ndef clean_url(url):\n    \"\"\"Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt.\"\"\"\n    url = str(Path(url)).replace(':/', '://')  # Pathlib turns :// -> :/\n    return urllib.parse.unquote(url).split('?')[0]  # '%2F' to '/', split https://url.com/file.txt?auth\n\n\ndef url2file(url):\n    \"\"\"Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt.\"\"\"\n    return Path(clean_url(url)).name\n\n\n# Run below code on yolo/utils init ------------------------------------------------------------------------------------\n\n# Check first-install steps\nPREFIX = colorstr('Ultralytics: ')\nSETTINGS = get_settings()\nDATASETS_DIR = Path(SETTINGS['datasets_dir'])  # global datasets directory\nENVIRONMENT = 'Colab' if is_colab() else 'Kaggle' if is_kaggle() else 'Jupyter' if is_jupyter() else \\\n    'Docker' if is_docker() else platform.system()\nTESTS_RUNNING = is_pytest_running() or is_github_actions_ci()\nset_sentry()\n\n# Apply monkey patches if the script is being run from within the parent directory of the script's location\nfrom .patches import imread, imshow, imwrite\n\n# torch.save = torch_save\nif Path(inspect.stack()[0].filename).parent.parent.as_posix() in inspect.stack()[-1].filename:\n    cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow\n"
  },
  {
    "path": "ultralytics/yolo/utils/autobatch.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nFunctions for estimating the best YOLO batch size to use a fraction of the available CUDA memory in PyTorch.\n\"\"\"\n\nfrom copy import deepcopy\n\nimport numpy as np\nimport torch\n\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, colorstr\nfrom ultralytics.yolo.utils.torch_utils import profile\n\n\ndef check_train_batch_size(model, imgsz=640, amp=True):\n    \"\"\"\n    Check YOLO training batch size using the autobatch() function.\n\n    Args:\n        model (torch.nn.Module): YOLO model to check batch size for.\n        imgsz (int): Image size used for training.\n        amp (bool): If True, use automatic mixed precision (AMP) for training.\n\n    Returns:\n        (int): Optimal batch size computed using the autobatch() function.\n    \"\"\"\n\n    with torch.cuda.amp.autocast(amp):\n        return autobatch(deepcopy(model).train(), imgsz)  # compute optimal batch size\n\n\ndef autobatch(model, imgsz=640, fraction=0.67, batch_size=DEFAULT_CFG.batch):\n    \"\"\"\n    Automatically estimate the best YOLO batch size to use a fraction of the available CUDA memory.\n\n    Args:\n        model (torch.nn.module): YOLO model to compute batch size for.\n        imgsz (int, optional): The image size used as input for the YOLO model. Defaults to 640.\n        fraction (float, optional): The fraction of available CUDA memory to use. Defaults to 0.67.\n        batch_size (int, optional): The default batch size to use if an error is detected. Defaults to 16.\n\n    Returns:\n        (int): The optimal batch size.\n    \"\"\"\n\n    # Check device\n    prefix = colorstr('AutoBatch: ')\n    LOGGER.info(f'{prefix}Computing optimal batch size for imgsz={imgsz}')\n    device = next(model.parameters()).device  # get model device\n    if device.type == 'cpu':\n        LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}')\n        return batch_size\n    if torch.backends.cudnn.benchmark:\n        LOGGER.info(f'{prefix} ⚠️ Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}')\n        return batch_size\n\n    # Inspect CUDA memory\n    gb = 1 << 30  # bytes to GiB (1024 ** 3)\n    d = str(device).upper()  # 'CUDA:0'\n    properties = torch.cuda.get_device_properties(device)  # device properties\n    t = properties.total_memory / gb  # GiB total\n    r = torch.cuda.memory_reserved(device) / gb  # GiB reserved\n    a = torch.cuda.memory_allocated(device) / gb  # GiB allocated\n    f = t - (r + a)  # GiB free\n    LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')\n\n    # Profile batch sizes\n    batch_sizes = [1, 2, 4, 8, 16]\n    try:\n        img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes]\n        results = profile(img, model, n=3, device=device)\n\n        # Fit a solution\n        y = [x[2] for x in results if x]  # memory [2]\n        p = np.polyfit(batch_sizes[:len(y)], y, deg=1)  # first degree polynomial fit\n        b = int((f * fraction - p[1]) / p[0])  # y intercept (optimal batch size)\n        if None in results:  # some sizes failed\n            i = results.index(None)  # first fail index\n            if b >= batch_sizes[i]:  # y intercept above failure point\n                b = batch_sizes[max(i - 1, 0)]  # select prior safe point\n        if b < 1 or b > 1024:  # b outside of safe range\n            b = batch_size\n            LOGGER.info(f'{prefix}WARNING ⚠️ CUDA anomaly detected, using default batch-size {batch_size}.')\n\n        fraction = (np.polyval(p, b) + r + a) / t  # actual fraction predicted\n        LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅')\n        return b\n    except Exception as e:\n        LOGGER.warning(f'{prefix}WARNING ⚠️ error detected: {e},  using default batch-size {batch_size}.')\n        return batch_size\n"
  },
  {
    "path": "ultralytics/yolo/utils/benchmarks.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nBenchmark a YOLO model formats for speed and accuracy\n\nUsage:\n    from ultralytics.yolo.utils.benchmarks import ProfileModels, benchmark\n    ProfileModels(['yolov8n.yaml', 'yolov8s.yaml']).profile()\n    run_benchmarks(model='yolov8n.pt', imgsz=160)\n\nFormat                  | `format=argument`         | Model\n---                     | ---                       | ---\nPyTorch                 | -                         | yolov8n.pt\nTorchScript             | `torchscript`             | yolov8n.torchscript\nONNX                    | `onnx`                    | yolov8n.onnx\nOpenVINO                | `openvino`                | yolov8n_openvino_model/\nTensorRT                | `engine`                  | yolov8n.engine\nCoreML                  | `coreml`                  | yolov8n.mlmodel\nTensorFlow SavedModel   | `saved_model`             | yolov8n_saved_model/\nTensorFlow GraphDef     | `pb`                      | yolov8n.pb\nTensorFlow Lite         | `tflite`                  | yolov8n.tflite\nTensorFlow Edge TPU     | `edgetpu`                 | yolov8n_edgetpu.tflite\nTensorFlow.js           | `tfjs`                    | yolov8n_web_model/\nPaddlePaddle            | `paddle`                  | yolov8n_paddle_model/\n\"\"\"\n\nimport glob\nimport platform\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nimport torch.cuda\nfrom tqdm import tqdm\n\nfrom ultralytics import YOLO\nfrom ultralytics.yolo.engine.exporter import export_formats\nfrom ultralytics.yolo.utils import LINUX, LOGGER, MACOS, ROOT, SETTINGS\nfrom ultralytics.yolo.utils.checks import check_requirements, check_yolo\nfrom ultralytics.yolo.utils.downloads import download\nfrom ultralytics.yolo.utils.files import file_size\nfrom ultralytics.yolo.utils.torch_utils import select_device\n\n\ndef benchmark(model=Path(SETTINGS['weights_dir']) / 'yolov8n.pt',\n              imgsz=160,\n              half=False,\n              int8=False,\n              device='cpu',\n              hard_fail=False):\n    \"\"\"\n    Benchmark a YOLO model across different formats for speed and accuracy.\n\n    Args:\n        model (str | Path | optional): Path to the model file or directory. Default is\n            Path(SETTINGS['weights_dir']) / 'yolov8n.pt'.\n        imgsz (int, optional): Image size for the benchmark. Default is 160.\n        half (bool, optional): Use half-precision for the model if True. Default is False.\n        int8 (bool, optional): Use int8-precision for the model if True. Default is False.\n        device (str, optional): Device to run the benchmark on, either 'cpu' or 'cuda'. Default is 'cpu'.\n        hard_fail (bool | float | optional): If True or a float, assert benchmarks pass with given metric.\n            Default is False.\n\n    Returns:\n        df (pandas.DataFrame): A pandas DataFrame with benchmark results for each format, including file size,\n            metric, and inference time.\n    \"\"\"\n\n    import pandas as pd\n    pd.options.display.max_columns = 10\n    pd.options.display.width = 120\n    device = select_device(device, verbose=False)\n    if isinstance(model, (str, Path)):\n        model = YOLO(model)\n\n    y = []\n    t0 = time.time()\n    for i, (name, format, suffix, cpu, gpu) in export_formats().iterrows():  # index, (name, format, suffix, CPU, GPU)\n        emoji, filename = '❌', None  # export defaults\n        try:\n            assert i != 9 or LINUX, 'Edge TPU export only supported on Linux'\n            if i == 10:\n                assert MACOS or LINUX, 'TF.js export only supported on macOS and Linux'\n            if 'cpu' in device.type:\n                assert cpu, 'inference not supported on CPU'\n            if 'cuda' in device.type:\n                assert gpu, 'inference not supported on GPU'\n\n            # Export\n            if format == '-':\n                filename = model.ckpt_path or model.cfg\n                export = model  # PyTorch format\n            else:\n                filename = model.export(imgsz=imgsz, format=format, half=half, int8=int8, device=device, verbose=False)\n                export = YOLO(filename, task=model.task)\n                assert suffix in str(filename), 'export failed'\n            emoji = '❎'  # indicates export succeeded\n\n            # Predict\n            assert i not in (9, 10), 'inference not supported'  # Edge TPU and TF.js are unsupported\n            assert i != 5 or platform.system() == 'Darwin', 'inference only supported on macOS>=10.13'  # CoreML\n            if not (ROOT / 'assets/bus.jpg').exists():\n                download(url='https://ultralytics.com/images/bus.jpg', dir=ROOT / 'assets')\n            export.predict(ROOT / 'assets/bus.jpg', imgsz=imgsz, device=device, half=half)\n\n            # Validate\n            if model.task == 'detect':\n                data, key = 'coco8.yaml', 'metrics/mAP50-95(B)'\n            elif model.task == 'segment':\n                data, key = 'coco8-seg.yaml', 'metrics/mAP50-95(M)'\n            elif model.task == 'classify':\n                data, key = 'imagenet100', 'metrics/accuracy_top5'\n            elif model.task == 'pose':\n                data, key = 'coco8-pose.yaml', 'metrics/mAP50-95(P)'\n\n            results = export.val(data=data,\n                                 batch=1,\n                                 imgsz=imgsz,\n                                 plots=False,\n                                 device=device,\n                                 half=half,\n                                 int8=int8,\n                                 verbose=False)\n            metric, speed = results.results_dict[key], results.speed['inference']\n            y.append([name, '✅', round(file_size(filename), 1), round(metric, 4), round(speed, 2)])\n        except Exception as e:\n            if hard_fail:\n                assert type(e) is AssertionError, f'Benchmark hard_fail for {name}: {e}'\n            LOGGER.warning(f'ERROR ❌️ Benchmark failure for {name}: {e}')\n            y.append([name, emoji, round(file_size(filename), 1), None, None])  # mAP, t_inference\n\n    # Print results\n    check_yolo(device=device)  # print system info\n    df = pd.DataFrame(y, columns=['Format', 'Status❔', 'Size (MB)', key, 'Inference time (ms/im)'])\n\n    name = Path(model.ckpt_path).name\n    s = f'\\nBenchmarks complete for {name} on {data} at imgsz={imgsz} ({time.time() - t0:.2f}s)\\n{df}\\n'\n    LOGGER.info(s)\n    with open('benchmarks.log', 'a', errors='ignore', encoding='utf-8') as f:\n        f.write(s)\n\n    if hard_fail and isinstance(hard_fail, float):\n        metrics = df[key].array  # values to compare to floor\n        floor = hard_fail  # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n\n        assert all(x > floor for x in metrics if pd.notna(x)), f'HARD FAIL: one or more metric(s) < floor {floor}'\n\n    return df\n\n\nclass ProfileModels:\n    \"\"\"\n    ProfileModels class for profiling different models on ONNX and TensorRT.\n\n    This class profiles the performance of different models, provided their paths. The profiling includes parameters such as\n    model speed and FLOPs.\n\n    Attributes:\n        paths (list): Paths of the models to profile.\n        num_timed_runs (int): Number of timed runs for the profiling. Default is 100.\n        num_warmup_runs (int): Number of warmup runs before profiling. Default is 10.\n        min_time (float): Minimum number of seconds to profile for. Default is 60.\n        imgsz (int): Image size used in the models. Default is 640.\n\n    Methods:\n        profile(): Profiles the models and prints the result.\n    \"\"\"\n\n    def __init__(self,\n                 paths: list,\n                 num_timed_runs=100,\n                 num_warmup_runs=10,\n                 min_time=60,\n                 imgsz=640,\n                 trt=True,\n                 device=None):\n        self.paths = paths\n        self.num_timed_runs = num_timed_runs\n        self.num_warmup_runs = num_warmup_runs\n        self.min_time = min_time\n        self.imgsz = imgsz\n        self.trt = trt  # run TensorRT profiling\n        self.device = device or torch.device(0 if torch.cuda.is_available() else 'cpu')\n\n    def profile(self):\n        files = self.get_files()\n\n        if not files:\n            print('No matching *.pt or *.onnx files found.')\n            return\n\n        table_rows = []\n        output = []\n        for file in files:\n            engine_file = file.with_suffix('.engine')\n            if file.suffix in ('.pt', '.yaml'):\n                model = YOLO(str(file))\n                model.fuse()  # to report correct params and GFLOPs in model.info()\n                model_info = model.info()\n                if self.trt and self.device.type != 'cpu' and not engine_file.is_file():\n                    engine_file = model.export(format='engine',\n                                               half=True,\n                                               imgsz=self.imgsz,\n                                               device=self.device,\n                                               verbose=False)\n                onnx_file = model.export(format='onnx',\n                                         half=True,\n                                         imgsz=self.imgsz,\n                                         simplify=True,\n                                         device=self.device,\n                                         verbose=False)\n            elif file.suffix == '.onnx':\n                model_info = self.get_onnx_model_info(file)\n                onnx_file = file\n            else:\n                continue\n\n            t_engine = self.profile_tensorrt_model(str(engine_file))\n            t_onnx = self.profile_onnx_model(str(onnx_file))\n            table_rows.append(self.generate_table_row(file.stem, t_onnx, t_engine, model_info))\n            output.append(self.generate_results_dict(file.stem, t_onnx, t_engine, model_info))\n\n        self.print_table(table_rows)\n        return output\n\n    def get_files(self):\n        files = []\n        for path in self.paths:\n            path = Path(path)\n            if path.is_dir():\n                extensions = ['*.pt', '*.onnx', '*.yaml']\n                files.extend([file for ext in extensions for file in glob.glob(str(path / ext))])\n            elif path.suffix in {'.pt', '.yaml'}:  # add non-existing\n                files.append(str(path))\n            else:\n                files.extend(glob.glob(str(path)))\n\n        print(f'Profiling: {sorted(files)}')\n        return [Path(file) for file in sorted(files)]\n\n    def get_onnx_model_info(self, onnx_file: str):\n        # return (num_layers, num_params, num_gradients, num_flops)\n        return 0.0, 0.0, 0.0, 0.0\n\n    def iterative_sigma_clipping(self, data, sigma=2, max_iters=3):\n        data = np.array(data)\n        for _ in range(max_iters):\n            mean, std = np.mean(data), np.std(data)\n            clipped_data = data[(data > mean - sigma * std) & (data < mean + sigma * std)]\n            if len(clipped_data) == len(data):\n                break\n            data = clipped_data\n        return data\n\n    def profile_tensorrt_model(self, engine_file: str):\n        if not self.trt or not Path(engine_file).is_file():\n            return 0.0, 0.0\n\n        # Model and input\n        model = YOLO(engine_file)\n        input_data = np.random.rand(self.imgsz, self.imgsz, 3).astype(np.float32)  # must be FP32\n\n        # Warmup runs\n        elapsed = 0.0\n        for _ in range(3):\n            start_time = time.time()\n            for _ in range(self.num_warmup_runs):\n                model(input_data, imgsz=self.imgsz, verbose=False)\n            elapsed = time.time() - start_time\n\n        # Compute number of runs as higher of min_time or num_timed_runs\n        num_runs = max(round(self.min_time / elapsed * self.num_warmup_runs), self.num_timed_runs * 50)\n\n        # Timed runs\n        run_times = []\n        for _ in tqdm(range(num_runs), desc=engine_file):\n            results = model(input_data, imgsz=self.imgsz, verbose=False)\n            run_times.append(results[0].speed['inference'])  # Convert to milliseconds\n\n        run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=3)  # sigma clipping\n        return np.mean(run_times), np.std(run_times)\n\n    def profile_onnx_model(self, onnx_file: str):\n        check_requirements('onnxruntime')\n        import onnxruntime as ort\n\n        # Session with either 'TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'\n        sess_options = ort.SessionOptions()\n        sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL\n        sess_options.intra_op_num_threads = 8  # Limit the number of threads\n        sess = ort.InferenceSession(onnx_file, sess_options, providers=['CPUExecutionProvider'])\n\n        input_tensor = sess.get_inputs()[0]\n        input_type = input_tensor.type\n\n        # Mapping ONNX datatype to numpy datatype\n        if 'float16' in input_type:\n            input_dtype = np.float16\n        elif 'float' in input_type:\n            input_dtype = np.float32\n        elif 'double' in input_type:\n            input_dtype = np.float64\n        elif 'int64' in input_type:\n            input_dtype = np.int64\n        elif 'int32' in input_type:\n            input_dtype = np.int32\n        else:\n            raise ValueError(f'Unsupported ONNX datatype {input_type}')\n\n        input_data = np.random.rand(*input_tensor.shape).astype(input_dtype)\n        input_name = input_tensor.name\n        output_name = sess.get_outputs()[0].name\n\n        # Warmup runs\n        elapsed = 0.0\n        for _ in range(3):\n            start_time = time.time()\n            for _ in range(self.num_warmup_runs):\n                sess.run([output_name], {input_name: input_data})\n            elapsed = time.time() - start_time\n\n        # Compute number of runs as higher of min_time or num_timed_runs\n        num_runs = max(round(self.min_time / elapsed * self.num_warmup_runs), self.num_timed_runs)\n\n        # Timed runs\n        run_times = []\n        for _ in tqdm(range(num_runs), desc=onnx_file):\n            start_time = time.time()\n            sess.run([output_name], {input_name: input_data})\n            run_times.append((time.time() - start_time) * 1000)  # Convert to milliseconds\n\n        run_times = self.iterative_sigma_clipping(np.array(run_times), sigma=2, max_iters=5)  # sigma clipping\n        return np.mean(run_times), np.std(run_times)\n\n    def generate_table_row(self, model_name, t_onnx, t_engine, model_info):\n        layers, params, gradients, flops = model_info\n        return f'| {model_name:18s} | {self.imgsz} | - | {t_onnx[0]:.2f} ± {t_onnx[1]:.2f} ms | {t_engine[0]:.2f} ± {t_engine[1]:.2f} ms | {params / 1e6:.1f} | {flops:.1f} |'\n\n    def generate_results_dict(self, model_name, t_onnx, t_engine, model_info):\n        layers, params, gradients, flops = model_info\n        return {\n            'model/name': model_name,\n            'model/parameters': params,\n            'model/GFLOPs': round(flops, 3),\n            'model/speed_ONNX(ms)': round(t_onnx[0], 3),\n            'model/speed_TensorRT(ms)': round(t_engine[0], 3)}\n\n    def print_table(self, table_rows):\n        gpu = torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'GPU'\n        header = f'| Model | size<br><sup>(pixels) | mAP<sup>val<br>50-95 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>{gpu} TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) |'\n        separator = '|-------------|---------------------|--------------------|------------------------------|-----------------------------------|------------------|-----------------|'\n\n        print(f'\\n\\n{header}')\n        print(separator)\n        for row in table_rows:\n            print(row)\n\n\nif __name__ == '__main__':\n    # Benchmark all export formats\n    benchmark()\n\n    # Profiling models on ONNX and TensorRT\n    ProfileModels(['yolov8n.yaml', 'yolov8s.yaml'])\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .base import add_integration_callbacks, default_callbacks, get_default_callbacks\n\n__all__ = 'add_integration_callbacks', 'default_callbacks', 'get_default_callbacks'\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/base.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nBase callbacks\n\"\"\"\n\nfrom collections import defaultdict\nfrom copy import deepcopy\n\n# Trainer callbacks ----------------------------------------------------------------------------------------------------\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Called before the pretraining routine starts.\"\"\"\n    pass\n\n\ndef on_pretrain_routine_end(trainer):\n    \"\"\"Called after the pretraining routine ends.\"\"\"\n    pass\n\n\ndef on_train_start(trainer):\n    \"\"\"Called when the training starts.\"\"\"\n    pass\n\n\ndef on_train_epoch_start(trainer):\n    \"\"\"Called at the start of each training epoch.\"\"\"\n    pass\n\n\ndef on_train_batch_start(trainer):\n    \"\"\"Called at the start of each training batch.\"\"\"\n    pass\n\n\ndef optimizer_step(trainer):\n    \"\"\"Called when the optimizer takes a step.\"\"\"\n    pass\n\n\ndef on_before_zero_grad(trainer):\n    \"\"\"Called before the gradients are set to zero.\"\"\"\n    pass\n\n\ndef on_train_batch_end(trainer):\n    \"\"\"Called at the end of each training batch.\"\"\"\n    pass\n\n\ndef on_train_epoch_end(trainer):\n    \"\"\"Called at the end of each training epoch.\"\"\"\n    pass\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Called at the end of each fit epoch (train + val).\"\"\"\n    pass\n\n\ndef on_model_save(trainer):\n    \"\"\"Called when the model is saved.\"\"\"\n    pass\n\n\ndef on_train_end(trainer):\n    \"\"\"Called when the training ends.\"\"\"\n    pass\n\n\ndef on_params_update(trainer):\n    \"\"\"Called when the model parameters are updated.\"\"\"\n    pass\n\n\ndef teardown(trainer):\n    \"\"\"Called during the teardown of the training process.\"\"\"\n    pass\n\n\n# Validator callbacks --------------------------------------------------------------------------------------------------\n\n\ndef on_val_start(validator):\n    \"\"\"Called when the validation starts.\"\"\"\n    pass\n\n\ndef on_val_batch_start(validator):\n    \"\"\"Called at the start of each validation batch.\"\"\"\n    pass\n\n\ndef on_val_batch_end(validator):\n    \"\"\"Called at the end of each validation batch.\"\"\"\n    pass\n\n\ndef on_val_end(validator):\n    \"\"\"Called when the validation ends.\"\"\"\n    pass\n\n\n# Predictor callbacks --------------------------------------------------------------------------------------------------\n\n\ndef on_predict_start(predictor):\n    \"\"\"Called when the prediction starts.\"\"\"\n    pass\n\n\ndef on_predict_batch_start(predictor):\n    \"\"\"Called at the start of each prediction batch.\"\"\"\n    pass\n\n\ndef on_predict_batch_end(predictor):\n    \"\"\"Called at the end of each prediction batch.\"\"\"\n    pass\n\n\ndef on_predict_postprocess_end(predictor):\n    \"\"\"Called after the post-processing of the prediction ends.\"\"\"\n    pass\n\n\ndef on_predict_end(predictor):\n    \"\"\"Called when the prediction ends.\"\"\"\n    pass\n\n\n# Exporter callbacks ---------------------------------------------------------------------------------------------------\n\n\ndef on_export_start(exporter):\n    \"\"\"Called when the model export starts.\"\"\"\n    pass\n\n\ndef on_export_end(exporter):\n    \"\"\"Called when the model export ends.\"\"\"\n    pass\n\n\ndefault_callbacks = {\n    # Run in trainer\n    'on_pretrain_routine_start': [on_pretrain_routine_start],\n    'on_pretrain_routine_end': [on_pretrain_routine_end],\n    'on_train_start': [on_train_start],\n    'on_train_epoch_start': [on_train_epoch_start],\n    'on_train_batch_start': [on_train_batch_start],\n    'optimizer_step': [optimizer_step],\n    'on_before_zero_grad': [on_before_zero_grad],\n    'on_train_batch_end': [on_train_batch_end],\n    'on_train_epoch_end': [on_train_epoch_end],\n    'on_fit_epoch_end': [on_fit_epoch_end],  # fit = train + val\n    'on_model_save': [on_model_save],\n    'on_train_end': [on_train_end],\n    'on_params_update': [on_params_update],\n    'teardown': [teardown],\n\n    # Run in validator\n    'on_val_start': [on_val_start],\n    'on_val_batch_start': [on_val_batch_start],\n    'on_val_batch_end': [on_val_batch_end],\n    'on_val_end': [on_val_end],\n\n    # Run in predictor\n    'on_predict_start': [on_predict_start],\n    'on_predict_batch_start': [on_predict_batch_start],\n    'on_predict_postprocess_end': [on_predict_postprocess_end],\n    'on_predict_batch_end': [on_predict_batch_end],\n    'on_predict_end': [on_predict_end],\n\n    # Run in exporter\n    'on_export_start': [on_export_start],\n    'on_export_end': [on_export_end]}\n\n\ndef get_default_callbacks():\n    \"\"\"\n    Return a copy of the default_callbacks dictionary with lists as default values.\n\n    Returns:\n        (defaultdict): A defaultdict with keys from default_callbacks and empty lists as default values.\n    \"\"\"\n    return defaultdict(list, deepcopy(default_callbacks))\n\n\ndef add_integration_callbacks(instance):\n    \"\"\"\n    Add integration callbacks from various sources to the instance's callbacks.\n\n    Args:\n        instance (Trainer, Predictor, Validator, Exporter): An object with a 'callbacks' attribute that is a dictionary\n            of callback lists.\n    \"\"\"\n    from .clearml import callbacks as clearml_cb\n    from .comet import callbacks as comet_cb\n    from .dvc import callbacks as dvc_cb\n    from .hub import callbacks as hub_cb\n    from .mlflow import callbacks as mlflow_cb\n    from .neptune import callbacks as neptune_cb\n    from .raytune import callbacks as tune_cb\n    from .tensorboard import callbacks as tensorboard_cb\n    from .wb import callbacks as wb_cb\n\n    for x in clearml_cb, comet_cb, hub_cb, mlflow_cb, neptune_cb, tune_cb, tensorboard_cb, wb_cb, dvc_cb:\n        for k, v in x.items():\n            if v not in instance.callbacks[k]:  # prevent duplicate callbacks addition\n                instance.callbacks[k].append(v)  # callback[name].append(func)\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/clearml.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport re\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\nfrom ultralytics.yolo.utils import LOGGER, TESTS_RUNNING\nfrom ultralytics.yolo.utils.torch_utils import model_info_for_loggers\n\ntry:\n    import clearml\n    from clearml import Task\n    from clearml.binding.frameworks.pytorch_bind import PatchPyTorchModelIO\n    from clearml.binding.matplotlib_bind import PatchedMatplotlib\n\n    assert hasattr(clearml, '__version__')  # verify package is not directory\n    assert not TESTS_RUNNING  # do not log pytest\nexcept (ImportError, AssertionError):\n    clearml = None\n\n\ndef _log_debug_samples(files, title='Debug Samples') -> None:\n    \"\"\"\n    Log files (images) as debug samples in the ClearML task.\n\n    Args:\n        files (list): A list of file paths in PosixPath format.\n        title (str): A title that groups together images with the same values.\n    \"\"\"\n    task = Task.current_task()\n    if task:\n        for f in files:\n            if f.exists():\n                it = re.search(r'_batch(\\d+)', f.name)\n                iteration = int(it.groups()[0]) if it else 0\n                task.get_logger().report_image(title=title,\n                                               series=f.name.replace(it.group(), ''),\n                                               local_path=str(f),\n                                               iteration=iteration)\n\n\ndef _log_plot(title, plot_path) -> None:\n    \"\"\"\n    Log an image as a plot in the plot section of ClearML.\n\n    Args:\n        title (str): The title of the plot.\n        plot_path (str): The path to the saved image file.\n    \"\"\"\n    img = mpimg.imread(plot_path)\n    fig = plt.figure()\n    ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect='auto', xticks=[], yticks=[])  # no ticks\n    ax.imshow(img)\n\n    Task.current_task().get_logger().report_matplotlib_figure(title=title,\n                                                              series='',\n                                                              figure=fig,\n                                                              report_interactive=False)\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Runs at start of pretraining routine; initializes and connects/ logs task to ClearML.\"\"\"\n    try:\n        task = Task.current_task()\n        if task:\n            # Make sure the automatic pytorch and matplotlib bindings are disabled!\n            # We are logging these plots and model files manually in the integration\n            PatchPyTorchModelIO.update_current_task(None)\n            PatchedMatplotlib.update_current_task(None)\n        else:\n            task = Task.init(project_name=trainer.args.project or 'YOLOv8',\n                             task_name=trainer.args.name,\n                             tags=['YOLOv8'],\n                             output_uri=True,\n                             reuse_last_task_id=False,\n                             auto_connect_frameworks={\n                                 'pytorch': False,\n                                 'matplotlib': False})\n            LOGGER.warning('ClearML Initialized a new task. If you want to run remotely, '\n                           'please add clearml-init and connect your arguments before initializing YOLO.')\n        task.connect(vars(trainer.args), name='General')\n    except Exception as e:\n        LOGGER.warning(f'WARNING ⚠️ ClearML installed but not initialized correctly, not logging this run. {e}')\n\n\ndef on_train_epoch_end(trainer):\n    task = Task.current_task()\n\n    if task:\n        \"\"\"Logs debug samples for the first epoch of YOLO training.\"\"\"\n        if trainer.epoch == 1:\n            _log_debug_samples(sorted(trainer.save_dir.glob('train_batch*.jpg')), 'Mosaic')\n        \"\"\"Report the current training progress.\"\"\"\n        for k, v in trainer.validator.metrics.results_dict.items():\n            task.get_logger().report_scalar('train', k, v, iteration=trainer.epoch)\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Reports model information to logger at the end of an epoch.\"\"\"\n    task = Task.current_task()\n    if task:\n        # You should have access to the validation bboxes under jdict\n        task.get_logger().report_scalar(title='Epoch Time',\n                                        series='Epoch Time',\n                                        value=trainer.epoch_time,\n                                        iteration=trainer.epoch)\n        if trainer.epoch == 0:\n            for k, v in model_info_for_loggers(trainer).items():\n                task.get_logger().report_single_value(k, v)\n\n\ndef on_val_end(validator):\n    \"\"\"Logs validation results including labels and predictions.\"\"\"\n    if Task.current_task():\n        # Log val_labels and val_pred\n        _log_debug_samples(sorted(validator.save_dir.glob('val*.jpg')), 'Validation')\n\n\ndef on_train_end(trainer):\n    \"\"\"Logs final model and its name on training completion.\"\"\"\n    task = Task.current_task()\n    if task:\n        # Log final results, CM matrix + PR plots\n        files = [\n            'results.png', 'confusion_matrix.png', 'confusion_matrix_normalized.png',\n            *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))]\n        files = [(trainer.save_dir / f) for f in files if (trainer.save_dir / f).exists()]  # filter\n        for f in files:\n            _log_plot(title=f.stem, plot_path=f)\n        # Report final metrics\n        for k, v in trainer.validator.metrics.results_dict.items():\n            task.get_logger().report_single_value(k, v)\n        # Log the final model\n        task.update_output_model(model_path=str(trainer.best), model_name=trainer.args.name, auto_delete_file=False)\n\n\ncallbacks = {\n    'on_pretrain_routine_start': on_pretrain_routine_start,\n    'on_train_epoch_end': on_train_epoch_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_val_end': on_val_end,\n    'on_train_end': on_train_end} if clearml else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/comet.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nfrom pathlib import Path\n\nfrom ultralytics.yolo.utils import LOGGER, RANK, TESTS_RUNNING, ops\nfrom ultralytics.yolo.utils.torch_utils import model_info_for_loggers\n\ntry:\n    import comet_ml\n\n    assert not TESTS_RUNNING  # do not log pytest\n    assert hasattr(comet_ml, '__version__')  # verify package is not directory\nexcept (ImportError, AssertionError):\n    comet_ml = None\n\n# Ensures certain logging functions only run for supported tasks\nCOMET_SUPPORTED_TASKS = ['detect']\n\n# Names of plots created by YOLOv8 that are logged to Comet\nEVALUATION_PLOT_NAMES = 'F1_curve', 'P_curve', 'R_curve', 'PR_curve', 'confusion_matrix'\nLABEL_PLOT_NAMES = 'labels', 'labels_correlogram'\n\n_comet_image_prediction_count = 0\n\n\ndef _get_comet_mode():\n    return os.getenv('COMET_MODE', 'online')\n\n\ndef _get_comet_model_name():\n    return os.getenv('COMET_MODEL_NAME', 'YOLOv8')\n\n\ndef _get_eval_batch_logging_interval():\n    return int(os.getenv('COMET_EVAL_BATCH_LOGGING_INTERVAL', 1))\n\n\ndef _get_max_image_predictions_to_log():\n    return int(os.getenv('COMET_MAX_IMAGE_PREDICTIONS', 100))\n\n\ndef _scale_confidence_score(score):\n    scale = float(os.getenv('COMET_MAX_CONFIDENCE_SCORE', 100.0))\n    return score * scale\n\n\ndef _should_log_confusion_matrix():\n    return os.getenv('COMET_EVAL_LOG_CONFUSION_MATRIX', 'false').lower() == 'true'\n\n\ndef _should_log_image_predictions():\n    return os.getenv('COMET_EVAL_LOG_IMAGE_PREDICTIONS', 'true').lower() == 'true'\n\n\ndef _get_experiment_type(mode, project_name):\n    \"\"\"Return an experiment based on mode and project name.\"\"\"\n    if mode == 'offline':\n        return comet_ml.OfflineExperiment(project_name=project_name)\n\n    return comet_ml.Experiment(project_name=project_name)\n\n\ndef _create_experiment(args):\n    \"\"\"Ensures that the experiment object is only created in a single process during distributed training.\"\"\"\n    if RANK not in (-1, 0):\n        return\n    try:\n        comet_mode = _get_comet_mode()\n        _project_name = os.getenv('COMET_PROJECT_NAME', args.project)\n        experiment = _get_experiment_type(comet_mode, _project_name)\n        experiment.log_parameters(vars(args))\n        experiment.log_others({\n            'eval_batch_logging_interval': _get_eval_batch_logging_interval(),\n            'log_confusion_matrix_on_eval': _should_log_confusion_matrix(),\n            'log_image_predictions': _should_log_image_predictions(),\n            'max_image_predictions': _get_max_image_predictions_to_log(), })\n        experiment.log_other('Created from', 'yolov8')\n\n    except Exception as e:\n        LOGGER.warning(f'WARNING ⚠️ Comet installed but not initialized correctly, not logging this run. {e}')\n\n\ndef _fetch_trainer_metadata(trainer):\n    \"\"\"Returns metadata for YOLO training including epoch and asset saving status.\"\"\"\n    curr_epoch = trainer.epoch + 1\n\n    train_num_steps_per_epoch = len(trainer.train_loader.dataset) // trainer.batch_size\n    curr_step = curr_epoch * train_num_steps_per_epoch\n    final_epoch = curr_epoch == trainer.epochs\n\n    save = trainer.args.save\n    save_period = trainer.args.save_period\n    save_interval = curr_epoch % save_period == 0\n    save_assets = save and save_period > 0 and save_interval and not final_epoch\n\n    return dict(\n        curr_epoch=curr_epoch,\n        curr_step=curr_step,\n        save_assets=save_assets,\n        final_epoch=final_epoch,\n    )\n\n\ndef _scale_bounding_box_to_original_image_shape(box, resized_image_shape, original_image_shape, ratio_pad):\n    \"\"\"YOLOv8 resizes images during training and the label values\n    are normalized based on this resized shape. This function rescales the\n    bounding box labels to the original image shape.\n    \"\"\"\n\n    resized_image_height, resized_image_width = resized_image_shape\n\n    # Convert normalized xywh format predictions to xyxy in resized scale format\n    box = ops.xywhn2xyxy(box, h=resized_image_height, w=resized_image_width)\n    # Scale box predictions from resized image scale back to original image scale\n    box = ops.scale_boxes(resized_image_shape, box, original_image_shape, ratio_pad)\n    # Convert bounding box format from xyxy to xywh for Comet logging\n    box = ops.xyxy2xywh(box)\n    # Adjust xy center to correspond top-left corner\n    box[:2] -= box[2:] / 2\n    box = box.tolist()\n\n    return box\n\n\ndef _format_ground_truth_annotations_for_detection(img_idx, image_path, batch, class_name_map=None):\n    \"\"\"Format ground truth annotations for detection.\"\"\"\n    indices = batch['batch_idx'] == img_idx\n    bboxes = batch['bboxes'][indices]\n    if len(bboxes) == 0:\n        LOGGER.debug(f'COMET WARNING: Image: {image_path} has no bounding boxes labels')\n        return None\n\n    cls_labels = batch['cls'][indices].squeeze(1).tolist()\n    if class_name_map:\n        cls_labels = [str(class_name_map[label]) for label in cls_labels]\n\n    original_image_shape = batch['ori_shape'][img_idx]\n    resized_image_shape = batch['resized_shape'][img_idx]\n    ratio_pad = batch['ratio_pad'][img_idx]\n\n    data = []\n    for box, label in zip(bboxes, cls_labels):\n        box = _scale_bounding_box_to_original_image_shape(box, resized_image_shape, original_image_shape, ratio_pad)\n        data.append({\n            'boxes': [box],\n            'label': f'gt_{label}',\n            'score': _scale_confidence_score(1.0), })\n\n    return {'name': 'ground_truth', 'data': data}\n\n\ndef _format_prediction_annotations_for_detection(image_path, metadata, class_label_map=None):\n    \"\"\"Format YOLO predictions for object detection visualization.\"\"\"\n    stem = image_path.stem\n    image_id = int(stem) if stem.isnumeric() else stem\n\n    predictions = metadata.get(image_id)\n    if not predictions:\n        LOGGER.debug(f'COMET WARNING: Image: {image_path} has no bounding boxes predictions')\n        return None\n\n    data = []\n    for prediction in predictions:\n        boxes = prediction['bbox']\n        score = _scale_confidence_score(prediction['score'])\n        cls_label = prediction['category_id']\n        if class_label_map:\n            cls_label = str(class_label_map[cls_label])\n\n        data.append({'boxes': [boxes], 'label': cls_label, 'score': score})\n\n    return {'name': 'prediction', 'data': data}\n\n\ndef _fetch_annotations(img_idx, image_path, batch, prediction_metadata_map, class_label_map):\n    \"\"\"Join the ground truth and prediction annotations if they exist.\"\"\"\n    ground_truth_annotations = _format_ground_truth_annotations_for_detection(img_idx, image_path, batch,\n                                                                              class_label_map)\n    prediction_annotations = _format_prediction_annotations_for_detection(image_path, prediction_metadata_map,\n                                                                          class_label_map)\n\n    annotations = [\n        annotation for annotation in [ground_truth_annotations, prediction_annotations] if annotation is not None]\n    return [annotations] if annotations else None\n\n\ndef _create_prediction_metadata_map(model_predictions):\n    \"\"\"Create metadata map for model predictions by groupings them based on image ID.\"\"\"\n    pred_metadata_map = {}\n    for prediction in model_predictions:\n        pred_metadata_map.setdefault(prediction['image_id'], [])\n        pred_metadata_map[prediction['image_id']].append(prediction)\n\n    return pred_metadata_map\n\n\ndef _log_confusion_matrix(experiment, trainer, curr_step, curr_epoch):\n    \"\"\"Log the confusion matrix to Comet experiment.\"\"\"\n    conf_mat = trainer.validator.confusion_matrix.matrix\n    names = list(trainer.data['names'].values()) + ['background']\n    experiment.log_confusion_matrix(\n        matrix=conf_mat,\n        labels=names,\n        max_categories=len(names),\n        epoch=curr_epoch,\n        step=curr_step,\n    )\n\n\ndef _log_images(experiment, image_paths, curr_step, annotations=None):\n    \"\"\"Logs images to the experiment with optional annotations.\"\"\"\n    if annotations:\n        for image_path, annotation in zip(image_paths, annotations):\n            experiment.log_image(image_path, name=image_path.stem, step=curr_step, annotations=annotation)\n\n    else:\n        for image_path in image_paths:\n            experiment.log_image(image_path, name=image_path.stem, step=curr_step)\n\n\ndef _log_image_predictions(experiment, validator, curr_step):\n    \"\"\"Logs predicted boxes for a single image during training.\"\"\"\n    global _comet_image_prediction_count\n\n    task = validator.args.task\n    if task not in COMET_SUPPORTED_TASKS:\n        return\n\n    jdict = validator.jdict\n    if not jdict:\n        return\n\n    predictions_metadata_map = _create_prediction_metadata_map(jdict)\n    dataloader = validator.dataloader\n    class_label_map = validator.names\n\n    batch_logging_interval = _get_eval_batch_logging_interval()\n    max_image_predictions = _get_max_image_predictions_to_log()\n\n    for batch_idx, batch in enumerate(dataloader):\n        if (batch_idx + 1) % batch_logging_interval != 0:\n            continue\n\n        image_paths = batch['im_file']\n        for img_idx, image_path in enumerate(image_paths):\n            if _comet_image_prediction_count >= max_image_predictions:\n                return\n\n            image_path = Path(image_path)\n            annotations = _fetch_annotations(\n                img_idx,\n                image_path,\n                batch,\n                predictions_metadata_map,\n                class_label_map,\n            )\n            _log_images(\n                experiment,\n                [image_path],\n                curr_step,\n                annotations=annotations,\n            )\n            _comet_image_prediction_count += 1\n\n\ndef _log_plots(experiment, trainer):\n    \"\"\"Logs evaluation plots and label plots for the experiment.\"\"\"\n    plot_filenames = [trainer.save_dir / f'{plots}.png' for plots in EVALUATION_PLOT_NAMES]\n    _log_images(experiment, plot_filenames, None)\n\n    label_plot_filenames = [trainer.save_dir / f'{labels}.jpg' for labels in LABEL_PLOT_NAMES]\n    _log_images(experiment, label_plot_filenames, None)\n\n\ndef _log_model(experiment, trainer):\n    \"\"\"Log the best-trained model to Comet.ml.\"\"\"\n    model_name = _get_comet_model_name()\n    experiment.log_model(\n        model_name,\n        file_or_folder=str(trainer.best),\n        file_name='best.pt',\n        overwrite=True,\n    )\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Creates or resumes a CometML experiment at the start of a YOLO pre-training routine.\"\"\"\n    experiment = comet_ml.get_global_experiment()\n    is_alive = getattr(experiment, 'alive', False)\n    if not experiment or not is_alive:\n        _create_experiment(trainer.args)\n\n\ndef on_train_epoch_end(trainer):\n    \"\"\"Log metrics and save batch images at the end of training epochs.\"\"\"\n    experiment = comet_ml.get_global_experiment()\n    if not experiment:\n        return\n\n    metadata = _fetch_trainer_metadata(trainer)\n    curr_epoch = metadata['curr_epoch']\n    curr_step = metadata['curr_step']\n\n    experiment.log_metrics(\n        trainer.label_loss_items(trainer.tloss, prefix='train'),\n        step=curr_step,\n        epoch=curr_epoch,\n    )\n\n    if curr_epoch == 1:\n        _log_images(experiment, trainer.save_dir.glob('train_batch*.jpg'), curr_step)\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Logs model assets at the end of each epoch.\"\"\"\n    experiment = comet_ml.get_global_experiment()\n    if not experiment:\n        return\n\n    metadata = _fetch_trainer_metadata(trainer)\n    curr_epoch = metadata['curr_epoch']\n    curr_step = metadata['curr_step']\n    save_assets = metadata['save_assets']\n\n    experiment.log_metrics(trainer.metrics, step=curr_step, epoch=curr_epoch)\n    experiment.log_metrics(trainer.lr, step=curr_step, epoch=curr_epoch)\n    if curr_epoch == 1:\n        experiment.log_metrics(model_info_for_loggers(trainer), step=curr_step, epoch=curr_epoch)\n\n    if not save_assets:\n        return\n\n    _log_model(experiment, trainer)\n    if _should_log_confusion_matrix():\n        _log_confusion_matrix(experiment, trainer, curr_step, curr_epoch)\n    if _should_log_image_predictions():\n        _log_image_predictions(experiment, trainer.validator, curr_step)\n\n\ndef on_train_end(trainer):\n    \"\"\"Perform operations at the end of training.\"\"\"\n    experiment = comet_ml.get_global_experiment()\n    if not experiment:\n        return\n\n    metadata = _fetch_trainer_metadata(trainer)\n    curr_epoch = metadata['curr_epoch']\n    curr_step = metadata['curr_step']\n    plots = trainer.args.plots\n\n    _log_model(experiment, trainer)\n    if plots:\n        _log_plots(experiment, trainer)\n\n    _log_confusion_matrix(experiment, trainer, curr_step, curr_epoch)\n    _log_image_predictions(experiment, trainer.validator, curr_step)\n    experiment.end()\n\n    global _comet_image_prediction_count\n    _comet_image_prediction_count = 0\n\n\ncallbacks = {\n    'on_pretrain_routine_start': on_pretrain_routine_start,\n    'on_train_epoch_end': on_train_epoch_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_train_end': on_train_end} if comet_ml else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/dvc.py",
    "content": "# Ultralytics YOLO 🚀, GPL-3.0 license\nimport os\n\nimport pkg_resources as pkg\n\nfrom ultralytics.yolo.utils import LOGGER, TESTS_RUNNING\nfrom ultralytics.yolo.utils.torch_utils import model_info_for_loggers\n\ntry:\n    from importlib.metadata import version\n\n    import dvclive\n\n    assert not TESTS_RUNNING  # do not log pytest\n\n    ver = version('dvclive')\n    if pkg.parse_version(ver) < pkg.parse_version('2.11.0'):\n        LOGGER.debug(f'DVCLive is detected but version {ver} is incompatible (>=2.11 required).')\n        dvclive = None  # noqa: F811\nexcept (ImportError, AssertionError, TypeError):\n    dvclive = None\n\n# DVCLive logger instance\nlive = None\n_processed_plots = {}\n\n# `on_fit_epoch_end` is called on final validation (probably need to be fixed)\n# for now this is the way we distinguish final evaluation of the best model vs\n# last epoch validation\n_training_epoch = False\n\n\ndef _logger_disabled():\n    return os.getenv('ULTRALYTICS_DVC_DISABLED', 'false').lower() == 'true'\n\n\ndef _log_images(image_path, prefix=''):\n    if live:\n        live.log_image(os.path.join(prefix, image_path.name), image_path)\n\n\ndef _log_plots(plots, prefix=''):\n    for name, params in plots.items():\n        timestamp = params['timestamp']\n        if _processed_plots.get(name) != timestamp:\n            _log_images(name, prefix)\n            _processed_plots[name] = timestamp\n\n\ndef _log_confusion_matrix(validator):\n    targets = []\n    preds = []\n    matrix = validator.confusion_matrix.matrix\n    names = list(validator.names.values())\n    if validator.confusion_matrix.task == 'detect':\n        names += ['background']\n\n    for ti, pred in enumerate(matrix.T.astype(int)):\n        for pi, num in enumerate(pred):\n            targets.extend([names[ti]] * num)\n            preds.extend([names[pi]] * num)\n\n    live.log_sklearn_plot('confusion_matrix', targets, preds, name='cf.json', normalized=True)\n\n\ndef on_pretrain_routine_start(trainer):\n    try:\n        global live\n        if not _logger_disabled():\n            live = dvclive.Live(save_dvc_exp=True)\n            LOGGER.info(\n                'DVCLive is detected and auto logging is enabled (can be disabled with `ULTRALYTICS_DVC_DISABLED=true`).'\n            )\n        else:\n            LOGGER.debug('DVCLive is detected and auto logging is disabled via `ULTRALYTICS_DVC_DISABLED`.')\n            live = None\n    except Exception as e:\n        LOGGER.warning(f'WARNING ⚠️ DVCLive installed but not initialized correctly, not logging this run. {e}')\n\n\ndef on_pretrain_routine_end(trainer):\n    _log_plots(trainer.plots, 'train')\n\n\ndef on_train_start(trainer):\n    if live:\n        live.log_params(trainer.args)\n\n\ndef on_train_epoch_start(trainer):\n    global _training_epoch\n    _training_epoch = True\n\n\ndef on_fit_epoch_end(trainer):\n    global _training_epoch\n    if live and _training_epoch:\n        all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix='train'), **trainer.metrics, **trainer.lr}\n        for metric, value in all_metrics.items():\n            live.log_metric(metric, value)\n\n        if trainer.epoch == 0:\n            for metric, value in model_info_for_loggers(trainer).items():\n                live.log_metric(metric, value, plot=False)\n\n        _log_plots(trainer.plots, 'train')\n        _log_plots(trainer.validator.plots, 'val')\n\n        live.next_step()\n        _training_epoch = False\n\n\ndef on_train_end(trainer):\n    if live:\n        # At the end log the best metrics. It runs validator on the best model internally.\n        all_metrics = {**trainer.label_loss_items(trainer.tloss, prefix='train'), **trainer.metrics, **trainer.lr}\n        for metric, value in all_metrics.items():\n            live.log_metric(metric, value, plot=False)\n\n        _log_plots(trainer.plots, 'eval')\n        _log_plots(trainer.validator.plots, 'eval')\n        _log_confusion_matrix(trainer.validator)\n\n        if trainer.best.exists():\n            live.log_artifact(trainer.best, copy=True)\n\n        live.end()\n\n\ncallbacks = {\n    'on_pretrain_routine_start': on_pretrain_routine_start,\n    'on_pretrain_routine_end': on_pretrain_routine_end,\n    'on_train_start': on_train_start,\n    'on_train_epoch_start': on_train_epoch_start,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_train_end': on_train_end} if dvclive else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/hub.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport json\nfrom time import time\n\nfrom ultralytics.hub.utils import PREFIX, events\nfrom ultralytics.yolo.utils import LOGGER\nfrom ultralytics.yolo.utils.torch_utils import model_info_for_loggers\n\n\ndef on_pretrain_routine_end(trainer):\n    \"\"\"Logs info before starting timer for upload rate limit.\"\"\"\n    session = getattr(trainer, 'hub_session', None)\n    if session:\n        # Start timer for upload rate limit\n        LOGGER.info(f'{PREFIX}View model at https://hub.ultralytics.com/models/{session.model_id} 🚀')\n        session.timers = {'metrics': time(), 'ckpt': time()}  # start timer on session.rate_limit\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Uploads training progress metrics at the end of each epoch.\"\"\"\n    session = getattr(trainer, 'hub_session', None)\n    if session:\n        # Upload metrics after val end\n        all_plots = {**trainer.label_loss_items(trainer.tloss, prefix='train'), **trainer.metrics}\n        if trainer.epoch == 0:\n            all_plots = {**all_plots, **model_info_for_loggers(trainer)}\n        session.metrics_queue[trainer.epoch] = json.dumps(all_plots)\n        if time() - session.timers['metrics'] > session.rate_limits['metrics']:\n            session.upload_metrics()\n            session.timers['metrics'] = time()  # reset timer\n            session.metrics_queue = {}  # reset queue\n\n\ndef on_model_save(trainer):\n    \"\"\"Saves checkpoints to Ultralytics HUB with rate limiting.\"\"\"\n    session = getattr(trainer, 'hub_session', None)\n    if session:\n        # Upload checkpoints with rate limiting\n        is_best = trainer.best_fitness == trainer.fitness\n        if time() - session.timers['ckpt'] > session.rate_limits['ckpt']:\n            LOGGER.info(f'{PREFIX}Uploading checkpoint https://hub.ultralytics.com/models/{session.model_id}')\n            session.upload_model(trainer.epoch, trainer.last, is_best)\n            session.timers['ckpt'] = time()  # reset timer\n\n\ndef on_train_end(trainer):\n    \"\"\"Upload final model and metrics to Ultralytics HUB at the end of training.\"\"\"\n    session = getattr(trainer, 'hub_session', None)\n    if session:\n        # Upload final model and metrics with exponential standoff\n        LOGGER.info(f'{PREFIX}Syncing final model...')\n        session.upload_model(trainer.epoch, trainer.best, map=trainer.metrics.get('metrics/mAP50-95(B)', 0), final=True)\n        session.alive = False  # stop heartbeats\n        LOGGER.info(f'{PREFIX}Done ✅\\n'\n                    f'{PREFIX}View model at https://hub.ultralytics.com/models/{session.model_id} 🚀')\n\n\ndef on_train_start(trainer):\n    \"\"\"Run events on train start.\"\"\"\n    events(trainer.args)\n\n\ndef on_val_start(validator):\n    \"\"\"Runs events on validation start.\"\"\"\n    events(validator.args)\n\n\ndef on_predict_start(predictor):\n    \"\"\"Run events on predict start.\"\"\"\n    events(predictor.args)\n\n\ndef on_export_start(exporter):\n    \"\"\"Run events on export start.\"\"\"\n    events(exporter.args)\n\n\ncallbacks = {\n    'on_pretrain_routine_end': on_pretrain_routine_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_model_save': on_model_save,\n    'on_train_end': on_train_end,\n    'on_train_start': on_train_start,\n    'on_val_start': on_val_start,\n    'on_predict_start': on_predict_start,\n    'on_export_start': on_export_start}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/mlflow.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nimport re\nfrom pathlib import Path\n\nfrom ultralytics.yolo.utils import LOGGER, TESTS_RUNNING, colorstr\n\ntry:\n    import mlflow\n\n    assert not TESTS_RUNNING  # do not log pytest\n    assert hasattr(mlflow, '__version__')  # verify package is not directory\nexcept (ImportError, AssertionError):\n    mlflow = None\n\n\ndef on_pretrain_routine_end(trainer):\n    \"\"\"Logs training parameters to MLflow.\"\"\"\n    global mlflow, run, run_id, experiment_name\n\n    if os.environ.get('MLFLOW_TRACKING_URI') is None:\n        mlflow = None\n\n    if mlflow:\n        mlflow_location = os.environ['MLFLOW_TRACKING_URI']  # \"http://192.168.xxx.xxx:5000\"\n        mlflow.set_tracking_uri(mlflow_location)\n\n        experiment_name = os.environ.get('MLFLOW_EXPERIMENT') or trainer.args.project or '/Shared/YOLOv8'\n        experiment = mlflow.get_experiment_by_name(experiment_name)\n        if experiment is None:\n            mlflow.create_experiment(experiment_name)\n        mlflow.set_experiment(experiment_name)\n\n        prefix = colorstr('MLFlow: ')\n        try:\n            run, active_run = mlflow, mlflow.active_run()\n            if not active_run:\n                active_run = mlflow.start_run(experiment_id=experiment.experiment_id)\n            run_id = active_run.info.run_id\n            LOGGER.info(f'{prefix}Using run_id({run_id}) at {mlflow_location}')\n            run.log_params(vars(trainer.model.args))\n        except Exception as err:\n            LOGGER.error(f'{prefix}Failing init - {repr(err)}')\n            LOGGER.warning(f'{prefix}Continuing without Mlflow')\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Logs training metrics to Mlflow.\"\"\"\n    if mlflow:\n        metrics_dict = {f\"{re.sub('[()]', '', k)}\": float(v) for k, v in trainer.metrics.items()}\n        run.log_metrics(metrics=metrics_dict, step=trainer.epoch)\n\n\ndef on_train_end(trainer):\n    \"\"\"Called at end of train loop to log model artifact info.\"\"\"\n    if mlflow:\n        root_dir = Path(__file__).resolve().parents[3]\n        run.log_artifact(trainer.last)\n        run.log_artifact(trainer.best)\n        run.pyfunc.log_model(artifact_path=experiment_name,\n                             code_path=[str(root_dir)],\n                             artifacts={'model_path': str(trainer.save_dir)},\n                             python_model=run.pyfunc.PythonModel())\n\n\ncallbacks = {\n    'on_pretrain_routine_end': on_pretrain_routine_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_train_end': on_train_end} if mlflow else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/neptune.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\nfrom ultralytics.yolo.utils import LOGGER, TESTS_RUNNING\nfrom ultralytics.yolo.utils.torch_utils import model_info_for_loggers\n\ntry:\n    import neptune\n    from neptune.types import File\n\n    assert not TESTS_RUNNING  # do not log pytest\n    assert hasattr(neptune, '__version__')\nexcept (ImportError, AssertionError):\n    neptune = None\n\nrun = None  # NeptuneAI experiment logger instance\n\n\ndef _log_scalars(scalars, step=0):\n    \"\"\"Log scalars to the NeptuneAI experiment logger.\"\"\"\n    if run:\n        for k, v in scalars.items():\n            run[k].append(value=v, step=step)\n\n\ndef _log_images(imgs_dict, group=''):\n    \"\"\"Log scalars to the NeptuneAI experiment logger.\"\"\"\n    if run:\n        for k, v in imgs_dict.items():\n            run[f'{group}/{k}'].upload(File(v))\n\n\ndef _log_plot(title, plot_path):\n    \"\"\"Log plots to the NeptuneAI experiment logger.\"\"\"\n    \"\"\"\n        Log image as plot in the plot section of NeptuneAI\n\n        arguments:\n        title (str) Title of the plot\n        plot_path (PosixPath or str) Path to the saved image file\n        \"\"\"\n    img = mpimg.imread(plot_path)\n    fig = plt.figure()\n    ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect='auto', xticks=[], yticks=[])  # no ticks\n    ax.imshow(img)\n    run[f'Plots/{title}'].upload(fig)\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Callback function called before the training routine starts.\"\"\"\n    try:\n        global run\n        run = neptune.init_run(project=trainer.args.project or 'YOLOv8', name=trainer.args.name, tags=['YOLOv8'])\n        run['Configuration/Hyperparameters'] = {k: '' if v is None else v for k, v in vars(trainer.args).items()}\n    except Exception as e:\n        LOGGER.warning(f'WARNING ⚠️ NeptuneAI installed but not initialized correctly, not logging this run. {e}')\n\n\ndef on_train_epoch_end(trainer):\n    \"\"\"Callback function called at end of each training epoch.\"\"\"\n    _log_scalars(trainer.label_loss_items(trainer.tloss, prefix='train'), trainer.epoch + 1)\n    _log_scalars(trainer.lr, trainer.epoch + 1)\n    if trainer.epoch == 1:\n        _log_images({f.stem: str(f) for f in trainer.save_dir.glob('train_batch*.jpg')}, 'Mosaic')\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Callback function called at end of each fit (train+val) epoch.\"\"\"\n    if run and trainer.epoch == 0:\n        run['Configuration/Model'] = model_info_for_loggers(trainer)\n    _log_scalars(trainer.metrics, trainer.epoch + 1)\n\n\ndef on_val_end(validator):\n    \"\"\"Callback function called at end of each validation.\"\"\"\n    if run:\n        # Log val_labels and val_pred\n        _log_images({f.stem: str(f) for f in validator.save_dir.glob('val*.jpg')}, 'Validation')\n\n\ndef on_train_end(trainer):\n    \"\"\"Callback function called at end of training.\"\"\"\n    if run:\n        # Log final results, CM matrix + PR plots\n        files = [\n            'results.png', 'confusion_matrix.png', 'confusion_matrix_normalized.png',\n            *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))]\n        files = [(trainer.save_dir / f) for f in files if (trainer.save_dir / f).exists()]  # filter\n        for f in files:\n            _log_plot(title=f.stem, plot_path=f)\n        # Log the final model\n        run[f'weights/{trainer.args.name or trainer.args.task}/{str(trainer.best.name)}'].upload(File(str(\n            trainer.best)))\n\n\ncallbacks = {\n    'on_pretrain_routine_start': on_pretrain_routine_start,\n    'on_train_epoch_end': on_train_epoch_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_val_end': on_val_end,\n    'on_train_end': on_train_end} if neptune else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/raytune.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\ntry:\n    import ray\n    from ray import tune\n    from ray.air import session\nexcept (ImportError, AssertionError):\n    tune = None\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Sends training metrics to Ray Tune at end of each epoch.\"\"\"\n    if ray.tune.is_session_enabled():\n        metrics = trainer.metrics\n        metrics['epoch'] = trainer.epoch\n        session.report(metrics)\n\n\ncallbacks = {\n    'on_fit_epoch_end': on_fit_epoch_end, } if tune else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/tensorboard.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom ultralytics.yolo.utils import LOGGER, TESTS_RUNNING, colorstr\n\ntry:\n    from torch.utils.tensorboard import SummaryWriter\n\n    assert not TESTS_RUNNING  # do not log pytest\nexcept (ImportError, AssertionError):\n    SummaryWriter = None\n\nwriter = None  # TensorBoard SummaryWriter instance\n\n\ndef _log_scalars(scalars, step=0):\n    \"\"\"Logs scalar values to TensorBoard.\"\"\"\n    if writer:\n        for k, v in scalars.items():\n            writer.add_scalar(k, v, step)\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Initialize TensorBoard logging with SummaryWriter.\"\"\"\n    if SummaryWriter:\n        try:\n            global writer\n            writer = SummaryWriter(str(trainer.save_dir))\n            prefix = colorstr('TensorBoard: ')\n            LOGGER.info(f\"{prefix}Start with 'tensorboard --logdir {trainer.save_dir}', view at http://localhost:6006/\")\n        except Exception as e:\n            LOGGER.warning(f'WARNING ⚠️ TensorBoard not initialized correctly, not logging this run. {e}')\n\n\ndef on_batch_end(trainer):\n    \"\"\"Logs scalar statistics at the end of a training batch.\"\"\"\n    _log_scalars(trainer.label_loss_items(trainer.tloss, prefix='train'), trainer.epoch + 1)\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Logs epoch metrics at end of training epoch.\"\"\"\n    _log_scalars(trainer.metrics, trainer.epoch + 1)\n\n\ncallbacks = {\n    'on_pretrain_routine_start': on_pretrain_routine_start,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_batch_end': on_batch_end}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/wb.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nfrom ultralytics.yolo.utils import TESTS_RUNNING\nfrom ultralytics.yolo.utils.torch_utils import model_info_for_loggers\n\ntry:\n    import wandb as wb\n\n    assert hasattr(wb, '__version__')\n    assert not TESTS_RUNNING  # do not log pytest\nexcept (ImportError, AssertionError):\n    wb = None\n\n_processed_plots = {}\n\n\ndef _log_plots(plots, step):\n    for name, params in plots.items():\n        timestamp = params['timestamp']\n        if _processed_plots.get(name, None) != timestamp:\n            wb.run.log({name.stem: wb.Image(str(name))}, step=step)\n            _processed_plots[name] = timestamp\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Initiate and start project if module is present.\"\"\"\n    wb.run or wb.init(project=trainer.args.project or 'YOLOv8', name=trainer.args.name, config=vars(trainer.args))\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Logs training metrics and model information at the end of an epoch.\"\"\"\n    wb.run.log(trainer.metrics, step=trainer.epoch + 1)\n    _log_plots(trainer.plots, step=trainer.epoch + 1)\n    _log_plots(trainer.validator.plots, step=trainer.epoch + 1)\n    if trainer.epoch == 0:\n        wb.run.log(model_info_for_loggers(trainer), step=trainer.epoch + 1)\n\n\ndef on_train_epoch_end(trainer):\n    \"\"\"Log metrics and save images at the end of each training epoch.\"\"\"\n    wb.run.log(trainer.label_loss_items(trainer.tloss, prefix='train'), step=trainer.epoch + 1)\n    wb.run.log(trainer.lr, step=trainer.epoch + 1)\n    if trainer.epoch == 1:\n        _log_plots(trainer.plots, step=trainer.epoch + 1)\n\n\ndef on_train_end(trainer):\n    \"\"\"Save the best model as an artifact at end of training.\"\"\"\n    _log_plots(trainer.validator.plots, step=trainer.epoch + 1)\n    _log_plots(trainer.plots, step=trainer.epoch + 1)\n    art = wb.Artifact(type='model', name=f'run_{wb.run.id}_model')\n    if trainer.best.exists():\n        art.add_file(trainer.best)\n        wb.run.log_artifact(art)\n\n\ncallbacks = {\n    'on_pretrain_routine_start': on_pretrain_routine_start,\n    'on_train_epoch_end': on_train_epoch_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_train_end': on_train_end} if wb else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/checks.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nimport contextlib\nimport glob\nimport inspect\nimport math\nimport os\nimport platform\nimport re\nimport shutil\nimport subprocess\nfrom pathlib import Path\nfrom typing import Optional\n\nimport cv2\nimport numpy as np\nimport pkg_resources as pkg\nimport psutil\nimport requests\nimport torch\nfrom matplotlib import font_manager\n\nfrom ultralytics.yolo.utils import (AUTOINSTALL, LOGGER, ONLINE, ROOT, USER_CONFIG_DIR, TryExcept, clean_url, colorstr,\n                                    downloads, emojis, is_colab, is_docker, is_jupyter, is_kaggle, is_online,\n                                    is_pip_package, url2file)\n\n\ndef is_ascii(s) -> bool:\n    \"\"\"\n    Check if a string is composed of only ASCII characters.\n\n    Args:\n        s (str): String to be checked.\n\n    Returns:\n        bool: True if the string is composed only of ASCII characters, False otherwise.\n    \"\"\"\n    # Convert list, tuple, None, etc. to string\n    s = str(s)\n\n    # Check if the string is composed of only ASCII characters\n    return all(ord(c) < 128 for c in s)\n\n\ndef check_imgsz(imgsz, stride=32, min_dim=1, max_dim=2, floor=0):\n    \"\"\"\n    Verify image size is a multiple of the given stride in each dimension. If the image size is not a multiple of the\n    stride, update it to the nearest multiple of the stride that is greater than or equal to the given floor value.\n\n    Args:\n        imgsz (int | cList[int]): Image size.\n        stride (int): Stride value.\n        min_dim (int): Minimum number of dimensions.\n        floor (int): Minimum allowed value for image size.\n\n    Returns:\n        (List[int]): Updated image size.\n    \"\"\"\n    # Convert stride to integer if it is a tensor\n    stride = int(stride.max() if isinstance(stride, torch.Tensor) else stride)\n\n    # Convert image size to list if it is an integer\n    if isinstance(imgsz, int):\n        imgsz = [imgsz]\n    elif isinstance(imgsz, (list, tuple)):\n        imgsz = list(imgsz)\n    else:\n        raise TypeError(f\"'imgsz={imgsz}' is of invalid type {type(imgsz).__name__}. \"\n                        f\"Valid imgsz types are int i.e. 'imgsz=640' or list i.e. 'imgsz=[640,640]'\")\n\n    # Apply max_dim\n    if len(imgsz) > max_dim:\n        msg = \"'train' and 'val' imgsz must be an integer, while 'predict' and 'export' imgsz may be a [h, w] list \" \\\n              \"or an integer, i.e. 'yolo export imgsz=640,480' or 'yolo export imgsz=640'\"\n        if max_dim != 1:\n            raise ValueError(f'imgsz={imgsz} is not a valid image size. {msg}')\n        LOGGER.warning(f\"WARNING ⚠️ updating to 'imgsz={max(imgsz)}'. {msg}\")\n        imgsz = [max(imgsz)]\n    # Make image size a multiple of the stride\n    sz = [max(math.ceil(x / stride) * stride, floor) for x in imgsz]\n\n    # Print warning message if image size was updated\n    if sz != imgsz:\n        LOGGER.warning(f'WARNING ⚠️ imgsz={imgsz} must be multiple of max stride {stride}, updating to {sz}')\n\n    # Add missing dimensions if necessary\n    sz = [sz[0], sz[0]] if min_dim == 2 and len(sz) == 1 else sz[0] if min_dim == 1 and len(sz) == 1 else sz\n\n    return sz\n\n\ndef check_version(current: str = '0.0.0',\n                  minimum: str = '0.0.0',\n                  name: str = 'version ',\n                  pinned: bool = False,\n                  hard: bool = False,\n                  verbose: bool = False) -> bool:\n    \"\"\"\n    Check current version against the required minimum version.\n\n    Args:\n        current (str): Current version.\n        minimum (str): Required minimum version.\n        name (str): Name to be used in warning message.\n        pinned (bool): If True, versions must match exactly. If False, minimum version must be satisfied.\n        hard (bool): If True, raise an AssertionError if the minimum version is not met.\n        verbose (bool): If True, print warning message if minimum version is not met.\n\n    Returns:\n        (bool): True if minimum version is met, False otherwise.\n    \"\"\"\n    current, minimum = (pkg.parse_version(x) for x in (current, minimum))\n    result = (current == minimum) if pinned else (current >= minimum)  # bool\n    warning_message = f'WARNING ⚠️ {name}{minimum} is required by YOLOv8, but {name}{current} is currently installed'\n    if hard:\n        assert result, emojis(warning_message)  # assert min requirements met\n    if verbose and not result:\n        LOGGER.warning(warning_message)\n    return result\n\n\ndef check_latest_pypi_version(package_name='ultralytics'):\n    \"\"\"\n    Returns the latest version of a PyPI package without downloading or installing it.\n\n    Parameters:\n        package_name (str): The name of the package to find the latest version for.\n\n    Returns:\n        (str): The latest version of the package.\n    \"\"\"\n    with contextlib.suppress(Exception):\n        requests.packages.urllib3.disable_warnings()  # Disable the InsecureRequestWarning\n        response = requests.get(f'https://pypi.org/pypi/{package_name}/json', timeout=3)\n        if response.status_code == 200:\n            return response.json()['info']['version']\n    return None\n\n\ndef check_pip_update_available():\n    \"\"\"\n    Checks if a new version of the ultralytics package is available on PyPI.\n\n    Returns:\n        (bool): True if an update is available, False otherwise.\n    \"\"\"\n    if ONLINE and is_pip_package():\n        with contextlib.suppress(Exception):\n            from ultralytics import __version__\n            latest = check_latest_pypi_version()\n            if pkg.parse_version(__version__) < pkg.parse_version(latest):  # update is available\n                LOGGER.info(f'New https://pypi.org/project/ultralytics/{latest} available 😃 '\n                            f\"Update with 'pip install -U ultralytics'\")\n                return True\n    return False\n\n\ndef check_font(font='Arial.ttf'):\n    \"\"\"\n    Find font locally or download to user's configuration directory if it does not already exist.\n\n    Args:\n        font (str): Path or name of font.\n\n    Returns:\n        file (Path): Resolved font file path.\n    \"\"\"\n    name = Path(font).name\n\n    # Check USER_CONFIG_DIR\n    file = USER_CONFIG_DIR / name\n    if file.exists():\n        return file\n\n    # Check system fonts\n    matches = [s for s in font_manager.findSystemFonts() if font in s]\n    if any(matches):\n        return matches[0]\n\n    # Download to USER_CONFIG_DIR if missing\n    url = f'https://ultralytics.com/assets/{name}'\n    if downloads.is_url(url):\n        downloads.safe_download(url=url, file=file)\n        return file\n\n\ndef check_python(minimum: str = '3.7.0') -> bool:\n    \"\"\"\n    Check current python version against the required minimum version.\n\n    Args:\n        minimum (str): Required minimum version of python.\n\n    Returns:\n        None\n    \"\"\"\n    return check_version(platform.python_version(), minimum, name='Python ', hard=True)\n\n\n@TryExcept()\ndef check_requirements(requirements=ROOT.parent / 'requirements.txt', exclude=(), install=True, cmds=''):\n    \"\"\"\n    Check if installed dependencies meet YOLOv8 requirements and attempt to auto-update if needed.\n\n    Args:\n        requirements (Union[Path, str, List[str]]): Path to a requirements.txt file, a single package requirement as a\n            string, or a list of package requirements as strings.\n        exclude (Tuple[str]): Tuple of package names to exclude from checking.\n        install (bool): If True, attempt to auto-update packages that don't meet requirements.\n        cmds (str): Additional commands to pass to the pip install command when auto-updating.\n    \"\"\"\n    prefix = colorstr('red', 'bold', 'requirements:')\n    check_python()  # check python version\n    file = None\n    if isinstance(requirements, Path):  # requirements.txt file\n        file = requirements.resolve()\n        assert file.exists(), f'{prefix} {file} not found, check failed.'\n        with file.open() as f:\n            requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(f) if x.name not in exclude]\n    elif isinstance(requirements, str):\n        requirements = [requirements]\n\n    s = ''  # console string\n    n = 0  # number of packages updates\n    for r in requirements:\n        try:\n            pkg.require(r)\n        except (pkg.VersionConflict, pkg.DistributionNotFound):  # exception if requirements not met\n            try:  # attempt to import (slower but more accurate)\n                import importlib\n                importlib.import_module(next(pkg.parse_requirements(r)).name)\n            except ImportError:\n                s += f'\"{r}\" '\n                n += 1\n\n    if s:\n        if install and AUTOINSTALL:  # check environment variable\n            LOGGER.info(f\"{prefix} Ultralytics requirement{'s' * (n > 1)} {s}not found, attempting AutoUpdate...\")\n            try:\n                assert is_online(), 'AutoUpdate skipped (offline)'\n                LOGGER.info(subprocess.check_output(f'pip install --no-cache {s} {cmds}', shell=True).decode())\n                s = f\"{prefix} {n} package{'s' * (n > 1)} updated per {file or requirements}\\n\" \\\n                    f\"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\\n\"\n                LOGGER.info(s)\n            except Exception as e:\n                LOGGER.warning(f'{prefix} ❌ {e}')\n                return False\n        else:\n            return False\n\n    return True\n\n\ndef check_suffix(file='yolov8n.pt', suffix='.pt', msg=''):\n    \"\"\"Check file(s) for acceptable suffix.\"\"\"\n    if file and suffix:\n        if isinstance(suffix, str):\n            suffix = (suffix, )\n        for f in file if isinstance(file, (list, tuple)) else [file]:\n            s = Path(f).suffix.lower().strip()  # file suffix\n            if len(s):\n                assert s in suffix, f'{msg}{f} acceptable suffix is {suffix}, not {s}'\n\n\ndef check_yolov5u_filename(file: str, verbose: bool = True):\n    \"\"\"Replace legacy YOLOv5 filenames with updated YOLOv5u filenames.\"\"\"\n    if ('yolov3' in file or 'yolov5' in file) and 'u' not in file:\n        original_file = file\n        file = re.sub(r'(.*yolov5([nsmlx]))\\.pt', '\\\\1u.pt', file)  # i.e. yolov5n.pt -> yolov5nu.pt\n        file = re.sub(r'(.*yolov5([nsmlx])6)\\.pt', '\\\\1u.pt', file)  # i.e. yolov5n6.pt -> yolov5n6u.pt\n        file = re.sub(r'(.*yolov3(|-tiny|-spp))\\.pt', '\\\\1u.pt', file)  # i.e. yolov3-spp.pt -> yolov3-sppu.pt\n        if file != original_file and verbose:\n            LOGGER.info(f\"PRO TIP 💡 Replace 'model={original_file}' with new 'model={file}'.\\nYOLOv5 'u' models are \"\n                        f'trained with https://github.com/ultralytics/ultralytics and feature improved performance vs '\n                        f'standard YOLOv5 models trained with https://github.com/ultralytics/yolov5.\\n')\n    return file\n\n\ndef check_file(file, suffix='', download=True, hard=True):\n    \"\"\"Search/download file (if necessary) and return path.\"\"\"\n    check_suffix(file, suffix)  # optional\n    file = str(file).strip()  # convert to string and strip spaces\n    file = check_yolov5u_filename(file)  # yolov5n -> yolov5nu\n    if not file or ('://' not in file and Path(file).exists()):  # exists ('://' check required in Windows Python<3.10)\n        return file\n    elif download and file.lower().startswith(('https://', 'http://', 'rtsp://', 'rtmp://')):  # download\n        url = file  # warning: Pathlib turns :// -> :/\n        file = url2file(file)  # '%2F' to '/', split https://url.com/file.txt?auth\n        if Path(file).exists():\n            LOGGER.info(f'Found {clean_url(url)} locally at {file}')  # file already exists\n        else:\n            downloads.safe_download(url=url, file=file, unzip=False)\n        return file\n    else:  # search\n        files = []\n        for d in 'models', 'datasets', 'tracker/cfg', 'yolo/cfg':  # search directories\n            files.extend(glob.glob(str(ROOT / d / '**' / file), recursive=True))  # find file\n        if not files and hard:\n            raise FileNotFoundError(f\"'{file}' does not exist\")\n        elif len(files) > 1 and hard:\n            raise FileNotFoundError(f\"Multiple files match '{file}', specify exact path: {files}\")\n        return files[0] if len(files) else []  # return file\n\n\ndef check_yaml(file, suffix=('.yaml', '.yml'), hard=True):\n    \"\"\"Search/download YAML file (if necessary) and return path, checking suffix.\"\"\"\n    return check_file(file, suffix, hard=hard)\n\n\ndef check_imshow(warn=False):\n    \"\"\"Check if environment supports image displays.\"\"\"\n    try:\n        assert not any((is_colab(), is_kaggle(), is_docker()))\n        cv2.imshow('test', np.zeros((1, 1, 3)))\n        cv2.waitKey(1)\n        cv2.destroyAllWindows()\n        cv2.waitKey(1)\n        return True\n    except Exception as e:\n        if warn:\n            LOGGER.warning(f'WARNING ⚠️ Environment does not support cv2.imshow() or PIL Image.show()\\n{e}')\n        return False\n\n\ndef check_yolo(verbose=True, device=''):\n    \"\"\"Return a human-readable YOLO software and hardware summary.\"\"\"\n    from ultralytics.yolo.utils.torch_utils import select_device\n\n    if is_jupyter():\n        if check_requirements('wandb', install=False):\n            os.system('pip uninstall -y wandb')  # uninstall wandb: unwanted account creation prompt with infinite hang\n        if is_colab():\n            shutil.rmtree('sample_data', ignore_errors=True)  # remove colab /sample_data directory\n\n    if verbose:\n        # System info\n        gib = 1 << 30  # bytes per GiB\n        ram = psutil.virtual_memory().total\n        total, used, free = shutil.disk_usage('/')\n        s = f'({os.cpu_count()} CPUs, {ram / gib:.1f} GB RAM, {(total - free) / gib:.1f}/{total / gib:.1f} GB disk)'\n        with contextlib.suppress(Exception):  # clear display if ipython is installed\n            from IPython import display\n            display.clear_output()\n    else:\n        s = ''\n\n    select_device(device=device, newline=False)\n    LOGGER.info(f'Setup complete ✅ {s}')\n\n\ndef check_amp(model):\n    \"\"\"\n    This function checks the PyTorch Automatic Mixed Precision (AMP) functionality of a YOLOv8 model.\n    If the checks fail, it means there are anomalies with AMP on the system that may cause NaN losses or zero-mAP\n    results, so AMP will be disabled during training.\n\n    Args:\n        model (nn.Module): A YOLOv8 model instance.\n\n    Returns:\n        (bool): Returns True if the AMP functionality works correctly with YOLOv8 model, else False.\n\n    Raises:\n        AssertionError: If the AMP checks fail, indicating anomalies with the AMP functionality on the system.\n    \"\"\"\n    device = next(model.parameters()).device  # get model device\n    if device.type in ('cpu', 'mps'):\n        return False  # AMP only used on CUDA devices\n\n    def amp_allclose(m, im):\n        \"\"\"All close FP32 vs AMP results.\"\"\"\n        a = m(im, device=device, verbose=False)[0].boxes.data  # FP32 inference\n        with torch.cuda.amp.autocast(True):\n            b = m(im, device=device, verbose=False)[0].boxes.data  # AMP inference\n        del m\n        return a.shape == b.shape and torch.allclose(a, b.float(), atol=0.5)  # close to 0.5 absolute tolerance\n\n    f = ROOT / 'assets/bus.jpg'  # image to check\n    im = f if f.exists() else 'https://ultralytics.com/images/bus.jpg' if ONLINE else np.ones((640, 640, 3))\n    prefix = colorstr('AMP: ')\n    LOGGER.info(f'{prefix}running Automatic Mixed Precision (AMP) checks with YOLOv8n...')\n    warning_msg = \"Setting 'amp=True'. If you experience zero-mAP or NaN losses you can disable AMP with amp=False.\"\n    try:\n        from ultralytics import YOLO\n        assert amp_allclose(YOLO('yolov8n.pt'), im)\n        LOGGER.info(f'{prefix}checks passed ✅')\n    except ConnectionError:\n        LOGGER.warning(f'{prefix}checks skipped ⚠️, offline and unable to download YOLOv8n. {warning_msg}')\n    except (AttributeError, ModuleNotFoundError):\n        LOGGER.warning(\n            f'{prefix}checks skipped ⚠️. Unable to load YOLOv8n due to possible Ultralytics package modifications. {warning_msg}'\n        )\n    except AssertionError:\n        LOGGER.warning(f'{prefix}checks failed ❌. Anomalies were detected with AMP on your system that may lead to '\n                       f'NaN losses or zero-mAP results, so AMP will be disabled during training.')\n        return False\n    return True\n\n\ndef git_describe(path=ROOT):  # path must be a directory\n    # Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe\n    try:\n        assert (Path(path) / '.git').is_dir()\n        return subprocess.check_output(f'git -C {path} describe --tags --long --always', shell=True).decode()[:-1]\n    except AssertionError:\n        return ''\n\n\ndef print_args(args: Optional[dict] = None, show_file=True, show_func=False):\n    \"\"\"Print function arguments (optional args dict).\"\"\"\n\n    def strip_auth(v):\n        \"\"\"Clean longer Ultralytics HUB URLs by stripping potential authentication information.\"\"\"\n        return clean_url(v) if (isinstance(v, str) and v.startswith('http') and len(v) > 100) else v\n\n    x = inspect.currentframe().f_back  # previous frame\n    file, _, func, _, _ = inspect.getframeinfo(x)\n    if args is None:  # get args automatically\n        args, _, _, frm = inspect.getargvalues(x)\n        args = {k: v for k, v in frm.items() if k in args}\n    try:\n        file = Path(file).resolve().relative_to(ROOT).with_suffix('')\n    except ValueError:\n        file = Path(file).stem\n    s = (f'{file}: ' if show_file else '') + (f'{func}: ' if show_func else '')\n    LOGGER.info(colorstr(s) + ', '.join(f'{k}={strip_auth(v)}' for k, v in args.items()))\n"
  },
  {
    "path": "ultralytics/yolo/utils/dist.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nimport re\nimport shutil\nimport socket\nimport sys\nimport tempfile\nfrom pathlib import Path\n\nfrom . import USER_CONFIG_DIR\nfrom .torch_utils import TORCH_1_9\n\n\ndef find_free_network_port() -> int:\n    \"\"\"Finds a free port on localhost.\n\n    It is useful in single-node training when we don't want to connect to a real main node but have to set the\n    `MASTER_PORT` environment variable.\n    \"\"\"\n    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n        s.bind(('127.0.0.1', 0))\n        return s.getsockname()[1]  # port\n\n\ndef generate_ddp_file(trainer):\n    \"\"\"Generates a DDP file and returns its file name.\"\"\"\n    module, name = f'{trainer.__class__.__module__}.{trainer.__class__.__name__}'.rsplit('.', 1)\n\n    content = f'''overrides = {vars(trainer.args)} \\nif __name__ == \"__main__\":\n    from {module} import {name}\n    from ultralytics.yolo.utils import DEFAULT_CFG_DICT\n\n    cfg = DEFAULT_CFG_DICT.copy()\n    cfg.update(save_dir='')   # handle the extra key 'save_dir'\n    trainer = {name}(cfg=cfg, overrides=overrides)\n    trainer.train()'''\n    (USER_CONFIG_DIR / 'DDP').mkdir(exist_ok=True)\n    with tempfile.NamedTemporaryFile(prefix='_temp_',\n                                     suffix=f'{id(trainer)}.py',\n                                     mode='w+',\n                                     encoding='utf-8',\n                                     dir=USER_CONFIG_DIR / 'DDP',\n                                     delete=False) as file:\n        file.write(content)\n    return file.name\n\n\ndef generate_ddp_command(world_size, trainer):\n    \"\"\"Generates and returns command for distributed training.\"\"\"\n    import __main__  # noqa local import to avoid https://github.com/Lightning-AI/lightning/issues/15218\n    if not trainer.resume:\n        shutil.rmtree(trainer.save_dir)  # remove the save_dir\n    file = str(Path(sys.argv[0]).resolve())\n    safe_pattern = re.compile(r'^[a-zA-Z0-9_. /\\\\-]{1,128}$')  # allowed characters and maximum of 100 characters\n    if not (safe_pattern.match(file) and Path(file).exists() and file.endswith('.py')):  # using CLI\n        file = generate_ddp_file(trainer)\n    dist_cmd = 'torch.distributed.run' if TORCH_1_9 else 'torch.distributed.launch'\n    port = find_free_network_port()\n    cmd = [sys.executable, '-m', dist_cmd, '--nproc_per_node', f'{world_size}', '--master_port', f'{port}', file]\n    return cmd, file\n\n\ndef ddp_cleanup(trainer, file):\n    \"\"\"Delete temp file if created.\"\"\"\n    if f'{id(trainer)}.py' in file:  # if temp_file suffix in file\n        os.remove(file)\n"
  },
  {
    "path": "ultralytics/yolo/utils/downloads.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport shutil\nimport subprocess\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom urllib import parse, request\nfrom zipfile import BadZipFile, ZipFile, is_zipfile\n\nimport requests\nimport torch\nfrom tqdm import tqdm\n\nfrom ultralytics.yolo.utils import LOGGER, checks, clean_url, emojis, is_online, url2file\n\nGITHUB_ASSET_NAMES = [f'yolov8{k}{suffix}.pt' for k in 'nsmlx' for suffix in ('', '6', '-cls', '-seg', '-pose')] + \\\n                     [f'yolov5{k}u.pt' for k in 'nsmlx'] + \\\n                     [f'yolov3{k}u.pt' for k in ('', '-spp', '-tiny')] + \\\n                     [f'sam_{k}.pt' for k in 'bl'] + \\\n                     [f'rtdetr-{k}.pt' for k in 'lx']\nGITHUB_ASSET_STEMS = [Path(k).stem for k in GITHUB_ASSET_NAMES]\n\n\ndef is_url(url, check=True):\n    \"\"\"Check if string is URL and check if URL exists.\"\"\"\n    with contextlib.suppress(Exception):\n        url = str(url)\n        result = parse.urlparse(url)\n        assert all([result.scheme, result.netloc])  # check if is url\n        if check:\n            with request.urlopen(url) as response:\n                return response.getcode() == 200  # check if exists online\n        return True\n    return False\n\n\ndef unzip_file(file, path=None, exclude=('.DS_Store', '__MACOSX')):\n    \"\"\"\n    Unzips a *.zip file to the specified path, excluding files containing strings in the exclude list.\n\n    If the zipfile does not contain a single top-level directory, the function will create a new\n    directory with the same name as the zipfile (without the extension) to extract its contents.\n    If a path is not provided, the function will use the parent directory of the zipfile as the default path.\n\n    Args:\n        file (str): The path to the zipfile to be extracted.\n        path (str, optional): The path to extract the zipfile to. Defaults to None.\n        exclude (tuple, optional): A tuple of filename strings to be excluded. Defaults to ('.DS_Store', '__MACOSX').\n\n    Raises:\n        BadZipFile: If the provided file does not exist or is not a valid zipfile.\n\n    Returns:\n        (Path): The path to the directory where the zipfile was extracted.\n    \"\"\"\n    if not (Path(file).exists() and is_zipfile(file)):\n        raise BadZipFile(f\"File '{file}' does not exist or is a bad zip file.\")\n    if path is None:\n        path = Path(file).parent  # default path\n\n    with ZipFile(file) as zipObj:\n        file_list = [f for f in zipObj.namelist() if all(x not in f for x in exclude)]\n        top_level_dirs = {Path(f).parts[0] for f in file_list}\n\n        if len(top_level_dirs) > 1 or not file_list[0].endswith('/'):\n            path = Path(path) / Path(file).stem  # define new unzip directory\n\n        for f in file_list:\n            zipObj.extract(f, path=path)\n\n    return path  # return unzip dir\n\n\ndef check_disk_space(url='https://ultralytics.com/assets/coco128.zip', sf=1.5, hard=True):\n    \"\"\"\n    Check if there is sufficient disk space to download and store a file.\n\n    Args:\n        url (str, optional): The URL to the file. Defaults to 'https://ultralytics.com/assets/coco128.zip'.\n        sf (float, optional): Safety factor, the multiplier for the required free space. Defaults to 2.0.\n        hard (bool, optional): Whether to throw an error or not on insufficient disk space. Defaults to True.\n\n    Returns:\n        (bool): True if there is sufficient disk space, False otherwise.\n    \"\"\"\n    with contextlib.suppress(Exception):\n        gib = 1 << 30  # bytes per GiB\n        data = int(requests.head(url).headers['Content-Length']) / gib  # file size (GB)\n        total, used, free = (x / gib for x in shutil.disk_usage('/'))  # bytes\n        if data * sf < free:\n            return True  # sufficient space\n\n        # Insufficient space\n        text = (f'WARNING ⚠️ Insufficient free disk space {free:.1f} GB < {data * sf:.3f} GB required, '\n                f'Please free {data * sf - free:.1f} GB additional disk space and try again.')\n        if hard:\n            raise MemoryError(text)\n        else:\n            LOGGER.warning(text)\n            return False\n\n            # Pass if error\n    return True\n\n\ndef safe_download(url,\n                  file=None,\n                  dir=None,\n                  unzip=True,\n                  delete=False,\n                  curl=False,\n                  retry=3,\n                  min_bytes=1E0,\n                  progress=True):\n    \"\"\"\n    Downloads files from a URL, with options for retrying, unzipping, and deleting the downloaded file.\n\n    Args:\n        url (str): The URL of the file to be downloaded.\n        file (str, optional): The filename of the downloaded file.\n            If not provided, the file will be saved with the same name as the URL.\n        dir (str, optional): The directory to save the downloaded file.\n            If not provided, the file will be saved in the current working directory.\n        unzip (bool, optional): Whether to unzip the downloaded file. Default: True.\n        delete (bool, optional): Whether to delete the downloaded file after unzipping. Default: False.\n        curl (bool, optional): Whether to use curl command line tool for downloading. Default: False.\n        retry (int, optional): The number of times to retry the download in case of failure. Default: 3.\n        min_bytes (float, optional): The minimum number of bytes that the downloaded file should have, to be considered\n            a successful download. Default: 1E0.\n        progress (bool, optional): Whether to display a progress bar during the download. Default: True.\n    \"\"\"\n    f = dir / url2file(url) if dir else Path(file)  # URL converted to filename\n    if '://' not in str(url) and Path(url).is_file():  # URL exists ('://' check required in Windows Python<3.10)\n        f = Path(url)  # filename\n    elif not f.is_file():  # URL and file do not exist\n        assert dir or file, 'dir or file required for download'\n        f = dir / url2file(url) if dir else Path(file)\n        desc = f'Downloading {clean_url(url)} to {f}'\n        LOGGER.info(f'{desc}...')\n        f.parent.mkdir(parents=True, exist_ok=True)  # make directory if missing\n        check_disk_space(url)\n        for i in range(retry + 1):\n            try:\n                if curl or i > 0:  # curl download with retry, continue\n                    s = 'sS' * (not progress)  # silent\n                    r = subprocess.run(['curl', '-#', f'-{s}L', url, '-o', f, '--retry', '3', '-C', '-']).returncode\n                    assert r == 0, f'Curl return value {r}'\n                else:  # urllib download\n                    method = 'torch'\n                    if method == 'torch':\n                        torch.hub.download_url_to_file(url, f, progress=progress)\n                    else:\n                        from ultralytics.yolo.utils import TQDM_BAR_FORMAT\n                        with request.urlopen(url) as response, tqdm(total=int(response.getheader('Content-Length', 0)),\n                                                                    desc=desc,\n                                                                    disable=not progress,\n                                                                    unit='B',\n                                                                    unit_scale=True,\n                                                                    unit_divisor=1024,\n                                                                    bar_format=TQDM_BAR_FORMAT) as pbar:\n                            with open(f, 'wb') as f_opened:\n                                for data in response:\n                                    f_opened.write(data)\n                                    pbar.update(len(data))\n\n                if f.exists():\n                    if f.stat().st_size > min_bytes:\n                        break  # success\n                    f.unlink()  # remove partial downloads\n            except Exception as e:\n                if i == 0 and not is_online():\n                    raise ConnectionError(emojis(f'❌  Download failure for {url}. Environment is not online.')) from e\n                elif i >= retry:\n                    raise ConnectionError(emojis(f'❌  Download failure for {url}. Retry limit reached.')) from e\n                LOGGER.warning(f'⚠️ Download failure, retrying {i + 1}/{retry} {url}...')\n\n    if unzip and f.exists() and f.suffix in ('', '.zip', '.tar', '.gz'):\n        unzip_dir = dir or f.parent  # unzip to dir if provided else unzip in place\n        LOGGER.info(f'Unzipping {f} to {unzip_dir}...')\n        if is_zipfile(f):\n            unzip_dir = unzip_file(file=f, path=unzip_dir)  # unzip\n        elif f.suffix == '.tar':\n            subprocess.run(['tar', 'xf', f, '--directory', unzip_dir], check=True)  # unzip\n        elif f.suffix == '.gz':\n            subprocess.run(['tar', 'xfz', f, '--directory', unzip_dir], check=True)  # unzip\n        if delete:\n            f.unlink()  # remove zip\n        return unzip_dir\n\n\ndef attempt_download_asset(file, repo='ultralytics/assets', release='v0.0.0'):\n    \"\"\"Attempt file download from GitHub release assets if not found locally. release = 'latest', 'v6.2', etc.\"\"\"\n    from ultralytics.yolo.utils import SETTINGS  # scoped for circular import\n\n    def github_assets(repository, version='latest'):\n        \"\"\"Return GitHub repo tag and assets (i.e. ['yolov8n.pt', 'yolov8s.pt', ...]).\"\"\"\n        if version != 'latest':\n            version = f'tags/{version}'  # i.e. tags/v6.2\n        response = requests.get(f'https://api.github.com/repos/{repository}/releases/{version}').json()  # github api\n        return response['tag_name'], [x['name'] for x in response['assets']]  # tag, assets\n\n    # YOLOv3/5u updates\n    file = str(file)\n    file = checks.check_yolov5u_filename(file)\n    file = Path(file.strip().replace(\"'\", ''))\n    if file.exists():\n        return str(file)\n    elif (SETTINGS['weights_dir'] / file).exists():\n        return str(SETTINGS['weights_dir'] / file)\n    else:\n        # URL specified\n        name = Path(parse.unquote(str(file))).name  # decode '%2F' to '/' etc.\n        if str(file).startswith(('http:/', 'https:/')):  # download\n            url = str(file).replace(':/', '://')  # Pathlib turns :// -> :/\n            file = url2file(name)  # parse authentication https://url.com/file.txt?auth...\n            if Path(file).is_file():\n                LOGGER.info(f'Found {clean_url(url)} locally at {file}')  # file already exists\n            else:\n                safe_download(url=url, file=file, min_bytes=1E5)\n            return file\n\n        # GitHub assets\n        assets = GITHUB_ASSET_NAMES\n        try:\n            tag, assets = github_assets(repo, release)\n        except Exception:\n            try:\n                tag, assets = github_assets(repo)  # latest release\n            except Exception:\n                try:\n                    tag = subprocess.check_output(['git', 'tag']).decode().split()[-1]\n                except Exception:\n                    tag = release\n\n        file.parent.mkdir(parents=True, exist_ok=True)  # make parent dir (if required)\n        if name in assets:\n            safe_download(url=f'https://github.com/{repo}/releases/download/{tag}/{name}', file=file, min_bytes=1E5)\n\n        return str(file)\n\n\ndef download(url, dir=Path.cwd(), unzip=True, delete=False, curl=False, threads=1, retry=3):\n    \"\"\"Downloads and unzips files concurrently if threads > 1, else sequentially.\"\"\"\n    dir = Path(dir)\n    dir.mkdir(parents=True, exist_ok=True)  # make directory\n    if threads > 1:\n        with ThreadPool(threads) as pool:\n            pool.map(\n                lambda x: safe_download(\n                    url=x[0], dir=x[1], unzip=unzip, delete=delete, curl=curl, retry=retry, progress=threads <= 1),\n                zip(url, repeat(dir)))\n            pool.close()\n            pool.join()\n    else:\n        for u in [url] if isinstance(url, (str, Path)) else url:\n            safe_download(url=u, dir=dir, unzip=unzip, delete=delete, curl=curl, retry=retry)\n"
  },
  {
    "path": "ultralytics/yolo/utils/errors.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom ultralytics.yolo.utils import emojis\n\n\nclass HUBModelError(Exception):\n\n    def __init__(self, message='Model not found. Please check model URL and try again.'):\n        \"\"\"Create an exception for when a model is not found.\"\"\"\n        super().__init__(emojis(message))\n"
  },
  {
    "path": "ultralytics/yolo/utils/files.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport glob\nimport os\nimport shutil\nfrom datetime import datetime\nfrom pathlib import Path\n\n\nclass WorkingDirectory(contextlib.ContextDecorator):\n    \"\"\"Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager.\"\"\"\n\n    def __init__(self, new_dir):\n        \"\"\"Sets the working directory to 'new_dir' upon instantiation.\"\"\"\n        self.dir = new_dir  # new dir\n        self.cwd = Path.cwd().resolve()  # current dir\n\n    def __enter__(self):\n        \"\"\"Changes the current directory to the specified directory.\"\"\"\n        os.chdir(self.dir)\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        \"\"\"Restore the current working directory on context exit.\"\"\"\n        os.chdir(self.cwd)\n\n\ndef increment_path(path, exist_ok=False, sep='', mkdir=False):\n    \"\"\"\n    Increments a file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.\n\n    If the path exists and exist_ok is not set to True, the path will be incremented by appending a number and sep to\n    the end of the path. If the path is a file, the file extension will be preserved. If the path is a directory, the\n    number will be appended directly to the end of the path. If mkdir is set to True, the path will be created as a\n    directory if it does not already exist.\n\n    Args:\n        path (str, pathlib.Path): Path to increment.\n        exist_ok (bool, optional): If True, the path will not be incremented and returned as-is. Defaults to False.\n        sep (str, optional): Separator to use between the path and the incrementation number. Defaults to ''.\n        mkdir (bool, optional): Create a directory if it does not exist. Defaults to False.\n\n    Returns:\n        (pathlib.Path): Incremented path.\n    \"\"\"\n    path = Path(path)  # os-agnostic\n    if path.exists() and not exist_ok:\n        path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')\n\n        # Method 1\n        for n in range(2, 9999):\n            p = f'{path}{sep}{n}{suffix}'  # increment path\n            if not os.path.exists(p):  #\n                break\n        path = Path(p)\n\n    if mkdir:\n        path.mkdir(parents=True, exist_ok=True)  # make directory\n\n    return path\n\n\ndef file_age(path=__file__):\n    \"\"\"Return days since last file update.\"\"\"\n    dt = (datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime))  # delta\n    return dt.days  # + dt.seconds / 86400  # fractional days\n\n\ndef file_date(path=__file__):\n    \"\"\"Return human-readable file modification date, i.e. '2021-3-26'.\"\"\"\n    t = datetime.fromtimestamp(Path(path).stat().st_mtime)\n    return f'{t.year}-{t.month}-{t.day}'\n\n\ndef file_size(path):\n    \"\"\"Return file/dir size (MB).\"\"\"\n    if isinstance(path, (str, Path)):\n        mb = 1 << 20  # bytes to MiB (1024 ** 2)\n        path = Path(path)\n        if path.is_file():\n            return path.stat().st_size / mb\n        elif path.is_dir():\n            return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / mb\n    return 0.0\n\n\ndef get_latest_run(search_dir='.'):\n    \"\"\"Return path to most recent 'last.pt' in /runs (i.e. to --resume from).\"\"\"\n    last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)\n    return max(last_list, key=os.path.getctime) if last_list else ''\n\n\ndef make_dirs(dir='new_dir/'):\n    # Create folders\n    dir = Path(dir)\n    if dir.exists():\n        shutil.rmtree(dir)  # delete dir\n    for p in dir, dir / 'labels', dir / 'images':\n        p.mkdir(parents=True, exist_ok=True)  # make dir\n    return dir\n"
  },
  {
    "path": "ultralytics/yolo/utils/instance.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom collections import abc\nfrom itertools import repeat\nfrom numbers import Number\nfrom typing import List\n\nimport numpy as np\n\nfrom .ops import ltwh2xywh, ltwh2xyxy, resample_segments, xywh2ltwh, xywh2xyxy, xyxy2ltwh, xyxy2xywh\n\n\ndef _ntuple(n):\n    \"\"\"From PyTorch internals.\"\"\"\n\n    def parse(x):\n        \"\"\"Parse bounding boxes format between XYWH and LTWH.\"\"\"\n        return x if isinstance(x, abc.Iterable) else tuple(repeat(x, n))\n\n    return parse\n\n\nto_4tuple = _ntuple(4)\n\n# `xyxy` means left top and right bottom\n# `xywh` means center x, center y and width, height(yolo format)\n# `ltwh` means left top and width, height(coco format)\n_formats = ['xyxy', 'xywh', 'ltwh']\n\n__all__ = 'Bboxes',  # tuple or list\n\n\nclass Bboxes:\n    \"\"\"Now only numpy is supported.\"\"\"\n\n    def __init__(self, bboxes, format='xyxy') -> None:\n        assert format in _formats, f'Invalid bounding box format: {format}, format must be one of {_formats}'\n        bboxes = bboxes[None, :] if bboxes.ndim == 1 else bboxes\n        assert bboxes.ndim == 2\n        assert bboxes.shape[1] == 4\n        self.bboxes = bboxes\n        self.format = format\n        # self.normalized = normalized\n\n    # def convert(self, format):\n    #     assert format in _formats\n    #     if self.format == format:\n    #         bboxes = self.bboxes\n    #     elif self.format == \"xyxy\":\n    #         if format == \"xywh\":\n    #             bboxes = xyxy2xywh(self.bboxes)\n    #         else:\n    #             bboxes = xyxy2ltwh(self.bboxes)\n    #     elif self.format == \"xywh\":\n    #         if format == \"xyxy\":\n    #             bboxes = xywh2xyxy(self.bboxes)\n    #         else:\n    #             bboxes = xywh2ltwh(self.bboxes)\n    #     else:\n    #         if format == \"xyxy\":\n    #             bboxes = ltwh2xyxy(self.bboxes)\n    #         else:\n    #             bboxes = ltwh2xywh(self.bboxes)\n    #\n    #     return Bboxes(bboxes, format)\n\n    def convert(self, format):\n        \"\"\"Converts bounding box format from one type to another.\"\"\"\n        assert format in _formats, f'Invalid bounding box format: {format}, format must be one of {_formats}'\n        if self.format == format:\n            return\n        elif self.format == 'xyxy':\n            bboxes = xyxy2xywh(self.bboxes) if format == 'xywh' else xyxy2ltwh(self.bboxes)\n        elif self.format == 'xywh':\n            bboxes = xywh2xyxy(self.bboxes) if format == 'xyxy' else xywh2ltwh(self.bboxes)\n        else:\n            bboxes = ltwh2xyxy(self.bboxes) if format == 'xyxy' else ltwh2xywh(self.bboxes)\n        self.bboxes = bboxes\n        self.format = format\n\n    def areas(self):\n        \"\"\"Return box areas.\"\"\"\n        self.convert('xyxy')\n        return (self.bboxes[:, 2] - self.bboxes[:, 0]) * (self.bboxes[:, 3] - self.bboxes[:, 1])\n\n    # def denormalize(self, w, h):\n    #    if not self.normalized:\n    #         return\n    #     assert (self.bboxes <= 1.0).all()\n    #     self.bboxes[:, 0::2] *= w\n    #     self.bboxes[:, 1::2] *= h\n    #     self.normalized = False\n    #\n    # def normalize(self, w, h):\n    #     if self.normalized:\n    #         return\n    #     assert (self.bboxes > 1.0).any()\n    #     self.bboxes[:, 0::2] /= w\n    #     self.bboxes[:, 1::2] /= h\n    #     self.normalized = True\n\n    def mul(self, scale):\n        \"\"\"\n        Args:\n            scale (tuple | list | int): the scale for four coords.\n        \"\"\"\n        if isinstance(scale, Number):\n            scale = to_4tuple(scale)\n        assert isinstance(scale, (tuple, list))\n        assert len(scale) == 4\n        self.bboxes[:, 0] *= scale[0]\n        self.bboxes[:, 1] *= scale[1]\n        self.bboxes[:, 2] *= scale[2]\n        self.bboxes[:, 3] *= scale[3]\n\n    def add(self, offset):\n        \"\"\"\n        Args:\n            offset (tuple | list | int): the offset for four coords.\n        \"\"\"\n        if isinstance(offset, Number):\n            offset = to_4tuple(offset)\n        assert isinstance(offset, (tuple, list))\n        assert len(offset) == 4\n        self.bboxes[:, 0] += offset[0]\n        self.bboxes[:, 1] += offset[1]\n        self.bboxes[:, 2] += offset[2]\n        self.bboxes[:, 3] += offset[3]\n\n    def __len__(self):\n        \"\"\"Return the number of boxes.\"\"\"\n        return len(self.bboxes)\n\n    @classmethod\n    def concatenate(cls, boxes_list: List['Bboxes'], axis=0) -> 'Bboxes':\n        \"\"\"\n        Concatenate a list of Bboxes objects into a single Bboxes object.\n\n        Args:\n            boxes_list (List[Bboxes]): A list of Bboxes objects to concatenate.\n            axis (int, optional): The axis along which to concatenate the bounding boxes.\n                                   Defaults to 0.\n\n        Returns:\n            Bboxes: A new Bboxes object containing the concatenated bounding boxes.\n\n        Note:\n            The input should be a list or tuple of Bboxes objects.\n        \"\"\"\n        assert isinstance(boxes_list, (list, tuple))\n        if not boxes_list:\n            return cls(np.empty(0))\n        assert all(isinstance(box, Bboxes) for box in boxes_list)\n\n        if len(boxes_list) == 1:\n            return boxes_list[0]\n        return cls(np.concatenate([b.bboxes for b in boxes_list], axis=axis))\n\n    def __getitem__(self, index) -> 'Bboxes':\n        \"\"\"\n        Retrieve a specific bounding box or a set of bounding boxes using indexing.\n\n        Args:\n            index (int, slice, or np.ndarray): The index, slice, or boolean array to select\n                                               the desired bounding boxes.\n\n        Returns:\n            Bboxes: A new Bboxes object containing the selected bounding boxes.\n\n        Raises:\n            AssertionError: If the indexed bounding boxes do not form a 2-dimensional matrix.\n\n        Note:\n            When using boolean indexing, make sure to provide a boolean array with the same\n            length as the number of bounding boxes.\n        \"\"\"\n        if isinstance(index, int):\n            return Bboxes(self.bboxes[index].view(1, -1))\n        b = self.bboxes[index]\n        assert b.ndim == 2, f'Indexing on Bboxes with {index} failed to return a matrix!'\n        return Bboxes(b)\n\n\nclass Instances:\n\n    def __init__(self, bboxes, segments=None, keypoints=None, bbox_format='xywh', normalized=True) -> None:\n        \"\"\"\n        Args:\n            bboxes (ndarray): bboxes with shape [N, 4].\n            segments (list | ndarray): segments.\n            keypoints (ndarray): keypoints(x, y, visible) with shape [N, 17, 3].\n        \"\"\"\n        if segments is None:\n            segments = []\n        self._bboxes = Bboxes(bboxes=bboxes, format=bbox_format)\n        self.keypoints = keypoints\n        self.normalized = normalized\n\n        if len(segments) > 0:\n            # list[np.array(1000, 2)] * num_samples\n            segments = resample_segments(segments)\n            # (N, 1000, 2)\n            segments = np.stack(segments, axis=0)\n        else:\n            segments = np.zeros((0, 1000, 2), dtype=np.float32)\n        self.segments = segments\n\n    def convert_bbox(self, format):\n        \"\"\"Convert bounding box format.\"\"\"\n        self._bboxes.convert(format=format)\n\n    @property\n    def bbox_areas(self):\n        \"\"\"Calculate the area of bounding boxes.\"\"\"\n        return self._bboxes.areas()\n\n    def scale(self, scale_w, scale_h, bbox_only=False):\n        \"\"\"this might be similar with denormalize func but without normalized sign.\"\"\"\n        self._bboxes.mul(scale=(scale_w, scale_h, scale_w, scale_h))\n        if bbox_only:\n            return\n        self.segments[..., 0] *= scale_w\n        self.segments[..., 1] *= scale_h\n        if self.keypoints is not None:\n            self.keypoints[..., 0] *= scale_w\n            self.keypoints[..., 1] *= scale_h\n\n    def denormalize(self, w, h):\n        \"\"\"Denormalizes boxes, segments, and keypoints from normalized coordinates.\"\"\"\n        if not self.normalized:\n            return\n        self._bboxes.mul(scale=(w, h, w, h))\n        self.segments[..., 0] *= w\n        self.segments[..., 1] *= h\n        if self.keypoints is not None:\n            self.keypoints[..., 0] *= w\n            self.keypoints[..., 1] *= h\n        self.normalized = False\n\n    def normalize(self, w, h):\n        \"\"\"Normalize bounding boxes, segments, and keypoints to image dimensions.\"\"\"\n        if self.normalized:\n            return\n        self._bboxes.mul(scale=(1 / w, 1 / h, 1 / w, 1 / h))\n        self.segments[..., 0] /= w\n        self.segments[..., 1] /= h\n        if self.keypoints is not None:\n            self.keypoints[..., 0] /= w\n            self.keypoints[..., 1] /= h\n        self.normalized = True\n\n    def add_padding(self, padw, padh):\n        \"\"\"Handle rect and mosaic situation.\"\"\"\n        assert not self.normalized, 'you should add padding with absolute coordinates.'\n        self._bboxes.add(offset=(padw, padh, padw, padh))\n        self.segments[..., 0] += padw\n        self.segments[..., 1] += padh\n        if self.keypoints is not None:\n            self.keypoints[..., 0] += padw\n            self.keypoints[..., 1] += padh\n\n    def __getitem__(self, index) -> 'Instances':\n        \"\"\"\n        Retrieve a specific instance or a set of instances using indexing.\n\n        Args:\n            index (int, slice, or np.ndarray): The index, slice, or boolean array to select\n                                               the desired instances.\n\n        Returns:\n            Instances: A new Instances object containing the selected bounding boxes,\n                       segments, and keypoints if present.\n\n        Note:\n            When using boolean indexing, make sure to provide a boolean array with the same\n            length as the number of instances.\n        \"\"\"\n        segments = self.segments[index] if len(self.segments) else self.segments\n        keypoints = self.keypoints[index] if self.keypoints is not None else None\n        bboxes = self.bboxes[index]\n        bbox_format = self._bboxes.format\n        return Instances(\n            bboxes=bboxes,\n            segments=segments,\n            keypoints=keypoints,\n            bbox_format=bbox_format,\n            normalized=self.normalized,\n        )\n\n    def flipud(self, h):\n        \"\"\"Flips the coordinates of bounding boxes, segments, and keypoints vertically.\"\"\"\n        if self._bboxes.format == 'xyxy':\n            y1 = self.bboxes[:, 1].copy()\n            y2 = self.bboxes[:, 3].copy()\n            self.bboxes[:, 1] = h - y2\n            self.bboxes[:, 3] = h - y1\n        else:\n            self.bboxes[:, 1] = h - self.bboxes[:, 1]\n        self.segments[..., 1] = h - self.segments[..., 1]\n        if self.keypoints is not None:\n            self.keypoints[..., 1] = h - self.keypoints[..., 1]\n\n    def fliplr(self, w):\n        \"\"\"Reverses the order of the bounding boxes and segments horizontally.\"\"\"\n        if self._bboxes.format == 'xyxy':\n            x1 = self.bboxes[:, 0].copy()\n            x2 = self.bboxes[:, 2].copy()\n            self.bboxes[:, 0] = w - x2\n            self.bboxes[:, 2] = w - x1\n        else:\n            self.bboxes[:, 0] = w - self.bboxes[:, 0]\n        self.segments[..., 0] = w - self.segments[..., 0]\n        if self.keypoints is not None:\n            self.keypoints[..., 0] = w - self.keypoints[..., 0]\n\n    def clip(self, w, h):\n        \"\"\"Clips bounding boxes, segments, and keypoints values to stay within image boundaries.\"\"\"\n        ori_format = self._bboxes.format\n        self.convert_bbox(format='xyxy')\n        self.bboxes[:, [0, 2]] = self.bboxes[:, [0, 2]].clip(0, w)\n        self.bboxes[:, [1, 3]] = self.bboxes[:, [1, 3]].clip(0, h)\n        if ori_format != 'xyxy':\n            self.convert_bbox(format=ori_format)\n        self.segments[..., 0] = self.segments[..., 0].clip(0, w)\n        self.segments[..., 1] = self.segments[..., 1].clip(0, h)\n        if self.keypoints is not None:\n            self.keypoints[..., 0] = self.keypoints[..., 0].clip(0, w)\n            self.keypoints[..., 1] = self.keypoints[..., 1].clip(0, h)\n\n    def remove_zero_area_boxes(self):\n        \"\"\"Remove zero-area boxes, i.e. after clipping some boxes may have zero width or height. This removes them.\"\"\"\n        good = self.bbox_areas > 0\n        if not all(good):\n            self._bboxes = self._bboxes[good]\n            if len(self.segments):\n                self.segments = self.segments[good]\n            if self.keypoints is not None:\n                self.keypoints = self.keypoints[good]\n        return good\n\n    def update(self, bboxes, segments=None, keypoints=None):\n        \"\"\"Updates instance variables.\"\"\"\n        self._bboxes = Bboxes(bboxes, format=self._bboxes.format)\n        if segments is not None:\n            self.segments = segments\n        if keypoints is not None:\n            self.keypoints = keypoints\n\n    def __len__(self):\n        \"\"\"Return the length of the instance list.\"\"\"\n        return len(self.bboxes)\n\n    @classmethod\n    def concatenate(cls, instances_list: List['Instances'], axis=0) -> 'Instances':\n        \"\"\"\n        Concatenates a list of Instances objects into a single Instances object.\n\n        Args:\n            instances_list (List[Instances]): A list of Instances objects to concatenate.\n            axis (int, optional): The axis along which the arrays will be concatenated. Defaults to 0.\n\n        Returns:\n            Instances: A new Instances object containing the concatenated bounding boxes,\n                       segments, and keypoints if present.\n\n        Note:\n            The `Instances` objects in the list should have the same properties, such as\n            the format of the bounding boxes, whether keypoints are present, and if the\n            coordinates are normalized.\n        \"\"\"\n        assert isinstance(instances_list, (list, tuple))\n        if not instances_list:\n            return cls(np.empty(0))\n        assert all(isinstance(instance, Instances) for instance in instances_list)\n\n        if len(instances_list) == 1:\n            return instances_list[0]\n\n        use_keypoint = instances_list[0].keypoints is not None\n        bbox_format = instances_list[0]._bboxes.format\n        normalized = instances_list[0].normalized\n\n        cat_boxes = np.concatenate([ins.bboxes for ins in instances_list], axis=axis)\n        cat_segments = np.concatenate([b.segments for b in instances_list], axis=axis)\n        cat_keypoints = np.concatenate([b.keypoints for b in instances_list], axis=axis) if use_keypoint else None\n        return cls(cat_boxes, cat_segments, cat_keypoints, bbox_format, normalized)\n\n    @property\n    def bboxes(self):\n        \"\"\"Return bounding boxes.\"\"\"\n        return self._bboxes.bboxes\n"
  },
  {
    "path": "ultralytics/yolo/utils/loss.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ultralytics.yolo.utils.metrics import OKS_SIGMA\nfrom ultralytics.yolo.utils.ops import crop_mask, xywh2xyxy, xyxy2xywh\nfrom ultralytics.yolo.utils.tal import TaskAlignedAssigner, dist2bbox, make_anchors\n\nfrom .metrics import bbox_iou\nfrom .tal import bbox2dist\n\n\nclass VarifocalLoss(nn.Module):\n    \"\"\"Varifocal loss by Zhang et al. https://arxiv.org/abs/2008.13367.\"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize the VarifocalLoss class.\"\"\"\n        super().__init__()\n\n    def forward(self, pred_score, gt_score, label, alpha=0.75, gamma=2.0):\n        \"\"\"Computes varfocal loss.\"\"\"\n        weight = alpha * pred_score.sigmoid().pow(gamma) * (1 - label) + gt_score * label\n        with torch.cuda.amp.autocast(enabled=False):\n            loss = (F.binary_cross_entropy_with_logits(pred_score.float(), gt_score.float(), reduction='none') *\n                    weight).mean(1).sum()\n        return loss\n\n\n# Losses\nclass FocalLoss(nn.Module):\n    \"\"\"Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5).\"\"\"\n\n    def __init__(self, ):\n        super().__init__()\n\n    def forward(self, pred, label, gamma=1.5, alpha=0.25):\n        \"\"\"Calculates and updates confusion matrix for object detection/classification tasks.\"\"\"\n        loss = F.binary_cross_entropy_with_logits(pred, label, reduction='none')\n        # p_t = torch.exp(-loss)\n        # loss *= self.alpha * (1.000001 - p_t) ** self.gamma  # non-zero power for gradient stability\n\n        # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py\n        pred_prob = pred.sigmoid()  # prob from logits\n        p_t = label * pred_prob + (1 - label) * (1 - pred_prob)\n        modulating_factor = (1.0 - p_t) ** gamma\n        loss *= modulating_factor\n        if alpha > 0:\n            alpha_factor = label * alpha + (1 - label) * (1 - alpha)\n            loss *= alpha_factor\n        return loss.mean(1).sum()\n\n\nclass BboxLoss(nn.Module):\n\n    def __init__(self, reg_max, use_dfl=False):\n        \"\"\"Initialize the BboxLoss module with regularization maximum and DFL settings.\"\"\"\n        super().__init__()\n        self.reg_max = reg_max\n        self.use_dfl = use_dfl\n\n    def forward(self, pred_dist, pred_bboxes, anchor_points, target_bboxes, target_scores, target_scores_sum, fg_mask):\n        \"\"\"IoU loss.\"\"\"\n        weight = target_scores.sum(-1)[fg_mask].unsqueeze(-1)\n        iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, CIoU=True)\n        loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum\n\n        # DFL loss\n        if self.use_dfl:\n            target_ltrb = bbox2dist(anchor_points, target_bboxes, self.reg_max)\n            loss_dfl = self._df_loss(pred_dist[fg_mask].view(-1, self.reg_max + 1), target_ltrb[fg_mask]) * weight\n            loss_dfl = loss_dfl.sum() / target_scores_sum\n        else:\n            loss_dfl = torch.tensor(0.0).to(pred_dist.device)\n\n        return loss_iou, loss_dfl\n\n    @staticmethod\n    def _df_loss(pred_dist, target):\n        \"\"\"Return sum of left and right DFL losses.\"\"\"\n        # Distribution Focal Loss (DFL) proposed in Generalized Focal Loss https://ieeexplore.ieee.org/document/9792391\n        tl = target.long()  # target left\n        tr = tl + 1  # target right\n        wl = tr - target  # weight left\n        wr = 1 - wl  # weight right\n        return (F.cross_entropy(pred_dist, tl.view(-1), reduction='none').view(tl.shape) * wl +\n                F.cross_entropy(pred_dist, tr.view(-1), reduction='none').view(tl.shape) * wr).mean(-1, keepdim=True)\n\n\nclass KeypointLoss(nn.Module):\n\n    def __init__(self, sigmas) -> None:\n        super().__init__()\n        self.sigmas = sigmas\n\n    def forward(self, pred_kpts, gt_kpts, kpt_mask, area):\n        \"\"\"Calculates keypoint loss factor and Euclidean distance loss for predicted and actual keypoints.\"\"\"\n        d = (pred_kpts[..., 0] - gt_kpts[..., 0]) ** 2 + (pred_kpts[..., 1] - gt_kpts[..., 1]) ** 2\n        kpt_loss_factor = (torch.sum(kpt_mask != 0) + torch.sum(kpt_mask == 0)) / (torch.sum(kpt_mask != 0) + 1e-9)\n        # e = d / (2 * (area * self.sigmas) ** 2 + 1e-9)  # from formula\n        e = d / (2 * self.sigmas) ** 2 / (area + 1e-9) / 2  # from cocoeval\n        return kpt_loss_factor * ((1 - torch.exp(-e)) * kpt_mask).mean()\n\n\n# Criterion class for computing Detection training losses\nclass v8DetectionLoss:\n\n    def __init__(self, model):  # model must be de-paralleled\n\n        device = next(model.parameters()).device  # get model device\n        h = model.args  # hyperparameters\n\n        m = model.model[-1]  # Detect() module\n        self.bce = nn.BCEWithLogitsLoss(reduction='none')\n        self.hyp = h\n        self.stride = m.stride  # model strides\n        self.nc = m.nc  # number of classes\n        self.no = m.no\n        self.reg_max = m.reg_max\n        self.device = device\n\n        self.use_dfl = m.reg_max > 1\n\n        self.assigner = TaskAlignedAssigner(topk=10, num_classes=self.nc, alpha=0.5, beta=6.0)\n        self.bbox_loss = BboxLoss(m.reg_max - 1, use_dfl=self.use_dfl).to(device)\n        self.proj = torch.arange(m.reg_max, dtype=torch.float, device=device)\n\n    def preprocess(self, targets, batch_size, scale_tensor):\n        \"\"\"Preprocesses the target counts and matches with the input batch size to output a tensor.\"\"\"\n        if targets.shape[0] == 0:\n            out = torch.zeros(batch_size, 0, 5, device=self.device)\n        else:\n            i = targets[:, 0]  # image index\n            _, counts = i.unique(return_counts=True)\n            counts = counts.to(dtype=torch.int32)\n            out = torch.zeros(batch_size, counts.max(), 5, device=self.device)\n            for j in range(batch_size):\n                matches = i == j\n                n = matches.sum()\n                if n:\n                    out[j, :n] = targets[matches, 1:]\n            out[..., 1:5] = xywh2xyxy(out[..., 1:5].mul_(scale_tensor))\n        return out\n\n    def bbox_decode(self, anchor_points, pred_dist):\n        \"\"\"Decode predicted object bounding box coordinates from anchor points and distribution.\"\"\"\n        if self.use_dfl:\n            b, a, c = pred_dist.shape  # batch, anchors, channels\n            pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype))\n            # pred_dist = pred_dist.view(b, a, c // 4, 4).transpose(2,3).softmax(3).matmul(self.proj.type(pred_dist.dtype))\n            # pred_dist = (pred_dist.view(b, a, c // 4, 4).softmax(2) * self.proj.type(pred_dist.dtype).view(1, 1, -1, 1)).sum(2)\n        return dist2bbox(pred_dist, anchor_points, xywh=False)\n\n    def __call__(self, preds, batch):\n        \"\"\"Calculate the sum of the loss for box, cls and dfl multiplied by batch size.\"\"\"\n        loss = torch.zeros(3, device=self.device)  # box, cls, dfl\n        feats = preds[1] if isinstance(preds, tuple) else preds\n        pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split(\n            (self.reg_max * 4, self.nc), 1)\n\n        pred_scores = pred_scores.permute(0, 2, 1).contiguous()\n        pred_distri = pred_distri.permute(0, 2, 1).contiguous()\n\n        dtype = pred_scores.dtype\n        batch_size = pred_scores.shape[0]\n        imgsz = torch.tensor(feats[0].shape[2:], device=self.device, dtype=dtype) * self.stride[0]  # image size (h,w)\n        anchor_points, stride_tensor = make_anchors(feats, self.stride, 0.5)\n\n        # targets\n        targets = torch.cat((batch['batch_idx'].view(-1, 1), batch['cls'].view(-1, 1), batch['bboxes']), 1)\n        targets = self.preprocess(targets.to(self.device), batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])\n        gt_labels, gt_bboxes = targets.split((1, 4), 2)  # cls, xyxy\n        mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0)\n\n        # pboxes\n        pred_bboxes = self.bbox_decode(anchor_points, pred_distri)  # xyxy, (b, h*w, 4)\n\n        _, target_bboxes, target_scores, fg_mask, _ = self.assigner(\n            pred_scores.detach().sigmoid(), (pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype),\n            anchor_points * stride_tensor, gt_labels, gt_bboxes, mask_gt)\n\n        target_scores_sum = max(target_scores.sum(), 1)\n\n        # cls loss\n        # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum  # VFL way\n        loss[1] = self.bce(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum  # BCE\n\n        # bbox loss\n        if fg_mask.sum():\n            target_bboxes /= stride_tensor\n            loss[0], loss[2] = self.bbox_loss(pred_distri, pred_bboxes, anchor_points, target_bboxes, target_scores,\n                                              target_scores_sum, fg_mask)\n\n        loss[0] *= self.hyp.box  # box gain\n        loss[1] *= self.hyp.cls  # cls gain\n        loss[2] *= self.hyp.dfl  # dfl gain\n\n        return loss.sum() * batch_size, loss.detach()  # loss(box, cls, dfl)\n\n\n# Criterion class for computing training losses\nclass v8SegmentationLoss(v8DetectionLoss):\n\n    def __init__(self, model):  # model must be de-paralleled\n        super().__init__(model)\n        self.nm = model.model[-1].nm  # number of masks\n        self.overlap = model.args.overlap_mask\n\n    def __call__(self, preds, batch):\n        \"\"\"Calculate and return the loss for the YOLO model.\"\"\"\n        loss = torch.zeros(4, device=self.device)  # box, cls, dfl\n        feats, pred_masks, proto = preds if len(preds) == 3 else preds[1]\n        batch_size, _, mask_h, mask_w = proto.shape  # batch size, number of masks, mask height, mask width\n        pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split(\n            (self.reg_max * 4, self.nc), 1)\n\n        # b, grids, ..\n        pred_scores = pred_scores.permute(0, 2, 1).contiguous()\n        pred_distri = pred_distri.permute(0, 2, 1).contiguous()\n        pred_masks = pred_masks.permute(0, 2, 1).contiguous()\n\n        dtype = pred_scores.dtype\n        imgsz = torch.tensor(feats[0].shape[2:], device=self.device, dtype=dtype) * self.stride[0]  # image size (h,w)\n        anchor_points, stride_tensor = make_anchors(feats, self.stride, 0.5)\n\n        # targets\n        try:\n            batch_idx = batch['batch_idx'].view(-1, 1)\n            targets = torch.cat((batch_idx, batch['cls'].view(-1, 1), batch['bboxes']), 1)\n            targets = self.preprocess(targets.to(self.device), batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])\n            gt_labels, gt_bboxes = targets.split((1, 4), 2)  # cls, xyxy\n            mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0)\n        except RuntimeError as e:\n            raise TypeError('ERROR ❌ segment dataset incorrectly formatted or not a segment dataset.\\n'\n                            \"This error can occur when incorrectly training a 'segment' model on a 'detect' dataset, \"\n                            \"i.e. 'yolo train model=yolov8n-seg.pt data=coco128.yaml'.\\nVerify your dataset is a \"\n                            \"correctly formatted 'segment' dataset using 'data=coco128-seg.yaml' \"\n                            'as an example.\\nSee https://docs.ultralytics.com/tasks/segment/ for help.') from e\n\n        # pboxes\n        pred_bboxes = self.bbox_decode(anchor_points, pred_distri)  # xyxy, (b, h*w, 4)\n\n        _, target_bboxes, target_scores, fg_mask, target_gt_idx = self.assigner(\n            pred_scores.detach().sigmoid(), (pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype),\n            anchor_points * stride_tensor, gt_labels, gt_bboxes, mask_gt)\n\n        target_scores_sum = max(target_scores.sum(), 1)\n\n        # cls loss\n        # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum  # VFL way\n        loss[2] = self.bce(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum  # BCE\n\n        if fg_mask.sum():\n            # bbox loss\n            loss[0], loss[3] = self.bbox_loss(pred_distri, pred_bboxes, anchor_points, target_bboxes / stride_tensor,\n                                              target_scores, target_scores_sum, fg_mask)\n            # masks loss\n            masks = batch['masks'].to(self.device).float()\n            if tuple(masks.shape[-2:]) != (mask_h, mask_w):  # downsample\n                masks = F.interpolate(masks[None], (mask_h, mask_w), mode='nearest')[0]\n\n            for i in range(batch_size):\n                if fg_mask[i].sum():\n                    mask_idx = target_gt_idx[i][fg_mask[i]]\n                    if self.overlap:\n                        gt_mask = torch.where(masks[[i]] == (mask_idx + 1).view(-1, 1, 1), 1.0, 0.0)\n                    else:\n                        gt_mask = masks[batch_idx.view(-1) == i][mask_idx]\n                    xyxyn = target_bboxes[i][fg_mask[i]] / imgsz[[1, 0, 1, 0]]\n                    marea = xyxy2xywh(xyxyn)[:, 2:].prod(1)\n                    mxyxy = xyxyn * torch.tensor([mask_w, mask_h, mask_w, mask_h], device=self.device)\n                    loss[1] += self.single_mask_loss(gt_mask, pred_masks[i][fg_mask[i]], proto[i], mxyxy, marea)  # seg\n\n                # WARNING: lines below prevents Multi-GPU DDP 'unused gradient' PyTorch errors, do not remove\n                else:\n                    loss[1] += (proto * 0).sum() + (pred_masks * 0).sum()  # inf sums may lead to nan loss\n\n        # WARNING: lines below prevent Multi-GPU DDP 'unused gradient' PyTorch errors, do not remove\n        else:\n            loss[1] += (proto * 0).sum() + (pred_masks * 0).sum()  # inf sums may lead to nan loss\n\n        loss[0] *= self.hyp.box  # box gain\n        loss[1] *= self.hyp.box / batch_size  # seg gain\n        loss[2] *= self.hyp.cls  # cls gain\n        loss[3] *= self.hyp.dfl  # dfl gain\n\n        return loss.sum() * batch_size, loss.detach()  # loss(box, cls, dfl)\n\n    def single_mask_loss(self, gt_mask, pred, proto, xyxy, area):\n        \"\"\"Mask loss for one image.\"\"\"\n        pred_mask = (pred @ proto.view(self.nm, -1)).view(-1, *proto.shape[1:])  # (n, 32) @ (32,80,80) -> (n,80,80)\n        loss = F.binary_cross_entropy_with_logits(pred_mask, gt_mask, reduction='none')\n        return (crop_mask(loss, xyxy).mean(dim=(1, 2)) / area).mean()\n\n\n# Criterion class for computing training losses\nclass v8PoseLoss(v8DetectionLoss):\n\n    def __init__(self, model):  # model must be de-paralleled\n        super().__init__(model)\n        self.kpt_shape = model.model[-1].kpt_shape\n        self.bce_pose = nn.BCEWithLogitsLoss()\n        is_pose = self.kpt_shape == [17, 3]\n        nkpt = self.kpt_shape[0]  # number of keypoints\n        sigmas = torch.from_numpy(OKS_SIGMA).to(self.device) if is_pose else torch.ones(nkpt, device=self.device) / nkpt\n        self.keypoint_loss = KeypointLoss(sigmas=sigmas)\n\n    def __call__(self, preds, batch):\n        \"\"\"Calculate the total loss and detach it.\"\"\"\n        loss = torch.zeros(5, device=self.device)  # box, cls, dfl, kpt_location, kpt_visibility\n        feats, pred_kpts = preds if isinstance(preds[0], list) else preds[1]\n        pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split(\n            (self.reg_max * 4, self.nc), 1)\n\n        # b, grids, ..\n        pred_scores = pred_scores.permute(0, 2, 1).contiguous()\n        pred_distri = pred_distri.permute(0, 2, 1).contiguous()\n        pred_kpts = pred_kpts.permute(0, 2, 1).contiguous()\n\n        dtype = pred_scores.dtype\n        imgsz = torch.tensor(feats[0].shape[2:], device=self.device, dtype=dtype) * self.stride[0]  # image size (h,w)\n        anchor_points, stride_tensor = make_anchors(feats, self.stride, 0.5)\n\n        # targets\n        batch_size = pred_scores.shape[0]\n        batch_idx = batch['batch_idx'].view(-1, 1)\n        targets = torch.cat((batch_idx, batch['cls'].view(-1, 1), batch['bboxes']), 1)\n        targets = self.preprocess(targets.to(self.device), batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])\n        gt_labels, gt_bboxes = targets.split((1, 4), 2)  # cls, xyxy\n        mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0)\n\n        # pboxes\n        pred_bboxes = self.bbox_decode(anchor_points, pred_distri)  # xyxy, (b, h*w, 4)\n        pred_kpts = self.kpts_decode(anchor_points, pred_kpts.view(batch_size, -1, *self.kpt_shape))  # (b, h*w, 17, 3)\n\n        _, target_bboxes, target_scores, fg_mask, target_gt_idx = self.assigner(\n            pred_scores.detach().sigmoid(), (pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype),\n            anchor_points * stride_tensor, gt_labels, gt_bboxes, mask_gt)\n\n        target_scores_sum = max(target_scores.sum(), 1)\n\n        # cls loss\n        # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum  # VFL way\n        loss[3] = self.bce(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum  # BCE\n\n        # bbox loss\n        if fg_mask.sum():\n            target_bboxes /= stride_tensor\n            loss[0], loss[4] = self.bbox_loss(pred_distri, pred_bboxes, anchor_points, target_bboxes, target_scores,\n                                              target_scores_sum, fg_mask)\n            keypoints = batch['keypoints'].to(self.device).float().clone()\n            keypoints[..., 0] *= imgsz[1]\n            keypoints[..., 1] *= imgsz[0]\n            for i in range(batch_size):\n                if fg_mask[i].sum():\n                    idx = target_gt_idx[i][fg_mask[i]]\n                    gt_kpt = keypoints[batch_idx.view(-1) == i][idx]  # (n, 51)\n                    gt_kpt[..., 0] /= stride_tensor[fg_mask[i]]\n                    gt_kpt[..., 1] /= stride_tensor[fg_mask[i]]\n                    area = xyxy2xywh(target_bboxes[i][fg_mask[i]])[:, 2:].prod(1, keepdim=True)\n                    pred_kpt = pred_kpts[i][fg_mask[i]]\n                    kpt_mask = gt_kpt[..., 2] != 0\n                    loss[1] += self.keypoint_loss(pred_kpt, gt_kpt, kpt_mask, area)  # pose loss\n                    # kpt_score loss\n                    if pred_kpt.shape[-1] == 3:\n                        loss[2] += self.bce_pose(pred_kpt[..., 2], kpt_mask.float())  # keypoint obj loss\n\n        loss[0] *= self.hyp.box  # box gain\n        loss[1] *= self.hyp.pose / batch_size  # pose gain\n        loss[2] *= self.hyp.kobj / batch_size  # kobj gain\n        loss[3] *= self.hyp.cls  # cls gain\n        loss[4] *= self.hyp.dfl  # dfl gain\n\n        return loss.sum() * batch_size, loss.detach()  # loss(box, cls, dfl)\n\n    def kpts_decode(self, anchor_points, pred_kpts):\n        \"\"\"Decodes predicted keypoints to image coordinates.\"\"\"\n        y = pred_kpts.clone()\n        y[..., :2] *= 2.0\n        y[..., 0] += anchor_points[:, [0]] - 0.5\n        y[..., 1] += anchor_points[:, [1]] - 0.5\n        return y\n\n\nclass v8ClassificationLoss:\n\n    def __call__(self, preds, batch):\n        \"\"\"Compute the classification loss between predictions and true labels.\"\"\"\n        loss = torch.nn.functional.cross_entropy(preds, batch['cls'], reduction='sum') / 64\n        loss_items = loss.detach()\n        return loss, loss_items\n"
  },
  {
    "path": "ultralytics/yolo/utils/metrics.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nModel validation metrics\n\"\"\"\nimport math\nimport warnings\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\n\nfrom ultralytics.yolo.utils import LOGGER, SimpleClass, TryExcept, plt_settings\n\nOKS_SIGMA = np.array([.26, .25, .25, .35, .35, .79, .79, .72, .72, .62, .62, 1.07, 1.07, .87, .87, .89, .89]) / 10.0\n\n\n# Boxes\ndef box_area(box):\n    \"\"\"Return box area, where box shape is xyxy(4,n).\"\"\"\n    return (box[2] - box[0]) * (box[3] - box[1])\n\n\ndef bbox_ioa(box1, box2, eps=1e-7):\n    \"\"\"\n    Calculate the intersection over box2 area given box1 and box2. Boxes are in x1y1x2y2 format.\n\n    Args:\n        box1 (np.array): A numpy array of shape (n, 4) representing n bounding boxes.\n        box2 (np.array): A numpy array of shape (m, 4) representing m bounding boxes.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (np.array): A numpy array of shape (n, m) representing the intersection over box2 area.\n    \"\"\"\n\n    # Get the coordinates of bounding boxes\n    b1_x1, b1_y1, b1_x2, b1_y2 = box1.T\n    b2_x1, b2_y1, b2_x2, b2_y2 = box2.T\n\n    # Intersection area\n    inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * \\\n                 (np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)).clip(0)\n\n    # box2 area\n    box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps\n\n    # Intersection over box2 area\n    return inter_area / box2_area\n\n\ndef box_iou(box1, box2, eps=1e-7):\n    \"\"\"\n    Calculate intersection-over-union (IoU) of boxes.\n    Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n    Based on https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\n\n    Args:\n        box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes.\n        box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): An NxM tensor containing the pairwise IoU values for every element in box1 and box2.\n    \"\"\"\n\n    # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\n    (a1, a2), (b1, b2) = box1.unsqueeze(1).chunk(2, 2), box2.unsqueeze(0).chunk(2, 2)\n    inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp_(0).prod(2)\n\n    # IoU = inter / (area1 + area2 - inter)\n    return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)\n\n\ndef bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):\n    \"\"\"\n    Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).\n\n    Args:\n        box1 (torch.Tensor): A tensor representing a single bounding box with shape (1, 4).\n        box2 (torch.Tensor): A tensor representing n bounding boxes with shape (n, 4).\n        xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in\n                               (x1, y1, x2, y2) format. Defaults to True.\n        GIoU (bool, optional): If True, calculate Generalized IoU. Defaults to False.\n        DIoU (bool, optional): If True, calculate Distance IoU. Defaults to False.\n        CIoU (bool, optional): If True, calculate Complete IoU. Defaults to False.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.\n    \"\"\"\n\n    # Get the coordinates of bounding boxes\n    if xywh:  # transform from xywh to xyxy\n        (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)\n        w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2\n        b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_\n        b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_\n    else:  # x1, y1, x2, y2 = box1\n        b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)\n        b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)\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\n    # Intersection area\n    inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \\\n            (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)\n\n    # Union Area\n    union = w1 * h1 + w2 * h2 - inter + eps\n\n    # IoU\n    iou = inter / union\n    if CIoU or DIoU or GIoU:\n        cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1)  # convex (smallest enclosing box) width\n        ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(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 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4  # center dist ** 2\n            if CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47\n                v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)\n                with torch.no_grad():\n                    alpha = v / (v - iou + (1 + eps))\n                return iou - (rho2 / c2 + v * alpha)  # CIoU\n            return iou - rho2 / c2  # DIoU\n        c_area = cw * ch + eps  # convex area\n        return iou - (c_area - union) / c_area  # GIoU https://arxiv.org/pdf/1902.09630.pdf\n    return iou  # IoU\n\n\ndef mask_iou(mask1, mask2, eps=1e-7):\n    \"\"\"\n    Calculate masks IoU.\n\n    Args:\n        mask1 (torch.Tensor): A tensor of shape (N, n) where N is the number of ground truth objects and n is the\n                        product of image width and height.\n        mask2 (torch.Tensor): A tensor of shape (M, n) where M is the number of predicted objects and n is the\n                        product of image width and height.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): A tensor of shape (N, M) representing masks IoU.\n    \"\"\"\n    intersection = torch.matmul(mask1, mask2.T).clamp_(0)\n    union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection  # (area1 + area2) - intersection\n    return intersection / (union + eps)\n\n\ndef kpt_iou(kpt1, kpt2, area, sigma, eps=1e-7):\n    \"\"\"\n    Calculate Object Keypoint Similarity (OKS).\n\n    Args:\n        kpt1 (torch.Tensor): A tensor of shape (N, 17, 3) representing ground truth keypoints.\n        kpt2 (torch.Tensor): A tensor of shape (M, 17, 3) representing predicted keypoints.\n        area (torch.Tensor): A tensor of shape (N,) representing areas from ground truth.\n        sigma (list): A list containing 17 values representing keypoint scales.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): A tensor of shape (N, M) representing keypoint similarities.\n    \"\"\"\n    d = (kpt1[:, None, :, 0] - kpt2[..., 0]) ** 2 + (kpt1[:, None, :, 1] - kpt2[..., 1]) ** 2  # (N, M, 17)\n    sigma = torch.tensor(sigma, device=kpt1.device, dtype=kpt1.dtype)  # (17, )\n    kpt_mask = kpt1[..., 2] != 0  # (N, 17)\n    e = d / (2 * sigma) ** 2 / (area[:, None, None] + eps) / 2  # from cocoeval\n    # e = d / ((area[None, :, None] + eps) * sigma) ** 2 / 2  # from formula\n    return (torch.exp(-e) * kpt_mask[:, None]).sum(-1) / (kpt_mask.sum(-1)[:, None] + eps)\n\n\ndef smooth_BCE(eps=0.1):  # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441\n    # return positive, negative label smoothing BCE targets\n    return 1.0 - 0.5 * eps, 0.5 * eps\n\n\nclass ConfusionMatrix:\n    \"\"\"\n    A class for calculating and updating a confusion matrix for object detection and classification tasks.\n\n    Attributes:\n        task (str): The type of task, either 'detect' or 'classify'.\n        matrix (np.array): The confusion matrix, with dimensions depending on the task.\n        nc (int): The number of classes.\n        conf (float): The confidence threshold for detections.\n        iou_thres (float): The Intersection over Union threshold.\n    \"\"\"\n\n    def __init__(self, nc, conf=0.25, iou_thres=0.45, task='detect'):\n        \"\"\"Initialize attributes for the YOLO model.\"\"\"\n        self.task = task\n        self.matrix = np.zeros((nc + 1, nc + 1)) if self.task == 'detect' else np.zeros((nc, nc))\n        self.nc = nc  # number of classes\n        self.conf = conf\n        self.iou_thres = iou_thres\n\n    def process_cls_preds(self, preds, targets):\n        \"\"\"\n        Update confusion matrix for classification task\n\n        Args:\n            preds (Array[N, min(nc,5)]): Predicted class labels.\n            targets (Array[N, 1]): Ground truth class labels.\n        \"\"\"\n        preds, targets = torch.cat(preds)[:, 0], torch.cat(targets)\n        for p, t in zip(preds.cpu().numpy(), targets.cpu().numpy()):\n            self.matrix[p][t] += 1\n\n    def process_batch(self, detections, labels):\n        \"\"\"\n        Update confusion matrix for object detection task.\n\n        Args:\n            detections (Array[N, 6]): Detected bounding boxes and their associated information.\n                                      Each row should contain (x1, y1, x2, y2, conf, class).\n            labels (Array[M, 5]): Ground truth bounding boxes and their associated class labels.\n                                  Each row should contain (class, x1, y1, x2, y2).\n        \"\"\"\n        if detections is None:\n            gt_classes = labels.int()\n            for gc in gt_classes:\n                self.matrix[self.nc, gc] += 1  # background FN\n            return\n\n        detections = detections[detections[:, 4] > self.conf]\n        gt_classes = labels[:, 0].int()\n        detection_classes = detections[:, 5].int()\n        iou = box_iou(labels[:, 1:], detections[:, :4])\n\n        x = torch.where(iou > self.iou_thres)\n        if x[0].shape[0]:\n            matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()\n            if x[0].shape[0] > 1:\n                matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n        else:\n            matches = np.zeros((0, 3))\n\n        n = matches.shape[0] > 0\n        m0, m1, _ = matches.transpose().astype(int)\n        for i, gc in enumerate(gt_classes):\n            j = m0 == i\n            if n and sum(j) == 1:\n                self.matrix[detection_classes[m1[j]], gc] += 1  # correct\n            else:\n                self.matrix[self.nc, gc] += 1  # true background\n\n        if n:\n            for i, dc in enumerate(detection_classes):\n                if not any(m1 == i):\n                    self.matrix[dc, self.nc] += 1  # predicted background\n\n    def matrix(self):\n        \"\"\"Returns the confusion matrix.\"\"\"\n        return self.matrix\n\n    def tp_fp(self):\n        \"\"\"Returns true positives and false positives.\"\"\"\n        tp = self.matrix.diagonal()  # true positives\n        fp = self.matrix.sum(1) - tp  # false positives\n        # fn = self.matrix.sum(0) - tp  # false negatives (missed detections)\n        return (tp[:-1], fp[:-1]) if self.task == 'detect' else (tp, fp)  # remove background class if task=detect\n\n    @TryExcept('WARNING ⚠️ ConfusionMatrix plot failure')\n    @plt_settings()\n    def plot(self, normalize=True, save_dir='', names=(), on_plot=None):\n        \"\"\"\n        Plot the confusion matrix using seaborn and save it to a file.\n\n        Args:\n            normalize (bool): Whether to normalize the confusion matrix.\n            save_dir (str): Directory where the plot will be saved.\n            names (tuple): Names of classes, used as labels on the plot.\n            on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        \"\"\"\n        import seaborn as sn\n\n        array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1)  # normalize columns\n        array[array < 0.005] = np.nan  # don't annotate (would appear as 0.00)\n\n        fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)\n        nc, nn = self.nc, len(names)  # number of classes, names\n        sn.set(font_scale=1.0 if nc < 50 else 0.8)  # for label size\n        labels = (0 < nn < 99) and (nn == nc)  # apply names to ticklabels\n        ticklabels = (list(names) + ['background']) if labels else 'auto'\n        with warnings.catch_warnings():\n            warnings.simplefilter('ignore')  # suppress empty matrix RuntimeWarning: All-NaN slice encountered\n            sn.heatmap(array,\n                       ax=ax,\n                       annot=nc < 30,\n                       annot_kws={\n                           'size': 8},\n                       cmap='Blues',\n                       fmt='.2f' if normalize else '.0f',\n                       square=True,\n                       vmin=0.0,\n                       xticklabels=ticklabels,\n                       yticklabels=ticklabels).set_facecolor((1, 1, 1))\n        title = 'Confusion Matrix' + ' Normalized' * normalize\n        ax.set_xlabel('True')\n        ax.set_ylabel('Predicted')\n        ax.set_title(title)\n        plot_fname = Path(save_dir) / f'{title.lower().replace(\" \", \"_\")}.png'\n        fig.savefig(plot_fname, dpi=250)\n        plt.close(fig)\n        if on_plot:\n            on_plot(plot_fname)\n\n    def print(self):\n        \"\"\"\n        Print the confusion matrix to the console.\n        \"\"\"\n        for i in range(self.nc + 1):\n            LOGGER.info(' '.join(map(str, self.matrix[i])))\n\n\ndef smooth(y, f=0.05):\n    \"\"\"Box filter of fraction f.\"\"\"\n    nf = round(len(y) * f * 2) // 2 + 1  # number of filter elements (must be odd)\n    p = np.ones(nf // 2)  # ones padding\n    yp = np.concatenate((p * y[0], y, p * y[-1]), 0)  # y padded\n    return np.convolve(yp, np.ones(nf) / nf, mode='valid')  # y-smoothed\n\n\n@plt_settings()\ndef plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=(), on_plot=None):\n    \"\"\"Plots a precision-recall curve.\"\"\"\n    fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)\n    py = np.stack(py, axis=1)\n\n    if 0 < len(names) < 21:  # display per-class legend if < 21 classes\n        for i, y in enumerate(py.T):\n            ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}')  # plot(recall, precision)\n    else:\n        ax.plot(px, py, linewidth=1, color='grey')  # plot(recall, precision)\n\n    ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())\n    ax.set_xlabel('Recall')\n    ax.set_ylabel('Precision')\n    ax.set_xlim(0, 1)\n    ax.set_ylim(0, 1)\n    ax.legend(bbox_to_anchor=(1.04, 1), loc='upper left')\n    ax.set_title('Precision-Recall Curve')\n    fig.savefig(save_dir, dpi=250)\n    plt.close(fig)\n    if on_plot:\n        on_plot(save_dir)\n\n\n@plt_settings()\ndef plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric', on_plot=None):\n    \"\"\"Plots a metric-confidence curve.\"\"\"\n    fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)\n\n    if 0 < len(names) < 21:  # display per-class legend if < 21 classes\n        for i, y in enumerate(py):\n            ax.plot(px, y, linewidth=1, label=f'{names[i]}')  # plot(confidence, metric)\n    else:\n        ax.plot(px, py.T, linewidth=1, color='grey')  # plot(confidence, metric)\n\n    y = smooth(py.mean(0), 0.05)\n    ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')\n    ax.set_xlabel(xlabel)\n    ax.set_ylabel(ylabel)\n    ax.set_xlim(0, 1)\n    ax.set_ylim(0, 1)\n    ax.legend(bbox_to_anchor=(1.04, 1), loc='upper left')\n    ax.set_title(f'{ylabel}-Confidence Curve')\n    fig.savefig(save_dir, dpi=250)\n    plt.close(fig)\n    if on_plot:\n        on_plot(save_dir)\n\n\ndef compute_ap(recall, precision):\n    \"\"\"\n    Compute the average precision (AP) given the recall and precision curves.\n\n    Arguments:\n        recall (list): The recall curve.\n        precision (list): The precision curve.\n\n    Returns:\n        (float): Average precision.\n        (np.ndarray): Precision envelope curve.\n        (np.ndarray): Modified recall curve with sentinel values added at the beginning and end.\n    \"\"\"\n\n    # Append sentinel values to beginning and end\n    mrec = np.concatenate(([0.0], recall, [1.0]))\n    mpre = np.concatenate(([1.0], precision, [0.0]))\n\n    # Compute the precision envelope\n    mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))\n\n    # Integrate area under curve\n    method = 'interp'  # methods: 'continuous', 'interp'\n    if method == 'interp':\n        x = np.linspace(0, 1, 101)  # 101-point interp (COCO)\n        ap = np.trapz(np.interp(x, mrec, mpre), x)  # integrate\n    else:  # 'continuous'\n        i = np.where(mrec[1:] != mrec[:-1])[0]  # points where x-axis (recall) changes\n        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])  # area under curve\n\n    return ap, mpre, mrec\n\n\ndef ap_per_class(tp,\n                 conf,\n                 pred_cls,\n                 target_cls,\n                 plot=False,\n                 on_plot=None,\n                 save_dir=Path(),\n                 names=(),\n                 eps=1e-16,\n                 prefix=''):\n    \"\"\"\n    Computes the average precision per class for object detection evaluation.\n\n    Args:\n        tp (np.ndarray): Binary array indicating whether the detection is correct (True) or not (False).\n        conf (np.ndarray): Array of confidence scores of the detections.\n        pred_cls (np.ndarray): Array of predicted classes of the detections.\n        target_cls (np.ndarray): Array of true classes of the detections.\n        plot (bool, optional): Whether to plot PR curves or not. Defaults to False.\n        on_plot (func, optional): A callback to pass plots path and data when they are rendered. Defaults to None.\n        save_dir (Path, optional): Directory to save the PR curves. Defaults to an empty path.\n        names (tuple, optional): Tuple of class names to plot PR curves. Defaults to an empty tuple.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-16.\n        prefix (str, optional): A prefix string for saving the plot files. Defaults to an empty string.\n\n    Returns:\n        (tuple): A tuple of six arrays and one array of unique classes, where:\n            tp (np.ndarray): True positive counts for each class.\n            fp (np.ndarray): False positive counts for each class.\n            p (np.ndarray): Precision values at each confidence threshold.\n            r (np.ndarray): Recall values at each confidence threshold.\n            f1 (np.ndarray): F1-score values at each confidence threshold.\n            ap (np.ndarray): Average precision for each class at different IoU thresholds.\n            unique_classes (np.ndarray): An array of unique classes that have data.\n\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, nt = np.unique(target_cls, return_counts=True)\n    nc = unique_classes.shape[0]  # number of classes, number of detections\n\n    # Create Precision-Recall curve and compute AP for each class\n    px, py = np.linspace(0, 1, 1000), []  # for plotting\n    ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))\n    for ci, c in enumerate(unique_classes):\n        i = pred_cls == c\n        n_l = nt[ci]  # number of labels\n        n_p = i.sum()  # number of predictions\n        if n_p == 0 or n_l == 0:\n            continue\n\n        # Accumulate FPs and TPs\n        fpc = (1 - tp[i]).cumsum(0)\n        tpc = tp[i].cumsum(0)\n\n        # Recall\n        recall = tpc / (n_l + eps)  # recall curve\n        r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0)  # negative x, xp because xp decreases\n\n        # Precision\n        precision = tpc / (tpc + fpc)  # precision curve\n        p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1)  # p at pr_score\n\n        # AP from recall-precision curve\n        for j in range(tp.shape[1]):\n            ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])\n            if plot and j == 0:\n                py.append(np.interp(px, mrec, mpre))  # precision at mAP@0.5\n\n    # Compute F1 (harmonic mean of precision and recall)\n    f1 = 2 * p * r / (p + r + eps)\n    names = [v for k, v in names.items() if k in unique_classes]  # list: only classes that have data\n    names = dict(enumerate(names))  # to dict\n    if plot:\n        plot_pr_curve(px, py, ap, save_dir / f'{prefix}PR_curve.png', names, on_plot=on_plot)\n        plot_mc_curve(px, f1, save_dir / f'{prefix}F1_curve.png', names, ylabel='F1', on_plot=on_plot)\n        plot_mc_curve(px, p, save_dir / f'{prefix}P_curve.png', names, ylabel='Precision', on_plot=on_plot)\n        plot_mc_curve(px, r, save_dir / f'{prefix}R_curve.png', names, ylabel='Recall', on_plot=on_plot)\n\n    i = smooth(f1.mean(0), 0.1).argmax()  # max F1 index\n    p, r, f1 = p[:, i], r[:, i], f1[:, i]\n    tp = (r * nt).round()  # true positives\n    fp = (tp / (p + eps) - tp).round()  # false positives\n    return tp, fp, p, r, f1, ap, unique_classes.astype(int)\n\n\nclass Metric(SimpleClass):\n    \"\"\"\n        Class for computing evaluation metrics for YOLOv8 model.\n\n        Attributes:\n            p (list): Precision for each class. Shape: (nc,).\n            r (list): Recall for each class. Shape: (nc,).\n            f1 (list): F1 score for each class. Shape: (nc,).\n            all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).\n            ap_class_index (list): Index of class for each AP score. Shape: (nc,).\n            nc (int): Number of classes.\n\n        Methods:\n            ap50(): AP at IoU threshold of 0.5 for all classes. Returns: List of AP scores. Shape: (nc,) or [].\n            ap(): AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: List of AP scores. Shape: (nc,) or [].\n            mp(): Mean precision of all classes. Returns: Float.\n            mr(): Mean recall of all classes. Returns: Float.\n            map50(): Mean AP at IoU threshold of 0.5 for all classes. Returns: Float.\n            map75(): Mean AP at IoU threshold of 0.75 for all classes. Returns: Float.\n            map(): Mean AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: Float.\n            mean_results(): Mean of results, returns mp, mr, map50, map.\n            class_result(i): Class-aware result, returns p[i], r[i], ap50[i], ap[i].\n            maps(): mAP of each class. Returns: Array of mAP scores, shape: (nc,).\n            fitness(): Model fitness as a weighted combination of metrics. Returns: Float.\n            update(results): Update metric attributes with new evaluation results.\n\n        \"\"\"\n\n    def __init__(self) -> None:\n        self.p = []  # (nc, )\n        self.r = []  # (nc, )\n        self.f1 = []  # (nc, )\n        self.all_ap = []  # (nc, 10)\n        self.ap_class_index = []  # (nc, )\n        self.nc = 0\n\n    @property\n    def ap50(self):\n        \"\"\"\n        Returns the Average Precision (AP) at an IoU threshold of 0.5 for all classes.\n\n        Returns:\n            (np.ndarray, list): Array of shape (nc,) with AP50 values per class, or an empty list if not available.\n        \"\"\"\n        return self.all_ap[:, 0] if len(self.all_ap) else []\n\n    @property\n    def ap(self):\n        \"\"\"\n        Returns the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes.\n\n        Returns:\n            (np.ndarray, list): Array of shape (nc,) with AP50-95 values per class, or an empty list if not available.\n        \"\"\"\n        return self.all_ap.mean(1) if len(self.all_ap) else []\n\n    @property\n    def mp(self):\n        \"\"\"\n        Returns the Mean Precision of all classes.\n\n        Returns:\n            (float): The mean precision of all classes.\n        \"\"\"\n        return self.p.mean() if len(self.p) else 0.0\n\n    @property\n    def mr(self):\n        \"\"\"\n        Returns the Mean Recall of all classes.\n\n        Returns:\n            (float): The mean recall of all classes.\n        \"\"\"\n        return self.r.mean() if len(self.r) else 0.0\n\n    @property\n    def map50(self):\n        \"\"\"\n        Returns the mean Average Precision (mAP) at an IoU threshold of 0.5.\n\n        Returns:\n            (float): The mAP50 at an IoU threshold of 0.5.\n        \"\"\"\n        return self.all_ap[:, 0].mean() if len(self.all_ap) else 0.0\n\n    @property\n    def map75(self):\n        \"\"\"\n        Returns the mean Average Precision (mAP) at an IoU threshold of 0.75.\n\n        Returns:\n            (float): The mAP50 at an IoU threshold of 0.75.\n        \"\"\"\n        return self.all_ap[:, 5].mean() if len(self.all_ap) else 0.0\n\n    @property\n    def map(self):\n        \"\"\"\n        Returns the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05.\n\n        Returns:\n            (float): The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05.\n        \"\"\"\n        return self.all_ap.mean() if len(self.all_ap) else 0.0\n\n    def mean_results(self):\n        \"\"\"Mean of results, return mp, mr, map50, map.\"\"\"\n        return [self.mp, self.mr, self.map50, self.map]\n\n    def class_result(self, i):\n        \"\"\"class-aware result, return p[i], r[i], ap50[i], ap[i].\"\"\"\n        return self.p[i], self.r[i], self.ap50[i], self.ap[i]\n\n    @property\n    def maps(self):\n        \"\"\"mAP of each class.\"\"\"\n        maps = np.zeros(self.nc) + self.map\n        for i, c in enumerate(self.ap_class_index):\n            maps[c] = self.ap[i]\n        return maps\n\n    def fitness(self):\n        \"\"\"Model fitness as a weighted combination of metrics.\"\"\"\n        w = [0.0, 0.0, 0.1, 0.9]  # weights for [P, R, mAP@0.5, mAP@0.5:0.95]\n        return (np.array(self.mean_results()) * w).sum()\n\n    def update(self, results):\n        \"\"\"\n        Args:\n            results (tuple): A tuple of (p, r, ap, f1, ap_class)\n        \"\"\"\n        self.p, self.r, self.f1, self.all_ap, self.ap_class_index = results\n\n\nclass DetMetrics(SimpleClass):\n    \"\"\"\n    This class is a utility class for computing detection metrics such as precision, recall, and mean average precision\n    (mAP) of an object detection model.\n\n    Args:\n        save_dir (Path): A path to the directory where the output plots will be saved. Defaults to current directory.\n        plot (bool): A flag that indicates whether to plot precision-recall curves for each class. Defaults to False.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.\n        names (tuple of str): A tuple of strings that represents the names of the classes. Defaults to an empty tuple.\n\n    Attributes:\n        save_dir (Path): A path to the directory where the output plots will be saved.\n        plot (bool): A flag that indicates whether to plot the precision-recall curves for each class.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        names (tuple of str): A tuple of strings that represents the names of the classes.\n        box (Metric): An instance of the Metric class for storing the results of the detection metrics.\n        speed (dict): A dictionary for storing the execution time of different parts of the detection process.\n\n    Methods:\n        process(tp, conf, pred_cls, target_cls): Updates the metric results with the latest batch of predictions.\n        keys: Returns a list of keys for accessing the computed detection metrics.\n        mean_results: Returns a list of mean values for the computed detection metrics.\n        class_result(i): Returns a list of values for the computed detection metrics for a specific class.\n        maps: Returns a dictionary of mean average precision (mAP) values for different IoU thresholds.\n        fitness: Computes the fitness score based on the computed detection metrics.\n        ap_class_index: Returns a list of class indices sorted by their average precision (AP) values.\n        results_dict: Returns a dictionary that maps detection metric keys to their computed values.\n    \"\"\"\n\n    def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:\n        self.save_dir = save_dir\n        self.plot = plot\n        self.on_plot = on_plot\n        self.names = names\n        self.box = Metric()\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def process(self, tp, conf, pred_cls, target_cls):\n        \"\"\"Process predicted results for object detection and update metrics.\"\"\"\n        results = ap_per_class(tp,\n                               conf,\n                               pred_cls,\n                               target_cls,\n                               plot=self.plot,\n                               save_dir=self.save_dir,\n                               names=self.names,\n                               on_plot=self.on_plot)[2:]\n        self.box.nc = len(self.names)\n        self.box.update(results)\n\n    @property\n    def keys(self):\n        \"\"\"Returns a list of keys for accessing specific metrics.\"\"\"\n        return ['metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)']\n\n    def mean_results(self):\n        \"\"\"Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.\"\"\"\n        return self.box.mean_results()\n\n    def class_result(self, i):\n        \"\"\"Return the result of evaluating the performance of an object detection model on a specific class.\"\"\"\n        return self.box.class_result(i)\n\n    @property\n    def maps(self):\n        \"\"\"Returns mean Average Precision (mAP) scores per class.\"\"\"\n        return self.box.maps\n\n    @property\n    def fitness(self):\n        \"\"\"Returns the fitness of box object.\"\"\"\n        return self.box.fitness()\n\n    @property\n    def ap_class_index(self):\n        \"\"\"Returns the average precision index per class.\"\"\"\n        return self.box.ap_class_index\n\n    @property\n    def results_dict(self):\n        \"\"\"Returns dictionary of computed performance metrics and statistics.\"\"\"\n        return dict(zip(self.keys + ['fitness'], self.mean_results() + [self.fitness]))\n\n\nclass SegmentMetrics(SimpleClass):\n    \"\"\"\n    Calculates and aggregates detection and segmentation metrics over a given set of classes.\n\n    Args:\n        save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.\n        plot (bool): Whether to save the detection and segmentation plots. Default is False.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.\n        names (list): List of class names. Default is an empty list.\n\n    Attributes:\n        save_dir (Path): Path to the directory where the output plots should be saved.\n        plot (bool): Whether to save the detection and segmentation plots.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        names (list): List of class names.\n        box (Metric): An instance of the Metric class to calculate box detection metrics.\n        seg (Metric): An instance of the Metric class to calculate mask segmentation metrics.\n        speed (dict): Dictionary to store the time taken in different phases of inference.\n\n    Methods:\n        process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.\n        mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.\n        class_result(i): Returns the detection and segmentation metrics of class `i`.\n        maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.\n        fitness: Returns the fitness scores, which are a single weighted combination of metrics.\n        ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).\n        results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.\n    \"\"\"\n\n    def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:\n        self.save_dir = save_dir\n        self.plot = plot\n        self.on_plot = on_plot\n        self.names = names\n        self.box = Metric()\n        self.seg = Metric()\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def process(self, tp_b, tp_m, conf, pred_cls, target_cls):\n        \"\"\"\n        Processes the detection and segmentation metrics over the given set of predictions.\n\n        Args:\n            tp_b (list): List of True Positive boxes.\n            tp_m (list): List of True Positive masks.\n            conf (list): List of confidence scores.\n            pred_cls (list): List of predicted classes.\n            target_cls (list): List of target classes.\n        \"\"\"\n\n        results_mask = ap_per_class(tp_m,\n                                    conf,\n                                    pred_cls,\n                                    target_cls,\n                                    plot=self.plot,\n                                    on_plot=self.on_plot,\n                                    save_dir=self.save_dir,\n                                    names=self.names,\n                                    prefix='Mask')[2:]\n        self.seg.nc = len(self.names)\n        self.seg.update(results_mask)\n        results_box = ap_per_class(tp_b,\n                                   conf,\n                                   pred_cls,\n                                   target_cls,\n                                   plot=self.plot,\n                                   on_plot=self.on_plot,\n                                   save_dir=self.save_dir,\n                                   names=self.names,\n                                   prefix='Box')[2:]\n        self.box.nc = len(self.names)\n        self.box.update(results_box)\n\n    @property\n    def keys(self):\n        \"\"\"Returns a list of keys for accessing metrics.\"\"\"\n        return [\n            'metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)',\n            'metrics/precision(M)', 'metrics/recall(M)', 'metrics/mAP50(M)', 'metrics/mAP50-95(M)']\n\n    def mean_results(self):\n        \"\"\"Return the mean metrics for bounding box and segmentation results.\"\"\"\n        return self.box.mean_results() + self.seg.mean_results()\n\n    def class_result(self, i):\n        \"\"\"Returns classification results for a specified class index.\"\"\"\n        return self.box.class_result(i) + self.seg.class_result(i)\n\n    @property\n    def maps(self):\n        \"\"\"Returns mAP scores for object detection and semantic segmentation models.\"\"\"\n        return self.box.maps + self.seg.maps\n\n    @property\n    def fitness(self):\n        \"\"\"Get the fitness score for both segmentation and bounding box models.\"\"\"\n        return self.seg.fitness() + self.box.fitness()\n\n    @property\n    def ap_class_index(self):\n        \"\"\"Boxes and masks have the same ap_class_index.\"\"\"\n        return self.box.ap_class_index\n\n    @property\n    def results_dict(self):\n        \"\"\"Returns results of object detection model for evaluation.\"\"\"\n        return dict(zip(self.keys + ['fitness'], self.mean_results() + [self.fitness]))\n\n\nclass PoseMetrics(SegmentMetrics):\n    \"\"\"\n    Calculates and aggregates detection and pose metrics over a given set of classes.\n\n    Args:\n        save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.\n        plot (bool): Whether to save the detection and segmentation plots. Default is False.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.\n        names (list): List of class names. Default is an empty list.\n\n    Attributes:\n        save_dir (Path): Path to the directory where the output plots should be saved.\n        plot (bool): Whether to save the detection and segmentation plots.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        names (list): List of class names.\n        box (Metric): An instance of the Metric class to calculate box detection metrics.\n        pose (Metric): An instance of the Metric class to calculate mask segmentation metrics.\n        speed (dict): Dictionary to store the time taken in different phases of inference.\n\n    Methods:\n        process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.\n        mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.\n        class_result(i): Returns the detection and segmentation metrics of class `i`.\n        maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.\n        fitness: Returns the fitness scores, which are a single weighted combination of metrics.\n        ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).\n        results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.\n    \"\"\"\n\n    def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:\n        super().__init__(save_dir, plot, names)\n        self.save_dir = save_dir\n        self.plot = plot\n        self.on_plot = on_plot\n        self.names = names\n        self.box = Metric()\n        self.pose = Metric()\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def __getattr__(self, attr):\n        \"\"\"Raises an AttributeError if an invalid attribute is accessed.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n\n    def process(self, tp_b, tp_p, conf, pred_cls, target_cls):\n        \"\"\"\n        Processes the detection and pose metrics over the given set of predictions.\n\n        Args:\n            tp_b (list): List of True Positive boxes.\n            tp_p (list): List of True Positive keypoints.\n            conf (list): List of confidence scores.\n            pred_cls (list): List of predicted classes.\n            target_cls (list): List of target classes.\n        \"\"\"\n\n        results_pose = ap_per_class(tp_p,\n                                    conf,\n                                    pred_cls,\n                                    target_cls,\n                                    plot=self.plot,\n                                    on_plot=self.on_plot,\n                                    save_dir=self.save_dir,\n                                    names=self.names,\n                                    prefix='Pose')[2:]\n        self.pose.nc = len(self.names)\n        self.pose.update(results_pose)\n        results_box = ap_per_class(tp_b,\n                                   conf,\n                                   pred_cls,\n                                   target_cls,\n                                   plot=self.plot,\n                                   on_plot=self.on_plot,\n                                   save_dir=self.save_dir,\n                                   names=self.names,\n                                   prefix='Box')[2:]\n        self.box.nc = len(self.names)\n        self.box.update(results_box)\n\n    @property\n    def keys(self):\n        \"\"\"Returns list of evaluation metric keys.\"\"\"\n        return [\n            'metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)',\n            'metrics/precision(P)', 'metrics/recall(P)', 'metrics/mAP50(P)', 'metrics/mAP50-95(P)']\n\n    def mean_results(self):\n        \"\"\"Return the mean results of box and pose.\"\"\"\n        return self.box.mean_results() + self.pose.mean_results()\n\n    def class_result(self, i):\n        \"\"\"Return the class-wise detection results for a specific class i.\"\"\"\n        return self.box.class_result(i) + self.pose.class_result(i)\n\n    @property\n    def maps(self):\n        \"\"\"Returns the mean average precision (mAP) per class for both box and pose detections.\"\"\"\n        return self.box.maps + self.pose.maps\n\n    @property\n    def fitness(self):\n        \"\"\"Computes classification metrics and speed using the `targets` and `pred` inputs.\"\"\"\n        return self.pose.fitness() + self.box.fitness()\n\n\nclass ClassifyMetrics(SimpleClass):\n    \"\"\"\n    Class for computing classification metrics including top-1 and top-5 accuracy.\n\n    Attributes:\n        top1 (float): The top-1 accuracy.\n        top5 (float): The top-5 accuracy.\n        speed (Dict[str, float]): A dictionary containing the time taken for each step in the pipeline.\n\n    Properties:\n        fitness (float): The fitness of the model, which is equal to top-5 accuracy.\n        results_dict (Dict[str, Union[float, str]]): A dictionary containing the classification metrics and fitness.\n        keys (List[str]): A list of keys for the results_dict.\n\n    Methods:\n        process(targets, pred): Processes the targets and predictions to compute classification metrics.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.top1 = 0\n        self.top5 = 0\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def process(self, targets, pred):\n        \"\"\"Target classes and predicted classes.\"\"\"\n        pred, targets = torch.cat(pred), torch.cat(targets)\n        correct = (targets[:, None] == pred).float()\n        acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1)  # (top1, top5) accuracy\n        self.top1, self.top5 = acc.mean(0).tolist()\n\n    @property\n    def fitness(self):\n        \"\"\"Returns top-5 accuracy as fitness score.\"\"\"\n        return self.top5\n\n    @property\n    def results_dict(self):\n        \"\"\"Returns a dictionary with model's performance metrics and fitness score.\"\"\"\n        return dict(zip(self.keys + ['fitness'], [self.top1, self.top5, self.fitness]))\n\n    @property\n    def keys(self):\n        \"\"\"Returns a list of keys for the results_dict property.\"\"\"\n        return ['metrics/accuracy_top1', 'metrics/accuracy_top5']\n"
  },
  {
    "path": "ultralytics/yolo/utils/ops.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport math\nimport re\nimport time\n\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torchvision\n\nfrom ultralytics.yolo.utils import LOGGER\n\nfrom .metrics import box_iou\n\n\nclass Profile(contextlib.ContextDecorator):\n    \"\"\"\n    YOLOv8 Profile class.\n    Usage: as a decorator with @Profile() or as a context manager with 'with Profile():'\n    \"\"\"\n\n    def __init__(self, t=0.0):\n        \"\"\"\n        Initialize the Profile class.\n\n        Args:\n            t (float): Initial time. Defaults to 0.0.\n        \"\"\"\n        self.t = t\n        self.cuda = torch.cuda.is_available()\n\n    def __enter__(self):\n        \"\"\"\n        Start timing.\n        \"\"\"\n        self.start = self.time()\n        return self\n\n    def __exit__(self, type, value, traceback):\n        \"\"\"\n        Stop timing.\n        \"\"\"\n        self.dt = self.time() - self.start  # delta-time\n        self.t += self.dt  # accumulate dt\n\n    def time(self):\n        \"\"\"\n        Get current time.\n        \"\"\"\n        if self.cuda:\n            torch.cuda.synchronize()\n        return time.time()\n\n\ndef coco80_to_coco91_class():  # converts 80-index (val2014) to 91-index (paper)\n    # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/\n    # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\\n')\n    # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\\n')\n    # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)]  # darknet to coco\n    # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)]  # coco to darknet\n    return [\n        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,\n        35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,\n        64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]\n\n\ndef segment2box(segment, width=640, height=640):\n    \"\"\"\n    Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)\n\n    Args:\n      segment (torch.Tensor): the segment label\n      width (int): the width of the image. Defaults to 640\n      height (int): The height of the image. Defaults to 640\n\n    Returns:\n      (np.ndarray): the minimum and maximum x and y values of the segment.\n    \"\"\"\n    # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)\n    x, y = segment.T  # segment xy\n    inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)\n    x, y, = x[inside], y[inside]\n    return np.array([x.min(), y.min(), x.max(), y.max()], dtype=segment.dtype) if any(x) else np.zeros(\n        4, dtype=segment.dtype)  # xyxy\n\n\ndef scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):\n    \"\"\"\n    Rescales bounding boxes (in the format of xyxy) from the shape of the image they were originally specified in\n    (img1_shape) to the shape of a different image (img0_shape).\n\n    Args:\n      img1_shape (tuple): The shape of the image that the bounding boxes are for, in the format of (height, width).\n      boxes (torch.Tensor): the bounding boxes of the objects in the image, in the format of (x1, y1, x2, y2)\n      img0_shape (tuple): the shape of the target image, in the format of (height, width).\n      ratio_pad (tuple): a tuple of (ratio, pad) for scaling the boxes. If not provided, the ratio and pad will be\n                         calculated based on the size difference between the two images.\n\n    Returns:\n      boxes (torch.Tensor): The scaled bounding boxes, in the format of (x1, y1, x2, y2)\n    \"\"\"\n    if ratio_pad is None:  # calculate from img0_shape\n        gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])  # gain  = old / new\n        pad = round((img1_shape[1] - img0_shape[1] * gain) / 2 - 0.1), round(\n            (img1_shape[0] - img0_shape[0] * gain) / 2 - 0.1)  # wh padding\n    else:\n        gain = ratio_pad[0][0]\n        pad = ratio_pad[1]\n\n    boxes[..., [0, 2]] -= pad[0]  # x padding\n    boxes[..., [1, 3]] -= pad[1]  # y padding\n    boxes[..., :4] /= gain\n    clip_boxes(boxes, img0_shape)\n    return boxes\n\n\ndef make_divisible(x, divisor):\n    \"\"\"\n    Returns the nearest number that is divisible by the given divisor.\n\n    Args:\n        x (int): The number to make divisible.\n        divisor (int | torch.Tensor): The divisor.\n\n    Returns:\n        (int): The nearest number divisible by the divisor.\n    \"\"\"\n    if isinstance(divisor, torch.Tensor):\n        divisor = int(divisor.max())  # to int\n    return math.ceil(x / divisor) * divisor\n\n\ndef non_max_suppression(\n        prediction,\n        conf_thres=0.25,\n        iou_thres=0.45,\n        classes=None,\n        agnostic=False,\n        multi_label=False,\n        labels=(),\n        max_det=300,\n        nc=0,  # number of classes (optional)\n        max_time_img=0.05,\n        max_nms=30000,\n        max_wh=7680,\n):\n    \"\"\"\n    Perform non-maximum suppression (NMS) on a set of boxes, with support for masks and multiple labels per box.\n\n    Arguments:\n        prediction (torch.Tensor): A tensor of shape (batch_size, num_classes + 4 + num_masks, num_boxes)\n            containing the predicted boxes, classes, and masks. The tensor should be in the format\n            output by a model, such as YOLO.\n        conf_thres (float): The confidence threshold below which boxes will be filtered out.\n            Valid values are between 0.0 and 1.0.\n        iou_thres (float): The IoU threshold below which boxes will be filtered out during NMS.\n            Valid values are between 0.0 and 1.0.\n        classes (List[int]): A list of class indices to consider. If None, all classes will be considered.\n        agnostic (bool): If True, the model is agnostic to the number of classes, and all\n            classes will be considered as one.\n        multi_label (bool): If True, each box may have multiple labels.\n        labels (List[List[Union[int, float, torch.Tensor]]]): A list of lists, where each inner\n            list contains the apriori labels for a given image. The list should be in the format\n            output by a dataloader, with each label being a tuple of (class_index, x1, y1, x2, y2).\n        max_det (int): The maximum number of boxes to keep after NMS.\n        nc (int, optional): The number of classes output by the model. Any indices after this will be considered masks.\n        max_time_img (float): The maximum time (seconds) for processing one image.\n        max_nms (int): The maximum number of boxes into torchvision.ops.nms().\n        max_wh (int): The maximum box width and height in pixels\n\n    Returns:\n        (List[torch.Tensor]): A list of length batch_size, where each element is a tensor of\n            shape (num_boxes, 6 + num_masks) containing the kept boxes, with columns\n            (x1, y1, x2, y2, confidence, class, mask1, mask2, ...).\n    \"\"\"\n\n    # Checks\n    assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'\n    assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'\n    if isinstance(prediction, (list, tuple)):  # YOLOv8 model in validation model, output = (inference_out, loss_out)\n        prediction = prediction[0]  # select only inference output\n\n    device = prediction.device\n    mps = 'mps' in device.type  # Apple MPS\n    if mps:  # MPS not fully supported yet, convert tensors to CPU before NMS\n        prediction = prediction.cpu()\n    bs = prediction.shape[0]  # batch size\n    nc = nc or (prediction.shape[1] - 4)  # number of classes\n    nm = prediction.shape[1] - nc - 4\n    mi = 4 + nc  # mask start index\n    xc = prediction[:, 4:mi].amax(1) > conf_thres  # candidates\n\n    # Settings\n    # min_wh = 2  # (pixels) minimum box width and height\n    time_limit = 0.5 + max_time_img * bs  # seconds to quit after\n    redundant = True  # require redundant detections\n    multi_label &= nc > 1  # multiple labels per box (adds 0.5ms/img)\n    merge = False  # use merge-NMS\n\n    t = time.time()\n    output = [torch.zeros((0, 6 + nm), device=prediction.device)] * bs\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.transpose(0, -1)[xc[xi]]  # confidence\n\n        # Cat apriori labels if autolabelling\n        if labels and len(labels[xi]):\n            lb = labels[xi]\n            v = torch.zeros((len(lb), nc + nm + 5), device=x.device)\n            v[:, :4] = lb[:, 1:5]  # box\n            v[range(len(lb)), lb[:, 0].long() + 4] = 1.0  # cls\n            x = torch.cat((x, v), 0)\n\n        # If none remain process next image\n        if not x.shape[0]:\n            continue\n\n        # Detections matrix nx6 (xyxy, conf, cls)\n        box, cls, mask = x.split((4, nc, nm), 1)\n        box = xywh2xyxy(box)  # center_x, center_y, width, height) to (x1, y1, x2, y2)\n        if multi_label:\n            i, j = (cls > conf_thres).nonzero(as_tuple=False).T\n            x = torch.cat((box[i], x[i, 4 + j, None], j[:, None].float(), mask[i]), 1)\n        else:  # best class only\n            conf, j = cls.max(1, keepdim=True)\n            x = torch.cat((box, conf, j.float(), mask), 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        # Apply finite constraint\n        # if not torch.isfinite(x).all():\n        #     x = x[torch.isfinite(x).all(1)]\n\n        # Check shape\n        n = x.shape[0]  # number of boxes\n        if not n:  # no boxes\n            continue\n        x = x[x[:, 4].argsort(descending=True)[:max_nms]]  # sort by confidence and remove excess boxes\n\n        # Batched NMS\n        c = x[:, 5:6] * (0 if agnostic else max_wh)  # classes\n        boxes, scores = x[:, :4] + c, x[:, 4]  # boxes (offset by class), scores\n        i = torchvision.ops.nms(boxes, scores, iou_thres)  # NMS\n        i = i[:max_det]  # limit detections\n        if merge and (1 < n < 3E3):  # Merge NMS (boxes merged using weighted mean)\n            # Update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\n            iou = box_iou(boxes[i], boxes) > iou_thres  # iou matrix\n            weights = iou * scores[None]  # box weights\n            x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True)  # merged boxes\n            if redundant:\n                i = i[iou.sum(1) > 1]  # require redundancy\n\n        output[xi] = x[i]\n        if mps:\n            output[xi] = output[xi].to(device)\n        if (time.time() - t) > time_limit:\n            LOGGER.warning(f'WARNING ⚠️ NMS time limit {time_limit:.3f}s exceeded')\n            break  # time limit exceeded\n\n    return output\n\n\ndef clip_boxes(boxes, shape):\n    \"\"\"\n    It takes a list of bounding boxes and a shape (height, width) and clips the bounding boxes to the\n    shape\n\n    Args:\n      boxes (torch.Tensor): the bounding boxes to clip\n      shape (tuple): the shape of the image\n    \"\"\"\n    if isinstance(boxes, torch.Tensor):  # faster individually\n        boxes[..., 0].clamp_(0, shape[1])  # x1\n        boxes[..., 1].clamp_(0, shape[0])  # y1\n        boxes[..., 2].clamp_(0, shape[1])  # x2\n        boxes[..., 3].clamp_(0, shape[0])  # y2\n    else:  # np.array (faster grouped)\n        boxes[..., [0, 2]] = boxes[..., [0, 2]].clip(0, shape[1])  # x1, x2\n        boxes[..., [1, 3]] = boxes[..., [1, 3]].clip(0, shape[0])  # y1, y2\n\n\ndef clip_coords(coords, shape):\n    \"\"\"\n    Clip line coordinates to the image boundaries.\n\n    Args:\n        coords (torch.Tensor | numpy.ndarray): A list of line coordinates.\n        shape (tuple): A tuple of integers representing the size of the image in the format (height, width).\n\n    Returns:\n        (None): The function modifies the input `coordinates` in place, by clipping each coordinate to the image boundaries.\n    \"\"\"\n    if isinstance(coords, torch.Tensor):  # faster individually\n        coords[..., 0].clamp_(0, shape[1])  # x\n        coords[..., 1].clamp_(0, shape[0])  # y\n    else:  # np.array (faster grouped)\n        coords[..., 0] = coords[..., 0].clip(0, shape[1])  # x\n        coords[..., 1] = coords[..., 1].clip(0, shape[0])  # y\n\n\ndef scale_image(masks, im0_shape, ratio_pad=None):\n    \"\"\"\n    Takes a mask, and resizes it to the original image size\n\n    Args:\n      masks (torch.Tensor): resized and padded masks/images, [h, w, num]/[h, w, 3].\n      im0_shape (tuple): the original image shape\n      ratio_pad (tuple): the ratio of the padding to the original image.\n\n    Returns:\n      masks (torch.Tensor): The masks that are being returned.\n    \"\"\"\n    # Rescale coordinates (xyxy) from im1_shape to im0_shape\n    im1_shape = masks.shape\n    if im1_shape[:2] == im0_shape[:2]:\n        return masks\n    if ratio_pad is None:  # calculate from im0_shape\n        gain = min(im1_shape[0] / im0_shape[0], im1_shape[1] / im0_shape[1])  # gain  = old / new\n        pad = (im1_shape[1] - im0_shape[1] * gain) / 2, (im1_shape[0] - im0_shape[0] * gain) / 2  # wh padding\n    else:\n        gain = ratio_pad[0][0]\n        pad = ratio_pad[1]\n    top, left = int(pad[1]), int(pad[0])  # y, x\n    bottom, right = int(im1_shape[0] - pad[1]), int(im1_shape[1] - pad[0])\n\n    if len(masks.shape) < 2:\n        raise ValueError(f'\"len of masks shape\" should be 2 or 3, but got {len(masks.shape)}')\n    masks = masks[top:bottom, left:right]\n    # masks = masks.permute(2, 0, 1).contiguous()\n    # masks = F.interpolate(masks[None], im0_shape[:2], mode='bilinear', align_corners=False)[0]\n    # masks = masks.permute(1, 2, 0).contiguous()\n    masks = cv2.resize(masks, (im0_shape[1], im0_shape[0]))\n    if len(masks.shape) == 2:\n        masks = masks[:, :, None]\n\n    return masks\n\n\ndef xyxy2xywh(x):\n    \"\"\"\n    Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height) format.\n\n    Args:\n        x (np.ndarray | torch.Tensor): The input bounding box coordinates in (x1, y1, x2, y2) format.\n    Returns:\n       y (np.ndarray | torch.Tensor): The bounding box coordinates in (x, y, width, height) format.\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[..., 0] = (x[..., 0] + x[..., 2]) / 2  # x center\n    y[..., 1] = (x[..., 1] + x[..., 3]) / 2  # y center\n    y[..., 2] = x[..., 2] - x[..., 0]  # width\n    y[..., 3] = x[..., 3] - x[..., 1]  # height\n    return y\n\n\ndef xywh2xyxy(x):\n    \"\"\"\n    Convert bounding box coordinates from (x, y, width, height) format to (x1, y1, x2, y2) format where (x1, y1) is the\n    top-left corner and (x2, y2) is the bottom-right corner.\n\n    Args:\n        x (np.ndarray | torch.Tensor): The input bounding box coordinates in (x, y, width, height) format.\n    Returns:\n        y (np.ndarray | torch.Tensor): The bounding box coordinates in (x1, y1, x2, y2) format.\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[..., 0] = x[..., 0] - x[..., 2] / 2  # top left x\n    y[..., 1] = x[..., 1] - x[..., 3] / 2  # top left y\n    y[..., 2] = x[..., 0] + x[..., 2] / 2  # bottom right x\n    y[..., 3] = x[..., 1] + x[..., 3] / 2  # bottom right y\n    return y\n\n\ndef xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):\n    \"\"\"\n    Convert normalized bounding box coordinates to pixel coordinates.\n\n    Args:\n        x (np.ndarray | torch.Tensor): The bounding box coordinates.\n        w (int): Width of the image. Defaults to 640\n        h (int): Height of the image. Defaults to 640\n        padw (int): Padding width. Defaults to 0\n        padh (int): Padding height. Defaults to 0\n    Returns:\n        y (np.ndarray | torch.Tensor): The coordinates of the bounding box in the format [x1, y1, x2, y2] where\n            x1,y1 is the top-left corner, x2,y2 is the bottom-right corner of the bounding box.\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[..., 0] = w * (x[..., 0] - x[..., 2] / 2) + padw  # top left x\n    y[..., 1] = h * (x[..., 1] - x[..., 3] / 2) + padh  # top left y\n    y[..., 2] = w * (x[..., 0] + x[..., 2] / 2) + padw  # bottom right x\n    y[..., 3] = h * (x[..., 1] + x[..., 3] / 2) + padh  # bottom right y\n    return y\n\n\ndef xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):\n    \"\"\"\n    Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height, normalized) format.\n    x, y, width and height are normalized to image dimensions\n\n    Args:\n        x (np.ndarray | torch.Tensor): The input bounding box coordinates in (x1, y1, x2, y2) format.\n        w (int): The width of the image. Defaults to 640\n        h (int): The height of the image. Defaults to 640\n        clip (bool): If True, the boxes will be clipped to the image boundaries. Defaults to False\n        eps (float): The minimum value of the box's width and height. Defaults to 0.0\n    Returns:\n        y (np.ndarray | torch.Tensor): The bounding box coordinates in (x, y, width, height, normalized) format\n    \"\"\"\n    if clip:\n        clip_boxes(x, (h - eps, w - eps))  # warning: inplace clip\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[..., 0] = ((x[..., 0] + x[..., 2]) / 2) / w  # x center\n    y[..., 1] = ((x[..., 1] + x[..., 3]) / 2) / h  # y center\n    y[..., 2] = (x[..., 2] - x[..., 0]) / w  # width\n    y[..., 3] = (x[..., 3] - x[..., 1]) / h  # height\n    return y\n\n\ndef xyn2xy(x, w=640, h=640, padw=0, padh=0):\n    \"\"\"\n    Convert normalized coordinates to pixel coordinates of shape (n,2)\n\n    Args:\n        x (np.ndarray | torch.Tensor): The input tensor of normalized bounding box coordinates\n        w (int): The width of the image. Defaults to 640\n        h (int): The height of the image. Defaults to 640\n        padw (int): The width of the padding. Defaults to 0\n        padh (int): The height of the padding. Defaults to 0\n    Returns:\n        y (np.ndarray | torch.Tensor): The x and y coordinates of the top left corner of the bounding box\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[..., 0] = w * x[..., 0] + padw  # top left x\n    y[..., 1] = h * x[..., 1] + padh  # top left y\n    return y\n\n\ndef xywh2ltwh(x):\n    \"\"\"\n    Convert the bounding box format from [x, y, w, h] to [x1, y1, w, h], where x1, y1 are the top-left coordinates.\n\n    Args:\n        x (np.ndarray | torch.Tensor): The input tensor with the bounding box coordinates in the xywh format\n    Returns:\n        y (np.ndarray | torch.Tensor): The bounding box coordinates in the xyltwh format\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = x[:, 0] - x[:, 2] / 2  # top left x\n    y[:, 1] = x[:, 1] - x[:, 3] / 2  # top left y\n    return y\n\n\ndef xyxy2ltwh(x):\n    \"\"\"\n    Convert nx4 bounding boxes from [x1, y1, x2, y2] to [x1, y1, w, h], where xy1=top-left, xy2=bottom-right\n\n    Args:\n      x (np.ndarray | torch.Tensor): The input tensor with the bounding boxes coordinates in the xyxy format\n    Returns:\n      y (np.ndarray | torch.Tensor): The bounding box coordinates in the xyltwh format.\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 2] = x[:, 2] - x[:, 0]  # width\n    y[:, 3] = x[:, 3] - x[:, 1]  # height\n    return y\n\n\ndef ltwh2xywh(x):\n    \"\"\"\n    Convert nx4 boxes from [x1, y1, w, h] to [x, y, w, h] where xy1=top-left, xy=center\n\n    Args:\n      x (torch.Tensor): the input tensor\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = x[:, 0] + x[:, 2] / 2  # center x\n    y[:, 1] = x[:, 1] + x[:, 3] / 2  # center y\n    return y\n\n\ndef ltwh2xyxy(x):\n    \"\"\"\n    It converts the bounding box from [x1, y1, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n\n    Args:\n      x (np.ndarray | torch.Tensor): the input image\n\n    Returns:\n      y (np.ndarray | torch.Tensor): the xyxy coordinates of the bounding boxes.\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 2] = x[:, 2] + x[:, 0]  # width\n    y[:, 3] = x[:, 3] + x[:, 1]  # height\n    return y\n\n\ndef segments2boxes(segments):\n    \"\"\"\n    It converts segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)\n\n    Args:\n      segments (list): list of segments, each segment is a list of points, each point is a list of x, y coordinates\n\n    Returns:\n      (np.ndarray): the xywh coordinates of the bounding boxes.\n    \"\"\"\n    boxes = []\n    for s in segments:\n        x, y = s.T  # segment xy\n        boxes.append([x.min(), y.min(), x.max(), y.max()])  # cls, xyxy\n    return xyxy2xywh(np.array(boxes))  # cls, xywh\n\n\ndef resample_segments(segments, n=1000):\n    \"\"\"\n    Inputs a list of segments (n,2) and returns a list of segments (n,2) up-sampled to n points each.\n\n    Args:\n      segments (list): a list of (n,2) arrays, where n is the number of points in the segment.\n      n (int): number of points to resample the segment to. Defaults to 1000\n\n    Returns:\n      segments (list): the resampled segments.\n    \"\"\"\n    for i, s in enumerate(segments):\n        s = np.concatenate((s, s[0:1, :]), axis=0)\n        x = np.linspace(0, len(s) - 1, n)\n        xp = np.arange(len(s))\n        segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)],\n                                     dtype=np.float32).reshape(2, -1).T  # segment xy\n    return segments\n\n\ndef crop_mask(masks, boxes):\n    \"\"\"\n    It takes a mask and a bounding box, and returns a mask that is cropped to the bounding box\n\n    Args:\n      masks (torch.Tensor): [h, w, n] tensor of masks\n      boxes (torch.Tensor): [n, 4] tensor of bbox coordinates in relative point form\n\n    Returns:\n      (torch.Tensor): The masks are being cropped to the bounding box.\n    \"\"\"\n    n, h, w = masks.shape\n    x1, y1, x2, y2 = torch.chunk(boxes[:, :, None], 4, 1)  # x1 shape(n,1,1)\n    r = torch.arange(w, device=masks.device, dtype=x1.dtype)[None, None, :]  # rows shape(1,1,w)\n    c = torch.arange(h, device=masks.device, dtype=x1.dtype)[None, :, None]  # cols shape(1,h,1)\n\n    return masks * ((r >= x1) * (r < x2) * (c >= y1) * (c < y2))\n\n\ndef process_mask_upsample(protos, masks_in, bboxes, shape):\n    \"\"\"\n    It takes the output of the mask head, and applies the mask to the bounding boxes. This produces masks of higher\n    quality but is slower.\n\n    Args:\n      protos (torch.Tensor): [mask_dim, mask_h, mask_w]\n      masks_in (torch.Tensor): [n, mask_dim], n is number of masks after nms\n      bboxes (torch.Tensor): [n, 4], n is number of masks after nms\n      shape (tuple): the size of the input image (h,w)\n\n    Returns:\n      (torch.Tensor): The upsampled masks.\n    \"\"\"\n    c, mh, mw = protos.shape  # CHW\n    masks = (masks_in @ protos.float().view(c, -1)).view(-1, mh, mw)\n    masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0]  # CHW\n    masks = crop_mask(masks, bboxes)  # CHW\n    return masks.gt_(0)\n\n\ndef process_mask(protos, masks_in, bboxes, shape, upsample=False):\n    \"\"\"\n    Apply masks to bounding boxes using the output of the mask head.\n\n    Args:\n        protos (torch.Tensor): A tensor of shape [mask_dim, mask_h, mask_w].\n        masks_in (torch.Tensor): A tensor of shape [n, mask_dim], where n is the number of masks after NMS.\n        bboxes (torch.Tensor): A tensor of shape [n, 4], where n is the number of masks after NMS.\n        shape (tuple): A tuple of integers representing the size of the input image in the format (h, w).\n        upsample (bool): A flag to indicate whether to upsample the mask to the original image size. Default is False.\n\n    Returns:\n        (torch.Tensor): A binary mask tensor of shape [n, h, w], where n is the number of masks after NMS, and h and w\n            are the height and width of the input image. The mask is applied to the bounding boxes.\n    \"\"\"\n\n    c, mh, mw = protos.shape  # CHW\n    ih, iw = shape\n    masks = (masks_in @ protos.float().view(c, -1)).view(-1, mh, mw)  # CHW\n\n    downsampled_bboxes = bboxes.clone()\n    downsampled_bboxes[:, 0] *= mw / iw\n    downsampled_bboxes[:, 2] *= mw / iw\n    downsampled_bboxes[:, 3] *= mh / ih\n    downsampled_bboxes[:, 1] *= mh / ih\n\n    masks = crop_mask(masks, downsampled_bboxes)  # CHW\n    if upsample:\n        masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0]  # CHW\n    return masks.gt_(0)\n\n\ndef process_mask_native(protos, masks_in, bboxes, shape):\n    \"\"\"\n    It takes the output of the mask head, and crops it after upsampling to the bounding boxes.\n\n    Args:\n      protos (torch.Tensor): [mask_dim, mask_h, mask_w]\n      masks_in (torch.Tensor): [n, mask_dim], n is number of masks after nms\n      bboxes (torch.Tensor): [n, 4], n is number of masks after nms\n      shape (tuple): the size of the input image (h,w)\n\n    Returns:\n      masks (torch.Tensor): The returned masks with dimensions [h, w, n]\n    \"\"\"\n    c, mh, mw = protos.shape  # CHW\n    masks = (masks_in @ protos.float().view(c, -1)).view(-1, mh, mw)\n    gain = min(mh / shape[0], mw / shape[1])  # gain  = old / new\n    pad = (mw - shape[1] * gain) / 2, (mh - shape[0] * gain) / 2  # wh padding\n    top, left = int(pad[1]), int(pad[0])  # y, x\n    bottom, right = int(mh - pad[1]), int(mw - pad[0])\n    masks = masks[:, top:bottom, left:right]\n\n    masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0]  # CHW\n    masks = crop_mask(masks, bboxes)  # CHW\n    return masks.gt_(0)\n\n\ndef scale_coords(img1_shape, coords, img0_shape, ratio_pad=None, normalize=False):\n    \"\"\"\n    Rescale segment coordinates (xyxy) from img1_shape to img0_shape\n\n    Args:\n      img1_shape (tuple): The shape of the image that the coords are from.\n      coords (torch.Tensor): the coords to be scaled\n      img0_shape (tuple): the shape of the image that the segmentation is being applied to\n      ratio_pad (tuple): the ratio of the image size to the padded image size.\n      normalize (bool): If True, the coordinates will be normalized to the range [0, 1]. Defaults to False\n\n    Returns:\n      coords (torch.Tensor): the segmented image.\n    \"\"\"\n    if ratio_pad is None:  # calculate from img0_shape\n        gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])  # gain  = old / new\n        pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2  # wh padding\n    else:\n        gain = ratio_pad[0][0]\n        pad = ratio_pad[1]\n\n    coords[..., 0] -= pad[0]  # x padding\n    coords[..., 1] -= pad[1]  # y padding\n    coords[..., 0] /= gain\n    coords[..., 1] /= gain\n    clip_coords(coords, img0_shape)\n    if normalize:\n        coords[..., 0] /= img0_shape[1]  # width\n        coords[..., 1] /= img0_shape[0]  # height\n    return coords\n\n\ndef masks2segments(masks, strategy='largest'):\n    \"\"\"\n    It takes a list of masks(n,h,w) and returns a list of segments(n,xy)\n\n    Args:\n      masks (torch.Tensor): the output of the model, which is a tensor of shape (batch_size, 160, 160)\n      strategy (str): 'concat' or 'largest'. Defaults to largest\n\n    Returns:\n      segments (List): list of segment masks\n    \"\"\"\n    segments = []\n    for x in masks.int().cpu().numpy().astype('uint8'):\n        c = cv2.findContours(x, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]\n        if c:\n            if strategy == 'concat':  # concatenate all segments\n                c = np.concatenate([x.reshape(-1, 2) for x in c])\n            elif strategy == 'largest':  # select largest segment\n                c = np.array(c[np.array([len(x) for x in c]).argmax()]).reshape(-1, 2)\n        else:\n            c = np.zeros((0, 2))  # no segments found\n        segments.append(c.astype('float32'))\n    return segments\n\n\ndef clean_str(s):\n    \"\"\"\n    Cleans a string by replacing special characters with underscore _\n\n    Args:\n      s (str): a string needing special characters replaced\n\n    Returns:\n      (str): a string with special characters replaced by an underscore _\n    \"\"\"\n    return re.sub(pattern='[|@#!¡·$€%&()=?¿^*;:,¨´><+]', repl='_', string=s)\n"
  },
  {
    "path": "ultralytics/yolo/utils/patches.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nMonkey patches to update/extend functionality of existing functions\n\"\"\"\n\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport torch\n\n# OpenCV Multilanguage-friendly functions ------------------------------------------------------------------------------\n_imshow = cv2.imshow  # copy to avoid recursion errors\n\n\ndef imread(filename, flags=cv2.IMREAD_COLOR):\n    return cv2.imdecode(np.fromfile(filename, np.uint8), flags)\n\n\ndef imwrite(filename, img):\n    try:\n        cv2.imencode(Path(filename).suffix, img)[1].tofile(filename)\n        return True\n    except Exception:\n        return False\n\n\ndef imshow(path, im):\n    _imshow(path.encode('unicode_escape').decode(), im)\n\n\n# PyTorch functions ----------------------------------------------------------------------------------------------------\n_torch_save = torch.save  # copy to avoid recursion errors\n\n\ndef torch_save(*args, **kwargs):\n    # Use dill (if exists) to serialize the lambda functions where pickle does not do this\n    try:\n        import dill as pickle\n    except ImportError:\n        import pickle\n\n    if 'pickle_module' not in kwargs:\n        kwargs['pickle_module'] = pickle\n    return _torch_save(*args, **kwargs)\n"
  },
  {
    "path": "ultralytics/yolo/utils/plotting.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport math\nfrom pathlib import Path\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom PIL import Image, ImageDraw, ImageFont\nfrom PIL import __version__ as pil_version\nfrom scipy.ndimage import gaussian_filter1d\n\nfrom ultralytics.yolo.utils import LOGGER, TryExcept, plt_settings, threaded\n\nfrom .checks import check_font, check_version, is_ascii\nfrom .files import increment_path\nfrom .ops import clip_boxes, scale_image, xywh2xyxy, xyxy2xywh\n\n\nclass Colors:\n    # Ultralytics color palette https://ultralytics.com/\n    def __init__(self):\n        \"\"\"Initialize colors as hex = matplotlib.colors.TABLEAU_COLORS.values().\"\"\"\n        hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',\n                '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')\n        self.palette = [self.hex2rgb(f'#{c}') for c in hexs]\n        self.n = len(self.palette)\n        self.pose_palette = np.array([[255, 128, 0], [255, 153, 51], [255, 178, 102], [230, 230, 0], [255, 153, 255],\n                                      [153, 204, 255], [255, 102, 255], [255, 51, 255], [102, 178, 255], [51, 153, 255],\n                                      [255, 153, 153], [255, 102, 102], [255, 51, 51], [153, 255, 153], [102, 255, 102],\n                                      [51, 255, 51], [0, 255, 0], [0, 0, 255], [255, 0, 0], [255, 255, 255]],\n                                     dtype=np.uint8)\n\n    def __call__(self, i, bgr=False):\n        \"\"\"Converts hex color codes to rgb values.\"\"\"\n        c = self.palette[int(i) % self.n]\n        return (c[2], c[1], c[0]) if bgr else c\n\n    @staticmethod\n    def hex2rgb(h):  # rgb order (PIL)\n        return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))\n\n\ncolors = Colors()  # create instance for 'from utils.plots import colors'\n\n\nclass Annotator:\n    # YOLOv8 Annotator for train/val mosaics and jpgs and detect/hub inference annotations\n    def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'):\n        \"\"\"Initialize the Annotator class with image and line width along with color palette for keypoints and limbs.\"\"\"\n        assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.'\n        non_ascii = not is_ascii(example)  # non-latin labels, i.e. asian, arabic, cyrillic\n        self.pil = pil or non_ascii\n        if self.pil:  # use PIL\n            self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)\n            self.draw = ImageDraw.Draw(self.im)\n            try:\n                font = check_font('Arial.Unicode.ttf' if non_ascii else font)\n                size = font_size or max(round(sum(self.im.size) / 2 * 0.035), 12)\n                self.font = ImageFont.truetype(str(font), size)\n            except Exception:\n                self.font = ImageFont.load_default()\n            # Deprecation fix for w, h = getsize(string) -> _, _, w, h = getbox(string)\n            if check_version(pil_version, '9.2.0'):\n                self.font.getsize = lambda x: self.font.getbbox(x)[2:4]  # text width, height\n        else:  # use cv2\n            self.im = im\n        self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2)  # line width\n        # Pose\n        self.skeleton = [[16, 14], [14, 12], [17, 15], [15, 13], [12, 13], [6, 12], [7, 13], [6, 7], [6, 8], [7, 9],\n                         [8, 10], [9, 11], [2, 3], [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7]]\n\n        self.limb_color = colors.pose_palette[[9, 9, 9, 9, 7, 7, 7, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16]]\n        self.kpt_color = colors.pose_palette[[16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9]]\n\n    def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):\n        \"\"\"Add one xyxy box to image with label.\"\"\"\n        if isinstance(box, torch.Tensor):\n            box = box.tolist()\n        if self.pil or not is_ascii(label):\n            self.draw.rectangle(box, width=self.lw, outline=color)  # box\n            if label:\n                w, h = self.font.getsize(label)  # text width, height\n                outside = box[1] - h >= 0  # label fits outside box\n                self.draw.rectangle(\n                    (box[0], box[1] - h if outside else box[1], box[0] + w + 1,\n                     box[1] + 1 if outside else box[1] + h + 1),\n                    fill=color,\n                )\n                # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls')  # for PIL>8.0\n                self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font)\n        else:  # cv2\n            p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))\n            cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA)\n            if label:\n                tf = max(self.lw - 1, 1)  # font thickness\n                w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0]  # text width, height\n                outside = p1[1] - h >= 3\n                p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3\n                cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA)  # filled\n                cv2.putText(self.im,\n                            label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2),\n                            0,\n                            self.lw / 3,\n                            txt_color,\n                            thickness=tf,\n                            lineType=cv2.LINE_AA)\n\n    def masks(self, masks, colors, im_gpu, alpha=0.5, retina_masks=False):\n        \"\"\"Plot masks at once.\n        Args:\n            masks (tensor): predicted masks on cuda, shape: [n, h, w]\n            colors (List[List[Int]]): colors for predicted masks, [[r, g, b] * n]\n            im_gpu (tensor): img is in cuda, shape: [3, h, w], range: [0, 1]\n            alpha (float): mask transparency: 0.0 fully transparent, 1.0 opaque\n        \"\"\"\n        if self.pil:\n            # Convert to numpy first\n            self.im = np.asarray(self.im).copy()\n        if len(masks) == 0:\n            self.im[:] = im_gpu.permute(1, 2, 0).contiguous().cpu().numpy() * 255\n        if im_gpu.device != masks.device:\n            im_gpu = im_gpu.to(masks.device)\n        colors = torch.tensor(colors, device=masks.device, dtype=torch.float32) / 255.0  # shape(n,3)\n        colors = colors[:, None, None]  # shape(n,1,1,3)\n        masks = masks.unsqueeze(3)  # shape(n,h,w,1)\n        masks_color = masks * (colors * alpha)  # shape(n,h,w,3)\n\n        inv_alph_masks = (1 - masks * alpha).cumprod(0)  # shape(n,h,w,1)\n        mcs = masks_color.max(dim=0).values  # shape(n,h,w,3)\n\n        im_gpu = im_gpu.flip(dims=[0])  # flip channel\n        im_gpu = im_gpu.permute(1, 2, 0).contiguous()  # shape(h,w,3)\n        im_gpu = im_gpu * inv_alph_masks[-1] + mcs\n        im_mask = (im_gpu * 255)\n        im_mask_np = im_mask.byte().cpu().numpy()\n        self.im[:] = im_mask_np if retina_masks else scale_image(im_mask_np, self.im.shape)\n        if self.pil:\n            # Convert im back to PIL and update draw\n            self.fromarray(self.im)\n\n    def kpts(self, kpts, shape=(640, 640), radius=5, kpt_line=True):\n        \"\"\"Plot keypoints on the image.\n\n        Args:\n            kpts (tensor): Predicted keypoints with shape [17, 3]. Each keypoint has (x, y, confidence).\n            shape (tuple): Image shape as a tuple (h, w), where h is the height and w is the width.\n            radius (int, optional): Radius of the drawn keypoints. Default is 5.\n            kpt_line (bool, optional): If True, the function will draw lines connecting keypoints\n                                       for human pose. Default is True.\n\n        Note: `kpt_line=True` currently only supports human pose plotting.\n        \"\"\"\n        if self.pil:\n            # Convert to numpy first\n            self.im = np.asarray(self.im).copy()\n        nkpt, ndim = kpts.shape\n        is_pose = nkpt == 17 and ndim == 3\n        kpt_line &= is_pose  # `kpt_line=True` for now only supports human pose plotting\n        for i, k in enumerate(kpts):\n            color_k = [int(x) for x in self.kpt_color[i]] if is_pose else colors(i)\n            x_coord, y_coord = k[0], k[1]\n            if x_coord % shape[1] != 0 and y_coord % shape[0] != 0:\n                if len(k) == 3:\n                    conf = k[2]\n                    if conf < 0.5:\n                        continue\n                cv2.circle(self.im, (int(x_coord), int(y_coord)), radius, color_k, -1, lineType=cv2.LINE_AA)\n\n        if kpt_line:\n            ndim = kpts.shape[-1]\n            for i, sk in enumerate(self.skeleton):\n                pos1 = (int(kpts[(sk[0] - 1), 0]), int(kpts[(sk[0] - 1), 1]))\n                pos2 = (int(kpts[(sk[1] - 1), 0]), int(kpts[(sk[1] - 1), 1]))\n                if ndim == 3:\n                    conf1 = kpts[(sk[0] - 1), 2]\n                    conf2 = kpts[(sk[1] - 1), 2]\n                    if conf1 < 0.5 or conf2 < 0.5:\n                        continue\n                if pos1[0] % shape[1] == 0 or pos1[1] % shape[0] == 0 or pos1[0] < 0 or pos1[1] < 0:\n                    continue\n                if pos2[0] % shape[1] == 0 or pos2[1] % shape[0] == 0 or pos2[0] < 0 or pos2[1] < 0:\n                    continue\n                cv2.line(self.im, pos1, pos2, [int(x) for x in self.limb_color[i]], thickness=2, lineType=cv2.LINE_AA)\n        if self.pil:\n            # Convert im back to PIL and update draw\n            self.fromarray(self.im)\n\n    def rectangle(self, xy, fill=None, outline=None, width=1):\n        \"\"\"Add rectangle to image (PIL-only).\"\"\"\n        self.draw.rectangle(xy, fill, outline, width)\n\n    def text(self, xy, text, txt_color=(255, 255, 255), anchor='top', box_style=False):\n        \"\"\"Adds text to an image using PIL or cv2.\"\"\"\n        if anchor == 'bottom':  # start y from font bottom\n            w, h = self.font.getsize(text)  # text width, height\n            xy[1] += 1 - h\n        if self.pil:\n            if box_style:\n                w, h = self.font.getsize(text)\n                self.draw.rectangle((xy[0], xy[1], xy[0] + w + 1, xy[1] + h + 1), fill=txt_color)\n                # Using `txt_color` for background and draw fg with white color\n                txt_color = (255, 255, 255)\n            self.draw.text(xy, text, fill=txt_color, font=self.font)\n        else:\n            if box_style:\n                tf = max(self.lw - 1, 1)  # font thickness\n                w, h = cv2.getTextSize(text, 0, fontScale=self.lw / 3, thickness=tf)[0]  # text width, height\n                outside = xy[1] - h >= 3\n                p2 = xy[0] + w, xy[1] - h - 3 if outside else xy[1] + h + 3\n                cv2.rectangle(self.im, xy, p2, txt_color, -1, cv2.LINE_AA)  # filled\n                # Using `txt_color` for background and draw fg with white color\n                txt_color = (255, 255, 255)\n            tf = max(self.lw - 1, 1)  # font thickness\n            cv2.putText(self.im, text, xy, 0, self.lw / 3, txt_color, thickness=tf, lineType=cv2.LINE_AA)\n\n    def fromarray(self, im):\n        \"\"\"Update self.im from a numpy array.\"\"\"\n        self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)\n        self.draw = ImageDraw.Draw(self.im)\n\n    def result(self):\n        \"\"\"Return annotated image as array.\"\"\"\n        return np.asarray(self.im)\n\n\n@TryExcept()  # known issue https://github.com/ultralytics/yolov5/issues/5395\n@plt_settings()\ndef plot_labels(boxes, cls, names=(), save_dir=Path(''), on_plot=None):\n    \"\"\"Save and plot image with no axis or spines.\"\"\"\n    import pandas as pd\n    import seaborn as sn\n\n    # Plot dataset labels\n    LOGGER.info(f\"Plotting labels to {save_dir / 'labels.jpg'}... \")\n    b = boxes.transpose()  # classes, boxes\n    nc = int(cls.max() + 1)  # number of classes\n    x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])\n\n    # Seaborn correlogram\n    sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))\n    plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)\n    plt.close()\n\n    # Matplotlib labels\n    ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()\n    y = ax[0].hist(cls, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)\n    with contextlib.suppress(Exception):  # color histogram bars by class\n        [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)]  # known issue #3195\n    ax[0].set_ylabel('instances')\n    if 0 < len(names) < 30:\n        ax[0].set_xticks(range(len(names)))\n        ax[0].set_xticklabels(list(names.values()), rotation=90, fontsize=10)\n    else:\n        ax[0].set_xlabel('classes')\n    sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)\n    sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)\n\n    # Rectangles\n    boxes[:, 0:2] = 0.5  # center\n    boxes = xywh2xyxy(boxes) * 1000\n    img = Image.fromarray(np.ones((1000, 1000, 3), dtype=np.uint8) * 255)\n    for cls, box in zip(cls[:500], boxes[:500]):\n        ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls))  # plot\n    ax[1].imshow(img)\n    ax[1].axis('off')\n\n    for a in [0, 1, 2, 3]:\n        for s in ['top', 'right', 'left', 'bottom']:\n            ax[a].spines[s].set_visible(False)\n\n    fname = save_dir / 'labels.jpg'\n    plt.savefig(fname, dpi=200)\n    plt.close()\n    if on_plot:\n        on_plot(fname)\n\n\ndef save_one_box(xyxy, im, file=Path('im.jpg'), gain=1.02, pad=10, square=False, BGR=False, save=True):\n    \"\"\"Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop.\"\"\"\n    b = xyxy2xywh(xyxy.view(-1, 4))  # boxes\n    if square:\n        b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1)  # attempt rectangle to square\n    b[:, 2:] = b[:, 2:] * gain + pad  # box wh * gain + pad\n    xyxy = xywh2xyxy(b).long()\n    clip_boxes(xyxy, im.shape)\n    crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)]\n    if save:\n        file.parent.mkdir(parents=True, exist_ok=True)  # make directory\n        f = str(increment_path(file).with_suffix('.jpg'))\n        # cv2.imwrite(f, crop)  # save BGR, https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue\n        Image.fromarray(crop[..., ::-1]).save(f, quality=95, subsampling=0)  # save RGB\n    return crop\n\n\n@threaded\ndef plot_images(images,\n                batch_idx,\n                cls,\n                bboxes=np.zeros(0, dtype=np.float32),\n                masks=np.zeros(0, dtype=np.uint8),\n                kpts=np.zeros((0, 51), dtype=np.float32),\n                paths=None,\n                fname='images.jpg',\n                names=None,\n                on_plot=None):\n    # Plot image grid with labels\n    if isinstance(images, torch.Tensor):\n        images = images.cpu().float().numpy()\n    if isinstance(cls, torch.Tensor):\n        cls = cls.cpu().numpy()\n    if isinstance(bboxes, torch.Tensor):\n        bboxes = bboxes.cpu().numpy()\n    if isinstance(masks, torch.Tensor):\n        masks = masks.cpu().numpy().astype(int)\n    if isinstance(kpts, torch.Tensor):\n        kpts = kpts.cpu().numpy()\n    if isinstance(batch_idx, torch.Tensor):\n        batch_idx = batch_idx.cpu().numpy()\n\n    max_size = 1920  # max image size\n    max_subplots = 16  # max image subplots, i.e. 4x4\n    bs, _, h, w = images.shape  # batch size, _, height, width\n    bs = min(bs, max_subplots)  # limit plot images\n    ns = np.ceil(bs ** 0.5)  # number of subplots (square)\n    if np.max(images[0]) <= 1:\n        images *= 255  # de-normalise (optional)\n\n    # Build Image\n    mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8)  # init\n    for i, im in enumerate(images):\n        if i == max_subplots:  # if last batch has fewer images than we expect\n            break\n        x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n        im = im.transpose(1, 2, 0)\n        mosaic[y:y + h, x:x + w, :] = im\n\n    # Resize (optional)\n    scale = max_size / ns / max(h, w)\n    if scale < 1:\n        h = math.ceil(scale * h)\n        w = math.ceil(scale * w)\n        mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))\n\n    # Annotate\n    fs = int((h + w) * ns * 0.01)  # font size\n    annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names)\n    for i in range(i + 1):\n        x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n        annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2)  # borders\n        if paths:\n            annotator.text((x + 5, y + 5), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220))  # filenames\n        if len(cls) > 0:\n            idx = batch_idx == i\n            classes = cls[idx].astype('int')\n\n            if len(bboxes):\n                boxes = xywh2xyxy(bboxes[idx, :4]).T\n                labels = bboxes.shape[1] == 4  # labels if no conf column\n                conf = None if labels else bboxes[idx, 4]  # check for confidence presence (label vs pred)\n\n                if boxes.shape[1]:\n                    if boxes.max() <= 1.01:  # if normalized with tolerance 0.01\n                        boxes[[0, 2]] *= w  # scale to pixels\n                        boxes[[1, 3]] *= h\n                    elif scale < 1:  # absolute coords need scale if image scales\n                        boxes *= scale\n                boxes[[0, 2]] += x\n                boxes[[1, 3]] += y\n                for j, box in enumerate(boxes.T.tolist()):\n                    c = classes[j]\n                    color = colors(c)\n                    c = names.get(c, c) if names else c\n                    if labels or conf[j] > 0.25:  # 0.25 conf thresh\n                        label = f'{c}' if labels else f'{c} {conf[j]:.1f}'\n                        annotator.box_label(box, label, color=color)\n            elif len(classes):\n                for c in classes:\n                    color = colors(c)\n                    c = names.get(c, c) if names else c\n                    annotator.text((x, y), f'{c}', txt_color=color, box_style=True)\n\n            # Plot keypoints\n            if len(kpts):\n                kpts_ = kpts[idx].copy()\n                if len(kpts_):\n                    if kpts_[..., 0].max() <= 1.01 or kpts_[..., 1].max() <= 1.01:  # if normalized with tolerance .01\n                        kpts_[..., 0] *= w  # scale to pixels\n                        kpts_[..., 1] *= h\n                    elif scale < 1:  # absolute coords need scale if image scales\n                        kpts_ *= scale\n                kpts_[..., 0] += x\n                kpts_[..., 1] += y\n                for j in range(len(kpts_)):\n                    if labels or conf[j] > 0.25:  # 0.25 conf thresh\n                        annotator.kpts(kpts_[j])\n\n            # Plot masks\n            if len(masks):\n                if idx.shape[0] == masks.shape[0]:  # overlap_masks=False\n                    image_masks = masks[idx]\n                else:  # overlap_masks=True\n                    image_masks = masks[[i]]  # (1, 640, 640)\n                    nl = idx.sum()\n                    index = np.arange(nl).reshape((nl, 1, 1)) + 1\n                    image_masks = np.repeat(image_masks, nl, axis=0)\n                    image_masks = np.where(image_masks == index, 1.0, 0.0)\n\n                im = np.asarray(annotator.im).copy()\n                for j, box in enumerate(boxes.T.tolist()):\n                    if labels or conf[j] > 0.25:  # 0.25 conf thresh\n                        color = colors(classes[j])\n                        mh, mw = image_masks[j].shape\n                        if mh != h or mw != w:\n                            mask = image_masks[j].astype(np.uint8)\n                            mask = cv2.resize(mask, (w, h))\n                            mask = mask.astype(bool)\n                        else:\n                            mask = image_masks[j].astype(bool)\n                        with contextlib.suppress(Exception):\n                            im[y:y + h, x:x + w, :][mask] = im[y:y + h, x:x + w, :][mask] * 0.4 + np.array(color) * 0.6\n                annotator.fromarray(im)\n    annotator.im.save(fname)  # save\n    if on_plot:\n        on_plot(fname)\n\n\n@plt_settings()\ndef plot_results(file='path/to/results.csv', dir='', segment=False, pose=False, classify=False, on_plot=None):\n    \"\"\"Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv').\"\"\"\n    import pandas as pd\n    save_dir = Path(file).parent if file else Path(dir)\n    if classify:\n        fig, ax = plt.subplots(2, 2, figsize=(6, 6), tight_layout=True)\n        index = [1, 4, 2, 3]\n    elif segment:\n        fig, ax = plt.subplots(2, 8, figsize=(18, 6), tight_layout=True)\n        index = [1, 2, 3, 4, 5, 6, 9, 10, 13, 14, 15, 16, 7, 8, 11, 12]\n    elif pose:\n        fig, ax = plt.subplots(2, 9, figsize=(21, 6), tight_layout=True)\n        index = [1, 2, 3, 4, 5, 6, 7, 10, 11, 14, 15, 16, 17, 18, 8, 9, 12, 13]\n    else:\n        fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)\n        index = [1, 2, 3, 4, 5, 8, 9, 10, 6, 7]\n    ax = ax.ravel()\n    files = list(save_dir.glob('results*.csv'))\n    assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.'\n    for f in files:\n        try:\n            data = pd.read_csv(f)\n            s = [x.strip() for x in data.columns]\n            x = data.values[:, 0]\n            for i, j in enumerate(index):\n                y = data.values[:, j].astype('float')\n                # y[y == 0] = np.nan  # don't show zero values\n                ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8)  # actual results\n                ax[i].plot(x, gaussian_filter1d(y, sigma=3), ':', label='smooth', linewidth=2)  # smoothing line\n                ax[i].set_title(s[j], fontsize=12)\n                # if j in [8, 9, 10]:  # share train and val loss y axes\n                #     ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])\n        except Exception as e:\n            LOGGER.warning(f'WARNING: Plotting error for {f}: {e}')\n    ax[1].legend()\n    fname = save_dir / 'results.png'\n    fig.savefig(fname, dpi=200)\n    plt.close()\n    if on_plot:\n        on_plot(fname)\n\n\ndef output_to_target(output, max_det=300):\n    \"\"\"Convert model output to target format [batch_id, class_id, x, y, w, h, conf] for plotting.\"\"\"\n    targets = []\n    for i, o in enumerate(output):\n        box, conf, cls = o[:max_det, :6].cpu().split((4, 1, 1), 1)\n        j = torch.full((conf.shape[0], 1), i)\n        targets.append(torch.cat((j, cls, xyxy2xywh(box), conf), 1))\n    targets = torch.cat(targets, 0).numpy()\n    return targets[:, 0], targets[:, 1], targets[:, 2:]\n\n\ndef feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')):\n    \"\"\"\n    Visualize feature maps of a given model module during inference.\n\n    Args:\n        x (torch.Tensor): Features to be visualized.\n        module_type (str): Module type.\n        stage (int): Module stage within the model.\n        n (int, optional): Maximum number of feature maps to plot. Defaults to 32.\n        save_dir (Path, optional): Directory to save results. Defaults to Path('runs/detect/exp').\n    \"\"\"\n    for m in ['Detect', 'Pose', 'Segment']:\n        if m in module_type:\n            return\n    batch, channels, height, width = x.shape  # batch, channels, height, width\n    if height > 1 and width > 1:\n        f = save_dir / f\"stage{stage}_{module_type.split('.')[-1]}_features.png\"  # filename\n\n        blocks = torch.chunk(x[0].cpu(), channels, dim=0)  # select batch index 0, block by channels\n        n = min(n, channels)  # number of plots\n        fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True)  # 8 rows x n/8 cols\n        ax = ax.ravel()\n        plt.subplots_adjust(wspace=0.05, hspace=0.05)\n        for i in range(n):\n            ax[i].imshow(blocks[i].squeeze())  # cmap='gray'\n            ax[i].axis('off')\n\n        LOGGER.info(f'Saving {f}... ({n}/{channels})')\n        plt.savefig(f, dpi=300, bbox_inches='tight')\n        plt.close()\n        np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy())  # npy save\n"
  },
  {
    "path": "ultralytics/yolo/utils/tal.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\nimport torch.nn as nn\n\nfrom .checks import check_version\nfrom .metrics import bbox_iou\n\nTORCH_1_10 = check_version(torch.__version__, '1.10.0')\n\n\ndef select_candidates_in_gts(xy_centers, gt_bboxes, eps=1e-9):\n    \"\"\"select the positive anchor center in gt\n\n    Args:\n        xy_centers (Tensor): shape(h*w, 4)\n        gt_bboxes (Tensor): shape(b, n_boxes, 4)\n    Return:\n        (Tensor): shape(b, n_boxes, h*w)\n    \"\"\"\n    n_anchors = xy_centers.shape[0]\n    bs, n_boxes, _ = gt_bboxes.shape\n    lt, rb = gt_bboxes.view(-1, 1, 4).chunk(2, 2)  # left-top, right-bottom\n    bbox_deltas = torch.cat((xy_centers[None] - lt, rb - xy_centers[None]), dim=2).view(bs, n_boxes, n_anchors, -1)\n    # return (bbox_deltas.min(3)[0] > eps).to(gt_bboxes.dtype)\n    return bbox_deltas.amin(3).gt_(eps)\n\n\ndef select_highest_overlaps(mask_pos, overlaps, n_max_boxes):\n    \"\"\"if an anchor box is assigned to multiple gts,\n        the one with the highest iou will be selected.\n\n    Args:\n        mask_pos (Tensor): shape(b, n_max_boxes, h*w)\n        overlaps (Tensor): shape(b, n_max_boxes, h*w)\n    Return:\n        target_gt_idx (Tensor): shape(b, h*w)\n        fg_mask (Tensor): shape(b, h*w)\n        mask_pos (Tensor): shape(b, n_max_boxes, h*w)\n    \"\"\"\n    # (b, n_max_boxes, h*w) -> (b, h*w)\n    fg_mask = mask_pos.sum(-2)\n    if fg_mask.max() > 1:  # one anchor is assigned to multiple gt_bboxes\n        mask_multi_gts = (fg_mask.unsqueeze(1) > 1).expand(-1, n_max_boxes, -1)  # (b, n_max_boxes, h*w)\n        max_overlaps_idx = overlaps.argmax(1)  # (b, h*w)\n\n        is_max_overlaps = torch.zeros(mask_pos.shape, dtype=mask_pos.dtype, device=mask_pos.device)\n        is_max_overlaps.scatter_(1, max_overlaps_idx.unsqueeze(1), 1)\n\n        mask_pos = torch.where(mask_multi_gts, is_max_overlaps, mask_pos).float()  # (b, n_max_boxes, h*w)\n        fg_mask = mask_pos.sum(-2)\n    # Find each grid serve which gt(index)\n    target_gt_idx = mask_pos.argmax(-2)  # (b, h*w)\n    return target_gt_idx, fg_mask, mask_pos\n\n\nclass TaskAlignedAssigner(nn.Module):\n    \"\"\"\n    A task-aligned assigner for object detection.\n\n    This class assigns ground-truth (gt) objects to anchors based on the task-aligned metric,\n    which combines both classification and localization information.\n\n    Attributes:\n        topk (int): The number of top candidates to consider.\n        num_classes (int): The number of object classes.\n        alpha (float): The alpha parameter for the classification component of the task-aligned metric.\n        beta (float): The beta parameter for the localization component of the task-aligned metric.\n        eps (float): A small value to prevent division by zero.\n    \"\"\"\n\n    def __init__(self, topk=13, num_classes=80, alpha=1.0, beta=6.0, eps=1e-9):\n        \"\"\"Initialize a TaskAlignedAssigner object with customizable hyperparameters.\"\"\"\n        super().__init__()\n        self.topk = topk\n        self.num_classes = num_classes\n        self.bg_idx = num_classes\n        self.alpha = alpha\n        self.beta = beta\n        self.eps = eps\n\n    @torch.no_grad()\n    def forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt):\n        \"\"\"\n        Compute the task-aligned assignment.\n        Reference https://github.com/Nioolek/PPYOLOE_pytorch/blob/master/ppyoloe/assigner/tal_assigner.py\n\n        Args:\n            pd_scores (Tensor): shape(bs, num_total_anchors, num_classes)\n            pd_bboxes (Tensor): shape(bs, num_total_anchors, 4)\n            anc_points (Tensor): shape(num_total_anchors, 2)\n            gt_labels (Tensor): shape(bs, n_max_boxes, 1)\n            gt_bboxes (Tensor): shape(bs, n_max_boxes, 4)\n            mask_gt (Tensor): shape(bs, n_max_boxes, 1)\n\n        Returns:\n            target_labels (Tensor): shape(bs, num_total_anchors)\n            target_bboxes (Tensor): shape(bs, num_total_anchors, 4)\n            target_scores (Tensor): shape(bs, num_total_anchors, num_classes)\n            fg_mask (Tensor): shape(bs, num_total_anchors)\n            target_gt_idx (Tensor): shape(bs, num_total_anchors)\n        \"\"\"\n        self.bs = pd_scores.size(0)\n        self.n_max_boxes = gt_bboxes.size(1)\n\n        if self.n_max_boxes == 0:\n            device = gt_bboxes.device\n            return (torch.full_like(pd_scores[..., 0], self.bg_idx).to(device), torch.zeros_like(pd_bboxes).to(device),\n                    torch.zeros_like(pd_scores).to(device), torch.zeros_like(pd_scores[..., 0]).to(device),\n                    torch.zeros_like(pd_scores[..., 0]).to(device))\n\n        mask_pos, align_metric, overlaps = self.get_pos_mask(pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points,\n                                                             mask_gt)\n\n        target_gt_idx, fg_mask, mask_pos = select_highest_overlaps(mask_pos, overlaps, self.n_max_boxes)\n\n        # Assigned target\n        target_labels, target_bboxes, target_scores = self.get_targets(gt_labels, gt_bboxes, target_gt_idx, fg_mask)\n\n        # Normalize\n        align_metric *= mask_pos\n        pos_align_metrics = align_metric.amax(axis=-1, keepdim=True)  # b, max_num_obj\n        pos_overlaps = (overlaps * mask_pos).amax(axis=-1, keepdim=True)  # b, max_num_obj\n        norm_align_metric = (align_metric * pos_overlaps / (pos_align_metrics + self.eps)).amax(-2).unsqueeze(-1)\n        target_scores = target_scores * norm_align_metric\n\n        return target_labels, target_bboxes, target_scores, fg_mask.bool(), target_gt_idx\n\n    def get_pos_mask(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt):\n        \"\"\"Get in_gts mask, (b, max_num_obj, h*w).\"\"\"\n        mask_in_gts = select_candidates_in_gts(anc_points, gt_bboxes)\n        # Get anchor_align metric, (b, max_num_obj, h*w)\n        align_metric, overlaps = self.get_box_metrics(pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_in_gts * mask_gt)\n        # Get topk_metric mask, (b, max_num_obj, h*w)\n        mask_topk = self.select_topk_candidates(align_metric, topk_mask=mask_gt.expand(-1, -1, self.topk).bool())\n        # Merge all mask to a final mask, (b, max_num_obj, h*w)\n        mask_pos = mask_topk * mask_in_gts * mask_gt\n\n        return mask_pos, align_metric, overlaps\n\n    def get_box_metrics(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_gt):\n        \"\"\"Compute alignment metric given predicted and ground truth bounding boxes.\"\"\"\n        na = pd_bboxes.shape[-2]\n        mask_gt = mask_gt.bool()  # b, max_num_obj, h*w\n        overlaps = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_bboxes.dtype, device=pd_bboxes.device)\n        bbox_scores = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_scores.dtype, device=pd_scores.device)\n\n        ind = torch.zeros([2, self.bs, self.n_max_boxes], dtype=torch.long)  # 2, b, max_num_obj\n        ind[0] = torch.arange(end=self.bs).view(-1, 1).expand(-1, self.n_max_boxes)  # b, max_num_obj\n        ind[1] = gt_labels.squeeze(-1)  # b, max_num_obj\n        # Get the scores of each grid for each gt cls\n        bbox_scores[mask_gt] = pd_scores[ind[0], :, ind[1]][mask_gt]  # b, max_num_obj, h*w\n\n        # (b, max_num_obj, 1, 4), (b, 1, h*w, 4)\n        pd_boxes = pd_bboxes.unsqueeze(1).expand(-1, self.n_max_boxes, -1, -1)[mask_gt]\n        gt_boxes = gt_bboxes.unsqueeze(2).expand(-1, -1, na, -1)[mask_gt]\n        overlaps[mask_gt] = bbox_iou(gt_boxes, pd_boxes, xywh=False, CIoU=True).squeeze(-1).clamp_(0)\n\n        align_metric = bbox_scores.pow(self.alpha) * overlaps.pow(self.beta)\n        return align_metric, overlaps\n\n    def select_topk_candidates(self, metrics, largest=True, topk_mask=None):\n        \"\"\"\n        Select the top-k candidates based on the given metrics.\n\n        Args:\n            metrics (Tensor): A tensor of shape (b, max_num_obj, h*w), where b is the batch size,\n                              max_num_obj is the maximum number of objects, and h*w represents the\n                              total number of anchor points.\n            largest (bool): If True, select the largest values; otherwise, select the smallest values.\n            topk_mask (Tensor): An optional boolean tensor of shape (b, max_num_obj, topk), where\n                                topk is the number of top candidates to consider. If not provided,\n                                the top-k values are automatically computed based on the given metrics.\n\n        Returns:\n            (Tensor): A tensor of shape (b, max_num_obj, h*w) containing the selected top-k candidates.\n        \"\"\"\n\n        # (b, max_num_obj, topk)\n        topk_metrics, topk_idxs = torch.topk(metrics, self.topk, dim=-1, largest=largest)\n        if topk_mask is None:\n            topk_mask = (topk_metrics.max(-1, keepdim=True)[0] > self.eps).expand_as(topk_idxs)\n        # (b, max_num_obj, topk)\n        topk_idxs.masked_fill_(~topk_mask, 0)\n\n        # (b, max_num_obj, topk, h*w) -> (b, max_num_obj, h*w)\n        count_tensor = torch.zeros(metrics.shape, dtype=torch.int8, device=topk_idxs.device)\n        ones = torch.ones_like(topk_idxs[:, :, :1], dtype=torch.int8, device=topk_idxs.device)\n        for k in range(self.topk):\n            # Expand topk_idxs for each value of k and add 1 at the specified positions\n            count_tensor.scatter_add_(-1, topk_idxs[:, :, k:k + 1], ones)\n        # count_tensor.scatter_add_(-1, topk_idxs, torch.ones_like(topk_idxs, dtype=torch.int8, device=topk_idxs.device))\n        # filter invalid bboxes\n        count_tensor.masked_fill_(count_tensor > 1, 0)\n\n        return count_tensor.to(metrics.dtype)\n\n    def get_targets(self, gt_labels, gt_bboxes, target_gt_idx, fg_mask):\n        \"\"\"\n        Compute target labels, target bounding boxes, and target scores for the positive anchor points.\n\n        Args:\n            gt_labels (Tensor): Ground truth labels of shape (b, max_num_obj, 1), where b is the\n                                batch size and max_num_obj is the maximum number of objects.\n            gt_bboxes (Tensor): Ground truth bounding boxes of shape (b, max_num_obj, 4).\n            target_gt_idx (Tensor): Indices of the assigned ground truth objects for positive\n                                    anchor points, with shape (b, h*w), where h*w is the total\n                                    number of anchor points.\n            fg_mask (Tensor): A boolean tensor of shape (b, h*w) indicating the positive\n                              (foreground) anchor points.\n\n        Returns:\n            (Tuple[Tensor, Tensor, Tensor]): A tuple containing the following tensors:\n                - target_labels (Tensor): Shape (b, h*w), containing the target labels for\n                                          positive anchor points.\n                - target_bboxes (Tensor): Shape (b, h*w, 4), containing the target bounding boxes\n                                          for positive anchor points.\n                - target_scores (Tensor): Shape (b, h*w, num_classes), containing the target scores\n                                          for positive anchor points, where num_classes is the number\n                                          of object classes.\n        \"\"\"\n\n        # Assigned target labels, (b, 1)\n        batch_ind = torch.arange(end=self.bs, dtype=torch.int64, device=gt_labels.device)[..., None]\n        target_gt_idx = target_gt_idx + batch_ind * self.n_max_boxes  # (b, h*w)\n        target_labels = gt_labels.long().flatten()[target_gt_idx]  # (b, h*w)\n\n        # Assigned target boxes, (b, max_num_obj, 4) -> (b, h*w)\n        target_bboxes = gt_bboxes.view(-1, 4)[target_gt_idx]\n\n        # Assigned target scores\n        target_labels.clamp_(0)\n\n        # 10x faster than F.one_hot()\n        target_scores = torch.zeros((target_labels.shape[0], target_labels.shape[1], self.num_classes),\n                                    dtype=torch.int64,\n                                    device=target_labels.device)  # (b, h*w, 80)\n        target_scores.scatter_(2, target_labels.unsqueeze(-1), 1)\n\n        fg_scores_mask = fg_mask[:, :, None].repeat(1, 1, self.num_classes)  # (b, h*w, 80)\n        target_scores = torch.where(fg_scores_mask > 0, target_scores, 0)\n\n        return target_labels, target_bboxes, target_scores\n\n\ndef make_anchors(feats, strides, grid_cell_offset=0.5):\n    \"\"\"Generate anchors from features.\"\"\"\n    anchor_points, stride_tensor = [], []\n    assert feats is not None\n    dtype, device = feats[0].dtype, feats[0].device\n    for i, stride in enumerate(strides):\n        _, _, h, w = feats[i].shape\n        sx = torch.arange(end=w, device=device, dtype=dtype) + grid_cell_offset  # shift x\n        sy = torch.arange(end=h, device=device, dtype=dtype) + grid_cell_offset  # shift y\n        sy, sx = torch.meshgrid(sy, sx, indexing='ij') if TORCH_1_10 else torch.meshgrid(sy, sx)\n        anchor_points.append(torch.stack((sx, sy), -1).view(-1, 2))\n        stride_tensor.append(torch.full((h * w, 1), stride, dtype=dtype, device=device))\n    return torch.cat(anchor_points), torch.cat(stride_tensor)\n\n\ndef dist2bbox(distance, anchor_points, xywh=True, dim=-1):\n    \"\"\"Transform distance(ltrb) to box(xywh or xyxy).\"\"\"\n    lt, rb = distance.chunk(2, dim)\n    x1y1 = anchor_points - lt\n    x2y2 = anchor_points + rb\n    if xywh:\n        c_xy = (x1y1 + x2y2) / 2\n        wh = x2y2 - x1y1\n        return torch.cat((c_xy, wh), dim)  # xywh bbox\n    return torch.cat((x1y1, x2y2), dim)  # xyxy bbox\n\n\ndef bbox2dist(anchor_points, bbox, reg_max):\n    \"\"\"Transform bbox(xyxy) to dist(ltrb).\"\"\"\n    x1y1, x2y2 = bbox.chunk(2, -1)\n    return torch.cat((anchor_points - x1y1, x2y2 - anchor_points), -1).clamp_(0, reg_max - 0.01)  # dist (lt, rb)\n"
  },
  {
    "path": "ultralytics/yolo/utils/torch_utils.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport math\nimport os\nimport platform\nimport random\nimport time\nfrom contextlib import contextmanager\nfrom copy import deepcopy\nfrom pathlib import Path\nfrom typing import Union\n\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\n\nfrom ultralytics.yolo.utils import DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, RANK, __version__\nfrom ultralytics.yolo.utils.checks import check_version\n\ntry:\n    import thop\nexcept ImportError:\n    thop = None\n\nTORCHVISION_0_10 = check_version(torchvision.__version__, '0.10.0')\nTORCH_1_9 = check_version(torch.__version__, '1.9.0')\nTORCH_1_11 = check_version(torch.__version__, '1.11.0')\nTORCH_1_12 = check_version(torch.__version__, '1.12.0')\nTORCH_2_0 = check_version(torch.__version__, minimum='2.0')\n\n\n@contextmanager\ndef torch_distributed_zero_first(local_rank: int):\n    \"\"\"Decorator to make all processes in distributed training wait for each local_master to do something.\"\"\"\n    initialized = torch.distributed.is_available() and torch.distributed.is_initialized()\n    if initialized and local_rank not in (-1, 0):\n        dist.barrier(device_ids=[local_rank])\n    yield\n    if initialized and local_rank == 0:\n        dist.barrier(device_ids=[0])\n\n\ndef smart_inference_mode():\n    \"\"\"Applies torch.inference_mode() decorator if torch>=1.9.0 else torch.no_grad() decorator.\"\"\"\n\n    def decorate(fn):\n        \"\"\"Applies appropriate torch decorator for inference mode based on torch version.\"\"\"\n        return (torch.inference_mode if TORCH_1_9 else torch.no_grad)()(fn)\n\n    return decorate\n\n\ndef select_device(device='', batch=0, newline=False, verbose=True):\n    \"\"\"Selects PyTorch Device. Options are device = None or 'cpu' or 0 or '0' or '0,1,2,3'.\"\"\"\n    s = f'Ultralytics YOLOv{__version__} 🚀 Python-{platform.python_version()} torch-{torch.__version__} '\n    device = str(device).lower()\n    for remove in 'cuda:', 'none', '(', ')', '[', ']', \"'\", ' ':\n        device = device.replace(remove, '')  # to string, 'cuda:0' -> '0' and '(0, 1)' -> '0,1'\n    cpu = device == 'cpu'\n    mps = device == 'mps'  # Apple Metal Performance Shaders (MPS)\n    if cpu or mps:\n        os.environ['CUDA_VISIBLE_DEVICES'] = '-1'  # force torch.cuda.is_available() = False\n    elif device:  # non-cpu device requested\n        if device == 'cuda':\n            device = '0'\n        visible = os.environ.get('CUDA_VISIBLE_DEVICES', None)\n        os.environ['CUDA_VISIBLE_DEVICES'] = device  # set environment variable - must be before assert is_available()\n        if not (torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', ''))):\n            LOGGER.info(s)\n            install = 'See https://pytorch.org/get-started/locally/ for up-to-date torch install instructions if no ' \\\n                      'CUDA devices are seen by torch.\\n' if torch.cuda.device_count() == 0 else ''\n            raise ValueError(f\"Invalid CUDA 'device={device}' requested.\"\n                             f\" Use 'device=cpu' or pass valid CUDA device(s) if available,\"\n                             f\" i.e. 'device=0' or 'device=0,1,2,3' for Multi-GPU.\\n\"\n                             f'\\ntorch.cuda.is_available(): {torch.cuda.is_available()}'\n                             f'\\ntorch.cuda.device_count(): {torch.cuda.device_count()}'\n                             f\"\\nos.environ['CUDA_VISIBLE_DEVICES']: {visible}\\n\"\n                             f'{install}')\n\n    if not cpu and not mps and torch.cuda.is_available():  # prefer GPU if available\n        devices = device.split(',') if device else '0'  # range(torch.cuda.device_count())  # i.e. 0,1,6,7\n        n = len(devices)  # device count\n        if n > 1 and batch > 0 and batch % n != 0:  # check batch_size is divisible by device_count\n            raise ValueError(f\"'batch={batch}' must be a multiple of GPU count {n}. Try 'batch={batch // n * n}' or \"\n                             f\"'batch={batch // n * n + n}', the nearest batch sizes evenly divisible by {n}.\")\n        space = ' ' * (len(s) + 1)\n        for i, d in enumerate(devices):\n            p = torch.cuda.get_device_properties(i)\n            s += f\"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\\n\"  # bytes to MB\n        arg = 'cuda:0'\n    elif mps and getattr(torch, 'has_mps', False) and torch.backends.mps.is_available() and TORCH_2_0:\n        # Prefer MPS if available\n        s += 'MPS\\n'\n        arg = 'mps'\n    else:  # revert to CPU\n        s += 'CPU\\n'\n        arg = 'cpu'\n\n    if verbose and RANK == -1:\n        LOGGER.info(s if newline else s.rstrip())\n    return torch.device(arg)\n\n\ndef time_sync():\n    \"\"\"PyTorch-accurate time.\"\"\"\n    if torch.cuda.is_available():\n        torch.cuda.synchronize()\n    return time.time()\n\n\ndef fuse_conv_and_bn(conv, bn):\n    \"\"\"Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/.\"\"\"\n    fusedconv = nn.Conv2d(conv.in_channels,\n                          conv.out_channels,\n                          kernel_size=conv.kernel_size,\n                          stride=conv.stride,\n                          padding=conv.padding,\n                          dilation=conv.dilation,\n                          groups=conv.groups,\n                          bias=True).requires_grad_(False).to(conv.weight.device)\n\n    # Prepare filters\n    w_conv = conv.weight.clone().view(conv.out_channels, -1)\n    w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))\n    fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))\n\n    # Prepare spatial bias\n    b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias\n    b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))\n    fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)\n\n    return fusedconv\n\n\ndef fuse_deconv_and_bn(deconv, bn):\n    \"\"\"Fuse ConvTranspose2d() and BatchNorm2d() layers.\"\"\"\n    fuseddconv = nn.ConvTranspose2d(deconv.in_channels,\n                                    deconv.out_channels,\n                                    kernel_size=deconv.kernel_size,\n                                    stride=deconv.stride,\n                                    padding=deconv.padding,\n                                    output_padding=deconv.output_padding,\n                                    dilation=deconv.dilation,\n                                    groups=deconv.groups,\n                                    bias=True).requires_grad_(False).to(deconv.weight.device)\n\n    # Prepare filters\n    w_deconv = deconv.weight.clone().view(deconv.out_channels, -1)\n    w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))\n    fuseddconv.weight.copy_(torch.mm(w_bn, w_deconv).view(fuseddconv.weight.shape))\n\n    # Prepare spatial bias\n    b_conv = torch.zeros(deconv.weight.size(1), device=deconv.weight.device) if deconv.bias is None else deconv.bias\n    b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))\n    fuseddconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)\n\n    return fuseddconv\n\n\ndef model_info(model, detailed=False, verbose=True, imgsz=640):\n    \"\"\"Model information. imgsz may be int or list, i.e. imgsz=640 or imgsz=[640, 320].\"\"\"\n    if not verbose:\n        return\n    n_p = get_num_params(model)  # number of parameters\n    n_g = get_num_gradients(model)  # number of gradients\n    n_l = len(list(model.modules()))  # number of layers\n    if detailed:\n        LOGGER.info(\n            f\"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}\")\n        for i, (name, p) in enumerate(model.named_parameters()):\n            name = name.replace('module_list.', '')\n            LOGGER.info('%5g %40s %9s %12g %20s %10.3g %10.3g %10s' %\n                        (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std(), p.dtype))\n\n    flops = get_flops(model, imgsz)\n    fused = ' (fused)' if getattr(model, 'is_fused', lambda: False)() else ''\n    fs = f', {flops:.1f} GFLOPs' if flops else ''\n    yaml_file = getattr(model, 'yaml_file', '') or getattr(model, 'yaml', {}).get('yaml_file', '')\n    model_name = Path(yaml_file).stem.replace('yolo', 'YOLO') or 'Model'\n    LOGGER.info(f'{model_name} summary{fused}: {n_l} layers, {n_p} parameters, {n_g} gradients{fs}')\n    return n_l, n_p, n_g, flops\n\n\ndef get_num_params(model):\n    \"\"\"Return the total number of parameters in a YOLO model.\"\"\"\n    return sum(x.numel() for x in model.parameters())\n\n\ndef get_num_gradients(model):\n    \"\"\"Return the total number of parameters with gradients in a YOLO model.\"\"\"\n    return sum(x.numel() for x in model.parameters() if x.requires_grad)\n\n\ndef model_info_for_loggers(trainer):\n    \"\"\"\n    Return model info dict with useful model information.\n\n    Example for YOLOv8n:\n        {'model/parameters': 3151904,\n         'model/GFLOPs': 8.746,\n         'model/speed_ONNX(ms)': 41.244,\n         'model/speed_TensorRT(ms)': 3.211,\n         'model/speed_PyTorch(ms)': 18.755}\n    \"\"\"\n    if trainer.args.profile:  # profile ONNX and TensorRT times\n        from ultralytics.yolo.utils.benchmarks import ProfileModels\n        results = ProfileModels([trainer.last], device=trainer.device).profile()[0]\n        results.pop('model/name')\n    else:  # only return PyTorch times from most recent validation\n        results = {\n            'model/parameters': get_num_params(trainer.model),\n            'model/GFLOPs': round(get_flops(trainer.model), 3)}\n    results['model/speed_PyTorch(ms)'] = round(trainer.validator.speed['inference'], 3)\n    return results\n\n\ndef get_flops(model, imgsz=640):\n    \"\"\"Return a YOLO model's FLOPs.\"\"\"\n    try:\n        model = de_parallel(model)\n        p = next(model.parameters())\n        stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32  # max stride\n        im = torch.empty((1, p.shape[1], stride, stride), device=p.device)  # input image in BCHW format\n        flops = thop.profile(deepcopy(model), inputs=[im], verbose=False)[0] / 1E9 * 2 if thop else 0  # stride GFLOPs\n        imgsz = imgsz if isinstance(imgsz, list) else [imgsz, imgsz]  # expand if int/float\n        return flops * imgsz[0] / stride * imgsz[1] / stride  # 640x640 GFLOPs\n    except Exception:\n        return 0\n\n\ndef get_flops_with_torch_profiler(model, imgsz=640):\n    # Compute model FLOPs (thop alternative)\n    model = de_parallel(model)\n    p = next(model.parameters())\n    stride = (max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32) * 2  # max stride\n    im = torch.zeros((1, p.shape[1], stride, stride), device=p.device)  # input image in BCHW format\n    with torch.profiler.profile(with_flops=True) as prof:\n        model(im)\n    flops = sum(x.flops for x in prof.key_averages()) / 1E9\n    imgsz = imgsz if isinstance(imgsz, list) else [imgsz, imgsz]  # expand if int/float\n    flops = flops * imgsz[0] / stride * imgsz[1] / stride  # 640x640 GFLOPs\n    return flops\n\n\ndef initialize_weights(model):\n    \"\"\"Initialize model weights to random values.\"\"\"\n    for m in model.modules():\n        t = type(m)\n        if t is nn.Conv2d:\n            pass  # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n        elif t is nn.BatchNorm2d:\n            m.eps = 1e-3\n            m.momentum = 0.03\n        elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:\n            m.inplace = True\n\n\ndef scale_img(img, ratio=1.0, same_shape=False, gs=32):  # img(16,3,256,416)\n    # Scales img(bs,3,y,x) by ratio constrained to gs-multiple\n    if ratio == 1.0:\n        return img\n    h, w = img.shape[2:]\n    s = (int(h * ratio), int(w * ratio))  # new size\n    img = F.interpolate(img, size=s, mode='bilinear', align_corners=False)  # resize\n    if not same_shape:  # pad/crop img\n        h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w))\n    return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447)  # value = imagenet mean\n\n\ndef make_divisible(x, divisor):\n    \"\"\"Returns nearest x divisible by divisor.\"\"\"\n    if isinstance(divisor, torch.Tensor):\n        divisor = int(divisor.max())  # to int\n    return math.ceil(x / divisor) * divisor\n\n\ndef copy_attr(a, b, include=(), exclude=()):\n    \"\"\"Copies attributes from object 'b' to object 'a', with options to include/exclude certain attributes.\"\"\"\n    for k, v in b.__dict__.items():\n        if (len(include) and k not in include) or k.startswith('_') or k in exclude:\n            continue\n        else:\n            setattr(a, k, v)\n\n\ndef get_latest_opset():\n    \"\"\"Return second-most (for maturity) recently supported ONNX opset by this version of torch.\"\"\"\n    return max(int(k[14:]) for k in vars(torch.onnx) if 'symbolic_opset' in k) - 1  # opset\n\n\ndef intersect_dicts(da, db, exclude=()):\n    \"\"\"Returns a dictionary of intersecting keys with matching shapes, excluding 'exclude' keys, using da values.\"\"\"\n    return {k: v for k, v in da.items() if k in db and all(x not in k for x in exclude) and v.shape == db[k].shape}\n\n\ndef is_parallel(model):\n    \"\"\"Returns True if model is of type DP or DDP.\"\"\"\n    return isinstance(model, (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel))\n\n\ndef de_parallel(model):\n    \"\"\"De-parallelize a model: returns single-GPU model if model is of type DP or DDP.\"\"\"\n    return model.module if is_parallel(model) else model\n\n\ndef one_cycle(y1=0.0, y2=1.0, steps=100):\n    \"\"\"Returns a lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf.\"\"\"\n    return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1\n\n\ndef init_seeds(seed=0, deterministic=False):\n    \"\"\"Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html.\"\"\"\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)  # for Multi-GPU, exception safe\n    # torch.backends.cudnn.benchmark = True  # AutoBatch problem https://github.com/ultralytics/yolov5/issues/9287\n    if deterministic:  # https://github.com/ultralytics/yolov5/pull/8213\n        if TORCH_2_0:\n            torch.use_deterministic_algorithms(True)\n            torch.backends.cudnn.deterministic = True\n            os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'\n            os.environ['PYTHONHASHSEED'] = str(seed)\n        else:\n            LOGGER.warning('WARNING ⚠️ Upgrade to torch>=2.0.0 for deterministic training.')\n    else:\n        torch.use_deterministic_algorithms(False)\n        torch.backends.cudnn.deterministic = False\n\n\nclass ModelEMA:\n    \"\"\"Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models\n    Keeps a moving average of everything in the model state_dict (parameters and buffers)\n    For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage\n    To disable EMA set the `enabled` attribute to `False`.\n    \"\"\"\n\n    def __init__(self, model, decay=0.9999, tau=2000, updates=0):\n        \"\"\"Create EMA.\"\"\"\n        self.ema = deepcopy(de_parallel(model)).eval()  # FP32 EMA\n        self.updates = updates  # number of EMA updates\n        self.decay = lambda x: decay * (1 - math.exp(-x / tau))  # decay exponential ramp (to help early epochs)\n        for p in self.ema.parameters():\n            p.requires_grad_(False)\n        self.enabled = True\n\n    def update(self, model):\n        \"\"\"Update EMA parameters.\"\"\"\n        if self.enabled:\n            self.updates += 1\n            d = self.decay(self.updates)\n\n            msd = de_parallel(model).state_dict()  # model state_dict\n            for k, v in self.ema.state_dict().items():\n                if v.dtype.is_floating_point:  # true for FP16 and FP32\n                    v *= d\n                    v += (1 - d) * msd[k].detach()\n                    # assert v.dtype == msd[k].dtype == torch.float32, f'{k}: EMA {v.dtype},  model {msd[k].dtype}'\n\n    def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):\n        \"\"\"Updates attributes and saves stripped model with optimizer removed.\"\"\"\n        if self.enabled:\n            copy_attr(self.ema, model, include, exclude)\n\n\ndef strip_optimizer(f: Union[str, Path] = 'best.pt', s: str = '') -> None:\n    \"\"\"\n    Strip optimizer from 'f' to finalize training, optionally save as 's'.\n\n    Args:\n        f (str): file path to model to strip the optimizer from. Default is 'best.pt'.\n        s (str): file path to save the model with stripped optimizer to. If not provided, 'f' will be overwritten.\n\n    Returns:\n        None\n\n    Usage:\n        from pathlib import Path\n        from ultralytics.yolo.utils.torch_utils import strip_optimizer\n        for f in Path('/Users/glennjocher/Downloads/weights').rglob('*.pt'):\n            strip_optimizer(f)\n    \"\"\"\n    # Use dill (if exists) to serialize the lambda functions where pickle does not do this\n    try:\n        import dill as pickle\n    except ImportError:\n        import pickle\n\n    x = torch.load(f, map_location=torch.device('cpu'))\n    args = {**DEFAULT_CFG_DICT, **x['train_args']} if 'train_args' in x else None  # combine args\n    if x.get('ema'):\n        x['model'] = x['ema']  # replace model with ema\n    for k in 'optimizer', 'best_fitness', 'ema', 'updates':  # keys\n        x[k] = None\n    x['epoch'] = -1\n    x['model'].half()  # to FP16\n    for p in x['model'].parameters():\n        p.requires_grad = False\n    x['train_args'] = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS}  # strip non-default keys\n    # x['model'].args = x['train_args']\n    torch.save(x, s or f, pickle_module=pickle)\n    mb = os.path.getsize(s or f) / 1E6  # filesize\n    LOGGER.info(f\"Optimizer stripped from {f},{f' saved as {s},' if s else ''} {mb:.1f}MB\")\n\n\ndef profile(input, ops, n=10, device=None):\n    \"\"\"\n    YOLOv8 speed/memory/FLOPs profiler\n\n    Usage:\n        input = torch.randn(16, 3, 640, 640)\n        m1 = lambda x: x * torch.sigmoid(x)\n        m2 = nn.SiLU()\n        profile(input, [m1, m2], n=100)  # profile over 100 iterations\n    \"\"\"\n    results = []\n    if not isinstance(device, torch.device):\n        device = select_device(device)\n    LOGGER.info(f\"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}\"\n                f\"{'input':>24s}{'output':>24s}\")\n\n    for x in input if isinstance(input, list) else [input]:\n        x = x.to(device)\n        x.requires_grad = True\n        for m in ops if isinstance(ops, list) else [ops]:\n            m = m.to(device) if hasattr(m, 'to') else m  # device\n            m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m\n            tf, tb, t = 0, 0, [0, 0, 0]  # dt forward, backward\n            try:\n                flops = thop.profile(m, inputs=[x], verbose=False)[0] / 1E9 * 2 if thop else 0  # GFLOPs\n            except Exception:\n                flops = 0\n\n            try:\n                for _ in range(n):\n                    t[0] = time_sync()\n                    y = m(x)\n                    t[1] = time_sync()\n                    try:\n                        _ = (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward()\n                        t[2] = time_sync()\n                    except Exception:  # no backward method\n                        # print(e)  # for debug\n                        t[2] = float('nan')\n                    tf += (t[1] - t[0]) * 1000 / n  # ms per op forward\n                    tb += (t[2] - t[1]) * 1000 / n  # ms per op backward\n                mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0  # (GB)\n                s_in, s_out = (tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' for x in (x, y))  # shapes\n                p = sum(x.numel() for x in m.parameters()) if isinstance(m, nn.Module) else 0  # parameters\n                LOGGER.info(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}')\n                results.append([p, flops, mem, tf, tb, s_in, s_out])\n            except Exception as e:\n                LOGGER.info(e)\n                results.append(None)\n            torch.cuda.empty_cache()\n    return results\n\n\nclass EarlyStopping:\n    \"\"\"\n    Early stopping class that stops training when a specified number of epochs have passed without improvement.\n    \"\"\"\n\n    def __init__(self, patience=50):\n        \"\"\"\n        Initialize early stopping object\n\n        Args:\n            patience (int, optional): Number of epochs to wait after fitness stops improving before stopping.\n        \"\"\"\n        self.best_fitness = 0.0  # i.e. mAP\n        self.best_epoch = 0\n        self.patience = patience or float('inf')  # epochs to wait after fitness stops improving to stop\n        self.possible_stop = False  # possible stop may occur next epoch\n\n    def __call__(self, epoch, fitness):\n        \"\"\"\n        Check whether to stop training\n\n        Args:\n            epoch (int): Current epoch of training\n            fitness (float): Fitness value of current epoch\n\n        Returns:\n            (bool): True if training should stop, False otherwise\n        \"\"\"\n        if fitness is None:  # check if fitness=None (happens when val=False)\n            return False\n\n        if fitness >= self.best_fitness:  # >= 0 to allow for early zero-fitness stage of training\n            self.best_epoch = epoch\n            self.best_fitness = fitness\n        delta = epoch - self.best_epoch  # epochs without improvement\n        self.possible_stop = delta >= (self.patience - 1)  # possible stop may occur next epoch\n        stop = delta >= self.patience  # stop training if patience exceeded\n        if stop:\n            LOGGER.info(f'Stopping training early as no improvement observed in last {self.patience} epochs. '\n                        f'Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\\n'\n                        f'To update EarlyStopping(patience={self.patience}) pass a new patience value, '\n                        f'i.e. `patience=300` or use `patience=0` to disable EarlyStopping.')\n        return stop\n"
  },
  {
    "path": "ultralytics/yolo/utils/tuner.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom ultralytics.yolo.utils import LOGGER\n\ntry:\n    from ray import tune\n    from ray.air import RunConfig, session  # noqa\n    from ray.air.integrations.wandb import WandbLoggerCallback  # noqa\n    from ray.tune.schedulers import ASHAScheduler  # noqa\n    from ray.tune.schedulers import AsyncHyperBandScheduler as AHB  # noqa\n\nexcept ImportError:\n    LOGGER.info(\"Tuning hyperparameters requires ray/tune. Install using `pip install 'ray[tune]'`\")\n    tune = None\n\ndefault_space = {\n    # 'optimizer': tune.choice(['SGD', 'Adam', 'AdamW', 'NAdam', 'RAdam', 'RMSProp']),\n    'lr0': tune.uniform(1e-5, 1e-1),\n    'lrf': tune.uniform(0.01, 1.0),  # final OneCycleLR learning rate (lr0 * lrf)\n    'momentum': tune.uniform(0.6, 0.98),  # SGD momentum/Adam beta1\n    'weight_decay': tune.uniform(0.0, 0.001),  # optimizer weight decay 5e-4\n    'warmup_epochs': tune.uniform(0.0, 5.0),  # warmup epochs (fractions ok)\n    'warmup_momentum': tune.uniform(0.0, 0.95),  # warmup initial momentum\n    'box': tune.uniform(0.02, 0.2),  # box loss gain\n    'cls': tune.uniform(0.2, 4.0),  # cls loss gain (scale with pixels)\n    'hsv_h': tune.uniform(0.0, 0.1),  # image HSV-Hue augmentation (fraction)\n    'hsv_s': tune.uniform(0.0, 0.9),  # image HSV-Saturation augmentation (fraction)\n    'hsv_v': tune.uniform(0.0, 0.9),  # image HSV-Value augmentation (fraction)\n    'degrees': tune.uniform(0.0, 45.0),  # image rotation (+/- deg)\n    'translate': tune.uniform(0.0, 0.9),  # image translation (+/- fraction)\n    'scale': tune.uniform(0.0, 0.9),  # image scale (+/- gain)\n    'shear': tune.uniform(0.0, 10.0),  # image shear (+/- deg)\n    'perspective': tune.uniform(0.0, 0.001),  # image perspective (+/- fraction), range 0-0.001\n    'flipud': tune.uniform(0.0, 1.0),  # image flip up-down (probability)\n    'fliplr': tune.uniform(0.0, 1.0),  # image flip left-right (probability)\n    'mosaic': tune.uniform(0.0, 1.0),  # image mixup (probability)\n    'mixup': tune.uniform(0.0, 1.0),  # image mixup (probability)\n    'copy_paste': tune.uniform(0.0, 1.0)}  # segment copy-paste (probability)\n\ntask_metric_map = {\n    'detect': 'metrics/mAP50-95(B)',\n    'segment': 'metrics/mAP50-95(M)',\n    'classify': 'metrics/accuracy_top1',\n    'pose': 'metrics/mAP50-95(P)'}\n"
  },
  {
    "path": "ultralytics/yolo/v8/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom ultralytics.yolo.v8 import classify, detect, pose, segment\n\n__all__ = 'classify', 'segment', 'detect', 'pose'\n"
  },
  {
    "path": "ultralytics/yolo/v8/classify/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom ultralytics.yolo.v8.classify.predict import ClassificationPredictor, predict\nfrom ultralytics.yolo.v8.classify.train import ClassificationTrainer, train\nfrom ultralytics.yolo.v8.classify.val import ClassificationValidator, val\n\n__all__ = 'ClassificationPredictor', 'predict', 'ClassificationTrainer', 'train', 'ClassificationValidator', 'val'\n"
  },
  {
    "path": "ultralytics/yolo/v8/classify/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.engine.predictor import BasePredictor\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import DEFAULT_CFG, ROOT\n\n\nclass ClassificationPredictor(BasePredictor):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        super().__init__(cfg, overrides, _callbacks)\n        self.args.task = 'classify'\n\n    def preprocess(self, img):\n        \"\"\"Converts input image to model-compatible data type.\"\"\"\n        if not isinstance(img, torch.Tensor):\n            img = torch.stack([self.transforms(im) for im in img], dim=0)\n        img = (img if isinstance(img, torch.Tensor) else torch.from_numpy(img)).to(self.model.device)\n        return img.half() if self.model.fp16 else img.float()  # uint8 to fp16/32\n\n    def postprocess(self, preds, img, orig_imgs):\n        \"\"\"Postprocesses predictions to return Results objects.\"\"\"\n        results = []\n        for i, pred in enumerate(preds):\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, probs=pred))\n\n        return results\n\n\ndef predict(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Run YOLO model predictions on input images/videos.\"\"\"\n    model = cfg.model or 'yolov8n-cls.pt'  # or \"resnet18\"\n    source = cfg.source if cfg.source is not None else ROOT / 'assets' if (ROOT / 'assets').exists() \\\n        else 'https://ultralytics.com/images/bus.jpg'\n\n    args = dict(model=model, source=source)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model)(**args)\n    else:\n        predictor = ClassificationPredictor(overrides=args)\n        predictor.predict_cli()\n\n\nif __name__ == '__main__':\n    predict()\n"
  },
  {
    "path": "ultralytics/yolo/v8/classify/train.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\nimport torchvision\n\nfrom ultralytics.nn.tasks import ClassificationModel, attempt_load_one_weight\nfrom ultralytics.yolo import v8\nfrom ultralytics.yolo.data import ClassificationDataset, build_dataloader\nfrom ultralytics.yolo.engine.trainer import BaseTrainer\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, RANK, colorstr\nfrom ultralytics.yolo.utils.plotting import plot_images, plot_results\nfrom ultralytics.yolo.utils.torch_utils import is_parallel, strip_optimizer, torch_distributed_zero_first\n\n\nclass ClassificationTrainer(BaseTrainer):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"Initialize a ClassificationTrainer object with optional configuration overrides and callbacks.\"\"\"\n        if overrides is None:\n            overrides = {}\n        overrides['task'] = 'classify'\n        if overrides.get('imgsz') is None:\n            overrides['imgsz'] = 224\n        super().__init__(cfg, overrides, _callbacks)\n\n    def set_model_attributes(self):\n        \"\"\"Set the YOLO model's class names from the loaded dataset.\"\"\"\n        self.model.names = self.data['names']\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Returns a modified PyTorch model configured for training YOLO.\"\"\"\n        model = ClassificationModel(cfg, nc=self.data['nc'], verbose=verbose and RANK == -1)\n        if weights:\n            model.load(weights)\n\n        for m in model.modules():\n            if not self.args.pretrained and hasattr(m, 'reset_parameters'):\n                m.reset_parameters()\n            if isinstance(m, torch.nn.Dropout) and self.args.dropout:\n                m.p = self.args.dropout  # set dropout\n        for p in model.parameters():\n            p.requires_grad = True  # for training\n        return model\n\n    def setup_model(self):\n        \"\"\"\n        load/create/download model for any task\n        \"\"\"\n        # Classification models require special handling\n\n        if isinstance(self.model, torch.nn.Module):  # if model is loaded beforehand. No setup needed\n            return\n\n        model = str(self.model)\n        # Load a YOLO model locally, from torchvision, or from Ultralytics assets\n        if model.endswith('.pt'):\n            self.model, _ = attempt_load_one_weight(model, device='cpu')\n            for p in self.model.parameters():\n                p.requires_grad = True  # for training\n        elif model.endswith('.yaml'):\n            self.model = self.get_model(cfg=model)\n        elif model in torchvision.models.__dict__:\n            self.model = torchvision.models.__dict__[model](weights='IMAGENET1K_V1' if self.args.pretrained else None)\n        else:\n            FileNotFoundError(f'ERROR: model={model} not found locally or online. Please check model name.')\n        ClassificationModel.reshape_outputs(self.model, self.data['nc'])\n\n        return  # dont return ckpt. Classification doesn't support resume\n\n    def build_dataset(self, img_path, mode='train', batch=None):\n        return ClassificationDataset(root=img_path, args=self.args, augment=mode == 'train')\n\n    def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode='train'):\n        \"\"\"Returns PyTorch DataLoader with transforms to preprocess images for inference.\"\"\"\n        with torch_distributed_zero_first(rank):  # init dataset *.cache only once if DDP\n            dataset = self.build_dataset(dataset_path, mode)\n\n        loader = build_dataloader(dataset, batch_size, self.args.workers, rank=rank)\n        # Attach inference transforms\n        if mode != 'train':\n            if is_parallel(self.model):\n                self.model.module.transforms = loader.dataset.torch_transforms\n            else:\n                self.model.transforms = loader.dataset.torch_transforms\n        return loader\n\n    def preprocess_batch(self, batch):\n        \"\"\"Preprocesses a batch of images and classes.\"\"\"\n        batch['img'] = batch['img'].to(self.device)\n        batch['cls'] = batch['cls'].to(self.device)\n        return batch\n\n    def progress_string(self):\n        \"\"\"Returns a formatted string showing training progress.\"\"\"\n        return ('\\n' + '%11s' * (4 + len(self.loss_names))) % \\\n            ('Epoch', 'GPU_mem', *self.loss_names, 'Instances', 'Size')\n\n    def get_validator(self):\n        \"\"\"Returns an instance of ClassificationValidator for validation.\"\"\"\n        self.loss_names = ['loss']\n        return v8.classify.ClassificationValidator(self.test_loader, self.save_dir)\n\n    def label_loss_items(self, loss_items=None, prefix='train'):\n        \"\"\"\n        Returns a loss dict with labelled training loss items tensor\n        \"\"\"\n        # Not needed for classification but necessary for segmentation & detection\n        keys = [f'{prefix}/{x}' for x in self.loss_names]\n        if loss_items is None:\n            return keys\n        loss_items = [round(float(loss_items), 5)]\n        return dict(zip(keys, loss_items))\n\n    def resume_training(self, ckpt):\n        \"\"\"Resumes training from a given checkpoint.\"\"\"\n        pass\n\n    def plot_metrics(self):\n        \"\"\"Plots metrics from a CSV file.\"\"\"\n        plot_results(file=self.csv, classify=True, on_plot=self.on_plot)  # save results.png\n\n    def final_eval(self):\n        \"\"\"Evaluate trained model and save validation results.\"\"\"\n        for f in self.last, self.best:\n            if f.exists():\n                strip_optimizer(f)  # strip optimizers\n                # TODO: validate best.pt after training completes\n                # if f is self.best:\n                #     LOGGER.info(f'\\nValidating {f}...')\n                #     self.validator.args.save_json = True\n                #     self.metrics = self.validator(model=f)\n                #     self.metrics.pop('fitness', None)\n                #     self.run_callbacks('on_fit_epoch_end')\n        LOGGER.info(f\"Results saved to {colorstr('bold', self.save_dir)}\")\n\n    def plot_training_samples(self, batch, ni):\n        \"\"\"Plots training samples with their annotations.\"\"\"\n        plot_images(images=batch['img'],\n                    batch_idx=torch.arange(len(batch['img'])),\n                    cls=batch['cls'].squeeze(-1),\n                    fname=self.save_dir / f'train_batch{ni}.jpg',\n                    on_plot=self.on_plot)\n\n\ndef train(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Train the YOLO classification model.\"\"\"\n    model = cfg.model or 'yolov8n-cls.pt'  # or \"resnet18\"\n    data = cfg.data or 'mnist160'  # or yolo.ClassificationDataset(\"mnist\")\n    device = cfg.device if cfg.device is not None else ''\n\n    args = dict(model=model, data=data, device=device)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).train(**args)\n    else:\n        trainer = ClassificationTrainer(overrides=args)\n        trainer.train()\n\n\nif __name__ == '__main__':\n    train()\n"
  },
  {
    "path": "ultralytics/yolo/v8/classify/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.data import ClassificationDataset, build_dataloader\nfrom ultralytics.yolo.engine.validator import BaseValidator\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER\nfrom ultralytics.yolo.utils.metrics import ClassifyMetrics, ConfusionMatrix\nfrom ultralytics.yolo.utils.plotting import plot_images\n\n\nclass ClassificationValidator(BaseValidator):\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"Initializes ClassificationValidator instance with args, dataloader, save_dir, and progress bar.\"\"\"\n        super().__init__(dataloader, save_dir, pbar, args, _callbacks)\n        self.args.task = 'classify'\n        self.metrics = ClassifyMetrics()\n\n    def get_desc(self):\n        \"\"\"Returns a formatted string summarizing classification metrics.\"\"\"\n        return ('%22s' + '%11s' * 2) % ('classes', 'top1_acc', 'top5_acc')\n\n    def init_metrics(self, model):\n        \"\"\"Initialize confusion matrix, class names, and top-1 and top-5 accuracy.\"\"\"\n        self.names = model.names\n        self.nc = len(model.names)\n        self.confusion_matrix = ConfusionMatrix(nc=self.nc, task='classify')\n        self.pred = []\n        self.targets = []\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses input batch and returns it.\"\"\"\n        batch['img'] = batch['img'].to(self.device, non_blocking=True)\n        batch['img'] = batch['img'].half() if self.args.half else batch['img'].float()\n        batch['cls'] = batch['cls'].to(self.device)\n        return batch\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Updates running metrics with model predictions and batch targets.\"\"\"\n        n5 = min(len(self.model.names), 5)\n        self.pred.append(preds.argsort(1, descending=True)[:, :n5])\n        self.targets.append(batch['cls'])\n\n    def finalize_metrics(self, *args, **kwargs):\n        \"\"\"Finalizes metrics of the model such as confusion_matrix and speed.\"\"\"\n        self.confusion_matrix.process_cls_preds(self.pred, self.targets)\n        if self.args.plots:\n            for normalize in True, False:\n                self.confusion_matrix.plot(save_dir=self.save_dir,\n                                           names=self.names.values(),\n                                           normalize=normalize,\n                                           on_plot=self.on_plot)\n        self.metrics.speed = self.speed\n        self.metrics.confusion_matrix = self.confusion_matrix\n\n    def get_stats(self):\n        \"\"\"Returns a dictionary of metrics obtained by processing targets and predictions.\"\"\"\n        self.metrics.process(self.targets, self.pred)\n        return self.metrics.results_dict\n\n    def build_dataset(self, img_path):\n        return ClassificationDataset(root=img_path, args=self.args, augment=False)\n\n    def get_dataloader(self, dataset_path, batch_size):\n        \"\"\"Builds and returns a data loader for classification tasks with given parameters.\"\"\"\n        dataset = self.build_dataset(dataset_path)\n        return build_dataloader(dataset, batch_size, self.args.workers, rank=-1)\n\n    def print_results(self):\n        \"\"\"Prints evaluation metrics for YOLO object detection model.\"\"\"\n        pf = '%22s' + '%11.3g' * len(self.metrics.keys)  # print format\n        LOGGER.info(pf % ('all', self.metrics.top1, self.metrics.top5))\n\n    def plot_val_samples(self, batch, ni):\n        \"\"\"Plot validation image samples.\"\"\"\n        plot_images(images=batch['img'],\n                    batch_idx=torch.arange(len(batch['img'])),\n                    cls=batch['cls'].squeeze(-1),\n                    fname=self.save_dir / f'val_batch{ni}_labels.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)\n\n    def plot_predictions(self, batch, preds, ni):\n        \"\"\"Plots predicted bounding boxes on input images and saves the result.\"\"\"\n        plot_images(batch['img'],\n                    batch_idx=torch.arange(len(batch['img'])),\n                    cls=torch.argmax(preds, dim=1),\n                    fname=self.save_dir / f'val_batch{ni}_pred.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)  # pred\n\n\ndef val(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Validate YOLO model using custom data.\"\"\"\n    model = cfg.model or 'yolov8n-cls.pt'  # or \"resnet18\"\n    data = cfg.data or 'mnist160'\n\n    args = dict(model=model, data=data)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).val(**args)\n    else:\n        validator = ClassificationValidator(args=args)\n        validator(model=args['model'])\n\n\nif __name__ == '__main__':\n    val()\n"
  },
  {
    "path": "ultralytics/yolo/v8/detect/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .predict import DetectionPredictor, predict\nfrom .train import DetectionTrainer, train\nfrom .val import DetectionValidator, val\n\n__all__ = 'DetectionPredictor', 'predict', 'DetectionTrainer', 'train', 'DetectionValidator', 'val'\n"
  },
  {
    "path": "ultralytics/yolo/v8/detect/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.engine.predictor import BasePredictor\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import DEFAULT_CFG, ROOT, ops\n\n\nclass DetectionPredictor(BasePredictor):\n\n    def postprocess(self, preds, img, orig_imgs):\n        \"\"\"Postprocesses predictions and returns a list of Results objects.\"\"\"\n        preds = ops.non_max_suppression(preds,\n                                        self.args.conf,\n                                        self.args.iou,\n                                        agnostic=self.args.agnostic_nms,\n                                        max_det=self.args.max_det,\n                                        classes=self.args.classes)\n\n        results = []\n        for i, pred in enumerate(preds):\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            if not isinstance(orig_imgs, torch.Tensor):\n                pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred))\n        return results\n\n\ndef predict(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Runs YOLO model inference on input image(s).\"\"\"\n    model = cfg.model or 'yolov8n.pt'\n    source = cfg.source if cfg.source is not None else ROOT / 'assets' if (ROOT / 'assets').exists() \\\n        else 'https://ultralytics.com/images/bus.jpg'\n\n    args = dict(model=model, source=source)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model)(**args)\n    else:\n        predictor = DetectionPredictor(overrides=args)\n        predictor.predict_cli()\n\n\nif __name__ == '__main__':\n    predict()\n"
  },
  {
    "path": "ultralytics/yolo/v8/detect/train.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nfrom copy import copy\n\nimport numpy as np\n\nfrom ultralytics.nn.tasks import DetectionModel\nfrom ultralytics.yolo import v8\nfrom ultralytics.yolo.data import build_dataloader, build_yolo_dataset\nfrom ultralytics.yolo.data.dataloaders.v5loader import create_dataloader\nfrom ultralytics.yolo.engine.trainer import BaseTrainer\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, RANK, colorstr\nfrom ultralytics.yolo.utils.plotting import plot_images, plot_labels, plot_results\nfrom ultralytics.yolo.utils.torch_utils import de_parallel, torch_distributed_zero_first\n\n\n# BaseTrainer python usage\nclass DetectionTrainer(BaseTrainer):\n\n    def build_dataset(self, img_path, mode='train', batch=None):\n        \"\"\"Build YOLO Dataset\n\n        Args:\n            img_path (str): Path to the folder containing images.\n            mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.\n            batch (int, optional): Size of batches, this is for `rect`. Defaults to None.\n        \"\"\"\n        gs = max(int(de_parallel(self.model).stride.max() if self.model else 0), 32)\n        return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, rect=mode == 'val', stride=gs)\n\n    def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode='train'):\n        \"\"\"TODO: manage splits differently.\"\"\"\n        # Calculate stride - check if model is initialized\n        if self.args.v5loader:\n            LOGGER.warning(\"WARNING ⚠️ 'v5loader' feature is deprecated and will be removed soon. You can train using \"\n                           'the default YOLOv8 dataloader instead, no argument is needed.')\n            gs = max(int(de_parallel(self.model).stride.max() if self.model else 0), 32)\n            return create_dataloader(path=dataset_path,\n                                     imgsz=self.args.imgsz,\n                                     batch_size=batch_size,\n                                     stride=gs,\n                                     hyp=vars(self.args),\n                                     augment=mode == 'train',\n                                     cache=self.args.cache,\n                                     pad=0 if mode == 'train' else 0.5,\n                                     rect=self.args.rect or mode == 'val',\n                                     rank=rank,\n                                     workers=self.args.workers,\n                                     close_mosaic=self.args.close_mosaic != 0,\n                                     prefix=colorstr(f'{mode}: '),\n                                     shuffle=mode == 'train',\n                                     seed=self.args.seed)[0]\n        assert mode in ['train', 'val']\n        with torch_distributed_zero_first(rank):  # init dataset *.cache only once if DDP\n            dataset = self.build_dataset(dataset_path, mode, batch_size)\n        shuffle = mode == 'train'\n        if getattr(dataset, 'rect', False) and shuffle:\n            LOGGER.warning(\"WARNING ⚠️ 'rect=True' is incompatible with DataLoader shuffle, setting shuffle=False\")\n            shuffle = False\n        workers = self.args.workers if mode == 'train' else self.args.workers * 2\n        return build_dataloader(dataset, batch_size, workers, shuffle, rank)  # return dataloader\n\n    def preprocess_batch(self, batch):\n        \"\"\"Preprocesses a batch of images by scaling and converting to float.\"\"\"\n        batch['img'] = batch['img'].to(self.device, non_blocking=True).float() / 255\n        return batch\n\n    def set_model_attributes(self):\n        \"\"\"nl = de_parallel(self.model).model[-1].nl  # number of detection layers (to scale hyps).\"\"\"\n        # self.args.box *= 3 / nl  # scale to layers\n        # self.args.cls *= self.data[\"nc\"] / 80 * 3 / nl  # scale to classes and layers\n        # self.args.cls *= (self.args.imgsz / 640) ** 2 * 3 / nl  # scale to image size and layers\n        self.model.nc = self.data['nc']  # attach number of classes to model\n        self.model.names = self.data['names']  # attach class names to model\n        self.model.args = self.args  # attach hyperparameters to model\n        # TODO: self.model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Return a YOLO detection model.\"\"\"\n        model = DetectionModel(cfg, nc=self.data['nc'], verbose=verbose and RANK == -1)\n        if weights:\n            model.load(weights)\n        return model\n\n    def get_validator(self):\n        \"\"\"Returns a DetectionValidator for YOLO model validation.\"\"\"\n        self.loss_names = 'box_loss', 'cls_loss', 'dfl_loss'\n        return v8.detect.DetectionValidator(self.test_loader, save_dir=self.save_dir, args=copy(self.args))\n\n    def label_loss_items(self, loss_items=None, prefix='train'):\n        \"\"\"\n        Returns a loss dict with labelled training loss items tensor\n        \"\"\"\n        # Not needed for classification but necessary for segmentation & detection\n        keys = [f'{prefix}/{x}' for x in self.loss_names]\n        if loss_items is not None:\n            loss_items = [round(float(x), 5) for x in loss_items]  # convert tensors to 5 decimal place floats\n            return dict(zip(keys, loss_items))\n        else:\n            return keys\n\n    def progress_string(self):\n        \"\"\"Returns a formatted string of training progress with epoch, GPU memory, loss, instances and size.\"\"\"\n        return ('\\n' + '%11s' *\n                (4 + len(self.loss_names))) % ('Epoch', 'GPU_mem', *self.loss_names, 'Instances', 'Size')\n\n    def plot_training_samples(self, batch, ni):\n        \"\"\"Plots training samples with their annotations.\"\"\"\n        plot_images(images=batch['img'],\n                    batch_idx=batch['batch_idx'],\n                    cls=batch['cls'].squeeze(-1),\n                    bboxes=batch['bboxes'],\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'train_batch{ni}.jpg',\n                    on_plot=self.on_plot)\n\n    def plot_metrics(self):\n        \"\"\"Plots metrics from a CSV file.\"\"\"\n        plot_results(file=self.csv, on_plot=self.on_plot)  # save results.png\n\n    def plot_training_labels(self):\n        \"\"\"Create a labeled training plot of the YOLO model.\"\"\"\n        boxes = np.concatenate([lb['bboxes'] for lb in self.train_loader.dataset.labels], 0)\n        cls = np.concatenate([lb['cls'] for lb in self.train_loader.dataset.labels], 0)\n        plot_labels(boxes, cls.squeeze(), names=self.data['names'], save_dir=self.save_dir, on_plot=self.on_plot)\n\n\ndef train(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Train and optimize YOLO model given training data and device.\"\"\"\n    model = cfg.model or 'yolov8n.pt'\n    data = cfg.data or 'coco128.yaml'  # or yolo.ClassificationDataset(\"mnist\")\n    device = cfg.device if cfg.device is not None else ''\n\n    args = dict(model=model, data=data, device=device)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).train(**args)\n    else:\n        trainer = DetectionTrainer(overrides=args)\n        trainer.train()\n\n\nif __name__ == '__main__':\n    train()\n"
  },
  {
    "path": "ultralytics/yolo/v8/detect/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\n\nfrom ultralytics.yolo.data import build_dataloader, build_yolo_dataset\nfrom ultralytics.yolo.data.dataloaders.v5loader import create_dataloader\nfrom ultralytics.yolo.engine.validator import BaseValidator\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, colorstr, ops\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.metrics import ConfusionMatrix, DetMetrics, box_iou\nfrom ultralytics.yolo.utils.plotting import output_to_target, plot_images\nfrom ultralytics.yolo.utils.torch_utils import de_parallel\n\n\nclass DetectionValidator(BaseValidator):\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"Initialize detection model with necessary variables and settings.\"\"\"\n        super().__init__(dataloader, save_dir, pbar, args, _callbacks)\n        self.args.task = 'detect'\n        self.is_coco = False\n        self.class_map = None\n        self.metrics = DetMetrics(save_dir=self.save_dir, on_plot=self.on_plot)\n        self.iouv = torch.linspace(0.5, 0.95, 10)  # iou vector for mAP@0.5:0.95\n        self.niou = self.iouv.numel()\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses batch of images for YOLO training.\"\"\"\n        batch['img'] = batch['img'].to(self.device, non_blocking=True)\n        batch['img'] = (batch['img'].half() if self.args.half else batch['img'].float()) / 255\n        for k in ['batch_idx', 'cls', 'bboxes']:\n            batch[k] = batch[k].to(self.device)\n\n        nb = len(batch['img'])\n        self.lb = [torch.cat([batch['cls'], batch['bboxes']], dim=-1)[batch['batch_idx'] == i]\n                   for i in range(nb)] if self.args.save_hybrid else []  # for autolabelling\n\n        return batch\n\n    def init_metrics(self, model):\n        \"\"\"Initialize evaluation metrics for YOLO.\"\"\"\n        val = self.data.get(self.args.split, '')  # validation path\n        self.is_coco = isinstance(val, str) and 'coco' in val and val.endswith(f'{os.sep}val2017.txt')  # is COCO\n        self.class_map = ops.coco80_to_coco91_class() if self.is_coco else list(range(1000))\n        self.args.save_json |= self.is_coco and not self.training  # run on final val if training COCO\n        self.names = model.names\n        self.nc = len(model.names)\n        self.metrics.names = self.names\n        self.metrics.plot = self.args.plots\n        self.confusion_matrix = ConfusionMatrix(nc=self.nc)\n        self.seen = 0\n        self.jdict = []\n        self.stats = []\n\n    def get_desc(self):\n        \"\"\"Return a formatted string summarizing class metrics of YOLO model.\"\"\"\n        return ('%22s' + '%11s' * 6) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)')\n\n    def postprocess(self, preds):\n        \"\"\"Apply Non-maximum suppression to prediction outputs.\"\"\"\n        return ops.non_max_suppression(preds,\n                                       self.args.conf,\n                                       self.args.iou,\n                                       labels=self.lb,\n                                       multi_label=True,\n                                       agnostic=self.args.single_cls,\n                                       max_det=self.args.max_det)\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Metrics.\"\"\"\n        for si, pred in enumerate(preds):\n            idx = batch['batch_idx'] == si\n            cls = batch['cls'][idx]\n            bbox = batch['bboxes'][idx]\n            nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n            shape = batch['ori_shape'][si]\n            correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            self.seen += 1\n\n            if npr == 0:\n                if nl:\n                    self.stats.append((correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))\n                    if self.args.plots:\n                        self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))\n                continue\n\n            # Predictions\n            if self.args.single_cls:\n                pred[:, 5] = 0\n            predn = pred.clone()\n            ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,\n                            ratio_pad=batch['ratio_pad'][si])  # native-space pred\n\n            # Evaluate\n            if nl:\n                height, width = batch['img'].shape[2:]\n                tbox = ops.xywh2xyxy(bbox) * torch.tensor(\n                    (width, height, width, height), device=self.device)  # target boxes\n                ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,\n                                ratio_pad=batch['ratio_pad'][si])  # native-space labels\n                labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                correct_bboxes = self._process_batch(predn, labelsn)\n                # TODO: maybe remove these `self.` arguments as they already are member variable\n                if self.args.plots:\n                    self.confusion_matrix.process_batch(predn, labelsn)\n            self.stats.append((correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1)))  # (conf, pcls, tcls)\n\n            # Save\n            if self.args.save_json:\n                self.pred_to_json(predn, batch['im_file'][si])\n            if self.args.save_txt:\n                file = self.save_dir / 'labels' / f'{Path(batch[\"im_file\"][si]).stem}.txt'\n                self.save_one_txt(predn, self.args.save_conf, shape, file)\n\n    def finalize_metrics(self, *args, **kwargs):\n        \"\"\"Set final values for metrics speed and confusion matrix.\"\"\"\n        self.metrics.speed = self.speed\n        self.metrics.confusion_matrix = self.confusion_matrix\n\n    def get_stats(self):\n        \"\"\"Returns metrics statistics and results dictionary.\"\"\"\n        stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*self.stats)]  # to numpy\n        if len(stats) and stats[0].any():\n            self.metrics.process(*stats)\n        self.nt_per_class = np.bincount(stats[-1].astype(int), minlength=self.nc)  # number of targets per class\n        return self.metrics.results_dict\n\n    def print_results(self):\n        \"\"\"Prints training/validation set metrics per class.\"\"\"\n        pf = '%22s' + '%11i' * 2 + '%11.3g' * len(self.metrics.keys)  # print format\n        LOGGER.info(pf % ('all', self.seen, self.nt_per_class.sum(), *self.metrics.mean_results()))\n        if self.nt_per_class.sum() == 0:\n            LOGGER.warning(\n                f'WARNING ⚠️ no labels found in {self.args.task} set, can not compute metrics without labels')\n\n        # Print results per class\n        if self.args.verbose and not self.training and self.nc > 1 and len(self.stats):\n            for i, c in enumerate(self.metrics.ap_class_index):\n                LOGGER.info(pf % (self.names[c], self.seen, self.nt_per_class[c], *self.metrics.class_result(i)))\n\n        if self.args.plots:\n            for normalize in True, False:\n                self.confusion_matrix.plot(save_dir=self.save_dir,\n                                           names=self.names.values(),\n                                           normalize=normalize,\n                                           on_plot=self.on_plot)\n\n    def _process_batch(self, detections, labels):\n        \"\"\"\n        Return correct prediction matrix\n        Arguments:\n            detections (array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (array[M, 5]), class, x1, y1, x2, y2\n        Returns:\n            correct (array[N, 10]), for 10 IoU levels\n        \"\"\"\n        iou = box_iou(labels[:, 1:], detections[:, :4])\n        correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool)\n        correct_class = labels[:, 0:1] == detections[:, 5]\n        for i in range(len(self.iouv)):\n            x = torch.where((iou >= self.iouv[i]) & correct_class)  # IoU > threshold and classes match\n            if x[0].shape[0]:\n                matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]),\n                                    1).cpu().numpy()  # [label, detect, iou]\n                if x[0].shape[0] > 1:\n                    matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                    # matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n                correct[matches[:, 1].astype(int), i] = True\n        return torch.tensor(correct, dtype=torch.bool, device=detections.device)\n\n    def build_dataset(self, img_path, mode='val', batch=None):\n        \"\"\"Build YOLO Dataset\n\n        Args:\n            img_path (str): Path to the folder containing images.\n            mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.\n            batch (int, optional): Size of batches, this is for `rect`. Defaults to None.\n        \"\"\"\n        gs = max(int(de_parallel(self.model).stride if self.model else 0), 32)\n        return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, stride=gs)\n\n    def get_dataloader(self, dataset_path, batch_size):\n        \"\"\"TODO: manage splits differently.\"\"\"\n        # Calculate stride - check if model is initialized\n        if self.args.v5loader:\n            LOGGER.warning(\"WARNING ⚠️ 'v5loader' feature is deprecated and will be removed soon. You can train using \"\n                           'the default YOLOv8 dataloader instead, no argument is needed.')\n            gs = max(int(de_parallel(self.model).stride if self.model else 0), 32)\n            return create_dataloader(path=dataset_path,\n                                     imgsz=self.args.imgsz,\n                                     batch_size=batch_size,\n                                     stride=gs,\n                                     hyp=vars(self.args),\n                                     cache=False,\n                                     pad=0.5,\n                                     rect=self.args.rect,\n                                     workers=self.args.workers,\n                                     prefix=colorstr(f'{self.args.mode}: '),\n                                     shuffle=False,\n                                     seed=self.args.seed)[0]\n\n        dataset = self.build_dataset(dataset_path, batch=batch_size, mode='val')\n        dataloader = build_dataloader(dataset, batch_size, self.args.workers, shuffle=False, rank=-1)\n        return dataloader\n\n    def plot_val_samples(self, batch, ni):\n        \"\"\"Plot validation image samples.\"\"\"\n        plot_images(batch['img'],\n                    batch['batch_idx'],\n                    batch['cls'].squeeze(-1),\n                    batch['bboxes'],\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'val_batch{ni}_labels.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)\n\n    def plot_predictions(self, batch, preds, ni):\n        \"\"\"Plots predicted bounding boxes on input images and saves the result.\"\"\"\n        plot_images(batch['img'],\n                    *output_to_target(preds, max_det=self.args.max_det),\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'val_batch{ni}_pred.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)  # pred\n\n    def save_one_txt(self, predn, save_conf, shape, file):\n        \"\"\"Save YOLO detections to a txt file in normalized coordinates in a specific format.\"\"\"\n        gn = torch.tensor(shape)[[1, 0, 1, 0]]  # normalization gain whwh\n        for *xyxy, conf, cls in predn.tolist():\n            xywh = (ops.xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh\n            line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format\n            with open(file, 'a') as f:\n                f.write(('%g ' * len(line)).rstrip() % line + '\\n')\n\n    def pred_to_json(self, predn, filename):\n        \"\"\"Serialize YOLO predictions to COCO json format.\"\"\"\n        stem = Path(filename).stem\n        image_id = int(stem) if stem.isnumeric() else stem\n        box = ops.xyxy2xywh(predn[:, :4])  # xywh\n        box[:, :2] -= box[:, 2:] / 2  # xy center to top-left corner\n        for p, b in zip(predn.tolist(), box.tolist()):\n            self.jdict.append({\n                'image_id': image_id,\n                'category_id': self.class_map[int(p[5])],\n                'bbox': [round(x, 3) for x in b],\n                'score': round(p[4], 5)})\n\n    def eval_json(self, stats):\n        \"\"\"Evaluates YOLO output in JSON format and returns performance statistics.\"\"\"\n        if self.args.save_json and self.is_coco and len(self.jdict):\n            anno_json = self.data['path'] / 'annotations/instances_val2017.json'  # annotations\n            pred_json = self.save_dir / 'predictions.json'  # predictions\n            LOGGER.info(f'\\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')\n            try:  # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n                check_requirements('pycocotools>=2.0.6')\n                from pycocotools.coco import COCO  # noqa\n                from pycocotools.cocoeval import COCOeval  # noqa\n\n                for x in anno_json, pred_json:\n                    assert x.is_file(), f'{x} file not found'\n                anno = COCO(str(anno_json))  # init annotations api\n                pred = anno.loadRes(str(pred_json))  # init predictions api (must pass string, not Path)\n                eval = COCOeval(anno, pred, 'bbox')\n                if self.is_coco:\n                    eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files]  # images to eval\n                eval.evaluate()\n                eval.accumulate()\n                eval.summarize()\n                stats[self.metrics.keys[-1]], stats[self.metrics.keys[-2]] = eval.stats[:2]  # update mAP50-95 and mAP50\n            except Exception as e:\n                LOGGER.warning(f'pycocotools unable to run: {e}')\n        return stats\n\n\ndef val(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Validate trained YOLO model on validation dataset.\"\"\"\n    model = cfg.model or 'yolov8n.pt'\n    data = cfg.data or 'coco128.yaml'\n\n    args = dict(model=model, data=data)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).val(**args)\n    else:\n        validator = DetectionValidator(args=args)\n        validator(model=args['model'])\n\n\nif __name__ == '__main__':\n    val()\n"
  },
  {
    "path": "ultralytics/yolo/v8/pose/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .predict import PosePredictor, predict\nfrom .train import PoseTrainer, train\nfrom .val import PoseValidator, val\n\n__all__ = 'PoseTrainer', 'train', 'PoseValidator', 'val', 'PosePredictor', 'predict'\n"
  },
  {
    "path": "ultralytics/yolo/v8/pose/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import DEFAULT_CFG, ROOT, ops\nfrom ultralytics.yolo.v8.detect.predict import DetectionPredictor\n\n\nclass PosePredictor(DetectionPredictor):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        super().__init__(cfg, overrides, _callbacks)\n        self.args.task = 'pose'\n\n    def postprocess(self, preds, img, orig_imgs):\n        \"\"\"Return detection results for a given input image or list of images.\"\"\"\n        preds = ops.non_max_suppression(preds,\n                                        self.args.conf,\n                                        self.args.iou,\n                                        agnostic=self.args.agnostic_nms,\n                                        max_det=self.args.max_det,\n                                        classes=self.args.classes,\n                                        nc=len(self.model.names))\n\n        results = []\n        for i, pred in enumerate(preds):\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            shape = orig_img.shape\n            pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], shape).round()\n            pred_kpts = pred[:, 6:].view(len(pred), *self.model.kpt_shape) if len(pred) else pred[:, 6:]\n            pred_kpts = ops.scale_coords(img.shape[2:], pred_kpts, shape)\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(\n                Results(orig_img=orig_img,\n                        path=img_path,\n                        names=self.model.names,\n                        boxes=pred[:, :6],\n                        keypoints=pred_kpts))\n        return results\n\n\ndef predict(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Runs YOLO to predict objects in an image or video.\"\"\"\n    model = cfg.model or 'yolov8n-pose.pt'\n    source = cfg.source if cfg.source is not None else ROOT / 'assets' if (ROOT / 'assets').exists() \\\n        else 'https://ultralytics.com/images/bus.jpg'\n\n    args = dict(model=model, source=source)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model)(**args)\n    else:\n        predictor = PosePredictor(overrides=args)\n        predictor.predict_cli()\n\n\nif __name__ == '__main__':\n    predict()\n"
  },
  {
    "path": "ultralytics/yolo/v8/pose/train.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom copy import copy\n\nfrom ultralytics.nn.tasks import PoseModel\nfrom ultralytics.yolo import v8\nfrom ultralytics.yolo.utils import DEFAULT_CFG\nfrom ultralytics.yolo.utils.plotting import plot_images, plot_results\n\n\n# BaseTrainer python usage\nclass PoseTrainer(v8.detect.DetectionTrainer):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"Initialize a PoseTrainer object with specified configurations and overrides.\"\"\"\n        if overrides is None:\n            overrides = {}\n        overrides['task'] = 'pose'\n        super().__init__(cfg, overrides, _callbacks)\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Get pose estimation model with specified configuration and weights.\"\"\"\n        model = PoseModel(cfg, ch=3, nc=self.data['nc'], data_kpt_shape=self.data['kpt_shape'], verbose=verbose)\n        if weights:\n            model.load(weights)\n\n        return model\n\n    def set_model_attributes(self):\n        \"\"\"Sets keypoints shape attribute of PoseModel.\"\"\"\n        super().set_model_attributes()\n        self.model.kpt_shape = self.data['kpt_shape']\n\n    def get_validator(self):\n        \"\"\"Returns an instance of the PoseValidator class for validation.\"\"\"\n        self.loss_names = 'box_loss', 'pose_loss', 'kobj_loss', 'cls_loss', 'dfl_loss'\n        return v8.pose.PoseValidator(self.test_loader, save_dir=self.save_dir, args=copy(self.args))\n\n    def plot_training_samples(self, batch, ni):\n        \"\"\"Plot a batch of training samples with annotated class labels, bounding boxes, and keypoints.\"\"\"\n        images = batch['img']\n        kpts = batch['keypoints']\n        cls = batch['cls'].squeeze(-1)\n        bboxes = batch['bboxes']\n        paths = batch['im_file']\n        batch_idx = batch['batch_idx']\n        plot_images(images,\n                    batch_idx,\n                    cls,\n                    bboxes,\n                    kpts=kpts,\n                    paths=paths,\n                    fname=self.save_dir / f'train_batch{ni}.jpg',\n                    on_plot=self.on_plot)\n\n    def plot_metrics(self):\n        \"\"\"Plots training/val metrics.\"\"\"\n        plot_results(file=self.csv, pose=True, on_plot=self.on_plot)  # save results.png\n\n\ndef train(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Train the YOLO model on the given data and device.\"\"\"\n    model = cfg.model or 'yolov8n-pose.yaml'\n    data = cfg.data or 'coco8-pose.yaml'\n    device = cfg.device if cfg.device is not None else ''\n\n    args = dict(model=model, data=data, device=device)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).train(**args)\n    else:\n        trainer = PoseTrainer(overrides=args)\n        trainer.train()\n\n\nif __name__ == '__main__':\n    train()\n"
  },
  {
    "path": "ultralytics/yolo/v8/pose/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\n\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, ops\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.metrics import OKS_SIGMA, PoseMetrics, box_iou, kpt_iou\nfrom ultralytics.yolo.utils.plotting import output_to_target, plot_images\nfrom ultralytics.yolo.v8.detect import DetectionValidator\n\n\nclass PoseValidator(DetectionValidator):\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"Initialize a 'PoseValidator' object with custom parameters and assigned attributes.\"\"\"\n        super().__init__(dataloader, save_dir, pbar, args, _callbacks)\n        self.args.task = 'pose'\n        self.metrics = PoseMetrics(save_dir=self.save_dir, on_plot=self.on_plot)\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses the batch by converting the 'keypoints' data into a float and moving it to the device.\"\"\"\n        batch = super().preprocess(batch)\n        batch['keypoints'] = batch['keypoints'].to(self.device).float()\n        return batch\n\n    def get_desc(self):\n        \"\"\"Returns description of evaluation metrics in string format.\"\"\"\n        return ('%22s' + '%11s' * 10) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)', 'Pose(P',\n                                         'R', 'mAP50', 'mAP50-95)')\n\n    def postprocess(self, preds):\n        \"\"\"Apply non-maximum suppression and return detections with high confidence scores.\"\"\"\n        return ops.non_max_suppression(preds,\n                                       self.args.conf,\n                                       self.args.iou,\n                                       labels=self.lb,\n                                       multi_label=True,\n                                       agnostic=self.args.single_cls,\n                                       max_det=self.args.max_det,\n                                       nc=self.nc)\n\n    def init_metrics(self, model):\n        \"\"\"Initiate pose estimation metrics for YOLO model.\"\"\"\n        super().init_metrics(model)\n        self.kpt_shape = self.data['kpt_shape']\n        is_pose = self.kpt_shape == [17, 3]\n        nkpt = self.kpt_shape[0]\n        self.sigma = OKS_SIGMA if is_pose else np.ones(nkpt) / nkpt\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Metrics.\"\"\"\n        for si, pred in enumerate(preds):\n            idx = batch['batch_idx'] == si\n            cls = batch['cls'][idx]\n            bbox = batch['bboxes'][idx]\n            kpts = batch['keypoints'][idx]\n            nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n            nk = kpts.shape[1]  # number of keypoints\n            shape = batch['ori_shape'][si]\n            correct_kpts = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            self.seen += 1\n\n            if npr == 0:\n                if nl:\n                    self.stats.append((correct_bboxes, correct_kpts, *torch.zeros(\n                        (2, 0), device=self.device), cls.squeeze(-1)))\n                    if self.args.plots:\n                        self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))\n                continue\n\n            # Predictions\n            if self.args.single_cls:\n                pred[:, 5] = 0\n            predn = pred.clone()\n            ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,\n                            ratio_pad=batch['ratio_pad'][si])  # native-space pred\n            pred_kpts = predn[:, 6:].view(npr, nk, -1)\n            ops.scale_coords(batch['img'][si].shape[1:], pred_kpts, shape, ratio_pad=batch['ratio_pad'][si])\n\n            # Evaluate\n            if nl:\n                height, width = batch['img'].shape[2:]\n                tbox = ops.xywh2xyxy(bbox) * torch.tensor(\n                    (width, height, width, height), device=self.device)  # target boxes\n                ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,\n                                ratio_pad=batch['ratio_pad'][si])  # native-space labels\n                tkpts = kpts.clone()\n                tkpts[..., 0] *= width\n                tkpts[..., 1] *= height\n                tkpts = ops.scale_coords(batch['img'][si].shape[1:], tkpts, shape, ratio_pad=batch['ratio_pad'][si])\n                labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                correct_bboxes = self._process_batch(predn[:, :6], labelsn)\n                correct_kpts = self._process_batch(predn[:, :6], labelsn, pred_kpts, tkpts)\n                if self.args.plots:\n                    self.confusion_matrix.process_batch(predn, labelsn)\n\n            # Append correct_masks, correct_boxes, pconf, pcls, tcls\n            self.stats.append((correct_bboxes, correct_kpts, pred[:, 4], pred[:, 5], cls.squeeze(-1)))\n\n            # Save\n            if self.args.save_json:\n                self.pred_to_json(predn, batch['im_file'][si])\n            # if self.args.save_txt:\n            #    save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / f'{path.stem}.txt')\n\n    def _process_batch(self, detections, labels, pred_kpts=None, gt_kpts=None):\n        \"\"\"\n        Return correct prediction matrix\n        Arguments:\n            detections (array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (array[M, 5]), class, x1, y1, x2, y2\n            pred_kpts (array[N, 51]), 51 = 17 * 3\n            gt_kpts (array[N, 51])\n        Returns:\n            correct (array[N, 10]), for 10 IoU levels\n        \"\"\"\n        if pred_kpts is not None and gt_kpts is not None:\n            # `0.53` is from https://github.com/jin-s13/xtcocoapi/blob/master/xtcocotools/cocoeval.py#L384\n            area = ops.xyxy2xywh(labels[:, 1:])[:, 2:].prod(1) * 0.53\n            iou = kpt_iou(gt_kpts, pred_kpts, sigma=self.sigma, area=area)\n        else:  # boxes\n            iou = box_iou(labels[:, 1:], detections[:, :4])\n\n        correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool)\n        correct_class = labels[:, 0:1] == detections[:, 5]\n        for i in range(len(self.iouv)):\n            x = torch.where((iou >= self.iouv[i]) & correct_class)  # IoU > threshold and classes match\n            if x[0].shape[0]:\n                matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]),\n                                    1).cpu().numpy()  # [label, detect, iou]\n                if x[0].shape[0] > 1:\n                    matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                    # matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n                correct[matches[:, 1].astype(int), i] = True\n        return torch.tensor(correct, dtype=torch.bool, device=detections.device)\n\n    def plot_val_samples(self, batch, ni):\n        \"\"\"Plots and saves validation set samples with predicted bounding boxes and keypoints.\"\"\"\n        plot_images(batch['img'],\n                    batch['batch_idx'],\n                    batch['cls'].squeeze(-1),\n                    batch['bboxes'],\n                    kpts=batch['keypoints'],\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'val_batch{ni}_labels.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)\n\n    def plot_predictions(self, batch, preds, ni):\n        \"\"\"Plots predictions for YOLO model.\"\"\"\n        pred_kpts = torch.cat([p[:, 6:].view(-1, *self.kpt_shape) for p in preds], 0)\n        plot_images(batch['img'],\n                    *output_to_target(preds, max_det=self.args.max_det),\n                    kpts=pred_kpts,\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'val_batch{ni}_pred.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)  # pred\n\n    def pred_to_json(self, predn, filename):\n        \"\"\"Converts YOLO predictions to COCO JSON format.\"\"\"\n        stem = Path(filename).stem\n        image_id = int(stem) if stem.isnumeric() else stem\n        box = ops.xyxy2xywh(predn[:, :4])  # xywh\n        box[:, :2] -= box[:, 2:] / 2  # xy center to top-left corner\n        for p, b in zip(predn.tolist(), box.tolist()):\n            self.jdict.append({\n                'image_id': image_id,\n                'category_id': self.class_map[int(p[5])],\n                'bbox': [round(x, 3) for x in b],\n                'keypoints': p[6:],\n                'score': round(p[4], 5)})\n\n    def eval_json(self, stats):\n        \"\"\"Evaluates object detection model using COCO JSON format.\"\"\"\n        if self.args.save_json and self.is_coco and len(self.jdict):\n            anno_json = self.data['path'] / 'annotations/person_keypoints_val2017.json'  # annotations\n            pred_json = self.save_dir / 'predictions.json'  # predictions\n            LOGGER.info(f'\\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')\n            try:  # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n                check_requirements('pycocotools>=2.0.6')\n                from pycocotools.coco import COCO  # noqa\n                from pycocotools.cocoeval import COCOeval  # noqa\n\n                for x in anno_json, pred_json:\n                    assert x.is_file(), f'{x} file not found'\n                anno = COCO(str(anno_json))  # init annotations api\n                pred = anno.loadRes(str(pred_json))  # init predictions api (must pass string, not Path)\n                for i, eval in enumerate([COCOeval(anno, pred, 'bbox'), COCOeval(anno, pred, 'keypoints')]):\n                    if self.is_coco:\n                        eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files]  # im to eval\n                    eval.evaluate()\n                    eval.accumulate()\n                    eval.summarize()\n                    idx = i * 4 + 2\n                    stats[self.metrics.keys[idx + 1]], stats[\n                        self.metrics.keys[idx]] = eval.stats[:2]  # update mAP50-95 and mAP50\n            except Exception as e:\n                LOGGER.warning(f'pycocotools unable to run: {e}')\n        return stats\n\n\ndef val(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Performs validation on YOLO model using given data.\"\"\"\n    model = cfg.model or 'yolov8n-pose.pt'\n    data = cfg.data or 'coco8-pose.yaml'\n\n    args = dict(model=model, data=data)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).val(**args)\n    else:\n        validator = PoseValidator(args=args)\n        validator(model=args['model'])\n\n\nif __name__ == '__main__':\n    val()\n"
  },
  {
    "path": "ultralytics/yolo/v8/segment/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .predict import SegmentationPredictor, predict\nfrom .train import SegmentationTrainer, train\nfrom .val import SegmentationValidator, val\n\n__all__ = 'SegmentationPredictor', 'predict', 'SegmentationTrainer', 'train', 'SegmentationValidator', 'val'\n"
  },
  {
    "path": "ultralytics/yolo/v8/segment/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import DEFAULT_CFG, ROOT, ops\nfrom ultralytics.yolo.v8.detect.predict import DetectionPredictor\n\n\nclass SegmentationPredictor(DetectionPredictor):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        super().__init__(cfg, overrides, _callbacks)\n        self.args.task = 'segment'\n\n    def postprocess(self, preds, img, orig_imgs):\n        \"\"\"TODO: filter by classes.\"\"\"\n        p = ops.non_max_suppression(preds[0],\n                                    self.args.conf,\n                                    self.args.iou,\n                                    agnostic=self.args.agnostic_nms,\n                                    max_det=self.args.max_det,\n                                    nc=len(self.model.names),\n                                    classes=self.args.classes)\n        results = []\n        proto = preds[1][-1] if len(preds[1]) == 3 else preds[1]  # second output is len 3 if pt, but only 1 if exported\n        for i, pred in enumerate(p):\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            if not len(pred):  # save empty boxes\n                results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6]))\n                continue\n            if self.args.retina_masks:\n                if not isinstance(orig_imgs, torch.Tensor):\n                    pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)\n                masks = ops.process_mask_native(proto[i], pred[:, 6:], pred[:, :4], orig_img.shape[:2])  # HWC\n            else:\n                masks = ops.process_mask(proto[i], pred[:, 6:], pred[:, :4], img.shape[2:], upsample=True)  # HWC\n                if not isinstance(orig_imgs, torch.Tensor):\n                    pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)\n            results.append(\n                Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6], masks=masks))\n        return results\n\n\ndef predict(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Runs YOLO object detection on an image or video source.\"\"\"\n    model = cfg.model or 'yolov8n-seg.pt'\n    source = cfg.source if cfg.source is not None else ROOT / 'assets' if (ROOT / 'assets').exists() \\\n        else 'https://ultralytics.com/images/bus.jpg'\n\n    args = dict(model=model, source=source)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model)(**args)\n    else:\n        predictor = SegmentationPredictor(overrides=args)\n        predictor.predict_cli()\n\n\nif __name__ == '__main__':\n    predict()\n"
  },
  {
    "path": "ultralytics/yolo/v8/segment/train.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nfrom copy import copy\n\nfrom ultralytics.nn.tasks import SegmentationModel\nfrom ultralytics.yolo import v8\nfrom ultralytics.yolo.utils import DEFAULT_CFG, RANK\nfrom ultralytics.yolo.utils.plotting import plot_images, plot_results\n\n\n# BaseTrainer python usage\nclass SegmentationTrainer(v8.detect.DetectionTrainer):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"Initialize a SegmentationTrainer object with given arguments.\"\"\"\n        if overrides is None:\n            overrides = {}\n        overrides['task'] = 'segment'\n        super().__init__(cfg, overrides, _callbacks)\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Return SegmentationModel initialized with specified config and weights.\"\"\"\n        model = SegmentationModel(cfg, ch=3, nc=self.data['nc'], verbose=verbose and RANK == -1)\n        if weights:\n            model.load(weights)\n\n        return model\n\n    def get_validator(self):\n        \"\"\"Return an instance of SegmentationValidator for validation of YOLO model.\"\"\"\n        self.loss_names = 'box_loss', 'seg_loss', 'cls_loss', 'dfl_loss'\n        return v8.segment.SegmentationValidator(self.test_loader, save_dir=self.save_dir, args=copy(self.args))\n\n    def plot_training_samples(self, batch, ni):\n        \"\"\"Creates a plot of training sample images with labels and box coordinates.\"\"\"\n        plot_images(batch['img'],\n                    batch['batch_idx'],\n                    batch['cls'].squeeze(-1),\n                    batch['bboxes'],\n                    batch['masks'],\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'train_batch{ni}.jpg',\n                    on_plot=self.on_plot)\n\n    def plot_metrics(self):\n        \"\"\"Plots training/val metrics.\"\"\"\n        plot_results(file=self.csv, segment=True, on_plot=self.on_plot)  # save results.png\n\n\ndef train(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Train a YOLO segmentation model based on passed arguments.\"\"\"\n    model = cfg.model or 'yolov8n-seg.pt'\n    data = cfg.data or 'coco128-seg.yaml'  # or yolo.ClassificationDataset(\"mnist\")\n    device = cfg.device if cfg.device is not None else ''\n\n    args = dict(model=model, data=data, device=device)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).train(**args)\n    else:\n        trainer = SegmentationTrainer(overrides=args)\n        trainer.train()\n\n\nif __name__ == '__main__':\n    train()\n"
  },
  {
    "path": "ultralytics/yolo/v8/segment/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\n\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, NUM_THREADS, ops\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.metrics import SegmentMetrics, box_iou, mask_iou\nfrom ultralytics.yolo.utils.plotting import output_to_target, plot_images\nfrom ultralytics.yolo.v8.detect import DetectionValidator\n\n\nclass SegmentationValidator(DetectionValidator):\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"Initialize SegmentationValidator and set task to 'segment', metrics to SegmentMetrics.\"\"\"\n        super().__init__(dataloader, save_dir, pbar, args, _callbacks)\n        self.args.task = 'segment'\n        self.metrics = SegmentMetrics(save_dir=self.save_dir, on_plot=self.on_plot)\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses batch by converting masks to float and sending to device.\"\"\"\n        batch = super().preprocess(batch)\n        batch['masks'] = batch['masks'].to(self.device).float()\n        return batch\n\n    def init_metrics(self, model):\n        \"\"\"Initialize metrics and select mask processing function based on save_json flag.\"\"\"\n        super().init_metrics(model)\n        self.plot_masks = []\n        if self.args.save_json:\n            check_requirements('pycocotools>=2.0.6')\n            self.process = ops.process_mask_upsample  # more accurate\n        else:\n            self.process = ops.process_mask  # faster\n\n    def get_desc(self):\n        \"\"\"Return a formatted description of evaluation metrics.\"\"\"\n        return ('%22s' + '%11s' * 10) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)', 'Mask(P',\n                                         'R', 'mAP50', 'mAP50-95)')\n\n    def postprocess(self, preds):\n        \"\"\"Postprocesses YOLO predictions and returns output detections with proto.\"\"\"\n        p = ops.non_max_suppression(preds[0],\n                                    self.args.conf,\n                                    self.args.iou,\n                                    labels=self.lb,\n                                    multi_label=True,\n                                    agnostic=self.args.single_cls,\n                                    max_det=self.args.max_det,\n                                    nc=self.nc)\n        proto = preds[1][-1] if len(preds[1]) == 3 else preds[1]  # second output is len 3 if pt, but only 1 if exported\n        return p, proto\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Metrics.\"\"\"\n        for si, (pred, proto) in enumerate(zip(preds[0], preds[1])):\n            idx = batch['batch_idx'] == si\n            cls = batch['cls'][idx]\n            bbox = batch['bboxes'][idx]\n            nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n            shape = batch['ori_shape'][si]\n            correct_masks = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            self.seen += 1\n\n            if npr == 0:\n                if nl:\n                    self.stats.append((correct_bboxes, correct_masks, *torch.zeros(\n                        (2, 0), device=self.device), cls.squeeze(-1)))\n                    if self.args.plots:\n                        self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))\n                continue\n\n            # Masks\n            midx = [si] if self.args.overlap_mask else idx\n            gt_masks = batch['masks'][midx]\n            pred_masks = self.process(proto, pred[:, 6:], pred[:, :4], shape=batch['img'][si].shape[1:])\n\n            # Predictions\n            if self.args.single_cls:\n                pred[:, 5] = 0\n            predn = pred.clone()\n            ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,\n                            ratio_pad=batch['ratio_pad'][si])  # native-space pred\n\n            # Evaluate\n            if nl:\n                height, width = batch['img'].shape[2:]\n                tbox = ops.xywh2xyxy(bbox) * torch.tensor(\n                    (width, height, width, height), device=self.device)  # target boxes\n                ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,\n                                ratio_pad=batch['ratio_pad'][si])  # native-space labels\n                labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                correct_bboxes = self._process_batch(predn, labelsn)\n                # TODO: maybe remove these `self.` arguments as they already are member variable\n                correct_masks = self._process_batch(predn,\n                                                    labelsn,\n                                                    pred_masks,\n                                                    gt_masks,\n                                                    overlap=self.args.overlap_mask,\n                                                    masks=True)\n                if self.args.plots:\n                    self.confusion_matrix.process_batch(predn, labelsn)\n\n            # Append correct_masks, correct_boxes, pconf, pcls, tcls\n            self.stats.append((correct_bboxes, correct_masks, pred[:, 4], pred[:, 5], cls.squeeze(-1)))\n\n            pred_masks = torch.as_tensor(pred_masks, dtype=torch.uint8)\n            if self.args.plots and self.batch_i < 3:\n                self.plot_masks.append(pred_masks[:15].cpu())  # filter top 15 to plot\n\n            # Save\n            if self.args.save_json:\n                pred_masks = ops.scale_image(pred_masks.permute(1, 2, 0).contiguous().cpu().numpy(),\n                                             shape,\n                                             ratio_pad=batch['ratio_pad'][si])\n                self.pred_to_json(predn, batch['im_file'][si], pred_masks)\n            # if self.args.save_txt:\n            #    save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / f'{path.stem}.txt')\n\n    def finalize_metrics(self, *args, **kwargs):\n        \"\"\"Sets speed and confusion matrix for evaluation metrics.\"\"\"\n        self.metrics.speed = self.speed\n        self.metrics.confusion_matrix = self.confusion_matrix\n\n    def _process_batch(self, detections, labels, pred_masks=None, gt_masks=None, overlap=False, masks=False):\n        \"\"\"\n        Return correct prediction matrix\n        Arguments:\n            detections (array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (array[M, 5]), class, x1, y1, x2, y2\n        Returns:\n            correct (array[N, 10]), for 10 IoU levels\n        \"\"\"\n        if masks:\n            if overlap:\n                nl = len(labels)\n                index = torch.arange(nl, device=gt_masks.device).view(nl, 1, 1) + 1\n                gt_masks = gt_masks.repeat(nl, 1, 1)  # shape(1,640,640) -> (n,640,640)\n                gt_masks = torch.where(gt_masks == index, 1.0, 0.0)\n            if gt_masks.shape[1:] != pred_masks.shape[1:]:\n                gt_masks = F.interpolate(gt_masks[None], pred_masks.shape[1:], mode='bilinear', align_corners=False)[0]\n                gt_masks = gt_masks.gt_(0.5)\n            iou = mask_iou(gt_masks.view(gt_masks.shape[0], -1), pred_masks.view(pred_masks.shape[0], -1))\n        else:  # boxes\n            iou = box_iou(labels[:, 1:], detections[:, :4])\n\n        correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool)\n        correct_class = labels[:, 0:1] == detections[:, 5]\n        for i in range(len(self.iouv)):\n            x = torch.where((iou >= self.iouv[i]) & correct_class)  # IoU > threshold and classes match\n            if x[0].shape[0]:\n                matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]),\n                                    1).cpu().numpy()  # [label, detect, iou]\n                if x[0].shape[0] > 1:\n                    matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                    # matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n                correct[matches[:, 1].astype(int), i] = True\n        return torch.tensor(correct, dtype=torch.bool, device=detections.device)\n\n    def plot_val_samples(self, batch, ni):\n        \"\"\"Plots validation samples with bounding box labels.\"\"\"\n        plot_images(batch['img'],\n                    batch['batch_idx'],\n                    batch['cls'].squeeze(-1),\n                    batch['bboxes'],\n                    batch['masks'],\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'val_batch{ni}_labels.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)\n\n    def plot_predictions(self, batch, preds, ni):\n        \"\"\"Plots batch predictions with masks and bounding boxes.\"\"\"\n        plot_images(\n            batch['img'],\n            *output_to_target(preds[0], max_det=15),  # not set to self.args.max_det due to slow plotting speed\n            torch.cat(self.plot_masks, dim=0) if len(self.plot_masks) else self.plot_masks,\n            paths=batch['im_file'],\n            fname=self.save_dir / f'val_batch{ni}_pred.jpg',\n            names=self.names,\n            on_plot=self.on_plot)  # pred\n        self.plot_masks.clear()\n\n    def pred_to_json(self, predn, filename, pred_masks):\n        \"\"\"Save one JSON result.\"\"\"\n        # Example result = {\"image_id\": 42, \"category_id\": 18, \"bbox\": [258.15, 41.29, 348.26, 243.78], \"score\": 0.236}\n        from pycocotools.mask import encode  # noqa\n\n        def single_encode(x):\n            \"\"\"Encode predicted masks as RLE and append results to jdict.\"\"\"\n            rle = encode(np.asarray(x[:, :, None], order='F', dtype='uint8'))[0]\n            rle['counts'] = rle['counts'].decode('utf-8')\n            return rle\n\n        stem = Path(filename).stem\n        image_id = int(stem) if stem.isnumeric() else stem\n        box = ops.xyxy2xywh(predn[:, :4])  # xywh\n        box[:, :2] -= box[:, 2:] / 2  # xy center to top-left corner\n        pred_masks = np.transpose(pred_masks, (2, 0, 1))\n        with ThreadPool(NUM_THREADS) as pool:\n            rles = pool.map(single_encode, pred_masks)\n        for i, (p, b) in enumerate(zip(predn.tolist(), box.tolist())):\n            self.jdict.append({\n                'image_id': image_id,\n                'category_id': self.class_map[int(p[5])],\n                'bbox': [round(x, 3) for x in b],\n                'score': round(p[4], 5),\n                'segmentation': rles[i]})\n\n    def eval_json(self, stats):\n        \"\"\"Return COCO-style object detection evaluation metrics.\"\"\"\n        if self.args.save_json and self.is_coco and len(self.jdict):\n            anno_json = self.data['path'] / 'annotations/instances_val2017.json'  # annotations\n            pred_json = self.save_dir / 'predictions.json'  # predictions\n            LOGGER.info(f'\\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')\n            try:  # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n                check_requirements('pycocotools>=2.0.6')\n                from pycocotools.coco import COCO  # noqa\n                from pycocotools.cocoeval import COCOeval  # noqa\n\n                for x in anno_json, pred_json:\n                    assert x.is_file(), f'{x} file not found'\n                anno = COCO(str(anno_json))  # init annotations api\n                pred = anno.loadRes(str(pred_json))  # init predictions api (must pass string, not Path)\n                for i, eval in enumerate([COCOeval(anno, pred, 'bbox'), COCOeval(anno, pred, 'segm')]):\n                    if self.is_coco:\n                        eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files]  # im to eval\n                    eval.evaluate()\n                    eval.accumulate()\n                    eval.summarize()\n                    idx = i * 4 + 2\n                    stats[self.metrics.keys[idx + 1]], stats[\n                        self.metrics.keys[idx]] = eval.stats[:2]  # update mAP50-95 and mAP50\n            except Exception as e:\n                LOGGER.warning(f'pycocotools unable to run: {e}')\n        return stats\n\n\ndef val(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Validate trained YOLO model on validation data.\"\"\"\n    model = cfg.model or 'yolov8n-seg.pt'\n    data = cfg.data or 'coco128-seg.yaml'\n\n    args = dict(model=model, data=data)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).val(**args)\n    else:\n        validator = SegmentationValidator(args=args)\n        validator(model=args['model'])\n\n\nif __name__ == '__main__':\n    val()\n"
  },
  {
    "path": "utils/__init__.py",
    "content": ""
  },
  {
    "path": "utils/tools.py",
    "content": "import numpy as np\r\nfrom PIL import Image\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nimport torch\r\nimport os\r\nimport sys\r\n\r\n\r\ndef convert_box_xywh_to_xyxy(box):\r\n    if len(box) == 4:\r\n        return [box[0], box[1], box[0] + box[2], box[1] + box[3]]\r\n    else:\r\n        result = []\r\n        for b in box:\r\n            b = convert_box_xywh_to_xyxy(b)\r\n            result.append(b)               \r\n    return result\r\n\r\n\r\ndef segment_image(image, bbox):\r\n    image_array = np.array(image)\r\n    segmented_image_array = np.zeros_like(image_array)\r\n    x1, y1, x2, y2 = bbox\r\n    segmented_image_array[y1:y2, x1:x2] = image_array[y1:y2, x1:x2]\r\n    segmented_image = Image.fromarray(segmented_image_array)\r\n    black_image = Image.new(\"RGB\", image.size, (255, 255, 255))\r\n    # transparency_mask = np.zeros_like((), dtype=np.uint8)\r\n    transparency_mask = np.zeros(\r\n        (image_array.shape[0], image_array.shape[1]), dtype=np.uint8\r\n    )\r\n    transparency_mask[y1:y2, x1:x2] = 255\r\n    transparency_mask_image = Image.fromarray(transparency_mask, mode=\"L\")\r\n    black_image.paste(segmented_image, mask=transparency_mask_image)\r\n    return black_image\r\n\r\n\r\ndef format_results(result, filter=0):\r\n    annotations = []\r\n    n = len(result.masks.data)\r\n    for i in range(n):\r\n        annotation = {}\r\n        mask = result.masks.data[i] == 1.0\r\n\r\n        if torch.sum(mask) < filter:\r\n            continue\r\n        annotation[\"id\"] = i\r\n        annotation[\"segmentation\"] = mask.cpu().numpy()\r\n        annotation[\"bbox\"] = result.boxes.data[i]\r\n        annotation[\"score\"] = result.boxes.conf[i]\r\n        annotation[\"area\"] = annotation[\"segmentation\"].sum()\r\n        annotations.append(annotation)\r\n    return annotations\r\n\r\n\r\ndef filter_masks(annotations):  # filter the overlap mask\r\n    annotations.sort(key=lambda x: x[\"area\"], reverse=True)\r\n    to_remove = set()\r\n    for i in range(0, len(annotations)):\r\n        a = annotations[i]\r\n        for j in range(i + 1, len(annotations)):\r\n            b = annotations[j]\r\n            if i != j and j not in to_remove:\r\n                # check if\r\n                if b[\"area\"] < a[\"area\"]:\r\n                    if (a[\"segmentation\"] & b[\"segmentation\"]).sum() / b[\r\n                        \"segmentation\"\r\n                    ].sum() > 0.8:\r\n                        to_remove.add(j)\r\n\r\n    return [a for i, a in enumerate(annotations) if i not in to_remove], to_remove\r\n\r\n\r\ndef get_bbox_from_mask(mask):\r\n    mask = mask.astype(np.uint8)\r\n    contours, hierarchy = cv2.findContours(\r\n        mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE\r\n    )\r\n    x1, y1, w, h = cv2.boundingRect(contours[0])\r\n    x2, y2 = x1 + w, y1 + h\r\n    if len(contours) > 1:\r\n        for b in contours:\r\n            x_t, y_t, w_t, h_t = cv2.boundingRect(b)\r\n            # 将多个bbox合并成一个\r\n            x1 = min(x1, x_t)\r\n            y1 = min(y1, y_t)\r\n            x2 = max(x2, x_t + w_t)\r\n            y2 = max(y2, y_t + h_t)\r\n        h = y2 - y1\r\n        w = x2 - x1\r\n    return [x1, y1, x2, y2]\r\n\r\n\r\ndef fast_process(\r\n    annotations, args, mask_random_color, bbox=None, points=None, edges=False\r\n):\r\n    if isinstance(annotations[0], dict):\r\n        annotations = [annotation[\"segmentation\"] for annotation in annotations]\r\n    result_name = os.path.basename(args.img_path)\r\n    image = cv2.imread(args.img_path)\r\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\r\n    original_h = image.shape[0]\r\n    original_w = image.shape[1]\r\n    if sys.platform == \"darwin\":\r\n            plt.switch_backend(\"TkAgg\")\r\n    plt.figure(figsize=(original_w/100, original_h/100))\r\n    # Add subplot with no margin.\r\n    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\r\n    plt.margins(0, 0)\r\n    plt.gca().xaxis.set_major_locator(plt.NullLocator())\r\n    plt.gca().yaxis.set_major_locator(plt.NullLocator())\r\n    plt.imshow(image)\r\n    if args.better_quality == True:\r\n        if isinstance(annotations[0], torch.Tensor):\r\n            annotations = np.array(annotations.cpu())\r\n        for i, mask in enumerate(annotations):\r\n            mask = cv2.morphologyEx(\r\n                mask.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8)\r\n            )\r\n            annotations[i] = cv2.morphologyEx(\r\n                mask.astype(np.uint8), cv2.MORPH_OPEN, np.ones((8, 8), np.uint8)\r\n            )\r\n    if args.device == \"cpu\":\r\n        annotations = np.array(annotations)\r\n        fast_show_mask(\r\n            annotations,\r\n            plt.gca(),\r\n            random_color=mask_random_color,\r\n            bbox=bbox,\r\n            points=points,\r\n            point_label=args.point_label,\r\n            retinamask=args.retina,\r\n            target_height=original_h,\r\n            target_width=original_w,\r\n        )\r\n    else:\r\n        if isinstance(annotations[0], np.ndarray):\r\n            annotations = torch.from_numpy(annotations)\r\n        fast_show_mask_gpu(\r\n            annotations,\r\n            plt.gca(),\r\n            random_color=args.randomcolor,\r\n            bbox=bbox,\r\n            points=points,\r\n            point_label=args.point_label,\r\n            retinamask=args.retina,\r\n            target_height=original_h,\r\n            target_width=original_w,\r\n        )\r\n    if isinstance(annotations, torch.Tensor):\r\n        annotations = annotations.cpu().numpy()\r\n    if args.withContours == True:\r\n        contour_all = []\r\n        temp = np.zeros((original_h, original_w, 1))\r\n        for i, mask in enumerate(annotations):\r\n            if type(mask) == dict:\r\n                mask = mask[\"segmentation\"]\r\n            annotation = mask.astype(np.uint8)\r\n            if args.retina == False:\r\n                annotation = cv2.resize(\r\n                    annotation,\r\n                    (original_w, original_h),\r\n                    interpolation=cv2.INTER_NEAREST,\r\n                )\r\n            contours, hierarchy = cv2.findContours(\r\n                annotation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE\r\n            )\r\n            for contour in contours:\r\n                contour_all.append(contour)\r\n        cv2.drawContours(temp, contour_all, -1, (255, 255, 255), 2)\r\n        color = np.array([0 / 255, 0 / 255, 255 / 255, 0.8])\r\n        contour_mask = temp / 255 * color.reshape(1, 1, -1)\r\n        plt.imshow(contour_mask)\r\n\r\n    save_path = args.output\r\n    if not os.path.exists(save_path):\r\n        os.makedirs(save_path)\r\n    plt.axis(\"off\")\r\n    fig = plt.gcf()\r\n    plt.draw()\r\n    \r\n    try:\r\n        buf = fig.canvas.tostring_rgb()\r\n    except AttributeError:\r\n        fig.canvas.draw()\r\n        buf = fig.canvas.tostring_rgb()\r\n    \r\n    cols, rows = fig.canvas.get_width_height()\r\n    img_array = np.fromstring(buf, dtype=np.uint8).reshape(rows, cols, 3)\r\n    cv2.imwrite(os.path.join(save_path, result_name), cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR))\r\n\r\n\r\n# CPU post process\r\ndef fast_show_mask(\r\n    annotation,\r\n    ax,\r\n    random_color=False,\r\n    bbox=None,\r\n    points=None,\r\n    point_label=None,\r\n    retinamask=True,\r\n    target_height=960,\r\n    target_width=960,\r\n):\r\n    msak_sum = annotation.shape[0]\r\n    height = annotation.shape[1]\r\n    weight = annotation.shape[2]\r\n    # 将annotation 按照面积 排序\r\n    areas = np.sum(annotation, axis=(1, 2))\r\n    sorted_indices = np.argsort(areas)\r\n    annotation = annotation[sorted_indices]\r\n\r\n    index = (annotation != 0).argmax(axis=0)\r\n    if random_color == True:\r\n        color = np.random.random((msak_sum, 1, 1, 3))\r\n    else:\r\n        color = np.ones((msak_sum, 1, 1, 3)) * np.array(\r\n            [30 / 255, 144 / 255, 255 / 255]\r\n        )\r\n    transparency = np.ones((msak_sum, 1, 1, 1)) * 0.6\r\n    visual = np.concatenate([color, transparency], axis=-1)\r\n    mask_image = np.expand_dims(annotation, -1) * visual\r\n\r\n    show = np.zeros((height, weight, 4))\r\n    h_indices, w_indices = np.meshgrid(\r\n        np.arange(height), np.arange(weight), indexing=\"ij\"\r\n    )\r\n    indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))\r\n    # 使用向量化索引更新show的值\r\n    show[h_indices, w_indices, :] = mask_image[indices]\r\n    if bbox is not None:\r\n        x1, y1, x2, y2 = bbox\r\n        ax.add_patch(\r\n            plt.Rectangle(\r\n                (x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor=\"b\", linewidth=1\r\n            )\r\n        )\r\n    # draw point\r\n    if points is not None:\r\n        plt.scatter(\r\n            [point[0] for i, point in enumerate(points) if point_label[i] == 1],\r\n            [point[1] for i, point in enumerate(points) if point_label[i] == 1],\r\n            s=20,\r\n            c=\"y\",\r\n        )\r\n        plt.scatter(\r\n            [point[0] for i, point in enumerate(points) if point_label[i] == 0],\r\n            [point[1] for i, point in enumerate(points) if point_label[i] == 0],\r\n            s=20,\r\n            c=\"m\",\r\n        )\r\n\r\n    if retinamask == False:\r\n        show = cv2.resize(\r\n            show, (target_width, target_height), interpolation=cv2.INTER_NEAREST\r\n        )\r\n    ax.imshow(show)\r\n\r\n\r\ndef fast_show_mask_gpu(\r\n    annotation,\r\n    ax,\r\n    random_color=False,\r\n    bbox=None,\r\n    points=None,\r\n    point_label=None,\r\n    retinamask=True,\r\n    target_height=960,\r\n    target_width=960,\r\n):\r\n    msak_sum = annotation.shape[0]\r\n    height = annotation.shape[1]\r\n    weight = annotation.shape[2]\r\n    areas = torch.sum(annotation, dim=(1, 2))\r\n    sorted_indices = torch.argsort(areas, descending=False)\r\n    annotation = annotation[sorted_indices]\r\n    # 找每个位置第一个非零值下标\r\n    index = (annotation != 0).to(torch.long).argmax(dim=0)\r\n    if random_color == True:\r\n        color = torch.rand((msak_sum, 1, 1, 3)).to(annotation.device)\r\n    else:\r\n        color = torch.ones((msak_sum, 1, 1, 3)).to(annotation.device) * torch.tensor(\r\n            [30 / 255, 144 / 255, 255 / 255]\r\n        ).to(annotation.device)\r\n    transparency = torch.ones((msak_sum, 1, 1, 1)).to(annotation.device) * 0.6\r\n    visual = torch.cat([color, transparency], dim=-1)\r\n    mask_image = torch.unsqueeze(annotation, -1) * visual\r\n    # 按index取数，index指每个位置选哪个batch的数，把mask_image转成一个batch的形式\r\n    show = torch.zeros((height, weight, 4)).to(annotation.device)\r\n    h_indices, w_indices = torch.meshgrid(\r\n        torch.arange(height), torch.arange(weight), indexing=\"ij\"\r\n    )\r\n    indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))\r\n    # 使用向量化索引更新show的值\r\n    show[h_indices, w_indices, :] = mask_image[indices]\r\n    show_cpu = show.cpu().numpy()\r\n    if bbox is not None:\r\n        x1, y1, x2, y2 = bbox\r\n        ax.add_patch(\r\n            plt.Rectangle(\r\n                (x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor=\"b\", linewidth=1\r\n            )\r\n        )\r\n    # draw point\r\n    if points is not None:\r\n        plt.scatter(\r\n            [point[0] for i, point in enumerate(points) if point_label[i] == 1],\r\n            [point[1] for i, point in enumerate(points) if point_label[i] == 1],\r\n            s=20,\r\n            c=\"y\",\r\n        )\r\n        plt.scatter(\r\n            [point[0] for i, point in enumerate(points) if point_label[i] == 0],\r\n            [point[1] for i, point in enumerate(points) if point_label[i] == 0],\r\n            s=20,\r\n            c=\"m\",\r\n        )\r\n    if retinamask == False:\r\n        show_cpu = cv2.resize(\r\n            show_cpu, (target_width, target_height), interpolation=cv2.INTER_NEAREST\r\n        )\r\n    ax.imshow(show_cpu)\r\n\r\n\r\n# clip\r\n@torch.no_grad()\r\ndef retriev(\r\n    model, preprocess, elements: [Image.Image], search_text: str, device\r\n):\r\n    preprocessed_images = [preprocess(image).to(device) for image in elements]\r\n    import clip\r\n    tokenized_text = clip.tokenize([search_text]).to(device)\r\n    stacked_images = torch.stack(preprocessed_images)\r\n    image_features = model.encode_image(stacked_images)\r\n    text_features = model.encode_text(tokenized_text)\r\n    image_features /= image_features.norm(dim=-1, keepdim=True)\r\n    text_features /= text_features.norm(dim=-1, keepdim=True)\r\n    probs = 100.0 * image_features @ text_features.T\r\n    return probs[:, 0].softmax(dim=0)\r\n\r\n\r\ndef crop_image(annotations, image_like):\r\n    if isinstance(image_like, str):\r\n        image = Image.open(image_like)\r\n    else:\r\n        image = image_like\r\n    ori_w, ori_h = image.size\r\n    mask_h, mask_w = annotations[0][\"segmentation\"].shape\r\n    if ori_w != mask_w or ori_h != mask_h:\r\n        image = image.resize((mask_w, mask_h))\r\n    cropped_boxes = []\r\n    cropped_images = []\r\n    not_crop = []\r\n    origin_id = []\r\n    for _, mask in enumerate(annotations):\r\n        if np.sum(mask[\"segmentation\"]) <= 100:\r\n            continue\r\n        origin_id.append(_)\r\n        bbox = get_bbox_from_mask(mask[\"segmentation\"])  # mask 的 bbox\r\n        cropped_boxes.append(segment_image(image, bbox))  # 保存裁剪的图片\r\n        # cropped_boxes.append(segment_image(image,mask[\"segmentation\"]))\r\n        cropped_images.append(bbox)  # 保存裁剪的图片的bbox\r\n    return cropped_boxes, cropped_images, not_crop, origin_id, annotations\r\n\r\n\r\ndef box_prompt(masks, bbox, target_height, target_width):\r\n    h = masks.shape[1]\r\n    w = masks.shape[2]\r\n    if h != target_height or w != target_width:\r\n        bbox = [\r\n            int(bbox[0] * w / target_width),\r\n            int(bbox[1] * h / target_height),\r\n            int(bbox[2] * w / target_width),\r\n            int(bbox[3] * h / target_height),\r\n        ]\r\n    bbox[0] = round(bbox[0]) if round(bbox[0]) > 0 else 0\r\n    bbox[1] = round(bbox[1]) if round(bbox[1]) > 0 else 0\r\n    bbox[2] = round(bbox[2]) if round(bbox[2]) < w else w\r\n    bbox[3] = round(bbox[3]) if round(bbox[3]) < h else h\r\n\r\n    # IoUs = torch.zeros(len(masks), dtype=torch.float32)\r\n    bbox_area = (bbox[3] - bbox[1]) * (bbox[2] - bbox[0])\r\n\r\n    masks_area = torch.sum(masks[:, bbox[1] : bbox[3], bbox[0] : bbox[2]], dim=(1, 2))\r\n    orig_masks_area = torch.sum(masks, dim=(1, 2))\r\n\r\n    union = bbox_area + orig_masks_area - masks_area\r\n    IoUs = masks_area / union\r\n    max_iou_index = torch.argmax(IoUs)\r\n\r\n    return masks[max_iou_index].cpu().numpy(), max_iou_index\r\n\r\n\r\ndef point_prompt(masks, points, point_label, target_height, target_width):  # numpy 处理\r\n    h = masks[0][\"segmentation\"].shape[0]\r\n    w = masks[0][\"segmentation\"].shape[1]\r\n    if h != target_height or w != target_width:\r\n        points = [\r\n            [int(point[0] * w / target_width), int(point[1] * h / target_height)]\r\n            for point in points\r\n        ]\r\n    onemask = np.zeros((h, w))\r\n    masks = sorted(masks, key=lambda x: x['area'], reverse=True)\r\n    for i, annotation in enumerate(masks):\r\n        if type(annotation) == dict:\r\n            mask = annotation['segmentation']\r\n        else:\r\n            mask = annotation\r\n        for i, point in enumerate(points):\r\n            if mask[point[1], point[0]] == 1 and point_label[i] == 1:\r\n                onemask[mask] = 1\r\n            if mask[point[1], point[0]] == 1 and point_label[i] == 0:\r\n                onemask[mask] = 0\r\n    onemask = onemask >= 1\r\n    return onemask, 0\r\n\r\n\r\ndef text_prompt(annotations, text, img_path, device, wider=False, threshold=0.9):\r\n    cropped_boxes, cropped_images, not_crop, origin_id, annotations_ = crop_image(\r\n        annotations, img_path\r\n    )\r\n\r\n    import clip\r\n    clip_model, preprocess = clip.load(\"ViT-B/32\", device=device)\r\n    scores = retriev(\r\n        clip_model, preprocess, cropped_boxes, text, device=device\r\n    )\r\n    max_idx = scores.argsort()\r\n    max_idx = max_idx[-1]\r\n    max_idx = origin_id[int(max_idx)]\r\n\r\n    # find the biggest mask which contains the mask with max score\r\n    if wider:\r\n        mask0 = annotations_[max_idx][\"segmentation\"]\r\n        area0 = np.sum(mask0)\r\n        areas = [(i, np.sum(mask[\"segmentation\"])) for i, mask in enumerate(annotations_) if i in origin_id]\r\n        areas = sorted(areas, key=lambda area: area[1], reverse=True)\r\n        indices = [area[0] for area in areas]\r\n        for index in indices:\r\n            if index == max_idx or np.sum(annotations_[index][\"segmentation\"] & mask0) / area0 > threshold:\r\n                max_idx = index\r\n                break\r\n\r\n    return annotations_[max_idx][\"segmentation\"], max_idx\r\n"
  },
  {
    "path": "utils/tools_gradio.py",
    "content": "import numpy as np\r\nfrom PIL import Image\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nimport torch\r\n\r\n\r\ndef fast_process(\r\n    annotations,\r\n    image,\r\n    device,\r\n    scale,\r\n    better_quality=False,\r\n    mask_random_color=True,\r\n    bbox=None,\r\n    use_retina=True,\r\n    withContours=True,\r\n):\r\n    if isinstance(annotations[0], dict):\r\n        annotations = [annotation['segmentation'] for annotation in annotations]\r\n\r\n    original_h = image.height\r\n    original_w = image.width\r\n    if better_quality:\r\n        if isinstance(annotations[0], torch.Tensor):\r\n            annotations = np.array(annotations.cpu())\r\n        for i, mask in enumerate(annotations):\r\n            mask = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))\r\n            annotations[i] = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_OPEN, np.ones((8, 8), np.uint8))\r\n    if device == 'cpu':\r\n        annotations = np.array(annotations)\r\n        inner_mask = fast_show_mask(\r\n            annotations,\r\n            plt.gca(),\r\n            random_color=mask_random_color,\r\n            bbox=bbox,\r\n            retinamask=use_retina,\r\n            target_height=original_h,\r\n            target_width=original_w,\r\n        )\r\n    else:\r\n        if isinstance(annotations[0], np.ndarray):\r\n            annotations = torch.from_numpy(annotations)\r\n        inner_mask = fast_show_mask_gpu(\r\n            annotations,\r\n            plt.gca(),\r\n            random_color=mask_random_color,\r\n            bbox=bbox,\r\n            retinamask=use_retina,\r\n            target_height=original_h,\r\n            target_width=original_w,\r\n        )\r\n    if isinstance(annotations, torch.Tensor):\r\n        annotations = annotations.cpu().numpy()\r\n\r\n    if withContours:\r\n        contour_all = []\r\n        temp = np.zeros((original_h, original_w, 1))\r\n        for i, mask in enumerate(annotations):\r\n            if type(mask) == dict:\r\n                mask = mask['segmentation']\r\n            annotation = mask.astype(np.uint8)\r\n            if use_retina == False:\r\n                annotation = cv2.resize(\r\n                    annotation,\r\n                    (original_w, original_h),\r\n                    interpolation=cv2.INTER_NEAREST,\r\n                )\r\n            contours, _ = cv2.findContours(annotation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\n            for contour in contours:\r\n                contour_all.append(contour)\r\n        cv2.drawContours(temp, contour_all, -1, (255, 255, 255), 2 // scale)\r\n        color = np.array([0 / 255, 0 / 255, 255 / 255, 0.9])\r\n        contour_mask = temp / 255 * color.reshape(1, 1, -1)\r\n\r\n    image = image.convert('RGBA')\r\n    overlay_inner = Image.fromarray((inner_mask * 255).astype(np.uint8), 'RGBA')\r\n    image.paste(overlay_inner, (0, 0), overlay_inner)\r\n\r\n    if withContours:\r\n        overlay_contour = Image.fromarray((contour_mask * 255).astype(np.uint8), 'RGBA')\r\n        image.paste(overlay_contour, (0, 0), overlay_contour)\r\n\r\n    return image\r\n\r\n\r\n# CPU post process\r\ndef fast_show_mask(\r\n    annotation,\r\n    ax,\r\n    random_color=False,\r\n    bbox=None,\r\n    retinamask=True,\r\n    target_height=960,\r\n    target_width=960,\r\n):\r\n    mask_sum = annotation.shape[0]\r\n    height = annotation.shape[1]\r\n    weight = annotation.shape[2]\r\n    # 将annotation 按照面积 排序\r\n    areas = np.sum(annotation, axis=(1, 2))\r\n    sorted_indices = np.argsort(areas)[::1]\r\n    annotation = annotation[sorted_indices]\r\n\r\n    index = (annotation != 0).argmax(axis=0)\r\n    if random_color:\r\n        color = np.random.random((mask_sum, 1, 1, 3))\r\n    else:\r\n        color = np.ones((mask_sum, 1, 1, 3)) * np.array([30 / 255, 144 / 255, 255 / 255])\r\n    transparency = np.ones((mask_sum, 1, 1, 1)) * 0.6\r\n    visual = np.concatenate([color, transparency], axis=-1)\r\n    mask_image = np.expand_dims(annotation, -1) * visual\r\n\r\n    mask = np.zeros((height, weight, 4))\r\n\r\n    h_indices, w_indices = np.meshgrid(np.arange(height), np.arange(weight), indexing='ij')\r\n    indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))\r\n\r\n    mask[h_indices, w_indices, :] = mask_image[indices]\r\n    if bbox is not None:\r\n        x1, y1, x2, y2 = bbox\r\n        ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor='b', linewidth=1))\r\n\r\n    if not retinamask:\r\n        mask = cv2.resize(mask, (target_width, target_height), interpolation=cv2.INTER_NEAREST)\r\n\r\n    return mask\r\n\r\n\r\ndef fast_show_mask_gpu(\r\n    annotation,\r\n    ax,\r\n    random_color=False,\r\n    bbox=None,\r\n    retinamask=True,\r\n    target_height=960,\r\n    target_width=960,\r\n):\r\n    device = annotation.device\r\n    mask_sum = annotation.shape[0]\r\n    height = annotation.shape[1]\r\n    weight = annotation.shape[2]\r\n    areas = torch.sum(annotation, dim=(1, 2))\r\n    sorted_indices = torch.argsort(areas, descending=False)\r\n    annotation = annotation[sorted_indices]\r\n    # 找每个位置第一个非零值下标\r\n    index = (annotation != 0).to(torch.long).argmax(dim=0)\r\n    if random_color:\r\n        color = torch.rand((mask_sum, 1, 1, 3)).to(device)\r\n    else:\r\n        color = torch.ones((mask_sum, 1, 1, 3)).to(device) * torch.tensor(\r\n            [30 / 255, 144 / 255, 255 / 255]\r\n        ).to(device)\r\n    transparency = torch.ones((mask_sum, 1, 1, 1)).to(device) * 0.6\r\n    visual = torch.cat([color, transparency], dim=-1)\r\n    mask_image = torch.unsqueeze(annotation, -1) * visual\r\n    # 按index取数，index指每个位置选哪个batch的数，把mask_image转成一个batch的形式\r\n    mask = torch.zeros((height, weight, 4)).to(device)\r\n    h_indices, w_indices = torch.meshgrid(torch.arange(height), torch.arange(weight))\r\n    indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))\r\n    # 使用向量化索引更新show的值\r\n    mask[h_indices, w_indices, :] = mask_image[indices]\r\n    mask_cpu = mask.cpu().numpy()\r\n    if bbox is not None:\r\n        x1, y1, x2, y2 = bbox\r\n        ax.add_patch(\r\n            plt.Rectangle(\r\n                (x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor=\"b\", linewidth=1\r\n            )\r\n        )\r\n    if not retinamask:\r\n        mask_cpu = cv2.resize(\r\n            mask_cpu, (target_width, target_height), interpolation=cv2.INTER_NEAREST\r\n        )\r\n    return mask_cpu\r\n"
  }
]