Instagram face-recognition:

The next program is just educational, and you should not execute it unless you want your Instagram account blocked. The code is an automated bot that, with the Instagram username and password, downloads pictures of the followers in order to perform face recognition on their faces. This program uses the web-scraping library Selenium to download the latest pictures of all the followers by retrieving the HTML code. Once all the pictures are downloaded, they are uploaded to the face recognition library to save and recognize the faces. This code is also the reason why my Instagram account was blocked.

The program is dividen in 4 steps:

1) Read the followers:
The Instagram API has a function that returns a list with the people whom we follow.

2) First picture:
The next step in your program is to enter our Instagram account automatically using Selenium. Once we are logged into your Instagram account, the code will execute a for loop for all the followers and enter their profiles to download their images locally with the name of the user.

Once the images are saved, the code will encode them to detect faces and return a list with the usernames of the users where a face couldn’t be found.

3) Second picture:
In this step, the code will use an Instagram API function to download the profile picture of the followers that could find a face. It will save and encode the profile picture.

4) Facial Recognition:
Finally, we will have to open the camera, send the encoded images, and let the program detect which of our followers is in front of the camera, displaying the username.

import instaloader
import time
from selenium import webdriver
import datetime
import random
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import requests
import instaloader

# Face recognition
import cv2
import face_recognition
from matplotlib import pyplot as plt
from datetime import datetime
import shutil
import glob
from PIL import Image



# List of the followers:

# get all the followers username of the accound you enter:

try:
    L = instaloader.Instaloader()

    # Login or load session
    username = ""  #<----------- Entern username
    password = ""  #<----------- Entern password
    L.login(username, password)  # (login)

    # Obtain profile metadata
    profile = instaloader.Profile.from_username(L.context, username)

    # Print list of followees
    follow_list = []
    count = 0
    for followee in profile.get_followees():
        follow_list.append(followee.username)
        file = open("prada_followers.txt", "a+")
        file.write(follow_list[count])
        file.write("\n")
        file.close()
        print(follow_list[count])
        count = count + 1
except:
    pass

# Get the pic of all the followers

#Enter to your perfoil

browser = webdriver.Chrome(executable_path = r"C:\Users\....\driver\chromedriver.exe") # ---> Enter Selenium path driver
browser.get("https://www.instagram.com/")

# Acceptar cookies
But_Cokkies = browser.find_element_by_xpath("/html/body/div[4]/div/div/button[1]")
But_Cokkies.click()

time.sleep(5)

# LOG IN________________________________________________________________

# User
user = browser.find_element_by_xpath("//*[@id='loginForm']/div/div[1]/div/label/input")
user.click()
user.send_keys(username)

#Password
passw = browser.find_element_by_xpath("//*[@id='loginForm']/div/div[2]/div/label/input")
passw.click()
passw.send_keys(password)

#Button log in
libtn = browser.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]/button/div')
libtn.click()

time.sleep(5)

#Don't save info 
infobtn = browser.find_element_by_xpath("//*[@id='react-root']/section/main/div/div/div/section/div/button")
infobtn.click()

time.sleep(10)

#Notifications of:
notibtn = browser.find_element_by_xpath('/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div/div/div/div[3]/button[2]')
notibtn.click()

time.sleep(5)

# User to download the imatge:
follwers = follow_list[:25]

# list with the not saved users pics:
not_saved_list = []

# list with the saved users pics:
Saved_list = []

for follower in follwers:
    
    print("Dowlondig the pic of:", follower )
    
    try: 

        searchbox=browser.find_element_by_css_selector("input[placeholder='Busca']")
        searchbox.clear()
        searchbox.send_keys(follower)
        time.sleep(5)
        searchbox.send_keys(Keys.ENTER)
        time.sleep(5)
        searchbox.send_keys(Keys.ENTER)
        time.sleep(5)

        # slect image

        img_1 = browser.find_element_by_xpath('//*[@id="mount_0_0_ud"]/div/div/div/div[1]/div/div/div/div[1]/div[1]/section/main/div/div[2]/article/div/div/div/div[1]/a')
        img_1.click()
    
    

        ''' Fetch the source file of the html page using BeautifulSoup'''
        soup = BeautifulSoup(browser.page_source, 'lxml')

        ''' Extract the url of the image from the source code''' 
        img = soup.find('img', class_='FFVAD')
        img_url = img['src']


        '''Download the image via the url using the requests library'''
        r = requests.get(img_url)



        with open(follower  +".png",'wb') as f: 
            f.write(r.content)

        print('Success!')
        
        Saved_list.append(follower)
    
    # Cerrar imagen:
        colseimg = browser.find_element_by_xpath("/html/body/div[6]/div[3]/button")
        colseimg.click()
    
        time.sleep(5)
    
    # delet the user
    #del_user = browser.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/div[2]')
    #del_user.click()
    
        
    
    except:
        
        print("Didn't save the pic, adding to the don't save list not_saved_list.")
        
        # Add the user to the don't saved pics:
        not_saved_list.append(follower)
        
        pass


# Where are the pics saved:
import os
print(os.getcwd())

## List of saved and not:

### Not saved List:

not_saved_list

### Saved pics list

Saved_list

## Save the pics wher we can find the faces

# encodings imatges:
# declar the list to fit the users depending if there is a face detected or not:
face_detected = []
Not_face_dtected = []

for follower in Saved_list: 

    try:
        print("Encoding", follower , "pic")
        
        # Get the name of the .png imatge
        imatge_name = follower + ".png"
        
        print(imatge_name)
        
        #Declare img variables:
        img_follower = "img_" + follower
        rgb_follower = "rgb_" + follower
        enc_img_follower = "enc_img_" + follower
        
        
        # Encode rhe faces
        img_follower = cv2.imread(imatge_name)
        rgb_follower = cv2.cvtColor(img_follower, cv2.COLOR_BGR2RGB)
        enc_img_follower = face_recognition.face_encodings(rgb_follower)[0]    
        
        
        face_detected.append(follower)
        
        destination = "C:\\Users...\\" + imatge_name # ----> Fill the path
        shutil.copyfile(imatge_name, destination)
        #os.replace(imatge_name, destination )
        print(imatge_name + " Was moved")
        
        print("Success!")
        print("")
    except:
        
        print( follower , "Pic can`t not be encoded")
        print("")
        
        Not_face_dtected.append(follower)
        
        pass
        

# Listas caras detectadas y no caras:

### Fotos ya guardadas con caras encontradas

face_detected

### Craras no encontradas:

Not_face_dtected

### Merge the 2 list of no face detected and don't saved.

Get_second_pic_list =  Not_face_dtected + not_saved_list
Get_second_pic_list

# Get the second pic

for user in Get_second_pic_list:
    # Donload a folder with the perfoil pic
    
    ig = instaloader.Instaloader()
    ig.download_profile(user , profile_pic_only=True)
    
    #Get the  perfoil pic
    images = glob.glob("C:\\Users...\\"+ user +"//*.JPG")   # ----> Fill the path
    
    #Get the first imatge:
    pic = images[0]
    #Split the direction of the folder
    pic_list = pic.split("\\")
    #Get the folder
    folder_list = pic_list[0:9]
    folder = "//".join(folder_list)
    
    try:
        # rename the pic with the username
        os.rename(pic , folder + "//" +  user + ".jpg" )
    
        user_pic =  user + ".jpg"
    
        folder_with_new_pic = folder + "//" + user_pic
        
        # Move the photo to the next folder
        destination = "C:\\Users...Second_pics\\" +  user_pic  # ----> Fill the path
        shutil.copyfile(folder_with_new_pic , destination)
        
    except:
        
        print("Ya existe")


## Encode second image

# encodings imatges:

# declar the list to fit the users depending if there is a face detected or not:
face_detected = []
Not_face_dtected = []

for follower in Get_second_pic_list: 

    try:
        print("Encoding", follower , "pic")
        
        # Get the name of the .png imatge
        imatge_name = follower + ".jpg"
        
        print(imatge_name)
        
        #Declare img variables:
        img_follower = "img_" + follower
        rgb_follower = "rgb_" + follower
        enc_img_follower = "enc_img_" + follower
        
        
        # Encode rhe faces
        img_follower = cv2.imread(imatge_name)
        rgb_follower = cv2.cvtColor(img_follower, cv2.COLOR_BGR2RGB)
        enc_img_follower = face_recognition.face_encodings(rgb_follower)[0]    
        
        
        face_detected.append(follower)
        
        destination = "C:...." + imatge_name # Path with the images
        shutil.copyfile(imatge_name, destination)
        #os.replace(imatge_name, destination )
        print(imatge_name + " Was moved")
        
        print("Success!")
        print("")
    except:
        
        print( follower , "Pic cann`t not be encoded")
        print("")
        
        Not_face_dtected.append(follower)
        
        pass

# Facial recognition:

## Encode faces

sfr = SimpleFacerec()
sfr.load_encoding_images("C:....")  # path with all the faces detected.

## Load Camera

cap = cv2.VideoCapture(0)

# facial recognition in life
while True:
    
    
    # Detect faces:
    ret, frame = cap.read()
    face_locations, face_names = sfr.detect_known_faces(frame)
    
    for face_loc, name in zip(face_locations, face_names):
        y1, x1, y2, x2 = face_loc[0], face_loc[1], face_loc[2], face_loc[3]
        
        cv2.putText(frame, name,(x1, y1 - 10), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 200), 2)
        cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 200), 4)
        
        
    
   
    
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1)
    
    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()

Leave a Comment

Your email address will not be published. Required fields are marked *