main d62da44c11c8 cached
23 files
10.3 MB
39.0k tokens
137 symbols
1 requests
Download .txt
Repository: karayaman/Play-online-chess-with-real-chess-board
Branch: main
Commit: d62da44c11c8
Files: 23
Total size: 10.3 MB

Directory structure:
gitextract_antnu9xm/

├── LICENSE
├── README.md
├── board_basics.py
├── board_calibration.py
├── board_calibration_machine_learning.py
├── chessboard_detection.py
├── classifier.py
├── cnn_color.onnx
├── cnn_piece.onnx
├── commentator.py
├── diagnostic.py
├── game.py
├── gui.py
├── helper.py
├── internet_game.py
├── languages.py
├── lichess_commentator.py
├── lichess_game.py
├── main.py
├── requirements.txt
├── speech.py
├── videocapture.py
└── yolo_corner.onnx

================================================
FILE CONTENTS
================================================

================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# Play online chess with a real chess board
Program 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.

## Setup

1. 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. 
2. 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.
3. Enable auto-promotion to queen from settings of online game. You can skip this step if you enter your Lichess API Access Token.
4. Place your webcam near to your chessboard so that all of the squares and pieces can be clearly seen by it.
5. Select a board calibration mode and follow its instructions.

## Board Calibration(The board is empty.)

1. Remove all pieces from your chess board.

2. Click the "Board Calibration" button.

3. 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:

   ![](https://github.com/karayaman/Play-online-chess-with-real-chess-board/blob/main/chessboard_detection_result.jpg?raw=true)

## Board Calibration(Pieces are in their starting positions.)

1. Place the pieces in their starting positions.
2. Click the "Board Calibration" button.
3. Please ensure your chess board is correctly positioned and detected. Guiding lines will be drawn to mark the board's edges:
   - The line near the white pieces will be blue.
   - The line near the black pieces will be green.
   - Press any key to exit once you've confirmed the board setup.

<img src="https://github.com/karayaman/Play-online-chess-with-real-chess-board/raw/main/board_detection_result.jpg" style="zoom:67%;" />

## Board Calibration(Just before the game starts.)

1. Click the "Start Game" button. The software will calibrate the board just before it begins move recognition.

## Usage

1. Place pieces of chess board to their starting position.
2. Start the online game.
3. Click the "Start Game" button.
4. 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.
5.  Wait until the program says "game started".
6. Make your move if it's your turn , otherwise make your opponent's move.
8. 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.
9. Go to step 6.

## GUI

You 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).

![](https://github.com/karayaman/Play-online-chess-with-real-chess-board/blob/main/gui.jpg?raw=true)

## Diagnostic

You 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.

![](https://github.com/karayaman/Play-online-chess-with-real-chess-board/blob/main/diagnostic.jpg?raw=true)

## Video

In this section you can find video content related to the software.

[Play online chess with real chess board and web camera | NO DGT BOARD!](https://www.youtube.com/watch?v=LX-4czb3xi0&lc=Ugxo6cXY0cR2TArDpuZ4AaABAg)

## Frequently Asked Questions

### What is the program doing? How does it work? 

It 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.

### Placing a webcam on top of the chess board sounds difficult. Can I put my laptop aside with the webcam on the laptop display?

Yes, 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.

### How well does it work?

Using this software I am able to make up to 100 moves in 15+10 rapid online game without getting any errors.

### I am getting error message "Move registration failed. Please redo your move." What is the problem?

The 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. 

### Why does it take forever to detect corners of the chess board?

It 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.

## Required libraries

- opencv-python
- python-chess
- pyautogui
- mss
- numpy
- pyttsx3
- scikit-image
- pygrabber
- berserk


================================================
FILE: board_basics.py
================================================
import sys

from skimage.metrics import structural_similarity
import chess
import pickle
import os


class Board_basics:
    def __init__(self, side_view_compensation, rotation_count):
        self.d = [side_view_compensation, (0, 0)]
        self.rotation_count = rotation_count
        self.SSIM_THRESHOLD = 0.8
        self.SSIM_THRESHOLD_LIGHT_WHITE = 1.0
        self.SSIM_THRESHOLD_LIGHT_BLACK = 1.0
        self.SSIM_THRESHOLD_DARK_WHITE = 1.0
        self.SSIM_THRESHOLD_DARK_BLACK = 1.0
        self.ssim_table = [[self.SSIM_THRESHOLD_DARK_BLACK, self.SSIM_THRESHOLD_DARK_WHITE],
                           [self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_LIGHT_WHITE]]
        self.save_file = "ssim.bin"

    def initialize_ssim(self, frame):
        light_white = []
        dark_white = []
        light_empty = []
        dark_empty = []
        light_black = []
        dark_black = []
        for row in range(8):
            for column in range(8):
                square_name = self.convert_row_column_to_square_name(row, column)
                if square_name[1] == "2":
                    if self.is_light(square_name):
                        light_white.append(self.get_square_image(row, column, frame))
                    else:
                        dark_white.append(self.get_square_image(row, column, frame))
                elif square_name[1] == "4":
                    if self.is_light(square_name):
                        light_empty.append(self.get_square_image(row, column, frame))
                    else:
                        dark_empty.append(self.get_square_image(row, column, frame))
                elif square_name[1] == "7":
                    if self.is_light(square_name):
                        light_black.append(self.get_square_image(row, column, frame))
                    else:
                        dark_black.append(self.get_square_image(row, column, frame))
        ssim_light_white = max(structural_similarity(empty,
                                                     piece, channel_axis=-1) for piece, empty in
                               zip(light_white, light_empty))
        ssim_light_black = max(structural_similarity(empty,
                                                     piece, channel_axis=-1) for piece, empty in
                               zip(light_black, light_empty))
        ssim_dark_white = max(structural_similarity(empty,
                                                    piece, channel_axis=-1) for piece, empty in
                              zip(dark_white, dark_empty))
        ssim_dark_black = max(structural_similarity(empty,
                                                    piece, channel_axis=-1) for piece, empty in
                              zip(dark_black, dark_empty))
        self.SSIM_THRESHOLD_LIGHT_WHITE = min(self.SSIM_THRESHOLD_LIGHT_WHITE, ssim_light_white + 0.2)
        self.SSIM_THRESHOLD_LIGHT_BLACK = min(self.SSIM_THRESHOLD_LIGHT_BLACK, ssim_light_black + 0.2)
        self.SSIM_THRESHOLD_DARK_WHITE = min(self.SSIM_THRESHOLD_DARK_WHITE, ssim_dark_white + 0.2)
        self.SSIM_THRESHOLD_DARK_BLACK = min(self.SSIM_THRESHOLD_DARK_BLACK, ssim_dark_black + 0.2)
        self.SSIM_THRESHOLD = max(
            [self.SSIM_THRESHOLD, self.SSIM_THRESHOLD_LIGHT_WHITE, self.SSIM_THRESHOLD_LIGHT_BLACK,
             self.SSIM_THRESHOLD_DARK_WHITE, self.SSIM_THRESHOLD_DARK_BLACK])
        print(self.SSIM_THRESHOLD_LIGHT_WHITE, self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_DARK_WHITE,
              self.SSIM_THRESHOLD_DARK_BLACK)
        self.ssim_table = [[self.SSIM_THRESHOLD_DARK_BLACK, self.SSIM_THRESHOLD_DARK_WHITE],
                           [self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_LIGHT_WHITE]]

        outfile = open(self.save_file, 'wb')
        pickle.dump((self.SSIM_THRESHOLD_LIGHT_WHITE, self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_DARK_WHITE,
                     self.SSIM_THRESHOLD_DARK_BLACK, self.SSIM_THRESHOLD), outfile)
        outfile.close()

    def load_ssim(self):
        if os.path.exists(self.save_file):
            infile = open(self.save_file, 'rb')
            (self.SSIM_THRESHOLD_LIGHT_WHITE, self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_DARK_WHITE,
             self.SSIM_THRESHOLD_DARK_BLACK, self.SSIM_THRESHOLD) = pickle.load(infile)
            infile.close()
            print(self.SSIM_THRESHOLD_LIGHT_WHITE, self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_DARK_WHITE,
                  self.SSIM_THRESHOLD_DARK_BLACK)
            self.ssim_table = [[self.SSIM_THRESHOLD_DARK_BLACK, self.SSIM_THRESHOLD_DARK_WHITE],
                               [self.SSIM_THRESHOLD_LIGHT_BLACK, self.SSIM_THRESHOLD_LIGHT_WHITE]]
        else:
            print("You need to play at least 1 game before starting a game from position.")
            sys.exit(0)

    def update_ssim(self, previous_frame, next_frame, move, is_capture, color):
        from_square = chess.square_name(move.from_square)
        to_square = chess.square_name(move.to_square)
        for row in range(8):
            for column in range(8):
                square_name = self.convert_row_column_to_square_name(row, column)
                if square_name not in [from_square, to_square]:
                    continue
                previous_square = self.get_square_image(row, column, previous_frame)
                next_square = self.get_square_image(row, column, next_frame)
                ssim = structural_similarity(next_square, previous_square, channel_axis=-1)
                ssim = ssim + 0.1
                if ssim > self.SSIM_THRESHOLD:
                    self.SSIM_THRESHOLD = ssim
                    print("new threshold is " + str(ssim))
                is_light = int(self.is_light(square_name))
                if (square_name == from_square) or (not is_capture):
                    if ssim > self.ssim_table[is_light][color]:
                        self.ssim_table[is_light][color] = ssim
                        print((is_light, color, ssim))

    def get_square_image(self, row, column,
                         board_img):
        height, width = board_img.shape[:2]
        minX = int(column * width / 8)
        maxX = int((column + 1) * width / 8)
        minY = int(row * height / 8)
        maxY = int((row + 1) * height / 8)
        square = board_img[minY:maxY, minX:maxX]
        return square

    def convert_row_column_to_square_name(self, row, column):
        if self.rotation_count == 0:
            number = repr(8 - row)
            letter = str(chr(97 + column))
        elif self.rotation_count == 1:
            number = repr(8 - column)
            letter = str(chr(97 + (7 - row)))
        elif self.rotation_count == 2:
            number = repr(row + 1)
            letter = str(chr(97 + (7 - column)))
        elif self.rotation_count == 3:
            number = repr(column + 1)
            letter = str(chr(97 + row))
        return letter + number

    def square_region(self, row, column):
        region = set()
        for d_row, d_column in self.d:
            n_row = row + d_row
            n_column = column + d_column
            if not (0 <= n_row < 8):
                continue
            if not (0 <= n_column < 8):
                continue
            region.add((n_row, column))
        return region

    def is_light(self, square_name):
        if square_name[0] in "aceg":
            if square_name[1] in "1357":
                return False
            else:
                return True
        else:
            if square_name[1] in "1357":
                return True
            else:
                return False

    def get_potential_moves(self, fgmask, previous_frame, next_frame, chessboard):
        board = [[self.get_square_image(row, column, fgmask).mean() for column in range(8)] for row in range(8)]
        previous_board = [[self.get_square_image(row, column, previous_frame) for column in range(8)] for row in
                          range(8)]
        next_board = [[self.get_square_image(row, column, next_frame) for column in range(8)] for row in
                      range(8)]
        potential_squares = []
        for row in range(8):
            for column in range(8):
                score = board[row][column]
                if score < 10.0:
                    continue

                ssim = structural_similarity(next_board[row][column],
                                             previous_board[row][column], channel_axis=-1)
                square_name = self.convert_row_column_to_square_name(row, column)
                print(ssim, square_name)
                if ssim > self.SSIM_THRESHOLD:
                    continue
                square = chess.parse_square(square_name)
                piece = chessboard.piece_at(square)
                if piece and piece.color == chessboard.turn:
                    is_light = int(self.is_light(square_name))
                    color = int(piece.color)
                    if ssim > self.ssim_table[is_light][color]:
                        continue
                potential_squares.append((score, row, column, ssim))

        potential_squares.sort(reverse=True)
        potential_squares_castling = []
        for i in range(min(6, len(potential_squares))):
            score, row, column, ssim = potential_squares[i]
            potential_square = (score, self.convert_row_column_to_square_name(row, column))
            potential_squares_castling.append(potential_square)
        potential_squares = potential_squares[:4]
        potential_moves = []

        for start_square_score, start_row, start_column, start_ssim in potential_squares:
            start_square_name = self.convert_row_column_to_square_name(start_row, start_column)
            start_square = chess.parse_square(start_square_name)
            start_piece = chessboard.piece_at(start_square)
            if start_piece:
                if start_piece.color != chessboard.turn:
                    continue
            else:
                continue
            start_region = self.square_region(start_row, start_column)
            for arrival_square_score, arrival_row, arrival_column, arrival_ssim in potential_squares:
                if (start_row, start_column) == (arrival_row, arrival_column):
                    continue
                arrival_square_name = self.convert_row_column_to_square_name(arrival_row, arrival_column)
                arrival_square = chess.parse_square(arrival_square_name)
                arrival_piece = chessboard.piece_at(arrival_square)
                if arrival_piece:
                    if arrival_piece.color == chessboard.turn:
                        continue
                else:
                    is_light = int(self.is_light(arrival_square_name))
                    color = int(start_piece.color)
                    if arrival_ssim > self.ssim_table[is_light][color]:
                        continue
                arrival_region = self.square_region(arrival_row, arrival_column)
                region = start_region.union(arrival_region)
                total_square_score = sum(
                    board[row][column] for row, column in region) + start_square_score + arrival_square_score
                potential_moves.append(
                    (total_square_score, start_square_name, arrival_square_name))

        potential_moves.sort(reverse=True)

        return potential_squares_castling, potential_moves


================================================
FILE: board_calibration.py
================================================
import cv2
import platform
from math import inf
import pickle

from board_calibration_machine_learning import detect_board
from helper import rotateMatrix, perspective_transform, edge_detection, euclidean_distance
import numpy as np
import sys
from tkinter import messagebox
import tkinter as tk

filename = 'constants.bin'
corner_model = cv2.dnn.readNetFromONNX("yolo_corner.onnx")
piece_model = cv2.dnn.readNetFromONNX("cnn_piece.onnx")
color_model = cv2.dnn.readNetFromONNX("cnn_color.onnx")

webcam_width = None
webcam_height = None
fps = None
is_machine_learning = False
show_info = False
cap_index = 0
cap_api = cv2.CAP_ANY
platform_name = platform.system()
for argument in sys.argv:
    if argument == "show-info":
        show_info = True
    elif argument.startswith("cap="):
        cap_index = int("".join(c for c in argument if c.isdigit()))
        if platform_name == "Darwin":
            cap_api = cv2.CAP_AVFOUNDATION
        elif platform_name == "Linux":
            cap_api = cv2.CAP_V4L2
        else:
            cap_api = cv2.CAP_DSHOW
    elif argument == "ml":
        is_machine_learning = True
    elif argument.startswith("width="):
        webcam_width = int(argument[len("width="):])
    elif argument.startswith("height="):
        webcam_height = int(argument[len("height="):])
    elif argument.startswith("fps="):
        fps = int(argument[len("fps="):])

if show_info:
    root = tk.Tk()
    root.withdraw()
    messagebox.showinfo("Board Calibration",
                        '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.')


def mark_corners(frame, augmented_corners, rotation_count):
    height, width = frame.shape[:2]
    if rotation_count == 1:
        frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)
    elif rotation_count == 2:
        frame = cv2.rotate(frame, cv2.ROTATE_180)
    elif rotation_count == 3:
        frame = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)

    for i in range(len(augmented_corners)):
        for j in range(len(augmented_corners[i])):
            if rotation_count == 0:
                index = str(i) + "," + str(j)
                corner = augmented_corners[i][j]
            elif rotation_count == 1:
                index = str(j) + "," + str(8 - i)
                corner = (height - augmented_corners[i][j][1], augmented_corners[i][j][0])
            elif rotation_count == 2:
                index = str(8 - i) + "," + str(8 - j)
                corner = (width - augmented_corners[i][j][0], height - augmented_corners[i][j][1])
            elif rotation_count == 3:
                index = str(8 - j) + "," + str(i)
                corner = (augmented_corners[i][j][1], width - augmented_corners[i][j][0])
            corner = (int(corner[0]), int(corner[1]))
            frame = cv2.putText(frame, index, corner, cv2.FONT_HERSHEY_SIMPLEX,
                                0.5, (255, 0, 0), 1, cv2.LINE_AA)

    return frame


cap = cv2.VideoCapture(cap_index, cap_api)
if webcam_width is not None:
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, webcam_width)
if webcam_height is not None:
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, webcam_height)
if fps is not None:
    cap.set(cv2.CAP_PROP_FPS, fps)

if not cap.isOpened():
    print("Couldn't open your webcam. Please check your webcam connection.")
    sys.exit(0)
board_dimensions = (7, 7)

for _ in range(10):
    ret, frame = cap.read()
    if ret == False:
        print("Error reading frame. Please check your webcam connection.")
        continue

while True:
    ret, frame = cap.read()
    if ret == False:
        print("Error reading frame. Please check your webcam connection.")
        continue
    if is_machine_learning:
        result = detect_board(frame, corner_model, piece_model, color_model)
        if result:
            pts1, side_view_compensation, rotation_count = result
            outfile = open(filename, 'wb')
            pickle.dump([is_machine_learning, [pts1, side_view_compensation, rotation_count]], outfile)
            outfile.close()
            if show_info:
                if platform_name == "Darwin":
                    root = tk.Tk()
                    root.withdraw()
                messagebox.showinfo(
                    "Chess Board Detected",
                    "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\n"
                    "Press any key to exit once you've confirmed the board setup."
                )
                root.destroy()
            cv2.imshow('frame', frame)
            cv2.waitKey(0)
            cap.release()
            cv2.destroyAllWindows()
            sys.exit(0)
    else:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        retval, corners = cv2.findChessboardCorners(gray, patternSize=board_dimensions)
        if retval:
            if show_info:
                if platform_name == "Darwin":
                    root = tk.Tk()
                    root.withdraw()
                messagebox.showinfo("Chess Board Detected",
                                    '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.')
                root.destroy()
            if corners[0][0][0] > corners[-1][0][0]:  # corners returned in reverse order
                corners = corners[::-1]
            minX, maxX, minY, maxY = inf, -inf, inf, -inf
            augmented_corners = []
            row = []
            for i in range(6):
                corner1 = corners[i]
                corner2 = corners[i + 8]
                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])
                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])
                row.append((x, y))

            for i in range(4, 7):
                corner1 = corners[i]
                corner2 = corners[i + 6]
                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])
                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])
                row.append((x, y))

            augmented_corners.append(row)

            for i in range(7):
                row = []
                corner1 = corners[i * 7]
                corner2 = corners[i * 7 + 1]
                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])
                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])
                row.append((x, y))

                for corner in corners[i * 7:(i + 1) * 7]:
                    x = corner[0][0]
                    y = corner[0][1]
                    row.append((x, y))

                corner1 = corners[i * 7 + 6]
                corner2 = corners[i * 7 + 5]
                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])
                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])
                row.append((x, y))
                augmented_corners.append(row)

            row = []
            for i in range(6):
                corner1 = corners[42 + i]
                corner2 = corners[42 + i - 6]
                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])
                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])
                row.append((x, y))

            for i in range(4, 7):
                corner1 = corners[42 + i]
                corner2 = corners[42 + i - 8]
                x = corner1[0][0] + (corner1[0][0] - corner2[0][0])
                y = corner1[0][1] + (corner1[0][1] - corner2[0][1])
                row.append((x, y))

            augmented_corners.append(row)

            while augmented_corners[0][0][0] > augmented_corners[8][8][0] or augmented_corners[0][0][1] > \
                    augmented_corners[8][8][1]:
                rotateMatrix(augmented_corners)

            pts1 = np.float32([list(augmented_corners[0][0]), list(augmented_corners[8][0]), list(augmented_corners[0][8]),
                               list(augmented_corners[8][8])])
            empty_board = perspective_transform(frame, pts1)
            edges = edge_detection(empty_board)
            # cv2.imshow("edge", edges)
            # cv2.waitKey(0)
            kernel = np.ones((7, 7), np.uint8)
            edges = cv2.dilate(edges, kernel, iterations=1)
            roi_mask = cv2.bitwise_not(edges)
            # cv2.imshow("edge", edges)
            # cv2.waitKey(0)
            # cv2.imshow("roi", roi_mask)
            # cv2.waitKey(0)
            roi_mask[:7, :] = 0
            roi_mask[:, :7] = 0
            roi_mask[-7:, :] = 0
            roi_mask[:, -7:] = 0
            # cv2.imshow("roi", roi_mask)
            # cv2.waitKey(0)
            # cv2.imwrite("empty_board.jpg", empty_board)

            rotation_count = 0
            while True:
                cv2.imshow('frame', mark_corners(frame.copy(), augmented_corners, rotation_count))
                response = cv2.waitKey(0)
                if response & 0xFF == ord('r'):
                    rotation_count += 1
                    rotation_count %= 4
                elif response & 0xFF == ord('q'):
                    break
            break

    cv2.imshow('frame', frame)
    if cv2.waitKey(3) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

first_row = euclidean_distance(augmented_corners[1][1], augmented_corners[1][7])
last_row = euclidean_distance(augmented_corners[7][1], augmented_corners[7][7])
first_column = euclidean_distance(augmented_corners[1][1], augmented_corners[7][1])
last_column = euclidean_distance(augmented_corners[1][7], augmented_corners[7][7])

if abs(first_row - last_row) >= abs(first_column - last_column):
    if first_row >= last_row:
        side_view_compensation = (1, 0)
    else:
        side_view_compensation = (-1, 0)
else:
    if first_column >= last_column:
        side_view_compensation = (0, -1)
    else:
        side_view_compensation = (0, 1)

print("Side view compensation" + str(side_view_compensation))
print("Rotation count " + str(rotation_count))

outfile = open(filename, 'wb')
pickle.dump([is_machine_learning, [augmented_corners, side_view_compensation, rotation_count, roi_mask]], outfile)
outfile.close()


================================================
FILE: board_calibration_machine_learning.py
================================================
import numpy as np
import cv2

from helper import euclidean_distance, perspective_transform, predict


def detect_board(original_image, corner_model, piece_model, color_model):
    [height, width, _] = original_image.shape

    length = max((height, width))
    image = np.zeros((length, length, 3), np.uint8)
    image[0:height, 0:width] = original_image

    scale = length / 640

    blob = cv2.dnn.blobFromImage(image, scalefactor=1 / 255, size=(640, 640), swapRB=True)
    corner_model.setInput(blob)
    outputs = corner_model.forward()
    outputs = np.array([cv2.transpose(outputs[0])])
    rows = outputs.shape[1]

    boxes = []
    scores = []
    class_ids = []

    for i in range(rows):
        classes_scores = outputs[0][i][4:]
        (minScore, maxScore, minClassLoc, (x, maxClassIndex)) = cv2.minMaxLoc(classes_scores)
        if maxScore >= 0.25:
            box = [
                outputs[0][i][0] - (0.5 * outputs[0][i][2]), outputs[0][i][1] - (0.5 * outputs[0][i][3]),
                outputs[0][i][2], outputs[0][i][3]]
            boxes.append(box)
            scores.append(maxScore)
            class_ids.append(maxClassIndex)

    result_boxes = cv2.dnn.NMSBoxes(boxes, scores, 0.25, 0.45, 0.5)

    detections = []
    for i in range(len(result_boxes)):
        index = result_boxes[i]
        box = boxes[index]
        detection = {
            'confidence': scores[index],
            'box': box,
        }
        detections.append(detection)

    if len(detections) < 4:
        return

    detections.sort(key=lambda detection: detection['confidence'], reverse=True)
    detections = detections[:4]

    middle_points = []
    for detection in detections:
        box = detection['box']
        x, y, w, h = box
        middle_x = (x + (w / 2)) * scale
        middle_y = (y + (h / 2)) * scale
        middle_points.append([middle_x, middle_y])

    minX = min(point[0] for point in middle_points)
    minY = min(point[1] for point in middle_points)
    maxX = max(point[0] for point in middle_points)
    maxY = max(point[1] for point in middle_points)

    top_left = min(middle_points, key=lambda point: euclidean_distance(point, [minX, minY]))
    top_right = min(middle_points, key=lambda point: euclidean_distance(point, [maxX, minY]))
    bottom_left = min(middle_points, key=lambda point: euclidean_distance(point, [minX, maxY]))
    bottom_right = min(middle_points, key=lambda point: euclidean_distance(point, [maxX, maxY]))

    first_row = euclidean_distance(top_left, top_right)
    last_row = euclidean_distance(bottom_left, bottom_right)
    first_column = euclidean_distance(top_left, bottom_left)
    last_column = euclidean_distance(top_right, bottom_right)

    if abs(first_row - last_row) >= abs(first_column - last_column):
        if first_row >= last_row:
            side_view_compensation = (1, 0)
        else:
            side_view_compensation = (-1, 0)
    else:
        if first_column >= last_column:
            side_view_compensation = (0, -1)
        else:
            side_view_compensation = (0, 1)

    pts1 = np.float32([top_left, bottom_left, top_right, bottom_right])
    board_image = perspective_transform(original_image, pts1)

    squares_to_check_for_rotation_count = [
        [(0, i) for i in range(7)],
        [(i, 0) for i in range(7)],
        [(7, i) for i in range(7)],
        [(i, 7) for i in range(7)],
    ]

    rotation_count = 0
    score = 0
    for i in range(len(squares_to_check_for_rotation_count)):
        current_score = 0
        for row, column in squares_to_check_for_rotation_count[i]:
            height, width = board_image.shape[:2]
            minX = int(column * width / 8)
            maxX = int((column + 1) * width / 8)
            minY = int(row * height / 8)
            maxY = int((row + 1) * height / 8)
            square_image = board_image[minY:maxY, minX:maxX]
            is_piece = predict(square_image, piece_model)
            if is_piece:
                is_white = predict(square_image, color_model)
                if not is_white:
                    current_score += 1
        if current_score > score:
            score = current_score
            rotation_count = i

    green_color = (0, 255, 0)
    blue_color = (255, 0, 0)
    red_color = (0, 0, 255)

    top_left, top_right, bottom_left, bottom_right = [(int(point[0]), int(point[1])) for point in
                                                      (top_left, top_right, bottom_left, bottom_right)]

    if rotation_count == 0:
        cv2.line(original_image, top_left, top_right, green_color, 5)
        cv2.line(original_image, top_right, bottom_right, red_color, 5)
        cv2.line(original_image, bottom_left, bottom_right, blue_color, 5)
        cv2.line(original_image, top_left, bottom_left, red_color, 5)
    elif rotation_count == 1:
        cv2.line(original_image, top_left, top_right, red_color, 5)
        cv2.line(original_image, top_right, bottom_right, blue_color, 5)
        cv2.line(original_image, bottom_left, bottom_right, red_color, 5)
        cv2.line(original_image, top_left, bottom_left, green_color, 5)
    elif rotation_count == 2:
        cv2.line(original_image, top_left, top_right, blue_color, 5)
        cv2.line(original_image, top_right, bottom_right, red_color, 5)
        cv2.line(original_image, bottom_left, bottom_right, green_color, 5)
        cv2.line(original_image, top_left, bottom_left, red_color, 5)
    elif rotation_count == 3:
        cv2.line(original_image, top_left, top_right, red_color, 5)
        cv2.line(original_image, top_right, bottom_right, green_color, 5)
        cv2.line(original_image, bottom_left, bottom_right, red_color, 5)
        cv2.line(original_image, top_left, bottom_left, blue_color, 5)

    print("Side view compensation" + str(side_view_compensation))
    print("Rotation count " + str(rotation_count))
    return pts1, side_view_compensation, rotation_count


================================================
FILE: chessboard_detection.py
================================================
import sys

import numpy as np
import cv2
import pyautogui
import mss
from statistics import median


class Board_position:
    def __init__(self, minX, minY, maxX, maxY):
        self.minX = minX
        self.minY = minY
        self.maxX = maxX
        self.maxY = maxY


def find_chessboard():
    screenshot_shape = np.array(pyautogui.screenshot()).shape
    monitor = {'top': 0, 'left': 0, 'width': screenshot_shape[1], 'height': screenshot_shape[0]}
    sct = mss.mss()
    large_image = np.array(np.array(sct.grab(monitor)))
    large_image = cv2.cvtColor(large_image, cv2.COLOR_BGR2RGB)
    method = cv2.TM_SQDIFF_NORMED
    white_image = cv2.imread("white.JPG")
    black_image = cv2.imread("black.JPG")
    result_white = cv2.matchTemplate(white_image, large_image, method)
    result_black = cv2.matchTemplate(black_image, large_image, method)
    we_are_white = True
    result = result_white
    small_image = white_image
    if cv2.minMaxLoc(result_black)[0] < cv2.minMaxLoc(result_white)[0]:  # If black is more accurate:
        result = result_black
        we_are_white = False
        small_image = black_image
    minimum_value, maximum_value, minimum_location, maximum_location = cv2.minMaxLoc(result)

    minX, minY = minimum_location
    maxX = minX + small_image.shape[1]
    maxY = minY + small_image.shape[0]

    position = Board_position(minX, minY, maxX, maxY)
    return position, we_are_white


def auto_find_chessboard():
    screenshot_shape = np.array(pyautogui.screenshot()).shape
    monitor = {'top': 0, 'left': 0, 'width': screenshot_shape[1], 'height': screenshot_shape[0]}
    sct = mss.mss()
    img = np.array(np.array(sct.grab(monitor)))
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    is_found, current_chessboard_image, minX, minY, maxX, maxY, test_image = find_chessboard_from_image(img)
    if not is_found:
        sys.exit(0)
    position = Board_position(minX, minY, maxX, maxY)
    return position, is_white_on_bottom(current_chessboard_image)


def is_white_on_bottom(current_chessboard_image):
    m1 = get_square_image(0, 0, current_chessboard_image).mean()
    m2 = get_square_image(7, 7, current_chessboard_image).mean()
    if m1 < m2:
        return True
    else:
        return False


def get_square_image(row, column, board_img):
    height, width = board_img.shape
    minX = int(column * width / 8)
    maxX = int((column + 1) * width / 8)
    minY = int(row * width / 8)
    maxY = int((row + 1) * width / 8)
    square = board_img[minY:maxY, minX:maxX]
    square_without_borders = square[3:-3, 3:-3]
    return square_without_borders


def prepare(lines, kernel_close, kernel_open):
    ret, lines = cv2.threshold(lines, 30, 255, cv2.THRESH_BINARY)
    lines = cv2.morphologyEx(lines, cv2.MORPH_CLOSE, kernel_close)
    lines = cv2.morphologyEx(lines, cv2.MORPH_OPEN, kernel_open)
    return lines


def prepare_vertical(lines):
    kernel_close = np.ones((3, 1), np.uint8)
    kernel_open = np.ones((50, 1), np.uint8)
    return prepare(lines, kernel_close, kernel_open)


def prepare_horizontal(lines):
    kernel_close = np.ones((1, 3), np.uint8)
    kernel_open = np.ones((1, 50), np.uint8)
    return prepare(lines, kernel_close, kernel_open)


def find_chessboard_from_image(img):
    image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    kernelH = np.array([[-1, 1]])
    kernelV = np.array([[-1], [1]])
    vertical_lines = np.absolute(cv2.filter2D(image.astype('float'), -1, kernelH))
    image_vertical = prepare_vertical(vertical_lines)
    horizontal_lines = np.absolute(cv2.filter2D(image.astype('float'), -1, kernelV))
    image_horizontal = prepare_horizontal(horizontal_lines)
    vertical_lines = cv2.HoughLinesP(image_vertical.astype(np.uint8), 1, np.pi / 180, 100, minLineLength=100,
                                     maxLineGap=10)
    horizontal_lines = cv2.HoughLinesP(image_horizontal.astype(np.uint8), 1, np.pi / 180, 100, minLineLength=100,
                                       maxLineGap=10)
    v_count = [0 for _ in range(len(vertical_lines))]
    h_count = [0 for _ in range(len(horizontal_lines))]
    for i, line in enumerate(vertical_lines):
        x1, y1, x2, y2 = line[0]
        for j, other_line in enumerate(horizontal_lines):
            x3, y3, x4, y4 = other_line[0]
            if ((x3 <= x1 <= x4) or (x4 <= x1 <= x3)) and ((y2 <= y3 <= y1) or (y1 <= y3 <= y2)):
                v_count[i] += 1
                h_count[j] += 1
    v_board = []
    h_board = []
    for i, line in enumerate(vertical_lines):
        if v_count[i] <= 6:
            continue
        v_board.append(line)

    for i, line in enumerate(horizontal_lines):
        if h_count[i] <= 6:
            continue
        h_board.append(line)

    if v_board and h_board:
        y_min = int(median(min(v[0][1], v[0][3]) for v in v_board))
        y_max = int(median(max(v[0][1], v[0][3]) for v in v_board))
        x_min = int(median(min(h[0][0], h[0][2]) for h in h_board))
        x_max = int(median(max(h[0][0], h[0][2]) for h in h_board))
        if abs((x_max - x_min) - (y_max - y_min)) > 3:
            print("Board is not square.")
            return False, image, 0, 0, 0, 0, image
        board = image[y_min:y_max, x_min:x_max]
        dim = (800, 800)
        resized_board = cv2.resize(board, dim,
                                   interpolation=cv2.INTER_AREA)
        # cv2.imwrite("board.jpg", resized_board)
        return True, resized_board, int(x_min), int(y_min), int(x_max), int(y_max), resized_board
    else:
        print("Chess board of online game could not be found.")
        return False, image, 0, 0, 0, 0, image


================================================
FILE: classifier.py
================================================
import numpy as np
import cv2
from math import pi


# https://github.com/youyexie/Chess-Piece-Recognition-using-Oriented-Chamfer-Matching-with-a-Comparison-to-CNN
class Classifier:
    def __init__(self, game_state):
        self.dim = (480, 480)
        self.img = cv2.resize(game_state.previous_chessboard_image, self.dim,
                              interpolation=cv2.INTER_AREA)
        self.img_x, self.img_y = self.unit_gradients(self.img)
        self.edges = cv2.Canny(self.img, 100, 200)
        self.inverted_edges = cv2.bitwise_not(self.edges)
        self.dist = cv2.distanceTransform(self.inverted_edges, cv2.DIST_L2, 3)
        self.dist_board = [[self.get_square_image(row, column, self.dist) for column in range(8)] for row in range(8)]
        self.edge_board = [[self.get_square_image(row, column, self.edges) for column in range(8)] for row in range(8)]
        self.gradient_x = [[self.get_square_image(row, column, self.img_x) for column in range(8)] for row in range(8)]
        self.gradient_y = [[self.get_square_image(row, column, self.img_y) for column in range(8)] for row in range(8)]

        def intensity(x):
            return self.edge_board[x[0]][x[1]].mean()

        pawn_templates = [max([(1, i) for i in range(8)], key=intensity),
                          max([(6, i) for i in range(8)], key=intensity)]

        self.templates = [pawn_templates] + [[(0, i), (7, i)] for i in range(5)]

        if intensity((0, 6)) > intensity((0, 1)):
            self.templates[2][0] = (0, 6)

        if intensity((7, 6)) > intensity((7, 1)):
            self.templates[2][1] = (7, 6)

        self.piece_symbol = [".", "p", "r", "n", "b", "q", "k"]
        if game_state.we_play_white == False:
            self.piece_symbol[-1], self.piece_symbol[-2] = self.piece_symbol[-2], self.piece_symbol[-1]

    def classify(self, img):
        img = cv2.resize(img, self.dim,
                         interpolation=cv2.INTER_AREA)

        img_x, img_y = self.unit_gradients(img)
        edges = cv2.Canny(img, 100, 200)
        inverted_edges = cv2.bitwise_not(edges)
        dist = cv2.distanceTransform(inverted_edges, cv2.DIST_L2, 3)
        dist_board = [[self.get_square_image(row, column, dist) for column in range(8)] for row in range(8)]
        gradient_x = [[self.get_square_image(row, column, img_x) for column in range(8)] for row in range(8)]
        gradient_y = [[self.get_square_image(row, column, img_y) for column in range(8)] for row in range(8)]

        result = []
        for row in range(8):
            row_result = []
            for col in range(8):
                d = dist_board[row][col]
                template_scores = []
                for piece in self.templates:
                    piece_scores = []
                    for tr, tc in piece:
                        t = self.edge_board[tr][tc]
                        e = t / 255.0
                        e_c = e.sum()
                        r_d = np.multiply(d, e).sum() / e_c

                        dp = np.multiply(self.gradient_x[tr][tc], gradient_x[row][col]) + np.multiply(
                            self.gradient_y[tr][tc],
                            gradient_y[row][col])
                        dp = np.abs(dp)
                        dp[dp > 1.0] = 1.0
                        angle_difference = np.arccos(dp)
                        r_o = np.multiply(angle_difference, e).sum() / (e_c * (pi / 2))
                        piece_scores.append(r_d * 0.5 + r_o * 0.5)
                    template_scores.append(min(piece_scores))
                min_score = float("inf")
                min_index = -1
                for i in range(len(template_scores)):
                    if min_score > template_scores[i]:
                        min_score = template_scores[i]
                        min_index = i
                if min_score < 2.0:
                    row_result.append(self.piece_symbol[min_index + 1])
                else:
                    row_result.append(self.piece_symbol[0])

            result.append(row_result)
        return result

    def unit_gradients(self, gray):
        sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
        sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)
        mag, direction = cv2.cartToPolar(sobelx, sobely)
        mag[mag == 0] = 1
        unit_x = sobelx / mag
        unit_y = sobely / mag
        return unit_x, unit_y

    def get_square_image(self, row, column,
                         board_img):
        height, width = board_img.shape[:2]
        minX = int(column * width / 8)
        maxX = int((column + 1) * width / 8)
        minY = int(row * height / 8)
        maxY = int((row + 1) * height / 8)
        square = board_img[minY:maxY, minX:maxX]
        square_without_borders = square[3:-3, 3:-3]
        return square_without_borders


================================================
FILE: commentator.py
================================================
from threading import Thread
import chess
import mss
import numpy as np
import cv2
import time
from classifier import Classifier


class Commentator_thread(Thread):

    def __init__(self, *args, **kwargs):
        super(Commentator_thread, self).__init__(*args, **kwargs)
        self.speech_thread = None
        self.game_state = Game_state()
        self.comment_me = None
        self.comment_opponent = None
        self.language = None
        self.classifier = None

    def run(self):
        self.game_state.sct = mss.mss()
        resized_chessboard = self.game_state.get_chessboard()
        self.game_state.previous_chessboard_image = resized_chessboard
        self.game_state.classifier = Classifier(self.game_state)

        while not self.game_state.board.is_game_over():
            is_my_turn = (self.game_state.we_play_white) == (self.game_state.board.turn == chess.WHITE)
            found_move, move = self.game_state.register_move_if_needed()
            if found_move and ((self.comment_me and is_my_turn) or (self.comment_opponent and (not is_my_turn))):
                self.speech_thread.put_text(self.language.comment(self.game_state.board, move))


class Game_state:

    def __init__(self):
        self.game_thread = None
        self.we_play_white = None
        self.previous_chessboard_image = None
        self.board = chess.Board()
        self.board_position_on_screen = None
        self.sct = mss.mss()
        self.classifier = None
        self.registered_moves = []
        self.resign_or_draw = False
        self.variant = 'standard'

    def get_chessboard(self):
        position = self.board_position_on_screen
        monitor = {'top': 0, 'left': 0, 'width': position.maxX + 10, 'height': position.maxY + 10}
        img = np.array(np.array(self.sct.grab(monitor)))
        image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        dim = (800, 800)
        resizedChessBoard = cv2.resize(image[position.minY:position.maxY, position.minX:position.maxX], dim,
                                       interpolation=cv2.INTER_AREA)
        return resizedChessBoard

    def get_square_image(self, row, column,
                         board_img):
        height, width = board_img.shape
        minX = int(column * width / 8)
        maxX = int((column + 1) * width / 8)
        minY = int(row * width / 8)
        maxY = int((row + 1) * width / 8)
        square = board_img[minY:maxY, minX:maxX]
        square_without_borders = square[6:-6, 6:-6]
        return square_without_borders

    def can_image_correspond_to_chessboard(self, move, result):
        self.board.push(move)
        squares = chess.SquareSet(chess.BB_ALL)
        for square in squares:
            row = chess.square_rank(square)
            column = chess.square_file(square)
            piece = self.board.piece_at(square)
            shouldBeEmpty = (piece == None)

            if self.we_play_white == True:
                rowOnImage = 7 - row
                columnOnImage = column
            else:
                rowOnImage = row
                columnOnImage = 7 - column

            isEmpty = result[rowOnImage][columnOnImage] == '.'
            if isEmpty != shouldBeEmpty:
                self.board.pop()
                # print("Problem with : ", self.board.uci(move), " the square ",
                #      self.convert_row_column_to_square_name(row, column), "should ",
                #      'be empty' if shouldBeEmpty else 'contain a piece')
                return False
            if piece and (piece.symbol().lower() != result[rowOnImage][columnOnImage]):
                self.board.pop()
                # print(piece.symbol(), result[rowOnImage][columnOnImage],
                #      self.convert_row_column_to_square_name(rowOnImage, columnOnImage))
                return False
        self.board.pop()
        return True

    def find_premove(self, result):
        start_squares = []
        squares = chess.SquareSet(chess.BB_ALL)
        for square in squares:
            row = chess.square_rank(square)
            column = chess.square_file(square)
            piece = self.board.piece_at(square)

            if self.we_play_white == True:
                rowOnImage = 7 - row
                columnOnImage = column
            else:
                rowOnImage = row
                columnOnImage = 7 - column

            isEmpty = result[rowOnImage][columnOnImage] == '.'
            if piece and isEmpty:
                start_squares.append(square)
        return squares

    def get_valid_move(self, potential_starts, potential_arrivals, current_chessboard_image):
        result = self.classifier.classify(current_chessboard_image)
        valid_move_string = ""
        for start in potential_starts:
            if valid_move_string:
                break
            for arrival in potential_arrivals:
                if valid_move_string:
                    break
                if start == arrival:
                    continue
                uci_move = start + arrival
                try:
                    move = chess.Move.from_uci(uci_move)
                except:
                    continue

                if move in self.board.legal_moves:
                    if self.can_image_correspond_to_chessboard(move,
                                                               result):
                        valid_move_string = uci_move
                else:
                    r, c = self.convert_square_name_to_row_column(arrival)
                    if result[r][c] not in ["q", "r", "b", "n"]:
                        continue
                    uci_move_promoted = uci_move + result[r][c]
                    promoted_move = chess.Move.from_uci(uci_move_promoted)
                    if promoted_move in self.board.legal_moves:
                        if self.can_image_correspond_to_chessboard(promoted_move,
                                                                   result):
                            valid_move_string = uci_move_promoted

        # Detect castling king side with white
        if ("e1" in potential_starts) and ("h1" in potential_starts) and ("f1" in potential_arrivals) and (
                "g1" in potential_arrivals) and (chess.Move.from_uci("e1g1") in self.board.legal_moves):
            if (self.board.peek() != chess.Move.from_uci("e1g1")) and \
                    self.can_image_correspond_to_chessboard(chess.Move.from_uci("e1g1"), result):
                valid_move_string = "e1g1"

        # Detect castling queen side with white
        if ("e1" in potential_starts) and ("a1" in potential_starts) and ("c1" in potential_arrivals) and (
                "d1" in potential_arrivals) and (chess.Move.from_uci("e1c1") in self.board.legal_moves):
            if (self.board.peek() != chess.Move.from_uci("e1c1")) and \
                    self.can_image_correspond_to_chessboard(chess.Move.from_uci("e1c1"), result):
                valid_move_string = "e1c1"

        # Detect castling king side with black
        if ("e8" in potential_starts) and ("h8" in potential_starts) and ("f8" in potential_arrivals) and (
                "g8" in potential_arrivals) and (chess.Move.from_uci("e8g8") in self.board.legal_moves):
            if (self.board.peek() != chess.Move.from_uci("e8g8")) and self.can_image_correspond_to_chessboard(
                    chess.Move.from_uci("e8g8"), result):
                valid_move_string = "e8g8"

        # Detect castling queen side with black
        if ("e8" in potential_starts) and ("a8" in potential_starts) and ("c8" in potential_arrivals) and (
                "d8" in potential_arrivals) and (chess.Move.from_uci("e8c8") in self.board.legal_moves):
            if (self.board.peek() != chess.Move.from_uci("e8c8")) and self.can_image_correspond_to_chessboard(
                    chess.Move.from_uci("e8c8"), result):
                valid_move_string = "e8c8"

        if not valid_move_string:  # Search for premove
            premove_starts = self.find_premove(result)
            for start_square in premove_starts:
                for move in self.board.legal_moves:
                    if move.from_square == start_square:
                        if self.can_image_correspond_to_chessboard(move, result):
                            return move.uci()

        return valid_move_string

    def has_square_image_changed(self, old_square,
                                 new_square):
        diff = cv2.absdiff(old_square, new_square)
        if diff.mean() > 8:
            return True
        else:
            return False

    def convert_row_column_to_square_name(self, row, column):
        if self.we_play_white:
            number = repr(8 - row)
            letter = str(chr(97 + column))
            return letter + number
        else:
            number = repr(row + 1)
            letter = str(chr(97 + (7 - column)))
            return letter + number

    def convert_square_name_to_row_column(self, square_name):
        for row in range(8):
            for column in range(8):
                this_square_name = self.convert_row_column_to_square_name(row, column)
                if this_square_name == square_name:
                    return row, column
        return 0, 0

    def get_potential_moves(self, old_image, new_image):
        potential_starts = []
        potential_arrivals = []
        for row in range(8):
            for column in range(8):
                old_square = self.get_square_image(row, column, old_image)
                new_square = self.get_square_image(row, column, new_image)
                if self.has_square_image_changed(old_square, new_square):
                    square_name = self.convert_row_column_to_square_name(row, column)
                    potential_starts.append(square_name)
                    potential_arrivals.append(square_name)
        return potential_starts, potential_arrivals

    def register_move_if_needed(self):
        new_board = self.get_chessboard()
        potential_starts, potential_arrivals = self.get_potential_moves(self.previous_chessboard_image, new_board)

        valid_move_string1 = self.get_valid_move(potential_starts, potential_arrivals, new_board)

        if len(valid_move_string1) > 0:
            time.sleep(0.1)
            # Check that we were not in the middle of a move animation
            new_board = self.get_chessboard()
            potential_starts, potential_arrivals = self.get_potential_moves(self.previous_chessboard_image, new_board)
            valid_move_string2 = self.get_valid_move(potential_starts, potential_arrivals, new_board)
            if valid_move_string2 != valid_move_string1:
                return False, "The move has changed"
            valid_move_UCI = chess.Move.from_uci(valid_move_string1)
            self.register_move(valid_move_UCI, new_board)
            return True, valid_move_UCI
        elif potential_starts:  # Fix for premove
            if len(self.registered_moves) < len(self.game_thread.played_moves):
                valid_move_UCI = self.game_thread.played_moves[len(self.registered_moves)]
                self.register_move(valid_move_UCI, self.previous_chessboard_image)
                return True, valid_move_UCI
        return False, "No move found"

    def register_move(self, move, board_image):
        if move in self.board.legal_moves:
            self.board.push(move)
            self.previous_chessboard_image = board_image
            self.registered_moves.append(move)
            # cv2.imwrite("registered.jpg", board_image)
            return True
        else:
            return False


================================================
FILE: diagnostic.py
================================================
import cv2
import numpy as np
import pickle

from board_calibration_machine_learning import detect_board
from helper import perspective_transform, predict
import platform
import sys
import tkinter as tk
from tkinter import messagebox

webcam_width = None
webcam_height = None
fps = None
calibrate = False
cap_index = 0
cap_api = cv2.CAP_ANY
platform_name = platform.system()
for argument in sys.argv:
    if argument.startswith("cap="):
        cap_index = int("".join(c for c in argument if c.isdigit()))
        if platform_name == "Darwin":
            cap_api = cv2.CAP_AVFOUNDATION
        elif platform_name == "Linux":
            cap_api = cv2.CAP_V4L2
        else:
            cap_api = cv2.CAP_DSHOW
    elif argument == "calibrate":
        calibrate = True
    elif argument.startswith("width="):
        webcam_width = int(argument[len("width="):])
    elif argument.startswith("height="):
        webcam_height = int(argument[len("height="):])
    elif argument.startswith("fps="):
        fps = int(argument[len("fps="):])

corner_model = cv2.dnn.readNetFromONNX("yolo_corner.onnx")
piece_model = cv2.dnn.readNetFromONNX("cnn_piece.onnx")
color_model = cv2.dnn.readNetFromONNX("cnn_color.onnx")


cap = cv2.VideoCapture(cap_index, cap_api)
if webcam_width is not None:
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, webcam_width)
if webcam_height is not None:
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, webcam_height)
if fps is not None:
    cap.set(cv2.CAP_PROP_FPS, fps)

if not cap.isOpened():
    print("Couldn't open your webcam. Please check your webcam connection.")
    sys.exit(0)


for _ in range(10):
    ret, frame = cap.read()

if calibrate:
    is_detected = False
    for _ in range(100):
        ret, frame = cap.read()
        if not ret:
            print("Error reading frame. Please check your webcam connection.")
            continue
        result = detect_board(frame, corner_model, piece_model, color_model)
        if result:
            pts1, side_view_compensation, rotation_count = result
            is_detected = True
            break

    if not is_detected:
        print("Could not detect the chess board.")
        cap.release()
        sys.exit(0)
else:
    filename = 'constants.bin'
    infile = open(filename, 'rb')
    calibration_data = pickle.load(infile)
    infile.close()
    if calibration_data[0]:
        pts1, side_view_compensation, rotation_count = calibration_data[1]
    else:
        corners, side_view_compensation, rotation_count, roi_mask = calibration_data[1]
        pts1 = np.float32([list(corners[0][0]), list(corners[8][0]), list(corners[0][8]),
                           list(corners[8][8])])


def process(image):
    for row in range(8):
        for column in range(8):
            height, width = image.shape[:2]
            minX = int(column * width / 8)
            maxX = int((column + 1) * width / 8)
            minY = int(row * height / 8)
            maxY = int((row + 1) * height / 8)
            square_image = image[minY:maxY, minX:maxX]
            is_piece = predict(square_image, piece_model)
            if is_piece:
                centerX = int((minX + maxX) / 2)
                centerY = int((minY + maxY) / 2)
                radius = 10
                is_white = predict(square_image, color_model)
                if is_white:
                    cv2.circle(image, (centerX, centerY), radius, (255, 0, 0), 2)
                else:
                    cv2.circle(image, (centerX, centerY), radius, (0, 255, 0), 2)
    return image


root = tk.Tk()
root.withdraw()
messagebox.showinfo("Diagnostic",
                    "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.")

while True:
    ret, frame = cap.read()
    if not ret:
        print("Error reading frame. Please check your webcam connection.")
        continue

    frame = perspective_transform(frame, pts1)
    processed_frame = process(frame.copy())
    
    cv2.imshow('Diagnostic', np.hstack((processed_frame, frame)))

    if cv2.waitKey(1000) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()


================================================
FILE: game.py
================================================
import time

import chess
import cv2
import numpy as np
import pickle
import os
import sys
from helper import detect_state, get_square_image, predict
from internet_game import Internet_game
from lichess_game import Lichess_game
from commentator import Commentator_thread
from lichess_commentator import Lichess_commentator


class Game:
    def __init__(self, board_basics, speech_thread, use_template, make_opponent, start_delay, comment_me,
                 comment_opponent, drag_drop, language, token, roi_mask):
        if token:
            self.internet_game = Lichess_game(token)
        else:
            self.internet_game = Internet_game(use_template, start_delay, drag_drop)
        self.make_opponent = make_opponent
        self.board_basics = board_basics
        self.speech_thread = speech_thread
        self.executed_moves = []
        self.played_moves = []
        self.board = chess.Board()
        self.comment_me = comment_me
        self.comment_opponent = comment_opponent
        self.language = language
        self.roi_mask = roi_mask
        self.hog = cv2.HOGDescriptor((64, 64), (16, 16), (8, 8), (8, 8), 9)
        self.knn = cv2.ml.KNearest_create()
        self.features = None
        self.labels = None
        self.save_file = 'hog.bin'
        self.piece_model = cv2.dnn.readNetFromONNX("cnn_piece.onnx")
        self.color_model = cv2.dnn.readNetFromONNX("cnn_color.onnx")

        if token:
            commentator_thread = Lichess_commentator()
            commentator_thread.daemon = True
            commentator_thread.stream = self.internet_game.client.board.stream_game_state(self.internet_game.game_id)
            commentator_thread.speech_thread = self.speech_thread
            commentator_thread.game_state.we_play_white = self.internet_game.we_play_white
            commentator_thread.game_state.game = self
            commentator_thread.comment_me = self.comment_me
            commentator_thread.comment_opponent = self.comment_opponent
            commentator_thread.language = self.language
            self.commentator = commentator_thread
        else:
            commentator_thread = Commentator_thread()
            commentator_thread.daemon = True
            commentator_thread.speech_thread = self.speech_thread
            commentator_thread.game_state.game_thread = self
            commentator_thread.game_state.we_play_white = self.internet_game.we_play_white
            commentator_thread.game_state.board_position_on_screen = self.internet_game.position
            commentator_thread.comment_me = self.comment_me
            commentator_thread.comment_opponent = self.comment_opponent
            commentator_thread.language = self.language
            self.commentator = commentator_thread

    def initialize_hog(self, frame):
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        pieces = []
        squares = []
        for row in range(8):
            for column in range(8):
                square_name = self.board_basics.convert_row_column_to_square_name(row, column)
                square = chess.parse_square(square_name)
                piece = self.board.piece_at(square)
                square_image = get_square_image(row, column, frame)
                square_image = cv2.resize(square_image, (64, 64))
                if piece:
                    pieces.append(square_image)
                else:
                    squares.append(square_image)
        pieces_hog = [self.hog.compute(piece) for piece in pieces]
        squares_hog = [self.hog.compute(square) for square in squares]
        labels_pieces = np.ones((len(pieces_hog), 1), np.int32)
        labels_squares = np.zeros((len(squares_hog), 1), np.int32)
        pieces_hog = np.array(pieces_hog)
        squares_hog = np.array(squares_hog)
        features = np.float32(np.concatenate((pieces_hog, squares_hog), axis=0))
        labels = np.concatenate((labels_pieces, labels_squares), axis=0)
        self.knn.train(features, cv2.ml.ROW_SAMPLE, labels)
        self.features = features
        self.labels = labels

        outfile = open(self.save_file, 'wb')
        pickle.dump([features, labels], outfile)
        outfile.close()

    def detect_state_cnn(self, chessboard_image):
        state = []
        for row in range(8):
            row_state = []
            for column in range(8):
                height, width = chessboard_image.shape[:2]
                minX = int(column * width / 8)
                maxX = int((column + 1) * width / 8)
                minY = int(row * height / 8)
                maxY = int((row + 1) * height / 8)
                square_image = chessboard_image[minY:maxY, minX:maxX]
                is_piece = predict(square_image, self.piece_model)
                if is_piece:
                    is_white = predict(square_image, self.color_model)
                    if is_white:
                        row_state.append('w')
                    else:
                        row_state.append('b')
                else:
                    row_state.append('.')
            state.append(row_state)
        return state

    def check_state_cnn(self, result):
        for row in range(8):
            for column in range(8):
                square_name = self.board_basics.convert_row_column_to_square_name(row, column)
                square = chess.parse_square(square_name)
                piece = self.board.piece_at(square)
                expected_state = '.'
                if piece:
                    if piece.color == chess.WHITE:
                        expected_state = 'w'
                    else:
                        expected_state = 'b'

                if result[row][column] != expected_state:
                    return False
        return True

    def get_valid_2_move_cnn(self, frame):
        board_result = self.detect_state_cnn(frame)

        move_to_register = self.get_move_to_register()

        if move_to_register:
            self.board.push(move_to_register)
            for move in self.board.legal_moves:
                if move.promotion and move.promotion != chess.QUEEN:
                    continue
                self.board.push(move)
                if self.check_state_cnn(board_result):
                    self.board.pop()
                    valid_move_string = move_to_register.uci()
                    self.speech_thread.put_text(valid_move_string[:4])
                    self.played_moves.append(move_to_register)
                    self.board.pop()
                    self.executed_moves.append(self.board.san(move_to_register))
                    self.board.push(move_to_register)
                    if self.internet_game:
                        self.internet_game.is_our_turn = not self.internet_game.is_our_turn
                    print(f"First move is {valid_move_string}")
                    return True, move.uci()
                else:
                    self.board.pop()
            self.board.pop()

        return False, ""

    def get_valid_move_cnn(self, frame):
        board_result = self.detect_state_cnn(frame)

        move_to_register = self.get_move_to_register()

        if move_to_register:
            self.board.push(move_to_register)
            if self.check_state_cnn(board_result):
                self.board.pop()
                return True, move_to_register.uci()
            else:
                self.board.pop()
                return False, ""
        else:
            for move in self.board.legal_moves:
                if move.promotion and move.promotion != chess.QUEEN:
                    continue
                self.board.push(move)
                if self.check_state_cnn(board_result):
                    self.board.pop()
                    return True, move.uci()
                else:
                    self.board.pop()
        return False, ""

    def load_hog(self):
        if os.path.exists(self.save_file):
            infile = open(self.save_file, 'rb')
            self.features, self.labels = pickle.load(infile)
            infile.close()
            self.knn.train(self.features, cv2.ml.ROW_SAMPLE, self.labels)
        else:
            print("You need to play at least 1 game before starting a game from position.")
            sys.exit(0)

    def detect_state_hog(self, chessboard_image):
        chessboard_image = cv2.cvtColor(chessboard_image, cv2.COLOR_BGR2GRAY)
        chessboard = [[get_square_image(row, column, chessboard_image) for column in range(8)] for row
                      in
                      range(8)]

        board_hog = [[self.hog.compute(cv2.resize(chessboard[row][column], (64, 64))) for column in range(8)] for row
                     in
                     range(8)]
        knn_result = []
        for row in range(8):
            knn_row = []
            for column in range(8):
                ret, result, neighbours, dist = self.knn.findNearest(np.array([board_hog[row][column]]), k=3)
                knn_row.append(result[0][0])
            knn_result.append(knn_row)
        board_state = [[knn_result[row][column] > 0.5 for column in range(8)] for row
                       in
                       range(8)]
        return board_state

    def get_valid_move_hog(self, fgmask, frame):
        board = [[self.board_basics.get_square_image(row, column, fgmask).mean() for column in range(8)] for row in
                 range(8)]
        potential_squares = []
        square_scores = {}
        for row in range(8):
            for column in range(8):
                score = board[row][column]
                if score < 10.0:
                    continue
                square_name = self.board_basics.convert_row_column_to_square_name(row, column)
                square = chess.parse_square(square_name)
                potential_squares.append(square)
                square_scores[square] = score

        move_to_register = self.get_move_to_register()
        potential_moves = []

        board_result = self.detect_state_hog(frame)
        if move_to_register:
            if (move_to_register.from_square in potential_squares) and (
                    move_to_register.to_square in potential_squares):
                self.board.push(move_to_register)
                if self.check_state_hog(board_result):
                    self.board.pop()
                    return True, move_to_register.uci()
                else:
                    self.board.pop()
                    return False, ""
        else:
            for move in self.board.legal_moves:
                if (move.from_square in potential_squares) and (move.to_square in potential_squares):
                    if move.promotion and move.promotion != chess.QUEEN:
                        continue
                    self.board.push(move)
                    if self.check_state_hog(board_result):
                        self.board.pop()
                        total_score = square_scores[move.from_square] + square_scores[move.to_square]
                        potential_moves.append((total_score, move.uci()))
                    else:
                        self.board.pop()
        if potential_moves:
            return True, max(potential_moves)[1]
        else:
            return False, ""

    def get_move_to_register(self):
        if self.commentator:
            if len(self.executed_moves) < len(self.commentator.game_state.registered_moves):
                return self.commentator.game_state.registered_moves[len(self.executed_moves)]
            else:
                return None
        else:
            return None

    def is_light_change(self, frame):
        state = False
        if self.roi_mask is not None:
            result = detect_state(frame, self.board_basics.d[0], self.roi_mask)
            result_hog = self.detect_state_hog(frame)
            state = self.check_state_for_light(result, result_hog)
        if state:
            print("Light change")
            return True
        else:
            result_cnn = self.detect_state_cnn(frame)
            state_cnn = self.check_state_cnn(result_cnn)
            if state_cnn:
                print("Light change cnn")
            return state_cnn

    def check_state_hog(self, result):
        for row in range(8):
            for column in range(8):
                square_name = self.board_basics.convert_row_column_to_square_name(row, column)
                square = chess.parse_square(square_name)
                piece = self.board.piece_at(square)
                if piece and (not result[row][column]):
                    print("Expected piece at " + square_name)
                    return False
                if (not piece) and (result[row][column]):
                    print("Expected empty at " + square_name)
                    return False
        return True

    def check_state_for_move(self, result):
        for row in range(8):
            for column in range(8):
                square_name = self.board_basics.convert_row_column_to_square_name(row, column)
                square = chess.parse_square(square_name)
                piece = self.board.piece_at(square)
                if piece and (True not in result[row][column]):
                    print("Expected piece at " + square_name)
                    return False
                if (not piece) and (False not in result[row][column]):
                    print("Expected empty at " + square_name)
                    return False
        return True

    def check_state_for_light(self, result, result_hog):
        for row in range(8):
            for column in range(8):
                if len(result[row][column]) > 1:
                    result[row][column] = [result_hog[row][column]]
                square_name = self.board_basics.convert_row_column_to_square_name(row, column)
                square = chess.parse_square(square_name)
                piece = self.board.piece_at(square)
                if piece and (False in result[row][column]):
                    print(square_name)
                    return False
                if (not piece) and (True in result[row][column]):
                    print(square_name)
                    return False
        return True

    def get_valid_move_canny(self, fgmask, frame):
        if self.roi_mask is None:
            return False, ""
        board = [[self.board_basics.get_square_image(row, column, fgmask).mean() for column in range(8)] for row in
                 range(8)]
        potential_squares = []
        square_scores = {}
        for row in range(8):
            for column in range(8):
                score = board[row][column]
                if score < 10.0:
                    continue
                square_name = self.board_basics.convert_row_column_to_square_name(row, column)
                square = chess.parse_square(square_name)
                potential_squares.append(square)
                square_scores[square] = score

        move_to_register = self.get_move_to_register()
        potential_moves = []

        board_result = detect_state(frame, self.board_basics.d[0], self.roi_mask)
        if move_to_register:
            if (move_to_register.from_square in potential_squares) and (
                    move_to_register.to_square in potential_squares):
                self.board.push(move_to_register)
                if self.check_state_for_move(board_result):
                    self.board.pop()
                    return True, move_to_register.uci()
                else:
                    self.board.pop()
                    return False, ""
        else:
            for move in self.board.legal_moves:
                if (move.from_square in potential_squares) and (move.to_square in potential_squares):
                    if move.promotion and move.promotion != chess.QUEEN:
                        continue
                    self.board.push(move)
                    if self.check_state_for_move(board_result):
                        self.board.pop()
                        total_score = square_scores[move.from_square] + square_scores[move.to_square]
                        potential_moves.append((total_score, move.uci()))
                    else:
                        self.board.pop()
        if potential_moves:
            return True, max(potential_moves)[1]
        else:
            return False, ""

    def register_move(self, fgmask, previous_frame, next_frame):
        success, valid_move_string = self.get_valid_2_move_cnn(next_frame)
        if not success:
            success, valid_move_string = self.get_valid_move_cnn(next_frame)
            if not success:
                potential_squares, potential_moves = self.board_basics.get_potential_moves(fgmask, previous_frame,
                                                                                           next_frame,
                                                                                           self.board)
                success, valid_move_string = self.get_valid_move(potential_squares, potential_moves)
                if not success:
                    success, valid_move_string = self.get_valid_move_canny(fgmask, next_frame)

                    if not success:
                        success, valid_move_string = self.get_valid_move_hog(fgmask, next_frame)
                        if not success:
                            self.speech_thread.put_text(self.language.move_failed)
                            print(self.board.fen())
                            return False
                        else:
                            print("Valid move string 5:" + valid_move_string)
                    else:
                        print("Valid move string 4:" + valid_move_string)
                else:
                    print("Valid move string 3:" + valid_move_string)
            else:
                print("Valid move string 2:" + valid_move_string)
        else:
            print("Valid move string 1:" + valid_move_string)

        valid_move_UCI = chess.Move.from_uci(valid_move_string)

        print("Move has been registered")

        if self.internet_game.is_our_turn or self.make_opponent:
            self.internet_game.move(valid_move_UCI)
            self.played_moves.append(valid_move_UCI)
            while self.commentator:
                time.sleep(0.1)
                move_to_register = self.get_move_to_register()
                if move_to_register:
                    valid_move_UCI = move_to_register
                    break
        else:
            self.speech_thread.put_text(valid_move_string[:4])
            self.played_moves.append(valid_move_UCI)

        self.executed_moves.append(self.board.san(valid_move_UCI))
        is_capture = self.board.is_capture(valid_move_UCI)
        color = int(self.board.turn)
        self.board.push(valid_move_UCI)

        self.internet_game.is_our_turn = not self.internet_game.is_our_turn

        self.learn(next_frame)
        self.board_basics.update_ssim(previous_frame, next_frame, valid_move_UCI, is_capture, color)
        return True

    def learn(self, frame):
        result = self.detect_state_hog(frame)
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        new_pieces = []
        new_squares = []

        for row in range(8):
            for column in range(8):
                square_name = self.board_basics.convert_row_column_to_square_name(row, column)
                square = chess.parse_square(square_name)
                piece = self.board.piece_at(square)
                if piece and (not result[row][column]):
                    print("Learning piece at " + square_name)
                    piece_hog = self.hog.compute(cv2.resize(get_square_image(row, column, frame), (64, 64)))
                    new_pieces.append(piece_hog)
                if (not piece) and (result[row][column]):
                    print("Learning empty at " + square_name)
                    square_hog = self.hog.compute(cv2.resize(get_square_image(row, column, frame), (64, 64)))
                    new_squares.append(square_hog)
        labels_pieces = np.ones((len(new_pieces), 1), np.int32)
        labels_squares = np.zeros((len(new_squares), 1), np.int32)
        if new_pieces:
            new_pieces = np.array(new_pieces)
            self.features = np.float32(np.concatenate((self.features, new_pieces), axis=0))
            self.labels = np.concatenate((self.labels, labels_pieces), axis=0)
        if new_squares:
            new_squares = np.array(new_squares)
            self.features = np.float32(np.concatenate((self.features, new_squares), axis=0))
            self.labels = np.concatenate((self.labels, labels_squares), axis=0)

        self.features = self.features[:100]
        self.labels = self.labels[:100]
        self.knn = cv2.ml.KNearest_create()
        self.knn.train(self.features, cv2.ml.ROW_SAMPLE, self.labels)

    def get_valid_move(self, potential_squares, potential_moves):
        print("Potential squares")
        print(potential_squares)
        print("Potential moves")
        print(potential_moves)

        move_to_register = self.get_move_to_register()

        valid_move_string = ""
        for score, start, arrival in potential_moves:
            if valid_move_string:
                break

            if move_to_register:
                if chess.square_name(move_to_register.from_square) != start:
                    continue
                if chess.square_name(move_to_register.to_square) != arrival:
                    continue

            uci_move = start + arrival
            try:
                move = chess.Move.from_uci(uci_move)
            except Exception as e:
                print(e)
                continue

            if move in self.board.legal_moves:
                valid_move_string = uci_move
            else:
                if move_to_register:
                    uci_move_promoted = move_to_register.uci()
                else:
                    uci_move_promoted = uci_move + 'q'
                promoted_move = chess.Move.from_uci(uci_move_promoted)
                if promoted_move in self.board.legal_moves:
                    valid_move_string = uci_move_promoted
                    # print("There has been a promotion")

        potential_squares = [square[1] for square in potential_squares]
        print(potential_squares)
        # Detect castling king side with white
        if ("e1" in potential_squares) and ("h1" in potential_squares) and ("f1" in potential_squares) and (
                "g1" in potential_squares) and (chess.Move.from_uci("e1g1") in self.board.legal_moves):
            valid_move_string = "e1g1"

        # Detect castling queen side with white
        if ("e1" in potential_squares) and ("a1" in potential_squares) and ("c1" in potential_squares) and (
                "d1" in potential_squares) and (chess.Move.from_uci("e1c1") in self.board.legal_moves):
            valid_move_string = "e1c1"

        # Detect castling king side with black
        if ("e8" in potential_squares) and ("h8" in potential_squares) and ("f8" in potential_squares) and (
                "g8" in potential_squares) and (chess.Move.from_uci("e8g8") in self.board.legal_moves):
            valid_move_string = "e8g8"

        # Detect castling queen side with black
        if ("e8" in potential_squares) and ("a8" in potential_squares) and ("c8" in potential_squares) and (
                "d8" in potential_squares) and (chess.Move.from_uci("e8c8") in self.board.legal_moves):
            valid_move_string = "e8c8"

        if move_to_register and (move_to_register.uci() != valid_move_string):
            return False, valid_move_string

        if valid_move_string:
            return True, valid_move_string
        else:
            return False, valid_move_string


================================================
FILE: gui.py
================================================
import tkinter as tk
from tkinter.simpledialog import askstring
from tkinter import messagebox
import subprocess
import sys
from threading import Thread
import pickle
import os

running_process = None

token = ""


def lichess():
    global token
    new_token = askstring("Lichess API Access Token", "Please enter your Lichess API Access Token below.",
                          initialvalue=token)
    if new_token is None:
        pass
    else:
        token = new_token


def on_closing():
    if running_process:
        if running_process.poll() is None:
            running_process.terminate()
    save_settings()
    window.destroy()


def log_process(process, finish_message):
    global button_frame
    button_stop = tk.Button(button_frame, text="Stop", command=stop_process)
    button_stop.grid(row=0, column=0, columnspan=3, sticky="ew")
    while True:
        output = process.stdout.readline()
        if output:
            logs_text.insert(tk.END, output.decode())
        if process.poll() is not None:
            logs_text.insert(tk.END, finish_message)
            break
    global start, board
    start = tk.Button(button_frame, text="Start Game", command=start_game)
    start.grid(row=0, column=0)
    board = tk.Button(button_frame, text="Board Calibration", command=board_calibration)
    board.grid(row=0, column=1)
    diagnostic_button = tk.Button(button_frame, text="Diagnostic", command=diagnostic)
    diagnostic_button.grid(row=0, column=2)
    if promotion_menu.cget("state") == "normal":
        promotion.set(PROMOTION_OPTIONS[0])
        promotion_menu.configure(state="disabled")


def stop_process(ignore=None):
    if running_process:
        if running_process.poll() is None:
            running_process.terminate()


def diagnostic(ignore=None):
    arguments = [sys.executable, "diagnostic.py"]
    # arguments = ["diagnostic.exe"]
    # working_directory = sys.argv[0][:-3]
    # arguments = [working_directory+"diagnostic"]
    selected_camera = camera.get()
    if selected_camera != OPTIONS[0]:
        cap_index = OPTIONS.index(selected_camera) - 1
        arguments.append("cap=" + str(cap_index))
    selected_resolution = resolution.get()
    if selected_resolution != RESOLUTION_OPTIONS[0]:
        width, height = selected_resolution.split(" x ")
        arguments.append(f"width={width}")
        arguments.append(f"height={height}")
    selected_fps = fps.get()
    if selected_fps != FPS_OPTIONS[0]:
        arguments.append(f"fps={selected_fps}")
    if calibration_mode.get() == CALIBRATION_OPTIONS[-1]:
        arguments.append("calibrate")
    process = subprocess.Popen(arguments, stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT)
    # startupinfo = subprocess.STARTUPINFO()
    # startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE,
    #                           stderr=subprocess.STDOUT, stdin=subprocess.PIPE, startupinfo=startupinfo)
    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE,
    #                           stderr=subprocess.STDOUT, cwd=working_directory)
    global running_process
    running_process = process
    log_thread = Thread(target=log_process, args=(process, "Diagnostic finished.\n"))
    log_thread.daemon = True
    log_thread.start()


def board_calibration(ignore=None):
    if calibration_mode.get() == CALIBRATION_OPTIONS[-1]:
        messagebox.showinfo(
            "Board Calibration Not Required",
            "Calibration is not necessary for this mode. "
            "You can proceed directly without calibration."
        )
        return

    arguments = [sys.executable, "board_calibration.py", "show-info"]
    # arguments = ["board_calibration.exe", "show-info"]
    # working_directory = sys.argv[0][:-3]
    # arguments = [working_directory+"board_calibration", "show-info"]
    selected_camera = camera.get()
    if selected_camera != OPTIONS[0]:
        cap_index = OPTIONS.index(selected_camera) - 1
        arguments.append("cap=" + str(cap_index))
    selected_resolution = resolution.get()
    if selected_resolution != RESOLUTION_OPTIONS[0]:
        width, height = selected_resolution.split(" x ")
        arguments.append(f"width={width}")
        arguments.append(f"height={height}")
    selected_fps = fps.get()
    if selected_fps != FPS_OPTIONS[0]:
        arguments.append(f"fps={selected_fps}")
    if calibration_mode.get() == CALIBRATION_OPTIONS[1]:
        arguments.append("ml")
    process = subprocess.Popen(arguments, stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT)
    # startupinfo = subprocess.STARTUPINFO()
    # startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE,
    #                           stderr=subprocess.STDOUT, stdin=subprocess.PIPE, startupinfo=startupinfo)
    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE,
    #                           stderr=subprocess.STDOUT, cwd=working_directory)
    global running_process
    running_process = process
    log_thread = Thread(target=log_process, args=(process, "Board calibration finished.\n"))
    log_thread.daemon = True
    log_thread.start()


def start_game(ignore=None):
    arguments = [sys.executable, "main.py"]
    # arguments = ["main.exe"]
    # working_directory = sys.argv[0][:-3]
    # arguments = [working_directory+"main"]
    if no_template.get():
        arguments.append("no-template")
    if make_opponent.get():
        arguments.append("make-opponent")
    if comment_me.get():
        arguments.append("comment-me")
    if comment_opponent.get():
        arguments.append("comment-opponent")
    if drag_drop.get():
        arguments.append("drag")
    global token
    if token:
        arguments.append("token=" + token)
        promotion_menu.configure(state="normal")
        promotion.set(PROMOTION_OPTIONS[0])

    arguments.append("delay=" + str(values.index(default_value.get())))

    selected_camera = camera.get()
    if selected_camera != OPTIONS[0]:
        cap_index = OPTIONS.index(selected_camera) - 1
        arguments.append("cap=" + str(cap_index))
    selected_resolution = resolution.get()
    if selected_resolution != RESOLUTION_OPTIONS[0]:
        width, height = selected_resolution.split(" x ")
        arguments.append(f"width={width}")
        arguments.append(f"height={height}")
    selected_fps = fps.get()
    if selected_fps != FPS_OPTIONS[0]:
        arguments.append(f"fps={selected_fps}")
    selected_voice = voice.get()
    if selected_voice != VOICE_OPTIONS[0]:
        voice_index = VOICE_OPTIONS.index(selected_voice) - 1
        arguments.append("voice=" + str(voice_index))
        language = "English"
        languages = ["English", "German", "Russian", "Turkish", "Italian", "French"]
        codes = ["en_", "de_", "ru_", "tr_", "it_", "fr_"]
        for l, c in zip(languages, codes):
            if (l in selected_voice) or (l.lower() in selected_voice) or (c in selected_voice):
                language = l
                break
        arguments.append("lang=" + language)

    if calibration_mode.get() == CALIBRATION_OPTIONS[-1]:
        arguments.append("calibrate")

    process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    # startupinfo = subprocess.STARTUPINFO()
    # startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE,
    #                           stderr=subprocess.STDOUT, stdin=subprocess.PIPE, startupinfo=startupinfo)
    # process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=working_directory)
    global running_process
    running_process = process
    log_thread = Thread(target=log_process, args=(process, "Game finished.\n"))
    log_thread.daemon = True
    log_thread.start()


window = tk.Tk()
window.title("Play online chess with a real chess board by Alper Karayaman")

menu_bar = tk.Menu(window)
connection = tk.Menu(menu_bar, tearoff=False)
connection.add_command(label="Lichess", command=lichess)

menu_bar.add_cascade(label="Connection", menu=connection)

window.config(menu=menu_bar)

no_template = tk.IntVar()
make_opponent = tk.IntVar()
drag_drop = tk.IntVar()
comment_me = tk.IntVar()
comment_opponent = tk.IntVar()

menu_frame = tk.Frame(window)
menu_frame.grid(row=0, column=0, columnspan=2, sticky="W")
camera = tk.StringVar()
OPTIONS = ["Default"]
try:
    import platform

    platform_name = platform.system()
    if platform_name == "Darwin":
        cmd = 'system_profiler SPCameraDataType | grep "^    [^ ]" | sed "s/    //" | sed "s/://"'
        result = subprocess.check_output(cmd, shell=True)
        result = result.decode()
        result = [r for r in result.split("\n") if r]
        OPTIONS.extend(result)
    elif platform_name == "Linux":
        cmd = 'for I in /sys/class/video4linux/*; do cat $I/name; done'
        result = subprocess.check_output(cmd, shell=True)
        result = result.decode()
        result = [r for r in result.split("\n") if r]
        OPTIONS.extend(result)
    else:
        from pygrabber.dshow_graph import FilterGraph

        OPTIONS.extend(FilterGraph().get_input_devices())
except:
    pass
camera.set(OPTIONS[0])
label = tk.Label(menu_frame, text='Select Webcam:')
label.grid(column=0, row=0, sticky=tk.W)
menu = tk.OptionMenu(menu_frame, camera, *OPTIONS)
menu.config(width=max(len(option) for option in OPTIONS), anchor="w")
menu.grid(column=1, row=0, sticky=tk.W)

resolution_frame = tk.Frame(window)
resolution_frame.grid(row=1, column=0, columnspan=2, sticky="W")
resolution = tk.StringVar()
RESOLUTION_OPTIONS = ["Default", "640 x 480", "1280 x 720", "1920 x 1080", "2560 x 1440", "3840 x 2160"]
resolution.set(RESOLUTION_OPTIONS[0])
resolution_label = tk.Label(resolution_frame, text='Select Webcam Resolution:')
resolution_label.grid(column=0, row=0, sticky=tk.W)
resolution_menu = tk.OptionMenu(resolution_frame, resolution, *RESOLUTION_OPTIONS)
resolution_menu.config(width=max(len(option) for option in RESOLUTION_OPTIONS), anchor="w")
resolution_menu.grid(column=1, row=0, sticky=tk.W)

fps_frame = tk.Frame(window)
fps_frame.grid(row=2, column=0, columnspan=2, sticky="W")
fps = tk.StringVar()
FPS_OPTIONS = ["Default", "15", "24", "30", "60", "120", "144", "240"]
fps.set(FPS_OPTIONS[0])
fps_label = tk.Label(fps_frame, text='Select Webcam FPS:')
fps_label.grid(column=0, row=0, sticky=tk.W)
fps_menu = tk.OptionMenu(fps_frame, fps, *FPS_OPTIONS)
fps_menu.config(width=max(len(option) for option in FPS_OPTIONS), anchor="w")
fps_menu.grid(column=1, row=0, sticky=tk.W)

calibration_frame = tk.Frame(window)
calibration_frame.grid(row=3, column=0, columnspan=2, sticky="W")
calibration_mode = tk.StringVar()
CALIBRATION_OPTIONS = ["The board is empty.", "Pieces are in their starting positions.",
                       "Just before the game starts."]
calibration_mode.set(CALIBRATION_OPTIONS[0])
calibration_label = tk.Label(calibration_frame, text='Board Calibration Mode:')
calibration_label.grid(column=0, row=0, sticky=tk.W)
calibration_menu = tk.OptionMenu(calibration_frame, calibration_mode, *CALIBRATION_OPTIONS)
calibration_menu.config(width=max(len(option) for option in CALIBRATION_OPTIONS), anchor="w")
calibration_menu.grid(column=1, row=0, sticky=tk.W)

voice_frame = tk.Frame(window)
voice_frame.grid(row=4, column=0, columnspan=2, sticky="W")
voice = tk.StringVar()
VOICE_OPTIONS = ["Default"]
try:
    import platform

    if platform.system() == "Darwin":
        result = subprocess.run(['say', '-v', '?'], stdout=subprocess.PIPE)
        output = result.stdout.decode('utf-8')
        for line in output.splitlines():
            if line:
                voice_info = line.split()
                VOICE_OPTIONS.append(f'{voice_info[0]} {voice_info[1]}')
    else:
        import pyttsx3

        engine = pyttsx3.init()
        for v in engine.getProperty('voices'):
            VOICE_OPTIONS.append(v.name)
except:
    pass
voice.set(VOICE_OPTIONS[0])
voice_label = tk.Label(voice_frame, text='Select Voice:')
voice_label.grid(column=0, row=0, sticky=tk.W)
voice_menu = tk.OptionMenu(voice_frame, voice, *VOICE_OPTIONS)
voice_menu.config(width=max(len(option) for option in VOICE_OPTIONS), anchor="w")
voice_menu.grid(column=1, row=0, sticky=tk.W)


def save_promotion(*args):
    outfile = open("promotion.bin", 'wb')
    pickle.dump(promotion.get(), outfile)
    outfile.close()


promotion_frame = tk.Frame(window)
promotion_frame.grid(row=5, column=0, columnspan=2, sticky="W")
promotion = tk.StringVar()
promotion.trace("w", save_promotion)
PROMOTION_OPTIONS = ["Queen", "Knight", "Rook", "Bishop"]
promotion.set(PROMOTION_OPTIONS[0])
promotion_label = tk.Label(promotion_frame, text='Select Promotion Piece:')
promotion_label.grid(column=0, row=0, sticky=tk.W)
promotion_menu = tk.OptionMenu(promotion_frame, promotion, *PROMOTION_OPTIONS)
promotion_menu.config(width=max(len(option) for option in PROMOTION_OPTIONS), anchor="w")
promotion_menu.grid(column=1, row=0, sticky=tk.W)
promotion_menu.configure(state="disabled")

c = tk.Checkbutton(window, text="Find chess board of online game without template images.", variable=no_template)
c.grid(row=6, column=0, sticky="W", columnspan=1)

c1 = tk.Checkbutton(window, text="Make moves of opponent too.", variable=make_opponent)
c1.grid(row=7, column=0, sticky="W", columnspan=1)

c2 = tk.Checkbutton(window, text="Make moves by drag and drop.", variable=drag_drop)
c2.grid(row=8, column=0, sticky="W", columnspan=1)

c2 = tk.Checkbutton(window, text="Speak my moves.", variable=comment_me)
c2.grid(row=9, column=0, sticky="W", columnspan=1)

c3 = tk.Checkbutton(window, text="Speak opponent's moves.", variable=comment_opponent)
c3.grid(row=10, column=0, sticky="W", columnspan=1)

values = ["Do not delay game start.", "1 second delayed game start."] + [str(i) + " seconds delayed game start." for i
                                                                         in range(2, 6)]
default_value = tk.StringVar()
s = tk.Spinbox(window, values=values, textvariable=default_value, width=max(len(value) for value in values))
default_value.set(values[-1])
s.grid(row=11, column=0, sticky="W", columnspan=2)
button_frame = tk.Frame(window)
button_frame.grid(row=12, column=0, columnspan=2, sticky="W")
start = tk.Button(button_frame, text="Start Game", command=start_game)
start.grid(row=0, column=0)
board = tk.Button(button_frame, text="Board Calibration", command=board_calibration)
board.grid(row=0, column=1)
diagnostic_button = tk.Button(button_frame, text="Diagnostic", command=diagnostic)
diagnostic_button.grid(row=0, column=2)
text_frame = tk.Frame(window)
text_frame.grid(row=13, column=0)
scroll_bar = tk.Scrollbar(text_frame)
logs_text = tk.Text(text_frame, background='gray', yscrollcommand=scroll_bar.set)
scroll_bar.config(command=logs_text.yview)
scroll_bar.pack(side=tk.RIGHT, fill=tk.Y)
logs_text.pack(side="left")

fields = [no_template, make_opponent, comment_me, comment_opponent, calibration_mode, resolution, fps, drag_drop,
          default_value, camera, voice]
save_file = 'gui.bin'


def save_settings():
    outfile = open(save_file, 'wb')
    pickle.dump([field.get() for field in fields] + [token], outfile)
    outfile.close()


def load_settings():
    if os.path.exists(save_file):
        infile = open(save_file, 'rb')
        variables = pickle.load(infile)
        infile.close()
        global token
        token = variables[-1]
        if variables[-2] in VOICE_OPTIONS:
            voice.set(variables[-2])

        if variables[-3] in OPTIONS:
            camera.set(variables[-3])

        for i in range(9):
            fields[i].set(variables[i])


load_settings()
window.protocol("WM_DELETE_WINDOW", on_closing)
window.mainloop()


================================================
FILE: helper.py
================================================
import cv2
import numpy as np
from math import sqrt


def euclidean_distance(first, second):
    return sqrt((first[0] - second[0]) ** 2 + (first[1] - second[1]) ** 2)


def perspective_transform(image, pts1):
    dimension = 480
    pts2 = np.float32([[0, 0], [0, dimension], [dimension, 0], [dimension, dimension]])
    M = cv2.getPerspectiveTransform(pts1, pts2)
    dst = cv2.warpPerspective(image, M, (dimension, dimension))
    return dst


def rotateMatrix(matrix):
    size = len(matrix)
    for row in range(size // 2):
        for column in range(row, size - row - 1):
            temp = matrix[row][column]
            matrix[row][column] = matrix[column][size - 1 - row]
            matrix[column][size - 1 - row] = matrix[size - 1 - row][size - 1 - column]
            matrix[size - 1 - row][size - 1 - column] = matrix[size - 1 - column][row]
            matrix[size - 1 - column][row] = temp


def auto_canny(image):
    sigma_upper = 0.2
    sigma_lower = 0.8
    median_intensity = np.median(image)
    lower = int(max(0, (1.0 - sigma_lower) * median_intensity))
    upper = int(min(255, (1.0 + sigma_upper) * median_intensity))
    edged = cv2.Canny(image, lower, upper)
    return edged


def edge_detection(frame):
    kernel = np.ones((3, 3), np.uint8)
    clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
    edges = []
    for gray in cv2.split(frame):
        gray = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)
        gray = clahe.apply(gray)
        gray = cv2.GaussianBlur(gray, (3, 3), 0)
        edge = auto_canny(gray)
        edges.append(edge)
    edges = cv2.bitwise_or(cv2.bitwise_or(edges[0], edges[1]), edges[2])
    kernel2 = np.ones((3, 3), np.uint8)
    edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel2)
    return edges

def get_square_image(row, column,
                     board_img):
    height, width = board_img.shape[:2]
    minX = int(column * width / 8)
    maxX = int((column + 1) * width / 8)
    minY = int(row * height / 8)
    maxY = int((row + 1) * height / 8)
    square = board_img[minY:maxY, minX:maxX]
    square_without_borders = square[3:-3, 3:-3]
    return square_without_borders


def contains_piece(square, view):
    height, width = square.shape[:2]
    if view == (0, -1):
        half = square[:, width // 2:]
    elif view == (0, 1):
        half = square[:, :width // 2]
    elif view == (1, 0):
        half = square[height // 2:, :]
    elif view == (-1, 0):
        half = square[:height // 2, :]
    if half.mean() < 1.0:
        return [False]
    elif square.mean() > 15.0:
        return [True]
    elif square.mean() > 6.0:
        return [True, False]
    else:
        if square.mean() > 2.0:
            print("empty " + str(square.mean()))
        return [False]


def detect_state(frame, view, roi_mask):
    edges = edge_detection(frame)
    edges = cv2.bitwise_and(edges, roi_mask)
    # cv2.imwrite("edge.jpg", edges)
    board_image = [[get_square_image(row, column, edges) for column in range(8)] for row
                   in
                   range(8)]
    result = [[contains_piece(board_image[row][column], view) for column in range(8)] for row in
              range(8)]
    return result


def predict(image, model):
    image = cv2.resize(image, (64, 64))
    image = image.astype(np.float32) / 255.0
    image = np.transpose(image, (2, 0, 1))
    image = np.expand_dims(image, axis=0)

    # Make a forward pass through the network
    model.setInput(image)
    output = model.forward()

    # Get the predicted class label
    label = np.argmax(output)
    return label


================================================
FILE: internet_game.py
================================================
import chessboard_detection
import pyautogui
import time


class Internet_game:
    def __init__(self, use_template, start_delay, drag_drop):
        self.drag_drop = drag_drop
        time.sleep(start_delay)
        if use_template:
            self.position, self.we_play_white = chessboard_detection.find_chessboard()
        else:
            self.position, self.we_play_white = chessboard_detection.auto_find_chessboard()
        self.is_our_turn = self.we_play_white

    def move(self, move):
        move_string = move.uci()

        origin_square = move_string[0:2]
        destination_square = move_string[2:4]

        centerXOrigin, centerYOrigin = self.get_square_center(origin_square)
        centerXDest, centerYDest = self.get_square_center(destination_square)

        if self.drag_drop:
            pyautogui.moveTo(centerXOrigin, centerYOrigin, 0.01)
            pyautogui.dragTo(centerXOrigin, centerYOrigin + 1, button='left',
                             duration=0.01)
            pyautogui.dragTo(centerXDest, centerYDest, button='left', duration=0.3)
        else:
            pyautogui.click(centerXOrigin, centerYOrigin, duration=0.1)
            pyautogui.click(centerXDest, centerYDest, duration=0.1)

        print("Done playing move", origin_square, destination_square)
        return

    def get_square_center(self, square_name):
        row, column = self.convert_square_name_to_row_column(square_name, self.we_play_white)
        position = self.position
        centerX = int(position.minX + (column + 0.5) * (position.maxX - position.minX) / 8)
        centerY = int(position.minY + (row + 0.5) * (position.maxY - position.minY) / 8)
        return centerX, centerY

    def convert_square_name_to_row_column(self, square_name, is_white_on_bottom):
        for row in range(8):
            for column in range(8):
                this_square_name = self.convert_row_column_to_square_name(row, column, is_white_on_bottom)
                if this_square_name == square_name:
                    return row, column
        return 0, 0

    def convert_row_column_to_square_name(self, row, column, is_white_on_bottom):
        if is_white_on_bottom == True:
            number = repr(8 - row)
            letter = str(chr(97 + column))
            return letter + number
        else:
            number = repr(row + 1)
            letter = str(chr(97 + (7 - column)))
            return letter + number


================================================
FILE: languages.py
================================================
import chess


class English:
    def __init__(self):
        self.game_started = "Game started"
        self.move_failed = "Move registration failed. Please redo your move."

    def name(self, piece_type):
        if piece_type == chess.PAWN:
            return "pawn"
        elif piece_type == chess.KNIGHT:
            return "knight"
        elif piece_type == chess.BISHOP:
            return "bishop"
        elif piece_type == chess.ROOK:
            return "rook"
        elif piece_type == chess.QUEEN:
            return "queen"
        elif piece_type == chess.KING:
            return "king"

    def comment(self, board, move):
        check = ""
        if board.is_checkmate():
            check = " checkmate"
        elif board.is_check():
            check = " check"
        board.pop()
        if board.is_kingside_castling(move):
            board.push(move)
            return "castling short" + check
        if board.is_queenside_castling(move):
            board.push(move)
            return "castling long" + check

        piece = board.piece_at(move.from_square)
        from_square = chess.square_name(move.from_square)
        to_square = chess.square_name(move.to_square)
        promotion = move.promotion

        is_capture = board.is_capture(move)
        board.push(move)
        comment = ""
        comment += self.name(piece.piece_type)

        comment += " " + from_square
        comment += " takes" if is_capture else " to"
        comment += " " + to_square
        if promotion:
            comment += " promotion to " + self.name(promotion)
        comment += check
        return comment


class German:
    def __init__(self):
        self.game_started = "Das Spiel hat gestartet."
        self.move_failed = "Der Zug ist ungültig, bitte wiederholen."

    def name(self, piece_type):
        if piece_type == chess.PAWN:
            return "Bauer"
        elif piece_type == chess.KNIGHT:
            return "Springer"
        elif piece_type == chess.BISHOP:
            return "Läufer"
        elif piece_type == chess.ROOK:
            return "Turm"
        elif piece_type == chess.QUEEN:
            return "Dame"
        elif piece_type == chess.KING:
            return "König"

    def comment(self, board, move):
        check = ""
        if board.is_checkmate():
            check = " Schachmatt"
        elif board.is_check():
            check = " Schach"
        board.pop()
        if board.is_kingside_castling(move):
            board.push(move)
            return "kurze Rochade" + check
        if board.is_queenside_castling(move):
            board.push(move)
            return "lange Rochade" + check

        piece = board.piece_at(move.from_square)
        from_square = chess.square_name(move.from_square)
        to_square = chess.square_name(move.to_square)
        promotion = move.promotion

        is_capture = board.is_capture(move)
        board.push(move)
        comment = ""
        comment += self.name(piece.piece_type)

        comment += " " + from_square
        comment += " schlägt" if is_capture else " nach"
        comment += " " + to_square
        if promotion:
            comment += " Umwandlung in " + self.name(promotion)
        comment += check
        return comment


class Russian:
    def __init__(self):
        self.game_started = "игра началась"
        self.move_failed = "Ошибка регистрации хода. Пожалуйста, повторите свой ход"

    def name(self, piece_type):
        if piece_type == chess.PAWN:
            return "пешка"
        elif piece_type == chess.KNIGHT:
            return "конь"
        elif piece_type == chess.BISHOP:
            return "слон"
        elif piece_type == chess.ROOK:
            return "ладья"
        elif piece_type == chess.QUEEN:
            return "ферзь"
        elif piece_type == chess.KING:
            return "король"

    def comment(self, board, move):
        check = ""
        if board.is_checkmate():
            check = " шах и мат"
        elif board.is_check():
            check = " шах"
        board.pop()
        if board.is_kingside_castling(move):
            board.push(move)
            return "короткая рокировка" + check
        if board.is_queenside_castling(move):
            board.push(move)
            return "длинная рокировка" + check

        piece = board.piece_at(move.from_square)
        from_square = chess.square_name(move.from_square)
        to_square = chess.square_name(move.to_square)
        promotion = move.promotion

        is_capture = board.is_capture(move)
        board.push(move)
        comment = ""
        comment += self.name(piece.piece_type)

        comment += " " + from_square
        comment += " бьёт" if is_capture else ""
        comment += " " + to_square
        if promotion:
            comment += " превращение в " + self.name(promotion)
        comment += check
        return comment


class Turkish:
    def __init__(self):
        self.game_started = "Oyun başladı."
        self.move_failed = "Hamle geçersiz. Lütfen hamlenizi yeniden yapın."

    def capture_suffix(self, to_square):
        if to_square[-1] in "158":
            return "i"
        elif to_square[-1] in "27":
            return "yi"
        elif to_square[-1] in "34":
            return "ü"
        else:  # 6
            return "yı"

    def from_suffix(self, from_square):
        if from_square[-1] in "1278":
            return "den"
        elif from_square[-1] in "345":
            return "ten"
        else:  # 6
            return "dan"

    def to_suffix(self, to_square):
        if to_square[-1] in "13458":
            return "e"
        elif to_square[-1] in "27":
            return "ye"
        else:  # 6
            return "ya"

    def comment(self, board, move):
        check = ""
        if board.is_checkmate():
            check = " şahmat"
        elif board.is_check():
            check = " şah"
        board.pop()
        if board.is_kingside_castling(move):
            board.push(move)
            return "kısa rok" + check
        if board.is_queenside_castling(move):
            board.push(move)
            return "uzun rok" + check

        piece = board.piece_at(move.from_square)
        from_square = chess.square_name(move.from_square)
        to_square = chess.square_name(move.to_square)
        promotion = move.promotion

        is_capture = board.is_capture(move)
        board.push(move)
        comment = ""
        if piece.piece_type == chess.PAWN:
            comment += "piyon"
        elif piece.piece_type == chess.KNIGHT:
            comment += "at"
        elif piece.piece_type == chess.BISHOP:
            comment += "fil"
        elif piece.piece_type == chess.ROOK:
            comment += "kale"
        elif piece.piece_type == chess.QUEEN:
            comment += "vezir"
        elif piece.piece_type == chess.KING:
            comment += "şah"

        comment += " " + from_square
        if is_capture:
            comment += " alır"
            comment += " " + to_square + "'" + self.capture_suffix(to_square)
        else:
            comment += "'" + self.from_suffix(from_square) + " " + to_square + "'" + self.to_suffix(to_square)

        if promotion:
            comment += " "
            if promotion == chess.KNIGHT:
                comment += "ata"
            elif promotion == chess.BISHOP:
                comment += "file"
            elif promotion == chess.ROOK:
                comment += "kaleye"
            elif promotion == chess.QUEEN:
                comment += "vezire"
            comment += " terfi"
        comment += check
        return comment


class Italian:
    def __init__(self):
        self.game_started = "Gioco iniziato"
        self.move_failed = "Registrazione spostamento non riuscita. Per favore rifai la tua mossa."

    def name(self, piece_type):
        if piece_type == chess.PAWN:
            return "pedone"
        elif piece_type == chess.KNIGHT:
            return "cavallo"
        elif piece_type == chess.BISHOP:
            return "alfiere"
        elif piece_type == chess.ROOK:
            return "torre"
        elif piece_type == chess.QUEEN:
            return "regina"
        elif piece_type == chess.KING:
            return "re"

    def prefix_name(self, piece_type):
        if piece_type == chess.PAWN:
            return "il pedone"
        elif piece_type == chess.KNIGHT:
            return "il cavallo"
        elif piece_type == chess.BISHOP:
            return "l'alfiere"
        elif piece_type == chess.ROOK:
            return "la torre"
        elif piece_type == chess.QUEEN:
            return "la regina"
        elif piece_type == chess.KING:
            return "il re"

    def comment(self, board, move):
        check = ""
        if board.is_checkmate():
            check = " scacco matto"
        elif board.is_check():
            check = " scacco"
        board.pop()
        if board.is_kingside_castling(move):
            board.push(move)
            return "arrocco corto" + check
        if board.is_queenside_castling(move):
            board.push(move)
            return "arrocco lungo" + check

        piece = board.piece_at(move.from_square)
        from_square = chess.square_name(move.from_square)
        to_square = chess.square_name(move.to_square)
        promotion = move.promotion

        is_capture = board.is_capture(move)
        board.push(move)
        comment = ""
        if is_capture:
            comment += self.prefix_name(piece.piece_type)
            comment += " " + from_square
            comment += " cattura"
            comment += " " + to_square
        else:
            comment += self.name(piece.piece_type)
            comment += " da " + from_square
            comment += " a " + to_square
        if promotion:
            comment += " promuove a " + self.name(promotion)
        comment += check
        return comment


class French:
    def __init__(self):
        self.game_started = "Partie démarrée"
        self.move_failed = "La reconnaissance a échoué. Veuillez réessayer."

    def name(self, piece_type):
        if piece_type == chess.PAWN:
            return "pion"
        elif piece_type == chess.KNIGHT:
            return "cavalier"
        elif piece_type == chess.BISHOP:
            return "fou"
        elif piece_type == chess.ROOK:
            return "tour"
        elif piece_type == chess.QUEEN:
            return "reine"
        elif piece_type == chess.KING:
            return "roi"

    def comment(self, board, move):
        check = ""
        if board.is_checkmate():
            check = " échec et mat"
        elif board.is_check():
            check = " échec"
        board.pop()
        if board.is_kingside_castling(move):
            board.push(move)
            return "petit roc" + check
        if board.is_queenside_castling(move):
            board.push(move)
            return "grand roc" + check

        piece = board.piece_at(move.from_square)
        from_square = chess.square_name(move.from_square)
        to_square = chess.square_name(move.to_square)
        promotion = move.promotion

        is_capture = board.is_capture(move)
        board.push(move)
        comment = ""
        comment += self.name(piece.piece_type)

        comment += " " + from_square
        comment += " prend" if is_capture else " vers"
        comment += " " + to_square
        if promotion:
            comment += " promu en " + self.name(promotion)
        comment += check
        return comment


================================================
FILE: lichess_commentator.py
================================================
from threading import Thread
import chess


class Lichess_commentator(Thread):

    def __init__(self, *args, **kwargs):
        super(Lichess_commentator, self).__init__(*args, **kwargs)
        self.stream = None
        self.speech_thread = None
        self.game_state = Game_state()
        self.comment_me = None
        self.comment_opponent = None
        self.language = None

    def run(self):
        while not self.game_state.board.is_game_over():
            is_my_turn = (self.game_state.we_play_white) == (self.game_state.board.turn == chess.WHITE)
            found_move, move = self.game_state.register_move_if_needed(self.stream)
            if found_move and ((self.comment_me and is_my_turn) or (self.comment_opponent and (not is_my_turn))):
                self.speech_thread.put_text(self.language.comment(self.game_state.board, move))


class Game_state:

    def __init__(self):
        self.we_play_white = None
        self.board = chess.Board()
        self.registered_moves = []
        self.resign_or_draw = False
        self.game = None
        self.variant = 'wait'

    def register_move_if_needed(self, stream):
        current_state = next(stream)
        if 'state' in current_state:
            if current_state['initialFen'] == 'startpos':
                self.variant = 'standard'
            else:
                self.variant = 'fromPosition'
                self.from_position(current_state['initialFen'])
            current_state = current_state['state']
        if 'moves' in current_state:
            moves = current_state['moves'].split()
            if len(moves) > len(self.registered_moves):
                valid_move_string = moves[len(self.registered_moves)]
                valid_move_UCI = chess.Move.from_uci(valid_move_string)
                self.register_move(valid_move_UCI)
                return True, valid_move_UCI
            while len(moves) < len(self.registered_moves):
                self.unregister_move()
        if 'status' in current_state and current_state['status'] in ["resign", "draw"]:
            self.resign_or_draw = True
        return False, "No move found"

    def register_move(self, move):
        if move in self.board.legal_moves:
            self.board.push(move)
            self.registered_moves.append(move)
            return True
        else:
            return False

    def unregister_move(self):
        self.board.pop()
        self.registered_moves.pop()
        if len(self.registered_moves) < len(self.game.executed_moves):
            self.game.executed_moves.pop()
            self.game.played_moves.pop()
            self.game.board.pop()
            self.game.internet_game.is_our_turn = not self.game.internet_game.is_our_turn

    def from_position(self, fen):
        self.board = chess.Board(fen)
        self.game.board = chess.Board(fen)
        if self.board.turn == chess.BLACK:
            self.game.internet_game.is_our_turn = not self.game.internet_game.is_our_turn


================================================
FILE: lichess_game.py
================================================
import berserk
import sys
import os
import chess
import pickle


class Lichess_game:
    def __init__(self, token):
        session = berserk.TokenSession(token)
        client = berserk.Client(session)
        games = client.games.get_ongoing()
        if len(games) == 0:
            print("No games found. Please create your game on Lichess.")
            sys.exit(0)
        if len(games) > 1:
            print("Multiple games found. Please make sure there is only one ongoing game on Lichess.")
            sys.exit(0)
        game = games[0]
        self.we_play_white = game['color'] == 'white'
        self.is_our_turn = self.we_play_white
        self.client = client
        self.game_id = game['gameId']
        self.token = token
        self.save_file = "promotion.bin"
        self.promotion_pieces = {
            "Queen": chess.QUEEN,
            "Knight": chess.KNIGHT,
            "Rook": chess.ROOK,
            "Bishop": chess.BISHOP
        }

    def move(self, move):
        if move.promotion and os.path.exists(self.save_file):
            infile = open(self.save_file, 'rb')
            piece_name = pickle.load(infile)
            infile.close()
            move.promotion = self.promotion_pieces[piece_name]
        move_string = move.uci()
        try:
            self.client.board.make_move(self.game_id, move_string)
        except:
            session = berserk.TokenSession(self.token)
            self.client = berserk.Client(session)
            self.client.board.make_move(self.game_id, move_string)
            print("Reconnected to Lichess.")
        print("Done playing move " + move_string)


================================================
FILE: main.py
================================================
import time
import cv2
import pickle
import numpy as np
import sys
from collections import deque
import platform
from board_calibration_machine_learning import detect_board
from game import Game
from board_basics import Board_basics
from helper import perspective_transform
from speech import Speech_thread
from videocapture import Video_capture_thread
from languages import *

webcam_width = None
webcam_height = None
fps = None
use_template = True
make_opponent = False
drag_drop = False
comment_me = False
comment_opponent = False
calibrate = False
start_delay = 5  # seconds
cap_index = 0
cap_api = cv2.CAP_ANY
voice_index = 0
language = English()
token = ""
for argument in sys.argv:
    if argument == "no-template":
        use_template = False
    elif argument == "make-opponent":
        make_opponent = True
    elif argument == "comment-me":
        comment_me = True
    elif argument == "comment-opponent":
        comment_opponent = True
    elif argument.startswith("delay="):
        start_delay = int("".join(c for c in argument if c.isdigit()))
    elif argument == "drag":
        drag_drop = True
    elif argument.startswith("cap="):
        cap_index = int("".join(c for c in argument if c.isdigit()))
        platform_name = platform.system()
        if platform_name == "Darwin":
            cap_api = cv2.CAP_AVFOUNDATION
        elif platform_name == "Linux":
            cap_api = cv2.CAP_V4L2
        else:
            cap_api = cv2.CAP_DSHOW
    elif argument.startswith("voice="):
        voice_index = int("".join(c for c in argument if c.isdigit()))
    elif argument.startswith("lang="):
        if "German" in argument:
            language = German()
        elif "Russian" in argument:
            language = Russian()
        elif "Turkish" in argument:
            language = Turkish()
        elif "Italian" in argument:
            language = Italian()
        elif "French" in argument:
            language = French()
    elif argument.startswith("token="):
        token = argument[len("token="):].strip()
    elif argument == "calibrate":
        calibrate = True
    elif argument.startswith("width="):
        webcam_width = int(argument[len("width="):])
    elif argument.startswith("height="):
        webcam_height = int(argument[len("height="):])
    elif argument.startswith("fps="):
        fps = int(argument[len("fps="):])
MOTION_START_THRESHOLD = 1.0
HISTORY = 100
MAX_MOVE_MEAN = 50
COUNTER_MAX_VALUE = 3

move_fgbg = cv2.createBackgroundSubtractorKNN()
motion_fgbg = cv2.createBackgroundSubtractorKNN(history=HISTORY)

video_capture_thread = Video_capture_thread()
video_capture_thread.daemon = True
video_capture_thread.capture = cv2.VideoCapture(cap_index, cap_api)
if webcam_width is not None:
    video_capture_thread.capture.set(cv2.CAP_PROP_FRAME_WIDTH, webcam_width)
if webcam_height is not None:
    video_capture_thread.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, webcam_height)
if fps is not None:
    video_capture_thread.capture.set(cv2.CAP_PROP_FPS, fps)
if calibrate:
    corner_model = cv2.dnn.readNetFromONNX("yolo_corner.onnx")
    piece_model = cv2.dnn.readNetFromONNX("cnn_piece.onnx")
    color_model = cv2.dnn.readNetFromONNX("cnn_color.onnx")
    for _ in range(10):
        ret, frame = video_capture_thread.capture.read()
        if ret == False:
            print("Error reading frame. Please check your webcam connection.")
            continue
    is_detected = False
    for _ in range(100):
        ret, frame = video_capture_thread.capture.read()
        if ret == False:
            print("Error reading frame. Please check your webcam connection.")
            continue
        result = detect_board(frame, corner_model, piece_model, color_model)
        if result:
            pts1, side_view_compensation, rotation_count = result
            roi_mask = None
            is_detected = True
            break
    if not is_detected:
        print("Could not detect the chess board.")
        video_capture_thread.capture.release()
        sys.exit(0)
else:
    filename = 'constants.bin'
    infile = open(filename, 'rb')
    calibration_data = pickle.load(infile)
    infile.close()
    if calibration_data[0]:
        pts1, side_view_compensation, rotation_count = calibration_data[1]
        roi_mask = None
    else:
        corners, side_view_compensation, rotation_count, roi_mask = calibration_data[1]
        pts1 = np.float32([list(corners[0][0]), list(corners[8][0]), list(corners[0][8]),
                           list(corners[8][8])])
video_capture_thread.start()
board_basics = Board_basics(side_view_compensation, rotation_count)

speech_thread = Speech_thread()
speech_thread.daemon = True
speech_thread.index = voice_index
speech_thread.start()

game = Game(board_basics, speech_thread, use_template, make_opponent, start_delay, comment_me, comment_opponent,
            drag_drop, language, token, roi_mask)

def waitUntilMotionCompletes():
    counter = 0
    while counter < COUNTER_MAX_VALUE:
        frame = video_capture_thread.get_frame()
        frame = perspective_transform(frame, pts1)
        fgmask = motion_fgbg.apply(frame)
        ret, fgmask = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY)
        mean = fgmask.mean()
        if mean < MOTION_START_THRESHOLD:
            counter += 1
        else:
            counter = 0


def stabilize_background_subtractors():
    best_mean = float("inf")
    counter = 0
    while counter < COUNTER_MAX_VALUE:
        frame = video_capture_thread.get_frame()
        frame = perspective_transform(frame, pts1)
        move_fgbg.apply(frame)
        fgmask = motion_fgbg.apply(frame, learningRate=0.1)
        ret, fgmask = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY)
        mean = fgmask.mean()
        if mean >= best_mean:
            counter += 1
        else:
            best_mean = mean
            counter = 0

    best_mean = float("inf")
    counter = 0
    while counter < COUNTER_MAX_VALUE:
        frame = video_capture_thread.get_frame()
        frame = perspective_transform(frame, pts1)
        fgmask = move_fgbg.apply(frame, learningRate=0.1)
        ret, fgmask = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY)
        motion_fgbg.apply(frame)
        mean = fgmask.mean()
        if mean >= best_mean:
            counter += 1
        else:
            best_mean = mean
            counter = 0

    return frame


previous_frame = stabilize_background_subtractors()
previous_frame_queue = deque(maxlen=10)
previous_frame_queue.append(previous_frame)
speech_thread.put_text(language.game_started)
game.commentator.start()
while game.commentator.game_state.variant == 'wait':
    time.sleep(0.1)
if game.commentator.game_state.variant == 'standard':
    board_basics.initialize_ssim(previous_frame)
    game.initialize_hog(previous_frame)
else:
    board_basics.load_ssim()
    game.load_hog()
while not game.board.is_game_over() and not game.commentator.game_state.resign_or_draw:
    sys.stdout.flush()
    frame = video_capture_thread.get_frame()
    frame = perspective_transform(frame, pts1)
    fgmask = motion_fgbg.apply(frame)
    ret, fgmask = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY)
    kernel = np.ones((11, 11), np.uint8)
    fgmask = cv2.erode(fgmask, kernel, iterations=1)
    mean = fgmask.mean()
    if mean > MOTION_START_THRESHOLD:
        # cv2.imwrite("motion.jpg", fgmask)
        waitUntilMotionCompletes()
        frame = video_capture_thread.get_frame()
        frame = perspective_transform(frame, pts1)
        fgmask = move_fgbg.apply(frame, learningRate=0.0)
        if fgmask.mean() >= 10.0:
            ret, fgmask = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY)
        # print("Move mean " + str(fgmask.mean()))
        if fgmask.mean() >= MAX_MOVE_MEAN:
            fgmask = np.zeros(fgmask.shape, dtype=np.uint8)
        motion_fgbg.apply(frame)
        move_fgbg.apply(frame, learningRate=1.0)
        last_frame = stabilize_background_subtractors()
        previous_frame = previous_frame_queue[0]

        if (game.is_light_change(last_frame) == False) and game.register_move(fgmask, previous_frame, last_frame):
            pass
            # cv2.imwrite(game.executed_moves[-1] + " frame.jpg", last_frame)
            # cv2.imwrite(game.executed_moves[-1] + " mask.jpg", fgmask)
            # cv2.imwrite(game.executed_moves[-1] + " background.jpg", previous_frame)
        else:
            pass
            # import uuid
            # id = str(uuid.uuid1())
            # cv2.imwrite(id+"frame_fail.jpg", last_frame)
            # cv2.imwrite(id+"mask_fail.jpg", fgmask)
            # cv2.imwrite(id+"background_fail.jpg", previous_frame)
        previous_frame_queue = deque(maxlen=10)
        previous_frame_queue.append(last_frame)
    else:
        move_fgbg.apply(frame)
        previous_frame_queue.append(frame)
cv2.destroyAllWindows()
time.sleep(2)


================================================
FILE: requirements.txt
================================================
opencv-python
python-chess
pyautogui
mss
numpy
pyttsx3
scikit-image
pygrabber
berserk

================================================
FILE: speech.py
================================================
from threading import Thread
from queue import Queue
import platform
import os
import subprocess


class Speech_thread(Thread):

    def __init__(self, *args, **kwargs):
        super(Speech_thread, self).__init__(*args, **kwargs)
        self.queue = Queue()
        self.index = None

    def run(self):
        if platform.system() == "Darwin":
            result = subprocess.run(['say', '-v', '?'], stdout=subprocess.PIPE)
            output = result.stdout.decode('utf-8')
            voices = []
            for line in output.splitlines():
                if line:
                    voices.append(line.split()[0])
            name = voices[self.index]
            while True:
                text = self.queue.get()
                os.system(f'say -v {name} "{text}"')
        else:
            import pyttsx3
            while True:
                engine = pyttsx3.init()
                voices = engine.getProperty('voices')
                voice = voices[self.index]
                engine.setProperty('voice', voice.id)
                text = self.queue.get()
                engine.say(text)
                engine.runAndWait()

    def put_text(self, text):
        self.queue.put(text)


================================================
FILE: videocapture.py
================================================
from threading import Thread
from queue import Queue


class Video_capture_thread(Thread):

    def __init__(self, *args, **kwargs):
        super(Video_capture_thread, self).__init__(*args, **kwargs)
        self.queue = Queue()
        self.capture = None

    def run(self):
        while True:
            ret, frame = self.capture.read()
            if ret == False:
                continue
            self.queue.put(frame)

    def get_frame(self):
        return self.queue.get()


================================================
FILE: yolo_corner.onnx
================================================
[File too large to display: 10.1 MB]
Download .txt
gitextract_antnu9xm/

├── LICENSE
├── README.md
├── board_basics.py
├── board_calibration.py
├── board_calibration_machine_learning.py
├── chessboard_detection.py
├── classifier.py
├── cnn_color.onnx
├── cnn_piece.onnx
├── commentator.py
├── diagnostic.py
├── game.py
├── gui.py
├── helper.py
├── internet_game.py
├── languages.py
├── lichess_commentator.py
├── lichess_game.py
├── main.py
├── requirements.txt
├── speech.py
├── videocapture.py
└── yolo_corner.onnx
Download .txt
SYMBOL INDEX (137 symbols across 17 files)

FILE: board_basics.py
  class Board_basics (line 9) | class Board_basics:
    method __init__ (line 10) | def __init__(self, side_view_compensation, rotation_count):
    method initialize_ssim (line 22) | def initialize_ssim(self, frame):
    method load_ssim (line 76) | def load_ssim(self):
    method update_ssim (line 90) | def update_ssim(self, previous_frame, next_frame, move, is_capture, co...
    method get_square_image (line 111) | def get_square_image(self, row, column,
    method convert_row_column_to_square_name (line 121) | def convert_row_column_to_square_name(self, row, column):
    method square_region (line 136) | def square_region(self, row, column):
    method is_light (line 148) | def is_light(self, square_name):
    method get_potential_moves (line 160) | def get_potential_moves(self, fgmask, previous_frame, next_frame, ches...

FILE: board_calibration.py
  function mark_corners (line 53) | def mark_corners(frame, augmented_corners, rotation_count):

FILE: board_calibration_machine_learning.py
  function detect_board (line 7) | def detect_board(original_image, corner_model, piece_model, color_model):

FILE: chessboard_detection.py
  class Board_position (line 10) | class Board_position:
    method __init__ (line 11) | def __init__(self, minX, minY, maxX, maxY):
  function find_chessboard (line 18) | def find_chessboard():
  function auto_find_chessboard (line 46) | def auto_find_chessboard():
  function is_white_on_bottom (line 59) | def is_white_on_bottom(current_chessboard_image):
  function get_square_image (line 68) | def get_square_image(row, column, board_img):
  function prepare (line 79) | def prepare(lines, kernel_close, kernel_open):
  function prepare_vertical (line 86) | def prepare_vertical(lines):
  function prepare_horizontal (line 92) | def prepare_horizontal(lines):
  function find_chessboard_from_image (line 98) | def find_chessboard_from_image(img):

FILE: classifier.py
  class Classifier (line 7) | class Classifier:
    method __init__ (line 8) | def __init__(self, game_state):
    method classify (line 39) | def classify(self, img):
    method unit_gradients (line 88) | def unit_gradients(self, gray):
    method get_square_image (line 97) | def get_square_image(self, row, column,

FILE: commentator.py
  class Commentator_thread (line 10) | class Commentator_thread(Thread):
    method __init__ (line 12) | def __init__(self, *args, **kwargs):
    method run (line 21) | def run(self):
  class Game_state (line 34) | class Game_state:
    method __init__ (line 36) | def __init__(self):
    method get_chessboard (line 48) | def get_chessboard(self):
    method get_square_image (line 58) | def get_square_image(self, row, column,
    method can_image_correspond_to_chessboard (line 69) | def can_image_correspond_to_chessboard(self, move, result):
    method find_premove (line 100) | def find_premove(self, result):
    method get_valid_move (line 120) | def get_valid_move(self, potential_starts, potential_arrivals, current...
    method has_square_image_changed (line 190) | def has_square_image_changed(self, old_square,
    method convert_row_column_to_square_name (line 198) | def convert_row_column_to_square_name(self, row, column):
    method convert_square_name_to_row_column (line 208) | def convert_square_name_to_row_column(self, square_name):
    method get_potential_moves (line 216) | def get_potential_moves(self, old_image, new_image):
    method register_move_if_needed (line 229) | def register_move_if_needed(self):
    method register_move (line 253) | def register_move(self, move, board_image):

FILE: diagnostic.py
  function process (line 88) | def process(image):

FILE: game.py
  class Game (line 16) | class Game:
    method __init__ (line 17) | def __init__(self, board_basics, speech_thread, use_template, make_opp...
    method initialize_hog (line 64) | def initialize_hog(self, frame):
    method detect_state_cnn (line 95) | def detect_state_cnn(self, chessboard_image):
    method check_state_cnn (line 118) | def check_state_cnn(self, result):
    method get_valid_2_move_cnn (line 135) | def get_valid_2_move_cnn(self, frame):
    method get_valid_move_cnn (line 164) | def get_valid_move_cnn(self, frame):
    method load_hog (line 189) | def load_hog(self):
    method detect_state_hog (line 199) | def detect_state_hog(self, chessboard_image):
    method get_valid_move_hog (line 220) | def get_valid_move_hog(self, fgmask, frame):
    method get_move_to_register (line 266) | def get_move_to_register(self):
    method is_light_change (line 275) | def is_light_change(self, frame):
    method check_state_hog (line 291) | def check_state_hog(self, result):
    method check_state_for_move (line 305) | def check_state_for_move(self, result):
    method check_state_for_light (line 319) | def check_state_for_light(self, result, result_hog):
    method get_valid_move_canny (line 335) | def get_valid_move_canny(self, fgmask, frame):
    method register_move (line 383) | def register_move(self, fgmask, previous_frame, next_frame):
    method learn (line 440) | def learn(self, frame):
    method get_valid_move (line 475) | def get_valid_move(self, potential_squares, potential_moves):

FILE: gui.py
  function lichess (line 15) | def lichess():
  function on_closing (line 25) | def on_closing():
  function log_process (line 33) | def log_process(process, finish_message):
  function stop_process (line 56) | def stop_process(ignore=None):
  function diagnostic (line 62) | def diagnostic(ignore=None):
  function board_calibration (line 96) | def board_calibration(ignore=None):
  function start_game (line 138) | def start_game(ignore=None):
  function save_promotion (line 316) | def save_promotion(*args):
  function save_settings (line 377) | def save_settings():
  function load_settings (line 383) | def load_settings():

FILE: helper.py
  function euclidean_distance (line 6) | def euclidean_distance(first, second):
  function perspective_transform (line 10) | def perspective_transform(image, pts1):
  function rotateMatrix (line 18) | def rotateMatrix(matrix):
  function auto_canny (line 29) | def auto_canny(image):
  function edge_detection (line 39) | def edge_detection(frame):
  function get_square_image (line 54) | def get_square_image(row, column,
  function contains_piece (line 66) | def contains_piece(square, view):
  function detect_state (line 88) | def detect_state(frame, view, roi_mask):
  function predict (line 100) | def predict(image, model):

FILE: internet_game.py
  class Internet_game (line 6) | class Internet_game:
    method __init__ (line 7) | def __init__(self, use_template, start_delay, drag_drop):
    method move (line 16) | def move(self, move):
    method get_square_center (line 37) | def get_square_center(self, square_name):
    method convert_square_name_to_row_column (line 44) | def convert_square_name_to_row_column(self, square_name, is_white_on_b...
    method convert_row_column_to_square_name (line 52) | def convert_row_column_to_square_name(self, row, column, is_white_on_b...

FILE: languages.py
  class English (line 4) | class English:
    method __init__ (line 5) | def __init__(self):
    method name (line 9) | def name(self, piece_type):
    method comment (line 23) | def comment(self, board, move):
  class German (line 56) | class German:
    method __init__ (line 57) | def __init__(self):
    method name (line 61) | def name(self, piece_type):
    method comment (line 75) | def comment(self, board, move):
  class Russian (line 108) | class Russian:
    method __init__ (line 109) | def __init__(self):
    method name (line 113) | def name(self, piece_type):
    method comment (line 127) | def comment(self, board, move):
  class Turkish (line 160) | class Turkish:
    method __init__ (line 161) | def __init__(self):
    method capture_suffix (line 165) | def capture_suffix(self, to_square):
    method from_suffix (line 175) | def from_suffix(self, from_square):
    method to_suffix (line 183) | def to_suffix(self, to_square):
    method comment (line 191) | def comment(self, board, move):
  class Italian (line 248) | class Italian:
    method __init__ (line 249) | def __init__(self):
    method name (line 253) | def name(self, piece_type):
    method prefix_name (line 267) | def prefix_name(self, piece_type):
    method comment (line 281) | def comment(self, board, move):
  class French (line 318) | class French:
    method __init__ (line 319) | def __init__(self):
    method name (line 323) | def name(self, piece_type):
    method comment (line 337) | def comment(self, board, move):

FILE: lichess_commentator.py
  class Lichess_commentator (line 5) | class Lichess_commentator(Thread):
    method __init__ (line 7) | def __init__(self, *args, **kwargs):
    method run (line 16) | def run(self):
  class Game_state (line 24) | class Game_state:
    method __init__ (line 26) | def __init__(self):
    method register_move_if_needed (line 34) | def register_move_if_needed(self, stream):
    method register_move (line 56) | def register_move(self, move):
    method unregister_move (line 64) | def unregister_move(self):
    method from_position (line 73) | def from_position(self, fen):

FILE: lichess_game.py
  class Lichess_game (line 8) | class Lichess_game:
    method __init__ (line 9) | def __init__(self, token):
    method move (line 33) | def move(self, move):

FILE: main.py
  function waitUntilMotionCompletes (line 141) | def waitUntilMotionCompletes():
  function stabilize_background_subtractors (line 155) | def stabilize_background_subtractors():

FILE: speech.py
  class Speech_thread (line 8) | class Speech_thread(Thread):
    method __init__ (line 10) | def __init__(self, *args, **kwargs):
    method run (line 15) | def run(self):
    method put_text (line 38) | def put_text(self, text):

FILE: videocapture.py
  class Video_capture_thread (line 5) | class Video_capture_thread(Thread):
    method __init__ (line 7) | def __init__(self, *args, **kwargs):
    method run (line 12) | def run(self):
    method get_frame (line 19) | def get_frame(self):
Condensed preview — 23 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (182K chars).
[
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 6844,
    "preview": "# Play online chess with a real chess board\nProgram that enables you to play online chess using real chess boards.  Usin"
  },
  {
    "path": "board_basics.py",
    "chars": 11723,
    "preview": "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"
  },
  {
    "path": "board_calibration.py",
    "chars": 10857,
    "preview": "import cv2\r\nimport platform\r\nfrom math import inf\r\nimport pickle\r\n\r\nfrom board_calibration_machine_learning import detec"
  },
  {
    "path": "board_calibration_machine_learning.py",
    "chars": 6083,
    "preview": "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_"
  },
  {
    "path": "chessboard_detection.py",
    "chars": 5777,
    "preview": "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 Boa"
  },
  {
    "path": "classifier.py",
    "chars": 4944,
    "preview": "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-Ori"
  },
  {
    "path": "commentator.py",
    "chars": 11911,
    "preview": "from threading import Thread\r\nimport chess\r\nimport mss\r\nimport numpy as np\r\nimport cv2\r\nimport time\r\nfrom classifier imp"
  },
  {
    "path": "diagnostic.py",
    "chars": 4296,
    "preview": "import cv2\r\nimport numpy as np\r\nimport pickle\r\n\r\nfrom board_calibration_machine_learning import detect_board\r\nfrom helpe"
  },
  {
    "path": "game.py",
    "chars": 24401,
    "preview": "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 de"
  },
  {
    "path": "gui.py",
    "chars": 16331,
    "preview": "import tkinter as tk\r\nfrom tkinter.simpledialog import askstring\r\nfrom tkinter import messagebox\r\nimport subprocess\r\nimp"
  },
  {
    "path": "helper.py",
    "chars": 3703,
    "preview": "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((firs"
  },
  {
    "path": "internet_game.py",
    "chars": 2497,
    "preview": "import chessboard_detection\r\nimport pyautogui\r\nimport time\r\n\r\n\r\nclass Internet_game:\r\n    def __init__(self, use_templat"
  },
  {
    "path": "languages.py",
    "chars": 11911,
    "preview": "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"
  },
  {
    "path": "lichess_commentator.py",
    "chars": 3065,
    "preview": "from threading import Thread\r\nimport chess\r\n\r\n\r\nclass Lichess_commentator(Thread):\r\n\r\n    def __init__(self, *args, **kw"
  },
  {
    "path": "lichess_game.py",
    "chars": 1680,
    "preview": "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, toke"
  },
  {
    "path": "main.py",
    "chars": 9152,
    "preview": "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\n"
  },
  {
    "path": "requirements.txt",
    "chars": 93,
    "preview": "opencv-python\r\npython-chess\r\npyautogui\r\nmss\r\nnumpy\r\npyttsx3\r\nscikit-image\r\npygrabber\r\nberserk"
  },
  {
    "path": "speech.py",
    "chars": 1243,
    "preview": "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_t"
  },
  {
    "path": "videocapture.py",
    "chars": 509,
    "preview": "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,"
  }
]

// ... and 3 more files (download for full content)

About this extraction

This page contains the full source code of the karayaman/Play-online-chess-with-real-chess-board GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 23 files (10.3 MB), approximately 39.0k tokens, and a symbol index with 137 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!