This repository has been archived by the owner on Aug 27, 2018. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathginger.py
145 lines (118 loc) · 3.98 KB
/
ginger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple grammar checker
This grammar checker will fix grammar mistakes using Ginger.
"""
import sys
import urllib.parse
import urllib.request
from urllib.error import HTTPError
from urllib.error import URLError
import json
class ColoredText:
"""Colored text class"""
colors = ['black', 'red', 'green', 'orange', 'blue', 'magenta', 'cyan', 'white']
color_dict = {}
for i, c in enumerate(colors):
color_dict[c] = (i + 30, i + 40)
@classmethod
def colorize(cls, text, color=None, bgcolor=None):
"""Colorize text
@param cls Class
@param text Text
@param color Text color
@param bgcolor Background color
"""
c = None
bg = None
gap = 0
if color is not None:
try:
c = cls.color_dict[color][0]
except KeyError:
print("Invalid text color:", color)
return(text, gap)
if bgcolor is not None:
try:
bg = cls.color_dict[bgcolor][1]
except KeyError:
print("Invalid background color:", bgcolor)
return(text, gap)
s_open, s_close = '', ''
if c is not None:
s_open = '\033[%dm' % c
gap = len(s_open)
if bg is not None:
s_open += '\033[%dm' % bg
gap = len(s_open)
if not c is None or bg is None:
s_close = '\033[0m'
gap += len(s_close)
return('%s%s%s' % (s_open, text, s_close), gap)
def get_ginger_url(text):
"""Get URL for checking grammar using Ginger.
@param text English text
@return URL
"""
API_KEY = "6ae0c3a0-afdc-4532-a810-82ded0054236"
scheme = "http"
netloc = "services.gingersoftware.com"
path = "/Ginger/correct/json/GingerTheText"
params = ""
query = urllib.parse.urlencode([
("lang", "US"),
("clientVersion", "2.0"),
("apiKey", API_KEY),
("text", text)])
fragment = ""
return(urllib.parse.urlunparse((scheme, netloc, path, params, query, fragment)))
def get_ginger_result(text):
"""Get a result of checking grammar.
@param text English text
@return result of grammar check by Ginger
"""
url = get_ginger_url(text)
try:
response = urllib.request.urlopen(url)
except HTTPError as e:
print("HTTP Error:", e.code)
quit()
except URLError as e:
print("URL Error:", e.reason)
quit()
try:
result = json.loads(response.read().decode('utf-8'))
except ValueError:
print("Value Error: Invalid server response.")
quit()
return(result)
def main():
"""main function"""
original_text = " ".join(sys.argv[1:])
if len(original_text) > 600:
print("You can't check more than 600 characters at a time.")
quit()
fixed_text = original_text
results = get_ginger_result(original_text)
# Correct grammar
if(not results["LightGingerTheTextResult"]):
print("Good English :)")
quit()
# Incorrect grammar
color_gap, fixed_gap = 0, 0
for result in results["LightGingerTheTextResult"]:
if(result["Suggestions"]):
from_index = result["From"] + color_gap
to_index = result["To"] + 1 + color_gap
suggest = result["Suggestions"][0]["Text"]
# Colorize text
colored_incorrect = ColoredText.colorize(original_text[from_index:to_index], 'red')[0]
colored_suggest, gap = ColoredText.colorize(suggest, 'green')
original_text = original_text[:from_index] + colored_incorrect + original_text[to_index:]
fixed_text = fixed_text[:from_index-fixed_gap] + colored_suggest + fixed_text[to_index-fixed_gap:]
color_gap += gap
fixed_gap += to_index-from_index-len(suggest)
print("from: " + original_text)
print("to: " + fixed_text)
if __name__ == '__main__':
main()