root / captcha / src / captcha / captcha.py

Revision 189:8100d67665d7, 3.1 kB (checked in by tziade@…, 15 months ago)

eggified

Line 
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3#
4# Copyright (c) 2007 Tarek Ziadé
5#
6# Authors:
7#   Tarek Ziadé <tarek@ziade.org>
8#
9# This program is free software; you can redistribute it and/or
10# modify it under the terms of the GNU General Public License
11# as published by the Free Software Foundation; either version 2
12# of the License, or (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22import os
23import random
24import base64
25
26import Image
27import ImageFont
28import ImageDraw
29import ImageFilter
30
31dirname = os.path.dirname(__file__)
32fontdir = os.path.join(dirname, 'fonts')
33fonts = [os.path.realpath(os.path.join(fontdir, filename))
34         for filename in os.listdir(fontdir)
35         if filename.endswith('ttf')]
36
37CHARS = "abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWZYZ0123456789"
38
39def gen_random_word(wordLen=6):
40    word = ""
41    for i in range(0, wordLen):
42        word = word + CHARS[random.randint(0, 0xffffff) % len(CHARS)]
43    return word.strip()
44
45def gen_captcha(text, fnt=random.choice(fonts), fnt_sz=35):
46    """Generate a captcha image"""
47    fgcolor = random.randint(0, 0xffff00)
48    bgcolor = fgcolor ^ 0xffffff
49    font = ImageFont.truetype(fnt,fnt_sz)
50    dim = font.getsize(text)
51    im = Image.new('RGB', (dim[0] + 10, dim[1] + 10), bgcolor)
52    d = ImageDraw.Draw(im)
53    x, y = im.size
54    r = random.randint
55    for num in range(100):
56        d.rectangle((r(0,x),r(0,y),r(0,x),r(0,y)),fill=r(0,0xffffff))
57    d.text((3,3), text, font=font, fill=fgcolor)
58    return im.filter(ImageFilter.EDGE_ENHANCE_MORE)
59
60def save_image(image, file_name, fmt):
61    image.save(file_name, format=fmt)
62
63def save_captcha(text=gen_random_word(), fnt=random.choice(fonts),
64                 fnt_sz=35, file_name='test.jpg', fmt='JPEG'):
65    save_image(gen_captcha(text, fnt, fnt_sz), file_name, fmt)
66
67def get_captcha(text=gen_random_word(), fnt=random.choice(fonts), fnt_sz=35):
68    captcha = gen_captcha(text, fnt, fnt_sz).tostring('jpeg', 'RGB')
69    return captcha.encode('base64')
70
71def get_html_captcha(text=gen_random_word(), fnt=random.choice(fonts), fnt_sz=35):
72    pattern = """\
73    <img src="data:image/jpg;base64,%s">
74    <br/>
75    <div>
76      <input type="hidden" value="%s" name="word"/>
77      bender ? <input type="text" name="guess"/>
78    </div>
79    """
80    return pattern % (get_captcha(text, fnt, fnt_sz), text.encode('base64').strip())
81
82def check_captcha(guess, b64word):
83    return guess.strip().encode('base64') == b64word
84
85if __name__ == '__main__':
86    """Example: This grabs a random word from the dictionary 'words' (one
87    word per line) and generates a jpeg image named 'test.jpg' using
88    the truetype font 'porkys.ttf' with a font size of 25.
89    """
90    print get_html_captcha()
Note: See TracBrowser for help on using the browser.