def __init__(self):
        super(MainServer, self).__init__(socket.AF_INET, socket.SOCK_STREAM)

        # Getting a connection to the DB.
        self.db = DBUtil(DB_CONFIG)

        # Creating the necessary tables. for more information see the DDLs above...
        self.create_tables()

        self.socket_to_address_dict = {}

        self.socket_to_username_dict = {}

        # Creating dictionary that maps from client to the latest captcha that has been send to him.
        self.last_captcha_text = {}

        self.captcha_image_generator = ImageCaptcha(fonts=FONTS)

        self.captcha_audio_generator = AudioCaptcha(voicedir=VOICES_DIR)

        # Listening to the required IP and PORT.
        self.bind((BIND_IP, BIND_PORT))

        # Limiting the number of clients to BACKLOG.
        self.listen(BACKLOG)

        # starting a new thread that accepts new clients
        Thread(target=self.accept_clients).start()
Example #2
0
def get_captcha(text=None,
                lang=getattr(settings, 'CAPTCHA_DEFAULT_LANG',
                             CAPTCHA_DEFAULT_LANG)):
    fonts = getattr(settings, 'CAPTCHA_FONTS', None)
    length = getattr(settings, 'CAPTCHA_LENGTH', 5)
    voicedir = getattr(
        settings, 'CAPTCHA_VOICEDIR',
        os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data',
                     'audio_captcha', lang))
    # if audio for that language is not available
    # fallback to settings default (english: en)
    if not os.path.exists(voicedir):
        voicedir = getattr(
            settings, 'CAPTCHA_VOICEDIR',
            os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data',
                         'audio_captcha', CAPTCHA_DEFAULT_LANG))
    image = ImageCaptcha(fonts=fonts)

    try:
        audio = AudioCaptcha(voicedir=voicedir)
    except IndexError as e:
        raise AudioCaptchaLangPackNotFound()

    text = text or ''.join([
        random.choice(string.ascii_letters + string.hexdigits)  # nosec
        for i in range(length)
    ])

    data_image = image.generate(text)
    data_audio = audio.generate(text)
    return data_image, data_audio
Example #3
0
def generate_captcha():

    alphabet = "12345679abcdeghijkmnopqrtuvwxyz"
    text = ''.join(secrets.choice(alphabet) for i in range(5))

    image = ImageCaptcha()
    audio = AudioCaptcha(voicedir='audiocaptcha')

    img_data = image.generate(text)

    img_str = base64.b64encode(img_data.getvalue())
    img_base64 = "data:image/png;base64," + img_str.decode("utf-8")

    audio_data = audio.generate(text)

    audio_str = base64.b64encode(audio_data)
    audio_base64 = "data:audio/wav;base64," + audio_str.decode("utf-8")

    captcha_hash = bcrypt.hashpw(text, bcrypt.gensalt(12))

    return {
        "captcha_image": img_base64,
        "captcha_audio": audio_base64,
        "captcha_hashed": captcha_hash
    }
Example #4
0
    def _generate_audio(self):
        # Create an encoded audio CAPTCHA.
        captcha_generator = AudioCaptcha()
        audio_buffer = captcha_generator.generate(self._secret)
        encoded_audio = ('data:audio/wav;base64,%s' %
                            base64.encodestring(audio_buffer).decode())

        self.audio = encoded_audio
Example #5
0
def generate_audio_captcha(numbers):
    """
    Function to generate the audio captcha.
    :param numbers: is what will be generated
    :return:
    """
    audio = AudioCaptcha()  # Store the captcha into a variable image
    audio.write(numbers, "demo.wav")
Example #6
0
 def get_challenge(self, obj: models.Captcha):
     # TODO Does this need to be stored in the object instance, in case this method gets called twice?
     if obj.kind == models.Captcha.Kind.IMAGE:
         challenge = ImageCaptcha().generate(obj.content).getvalue()
     elif obj.kind == models.Captcha.Kind.AUDIO:
         challenge = AudioCaptcha().generate(obj.content)
     else:
         raise ValueError(f'Unknown captcha type {obj.kind}')
     return b64encode(challenge)
Example #7
0
def create_audio_captcha(captcha_text):
    # Create the audio captcha with the specified voice wav file library folder.
    # Each captcha char should has it's own directory under the specified folder ( such as ./voices),
    # for example ./voices/a/a.wav will be played when the character is a.
    # If you do not specify your own voice file library folder, the default built-in voice library which has only digital voice file will be used.
    # audio_captcha = AudioCaptcha(voicedir='./voices')
    # Create an audio captcha which use digital voice file only.
    audio_captcha = AudioCaptcha()
    audio_data = audio_captcha.generate(captcha_text)

    # audio_file = "./captcha_"+captcha_text+'.wav'
    # audio_captcha.write(captcha_text, audio_file)

    return audio_data
Example #8
0
def audio(request):
    global atext
    if request.method == 'POST':
        response = request.POST.get("captcha-text")

        if response == atext:
            return render(request, 'success.html')
        else:
            return render(request, 'audio.html', {'message': 'Try Again'})

    captcha_text = str(random.randint(1000, 9999))
    audio_captcha = AudioCaptcha()
    audio_data = audio_captcha.generate(captcha_text)
    audio_captcha.write(captcha_text, './static/cap.wav')
    atext = captcha_text
    return render(request, 'audio.html')
def main():
    if len(sys.argv) != 4:
        print("Usage: {} output_dir length count".format(sys.argv[0]))
        return

    output_dir = sys.argv[1]
    length = int(sys.argv[2])
    count = int(sys.argv[3])

    if not os.path.exists(output_dir):
        print("{} does not exist".format(output_dir))

    audio = AudioCaptcha(voicedir=os.path.join(
        os.path.dirname(os.path.realpath(__file__)), "voices_en"))

    for i in range(count):
        inp = ''.join(random.choices(CHARSET, k=length))
        filename = "{}_{}.wav".format(inp, secrets.token_hex(4))
        audio.write(inp, os.path.join(output_dir, filename))
        print("Generated: {}".format(filename))
def create_audio_captcha():

    # Create the audio captcha with the specified voice wav file library folder.
    # Each captcha char should has it's own directory under the specified folder ( such as ./voices),
    # for example ./voices/a/a.wav will be played when the character is a.
    # If you do not specify your own voice file library folder, the default built-in voice library which has only digital voice file will be used. 
    # audio_captcha = AudioCaptcha(voicedir='./voices')
    # Create an audio captcha which use digital voice file only.
    audio_captcha = AudioCaptcha()

    # Because we use the default module voice library, so we can only generate digital text voice.
    captcha_text = create_random_digital_text()

    # Generate the audio captcha file.
    audio_data = audio_captcha.generate(captcha_text)

    # Save the autiod captcha file.
    audio_file = "./captcha_"+captcha_text+'.wav'
    audio_captcha.write(captcha_text, audio_file)

    print(audio_file + " has been created.")
def create_audio_and_convert(output_dir, captcha_text):
    pwd = os.getcwd()
    work_dir = pwd + '\\symbols\\'
    #combined_sounds = None
    #for symbol in captcha_text:
    #tts_service = random.choice(tts_list)
    #raw_path = work_dir + tts_service + '\\' + symbol
    #sound = AudioSegment.from_wav(raw_path + ".wav")
    #if combined_sounds is None:
    #    combined_sounds = sound
    #else:
    #    combined_sounds = combined_sounds + sound

    audio = AudioCaptcha()
    audio.write(captcha_text, output_dir)

    if not os.path.exists(pwd + '\\' + tempDir):
        print("Creating temp directory " + tempDir)
        os.makedirs(pwd + '\\' + tempDir)

    output_dir_tts = pwd + '\\' + tempDir + '\\'
    wav_audio_path = output_dir_tts + captcha_text + '.wav'
    audio.export(wav_audio_path, format="wav")

    plt.interactive(False)
    clip, sample_rate = librosa.load(wav_audio_path, sr=None)
    fig = plt.figure(figsize=[0.415, 0.210])
    ax = fig.add_subplot(111)
    ax.axes.get_xaxis().set_visible(False)
    ax.axes.get_yaxis().set_visible(False)
    ax.set_frame_on(False)
    S = librosa.feature.melspectrogram(y=clip, sr=sample_rate)
    librosa.display.specshow(librosa.power_to_db(S, ref=np.max))
    filename = os.path.join(output_dir, captcha_text + '.jpg')
    plt.savefig(filename, dpi=400, bbox_inches='tight', pad_inches=0)
    plt.close()
    fig.clf()
    plt.close(fig)
    plt.close('all')
    del clip, sample_rate, fig, ax, S
Example #12
0
def create_audio_captcha():

    # Create the audio captcha with the specified voice wav file library folder.
    # Each captcha char should has it's own directory under the specified folder ( such as ./voices),
    # for example ./voices/a/a.wav will be played when the character is a.
    # If you do not specify your own voice file library folder, the default built-in voice library which has only digital voice file will be used. 
    # audio_captcha = AudioCaptcha(voicedir='./voices')

    # Create an audio captcha which use digital voice file only.
    audio_captcha = AudioCaptcha(voicedir='./voices')
    #audio_captcha = AudioCaptcha(voicedir='C:\\Users\\SIDDHARTHA\\Dropbox\\Trinity Data Science\\Scalable Computing\\Projects\\audio-alphabet')
    # Because we use the default module voice library, so we can only generate digital text voice.
    #captcha_text = create_random_digital_text()
    captcha_text = "a"

    # Generate the audio captcha file.
    audio_data = audio_captcha.generate(captcha_text)

    # Save the autiod captcha file.
    audio_file = "./"+captcha_text+'.wav'
    audio_captcha.write(captcha_text, audio_file)

    print(audio_file + " has been created.")
Example #13
0
def generate_audio_captcha(num):
    audio = AudioCaptcha()
    data = audio.generate(num)
    audio.write(num, 'captcha.wav')
from captcha.audio import AudioCaptcha

from twisted.internet import reactor
from twisted.web import resource
from twisted.web import static
from twisted.web.server import Site
from twisted.web.util import redirectTo

TEMPLATE_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                            "templates")
lookup = TemplateLookup(directories=[TEMPLATE_DIR],
                        output_encoding='utf-8',
                        filesystem_checks=False,
                        collection_size=500)
audio = AudioCaptcha(
    voicedir=os.path.join(TEMPLATE_DIR, "assets/captcha-audio"))


def stringifyRequestArgs(args):
    # Convert all key/value pairs from bytes to str.
    str_args = {}
    for arg, values in args.items():
        arg = arg if isinstance(arg, str) else arg.decode("utf-8")
        values = [
            value.decode("utf-8") if isinstance(value, bytes) else value
            for value in values
        ]
        str_args[arg] = values

    return str_args
Example #15
0
from captcha.audio import AudioCaptcha
from captcha.image import ImageCaptcha

audio = AudioCaptcha(voicedir='/path/to/voices')
image = ImageCaptcha(fonts=['/path/A.ttf', '/path/B.ttf'])

data = audio.generate('1234')
audio.write('1234', 'out.wav')

data = image.generate('1234')
image.write('1234', 'out.png')
Example #16
0
from captcha.image import ImageCaptcha
from captcha.audio import AudioCaptcha

##################### 图片验证码

image = ImageCaptcha(fonts=['almfixed.ttf', 'Arimo-BoldItalic.ttf'])
# 添加想要的字体

image.write("FishC", "captcha2.png")
# 第一个参数指定要写入的内容,第二个参数是名字

##################### 音频验证码
audio = AudioCaptcha(voicedir='dog.wav')
# 参数指定声音素材

audio.write("dog", 'captcha.wav')
Example #17
0
def test_audio_generate():
    captcha = AudioCaptcha()
    data = captcha.generate('1234')
    assert isinstance(data, bytearray)
    assert bytearray(b'RIFF') in data
Example #18
0
def test_audio_random():
    captcha = AudioCaptcha()
    data = captcha.random(4)
    assert len(data) == 4
Example #19
0
from captcha.audio import AudioCaptcha
audio = AudioCaptcha('data/')
audio.write('1024', 'e:/test.mp3')
Example #20
0
from captcha.audio import AudioCaptcha
from captcha.image import ImageCaptcha

outdir = 'C:/local/captcha/'

audio = AudioCaptcha(voicedir=outdir + 'voices')
image = ImageCaptcha(fonts=[outdir + 'Ubuntu-M.ttf', outdir + 'platech.ttf'])

#data = audio.generate('1234')
#audio.write('1234', 'out.wav')

s = '1234'
data = image.generate(s)
image.write(s, outdir + s + '.png')
Example #21
0
def GenerateAudioCaptcha(text, out_path, voicedir=None):
    audio = AudioCaptcha(voicedir=voicedir)
    # data = audio.generate(text)
    audio.write(text, out_path)
Example #22
0
data = image.generate("CCCCVGFD")
image.write('CCCCVGFD', 'demo2.png')

# In[10]:

from captcha.image import ImageCaptcha

image = ImageCaptcha(width=280, height=90)
data = image.generate("BHBHGFFDD")
image.write('BHBHGFFDD', 'demo3.png')

# In[16]:

from captcha.image import ImageCaptcha

image = ImageCaptcha(width=270, height=80)
data = image.generate("12CCP890")
image.write('12CCP890', 'demo4.png')

# # Audio Captcha

# In[27]:

from captcha.audio import AudioCaptcha

audio = AudioCaptcha()
data = audio.generate("99898")
audio.write('99898', 'demo6.wmv')

# In[ ]:
Example #23
0
# -*- coding: utf-8 -*-
"""
Created on Mon Oct  7 23:15:59 2019

@author: SIDDHARTHA
"""

from captcha.audio import AudioCaptcha
from captcha.image import ImageCaptcha

audio = AudioCaptcha(voicedir='C:\\Users\\SIDDHARTHA\\Downloads\\19301936-project3\\Audio')

data = audio.generate('1234')
audio.write('1234', 'out.wav')