[
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Play online chess with a real chess board\nProgram that enables you to play online chess using real chess boards.  Using computer vision it will detect the moves you make on a chess board. After that, if it's your turn to move in the online game, it will make the necessary clicks to make the move.\n\n## Setup\n\n1. Turn off all the animations and extra features to keep chess board of online game as simple as possible. You can skip this step if you enter your Lichess API Access Token. \n2. Take screenshots of the chess board of an online game at starting position, one for when you play white and one for when you play black and save them as \"white.JPG\" and \"black.JPG\" similar to the images included in the source code. You can skip this step if you enable \"Find chess board of online game without template images.\" option or enter your Lichess API Access Token.\n3. Enable auto-promotion to queen from settings of online game. You can skip this step if you enter your Lichess API Access Token.\n4. Place your webcam near to your chessboard so that all of the squares and pieces can be clearly seen by it.\n5. Select a board calibration mode and follow its instructions.\n\n## Board Calibration(The board is empty.)\n\n1. Remove all pieces from your chess board.\n\n2. Click the \"Board Calibration\" button.\n\n3. Check that corners of your chess board are correctly detected by \"board_calibration.py\" and press key \"q\" to save detected chess board corners. You don't need to manually select chess board corners; it should be automatically detected by the program. The square covered by points (0,0), (0,1),(1,0) and (1,1) should be a8. You can rotate the image by pressing the key \"r\" to adjust that. Example chess board detection result:\n\n   ![](https://github.com/karayaman/Play-online-chess-with-real-chess-board/blob/main/chessboard_detection_result.jpg?raw=true)\n\n## Board Calibration(Pieces are in their starting positions.)\n\n1. Place the pieces in their starting positions.\n2. Click the \"Board Calibration\" button.\n3. Please ensure your chess board is correctly positioned and detected. Guiding lines will be drawn to mark the board's edges:\n   - The line near the white pieces will be blue.\n   - The line near the black pieces will be green.\n   - Press any key to exit once you've confirmed the board setup.\n\n<img src=\"https://github.com/karayaman/Play-online-chess-with-real-chess-board/raw/main/board_detection_result.jpg\" style=\"zoom:67%;\" />\n\n## Board Calibration(Just before the game starts.)\n\n1. Click the \"Start Game\" button. The software will calibrate the board just before it begins move recognition.\n\n## Usage\n\n1. Place pieces of chess board to their starting position.\n2. Start the online game.\n3. Click the \"Start Game\" button.\n4. Switch to the online game so that program detects chess board of online game. You have 5 seconds to complete this step. You can skip this step if you enter your Lichess API Access Token.\n5.  Wait until the program says \"game started\".\n6. Make your move if it's your turn , otherwise make your opponent's move.\n8. Notice that the program actually makes your move on the internet game if it's your turn. Otherwise, wait until the program says starting and ending squares of the opponent's move. To save clock time, you may choose not to wait, but this is not recommended.\n9. Go to step 6.\n\n## GUI\n\nYou need to run the GUI to do the steps in Setup, Usage and Diagnostic sections. Also, you can enter your Lichess API Access Token via Connection&#8594;Lichess (You need to enable \"Play games with the board API\" while generating the token).\n\n![](https://github.com/karayaman/Play-online-chess-with-real-chess-board/blob/main/gui.jpg?raw=true)\n\n## Diagnostic\n\nYou need to click the \"Diagnostic\" button to run the diagnostic process. It will show your chessboard in a perspective-transformed form, exactly as the software sees it. Additionally, it will mark white pieces with a blue circle and black pieces with a green circle, allowing you to verify if the software can detect the pieces on the chess board.\n\n![](https://github.com/karayaman/Play-online-chess-with-real-chess-board/blob/main/diagnostic.jpg?raw=true)\n\n## Video\n\nIn this section you can find video content related to the software.\n\n[Play online chess with real chess board and web camera | NO DGT BOARD!](https://www.youtube.com/watch?v=LX-4czb3xi0&lc=Ugxo6cXY0cR2TArDpuZ4AaABAg)\n\n## Frequently Asked Questions\n\n### What is the program doing? How does it work? \n\nIt tracks your chess board via a webcam. You should place it on top of your chess board. Make sure there is enough light in the environment and all squares are clearly visible. When you make a move on your chess board, it understands the move you made and transfers it to the chess GUI by simulating mouse clicks (It clicks the starting and ending squares of your move). This way, using your chess board, you can play chess in any chess program, either websites like lichess.org, chess.com, or desktop programs like Fritz, Chessmaster etc.\n\n### Placing a webcam on top of the chess board sounds difficult. Can I put my laptop aside with the webcam on the laptop display?\n\nYes, you can do that with a small chess board. However, placing a webcam on top of the chess board is recommended. Personally, while using the program I am putting my laptop aside and it gives out moves via chess gui and shows clocks. Instead of using the laptop's webcam, I disable it and use my old android phone's camera as a webcam using an app called DroidCam. I place my phone somewhere high enough (a bookshelf, for instance) so that all of the squares and pieces can be clearly seen by it.\n\n### How well does it work?\n\nUsing this software I am able to make up to 100 moves in 15+10 rapid online game without getting any errors.\n\n### I am getting error message \"Move registration failed. Please redo your move.\" What is the problem?\n\nThe program asked you to redo your move because it understood that you had made a move. However, it failed to figure out which move you made. This can happen if your board calibration is incorrect or the color of your pieces are very similar to the color of your squares. If the latter is the case, you will get this error message when playing white piece to light square or black piece to dark square. \n\n### Why does it take forever to detect corners of the chess board?\n\nIt should detect corners of the chess board almost immediately. Please do not spend any time waiting for it to detect corners of the chess board. If it can't detect corners of the chess board almost immediately, this means that it can't see your chess board well from that position/angle. Placing your webcam somewhere a bit higher or lower might solve the issue.\n\n## Required libraries\n\n- opencv-python\n- python-chess\n- pyautogui\n- mss\n- numpy\n- pyttsx3\n- scikit-image\n- pygrabber\n- berserk\n"
  },
  {
    "path": "board_basics.py",
    "content": "import sys\r\n\r\nfrom skimage.metrics import structural_similarity\r\nimport chess\r\nimport pickle\r\nimport os\r\n\r\n\r\nclass Board_basics:\r\n    def __init__(self, side_view_compensation, rotation_count):\r\n        self.d = [side_view_compensation, (0, 0)]\r\n        self.rotation_count = rotation_count\r\n        self.SSIM_THRESHOLD = 0.8\r\n        self.SSIM_THRESHOLD_LIGHT_WHITE = 1.0\r\n        self.SSIM_THRESHOLD_LIGHT_BLACK = 1.0\r\n        self.SSIM_THRESHOLD_DARK_WHITE = 1.0\r\n        self.SSIM_THRESHOLD_DARK_BLACK = 1.0\r\n        self.ssim_table = [[self.SSIM_THRESHOLD_DARK_BLACK, self.SSIM_THRESHOLD_DARK_WHITE],\r\n                           [self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_LIGHT_WHITE]]\r\n        self.save_file = \"ssim.bin\"\r\n\r\n    def initialize_ssim(self, frame):\r\n        light_white = []\r\n        dark_white = []\r\n        light_empty = []\r\n        dark_empty = []\r\n        light_black = []\r\n        dark_black = []\r\n        for row in range(8):\r\n            for column in range(8):\r\n                square_name = self.convert_row_column_to_square_name(row, column)\r\n                if square_name[1] == \"2\":\r\n                    if self.is_light(square_name):\r\n                        light_white.append(self.get_square_image(row, column, frame))\r\n                    else:\r\n                        dark_white.append(self.get_square_image(row, column, frame))\r\n                elif square_name[1] == \"4\":\r\n                    if self.is_light(square_name):\r\n                        light_empty.append(self.get_square_image(row, column, frame))\r\n                    else:\r\n                        dark_empty.append(self.get_square_image(row, column, frame))\r\n                elif square_name[1] == \"7\":\r\n                    if self.is_light(square_name):\r\n                        light_black.append(self.get_square_image(row, column, frame))\r\n                    else:\r\n                        dark_black.append(self.get_square_image(row, column, frame))\r\n        ssim_light_white = max(structural_similarity(empty,\r\n                                                     piece, channel_axis=-1) for piece, empty in\r\n                               zip(light_white, light_empty))\r\n        ssim_light_black = max(structural_similarity(empty,\r\n                                                     piece, channel_axis=-1) for piece, empty in\r\n                               zip(light_black, light_empty))\r\n        ssim_dark_white = max(structural_similarity(empty,\r\n                                                    piece, channel_axis=-1) for piece, empty in\r\n                              zip(dark_white, dark_empty))\r\n        ssim_dark_black = max(structural_similarity(empty,\r\n                                                    piece, channel_axis=-1) for piece, empty in\r\n                              zip(dark_black, dark_empty))\r\n        self.SSIM_THRESHOLD_LIGHT_WHITE = min(self.SSIM_THRESHOLD_LIGHT_WHITE, ssim_light_white + 0.2)\r\n        self.SSIM_THRESHOLD_LIGHT_BLACK = min(self.SSIM_THRESHOLD_LIGHT_BLACK, ssim_light_black + 0.2)\r\n        self.SSIM_THRESHOLD_DARK_WHITE = min(self.SSIM_THRESHOLD_DARK_WHITE, ssim_dark_white + 0.2)\r\n        self.SSIM_THRESHOLD_DARK_BLACK = min(self.SSIM_THRESHOLD_DARK_BLACK, ssim_dark_black + 0.2)\r\n        self.SSIM_THRESHOLD = max(\r\n            [self.SSIM_THRESHOLD, self.SSIM_THRESHOLD_LIGHT_WHITE, self.SSIM_THRESHOLD_LIGHT_BLACK,\r\n             self.SSIM_THRESHOLD_DARK_WHITE, self.SSIM_THRESHOLD_DARK_BLACK])\r\n        print(self.SSIM_THRESHOLD_LIGHT_WHITE, self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_DARK_WHITE,\r\n              self.SSIM_THRESHOLD_DARK_BLACK)\r\n        self.ssim_table = [[self.SSIM_THRESHOLD_DARK_BLACK, self.SSIM_THRESHOLD_DARK_WHITE],\r\n                           [self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_LIGHT_WHITE]]\r\n\r\n        outfile = open(self.save_file, 'wb')\r\n        pickle.dump((self.SSIM_THRESHOLD_LIGHT_WHITE, self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_DARK_WHITE,\r\n                     self.SSIM_THRESHOLD_DARK_BLACK, self.SSIM_THRESHOLD), outfile)\r\n        outfile.close()\r\n\r\n    def load_ssim(self):\r\n        if os.path.exists(self.save_file):\r\n            infile = open(self.save_file, 'rb')\r\n            (self.SSIM_THRESHOLD_LIGHT_WHITE, self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_DARK_WHITE,\r\n             self.SSIM_THRESHOLD_DARK_BLACK, self.SSIM_THRESHOLD) = pickle.load(infile)\r\n            infile.close()\r\n            print(self.SSIM_THRESHOLD_LIGHT_WHITE, self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_DARK_WHITE,\r\n                  self.SSIM_THRESHOLD_DARK_BLACK)\r\n            self.ssim_table = [[self.SSIM_THRESHOLD_DARK_BLACK, self.SSIM_THRESHOLD_DARK_WHITE],\r\n                               [self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_LIGHT_WHITE]]\r\n        else:\r\n            print(\"You need to play at least 1 game before starting a game from position.\")\r\n            sys.exit(0)\r\n\r\n    def update_ssim(self, previous_frame, next_frame, move, is_capture, color):\r\n        from_square = chess.square_name(move.from_square)\r\n        to_square = chess.square_name(move.to_square)\r\n        for row in range(8):\r\n            for column in range(8):\r\n                square_name = self.convert_row_column_to_square_name(row, column)\r\n                if square_name not in [from_square, to_square]:\r\n                    continue\r\n                previous_square = self.get_square_image(row, column, previous_frame)\r\n                next_square = self.get_square_image(row, column, next_frame)\r\n                ssim = structural_similarity(next_square, previous_square, channel_axis=-1)\r\n                ssim = ssim + 0.1\r\n                if ssim > self.SSIM_THRESHOLD:\r\n                    self.SSIM_THRESHOLD = ssim\r\n                    print(\"new threshold is \" + str(ssim))\r\n                is_light = int(self.is_light(square_name))\r\n                if (square_name == from_square) or (not is_capture):\r\n                    if ssim > self.ssim_table[is_light][color]:\r\n                        self.ssim_table[is_light][color] = ssim\r\n                        print((is_light, color, ssim))\r\n\r\n    def get_square_image(self, row, column,\r\n                         board_img):\r\n        height, width = board_img.shape[:2]\r\n        minX = int(column * width / 8)\r\n        maxX = int((column + 1) * width / 8)\r\n        minY = int(row * height / 8)\r\n        maxY = int((row + 1) * height / 8)\r\n        square = board_img[minY:maxY, minX:maxX]\r\n        return square\r\n\r\n    def convert_row_column_to_square_name(self, row, column):\r\n        if self.rotation_count == 0:\r\n            number = repr(8 - row)\r\n            letter = str(chr(97 + column))\r\n        elif self.rotation_count == 1:\r\n            number = repr(8 - column)\r\n            letter = str(chr(97 + (7 - row)))\r\n        elif self.rotation_count == 2:\r\n            number = repr(row + 1)\r\n            letter = str(chr(97 + (7 - column)))\r\n        elif self.rotation_count == 3:\r\n            number = repr(column + 1)\r\n            letter = str(chr(97 + row))\r\n        return letter + number\r\n\r\n    def square_region(self, row, column):\r\n        region = set()\r\n        for d_row, d_column in self.d:\r\n            n_row = row + d_row\r\n            n_column = column + d_column\r\n            if not (0 <= n_row < 8):\r\n                continue\r\n            if not (0 <= n_column < 8):\r\n                continue\r\n            region.add((n_row, column))\r\n        return region\r\n\r\n    def is_light(self, square_name):\r\n        if square_name[0] in \"aceg\":\r\n            if square_name[1] in \"1357\":\r\n                return False\r\n            else:\r\n                return True\r\n        else:\r\n            if square_name[1] in \"1357\":\r\n                return True\r\n            else:\r\n                return False\r\n\r\n    def get_potential_moves(self, fgmask, previous_frame, next_frame, chessboard):\r\n        board = [[self.get_square_image(row, column, fgmask).mean() for column in range(8)] for row in range(8)]\r\n        previous_board = [[self.get_square_image(row, column, previous_frame) for column in range(8)] for row in\r\n                          range(8)]\r\n        next_board = [[self.get_square_image(row, column, next_frame) for column in range(8)] for row in\r\n                      range(8)]\r\n        potential_squares = []\r\n        for row in range(8):\r\n            for column in range(8):\r\n                score = board[row][column]\r\n                if score < 10.0:\r\n                    continue\r\n\r\n                ssim = structural_similarity(next_board[row][column],\r\n                                             previous_board[row][column], channel_axis=-1)\r\n                square_name = self.convert_row_column_to_square_name(row, column)\r\n                print(ssim, square_name)\r\n                if ssim > self.SSIM_THRESHOLD:\r\n                    continue\r\n                square = chess.parse_square(square_name)\r\n                piece = chessboard.piece_at(square)\r\n                if piece and piece.color == chessboard.turn:\r\n                    is_light = int(self.is_light(square_name))\r\n                    color = int(piece.color)\r\n                    if ssim > self.ssim_table[is_light][color]:\r\n                        continue\r\n                potential_squares.append((score, row, column, ssim))\r\n\r\n        potential_squares.sort(reverse=True)\r\n        potential_squares_castling = []\r\n        for i in range(min(6, len(potential_squares))):\r\n            score, row, column, ssim = potential_squares[i]\r\n            potential_square = (score, self.convert_row_column_to_square_name(row, column))\r\n            potential_squares_castling.append(potential_square)\r\n        potential_squares = potential_squares[:4]\r\n        potential_moves = []\r\n\r\n        for start_square_score, start_row, start_column, start_ssim in potential_squares:\r\n            start_square_name = self.convert_row_column_to_square_name(start_row, start_column)\r\n            start_square = chess.parse_square(start_square_name)\r\n            start_piece = chessboard.piece_at(start_square)\r\n            if start_piece:\r\n                if start_piece.color != chessboard.turn:\r\n                    continue\r\n            else:\r\n                continue\r\n            start_region = self.square_region(start_row, start_column)\r\n            for arrival_square_score, arrival_row, arrival_column, arrival_ssim in potential_squares:\r\n                if (start_row, start_column) == (arrival_row, arrival_column):\r\n                    continue\r\n                arrival_square_name = self.convert_row_column_to_square_name(arrival_row, arrival_column)\r\n                arrival_square = chess.parse_square(arrival_square_name)\r\n                arrival_piece = chessboard.piece_at(arrival_square)\r\n                if arrival_piece:\r\n                    if arrival_piece.color == chessboard.turn:\r\n                        continue\r\n                else:\r\n                    is_light = int(self.is_light(arrival_square_name))\r\n                    color = int(start_piece.color)\r\n                    if arrival_ssim > self.ssim_table[is_light][color]:\r\n                        continue\r\n                arrival_region = self.square_region(arrival_row, arrival_column)\r\n                region = start_region.union(arrival_region)\r\n                total_square_score = sum(\r\n                    board[row][column] for row, column in region) + start_square_score + arrival_square_score\r\n                potential_moves.append(\r\n                    (total_square_score, start_square_name, arrival_square_name))\r\n\r\n        potential_moves.sort(reverse=True)\r\n\r\n        return potential_squares_castling, potential_moves\r\n"
  },
  {
    "path": "board_calibration.py",
    "content": "import cv2\r\nimport platform\r\nfrom math import inf\r\nimport pickle\r\n\r\nfrom board_calibration_machine_learning import detect_board\r\nfrom helper import rotateMatrix, perspective_transform, edge_detection, euclidean_distance\r\nimport numpy as np\r\nimport sys\r\nfrom tkinter import messagebox\r\nimport tkinter as tk\r\n\r\nfilename = 'constants.bin'\r\ncorner_model = cv2.dnn.readNetFromONNX(\"yolo_corner.onnx\")\r\npiece_model = cv2.dnn.readNetFromONNX(\"cnn_piece.onnx\")\r\ncolor_model = cv2.dnn.readNetFromONNX(\"cnn_color.onnx\")\r\n\r\nwebcam_width = None\r\nwebcam_height = None\r\nfps = None\r\nis_machine_learning = False\r\nshow_info = False\r\ncap_index = 0\r\ncap_api = cv2.CAP_ANY\r\nplatform_name = platform.system()\r\nfor argument in sys.argv:\r\n    if argument == \"show-info\":\r\n        show_info = True\r\n    elif argument.startswith(\"cap=\"):\r\n        cap_index = int(\"\".join(c for c in argument if c.isdigit()))\r\n        if platform_name == \"Darwin\":\r\n            cap_api = cv2.CAP_AVFOUNDATION\r\n        elif platform_name == \"Linux\":\r\n            cap_api = cv2.CAP_V4L2\r\n        else:\r\n            cap_api = cv2.CAP_DSHOW\r\n    elif argument == \"ml\":\r\n        is_machine_learning = True\r\n    elif argument.startswith(\"width=\"):\r\n        webcam_width = int(argument[len(\"width=\"):])\r\n    elif argument.startswith(\"height=\"):\r\n        webcam_height = int(argument[len(\"height=\"):])\r\n    elif argument.startswith(\"fps=\"):\r\n        fps = int(argument[len(\"fps=\"):])\r\n\r\nif show_info:\r\n    root = tk.Tk()\r\n    root.withdraw()\r\n    messagebox.showinfo(\"Board Calibration\",\r\n                        'Board calibration will start. It should detect corners of the chess board almost immediately. If it does not, you should press key \"q\" to stop board calibration and change webcam/board position.')\r\n\r\n\r\ndef mark_corners(frame, augmented_corners, rotation_count):\r\n    height, width = frame.shape[:2]\r\n    if rotation_count == 1:\r\n        frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)\r\n    elif rotation_count == 2:\r\n        frame = cv2.rotate(frame, cv2.ROTATE_180)\r\n    elif rotation_count == 3:\r\n        frame = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)\r\n\r\n    for i in range(len(augmented_corners)):\r\n        for j in range(len(augmented_corners[i])):\r\n            if rotation_count == 0:\r\n                index = str(i) + \",\" + str(j)\r\n                corner = augmented_corners[i][j]\r\n            elif rotation_count == 1:\r\n                index = str(j) + \",\" + str(8 - i)\r\n                corner = (height - augmented_corners[i][j][1], augmented_corners[i][j][0])\r\n            elif rotation_count == 2:\r\n                index = str(8 - i) + \",\" + str(8 - j)\r\n                corner = (width - augmented_corners[i][j][0], height - augmented_corners[i][j][1])\r\n            elif rotation_count == 3:\r\n                index = str(8 - j) + \",\" + str(i)\r\n                corner = (augmented_corners[i][j][1], width - augmented_corners[i][j][0])\r\n            corner = (int(corner[0]), int(corner[1]))\r\n            frame = cv2.putText(frame, index, corner, cv2.FONT_HERSHEY_SIMPLEX,\r\n                                0.5, (255, 0, 0), 1, cv2.LINE_AA)\r\n\r\n    return frame\r\n\r\n\r\ncap = cv2.VideoCapture(cap_index, cap_api)\r\nif webcam_width is not None:\r\n    cap.set(cv2.CAP_PROP_FRAME_WIDTH, webcam_width)\r\nif webcam_height is not None:\r\n    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, webcam_height)\r\nif fps is not None:\r\n    cap.set(cv2.CAP_PROP_FPS, fps)\r\n\r\nif not cap.isOpened():\r\n    print(\"Couldn't open your webcam. Please check your webcam connection.\")\r\n    sys.exit(0)\r\nboard_dimensions = (7, 7)\r\n\r\nfor _ in range(10):\r\n    ret, frame = cap.read()\r\n    if ret == False:\r\n        print(\"Error reading frame. Please check your webcam connection.\")\r\n        continue\r\n\r\nwhile True:\r\n    ret, frame = cap.read()\r\n    if ret == False:\r\n        print(\"Error reading frame. Please check your webcam connection.\")\r\n        continue\r\n    if is_machine_learning:\r\n        result = detect_board(frame, corner_model, piece_model, color_model)\r\n        if result:\r\n            pts1, side_view_compensation, rotation_count = result\r\n            outfile = open(filename, 'wb')\r\n            pickle.dump([is_machine_learning, [pts1, side_view_compensation, rotation_count]], outfile)\r\n            outfile.close()\r\n            if show_info:\r\n                if platform_name == \"Darwin\":\r\n                    root = tk.Tk()\r\n                    root.withdraw()\r\n                messagebox.showinfo(\r\n                    \"Chess Board Detected\",\r\n                    \"Please ensure your chess board is correctly positioned and detected. \"\r\n                    \"Guiding lines will be drawn to mark the board's edges:\\n\"\r\n                    \"- The line near the white pieces will be blue.\\n\"\r\n                    \"- The line near the black pieces will be green.\\n\\n\"\r\n                    \"Press any key to exit once you've confirmed the board setup.\"\r\n                )\r\n                root.destroy()\r\n            cv2.imshow('frame', frame)\r\n            cv2.waitKey(0)\r\n            cap.release()\r\n            cv2.destroyAllWindows()\r\n            sys.exit(0)\r\n    else:\r\n        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n        retval, corners = cv2.findChessboardCorners(gray, patternSize=board_dimensions)\r\n        if retval:\r\n            if show_info:\r\n                if platform_name == \"Darwin\":\r\n                    root = tk.Tk()\r\n                    root.withdraw()\r\n                messagebox.showinfo(\"Chess Board Detected\",\r\n                                    'Please check that corners of your chess board are correctly detected. The square covered by points (0,0), (0,1),(1,0) and (1,1) should be a8. You can rotate the image by pressing key \"r\" to adjust that. Press key \"q\" to save detected chess board corners and finish board calibration.')\r\n                root.destroy()\r\n            if corners[0][0][0] > corners[-1][0][0]:  # corners returned in reverse order\r\n                corners = corners[::-1]\r\n            minX, maxX, minY, maxY = inf, -inf, inf, -inf\r\n            augmented_corners = []\r\n            row = []\r\n            for i in range(6):\r\n                corner1 = corners[i]\r\n                corner2 = corners[i + 8]\r\n                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])\r\n                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])\r\n                row.append((x, y))\r\n\r\n            for i in range(4, 7):\r\n                corner1 = corners[i]\r\n                corner2 = corners[i + 6]\r\n                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])\r\n                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])\r\n                row.append((x, y))\r\n\r\n            augmented_corners.append(row)\r\n\r\n            for i in range(7):\r\n                row = []\r\n                corner1 = corners[i * 7]\r\n                corner2 = corners[i * 7 + 1]\r\n                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])\r\n                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])\r\n                row.append((x, y))\r\n\r\n                for corner in corners[i * 7:(i + 1) * 7]:\r\n                    x = corner[0][0]\r\n                    y = corner[0][1]\r\n                    row.append((x, y))\r\n\r\n                corner1 = corners[i * 7 + 6]\r\n                corner2 = corners[i * 7 + 5]\r\n                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])\r\n                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])\r\n                row.append((x, y))\r\n                augmented_corners.append(row)\r\n\r\n            row = []\r\n            for i in range(6):\r\n                corner1 = corners[42 + i]\r\n                corner2 = corners[42 + i - 6]\r\n                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])\r\n                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])\r\n                row.append((x, y))\r\n\r\n            for i in range(4, 7):\r\n                corner1 = corners[42 + i]\r\n                corner2 = corners[42 + i - 8]\r\n                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])\r\n                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])\r\n                row.append((x, y))\r\n\r\n            augmented_corners.append(row)\r\n\r\n            while augmented_corners[0][0][0] > augmented_corners[8][8][0] or augmented_corners[0][0][1] > \\\r\n                    augmented_corners[8][8][1]:\r\n                rotateMatrix(augmented_corners)\r\n\r\n            pts1 = np.float32([list(augmented_corners[0][0]), list(augmented_corners[8][0]), list(augmented_corners[0][8]),\r\n                               list(augmented_corners[8][8])])\r\n            empty_board = perspective_transform(frame, pts1)\r\n            edges = edge_detection(empty_board)\r\n            # cv2.imshow(\"edge\", edges)\r\n            # cv2.waitKey(0)\r\n            kernel = np.ones((7, 7), np.uint8)\r\n            edges = cv2.dilate(edges, kernel, iterations=1)\r\n            roi_mask = cv2.bitwise_not(edges)\r\n            # cv2.imshow(\"edge\", edges)\r\n            # cv2.waitKey(0)\r\n            # cv2.imshow(\"roi\", roi_mask)\r\n            # cv2.waitKey(0)\r\n            roi_mask[:7, :] = 0\r\n            roi_mask[:, :7] = 0\r\n            roi_mask[-7:, :] = 0\r\n            roi_mask[:, -7:] = 0\r\n            # cv2.imshow(\"roi\", roi_mask)\r\n            # cv2.waitKey(0)\r\n            # cv2.imwrite(\"empty_board.jpg\", empty_board)\r\n\r\n            rotation_count = 0\r\n            while True:\r\n                cv2.imshow('frame', mark_corners(frame.copy(), augmented_corners, rotation_count))\r\n                response = cv2.waitKey(0)\r\n                if response & 0xFF == ord('r'):\r\n                    rotation_count += 1\r\n                    rotation_count %= 4\r\n                elif response & 0xFF == ord('q'):\r\n                    break\r\n            break\r\n\r\n    cv2.imshow('frame', frame)\r\n    if cv2.waitKey(3) & 0xFF == ord('q'):\r\n        break\r\n\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n\r\nfirst_row = euclidean_distance(augmented_corners[1][1], augmented_corners[1][7])\r\nlast_row = euclidean_distance(augmented_corners[7][1], augmented_corners[7][7])\r\nfirst_column = euclidean_distance(augmented_corners[1][1], augmented_corners[7][1])\r\nlast_column = euclidean_distance(augmented_corners[1][7], augmented_corners[7][7])\r\n\r\nif abs(first_row - last_row) >= abs(first_column - last_column):\r\n    if first_row >= last_row:\r\n        side_view_compensation = (1, 0)\r\n    else:\r\n        side_view_compensation = (-1, 0)\r\nelse:\r\n    if first_column >= last_column:\r\n        side_view_compensation = (0, -1)\r\n    else:\r\n        side_view_compensation = (0, 1)\r\n\r\nprint(\"Side view compensation\" + str(side_view_compensation))\r\nprint(\"Rotation count \" + str(rotation_count))\r\n\r\noutfile = open(filename, 'wb')\r\npickle.dump([is_machine_learning, [augmented_corners, side_view_compensation, rotation_count, roi_mask]], outfile)\r\noutfile.close()\r\n"
  },
  {
    "path": "board_calibration_machine_learning.py",
    "content": "import numpy as np\r\nimport cv2\r\n\r\nfrom helper import euclidean_distance, perspective_transform, predict\r\n\r\n\r\ndef detect_board(original_image, corner_model, piece_model, color_model):\r\n    [height, width, _] = original_image.shape\r\n\r\n    length = max((height, width))\r\n    image = np.zeros((length, length, 3), np.uint8)\r\n    image[0:height, 0:width] = original_image\r\n\r\n    scale = length / 640\r\n\r\n    blob = cv2.dnn.blobFromImage(image, scalefactor=1 / 255, size=(640, 640), swapRB=True)\r\n    corner_model.setInput(blob)\r\n    outputs = corner_model.forward()\r\n    outputs = np.array([cv2.transpose(outputs[0])])\r\n    rows = outputs.shape[1]\r\n\r\n    boxes = []\r\n    scores = []\r\n    class_ids = []\r\n\r\n    for i in range(rows):\r\n        classes_scores = outputs[0][i][4:]\r\n        (minScore, maxScore, minClassLoc, (x, maxClassIndex)) = cv2.minMaxLoc(classes_scores)\r\n        if maxScore >= 0.25:\r\n            box = [\r\n                outputs[0][i][0] - (0.5 * outputs[0][i][2]), outputs[0][i][1] - (0.5 * outputs[0][i][3]),\r\n                outputs[0][i][2], outputs[0][i][3]]\r\n            boxes.append(box)\r\n            scores.append(maxScore)\r\n            class_ids.append(maxClassIndex)\r\n\r\n    result_boxes = cv2.dnn.NMSBoxes(boxes, scores, 0.25, 0.45, 0.5)\r\n\r\n    detections = []\r\n    for i in range(len(result_boxes)):\r\n        index = result_boxes[i]\r\n        box = boxes[index]\r\n        detection = {\r\n            'confidence': scores[index],\r\n            'box': box,\r\n        }\r\n        detections.append(detection)\r\n\r\n    if len(detections) < 4:\r\n        return\r\n\r\n    detections.sort(key=lambda detection: detection['confidence'], reverse=True)\r\n    detections = detections[:4]\r\n\r\n    middle_points = []\r\n    for detection in detections:\r\n        box = detection['box']\r\n        x, y, w, h = box\r\n        middle_x = (x + (w / 2)) * scale\r\n        middle_y = (y + (h / 2)) * scale\r\n        middle_points.append([middle_x, middle_y])\r\n\r\n    minX = min(point[0] for point in middle_points)\r\n    minY = min(point[1] for point in middle_points)\r\n    maxX = max(point[0] for point in middle_points)\r\n    maxY = max(point[1] for point in middle_points)\r\n\r\n    top_left = min(middle_points, key=lambda point: euclidean_distance(point, [minX, minY]))\r\n    top_right = min(middle_points, key=lambda point: euclidean_distance(point, [maxX, minY]))\r\n    bottom_left = min(middle_points, key=lambda point: euclidean_distance(point, [minX, maxY]))\r\n    bottom_right = min(middle_points, key=lambda point: euclidean_distance(point, [maxX, maxY]))\r\n\r\n    first_row = euclidean_distance(top_left, top_right)\r\n    last_row = euclidean_distance(bottom_left, bottom_right)\r\n    first_column = euclidean_distance(top_left, bottom_left)\r\n    last_column = euclidean_distance(top_right, bottom_right)\r\n\r\n    if abs(first_row - last_row) >= abs(first_column - last_column):\r\n        if first_row >= last_row:\r\n            side_view_compensation = (1, 0)\r\n        else:\r\n            side_view_compensation = (-1, 0)\r\n    else:\r\n        if first_column >= last_column:\r\n            side_view_compensation = (0, -1)\r\n        else:\r\n            side_view_compensation = (0, 1)\r\n\r\n    pts1 = np.float32([top_left, bottom_left, top_right, bottom_right])\r\n    board_image = perspective_transform(original_image, pts1)\r\n\r\n    squares_to_check_for_rotation_count = [\r\n        [(0, i) for i in range(7)],\r\n        [(i, 0) for i in range(7)],\r\n        [(7, i) for i in range(7)],\r\n        [(i, 7) for i in range(7)],\r\n    ]\r\n\r\n    rotation_count = 0\r\n    score = 0\r\n    for i in range(len(squares_to_check_for_rotation_count)):\r\n        current_score = 0\r\n        for row, column in squares_to_check_for_rotation_count[i]:\r\n            height, width = board_image.shape[:2]\r\n            minX = int(column * width / 8)\r\n            maxX = int((column + 1) * width / 8)\r\n            minY = int(row * height / 8)\r\n            maxY = int((row + 1) * height / 8)\r\n            square_image = board_image[minY:maxY, minX:maxX]\r\n            is_piece = predict(square_image, piece_model)\r\n            if is_piece:\r\n                is_white = predict(square_image, color_model)\r\n                if not is_white:\r\n                    current_score += 1\r\n        if current_score > score:\r\n            score = current_score\r\n            rotation_count = i\r\n\r\n    green_color = (0, 255, 0)\r\n    blue_color = (255, 0, 0)\r\n    red_color = (0, 0, 255)\r\n\r\n    top_left, top_right, bottom_left, bottom_right = [(int(point[0]), int(point[1])) for point in\r\n                                                      (top_left, top_right, bottom_left, bottom_right)]\r\n\r\n    if rotation_count == 0:\r\n        cv2.line(original_image, top_left, top_right, green_color, 5)\r\n        cv2.line(original_image, top_right, bottom_right, red_color, 5)\r\n        cv2.line(original_image, bottom_left, bottom_right, blue_color, 5)\r\n        cv2.line(original_image, top_left, bottom_left, red_color, 5)\r\n    elif rotation_count == 1:\r\n        cv2.line(original_image, top_left, top_right, red_color, 5)\r\n        cv2.line(original_image, top_right, bottom_right, blue_color, 5)\r\n        cv2.line(original_image, bottom_left, bottom_right, red_color, 5)\r\n        cv2.line(original_image, top_left, bottom_left, green_color, 5)\r\n    elif rotation_count == 2:\r\n        cv2.line(original_image, top_left, top_right, blue_color, 5)\r\n        cv2.line(original_image, top_right, bottom_right, red_color, 5)\r\n        cv2.line(original_image, bottom_left, bottom_right, green_color, 5)\r\n        cv2.line(original_image, top_left, bottom_left, red_color, 5)\r\n    elif rotation_count == 3:\r\n        cv2.line(original_image, top_left, top_right, red_color, 5)\r\n        cv2.line(original_image, top_right, bottom_right, green_color, 5)\r\n        cv2.line(original_image, bottom_left, bottom_right, red_color, 5)\r\n        cv2.line(original_image, top_left, bottom_left, blue_color, 5)\r\n\r\n    print(\"Side view compensation\" + str(side_view_compensation))\r\n    print(\"Rotation count \" + str(rotation_count))\r\n    return pts1, side_view_compensation, rotation_count\r\n"
  },
  {
    "path": "chessboard_detection.py",
    "content": "import sys\r\n\r\nimport numpy as np\r\nimport cv2\r\nimport pyautogui\r\nimport mss\r\nfrom statistics import median\r\n\r\n\r\nclass Board_position:\r\n    def __init__(self, minX, minY, maxX, maxY):\r\n        self.minX = minX\r\n        self.minY = minY\r\n        self.maxX = maxX\r\n        self.maxY = maxY\r\n\r\n\r\ndef find_chessboard():\r\n    screenshot_shape = np.array(pyautogui.screenshot()).shape\r\n    monitor = {'top': 0, 'left': 0, 'width': screenshot_shape[1], 'height': screenshot_shape[0]}\r\n    sct = mss.mss()\r\n    large_image = np.array(np.array(sct.grab(monitor)))\r\n    large_image = cv2.cvtColor(large_image, cv2.COLOR_BGR2RGB)\r\n    method = cv2.TM_SQDIFF_NORMED\r\n    white_image = cv2.imread(\"white.JPG\")\r\n    black_image = cv2.imread(\"black.JPG\")\r\n    result_white = cv2.matchTemplate(white_image, large_image, method)\r\n    result_black = cv2.matchTemplate(black_image, large_image, method)\r\n    we_are_white = True\r\n    result = result_white\r\n    small_image = white_image\r\n    if cv2.minMaxLoc(result_black)[0] < cv2.minMaxLoc(result_white)[0]:  # If black is more accurate:\r\n        result = result_black\r\n        we_are_white = False\r\n        small_image = black_image\r\n    minimum_value, maximum_value, minimum_location, maximum_location = cv2.minMaxLoc(result)\r\n\r\n    minX, minY = minimum_location\r\n    maxX = minX + small_image.shape[1]\r\n    maxY = minY + small_image.shape[0]\r\n\r\n    position = Board_position(minX, minY, maxX, maxY)\r\n    return position, we_are_white\r\n\r\n\r\ndef auto_find_chessboard():\r\n    screenshot_shape = np.array(pyautogui.screenshot()).shape\r\n    monitor = {'top': 0, 'left': 0, 'width': screenshot_shape[1], 'height': screenshot_shape[0]}\r\n    sct = mss.mss()\r\n    img = np.array(np.array(sct.grab(monitor)))\r\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n    is_found, current_chessboard_image, minX, minY, maxX, maxY, test_image = find_chessboard_from_image(img)\r\n    if not is_found:\r\n        sys.exit(0)\r\n    position = Board_position(minX, minY, maxX, maxY)\r\n    return position, is_white_on_bottom(current_chessboard_image)\r\n\r\n\r\ndef is_white_on_bottom(current_chessboard_image):\r\n    m1 = get_square_image(0, 0, current_chessboard_image).mean()\r\n    m2 = get_square_image(7, 7, current_chessboard_image).mean()\r\n    if m1 < m2:\r\n        return True\r\n    else:\r\n        return False\r\n\r\n\r\ndef get_square_image(row, column, board_img):\r\n    height, width = board_img.shape\r\n    minX = int(column * width / 8)\r\n    maxX = int((column + 1) * width / 8)\r\n    minY = int(row * width / 8)\r\n    maxY = int((row + 1) * width / 8)\r\n    square = board_img[minY:maxY, minX:maxX]\r\n    square_without_borders = square[3:-3, 3:-3]\r\n    return square_without_borders\r\n\r\n\r\ndef prepare(lines, kernel_close, kernel_open):\r\n    ret, lines = cv2.threshold(lines, 30, 255, cv2.THRESH_BINARY)\r\n    lines = cv2.morphologyEx(lines, cv2.MORPH_CLOSE, kernel_close)\r\n    lines = cv2.morphologyEx(lines, cv2.MORPH_OPEN, kernel_open)\r\n    return lines\r\n\r\n\r\ndef prepare_vertical(lines):\r\n    kernel_close = np.ones((3, 1), np.uint8)\r\n    kernel_open = np.ones((50, 1), np.uint8)\r\n    return prepare(lines, kernel_close, kernel_open)\r\n\r\n\r\ndef prepare_horizontal(lines):\r\n    kernel_close = np.ones((1, 3), np.uint8)\r\n    kernel_open = np.ones((1, 50), np.uint8)\r\n    return prepare(lines, kernel_close, kernel_open)\r\n\r\n\r\ndef find_chessboard_from_image(img):\r\n    image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n    kernelH = np.array([[-1, 1]])\r\n    kernelV = np.array([[-1], [1]])\r\n    vertical_lines = np.absolute(cv2.filter2D(image.astype('float'), -1, kernelH))\r\n    image_vertical = prepare_vertical(vertical_lines)\r\n    horizontal_lines = np.absolute(cv2.filter2D(image.astype('float'), -1, kernelV))\r\n    image_horizontal = prepare_horizontal(horizontal_lines)\r\n    vertical_lines = cv2.HoughLinesP(image_vertical.astype(np.uint8), 1, np.pi / 180, 100, minLineLength=100,\r\n                                     maxLineGap=10)\r\n    horizontal_lines = cv2.HoughLinesP(image_horizontal.astype(np.uint8), 1, np.pi / 180, 100, minLineLength=100,\r\n                                       maxLineGap=10)\r\n    v_count = [0 for _ in range(len(vertical_lines))]\r\n    h_count = [0 for _ in range(len(horizontal_lines))]\r\n    for i, line in enumerate(vertical_lines):\r\n        x1, y1, x2, y2 = line[0]\r\n        for j, other_line in enumerate(horizontal_lines):\r\n            x3, y3, x4, y4 = other_line[0]\r\n            if ((x3 <= x1 <= x4) or (x4 <= x1 <= x3)) and ((y2 <= y3 <= y1) or (y1 <= y3 <= y2)):\r\n                v_count[i] += 1\r\n                h_count[j] += 1\r\n    v_board = []\r\n    h_board = []\r\n    for i, line in enumerate(vertical_lines):\r\n        if v_count[i] <= 6:\r\n            continue\r\n        v_board.append(line)\r\n\r\n    for i, line in enumerate(horizontal_lines):\r\n        if h_count[i] <= 6:\r\n            continue\r\n        h_board.append(line)\r\n\r\n    if v_board and h_board:\r\n        y_min = int(median(min(v[0][1], v[0][3]) for v in v_board))\r\n        y_max = int(median(max(v[0][1], v[0][3]) for v in v_board))\r\n        x_min = int(median(min(h[0][0], h[0][2]) for h in h_board))\r\n        x_max = int(median(max(h[0][0], h[0][2]) for h in h_board))\r\n        if abs((x_max - x_min) - (y_max - y_min)) > 3:\r\n            print(\"Board is not square.\")\r\n            return False, image, 0, 0, 0, 0, image\r\n        board = image[y_min:y_max, x_min:x_max]\r\n        dim = (800, 800)\r\n        resized_board = cv2.resize(board, dim,\r\n                                   interpolation=cv2.INTER_AREA)\r\n        # cv2.imwrite(\"board.jpg\", resized_board)\r\n        return True, resized_board, int(x_min), int(y_min), int(x_max), int(y_max), resized_board\r\n    else:\r\n        print(\"Chess board of online game could not be found.\")\r\n        return False, image, 0, 0, 0, 0, image\r\n"
  },
  {
    "path": "classifier.py",
    "content": "import numpy as np\r\nimport cv2\r\nfrom math import pi\r\n\r\n\r\n# https://github.com/youyexie/Chess-Piece-Recognition-using-Oriented-Chamfer-Matching-with-a-Comparison-to-CNN\r\nclass Classifier:\r\n    def __init__(self, game_state):\r\n        self.dim = (480, 480)\r\n        self.img = cv2.resize(game_state.previous_chessboard_image, self.dim,\r\n                              interpolation=cv2.INTER_AREA)\r\n        self.img_x, self.img_y = self.unit_gradients(self.img)\r\n        self.edges = cv2.Canny(self.img, 100, 200)\r\n        self.inverted_edges = cv2.bitwise_not(self.edges)\r\n        self.dist = cv2.distanceTransform(self.inverted_edges, cv2.DIST_L2, 3)\r\n        self.dist_board = [[self.get_square_image(row, column, self.dist) for column in range(8)] for row in range(8)]\r\n        self.edge_board = [[self.get_square_image(row, column, self.edges) for column in range(8)] for row in range(8)]\r\n        self.gradient_x = [[self.get_square_image(row, column, self.img_x) for column in range(8)] for row in range(8)]\r\n        self.gradient_y = [[self.get_square_image(row, column, self.img_y) for column in range(8)] for row in range(8)]\r\n\r\n        def intensity(x):\r\n            return self.edge_board[x[0]][x[1]].mean()\r\n\r\n        pawn_templates = [max([(1, i) for i in range(8)], key=intensity),\r\n                          max([(6, i) for i in range(8)], key=intensity)]\r\n\r\n        self.templates = [pawn_templates] + [[(0, i), (7, i)] for i in range(5)]\r\n\r\n        if intensity((0, 6)) > intensity((0, 1)):\r\n            self.templates[2][0] = (0, 6)\r\n\r\n        if intensity((7, 6)) > intensity((7, 1)):\r\n            self.templates[2][1] = (7, 6)\r\n\r\n        self.piece_symbol = [\".\", \"p\", \"r\", \"n\", \"b\", \"q\", \"k\"]\r\n        if game_state.we_play_white == False:\r\n            self.piece_symbol[-1], self.piece_symbol[-2] = self.piece_symbol[-2], self.piece_symbol[-1]\r\n\r\n    def classify(self, img):\r\n        img = cv2.resize(img, self.dim,\r\n                         interpolation=cv2.INTER_AREA)\r\n\r\n        img_x, img_y = self.unit_gradients(img)\r\n        edges = cv2.Canny(img, 100, 200)\r\n        inverted_edges = cv2.bitwise_not(edges)\r\n        dist = cv2.distanceTransform(inverted_edges, cv2.DIST_L2, 3)\r\n        dist_board = [[self.get_square_image(row, column, dist) for column in range(8)] for row in range(8)]\r\n        gradient_x = [[self.get_square_image(row, column, img_x) for column in range(8)] for row in range(8)]\r\n        gradient_y = [[self.get_square_image(row, column, img_y) for column in range(8)] for row in range(8)]\r\n\r\n        result = []\r\n        for row in range(8):\r\n            row_result = []\r\n            for col in range(8):\r\n                d = dist_board[row][col]\r\n                template_scores = []\r\n                for piece in self.templates:\r\n                    piece_scores = []\r\n                    for tr, tc in piece:\r\n                        t = self.edge_board[tr][tc]\r\n                        e = t / 255.0\r\n                        e_c = e.sum()\r\n                        r_d = np.multiply(d, e).sum() / e_c\r\n\r\n                        dp = np.multiply(self.gradient_x[tr][tc], gradient_x[row][col]) + np.multiply(\r\n                            self.gradient_y[tr][tc],\r\n                            gradient_y[row][col])\r\n                        dp = np.abs(dp)\r\n                        dp[dp > 1.0] = 1.0\r\n                        angle_difference = np.arccos(dp)\r\n                        r_o = np.multiply(angle_difference, e).sum() / (e_c * (pi / 2))\r\n                        piece_scores.append(r_d * 0.5 + r_o * 0.5)\r\n                    template_scores.append(min(piece_scores))\r\n                min_score = float(\"inf\")\r\n                min_index = -1\r\n                for i in range(len(template_scores)):\r\n                    if min_score > template_scores[i]:\r\n                        min_score = template_scores[i]\r\n                        min_index = i\r\n                if min_score < 2.0:\r\n                    row_result.append(self.piece_symbol[min_index + 1])\r\n                else:\r\n                    row_result.append(self.piece_symbol[0])\r\n\r\n            result.append(row_result)\r\n        return result\r\n\r\n    def unit_gradients(self, gray):\r\n        sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)\r\n        sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)\r\n        mag, direction = cv2.cartToPolar(sobelx, sobely)\r\n        mag[mag == 0] = 1\r\n        unit_x = sobelx / mag\r\n        unit_y = sobely / mag\r\n        return unit_x, unit_y\r\n\r\n    def get_square_image(self, row, column,\r\n                         board_img):\r\n        height, width = board_img.shape[:2]\r\n        minX = int(column * width / 8)\r\n        maxX = int((column + 1) * width / 8)\r\n        minY = int(row * height / 8)\r\n        maxY = int((row + 1) * height / 8)\r\n        square = board_img[minY:maxY, minX:maxX]\r\n        square_without_borders = square[3:-3, 3:-3]\r\n        return square_without_borders\r\n"
  },
  {
    "path": "commentator.py",
    "content": "from threading import Thread\r\nimport chess\r\nimport mss\r\nimport numpy as np\r\nimport cv2\r\nimport time\r\nfrom classifier import Classifier\r\n\r\n\r\nclass Commentator_thread(Thread):\r\n\r\n    def __init__(self, *args, **kwargs):\r\n        super(Commentator_thread, self).__init__(*args, **kwargs)\r\n        self.speech_thread = None\r\n        self.game_state = Game_state()\r\n        self.comment_me = None\r\n        self.comment_opponent = None\r\n        self.language = None\r\n        self.classifier = None\r\n\r\n    def run(self):\r\n        self.game_state.sct = mss.mss()\r\n        resized_chessboard = self.game_state.get_chessboard()\r\n        self.game_state.previous_chessboard_image = resized_chessboard\r\n        self.game_state.classifier = Classifier(self.game_state)\r\n\r\n        while not self.game_state.board.is_game_over():\r\n            is_my_turn = (self.game_state.we_play_white) == (self.game_state.board.turn == chess.WHITE)\r\n            found_move, move = self.game_state.register_move_if_needed()\r\n            if found_move and ((self.comment_me and is_my_turn) or (self.comment_opponent and (not is_my_turn))):\r\n                self.speech_thread.put_text(self.language.comment(self.game_state.board, move))\r\n\r\n\r\nclass Game_state:\r\n\r\n    def __init__(self):\r\n        self.game_thread = None\r\n        self.we_play_white = None\r\n        self.previous_chessboard_image = None\r\n        self.board = chess.Board()\r\n        self.board_position_on_screen = None\r\n        self.sct = mss.mss()\r\n        self.classifier = None\r\n        self.registered_moves = []\r\n        self.resign_or_draw = False\r\n        self.variant = 'standard'\r\n\r\n    def get_chessboard(self):\r\n        position = self.board_position_on_screen\r\n        monitor = {'top': 0, 'left': 0, 'width': position.maxX + 10, 'height': position.maxY + 10}\r\n        img = np.array(np.array(self.sct.grab(monitor)))\r\n        image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n        dim = (800, 800)\r\n        resizedChessBoard = cv2.resize(image[position.minY:position.maxY, position.minX:position.maxX], dim,\r\n                                       interpolation=cv2.INTER_AREA)\r\n        return resizedChessBoard\r\n\r\n    def get_square_image(self, row, column,\r\n                         board_img):\r\n        height, width = board_img.shape\r\n        minX = int(column * width / 8)\r\n        maxX = int((column + 1) * width / 8)\r\n        minY = int(row * width / 8)\r\n        maxY = int((row + 1) * width / 8)\r\n        square = board_img[minY:maxY, minX:maxX]\r\n        square_without_borders = square[6:-6, 6:-6]\r\n        return square_without_borders\r\n\r\n    def can_image_correspond_to_chessboard(self, move, result):\r\n        self.board.push(move)\r\n        squares = chess.SquareSet(chess.BB_ALL)\r\n        for square in squares:\r\n            row = chess.square_rank(square)\r\n            column = chess.square_file(square)\r\n            piece = self.board.piece_at(square)\r\n            shouldBeEmpty = (piece == None)\r\n\r\n            if self.we_play_white == True:\r\n                rowOnImage = 7 - row\r\n                columnOnImage = column\r\n            else:\r\n                rowOnImage = row\r\n                columnOnImage = 7 - column\r\n\r\n            isEmpty = result[rowOnImage][columnOnImage] == '.'\r\n            if isEmpty != shouldBeEmpty:\r\n                self.board.pop()\r\n                # print(\"Problem with : \", self.board.uci(move), \" the square \",\r\n                #      self.convert_row_column_to_square_name(row, column), \"should \",\r\n                #      'be empty' if shouldBeEmpty else 'contain a piece')\r\n                return False\r\n            if piece and (piece.symbol().lower() != result[rowOnImage][columnOnImage]):\r\n                self.board.pop()\r\n                # print(piece.symbol(), result[rowOnImage][columnOnImage],\r\n                #      self.convert_row_column_to_square_name(rowOnImage, columnOnImage))\r\n                return False\r\n        self.board.pop()\r\n        return True\r\n\r\n    def find_premove(self, result):\r\n        start_squares = []\r\n        squares = chess.SquareSet(chess.BB_ALL)\r\n        for square in squares:\r\n            row = chess.square_rank(square)\r\n            column = chess.square_file(square)\r\n            piece = self.board.piece_at(square)\r\n\r\n            if self.we_play_white == True:\r\n                rowOnImage = 7 - row\r\n                columnOnImage = column\r\n            else:\r\n                rowOnImage = row\r\n                columnOnImage = 7 - column\r\n\r\n            isEmpty = result[rowOnImage][columnOnImage] == '.'\r\n            if piece and isEmpty:\r\n                start_squares.append(square)\r\n        return squares\r\n\r\n    def get_valid_move(self, potential_starts, potential_arrivals, current_chessboard_image):\r\n        result = self.classifier.classify(current_chessboard_image)\r\n        valid_move_string = \"\"\r\n        for start in potential_starts:\r\n            if valid_move_string:\r\n                break\r\n            for arrival in potential_arrivals:\r\n                if valid_move_string:\r\n                    break\r\n                if start == arrival:\r\n                    continue\r\n                uci_move = start + arrival\r\n                try:\r\n                    move = chess.Move.from_uci(uci_move)\r\n                except:\r\n                    continue\r\n\r\n                if move in self.board.legal_moves:\r\n                    if self.can_image_correspond_to_chessboard(move,\r\n                                                               result):\r\n                        valid_move_string = uci_move\r\n                else:\r\n                    r, c = self.convert_square_name_to_row_column(arrival)\r\n                    if result[r][c] not in [\"q\", \"r\", \"b\", \"n\"]:\r\n                        continue\r\n                    uci_move_promoted = uci_move + result[r][c]\r\n                    promoted_move = chess.Move.from_uci(uci_move_promoted)\r\n                    if promoted_move in self.board.legal_moves:\r\n                        if self.can_image_correspond_to_chessboard(promoted_move,\r\n                                                                   result):\r\n                            valid_move_string = uci_move_promoted\r\n\r\n        # Detect castling king side with white\r\n        if (\"e1\" in potential_starts) and (\"h1\" in potential_starts) and (\"f1\" in potential_arrivals) and (\r\n                \"g1\" in potential_arrivals) and (chess.Move.from_uci(\"e1g1\") in self.board.legal_moves):\r\n            if (self.board.peek() != chess.Move.from_uci(\"e1g1\")) and \\\r\n                    self.can_image_correspond_to_chessboard(chess.Move.from_uci(\"e1g1\"), result):\r\n                valid_move_string = \"e1g1\"\r\n\r\n        # Detect castling queen side with white\r\n        if (\"e1\" in potential_starts) and (\"a1\" in potential_starts) and (\"c1\" in potential_arrivals) and (\r\n                \"d1\" in potential_arrivals) and (chess.Move.from_uci(\"e1c1\") in self.board.legal_moves):\r\n            if (self.board.peek() != chess.Move.from_uci(\"e1c1\")) and \\\r\n                    self.can_image_correspond_to_chessboard(chess.Move.from_uci(\"e1c1\"), result):\r\n                valid_move_string = \"e1c1\"\r\n\r\n        # Detect castling king side with black\r\n        if (\"e8\" in potential_starts) and (\"h8\" in potential_starts) and (\"f8\" in potential_arrivals) and (\r\n                \"g8\" in potential_arrivals) and (chess.Move.from_uci(\"e8g8\") in self.board.legal_moves):\r\n            if (self.board.peek() != chess.Move.from_uci(\"e8g8\")) and self.can_image_correspond_to_chessboard(\r\n                    chess.Move.from_uci(\"e8g8\"), result):\r\n                valid_move_string = \"e8g8\"\r\n\r\n        # Detect castling queen side with black\r\n        if (\"e8\" in potential_starts) and (\"a8\" in potential_starts) and (\"c8\" in potential_arrivals) and (\r\n                \"d8\" in potential_arrivals) and (chess.Move.from_uci(\"e8c8\") in self.board.legal_moves):\r\n            if (self.board.peek() != chess.Move.from_uci(\"e8c8\")) and self.can_image_correspond_to_chessboard(\r\n                    chess.Move.from_uci(\"e8c8\"), result):\r\n                valid_move_string = \"e8c8\"\r\n\r\n        if not valid_move_string:  # Search for premove\r\n            premove_starts = self.find_premove(result)\r\n            for start_square in premove_starts:\r\n                for move in self.board.legal_moves:\r\n                    if move.from_square == start_square:\r\n                        if self.can_image_correspond_to_chessboard(move, result):\r\n                            return move.uci()\r\n\r\n        return valid_move_string\r\n\r\n    def has_square_image_changed(self, old_square,\r\n                                 new_square):\r\n        diff = cv2.absdiff(old_square, new_square)\r\n        if diff.mean() > 8:\r\n            return True\r\n        else:\r\n            return False\r\n\r\n    def convert_row_column_to_square_name(self, row, column):\r\n        if self.we_play_white:\r\n            number = repr(8 - row)\r\n            letter = str(chr(97 + column))\r\n            return letter + number\r\n        else:\r\n            number = repr(row + 1)\r\n            letter = str(chr(97 + (7 - column)))\r\n            return letter + number\r\n\r\n    def convert_square_name_to_row_column(self, square_name):\r\n        for row in range(8):\r\n            for column in range(8):\r\n                this_square_name = self.convert_row_column_to_square_name(row, column)\r\n                if this_square_name == square_name:\r\n                    return row, column\r\n        return 0, 0\r\n\r\n    def get_potential_moves(self, old_image, new_image):\r\n        potential_starts = []\r\n        potential_arrivals = []\r\n        for row in range(8):\r\n            for column in range(8):\r\n                old_square = self.get_square_image(row, column, old_image)\r\n                new_square = self.get_square_image(row, column, new_image)\r\n                if self.has_square_image_changed(old_square, new_square):\r\n                    square_name = self.convert_row_column_to_square_name(row, column)\r\n                    potential_starts.append(square_name)\r\n                    potential_arrivals.append(square_name)\r\n        return potential_starts, potential_arrivals\r\n\r\n    def register_move_if_needed(self):\r\n        new_board = self.get_chessboard()\r\n        potential_starts, potential_arrivals = self.get_potential_moves(self.previous_chessboard_image, new_board)\r\n\r\n        valid_move_string1 = self.get_valid_move(potential_starts, potential_arrivals, new_board)\r\n\r\n        if len(valid_move_string1) > 0:\r\n            time.sleep(0.1)\r\n            # Check that we were not in the middle of a move animation\r\n            new_board = self.get_chessboard()\r\n            potential_starts, potential_arrivals = self.get_potential_moves(self.previous_chessboard_image, new_board)\r\n            valid_move_string2 = self.get_valid_move(potential_starts, potential_arrivals, new_board)\r\n            if valid_move_string2 != valid_move_string1:\r\n                return False, \"The move has changed\"\r\n            valid_move_UCI = chess.Move.from_uci(valid_move_string1)\r\n            self.register_move(valid_move_UCI, new_board)\r\n            return True, valid_move_UCI\r\n        elif potential_starts:  # Fix for premove\r\n            if len(self.registered_moves) < len(self.game_thread.played_moves):\r\n                valid_move_UCI = self.game_thread.played_moves[len(self.registered_moves)]\r\n                self.register_move(valid_move_UCI, self.previous_chessboard_image)\r\n                return True, valid_move_UCI\r\n        return False, \"No move found\"\r\n\r\n    def register_move(self, move, board_image):\r\n        if move in self.board.legal_moves:\r\n            self.board.push(move)\r\n            self.previous_chessboard_image = board_image\r\n            self.registered_moves.append(move)\r\n            # cv2.imwrite(\"registered.jpg\", board_image)\r\n            return True\r\n        else:\r\n            return False\r\n"
  },
  {
    "path": "diagnostic.py",
    "content": "import cv2\r\nimport numpy as np\r\nimport pickle\r\n\r\nfrom board_calibration_machine_learning import detect_board\r\nfrom helper import perspective_transform, predict\r\nimport platform\r\nimport sys\r\nimport tkinter as tk\r\nfrom tkinter import messagebox\r\n\r\nwebcam_width = None\r\nwebcam_height = None\r\nfps = None\r\ncalibrate = False\r\ncap_index = 0\r\ncap_api = cv2.CAP_ANY\r\nplatform_name = platform.system()\r\nfor argument in sys.argv:\r\n    if argument.startswith(\"cap=\"):\r\n        cap_index = int(\"\".join(c for c in argument if c.isdigit()))\r\n        if platform_name == \"Darwin\":\r\n            cap_api = cv2.CAP_AVFOUNDATION\r\n        elif platform_name == \"Linux\":\r\n            cap_api = cv2.CAP_V4L2\r\n        else:\r\n            cap_api = cv2.CAP_DSHOW\r\n    elif argument == \"calibrate\":\r\n        calibrate = True\r\n    elif argument.startswith(\"width=\"):\r\n        webcam_width = int(argument[len(\"width=\"):])\r\n    elif argument.startswith(\"height=\"):\r\n        webcam_height = int(argument[len(\"height=\"):])\r\n    elif argument.startswith(\"fps=\"):\r\n        fps = int(argument[len(\"fps=\"):])\r\n\r\ncorner_model = cv2.dnn.readNetFromONNX(\"yolo_corner.onnx\")\r\npiece_model = cv2.dnn.readNetFromONNX(\"cnn_piece.onnx\")\r\ncolor_model = cv2.dnn.readNetFromONNX(\"cnn_color.onnx\")\r\n\r\n\r\ncap = cv2.VideoCapture(cap_index, cap_api)\r\nif webcam_width is not None:\r\n    cap.set(cv2.CAP_PROP_FRAME_WIDTH, webcam_width)\r\nif webcam_height is not None:\r\n    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, webcam_height)\r\nif fps is not None:\r\n    cap.set(cv2.CAP_PROP_FPS, fps)\r\n\r\nif not cap.isOpened():\r\n    print(\"Couldn't open your webcam. Please check your webcam connection.\")\r\n    sys.exit(0)\r\n\r\n\r\nfor _ in range(10):\r\n    ret, frame = cap.read()\r\n\r\nif calibrate:\r\n    is_detected = False\r\n    for _ in range(100):\r\n        ret, frame = cap.read()\r\n        if not ret:\r\n            print(\"Error reading frame. Please check your webcam connection.\")\r\n            continue\r\n        result = detect_board(frame, corner_model, piece_model, color_model)\r\n        if result:\r\n            pts1, side_view_compensation, rotation_count = result\r\n            is_detected = True\r\n            break\r\n\r\n    if not is_detected:\r\n        print(\"Could not detect the chess board.\")\r\n        cap.release()\r\n        sys.exit(0)\r\nelse:\r\n    filename = 'constants.bin'\r\n    infile = open(filename, 'rb')\r\n    calibration_data = pickle.load(infile)\r\n    infile.close()\r\n    if calibration_data[0]:\r\n        pts1, side_view_compensation, rotation_count = calibration_data[1]\r\n    else:\r\n        corners, side_view_compensation, rotation_count, roi_mask = calibration_data[1]\r\n        pts1 = np.float32([list(corners[0][0]), list(corners[8][0]), list(corners[0][8]),\r\n                           list(corners[8][8])])\r\n\r\n\r\ndef process(image):\r\n    for row in range(8):\r\n        for column in range(8):\r\n            height, width = image.shape[:2]\r\n            minX = int(column * width / 8)\r\n            maxX = int((column + 1) * width / 8)\r\n            minY = int(row * height / 8)\r\n            maxY = int((row + 1) * height / 8)\r\n            square_image = image[minY:maxY, minX:maxX]\r\n            is_piece = predict(square_image, piece_model)\r\n            if is_piece:\r\n                centerX = int((minX + maxX) / 2)\r\n                centerY = int((minY + maxY) / 2)\r\n                radius = 10\r\n                is_white = predict(square_image, color_model)\r\n                if is_white:\r\n                    cv2.circle(image, (centerX, centerY), radius, (255, 0, 0), 2)\r\n                else:\r\n                    cv2.circle(image, (centerX, centerY), radius, (0, 255, 0), 2)\r\n    return image\r\n\r\n\r\nroot = tk.Tk()\r\nroot.withdraw()\r\nmessagebox.showinfo(\"Diagnostic\",\r\n                    \"The diagnostic process will start. It will mark white pieces with a blue circle and black pieces with a green circle. Press the 'q' key to exit.\")\r\n\r\nwhile True:\r\n    ret, frame = cap.read()\r\n    if not ret:\r\n        print(\"Error reading frame. Please check your webcam connection.\")\r\n        continue\r\n\r\n    frame = perspective_transform(frame, pts1)\r\n    processed_frame = process(frame.copy())\r\n    \r\n    cv2.imshow('Diagnostic', np.hstack((processed_frame, frame)))\r\n\r\n    if cv2.waitKey(1000) & 0xFF == ord('q'):\r\n        break\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n"
  },
  {
    "path": "game.py",
    "content": "import time\r\n\r\nimport chess\r\nimport cv2\r\nimport numpy as np\r\nimport pickle\r\nimport os\r\nimport sys\r\nfrom helper import detect_state, get_square_image, predict\r\nfrom internet_game import Internet_game\r\nfrom lichess_game import Lichess_game\r\nfrom commentator import Commentator_thread\r\nfrom lichess_commentator import Lichess_commentator\r\n\r\n\r\nclass Game:\r\n    def __init__(self, board_basics, speech_thread, use_template, make_opponent, start_delay, comment_me,\r\n                 comment_opponent, drag_drop, language, token, roi_mask):\r\n        if token:\r\n            self.internet_game = Lichess_game(token)\r\n        else:\r\n            self.internet_game = Internet_game(use_template, start_delay, drag_drop)\r\n        self.make_opponent = make_opponent\r\n        self.board_basics = board_basics\r\n        self.speech_thread = speech_thread\r\n        self.executed_moves = []\r\n        self.played_moves = []\r\n        self.board = chess.Board()\r\n        self.comment_me = comment_me\r\n        self.comment_opponent = comment_opponent\r\n        self.language = language\r\n        self.roi_mask = roi_mask\r\n        self.hog = cv2.HOGDescriptor((64, 64), (16, 16), (8, 8), (8, 8), 9)\r\n        self.knn = cv2.ml.KNearest_create()\r\n        self.features = None\r\n        self.labels = None\r\n        self.save_file = 'hog.bin'\r\n        self.piece_model = cv2.dnn.readNetFromONNX(\"cnn_piece.onnx\")\r\n        self.color_model = cv2.dnn.readNetFromONNX(\"cnn_color.onnx\")\r\n\r\n        if token:\r\n            commentator_thread = Lichess_commentator()\r\n            commentator_thread.daemon = True\r\n            commentator_thread.stream = self.internet_game.client.board.stream_game_state(self.internet_game.game_id)\r\n            commentator_thread.speech_thread = self.speech_thread\r\n            commentator_thread.game_state.we_play_white = self.internet_game.we_play_white\r\n            commentator_thread.game_state.game = self\r\n            commentator_thread.comment_me = self.comment_me\r\n            commentator_thread.comment_opponent = self.comment_opponent\r\n            commentator_thread.language = self.language\r\n            self.commentator = commentator_thread\r\n        else:\r\n            commentator_thread = Commentator_thread()\r\n            commentator_thread.daemon = True\r\n            commentator_thread.speech_thread = self.speech_thread\r\n            commentator_thread.game_state.game_thread = self\r\n            commentator_thread.game_state.we_play_white = self.internet_game.we_play_white\r\n            commentator_thread.game_state.board_position_on_screen = self.internet_game.position\r\n            commentator_thread.comment_me = self.comment_me\r\n            commentator_thread.comment_opponent = self.comment_opponent\r\n            commentator_thread.language = self.language\r\n            self.commentator = commentator_thread\r\n\r\n    def initialize_hog(self, frame):\r\n        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n        pieces = []\r\n        squares = []\r\n        for row in range(8):\r\n            for column in range(8):\r\n                square_name = self.board_basics.convert_row_column_to_square_name(row, column)\r\n                square = chess.parse_square(square_name)\r\n                piece = self.board.piece_at(square)\r\n                square_image = get_square_image(row, column, frame)\r\n                square_image = cv2.resize(square_image, (64, 64))\r\n                if piece:\r\n                    pieces.append(square_image)\r\n                else:\r\n                    squares.append(square_image)\r\n        pieces_hog = [self.hog.compute(piece) for piece in pieces]\r\n        squares_hog = [self.hog.compute(square) for square in squares]\r\n        labels_pieces = np.ones((len(pieces_hog), 1), np.int32)\r\n        labels_squares = np.zeros((len(squares_hog), 1), np.int32)\r\n        pieces_hog = np.array(pieces_hog)\r\n        squares_hog = np.array(squares_hog)\r\n        features = np.float32(np.concatenate((pieces_hog, squares_hog), axis=0))\r\n        labels = np.concatenate((labels_pieces, labels_squares), axis=0)\r\n        self.knn.train(features, cv2.ml.ROW_SAMPLE, labels)\r\n        self.features = features\r\n        self.labels = labels\r\n\r\n        outfile = open(self.save_file, 'wb')\r\n        pickle.dump([features, labels], outfile)\r\n        outfile.close()\r\n\r\n    def detect_state_cnn(self, chessboard_image):\r\n        state = []\r\n        for row in range(8):\r\n            row_state = []\r\n            for column in range(8):\r\n                height, width = chessboard_image.shape[:2]\r\n                minX = int(column * width / 8)\r\n                maxX = int((column + 1) * width / 8)\r\n                minY = int(row * height / 8)\r\n                maxY = int((row + 1) * height / 8)\r\n                square_image = chessboard_image[minY:maxY, minX:maxX]\r\n                is_piece = predict(square_image, self.piece_model)\r\n                if is_piece:\r\n                    is_white = predict(square_image, self.color_model)\r\n                    if is_white:\r\n                        row_state.append('w')\r\n                    else:\r\n                        row_state.append('b')\r\n                else:\r\n                    row_state.append('.')\r\n            state.append(row_state)\r\n        return state\r\n\r\n    def check_state_cnn(self, result):\r\n        for row in range(8):\r\n            for column in range(8):\r\n                square_name = self.board_basics.convert_row_column_to_square_name(row, column)\r\n                square = chess.parse_square(square_name)\r\n                piece = self.board.piece_at(square)\r\n                expected_state = '.'\r\n                if piece:\r\n                    if piece.color == chess.WHITE:\r\n                        expected_state = 'w'\r\n                    else:\r\n                        expected_state = 'b'\r\n\r\n                if result[row][column] != expected_state:\r\n                    return False\r\n        return True\r\n\r\n    def get_valid_2_move_cnn(self, frame):\r\n        board_result = self.detect_state_cnn(frame)\r\n\r\n        move_to_register = self.get_move_to_register()\r\n\r\n        if move_to_register:\r\n            self.board.push(move_to_register)\r\n            for move in self.board.legal_moves:\r\n                if move.promotion and move.promotion != chess.QUEEN:\r\n                    continue\r\n                self.board.push(move)\r\n                if self.check_state_cnn(board_result):\r\n                    self.board.pop()\r\n                    valid_move_string = move_to_register.uci()\r\n                    self.speech_thread.put_text(valid_move_string[:4])\r\n                    self.played_moves.append(move_to_register)\r\n                    self.board.pop()\r\n                    self.executed_moves.append(self.board.san(move_to_register))\r\n                    self.board.push(move_to_register)\r\n                    if self.internet_game:\r\n                        self.internet_game.is_our_turn = not self.internet_game.is_our_turn\r\n                    print(f\"First move is {valid_move_string}\")\r\n                    return True, move.uci()\r\n                else:\r\n                    self.board.pop()\r\n            self.board.pop()\r\n\r\n        return False, \"\"\r\n\r\n    def get_valid_move_cnn(self, frame):\r\n        board_result = self.detect_state_cnn(frame)\r\n\r\n        move_to_register = self.get_move_to_register()\r\n\r\n        if move_to_register:\r\n            self.board.push(move_to_register)\r\n            if self.check_state_cnn(board_result):\r\n                self.board.pop()\r\n                return True, move_to_register.uci()\r\n            else:\r\n                self.board.pop()\r\n                return False, \"\"\r\n        else:\r\n            for move in self.board.legal_moves:\r\n                if move.promotion and move.promotion != chess.QUEEN:\r\n                    continue\r\n                self.board.push(move)\r\n                if self.check_state_cnn(board_result):\r\n                    self.board.pop()\r\n                    return True, move.uci()\r\n                else:\r\n                    self.board.pop()\r\n        return False, \"\"\r\n\r\n    def load_hog(self):\r\n        if os.path.exists(self.save_file):\r\n            infile = open(self.save_file, 'rb')\r\n            self.features, self.labels = pickle.load(infile)\r\n            infile.close()\r\n            self.knn.train(self.features, cv2.ml.ROW_SAMPLE, self.labels)\r\n        else:\r\n            print(\"You need to play at least 1 game before starting a game from position.\")\r\n            sys.exit(0)\r\n\r\n    def detect_state_hog(self, chessboard_image):\r\n        chessboard_image = cv2.cvtColor(chessboard_image, cv2.COLOR_BGR2GRAY)\r\n        chessboard = [[get_square_image(row, column, chessboard_image) for column in range(8)] for row\r\n                      in\r\n                      range(8)]\r\n\r\n        board_hog = [[self.hog.compute(cv2.resize(chessboard[row][column], (64, 64))) for column in range(8)] for row\r\n                     in\r\n                     range(8)]\r\n        knn_result = []\r\n        for row in range(8):\r\n            knn_row = []\r\n            for column in range(8):\r\n                ret, result, neighbours, dist = self.knn.findNearest(np.array([board_hog[row][column]]), k=3)\r\n                knn_row.append(result[0][0])\r\n            knn_result.append(knn_row)\r\n        board_state = [[knn_result[row][column] > 0.5 for column in range(8)] for row\r\n                       in\r\n                       range(8)]\r\n        return board_state\r\n\r\n    def get_valid_move_hog(self, fgmask, frame):\r\n        board = [[self.board_basics.get_square_image(row, column, fgmask).mean() for column in range(8)] for row in\r\n                 range(8)]\r\n        potential_squares = []\r\n        square_scores = {}\r\n        for row in range(8):\r\n            for column in range(8):\r\n                score = board[row][column]\r\n                if score < 10.0:\r\n                    continue\r\n                square_name = self.board_basics.convert_row_column_to_square_name(row, column)\r\n                square = chess.parse_square(square_name)\r\n                potential_squares.append(square)\r\n                square_scores[square] = score\r\n\r\n        move_to_register = self.get_move_to_register()\r\n        potential_moves = []\r\n\r\n        board_result = self.detect_state_hog(frame)\r\n        if move_to_register:\r\n            if (move_to_register.from_square in potential_squares) and (\r\n                    move_to_register.to_square in potential_squares):\r\n                self.board.push(move_to_register)\r\n                if self.check_state_hog(board_result):\r\n                    self.board.pop()\r\n                    return True, move_to_register.uci()\r\n                else:\r\n                    self.board.pop()\r\n                    return False, \"\"\r\n        else:\r\n            for move in self.board.legal_moves:\r\n                if (move.from_square in potential_squares) and (move.to_square in potential_squares):\r\n                    if move.promotion and move.promotion != chess.QUEEN:\r\n                        continue\r\n                    self.board.push(move)\r\n                    if self.check_state_hog(board_result):\r\n                        self.board.pop()\r\n                        total_score = square_scores[move.from_square] + square_scores[move.to_square]\r\n                        potential_moves.append((total_score, move.uci()))\r\n                    else:\r\n                        self.board.pop()\r\n        if potential_moves:\r\n            return True, max(potential_moves)[1]\r\n        else:\r\n            return False, \"\"\r\n\r\n    def get_move_to_register(self):\r\n        if self.commentator:\r\n            if len(self.executed_moves) < len(self.commentator.game_state.registered_moves):\r\n                return self.commentator.game_state.registered_moves[len(self.executed_moves)]\r\n            else:\r\n                return None\r\n        else:\r\n            return None\r\n\r\n    def is_light_change(self, frame):\r\n        state = False\r\n        if self.roi_mask is not None:\r\n            result = detect_state(frame, self.board_basics.d[0], self.roi_mask)\r\n            result_hog = self.detect_state_hog(frame)\r\n            state = self.check_state_for_light(result, result_hog)\r\n        if state:\r\n            print(\"Light change\")\r\n            return True\r\n        else:\r\n            result_cnn = self.detect_state_cnn(frame)\r\n            state_cnn = self.check_state_cnn(result_cnn)\r\n            if state_cnn:\r\n                print(\"Light change cnn\")\r\n            return state_cnn\r\n\r\n    def check_state_hog(self, result):\r\n        for row in range(8):\r\n            for column in range(8):\r\n                square_name = self.board_basics.convert_row_column_to_square_name(row, column)\r\n                square = chess.parse_square(square_name)\r\n                piece = self.board.piece_at(square)\r\n                if piece and (not result[row][column]):\r\n                    print(\"Expected piece at \" + square_name)\r\n                    return False\r\n                if (not piece) and (result[row][column]):\r\n                    print(\"Expected empty at \" + square_name)\r\n                    return False\r\n        return True\r\n\r\n    def check_state_for_move(self, result):\r\n        for row in range(8):\r\n            for column in range(8):\r\n                square_name = self.board_basics.convert_row_column_to_square_name(row, column)\r\n                square = chess.parse_square(square_name)\r\n                piece = self.board.piece_at(square)\r\n                if piece and (True not in result[row][column]):\r\n                    print(\"Expected piece at \" + square_name)\r\n                    return False\r\n                if (not piece) and (False not in result[row][column]):\r\n                    print(\"Expected empty at \" + square_name)\r\n                    return False\r\n        return True\r\n\r\n    def check_state_for_light(self, result, result_hog):\r\n        for row in range(8):\r\n            for column in range(8):\r\n                if len(result[row][column]) > 1:\r\n                    result[row][column] = [result_hog[row][column]]\r\n                square_name = self.board_basics.convert_row_column_to_square_name(row, column)\r\n                square = chess.parse_square(square_name)\r\n                piece = self.board.piece_at(square)\r\n                if piece and (False in result[row][column]):\r\n                    print(square_name)\r\n                    return False\r\n                if (not piece) and (True in result[row][column]):\r\n                    print(square_name)\r\n                    return False\r\n        return True\r\n\r\n    def get_valid_move_canny(self, fgmask, frame):\r\n        if self.roi_mask is None:\r\n            return False, \"\"\r\n        board = [[self.board_basics.get_square_image(row, column, fgmask).mean() for column in range(8)] for row in\r\n                 range(8)]\r\n        potential_squares = []\r\n        square_scores = {}\r\n        for row in range(8):\r\n            for column in range(8):\r\n                score = board[row][column]\r\n                if score < 10.0:\r\n                    continue\r\n                square_name = self.board_basics.convert_row_column_to_square_name(row, column)\r\n                square = chess.parse_square(square_name)\r\n                potential_squares.append(square)\r\n                square_scores[square] = score\r\n\r\n        move_to_register = self.get_move_to_register()\r\n        potential_moves = []\r\n\r\n        board_result = detect_state(frame, self.board_basics.d[0], self.roi_mask)\r\n        if move_to_register:\r\n            if (move_to_register.from_square in potential_squares) and (\r\n                    move_to_register.to_square in potential_squares):\r\n                self.board.push(move_to_register)\r\n                if self.check_state_for_move(board_result):\r\n                    self.board.pop()\r\n                    return True, move_to_register.uci()\r\n                else:\r\n                    self.board.pop()\r\n                    return False, \"\"\r\n        else:\r\n            for move in self.board.legal_moves:\r\n                if (move.from_square in potential_squares) and (move.to_square in potential_squares):\r\n                    if move.promotion and move.promotion != chess.QUEEN:\r\n                        continue\r\n                    self.board.push(move)\r\n                    if self.check_state_for_move(board_result):\r\n                        self.board.pop()\r\n                        total_score = square_scores[move.from_square] + square_scores[move.to_square]\r\n                        potential_moves.append((total_score, move.uci()))\r\n                    else:\r\n                        self.board.pop()\r\n        if potential_moves:\r\n            return True, max(potential_moves)[1]\r\n        else:\r\n            return False, \"\"\r\n\r\n    def register_move(self, fgmask, previous_frame, next_frame):\r\n        success, valid_move_string = self.get_valid_2_move_cnn(next_frame)\r\n        if not success:\r\n            success, valid_move_string = self.get_valid_move_cnn(next_frame)\r\n            if not success:\r\n                potential_squares, potential_moves = self.board_basics.get_potential_moves(fgmask, previous_frame,\r\n                                                                                           next_frame,\r\n                                                                                           self.board)\r\n                success, valid_move_string = self.get_valid_move(potential_squares, potential_moves)\r\n                if not success:\r\n                    success, valid_move_string = self.get_valid_move_canny(fgmask, next_frame)\r\n\r\n                    if not success:\r\n                        success, valid_move_string = self.get_valid_move_hog(fgmask, next_frame)\r\n                        if not success:\r\n                            self.speech_thread.put_text(self.language.move_failed)\r\n                            print(self.board.fen())\r\n                            return False\r\n                        else:\r\n                            print(\"Valid move string 5:\" + valid_move_string)\r\n                    else:\r\n                        print(\"Valid move string 4:\" + valid_move_string)\r\n                else:\r\n                    print(\"Valid move string 3:\" + valid_move_string)\r\n            else:\r\n                print(\"Valid move string 2:\" + valid_move_string)\r\n        else:\r\n            print(\"Valid move string 1:\" + valid_move_string)\r\n\r\n        valid_move_UCI = chess.Move.from_uci(valid_move_string)\r\n\r\n        print(\"Move has been registered\")\r\n\r\n        if self.internet_game.is_our_turn or self.make_opponent:\r\n            self.internet_game.move(valid_move_UCI)\r\n            self.played_moves.append(valid_move_UCI)\r\n            while self.commentator:\r\n                time.sleep(0.1)\r\n                move_to_register = self.get_move_to_register()\r\n                if move_to_register:\r\n                    valid_move_UCI = move_to_register\r\n                    break\r\n        else:\r\n            self.speech_thread.put_text(valid_move_string[:4])\r\n            self.played_moves.append(valid_move_UCI)\r\n\r\n        self.executed_moves.append(self.board.san(valid_move_UCI))\r\n        is_capture = self.board.is_capture(valid_move_UCI)\r\n        color = int(self.board.turn)\r\n        self.board.push(valid_move_UCI)\r\n\r\n        self.internet_game.is_our_turn = not self.internet_game.is_our_turn\r\n\r\n        self.learn(next_frame)\r\n        self.board_basics.update_ssim(previous_frame, next_frame, valid_move_UCI, is_capture, color)\r\n        return True\r\n\r\n    def learn(self, frame):\r\n        result = self.detect_state_hog(frame)\r\n        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n        new_pieces = []\r\n        new_squares = []\r\n\r\n        for row in range(8):\r\n            for column in range(8):\r\n                square_name = self.board_basics.convert_row_column_to_square_name(row, column)\r\n                square = chess.parse_square(square_name)\r\n                piece = self.board.piece_at(square)\r\n                if piece and (not result[row][column]):\r\n                    print(\"Learning piece at \" + square_name)\r\n                    piece_hog = self.hog.compute(cv2.resize(get_square_image(row, column, frame), (64, 64)))\r\n                    new_pieces.append(piece_hog)\r\n                if (not piece) and (result[row][column]):\r\n                    print(\"Learning empty at \" + square_name)\r\n                    square_hog = self.hog.compute(cv2.resize(get_square_image(row, column, frame), (64, 64)))\r\n                    new_squares.append(square_hog)\r\n        labels_pieces = np.ones((len(new_pieces), 1), np.int32)\r\n        labels_squares = np.zeros((len(new_squares), 1), np.int32)\r\n        if new_pieces:\r\n            new_pieces = np.array(new_pieces)\r\n            self.features = np.float32(np.concatenate((self.features, new_pieces), axis=0))\r\n            self.labels = np.concatenate((self.labels, labels_pieces), axis=0)\r\n        if new_squares:\r\n            new_squares = np.array(new_squares)\r\n            self.features = np.float32(np.concatenate((self.features, new_squares), axis=0))\r\n            self.labels = np.concatenate((self.labels, labels_squares), axis=0)\r\n\r\n        self.features = self.features[:100]\r\n        self.labels = self.labels[:100]\r\n        self.knn = cv2.ml.KNearest_create()\r\n        self.knn.train(self.features, cv2.ml.ROW_SAMPLE, self.labels)\r\n\r\n    def get_valid_move(self, potential_squares, potential_moves):\r\n        print(\"Potential squares\")\r\n        print(potential_squares)\r\n        print(\"Potential moves\")\r\n        print(potential_moves)\r\n\r\n        move_to_register = self.get_move_to_register()\r\n\r\n        valid_move_string = \"\"\r\n        for score, start, arrival in potential_moves:\r\n            if valid_move_string:\r\n                break\r\n\r\n            if move_to_register:\r\n                if chess.square_name(move_to_register.from_square) != start:\r\n                    continue\r\n                if chess.square_name(move_to_register.to_square) != arrival:\r\n                    continue\r\n\r\n            uci_move = start + arrival\r\n            try:\r\n                move = chess.Move.from_uci(uci_move)\r\n            except Exception as e:\r\n                print(e)\r\n                continue\r\n\r\n            if move in self.board.legal_moves:\r\n                valid_move_string = uci_move\r\n            else:\r\n                if move_to_register:\r\n                    uci_move_promoted = move_to_register.uci()\r\n                else:\r\n                    uci_move_promoted = uci_move + 'q'\r\n                promoted_move = chess.Move.from_uci(uci_move_promoted)\r\n                if promoted_move in self.board.legal_moves:\r\n                    valid_move_string = uci_move_promoted\r\n                    # print(\"There has been a promotion\")\r\n\r\n        potential_squares = [square[1] for square in potential_squares]\r\n        print(potential_squares)\r\n        # Detect castling king side with white\r\n        if (\"e1\" in potential_squares) and (\"h1\" in potential_squares) and (\"f1\" in potential_squares) and (\r\n                \"g1\" in potential_squares) and (chess.Move.from_uci(\"e1g1\") in self.board.legal_moves):\r\n            valid_move_string = \"e1g1\"\r\n\r\n        # Detect castling queen side with white\r\n        if (\"e1\" in potential_squares) and (\"a1\" in potential_squares) and (\"c1\" in potential_squares) and (\r\n                \"d1\" in potential_squares) and (chess.Move.from_uci(\"e1c1\") in self.board.legal_moves):\r\n            valid_move_string = \"e1c1\"\r\n\r\n        # Detect castling king side with black\r\n        if (\"e8\" in potential_squares) and (\"h8\" in potential_squares) and (\"f8\" in potential_squares) and (\r\n                \"g8\" in potential_squares) and (chess.Move.from_uci(\"e8g8\") in self.board.legal_moves):\r\n            valid_move_string = \"e8g8\"\r\n\r\n        # Detect castling queen side with black\r\n        if (\"e8\" in potential_squares) and (\"a8\" in potential_squares) and (\"c8\" in potential_squares) and (\r\n                \"d8\" in potential_squares) and (chess.Move.from_uci(\"e8c8\") in self.board.legal_moves):\r\n            valid_move_string = \"e8c8\"\r\n\r\n        if move_to_register and (move_to_register.uci() != valid_move_string):\r\n            return False, valid_move_string\r\n\r\n        if valid_move_string:\r\n            return True, valid_move_string\r\n        else:\r\n            return False, valid_move_string\r\n"
  },
  {
    "path": "gui.py",
    "content": "import tkinter as tk\r\nfrom tkinter.simpledialog import askstring\r\nfrom tkinter import messagebox\r\nimport subprocess\r\nimport sys\r\nfrom threading import Thread\r\nimport pickle\r\nimport os\r\n\r\nrunning_process = None\r\n\r\ntoken = \"\"\r\n\r\n\r\ndef lichess():\r\n    global token\r\n    new_token = askstring(\"Lichess API Access Token\", \"Please enter your Lichess API Access Token below.\",\r\n                          initialvalue=token)\r\n    if new_token is None:\r\n        pass\r\n    else:\r\n        token = new_token\r\n\r\n\r\ndef on_closing():\r\n    if running_process:\r\n        if running_process.poll() is None:\r\n            running_process.terminate()\r\n    save_settings()\r\n    window.destroy()\r\n\r\n\r\ndef log_process(process, finish_message):\r\n    global button_frame\r\n    button_stop = tk.Button(button_frame, text=\"Stop\", command=stop_process)\r\n    button_stop.grid(row=0, column=0, columnspan=3, sticky=\"ew\")\r\n    while True:\r\n        output = process.stdout.readline()\r\n        if output:\r\n            logs_text.insert(tk.END, output.decode())\r\n        if process.poll() is not None:\r\n            logs_text.insert(tk.END, finish_message)\r\n            break\r\n    global start, board\r\n    start = tk.Button(button_frame, text=\"Start Game\", command=start_game)\r\n    start.grid(row=0, column=0)\r\n    board = tk.Button(button_frame, text=\"Board Calibration\", command=board_calibration)\r\n    board.grid(row=0, column=1)\r\n    diagnostic_button = tk.Button(button_frame, text=\"Diagnostic\", command=diagnostic)\r\n    diagnostic_button.grid(row=0, column=2)\r\n    if promotion_menu.cget(\"state\") == \"normal\":\r\n        promotion.set(PROMOTION_OPTIONS[0])\r\n        promotion_menu.configure(state=\"disabled\")\r\n\r\n\r\ndef stop_process(ignore=None):\r\n    if running_process:\r\n        if running_process.poll() is None:\r\n            running_process.terminate()\r\n\r\n\r\ndef diagnostic(ignore=None):\r\n    arguments = [sys.executable, \"diagnostic.py\"]\r\n    # arguments = [\"diagnostic.exe\"]\r\n    # working_directory = sys.argv[0][:-3]\r\n    # arguments = [working_directory+\"diagnostic\"]\r\n    selected_camera = camera.get()\r\n    if selected_camera != OPTIONS[0]:\r\n        cap_index = OPTIONS.index(selected_camera) - 1\r\n        arguments.append(\"cap=\" + str(cap_index))\r\n    selected_resolution = resolution.get()\r\n    if selected_resolution != RESOLUTION_OPTIONS[0]:\r\n        width, height = selected_resolution.split(\" x \")\r\n        arguments.append(f\"width={width}\")\r\n        arguments.append(f\"height={height}\")\r\n    selected_fps = fps.get()\r\n    if selected_fps != FPS_OPTIONS[0]:\r\n        arguments.append(f\"fps={selected_fps}\")\r\n    if calibration_mode.get() == CALIBRATION_OPTIONS[-1]:\r\n        arguments.append(\"calibrate\")\r\n    process = subprocess.Popen(arguments, stdout=subprocess.PIPE,\r\n                               stderr=subprocess.STDOUT)\r\n    # startupinfo = subprocess.STARTUPINFO()\r\n    # startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\r\n    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE,\r\n    #                           stderr=subprocess.STDOUT, stdin=subprocess.PIPE, startupinfo=startupinfo)\r\n    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE,\r\n    #                           stderr=subprocess.STDOUT, cwd=working_directory)\r\n    global running_process\r\n    running_process = process\r\n    log_thread = Thread(target=log_process, args=(process, \"Diagnostic finished.\\n\"))\r\n    log_thread.daemon = True\r\n    log_thread.start()\r\n\r\n\r\ndef board_calibration(ignore=None):\r\n    if calibration_mode.get() == CALIBRATION_OPTIONS[-1]:\r\n        messagebox.showinfo(\r\n            \"Board Calibration Not Required\",\r\n            \"Calibration is not necessary for this mode. \"\r\n            \"You can proceed directly without calibration.\"\r\n        )\r\n        return\r\n\r\n    arguments = [sys.executable, \"board_calibration.py\", \"show-info\"]\r\n    # arguments = [\"board_calibration.exe\", \"show-info\"]\r\n    # working_directory = sys.argv[0][:-3]\r\n    # arguments = [working_directory+\"board_calibration\", \"show-info\"]\r\n    selected_camera = camera.get()\r\n    if selected_camera != OPTIONS[0]:\r\n        cap_index = OPTIONS.index(selected_camera) - 1\r\n        arguments.append(\"cap=\" + str(cap_index))\r\n    selected_resolution = resolution.get()\r\n    if selected_resolution != RESOLUTION_OPTIONS[0]:\r\n        width, height = selected_resolution.split(\" x \")\r\n        arguments.append(f\"width={width}\")\r\n        arguments.append(f\"height={height}\")\r\n    selected_fps = fps.get()\r\n    if selected_fps != FPS_OPTIONS[0]:\r\n        arguments.append(f\"fps={selected_fps}\")\r\n    if calibration_mode.get() == CALIBRATION_OPTIONS[1]:\r\n        arguments.append(\"ml\")\r\n    process = subprocess.Popen(arguments, stdout=subprocess.PIPE,\r\n                               stderr=subprocess.STDOUT)\r\n    # startupinfo = subprocess.STARTUPINFO()\r\n    # startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\r\n    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE,\r\n    #                           stderr=subprocess.STDOUT, stdin=subprocess.PIPE, startupinfo=startupinfo)\r\n    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE,\r\n    #                           stderr=subprocess.STDOUT, cwd=working_directory)\r\n    global running_process\r\n    running_process = process\r\n    log_thread = Thread(target=log_process, args=(process, \"Board calibration finished.\\n\"))\r\n    log_thread.daemon = True\r\n    log_thread.start()\r\n\r\n\r\ndef start_game(ignore=None):\r\n    arguments = [sys.executable, \"main.py\"]\r\n    # arguments = [\"main.exe\"]\r\n    # working_directory = sys.argv[0][:-3]\r\n    # arguments = [working_directory+\"main\"]\r\n    if no_template.get():\r\n        arguments.append(\"no-template\")\r\n    if make_opponent.get():\r\n        arguments.append(\"make-opponent\")\r\n    if comment_me.get():\r\n        arguments.append(\"comment-me\")\r\n    if comment_opponent.get():\r\n        arguments.append(\"comment-opponent\")\r\n    if drag_drop.get():\r\n        arguments.append(\"drag\")\r\n    global token\r\n    if token:\r\n        arguments.append(\"token=\" + token)\r\n        promotion_menu.configure(state=\"normal\")\r\n        promotion.set(PROMOTION_OPTIONS[0])\r\n\r\n    arguments.append(\"delay=\" + str(values.index(default_value.get())))\r\n\r\n    selected_camera = camera.get()\r\n    if selected_camera != OPTIONS[0]:\r\n        cap_index = OPTIONS.index(selected_camera) - 1\r\n        arguments.append(\"cap=\" + str(cap_index))\r\n    selected_resolution = resolution.get()\r\n    if selected_resolution != RESOLUTION_OPTIONS[0]:\r\n        width, height = selected_resolution.split(\" x \")\r\n        arguments.append(f\"width={width}\")\r\n        arguments.append(f\"height={height}\")\r\n    selected_fps = fps.get()\r\n    if selected_fps != FPS_OPTIONS[0]:\r\n        arguments.append(f\"fps={selected_fps}\")\r\n    selected_voice = voice.get()\r\n    if selected_voice != VOICE_OPTIONS[0]:\r\n        voice_index = VOICE_OPTIONS.index(selected_voice) - 1\r\n        arguments.append(\"voice=\" + str(voice_index))\r\n        language = \"English\"\r\n        languages = [\"English\", \"German\", \"Russian\", \"Turkish\", \"Italian\", \"French\"]\r\n        codes = [\"en_\", \"de_\", \"ru_\", \"tr_\", \"it_\", \"fr_\"]\r\n        for l, c in zip(languages, codes):\r\n            if (l in selected_voice) or (l.lower() in selected_voice) or (c in selected_voice):\r\n                language = l\r\n                break\r\n        arguments.append(\"lang=\" + language)\r\n\r\n    if calibration_mode.get() == CALIBRATION_OPTIONS[-1]:\r\n        arguments.append(\"calibrate\")\r\n\r\n    process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\r\n    # startupinfo = subprocess.STARTUPINFO()\r\n    # startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\r\n    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE,\r\n    #                           stderr=subprocess.STDOUT, stdin=subprocess.PIPE, startupinfo=startupinfo)\r\n    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=working_directory)\r\n    global running_process\r\n    running_process = process\r\n    log_thread = Thread(target=log_process, args=(process, \"Game finished.\\n\"))\r\n    log_thread.daemon = True\r\n    log_thread.start()\r\n\r\n\r\nwindow = tk.Tk()\r\nwindow.title(\"Play online chess with a real chess board by Alper Karayaman\")\r\n\r\nmenu_bar = tk.Menu(window)\r\nconnection = tk.Menu(menu_bar, tearoff=False)\r\nconnection.add_command(label=\"Lichess\", command=lichess)\r\n\r\nmenu_bar.add_cascade(label=\"Connection\", menu=connection)\r\n\r\nwindow.config(menu=menu_bar)\r\n\r\nno_template = tk.IntVar()\r\nmake_opponent = tk.IntVar()\r\ndrag_drop = tk.IntVar()\r\ncomment_me = tk.IntVar()\r\ncomment_opponent = tk.IntVar()\r\n\r\nmenu_frame = tk.Frame(window)\r\nmenu_frame.grid(row=0, column=0, columnspan=2, sticky=\"W\")\r\ncamera = tk.StringVar()\r\nOPTIONS = [\"Default\"]\r\ntry:\r\n    import platform\r\n\r\n    platform_name = platform.system()\r\n    if platform_name == \"Darwin\":\r\n        cmd = 'system_profiler SPCameraDataType | grep \"^    [^ ]\" | sed \"s/    //\" | sed \"s/://\"'\r\n        result = subprocess.check_output(cmd, shell=True)\r\n        result = result.decode()\r\n        result = [r for r in result.split(\"\\n\") if r]\r\n        OPTIONS.extend(result)\r\n    elif platform_name == \"Linux\":\r\n        cmd = 'for I in /sys/class/video4linux/*; do cat $I/name; done'\r\n        result = subprocess.check_output(cmd, shell=True)\r\n        result = result.decode()\r\n        result = [r for r in result.split(\"\\n\") if r]\r\n        OPTIONS.extend(result)\r\n    else:\r\n        from pygrabber.dshow_graph import FilterGraph\r\n\r\n        OPTIONS.extend(FilterGraph().get_input_devices())\r\nexcept:\r\n    pass\r\ncamera.set(OPTIONS[0])\r\nlabel = tk.Label(menu_frame, text='Select Webcam:')\r\nlabel.grid(column=0, row=0, sticky=tk.W)\r\nmenu = tk.OptionMenu(menu_frame, camera, *OPTIONS)\r\nmenu.config(width=max(len(option) for option in OPTIONS), anchor=\"w\")\r\nmenu.grid(column=1, row=0, sticky=tk.W)\r\n\r\nresolution_frame = tk.Frame(window)\r\nresolution_frame.grid(row=1, column=0, columnspan=2, sticky=\"W\")\r\nresolution = tk.StringVar()\r\nRESOLUTION_OPTIONS = [\"Default\", \"640 x 480\", \"1280 x 720\", \"1920 x 1080\", \"2560 x 1440\", \"3840 x 2160\"]\r\nresolution.set(RESOLUTION_OPTIONS[0])\r\nresolution_label = tk.Label(resolution_frame, text='Select Webcam Resolution:')\r\nresolution_label.grid(column=0, row=0, sticky=tk.W)\r\nresolution_menu = tk.OptionMenu(resolution_frame, resolution, *RESOLUTION_OPTIONS)\r\nresolution_menu.config(width=max(len(option) for option in RESOLUTION_OPTIONS), anchor=\"w\")\r\nresolution_menu.grid(column=1, row=0, sticky=tk.W)\r\n\r\nfps_frame = tk.Frame(window)\r\nfps_frame.grid(row=2, column=0, columnspan=2, sticky=\"W\")\r\nfps = tk.StringVar()\r\nFPS_OPTIONS = [\"Default\", \"15\", \"24\", \"30\", \"60\", \"120\", \"144\", \"240\"]\r\nfps.set(FPS_OPTIONS[0])\r\nfps_label = tk.Label(fps_frame, text='Select Webcam FPS:')\r\nfps_label.grid(column=0, row=0, sticky=tk.W)\r\nfps_menu = tk.OptionMenu(fps_frame, fps, *FPS_OPTIONS)\r\nfps_menu.config(width=max(len(option) for option in FPS_OPTIONS), anchor=\"w\")\r\nfps_menu.grid(column=1, row=0, sticky=tk.W)\r\n\r\ncalibration_frame = tk.Frame(window)\r\ncalibration_frame.grid(row=3, column=0, columnspan=2, sticky=\"W\")\r\ncalibration_mode = tk.StringVar()\r\nCALIBRATION_OPTIONS = [\"The board is empty.\", \"Pieces are in their starting positions.\",\r\n                       \"Just before the game starts.\"]\r\ncalibration_mode.set(CALIBRATION_OPTIONS[0])\r\ncalibration_label = tk.Label(calibration_frame, text='Board Calibration Mode:')\r\ncalibration_label.grid(column=0, row=0, sticky=tk.W)\r\ncalibration_menu = tk.OptionMenu(calibration_frame, calibration_mode, *CALIBRATION_OPTIONS)\r\ncalibration_menu.config(width=max(len(option) for option in CALIBRATION_OPTIONS), anchor=\"w\")\r\ncalibration_menu.grid(column=1, row=0, sticky=tk.W)\r\n\r\nvoice_frame = tk.Frame(window)\r\nvoice_frame.grid(row=4, column=0, columnspan=2, sticky=\"W\")\r\nvoice = tk.StringVar()\r\nVOICE_OPTIONS = [\"Default\"]\r\ntry:\r\n    import platform\r\n\r\n    if platform.system() == \"Darwin\":\r\n        result = subprocess.run(['say', '-v', '?'], stdout=subprocess.PIPE)\r\n        output = result.stdout.decode('utf-8')\r\n        for line in output.splitlines():\r\n            if line:\r\n                voice_info = line.split()\r\n                VOICE_OPTIONS.append(f'{voice_info[0]} {voice_info[1]}')\r\n    else:\r\n        import pyttsx3\r\n\r\n        engine = pyttsx3.init()\r\n        for v in engine.getProperty('voices'):\r\n            VOICE_OPTIONS.append(v.name)\r\nexcept:\r\n    pass\r\nvoice.set(VOICE_OPTIONS[0])\r\nvoice_label = tk.Label(voice_frame, text='Select Voice:')\r\nvoice_label.grid(column=0, row=0, sticky=tk.W)\r\nvoice_menu = tk.OptionMenu(voice_frame, voice, *VOICE_OPTIONS)\r\nvoice_menu.config(width=max(len(option) for option in VOICE_OPTIONS), anchor=\"w\")\r\nvoice_menu.grid(column=1, row=0, sticky=tk.W)\r\n\r\n\r\ndef save_promotion(*args):\r\n    outfile = open(\"promotion.bin\", 'wb')\r\n    pickle.dump(promotion.get(), outfile)\r\n    outfile.close()\r\n\r\n\r\npromotion_frame = tk.Frame(window)\r\npromotion_frame.grid(row=5, column=0, columnspan=2, sticky=\"W\")\r\npromotion = tk.StringVar()\r\npromotion.trace(\"w\", save_promotion)\r\nPROMOTION_OPTIONS = [\"Queen\", \"Knight\", \"Rook\", \"Bishop\"]\r\npromotion.set(PROMOTION_OPTIONS[0])\r\npromotion_label = tk.Label(promotion_frame, text='Select Promotion Piece:')\r\npromotion_label.grid(column=0, row=0, sticky=tk.W)\r\npromotion_menu = tk.OptionMenu(promotion_frame, promotion, *PROMOTION_OPTIONS)\r\npromotion_menu.config(width=max(len(option) for option in PROMOTION_OPTIONS), anchor=\"w\")\r\npromotion_menu.grid(column=1, row=0, sticky=tk.W)\r\npromotion_menu.configure(state=\"disabled\")\r\n\r\nc = tk.Checkbutton(window, text=\"Find chess board of online game without template images.\", variable=no_template)\r\nc.grid(row=6, column=0, sticky=\"W\", columnspan=1)\r\n\r\nc1 = tk.Checkbutton(window, text=\"Make moves of opponent too.\", variable=make_opponent)\r\nc1.grid(row=7, column=0, sticky=\"W\", columnspan=1)\r\n\r\nc2 = tk.Checkbutton(window, text=\"Make moves by drag and drop.\", variable=drag_drop)\r\nc2.grid(row=8, column=0, sticky=\"W\", columnspan=1)\r\n\r\nc2 = tk.Checkbutton(window, text=\"Speak my moves.\", variable=comment_me)\r\nc2.grid(row=9, column=0, sticky=\"W\", columnspan=1)\r\n\r\nc3 = tk.Checkbutton(window, text=\"Speak opponent's moves.\", variable=comment_opponent)\r\nc3.grid(row=10, column=0, sticky=\"W\", columnspan=1)\r\n\r\nvalues = [\"Do not delay game start.\", \"1 second delayed game start.\"] + [str(i) + \" seconds delayed game start.\" for i\r\n                                                                         in range(2, 6)]\r\ndefault_value = tk.StringVar()\r\ns = tk.Spinbox(window, values=values, textvariable=default_value, width=max(len(value) for value in values))\r\ndefault_value.set(values[-1])\r\ns.grid(row=11, column=0, sticky=\"W\", columnspan=2)\r\nbutton_frame = tk.Frame(window)\r\nbutton_frame.grid(row=12, column=0, columnspan=2, sticky=\"W\")\r\nstart = tk.Button(button_frame, text=\"Start Game\", command=start_game)\r\nstart.grid(row=0, column=0)\r\nboard = tk.Button(button_frame, text=\"Board Calibration\", command=board_calibration)\r\nboard.grid(row=0, column=1)\r\ndiagnostic_button = tk.Button(button_frame, text=\"Diagnostic\", command=diagnostic)\r\ndiagnostic_button.grid(row=0, column=2)\r\ntext_frame = tk.Frame(window)\r\ntext_frame.grid(row=13, column=0)\r\nscroll_bar = tk.Scrollbar(text_frame)\r\nlogs_text = tk.Text(text_frame, background='gray', yscrollcommand=scroll_bar.set)\r\nscroll_bar.config(command=logs_text.yview)\r\nscroll_bar.pack(side=tk.RIGHT, fill=tk.Y)\r\nlogs_text.pack(side=\"left\")\r\n\r\nfields = [no_template, make_opponent, comment_me, comment_opponent, calibration_mode, resolution, fps, drag_drop,\r\n          default_value, camera, voice]\r\nsave_file = 'gui.bin'\r\n\r\n\r\ndef save_settings():\r\n    outfile = open(save_file, 'wb')\r\n    pickle.dump([field.get() for field in fields] + [token], outfile)\r\n    outfile.close()\r\n\r\n\r\ndef load_settings():\r\n    if os.path.exists(save_file):\r\n        infile = open(save_file, 'rb')\r\n        variables = pickle.load(infile)\r\n        infile.close()\r\n        global token\r\n        token = variables[-1]\r\n        if variables[-2] in VOICE_OPTIONS:\r\n            voice.set(variables[-2])\r\n\r\n        if variables[-3] in OPTIONS:\r\n            camera.set(variables[-3])\r\n\r\n        for i in range(9):\r\n            fields[i].set(variables[i])\r\n\r\n\r\nload_settings()\r\nwindow.protocol(\"WM_DELETE_WINDOW\", on_closing)\r\nwindow.mainloop()\r\n"
  },
  {
    "path": "helper.py",
    "content": "import cv2\r\nimport numpy as np\r\nfrom math import sqrt\r\n\r\n\r\ndef euclidean_distance(first, second):\r\n    return sqrt((first[0] - second[0]) ** 2 + (first[1] - second[1]) ** 2)\r\n\r\n\r\ndef perspective_transform(image, pts1):\r\n    dimension = 480\r\n    pts2 = np.float32([[0, 0], [0, dimension], [dimension, 0], [dimension, dimension]])\r\n    M = cv2.getPerspectiveTransform(pts1, pts2)\r\n    dst = cv2.warpPerspective(image, M, (dimension, dimension))\r\n    return dst\r\n\r\n\r\ndef rotateMatrix(matrix):\r\n    size = len(matrix)\r\n    for row in range(size // 2):\r\n        for column in range(row, size - row - 1):\r\n            temp = matrix[row][column]\r\n            matrix[row][column] = matrix[column][size - 1 - row]\r\n            matrix[column][size - 1 - row] = matrix[size - 1 - row][size - 1 - column]\r\n            matrix[size - 1 - row][size - 1 - column] = matrix[size - 1 - column][row]\r\n            matrix[size - 1 - column][row] = temp\r\n\r\n\r\ndef auto_canny(image):\r\n    sigma_upper = 0.2\r\n    sigma_lower = 0.8\r\n    median_intensity = np.median(image)\r\n    lower = int(max(0, (1.0 - sigma_lower) * median_intensity))\r\n    upper = int(min(255, (1.0 + sigma_upper) * median_intensity))\r\n    edged = cv2.Canny(image, lower, upper)\r\n    return edged\r\n\r\n\r\ndef edge_detection(frame):\r\n    kernel = np.ones((3, 3), np.uint8)\r\n    clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))\r\n    edges = []\r\n    for gray in cv2.split(frame):\r\n        gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)\r\n        gray = clahe.apply(gray)\r\n        gray = cv2.GaussianBlur(gray, (3, 3), 0)\r\n        edge = auto_canny(gray)\r\n        edges.append(edge)\r\n    edges = cv2.bitwise_or(cv2.bitwise_or(edges[0], edges[1]), edges[2])\r\n    kernel2 = np.ones((3, 3), np.uint8)\r\n    edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel2)\r\n    return edges\r\n\r\ndef get_square_image(row, column,\r\n                     board_img):\r\n    height, width = board_img.shape[:2]\r\n    minX = int(column * width / 8)\r\n    maxX = int((column + 1) * width / 8)\r\n    minY = int(row * height / 8)\r\n    maxY = int((row + 1) * height / 8)\r\n    square = board_img[minY:maxY, minX:maxX]\r\n    square_without_borders = square[3:-3, 3:-3]\r\n    return square_without_borders\r\n\r\n\r\ndef contains_piece(square, view):\r\n    height, width = square.shape[:2]\r\n    if view == (0, -1):\r\n        half = square[:, width // 2:]\r\n    elif view == (0, 1):\r\n        half = square[:, :width // 2]\r\n    elif view == (1, 0):\r\n        half = square[height // 2:, :]\r\n    elif view == (-1, 0):\r\n        half = square[:height // 2, :]\r\n    if half.mean() < 1.0:\r\n        return [False]\r\n    elif square.mean() > 15.0:\r\n        return [True]\r\n    elif square.mean() > 6.0:\r\n        return [True, False]\r\n    else:\r\n        if square.mean() > 2.0:\r\n            print(\"empty \" + str(square.mean()))\r\n        return [False]\r\n\r\n\r\ndef detect_state(frame, view, roi_mask):\r\n    edges = edge_detection(frame)\r\n    edges = cv2.bitwise_and(edges, roi_mask)\r\n    # cv2.imwrite(\"edge.jpg\", edges)\r\n    board_image = [[get_square_image(row, column, edges) for column in range(8)] for row\r\n                   in\r\n                   range(8)]\r\n    result = [[contains_piece(board_image[row][column], view) for column in range(8)] for row in\r\n              range(8)]\r\n    return result\r\n\r\n\r\ndef predict(image, model):\r\n    image = cv2.resize(image, (64, 64))\r\n    image = image.astype(np.float32) / 255.0\r\n    image = np.transpose(image, (2, 0, 1))\r\n    image = np.expand_dims(image, axis=0)\r\n\r\n    # Make a forward pass through the network\r\n    model.setInput(image)\r\n    output = model.forward()\r\n\r\n    # Get the predicted class label\r\n    label = np.argmax(output)\r\n    return label\r\n"
  },
  {
    "path": "internet_game.py",
    "content": "import chessboard_detection\r\nimport pyautogui\r\nimport time\r\n\r\n\r\nclass Internet_game:\r\n    def __init__(self, use_template, start_delay, drag_drop):\r\n        self.drag_drop = drag_drop\r\n        time.sleep(start_delay)\r\n        if use_template:\r\n            self.position, self.we_play_white = chessboard_detection.find_chessboard()\r\n        else:\r\n            self.position, self.we_play_white = chessboard_detection.auto_find_chessboard()\r\n        self.is_our_turn = self.we_play_white\r\n\r\n    def move(self, move):\r\n        move_string = move.uci()\r\n\r\n        origin_square = move_string[0:2]\r\n        destination_square = move_string[2:4]\r\n\r\n        centerXOrigin, centerYOrigin = self.get_square_center(origin_square)\r\n        centerXDest, centerYDest = self.get_square_center(destination_square)\r\n\r\n        if self.drag_drop:\r\n            pyautogui.moveTo(centerXOrigin, centerYOrigin, 0.01)\r\n            pyautogui.dragTo(centerXOrigin, centerYOrigin + 1, button='left',\r\n                             duration=0.01)\r\n            pyautogui.dragTo(centerXDest, centerYDest, button='left', duration=0.3)\r\n        else:\r\n            pyautogui.click(centerXOrigin, centerYOrigin, duration=0.1)\r\n            pyautogui.click(centerXDest, centerYDest, duration=0.1)\r\n\r\n        print(\"Done playing move\", origin_square, destination_square)\r\n        return\r\n\r\n    def get_square_center(self, square_name):\r\n        row, column = self.convert_square_name_to_row_column(square_name, self.we_play_white)\r\n        position = self.position\r\n        centerX = int(position.minX + (column + 0.5) * (position.maxX - position.minX) / 8)\r\n        centerY = int(position.minY + (row + 0.5) * (position.maxY - position.minY) / 8)\r\n        return centerX, centerY\r\n\r\n    def convert_square_name_to_row_column(self, square_name, is_white_on_bottom):\r\n        for row in range(8):\r\n            for column in range(8):\r\n                this_square_name = self.convert_row_column_to_square_name(row, column, is_white_on_bottom)\r\n                if this_square_name == square_name:\r\n                    return row, column\r\n        return 0, 0\r\n\r\n    def convert_row_column_to_square_name(self, row, column, is_white_on_bottom):\r\n        if is_white_on_bottom == True:\r\n            number = repr(8 - row)\r\n            letter = str(chr(97 + column))\r\n            return letter + number\r\n        else:\r\n            number = repr(row + 1)\r\n            letter = str(chr(97 + (7 - column)))\r\n            return letter + number\r\n"
  },
  {
    "path": "languages.py",
    "content": "import chess\r\n\r\n\r\nclass English:\r\n    def __init__(self):\r\n        self.game_started = \"Game started\"\r\n        self.move_failed = \"Move registration failed. Please redo your move.\"\r\n\r\n    def name(self, piece_type):\r\n        if piece_type == chess.PAWN:\r\n            return \"pawn\"\r\n        elif piece_type == chess.KNIGHT:\r\n            return \"knight\"\r\n        elif piece_type == chess.BISHOP:\r\n            return \"bishop\"\r\n        elif piece_type == chess.ROOK:\r\n            return \"rook\"\r\n        elif piece_type == chess.QUEEN:\r\n            return \"queen\"\r\n        elif piece_type == chess.KING:\r\n            return \"king\"\r\n\r\n    def comment(self, board, move):\r\n        check = \"\"\r\n        if board.is_checkmate():\r\n            check = \" checkmate\"\r\n        elif board.is_check():\r\n            check = \" check\"\r\n        board.pop()\r\n        if board.is_kingside_castling(move):\r\n            board.push(move)\r\n            return \"castling short\" + check\r\n        if board.is_queenside_castling(move):\r\n            board.push(move)\r\n            return \"castling long\" + check\r\n\r\n        piece = board.piece_at(move.from_square)\r\n        from_square = chess.square_name(move.from_square)\r\n        to_square = chess.square_name(move.to_square)\r\n        promotion = move.promotion\r\n\r\n        is_capture = board.is_capture(move)\r\n        board.push(move)\r\n        comment = \"\"\r\n        comment += self.name(piece.piece_type)\r\n\r\n        comment += \" \" + from_square\r\n        comment += \" takes\" if is_capture else \" to\"\r\n        comment += \" \" + to_square\r\n        if promotion:\r\n            comment += \" promotion to \" + self.name(promotion)\r\n        comment += check\r\n        return comment\r\n\r\n\r\nclass German:\r\n    def __init__(self):\r\n        self.game_started = \"Das Spiel hat gestartet.\"\r\n        self.move_failed = \"Der Zug ist ungültig, bitte wiederholen.\"\r\n\r\n    def name(self, piece_type):\r\n        if piece_type == chess.PAWN:\r\n            return \"Bauer\"\r\n        elif piece_type == chess.KNIGHT:\r\n            return \"Springer\"\r\n        elif piece_type == chess.BISHOP:\r\n            return \"Läufer\"\r\n        elif piece_type == chess.ROOK:\r\n            return \"Turm\"\r\n        elif piece_type == chess.QUEEN:\r\n            return \"Dame\"\r\n        elif piece_type == chess.KING:\r\n            return \"König\"\r\n\r\n    def comment(self, board, move):\r\n        check = \"\"\r\n        if board.is_checkmate():\r\n            check = \" Schachmatt\"\r\n        elif board.is_check():\r\n            check = \" Schach\"\r\n        board.pop()\r\n        if board.is_kingside_castling(move):\r\n            board.push(move)\r\n            return \"kurze Rochade\" + check\r\n        if board.is_queenside_castling(move):\r\n            board.push(move)\r\n            return \"lange Rochade\" + check\r\n\r\n        piece = board.piece_at(move.from_square)\r\n        from_square = chess.square_name(move.from_square)\r\n        to_square = chess.square_name(move.to_square)\r\n        promotion = move.promotion\r\n\r\n        is_capture = board.is_capture(move)\r\n        board.push(move)\r\n        comment = \"\"\r\n        comment += self.name(piece.piece_type)\r\n\r\n        comment += \" \" + from_square\r\n        comment += \" schlägt\" if is_capture else \" nach\"\r\n        comment += \" \" + to_square\r\n        if promotion:\r\n            comment += \" Umwandlung in \" + self.name(promotion)\r\n        comment += check\r\n        return comment\r\n\r\n\r\nclass Russian:\r\n    def __init__(self):\r\n        self.game_started = \"игра началась\"\r\n        self.move_failed = \"Ошибка регистрации хода. Пожалуйста, повторите свой ход\"\r\n\r\n    def name(self, piece_type):\r\n        if piece_type == chess.PAWN:\r\n            return \"пешка\"\r\n        elif piece_type == chess.KNIGHT:\r\n            return \"конь\"\r\n        elif piece_type == chess.BISHOP:\r\n            return \"слон\"\r\n        elif piece_type == chess.ROOK:\r\n            return \"ладья\"\r\n        elif piece_type == chess.QUEEN:\r\n            return \"ферзь\"\r\n        elif piece_type == chess.KING:\r\n            return \"король\"\r\n\r\n    def comment(self, board, move):\r\n        check = \"\"\r\n        if board.is_checkmate():\r\n            check = \" шах и мат\"\r\n        elif board.is_check():\r\n            check = \" шах\"\r\n        board.pop()\r\n        if board.is_kingside_castling(move):\r\n            board.push(move)\r\n            return \"короткая рокировка\" + check\r\n        if board.is_queenside_castling(move):\r\n            board.push(move)\r\n            return \"длинная рокировка\" + check\r\n\r\n        piece = board.piece_at(move.from_square)\r\n        from_square = chess.square_name(move.from_square)\r\n        to_square = chess.square_name(move.to_square)\r\n        promotion = move.promotion\r\n\r\n        is_capture = board.is_capture(move)\r\n        board.push(move)\r\n        comment = \"\"\r\n        comment += self.name(piece.piece_type)\r\n\r\n        comment += \" \" + from_square\r\n        comment += \" бьёт\" if is_capture else \"\"\r\n        comment += \" \" + to_square\r\n        if promotion:\r\n            comment += \" превращение в \" + self.name(promotion)\r\n        comment += check\r\n        return comment\r\n\r\n\r\nclass Turkish:\r\n    def __init__(self):\r\n        self.game_started = \"Oyun başladı.\"\r\n        self.move_failed = \"Hamle geçersiz. Lütfen hamlenizi yeniden yapın.\"\r\n\r\n    def capture_suffix(self, to_square):\r\n        if to_square[-1] in \"158\":\r\n            return \"i\"\r\n        elif to_square[-1] in \"27\":\r\n            return \"yi\"\r\n        elif to_square[-1] in \"34\":\r\n            return \"ü\"\r\n        else:  # 6\r\n            return \"yı\"\r\n\r\n    def from_suffix(self, from_square):\r\n        if from_square[-1] in \"1278\":\r\n            return \"den\"\r\n        elif from_square[-1] in \"345\":\r\n            return \"ten\"\r\n        else:  # 6\r\n            return \"dan\"\r\n\r\n    def to_suffix(self, to_square):\r\n        if to_square[-1] in \"13458\":\r\n            return \"e\"\r\n        elif to_square[-1] in \"27\":\r\n            return \"ye\"\r\n        else:  # 6\r\n            return \"ya\"\r\n\r\n    def comment(self, board, move):\r\n        check = \"\"\r\n        if board.is_checkmate():\r\n            check = \" şahmat\"\r\n        elif board.is_check():\r\n            check = \" şah\"\r\n        board.pop()\r\n        if board.is_kingside_castling(move):\r\n            board.push(move)\r\n            return \"kısa rok\" + check\r\n        if board.is_queenside_castling(move):\r\n            board.push(move)\r\n            return \"uzun rok\" + check\r\n\r\n        piece = board.piece_at(move.from_square)\r\n        from_square = chess.square_name(move.from_square)\r\n        to_square = chess.square_name(move.to_square)\r\n        promotion = move.promotion\r\n\r\n        is_capture = board.is_capture(move)\r\n        board.push(move)\r\n        comment = \"\"\r\n        if piece.piece_type == chess.PAWN:\r\n            comment += \"piyon\"\r\n        elif piece.piece_type == chess.KNIGHT:\r\n            comment += \"at\"\r\n        elif piece.piece_type == chess.BISHOP:\r\n            comment += \"fil\"\r\n        elif piece.piece_type == chess.ROOK:\r\n            comment += \"kale\"\r\n        elif piece.piece_type == chess.QUEEN:\r\n            comment += \"vezir\"\r\n        elif piece.piece_type == chess.KING:\r\n            comment += \"şah\"\r\n\r\n        comment += \" \" + from_square\r\n        if is_capture:\r\n            comment += \" alır\"\r\n            comment += \" \" + to_square + \"'\" + self.capture_suffix(to_square)\r\n        else:\r\n            comment += \"'\" + self.from_suffix(from_square) + \" \" + to_square + \"'\" + self.to_suffix(to_square)\r\n\r\n        if promotion:\r\n            comment += \" \"\r\n            if promotion == chess.KNIGHT:\r\n                comment += \"ata\"\r\n            elif promotion == chess.BISHOP:\r\n                comment += \"file\"\r\n            elif promotion == chess.ROOK:\r\n                comment += \"kaleye\"\r\n            elif promotion == chess.QUEEN:\r\n                comment += \"vezire\"\r\n            comment += \" terfi\"\r\n        comment += check\r\n        return comment\r\n\r\n\r\nclass Italian:\r\n    def __init__(self):\r\n        self.game_started = \"Gioco iniziato\"\r\n        self.move_failed = \"Registrazione spostamento non riuscita. Per favore rifai la tua mossa.\"\r\n\r\n    def name(self, piece_type):\r\n        if piece_type == chess.PAWN:\r\n            return \"pedone\"\r\n        elif piece_type == chess.KNIGHT:\r\n            return \"cavallo\"\r\n        elif piece_type == chess.BISHOP:\r\n            return \"alfiere\"\r\n        elif piece_type == chess.ROOK:\r\n            return \"torre\"\r\n        elif piece_type == chess.QUEEN:\r\n            return \"regina\"\r\n        elif piece_type == chess.KING:\r\n            return \"re\"\r\n\r\n    def prefix_name(self, piece_type):\r\n        if piece_type == chess.PAWN:\r\n            return \"il pedone\"\r\n        elif piece_type == chess.KNIGHT:\r\n            return \"il cavallo\"\r\n        elif piece_type == chess.BISHOP:\r\n            return \"l'alfiere\"\r\n        elif piece_type == chess.ROOK:\r\n            return \"la torre\"\r\n        elif piece_type == chess.QUEEN:\r\n            return \"la regina\"\r\n        elif piece_type == chess.KING:\r\n            return \"il re\"\r\n\r\n    def comment(self, board, move):\r\n        check = \"\"\r\n        if board.is_checkmate():\r\n            check = \" scacco matto\"\r\n        elif board.is_check():\r\n            check = \" scacco\"\r\n        board.pop()\r\n        if board.is_kingside_castling(move):\r\n            board.push(move)\r\n            return \"arrocco corto\" + check\r\n        if board.is_queenside_castling(move):\r\n            board.push(move)\r\n            return \"arrocco lungo\" + check\r\n\r\n        piece = board.piece_at(move.from_square)\r\n        from_square = chess.square_name(move.from_square)\r\n        to_square = chess.square_name(move.to_square)\r\n        promotion = move.promotion\r\n\r\n        is_capture = board.is_capture(move)\r\n        board.push(move)\r\n        comment = \"\"\r\n        if is_capture:\r\n            comment += self.prefix_name(piece.piece_type)\r\n            comment += \" \" + from_square\r\n            comment += \" cattura\"\r\n            comment += \" \" + to_square\r\n        else:\r\n            comment += self.name(piece.piece_type)\r\n            comment += \" da \" + from_square\r\n            comment += \" a \" + to_square\r\n        if promotion:\r\n            comment += \" promuove a \" + self.name(promotion)\r\n        comment += check\r\n        return comment\r\n\r\n\r\nclass French:\r\n    def __init__(self):\r\n        self.game_started = \"Partie démarrée\"\r\n        self.move_failed = \"La reconnaissance a échoué. Veuillez réessayer.\"\r\n\r\n    def name(self, piece_type):\r\n        if piece_type == chess.PAWN:\r\n            return \"pion\"\r\n        elif piece_type == chess.KNIGHT:\r\n            return \"cavalier\"\r\n        elif piece_type == chess.BISHOP:\r\n            return \"fou\"\r\n        elif piece_type == chess.ROOK:\r\n            return \"tour\"\r\n        elif piece_type == chess.QUEEN:\r\n            return \"reine\"\r\n        elif piece_type == chess.KING:\r\n            return \"roi\"\r\n\r\n    def comment(self, board, move):\r\n        check = \"\"\r\n        if board.is_checkmate():\r\n            check = \" échec et mat\"\r\n        elif board.is_check():\r\n            check = \" échec\"\r\n        board.pop()\r\n        if board.is_kingside_castling(move):\r\n            board.push(move)\r\n            return \"petit roc\" + check\r\n        if board.is_queenside_castling(move):\r\n            board.push(move)\r\n            return \"grand roc\" + check\r\n\r\n        piece = board.piece_at(move.from_square)\r\n        from_square = chess.square_name(move.from_square)\r\n        to_square = chess.square_name(move.to_square)\r\n        promotion = move.promotion\r\n\r\n        is_capture = board.is_capture(move)\r\n        board.push(move)\r\n        comment = \"\"\r\n        comment += self.name(piece.piece_type)\r\n\r\n        comment += \" \" + from_square\r\n        comment += \" prend\" if is_capture else \" vers\"\r\n        comment += \" \" + to_square\r\n        if promotion:\r\n            comment += \" promu en \" + self.name(promotion)\r\n        comment += check\r\n        return comment\r\n"
  },
  {
    "path": "lichess_commentator.py",
    "content": "from threading import Thread\r\nimport chess\r\n\r\n\r\nclass Lichess_commentator(Thread):\r\n\r\n    def __init__(self, *args, **kwargs):\r\n        super(Lichess_commentator, self).__init__(*args, **kwargs)\r\n        self.stream = None\r\n        self.speech_thread = None\r\n        self.game_state = Game_state()\r\n        self.comment_me = None\r\n        self.comment_opponent = None\r\n        self.language = None\r\n\r\n    def run(self):\r\n        while not self.game_state.board.is_game_over():\r\n            is_my_turn = (self.game_state.we_play_white) == (self.game_state.board.turn == chess.WHITE)\r\n            found_move, move = self.game_state.register_move_if_needed(self.stream)\r\n            if found_move and ((self.comment_me and is_my_turn) or (self.comment_opponent and (not is_my_turn))):\r\n                self.speech_thread.put_text(self.language.comment(self.game_state.board, move))\r\n\r\n\r\nclass Game_state:\r\n\r\n    def __init__(self):\r\n        self.we_play_white = None\r\n        self.board = chess.Board()\r\n        self.registered_moves = []\r\n        self.resign_or_draw = False\r\n        self.game = None\r\n        self.variant = 'wait'\r\n\r\n    def register_move_if_needed(self, stream):\r\n        current_state = next(stream)\r\n        if 'state' in current_state:\r\n            if current_state['initialFen'] == 'startpos':\r\n                self.variant = 'standard'\r\n            else:\r\n                self.variant = 'fromPosition'\r\n                self.from_position(current_state['initialFen'])\r\n            current_state = current_state['state']\r\n        if 'moves' in current_state:\r\n            moves = current_state['moves'].split()\r\n            if len(moves) > len(self.registered_moves):\r\n                valid_move_string = moves[len(self.registered_moves)]\r\n                valid_move_UCI = chess.Move.from_uci(valid_move_string)\r\n                self.register_move(valid_move_UCI)\r\n                return True, valid_move_UCI\r\n            while len(moves) < len(self.registered_moves):\r\n                self.unregister_move()\r\n        if 'status' in current_state and current_state['status'] in [\"resign\", \"draw\"]:\r\n            self.resign_or_draw = True\r\n        return False, \"No move found\"\r\n\r\n    def register_move(self, move):\r\n        if move in self.board.legal_moves:\r\n            self.board.push(move)\r\n            self.registered_moves.append(move)\r\n            return True\r\n        else:\r\n            return False\r\n\r\n    def unregister_move(self):\r\n        self.board.pop()\r\n        self.registered_moves.pop()\r\n        if len(self.registered_moves) < len(self.game.executed_moves):\r\n            self.game.executed_moves.pop()\r\n            self.game.played_moves.pop()\r\n            self.game.board.pop()\r\n            self.game.internet_game.is_our_turn = not self.game.internet_game.is_our_turn\r\n\r\n    def from_position(self, fen):\r\n        self.board = chess.Board(fen)\r\n        self.game.board = chess.Board(fen)\r\n        if self.board.turn == chess.BLACK:\r\n            self.game.internet_game.is_our_turn = not self.game.internet_game.is_our_turn\r\n"
  },
  {
    "path": "lichess_game.py",
    "content": "import berserk\r\nimport sys\r\nimport os\r\nimport chess\r\nimport pickle\r\n\r\n\r\nclass Lichess_game:\r\n    def __init__(self, token):\r\n        session = berserk.TokenSession(token)\r\n        client = berserk.Client(session)\r\n        games = client.games.get_ongoing()\r\n        if len(games) == 0:\r\n            print(\"No games found. Please create your game on Lichess.\")\r\n            sys.exit(0)\r\n        if len(games) > 1:\r\n            print(\"Multiple games found. Please make sure there is only one ongoing game on Lichess.\")\r\n            sys.exit(0)\r\n        game = games[0]\r\n        self.we_play_white = game['color'] == 'white'\r\n        self.is_our_turn = self.we_play_white\r\n        self.client = client\r\n        self.game_id = game['gameId']\r\n        self.token = token\r\n        self.save_file = \"promotion.bin\"\r\n        self.promotion_pieces = {\r\n            \"Queen\": chess.QUEEN,\r\n            \"Knight\": chess.KNIGHT,\r\n            \"Rook\": chess.ROOK,\r\n            \"Bishop\": chess.BISHOP\r\n        }\r\n\r\n    def move(self, move):\r\n        if move.promotion and os.path.exists(self.save_file):\r\n            infile = open(self.save_file, 'rb')\r\n            piece_name = pickle.load(infile)\r\n            infile.close()\r\n            move.promotion = self.promotion_pieces[piece_name]\r\n        move_string = move.uci()\r\n        try:\r\n            self.client.board.make_move(self.game_id, move_string)\r\n        except:\r\n            session = berserk.TokenSession(self.token)\r\n            self.client = berserk.Client(session)\r\n            self.client.board.make_move(self.game_id, move_string)\r\n            print(\"Reconnected to Lichess.\")\r\n        print(\"Done playing move \" + move_string)\r\n"
  },
  {
    "path": "main.py",
    "content": "import time\r\nimport cv2\r\nimport pickle\r\nimport numpy as np\r\nimport sys\r\nfrom collections import deque\r\nimport platform\r\nfrom board_calibration_machine_learning import detect_board\r\nfrom game import Game\r\nfrom board_basics import Board_basics\r\nfrom helper import perspective_transform\r\nfrom speech import Speech_thread\r\nfrom videocapture import Video_capture_thread\r\nfrom languages import *\r\n\r\nwebcam_width = None\r\nwebcam_height = None\r\nfps = None\r\nuse_template = True\r\nmake_opponent = False\r\ndrag_drop = False\r\ncomment_me = False\r\ncomment_opponent = False\r\ncalibrate = False\r\nstart_delay = 5  # seconds\r\ncap_index = 0\r\ncap_api = cv2.CAP_ANY\r\nvoice_index = 0\r\nlanguage = English()\r\ntoken = \"\"\r\nfor argument in sys.argv:\r\n    if argument == \"no-template\":\r\n        use_template = False\r\n    elif argument == \"make-opponent\":\r\n        make_opponent = True\r\n    elif argument == \"comment-me\":\r\n        comment_me = True\r\n    elif argument == \"comment-opponent\":\r\n        comment_opponent = True\r\n    elif argument.startswith(\"delay=\"):\r\n        start_delay = int(\"\".join(c for c in argument if c.isdigit()))\r\n    elif argument == \"drag\":\r\n        drag_drop = True\r\n    elif argument.startswith(\"cap=\"):\r\n        cap_index = int(\"\".join(c for c in argument if c.isdigit()))\r\n        platform_name = platform.system()\r\n        if platform_name == \"Darwin\":\r\n            cap_api = cv2.CAP_AVFOUNDATION\r\n        elif platform_name == \"Linux\":\r\n            cap_api = cv2.CAP_V4L2\r\n        else:\r\n            cap_api = cv2.CAP_DSHOW\r\n    elif argument.startswith(\"voice=\"):\r\n        voice_index = int(\"\".join(c for c in argument if c.isdigit()))\r\n    elif argument.startswith(\"lang=\"):\r\n        if \"German\" in argument:\r\n            language = German()\r\n        elif \"Russian\" in argument:\r\n            language = Russian()\r\n        elif \"Turkish\" in argument:\r\n            language = Turkish()\r\n        elif \"Italian\" in argument:\r\n            language = Italian()\r\n        elif \"French\" in argument:\r\n            language = French()\r\n    elif argument.startswith(\"token=\"):\r\n        token = argument[len(\"token=\"):].strip()\r\n    elif argument == \"calibrate\":\r\n        calibrate = True\r\n    elif argument.startswith(\"width=\"):\r\n        webcam_width = int(argument[len(\"width=\"):])\r\n    elif argument.startswith(\"height=\"):\r\n        webcam_height = int(argument[len(\"height=\"):])\r\n    elif argument.startswith(\"fps=\"):\r\n        fps = int(argument[len(\"fps=\"):])\r\nMOTION_START_THRESHOLD = 1.0\r\nHISTORY = 100\r\nMAX_MOVE_MEAN = 50\r\nCOUNTER_MAX_VALUE = 3\r\n\r\nmove_fgbg = cv2.createBackgroundSubtractorKNN()\r\nmotion_fgbg = cv2.createBackgroundSubtractorKNN(history=HISTORY)\r\n\r\nvideo_capture_thread = Video_capture_thread()\r\nvideo_capture_thread.daemon = True\r\nvideo_capture_thread.capture = cv2.VideoCapture(cap_index, cap_api)\r\nif webcam_width is not None:\r\n    video_capture_thread.capture.set(cv2.CAP_PROP_FRAME_WIDTH, webcam_width)\r\nif webcam_height is not None:\r\n    video_capture_thread.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, webcam_height)\r\nif fps is not None:\r\n    video_capture_thread.capture.set(cv2.CAP_PROP_FPS, fps)\r\nif calibrate:\r\n    corner_model = cv2.dnn.readNetFromONNX(\"yolo_corner.onnx\")\r\n    piece_model = cv2.dnn.readNetFromONNX(\"cnn_piece.onnx\")\r\n    color_model = cv2.dnn.readNetFromONNX(\"cnn_color.onnx\")\r\n    for _ in range(10):\r\n        ret, frame = video_capture_thread.capture.read()\r\n        if ret == False:\r\n            print(\"Error reading frame. Please check your webcam connection.\")\r\n            continue\r\n    is_detected = False\r\n    for _ in range(100):\r\n        ret, frame = video_capture_thread.capture.read()\r\n        if ret == False:\r\n            print(\"Error reading frame. Please check your webcam connection.\")\r\n            continue\r\n        result = detect_board(frame, corner_model, piece_model, color_model)\r\n        if result:\r\n            pts1, side_view_compensation, rotation_count = result\r\n            roi_mask = None\r\n            is_detected = True\r\n            break\r\n    if not is_detected:\r\n        print(\"Could not detect the chess board.\")\r\n        video_capture_thread.capture.release()\r\n        sys.exit(0)\r\nelse:\r\n    filename = 'constants.bin'\r\n    infile = open(filename, 'rb')\r\n    calibration_data = pickle.load(infile)\r\n    infile.close()\r\n    if calibration_data[0]:\r\n        pts1, side_view_compensation, rotation_count = calibration_data[1]\r\n        roi_mask = None\r\n    else:\r\n        corners, side_view_compensation, rotation_count, roi_mask = calibration_data[1]\r\n        pts1 = np.float32([list(corners[0][0]), list(corners[8][0]), list(corners[0][8]),\r\n                           list(corners[8][8])])\r\nvideo_capture_thread.start()\r\nboard_basics = Board_basics(side_view_compensation, rotation_count)\r\n\r\nspeech_thread = Speech_thread()\r\nspeech_thread.daemon = True\r\nspeech_thread.index = voice_index\r\nspeech_thread.start()\r\n\r\ngame = Game(board_basics, speech_thread, use_template, make_opponent, start_delay, comment_me, comment_opponent,\r\n            drag_drop, language, token, roi_mask)\r\n\r\ndef waitUntilMotionCompletes():\r\n    counter = 0\r\n    while counter < COUNTER_MAX_VALUE:\r\n        frame = video_capture_thread.get_frame()\r\n        frame = perspective_transform(frame, pts1)\r\n        fgmask = motion_fgbg.apply(frame)\r\n        ret, fgmask = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY)\r\n        mean = fgmask.mean()\r\n        if mean < MOTION_START_THRESHOLD:\r\n            counter += 1\r\n        else:\r\n            counter = 0\r\n\r\n\r\ndef stabilize_background_subtractors():\r\n    best_mean = float(\"inf\")\r\n    counter = 0\r\n    while counter < COUNTER_MAX_VALUE:\r\n        frame = video_capture_thread.get_frame()\r\n        frame = perspective_transform(frame, pts1)\r\n        move_fgbg.apply(frame)\r\n        fgmask = motion_fgbg.apply(frame, learningRate=0.1)\r\n        ret, fgmask = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY)\r\n        mean = fgmask.mean()\r\n        if mean >= best_mean:\r\n            counter += 1\r\n        else:\r\n            best_mean = mean\r\n            counter = 0\r\n\r\n    best_mean = float(\"inf\")\r\n    counter = 0\r\n    while counter < COUNTER_MAX_VALUE:\r\n        frame = video_capture_thread.get_frame()\r\n        frame = perspective_transform(frame, pts1)\r\n        fgmask = move_fgbg.apply(frame, learningRate=0.1)\r\n        ret, fgmask = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY)\r\n        motion_fgbg.apply(frame)\r\n        mean = fgmask.mean()\r\n        if mean >= best_mean:\r\n            counter += 1\r\n        else:\r\n            best_mean = mean\r\n            counter = 0\r\n\r\n    return frame\r\n\r\n\r\nprevious_frame = stabilize_background_subtractors()\r\nprevious_frame_queue = deque(maxlen=10)\r\nprevious_frame_queue.append(previous_frame)\r\nspeech_thread.put_text(language.game_started)\r\ngame.commentator.start()\r\nwhile game.commentator.game_state.variant == 'wait':\r\n    time.sleep(0.1)\r\nif game.commentator.game_state.variant == 'standard':\r\n    board_basics.initialize_ssim(previous_frame)\r\n    game.initialize_hog(previous_frame)\r\nelse:\r\n    board_basics.load_ssim()\r\n    game.load_hog()\r\nwhile not game.board.is_game_over() and not game.commentator.game_state.resign_or_draw:\r\n    sys.stdout.flush()\r\n    frame = video_capture_thread.get_frame()\r\n    frame = perspective_transform(frame, pts1)\r\n    fgmask = motion_fgbg.apply(frame)\r\n    ret, fgmask = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY)\r\n    kernel = np.ones((11, 11), np.uint8)\r\n    fgmask = cv2.erode(fgmask, kernel, iterations=1)\r\n    mean = fgmask.mean()\r\n    if mean > MOTION_START_THRESHOLD:\r\n        # cv2.imwrite(\"motion.jpg\", fgmask)\r\n        waitUntilMotionCompletes()\r\n        frame = video_capture_thread.get_frame()\r\n        frame = perspective_transform(frame, pts1)\r\n        fgmask = move_fgbg.apply(frame, learningRate=0.0)\r\n        if fgmask.mean() >= 10.0:\r\n            ret, fgmask = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY)\r\n        # print(\"Move mean \" + str(fgmask.mean()))\r\n        if fgmask.mean() >= MAX_MOVE_MEAN:\r\n            fgmask = np.zeros(fgmask.shape, dtype=np.uint8)\r\n        motion_fgbg.apply(frame)\r\n        move_fgbg.apply(frame, learningRate=1.0)\r\n        last_frame = stabilize_background_subtractors()\r\n        previous_frame = previous_frame_queue[0]\r\n\r\n        if (game.is_light_change(last_frame) == False) and game.register_move(fgmask, previous_frame, last_frame):\r\n            pass\r\n            # cv2.imwrite(game.executed_moves[-1] + \" frame.jpg\", last_frame)\r\n            # cv2.imwrite(game.executed_moves[-1] + \" mask.jpg\", fgmask)\r\n            # cv2.imwrite(game.executed_moves[-1] + \" background.jpg\", previous_frame)\r\n        else:\r\n            pass\r\n            # import uuid\r\n            # id = str(uuid.uuid1())\r\n            # cv2.imwrite(id+\"frame_fail.jpg\", last_frame)\r\n            # cv2.imwrite(id+\"mask_fail.jpg\", fgmask)\r\n            # cv2.imwrite(id+\"background_fail.jpg\", previous_frame)\r\n        previous_frame_queue = deque(maxlen=10)\r\n        previous_frame_queue.append(last_frame)\r\n    else:\r\n        move_fgbg.apply(frame)\r\n        previous_frame_queue.append(frame)\r\ncv2.destroyAllWindows()\r\ntime.sleep(2)\r\n"
  },
  {
    "path": "requirements.txt",
    "content": "opencv-python\r\npython-chess\r\npyautogui\r\nmss\r\nnumpy\r\npyttsx3\r\nscikit-image\r\npygrabber\r\nberserk"
  },
  {
    "path": "speech.py",
    "content": "from threading import Thread\r\nfrom queue import Queue\r\nimport platform\r\nimport os\r\nimport subprocess\r\n\r\n\r\nclass Speech_thread(Thread):\r\n\r\n    def __init__(self, *args, **kwargs):\r\n        super(Speech_thread, self).__init__(*args, **kwargs)\r\n        self.queue = Queue()\r\n        self.index = None\r\n\r\n    def run(self):\r\n        if platform.system() == \"Darwin\":\r\n            result = subprocess.run(['say', '-v', '?'], stdout=subprocess.PIPE)\r\n            output = result.stdout.decode('utf-8')\r\n            voices = []\r\n            for line in output.splitlines():\r\n                if line:\r\n                    voices.append(line.split()[0])\r\n            name = voices[self.index]\r\n            while True:\r\n                text = self.queue.get()\r\n                os.system(f'say -v {name} \"{text}\"')\r\n        else:\r\n            import pyttsx3\r\n            while True:\r\n                engine = pyttsx3.init()\r\n                voices = engine.getProperty('voices')\r\n                voice = voices[self.index]\r\n                engine.setProperty('voice', voice.id)\r\n                text = self.queue.get()\r\n                engine.say(text)\r\n                engine.runAndWait()\r\n\r\n    def put_text(self, text):\r\n        self.queue.put(text)\r\n"
  },
  {
    "path": "videocapture.py",
    "content": "from threading import Thread\r\nfrom queue import Queue\r\n\r\n\r\nclass Video_capture_thread(Thread):\r\n\r\n    def __init__(self, *args, **kwargs):\r\n        super(Video_capture_thread, self).__init__(*args, **kwargs)\r\n        self.queue = Queue()\r\n        self.capture = None\r\n\r\n    def run(self):\r\n        while True:\r\n            ret, frame = self.capture.read()\r\n            if ret == False:\r\n                continue\r\n            self.queue.put(frame)\r\n\r\n    def get_frame(self):\r\n        return self.queue.get()\r\n"
  }
]