FaceAnalysis / app.py
leonelhs's picture
init space code
7dcb9e0
#######################################################################################
#
# MIT License
#
# Copyright (c) [2025] [leonelhs@gmail.com]
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
#######################################################################################
#
# - [Demo] - [https://huggingface.co/spaces/leonelhs/FaceAnalysis]
#
# Source code is based on or inspired by several projects.
# For more details and proper attribution, please refer to the following resources:
#
# - [Deepinsight] - [https://github.com/deepinsight/insightface]
# - [FaceFusion] - [https://github.com/facefusion/facefusion]
#
from itertools import islice
import gradio as gr
from huggingface_hub import hf_hub_download
from face_analysis import FaceAnalysis
REPO_ID = "leonelhs/insightface"
model_inswapper_path = hf_hub_download(repo_id=REPO_ID, filename="inswapper_128.onnx")
face_analyser = FaceAnalysis()
def predict(image_path):
faces = face_analyser.get(image_path)
sections = []
if len(faces) > 0:
for face in faces:
box = face.bbox
label = f"Gender {face.sex} Age {face.age}"
sections.append(((int(box[0]), int(box[1]), int(box[2]), int(box[3])), label))
return image_path, sections
else:
raise gr.Error("No faces were found!")
with gr.Blocks(title="FaceAnalyser") as app:
navbar = gr.Navbar(visible=True, main_page_name="Workspace")
gr.Markdown("## Face Analyser")
with gr.Row():
with gr.Column(scale=1):
with gr.Row():
source_image = gr.Image(type="filepath", label="Face image")
image_btn = gr.Button("Analyze face")
with gr.Column(scale=1):
with gr.Row():
output_image = gr.AnnotatedImage(label="Faces detected")
image_btn.click(
fn=predict,
inputs=[source_image],
outputs=output_image,
)
with app.route("Readme", "/readme"):
with open("README.md") as f:
for line in islice(f, 12, None):
gr.Markdown(line.strip())
app.launch(share=False, debug=True, show_error=True, mcp_server=True, pwa=True)
app.queue()