def make_captcha(text=make_gibberish()): try: captcha = Claptcha(text, "../../FreeMono.ttf") except ClaptchaError as err: print(err) captcha = Claptcha(text, "src/resources/FreeMono.ttf") _, img = captcha.bytes return text, base64.b64encode(img.read()).decode()
def captcha(self, text: str) -> BytesIO: """ Converts a text to a captcha image. """ pic = Claptcha(text, "./assets/fonts/consola.ttf") bytes = pic.bytes[1] del pic gc.collect() return bytes
def captcha_number() -> dict: # Number CAPTCHA result = {} try: question = "" for _ in range(randint(3, 6)): question += str(randint(0, 9)) answer = question image = Claptcha(source=question, font=glovar.font_number, size=(300, 150), noise=glovar.noise) image_path = f"{get_new_path('.png')}" image.write(image_path) result = { "image": image_path, "question": lang("question_number"), "answer": answer, "limit": glovar.limit_try + 1 } except Exception as e: logger.warning(f"Captcha number error: {e}", exc_info=True) return result
def generate_captcha(): from claptcha import Claptcha word = random.choice( [x for x in COMMON_WORDS_SET if len(x) < CAPTCHA_WORD_LEN]) c = Claptcha(word, "gui_files/FreeMono.ttf", margin=(20, 10)) image_b64 = base64.b64encode(c.bytes[1].getvalue()).decode("utf-8") return "data:image/png;base64," + image_b64, word
def __init__(self, model, test_batch_count=100): self.model = model self.test_batch_count = test_batch_count c = Claptcha('g0vt1k', 'arial.ttf') text, image = c.image self.img_array = np.asarray(image)
def genClapchaImgStr(capthaText): c = Claptcha(capthaText, FONT, (500, 150), resample=Image.BICUBIC, noise=0.5) #c.size = (250, 200) c.margin = (5, 5) _, img = c.bytes prefix = f'data:image/png;base64,' imgStr = prefix + base64.b64encode(img.read()).decode('utf-8') return imgStr
def generateCaptchaImage(): global CAPTCHA_TEXT c = Claptcha(generateRandomCaptcha(), 'captcha/FreeMono.ttf', resample=Image.BICUBIC, noise=0.3) CAPTCHA_TEXT, _ = c.write('captcha/static/captcha/captcha.png') return CAPTCHA_TEXT
def gen_Captcha(FOLDER, nb_pic): for _ in range(nb_pic): ''' Random length captcha''' c = Claptcha(rdString, FONT_PATH + '/Raleway-SemiBold.ttf', (300, 100), resample=Image.BILINEAR, noise=randomNoise()) text, _ = c.write(FOLDER + 'temp.png') ''' print(text) ''' os.rename(FOLDER + 'temp.png', FOLDER + text + '.png')
def gen_Fix_Captcha(FOLDER, nb_pic): for _ in range(nb_pic): ''' Fixed length captcha''' c = Claptcha(rdFixString, randomFont(), (300, 100), resample=Image.BILINEAR, noise=randomNoise()) text, _ = c.write(FOLDER + 'temp.png') ''' print(text) ''' os.rename(FOLDER + 'temp.png', FOLDER + text + '.png')
def gen_Captcha(FOLDER, nb_pic, img_w, img_h): for _ in range(nb_pic): ''' Random length captcha''' c = Claptcha(rdString, randomFont(), (img_w, img_h), resample=Image.BILINEAR, noise=0) if not os.path.exists(FOLDER): os.makedirs(FOLDER) text, _ = c.write(FOLDER + 'temp.png') ''' print(text) ''' os.rename(FOLDER + 'temp.png', FOLDER + text + '.png')
def gen_captcha(self): text = "".join( choice(ascii_letters) for _ in range(self.extras.get("char_length", 6))) filename = "".join(choice(ascii_letters) for _ in range(12)) + ".png" c = Claptcha(text, choice([f"fonts/{f}" for f in os.listdir("fonts")]), resample=Image.BICUBIC, noise=self.extras.get("noise", 0.3)) c.write(filename) return text, filename
def next_img(rndLetters, font, im_w, im_h, noise): captcha = Claptcha(rndLetters, font, (300, 100), noise = noise) text, img = captcha.image img_dat = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2GRAY) img_dat = cv2.resize(img_dat, (im_w, im_h)) img_dat = np.array(img_dat) / 255.0 if K.image_data_format() == 'channels_first': img_dat = np.expand_dims(img_dat, axis=3) else: img_dat = np.expand_dims(img_dat, axis=0) img_dat = img_dat.T return img_dat
def gen_captcha(): # NOTE: This causes an invalid pointer or segfault on some systems. # See https://github.com/naphthasl/sakamoto/issues/7 code = ''.join([str(random.choice(string.hexdigits)) for _ in range(6)]) x = Captcha(image=Claptcha(source=code, font="./static/freemono/FreeMono.ttf", noise=0.3).bytes[1].read(), code=code, created=round(time.time())) commit() return x.id
def data_generator(): while True: x_batch = [] y_batch = [] for i in range(0, batch_size): rand_string = random_string() rand_font = random_font() c = Claptcha(rand_string, rand_font) text, image = c.image x = np.asarray(image) y = encode_text(rand_string) x_batch.append(x) y_batch.append(y) yield np.array(x_batch), np.array(y_batch)
def captcha( ): #generate a captcha with random letters with a length between min_char and max_char min_char = 4 max_char = 7 allchar = string.ascii_letters + string.digits captchaWord = "".join( choice(allchar) for x in range(randint(min_char, max_char))).lower() # Initialize Claptcha object with "Text" as text and FreeMono as font c = Claptcha(captchaWord, "./Captcha/FreeMono.ttf") # Save a PNG file 'test.png' text, file = c.write('./cache/captcha.png') #print(text) # 'Text' thebugs are everywhere! #print(file) # 'test.png' debugging! return text, file
def _gen(): try: fp = tempfile.mkstemp(prefix='captcha')[1] r = random.Random() secret = '' tmpFont = ttfFont() for x in range(length): secret += str(r.randint(0, 9)) secret = 'abcd' c = Claptcha(secret, tmpFont, resample=Image.BICUBIC, noise=noise) c.write(fp) return secret, fp except Exception: return None, None
def generate_claptcha_image(self, sequence): """ Receive a CAPTCHA sequence (string), creates a CAPTCHA image, and returns the generated file name. Using Calptcha to generate """ random_id = str(uuid.uuid4())[-8:] filename = "./{dirname}/{sequence}_{random_id}.png".format( dirname=self._base_dir_name, sequence=sequence, random_id=random_id) noise_level = round( random.uniform(0.0, 0.1), ndigits=3 ) # Randomly select a noise level for our generation, from a uniform distribution c = Claptcha(sequence, self.font, (self.img_w / 1.5, self.img_h / 1.5), noise=noise_level, resample=Image.BICUBIC) c.write(filename) return filename
def generate_captcha(outdir, font, num_captchas=20000): alphabets = 'abcdefghijklmnopqrstuvwxyz' alphabets = alphabets.upper() try: os.mkdir(outdir) except: 'Directory already present,writing captchas to the same' #rint(char_num_ind) # select one alphabet if indicator 1 else number for i in range(num_captchas): char_num_ind = list(np.random.randint(0, 2, 4)) text = '' for ind in char_num_ind: if ind == 1: loc = np.random.randint(0, 26, 1) text = text + alphabets[np.random.randint(0, 26, 1)[0]] else: text = text + str(np.random.randint(0, 10, 1)[0]) c = Claptcha(text, font) text, image = c.image image.save(outdir + text + '.png')
from utils.utils import random_text from captcha.image import ImageCaptcha from glob import glob from PIL import Image from claptcha import Claptcha WIDTH = 250 HEIGHT = 80 IMAGES_PER_TEXT_LENGTH = 100 OUTPUT_DIR = ".\\captcha_images\\" FONTS = glob("C:\\Windows\\fonts\\*.ttf") CHARACTERS = [ x for x in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ] for font in FONTS: for len in range(5, 11): for i in range(IMAGES_PER_TEXT_LENGTH): captcha_text = random_text(CHARACTERS, len) claptcha = Claptcha(captcha_text, font, size=(WIDTH, HEIGHT), resample=Image.NEAREST, noise=0.8) claptcha.write(OUTPUT_DIR + captcha_text + ".jpg") captcha_text = random_text(CHARACTERS, len) image_captcha = ImageCaptcha(WIDTH, HEIGHT, [font]) image_captcha.generate_image(captcha_text) image_captcha.write(captcha_text, OUTPUT_DIR + captcha_text + ".jpg")
start_time = datetime.datetime.now() print("Generating CLAPTCHA images.") for train in range(training_length): if train % 10 == 0: print("Completed {}/{} - {}.".format( train, training_length, (datetime.datetime.now() - start_time))) word = ''.join([ characters[random.randrange(0, len(characters))] for i in range(character_length) ]) try: claptcha = Claptcha(word, fonts[random.randint(0, (len(fonts)) - 1)], resample=Image.BICUBIC, noise=(random.randint(0, 6)) / 10) text, image = claptcha.image claptcha_data.append((text, image)) image = ImageCaptcha(fonts=fonts) data = image.generate(word) data.seek(0) img = Image.open(data) captcha_data.append((word, img)) except Exception as e: print(e) exit(0)
async def verify(message): author = message.author try: DataJson['setup'][str(message.guild.id)] except KeyError: embed = discord.Embed( title="Error", description="Bot not set up, please contact a server administrator", color=0xFF0000) await message.channel.send(embed=embed) return False role = discord.utils.get(message.guild.roles, id=DataJson['Verirole'][str(message.guild.id)]) if role in author.roles: embed = discord.Embed( title="Error", description="You are already verified in this server", color=0xFF0000) await message.channel.send(embed=embed) return False try: role.id except AttributeError: embed = discord.Embed( title="Error", description= "Specified role not found, please contact a server administrator", color=0xFF0000) await message.channel.send(embed=embed) return False embed = discord.Embed( title="Verification", description="Check your DM's to continue the verification process", color=0x808080) await message.channel.send(author.mention, embed=embed) channel = await author.create_dm() #create captcha captchatext = ''.join(random.SystemRandom().choice(string.ascii_uppercase) for _ in range(6)) c = Claptcha(captchatext, r'assets/Carlito-Regular.ttf') #send captcha embed = discord.Embed( title="Verification", description= f"Hello. Welcome to the {message.guild} server.\nPlease complete the following captchas to get access to the server." ) if DataJson['verification']['captcha'][str(message.guild.id)] == "True": image = discord.File(c.bytes[1], filename="captcha.png") embed.set_image(url="attachment://captcha.png") await channel.send(file=image, embed=embed) else: await channel.send(embed=embed) if DataJson['verification']['captcha'][str(message.guild.id)] == "True": msg = await client.wait_for('message') if msg.content != captchatext: embed = discord.Embed(title="Captcha Failed", color=0xFF0000) await channel.send(embed=embed) return if DataJson['verification']['reaction'][str(message.guild.id)] == "True": check = random.randint(1, 3) if check == 1: reaction = u"\u2705" if check == 2: reaction = u"\u2611" if check == 3: reaction = u"\u2714" msgc = 'React to this message with the check emoji' msg = await channel.send(msgc) emojiarr = [reaction] oldemoji = "" for c in range(3): emoji = random.choice(emojis.emojistring) while emoji == oldemoji: emoji = random.choice(emojis.emojistring) emojiarr += [emoji] random.shuffle(emojiarr) for e in emojiarr: await msg.add_reaction(e) def ac(reaction, user): return user == message.author msgreaction, user = await client.wait_for('reaction_add', timeout=180.0, check=ac) if not msgreaction.emoji == reaction: embed = discord.Embed(title="Captcha Failed", color=0xFF0000) await channel.send(embed=embed) return randomWord = random_line('Storage/words.txt') def check(message): return message.content == randomWord await channel.send(f"Please say the magic word: `{randomWord}`") msg = await client.wait_for('message', timeout=180.0) if msg.content != randomWord: embed = discord.Embed(title="Captcha Failed", color=0xFF0000) await channel.send(embed=embed) return role = discord.utils.get(message.guild.roles, id=DataJson['Verirole'][str(message.guild.id)]) await author.add_roles(role) await channel.send( f"Congratulations, you have been verified in the {message.guild} server!" )
def getPassword(path): c = Claptcha(randomString, settings.STATIC_ROOT+"/FreeMono.ttf", (250,75), resample=Image.BICUBIC, noise=0.1) text, image = c.image image.save(path) return text, image
import cv2 import tensorflowjs as tfjs import random import string from claptcha import Claptcha def randomString(): rndLetters = (random.choice(string.ascii_uppercase) for _ in range(3)) return "".join(rndLetters) # Initialize Claptcha object with random text, FreeMono as font, of size # 100x30px, using bicubic resampling filter and adding a bit of white noise r_string = randomString() c = Claptcha(r_string, "FreeMono.ttf", (1000,500), resample=Image.BICUBIC, noise=0.3) text, _ = c.write('captcha1.png') img = Image.open('captcha1.png') img.show() print('Generated captcha : ',text) # 'PZTBXB', string printed into captcha1.png x1 = 0 y1 = 0 w1 = 0 z1 = 0 ready = 'a' while(ready != 'r'): ready = input("type r when u are ready : ")
from claptcha import Claptcha c = Claptcha("2020", "2020.ttf", noise=0.4) c.write("2020.png")
print("Generating using Claptcha") for i in bar(range(num_images)): font = random.choice(fonts) #TODO: Generate some random string here text = gen_random_string(char_set) text_len = len(text) #Generator selector selection = random.randint(0, 1) #Number of generators #selection = 0 #For clapcha #Generate random amount of noise... if selection == 0: c = Claptcha(text, os.path.join(FONT_DIR, font), noise=np.random.uniform(low=0.2)) #c.write(os.path.join(DATA_DIR, str(text_len), text+'.png')) # Get PIL Image object text, image = c.image #plt.imshow(image) #plt.show() try: image.save(os.path.join(DATA_DIR, str(text_len), text+'.jpg')) except OSError as e: print(e) continue elif selection == 1: try: #captcha_gen.write(text, os.path.join(DATA_DIR, str(text_len), text+'.jpg')) image = captcha_gen.generate_image(text) image.save(os.path.join(DATA_DIR, str(text_len), text+'.jpg'))
import env from PIL import Image from claptcha import Claptcha import random import string import asyncio from discord import Spotify import requests def randomString(): rndLetters = (random.choice(string.ascii_uppercase) for _ in range(6)) return "".join(rndLetters) c = Claptcha(randomString, "Mom.ttf", noise=0.4) class Cogs(commands.Cog): def __init__(self, bot): self.bot = bot @commands.group(name='reload', hidden=True, invoke_without_command=True) @commands.is_owner() async def _reload(self, ctx, *, module=""): extensions = env.extensions embed2 = discord.Embed( title=f"<a:loading:735927020508414012> Reloading Cog(s)..") m = await ctx.send(embed=embed2) if module == "": try:
##import libraries import random import string from PIL import Image from claptcha import Claptcha import os #generate random string def randomString(): rndLetters = (random.choice(string.ascii_uppercase) for _ in range(6)) return "".join(rndLetters) # Initialize Claptcha object with random text, Newfont as font, of size # 300x150px, using bicubic resampling filter for i in range(2000): c = Claptcha(randomString, "newfont.ttf", (300, 150), resample=Image.BICUBIC) text, _ = c.write('captcha1.png') os.rename('captcha1.png', text + ".png")
from claptcha import Claptcha # Initialize Claptcha object with "Text" as text and FreeMono as font c = Claptcha("Text", "FreeMono.ttf") # Get PIL Image object text, image = c.image print(text) # 'Text' print(type(image)) # <class 'PIL.Image.Image'> # Get BytesIO object (note that it will represent a different image, just # with the same text) text, bytes = c.bytes print(text) # 'Text' print(type(bytes)) # <class '_io.BytesIO'> # Save a PNG file 'test.png' text, file = c.write('test.png') print(text) # 'Text' print(file) # 'test.png'
# Global variables CharInCaptcha = 5 pathname = os.path.dirname(__file__) path = pathname + "\\images" #Main for _ in range(1): #Create Captcha and write to Images Folder contours2 = [] num_array = [] String = CaptchaFunctions.randomString(CharInCaptcha) StringName = (String + '.png') c = Claptcha(String, "FreeMono.ttf", noise=0.6) text, _ = c.write(os.path.join(path, StringName)) contours, hierarchy, returnImage = CaptchaFunctions.ImageCreate( StringName, path) CaptchaFunctions.elimContours(contours, contours2, hierarchy) #Exception checker if (CharInCaptcha < len(contours2)): os.remove(os.path.join(path, StringName)) continue try: for i in range(len(contours2)): (_, _, w, _) = cv2.boundingRect(contours2[i]) if (w > 40):
import random import string from PIL import Image from claptcha import Claptcha def randomString(): rndLetters = (random.choice(string.ascii_uppercase) for _ in range(6)) return "".join(rndLetters) # Initialize Claptcha object with random text, FreeMono as font, of size # 100x30px, using bicubic resampling filter and adding a bit of white noise c = Claptcha(randomString, "FreeMonospaced-7ZXP.ttf", (100, 30), resample=Image.BICUBIC, noise=0.3) text, _ = c.write('captcha1.png') print(text) # 'PZTBXB', string printed into captcha1.png text, _ = c.write('captcha2.png') print(text) # 'NEDKEM', string printed into captcha2.png # Change images' size to 150x90 and estimated margin to 25x25 c.size = (150, 90) c.margin = (25, 25) text, _ = c.write('captcha3.png') print(text) # 'XCQYVS', captcha3.png has different dimentions than # captcha1.png and captcha2.png