Spaces:
Runtime error
Runtime error
Shafeek Saleem commited on
Commit ·
0cba43f
1
Parent(s): 3767003
added template files
Browse filesFiles changed (30)
- .idea/.gitignoreAdded+3
- .idea/ascii_demo.imlAdded+8
- .idea/inspectionProfiles/Project_Default.xmlAdded+27
- .idea/inspectionProfiles/profiles_settings.xmlAdded+6
- .idea/modules.xmlAdded+8
- .idea/sonarlint/issuestore/0/0/000a6190576126fbf86ffdd96d384deeb366af79Added+4
- .idea/sonarlint/issuestore/2/6/261359fd9dbbe29d2e8fa924e82dca6f103aeb4bAdded
- .idea/sonarlint/issuestore/8/7/87caad19f17efd4c3e8264659f523744ffa94ed8Added+2
- .idea/sonarlint/issuestore/a/a/aa7ba3dbfc6be1a7bca20c1e791bc3e201c04b60Added
- .idea/sonarlint/issuestore/c/b/cb19cfbf0eac792d9353415a9a0072a9219f871eAdded
- .idea/sonarlint/issuestore/e/2/e274ab1fb18a0b24ca276995515f2380ef55255fAdded
- .idea/sonarlint/issuestore/index.pbAdded+3
- .idea/vcs.xmlAdded+6
- 0_Introduction.pyAdded+32
- app.pyDeleted-50
- assets/logo.pngAdded
- pages/1_Technology Behind It.pyAdded+60
- pages/2_Collecting Your Data.pyAdded+70
- pages/3_Training the Model.pyAdded+93
- pages/4_Trying It Out.pyAdded+81
- pages/5_Congratulations.pyAdded+12
- requirements.txt-2
- utils/__init__.pyAdded
- utils/__pycache__/__init__.cpython-310.pycAdded
- utils/__pycache__/inference.cpython-310.pycAdded
- utils/__pycache__/levels.cpython-310.pycAdded
- utils/__pycache__/login.cpython-310.pycAdded
- utils/inference.pyAdded+10
- utils/levels.pyAdded+36
- utils/login.pyAdded+29
123# Default ignored files/shelf//workspace.xml12345678<?xml version="1.0" encoding="UTF-8"?><module type="PYTHON_MODULE" version="4"> <component name="NewModuleRootManager"> <content url="file://$MODULE_DIR$" /> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> </component></module>123456789101112131415161718192021222324252627<component name="InspectionProjectProfileManager"> <profile version="1.0"> <option name="myName" value="Project Default" /> <inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true"> <option name="ignoredErrors"> <list> <option value="E402" /> </list> </option> </inspection_tool> <inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true"> <option name="ignoredErrors"> <list> <option value="N806" /> </list> </option> </inspection_tool> <inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true"> <option name="ignoredIdentifiers"> <list> <option value="trx_clus" /> <option value="matrix_demand_transfer" /> </list> </option> </inspection_tool> </profile></component>123456<component name="InspectionProjectProfileManager"> <settings> <option name="USE_PROJECT_PROFILE" value="false" /> <version value="1.0" /> </settings></component>12345678<?xml version="1.0" encoding="UTF-8"?><project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/.idea/ascii_demo.iml" filepath="$PROJECT_DIR$/.idea/ascii_demo.iml" /> </modules> </component></project>1234
Ipython:S1481",Remove the unused local variable "username".(��̳�����Dpython:S1481 ",Remove the unused local variable "password".(��ͮLpython:S1135"4Complete the task associated to this "TODO" comment.(�ڭ�12
Gpython:S1066"/Merge this if statement with the enclosing one.(����123version https://git-lfs.github.com/spec/v1oid sha256:3cea10e0be6249b66ee773812cedaca53f00b10c64f0c5fc3741d5fad1cb3805size 412123456<?xml version="1.0" encoding="UTF-8"?><project version="4"> <component name="VcsDirectoryMappings"> <mapping directory="$PROJECT_DIR$" vcs="Git" /> </component></project>1234567891011121314151617181920212223242526272829303132import streamlit as stfrom utils.levels import complete_level, initialize_level, render_page, get_levelfrom utils.login import initialize_login
initialize_login()initialize_level()
LEVEL = 0
def intro_page(): st.header("Face Recognition") st.subheader("Introduction")
st.write( """Welcome to the interactive tutorial on creating your very own Face Recognition Application! In this tutorial, you will learn how to build a simple application that can detect and recognise faces from a given photo. Face recognition has revolutionized various industries, including security, entertainment, and personal identification. Are you ready to dive into the exciting world of face recognition?""" )
# st.image( # "https://miro.medium.com/v2/resize:fit:720/0*Ko6oX3rRb0aTgdUI.gif", # use_column_width=True, # )
st.info(f"Click on the button below to start the tutorial!")
if st.button("I am Ready!"): complete_level(LEVEL)
render_page(intro_page, LEVEL)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import streamlit as stfrom PIL import Imageimport face_recognitionimport osimport uuidimport streamlit as stfrom PIL import Imageimport face_recognition
st.header("Face Detection")st.write( "Now it's time to collect the pictures we need to create our known-faces data base for our face recognition model. " "But remember, we should always ask for permission before taking someone's picture. We can use a smartphone or a digital camera to capture pictures, and it's important to take pictures of different people. This will help our application to have a good known-faces database!")
img_dir = os.path.join(".sessions", "known_faces")os.makedirs(img_dir, exist_ok=True)
picture = st.file_uploader("Upload a candidate image",type=['jpg','png','jpeg'],accept_multiple_files=False)if picture: image = face_recognition.load_image_file(picture) st.image(image)
# Find all the faces in the image using the default HOG-based model. # This method is fairly accurate, but not as accurate as the CNN model and not GPU accelerated. # See also: find_faces_in_picture_cnn.py face_locations = face_recognition.face_locations(image) st.write("Algorithm found {} face(s) in this photograph.".format(len(face_locations)))
cols = st.columns(len(face_locations)) for i in range(len(face_locations)): col = cols[i] face = face_locations[i] # display faces with col: st.header("Face {}".format(i)) # Print the location of each face in this image top, right, bottom, left = face # You can access the actual face itself like this: face_image = image[top:bottom, left:right] pil_image = Image.fromarray(face_image) st.image(pil_image) face_name = st.text_input('Specify name', "This is a placeholder", key="text_"+str(i)) if st.button("Save", key="button_"+str(i)): img_name = str(uuid.uuid4()) + f"{face_name}" + ".jpg" img_path = os.path.join(img_dir, img_name) im1 = pil_image.save(img_path) st.success("Face added successfully!")else: st.write("Please upload an image to proceed.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import streamlit as stfrom utils.levels import complete_level, render_page, initialize_levelfrom utils.login import initialize_login
LEVEL = 1
initialize_login()initialize_level()
def step1_page(): st.header("How does it work?") st.markdown( """ ### How does it work? In this tutorial, we will explore the fascinating world of face recognition technology. Through this interactive web application, you will learn the fundamentals of face detection, feature encodings, and face recognition algorithms. Throughout the tutorial, you will have the opportunity to upload images and experience the power of face recognition firsthand. Step by step, we will guide you through the process, ensuring that you gain a deep understanding of each concept and its practical implementation. Here's how it works:
1. **Face Detection**: In this first step, discover how face detection algorithms locate and identify faces within an image. You will see how this crucial first step sets the foundation for subsequent face recognition tasks.
2. **Face Encodings**: Next, the application pays attention to learn about face encodings, a technique that extracts unique facial characteristics and represents them as numerical vectors. These features capture unique characteristics that enable reliable comparisons between faces. Here we will gereate face encodings for the known faces to create a data base. """ ) st.image( "https://media.istockphoto.com/id/1136827583/photo/futuristic-and-technological-scanning-of-face-for-facial-recognition.jpg?s=612x612&w=0&k=20&c=GsqBYxvE64TS8HY__OSn6qZU5HPBhIemnqjyf37TkQo=", use_column_width=True, ) st.markdown( """ 3. **Face Recognition**: Dive into the world of face recognition algorithms, where you will understand the mechanisms behind comparing face encodings and making accurate matches. It uses the face encoding of unknown face against the face encodings of known faces to compare and find matching features. """ ) st.image( "https://miro.medium.com/v2/resize:fit:1200/1*4rjT-RSOTdlPqp1UwcF3tg.jpeg", use_column_width=True, ) st.markdown( """ So, our emotion detection model is like a clever brain that looks at faces, notices important features, and guesses how someone is feeling based on those features. It's a way for computers to understand emotions, just like we do as humans! """ )
st.info("Click on the button below to continue!")
if st.button("Complete"): complete_level(LEVEL)
render_page(step1_page, LEVEL)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import streamlit as stfrom PIL import Imageimport face_recognitionfrom utils.levels import complete_level, render_page, initialize_levelfrom utils.login import get_loginimport osimport uuidfrom utils.login import initialize_login
initialize_login()initialize_level()
LEVEL = 2
def step2_page(): st.header("Face Detection") st.write( "Now it's time to collect the pictures we need to create our known-faces data base for our face recognition model. " "But remember, we should always ask for permission before taking someone's picture. We can use a smartphone or a digital camera to capture pictures, and it's important to take pictures of different people. This will help our application to have a good known-faces database!" )
img_dir = os.path.join(".sessions", get_login()["username"], "known_faces") os.makedirs(img_dir, exist_ok=True)
picture = st.camera_input("Take a picture") if picture: image = face_recognition.load_image_file(picture) st.image(image)
# Find all the faces in the image using the default HOG-based model. # This method is fairly accurate, but not as accurate as the CNN model and not GPU accelerated. # See also: find_faces_in_picture_cnn.py face_locations = face_recognition.face_locations(image) st.write("Algorithm found {} face(s) in this photograph.".format(len(face_locations)))
cols = st.columns(len(face_locations)) for i in range(len(face_locations)): col = cols[i] face = face_locations[i] # display faces with col: st.header("Face {}".format(i)) # Print the location of each face in this image top, right, bottom, left = face # You can access the actual face itself like this: face_image = image[top:bottom, left:right] pil_image = Image.fromarray(face_image) st.image(pil_image) face_name = st.text_input('Specify name', "This is a placeholder", key="text_"+str(i)) if st.button("Save", key="button_"+str(i)): img_name = str(uuid.uuid4()) + f"{face_name}_{i}" + ".jpg" img_path = os.path.join(img_dir, img_name) with open(img_path, "wb") as f: f.write(face_image.getvalue()) st.success("Face added successfully!")
images = os.listdir(img_dir) if st.button("Clear All"): for img in images: os.remove(os.path.join(img_dir, img)) st.success("All images cleared!") st.experimental_rerun()
st.info("If you are satisfied with your images, click on the button below to complete this level.") if st.button("Complete"): complete_level(LEVEL)
render_page(step2_page, LEVEL)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import streamlit as stfrom utils.levels import complete_level, render_page, initialize_levelfrom utils.login import get_login, initialize_loginfrom utils.inference import queryimport osimport timeimport json
initialize_login()initialize_level()
LEVEL = 3
def infer(image): time.sleep(1) output = query(image) cols = st.columns(2) cols[0].image(image, use_column_width=True) with cols[1]: for item in output: st.progress(item["score"], text=item["label"])
def step3_page(): st.header("Feature encoding") st.markdown( """ ### What is Face Encodings? In face recognition, face encodings are numerical representations of facial features that are used to uniquely identify individuals. These encodings are obtained by extracting relevant facial information from an input image or video frame. Face encodings are typically computed using deep learning models, such as Convolutional Neural Networks (CNNs), that are trained on large datasets of labeled faces. During the training process, these models learn to recognize patterns and extract discriminative features from facial images. """ ) st.image( "https://1.bp.blogspot.com/-Cehw4NbX2L8/X1-DJeQgtmI/AAAAAAAAKeE/fA55q9EXsgQLU0trbgX_vJkiFMwR927yQCLcBGAsYHQ/s853/final.gif", use_column_width=True, ) st.markdown( """ 3. **Finding Patterns**: Our teacher starts to notice patterns in the pictures and the emotions we assigned to them. They might see that smiling faces usually mean happiness, or that certain features are common in sad expressions. These patterns help the teacher understand how emotions are expressed on people's faces. """ ) st.image( "https://miro.medium.com/v2/resize:fit:1358/1*KoHwRNZGrVrhdbye3BDEew.png", use_column_width=True, ) st.markdown( """ Once the face encodings are obtained, they can be stored in a database or used for face recognition tasks. During face recognition, the encodings of input faces are compared to the stored encodings to determine if a match exists. Various similarity metrics, such as Euclidean distance or cosine similarity, can be utilized to measure the similarity between face encodings and determine potential matches. """ )
st.info( "Now it's your turn to create face encodings to the face database you have created earlier!" )
img_dir = os.path.join(".sessions", get_login()["username"], "known_faces") images = os.listdir(img_dir) if len(images) > 0: st.subheader("Lets see your available images in your known-face database.") cols = st.columns(len(images)) for i, img in enumerate(images): face_name = img.split("_")[0] cols[i].image(os.path.join(img_dir, img), use_column_width=True) cols[i].write(face_name) st.subheader("Lets create face encodings for the known-faces.") face_encodings_dict = {} if st.button("Create Face Encodings"): my_bar = st.progress(0, text="Generating encodings...") if len(images) > 0: for i, img in enumerate(images): with open(os.path.join(img_dir, img), "rb") as f: face_image = f.read() my_face_encoding = face_recognition.face_encodings(face_image)[0] my_bar.progress(int((i + 1) / len(images) * 100), text="Generating encodings...") face_encodings_dict[img] = my_face_encoding my_bar.progress(100, text="Successfully encoded all the known faces!") st.success("Face encoding completed successfully!") with open(os.path.join(".sessions", get_login()["username"], "face_encodings.json"), "w") as write_file: json.dump(face_encodings_dict, write_file, indent=4) complete_level(LEVEL) else: my_bar.empty() st.error("You have not taken any images yet! Do the previous steps first!")
render_page(step3_page, LEVEL)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import streamlit as stfrom utils.levels import complete_level, render_page, initialize_levelfrom utils.login import get_login, initialize_loginfrom utils.inference import queryimport osimport time
initialize_login()initialize_level()
LEVEL = 4
def infer(image): time.sleep(1) output = query(image) cols = st.columns(2) cols[0].image(image, use_column_width=True) with cols[1]: for item in output: st.progress(item["score"], text=item["label"])
def step4_page(): st.header("Trying It Out") st.markdown( """ ### How Our Emotion Detection Application Works Now that we have trained our emotion detection application, let's see how it works in action! Here's a simple explanation of how the application recognizes emotions:
1. **Looking at Faces**: When we use our emotion detection application, we can show it a picture of a face or use a camera to capture a real-time image. It's like giving our application a chance to see someone's expression.
2. **Observing the Features**: The application carefully looks at the face and pays attention to different parts, like the eyes, mouth, and eyebrows. It tries to understand the expressions by noticing how these parts look and how they are positioned. It's like the application is taking a close look at the face, just like we do when we try to understand someone's emotions. """ ) st.image( "https://camo.githubusercontent.com/3bb4e2eba7c8a91d71916496bc775e870222f19bb5098cb4bc514ed60078c1e7/68747470733a2f2f626c6f672e7161746573746c61622e636f6d2f77702d636f6e74656e742f75706c6f6164732f323032302f30312f4d4c5f6578616d706c652e6769663f7261773d74727565", use_column_width=True, ) st.markdown( """ 3. **Guessing the Emotion**: Based on what it observed, our application uses the knowledge it learned during training to make its best guess about the person's emotion. It remembers the patterns it saw before and tries to match them with the features it observed. It might think the person looks happy, sad, or maybe surprised! """ ) st.image( "https://miro.medium.com/v2/resize:fit:1358/1*KoHwRNZGrVrhdbye3BDEew.png", use_column_width=True, ) st.markdown( """ 4. **Providing a Result**: Finally, our emotion detection application tells us what emotion it thinks the person is feeling. It might say, "I think this person looks happy!" or "I think this person looks sad." It's like having a virtual friend who can give us their guess about someone's emotion.
By going through these steps, our emotion detection application can quickly analyze faces and give us an idea of how someone might be feeling. It's like having a special friend who can understand and guess emotions based on facial expressions! """ )
st.info( "Now that we know how our emotion detection application works, let's try it out!" )
st.info("Select an image to analyze!") input_type = st.radio("Select the Input Type", ["Image", "Camera"])
if input_type == "Camera": image = st.camera_input("Take a picture") byte_image = image.getvalue() if image else None else: image = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg"]) byte_image = image.read() if image else None try_img = os.path.join(".sessions", get_login()["username"], "try.jpg") if byte_image: with open(try_img, "wb") as f: f.write(byte_image) infer(try_img)
st.info("Click on the button below to complete this level!") if st.button("Complete Level"): complete_level(LEVEL)
render_page(step4_page, LEVEL)123456789101112import streamlit as stfrom utils.levels import render_page, initialize_level
initialize_level()
LEVEL = 5
def complete_page(): st.header("Congratulations!") st.subheader("You have completed the tutorial!")
render_page(complete_page, LEVEL)123transformerstorchface-recognition1face-recognition
12345678910import requests
API_URL = "https://api-inference.huggingface.co/models/CynthiaCR/emotions_classifier"headers = {"Authorization": "Bearer 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"}
def query(filename): with open(filename, "rb") as f: data = f.read() response = requests.post(API_URL, headers=headers, data=data) return response.json()123456789101112131415161718192021222324252627282930313233343536import streamlit as stfrom utils.login import get_loginimport os
def initialize_level(): if 'level' not in st.session_state: if get_login()["status"]: if not os.path.exists(f".sessions/{get_login()['username']}/level.txt"): with open(f".sessions/{get_login()['username']}/level.txt", "w") as f: f.write("0") st.session_state['level'] = 0 else: with open(f".sessions/{get_login()['username']}/level.txt", "r") as f: st.session_state['level'] = int(f.read())
def get_level(): return st.session_state['level']
def render_page(page, level): if get_login()["status"]: if st.session_state['level'] < level: st.error(f"You need to complete Level {st.session_state['level']} first!") else: page() else: st.error("You need to login first!")
def complete_level(level): if st.session_state['level'] > level: st.info(f'You have Already completed Level {level}!') else: st.session_state['level'] = level + 1 with open(f".sessions/{get_login()['username']}/level.txt", "w") as f: f.write(str(st.session_state['level'])) st.balloons() st.success(f'You have completed Level {level}! You can now move on to the next level.')1234567891011121314151617181920212223242526272829import streamlit as stimport os
def initialize_login(): if "login" not in st.session_state: st.columns(3)[1].image("assets/logo.png") username = st.text_input("Username") password = st.text_input("Password", type="password") if st.button("Login"): # TODO: replace with actual authorization check authorized = {"status": True, "Name": "John Doe", "username": "johndoe"} if authorized["status"]: st.session_state["login"] = authorized os.makedirs( os.path.join(".sessions", st.session_state["login"]["username"]), exist_ok=True, ) st.success("Login Successful!") st.experimental_rerun() else: st.error("Invalid username or password") else: st.sidebar.success(f'Hello, {st.session_state["login"]["Name"]}!') st.sidebar.image("assets/logo.png", use_column_width=True)
def get_login(): return st.session_state.get("login", {"status": False}).idea/.gitignoreAdded+3
.idea/ascii_demo.imlAdded+8
.idea/inspectionProfiles/Project_Default.xmlAdded+27
.idea/inspectionProfiles/profiles_settings.xmlAdded+6
.idea/modules.xmlAdded+8
.idea/sonarlint/issuestore/0/0/000a6190576126fbf86ffdd96d384deeb366af79Added+4
.idea/sonarlint/issuestore/2/6/261359fd9dbbe29d2e8fa924e82dca6f103aeb4bAdded
.idea/sonarlint/issuestore/8/7/87caad19f17efd4c3e8264659f523744ffa94ed8Added+2
.idea/sonarlint/issuestore/a/a/aa7ba3dbfc6be1a7bca20c1e791bc3e201c04b60Added
.idea/sonarlint/issuestore/c/b/cb19cfbf0eac792d9353415a9a0072a9219f871eAdded
.idea/sonarlint/issuestore/e/2/e274ab1fb18a0b24ca276995515f2380ef55255fAdded
.idea/sonarlint/issuestore/index.pbAdded+3
.idea/vcs.xmlAdded+6
0_Introduction.pyAdded+32
app.pyDeleted-50
assets/logo.pngAdded

pages/1_Technology Behind It.pyAdded+60
pages/2_Collecting Your Data.pyAdded+70
pages/3_Training the Model.pyAdded+93
pages/4_Trying It Out.pyAdded+81
pages/5_Congratulations.pyAdded+12
requirements.txt-2
utils/__init__.pyAdded
utils/__pycache__/__init__.cpython-310.pycAdded
utils/__pycache__/inference.cpython-310.pycAdded
utils/__pycache__/levels.cpython-310.pycAdded
utils/__pycache__/login.cpython-310.pycAdded
utils/inference.pyAdded+10
utils/levels.pyAdded+36
utils/login.pyAdded+29