def main():
        parser = argparse.ArgumentParser()
        parser.add_argument("font_path", help="Path to ttf font file")
        parser.add_argument("output", help="Output filename including extension (e.g. 'sample.jpg')")
        parser.add_argument("--num", help="Up to 4 digit number [Default: random]")
        args = parser.parse_args()

        captcha = ImageCaptcha(fonts=[args.font_path])
        captcha_str = args.num if args.num else DigitCaptcha.get_rand(3, 4)
        img = captcha.generate(captcha_str)
        img = np.fromstring(img.getvalue(), dtype='uint8')
        img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
        cv2.imwrite(args.output, img)
        print("Captcha image with digits {} written to {}".format([int(c) for c in captcha_str], args.output))
Beispiel #2
0
    def test_image_generate():
        captcha = ImageCaptcha()
        data = captcha.generate('1234')
        assert hasattr(data, 'read')

        captcha = WheezyCaptcha()
        data = captcha.generate('1234')
        assert hasattr(data, 'read')
Beispiel #3
0
def gen_captcha(length=None):
    length = length if length else LENGTH
    image = ImageCaptcha(width=130, height=60)  # fonts=FONTS)
    text = random_text(length)
    image.generate(text)
    code_signature = sign(text)
    fpath = os.path.join(OUTDIR, code_signature + ".png")
    image.write(text, fpath)
    return fpath, code_signature
Beispiel #4
0
 def getCaptcha(self):
     _chars = 'ABCDEFGHJKLMNPQRSTUVWXY23456789'
     chars = random.sample(_chars, 4)
     self.session.captcha = (''.join(chars)).lower()
     image = ImageCaptcha(fonts=['./static/fonts/arial.ttf', './static/fonts/arial.ttf'])
     data = image.generate(chars)
     return data
Beispiel #5
0
    def on_get(self, req, resp):
        # Generate a new captcha

        image = ImageCaptcha(fonts = ['fonts/UbuntuMono-R.ttf'])

        captcha_uuid = str(uuid.uuid4())
        captcha_answer = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(6))
        captcha_image = 'data:image/png;base64,' + str(base64.b64encode(image.generate(captcha_answer).getvalue())).split("'")[1]

        # The answer should be case insensitive, the caps are just there for the bots
        captcha_answer = captcha_answer.lower()

        captcha = db.Captcha(
            uuid = captcha_uuid,
            answer_hash = nacl.hash.sha256(str.encode(captcha_uuid + captcha_answer), encoder = nacl.encoding.RawEncoder),
            ip_address_hash = nacl.hash.sha256(str.encode(captcha_uuid + req.remote_addr), encoder = nacl.encoding.RawEncoder),
            user_agent_hash = nacl.hash.sha256(str.encode(captcha_uuid + req.user_agent), encoder = nacl.encoding.RawEncoder)
        )

        db_session = req.context['db_session']

        db_session.add(captcha)
        db_session.commit()

        resp.status = falcon.HTTP_200
        resp.body = json.dumps({
            'uuid': captcha_uuid,
            'image': captcha_image
        })
Beispiel #6
0
def gen_captcha_base64(length=None):
    length = length if length else LENGTH
    image = ImageCaptcha(width=130, height=60)  # fonts=FONTS)
    text = random_text(length).lower()
    im = image.generate(text)
    code_signature = sign(text)
    b64 = base64.b64encode(im.getvalue()).decode("utf-8")
    return f"data:image/png;base64, {b64}", code_signature
def gen_captcha_text_and_image():
    image = ImageCaptcha()
    #获得随机生成的验证码
    captcha_text = random_captcha_text()
    #把验证码列表转为字符串
    captcha_text = ''.join(captcha_text)
    #生成验证码
    captcha = image.generate(captcha_text)
    image.write(captcha_text, 'captcha/images/' + captcha_text + '.jpg')  # 写到文件
Beispiel #8
0
def gen_captcha_image_random():
    image = ImageCaptcha()

    captcha_text = random_captcha_text()
    captcha_text = ''.join(captcha_text)

    captcha = image.generate(captcha_text)
    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)
    print(captcha_image)
Beispiel #9
0
def gen_captcha_text_and_image():
	image = ImageCaptcha()
 
	captcha_text = random_captcha_text()
	captcha_text = ''.join(captcha_text)
 
	captcha = image.generate(captcha_text)
	#image.write(captcha_text, captcha_text + '.jpg')  # 写到文件
 
	captcha_image = Image.open(captcha)
	captcha_image = np.array(captcha_image)
	return captcha_text, captcha_image
Beispiel #10
0
def gen_captcha_text_and_image():
	image = ImageCaptcha()

	# captcha_text = random_captcha_text()#使用带有字母和数字的随机组合
	captcha_text = random_captcha_num()#使用只有数字的随机组合
	captcha_text = ''.join(captcha_text)

	captcha = image.generate(captcha_text)
	# image.write(captcha_text, save_file+captcha_text + '.jpg')  # 写到文件

	captcha_image = Image.open(captcha)
	captcha_image = np.array(captcha_image)
	return captcha_text, captcha_image
Beispiel #11
0
def request_img(request):
    captcha_id = request.params['id']
    if not captcha_id:
        return HTTPNotFound('Not Found Resource')
    with transaction.manager:
        captcha = DBSession.query(CaptchaCode).get(captcha_id)
        if not captcha:
            return HTTPNotFound('Not Found Resource')

        image = ImageCaptcha(fonts=[ttf_path], font_sizes=(48, 49, 50), width=130)
        image_data = image.generate(captcha.code)
        response = Response(image_data.read())
        response.content_type = "image/jpeg"
        return response
Beispiel #12
0
    def appear(self):
        # Make captcha
        row = str(uuid.uuid4())[:4]
        img = ImageCaptcha()
        data = img.generate("1")
        assert isinstance(data, BytesIO)
        img.write(row, "captcha.png")
        pixmap = QtGui.QPixmap("captcha.png")
        self.ui.captcha_lb.setPixmap(pixmap)
        os.remove("captcha.png")

        # Appear win
        self.show()
        self.animation_appear.start()
Beispiel #13
0
def newcaptcha(text, fontspath='captcha/fonts/'):
    cherrypy.session['capt_code'] = text
    fonts = []
    for x in os.listdir(fontspath):
        if x.split('.')[-1] == 'ttf':#if font file
            fonts.append(fontspath+x)
                     
    img = StringIO.StringIO()
    
    image = ImageCaptcha(fonts=fonts)
    data = image.generate(text)
    image.write(text, img)

    contents = img.getvalue()
    img.close()

    return contents
def add_to_form_context(context):
    config = pluginapi.get_config('mediagoblin.plugins.lepturecaptcha')
    captcha_secret = config.get('CAPTCHA_SECRET_PHRASE')
    captcha_charset = config.get('CAPTCHA_CHARACTER_SET')
    captcha_length = config.get('CAPTCHA_LENGTH')

    captcha_string = u''.join([choice(captcha_charset) for n in xrange(captcha_length)])

    captcha_hash = sha1(captcha_secret + captcha_string).hexdigest()
    context['captcha_hash'] = captcha_hash

    image = ImageCaptcha()
    data = image.generate(captcha_string)
    captcha_image = base64.b64encode(data.getvalue())
    context['captcha_image'] = captcha_image

    return context
Beispiel #15
0
def gen_captcha_text_and_image():
    while (1):
        image = ImageCaptcha()

        captcha_text = random_captcha_text()
        captcha_text = ''.join(captcha_text)

        captcha = image.generate(captcha_text)
        # image.write(captcha_text, captcha_text + '.jpg')  # 写到文件

        captcha_image = Image.open(captcha)
        # captcha_image.show()
        captcha_image = np.array(captcha_image)
        if captcha_image.shape == (60, 160, 3):
            break

    return captcha_text, captcha_image
Beispiel #16
0
class OCRIter(mx.io.DataIter):
    def __init__(self, count, batch_size, num_label, init_states):
        super(OCRIter, self).__init__()
        global SEQ_LENGTH
        # you can get this font from http://font.ubuntu.com/
        self.captcha = ImageCaptcha(fonts=['./data/Xerox.ttf'])
        self.batch_size = batch_size
        self.count = count
        self.num_label = num_label
        self.init_states = init_states
        self.init_state_arrays = [mx.nd.zeros(x[1]) for x in init_states]
        self.provide_data = [('data', (batch_size, 80, 30))] + init_states
        self.provide_label = [('label', (self.batch_size, 4))]
        self.cache_data = []
        self.cache_label = []

    def __iter__(self):
        print('iter')
        init_state_names = [x[0] for x in self.init_states]
        for k in range(self.count):
            data = []
            label = []
            for i in range(self.batch_size):
                num = gen_rand()
                img = self.captcha.generate(num)
                img = np.fromstring(img.getvalue(), dtype='uint8')
                img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
                img = cv2.resize(img, (80, 30))
                img = img.transpose(1, 0)
                img = img.reshape((80, 30))
                img = np.multiply(img, 1 / 255.0)
                data.append(img)
                label.append(get_label(num))

            data_all = [mx.nd.array(data)] + self.init_state_arrays
            label_all = [mx.nd.array(label)]
            data_names = ['data'] + init_state_names
            label_names = ['label']

            data_batch = SimpleBatch(data_names, data_all, label_names, label_all)
            yield data_batch

    def reset(self):
        self.cache_data.clear()
        self.cache_label.clear()
        pass
Beispiel #17
0
def gen_captcha_text_and_image():
    size = random.randint(4, 20)
    image = ImageCaptcha(height=128, width=(size * 40 + 40), font_sizes=(80, 90, 100, 112))
    captcha_text = random_captcha_text(captcha_size=size)
    captcha_text = ''.join(captcha_text)

    captcha = image.generate(captcha_text)
    # image.write(captcha_text, captcha_text + '.jpg')  # 写到文件

    captcha_image = Image.open(captcha)
    w, h = captcha_image.size
    captcha_image = captcha_image.resize((w // 4, h // 4))

    captcha_image.save('train_data/' + captcha_text + '.jpg', 'jpeg')  # 写到文件

    # 调试用显示
    # captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
Beispiel #18
0
 def captcha_ask(self, error=False, **kwargs):
     """
     helper method to generate a captcha and verify that the user entered the right answer.
     :param error: if True indicates that the previous captcha attempt failed
     :return: a bool indicating if the user entered the right answer or not
     """
     image = ImageCaptcha()
     captcha = j.data.idgenerator.generateXCharID(4)
     # this log is for development purposes so we can use the redis client
     self._log_info("generated captcha:%s" % captcha)
     data = image.generate(captcha)
     self.q_out.put({
         "cat": "captcha_ask",
         "captcha": base64.b64encode(data.read()).decode(),
         "msg": "Are you human?",
         "label": "Please enter a valid captcha" if error else "",
         "kwargs": kwargs,
     })
     return self.q_in.get() == captcha
Beispiel #19
0
def gen_captcha_text_and_image():
    image = ImageCaptcha()
    # plt.imshow(image)
    # plt.show()

    captcha_text = random_captcha_text()
    captcha_text = ''.join(captcha_text)
    #print(captcha_text)

    captcha = image.generate(captcha_text)
    #print(captcha)
    #image.write(captcha_text, captcha_text + '.jpg')  # 写到文件

    captcha_image = Image.open(captcha)
    #print(captcha_image)
    captcha_image = np.array(captcha_image)
    #print(captcha_image)

    return captcha_text, captcha_image
Beispiel #20
0
class OCRIter(mx.io.DataIter):
    def __init__(self, count, batch_size, num_label, init_states):
        super(OCRIter, self).__init__()
        # you can get this font from http://font.ubuntu.com/
        self.captcha = ImageCaptcha(fonts=['./font/Ubuntu-M.ttf'])
        self.batch_size = batch_size
        self.count = count
        self.num_label = num_label
        self.init_states = init_states
        self.init_state_arrays = [mx.nd.zeros(x[1]) for x in init_states]
        self.provide_data = [('data', (batch_size, 2400))] + init_states
        self.provide_label = [('label', (self.batch_size, 4))]

    def __iter__(self):
        print('iter')
        init_state_names = [x[0] for x in self.init_states]
        for k in range(self.count):
            data = []
            label = []
            for i in range(self.batch_size):
                num = gen_rand()
                img = self.captcha.generate(num)
                img = np.fromstring(img.getvalue(), dtype='uint8')
                img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
                img = cv2.resize(img, (80, 30))
                img = img.transpose(1, 0)
                img = img.reshape((80 * 30))
                img = np.multiply(img, 1 / 255.0)
                data.append(img)
                label.append(get_label(num))

            data_all = [mx.nd.array(data)] + self.init_state_arrays
            label_all = [mx.nd.array(label)]
            data_names = ['data'] + init_state_names
            label_names = ['label']

            data_batch = SimpleBatch(data_names, data_all, label_names,
                                     label_all)
            yield data_batch

    def reset(self):
        pass
def generateCaptchaTextAndImage(width=CAPTCHA_WIDTH,
                                height=CAPTCHA_HEIGHT,
                                save=False):
    """
    生成随机验证码
    :param width: 验证码图片宽度
    :param height: 验证码图片高度
    :param save: 是否保存(None)
    :return: 验证码字符串,验证码图像np数组
    """
    image = ImageCaptcha(width=width, height=height)
    # 验证码文本
    captchaText = randomCaptchaText(char_set=CAPTCHA_LIST,
                                    captcha_size=CAPTCHA_LENGTH)
    captcha = image.generate(captchaText)

    captcha_image = Image.open(captcha)
    # 转化为np数组
    captcha_image = np.array(captcha_image)
    return captchaText, captcha_image
Beispiel #22
0
def gen_captcha_text_and_image(width=CAPTCHA_WIDTH,
                               height=CAPTCHA_HEIGHT,
                               save=None):
    '''
    生成随机验证码
    :param width:
    :param height:
    :param save:
    :return: np数组
    '''
    image = ImageCaptcha(width=width, height=height)
    # 验证码文本
    captcha_text = random_captcha_text()
    captcha = image.generate(captcha_text)
    # 保存
    if save: image.write(captcha_text, captcha_text + '.jpg')
    captcha_image = Image.open(captcha)
    # 转化为np数组
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
Beispiel #23
0
    async def captcha_example(self, ctx):
        image = ImageCaptcha(fonts=['Others/font1.ttf', 'Others/font2.ttf'])

        data = image.generate("1234")

        image.write("1234", 'CaptchaExample.png')

        embed = discord.Embed(
            title = "Example of an Captcha",
            color = ctx.author.color,
            timestamp = ctx.message.created_at
        )
        files = discord.File("CaptchaExample.png")
        embed.set_image(
            url = "attachment://CaptchaExample.png"
        )
        embed.set_footer(
            text = "Note that Captchas are generated with different numbers and characters. This is only an example of a single captcha with the answer \"1234\"!"
        )
        await ctx.send(embed=embed, file=files)
Beispiel #24
0
def gen_captcha_text_and_image():
    # 验证码生成类
    image = ImageCaptcha()

    # 获取验证码文字
    captcha_text = random_captcha_text()
    # List转化为字符串
    captcha_text = ''.join(captcha_text)

    # 生成图片
    captcha = image.generate(captcha_text)

    # 保存到磁盘
    image.write(captcha_text, captcha_text + '.jpg')

    captcha_image = Image.open(captcha)
    # 转化为np.array(供Tensorflow识别)
    captcha_image = np.array(captcha_image)
    # 返回label,和图片
    return captcha_text, captcha_image
 def __init__(self):
     root = Tk()
     root.title("Captcha Verification")
     self.actual = str(random.randint(1, 100)) + self.randOps() + str(random.randint(1, 100))
     print(self.actual) #For generating random string of mathmatical expression
     Label(root, text = "Math based Captcha Verification",font = "comicsansms 19 bold").pack()
     image = ImageCaptcha(fonts = ['captcha.ttf']) #Font for captcha
     data = image.generate(self.actual) 
     image.write(self.actual, "out.png") #Output image of captcha
     img = Image.open("out.png")
     w,h = img.size
     img = img.resize((w*4,h*3))
     img.save("out.png")
     photo = ImageTk.PhotoImage(img)
     Label(root, text = "Submit", image = photo).pack() #Putting image of captcha in tkinter 
     Label(root, text = "Enter the captcha:", font = "comicsansms 12 bold").pack()
     self.captchaInput = Entry(root)
     self.captchaInput.pack()
     Button(root, text = "Submit", command=self.submit).pack()
     root.mainloop()
def gen_verifycode_pic():
    # 指定大小 180 * 67
    img = ImageCaptcha(180, 67)
    # 指定文本,长度4位
    txt = gen_verifycode_txt()
    txt = ''.join(txt)
    # 测试,打印出验证码文本
    # print('-------------- ' + txt)
    # 根据文本生成图像
    captcha = img.generate(txt)
    # 写入文件
    img.write(txt, PIC_DIR + txt + EXT)
    captcha_image = Image.open(captcha)

    # 图片显示出来
    # captcha_image.show()
    captcha_image = np.array(captcha_image)

    # 返回最终图形对象和文字
    return txt, captcha_image
Beispiel #27
0
def gen_captcha_text_and_image():

    while (1):
        image = ImageCaptcha(180, 67)
        # image = ImageCaptcha()

        captcha_text = random_captcha_text()
        captcha_text = ''.join(captcha_text)
        path = 'F://CNN_1/test/'
        print("-----------------" + captcha_text)
        captcha = image.generate(captcha_text)
        # image.write(captcha_text, path+captcha_text + '.jpg')  # 写到文件

        captcha_image = Image.open(captcha)
        #captcha_image.show()
        captcha_image = np.array(captcha_image)
        if captcha_image.shape == (67, 180, 3):
            break

    return captcha_text, captcha_image
class CaptchaGen(object):
    """
    Generates a captcha image
    """
    def __init__(self, h, w, font_paths):
        """
        Parameters
        ----------
        h: int
            Height of the generated images
        w: int
            Width of the generated images
        font_paths: list of str
            List of all fonts in ttf format
        """
        self.captcha = ImageCaptcha(fonts=font_paths)
        self.h = h
        self.w = w

    def image(self, captcha_str):
        """
        Generate a greyscale captcha image representing number string

        Parameters
        ----------
        captcha_str: str
            string a characters for captcha image

        Returns
        -------
        numpy.ndarray
            Generated greyscale image in np.ndarray float type with values normalized to [0, 1]
        """
        img = self.captcha.generate(captcha_str)
        img = np.fromstring(img.getvalue(), dtype='uint8')
        img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img, (self.h, self.w))
        img = img.transpose(1, 0)
        img = np.multiply(img, 1 / 255.0)
        # print(np.mean(img), np.std(img))
        return img
def gen_captcha_text_and_image(i):
    image = ImageCaptcha(width=width_p,
                         height=height_p,
                         font_sizes=[90, 100, 110])

    captcha_text = random_captcha_text()
    captcha_text = ''.join(captcha_text)

    path = './generated/'
    if os.path.exists(
            path) == False:  # if the folder is not existed, create it
        os.mkdir(path)

    captcha = image.generate(captcha_text)

    # naming rules: num(in order)+'_'+'captcha text'.include num is for avoiding the same name
    image.write(captcha_text, path + captcha_text + '.png')

    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
Beispiel #30
0
def gen_captcha_text_and_image():
    while 1:
        image = ImageCaptcha()

        captcha_text = random_captcha_text()
        captcha_text = ''.join(captcha_text)
        captcha = image.generate(captcha_text)
        # image.write(captcha_text, captcha_text + '.jpg')  # 写到文件
        train_image = []
        train_text = []
        captcha_image = Image.open(captcha)
        captcha_image = np.array(captcha_image)
        captcha_image = rgb2gray(captcha_image)
        captcha_text = to_one_hot(captcha_text, 4, 10)
        captcha_text = captcha_text.reshape(40)
        captcha_image = captcha_image / 255
        train_text.append(captcha_text)
        train_image.append(captcha_image)
        train_text = np.array(train_text)
        train_image = np.array(train_image)
        yield ({'conv2d_1_input': train_image}, {'dense_1': train_text})
Beispiel #31
0
def gen_captcha_text_and_image(width=CAPTCHA_WIDTH,
                               height=CAPTCHA_HEIGHT,
                               save=None):
    """
    生成随机验证码
    :param width: 验证码图片宽度
    :param height: 验证码图片高度
    :param save: 是否保存(None)
    :return: 验证码字符串,验证码图像np数组
    """
    image = ImageCaptcha(width=width, height=height)
    # 验证码文本
    captcha_text = random_captcha_text()
    captcha = image.generate(captcha_text)
    # 保存
    if save:
        image.write(captcha_text, './img/' + captcha_text + '.jpg')
    captcha_image = Image.open(captcha)
    # 转化为np数组
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
Beispiel #32
0
def gen_capthcha_text_and_image(m):
    """
    生成验证码图片
    :param m: 验证码序号
    :return: none
    """
    image = ImageCaptcha()
    # 获取写入字符串
    captcha_text = random_captcha_text()
    captcha_text = ' '.join(captcha_text)
    captcha = image.generate(captcha_text)

    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)
    # 写入标签
    with open(data_path + "label.txt", "a") as f:
        f.write(captcha_text)
        f.writelines("\n")
    # 写入图片
    name = data_path + 'src/' + '{0:0>4}'.format(m) + '.jpg'
    cv2.imwrite(name, captcha_image)
def gen_captcha_text_and_image():
	# image = ImageCaptcha(width=104, height=30)
	image = ImageCaptcha()

	captcha_text = random_captcha_text()
	captcha_text = ''.join(captcha_text)

	captcha = image.generate(captcha_text)
	#image.write(captcha_text, captcha_text + '.jpg')  # 写到文件

	#rm  =  'rm '+captcha_text + '.jpg'
	#print rm
	#os.system(rm)
	#time.sleep(10)

	captcha_image = Image.open(captcha)
        ca1 = captcha_image.resize((104,30), Image.ANTIALIAS)
        ca1 = np.array(ca1)
	captcha_image = np.array(captcha_image)
	# return captcha_text, captcha_image, ca1
	return captcha_text, captcha_image
Beispiel #34
0
def gen_captcha_text_and_image(i):
    image = ImageCaptcha(width=captcha_params_and_cfg.get_width(),
                         height=captcha_params_and_cfg.get_height(),
                         font_sizes=[50])

    captcha_text = random_captcha_text()
    captcha_text = ''.join(captcha_text)

    path = captcha_params_and_cfg.data_path + '/'
    if os.path.exists(
            path) == False:  # if the folder is not existed, create it
        os.mkdir(path)

    captcha = image.generate(captcha_text)

    # naming rules: num(in order)+'_'+'captcha text'.include num is for avoiding the same name
    image.write(captcha_text, path + str(i) + '_' + captcha_text + '.png')

    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
class CustomDataIter(mx.io.DataIter):
    def __init__(self, num_example, batch_size, label_length, height, width,
                 captcha_str, captcha_dic):
        super(CustomDataIter, self).__init__()
        self.captcha = ImageCaptcha(fonts=['./fonts/Ubuntu-M.ttf'])
        self.batch_size = batch_size
        self.num_example = num_example
        self.label_length = label_length
        self.height = height
        self.width = width
        self.captcha_str = captcha_str
        self.captcha_dic = captcha_dic
        self.provide_data = [('data', (batch_size, 3, height, width))]
        self.provide_label = [('softmax_label', (self.batch_size,
                                                 label_length))]

    def __iter__(self):
        for k in range(self.num_example / self.batch_size):
            data = []
            label = []
            for i in range(self.batch_size):
                num = get_captcha(length=self.label_length,
                                  captcha_str=self.captcha_str)
                img = self.captcha.generate(num)
                img = np.fromstring(img.getvalue(), dtype='uint8')
                img = cv2.imdecode(img, cv2.IMREAD_COLOR)
                img = cv2.resize(img, (self.width, self.height))
                cv2.imwrite("./tmp" + str(i % 10) + ".png", img)
                img = np.multiply(img, 1 / 255.0)
                img = img.transpose(2, 0, 1)
                data.append(img)
                label.append(get_label(num, self.captcha_dic))

            data_all = [mx.nd.array(data)]
            label_all = [mx.nd.array(label)]
            data_batch = mx.io.DataBatch(data=data_all, label=label_all)
            yield data_batch

    def reset(self):
        pass
class CaptchaGen(object):
    """
    Generates a captcha image
    """
    def __init__(self, h, w, font_paths):
        """
        Parameters
        ----------
        h: int
            Height of the generated images
        w: int
            Width of the generated images
        font_paths: list of str
            List of all fonts in ttf format
        """
        self.captcha = ImageCaptcha(fonts=font_paths)
        self.h = h
        self.w = w

    def image(self, captcha_str):
        """
        Generate a greyscale captcha image representing number string

        Parameters
        ----------
        captcha_str: str
            string a characters for captcha image

        Returns
        -------
        numpy.ndarray
            Generated greyscale image in np.ndarray float type with values normalized to [0, 1]
        """
        img = self.captcha.generate(captcha_str)
        img = np.fromstring(img.getvalue(), dtype='uint8')
        img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img, (self.h, self.w))
        img = img.transpose(1, 0)
        img = np.multiply(img, 1 / 255.0)
        return img
Beispiel #37
0
def base_capthca(lang):
    inline_kb_full = InlineKeyboardMarkup(row_width=4)
    # captcha_text_store = 'あかさたなはまやらわがざだばぴぢじぎりみひにちしきぃうぅくすつぬふむゆゅるぐずづぶぷぺべでぜげゑれめねてへせけぇえおこそとのほもよょろをごぞどぼぽ、ゞゝんっゔ'
    captcha_text_store = 'asdfghjkzxcvbnmqwertyu2345678'
    captcha_text = choices(captcha_text_store, k=8)
    btn_text = list(captcha_text)
    btn_pass = list(btn_text)
    btn_order = []
    btns = []
    for _ in range(8):
        random_index = randrange(len(btn_text))
        item = btn_text.pop(random_index)
        _id = f'btn_{item}'
        btn_order.append(btn_pass.index(item))
        btns.append(InlineKeyboardButton(str(item), callback_data=_id))
    inline_kb_full.row(*btns[0:4])
    inline_kb_full.row(*btns[4:8])
    backspace_btn = InlineKeyboardButton('⌫', callback_data='backspace')
    inline_kb_full.row(backspace_btn)

    # file = io.BytesIO()
    # image = Image.new('RGBA', size=(250, 50), color=(155, 0, 0))
    # d = ImageDraw.Draw(image)
    # d.text((10,10), "Hello World", fill=(255,255,0))
    # image.save(file, 'png')

    # image_captcha = ImageCaptcha(fonts=['/usr/share/fonts/truetype/fonts-japanese-gothic.ttf'],  width=460, height=200)
    # image_captcha = ImageCaptcha(fonts=['/home/albert/.local/share/fonts/Iosevka Term Nerd Font Complete.ttf'],  width=460, height=200)
    image_captcha = ImageCaptcha(fonts=['NotoSansCJKjp-Regular.otf'],
                                 width=350,
                                 height=200)
    image = image_captcha.generate_image(captcha_text)
    for _ in range(randint(1, 5)):
        image_captcha.create_noise_curve(image, image.getcolors())

    # Add noise dots for the image.
    image_captcha.create_noise_dots(image, image.getcolors())
    input_file = InputFile(image_captcha.generate(captcha_text))

    return (input_file, inline_kb_full, btn_pass)
Beispiel #38
0
class OCRIter(mx.io.DataIter):
    def __init__(self, count, batch_size, num_label, init_states):
        super(OCRIter, self).__init__()
        self.captcha = ImageCaptcha(fonts=["./data/Xerox.ttf"])
        self.batch_size = batch_size
        self.count = count
        self.num_label = num_label
        self.init_states = init_states
        self.init_state_arrays = [mx.nd.zeros(x[1]) for x in init_states]
        self.provide_data = [("data", (batch_size, 2400))] + init_states
        self.provide_label = [("label", (self.batch_size, 4))]

    def __iter__(self):
        print("iter")
        init_state_names = [x[0] for x in self.init_states]
        for k in range(self.count):
            data = []
            label = []
            for i in range(self.batch_size):
                num = gen_rand()
                img = self.captcha.generate(num)
                img = np.fromstring(img.getvalue(), dtype="uint8")
                img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
                img = cv2.resize(img, (80, 30))
                img = img.transpose(1, 0)
                img = img.reshape((80 * 30))
                img = np.multiply(img, 1 / 255.0)
                data.append(img)
                label.append(get_label(num))

            data_all = [mx.nd.array(data)] + self.init_state_arrays
            label_all = [mx.nd.array(label)]
            data_names = ["data"] + init_state_names
            label_names = ["label"]

            data_batch = SimpleBatch(data_names, data_all, label_names, label_all)
            yield data_batch

    def reset(self):
        pass
Beispiel #39
0
def gen_captcha(charset,nb_chars=None,font=None):
    if not font is None:
        image = ImageCaptcha(fonts=[font])

    buffer_index=1000
    buffer_size=1000
    nc_set = np.zeros(buffer_size)


    while True:
        if buffer_index==buffer_size:
            nc_set = np.random.randint(3, MAXLEN+1, buffer_size) if nb_chars is None else np.array([nb_chars] * buffer_size)
            buffer_index=0
        captcha_text = ''.join(random_chars(charset,nc_set[buffer_index]))
        buffer_index+=1

        img_text = ' '*np.random.randint(0,MAXLEN+1-len(captcha_text))*2+captcha_text #用空格模拟偏移
        captcha = image.generate(img_text)
        captcha_image = Image.open(captcha).resize((TARGET_WIDTH,TARGET_HEIGHT),Image.ANTIALIAS)
        #image.write(captcha_text, captcha_text + '.jpg')  # 写到文件
        captcha_array = np.array(captcha_image)
        yield captcha_array,captcha_text
Beispiel #40
0
def gen_captcha_text_and_image(width=CAPTCHA_WIDTH,
                               height=CAPTCHA_HEIGHT,
                               save=1):
    '''
    生成随机验证码
    :param width:
    :param height:
    :param save:
    :return: np数组
    '''
    for _ in range(20000):
        image = ImageCaptcha(width=width, height=height)
        # 验证码文本
        captcha_text = random_captcha_text()
        captcha = image.generate(captcha_text)
        # 保存
        path = f'./my/{captcha_text}.png'
        if save:
            image.write(captcha_text, path)
        print(
            f'{current_thread().name}: get {captcha_text}.png!!!!!!!!!!!!!!!!!!!!!!'
        )
Beispiel #41
0
class CaptchaGenerator(object):
    def __init__(self, image_length):
        self.image_length = image_length
        self.image_captcha = ImageCaptcha()

    def get_random_text(self):
        retVal = ''
        for _ in range(self.image_length):
            retVal += CHARSETS[random.randint(0, len(CHARSETS) - 1)]
        return retVal

    def get_labeled_image(self, samples):
        X, Y = [], []
        for _ in range(samples):
            text = self.get_random_text()
            image = self.image_captcha.generate(text, format='png')
            captcha_image = Image.open(image)
            array = np.array(captcha_image)
            X.append(array)
            Y.append(text)
            # self.image_captcha.write(text, "%s.png" % text)
        return X, Y
Beispiel #42
0
def gen_captcha_text_and_image(iter):

    image = ImageCaptcha(width=captcha_params.get_width(),
                         height=captcha_params.get_height(),
                         font_sizes=[30])
    #print(image)
    #captcha_text = random_text()
    captcha_text = "oO" + random_text()  #proof that "o" and "O" looks the same
    path = '../images/'  #go up one directory then create images folder

    if os.path.exists(
            path) == False:  # if the folder is not existed, create it
        os.mkdir(path)
    captcha = image.generate(captcha_text)
    print('c: ', captcha)
    # naming rules: num(in order)+'_'+'captcha text'.include num is for avoiding the same name
    image.write(captcha_text, path + str(iter) + '_' + captcha_text + '.png')

    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)

    return captcha_text, captcha_image
Beispiel #43
0
def gen_captcha_text_and_image(char_set, captcha_height, captcha_width,
                               captcha_size):
    '''
    产生验证码
    :param char_set: 验证码字符集
    :param captcha_height: 验证码图片高度
    :param captcha_width: 验证码图片宽度
    :param captcha_size: 验证码含有字符个数
    :return:
    '''
    image = ImageCaptcha(width=captcha_width, height=captcha_height)
    # 随机产生验证码字符
    captcha_text = random_captcha_text(char_set=char_set,
                                       captcha_size=captcha_size)
    captcha_text = ''.join(captcha_text)

    captcha = image.generate(captcha_text)
    # image.write(captcha_text, captcha_text + '.jpg')

    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)
    return captcha_text, captcha_image
Beispiel #44
0
    def get(self):
        #x_real_ip = self.request.headers.get("X-Real-IP")
        #remote_ip = self.request.remote_ip if not x_real_ip else x_real_ip
        if self.signin_service.is_ip_locked(self.request.remote_ip, 6):
            print "The ip is blocked!!!"

        self.signin_service.increment_ip(self.request.remote_ip)
        image = ImageCaptcha(fonts=[
            '/usr/share/fonts/dejavu/DejaVuSans.ttf',
            '/usr/share/calibre/fonts/liberation/LiberationSerif-Regular.ttf'
        ])
        string = random_string(5)
        anti_cache = random_string(22)
        self.session.set('captcha_string', string)
        data = image.generate(string)
        if os.path.exists('%s/static/captcha/%s%s.png' %
                          (firenado.conf.APP_CONFIG_ROOT_PATH, self.session.id,
                           self.session.get('anti_cache'))):
            os.remove('%s/static/captcha/%s%s.png' %
                      (firenado.conf.APP_CONFIG_ROOT_PATH, self.session.id,
                       self.session.get('anti_cache')))
        self.session.set('anti_cache', anti_cache)

        image.write(string,
                    'static/captcha/%s%s.png' % (self.session.id, anti_cache))
        f = Image.open(
            '%s/static/captcha/%s%s.png' %
            (firenado.conf.APP_CONFIG_ROOT_PATH, self.session.id, anti_cache))
        o = io.BytesIO()
        f.save(o, format="PNG")
        s = o.getvalue()

        #data = collections.defaultdict(lambda: collections.defaultdict(dict))
        #data['photo']=s

        self.render("jetpack:singin/email.html",
                    session_id=self.session.id,
                    anti_cache=anti_cache)
def gen_captcha_text_and_image():
    image = ImageCaptcha()

    captcha_text = random_captcha_text()
    captcha_text = ''.join(captcha_text)  # 用字符['m', 'i', 'R', 'd']转化为miRd

    captcha = image.generate(captcha_text)  # 将captcha_text转化为图片
    # image.write(captcha_text, captcha_text + '.jpg')  # 写到文件
    captcha_image = Image.open(captcha)
    # captcha_image.show() 测试是否成功生成验证码
    captcha_image = np.array(captcha_image)

    return captcha_text, captcha_image


# if __name__ == '__main__':
#     # 测试
#     text, image = gen_captcha_text_and_image()
#
#     f = plt.figure()
#     ax = f.add_subplot(111)
#     ax.text(0.1, 0.9,text, ha='center', va='center', transform=ax.transAxes)
#     plt.imshow(image)
Beispiel #46
0
def gen_captcha_text_and_image():
    image = ImageCaptcha()

    # 此处只训练只有小写字母的结果
    captcha_text = random_captcha_text()
    captcha_text = ''.join(captcha_text)

    captcha = image.generate(captcha_text)

    # # 存储文件使用
    # base_dir = os.path.abspath(os.path.dirname(__file__))
    # files_dir = os.path.abspath(os.path.join(os.getcwd(), '../static'))
    # print(files_dir)
    # image_dir = os.path.join(files_dir, 'captcha.jpg')
    #
    # image.write(captcha_text, image_dir)

    # 生成训练文件
    captcha_image = Image.open(captcha)
    # captcha_image.show()
    captcha_image = np.array(captcha_image)
#    print(captcha_image)
    return captcha_text, captcha_image
Beispiel #47
0
class CaptchaDataset(Dataset):
    def __init__(self, img_width, img_height, ds_size, n_chars=4, chars=None):
        self.gen = ImageCaptcha(img_width, img_height)
        self.size = ds_size

        self.n_chars = n_chars

        if chars is None:
            self.chars = list('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
        else:
            self.chars = list(chars)

        self.tokenizer = Tokenizer(self.chars)

        self.first_run = True

    def __len__(self):
        return self.size

    def __getitem__(self, item):
        if self.first_run:
            Random.atfork()
            self.first_run = False

        content = [random.randrange(0, len(self.chars)) for _ in range(self.n_chars)]

        s = ''.join([self.chars[i] for i in content])

        d = self.gen.generate(s)
        d = Image.open(d)

        label = torch.full((self.n_chars + 2, ), self.tokenizer.EOS_token, dtype=torch.long)

        ts = self.tokenizer.tokenize(s)
        label[:ts.shape[0]] = torch.tensor(ts)

        return img_trans(d), label
Beispiel #48
0
class OCRIter(mx.io.DataIter):
    def __init__(self, count, batch_size, num_label, height, width):
        super(OCRIter, self).__init__()
        self.captcha = ImageCaptcha(fonts=['./data/OpenSans-Regular.ttf'])
        self.batch_size = batch_size
        self.count = count
        self.height = height
        self.width = width
        self.provide_data = [('data', (batch_size, 3, height, width))]
        self.provide_label = [('softmax_label', (self.batch_size, num_label))]

    def __iter__(self):
        for k in range(self.count / self.batch_size):
            data = []
            label = []
            for i in range(self.batch_size):
                num = gen_rand()
                img = self.captcha.generate(num)
                img = np.fromstring(img.getvalue(), dtype='uint8')
                img = cv2.imdecode(img, cv2.IMREAD_COLOR)
                img = cv2.resize(img, (self.width, self.height))
                cv2.imwrite("./tmp" + str(i % 10) + ".png", img)
                img = np.multiply(img, 1 / 255.0)
                img = img.transpose(2, 0, 1)
                data.append(img)
                label.append(get_label(num))

            data_all = [mx.nd.array(data)]
            label_all = [mx.nd.array(label)]
            data_names = ['data']
            label_names = ['softmax_label']

            data_batch = OCRBatch(data_names, data_all, label_names, label_all)
            yield data_batch

    def reset(self):
        pass
Beispiel #49
0
def createImage(flag=0):
    """
    Defining the method createImage() which will create
    and generate a Captcha Image based on a randomly
    generated strings. The Captcha Image generated is then
    incorporated into the GUI window we have designed.
    """
    global random_string
    global image_label
    global image_display
    global entry
    global verify_label

    # The if block below works only when we press the
    # Reload Button in the GUI. It basically removes
    # the label (if visible) which shows whether the
    # entered string is correct or incorrect.
    if flag == 1:
        verify_label.grid_forget()

    # Removing the contents of the input box.
    entry.delete(0, END)

    # Generating a random string for the Captcha
    random_string = ''.join(
        random.choices(string.ascii_letters + string.digits, k=6))

    # Creating a Captcha Image
    image_captcha = ImageCaptcha(width=250, height=125)
    image_generated = image_captcha.generate(random_string)
    image_display = ImageTk.PhotoImage(Image.open(image_generated))

    # Removing the previous Image (if present) and
    # displaying a new one.
    image_label.grid_forget()
    image_label = Label(root, image=image_display)
    image_label.grid(row=1, column=0, columnspan=2, padx=10)
Beispiel #50
0
def generateCaptcha(output_file):

    captcha_text = str(random.randint(1111, 9999))

    # Загружам наш бип файл - используем чтобы обозначить начало и конец результирующего файла
    beep = AudioSegment.from_wav(SOUNDS_DIR + "beep.wav")
    sounds_cache = []
    # Загружаем наши цифры от 0 до 9
    for digit in range(10):
        sounds_cache.append(
            AudioSegment.from_wav(SOUNDS_DIR + str(digit) + ".wav"))
    # Начинаем собирать результирующий файл
    result = beep
    for char in captcha_text:
        result += sounds_cache[int(char)]
    result += beep
    result.export(output_file + ".wav", format="wav")

    #создаем графическую капчу
    image = ImageCaptcha(fonts=[TTF_DIR + '1.ttf'])
    data = image.generate(captcha_text)
    image.write(captcha_text, output_file + ".png")

    return captcha_text
Beispiel #51
0
from Crypto.Cipher import AES
from captcha.image import ImageCaptcha
import os
import random
hash = SHA256.new()
semilla=""
r=0
image = ImageCaptcha(fonts=['./fon/A.ttf', './fon/B.ttf'])
for i in range(5):
	r=random.randrange(100)
	semilla=semilla+chr(r)
	print str(i)+" "+str(r)+" "+chr(r)+" "+semilla
	
print semilla+"\n"

data = image.generate(semilla)
image.write(semilla, '/tmp/out.png')
image.write(semilla, 'out.png')

os.remove("/tmp/out.png")

hash.update(semilla)
otra=hash.digest()
llave = ""
print otra

for i  in range(16):
	llave=llave+otra[i]
	print str(i)+" "+otra[i]+" "+llave
	print "\n"
	print llave
Beispiel #52
0
from io import BytesIO
from captcha.image import ImageCaptcha
import base64

image = ImageCaptcha()

captcha_text = "humble"
data = image.generate(captcha_text)
assert isinstance(data, BytesIO)
image.write(captcha_text, "out.png")

# print('data')
# print(type(data))
# print(type(data.getvalue()))
# print(str(data.getvalue()))

encoded = base64.b64encode(data.getvalue())
print(encoded)


# with open('out.png', 'r') as f:
#    c = f.read()
#    print(c)
Beispiel #53
0
__author__ = 'wenjusun'


from io import BytesIO
from captcha.image import ImageCaptcha
import random

image = ImageCaptcha(fonts=['/var/shijing/Abyssinica_SIL.ttf', '/usr/share/fonts/vlgothic/VL-Gothic-Regular.ttf'])

data = image.generate('1234')
#assert isinstance(data, BytesIO)
image.write('1234', 'out.png')


class CaptchImage():
    def get_path(self):
        return ""

    def generate_captch(self):

        return ""

ch_az=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
       'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
       '0','1','2','3','4','5','6','7','8','9']

def get_random_characters(width=4):

    return random.sample(ch_az,width)

Beispiel #54
0
from captcha.image import ImageCaptcha

image = ImageCaptcha(fonts=['C:\\Users\\user\\Desktop\\RandomCodes\\CaptchaGenerator\\A.ttf'])

data = image.generate('I am Pragyaditya Das')
image.write('I am Pragyaditya Das', 'out.png')
Beispiel #55
0
        print("Captcha's wrong")
        raise Exception()
    username=form["username"].value
    message=form["message"].value
    timestamp=int(time.time())
    data={"name":cgi.escape(form["title"].value),"markdown":cgi.escape(message),"author":cgi.escape(username),"date":timestamp}
    storage.append("comments-%i"%aid,data)
except KeyError:
    pass


seed=random.SystemRandom().randint(0,2**24)
random.seed(seed)
checkstr="".join(random.choice(string.digits+string.ascii_lowercase) for _ in range(5))
image = ImageCaptcha()
capt = image.generate(checkstr)
html=htmlgen.HTMLgen(pagelayout.getLayoutXML().decode('utf-8'),"Comments")
html.appendHTML("<form action=\"comments.py?aid=%i\" method=\"POST\">"%aid)
html.appendHTML("<input type=\"hidden\" name=\"seed\" value=\"%i\" />"%seed)
html.appendHTML("<input placeholder=\"Username\" name=\"username\" /><br />")
html.appendHTML("<input placeholder=\"Title\" name=\"title\" /><br />")
html.appendHTML("<textarea rows=\"25\" cols=\"80\" name=\"message\" placeholder=\"Compose your message. Markdown is enabled.\" ></textarea><br />")
html.appendHTML("<img src=\"data:image/png;base64,%s\" alt=\"Captcha image\" />" % base64.b64encode(capt.getvalue()).decode("UTF-8"))
html.appendHTML("<input placeholder=\"Captcha. lowercase only. case sensitive\" name=\"checkstr\" />")
html.appendHTML("<input type=\"submit\" /></form>")
count=storage.count("comments-%i"%aid)
for i in range(count):
    html.addArticle(aid=aid,**(storage.get("comments-%i"%aid,i)))

sys.stdout.buffer.write("Content-type: text/html\r\n\r\n".encode('utf8'))
sys.stdout.buffer.write("<!DOCTYPE html>".encode('utf8'))
class OCR_data(object):
	def __init__(self, num, data_dir, batch_size=50, len_code=4, height=30, width=80):
		self.num = num
		self.data_dir = data_dir
		self.batch_size = batch_size
		self.len_code = len_code
		self.height = height
		self.width = width
		self.captcha = ImageCaptcha()
		self.index_in_epoch = 0
		self._imgs = []
		self._labels = []
		for i in range(self.num):
			if i % 100 == 0:
				print '%s images have been created.' % i
			img, label = self.create_captcha()
			self._imgs.append(img)
			self._labels.append(label)
		self._imgs = np.array(self._imgs)
		self._labels = np.array(self._labels)


	def create_captcha(self):
		code, label = self.gen_rand()
		img = self.captcha.generate(code)
		img = np.fromstring(img.getvalue(), dtype='uint8')
		img = cv2.imdecode(img, cv2.IMREAD_COLOR)
		img = cv2.resize(img, (self.width, self.height))
		return (img, label)

	def gen_rand(self):
		buf = ''
		label = []
		for i in range(self.len_code):
			rnd = random.randint(0, 61)
			label.append(rnd)
			if rnd < 10:
				ascii_code = chr(rnd+48)
			elif rnd < 36:
				ascii_code = chr(rnd+65)
			else:
				ascii_code = chr(rnd+97)
			buf += ascii_code
		label_one_hot = self.dense_to_one_hot(label, 62)
		return buf, label_one_hot

	def dense_to_one_hot(self, labels_dense, num_classes):
		num_labels = len(labels_dense)
		index_offest = np.arange(num_labels) * num_classes
		labels_one_hot = np.zeros((num_labels, num_classes))
		labels_one_hot.flat[index_offest + labels_dense] = 1
		labels_one_hot = labels_one_hot.reshape(num_labels*num_classes)
		return labels_one_hot

	def next_batch(self, batch_size):
		start = self.index_in_epoch
		self.index_in_epoch += batch_size
		if self.index_in_epoch > self.num:
			perm = np.arange(self.num)
			np.random.shuffle(perm)
			self._imgs = self._imgs[perm]
			self._labels = self._labels[perm]
			start = 0
			self.index_in_epoch = batch_size
			assert batch_size <= self.num
		end = self.index_in_epoch
		return self._imgs[start:end], self._labels[start:end]
Beispiel #57
0
    num_lstm_layer = 2

    num_epoch = 10
    learning_rate = 0.001
    momentum = 0.9
    num_label = 4

    n_channel = 1
    contexts = [mx.context.gpu(0)]
    _, arg_params, __ = mx.model.load_checkpoint('ocr', num_epoch)

    num = gen_rand()
    print('Generated number: ' + num)
    # change the fonts accordingly
    captcha = ImageCaptcha(fonts=['./data/OpenSans-Regular.ttf'])
    img = captcha.generate(num)
    img = np.fromstring(img.getvalue(), dtype='uint8')
    img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
    img = cv2.resize(img, (80, 30))

    img = img.transpose(1, 0)

    img = img.reshape((1, 80 * 30))
    img = np.multiply(img, 1 / 255.0)

    data_shape = [('data', (1, n_channel * 80 * 30))]
    input_shapes = dict(data_shape)

    model = LSTMInferenceModel(num_lstm_layer,
                               SEQ_LENGTH,
                               num_hidden=num_hidden,
def generate_new_captcha_image(captcha_text):
    image = ImageCaptcha()
    image_data = str(base64.b64encode(image.generate(captcha_text).getvalue())).replace("b'", "", 1).replace("'", "")
    return image_data