Skip to content

Commit 357c45a

Browse files
committed
reformat code and docstrings
1 parent 7e20002 commit 357c45a

File tree

4 files changed

+72
-47
lines changed

4 files changed

+72
-47
lines changed

docs/api_docs.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ CLI
1111
---
1212

1313

14-
.. automodule:: pylanguagetool
14+
.. automodule:: pylanguagetool.cli
1515
:members:
1616

1717
Converters

pylanguagetool/api.py

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,21 @@
99
... api_url='https://languagetool.org/api/v2/',
1010
... lang='en-US',
1111
... )
12-
{'software': {'name': 'LanguageTool', 'version': '4.6-SNAPSHOT', 'buildDate': '2019-05-15 19:25', 'apiVersion': 1, 'premium': False, 'premiumHint': 'You might be missing errors only the Premium version can find. Contact us at support<at>languagetoolplus.com.', 'status': ''}, 'warnings': {'incompleteResults': False}, 'language': {'name': 'English (US)', 'code': 'en-US', 'detectedLanguage': {'name': 'English (US)', 'code': 'en-US', 'confidence': 0.561}}, 'matches': [{'message': 'Use "an" instead of \'a\' if the following word starts with a vowel sound, e.g. \'an article\', \'an hour\'', 'shortMessage': 'Wrong article', 'replacements': [{'value': 'an'}], 'offset': 8, 'length': 1, 'context': {'text': 'This is a example', 'offset': 8, 'length': 1}, 'sentence': 'This is a example', 'type': {'typeName': 'Other'}, 'rule': {'id': 'EN_A_VS_AN', 'description': "Use of 'a' vs. 'an'", 'issueType': 'misspelling', 'category': {'id': 'MISC', 'name': 'Miscellaneous'}}, 'ignoreForIncompleteSentence': False, 'contextForSureMatch': 1}]}
13-
1412
"""
13+
from typing import Optional
14+
1515
import requests
1616

1717

18-
def get_languages(api_url):
18+
def get_languages(api_url: str) -> list[dict[str, str]]:
1919
"""
2020
Return supported languages as a list of dictionaries.
2121
2222
Args:
2323
api_url (str): API base url.
2424
2525
Returns:
26-
List[dict]:
26+
list[dict]:
2727
Supported languages as a list of dictionaries.
2828
2929
Each dictionary contains three keys, ``name``, ``code`` and
@@ -47,11 +47,15 @@ def _is_in_pwl(match, pwl):
4747
return word in pwl
4848

4949

50-
def check(input_text, api_url, lang, mother_tongue=None, preferred_variants=None,
51-
enabled_rules=None, disabled_rules=None,
52-
enabled_categories=None, disabled_categories=None,
53-
enabled_only=False, picky=False, verbose=False,
54-
pwl=None, username=None, api_key=None):
50+
def check(
51+
input_text: str, api_url: str,
52+
lang: str, pwl: list[str],
53+
mother_tongue: Optional[str] = None,
54+
preferred_variants: Optional[str] = None,
55+
enabled_rules: Optional[str] = None, disabled_rules: Optional[str] = None,
56+
enabled_categories: Optional[str] = None, disabled_categories: Optional[str] = None,
57+
enabled_only: bool = False, picky: bool = False, verbose: bool = False,
58+
username: Optional[str] = None, api_key: Optional[str] = None):
5559
"""
5660
Check given text and return API response as a dictionary.
5761
@@ -105,7 +109,7 @@ def check(input_text, api_url, lang, mother_tongue=None, preferred_variants=None
105109
If ``True``, a more verbose output will be printed. Defaults to
106110
``False``.
107111
108-
pwl (List[str]):
112+
pwl (list[str]):
109113
Personal world list. A custom dictionary of words that should be
110114
excluded from spell checking errors.
111115
@@ -125,30 +129,38 @@ def check(input_text, api_url, lang, mother_tongue=None, preferred_variants=None
125129
126130
{
127131
"language": {
128-
"code": "en-US",
132+
"name": "English (GB)",
133+
"code": "en-GB",
129134
"detectedLanguage": {
130-
"code": "en-US",
135+
"name": "English (GB)",
136+
"code": "en-GB",
131137
"confidence": 0.561,
132-
"name": "English (US)",
138+
"source": "fasttext",
133139
},
134-
"name": "English (US)",
135140
},
141+
"sentenceRanges": [[0, 17]],
142+
"extendedSentenceRanges": [
143+
{"from": 0, "to": 17, "detectedLanguages": [{"language": "en", "rate": 1.0}]}
144+
],
136145
"matches": [
137146
{
138-
"context": {"length": 1, "offset": 8, "text": "This is a example"},
147+
"context": {"text": "This is a example", "offset": 8, "length": 1},
139148
"contextForSureMatch": 1,
140149
"ignoreForIncompleteSentence": False,
141150
"length": 1,
142-
"message": "Use \"an\" instead of 'a' if the following word "
143-
"starts with a vowel sound, e.g. 'an article', 'an "
144-
"hour'",
151+
"message": "Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g.\xa0‘an article’, ‘an hour’.",
145152
"offset": 8,
146153
"replacements": [{"value": "an"}],
147154
"rule": {
148155
"category": {"id": "MISC", "name": "Miscellaneous"},
149156
"description": "Use of 'a' vs. 'an'",
150157
"id": "EN_A_VS_AN",
151158
"issueType": "misspelling",
159+
"urls": [
160+
{
161+
"value": "https://languagetool.org/insights/post/indefinite-articles/"
162+
}
163+
],
152164
},
153165
"sentence": "This is a example",
154166
"shortMessage": "Wrong article",
@@ -157,14 +169,12 @@ def check(input_text, api_url, lang, mother_tongue=None, preferred_variants=None
157169
],
158170
"software": {
159171
"apiVersion": 1,
160-
"buildDate": "2019-05-15 19:25",
172+
"buildDate": "2024-09-27 11:27:57 +0200",
173+
"version": "6.5",
161174
"name": "LanguageTool",
162175
"premium": False,
163-
"premiumHint": "You might be missing errors only the Premium "
164-
"version can find. Contact us at "
165-
"support<at>languagetoolplus.com.",
176+
"premiumHint": "You might be missing errors only the Premium version can find. Contact us at support<at>languagetoolplus.com.",
166177
"status": "",
167-
"version": "4.6-SNAPSHOT",
168178
},
169179
"warnings": {"incompleteResults": False},
170180
}
@@ -212,4 +222,5 @@ def check(input_text, api_url, lang, mother_tongue=None, preferred_variants=None
212222
match for match in matches
213223
if not _is_in_pwl(match, pwl)
214224
]
225+
print(print(data))
215226
return data

pylanguagetool/cli.py

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,22 @@
55
import sys
66
from importlib.metadata import version
77
from pprint import pprint
8+
from typing import Any, Optional
89

9-
import configargparse
1010
from colorama import Fore, init as init_colors
11+
from configargparse import ArgumentParser
1112

1213
from pylanguagetool import converters, CustomConfigFileParser, api
1314

1415
indention = " " * 4
1516

1617

17-
def init_config():
18-
p = configargparse.ArgParser(default_config_files=["~/.config/pyLanguagetool.conf"],
19-
config_file_parser_class=CustomConfigFileParser)
18+
def init_config() -> tuple[dict[str, Any], ArgumentParser]:
19+
"""
20+
Create ArgumentParser object
21+
"""
22+
p = ArgumentParser(default_config_files=["~/.config/pyLanguagetool.conf"],
23+
config_file_parser_class=CustomConfigFileParser)
2024
p.add_argument("-V", "--version", default=False, action='store_true', help="print version and exit")
2125
p.add_argument("-v", "--verbose", env_var="VERBOSE", default=False, action='store_true', help="verbose output")
2226
p.add_argument("-a", "--api-url", env_var="API_URL", default="https://languagetool.org/api/v2/",
@@ -83,7 +87,7 @@ def init_config():
8387
return c, p
8488

8589

86-
def get_clipboard():
90+
def get_clipboard() -> str:
8791
"""
8892
Return text stored in the operating system's clipboard.
8993
@@ -101,12 +105,12 @@ def get_clipboard():
101105
return clipboard
102106

103107

104-
def get_input_text(config):
108+
def get_input_text(config: dict[str, Any]) -> tuple[Optional[str], Optional[str]]:
105109
"""
106110
Return text from stdin, clipboard or file.
107111
108112
Returns:
109-
Tuple[str, str]:
113+
tuple[Optional[str], Optional[str]]:
110114
A tuple contain of the text and an optional file extension.
111115
If the text does not come from a file, the extension part of the
112116
tuple will be none.
@@ -128,7 +132,11 @@ def get_input_text(config):
128132
sys.exit(1)
129133

130134

131-
def print_errors(response, api_url, print_color=True, rules=False, rule_categories=False, explain_rule=False):
135+
def print_errors(response, api_url: str, print_color: bool = True, rules: bool = False,
136+
rule_categories: bool = False, explain_rule: bool = False) -> None:
137+
"""
138+
Print output from API response
139+
"""
132140
matches = response["matches"]
133141
language = response["language"]
134142
version = response["software"]["name"] + " " + response["software"]["version"]
@@ -140,13 +148,14 @@ def colored(text, color):
140148
else:
141149
return text
142150

151+
lang_name = language["detectedLanguage"]["name"]
152+
lang_confidence = language["detectedLanguage"]["confidence"] * 100
143153
print(colored(
144-
"{} detected ({:.0f}% confidence)".format(language["detectedLanguage"]["name"],
145-
language["detectedLanguage"]["confidence"] * 100)
154+
f"{lang_name} detected ({lang_confidence:.0f}% confidence)"
146155
, Fore.LIGHTBLACK_EX))
147156
if language["detectedLanguage"]["code"] != language["code"]:
148157
print(colored(
149-
"checking as {} text because of setting".format(language["name"])
158+
f"checking as {language['name']} text because of setting"
150159
, Fore.LIGHTBLACK_EX))
151160
print()
152161

@@ -212,7 +221,10 @@ def colored(text, color):
212221
print(colored(f"Text checked by {api_url} ({version})", Fore.LIGHTBLACK_EX))
213222

214223

215-
def main():
224+
def main() -> None:
225+
"""
226+
The main CLI entry point.
227+
"""
216228
config, argparser = init_config()
217229

218230
if config["verbose"]:
@@ -221,6 +233,8 @@ def main():
221233
if config['pwl']:
222234
with open(config['pwl']) as fs:
223235
config['pwl'] = [w.strip() for w in fs.readlines()]
236+
else:
237+
config['pwl'] = []
224238

225239
input_text, inputtype = get_input_text(config)
226240
if not input_text:
@@ -234,7 +248,7 @@ def main():
234248
print("But it doesn't have to:")
235249
print("You can simply use the output of detex")
236250
if config["input file"]:
237-
print(" $ detex {} | pylanguagetool".format(config["input file"]))
251+
print(f" $ detex {config['input file']} | pylanguagetool")
238252
print("or use the languagetool integration in TeXstudio.")
239253
sys.exit(3)
240254
check_text = converters.convert(input_text, inputtype)

pylanguagetool/converters.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
supported_extensions = ["txt", "html", "md", "markdown", "rst", "ipynb", "json", "xliff"]
1010

1111

12-
def convert(source, texttype):
12+
def convert(source: str, texttype: str) -> str:
1313
"""
1414
Convert files of various types to plaintext
1515
@@ -40,7 +40,7 @@ def convert(source, texttype):
4040
return source
4141

4242

43-
def html2text(html):
43+
def html2text(html: str) -> str:
4444
"""
4545
convert HTML to plaintext by parsing it with BeautifulSoup and removing code
4646
@@ -63,7 +63,7 @@ def html2text(html):
6363
return soup.get_text()
6464

6565

66-
def markdown2html(markdown):
66+
def markdown2html(markdown: str) -> str:
6767
"""
6868
convert Markdown to HTML via ``markdown2``
6969
@@ -83,7 +83,7 @@ def markdown2html(markdown):
8383
return markdown2.markdown(markdown)
8484

8585

86-
def ipynb2markdown(ipynb):
86+
def ipynb2markdown(ipynb: str) -> str:
8787
"""
8888
Extract Markdown cells from iPython Notebook
8989
@@ -102,7 +102,7 @@ def ipynb2markdown(ipynb):
102102
return markdown
103103

104104

105-
def rst2html(rst):
105+
def rst2html(rst: str) -> str:
106106
"""
107107
convert reStructuredText to HTML with ``docutils``
108108
@@ -121,7 +121,7 @@ def rst2html(rst):
121121
return publish_string(rst, writer_name="html5")
122122

123123

124-
def transifexjson2txt(jsondata):
124+
def transifexjson2txt(jsondata: str) -> str:
125125
"""
126126
extract translations from Transifex JSON file
127127
@@ -141,7 +141,7 @@ def transifexjson2txt(jsondata):
141141
return text
142142

143143

144-
def xliff2txt(source):
144+
def xliff2txt(source: str) -> str:
145145
"""
146146
extract translations from ``XLIFF`` file
147147
@@ -164,9 +164,9 @@ def xliff2txt(source):
164164
return text
165165

166166

167-
def notinstalled(package, convert_from, convert_to):
167+
def notinstalled(package: str, convert_from: str, convert_to: str) -> None:
168168
print(
169-
"""{package} is needed to convert {source} to {target}
169+
f"""{package} is needed to convert {convert_from} to {convert_to}
170170
you can install it with pip:
171-
pip install {package}""".format(package=package, source=convert_from, target=convert_to)
171+
pip install {package}"""
172172
)

0 commit comments

Comments
 (0)