summaryrefslogtreecommitdiffstats
path: root/languagetool/TextCheckerCGI.py
blob: 750d2ecf892e91dee6baa5629b2c11ac1263d8dd (plain)
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
#
# LanguageTool -- A Rule-Based Style and Grammar Checker
# Copyright (C) 2002,2003,2004 Daniel Naber <daniel.naber@t-online.de>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import cgi
import string
import sys
import os

os.chdir(sys.path[0])
sys.path.append(sys.path[0])
sys.path.append(os.path.join(sys.path[0], "src"))

import TagInfo
import TextChecker

# FIXME: for debugging only
import cgitb
cgitb.enable()

def main():
	form = cgi.FieldStorage()
	if form.getvalue("text"):
		check(form)
	elif form.getvalue("explain"):
		displayExplanation(form)
	else:
		displayForm(form)
	return	

def displayExplanation(form):
	print "Content-Type: text/html\n\n"
	tag = cgi.escape(form.getvalue("explain"))	# security: anti XSS
	taginfo = TagInfo.TagInfo(form.getvalue("lang"))
	print """<html><head>
		<title>LanguageTool: Tag explanation for %s</title>
		</head>
		<body>
		<h1>Tag explanation for %s</h1>

		<p><strong>%s:</strong> %s</p>
		
		</body></html>""" % (tag, tag, tag, taginfo.getExp(form.getvalue("explain")))
	return

def displayForm(form):
	print "Content-Type: text/html\n\n"
	print """<html><head>
		<title>LanguageTool Web Interface</title>
		<style rel='stylesheet'>
			<!--
			.error { font-weight: bold; color: red; }
			-->
		</style>
		</head>
		<body>
		<h1>LanguageTool Web Interface</h1>
		Enter text here:<br />
		<form action="/cgi-bin/languagetool/TextCheckerCGI.py" method="post">
			<textarea name="text" rows="8" cols="80"></textarea><br />
			<select name="lang">
				<option value="en">English</option>
				<option value="de">German</option>
				<option value="hu">Hungarian (experimental)</option>
			</select><br />
			<input type="checkbox" name="tags" checked="checked"> Show part-of-speech tags
			<input type="checkbox" name="german_ff" checked="checked"> Check for false friends (for German native speakers)<br />
			<input type="checkbox" name="style"> Check for some style issues (e.g. <em>don't</em> instead of <em>do not</em>)<br />
			<input type="checkbox" name="sentencelength"> Complain about long sentences (more than 30 words)
			<br />
			<input type="submit" value="Check Text">
		</form>
		<p><strong>Suggested test text</strong><br>
		The incorrect words are <span class="error">red</span> (copy and paste 
		into text field to try it):</p>

		<p>Then he <span class="error">look</span> at the building.<br>
		I definitely think <span class="error">is</span> should be less than four years.<br>
		This allows to provide a powerful <span class="error">a</span> help system.<br>
		His house is as big <span class="error">like</span> mine.<br>
		His car is larger <span class="error">then</span> mine.
		</p>
		<hr>
		<a href="http://www.danielnaber.de/languagetool/">LanguageTool Homepage</a>
		</body></html>"""
	return
	
def check(form):
	print "Content-Type: text/html\n\n"
	text = form.getvalue("text").decode('latin1')
	if not text:
		text = ""
	# TODO: put options for alle these in the web page? too confusing...
	grammar = None
	falsefriends = None
	words = None
	builtin = None
	textlanguage = "en"
	if not form.getvalue("style"):
		words = ["__NONE"]
	mothertongue = "de"
	if not form.getvalue("german_ff"):
		mothertongue = None
	if form.getvalue("lang"):
		textlanguage = form.getvalue("lang")
	max_sentence_length = 0
	if form.getvalue("sentencelength"):
		max_sentence_length = None
	checker = TextChecker.TextChecker(grammar, falsefriends, words, builtin, \
		textlanguage, mothertongue, max_sentence_length)

	print """<html><head>
		<title>Check result</title>
		<style rel='stylesheet'>
			<!--
			.tag { color: grey; }
			.error { font-weight: bold; color: red; }
			.expl { color: blue; }
			.repl { font-weight: bold; }
			-->
			</style>
		<script language="javascript">
			<!--
			var data = new Array();
			"""
	taginfo = TagInfo.TagInfo(textlanguage)
	print taginfo.getJavascriptCode()
	print """
			function info(s) {	
				alert(s + ": " + data[s]);
			}
			//-->
		</script>
		</head>
		<body>
		<h1>Result</h1>"""

	(rule_matches, res, tags) = checker.check(text)
	# TODO: add an option to print the complete checker XML response:
	#print "XML reply:<br><pre>%s</pre>" % cgi.escape(res)
	#print "<pre>%s</pre>" % tags
	taglist = []
	char_count = 0
	list_count = 0
	text_list = []
	for tag_triple in tags:
		tag_str = ""
		if form.getvalue("tags") and tag_triple[2]:
			w = tag_triple[2]
			tag_str = '<span class="tag"><a href="TextCheckerCGI.py?explain=%s&amp;lang=%s" \
				onclick="info(\'%s\');return false;">[%s]</a></span>' \
				% (w, textlanguage, w, w)
			if tag_triple[2] == 'SENT_END':
				tag_str = '%s<br>\n' % tag_str
		word = cgi.escape(tag_triple[0])
		text_list.append(word)
		text_list.append(tag_str)
		char_count = char_count + len(word)
	# guarantee that the rule_matches are ordered by their position:
	rule_matches.sort()
	rule_matches.reverse()	# add messages from end of list to avoid count confusion
	for rule_match in rule_matches:
		# TODO: this produces invalid code if the rule ranges are nested!
		ct = 0
		i = 0
		start_found = 0
		end_found = 0
		for el in text_list:
			if not el.startswith("<span"):
				from_pos = ct
				to_pos = ct + len(el)
				if rule_match.to_pos <= to_pos and rule_match.to_pos >= from_pos and not end_found:
					text_list[i] = '%s</span><span class="expl">[%s (%s)]</span>' % (text_list[i], \
						rule_match.message, rule_match.id)
					end_found = 1
				elif rule_match.from_pos <= to_pos and rule_match.from_pos >= from_pos and not start_found:
					text_list[i] = '<span class="error">%s' % text_list[i]
					start_found = 1
				ct = ct + len(el)
			if end_found and start_found:
				break
			i = i + 1
	text = string.join(text_list, '')
	print text.encode('latin1')

	if len(rule_matches) == 1:
		print "<p>%d possible error found.</p>" % len(rule_matches)
	else:
		print "<p>%d possible errors found.</p>" % len(rule_matches)
	
	#print "<p>" + cgi.escape(res)
	print "</body></html>"

main()