├── .flake8
├── .gitignore
├── .gitmodules
├── .pre-commit-config.yaml
├── LICENSE
├── MANIFEST.in
├── Pipfile
├── Pipfile.lock
├── README.rst
├── annotator
├── __init__.py
└── __main__.py
├── setup.py
└── tests
└── test_functions.py
/.flake8:
--------------------------------------------------------------------------------
1 | # vim: ft=toml:
2 |
3 | [flake8]
4 | ignore = E123,E133,W503
5 |
6 | # EOF
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pgn
2 | *.egg-info/
3 | build/
4 | dist/
5 | *.pyc
6 | annotator.log
7 | .cache
8 | .envrc
9 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "eco"]
2 | path = annotator/eco
3 | url = git@github.com:niklasf/eco.git
4 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | repos:
3 | - repo: https://github.com/pre-commit/pre-commit-hooks
4 | rev: v2.0.0 # Use the ref you want to point at
5 | hooks:
6 | # Makes sure files end in a newline and only a newline.
7 | # See also: mixed-line-ending
8 | - id: end-of-file-fixer
9 |
10 | # Trims trailing whitespace.
11 | - id: trailing-whitespace
12 | args: [--markdown-linebreak-ext=md]
13 |
14 | # Prevent giant files from being committed.
15 | # Specify what is "too large" with args: ['--maxkb=123'] (default=500kB)
16 | - id: check-added-large-files
17 |
18 | # Checks that non-binary executables have a proper shebang.
19 | - id: check-executables-have-shebangs
20 |
21 | # Checks for symlinks which do not point to anything.
22 | - id: check-symlinks
23 |
24 | # Attempts to load all json files to verify syntax.
25 | - id: check-json
26 |
27 | # git {{{
28 | # Check for files that contain merge conflict strings.
29 | - id: check-merge-conflict
30 | # git }}}
31 |
32 | # Secrets {{{
33 | # Check for the existence of private keys.
34 | - id: detect-private-key
35 |
36 | # Checks for the existence of AWS secrets that you have set up with the
37 | # AWS CLI. The following arguments are available:
38 | # --credentials-file - additional AWS CLI style configuration file in a
39 | # non-standard location to fetch configured credentials from. Can be
40 | # repeated multiple times.
41 | - id: detect-aws-credentials
42 | args: [--allow-missing-credentials]
43 | # Secrets }}}
44 |
45 | # Python {{{
46 | # Remove # -*- coding: utf-8 -*- to the top of python files.
47 | - id: fix-encoding-pragma
48 | args: [--remove]
49 |
50 | # Sorts entries in requirements.txt and removes incorrect entry for
51 | # `pkg-resources==0.0.0`
52 | - id: requirements-txt-fixer
53 |
54 | # Assert that files in tests/ end in `_test.py`.
55 | # - id: name-tests-test
56 |
57 | # Check for debugger imports and py37+ `breakpoint()` calls in python
58 | # source.
59 | - id: debug-statements
60 |
61 | # Checks for a common error of placing code before the docstring.
62 | - id: check-docstring-first
63 |
64 | # - `check-builtin-literals` - Require literal syntax when initializing
65 | # empty or zero Python builtin types.
66 | # - Allows calling constructors with positional arguments (e.g.,
67 | # `list('abc')`).
68 | # - Allows calling constructors from the `builtins` (`__builtin__`)
69 | # namespace (`builtins.list()`).
70 | # - Ignore this requirement for specific builtin types with
71 | # `--ignore=type1,type2,…`.
72 | # - Forbid `dict` keyword syntax with `--no-allow-dict-kwargs`.
73 |
74 | # Run flake8 on your python files.
75 | - repo: https://gitlab.com/pycqa/flake8
76 | rev: 3.7.3
77 | hooks:
78 | - id: flake8
79 |
80 | # Python }}}
81 |
82 | # shellcheck {{{
83 | - repo: git://github.com/detailyang/pre-commit-shell
84 | rev: 1.0.4
85 | hooks:
86 | - id: shell-lint
87 | # shellcheck }}}
88 |
89 |
90 | # vim: ft=yaml foldmethod=marker
91 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include annotator/eco/eco.json
2 |
--------------------------------------------------------------------------------
/Pipfile:
--------------------------------------------------------------------------------
1 | [[source]]
2 | name = "pypi"
3 | url = "https://pypi.org/simple"
4 | verify_ssl = true
5 |
6 | [dev-packages]
7 | pytest = "~=5.0.1"
8 | pytest-cov = "~=2.7.1"
9 | pytest-pudb = "~=0.7.0"
10 |
11 | [packages]
12 | python-chess = "==0.27.3"
13 |
14 | [requires]
15 | python_version = "3.7"
16 |
--------------------------------------------------------------------------------
/Pipfile.lock:
--------------------------------------------------------------------------------
1 | {
2 | "_meta": {
3 | "hash": {
4 | "sha256": "f8462b76fef9fb4f282ca38340f456935b29cad1a53ad4e373be6339cfc7a298"
5 | },
6 | "pipfile-spec": 6,
7 | "requires": {
8 | "python_version": "3.7"
9 | },
10 | "sources": [
11 | {
12 | "name": "pypi",
13 | "url": "https://pypi.org/simple",
14 | "verify_ssl": true
15 | }
16 | ]
17 | },
18 | "default": {
19 | "python-chess": {
20 | "hashes": [
21 | "sha256:7053ad0870ec889cb558298278887cd8b977ca5e752f452f5f0f1de67f7d18cf",
22 | "sha256:8b5745ae1cd250247ba2a5a2cefc3b3a1015e8f04909aca5ac1686f6102c1e24"
23 | ],
24 | "index": "pypi",
25 | "version": "==0.27.3"
26 | }
27 | },
28 | "develop": {
29 | "atomicwrites": {
30 | "hashes": [
31 | "sha256:03472c30eb2c5d1ba9227e4c2ca66ab8287fbfbbda3888aa93dc2e28fc6811b4",
32 | "sha256:75a9445bac02d8d058d5e1fe689654ba5a6556a1dfd8ce6ec55a0ed79866cfa6"
33 | ],
34 | "version": "==1.3.0"
35 | },
36 | "attrs": {
37 | "hashes": [
38 | "sha256:69c0dbf2ed392de1cb5ec704444b08a5ef81680a61cb899dc08127123af36a79",
39 | "sha256:f0b870f674851ecbfbbbd364d6b5cbdff9dcedbc7f3f5e18a6891057f21fe399"
40 | ],
41 | "version": "==19.1.0"
42 | },
43 | "coverage": {
44 | "hashes": [
45 | "sha256:08907593569fe59baca0bf152c43f3863201efb6113ecb38ce7e97ce339805a6",
46 | "sha256:0be0f1ed45fc0c185cfd4ecc19a1d6532d72f86a2bac9de7e24541febad72650",
47 | "sha256:141f08ed3c4b1847015e2cd62ec06d35e67a3ac185c26f7635f4406b90afa9c5",
48 | "sha256:19e4df788a0581238e9390c85a7a09af39c7b539b29f25c89209e6c3e371270d",
49 | "sha256:23cc09ed395b03424d1ae30dcc292615c1372bfba7141eb85e11e50efaa6b351",
50 | "sha256:245388cda02af78276b479f299bbf3783ef0a6a6273037d7c60dc73b8d8d7755",
51 | "sha256:331cb5115673a20fb131dadd22f5bcaf7677ef758741312bee4937d71a14b2ef",
52 | "sha256:386e2e4090f0bc5df274e720105c342263423e77ee8826002dcffe0c9533dbca",
53 | "sha256:3a794ce50daee01c74a494919d5ebdc23d58873747fa0e288318728533a3e1ca",
54 | "sha256:60851187677b24c6085248f0a0b9b98d49cba7ecc7ec60ba6b9d2e5574ac1ee9",
55 | "sha256:63a9a5fc43b58735f65ed63d2cf43508f462dc49857da70b8980ad78d41d52fc",
56 | "sha256:6b62544bb68106e3f00b21c8930e83e584fdca005d4fffd29bb39fb3ffa03cb5",
57 | "sha256:6ba744056423ef8d450cf627289166da65903885272055fb4b5e113137cfa14f",
58 | "sha256:7494b0b0274c5072bddbfd5b4a6c6f18fbbe1ab1d22a41e99cd2d00c8f96ecfe",
59 | "sha256:826f32b9547c8091679ff292a82aca9c7b9650f9fda3e2ca6bf2ac905b7ce888",
60 | "sha256:93715dffbcd0678057f947f496484e906bf9509f5c1c38fc9ba3922893cda5f5",
61 | "sha256:9a334d6c83dfeadae576b4d633a71620d40d1c379129d587faa42ee3e2a85cce",
62 | "sha256:af7ed8a8aa6957aac47b4268631fa1df984643f07ef00acd374e456364b373f5",
63 | "sha256:bf0a7aed7f5521c7ca67febd57db473af4762b9622254291fbcbb8cd0ba5e33e",
64 | "sha256:bf1ef9eb901113a9805287e090452c05547578eaab1b62e4ad456fcc049a9b7e",
65 | "sha256:c0afd27bc0e307a1ffc04ca5ec010a290e49e3afbe841c5cafc5c5a80ecd81c9",
66 | "sha256:dd579709a87092c6dbee09d1b7cfa81831040705ffa12a1b248935274aee0437",
67 | "sha256:df6712284b2e44a065097846488f66840445eb987eb81b3cc6e4149e7b6982e1",
68 | "sha256:e07d9f1a23e9e93ab5c62902833bf3e4b1f65502927379148b6622686223125c",
69 | "sha256:e2ede7c1d45e65e209d6093b762e98e8318ddeff95317d07a27a2140b80cfd24",
70 | "sha256:e4ef9c164eb55123c62411f5936b5c2e521b12356037b6e1c2617cef45523d47",
71 | "sha256:eca2b7343524e7ba246cab8ff00cab47a2d6d54ada3b02772e908a45675722e2",
72 | "sha256:eee64c616adeff7db37cc37da4180a3a5b6177f5c46b187894e633f088fb5b28",
73 | "sha256:ef824cad1f980d27f26166f86856efe11eff9912c4fed97d3804820d43fa550c",
74 | "sha256:efc89291bd5a08855829a3c522df16d856455297cf35ae827a37edac45f466a7",
75 | "sha256:fa964bae817babece5aa2e8c1af841bebb6d0b9add8e637548809d040443fee0",
76 | "sha256:ff37757e068ae606659c28c3bd0d923f9d29a85de79bf25b2b34b148473b5025"
77 | ],
78 | "version": "==4.5.4"
79 | },
80 | "importlib-metadata": {
81 | "hashes": [
82 | "sha256:23d3d873e008a513952355379d93cbcab874c58f4f034ff657c7a87422fa64e8",
83 | "sha256:80d2de76188eabfbfcf27e6a37342c2827801e59c4cc14b0371c56fed43820e3"
84 | ],
85 | "version": "==0.19"
86 | },
87 | "more-itertools": {
88 | "hashes": [
89 | "sha256:409cd48d4db7052af495b09dec721011634af3753ae1ef92d2b32f73a745f832",
90 | "sha256:92b8c4b06dac4f0611c0729b2f2ede52b2e1bac1ab48f089c7ddc12e26bb60c4"
91 | ],
92 | "version": "==7.2.0"
93 | },
94 | "packaging": {
95 | "hashes": [
96 | "sha256:a7ac867b97fdc07ee80a8058fe4435ccd274ecc3b0ed61d852d7d53055528cf9",
97 | "sha256:c491ca87294da7cc01902edbe30a5bc6c4c28172b5138ab4e4aa1b9d7bfaeafe"
98 | ],
99 | "version": "==19.1"
100 | },
101 | "pluggy": {
102 | "hashes": [
103 | "sha256:0825a152ac059776623854c1543d65a4ad408eb3d33ee114dff91e57ec6ae6fc",
104 | "sha256:b9817417e95936bf75d85d3f8767f7df6cdde751fc40aed3bb3074cbcb77757c"
105 | ],
106 | "version": "==0.12.0"
107 | },
108 | "pudb": {
109 | "hashes": [
110 | "sha256:ac30cfc64580958ab7265decb4cabb9141f08781ff072e9a336d5a7942ce35a6"
111 | ],
112 | "version": "==2019.1"
113 | },
114 | "py": {
115 | "hashes": [
116 | "sha256:64f65755aee5b381cea27766a3a147c3f15b9b6b9ac88676de66ba2ae36793fa",
117 | "sha256:dc639b046a6e2cff5bbe40194ad65936d6ba360b52b3c3fe1d08a82dd50b5e53"
118 | ],
119 | "version": "==1.8.0"
120 | },
121 | "pygments": {
122 | "hashes": [
123 | "sha256:71e430bc85c88a430f000ac1d9b331d2407f681d6f6aec95e8bcfbc3df5b0127",
124 | "sha256:881c4c157e45f30af185c1ffe8d549d48ac9127433f2c380c24b84572ad66297"
125 | ],
126 | "version": "==2.4.2"
127 | },
128 | "pyparsing": {
129 | "hashes": [
130 | "sha256:6f98a7b9397e206d78cc01df10131398f1c8b8510a2f4d97d9abd82e1aacdd80",
131 | "sha256:d9338df12903bbf5d65a0e4e87c2161968b10d2e489652bb47001d82a9b028b4"
132 | ],
133 | "version": "==2.4.2"
134 | },
135 | "pytest": {
136 | "hashes": [
137 | "sha256:6ef6d06de77ce2961156013e9dff62f1b2688aa04d0dc244299fe7d67e09370d",
138 | "sha256:a736fed91c12681a7b34617c8fcefe39ea04599ca72c608751c31d89579a3f77"
139 | ],
140 | "index": "pypi",
141 | "version": "==5.0.1"
142 | },
143 | "pytest-cov": {
144 | "hashes": [
145 | "sha256:2b097cde81a302e1047331b48cadacf23577e431b61e9c6f49a1170bbe3d3da6",
146 | "sha256:e00ea4fdde970725482f1f35630d12f074e121a23801aabf2ae154ec6bdd343a"
147 | ],
148 | "index": "pypi",
149 | "version": "==2.7.1"
150 | },
151 | "pytest-pudb": {
152 | "hashes": [
153 | "sha256:0ea87316d39c82163d340c28a168e08a163b8d3f484e60a53c9fd5eefe432c63",
154 | "sha256:21e96fc16f313a7bd75e1df1b151de8a721144318b0ae8350208d6554222005a"
155 | ],
156 | "index": "pypi",
157 | "version": "==0.7.0"
158 | },
159 | "six": {
160 | "hashes": [
161 | "sha256:3350809f0555b11f552448330d0b52d5f24c91a322ea4a15ef22629740f3761c",
162 | "sha256:d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73"
163 | ],
164 | "version": "==1.12.0"
165 | },
166 | "urwid": {
167 | "hashes": [
168 | "sha256:644d3e3900867161a2fc9287a9762753d66bd194754679adb26aede559bcccbc"
169 | ],
170 | "version": "==2.0.1"
171 | },
172 | "wcwidth": {
173 | "hashes": [
174 | "sha256:3df37372226d6e63e1b1e1eda15c594bca98a22d33a23832a90998faa96bc65e",
175 | "sha256:f4ebe71925af7b40a864553f761ed559b43544f8f71746c2d756c7fe788ade7c"
176 | ],
177 | "version": "==0.1.7"
178 | },
179 | "zipp": {
180 | "hashes": [
181 | "sha256:4970c3758f4e89a7857a973b1e2a5d75bcdc47794442f2e2dd4fe8e0466e809a",
182 | "sha256:8a5712cfd3bb4248015eb3b0b3c54a5f6ee3f2425963ef2a0125b8bc40aafaec"
183 | ],
184 | "version": "==0.5.2"
185 | }
186 | }
187 | }
188 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | python-chess-annotator
2 | ======================
3 | |MAINTAINED| |LANGUAGE| |VERSION|
4 |
5 | .. |MAINTAINED| image:: https://img.shields.io/maintenance/no/2019?logoColor=informational
6 | .. |LANGUAGE| image:: https://img.shields.io/pypi/pyversions/chess-annotator
7 | .. |VERSION| image:: https://img.shields.io/pypi/v/chess-annotator
8 | :target: https://pypi.org/project/chess-annotator
9 |
10 | Takes a PGN file as an argument and annotates the games in that file
11 | using an engine.
12 |
13 | Computes average centipawn loss (ACPL) for each side and stores it in
14 | the header.
15 |
16 | The result will be printed on standard output (the file on disk will be
17 | unchanged).
18 |
19 | Installation
20 | ------------
21 |
22 | ::
23 |
24 | pip3 install chess-annotator
25 |
26 | Dependencies
27 | ------------
28 |
29 | You will need a `UCI `_
30 | chess engine for analysis.
31 | `stockfish `_ is the default.
32 |
33 | Any of the `variants supported by python-chess `_ should work.
34 | You will need a UCI engine that supports the variant you are trying to analyze.
35 | `Daniel Dugovic's stockfish fork `_
36 | supports most of the popular variants.
37 |
38 | ============
39 | Development
40 | ============
41 |
42 | If you clone this repository, you will have to update the eco submodule, since
43 | git clone does not do this by default:
44 |
45 | ::
46 |
47 | git clone --recurse-submodules git@github.com:rpdelaney/python-chess-annotator.git
48 |
49 |
50 | To install development dependencies, you will need `pipenv `_
51 | and `pre-commit `_.
52 |
53 | ::
54 |
55 | pipenv sync --dev
56 | pre-commit install --install-hooks
57 |
58 | Usage
59 | -----
60 |
61 | ::
62 |
63 | $ python3 -m annotator -h
64 | usage: annotator [-h] --file FILE.pgn [--engine ENGINE] [--gametime MINUTES]
65 | [--threads THREADS] [--verbose]
66 |
67 | takes chess games in a PGN file and prints annotations to standard output
68 |
69 | optional arguments:
70 | -h, --help show this help message and exit
71 | --file FILE.pgn, -f FILE.pgn
72 | input PGN file
73 | --engine ENGINE, -e ENGINE
74 | analysis engine (default: stockfish)
75 | --gametime MINUTES, -g MINUTES
76 | how long to spend on each game (default: 1)
77 | --threads THREADS, -t THREADS
78 | threads for use by the engine (default: 1)
79 | --verbose, -v increase verbosity
80 |
81 | $ python3 -m annotator -f caruana-kasparov.pgn -g 15
82 | [Event "Ultimate Blitz Challenge"]
83 | [Site "St. Louis, MO USA"]
84 | [Date "2016.04.29"]
85 | [Round "18.1"]
86 | [White "Fabiano Caruana"]
87 | [Black "Garry Kasparov"]
88 | [Result "0-1"]
89 | [EventDate "2016.04.28"]
90 | [ECO "A05"]
91 | [WhiteElo "2795"]
92 | [BlackElo "2812"]
93 | [PlyCount "74"]
94 | [Opening "King's Indian Attack: Symmetrical Defense"]
95 | [WhiteACPL "252"]
96 | [BlackACPL "141"]
97 | [Annotator "Stockfish 8 64 POPCNT"]
98 |
99 | { Stockfish 8 64 POPCNT } 1. Nf3 Nf6 2. g3 g6 { A05 King's Indian Attack:
100 | Symmetrical Defense } 3. Bg2 Bg7 4. O-O O-O 5. c4 d6 6. b3 e5 7. Bb2 c5 8. e3
101 | Nc6 9. Nc3 Bf5 10. d4 e4 11. Ne1 Re8 12. Nc2 h5 13. Qd2 h4 14. Ba3 $6 { -1.13 }
102 | ( 14. h3 g5 15. g4 Bg6 16. Rad1 Qe7 17. Qe2 a6 18. Ba3 a5 { 0.19/25 } ) 14...
103 | b6 $6 { -0.04 } ( 14... Nh7 15. Nd5 Ng5 16. Bb2 Rc8 17. Rac1 Ne7 18. Nf4 h3 19.
104 | Bh1 { -1.11/24 } ) 15. Rfd1 $6 { -1.15 } ( 15. h3 d5 16. g4 Be6 17. cxd5 Nxd5
105 | 18. Nxe4 f5 19. gxf5 gxf5 { 0.00/26 } ) 15... Bg4 16. Rdc1 Qd7 17. b4 Qf5 18.
106 | Bb2 Rad8 19. Nb5 Bf3 20. d5 Ne5 $6 { -1.66 } ( 20... Nxb4 21. Ne1 Bxg2 22.
107 | Nxg2 Nd3 23. Nxh4 Qh3 24. Bxf6 Bxf6 25. f4 { -3.14/25 } ) 21. Bxe5 Rxe5 22.
108 | Ne1 hxg3 23. fxg3 Bh6 24. Rab1 Kg7 $6 { -1.08 } ( 24... Qh5 25. Rb3 Rf5 26.
109 | bxc5 dxc5 27. Rc2 Ng4 28. h3 Bxg2 29. Kxg2 { -2.48/24 } ) 25. Rb3 Qh5 26. h3
110 | $6 { -3.08 } ( 26. bxc5 bxc5 27. Nxa7 Rh8 28. h4 Qg4 29. Nc6 Rh5 30. Qf2
111 | Bd1 { -2.00/23 } ) 26... Nh7 $2 { -1.37 } ( 26... Rg5 27. Qf2 { -2.89/24 })
112 | 27. g4 Bxg4 28. hxg4 Qxg4 29. Qd1 $4 { -5.69 } ( 29. Qb2 Ng5 30. Nxd6 Qg3
113 | 31. Nf5+ gxf5 32. Kf1 Nf3 33. Qf2 Nh2+ { -2.30/24 } ) 29... Qg3 30. Qe2 Ng5
114 | 31. Kh1 Rh8 32. Nxd6 Kg8 33. bxc5 Bf8+ 34. Kg1 Nh3+ 35. Kf1 Bxd6
115 | 36. cxd6 Rf5+ 37. Nf3 Rxf3+ 0-1
116 |
117 | Legal
118 | -----
119 |
120 | This program is free software: you can redistribute it and/or modify it
121 | under the terms of the GNU General Public License as published by the
122 | Free Software Foundation, either version 3 of the License, or (at your
123 | option) any later version.
124 |
125 | You should have received a copy of the GNU General Public License along
126 | with this program. If not, see http://www.gnu.org/licenses/.
127 |
--------------------------------------------------------------------------------
/annotator/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rpdelaney-archive/python-chess-annotator/f2e76c615add8dacf6e80ef96bdf1da16ea1d91f/annotator/__init__.py
--------------------------------------------------------------------------------
/annotator/__main__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3 -W ignore::DeprecationWarning
2 |
3 | __author__ = "Ryan Delaney"
4 | __email__ = "ryan.delaney@gmail.com"
5 | __copyright__ = """© Copyright 2016-2018 Ryan Delaney. All rights reserved.
6 | This work is distributed WITHOUT ANY WARRANTY whatsoever; without even the
7 | implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8 | See the README file for additional terms and conditions on your use of this
9 | software.
10 | """
11 |
12 | import os
13 | import argparse
14 | import json
15 | import logging
16 | import math
17 | import chess
18 | import chess.pgn
19 | import chess.uci
20 | import chess.variant
21 |
22 |
23 | # Constants
24 | ERROR_THRESHOLD = {
25 | 'BLUNDER': -300,
26 | 'MISTAKE': -150,
27 | 'DUBIOUS': -75,
28 | }
29 | NEEDS_ANNOTATION_THRESHOLD = 7.5
30 | MAX_SCORE = 10000
31 | MAX_CPL = 2000
32 | SHORT_PV_LEN = 10
33 |
34 | # Initialize Logging Module
35 | logger = logging.getLogger(__name__)
36 | if not logger.handlers:
37 | ch = logging.StreamHandler()
38 | logger.addHandler(ch)
39 | # Uncomment this line to get EXTREMELY verbose UCI communication logging:
40 | # logging.basicConfig(level=logging.DEBUG)
41 |
42 |
43 | def parse_args():
44 | """
45 | Define an argument parser and return the parsed arguments
46 | """
47 | parser = argparse.ArgumentParser(
48 | prog='annotator',
49 | description='takes chess games in a PGN file and prints '
50 | 'annotations to standard output')
51 | parser.add_argument("--file", "-f",
52 | help="input PGN file",
53 | required=True,
54 | metavar="FILE.pgn")
55 | parser.add_argument("--engine", "-e",
56 | help="analysis engine (default: %(default)s)",
57 | default="stockfish")
58 | parser.add_argument("--gametime", "-g",
59 | help="how long to spend on each game \
60 | (default: %(default)s)",
61 | default="1",
62 | type=float,
63 | metavar="MINUTES")
64 | parser.add_argument("--threads", "-t",
65 | help="threads for use by the engine \
66 | (default: %(default)s)",
67 | type=int,
68 | default=1)
69 | parser.add_argument("--verbose", "-v", help="increase verbosity",
70 | action="count")
71 |
72 | return parser.parse_args()
73 |
74 |
75 | def setup_logging(args):
76 | """
77 | Sets logging module verbosity according to runtime arguments
78 | """
79 | if args.verbose:
80 | if args.verbose >= 3:
81 | # EVERYTHING TO LOG FILE
82 | logger.setLevel(logging.DEBUG)
83 | hldr = logging.FileHandler('annotator.log')
84 | logger.addHandler(hldr)
85 | elif args.verbose == 2:
86 | # DEBUG TO STDERR
87 | logger.setLevel(logging.DEBUG)
88 | elif args.verbose == 1:
89 | # INFO TO STDERR
90 | logger.setLevel(logging.INFO)
91 |
92 |
93 | def eval_numeric(info_handler):
94 | """
95 | Returns a numeric evaluation of the position, even if depth-to-mate was
96 | found. This facilitates comparing numerical evaluations with depth-to-mate
97 | evaluations
98 | """
99 | dtm = info_handler.info["score"][1].mate
100 | cp = info_handler.info["score"][1].cp
101 |
102 | if dtm is not None:
103 | # We have depth-to-mate (dtm), so translate it into a numerical
104 | # evaluation. This number needs to be just big enough to guarantee that
105 | # it is always greater than a non-dtm evaluation.
106 |
107 | if dtm >= 1:
108 | return MAX_SCORE - dtm
109 | else:
110 | return -(MAX_SCORE + dtm)
111 |
112 | elif cp is not None:
113 | # We don't have depth-to-mate, so return the numerical evaluation (in
114 | # centipawns)
115 | return cp
116 |
117 | # If we haven't returned yet, then the info_handler had garbage in it
118 | raise RuntimeError("Evaluation found in the info_handler was "
119 | "unintelligible")
120 |
121 |
122 | def eval_human(white_to_move, info_handler):
123 | """
124 | Returns a human-readable evaluation of the position:
125 | If depth-to-mate was found, return plain-text mate announcement
126 | (e.g. "Mate in 4")
127 | If depth-to-mate was not found, return an absolute numeric evaluation
128 | """
129 | dtm = info_handler.info["score"][1].mate
130 | cp = info_handler.info["score"][1].cp
131 |
132 | if dtm is not None:
133 | return "Mate in {}".format(abs(dtm))
134 | elif cp is not None:
135 | # We don't have depth-to-mate, so return the numerical evaluation (in
136 | # pawns)
137 | return '{:.2f}'.format(eval_absolute(cp / 100, white_to_move))
138 |
139 | # If we haven't returned yet, then the info_handler had garbage in it
140 | raise RuntimeError("Evaluation found in the info_handler was "
141 | "unintelligible")
142 |
143 |
144 | def eval_absolute(number, white_to_move):
145 | """
146 | Accepts a relative evaluation (from the point of view of the player to
147 | move) and returns an absolute evaluation (from the point of view of white)
148 | """
149 |
150 | return number if white_to_move else -number
151 |
152 |
153 | def winning_chances(centipawns):
154 | """
155 | Takes an evaluation in centipawns and returns an integer value estimating
156 | the chance the player to move will win the game
157 |
158 | winning chances = 50 + 50 * (2 / (1 + e^(-0.004 * centipawns)) - 1)
159 | """
160 | return 50 + 50 * (2 / (1 + math.exp(-0.004 * centipawns)) - 1)
161 |
162 |
163 | def needs_annotation(judgment):
164 | """
165 | Returns a boolean indicating whether a node with the given evaluations
166 | should have an annotation added
167 | """
168 | best = winning_chances(int(judgment["besteval"]))
169 | played = winning_chances(int(judgment["playedeval"]))
170 | delta = best - played
171 |
172 | return delta > NEEDS_ANNOTATION_THRESHOLD
173 |
174 |
175 | def judge_move(board, played_move, engine, info_handler, searchtime_s):
176 | """
177 | Evaluate the strength of a given move by comparing it to engine's best
178 | move and evaluation at a given depth, in a given board context
179 |
180 | Returns a judgment
181 |
182 | A judgment is a dictionary containing the following elements:
183 | "bestmove": The best move in the position, according to the
184 | engine
185 | "besteval": A numeric evaluation of the position after the best
186 | move is played
187 | "bestcomment": A plain-text comment appropriate for annotating the
188 | best move
189 | "pv": The engine's primary variation including the best
190 | move
191 | "playedeval": A numeric evaluation of the played move
192 | "playedcomment": A plain-text comment appropriate for annotating the
193 | played move
194 | "depth": Search depth in plies
195 | "nodes": Number nodes searched
196 | """
197 |
198 | # Calculate the search time in milliseconds
199 | searchtime_ms = searchtime_s * 1000
200 |
201 | judgment = {}
202 |
203 | # First, get the engine bestmove and evaluation
204 | engine.position(board)
205 | engine.go(movetime=searchtime_ms / 2)
206 |
207 | judgment["bestmove"] = info_handler.info["pv"][1][0]
208 | judgment["besteval"] = eval_numeric(info_handler)
209 | judgment["pv"] = info_handler.info["pv"][1]
210 | judgment["depth"] = info_handler.info["depth"]
211 | judgment["nodes"] = info_handler.info["nodes"]
212 |
213 | # Annotate the best move
214 | judgment["bestcomment"] = eval_human(board.turn, info_handler)
215 |
216 | # If the played move matches the engine bestmove, we're done
217 | if played_move == judgment["bestmove"]:
218 | judgment["playedeval"] = judgment["besteval"]
219 | else:
220 | # get the engine evaluation of the played move
221 | board.push(played_move)
222 | engine.position(board)
223 | engine.go(movetime=searchtime_ms / 2)
224 |
225 | # Store the numeric evaluation.
226 | # We invert the sign since we're now evaluating from the opponent's
227 | # perspective
228 | judgment["playedeval"] = -eval_numeric(info_handler)
229 |
230 | # Take the played move off the stack (reset the board)
231 | board.pop()
232 |
233 | # Annotate the played move
234 | judgment["playedcomment"] = eval_human(not board.turn, info_handler)
235 |
236 | return judgment
237 |
238 |
239 | def get_nags(judgment):
240 | """
241 | Returns a Numeric Annotation Glyph (NAG) according to how much worse the
242 | played move was vs the best move
243 | """
244 |
245 | delta = judgment["playedeval"] - judgment["besteval"]
246 |
247 | if delta < ERROR_THRESHOLD["BLUNDER"]:
248 | return [chess.pgn.NAG_BLUNDER]
249 | elif delta < ERROR_THRESHOLD["MISTAKE"]:
250 | return [chess.pgn.NAG_MISTAKE]
251 | elif delta < ERROR_THRESHOLD["DUBIOUS"]:
252 | return [chess.pgn.NAG_DUBIOUS_MOVE]
253 | else:
254 | return []
255 |
256 |
257 | def var_end_comment(board, judgment):
258 | """
259 | Return a human-readable annotation explaining the board state (if the game
260 | is over) or a numerical evaluation (if it is not)
261 | """
262 | score = judgment["bestcomment"]
263 | depth = judgment["depth"]
264 |
265 | if board.is_stalemate():
266 | return "Stalemate"
267 | elif board.is_insufficient_material():
268 | return "Insufficient material to mate"
269 | elif board.can_claim_fifty_moves():
270 | return "Fifty move rule"
271 | elif board.can_claim_threefold_repetition():
272 | return "Three-fold repetition"
273 | elif board.is_checkmate():
274 | # checkmate speaks for itself
275 | return ""
276 | return "{}/{}".format(str(score), str(depth))
277 |
278 |
279 | def truncate_pv(board, pv):
280 | """
281 | If the pv ends the game, return the full pv
282 | Otherwise, return the pv truncated to 10 half-moves
283 | """
284 |
285 | for move in pv:
286 | if not board.is_legal(move):
287 | raise AssertionError
288 | board.push(move)
289 |
290 | if board.is_game_over(claim_draw=True):
291 | return pv
292 | else:
293 | return pv[:SHORT_PV_LEN]
294 |
295 |
296 | def add_annotation(node, judgment):
297 | """
298 | Add evaluations and the engine's primary variation as annotations to a node
299 | """
300 | prev_node = node.parent
301 |
302 | # Add the engine evaluation
303 | if judgment["bestmove"] != node.move:
304 | node.comment = judgment["playedcomment"]
305 |
306 | # Get the engine primary variation
307 | variation = truncate_pv(prev_node.board(), judgment["pv"])
308 |
309 | # Add the engine's primary variation as an annotation
310 | prev_node.add_line(moves=variation)
311 |
312 | # Add a comment to the end of the variation explaining the game state
313 | var_end_node = prev_node.variation(judgment["pv"][0]).end()
314 | var_end_node.comment = var_end_comment(var_end_node.board(), judgment)
315 |
316 | # Add a Numeric Annotation Glyph (NAG) according to how weak the played
317 | # move was
318 | node.nags = get_nags(judgment)
319 |
320 |
321 | def classify_fen(fen, ecodb):
322 | """
323 | Searches a JSON file with Encyclopedia of Chess Openings (ECO) data to
324 | check if the given FEN matches an existing opening record
325 |
326 | Returns a classification
327 |
328 | A classfication is a dictionary containing the following elements:
329 | "code": The ECO code of the matched opening
330 | "desc": The long description of the matched opening
331 | "path": The main variation of the opening
332 | """
333 | classification = {}
334 | classification["code"] = ""
335 | classification["desc"] = ""
336 | classification["path"] = ""
337 |
338 | for opening in ecodb:
339 | if opening['f'] == fen:
340 | classification["code"] = opening['c']
341 | classification["desc"] = opening['n']
342 | classification["path"] = opening['m']
343 |
344 | return classification
345 |
346 |
347 | def eco_fen(board):
348 | """
349 | Takes a board position and returns a FEN string formatted for matching with
350 | eco.json
351 | """
352 | board_fen = board.board_fen()
353 | castling_fen = board.castling_xfen()
354 |
355 | to_move = 'w' if board.turn else 'b'
356 |
357 | return "{} {} {}".format(board_fen, to_move, castling_fen)
358 |
359 |
360 | def debug_print(node, judgment):
361 | """
362 | Prints some debugging info about a position that was just analyzed
363 | """
364 |
365 | logger.debug(node.board())
366 | logger.debug(node.board().fen())
367 | logger.debug("Played move: %s", format(node.parent.board().san(node.move)))
368 | logger.debug("Best move: %s",
369 | format(node.parent.board().san(judgment["bestmove"])))
370 | logger.debug("Best eval: %s", format(judgment["besteval"]))
371 | logger.debug("Best comment: %s", format(judgment["bestcomment"]))
372 | logger.debug("PV: %s",
373 | format(node.parent.board().variation_san(judgment["pv"])))
374 | logger.debug("Played eval: %s", format(judgment["playedeval"]))
375 | logger.debug("Played comment: %s", format(judgment["playedcomment"]))
376 | logger.debug("Delta: %s",
377 | format(judgment["besteval"] - judgment["playedeval"]))
378 | logger.debug("Depth: %s", format(judgment["depth"]))
379 | logger.debug("Nodes: %s", format(judgment["nodes"]))
380 | logger.debug("Needs annotation: %s", format(needs_annotation(judgment)))
381 | logger.debug("")
382 |
383 |
384 | def cpl(string):
385 | """
386 | Centipawn Loss
387 | Takes a string and returns an integer representing centipawn loss of the
388 | move We put a ceiling on this value so that big blunders don't skew the
389 | acpl too much
390 | """
391 |
392 | cpl = int(string)
393 |
394 | return min(cpl, MAX_CPL)
395 |
396 |
397 | def acpl(cpl_list):
398 | """
399 | Average Centipawn Loss
400 | Takes a list of integers and returns an average of the list contents
401 | """
402 | try:
403 | return sum(cpl_list) / len(cpl_list)
404 | except ZeroDivisionError:
405 | return 0
406 |
407 |
408 | def clean_game(game):
409 | """
410 | Takes a game and strips all comments and variations, returning the
411 | "cleaned" game
412 | """
413 | node = game.end()
414 |
415 | while True:
416 | prev_node = node.parent
417 |
418 | node.comment = None
419 | node.nags = []
420 | for variation in reversed(node.variations):
421 | if not variation.is_main_variation():
422 | node.remove_variation(variation)
423 |
424 | if node == game.root():
425 | break
426 |
427 | node = prev_node
428 |
429 | return node.root()
430 |
431 |
432 | def game_length(game):
433 | """
434 | Takes a game and returns an integer corresponding to the number of
435 | half-moves in the game
436 | """
437 | ply_count = 0
438 | node = game.end()
439 |
440 | while not node == game.root():
441 | node = node.parent
442 | ply_count += 1
443 |
444 | return ply_count
445 |
446 |
447 | def classify_opening(game):
448 | """
449 | Takes a game and adds an ECO code classification for the opening
450 | Returns the classified game and root_node, which is the node where the
451 | classification was made
452 | """
453 | ecopath = os.path.join(os.path.dirname(__file__), 'eco/eco.json')
454 | with open(ecopath, 'r') as ecofile:
455 | ecodata = json.load(ecofile)
456 |
457 | ply_count = 0
458 |
459 | root_node = game.root()
460 | node = game.end()
461 |
462 | # Opening classification for variant games is not implemented (yet?)
463 | is_960 = root_node.board().chess960
464 | if is_960:
465 | variant = "chess960"
466 | else:
467 | variant = type(node.board()).uci_variant
468 |
469 | if variant != "chess":
470 | logger.info("Skipping opening classification in variant "
471 | "game: {}".format(variant))
472 | return node.root(), root_node, game_length(game)
473 |
474 | logger.info("Classifying the opening for non-variant {} "
475 | "game...".format(variant))
476 |
477 | while not node == game.root():
478 | prev_node = node.parent
479 |
480 | fen = eco_fen(node.board())
481 | classification = classify_fen(fen, ecodata)
482 |
483 | if classification["code"] != "":
484 | # Add some comments classifying the opening
485 | node.root().headers["ECO"] = classification["code"]
486 | node.root().headers["Opening"] = classification["desc"]
487 | node.comment = "{} {}".format(classification["code"],
488 | classification["desc"])
489 | # Remember this position so we don't analyze the moves
490 | # preceding it later
491 | root_node = node
492 | # Break (don't classify previous positions)
493 | break
494 |
495 | ply_count += 1
496 | node = prev_node
497 |
498 | return node.root(), root_node, ply_count
499 |
500 |
501 | def add_acpl(game, root_node):
502 | """
503 | Takes a game and a root node, and adds PGN headers with the computed ACPL
504 | (average centipawn loss) for each player. Returns a game with the added
505 | headers.
506 | """
507 | white_cpl = []
508 | black_cpl = []
509 |
510 | node = game.end()
511 | while not node == root_node:
512 | prev_node = node.parent
513 |
514 | judgment = node.comment
515 | delta = judgment["besteval"] - judgment["playedeval"]
516 |
517 | if node.board().turn:
518 | black_cpl.append(cpl(delta))
519 | else:
520 | white_cpl.append(cpl(delta))
521 |
522 | node = prev_node
523 |
524 | node.root().headers["WhiteACPL"] = str(round(acpl(white_cpl)))
525 | node.root().headers["BlackACPL"] = str(round(acpl(black_cpl)))
526 |
527 | return node.root()
528 |
529 |
530 | def get_total_budget(arg_gametime):
531 | return float(arg_gametime) * 60
532 |
533 |
534 | def get_pass1_budget(total_budget):
535 | return total_budget / 10
536 |
537 |
538 | def get_pass2_budget(total_budget, pass1_budget):
539 | return total_budget - pass1_budget
540 |
541 |
542 | def get_time_per_move(pass_budget, ply_count):
543 | return float(pass_budget) / float(ply_count)
544 |
545 |
546 | def analyze_game(game, arg_gametime, enginepath, threads):
547 | """
548 | Take a PGN game and return a GameNode with engine analysis added
549 | - Attempt to classify the opening with ECO and identify the root node
550 | * The root node is the position immediately after the ECO
551 | classification
552 | * This allows us to skip analysis of moves that have an ECO
553 | classification
554 | - Analyze the game, adding annotations where appropriate
555 | - Return the root node with annotations
556 | """
557 |
558 | # First, check the game for PGN parsing errors
559 | # This is done so that we don't waste CPU time on nonsense games
560 | checkgame(game)
561 |
562 | ###########################################################################
563 | # Initialize the engine
564 | ###########################################################################
565 | try:
566 | engine = chess.uci.popen_engine(enginepath)
567 | except FileNotFoundError:
568 | errormsg = "Engine '{}' was not found. Aborting...".format(enginepath)
569 | logger.critical(errormsg)
570 | raise
571 | except PermissionError:
572 | errormsg = "Engine '{}' could not be executed. Aborting...".format(
573 | enginepath)
574 | logger.critical(errormsg)
575 | raise
576 |
577 | engine.uci()
578 | info_handler = chess.uci.InfoHandler()
579 | engine.info_handlers.append(info_handler)
580 | if game.board().uci_variant != "chess" or game.root().board().chess960:
581 | # This is a variant game, so confirm that the engine we're using
582 | # supports the variant.
583 | if game.root().board().chess960:
584 | try:
585 | engine.options["UCI_Chess960"]
586 | except KeyError:
587 | message = "UCI_Chess960 is not supported by the engine " \
588 | "and this is a chess960 game."
589 | logger.critical(message)
590 | raise RuntimeError(message)
591 |
592 | if game.board().uci_variant != "chess":
593 | try:
594 | engine_variants = engine.options["UCI_Variant"].var
595 | if not game.board().uci_variant in engine_variants:
596 | raise AssertionError
597 | except KeyError:
598 | message = "UCI_Variant option is not supported by the " \
599 | "engine and this is a variant game."
600 | logger.critical(message)
601 | raise RuntimeError(message)
602 | except AssertionError:
603 | message = "Variant {} is not supported by the engine.".format(
604 | game.board().uci_variant)
605 | logger.critical(message)
606 | raise RuntimeError(message)
607 |
608 | # Now that engine support for the variant is confirmed, set engine UCI
609 | # options as appropriate for the variant
610 | engine.setoption({
611 | "UCI_Variant": game.board().uci_variant,
612 | "UCI_Chess960": game.board().chess960,
613 | "Threads": threads
614 | })
615 | else:
616 | engine.setoption({
617 | "Threads": threads
618 | })
619 |
620 | # Start keeping track of the root node
621 | # This will change if we successfully classify the opening
622 | root_node = game.end()
623 | node = root_node
624 |
625 | ###########################################################################
626 | # Clear existing comments and variations
627 | ###########################################################################
628 | game = clean_game(game)
629 |
630 | ###########################################################################
631 | # Attempt to classify the opening and calculate the game length
632 | ###########################################################################
633 | game, root_node, ply_count = classify_opening(game)
634 |
635 | ###########################################################################
636 | # Perform game analysis
637 | ###########################################################################
638 |
639 | # Calculate how many seconds we have to accomplish this
640 | # The parameter is priced in minutes so we convert to seconds
641 | budget = get_total_budget(arg_gametime)
642 | logger.debug("Total budget is {} seconds".format(budget))
643 |
644 | # First pass:
645 | #
646 | # - Performs a shallow-depth search to the root node
647 | # - Leaves annotations showing the centipawn loss of each move
648 | #
649 | # These annotations form the basis of the second pass, which will analyze
650 | # those moves that had a high centipawn loss (mistakes)
651 |
652 | # We have a fraction of the total budget to finish the first pass
653 | pass1_budget = get_pass1_budget(budget)
654 |
655 | time_per_move = get_time_per_move(pass1_budget, ply_count)
656 |
657 | logger.debug("Pass 1 budget is %i seconds, with %f seconds per move",
658 | pass1_budget, time_per_move)
659 |
660 | # Loop through the game doing shallow analysis
661 | logger.info("Performing first pass...")
662 |
663 | # Count the number of mistakes that will have to be annotated later
664 | error_count = 0
665 |
666 | node = game.end()
667 | while not node == root_node:
668 | prev_node = node.parent
669 |
670 | # Get the engine judgment of the played move in this position
671 | judgment = judge_move(prev_node.board(), node.move, engine,
672 | info_handler, time_per_move)
673 |
674 | # Record the delta, to be referenced in the second pass
675 | node.comment = judgment
676 |
677 | # Count the number of mistakes that will have to be annotated later
678 | if needs_annotation(judgment):
679 | error_count += 1
680 |
681 | # Print some debugging info
682 | debug_print(node, judgment)
683 |
684 | node = prev_node
685 |
686 | # Calculate the average centipawn loss (ACPL) for each player
687 | game = add_acpl(game, root_node)
688 |
689 | # Second pass:
690 | #
691 | # - Iterate through the comments looking for moves with high centipawn
692 | # loss
693 | # - Leaves annotations on those moves showing what the player could have
694 | # done instead
695 | #
696 |
697 | # We use the rest of the budgeted time to perform the second pass
698 | pass2_budget = get_pass2_budget(budget, pass1_budget)
699 |
700 | try:
701 | time_per_move = pass2_budget / error_count
702 | except ZeroDivisionError:
703 | logger.debug("No errors found on first pass!")
704 | # There were no mistakes in the game, so deeply analyze all the moves
705 | time_per_move = pass2_budget / ply_count
706 | node = game.end()
707 | while not node == root_node:
708 | prev_node = node.parent
709 | # Reset the comments to a value high enough to ensure that they all
710 | # get analyzed
711 | comment = {}
712 | comment["besteval"] = "99999"
713 | comment["playedeval"] = "0"
714 | node.comment = comment
715 | node = prev_node
716 |
717 | logger.debug("Pass 2 budget is %i seconds, with %f seconds per move",
718 | pass2_budget, time_per_move)
719 |
720 | # Loop through the game doing deep analysis on the flagged moves
721 | logger.info("Performing second pass...")
722 |
723 | node = game.end()
724 | while not node == root_node:
725 | prev_node = node.parent
726 |
727 | judgment = node.comment
728 |
729 | if needs_annotation(judgment):
730 | # Get the engine judgment of the played move in this position
731 | judgment = judge_move(prev_node.board(), node.move, engine,
732 | info_handler, time_per_move)
733 |
734 | # Verify that the engine still dislikes the played move
735 | if needs_annotation(judgment):
736 | add_annotation(node, judgment)
737 | else:
738 | node.comment = None
739 |
740 | # Print some debugging info
741 | debug_print(node, judgment)
742 | else:
743 | node.comment = None
744 |
745 | node = prev_node
746 |
747 | ###########################################################################
748 |
749 | annotator = engine.name if engine.name else ""
750 | node.root().comment = annotator
751 | node.root().headers["Annotator"] = annotator
752 |
753 | return node.root()
754 |
755 |
756 | def checkgame(game):
757 | """
758 | Check for PGN parsing errors and abort if any were found
759 | This prevents us from burning up CPU time on nonsense positions
760 | """
761 | if game.errors:
762 | errormsg = "There were errors parsing the PGN game:"
763 | logger.critical(errormsg)
764 | for error in game.errors:
765 | logger.critical(error)
766 | logger.critical("Aborting...")
767 | raise RuntimeError(errormsg)
768 |
769 | # Try to verify that the PGN file was readable
770 | if game.end().parent is None:
771 | errormsg = "Could not render the board. Is the file legal PGN?" \
772 | "Aborting..."
773 | logger.critical(errormsg)
774 | raise RuntimeError(errormsg)
775 |
776 |
777 | def main():
778 | """
779 | Main function
780 |
781 | - Load games from the PGN file
782 | - Annotate each game, and print the game with the annotations
783 | """
784 | args = parse_args()
785 | setup_logging(args)
786 | engine = args.engine.split()
787 |
788 | pgnfile = args.file
789 | try:
790 | with open(pgnfile) as pgn:
791 | for game in iter(lambda: chess.pgn.read_game(pgn), None):
792 | try:
793 | analyzed_game = analyze_game(game, args.gametime,
794 | engine, args.threads)
795 | except KeyboardInterrupt:
796 | logger.critical("\nReceived KeyboardInterrupt.")
797 | raise
798 | except Exception as e:
799 | logger.critical("\nAn unhandled exception occurred: {}"
800 | .format(type(e)))
801 | raise e
802 | else:
803 | print(analyzed_game, '\n')
804 | except PermissionError:
805 | errormsg = "Input file not readable. Aborting..."
806 | logger.critical(errormsg)
807 | raise
808 |
809 |
810 | if __name__ == "__main__":
811 | main()
812 |
813 | # vim: ft=python expandtab smarttab shiftwidth=4 softtabstop=4
814 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | """A setuptools based setup module.
2 | See:
3 | https://packaging.python.org/en/latest/distributing.html
4 | https://github.com/pypa/sampleproject
5 | """
6 |
7 | # Always prefer setuptools over distutils
8 | from setuptools import setup, find_packages
9 | # To use a consistent encoding
10 | import codecs
11 | import os
12 |
13 | here = os.path.abspath(os.path.dirname(__file__))
14 |
15 | # Get the long description from the README file
16 | with codecs.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
17 | long_description = f.read()
18 |
19 | setup(
20 | name='chess-annotator',
21 |
22 | description='adds comments and analysis to chess games',
23 | long_description=long_description,
24 |
25 | version='1.1.4',
26 |
27 | # The project's main homepage.
28 | url='https://github.com/rpdelaney/python-chess-annotator',
29 |
30 | # Author details
31 | author='Ryan Delaney',
32 | author_email='ryan.delaney@gmail.com',
33 |
34 | # Choose your license
35 | license='GPL3',
36 |
37 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
38 | classifiers=[
39 | 'Development Status :: 5 - Production/Stable',
40 |
41 | # Software topics
42 | 'Topic :: Games/Entertainment :: Board Games',
43 |
44 | # Indicate who your project is intended for
45 | 'Intended Audience :: End Users/Desktop',
46 |
47 | # What kind of environment the application is intended for
48 | 'Environment :: Console',
49 |
50 | # Supported operating systems
51 | 'Operating System :: OS Independent',
52 |
53 | # Supported languages
54 | 'Natural Language :: English',
55 |
56 | # Pick your license as you wish (should match "license" above)
57 | 'License :: OSI Approved :: '
58 | 'GNU General Public License v3 or later (GPLv3+)',
59 |
60 | # Specify the Python versions you support here. In particular, ensure
61 | # that you indicate whether you support Python 2, Python 3 or both.
62 | 'Programming Language :: Python :: 3',
63 | 'Programming Language :: Python :: 3.3',
64 | 'Programming Language :: Python :: 3.4',
65 | 'Programming Language :: Python :: 3.5',
66 | 'Programming Language :: Python :: 3.6',
67 | 'Programming Language :: Python :: 3.7',
68 | ],
69 |
70 | # What does your project relate to?
71 | keywords='chess',
72 |
73 | # You can just specify the packages manually here if your project is
74 | # simple. Or you can use find_packages().
75 | packages=find_packages(exclude=['contrib', 'docs', 'tests']),
76 |
77 | # Alternatively, if you want to distribute just a my_module.py, uncomment
78 | # this:
79 | # py_modules=["my_module"],
80 |
81 | # List run-time dependencies here. These will be installed by pip when
82 | # your project is installed. For an analysis of "install_requires" vs pip's
83 | # requirements files see:
84 | # https://packaging.python.org/en/latest/requirements.html
85 | install_requires=['python-chess==0.27.3'],
86 |
87 | # List additional groups of dependencies here (e.g. development
88 | # dependencies). You can install these using the following syntax,
89 | # for example:
90 | # $ pip install -e .[dev,test]
91 | extras_require={
92 | # 'dev': ['black'],
93 | 'test': ['pytest', 'pytest-cov'],
94 | },
95 |
96 | # If there are data files included in your packages that need to be
97 | # installed, specify them here. If using Python 2.6 or less, then these
98 | # have to be included in MANIFEST.in as well.
99 | # package_data={
100 | # 'eco': ['annotator/eco/eco.json'],
101 | # },
102 | include_package_data=True,
103 |
104 | # To provide executable scripts, use entry points in preference to the
105 | # "scripts" keyword. Entry points provide cross-platform support and allow
106 | # pip to create the appropriate form of executable for the target platform.
107 | entry_points={
108 | 'console_scripts': [
109 | 'annotator=annotator.__main__:main',
110 | ],
111 | },
112 | )
113 |
--------------------------------------------------------------------------------
/tests/test_functions.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import unittest
4 | from unittest.mock import MagicMock
5 | import random
6 | from io import StringIO
7 | import json
8 | import os
9 |
10 | import chess
11 | import chess.variant
12 | import annotator.__main__ as annotator
13 |
14 |
15 | class test_eval_absolute(unittest.TestCase):
16 |
17 | def test_white_unpadded(self):
18 | result = annotator.eval_absolute(10.01, True)
19 | self.assertEqual(result, 10.01)
20 |
21 | def test_white_padded(self):
22 | result = annotator.eval_absolute(10, True)
23 | self.assertEqual(result, 10.00)
24 |
25 | def test_black(self):
26 | result = annotator.eval_absolute(10.00, False)
27 | self.assertEqual(result, -10.00)
28 |
29 |
30 | class test_eval_numeric(unittest.TestCase):
31 |
32 | def test_raises_runtimeerror(self):
33 | score = MagicMock()
34 | score.mate = None
35 | score.cp = None
36 | info_handler = MagicMock()
37 | info_handler.info = {'score': [None, score]}
38 | self.assertRaises(RuntimeError, annotator.eval_numeric, info_handler)
39 |
40 | def test_dtm_positive(self):
41 | score = MagicMock()
42 | score.mate = 5
43 | score.cp = None
44 | info_handler = MagicMock()
45 | info_handler.info = {'score': [None, score]}
46 |
47 | result = annotator.eval_numeric(info_handler)
48 | self.assertEqual(result, 9995)
49 |
50 | def test_dtm_negative(self):
51 | score = MagicMock()
52 | score.mate = -5
53 | score.cp = None
54 | info_handler = MagicMock()
55 | info_handler.info = {'score': [None, score]}
56 |
57 | result = annotator.eval_numeric(info_handler)
58 | self.assertEqual(result, -9995)
59 |
60 | def test_cp_positive(self):
61 | score = MagicMock()
62 | score.mate = None
63 | score.cp = 5
64 | info_handler = MagicMock()
65 | info_handler.info = {'score': [None, score]}
66 |
67 | result = annotator.eval_numeric(info_handler)
68 | self.assertEqual(result, 5)
69 |
70 | def test_cp_negative(self):
71 | score = MagicMock()
72 | score.mate = None
73 | score.cp = -5
74 | info_handler = MagicMock()
75 | info_handler.info = {'score': [None, score]}
76 |
77 | result = annotator.eval_numeric(info_handler)
78 | self.assertEqual(result, -5)
79 |
80 |
81 | class test_winning_chances(unittest.TestCase):
82 |
83 | def test_zero(self):
84 | score = 0
85 | result = round(annotator.winning_chances(score))
86 | self.assertEqual(result, 50)
87 |
88 | def test_one(self):
89 | score = 100
90 | result = round(annotator.winning_chances(score))
91 | self.assertEqual(result, 60)
92 |
93 | def test_four(self):
94 | score = 400
95 | result = round(annotator.winning_chances(score))
96 | self.assertEqual(result, 83)
97 |
98 | def test_negative_one(self):
99 | score = -100
100 | result = round(annotator.winning_chances(score))
101 | self.assertEqual(result, 40)
102 |
103 | def test_negative_four(self):
104 | score = -400
105 | result = round(annotator.winning_chances(score))
106 | self.assertEqual(result, 17)
107 |
108 | def test_raises_typeerror(self):
109 | score = 'a'
110 | self.assertRaises(TypeError, annotator.winning_chances, score)
111 |
112 |
113 | class test_needs_annotation(unittest.TestCase):
114 |
115 | def test_high(self):
116 | judgment = {}
117 | judgment["besteval"] = 200
118 | judgment["playedeval"] = 100
119 | result = annotator.needs_annotation(judgment)
120 | self.assertTrue(result)
121 |
122 | def test_low(self):
123 | judgment = {}
124 | judgment["besteval"] = 5
125 | judgment["playedeval"] = 0
126 | result = annotator.needs_annotation(judgment)
127 | self.assertFalse(result)
128 |
129 | def test_negative(self):
130 | judgment = {}
131 | judgment["besteval"] = 0
132 | judgment["playedeval"] = 100
133 | result = annotator.needs_annotation(judgment)
134 | self.assertFalse(result)
135 |
136 | def test_zero(self):
137 | judgment = {}
138 | judgment["besteval"] = 0
139 | judgment["playedeval"] = 0
140 | result = annotator.needs_annotation(judgment)
141 | self.assertFalse(result)
142 |
143 | def test_low_fraction(self):
144 | judgment = {}
145 | judgment["besteval"] = 5.333333
146 | judgment["playedeval"] = 0
147 | result = annotator.needs_annotation(judgment)
148 | self.assertFalse(result)
149 |
150 | def test_high_fraction(self):
151 | judgment = {}
152 | judgment["besteval"] = 500.33333
153 | judgment["playedeval"] = 0
154 | result = annotator.needs_annotation(judgment)
155 | self.assertTrue(result)
156 |
157 | def test_small_error_big_advantage(self):
158 | judgment = {}
159 | judgment["besteval"] = 600
160 | judgment["playedeval"] = 500
161 | result = annotator.needs_annotation(judgment)
162 | self.assertFalse(result)
163 |
164 | def test_small_error_big_disadvantage(self):
165 | judgment = {}
166 | judgment["besteval"] = -500
167 | judgment["playedeval"] = -600
168 | result = annotator.needs_annotation(judgment)
169 | self.assertFalse(result)
170 |
171 | def test_big_error_huge_advantage(self):
172 | judgment = {}
173 | judgment["besteval"] = 9998
174 | judgment["playedeval"] = 1000
175 | result = annotator.needs_annotation(judgment)
176 | self.assertFalse(result)
177 |
178 | def test_big_error_huge_disadvantage(self):
179 | judgment = {}
180 | judgment["besteval"] = -1000
181 | judgment["playedeval"] = -9998
182 | result = annotator.needs_annotation(judgment)
183 | self.assertFalse(result)
184 |
185 | def test_raises_typeerror(self):
186 | self.assertRaises(TypeError, annotator.needs_annotation, 'a')
187 |
188 |
189 | class test_cpl(unittest.TestCase):
190 |
191 | def test_int(self):
192 | result = annotator.cpl(5)
193 | self.assertEqual(result, 5)
194 |
195 | def test_string(self):
196 | result = annotator.cpl('5')
197 | self.assertEqual(result, 5)
198 |
199 | def test_bigstring(self):
200 | result = annotator.cpl('1000')
201 | self.assertEqual(result, 1000)
202 |
203 | def test_negativestring(self):
204 | result = annotator.cpl('-2001')
205 | self.assertEqual(result, -2001)
206 |
207 | def test_max_cpl(self):
208 | result = annotator.cpl('5000')
209 | self.assertEqual(result, annotator.MAX_CPL)
210 |
211 |
212 | class test_acpl(unittest.TestCase):
213 |
214 | def test_list(self):
215 | testlist = [1, 2, 3, 4, 5, 6]
216 | result = annotator.acpl(testlist)
217 | self.assertEqual(result, 3.5)
218 |
219 |
220 | class test_eco_fen(unittest.TestCase):
221 |
222 | def test_board(self):
223 | board = chess.Board('Q4R2/3kr3/1q3n1p/2p1p1p1/1p1bP1P1/1B1P3P/2PBK3/8 w - - 1 0') # noqa E501
224 | result = annotator.eco_fen(board)
225 | self.assertEqual(result, 'Q4R2/3kr3/1q3n1p/2p1p1p1/1p1bP1P1/1B1P3P/2PBK3/8 w -') # noqa E501
226 |
227 |
228 | class test_get_total_budget(unittest.TestCase):
229 |
230 | def test_is_float(self):
231 | result = annotator.get_total_budget(random.random())
232 | self.assertIsInstance(result, float)
233 |
234 | def test_math(self):
235 | seed = random.random()
236 | result = annotator.get_total_budget(seed)
237 | self.assertEqual(result, seed * 60)
238 |
239 | def test_raises_valueerror(self):
240 | self.assertRaises(ValueError, annotator.get_total_budget, 'a')
241 |
242 |
243 | class test_truncate_pv(unittest.TestCase):
244 |
245 | def test_long_mating_pv(self):
246 | """ A long pv that ends the game should not be truncated """
247 |
248 | board = chess.Board('1Q3bk1/5p2/2p3p1/1p1bN2p/4n2P/8/r5PK/8 b - - 1 34') # noqa E501
249 | line = [chess.Move.from_uci('g8g7'), chess.Move.from_uci('e5f7'),
250 | chess.Move.from_uci('d5f7'), chess.Move.from_uci('b8e5'),
251 | chess.Move.from_uci('e4f6'), chess.Move.from_uci('h2h3'),
252 | chess.Move.from_uci('b5b4'), chess.Move.from_uci('g2g4'),
253 | chess.Move.from_uci('f8d6'), chess.Move.from_uci('e5d6'),
254 | chess.Move.from_uci('h5g4'), chess.Move.from_uci('h3g3'),
255 | chess.Move.from_uci('f6e4'), chess.Move.from_uci('g3f4'),
256 | chess.Move.from_uci('e4d6'), chess.Move.from_uci('f4e5'),
257 | chess.Move.from_uci('b4b3'), chess.Move.from_uci('e5d6'),
258 | chess.Move.from_uci('b3b2'), chess.Move.from_uci('h4h5'),
259 | chess.Move.from_uci('g6h5'), chess.Move.from_uci('d6d7'),
260 | chess.Move.from_uci('b2b1q'), chess.Move.from_uci('d7c7'),
261 | chess.Move.from_uci('b1b4'), chess.Move.from_uci('c7c6'),
262 | chess.Move.from_uci('a2c2'), chess.Move.from_uci('c6d7'),
263 | chess.Move.from_uci('b4b8'), chess.Move.from_uci('d7e7'),
264 | chess.Move.from_uci('b8c7')]
265 | result = annotator.truncate_pv(board, line)
266 | self.assertEqual(result, line)
267 |
268 | def test_long_non_mating_pv(self):
269 | """
270 | A long pv that does not end the game should be truncated to 10 moves
271 | """
272 |
273 | board = chess.Board('1Q3bk1/5p2/2p3p1/1p1bN2p/4n2P/8/r5PK/8 b - - 1 34') # noqa E501
274 | line = [chess.Move.from_uci('g8g7'), chess.Move.from_uci('e5f7'),
275 | chess.Move.from_uci('d5f7'), chess.Move.from_uci('b8e5'),
276 | chess.Move.from_uci('e4f6'), chess.Move.from_uci('h2h3'),
277 | chess.Move.from_uci('b5b4'), chess.Move.from_uci('g2g4'),
278 | chess.Move.from_uci('f8d6'), chess.Move.from_uci('e5d6'),
279 | chess.Move.from_uci('h5g4'), chess.Move.from_uci('h3g3'),
280 | chess.Move.from_uci('f6e4'), chess.Move.from_uci('g3f4'),
281 | chess.Move.from_uci('e4d6'), chess.Move.from_uci('f4e5'),
282 | chess.Move.from_uci('b4b3'), chess.Move.from_uci('e5d6'),
283 | chess.Move.from_uci('b3b2'), chess.Move.from_uci('h4h5'),
284 | chess.Move.from_uci('g6h5'), chess.Move.from_uci('d6d7'),
285 | chess.Move.from_uci('b2b1q'), chess.Move.from_uci('d7c7'),
286 | chess.Move.from_uci('b1b4'), chess.Move.from_uci('c7c6'),
287 | chess.Move.from_uci('a2c2'), chess.Move.from_uci('c6d7'),
288 | chess.Move.from_uci('b4b8'), chess.Move.from_uci('d7e7')]
289 | target = line[:annotator.SHORT_PV_LEN]
290 | result = annotator.truncate_pv(board, line)
291 | self.assertEqual(len(result), annotator.SHORT_PV_LEN)
292 | self.assertEqual(result, target)
293 |
294 | def test_raises_assertionerror(self):
295 | """ A line with an illegal move should raise an AssertionError """
296 |
297 | board = chess.Board('1Q3bk1/5p2/2p3p1/1p1bN2p/4n2P/8/r5PK/8 b - - 1 34') # noqa E501
298 | line = [chess.Move.from_uci('g8g7'), chess.Move.from_uci('e5f7'),
299 | chess.Move.from_uci('d5f7'), chess.Move.from_uci('b8e5'),
300 | chess.Move.from_uci('e4f6'), chess.Move.from_uci('h2h3'),
301 | chess.Move.from_uci('b5b4'), chess.Move.from_uci('g2g4'),
302 | chess.Move.from_uci('f8d6'), chess.Move.from_uci('e5d6'),
303 | chess.Move.from_uci('h5g4'), chess.Move.from_uci('h3g3'),
304 | chess.Move.from_uci('f6e4'), chess.Move.from_uci('g3f4'),
305 | chess.Move.from_uci('e4d6'), chess.Move.from_uci('f4e5'),
306 | chess.Move.from_uci('b4b3'), chess.Move.from_uci('e5d6'),
307 | chess.Move.from_uci('b3b2'), chess.Move.from_uci('h4h5'),
308 | chess.Move.from_uci('g6h5'), chess.Move.from_uci('d6c8'),
309 | chess.Move.from_uci('b2b1q'), chess.Move.from_uci('d7c7'),
310 | chess.Move.from_uci('b1b4'), chess.Move.from_uci('c7c6'),
311 | chess.Move.from_uci('a2c2'), chess.Move.from_uci('c6d7'),
312 | chess.Move.from_uci('b4b8'), chess.Move.from_uci('d7e7'),
313 | chess.Move.from_uci('b8c7')]
314 | self.assertRaises(AssertionError, annotator.truncate_pv, board, line)
315 |
316 |
317 | class test_get_nags(unittest.TestCase):
318 |
319 | def test_zero(self):
320 | judgment = {'playedeval': 0, 'besteval': 0}
321 | result = annotator.get_nags(judgment)
322 | self.assertEqual(result, [])
323 |
324 | def test_negative(self):
325 | judgment = {'playedeval': 0, 'besteval': -10}
326 | result = annotator.get_nags(judgment)
327 | self.assertEqual(result, [])
328 |
329 | def test_float(self):
330 | judgment = {'playedeval': 0.001, 'besteval': -10.05}
331 | result = annotator.get_nags(judgment)
332 | self.assertEqual(result, [])
333 |
334 | def test_blunder(self):
335 | judgment = {'playedeval': 0, 'besteval': 350}
336 | result = annotator.get_nags(judgment)
337 | self.assertEqual(result, [chess.pgn.NAG_BLUNDER])
338 |
339 | def test_mistake(self):
340 | judgment = {'playedeval': 0, 'besteval': 200}
341 | result = annotator.get_nags(judgment)
342 | self.assertEqual(result, [chess.pgn.NAG_MISTAKE])
343 |
344 | def test_dubious(self):
345 | judgment = {'playedeval': 0, 'besteval': 100}
346 | result = annotator.get_nags(judgment)
347 | self.assertEqual(result, [chess.pgn.NAG_DUBIOUS_MOVE])
348 |
349 | def test_typeerror(self):
350 | judgment = {'playedeval': 0, 'besteval': 'foo'}
351 | self.assertRaises(TypeError, annotator.get_nags, judgment)
352 |
353 |
354 | class test_var_end_comment(unittest.TestCase):
355 |
356 | def test_stalemate(self):
357 | board = chess.Board(fen='7k/8/6Q1/8/8/8/8/K7 b - - 0 1')
358 | judgment = {'bestcomment': "", 'depth': ""}
359 | result = annotator.var_end_comment(board, judgment)
360 | self.assertEqual(result, "Stalemate")
361 |
362 | def test_insufficient_material(self):
363 | board = chess.Board(fen='7k/8/8/8/8/8/N7/K7 b - - 0 1')
364 | judgment = {'bestcomment': "", 'depth': ""}
365 | result = annotator.var_end_comment(board, judgment)
366 | self.assertEqual(result, "Insufficient material to mate")
367 |
368 | def test_fifty_move_rule(self):
369 | board = chess.Board(fen='7k/8/8/8/8/1P6/N7/K7 b - - 100 150')
370 | judgment = {'bestcomment': "", 'depth': ""}
371 | result = annotator.var_end_comment(board, judgment)
372 | self.assertEqual(result, "Fifty move rule")
373 |
374 | def test_threefold_repetition(self):
375 | board = chess.Board(fen='7k/8/8/8/8/1P6/N7/K7 b - - 0 1')
376 | moves = ["Kg8", "Nc1", "Kh8", "Na2", "Kg8", "Nc1", "Kh8", "Na2", "Kg8",
377 | "Nc1", "Kh8", "Na2"]
378 | for move in moves:
379 | board.push_san(move)
380 | judgment = {'bestcomment': "", 'depth': ""}
381 | result = annotator.var_end_comment(board, judgment)
382 | self.assertEqual(result, "Three-fold repetition")
383 |
384 | def test_checkmate(self):
385 | board = chess.Board(fen='8/8/8/8/8/1K6/8/1k1R4 b - - 0 1')
386 | judgment = {'bestcomment': "", 'depth': ""}
387 | result = annotator.var_end_comment(board, judgment)
388 | self.assertEqual(result, "")
389 |
390 | def test_other(self):
391 | board = chess.Board(fen='rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') # noqa E501
392 | judgment = {'bestcomment': "foo", 'depth': "bar"}
393 | result = annotator.var_end_comment(board, judgment)
394 | self.assertEqual(result, "foo/bar")
395 |
396 |
397 | class test_add_annotation(unittest.TestCase):
398 | pass
399 |
400 |
401 | class test_classify_fen(unittest.TestCase):
402 |
403 | def test_eco_json(self):
404 | ecopath = os.path.join(
405 | os.path.dirname(__file__), '../annotator/eco/eco.json'
406 | )
407 | with open(ecopath, 'r') as ecofile:
408 | ecodata = json.load(ecofile)
409 |
410 | for row in ecodata:
411 | fen = "{} {}".format(row["f"], '- 0 1')
412 | chess.Board(fen=fen)
413 |
414 | classification = annotator.classify_fen(row["f"], ecodata)
415 |
416 | assert classification["code"] == row["c"]
417 | assert classification["desc"] == row["n"]
418 | assert classification["path"] == row["m"]
419 |
420 |
421 | class test_clean_game(unittest.TestCase):
422 |
423 | def test_commented_game(self):
424 | pgn_string = "{ Stockfish 8 64 POPCNT } 1. Nf3 { test comment } Nf6 2. g3 g6 { A05 King's Indian Attack: Symmetrical Defense } 3. Bg2 Bg7 4. O-O O-O 5. c4 d6 6. b3 e5 7. Bb2 c5 8. e3 Nc6 9. Nc3 Bf5 10. d4 e4 11. Ne1 Re8 12. Nc2 h5 13. Qd2 h4 14. Ba3 $6 { -1.13 } ( 14. h3 g5 15. g4 Bg6 16. Rad1 Qe7 17. Qe2 a6 18. Ba3 a5 { 0.19/25 } ) 14... b6 $6 { -0.04 } ( 14... Nh7 15. Nd5 Ng5 16. Bb2 Rc8 17. Rac1 Ne7 18. Nf4 h3 19. Bh1 { -1.11/24 } ) 15. Rfd1 $6 { -1.15 } ( 15. h3 d5 16. g4 Be6 17. cxd5 Nxd5 18. Nxe4 f5 19. gxf5 gxf5 { 0.00/26 } ) 15... Bg4 16. Rdc1 Qd7 17. b4 Qf5 18. Bb2 Rad8 19. Nb5 Bf3 20. d5 Ne5 $6 { -1.66 } ( 20... Nxb4 21. Ne1 Bxg2 22. Nxg2 Nd3 23. Nxh4 Qh3 24. Bxf6 Bxf6 25. f4 { -3.14/25 } ) 21. Bxe5 Rxe5 22. Ne1 hxg3 23. fxg3 Bh6 24. Rab1 Kg7 $6 { -1.08 } ( 24... Qh5 25. Rb3 Rf5 26. bxc5 dxc5 27. Rc2 Ng4 28. h3 Bxg2 29. Kxg2 { -2.48/24 } ) 25. Rb3 Qh5 26. h3 $6 { -3.08 } ( 26. bxc5 bxc5 27. Nxa7 Rh8 28. h4 Qg4 29. Nc6 Rh5 30. Qf2 Bd1 { -2.00/23 } ) 26... Nh7 $2 { -1.37 } ( 26... Rg5 27. Qf2 { -2.89/24 }) 27. g4 Bxg4 28. hxg4 Qxg4 29. Qd1 $4 { -5.69 } ( 29. Qb2 Ng5 30. Nxd6 Qg3 31. Nf5+ gxf5 32. Kf1 Nf3 33. Qf2 Nh2+ { -2.30/24 } ) 29... Qg3 30. Qe2 Ng5 31. Kh1 Rh8 32. Nxd6 Kg8 33. bxc5 Bf8+ 34. Kg1 Nh3+ 35. Kf1 Bxd6 36. cxd6 Rf5+ 37. Nf3 Rxf3+ 0-1" # noqa E501
425 | pgn = StringIO(pgn_string)
426 | game = chess.pgn.read_game(pgn)
427 | result = annotator.clean_game(game)
428 | node = result.end()
429 | while True:
430 | assert len(node.variations) <= 1
431 | assert node.comment is None
432 | assert node.nags == []
433 | if node == game.root():
434 | break
435 | node = node.parent
436 |
437 | def test_zh_game(self):
438 | pgn_string = '[Variant "Crazyhouse"]\n{ Stockfish 020118 64 POPCNT } 1. e4 e5 2. Nf3 Nc6 3. Nc3 Bc5 4. Bc4 Nf6 5. d3 O-O 6. O-O d6 7. Bg5 h6 8. Bh4 Bg4 $2 { 3.23 } ( 8... Kh8 9. Nd5 { 0.99/19 } ) 9. Nd5 Nxd5 10. Bxd8 Raxd8 11. Bxd5 B@h5 12. Bxc6 $6 { 1.01 } ( 12. N@f5 { 2.27/17 } ) 12... bxc6 $2 { 3.70 } ( 12... Bxf3 13. gxf3 { 1.66/18 } ) 13. N@g5 hxg5 14. Nxg5 N@f6 15. Qxg4 Bxg4 16. N@e7+ $4 { -4.20 } ( 16. @h7+ Kh8 17. Q@g8+ Rxg8 18. Nxf7+ Kxh7 19. N@g5+ Kg6 20. @f5+ Bxf5 21. exf5+ Kxf5 22. B@e6+ Kg6 23. B@f5+ Kh5 24. g4+ Nxg4 25. Bxg4+ Kg6 26. N@h4+ Kf6 27. Ne4+ Ke7 28. Ng6+ Ke8 29. Nfxd6+ Rxd6 30. @f7+ Kd8 31. fxg8=Q+ N@e8 32. R@c8# ) 16... Kh8 17. Nxc6 $4 { -10.83 } ( 17. Q@h4+ Q@h6 { -4.31/16 } ) 17... Q@h4 18. B@g3 Qxg5 19. Nxd8 N@e2+ 20. Kh1 Nxg3+ $4 { -5.22 } ( 20... Rxd8 { -8.46/15 } ) 21. fxg3 $4 { -14.50 } ( 21. hxg3 Rxd8 { -5.41/16 } ) 21... B@h3 22. N@e1 N@f2+ 23. Rxf2 Bxf2 24. R@f1 Bxe1 25. @e7 Bxg2+ 26. Kg1 @f2+ 27. Rxf2 Bxf2+ 28. Kxg2 B@f3+ 29. Kf1 R@g1+ 30. Kxf2 R@g2# 0-1' # noqa E501
439 | pgn = StringIO(pgn_string)
440 | game = chess.pgn.read_game(pgn)
441 | result = annotator.clean_game(game)
442 | node = result.end()
443 | while True:
444 | assert len(node.variations) <= 1
445 | assert node.comment is None
446 | assert node.nags == []
447 | if node == game.root():
448 | break
449 | node = node.parent
450 |
451 |
452 | class test_game_length(unittest.TestCase):
453 |
454 | def test_commented_game(self):
455 | pgn_string = "{ Stockfish 8 64 POPCNT } 1. Nf3 Nf6 2. g3 g6 { A05 King's Indian Attack: Symmetrical Defense } 3. Bg2 Bg7 4. O-O O-O 5. c4 d6 6. b3 e5 7. Bb2 c5 8. e3 Nc6 9. Nc3 Bf5 10. d4 e4 11. Ne1 Re8 12. Nc2 h5 13. Qd2 h4 14. Ba3 $6 { -1.13 } ( 14. h3 g5 15. g4 Bg6 16. Rad1 Qe7 17. Qe2 a6 18. Ba3 a5 { 0.19/25 } ) 14... b6 $6 { -0.04 } ( 14... Nh7 15. Nd5 Ng5 16. Bb2 Rc8 17. Rac1 Ne7 18. Nf4 h3 19. Bh1 { -1.11/24 } ) 15. Rfd1 $6 { -1.15 } ( 15. h3 d5 16. g4 Be6 17. cxd5 Nxd5 18. Nxe4 f5 19. gxf5 gxf5 { 0.00/26 } ) 15... Bg4 16. Rdc1 Qd7 17. b4 Qf5 18. Bb2 Rad8 19. Nb5 Bf3 20. d5 Ne5 $6 { -1.66 } ( 20... Nxb4 21. Ne1 Bxg2 22. Nxg2 Nd3 23. Nxh4 Qh3 24. Bxf6 Bxf6 25. f4 { -3.14/25 } ) 21. Bxe5 Rxe5 22. Ne1 hxg3 23. fxg3 Bh6 24. Rab1 Kg7 $6 { -1.08 } ( 24... Qh5 25. Rb3 Rf5 26. bxc5 dxc5 27. Rc2 Ng4 28. h3 Bxg2 29. Kxg2 { -2.48/24 } ) 25. Rb3 Qh5 26. h3 $6 { -3.08 } ( 26. bxc5 bxc5 27. Nxa7 Rh8 28. h4 Qg4 29. Nc6 Rh5 30. Qf2 Bd1 { -2.00/23 } ) 26... Nh7 $2 { -1.37 } ( 26... Rg5 27. Qf2 { -2.89/24 }) 27. g4 Bxg4 28. hxg4 Qxg4 29. Qd1 $4 { -5.69 } ( 29. Qb2 Ng5 30. Nxd6 Qg3 31. Nf5+ gxf5 32. Kf1 Nf3 33. Qf2 Nh2+ { -2.30/24 } ) 29... Qg3 30. Qe2 Ng5 31. Kh1 Rh8 32. Nxd6 Kg8 33. bxc5 Bf8+ 34. Kg1 Nh3+ 35. Kf1 Bxd6 36. cxd6 Rf5+ 37. Nf3 Rxf3+ 0-1" # noqa E501
456 | pgn = StringIO(pgn_string)
457 | game = chess.pgn.read_game(pgn)
458 | result = annotator.game_length(game)
459 | self.assertEqual(result, 74)
460 |
461 | def test_zh_game(self):
462 | pgn_string = '[Variant "Crazyhouse"]\n{ Stockfish 020118 64 POPCNT } 1. e4 e5 2. Nf3 Nc6 3. Nc3 Bc5 4. Bc4 Nf6 5. d3 O-O 6. O-O d6 7. Bg5 h6 8. Bh4 Bg4 $2 { 3.23 } ( 8... Kh8 9. Nd5 { 0.99/19 } ) 9. Nd5 Nxd5 10. Bxd8 Raxd8 11. Bxd5 B@h5 12. Bxc6 $6 { 1.01 } ( 12. N@f5 { 2.27/17 } ) 12... bxc6 $2 { 3.70 } ( 12... Bxf3 13. gxf3 { 1.66/18 } ) 13. N@g5 hxg5 14. Nxg5 N@f6 15. Qxg4 Bxg4 16. N@e7+ $4 { -4.20 } ( 16. @h7+ Kh8 17. Q@g8+ Rxg8 18. Nxf7+ Kxh7 19. N@g5+ Kg6 20. @f5+ Bxf5 21. exf5+ Kxf5 22. B@e6+ Kg6 23. B@f5+ Kh5 24. g4+ Nxg4 25. Bxg4+ Kg6 26. N@h4+ Kf6 27. Ne4+ Ke7 28. Ng6+ Ke8 29. Nfxd6+ Rxd6 30. @f7+ Kd8 31. fxg8=Q+ N@e8 32. R@c8# ) 16... Kh8 17. Nxc6 $4 { -10.83 } ( 17. Q@h4+ Q@h6 { -4.31/16 } ) 17... Q@h4 18. B@g3 Qxg5 19. Nxd8 N@e2+ 20. Kh1 Nxg3+ $4 { -5.22 } ( 20... Rxd8 { -8.46/15 } ) 21. fxg3 $4 { -14.50 } ( 21. hxg3 Rxd8 { -5.41/16 } ) 21... B@h3 22. N@e1 N@f2+ 23. Rxf2 Bxf2 24. R@f1 Bxe1 25. @e7 Bxg2+ 26. Kg1 @f2+ 27. Rxf2 Bxf2+ 28. Kxg2 B@f3+ 29. Kf1 R@g1+ 30. Kxf2 R@g2# 0-1' # noqa E501
463 | pgn = StringIO(pgn_string)
464 | game = chess.pgn.read_game(pgn)
465 | assert game.errors == []
466 | result = annotator.game_length(game)
467 | self.assertEqual(result, 60)
468 |
469 |
470 | class test_classify_opening(unittest.TestCase):
471 | pass
472 |
473 |
474 | class test_add_acpl(unittest.TestCase):
475 | pass
476 |
477 |
478 | class test_get_pass1_budget(unittest.TestCase):
479 |
480 | def test_raises_typeerror(self):
481 | self.assertRaises(TypeError, annotator.get_pass1_budget, 'a')
482 |
483 | def test_math(self):
484 | seed = random.random()
485 | result = annotator.get_pass1_budget(seed)
486 | self.assertEqual(result, seed / 10)
487 |
488 |
489 | class test_get_pass2_budget(unittest.TestCase):
490 |
491 | def test_raises_typeerror(self):
492 | self.assertRaises(TypeError, annotator.get_pass2_budget, 1, 'a')
493 |
494 | def test_math(self):
495 | seed1 = random.random()
496 | seed2 = random.random()
497 | result = annotator.get_pass2_budget(seed1, seed2)
498 | self.assertEqual(result, seed1 - seed2)
499 |
500 |
501 | class test_get_time_per_move(unittest.TestCase):
502 |
503 | def test_divzero(self):
504 | pass_budget = "1"
505 | ply_count = "0"
506 | self.assertRaises(ZeroDivisionError, annotator.get_time_per_move,
507 | pass_budget, ply_count)
508 |
509 | def test_raises_valueerror(self):
510 | pass_budget = "1"
511 | ply_count = "a"
512 | self.assertRaises(ValueError, annotator.get_time_per_move, pass_budget,
513 | ply_count)
514 |
515 | def test_returns_float(self):
516 | pass_budget = "1"
517 | ply_count = "1"
518 | result = annotator.get_time_per_move(pass_budget, ply_count)
519 | assert isinstance(result, float)
520 |
521 | def test_divides_integers(self):
522 | pass_budget = "12"
523 | ply_count = "30"
524 | result = annotator.get_time_per_move(pass_budget, ply_count)
525 | self.assertEqual(result, 0.4)
526 |
527 | def test_divides_floats(self):
528 | pass_budget = "15.25"
529 | ply_count = "20"
530 | result = annotator.get_time_per_move(pass_budget, ply_count)
531 | self.assertEqual(result, 0.7625)
532 |
533 |
534 | class test_analyze_game(unittest.TestCase):
535 | pass
536 |
537 |
538 | class test_checkgame(unittest.TestCase):
539 | pass
540 |
541 |
542 | class test_eval_human(unittest.TestCase):
543 |
544 | def test_positive_dtm(self):
545 | score = MagicMock()
546 | score.mate = 5
547 | score.cp = None
548 | info_handler = MagicMock()
549 | info_handler.info = {'score': [None, score]}
550 | self.assertEqual(annotator.eval_human(True, info_handler), "Mate in 5")
551 | self.assertEqual(annotator.eval_human(False, info_handler),
552 | "Mate in 5")
553 |
554 | def test_negative_dtm(self):
555 | score = MagicMock()
556 | score.mate = -5
557 | score.cp = None
558 | info_handler = MagicMock()
559 | info_handler.info = {'score': [None, score]}
560 | self.assertEqual(annotator.eval_human(True, info_handler), "Mate in 5")
561 | self.assertEqual(annotator.eval_human(False, info_handler),
562 | "Mate in 5")
563 |
564 | def test_non_dtm(self):
565 | score = MagicMock()
566 | score.mate = None
567 | score.cp = 100
568 | info_handler = MagicMock()
569 | info_handler.info = {'score': [None, score]}
570 | self.assertEqual(annotator.eval_human(True, info_handler), "1.00")
571 | self.assertEqual(annotator.eval_human(False, info_handler), "-1.00")
572 |
573 | def test_raises_runtimeerror(self):
574 | score = MagicMock()
575 | score.mate = None
576 | score.cp = None
577 | info_handler = MagicMock()
578 | info_handler.info = {'score': [None, score]}
579 | self.assertRaises(RuntimeError, annotator.eval_human, True,
580 | info_handler)
581 | self.assertRaises(RuntimeError, annotator.eval_human, False,
582 | info_handler)
583 |
584 |
585 | class test_judge_move(unittest.TestCase):
586 | pass
587 |
588 |
589 | # vim: ft=python expandtab smarttab shiftwidth=4 softtabstop=4
590 |
--------------------------------------------------------------------------------