Debian Codegraph @

extensions/ConfirmEdit/captcha-old.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 import random
29 import math
30 import hashlib
31 from optparse import OptionParser
32 import os
33 import sys
34 import re
35 import multiprocessing
36
37 try:
38 from PIL import Image
39 from PIL import ImageFont
40 from PIL import ImageDraw
41 from PIL import ImageEnhance
42 from PIL import ImageOps
43 except ImportError:
44 sys.exit(
45 "This script requires the Python Imaging Library - http://www.pythonware.com/products/pil/"
46 )
47
48 # regex to test for suitability of words
49 nonalpha = re.compile("[^a-z]")
50
51 # Pillow 9.2 added getbbox to replace getsize, and getsize() was removed in Pillow 10
52 # https://pillow.readthedocs.io/en/stable/releasenotes/10.0.0.html#font-size-and-offset-methods
53 # We don't have a requirements.txt, and therefore don't declare any specific supported or min version...
54 IMAGEFONT_HAS_GETBBOX = hasattr(ImageFont.ImageFont, "getbbox")
55
56
57 # Does X-axis wobbly copy, sandwiched between two rotates
58 def wobbly_copy(src, wob, col, scale, ang):
59 x, y = src.size
60 f = random.uniform(4 * scale, 5 * scale)
61 p = random.uniform(0, math.pi * 2)
62 rr = ang + random.uniform(-30, 30) # vary, but not too much
63 int_d = Image.new("RGB", src.size, 0) # a black rectangle
64 rot = src.rotate(rr, Image.BILINEAR)
65 # Do a cheap bounding-box op here to try to limit work below
66 bbx = rot.getbbox()
67 if bbx is None:
68 return src
69 else:
70 l, t, r, b = bbx
71 # and only do lines with content on
72 for i in range(t, b + 1):
73 # Drop a scan line in
74 xoff = int(math.sin(p + (i * f / y)) * wob)
75 xoff += int(random.uniform(-wob * 0.5, wob * 0.5))
76 int_d.paste(rot.crop((0, i, x, i + 1)), (xoff, i))
77 # try to stop blurring from building up
78 int_d = int_d.rotate(-rr, Image.BILINEAR)
79 enh = ImageEnhance.Sharpness(int_d)
80 return enh.enhance(2)
81
82
83 def gen_captcha(text, fontname, fontsize, file_name):
84 """Generate a captcha image"""
85 # white text on a black background
86 bgcolor = 0x0
87 fgcolor = 0xFFFFFF
88 # create a font object
89 font = ImageFont.truetype(fontname, fontsize)
90
91 # determine dimensions of the text
92 if IMAGEFONT_HAS_GETBBOX:
93 dim = font.getbbox(text)[2:]
94 else:
95 dim = font.getsize(text)
96
97 # create a new image significantly larger that the text
98 edge = max(dim[0], dim[1]) + 2 * min(dim[0], dim[1])
99 im = Image.new("RGB", (edge, edge), bgcolor)
100 d = ImageDraw.Draw(im)
101 x, y = im.size
102 # add the text to the image
103 d.text((x / 2 - dim[0] / 2, y / 2 - dim[1] / 2), text, font=font, fill=fgcolor)
104 k = 3
105 wob = 0.20 * dim[1] / k
106 rot = 45
107 # Apply lots of small stirring operations, rather than a few large ones
108 # in order to get some uniformity of treatment, whilst
109 # maintaining randomness
110 for i in range(k):
111 im = wobbly_copy(im, wob, bgcolor, i * 2 + 3, rot + 0)
112 im = wobbly_copy(im, wob, bgcolor, i * 2 + 1, rot + 45)
113 im = wobbly_copy(im, wob, bgcolor, i * 2 + 2, rot + 90)
114 rot += 30
115
116 # now get the bounding box of the nonzero parts of the image
117 bbox = im.getbbox()
118 bord = min(dim[0], dim[1]) / 4 # a bit of a border
119 im = im.crop((bbox[0] - bord, bbox[1] - bord, bbox[2] + bord, bbox[3] + bord))
120 # and turn into black on white
121 im = ImageOps.invert(im)
122
123 # save the image, in format determined from filename
124 im.save(file_name)
125
126
127 def gen_subdir(basedir, md5hash, levels):
128 """Generate a subdirectory path out of the first _levels_
129 characters of _hash_, and ensure the directories exist
130 under _basedir_."""
131 subdir = None
132 for i in range(0, levels):
133 char = md5hash[i]
134 if subdir:
135 subdir = os.path.join(subdir, char)
136 else:
137 subdir = char
138 fulldir = os.path.join(basedir, subdir)
139 if not os.path.exists(fulldir):
140 os.mkdir(fulldir)
141 return subdir
142
143
144 def try_pick_word(words, badwordlist, verbose, nwords, min_length, max_length):
145 if words is not None:
146 word = words[random.randint(0, len(words) - 1)]
147 while nwords > 1:
148 word2 = words[random.randint(0, len(words) - 1)]
149 word = word + word2
150 nwords = nwords - 1
151 else:
152 word = ""
153 max_length = max_length if max_length > 0 else 10
154 for i in range(0, random.randint(min_length, max_length)):
155 word = word + chr(97 + random.randint(0, 25))
156
157 if verbose:
158 print("word is %s" % word)
159
160 if len(word) < min_length:
161 if verbose:
162 print(
163 "skipping word pair '%s' because it has fewer than %d characters"
164 % (word, min_length)
165 )
166 return None
167
168 if max_length > 0 and len(word) > max_length:
169 if verbose:
170 print(
171 "skipping word pair '%s' because it has more than %d characters"
172 % (word, max_length)
173 )
174 return None
175
176 if nonalpha.search(word):
177 if verbose:
178 print(
179 "skipping word pair '%s' because it contains non-alphabetic characters"
180 % word
181 )
182 return None
183
184 for naughty in badwordlist:
185 if naughty in word:
186 if verbose:
187 print(
188 "skipping word pair '%s' because it contains word '%s'"
189 % (word, naughty)
190 )
191 return None
192 return word
193
194
195 def pick_word(words, badwordlist, verbose, nwords, min_length, max_length):
196 for x in range(
197 1000
198 ): # If we can't find a valid combination in 1000 tries, just give up
199 word = try_pick_word(
200 words, badwordlist, verbose, nwords, min_length, max_length
201 )
202 if word:
203 return word
204 sys.exit("Unable to find valid word combinations")
205
206
207 def read_wordlist(filename):
208 if not os.path.isfile(filename):
209 return []
210 f = open(filename)
211 words = [x.strip().lower() for x in f.readlines()]
212 f.close()
213 return words
214
215
216 def run_in_thread(object):
217 count = object[0]
218 words = object[1]
219 badwordlist = object[2]
220 opts = object[3]
221 font = object[4]
222 fontsize = object[5]
223
224 for i in range(count):
225 word = pick_word(
226 words,
227 badwordlist,
228 opts.verbose,
229 opts.number_words,
230 opts.min_length,
231 opts.max_length,
232 )
233 salt = "%08x" % random.randrange(2**32)
234 # 64 bits of hash is plenty for this purpose
235 md5hash = hashlib.md5(
236 (key + salt + word + key + salt).encode("utf-8")
237 ).hexdigest()[:16]
238 filename = "image_%s_%s.png" % (salt, md5hash)
239 if opts.dirs:
240 subdir = gen_subdir(opts.output, md5hash, opts.dirs)
241 filename = os.path.join(subdir, filename)
242 if opts.verbose:
243 print(filename)
244 gen_captcha(word, font, fontsize, os.path.join(opts.output, filename))
245
246
247 if __name__ == "__main__":
248 """This grabs random words from the dictionary 'words' (one
249 word per line) and generates a captcha image for each one,
250 with a keyed salted hash of the correct answer in the filename.
251
252 To check a reply, hash it in the same way with the same salt and
253 secret key, then compare with the hash value given.
254 """
255 script_dir = os.path.dirname(os.path.realpath(__file__))
256 parser = OptionParser()
257 parser.add_option(
258 "--wordlist", help="A list of words (required)", metavar="WORDS.txt"
259 )
260 parser.add_option(
261 "--random",
262 help="Use random characters instead of a wordlist",
263 action="store_true",
264 )
265 parser.add_option(
266 "--key", help="The passphrase set as $wgCaptchaSecret (required)", metavar="KEY"
267 )
268 parser.add_option(
269 "--output",
270 help="The directory to put the images in - $wgCaptchaDirectory (required)",
271 metavar="DIR",
272 )
273 parser.add_option("--font", help="The font to use (required)", metavar="FONT.ttf")
274 parser.add_option(
275 "--font-size",
276 help="The font size (default 40)",
277 metavar="N",
278 type="int",
279 default=40,
280 )
281 parser.add_option(
282 "--count",
283 help="The maximum number of images to make (default 20)",
284 metavar="N",
285 type="int",
286 default=20,
287 )
288 parser.add_option(
289 "--badwordlist",
290 help="A list of words that should not be used",
291 metavar="FILE",
292 default=os.path.join(script_dir, "badwordlist"),
293 )
294 parser.add_option(
295 "--fill",
296 help="Fill the output directory to contain N files, overrides count, cannot be used with --dirs",
297 metavar="N",
298 type="int",
299 )
300 parser.add_option(
301 "--dirs",
302 help="Put the images into subdirectories N levels deep - $wgCaptchaDirectoryLevels",
303 metavar="N",
304 type="int",
305 )
306 parser.add_option(
307 "--verbose", "-v", help="Show debugging information", action="store_true"
308 )
309 parser.add_option(
310 "--number-words",
311 help="Number of words from the wordlist which make a captcha challenge (default 2)",
312 type="int",
313 default=2,
314 )
315 parser.add_option(
316 "--min-length",
317 help="Minimum length for a captcha challenge",
318 type="int",
319 default=1,
320 )
321 parser.add_option(
322 "--max-length",
323 help="Maximum length for a captcha challenge",
324 type="int",
325 default=-1,
326 )
327 parser.add_option(
328 "--threads",
329 help="Maximum number of threads to be used to generate captchas.",
330 type="int",
331 default=1,
332 )
333
334 opts, args = parser.parse_args()
335
336 if opts.wordlist:
337 wordlist = opts.wordlist
338 elif opts.random:
339 wordlist = None
340 else:
341 sys.exit("Need to specify a wordlist")
342 if opts.key:
343 key = opts.key
344 else:
345 sys.exit("Need to specify a key")
346 if opts.output:
347 output = opts.output
348 else:
349 sys.exit("Need to specify an output directory")
350 if opts.font and os.path.exists(opts.font):
351 font = opts.font
352 else:
353 sys.exit("Need to specify the location of a font")
354
355 print("captcha-old.py is deprecated and will be removed in the future!")
356
357 badwordlist = read_wordlist(opts.badwordlist)
358 count = opts.count
359 fill = opts.fill
360 fontsize = opts.font_size
361 threads = opts.threads
362
363 if fill:
364 count = max(0, fill - len(os.listdir(output)))
365
366 words = None
367 if wordlist:
368 words = read_wordlist(wordlist)
369 words = [
370 x
371 for x in words
372 if len(x) in (4, 5) and x[0] != "f" and x[0] != x[1] and x[-1] != x[-2]
373 ]
374
375 if count == 0:
376 sys.exit("No need to generate CAPTCHA images.")
377
378 if count < threads:
379 chunks = 1
380 threads = 1
381 else:
382 chunks = count // threads
383
384 p = multiprocessing.Pool(threads)
385 data = []
386 print(
387 "Generating %s CAPTCHA images separated in %s image(s) per chunk run by %s threads..."
388 % (count, chunks, threads)
389 )
390 for i in range(0, threads):
391 data.append([chunks, words, badwordlist, opts, font, fontsize])
392
393 p.map(run_in_thread, data)