Python Captcha Generator – Create Audio And Image Captcha in Python

Python Captcha FeaImg

Hey coders! I am pretty sure have come across CAPTCHA on a number of websites that validate if you are a human or a robot. Yes, you are right they are those annoying things that come when you are finishing off a long form or even doing payments at times. Look at a sample captcha below.

Captcha Example
Captcha Example

In this tutorial, we will try to generate our own captchas using Python! Interesting right? Let’s dive right into the code!

Install The Captcha Module

So just like any other program, the very first step is to install the CAPTCHA library. In order to do that open your command prompt and run the following command:

pip install captcha

Steps to Create Captcha Generator in Python

We would try to generate both images as well as audio captchas in this tutorial. Hence, when you are done installing the library, you need to import the ImageCaptcha and AudioCaptcha functions from captcha.image and captcha.audio sub-libraries respectively.

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

Generating Image Captcha in Python

Let’s start by creating an Image captcha. We will be taking input about the text that needs to display on the screen from the user and then generate the image captcha for the data.

To create the captcha, we need to create an Imagecaptcha object and then generate the captcha for the data using the generate function. Look at the code below.

img = ImageCaptcha(width = 280, height = 90)
text = input("Enter the Text for Captcha: ")
Cap_data = img.generate(text)

The image is generated but to save the image we need to use the write function using the code below.

img.write(text, 'Sample_Cap_1.png')

After we enter AskPython as the text for the captcha, we get the captcha as shown below:

Sample Cap 1 1
Sample Cap 1 1

Looks pretty cool right?!

Generating Audio Captcha Using Python

Now let’s try to generate an Audio captcha as well. For the audio captcha, we will try to generate a numerical captcha for the numbers entered by the user. Look at the code below. The audio captcha works similarly to the image captcha as well.

audio = AudioCaptcha()
text = input("Enter the Text for Captcha: ")
data = audio.generate(text)
audio.write(text,'Sample_Cap_2.wav')

When we enter 3422, we will hear something like the below.

It would definitely sound very weird but listen carefully! You will hear the numbers in between all the noise present in the audio.

Conclusion

Congratulations! You just learned how to generate your own captchas using the Python programming language. You can play around with the captchas and generate a lot more captchas. Just have fun with it!

Happy learning! 😁