├── .github
└── workflows
│ └── test.yml
├── .gitignore
├── LICENSE
├── MANIFEST.in
├── Makefile
├── README.md
├── build_and_publish.sh
├── extract_long_description.py
├── language_tool_python
├── __init__.py
├── __main__.py
├── config_file.py
├── download_lt.py
├── language_tag.py
├── match.py
├── server.py
└── utils.py
├── pyproject.toml
├── pytest.ini
└── tests
├── test_local.bash
├── test_major_functionality.py
└── test_remote.bash
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3 |
4 | name: Test with PyTest
5 |
6 | on:
7 | push:
8 | branches: [ master ]
9 | pull_request:
10 | branches: [ master ]
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-22.04
16 | strategy:
17 | matrix:
18 | python-version: ["3.9", "3.10", "3.11"]
19 |
20 | steps:
21 | - uses: actions/checkout@v2
22 |
23 | - name: Set up Python ${{ matrix.python-version }}
24 | uses: actions/setup-python@v4
25 | with:
26 | python-version: ${{ matrix.python-version }}
27 |
28 | - name: Set up JDK 21
29 | uses: actions/setup-java@v3
30 | with:
31 | distribution: 'temurin'
32 | java-version: '21'
33 |
34 | - name: Create and activate virtualenv
35 | run: |
36 | python -m venv venv
37 | source venv/bin/activate
38 | python -m pip install --upgrade pip
39 |
40 | - name: Install dependencies
41 | run: |
42 | source venv/bin/activate
43 | pip install setuptools wheel build pytest pytest-xdist
44 | python -m build --sdist --wheel
45 | pip install dist/*.whl
46 |
47 | - name: Verify installed packages
48 | run: |
49 | source venv/bin/activate
50 | pip list
51 |
52 | - name: Import language_tool_python
53 | run: |
54 | source venv/bin/activate
55 | printf "import language_tool_python\n" | python
56 |
57 | - name: Test with pytest
58 | run: |
59 | source venv/bin/activate
60 | pytest -vx --dist=loadfile -n auto
61 |
62 | - name: Run additional tests in bash scripts for Ubuntu
63 | run: |
64 | source venv/bin/activate
65 | bash tests/test_local.bash
66 | bash tests/test_remote.bash
67 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.egg-info/
2 | *.egg/
3 | *.pyc
4 | .*.swp
5 | .tox/
6 | .travis-solo/
7 | __pycache__/
8 | build/
9 | dist/
10 | language_tool_python/LanguageTool-*/
11 | language_tool_python-*/
12 | pytest-cache-files-*/
13 | .env
14 | .venv
15 | env/
16 | venv/
17 | ENV/
18 | env.bak/
19 | venv.bak/
20 |
--------------------------------------------------------------------------------
/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 run_doctest.py
2 | include tests/test_local.bash
3 | include tests/test_remote.bash
4 | prune pytest-cache-files-*/
5 | prune env/
6 | prune .env
7 | prune .venv
8 | prune env/
9 | prune venv/
10 | prune ENV/
11 | prune env.bak/
12 | prune venv.bak/
13 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | check:
2 | pycodestyle \
3 | --exclude ./language_tool_python/LanguageTool-* \
4 | --ignore=E402,W504 \
5 | ./language_tool_python \
6 | ./language_tool_python/ \
7 | $(wildcard *.py)
8 | pylint \
9 | --rcfile=/dev/null \
10 | --errors-only \
11 | --disable=import-error \
12 | --disable=no-member \
13 | --disable=no-name-in-module \
14 | --disable=raising-bad-type \
15 | ./language_tool_python \
16 | $(wildcard ./language_tool_python/*.py) \
17 | $(wildcard *.py)
18 | python extract_long_description.py | rstcheck -
19 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # `language_tool_python`: a grammar checker for Python 📝
2 |
3 | 
4 |
5 | 
6 |
7 | Current LanguageTool version: **6.7-SNAPSHOT**
8 |
9 | This is a Python wrapper for [LanguageTool](https://languagetool.org). LanguageTool is open-source grammar tool, also known as the spellchecker for OpenOffice. This library allows you to make to detect grammar errors and spelling mistakes through a Python script or through a command-line interface.
10 |
11 | ## Local and Remote Servers
12 |
13 | By default, `language_tool_python` will download a LanguageTool server `.jar` and run that in the background to detect grammar errors locally. However, LanguageTool also offers a [Public HTTP Proofreading API](https://dev.languagetool.org/public-http-api) that is supported as well. Follow the link for rate limiting details. (Running locally won't have the same restrictions.)
14 |
15 | ### Using `language_tool_python` locally
16 |
17 | Local server is the default setting. To use this, just initialize a LanguageTool object:
18 |
19 | ```python
20 | import language_tool_python
21 | tool = language_tool_python.LanguageTool('en-US') # use a local server (automatically set up), language English
22 | ```
23 |
24 | ### Using `language_tool_python` with the public LanguageTool remote server
25 |
26 | There is also a built-in class for querying LanguageTool's public servers. Initialize it like this:
27 |
28 | ```python
29 | import language_tool_python
30 | tool = language_tool_python.LanguageToolPublicAPI('es') # use the public API, language Spanish
31 | ```
32 |
33 | ### Using `language_tool_python` with the another remote server
34 |
35 | Finally, you're able to pass in your own remote server as an argument to the `LanguageTool` class:
36 |
37 | ```python
38 | import language_tool_python
39 | tool = language_tool_python.LanguageTool('ca-ES', remote_server='https://language-tool-api.mywebsite.net') # use a remote server API, language Catalan
40 | ```
41 |
42 | ### Apply a custom list of matches with `utils.correct`
43 |
44 | If you want to decide which `Match` objects to apply to your text, use `tool.check` (to generate the list of matches) in conjunction with `language_tool_python.utils.correct` (to apply the list of matches to text). Here is an example of generating, filtering, and applying a list of matches. In this case, spell-checking suggestions for uppercase words are ignored:
45 |
46 | ```python
47 | >>> s = "Department of medicine Colombia University closed on August 1 Milinda Samuelli"
48 | >>> is_bad_rule = lambda rule: rule.message == 'Possible spelling mistake found.' and len(rule.replacements) and rule.replacements[0][0].isupper()
49 | >>> import language_tool_python
50 | >>> tool = language_tool_python.LanguageTool('en-US')
51 | >>> matches = tool.check(s)
52 | >>> matches = [rule for rule in matches if not is_bad_rule(rule)]
53 | >>> language_tool_python.utils.correct(s, matches)
54 | 'Department of medicine Colombia University closed on August 1 Melinda Sam'
55 | ```
56 |
57 | ### Apply a specific suggestion of a match with `Match.select_replacement` and `utils.correct`
58 |
59 | If you want to apply a particular suggestion from a `Match`, use `Match.select_replacement` (to select a replacement with its index) in conjunction with `language_tool_python.utils.correct` (to apply selected replacements from the `Match` list to the text). Here is an example of generating, selecting replacements, and applying the list of matches. In this case, the third replacement (book) is selected.
60 |
61 | ```python
62 | >>> import language_tool_python
63 | >>> s = "There is a bok on the table."
64 | >>> tool = language_tool_python.LanguageTool('en-US')
65 | >>> matches = tool.check(s)
66 | >>> matches
67 | [Match({'ruleId': 'MORFOLOGIK_RULE_EN_US', 'message': 'Possible spelling mistake found.', 'replacements': ['BOK', 'OK', 'book', 'box'], 'offsetInContext': 11, 'context': 'There is a bok on the table.', 'offset': 11, 'errorLength': 3, 'category': 'TYPOS', 'ruleIssueType': 'misspelling', 'sentence': 'There is a bok on the table.'})]
68 | >>> matches[0].select_replacement(2)
69 | >>> patched_text = language_tool_python.utils.correct(s, matches)
70 | >>> patched_text
71 | 'There is a book on the table.'
72 | ```
73 |
74 | ### Determine whether a text is grammatically correct
75 |
76 | If you want to determine whether a text is grammatically correct, you can use the `classify_matches` function from `language_tool_python.utils`. It will return a `TextStatus` enum value indicating whether the text is correct, faulty, or garbage. Here is an example:
77 |
78 | ```python
79 | >>> import language_tool_python
80 | >>> from language_tool_python.utils import classify_matches
81 | >>> tool = language_tool_python.LanguageTool('en-US')
82 | >>> matches = tool.check('This is a cat.')
83 | >>> matches_1 = tool.check('This is a cats.')
84 | >>> matches_2 = tool.check('fabafbafzabfabfz')
85 | >>> classify_matches(matches)
86 |
87 | >>> classify_matches(matches_1)
88 |
89 | >>> classify_matches(matches_2)
90 |
91 | ```
92 |
93 | ## Example usage
94 |
95 | From the interpreter:
96 |
97 | ```python
98 | >>> import language_tool_python
99 | >>> tool = language_tool_python.LanguageTool('en-US')
100 | >>> text = 'A sentence with a error in the Hitchhiker’s Guide tot he Galaxy'
101 | >>> matches = tool.check(text)
102 | >>> len(matches)
103 | 2
104 | ...
105 | >>> tool.close() # Call `close()` to shut off the server when you're done.
106 | ```
107 |
108 | Check out some ``Match`` object attributes:
109 |
110 | ```python
111 | >>> matches[0].ruleId, matches[0].replacements # ('EN_A_VS_AN', ['an'])
112 | ('EN_A_VS_AN', ['an'])
113 | >>> matches[1].ruleId, matches[1].replacements
114 | ('TOT_HE', ['to the'])
115 | ```
116 |
117 | Print a ``Match`` object:
118 |
119 | ```python
120 | >>> print(matches[1])
121 | Line 1, column 51, Rule ID: TOT_HE[1]
122 | Message: Did you mean 'to the'?
123 | Suggestion: to the
124 | ...
125 | ```
126 |
127 | Automatically apply suggestions to the text:
128 |
129 | ```python
130 | >>> tool.correct(text)
131 | 'A sentence with an error in the Hitchhiker’s Guide to the Galaxy'
132 | ```
133 |
134 | From the command line:
135 |
136 | ```bash
137 | $ echo 'This are bad.' > example.txt
138 | $ language_tool_python example.txt
139 | example.txt:1:1: THIS_NNS[3]: Did you mean 'these'?
140 | ```
141 |
142 | ## Closing LanguageTool
143 |
144 | `language_tool_python` runs a LanguageTool Java server in the background. It will shut the server off when garbage collected, for example when a created `language_tool_python.LanguageTool` object goes out of scope. However, if garbage collection takes awhile, the process might not get deleted right away. If you're seeing lots of processes get spawned and not get deleted, you can explicitly close them:
145 |
146 |
147 | ```python
148 | import language_tool_python
149 | tool = language_tool_python.LanguageToolPublicAPI('de-DE') # starts a process
150 | # do stuff with `tool`
151 | tool.close() # explicitly shut off the LanguageTool
152 | ```
153 |
154 | You can also use a context manager (`with .. as`) to explicitly control when the server is started and stopped:
155 |
156 | ```python
157 | import language_tool_python
158 |
159 | with language_tool_python.LanguageToolPublicAPI('de-DE') as tool:
160 | # do stuff with `tool`
161 | # no need to call `close() as it will happen at the end of the with statement
162 | ```
163 |
164 | ## Client-Server Model
165 |
166 | You can run LanguageTool on one host and connect to it from another. This is useful in some distributed scenarios. Here's a simple example:
167 |
168 | #### server
169 |
170 | ```python
171 | >>> import language_tool_python
172 | >>> tool = language_tool_python.LanguageTool('en-US', host='0.0.0.0')
173 | >>> tool._url
174 | 'http://0.0.0.0:8081/v2/'
175 | ```
176 |
177 | #### client
178 | ```python
179 | >>> import language_tool_python
180 | >>> lang_tool = language_tool_python.LanguageTool('en-US', remote_server='http://0.0.0.0:8081')
181 | >>>
182 | >>>
183 | >>> lang_tool.check('helo darknes my old frend')
184 | [Match({'ruleId': 'UPPERCASE_SENTENCE_START', 'message': 'This sentence does not start with an uppercase letter.', 'replacements': ['Helo'], 'offsetInContext': 0, 'context': 'helo darknes my old frend', 'offset': 0, 'errorLength': 4, 'category': 'CASING', 'ruleIssueType': 'typographical', 'sentence': 'helo darknes my old frend'}), Match({'ruleId': 'MORFOLOGIK_RULE_EN_US', 'message': 'Possible spelling mistake found.', 'replacements': ['darkness', 'darkens', 'darkies'], 'offsetInContext': 5, 'context': 'helo darknes my old frend', 'offset': 5, 'errorLength': 7, 'category': 'TYPOS', 'ruleIssueType': 'misspelling', 'sentence': 'helo darknes my old frend'}), Match({'ruleId': 'MORFOLOGIK_RULE_EN_US', 'message': 'Possible spelling mistake found.', 'replacements': ['friend', 'trend', 'Fred', 'freed', 'Freud', 'Friend', 'fend', 'fiend', 'frond', 'rend', 'fr end'], 'offsetInContext': 20, 'context': 'helo darknes my old frend', 'offset': 20, 'errorLength': 5, 'category': 'TYPOS', 'ruleIssueType': 'misspelling', 'sentence': 'helo darknes my old frend'})]
185 | >>>
186 | ```
187 |
188 | ## Configuration
189 |
190 | LanguageTool offers lots of built-in configuration options.
191 |
192 | ### Example: Enabling caching
193 | Here's an example of using the configuration options to enable caching. Some users have reported that this helps performance a lot.
194 | ```python
195 | import language_tool_python
196 | tool = language_tool_python.LanguageTool('en-US', config={ 'cacheSize': 1000, 'pipelineCaching': True })
197 | ```
198 |
199 |
200 | ### Example: Setting maximum text length
201 |
202 | Here's an example showing how to configure LanguageTool to set a maximum length on grammar-checked text. Will throw an error (which propagates to Python as a `language_tool_python.LanguageToolError`) if text is too long.
203 | ```python
204 | import language_tool_python
205 | tool = language_tool_python.LanguageTool('en-US', config={ 'maxTextLength': 100 })
206 | ```
207 |
208 | ### Full list of configuration options
209 |
210 | Here's a full list of configuration options. See the LanguageTool [HTTPServerConfig](https://languagetool.org/development/api/org/languagetool/server/HTTPServerConfig.html) documentation for details.
211 |
212 | ```
213 | 'maxTextLength' - maximum text length, longer texts will cause an error (optional)
214 | 'maxTextHardLength' - maximum text length, applies even to users with a special secret 'token' parameter (optional)
215 | 'maxCheckTimeMillis' - maximum time in milliseconds allowed per check (optional)
216 | 'maxErrorsPerWordRate' - checking will stop with error if there are more rules matches per word (optional)
217 | 'maxSpellingSuggestions' - only this many spelling errors will have suggestions for performance reasons (optional,
218 | affects Hunspell-based languages only)
219 | 'maxCheckThreads' - maximum number of threads working in parallel (optional)
220 | 'cacheSize' - size of internal cache in number of sentences (optional, default: 0)
221 | 'cacheTTLSeconds' - how many seconds sentences are kept in cache (optional, default: 300 if 'cacheSize' is set)
222 | 'requestLimit' - maximum number of requests per requestLimitPeriodInSeconds (optional)
223 | 'requestLimitInBytes' - maximum aggregated size of requests per requestLimitPeriodInSeconds (optional)
224 | 'timeoutRequestLimit' - maximum number of timeout request (optional)
225 | 'requestLimitPeriodInSeconds' - time period to which requestLimit and timeoutRequestLimit applies (optional)
226 | 'languageModel' - a directory with '1grams', '2grams', '3grams' sub directories per language which contain a Lucene index
227 | each with ngram occurrence counts; activates the confusion rule if supported (optional)
228 | 'fasttextModel' - a model file for better language detection (optional), see
229 | https://fasttext.cc/docs/en/language-identification.html
230 | 'fasttextBinary' - compiled fasttext executable for language detection (optional), see
231 | https://fasttext.cc/docs/en/support.html
232 | 'maxWorkQueueSize' - reject request if request queue gets larger than this (optional)
233 | 'rulesFile' - a file containing rules configuration, such as .languagetool.cfg (optional)
234 | 'blockedReferrers' - a comma-separated list of HTTP referrers (and 'Origin' headers) that are blocked and will not be served (optional)
235 | 'premiumOnly' - activate only the premium rules (optional)
236 | 'disabledRuleIds' - a comma-separated list of rule ids that are turned off for this server (optional)
237 | 'pipelineCaching' - set to 'true' to enable caching of internal pipelines to improve performance
238 | 'maxPipelinePoolSize' - cache size if 'pipelineCaching' is set
239 | 'pipelineExpireTimeInSeconds' - time after which pipeline cache items expire
240 | 'pipelinePrewarming' - set to 'true' to fill pipeline cache on start (can slow down start a lot)
241 | ```
242 |
243 | ## Installation
244 |
245 | To install via pip:
246 |
247 | ```bash
248 | $ pip install --upgrade language_tool_python
249 | ```
250 |
251 | ### What rules does LanguageTool have?
252 |
253 | Searching for a specific rule to enable or disable? Curious the breadth of rules LanguageTool applies? This page contains a massive list of all 5,000+ grammatical rules that are programmed into LanguageTool: https://community.languagetool.org/rule/list?lang=en&offset=30&max=10
254 |
255 | ### Customizing Download URL or Path
256 |
257 | If LanguageTool is already installed on your system, you can defined the following environment variable:
258 | ```bash
259 | $ export LTP_JAR_DIR_PATH = /path/to/the/language/tool/jar/files
260 | ```
261 |
262 | Overwise, `language_tool_python` can download LanguageTool for you automatically.
263 |
264 | To overwrite the host part of URL that is used to download LanguageTool-{version}.zip:
265 |
266 | ```bash
267 | $ export LTP_DOWNLOAD_HOST = [alternate URL]
268 | ```
269 |
270 | This can be used to downgrade to an older version, for example, or to download from a mirror.
271 |
272 | And to choose the specific folder to download the server to:
273 |
274 | ```bash
275 | $ export LTP_PATH = /path/to/save/language/tool
276 | ```
277 |
278 | The default download path is `~/.cache/language_tool_python/`. The LanguageTool server is about 200 MB, so take that into account when choosing your download folder. (Or, if you you can't spare the disk space, use a remote URL!)
279 |
280 | ## Prerequisites
281 |
282 | - [Python 3.9+](https://www.python.org)
283 | - [LanguageTool](https://www.languagetool.org) (Java 8.0 or higher for version <= 6.5, Java 17.0 or higher for version >= 6.6)
284 |
285 | The installation process should take care of downloading LanguageTool (it may
286 | take a few minutes). Otherwise, you can manually download
287 | [LanguageTool-stable.zip](https://www.languagetool.org/download/LanguageTool-stable.zip) and unzip it
288 | into where the ``language_tool_python`` package resides.
289 |
290 | ### LanguageTool Version
291 |
292 | LanguageTool versions under 6.0 are no longer downloadable from the LanguageTool website. If you need to use an older version, you can download it from the [LanguageTool GitHub tags page](https://github.com/languagetool-org/languagetool/tags) and build it yourself.
293 |
294 | ### Acknowledgements
295 |
296 | This is a fork of https://github.com/myint/language-check/ that produces more easily parsable
297 | results from the command-line.
298 |
--------------------------------------------------------------------------------
/build_and_publish.sh:
--------------------------------------------------------------------------------
1 | rm -rf build/ dist/ *.egg-info/
2 | python -m pip install --upgrade pip setuptools wheel build
3 | python -m build
4 | twine check dist/*
5 | twine upload dist/* --verbose
--------------------------------------------------------------------------------
/extract_long_description.py:
--------------------------------------------------------------------------------
1 | import toml
2 | import os
3 |
4 | with open("pyproject.toml", "rb") as f:
5 | pyproject = toml.loads(f.read().decode('utf-8'))
6 |
7 | readme_path = pyproject["project"]["readme"]
8 |
9 | if os.path.exists(readme_path):
10 | with open(readme_path, "r", encoding="utf-8") as readme_file:
11 | print(readme_file.read())
12 | else:
13 | raise FileNotFoundError(f"{readme_path} not found.")
14 |
--------------------------------------------------------------------------------
/language_tool_python/__init__.py:
--------------------------------------------------------------------------------
1 | """LanguageTool API for Python."""
2 |
3 | from .language_tag import LanguageTag
4 | from .match import Match
5 | from .server import LanguageTool, LanguageToolPublicAPI
6 | from . import utils
--------------------------------------------------------------------------------
/language_tool_python/__main__.py:
--------------------------------------------------------------------------------
1 | """LanguageTool command line."""
2 |
3 | import argparse
4 | import locale
5 | import re
6 | import sys
7 | from importlib.metadata import version, PackageNotFoundError
8 | import toml
9 | from typing import Any, Optional, Set, Union
10 |
11 | from .server import LanguageTool
12 | from .utils import LanguageToolError
13 |
14 | try:
15 | __version__ = version("language_tool_python")
16 | except PackageNotFoundError: # If the package is not installed in the environment, read the version from pyproject.toml
17 | with open("pyproject.toml", "rb") as f:
18 | __version__ = toml.loads(f.read().decode('utf-8'))["project"]["version"]
19 |
20 |
21 | def parse_args() -> argparse.Namespace:
22 | """
23 | Parse command line arguments.
24 |
25 | :return: parsed arguments
26 | :rtype: argparse.Namespace
27 | """
28 | parser = argparse.ArgumentParser(
29 | description=__doc__.strip() if __doc__ else None,
30 | prog='language_tool_python')
31 | parser.add_argument('files', nargs='+',
32 | help='plain text file or "-" for stdin')
33 | parser.add_argument('-c', '--encoding',
34 | help='input encoding')
35 | parser.add_argument('-l', '--language', metavar='CODE',
36 | help='language code of the input or "auto"')
37 | parser.add_argument('-m', '--mother-tongue', metavar='CODE',
38 | help='language code of your first language')
39 | parser.add_argument('-d', '--disable', metavar='RULES', type=get_rules,
40 | action=RulesAction, default=set(),
41 | help='list of rule IDs to be disabled')
42 | parser.add_argument('-e', '--enable', metavar='RULES', type=get_rules,
43 | action=RulesAction, default=set(),
44 | help='list of rule IDs to be enabled')
45 | parser.add_argument('--enabled-only', action='store_true',
46 | help='disable all rules except those specified in '
47 | '--enable')
48 | parser.add_argument('-p', '--picky', action='store_true',
49 | help='If set, additional rules will be activated.')
50 | parser.add_argument(
51 | '--version', action='version',
52 | version=f'%(prog)s {__version__}',
53 | help='show version')
54 | parser.add_argument('-a', '--apply', action='store_true',
55 | help='automatically apply suggestions if available')
56 | parser.add_argument('-s', '--spell-check-off', dest='spell_check',
57 | action='store_false',
58 | help='disable spell-checking rules')
59 | parser.add_argument('--ignore-lines',
60 | help='ignore lines that match this regular expression')
61 | parser.add_argument('--remote-host',
62 | help='hostname of the remote LanguageTool server')
63 | parser.add_argument('--remote-port',
64 | help='port of the remote LanguageTool server')
65 |
66 | args = parser.parse_args()
67 |
68 | if args.enabled_only:
69 | if args.disable:
70 | parser.error('--enabled-only cannot be used with --disable')
71 |
72 | if not args.enable:
73 | parser.error('--enabled-only requires --enable')
74 |
75 | return args
76 |
77 |
78 | class RulesAction(argparse.Action):
79 | """
80 | Custom argparse action to update a set of rules in the namespace.
81 | This action is used to modify the set of rules stored in the argparse
82 | namespace when the action is triggered. It updates the attribute specified
83 | by 'self.dest' with the provided values.
84 |
85 | Attributes:
86 | dest (str): the destination attribute to update
87 | """
88 | def __call__(self, parser: argparse.ArgumentParser, namespace: Any, values: Any, option_string: Optional[str] = None):
89 | """
90 | This method is called when the action is triggered. It updates the set of rules
91 | in the namespace with the provided values. The method is invoked automatically
92 | by argparse when the corresponding command-line argument is encountered.
93 |
94 | :param parser: The ArgumentParser object which contains this action.
95 | :type parser: argparse.ArgumentParser
96 | :param namespace: The namespace object that will be returned by parse_args().
97 | :type namespace: Any
98 | :param values: The argument values associated with the action.
99 | :type values: Any
100 | :param option_string: The option string that was used to invoke this action.
101 | :type option_string: Optional[str]
102 | """
103 | getattr(namespace, self.dest).update(values)
104 |
105 |
106 | def get_rules(rules: str) -> Set[str]:
107 | """
108 | Parse a string of rules and return a set of rule IDs.
109 |
110 | :param rules: A string containing rule IDs separated by non-word characters.
111 | :type rules: str
112 | :return: A set of rule IDs.
113 | :rtype: Set[str]
114 | """
115 | return {rule.upper() for rule in re.findall(r"[\w\-]+", rules)}
116 |
117 |
118 | def get_text(filename: Union[str, int], encoding: Optional[str], ignore: Optional[str]) -> str:
119 | """
120 | Read the content of a file and return it as a string, optionally ignoring lines that match a regular expression.
121 |
122 | :param filename: The name of the file to read or file descriptor.
123 | :type filename: Union[str, int]
124 | :param encoding: The encoding to use for reading the file.
125 | :type encoding: Optional[str]
126 | :param ignore: A regular expression pattern to match lines that should be ignored.
127 | :type ignore: Optional[str]
128 | :return: The content of the file as a string.
129 | :rtype: str
130 | """
131 | with open(filename, encoding=encoding) as f:
132 | text = ''.join('\n' if (ignore and re.match(ignore, line)) else line
133 | for line in f.readlines())
134 | return text
135 |
136 |
137 | def main() -> int:
138 | """
139 | Main function to parse arguments, process files, and check text using LanguageTool.
140 |
141 | :return: Exit status code
142 | :rtype: int
143 | """
144 | args = parse_args()
145 |
146 | status = 0
147 |
148 | for filename in args.files:
149 | if len(args.files) > 1:
150 | print(filename, file=sys.stderr)
151 |
152 | if filename == '-':
153 | filename = sys.stdin.fileno()
154 | encoding = args.encoding or (
155 | sys.stdin.encoding if sys.stdin.isatty()
156 | else locale.getpreferredencoding()
157 | )
158 | else:
159 | encoding = args.encoding or 'utf-8'
160 |
161 | remote_server = None
162 | if args.remote_host is not None:
163 | remote_server = args.remote_host
164 | if args.remote_port is not None:
165 | remote_server += f':{args.remote_port}'
166 | lang_tool = LanguageTool(
167 | language=args.language,
168 | motherTongue=args.mother_tongue,
169 | remote_server=remote_server,
170 | )
171 |
172 | try:
173 | text = get_text(filename, encoding, ignore=args.ignore_lines)
174 | except UnicodeError as exception:
175 | print(f'{filename}: {exception}', file=sys.stderr)
176 | continue
177 |
178 | if not args.spell_check:
179 | lang_tool.disable_spellchecking()
180 |
181 | lang_tool.disabled_rules.update(args.disable)
182 | lang_tool.enabled_rules.update(args.enable)
183 | lang_tool.enabled_rules_only = args.enabled_only
184 |
185 | if args.picky:
186 | lang_tool.picky = True
187 |
188 | try:
189 | if args.apply:
190 | print(lang_tool.correct(text))
191 | else:
192 | for match in lang_tool.check(text):
193 | rule_id = match.ruleId
194 |
195 | replacement_text = ', '.join(
196 | f"'{word}'"
197 | for word in match.replacements).strip()
198 |
199 | message = match.message
200 |
201 | # Messages that end with punctuation already include the
202 | # suggestion.
203 | if replacement_text and not message.endswith('?'):
204 | message += ' Suggestions: ' + replacement_text
205 |
206 | line, column = match.get_line_and_column(text)
207 |
208 | print(f'{filename}:{line}:{column}: {rule_id}: {message}')
209 |
210 | status = 2
211 | except LanguageToolError as exception:
212 | print(f'{filename}: {exception}', file=sys.stderr)
213 | continue
214 |
215 | return status
216 |
217 |
218 | sys.exit(main())
219 |
--------------------------------------------------------------------------------
/language_tool_python/config_file.py:
--------------------------------------------------------------------------------
1 | """Module for configuring LanguageTool's local server."""
2 |
3 | from typing import Any, Dict
4 |
5 | import atexit
6 | import os
7 | import tempfile
8 |
9 | # Allowed configuration keys for LanguageTool.
10 | ALLOWED_CONFIG_KEYS = {
11 | 'maxTextLength', 'maxTextHardLength', 'maxCheckTimeMillis', 'maxErrorsPerWordRate',
12 | 'maxSpellingSuggestions', 'maxCheckThreads', 'cacheSize', 'cacheTTLSeconds', 'requestLimit',
13 | 'requestLimitInBytes', 'timeoutRequestLimit', 'requestLimitPeriodInSeconds', 'languageModel',
14 | 'fasttextModel', 'fasttextBinary', 'maxWorkQueueSize', 'rulesFile',
15 | 'blockedReferrers', 'premiumOnly', 'disabledRuleIds', 'pipelineCaching', 'maxPipelinePoolSize',
16 | 'pipelineExpireTimeInSeconds', 'pipelinePrewarming'
17 | }
18 |
19 | class LanguageToolConfig:
20 | """
21 | Configuration class for LanguageTool.
22 |
23 | :param config: Dictionary containing configuration keys and values.
24 | :type config: Dict[str, Any]
25 |
26 | Attributes:
27 | config (Dict[str, Any]): Dictionary containing configuration keys and values.
28 | path (str): Path to the temporary file storing the configuration.
29 | """
30 | config: Dict[str, Any]
31 | path: str
32 |
33 | def __init__(self, config: Dict[str, Any]):
34 | """
35 | Initialize the LanguageToolConfig object.
36 | """
37 | assert set(config.keys()) <= ALLOWED_CONFIG_KEYS, f"unexpected keys in config: {set(config.keys()) - ALLOWED_CONFIG_KEYS}"
38 | assert len(config), "config cannot be empty"
39 | self.config = config
40 |
41 | if 'disabledRuleIds' in self.config:
42 | self.config['disabledRuleIds'] = ','.join(self.config['disabledRuleIds'])
43 | if 'blockedReferrers' in self.config:
44 | self.config['blockedReferrers'] = ','.join(self.config['blockedReferrers'])
45 | for key in ["pipelineCaching", "premiumOnly", "pipelinePrewarming"]:
46 | if key in self.config:
47 | self.config[key] = str(bool(self.config[key])).lower()
48 |
49 | self.path = self._create_temp_file()
50 |
51 | def _create_temp_file(self) -> str:
52 | """
53 | Create a temporary file to store the configuration.
54 |
55 | :return: Path to the temporary file.
56 | :rtype: str
57 | """
58 | tmp_file = tempfile.NamedTemporaryFile(delete=False)
59 |
60 | # Write key=value entries as lines in temporary file.
61 | for key, value in self.config.items():
62 | next_line = f'{key}={value}\n'
63 | tmp_file.write(next_line.encode())
64 | tmp_file.close()
65 |
66 | # Remove file when program exits.
67 | atexit.register(lambda: os.unlink(tmp_file.name))
68 |
69 | return tmp_file.name
70 |
--------------------------------------------------------------------------------
/language_tool_python/download_lt.py:
--------------------------------------------------------------------------------
1 | """LanguageTool download module."""
2 |
3 | import logging
4 | import os
5 | import re
6 | import requests
7 | import subprocess
8 | import tempfile
9 | import tqdm
10 | from typing import IO, Dict, Optional, Tuple
11 | import zipfile
12 | from datetime import datetime
13 |
14 | from shutil import which
15 | from urllib.parse import urljoin
16 | from .utils import (
17 | find_existing_language_tool_downloads,
18 | get_language_tool_download_path,
19 | PathError,
20 | LTP_JAR_DIR_PATH_ENV_VAR
21 | )
22 |
23 | # Create logger for this file.
24 | logging.basicConfig(format='%(message)s')
25 | logger = logging.getLogger(__name__)
26 | logger.setLevel(logging.INFO)
27 |
28 |
29 | # Get download host from environment or default.
30 | BASE_URL_SNAPSHOT = os.environ.get('LTP_DOWNLOAD_HOST_SNAPSHOT', 'https://internal1.languagetool.org/snapshots/')
31 | FILENAME_SNAPSHOT = 'LanguageTool-{version}-snapshot.zip'
32 | BASE_URL_RELEASE = os.environ.get('LTP_DOWNLOAD_HOST_RELEASE', 'https://www.languagetool.org/download/')
33 | FILENAME_RELEASE = 'LanguageTool-{version}.zip'
34 |
35 | LTP_DOWNLOAD_VERSION = 'latest'
36 | LT_SNAPSHOT_CURRENT_VERSION = '6.7-SNAPSHOT'
37 |
38 | JAVA_VERSION_REGEX = re.compile(
39 | r'^(?:java|openjdk) version "(?P\d+)(|\.(?P\d+)\.[^"]+)"',
40 | re.MULTILINE)
41 |
42 | # Updated for later versions of java
43 | JAVA_VERSION_REGEX_UPDATED = re.compile(
44 | r'^(?:java|openjdk) [version ]?(?P\d+)\.(?P\d+)',
45 | re.MULTILINE)
46 |
47 | def parse_java_version(version_text: str) -> Tuple[int, int]:
48 | """
49 | Parse the Java version from a given version text.
50 |
51 | This function attempts to extract the major version numbers from the provided
52 | Java version string using regular expressions. It supports two different
53 | version formats defined by JAVA_VERSION_REGEX and JAVA_VERSION_REGEX_UPDATED.
54 |
55 | :param version_text: The Java version string to parse.
56 | :type version_text: str
57 | :return: A tuple containing the major version numbers.
58 | :rtype: Tuple[int, int]
59 | :raises SystemExit: If the version string cannot be parsed.
60 | """
61 | match = (
62 | re.search(JAVA_VERSION_REGEX, version_text)
63 | or re.search(JAVA_VERSION_REGEX_UPDATED, version_text)
64 | )
65 | if not match:
66 | raise SystemExit(f'Could not parse Java version from """{version_text}""".')
67 | major1 = int(match.group('major1'))
68 | major2 = int(match.group('major2')) if match.group('major2') else 0
69 | return (major1, major2)
70 |
71 |
72 | def confirm_java_compatibility(language_tool_version: Optional[str] = LTP_DOWNLOAD_VERSION) -> None:
73 | """
74 | Confirms if the installed Java version is compatible with language-tool-python.
75 | This function checks if Java is installed and verifies that the major version is at least 8 or 17 (depending on the LanguageTool version).
76 | It raises an error if Java is not installed or if the version is incompatible.
77 |
78 | :param language_tool_version: The version of LanguageTool to check compatibility for.
79 | :type language_tool_version: Optional[str]
80 | :raises ModuleNotFoundError: If no Java installation is detected.
81 | :raises SystemError: If the detected Java version is less than the required version.
82 | """
83 |
84 | java_path = which('java')
85 | if not java_path:
86 | raise ModuleNotFoundError(
87 | 'No java install detected. '
88 | 'Please install java to use language-tool-python.'
89 | )
90 |
91 | output = subprocess.check_output([java_path, '-version'],
92 | stderr=subprocess.STDOUT,
93 | universal_newlines=True)
94 |
95 | major_version, minor_version = parse_java_version(output)
96 | version_date_cutoff = datetime.strptime('2025-03-27', '%Y-%m-%d')
97 | is_old_version = (
98 | language_tool_version != 'latest' and (
99 | (re.match(r'^\d+\.\d+$', language_tool_version) and language_tool_version < '6.6') or
100 | (re.match(r'^\d{8}$', language_tool_version) and datetime.strptime(language_tool_version, '%Y%m%d') < version_date_cutoff)
101 | )
102 | )
103 |
104 | # Some installs of java show the version number like `14.0.1`
105 | # and others show `1.14.0.1`
106 | # (with a leading 1). We want to support both.
107 | # (See softwareengineering.stackexchange.com/questions/175075/why-is-java-version-1-x-referred-to-as-java-x)
108 | if is_old_version:
109 | if (major_version == 1 and minor_version < 8) or (major_version != 1 and major_version < 8):
110 | raise SystemError(f'Detected java {major_version}.{minor_version}. LanguageTool requires Java >= 8 for version {language_tool_version}.')
111 | else:
112 | if (major_version == 1 and minor_version < 17) or (major_version != 1 and major_version < 17):
113 | raise SystemError(f'Detected java {major_version}.{minor_version}. LanguageTool requires Java >= 17 for version {language_tool_version}.')
114 |
115 |
116 | def get_common_prefix(z: zipfile.ZipFile) -> Optional[str]:
117 | """
118 | Determine the common prefix of all file names in a zip archive.
119 |
120 | :param z: A ZipFile object representing the zip archive.
121 | :type z: zipfile.ZipFile
122 | :return: The common prefix of all file names in the zip archive, or None if there is no common prefix.
123 | :rtype: Optional[str]
124 | """
125 |
126 | name_list = z.namelist()
127 | if name_list and all(n.startswith(name_list[0]) for n in name_list[1:]):
128 | return name_list[0]
129 | return None
130 |
131 |
132 | def http_get(url: str, out_file: IO[bytes], proxies: Optional[Dict[str, str]] = None) -> None:
133 | """
134 | Downloads a file from a given URL and writes it to the specified output file.
135 |
136 | :param url: The URL to download the file from.
137 | :type url: str
138 | :param out_file: The file object to write the downloaded content to.
139 | :type out_file: IO[bytes]
140 | :param proxies: Optional dictionary of proxies to use for the request.
141 | :type proxies: Optional[Dict[str, str]]
142 | :raises PathError: If the file could not be found at the given URL (HTTP 404).
143 | """
144 | req = requests.get(url, stream=True, proxies=proxies)
145 | content_length = req.headers.get('Content-Length')
146 | total = int(content_length) if content_length is not None else None
147 | if req.status_code == 404:
148 | raise PathError(f'Could not find at URL {url}. The given version may not exist or is no longer available.')
149 | version = url.split('/')[-1].split('-')[1].replace('-snapshot', '').replace('.zip', '')
150 | progress = tqdm.tqdm(unit="B", unit_scale=True, total=total,
151 | desc=f'Downloading LanguageTool {version}')
152 | for chunk in req.iter_content(chunk_size=1024):
153 | if chunk: # filter out keep-alive new chunks
154 | progress.update(len(chunk))
155 | out_file.write(chunk)
156 | progress.close()
157 |
158 |
159 | def unzip_file(temp_file_name: str, directory_to_extract_to: str) -> None:
160 | """
161 | Unzips a zip file to a specified directory.
162 |
163 | :param temp_file_name: A temporary file object representing the zip file to be extracted.
164 | :type temp_file_name: str
165 | :param directory_to_extract_to: The directory where the contents of the zip file will be extracted.
166 | :type directory_to_extract_to: str
167 | """
168 |
169 | logger.info(f'Unzipping {temp_file_name} to {directory_to_extract_to}.')
170 | with zipfile.ZipFile(temp_file_name, 'r') as zip_ref:
171 | zip_ref.extractall(directory_to_extract_to)
172 |
173 |
174 | def download_zip(url: str, directory: str) -> None:
175 | """
176 | Downloads a ZIP file from the given URL and extracts it to the specified directory.
177 |
178 | :param url: The URL of the ZIP file to download.
179 | :type url: str
180 | :param directory: The directory where the ZIP file should be extracted.
181 | :type directory: str
182 | """
183 | # Download file.
184 | downloaded_file = tempfile.NamedTemporaryFile(suffix='.zip', delete=False)
185 | http_get(url, downloaded_file)
186 | # Close the file so we can extract it.
187 | downloaded_file.close()
188 | # Extract zip file to path.
189 | unzip_file(downloaded_file.name, directory)
190 | # Remove the temporary file.
191 | os.remove(downloaded_file.name)
192 | # Tell the user the download path.
193 | logger.info(f'Downloaded {url} to {directory}.')
194 |
195 |
196 | def download_lt(language_tool_version: Optional[str] = LTP_DOWNLOAD_VERSION) -> None:
197 | """
198 | Downloads and extracts the specified version of LanguageTool.
199 | This function checks for Java compatibility, creates the necessary download
200 | directory if it does not exist, and downloads the specified version of
201 | LanguageTool if it is not already present.
202 |
203 | :param language_tool_version: The version of LanguageTool to download. If not
204 | specified, the default version defined by
205 | LTP_DOWNLOAD_VERSION is used.
206 | :type language_tool_version: Optional[str]
207 | :raises AssertionError: If the download folder is not a directory.
208 | :raises ValueError: If the specified version format is invalid.
209 | """
210 |
211 | confirm_java_compatibility(language_tool_version)
212 |
213 | download_folder = get_language_tool_download_path()
214 |
215 | # Use the env var to the jar directory if it is defined
216 | # otherwise look in the download directory
217 | if os.environ.get(LTP_JAR_DIR_PATH_ENV_VAR):
218 | return
219 |
220 | # Make download path, if it doesn't exist.
221 | os.makedirs(download_folder, exist_ok=True)
222 |
223 | assert os.path.isdir(download_folder)
224 | old_path_list = find_existing_language_tool_downloads(download_folder)
225 |
226 | if language_tool_version:
227 | version = language_tool_version
228 | if re.match(r'^\d+\.\d+$', version):
229 | filename = FILENAME_RELEASE.format(version=version)
230 | language_tool_download_url = urljoin(BASE_URL_RELEASE, filename)
231 | elif version == "latest":
232 | filename = FILENAME_SNAPSHOT.format(version=version)
233 | language_tool_download_url = urljoin(BASE_URL_SNAPSHOT, filename)
234 | else:
235 | raise ValueError(
236 | f"You can only download a specific version of LanguageTool if it is "
237 | f"formatted like 'x.y' (e.g. '5.4'). The version you provided is {version}."
238 | f"You can also use 'latest' to download the latest snapshot of LanguageTool."
239 | )
240 | dirname, _ = os.path.splitext(filename)
241 | dirname = dirname.replace('latest', LT_SNAPSHOT_CURRENT_VERSION)
242 | if version == "latest":
243 | dirname = f"LanguageTool-{LT_SNAPSHOT_CURRENT_VERSION}"
244 | extract_path = os.path.join(download_folder, dirname)
245 |
246 | if extract_path not in old_path_list:
247 | download_zip(language_tool_download_url, download_folder)
248 |
--------------------------------------------------------------------------------
/language_tool_python/language_tag.py:
--------------------------------------------------------------------------------
1 | """LanguageTool language tag normalization module."""
2 |
3 | import re
4 | from typing import Iterable, Any
5 | from functools import total_ordering
6 |
7 | @total_ordering
8 | class LanguageTag:
9 | """
10 | A class to represent and normalize language tags.
11 |
12 | :param tag: The language tag.
13 | :type tag: str
14 | :param languages: An iterable of supported language tags.
15 | :type languages: Iterable[str]
16 |
17 | Attributes:
18 | tag (str): The language tag to be normalized.
19 | languages (Iterable[str]): An iterable of supported language tags.
20 | normalized_tag (str): The normalized language tag.
21 | _LANGUAGE_RE (re.Pattern): A regular expression to match language tags.
22 | """
23 | _LANGUAGE_RE = re.compile(r"^([a-z]{2,3})(?:[_-]([a-z]{2}))?$", re.I)
24 |
25 | def __init__(self, tag: str, languages: Iterable[str]) -> None:
26 | """
27 | Initialize a LanguageTag instance.
28 | """
29 | self.tag = tag
30 | self.languages = languages
31 | self.normalized_tag = self._normalize(tag)
32 |
33 | def __eq__(self, other: Any) -> bool:
34 | """
35 | Compare this LanguageTag object with another for equality.
36 |
37 | :param other: The other object to compare with.
38 | :type other: Any
39 | :return: True if the normalized tags are equal, False otherwise.
40 | :rtype: bool
41 | """
42 | return self.normalized_tag == self._normalize(other)
43 |
44 | def __lt__(self, other: Any) -> bool:
45 | """
46 | Compare this object with another for less-than ordering.
47 |
48 | :param other: The object to compare with.
49 | :type other: Any
50 | :return: True if this object is less than the other, False otherwise.
51 | :rtype: bool
52 | """
53 | return str(self) < self._normalize(other)
54 |
55 | def __str__(self) -> str:
56 | """
57 | Returns the string representation of the object.
58 |
59 | :return: The normalized tag as a string.
60 | :rtype: str
61 | """
62 | return self.normalized_tag
63 |
64 | def __repr__(self) -> str:
65 | """
66 | Return a string representation of the LanguageTag instance.
67 |
68 | :return: A string in the format ''
69 | :rtype: str
70 | """
71 | return f''
72 |
73 | def _normalize(self, tag: str) -> str:
74 | """
75 | Normalize a language tag to a standard format.
76 |
77 | :param tag: The language tag to normalize.
78 | :type tag: str
79 | :raises ValueError: If the tag is empty or unsupported.
80 | :return: The normalized language tag.
81 | :rtype: str
82 | """
83 | if not tag:
84 | raise ValueError('empty language tag')
85 | languages = {language.lower().replace('-', '_'): language
86 | for language in self.languages}
87 | try:
88 | return languages[tag.lower().replace('-', '_')]
89 | except KeyError:
90 | try:
91 | return languages[self._LANGUAGE_RE.match(tag).group(1).lower()]
92 | except (KeyError, AttributeError):
93 | raise ValueError(f'unsupported language: {tag!r}')
94 |
--------------------------------------------------------------------------------
/language_tool_python/match.py:
--------------------------------------------------------------------------------
1 | """LanguageTool API Match object representation and utility module."""
2 |
3 | import unicodedata
4 | from collections import OrderedDict
5 | from typing import Any, Dict, Tuple, Iterator, OrderedDict as OrderedDictType, List, Optional
6 | from functools import total_ordering
7 |
8 | def get_match_ordered_dict() -> OrderedDictType[str, type]:
9 | """
10 | Returns an ordered dictionary with predefined keys and their corresponding types.
11 |
12 | :return: An OrderedDict where each key is a string representing a specific attribute
13 | and each value is the type of that attribute.
14 | :rtype: OrderedDictType[str, type]
15 |
16 | The keys and their corresponding types are:
17 |
18 | - 'ruleId': str
19 | - 'message': str
20 | - 'replacements': list
21 | - 'offsetInContext': int
22 | - 'context': str
23 | - 'offset': int
24 | - 'errorLength': int
25 | - 'category': str
26 | - 'ruleIssueType': str
27 | - 'sentence': str
28 | """
29 | slots = OrderedDict([
30 | ('ruleId', str),
31 | ('message', str),
32 | ('replacements', list),
33 | ('offsetInContext', int),
34 | ('context', str),
35 | ('offset', int),
36 | ('errorLength', int),
37 | ('category', str),
38 | ('ruleIssueType', str),
39 | ('sentence', str),
40 | ])
41 | return slots
42 |
43 | def auto_type(obj: Any) -> Any:
44 | """
45 | Attempts to automatically convert the input object to an integer or float.
46 | If the conversion to an integer fails, it tries to convert to a float.
47 | If both conversions fail, it returns the original object.
48 |
49 | :param obj: The object to be converted.
50 | :type obj: Any
51 | :return: The converted object as an integer, float, or the original object.
52 | :rtype: Any
53 | """
54 |
55 | try:
56 | return int(obj)
57 | except ValueError:
58 | try:
59 | return float(obj)
60 | except ValueError:
61 | return obj
62 |
63 | def four_byte_char_positions(text: str) -> List[int]:
64 | """
65 | Identify positions of 4-byte encoded characters in a UTF-8 string.
66 | This function scans through the input text and identifies the positions
67 | of characters that are encoded with 4 bytes in UTF-8. These characters
68 | are typically non-BMP (Basic Multilingual Plane) characters, such as
69 | certain emoji and some rare Chinese, Japanese, and Korean characters.
70 |
71 | :param text: The input string to be analyzed.
72 | :type text: str
73 | :return: A list of positions where 4-byte encoded characters are found.
74 | :rtype: List[int]
75 | """
76 | positions = []
77 | char_index = 0
78 | for char in text:
79 | if len(char.encode('utf-8')) == 4:
80 | positions.append(char_index)
81 | # Adding 1 to the index because 4 byte characters are
82 | # 2 bytes in length in LanguageTool, instead of 1 byte in Python.
83 | char_index += 1
84 | char_index += 1
85 | return positions
86 |
87 | @total_ordering
88 | class Match:
89 | """
90 | Represents a match object that contains information about a language rule violation.
91 |
92 | :param attrib: A dictionary containing various attributes for the match.
93 | The dictionary is expected to have the following keys:
94 |
95 | - 'rule': A dictionary with keys 'category' (which has an 'id') and 'id', 'issueType'.
96 |
97 | - 'context': A dictionary with keys 'offset' and 'text'.
98 |
99 | - 'replacements': A list of dictionaries, each containing a 'value'.
100 |
101 | - 'length': The length of the error.
102 |
103 | - 'message': The message describing the error.
104 | :type attrib: Dict[str, Any]
105 | :param text: The original text in which the error occurred (the whole text, not just the context).
106 | :type text: str
107 |
108 | Attributes:
109 | PREVIOUS_MATCHES_TEXT (Optional[str]): The text of the previous match object.
110 | FOUR_BYTES_POSITIONS (Optional[List[int]]): The positions of 4-byte encoded characters in the text, registered by the previous match object (kept for optimization purposes if the text is the same).
111 | ruleId (str): The ID of the rule that was violated.
112 | message (str): The message describing the error.
113 | replacements (list): A list of suggested replacements for the error.
114 | offsetInContext (int): The offset of the error in the context.
115 | context (str): The context in which the error occurred.
116 | offset (int): The offset of the error.
117 | errorLength (int): The length of the error.
118 | category (str): The category of the rule that was violated.
119 | ruleIssueType (str): The issue type of the rule that was violated.
120 |
121 | Exemple of a match object received from the LanguageTool API :
122 |
123 | ```
124 | {
125 | 'message': 'Possible spelling mistake found.',
126 | 'shortMessage': 'Spelling mistake',
127 | 'replacements': [{'value': 'newt'}, {'value': 'not'}, {'value': 'new', 'shortDescription': 'having just been made'}, {'value': 'news'}, {'value': 'foot', 'shortDescription': 'singular'}, {'value': 'root', 'shortDescription': 'underground organ of a plant'}, {'value': 'boot'}, {'value': 'noon'}, {'value': 'loot', 'shortDescription': 'plunder'}, {'value': 'moot'}, {'value': 'Root'}, {'value': 'soot', 'shortDescription': 'carbon black'}, {'value': 'newts'}, {'value': 'nook'}, {'value': 'Lieut'}, {'value': 'coot'}, {'value': 'hoot'}, {'value': 'toot'}, {'value': 'snoot'}, {'value': 'neut'}, {'value': 'nowt'}, {'value': 'Noor'}, {'value': 'noob'}],
128 | 'offset': 8,
129 | 'length': 4,
130 | 'context': {'text': 'This is noot okay. ', 'offset': 8, 'length': 4}, 'sentence': 'This is noot okay.',
131 | 'type': {'typeName': 'Other'},
132 | 'rule': {'id': 'MORFOLOGIK_RULE_EN_US', 'description': 'Possible spelling mistake', 'issueType': 'misspelling', 'category': {'id': 'TYPOS', 'name': 'Possible Typo'}},
133 | 'ignoreForIncompleteSentence': False,
134 | 'contextForSureMatch': 0
135 | }
136 | ```
137 | """
138 |
139 | PREVIOUS_MATCHES_TEXT: Optional[str] = None
140 | FOUR_BYTES_POSITIONS: Optional[List[int]] = None
141 |
142 | def __init__(self, attrib: Dict[str, Any], text: str) -> None:
143 | """
144 | Initialize a Match object with the given attributes.
145 | The method processes and normalizes the attributes before storing them on the object.
146 | This method adjusts the positions of 4-byte encoded characters in the text
147 | to ensure the offsets of the matches are correct.
148 | """
149 | if text is None:
150 | raise ValueError("The text parameter must not be None")
151 | elif not isinstance(text, str):
152 | raise TypeError("The text parameter must be a string")
153 |
154 | # Process rule.
155 | attrib['category'] = attrib['rule']['category']['id']
156 | attrib['ruleId'] = attrib['rule']['id']
157 | attrib['ruleIssueType'] = attrib['rule']['issueType']
158 | del attrib['rule']
159 | # Process context.
160 | attrib['offsetInContext'] = attrib['context']['offset']
161 | attrib['context'] = attrib['context']['text']
162 | # Process replacements.
163 | attrib['replacements'] = [r['value'] for r in attrib['replacements']]
164 | # Rename error length.
165 | attrib['errorLength'] = attrib['length']
166 | # Normalize unicode
167 | attrib['message'] = unicodedata.normalize("NFKC", attrib['message'])
168 | # Store objects on self.
169 | for k, v in attrib.items():
170 | setattr(self, k, v)
171 |
172 | if Match.PREVIOUS_MATCHES_TEXT != text:
173 | Match.PREVIOUS_MATCHES_TEXT = text
174 | Match.FOUR_BYTES_POSITIONS = four_byte_char_positions(text)
175 | # Get the positions of 4-byte encoded characters in the text because without
176 | # carrying out this step, the offsets of the matches could be incorrect.
177 | self.offset -= sum(1 for pos in Match.FOUR_BYTES_POSITIONS if pos < self.offset)
178 |
179 | def __repr__(self) -> str:
180 | """
181 | Return a string representation of the object.
182 | This method provides a detailed string representation of the object,
183 | including its class name and a dictionary of its attributes.
184 |
185 | :return: A string representation of the object.
186 | :rtype: str
187 | """
188 | def _ordered_dict_repr() -> str:
189 | """
190 | Generate a string representation of the object's attributes in an ordered dictionary format.
191 |
192 | This method collects the attributes of the object, ensuring that the order of attributes
193 | is preserved as defined by `get_match_ordered_dict()`. Attributes that are not part of the
194 | ordered dictionary are appended at the end. Attributes starting with an underscore are
195 | excluded from the representation.
196 |
197 | :return: A string representation of the object's attributes in an ordered dictionary format.
198 | :rtype: str
199 | """
200 | slots = list(get_match_ordered_dict())
201 | slots += list(set(self.__dict__).difference(slots))
202 | attrs = [slot for slot in slots
203 | if slot in self.__dict__ and not slot.startswith('_')]
204 | return f"{{{', '.join([f'{attr!r}: {getattr(self, attr)!r}' for attr in attrs])}}}"
205 |
206 | return f'{self.__class__.__name__}({_ordered_dict_repr()})'
207 |
208 | def __str__(self) -> str:
209 | """
210 | Returns a string representation of the match object.
211 |
212 | The string includes the offset, error length, rule ID, message,
213 | suggestions, and context with a visual indicator of the error position.
214 |
215 | :return: A formatted string describing the match object.
216 | :rtype: str
217 | """
218 | ruleId = self.ruleId
219 | s = f'Offset {self.offset}, length {self.errorLength}, Rule ID: {ruleId}'
220 | if self.message:
221 | s += f'\nMessage: {self.message}'
222 | if self.replacements:
223 | s += f"\nSuggestion: {'; '.join(self.replacements)}"
224 | s += f"\n{self.context}\n{' ' * self.offsetInContext + '^' * self.errorLength}"
225 | return s
226 |
227 | @property
228 | def matchedText(self) -> str:
229 | """
230 | Returns the substring from the context that corresponds to the matched text.
231 |
232 | :return: The matched text from the context.
233 | :rtype: str
234 | """
235 | return self.context[self.offsetInContext:self.offsetInContext+self.errorLength]
236 |
237 | def get_line_and_column(self, original_text: str) -> Tuple[int, int]:
238 | """
239 | Returns the line and column number of the error in the context.
240 |
241 | :param original_text: The original text in which the error occurred. We need this to calculate the line and column number, because the context has no more newline characters.
242 | :type original_text: str
243 | :return: A tuple containing the line and column number of the error.
244 | :rtype: Tuple[int, int]
245 | """
246 |
247 | context_without_additions = self.context[3:-3] if len(self.context) > 6 else self.context
248 | if context_without_additions not in original_text.replace('\n', ' '):
249 | raise ValueError('The original text does not match the context of the error')
250 | line = original_text.count('\n', 0, self.offset)
251 | column = self.offset - original_text.rfind('\n', 0, self.offset)
252 | return line + 1, column
253 |
254 | def select_replacement(self, index: int) -> None:
255 | """
256 | Select a single replacement suggestion based on the given index and update the replacements list, leaving only the selected replacement.
257 |
258 | :param index: The index of the replacement to select.
259 | :type index: int
260 | :raises ValueError: If there are no replacement suggestions.
261 | :raises ValueError: If the index is out of the valid range.
262 | """
263 |
264 | if not self.replacements:
265 | raise ValueError('This Match has no suggestions')
266 | elif index < 0 or index >= len(self.replacements):
267 | raise ValueError(f'This Match\'s suggestions are numbered from 0 to {len(self.replacements) - 1}')
268 | self.replacements = [self.replacements[index]]
269 |
270 | def __eq__(self, other: Any) -> bool:
271 | """
272 | Compare this object with another for equality.
273 |
274 | :param other: The object to compare with.
275 | :type other: Any
276 | :return: True if both objects are equal, False otherwise.
277 | :rtype: bool
278 | """
279 | return list(self) == list(other)
280 |
281 | def __lt__(self, other: Any) -> bool:
282 | """
283 | Compare this object with another object for less-than ordering.
284 |
285 | :param other: The object to compare with.
286 | :type other: Any
287 | :return: True if this object is less than the other object, False otherwise.
288 | :rtype: bool
289 | """
290 | return list(self) < list(other)
291 |
292 | def __iter__(self) -> Iterator[Any]:
293 | """
294 | Return an iterator over the attributes of the match object.
295 |
296 | This method allows the match object to be iterated over, yielding the
297 | values of its attributes in the order defined by `get_match_ordered_dict`.
298 |
299 | :return: An iterator over the attribute values of the match object.
300 | :rtype: Iterator[Any]
301 | """
302 | return iter(getattr(self, attr) for attr in get_match_ordered_dict())
303 |
304 | def __setattr__(self, key: str, value: Any) -> None:
305 | """
306 | Set an attribute on the instance.
307 |
308 | This method overrides the default behavior of setting an attribute.
309 | It attempts to transform the value using a function from `get_match_ordered_dict()`
310 | based on the provided key. If the key is not found in the dictionary, the attribute
311 | is not set.
312 |
313 | :param key: The name of the attribute to set.
314 | :type key: str
315 | :param value: The value to set the attribute to.
316 | :type value: Any
317 | :raises KeyError: If the key is not found in the dictionary returned by `get_match_ordered_dict()`.
318 | """
319 | try:
320 | value = get_match_ordered_dict()[key](value)
321 | except KeyError:
322 | return
323 | super().__setattr__(key, value)
324 |
325 | def __getattr__(self, name: str) -> Any:
326 | """
327 | Handle attribute access for undefined attributes.
328 |
329 | This method is called when an attribute lookup has not found the attribute in the usual places
330 | (i.e., it is not an instance attribute nor is it found in the class tree for self). This method
331 | checks if the attribute name is in the ordered dictionary returned by `get_match_ordered_dict()`.
332 | If the attribute name is not found, it raises an AttributeError.
333 |
334 | :param name: The name of the attribute being accessed.
335 | :type name: str
336 | :return: The value of the attribute if it exists.
337 | :rtype: Any
338 | :raises AttributeError: If the attribute does not exist.
339 | """
340 | if name not in get_match_ordered_dict():
341 | raise AttributeError(f'{self.__class__.__name__!r} object has no attribute {name!r}')
342 |
--------------------------------------------------------------------------------
/language_tool_python/server.py:
--------------------------------------------------------------------------------
1 | """LanguageTool server management module."""
2 |
3 | from typing import Dict, List, Optional, Any, Set
4 |
5 | import atexit
6 | import http.client
7 | import json
8 | import os
9 | import re
10 | import requests
11 | import socket
12 | import subprocess
13 | import threading
14 | import urllib.parse
15 | import psutil
16 |
17 | from .config_file import LanguageToolConfig
18 | from .download_lt import download_lt, LTP_DOWNLOAD_VERSION
19 | from .language_tag import LanguageTag
20 | from .match import Match
21 | from .utils import (
22 | correct,
23 | parse_url, get_locale_language,
24 | get_language_tool_directory, get_server_cmd,
25 | FAILSAFE_LANGUAGE, startupinfo,
26 | LanguageToolError, ServerError, PathError, RateLimitError,
27 | kill_process_force
28 | )
29 |
30 |
31 | DEBUG_MODE = False
32 |
33 | # Keep track of running server PIDs in a global list. This way,
34 | # we can ensure they're killed on exit.
35 | RUNNING_SERVER_PROCESSES: List[subprocess.Popen] = []
36 |
37 |
38 | class LanguageTool:
39 | """
40 | A class to interact with the LanguageTool server for text checking and correction.
41 |
42 | :param language: The language to be used by the LanguageTool server. If None, it will try to detect the system language.
43 | :type language: Optional[str]
44 | :param motherTongue: The mother tongue of the user.
45 | :type motherTongue: Optional[str]
46 | :param remote_server: URL of a remote LanguageTool server. If provided, the local server will not be started.
47 | :type remote_server: Optional[str]
48 | :param newSpellings: Custom spellings to be added to the LanguageTool server.
49 | :type newSpellings: Optional[List[str]]
50 | :param new_spellings_persist: Whether the new spellings should persist across sessions.
51 | :type new_spellings_persist: Optional[bool]
52 | :param host: The host address for the LanguageTool server. Defaults to 'localhost'.
53 | :type host: Optional[str]
54 | :param config: Path to a configuration file for the LanguageTool server.
55 | :type config: Optional[str]
56 | :param language_tool_download_version: The version of LanguageTool to download if needed.
57 | :type language_tool_download_version: Optional[str]
58 |
59 | Attributes:
60 | _MIN_PORT (int): The minimum port number to use for the server.
61 | _MAX_PORT (int): The maximum port number to use for the server.
62 | _TIMEOUT (int): The timeout for server requests.
63 | _remote (bool): A flag to indicate if the server is remote.
64 | _port (int): The port number to use for the server.
65 | _server (subprocess.Popen): The server process.
66 | _consumer_thread (threading.Thread): The thread to consume server output.
67 | _PORT_RE (re.Pattern): A compiled regular expression pattern to match the server port.
68 | language_tool_download_version (str): The version of LanguageTool to download.
69 | _new_spellings (List[str]): A list of new spellings to register.
70 | _new_spellings_persist (bool): A flag to indicate if new spellings should persist.
71 | _host (str): The host to use for the server.
72 | config (LanguageToolConfig): The configuration to use for the server.
73 | _url (str): The URL of the server if remote.
74 | _stop_consume_event (threading.Event): An event to signal the consumer thread to stop.
75 | motherTongue (str): The user's mother tongue (used in requests to the server).
76 | disabled_rules (Set[str]): A set of disabled rules (used in requests to the server).
77 | enabled_rules (Set[str]): A set of enabled rules (used in requests to the server).
78 | disabled_categories (Set[str]): A set of disabled categories (used in requests to the server).
79 | enabled_categories (Set[str]): A set of enabled categories (used in requests to the server).
80 | enabled_rules_only (bool): A flag to indicate if only enabled rules should be used (used in requests to the server).
81 | preferred_variants (Set[str]): A set of preferred variants (used in requests to the server).
82 | picky (bool): A flag to indicate if the tool should be picky (used in requests to the server).
83 | language (str): The language to use (used in requests to the server and in other methods).
84 | _spell_checking_categories (Set[str]): A set of spell-checking categories.
85 | """
86 | _MIN_PORT = 8081
87 | _MAX_PORT = 8999
88 | _TIMEOUT = 5 * 60
89 | _remote = False
90 | _port = _MIN_PORT
91 | _server: subprocess.Popen = None
92 | _consumer_thread: threading.Thread = None
93 | _PORT_RE = re.compile(r"(?:https?://.*:|port\s+)(\d+)", re.I)
94 |
95 | def __init__(
96 | self, language=None, motherTongue=None,
97 | remote_server=None, newSpellings=None,
98 | new_spellings_persist=True,
99 | host=None, config=None,
100 | language_tool_download_version: str = LTP_DOWNLOAD_VERSION
101 | ) -> None:
102 | """
103 | Initialize the LanguageTool server.
104 | """
105 | self.language_tool_download_version = language_tool_download_version
106 | self._new_spellings = None
107 | self._new_spellings_persist = new_spellings_persist
108 | self._host = host or socket.gethostbyname('localhost')
109 |
110 | if remote_server:
111 | assert config is None, "cannot pass config file to remote server"
112 | self.config = LanguageToolConfig(config) if config else None
113 |
114 | if remote_server is not None:
115 | self._remote = True
116 | self._url = parse_url(remote_server)
117 | self._url = urllib.parse.urljoin(self._url, 'v2/')
118 | self._update_remote_server_config(self._url)
119 | elif not self._server_is_alive():
120 | self._stop_consume_event = threading.Event()
121 | self._start_server_on_free_port()
122 | if language is None:
123 | try:
124 | language = get_locale_language()
125 | except ValueError:
126 | language = FAILSAFE_LANGUAGE
127 | if newSpellings:
128 | self._new_spellings = newSpellings
129 | self._register_spellings()
130 | self._language = LanguageTag(language, self._get_languages())
131 | self.motherTongue = motherTongue
132 | self.disabled_rules = set()
133 | self.enabled_rules = set()
134 | self.disabled_categories = set()
135 | self.enabled_categories = set()
136 | self.enabled_rules_only = False
137 | self.preferred_variants = set()
138 | self.picky = False
139 |
140 | def __enter__(self) -> 'LanguageTool':
141 | """
142 | Enter the runtime context related to this object.
143 |
144 | This method is called when execution flow enters the context of the
145 | `with` statement using this object. It returns the object itself.
146 |
147 | :return: The object itself.
148 | :rtype: LanguageTool
149 | """
150 | return self
151 |
152 | def __exit__(self, exc_type: Optional[type], exc_val: Optional[BaseException], exc_tb: Optional[Any]) -> None:
153 | """
154 | Exit the runtime context related to this object.
155 | This method is called when the runtime context is exited. It can be used to
156 | clean up any resources that were allocated during the context. The parameters
157 | describe the exception that caused the context to be exited. If the context
158 | was exited without an exception, all three arguments will be None.
159 |
160 | :param exc_type: The exception type of the exception that caused the context
161 | to be exited, or None if no exception occurred.
162 | :type exc_type: Optional[type]
163 | :param exc_val: The exception instance that caused the context to be exited,
164 | or None if no exception occurred.
165 | :type exc_val: Optional[BaseException]
166 | :param exc_tb: The traceback object associated with the exception, or None
167 | if no exception occurred.
168 | :type exc_tb: Optional[Any]
169 | """
170 | self.close()
171 |
172 | def __del__(self) -> None:
173 | """
174 | Destructor method that ensures the server is properly closed.
175 | This method is called when the instance is about to be destroyed. It
176 | ensures that the `close` method is called to release any resources
177 | or perform any necessary cleanup.
178 | """
179 |
180 | self.close()
181 |
182 | def __repr__(self) -> str:
183 | """
184 | Return a string representation of the server instance.
185 |
186 | :return: A string that includes the class name, language, and mother tongue.
187 | :rtype: str
188 | """
189 | return f'{self.__class__.__name__}(language={self.language!r}, motherTongue={self.motherTongue!r})'
190 |
191 | def close(self) -> None:
192 | """
193 | Closes the server and performs necessary cleanup operations.
194 |
195 | This method performs the following actions:
196 | 1. Checks if the server is alive and terminates it if necessary.
197 | 2. If new spellings are not set to persist and there are new spellings,
198 | it unregisters the spellings and clears the list of new spellings.
199 | """
200 | if self._server_is_alive():
201 | self._terminate_server()
202 | if not self._new_spellings_persist and self._new_spellings:
203 | self._unregister_spellings()
204 | self._new_spellings = []
205 |
206 | @property
207 | def language(self) -> LanguageTag:
208 | """
209 | Returns the language tag associated with the server.
210 |
211 | :return: The language tag.
212 | :rtype: LanguageTag
213 | """
214 |
215 | return self._language
216 |
217 | @language.setter
218 | def language(self, language: str) -> None:
219 | """
220 | Sets the language for the language tool.
221 |
222 | :param language: The language code to set.
223 | :type language: str
224 | """
225 |
226 | self._language = LanguageTag(language, self._get_languages())
227 | self.disabled_rules.clear()
228 | self.enabled_rules.clear()
229 |
230 | @property
231 | def motherTongue(self) -> Optional[LanguageTag]:
232 | """
233 | Retrieve the mother tongue language tag.
234 |
235 | :return: The mother tongue language tag if set, otherwise None.
236 | :rtype: Optional[LanguageTag]
237 | """
238 |
239 | return self._motherTongue
240 |
241 | @motherTongue.setter
242 | def motherTongue(self, motherTongue: Optional[str]) -> None:
243 | """
244 | Sets the mother tongue for the language tool.
245 |
246 | :param motherTongue: The mother tongue language tag as a string. If None, the mother tongue is set to None.
247 | :type motherTongue: Optional[str]
248 | """
249 |
250 | self._motherTongue = (
251 | None if motherTongue is None
252 | else LanguageTag(motherTongue, self._get_languages())
253 | )
254 |
255 | @property
256 | def _spell_checking_categories(self) -> Set[str]:
257 | """
258 | Returns a set of categories used for spell checking.
259 |
260 | :return: A set containing the category 'TYPOS'.
261 | :rtype: Set[str]
262 | """
263 |
264 | return {'TYPOS'}
265 |
266 | def check(self, text: str) -> List[Match]:
267 | """
268 | Checks the given text for language issues using the LanguageTool server.
269 |
270 | :param text: The text to be checked for language issues.
271 | :type text: str
272 | :return: A list of Match objects representing the issues found in the text.
273 | :rtype: List[Match]
274 | """
275 | url = urllib.parse.urljoin(self._url, 'check')
276 | response = self._query_server(url, self._create_params(text))
277 | matches = response['matches']
278 | return [Match(match, text) for match in matches]
279 |
280 | def _create_params(self, text: str) -> Dict[str, str]:
281 | """
282 | Create a dictionary of parameters for the language tool server request.
283 |
284 | :param text: The text to be checked.
285 | :type text: str
286 | :return: A dictionary containing the parameters for the request.
287 | :rtype: Dict[str, str]
288 |
289 | The dictionary may contain the following keys:
290 | - 'language': The language code.
291 | - 'text': The text to be checked.
292 | - 'motherTongue': The mother tongue language code, if specified.
293 | - 'disabledRules': A comma-separated list of disabled rules, if specified.
294 | - 'enabledRules': A comma-separated list of enabled rules, if specified.
295 | - 'enabledOnly': 'true' if only enabled rules should be used.
296 | - 'disabledCategories': A comma-separated list of disabled categories, if specified.
297 | - 'enabledCategories': A comma-separated list of enabled categories, if specified.
298 | - 'preferredVariants': A comma-separated list of preferred language variants, if specified.
299 | - 'level': 'picky' if picky mode is enabled.
300 | """
301 | params = {'language': str(self.language), 'text': text}
302 | if self.motherTongue is not None:
303 | params['motherTongue'] = self.motherTongue
304 | if self.disabled_rules:
305 | params['disabledRules'] = ','.join(self.disabled_rules)
306 | if self.enabled_rules:
307 | params['enabledRules'] = ','.join(self.enabled_rules)
308 | if self.enabled_rules_only:
309 | params['enabledOnly'] = 'true'
310 | if self.disabled_categories:
311 | params['disabledCategories'] = ','.join(self.disabled_categories)
312 | if self.enabled_categories:
313 | params['enabledCategories'] = ','.join(self.enabled_categories)
314 | if self.preferred_variants:
315 | params['preferredVariants'] = ','.join(self.preferred_variants)
316 | if self.picky:
317 | params['level'] = 'picky'
318 | return params
319 |
320 | def correct(self, text: str) -> str:
321 | """
322 | Corrects the given text by applying language tool suggestions. Applies only the first suggestion for each issue.
323 |
324 | :param text: The text to be corrected.
325 | :type text: str
326 | :return: The corrected text.
327 | :rtype: str
328 | """
329 | return correct(text, self.check(text))
330 |
331 | def enable_spellchecking(self) -> None:
332 | """
333 | Enable spellchecking by removing spell checking categories from the disabled categories set.
334 | This method updates the `disabled_categories` attribute by removing any categories that are
335 | related to spell checking, which are defined in the `_spell_checking_categories` attribute.
336 | """
337 | self.disabled_categories.difference_update(
338 | self._spell_checking_categories
339 | )
340 |
341 | def disable_spellchecking(self) -> None:
342 | """
343 | Disable spellchecking by updating the disabled categories with spell checking categories.
344 | """
345 | self.disabled_categories.update(self._spell_checking_categories)
346 |
347 | @staticmethod
348 | def _get_valid_spelling_file_path() -> str:
349 | """
350 | Retrieve the valid file path for the spelling file.
351 | This function constructs the file path for the spelling file used by the
352 | language tool. It checks if the file exists at the constructed path and
353 | raises a FileNotFoundError if the file is not found.
354 |
355 | :raises FileNotFoundError: If the spelling file does not exist at the
356 | constructed path.
357 | :return: The valid file path for the spelling file.
358 | :rtype: str
359 | """
360 | library_path = get_language_tool_directory()
361 | spelling_file_path = os.path.join(
362 | library_path, "org/languagetool/resource/en/hunspell/spelling.txt"
363 | )
364 | if not os.path.exists(spelling_file_path):
365 | raise FileNotFoundError(
366 | f"Failed to find the spellings file at {spelling_file_path}\n "
367 | "Please file an issue at "
368 | "https://github.com/jxmorris12/language_tool_python/issues")
369 | return spelling_file_path
370 |
371 | def _register_spellings(self) -> None:
372 | """
373 | Registers new spellings by adding them to the spelling file.
374 | This method reads the existing spellings from the spelling file,
375 | filters out the new spellings that are already present, and appends
376 | the remaining new spellings to the file. If the DEBUG_MODE is enabled,
377 | it prints a message indicating the file where the new spellings were registered.
378 | """
379 |
380 | spelling_file_path = self._get_valid_spelling_file_path()
381 | with open(spelling_file_path, "r+", encoding='utf-8') as spellings_file:
382 | existing_spellings = set(line.strip() for line in spellings_file.readlines())
383 | new_spellings = [word for word in self._new_spellings if word not in existing_spellings]
384 | self._new_spellings = new_spellings
385 | if new_spellings:
386 | if len(existing_spellings) > 0:
387 | spellings_file.write("\n")
388 | spellings_file.write("\n".join(new_spellings))
389 | if DEBUG_MODE:
390 | print(f"Registered new spellings at {spelling_file_path}")
391 |
392 | def _unregister_spellings(self) -> None:
393 | """
394 | Unregister new spellings from the spelling file.
395 | This method reads the current spellings from the spelling file, removes any
396 | spellings that are present in the `_new_spellings` attribute, and writes the
397 | updated list back to the file.
398 | """
399 | spelling_file_path = self._get_valid_spelling_file_path()
400 |
401 | with open(spelling_file_path, 'r', encoding='utf-8') as spellings_file:
402 | lines = spellings_file.readlines()
403 |
404 | updated_lines = [
405 | line for line in lines if line.strip() not in self._new_spellings
406 | ]
407 | if updated_lines and updated_lines[-1].endswith('\n'):
408 | updated_lines[-1] = updated_lines[-1].strip()
409 |
410 | with open(spelling_file_path, 'w', encoding='utf-8', newline='\n') as spellings_file:
411 | spellings_file.writelines(updated_lines)
412 |
413 | if DEBUG_MODE:
414 | print(f"Unregistered new spellings at {spelling_file_path}")
415 |
416 | def _get_languages(self) -> Set[str]:
417 | """
418 | Retrieve the set of supported languages from the server.
419 | This method starts the server if it is not already running, constructs the URL
420 | for querying the supported languages, and sends a request to the server. It then
421 | processes the server's response to extract the language codes and adds them to
422 | a set. The special code "auto" is also added to the set before returning it.
423 |
424 | :return: A set of language codes supported by the server.
425 | :rtype: Set[str]
426 | """
427 | self._start_server_if_needed()
428 | url = urllib.parse.urljoin(self._url, 'languages')
429 | languages = set()
430 | for e in self._query_server(url, num_tries=1):
431 | languages.add(e.get('code'))
432 | languages.add(e.get('longCode'))
433 | languages.add("auto")
434 | return languages
435 |
436 | def _start_server_if_needed(self) -> None:
437 | """
438 | Starts the server if it is not already running and if it is not a remote server.
439 | This method checks if the server is alive and if it is not a remote server.
440 | If the server is not alive and it is not remote, it starts the server on a free port.
441 | """
442 | if not self._server_is_alive() and self._remote is False:
443 | self._start_server_on_free_port()
444 |
445 | def _update_remote_server_config(self, url: str) -> None:
446 | """
447 | Update the configuration to use a remote server.
448 |
449 | :param url: The URL of the remote server.
450 | :type url: str
451 | """
452 | self._url = url
453 | self._remote = True
454 |
455 | def _query_server(
456 | self, url: str, params: Optional[Dict[str, str]] = None, num_tries: int = 2
457 | ) -> Any:
458 | """
459 | Query the server with the given URL and parameters.
460 |
461 | :param url: The URL to query.
462 | :type url: str
463 | :param params: The parameters to include in the query, defaults to None.
464 | :type params: Optional[Dict[str, str]], optional
465 | :param num_tries: The number of times to retry the query in case of failure, defaults to 2.
466 | :type num_tries: int, optional
467 | :return: The JSON response from the server.
468 | :rtype: Any
469 | :raises LanguageToolError: If the server returns an invalid JSON response or if the query fails after the specified number of retries.
470 | """
471 | if DEBUG_MODE:
472 | print('_query_server url:', url, 'params:', params)
473 | for n in range(num_tries):
474 | try:
475 | with (
476 | requests.get(url, params=params, timeout=self._TIMEOUT)
477 | ) as response:
478 | try:
479 | return response.json()
480 | except json.decoder.JSONDecodeError as e:
481 | if DEBUG_MODE:
482 | print(
483 | f'URL {url} and params {params} '
484 | f'returned invalid JSON response: {e}'
485 | )
486 | print(response)
487 | print(response.content)
488 | if response.status_code == 426:
489 | raise RateLimitError(
490 | 'You have exceeded the rate limit for the free '
491 | 'LanguageTool API. Please try again later.'
492 | )
493 | raise LanguageToolError(response.content.decode())
494 | except (IOError, http.client.HTTPException) as e:
495 | if self._remote is False:
496 | self._terminate_server()
497 | self._start_local_server()
498 | if n + 1 >= num_tries:
499 | raise LanguageToolError(f'{self._url}: {e}')
500 |
501 | def _start_server_on_free_port(self) -> None:
502 | """
503 | Attempt to start the server on a free port within the specified range.
504 | This method continuously tries to start the local server on the current host and port.
505 | If the port is already in use, it increments the port number and tries again until a free port is found
506 | or the maximum port number is reached.
507 |
508 | :raises ServerError: If the server cannot be started and the maximum port number is reached.
509 | """
510 | while True:
511 | self._url = f'http://{self._host}:{self._port}/v2/'
512 | try:
513 | self._start_local_server()
514 | break
515 | except ServerError:
516 | if self._MIN_PORT <= self._port < self._MAX_PORT:
517 | self._port += 1
518 | else:
519 | raise
520 |
521 | def _start_local_server(self) -> None:
522 | """
523 | Start the local LanguageTool server.
524 | This method starts a local instance of the LanguageTool server. If the
525 | LanguageTool is not already downloaded, it will download the specified
526 | version. It handles the server initialization, including setting up
527 | the server command and managing the server process.
528 |
529 | Notes:
530 | - This method uses subprocess to start the server and reads the server
531 | output to determine the port it is running on.
532 | - It also starts a consumer thread to handle the server's stdout.
533 |
534 | :raises PathError: If the path to LanguageTool cannot be found.
535 | :raises LanguageToolError: If the server starts on a different port than requested.
536 | :raises ServerError: If the server is already running or cannot be started.
537 | """
538 | # Before starting local server, download language tool if needed.
539 | download_lt(self.language_tool_download_version)
540 | err = None
541 | try:
542 | if DEBUG_MODE:
543 | if self._port:
544 | print(
545 | 'language_tool_python initializing with port:',
546 | self._port
547 | )
548 | if self.config:
549 | print(
550 | 'language_tool_python initializing '
551 | 'with temporary config file:',
552 | self.config.path
553 | )
554 | server_cmd = get_server_cmd(self._port, self.config)
555 | except PathError as e:
556 | # Can't find path to LanguageTool.
557 | err = e
558 | else:
559 | # Need to PIPE all handles: http://bugs.python.org/issue3905
560 | self._server = subprocess.Popen(
561 | server_cmd,
562 | stdin=subprocess.PIPE,
563 | stdout=subprocess.PIPE,
564 | stderr=subprocess.PIPE,
565 | universal_newlines=True,
566 | startupinfo=startupinfo
567 | )
568 | global RUNNING_SERVER_PROCESSES
569 | RUNNING_SERVER_PROCESSES.append(self._server)
570 |
571 | match = None
572 | while True:
573 | line = self._server.stdout.readline()
574 | if not line:
575 | break
576 | match = self._PORT_RE.search(line)
577 | if match:
578 | port = int(match.group(1))
579 | if port != self._port:
580 | raise LanguageToolError(f'requested port {self._port}, but got {port}')
581 | break
582 | if not match:
583 | err_msg = self._terminate_server()
584 | match = self._PORT_RE.search(err_msg)
585 | if not match:
586 | raise LanguageToolError(err_msg)
587 | port = int(match.group(1))
588 | if port != self._port:
589 | raise LanguageToolError(err_msg)
590 |
591 | if self._server:
592 | self._consumer_thread = threading.Thread(
593 | target=lambda: self._consume(self._server.stdout))
594 | self._consumer_thread.daemon = True
595 | self._consumer_thread.start()
596 | else:
597 | # Couldn't start the server, so maybe there is already one running.
598 | if err:
599 | raise Exception(err)
600 | else:
601 | raise ServerError(
602 | 'Server running; don\'t start a server here.'
603 | )
604 |
605 | def _consume(self, stdout: Any) -> None:
606 | """
607 | Continuously reads from the provided stdout until a stop event is set.
608 |
609 | :param stdout: The output stream to read from.
610 | :type stdout: Any
611 | """
612 | while not self._stop_consume_event.is_set() and stdout.readline():
613 | pass
614 |
615 |
616 | def _server_is_alive(self) -> bool:
617 | """
618 | Check if the server is alive.
619 | This method checks if the server instance exists and is currently running.
620 |
621 | :return: True if the server is alive (exists and running), False otherwise.
622 | :rtype: bool
623 | """
624 | return self._server and self._server.poll() is None
625 |
626 | def _terminate_server(self) -> str:
627 | """
628 | Terminates the server process and associated consumer thread.
629 | This method performs the following steps:
630 | 1. Signals the consumer thread to stop consuming stdout.
631 | 2. Waits for the consumer thread to finish.
632 | 3. Attempts to terminate the server process gracefully.
633 | 4. If the server process does not terminate within the timeout, force kills it.
634 | 5. Closes all associated file descriptors (stdin, stdout, stderr).
635 | 6. Captures any error messages from stderr, if available.
636 |
637 | :return: Error message from stderr, if any, for further logging or debugging.
638 | :rtype: str
639 | """
640 | # Signal the consumer thread to stop consuming stdout
641 | self._stop_consume_event.set()
642 | if self._consumer_thread:
643 | # Wait for the consumer thread to finish
644 | self._consumer_thread.join(timeout=5)
645 |
646 | error_message = ''
647 | if self._server:
648 | try:
649 | try:
650 | # Get the main server process using psutil
651 | proc = psutil.Process(self._server.pid)
652 | except psutil.NoSuchProcess:
653 | # If the process doesn't exist, set proc to None
654 | proc = None
655 |
656 | # Attempt to terminate the process gracefully
657 | self._server.terminate()
658 | # Wait for the process to terminate and capture any stderr output
659 | _, stderr = self._server.communicate(timeout=5)
660 |
661 | except subprocess.TimeoutExpired:
662 | # If the process does not terminate within the timeout, force kill it
663 | kill_process_force(proc=proc)
664 | # Capture remaining stderr output after force termination
665 | _, stderr = self._server.communicate()
666 |
667 | finally:
668 | # Close all associated file descriptors (stdin, stdout, stderr)
669 | if self._server.stdin:
670 | self._server.stdin.close()
671 | if self._server.stdout:
672 | self._server.stdout.close()
673 | if self._server.stderr:
674 | self._server.stderr.close()
675 |
676 | # Release the server process object
677 | self._server = None
678 |
679 | # Capture any error messages from stderr, if available
680 | if stderr:
681 | error_message = stderr.strip()
682 |
683 | # Return the error message, if any, for further logging or debugging
684 | return error_message
685 |
686 |
687 | class LanguageToolPublicAPI(LanguageTool):
688 | """
689 | A class to interact with the public LanguageTool API.
690 | This class extends the `LanguageTool` class and initializes it with the
691 | remote server set to the public LanguageTool API endpoint.
692 |
693 | :param args: Positional arguments passed to the parent class initializer.
694 | :type args: Any
695 | :param kwargs: Keyword arguments passed to the parent class initializer.
696 | :type kwargs: Any
697 | """
698 | def __init__(self, *args: Any, **kwargs: Any) -> None:
699 | """
700 | Initialize the server with the given arguments.
701 | """
702 | super().__init__(
703 | *args, remote_server='https://languagetool.org/api/', **kwargs
704 | )
705 |
706 |
707 | @atexit.register
708 | def terminate_server() -> None:
709 | """
710 | Terminates all running server processes.
711 | This function iterates over the list of running server processes and
712 | forcefully kills each process by its PID.
713 | """
714 | for pid in [p.pid for p in RUNNING_SERVER_PROCESSES]:
715 | kill_process_force(pid=pid)
716 |
--------------------------------------------------------------------------------
/language_tool_python/utils.py:
--------------------------------------------------------------------------------
1 | """Utility functions for the LanguageTool library."""
2 |
3 | from typing import List, Tuple, Optional
4 | from shutil import which
5 |
6 | import glob
7 | import locale
8 | import os
9 | import subprocess
10 | import urllib.parse
11 | from enum import Enum
12 | import psutil
13 |
14 | from .config_file import LanguageToolConfig
15 | from .match import Match
16 |
17 | JAR_NAMES = [
18 | 'languagetool-server.jar',
19 | 'languagetool-standalone*.jar', # 2.1
20 | 'LanguageTool.jar',
21 | 'LanguageTool.uno.jar'
22 | ]
23 | FAILSAFE_LANGUAGE = 'en'
24 |
25 | LTP_PATH_ENV_VAR = "LTP_PATH" # LanguageTool download path
26 |
27 | # Directory containing the LanguageTool jar file:
28 | LTP_JAR_DIR_PATH_ENV_VAR = "LTP_JAR_DIR_PATH"
29 |
30 | # https://mail.python.org/pipermail/python-dev/2011-July/112551.html
31 |
32 | if os.name == 'nt':
33 | startupinfo = subprocess.STARTUPINFO()
34 | startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
35 | else:
36 | startupinfo = None
37 |
38 |
39 | class LanguageToolError(Exception):
40 | """
41 | Exception raised for errors in the LanguageTool library.
42 | This is a generic exception that can be used to indicate various types of
43 | errors encountered while using the LanguageTool library.
44 | """
45 | pass
46 |
47 |
48 | class ServerError(LanguageToolError):
49 | """
50 | Exception raised for errors that occur when interacting with the LanguageTool server.
51 | This exception is a subclass of `LanguageToolError` and is used to indicate
52 | issues such as server startup failures.
53 | """
54 | pass
55 |
56 |
57 | class JavaError(LanguageToolError):
58 | """
59 | Exception raised for errors related to the Java backend of LanguageTool.
60 | This exception is a subclass of `LanguageToolError` and is used to indicate
61 | issues that occur when interacting with Java, such as Java not being found.
62 | """
63 | pass
64 |
65 |
66 | class PathError(LanguageToolError):
67 | """
68 | Exception raised for errors in the file path used in LanguageTool.
69 | This error is raised when there is an issue with the file path provided
70 | to LanguageTool, such as the LanguageTool JAR file not being found,
71 | or a download path not being a valid available file path.
72 | """
73 | pass
74 |
75 |
76 | class RateLimitError(LanguageToolError):
77 | """
78 | Exception raised for errors related to rate limiting in the LanguageTool server.
79 | This exception is a subclass of `LanguageToolError` and is used to indicate
80 | issues such as exceeding the allowed number of requests to the public API without a key.
81 | """
82 | pass
83 |
84 |
85 | def parse_url(url_str: str) -> str:
86 | """
87 | Parse the given URL string and ensure it has a scheme.
88 | If the input URL string does not contain 'http', 'http://' is prepended to it.
89 | The function then parses the URL and returns its canonical form.
90 |
91 | :param url_str: The URL string to be parsed.
92 | :type url_str: str
93 | :return: The parsed URL in its canonical form.
94 | :rtype: str
95 | """
96 | if 'http' not in url_str:
97 | url_str = 'http://' + url_str
98 |
99 | return urllib.parse.urlparse(url_str).geturl()
100 |
101 |
102 | class TextStatus(Enum):
103 | CORRECT = "correct"
104 | FAULTY = "faulty"
105 | GARBAGE = "garbage"
106 |
107 |
108 | def classify_matches(matches: List[Match]) -> TextStatus:
109 | """
110 | Classify the matches (result of a check on a text) into one of three categories:
111 | CORRECT, FAULTY, or GARBAGE.
112 | This function checks the status of the matches and returns a corresponding
113 | `TextStatus` value.
114 |
115 | :param matches: A list of Match objects to be classified.
116 | :type matches: List[Match]
117 | :return: The classification of the matches as a `TextStatus` value.
118 | :rtype: TextStatus
119 | """
120 | if not len(matches):
121 | return TextStatus.CORRECT
122 | matches = [match for match in matches if match.replacements]
123 | if not len(matches):
124 | return TextStatus.GARBAGE
125 | return TextStatus.FAULTY
126 |
127 |
128 | def correct(text: str, matches: List[Match]) -> str:
129 | """
130 | Corrects the given text based on the provided matches.
131 | Only the first replacement for each match is applied to the text.
132 |
133 | :param text: The original text to be corrected.
134 | :type text: str
135 | :param matches: A list of Match objects that contain the positions and replacements for errors in the text.
136 | :type matches: List[Match]
137 | :return: The corrected text.
138 | :rtype: str
139 | """
140 | ltext = list(text)
141 | matches = [match for match in matches if match.replacements]
142 | errors = [ltext[match.offset:match.offset + match.errorLength]
143 | for match in matches]
144 | correct_offset = 0
145 | for n, match in enumerate(matches):
146 | frompos, topos = (correct_offset + match.offset,
147 | correct_offset + match.offset + match.errorLength)
148 | if ltext[frompos:topos] != errors[n]:
149 | continue
150 | repl = match.replacements[0]
151 | ltext[frompos:topos] = list(repl)
152 | correct_offset += len(repl) - len(errors[n])
153 | return ''.join(ltext)
154 |
155 |
156 | def get_language_tool_download_path() -> str:
157 | """
158 | Get the download path for LanguageTool.
159 | This function retrieves the download path for LanguageTool from the environment variable
160 | specified by `LTP_PATH_ENV_VAR`. If the environment variable is not set, it defaults to
161 | a path in the user's home directory under `.cache/language_tool_python`.
162 |
163 | :return: The download path for LanguageTool.
164 | :rtype: str
165 | """
166 | # Get download path from environment or use default.
167 | download_path = os.environ.get(
168 | LTP_PATH_ENV_VAR,
169 | os.path.join(os.path.expanduser("~"), ".cache", "language_tool_python")
170 | )
171 | return download_path
172 |
173 |
174 | def find_existing_language_tool_downloads(download_folder: str) -> List[str]:
175 | """
176 | Find existing LanguageTool downloads in the specified folder.
177 | This function searches for directories in the given download folder
178 | that match the pattern 'LanguageTool*' and returns a list of their paths.
179 |
180 | :param download_folder: The folder where LanguageTool downloads are stored.
181 | :type download_folder: str
182 | :return: A list of paths to the existing LanguageTool download directories.
183 | :rtype: List[str]
184 | """
185 | language_tool_path_list = [
186 | path for path in
187 | glob.glob(os.path.join(download_folder, 'LanguageTool*'))
188 | if os.path.isdir(path)
189 | ]
190 | return language_tool_path_list
191 |
192 |
193 | def get_language_tool_directory() -> str:
194 | """
195 | Get the directory path of the LanguageTool installation.
196 | This function checks the download folder for LanguageTool installations,
197 | verifies that the folder exists and is a directory, and returns the path
198 | to the latest version of LanguageTool found in the directory.
199 |
200 | :raises NotADirectoryError: If the download folder path is not a valid directory.
201 | :raises FileNotFoundError: If no LanguageTool installation is found in the download folder.
202 | :return: The path to the latest version of LanguageTool found in the directory.
203 | :rtype: str
204 | """
205 |
206 | download_folder = get_language_tool_download_path()
207 | if not os.path.isdir(download_folder):
208 | raise NotADirectoryError(f"LanguageTool directory path is not a valid directory {download_folder}.")
209 | language_tool_path_list = find_existing_language_tool_downloads(
210 | download_folder
211 | )
212 |
213 | if not len(language_tool_path_list):
214 | raise FileNotFoundError(f'LanguageTool not found in {download_folder}.')
215 |
216 | # Return the latest version found in the directory.
217 | return max(language_tool_path_list)
218 |
219 |
220 | def get_server_cmd(
221 | port: Optional[int] = None, config: Optional[LanguageToolConfig] = None
222 | ) -> List[str]:
223 | """
224 | Generate the command to start the LanguageTool HTTP server.
225 |
226 | :param port: Optional; The port number on which the server should run. If not provided, the default port will be used.
227 | :type port: Optional[int]
228 | :param config: Optional; The configuration for the LanguageTool server. If not provided, default configuration will be used.
229 | :type config: Optional[LanguageToolConfig]
230 | :return: A list of command line arguments to start the LanguageTool HTTP server.
231 | :rtype: List[str]
232 | """
233 | java_path, jar_path = get_jar_info()
234 | cmd = [java_path, '-cp', jar_path,
235 | 'org.languagetool.server.HTTPServer']
236 |
237 | if port is not None:
238 | cmd += ['-p', str(port)]
239 |
240 | if config is not None:
241 | cmd += ['--config', config.path]
242 |
243 | return cmd
244 |
245 |
246 | def get_jar_info() -> Tuple[str, str]:
247 | """
248 | Retrieve the path to the Java executable and the LanguageTool JAR file.
249 | This function searches for the Java executable in the system's PATH and
250 | locates the LanguageTool JAR file either in a directory specified by an
251 | environment variable or in a default download directory.
252 |
253 | :raises JavaError: If the Java executable cannot be found.
254 | :raises PathError: If the LanguageTool JAR file cannot be found in the specified directory.
255 | :return: A tuple containing the path to the Java executable and the path to the LanguageTool JAR file.
256 | :rtype: Tuple[str, str]
257 | """
258 |
259 | java_path = which('java')
260 | if not java_path:
261 | raise JavaError("can't find Java")
262 |
263 | # Use the env var to the jar directory if it is defined
264 | # otherwise look in the download directory
265 | jar_dir_name = os.environ.get(
266 | LTP_JAR_DIR_PATH_ENV_VAR,
267 | get_language_tool_directory()
268 | )
269 | jar_path = None
270 | for jar_name in JAR_NAMES:
271 | for jar_path in glob.glob(os.path.join(jar_dir_name, jar_name)):
272 | if os.path.isfile(jar_path):
273 | break
274 | else:
275 | jar_path = None
276 | if jar_path:
277 | break
278 | else:
279 | raise PathError(f"can't find languagetool-standalone in {jar_dir_name!r}")
280 | return java_path, jar_path
281 |
282 |
283 | def get_locale_language() -> str:
284 | """
285 | Get the current locale language.
286 | This function retrieves the current locale language setting of the system.
287 | It first attempts to get the locale using `locale.getlocale()`. If that fails,
288 | it falls back to using `locale.getdefaultlocale()`.
289 |
290 | :return: The language code of the current locale.
291 | :rtype: str
292 | """
293 | return locale.getlocale()[0] or locale.getdefaultlocale()[0]
294 |
295 |
296 | def kill_process_force(*, pid: Optional[int] = None, proc: Optional[psutil.Process] = None) -> None:
297 | """
298 | Forcefully kills a process and all its child processes.
299 | This function attempts to kill a process specified either by its PID or by a psutil.Process object.
300 | If the process has any child processes, they will be killed first.
301 |
302 | :param pid: The process ID of the process to be killed. Either `pid` or `proc` must be provided.
303 | :type pid: Optional[int]
304 | :param proc: A psutil.Process object representing the process to be killed. Either `pid` or `proc` must be provided.
305 | :type proc: Optional[psutil.Process]
306 | :raises AssertionError: If neither `pid` nor `proc` is provided.
307 | """
308 | assert any([pid, proc]), "Must pass either pid or proc"
309 | try:
310 | proc = psutil.Process(pid) if proc is None else proc
311 | except psutil.NoSuchProcess:
312 | return
313 | for child in proc.children(recursive=True):
314 | try:
315 | child.kill()
316 | except psutil.NoSuchProcess:
317 | pass
318 | try:
319 | proc.kill()
320 | except psutil.NoSuchProcess:
321 | pass
322 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = "language_tool_python"
3 | version = "2.9.4"
4 | requires-python = ">=3.9"
5 | description = "Checks grammar using LanguageTool."
6 | readme = { file = "README.md", content-type = "text/markdown" }
7 | license = { file = "LICENSE" }
8 | authors = [
9 | { name = "Jack Morris", email = "jxmorris12@gmail.com" }
10 | ]
11 | urls = { Repository = "https://github.com/jxmorris12/language_tool_python.git" }
12 |
13 | dependencies = [
14 | "requests",
15 | "tqdm",
16 | "psutil",
17 | "toml"
18 | ]
19 |
20 | [project.optional-dependencies]
21 | dev = [
22 | "pytest",
23 | "pytest-xdist",
24 | "pytest-cov",
25 | "pytest-runner"
26 | ]
27 |
28 | [project.scripts]
29 | language_tool_python = "language_tool_python.__main__:main"
30 |
31 | [build-system]
32 | requires = ["setuptools>=61.0", "wheel"]
33 | build-backend = "setuptools.build_meta"
34 |
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | [pytest]
2 | addopts = -ra
3 | testpaths = tests
--------------------------------------------------------------------------------
/tests/test_local.bash:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #
3 | # Test command-line usage.
4 |
5 | set -ex
6 |
7 | failed_message='\x1b[01;31mFailed\x1b[0m'
8 | trap "echo -e ${failed_message}" ERR
9 |
10 | exit_status=0
11 |
12 | echo 'This is okay.' | python -m language_tool_python - || exit_status=1
13 | echo 'This is noot okay.' | python -m language_tool_python - && exit_status=1
14 |
15 | echo 'This is okay.' | python -m language_tool_python --enabled-only \
16 | --enable=MORFOLOGIK_RULE_EN_US - || exit_status=1
17 | echo 'This is noot okay.' | python -m language_tool_python --enabled-only \
18 | --enable=MORFOLOGIK_RULE_EN_US - && exit_status=1
19 |
20 | echo 'These are “smart” quotes.' | python -m language_tool_python - || exit_status=1
21 | echo 'These are "dumb" quotes.' | python -m language_tool_python - || exit_status=1
22 | echo 'These are "dumb" quotes.' | python -m language_tool_python --enabled-only \
23 | --enable=EN_QUOTES - || exit_status=1
24 | echo 'These are "dumb" quotes.' | python -m language_tool_python --enabled-only \
25 | --enable=EN_UNPAIRED_BRACKETS - || exit_status=1
26 |
27 | echo '# These are "dumb".' | python -m language_tool_python --ignore-lines='^#' - || exit_status=1
28 |
29 | if [[ "$exit_status" == 0 ]]; then
30 | echo -e '\x1b[01;32mOkay\x1b[0m'
31 | else
32 | echo -e $failed_message
33 | fi
34 | exit "$exit_status"
35 |
--------------------------------------------------------------------------------
/tests/test_major_functionality.py:
--------------------------------------------------------------------------------
1 | import re
2 | import subprocess
3 | import time
4 |
5 | import pytest
6 |
7 | from language_tool_python.utils import LanguageToolError, RateLimitError
8 |
9 |
10 | # THESE TESTS ARE SUPPOSED TO BE RUN WITH 6.7-SNAPSHOT VERSION OF LT SERVER
11 |
12 |
13 | def test_langtool_load():
14 | import language_tool_python
15 | with language_tool_python.LanguageTool("en-US") as tool:
16 | matches = tool.check('ain\'t nothin but a thang')
17 |
18 | expected_matches = [
19 | {
20 | 'ruleId': 'UPPERCASE_SENTENCE_START',
21 | 'message': 'This sentence does not start with an uppercase letter.',
22 | 'replacements': ['Ai'],
23 | 'offsetInContext': 0,
24 | 'context': "ain't nothin but a thang",
25 | 'offset': 0, 'errorLength': 2,
26 | 'category': 'CASING', 'ruleIssueType': 'typographical',
27 | 'sentence': "ain't nothin but a thang"
28 | },
29 | {
30 | 'ruleId': 'MORFOLOGIK_RULE_EN_US',
31 | 'message': 'Possible spelling mistake found.',
32 | 'replacements': ['nothing', 'no thin'],
33 | 'offsetInContext': 6,
34 | 'context': "ain't nothin but a thang",
35 | 'offset': 6, 'errorLength': 6,
36 | 'category': 'TYPOS', 'ruleIssueType': 'misspelling',
37 | 'sentence': "ain't nothin but a thang"
38 | },
39 | {
40 | 'ruleId': 'MORFOLOGIK_RULE_EN_US',
41 | 'message': 'Possible spelling mistake found.',
42 | 'replacements': [
43 | 'than', 'thing', 'Zhang', 'hang', 'thank', 'Chang', 'tang', 'thong',
44 | 'twang', 'Thant', 'thane', 'Jhang', 'Shang', 'Thanh', 'bhang',
45 | ],
46 | 'offsetInContext': 19,
47 | 'context': "ain't nothin but a thang",
48 | 'offset': 19, 'errorLength': 5,
49 | 'category': 'TYPOS', 'ruleIssueType': 'misspelling',
50 | 'sentence': "ain't nothin but a thang"
51 | }
52 | ]
53 |
54 | assert len(matches) == len(expected_matches)
55 | for match_i, match in enumerate(matches):
56 | assert isinstance(match, language_tool_python.Match)
57 | for key in [
58 | 'ruleId', 'message', 'offsetInContext',
59 | 'context', 'offset', 'errorLength', 'category', 'ruleIssueType',
60 | 'sentence'
61 | ]:
62 | assert expected_matches[match_i][key] == getattr(match, key)
63 |
64 | # For replacements we allow some flexibility in the order
65 | # of the suggestions depending on the version of LT.
66 | for key in [
67 | 'replacements',
68 | ]:
69 | assert (
70 | set(expected_matches[match_i][key]) == set(getattr(match, key))
71 | )
72 |
73 |
74 | def test_process_starts_and_stops_in_context_manager():
75 | import language_tool_python
76 | with language_tool_python.LanguageTool("en-US") as tool:
77 | proc: subprocess.Popen = tool._server
78 | # Make sure process is running before killing language tool object.
79 | assert proc.poll() is None, "tool._server not running after creation"
80 | # Make sure process stopped after close() was called.
81 | assert proc.poll() is not None, "tool._server should stop running after deletion"
82 |
83 |
84 | def test_process_starts_and_stops_on_close():
85 | import language_tool_python
86 | tool = language_tool_python.LanguageTool("en-US")
87 | proc: subprocess.Popen = tool._server
88 | # Make sure process is running before killing language tool object.
89 | assert proc.poll() is None, "tool._server not running after creation"
90 | tool.close() # Explicitly close() object so process stops before garbage collection.
91 | del tool
92 | # Make sure process stopped after close() was called.
93 | assert proc.poll() is not None, "tool._server should stop running after deletion"
94 | # remember --> if poll is None: # p.subprocess is alive
95 |
96 |
97 | def test_local_client_server_connection():
98 | import language_tool_python
99 | with language_tool_python.LanguageTool('en-US', host='127.0.0.1') as tool1:
100 | url = 'http://{}:{}/'.format(tool1._host, tool1._port)
101 | with language_tool_python.LanguageTool('en-US', remote_server=url) as tool2:
102 | assert len(tool2.check('helo darknes my old frend'))
103 |
104 |
105 | def test_config_text_length():
106 | import language_tool_python
107 | with language_tool_python.LanguageTool('en-US', config={'maxTextLength': 12 }) as tool:
108 | # With this config file, checking text with >12 characters should raise an error.
109 | error_msg = re.escape("Error: Your text exceeds the limit of 12 characters (it's 27 characters). Please submit a shorter text.")
110 | with pytest.raises(LanguageToolError, match=error_msg):
111 | tool.check('Hello darkness my old frend')
112 | # But checking shorter text should work fine.
113 | # (should have 1 match for this one)
114 | assert len(tool.check('Hello darkne'))
115 |
116 |
117 | def test_config_caching():
118 | import language_tool_python
119 | with language_tool_python.LanguageTool('en-US', config={'cacheSize': 1000, 'pipelineCaching': True}) as tool:
120 | s = 'hello darkness my old frend'
121 | t1 = time.time()
122 | tool.check(s)
123 | t2 = time.time()
124 | tool.check(s)
125 | t3 = time.time()
126 |
127 | # This is a silly test that says: caching should speed up a grammary-checking by a factor
128 | # of speed_factor when checking the same sentence twice. It theoretically could be very flaky.
129 | # But in practice I've observed speedup of around 250x (6.76s to 0.028s).
130 | speedup_factor = 10.0
131 | assert (t2 - t1) / speedup_factor > (t3 - t2)
132 |
133 |
134 | def test_langtool_languages():
135 | import language_tool_python
136 | with language_tool_python.LanguageTool("en-US") as tool:
137 | assert tool._get_languages().issuperset(
138 | {
139 | 'es-AR', 'ast-ES', 'fa', 'ar', 'ja', 'pl', 'en-ZA', 'sl', 'be-BY',
140 | 'gl', 'de-DE-x-simple-language-DE', 'ga', 'da-DK',
141 | 'ca-ES-valencia', 'eo', 'pt-PT', 'ro', 'fr-FR', 'sv-SE', 'br-FR',
142 | 'es-ES', 'be', 'de-CH', 'pl-PL', 'it-IT',
143 | 'de-DE-x-simple-language', 'en-NZ', 'sv', 'auto', 'km', 'pt',
144 | 'da', 'ta-IN', 'de', 'fa-IR', 'ca', 'de-AT', 'de-DE', 'sk', 'ta',
145 | 'uk', 'en-US', 'zh', 'uk-UA', 'pt-AO', 'el-GR', 'br',
146 | 'ca-ES-balear', 'fr', 'sk-SK', 'pt-BR', 'ro-RO', 'it', 'es',
147 | 'ru-RU', 'km-KH', 'en-GB', 'sl-SI', 'gl-ES', 'pt-MZ', 'nl', 'el',
148 | 'ca-ES', 'zh-CN', 'de-LU', 'nl-NL', 'ja-JP', 'ast', 'tl', 'ga-IE',
149 | 'en-AU', 'en', 'ru', 'nl-BE', 'en-CA', 'tl-PH'
150 | }
151 | )
152 |
153 |
154 | def test_match():
155 | import language_tool_python
156 | with language_tool_python.LanguageTool('en-US') as tool:
157 | text = u'A sentence with a error in the Hitchhiker’s Guide tot he Galaxy'
158 | matches = tool.check(text)
159 | assert len(matches) == 2
160 | assert str(matches[0]) == (
161 | 'Offset 16, length 1, Rule ID: EN_A_VS_AN\n'
162 | 'Message: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.\n'
163 | 'Suggestion: an\n'
164 | 'A sentence with a error in the Hitchhiker’s Guide tot he ...'
165 | '\n ^'
166 | )
167 |
168 |
169 | def test_uk_typo():
170 | import language_tool_python
171 | with language_tool_python.LanguageTool("en-UK") as tool:
172 | sentence1 = "If you think this sentence is fine then, your wrong."
173 | results1 = tool.check(sentence1)
174 | assert len(results1) == 1
175 | assert language_tool_python.utils.correct(sentence1, results1) == "If you think this sentence is fine then, you're wrong."
176 |
177 | results2 = tool.check("You're mum is called Emily, is that right?")
178 | assert len(results2) == 0
179 |
180 |
181 | def test_remote_es():
182 | import language_tool_python
183 | try:
184 | with language_tool_python.LanguageToolPublicAPI('es') as tool:
185 | es_text = 'Escriba un texto aquí. LanguageTool le ayudará a afrentar algunas dificultades propias de la escritura. Se a hecho un esfuerzo para detectar errores tipográficos, ortograficos y incluso gramaticales. También algunos errores de estilo, a grosso modo.'
186 | matches = tool.check(es_text)
187 | assert str(matches) == """[Match({'ruleId': 'AFRENTAR_DIFICULTADES', 'message': 'Confusión entre «afrontar» y «afrentar».', 'replacements': ['afrontar'], 'offsetInContext': 43, 'context': '...n texto aquí. LanguageTool le ayudará a afrentar algunas dificultades propias de la escr...', 'offset': 49, 'errorLength': 8, 'category': 'INCORRECT_EXPRESSIONS', 'ruleIssueType': 'grammar', 'sentence': 'LanguageTool le ayudará a afrentar algunas dificultades propias de la escritura.'}), Match({'ruleId': 'PRON_HABER_PARTICIPIO', 'message': 'El v. ‘haber’ se escribe con hache.', 'replacements': ['ha'], 'offsetInContext': 43, 'context': '...ificultades propias de la escritura. Se a hecho un esfuerzo para detectar errores...', 'offset': 107, 'errorLength': 1, 'category': 'MISSPELLING', 'ruleIssueType': 'misspelling', 'sentence': 'Se a hecho un esfuerzo para detectar errores tipográficos, ortograficos y incluso gramaticales.'}), Match({'ruleId': 'MORFOLOGIK_RULE_ES', 'message': 'Se ha encontrado un posible error ortográfico.', 'replacements': ['ortográficos', 'ortográficas', 'ortográfico', 'orográficos', 'ortografiaos', 'ortografíeos'], 'offsetInContext': 43, 'context': '...rzo para detectar errores tipográficos, ortograficos y incluso gramaticales. También algunos...', 'offset': 163, 'errorLength': 12, 'category': 'TYPOS', 'ruleIssueType': 'misspelling', 'sentence': 'Se a hecho un esfuerzo para detectar errores tipográficos, ortograficos y incluso gramaticales.'}), Match({'ruleId': 'Y_E_O_U', 'message': 'Cuando precede a palabras que comienzan por ‘i’, la conjunción ‘y’ se transforma en ‘e’.', 'replacements': ['e'], 'offsetInContext': 43, 'context': '...ctar errores tipográficos, ortograficos y incluso gramaticales. También algunos e...', 'offset': 176, 'errorLength': 1, 'category': 'GRAMMAR', 'ruleIssueType': 'grammar', 'sentence': 'Se a hecho un esfuerzo para detectar errores tipográficos, ortograficos y incluso gramaticales.'}), Match({'ruleId': 'GROSSO_MODO', 'message': 'Esta expresión latina se usa sin preposición.', 'replacements': ['grosso modo'], 'offsetInContext': 43, 'context': '...les. También algunos errores de estilo, a grosso modo.', 'offset': 235, 'errorLength': 13, 'category': 'GRAMMAR', 'ruleIssueType': 'grammar', 'sentence': 'También algunos errores de estilo, a grosso modo.'})]"""
188 | except RateLimitError:
189 | print("Rate limit error: skipping test about public API.")
190 | return
191 |
192 |
193 | def test_correct_en_us():
194 | import language_tool_python
195 | with language_tool_python.LanguageTool('en-US') as tool:
196 | matches = tool.check('cz of this brand is awsome,,i love this brand very much')
197 | assert len(matches) == 4
198 |
199 | assert tool.correct('cz of this brand is awsome,,i love this brand very much') == 'CZ of this brand is awesome,I love this brand very much'
200 |
201 |
202 | def test_spellcheck_en_gb():
203 | import language_tool_python
204 |
205 | s = 'Wat is wrong with the spll chker'
206 |
207 | # Correct a sentence with spell-checking
208 | with language_tool_python.LanguageTool('en-GB') as tool:
209 | assert tool.correct(s) == "Was is wrong with the sell cheer"
210 |
211 | # Correct a sentence without spell-checking
212 | tool.disable_spellchecking()
213 | assert tool.correct(s) == "Wat is wrong with the spll chker"
214 |
215 |
216 | def test_session_only_new_spellings():
217 | import os
218 | import hashlib
219 | import language_tool_python
220 | library_path = language_tool_python.utils.get_language_tool_directory()
221 | spelling_file_path = os.path.join(
222 | library_path, "org/languagetool/resource/en/hunspell/spelling.txt"
223 | )
224 | with open(spelling_file_path, 'r') as spelling_file:
225 | initial_spelling_file_contents = spelling_file.read()
226 | initial_checksum = hashlib.sha256(initial_spelling_file_contents.encode())
227 |
228 | new_spellings = ["word1", "word2", "word3"]
229 | with language_tool_python.LanguageTool(
230 | 'en-US', newSpellings=new_spellings, new_spellings_persist=False
231 | ) as tool:
232 | tool.enabled_rules_only = True
233 | tool.enabled_rules = {'MORFOLOGIK_RULE_EN_US'}
234 | matches = tool.check(" ".join(new_spellings))
235 |
236 | with open(spelling_file_path, 'r') as spelling_file:
237 | subsequent_spelling_file_contents = spelling_file.read()
238 | subsequent_checksum = hashlib.sha256(
239 | subsequent_spelling_file_contents.encode()
240 | )
241 |
242 | if initial_checksum != subsequent_checksum:
243 | with open(spelling_file_path, 'w') as spelling_file:
244 | spelling_file.write(initial_spelling_file_contents)
245 |
246 | assert not matches
247 | assert initial_checksum.hexdigest() == subsequent_checksum.hexdigest()
248 |
249 |
250 | def test_disabled_rule_in_config():
251 | import language_tool_python
252 | GRAMMAR_TOOL_CONFIG = {
253 | 'disabledRuleIds': ['MORFOLOGIK_RULE_EN_US']
254 | }
255 | with language_tool_python.LanguageTool('en-US', config=GRAMMAR_TOOL_CONFIG) as tool:
256 | text = "He realised that the organization was in jeopardy."
257 | matches = tool.check(text)
258 | assert len(matches) == 0
259 |
260 | def test_special_char_in_text():
261 | import language_tool_python
262 | with language_tool_python.LanguageTool('en-US') as tool:
263 | text = "The sun was seting 🌅, casting a warm glow over the park. Birds chirpped softly 🐦 as the day slowly fade into night."
264 | assert tool.correct(text) == "The sun was setting 🌅, casting a warm glow over the park. Birds chipped softly 🐦 as the day slowly fade into night."
265 |
266 | def test_install_inexistent_version():
267 | import language_tool_python
268 | with pytest.raises(LanguageToolError):
269 | language_tool_python.LanguageTool(language_tool_download_version="0.0")
270 |
271 | def test_inexistant_language():
272 | import language_tool_python
273 | with language_tool_python.LanguageTool("en-US") as tool:
274 | with pytest.raises(ValueError):
275 | language_tool_python.LanguageTag("xx-XX", tool._get_languages())
276 |
277 |
278 | def test_debug_mode():
279 | from language_tool_python.server import DEBUG_MODE
280 | assert DEBUG_MODE is False
281 |
--------------------------------------------------------------------------------
/tests/test_remote.bash:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -eux
4 |
5 | readonly port=8081
6 | readonly ltp_path=$(printf "import language_tool_python\nprint(language_tool_python.utils.get_language_tool_download_path())\n" | python)
7 | readonly jar="${ltp_path}/LanguageTool-*/languagetool-server.jar"
8 |
9 | java -cp $jar org.languagetool.server.HTTPServer --port "$port" &
10 | java_pid=$!
11 | sleep 5
12 |
13 | clean ()
14 | {
15 | kill "$java_pid"
16 | }
17 | trap clean EXIT
18 |
19 | exit_status=0
20 |
21 | echo 'This is okay.' | \
22 | python -m language_tool_python --remote-host localhost --remote-port "$port" - || exit_status=1
23 |
24 | echo 'This is noot okay.' | \
25 | python -m language_tool_python --remote-host localhost --remote-port "$port" - && exit_status=1
26 |
27 | exit "$exit_status"
28 |
--------------------------------------------------------------------------------