Debian Codegraph @

extensions/ConfirmEdit/captcha.py

raw symbols SCIP
1 #!/usr/bin/python3
2 #
3 # Script to generate distorted text images for a captcha system.
4 #
5 # Copyright (C) 2005 Neil Harris
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with this program; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 # http://www.gnu.org/copyleft/gpl.html
21 #
22 # Further tweaks by Brion Vibber <[email protected]>:
23 # 2006-01-26: Add command-line options for the various parameters
24 # 2007-02-19: Add --dirs param for hash subdirectory splits
25 # Tweaks by Greg Sabino Mullane <[email protected]>:
26 # 2008-01-06: Add regex check to skip words containing other than a-z
27
28 from optparse import OptionParser
29 import hashlib
30 import json
31 import math
32 import multiprocessing
33 import os
34 import random
35 import re
36 import sys
37
38 try:
39 from PIL import Image, ImageDraw, ImageEnhance, ImageFont, ImageOps
40 except ImportError:
41 sys.exit(
42 "This script requires the Python Imaging Library - http://www.pythonware.com/products/pil/"
43 )
44
45 # regex to test for suitability of words
46 nonalpha = re.compile("[^a-z]")
47
48 # when il beside each other, hard to read
49 confusedletters = re.compile(
50 "[ijtlr][ijtl]|r[nompqr]|[il]"
51 )
52
53 # Pillow 9.2 added getbbox to replace getsize, and getsize() was removed in Pillow 10
54 # https://pillow.readthedocs.io/en/stable/releasenotes/10.0.0.html#font-size-and-offset-methods
55 # We don't have a requirements.txt, and therefore don't declare any specific supported or min version...
56 IMAGEFONT_HAS_GETBBOX = hasattr(ImageFont.ImageFont, "getbbox")
57
58
59 # Does X-axis wobbly copy, sandwiched between two rotates
60 def wobbly_copy(src, wob, col, scale, ang):
61 x, y = src.size
62 f = random.uniform(4 * scale, 5 * scale)
63 p = random.uniform(0, math.pi * 2)
64 rr = ang + random.uniform(-30, 30) # vary, but not too much
65 int_d = Image.new("RGB", src.size, 0) # a black rectangle
66 rot = src.rotate(rr, Image.BILINEAR)
67 # Do a cheap bounding-box op here to try to limit work below
68 bbx = rot.getbbox()
69 if bbx is None:
70 return src
71 else:
72 l, t, r, b = bbx
73 # and only do lines with content on
74 for i in range(t, b + 1):
75 # Drop a scan line in
76 xoff = int(math.sin(p + (i * f / y)) * wob)
77 xoff += int(random.uniform(-wob * 0.5, wob * 0.5))
78 int_d.paste(rot.crop((0, i, x, i + 1)), (xoff, i))
79 # try to stop blurring from building up
80 int_d = int_d.rotate(-rr, Image.BILINEAR)
81 enh = ImageEnhance.Sharpness(int_d)
82 return enh.enhance(2)
83
84
85 def gen_captcha(text, fontname, fontsize, file_name):
86 """Generate a captcha image"""
87 # white text on a black background
88 bgcolor = 0x0
89 fgcolor = 0xFFFFFF
90 # create a font object
91 font = ImageFont.truetype(fontname, fontsize)
92
93 # determine dimensions of the text
94 if IMAGEFONT_HAS_GETBBOX:
95 dim = font.getbbox(text)[2:]
96 else:
97 dim = font.getsize(text)
98
99 # create a new image significantly larger that the text
100 edge = max(dim[0], dim[1]) + 2 * min(dim[0], dim[1])
101 im = Image.new("RGB", (edge, edge), bgcolor)
102 d = ImageDraw.Draw(im)
103 x, y = im.size
104 # add the text to the image
105 # Using between 5-6 pixels of negative kerning seemed
106 # enough to confuse tesseract but still be very readable
107 offset = 0
108 for c in text:
109 d.text(
110 (x / 2 - dim[0] / 2 + offset, y / 2 - dim[1] / 2 + random.uniform(-3, 7)),
111 c,
112 font=font,
113 fill=fgcolor,
114 )
115 if IMAGEFONT_HAS_GETBBOX:
116 offset += font.getbbox(c)[2:][0]
117 else:
118 offset += font.getsize(c)[0]
119
120 offset -= random.uniform(5, 6)
121
122 for i in range(10):
123 x0 = int(
124 offset * ((i / 2) - 1) / 5
125 + x / 2
126 - dim[0] / 2
127 + random.uniform(0, 10)
128 )
129 y0 = int(y / 2 - dim[1] + 30 + random.uniform(-10, 15))
130
131 x1 = int(offset * i / 7 + x / 2 - dim[0] / 2 + random.uniform(-5, 5))
132 y1 = int(y / 2 - dim[1] + 30 + random.uniform(-10, 30))
133
134 if x1 < x0:
135 x0, x1 = x1, x0
136
137 if y1 < y0:
138 y0, y1 = y1, y0
139
140 d.arc(
141 (x0, y0, x1, y1),
142 int(random.uniform(-30, 30)),
143 int(random.uniform(160, 300)),
144 fill=fgcolor,
145 )
146
147 # now get the bounding box of the nonzero parts of the image
148 bbox = im.getbbox()
149 bord = min(dim[0], dim[1]) / 4 # a bit of a border
150 im = im.crop((bbox[0] - bord, bbox[1] - bord, bbox[2] + bord, bbox[3] + bord))
151
152 # and turn into black on white
153 im = ImageOps.invert(im)
154
155 # save the image, in format determined from filename
156 im.save(file_name)
157
158
159 def gen_subdir(basedir, md5hash, levels):
160 """Generate a subdirectory path out of the first _levels_
161 characters of _hash_, and ensure the directories exist
162 under _basedir_."""
163 subdir = None
164 for i in range(0, levels):
165 char = md5hash[i]
166 if subdir:
167 subdir = os.path.join(subdir, char)
168 else:
169 subdir = char
170 fulldir = os.path.join(basedir, subdir)
171 if not os.path.exists(fulldir):
172 os.mkdir(fulldir)
173 return subdir
174
175
176 def try_pick_word(words, badwordlist, verbose, nwords, min_length, max_length):
177 if words is not None:
178 word = words[random.randint(0, len(words) - 1)]
179 while nwords > 1:
180 word2 = words[random.randint(0, len(words) - 1)]
181 word = word + word2
182 nwords = nwords - 1
183 else:
184 word = ""
185 max_length = max_length if max_length > 0 else 10
186 for i in range(0, random.randint(min_length, max_length)):
187 word = word + chr(97 + random.randint(0, 25))
188
189 if verbose:
190 print("word is %s" % word)
191
192 if len(word) < min_length:
193 if verbose:
194 print(
195 "skipping word pair '%s' because it has fewer than %d characters"
196 % (word, min_length)
197 )
198 return None
199
200 if max_length > 0 and len(word) > max_length:
201 if verbose:
202 print(
203 "skipping word pair '%s' because it has more than %d characters"
204 % (word, max_length)
205 )
206 return None
207
208 if nonalpha.search(word):
209 if verbose:
210 print(
211 "skipping word pair '%s' because it contains non-alphabetic characters"
212 % word
213 )
214 return None
215 if confusedletters.search(word):
216 if verbose:
217 print(
218 "skipping word pair '%s' because it contains confusing letters beside each other"
219 % word
220 )
221 return None
222
223 for naughty in badwordlist:
224 if naughty in word:
225 if verbose:
226 print(
227 "skipping word pair '%s' because it contains word '%s'"
228 % (word, naughty)
229 )
230 return None
231 return word
232
233
234 def pick_word(words, badwordlist, verbose, nwords, min_length, max_length):
235 for x in range(
236 1000
237 ): # If we can't find a valid combination in 1000 tries, just give up
238 word = try_pick_word(
239 words, badwordlist, verbose, nwords, min_length, max_length
240 )
241 if word:
242 return word
243 sys.exit("Unable to find valid word combinations")
244
245
246 def read_wordlist(filename):
247 filename = os.path.expanduser(filename)
248 filename = os.path.expandvars(filename)
249 if not os.path.isfile(filename):
250 return []
251 f = open(filename)
252 words = [x.strip().lower() for x in f.readlines()]
253 f.close()
254 return words
255
256
257 def run_in_thread(object):
258 count = object[0]
259 words = object[1]
260 badwordlist = object[2]
261 opts = object[3]
262 font = object[4]
263 fontsize = object[5]
264 jsonmap = object[6]
265
266 for i in range(count):
267 word = pick_word(
268 words,
269 badwordlist,
270 opts.verbose,
271 opts.number_words,
272 opts.min_length,
273 opts.max_length,
274 )
275 salt = "%08x" % random.randrange(2**32)
276 # 64 bits of hash is plenty for this purpose
277 md5hash = hashlib.md5(
278 (opts.key + salt + word + opts.key + salt).encode("utf-8")
279 ).hexdigest()[:16]
280 filename = "image_%s_%s.png" % (salt, md5hash)
281 if opts.dirs:
282 subdir = gen_subdir(opts.output, md5hash, opts.dirs)
283 filename = os.path.join(subdir, filename)
284 if opts.verbose:
285 print(filename)
286 if opts.jsonmap:
287 jsonmap[filename] = word
288
289 gen_captcha(word, font, fontsize, os.path.join(opts.output, filename))
290
291
292 if __name__ == "__main__":
293 """This grabs random words from the dictionary 'words' (one
294 word per line) and generates a captcha image for each one,
295 with a keyed salted hash of the correct answer in the filename.
296
297 To check a reply, hash it in the same way with the same salt and
298 secret key, then compare with the hash value given.
299 """
300 script_dir = os.path.dirname(os.path.realpath(__file__))
301 parser = OptionParser()
302 parser.add_option(
303 "--wordlist",
304 help="A list of words (required)",
305 metavar="WORDS.txt"
306 )
307 parser.add_option(
308 "--random",
309 help="Use random characters instead of a wordlist",
310 action="store_true",
311 )
312 parser.add_option(
313 "--key",
314 help="The passphrase set as $wgCaptchaSecret (required)",
315 metavar="KEY"
316 )
317 parser.add_option(
318 "--output",
319 help="The directory to put the images in - $wgCaptchaDirectory (required)",
320 metavar="DIR",
321 )
322 parser.add_option(
323 "--font",
324 help="The font to use (required)",
325 metavar="FONT.ttf"
326 )
327 parser.add_option(
328 "--font-size",
329 help="The font size (default 40)",
330 metavar="N",
331 type="int",
332 default=40,
333 )
334 parser.add_option(
335 "--count",
336 help="The maximum number of images to make (default 20)",
337 metavar="N",
338 type="int",
339 default=20,
340 )
341 parser.add_option(
342 "--badwordlist",
343 help="A list of words that should not be used",
344 metavar="FILE",
345 default=os.path.join(script_dir, "badwordlist"),
346 )
347 parser.add_option(
348 "--fill",
349 help="Fill the output directory to contain N files, overrides count, cannot be used with --dirs",
350 metavar="N",
351 type="int",
352 )
353 parser.add_option(
354 "--dirs",
355 help="Put the images into subdirectories N levels deep - $wgCaptchaDirectoryLevels",
356 metavar="N",
357 type="int",
358 )
359 parser.add_option(
360 "--verbose",
361 "-v",
362 help="Show debugging information",
363 action="store_true"
364 )
365 parser.add_option(
366 "--number-words",
367 help="Number of words from the wordlist which make a captcha challenge (default 2)",
368 type="int",
369 default=2,
370 )
371 parser.add_option(
372 "--min-length",
373 help="Minimum length for a captcha challenge",
374 type="int",
375 default=1,
376 )
377 parser.add_option(
378 "--max-length",
379 help="Maximum length for a captcha challenge",
380 type="int",
381 default=-1,
382 )
383 parser.add_option(
384 "--threads",
385 help="Maximum number of threads to be used to generate captchas",
386 type="int",
387 default=1,
388 )
389 parser.add_option(
390 "--jsonmap",
391 help="Outputs \"filename\": \"word\" mapping for test/debug purposes",
392 action="store_true"
393 )
394
395 opts, args = parser.parse_args()
396
397 if opts.wordlist:
398 wordlist = opts.wordlist
399 elif opts.random:
400 wordlist = None
401 else:
402 sys.exit("Need to specify a wordlist")
403 if opts.key:
404 key = opts.key
405 else:
406 sys.exit("Need to specify a key")
407 if opts.output:
408 if not os.path.exists(opts.output):
409 try:
410 os.makedirs(opts.output)
411 except OSError:
412 sys.exit("%s doesn't exist, and unable to create it" % opts.output)
413
414 output = opts.output
415 else:
416 sys.exit("Need to specify an output directory")
417 if opts.font and os.path.exists(opts.font):
418 font = opts.font
419 else:
420 sys.exit("Need to specify the location of a font")
421
422 badwordlist = read_wordlist(opts.badwordlist)
423
424 if opts.verbose and not badwordlist:
425 print("badwordlist is empty.")
426
427 count = opts.count
428 fill = opts.fill
429 fontsize = opts.font_size
430 threads = opts.threads
431
432 if fill:
433 count = max(0, fill - len(os.listdir(output)))
434
435 if count == 0:
436 sys.exit("No need to generate CAPTCHA images.")
437
438 words = None
439 if wordlist:
440 words = read_wordlist(wordlist)
441
442 if not words:
443 sys.exit("No words were read from the wordlist")
444
445 words = [
446 x
447 for x in words
448 if len(x) in (4, 5) and x[0] != "f" and x[0] != x[1] and x[-1] != x[-2]
449 ]
450
451 if count < threads:
452 chunks = 1
453 threads = 1
454 else:
455 chunks = count // threads
456
457 p = multiprocessing.Pool(threads)
458 data = []
459 print(
460 "Generating %s CAPTCHA images separated in %s image(s) per chunk run by %s threads..."
461 % (count, chunks, threads)
462 )
463 jsonmap = multiprocessing.Manager().dict()
464 for i in range(0, threads):
465 data.append([chunks, words, badwordlist, opts, font, fontsize, jsonmap])
466
467 result = p.map_async(run_in_thread, data)
468 result.wait()
469
470 if opts.jsonmap:
471 with open("map.json", "w") as outfile:
472 json.dump(jsonmap.copy(), outfile, indent=4)