DEV Community

Mageshwaran
Mageshwaran

Posted on • Edited on

Ai Generated Faces - Access it using Python

You can find AI generated faces here
https://generated.photos/faces

Using this api its easy to access all the images

To access the API we will use requests package
before that get the api_key

import requests

api_key = "#####################"
base_url = "https://api.generated.photos/api/v1/faces?api_key=" + api_key
Enter fullscreen mode Exit fullscreen mode

Input fields for the api,

# Page number to retrieve, Default: 1
page = "1"
# Maximum: 100, Default: 10
per_page = "2"
# short, medium, long
hair_length = "medium"
# male, female
gender = "male"
# joy, neutral, surprise
emotion = "joy"
# infant, child, young-adult, adult, elderly
age = "child"
Enter fullscreen mode Exit fullscreen mode

add the query params value to base url

url = "{}&page={}&per_page={}&hair_length={}&gender={}&emotion={}&age={}".format(base_url, page, per_page, hair_length,gender, emotion, age)
r = requests.get(url=url)
data = r.json()
Enter fullscreen mode Exit fullscreen mode

Save the image in local for that it has to be downloaded using requests
File name be like

  • 0-32.jpg
  • 0-64.jpg

Use python for loop to iterate over the list of value, you a use the index if needed python enumerate will return both index and value when used in for loop.

for i, v in enumerate(data["faces"]):
    for j in v["urls"]:
        for key in j:
            r = requests.get(url=j[key])
            if r.status_code == 200:
                # write the image
                with open(str(i) + "-"+ key +".jpg", 'wb') as f:
                    f.write(r.content)
Enter fullscreen mode Exit fullscreen mode

Alt Text

Learn Python Programming in Programdoc

Top comments (1)

Collapse
 
iceorfiresite profile image
Ice or Fire

@magesh236 What's your use case for this? It's pretty interesting