The question of when Artificial Intelligence (AI) will be advanced enough to write its own code, resulting in a self-proliferation of AI’s is still a matter for science fiction writers. However, recent advances in Machine Learning (ML) have made it possible to automate the writing of code snippets, or even help assist programmers by automating the writing of “whole lines or entire functions right inside your editor,” which is the promise of GitHub’s Copilot.
The saying, “a good programmer is a lazy programmer,” is perhaps perfectly epitomized in using code to automate the writing of code. This article will help you do just that, using Python. 

The versatility and ease of use of Python, as well as the availability of APIs powered by AI, have opened up myriad programming possibilities in the realm of automation. I’ll show you how to use Python to write a program that recognizes voice input and generates the requested code in just a few steps:

  1. Set up voice recognition so we can tell the AI what to write for us
  2. Make sure the AI can parse the voice input 
  3. Code the code – write the routines you want the AI to be able to handle for you

All set to make your coding life that much easier? Let’s get started.

Before You Start: Install The AI CodeWriter Python Environment

To follow along with the code in this article, you can download and install our pre-built AI CodeWriter environment, which contains a version of Python 3.9 and the packages used in this post, along with already resolved dependencies!

In order to download this ready-to-use Python environment, you will need to create an ActiveState Platform account. Just use your GitHub credentials or your email address to register. Signing up is easy and it unlocks the ActiveState Platform’s many benefits for you!

Or you could also use our State tool to install this runtime environment.

runtime

For Windows users, run the following at a CMD prompt to automatically download and install our CLI, the State Tool along with the AI CodeWriter runtime into a virtual environment:

powershell -Command "& $([scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://platform.www.activestate.com/dl/cli/install.ps1'))) -activate-default Pizza-Team/AI-CodeWriter"

For Linux users, run the following to automatically download and install our CLI, the State Tool along with the AI CodeWriter runtime into a virtual environment:

sh <(curl -q https://platform.www.activestate.com/dl/cli/install.sh) --activate-default Pizza-Team/AI-CodeWriter

1–AI That Accepts Voice Input

It’s the 21st century, so if we’re going to tell the AI to write some code for us, we’re going to talk to it! The first step in creating our automated code writer is to make sure it can recognize our voice input. To do so, we’ll create a listen function using the libraries you just installed using the AI CodeWriter environment. We can import these libraries along with a few of the standard Python libraries like this:

import speech_recognition as sr
import os
import time
import numpy as np

In the function, we’ll use the SpeechRecognition library to activate your machine’s microphone, then convert the audio to text in the form of a string. When the microphone has been activated, we can print out a statement as well as the text that the microphone hears so that we know it’s working properly. I’ll also include conditionals to cover common errors that may occur if there’s too much background noise or if the request to the Google Cloud Speech API fails.

def listen():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("I am listening...")
        audio = r.listen(source)
    data = ""
    try:
        data = r.recognize_google(audio)
        print("You said: " + data)
    except sr.UnknownValueError:
        print("Google Speech Recognition did not understand audio")
    except sr.RequestError as e:
        print("Request Failed; {0}".format(e))
    return data    

Feel free to play around with the listen function to see how the Google Cloud Speech API interprets your voice. But now that the AI can hear us, we need to ensure it can parse and interpret the input string in order to write the code that we want. 

2–AI That Interprets Voice Input

We will need to parse the input string depending on the desired code you want to output. Some things to keep in mind:

  • To create a list, the format of the string will need to be different from the format you would use to create a dictionary or a function. 
  • We’ll also want to account for multiple data types so that we can differentiate between string one and the integer 1. This is where we can use a function to convert all text-based numbers to floats. 
    • This is especially useful when the Google Cloud Speech API struggles to consistently interpret numbers in the same format. 
def text2float(textnum, numwords={}):
    if not numwords:
        units = [
        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
        "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
        "sixteen", "seventeen", "eighteen", "nineteen",
        ]
        tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
        scales = ["hundred", "thousand", "million", "billion", "trillion"]
        numwords["and"] = (1, 0)
        for idx, word in enumerate(units):    numwords[word] = (1, idx)
        for idx, word in enumerate(tens):     numwords[word] = (1, idx * 10)
        for idx, word in enumerate(scales):   numwords[word] = (10 ** (idx * 3 or 2), 0)
    current = result = 0
    for word in textnum.split():
        if word not in numwords:
            raise Exception("Illegal word: " + word)
        scale, increment = numwords[word]
        current = current * scale + increment
        if scale > 100:
            result += current
            current = 0
    return float(result + current)

Just as with Siri, Google Assistant, or Alexa, the way in which something is stated determines how well it is interpreted. There are plenty of different ways to say, “create a list with the number five, the word player, and the number seven” or “write the function x squared plus one.” Part of the task is to identify the keyword list or function followed by the inputs for that keyword. Of course, how we parse the inputs will be dependent on the keyword used. To make this easier, we will assume that the keyword precedes any input arguments in the string.

3–AI That Writes Code

The goal is to have a single function that identifies the keyword, then directs the text string to another function to create the object identified by the keyword. This can be implemented with a series of if statements. The number of keywords is unlimited, and they can be modified according to your needs. For the sake of brevity, I will illustrate two examples of this strategy: 

  • Creation of a list 
  • Creation of a polynomial function 

Thus, our write_code function will look something like this:

def write_code(data):
    global listening
    data = data.split(" ")
    data = [x.lower() for x in data]
    if "list" in data:
        output = create_list(data)
        listening = False
    if "polynomial" in data:
        output = create_polynomial(data)        
        listening = False
        
    if "stop listening" in data:
        listening = False
        print('Listening stopped')
        
    return listening, output

To make it easier to process, we can split the text string up into multiple strings (delineated by spaces) or make everything lowercase. Then, we proceed with the if statements using our two chosen keywords, list and polynomial. Now, we need to create the functions corresponding to each keyword. Let’s start with lists

Automatically Create a List

As mentioned previously, we want to be able to specify the data type for each element in the list, whether it be a string, an integer, or a float. One might say: 

  • “I would like a list containing the integer seven and the string basketball.” 

Notice that the data type comes before the element. Thus, we can search for the index of the data type (i.e., integer), take the next element, and convert it to the data type. This is where the text2float function comes in handy. We loop through all of the elements of an identical data type, add them to an empty list, and move on to the next data type. The function looks something like this:   

def create_list(data):
    l = list()
    if 'integer' in data:
        indices = [i+1 for i, s in enumerate(data) if 'integer' in s]
        for i in indices:
            try:
                l.append(int(data[i]))
            except ValueError:
                l.append(text2float(data[i]))
    if 'float' in data:
        indices = [i+1 for i, s in enumerate(data) if 'float' in s]
        for i in indices:
            l.append(float(data[i]))
    if 'string' in data:
        indices = [i+1 for i, s in enumerate(data) if 'string' in s]
        for i in indices:
            l.append(data[i])
    return l

I used integer, float, and string because they are the most common Python data types, but you can add or adopt any of the other data types.  

Automatically Create a Polynomial Function

For our polynomial function, one might say: 

  • “Create the polynomial function two times x squared plus four times x plus seven.” 

At first, it may seem difficult to implement this in Python because the function has multiple terms with a different order and different coefficients. We can make a few assumptions to simplify this, however, so that the only important information that needs to be conveyed is a list containing the values of the coefficients. For example, we can assume that:  

  • The length of the list of coefficients (minus 1) corresponds to the maximum order (i.e., length 3 corresponds to a second-order polynomial) 
  • The coefficients are in descending order (i.e., the last coefficient is the constant) 

This means that we only have to state the coefficients, so the previous statement would become something like: 

  • “Create a polynomial function with coefficients two four seven.” 

This is much easier to implement once we recognize that everything after the word coefficient is a coefficient. Once we identify, separate, and convert the coefficients to float, we can use numpy poly1d to create the polynomial function. The function looks like this:  

def create_polynomial(data):
    indices = data.index('coefficients') + 1
    coeff_list = data[indices:]
    coeff_list = list(filter((coeff_list[1]).__ne__, coeff_list))
    co_list = list()
    for c in coeff_list:
        try:
            co = float(c)
        except ValueError:
            co = text2float(c)
        co_list.append(co)
    return np.poly1d(co_list)

Note that the Google Cloud Speech API has a tendency to interpret consecutive numbers as a single number, so it helps to state any delimiter between the numbers (such as “two dash four dash seven”) and then filter the delimiter out. Of course, you may want to write other types of functions. In this case, you can add a new keyword to the write_code function and create a new function. 

Finally, we put everything together and run a while loop:

time.sleep(2)
listening = True
while listening == True:
    data = listen()
    listening, output = write_code(data)

The corresponding output for a list looks like this:

I am listening...
You said: create a list with integer three float 1.5 and string basketball
[3, 1.5, 'basketball']

And for a polynomial function:

I am listening...
You said: create a polynomial with coefficients 5 - 7 - 6
polyld([5., 7., 6.])

Pretty cool, right? 

Conclusions – AI Can Help Automate Coding

The old adage of “anything you need to code twice is worth automating” gets a facelift here in that we’re letting our AI routine auto-generate code for us. While we’re not exactly in Skynet territory here, the routines shown here provide a good example of how current ML techniques can automate common coding tasks. When combined with your IDE’s auto-complete functionality, as well as GitHub’s Copilot program, code writing is becoming more and more automated. Less typing that results in more coding can’t be a bad thing. Well, at least until the AI singularity occurs. In the meantime: 

Configuration
With the ActiveState Platform, you can create your Python environment in minutes, just like the one we built for this project. Try it out for yourself or learn more about how it helps Python developers be more productive.

Related Reads

How to Build a Lyrics Generator with Python & Recurrent Neural Networks

Can an AI Classification Model detect AI-generated content?