doksd's picture
Rename app_gradio.py to app.py
ce96bfc verified
Raw History Blame Contribute Delete
5.39 kB
"""
Face Analyzer Professional v2.0 - Gradio Interface for Hugging Face Spaces
"""
import gradio as gr
import cv2
import numpy as np
from PIL import Image
from deepface import DeepFace
import traceback
def analyze_face_image(image):
"""
Analyze face from uploaded image using DeepFace
"""
try:
if image is None:
return "❌ Please upload an image!"
# Convert to numpy array if needed
if isinstance(image, Image.Image):
img_array = np.array(image)
else:
img_array = image
# Convert RGB to BGR for OpenCV
img_bgr = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
# Analyze with DeepFace
analysis = DeepFace.analyze(
img_path=img_bgr,
actions=['age', 'gender', 'race', 'emotion'],
enforce_detection=True,
detector_backend='opencv'
)
# Handle list result
if isinstance(analysis, list):
analysis = analysis[0]
# Extract results
age = analysis.get('age', 'N/A')
gender = analysis.get('dominant_gender', 'N/A')
race = analysis.get('dominant_race', 'N/A')
emotion = analysis.get('dominant_emotion', 'N/A')
# Get confidence scores
gender_conf = analysis.get('gender', {})
race_conf = analysis.get('race', {})
emotion_conf = analysis.get('emotion', {})
# Format output
result = f"""
# 🎯 Hasil Analisis Wajah Profesional
## πŸ“Š Informasi Dasar
- **Usia Estimasi:** {age} tahun
- **Jenis Kelamin:** {gender.capitalize()}
- **Ras/Etnis:** {race.capitalize()}
- **Emosi Dominan:** {emotion.capitalize()}
## 🎭 Detail Emosi
"""
for emo, conf in emotion_conf.items():
bar = "β–ˆ" * int(conf / 10)
result += f"\n- **{emo.capitalize()}:** {conf:.1f}% {bar}"
result += "\n\n## πŸ‘€ Detail Gender"
for gen, conf in gender_conf.items():
bar = "β–ˆ" * int(conf / 10)
result += f"\n- **{gen.capitalize()}:** {conf:.1f}% {bar}"
result += "\n\n## 🌍 Detail Ras/Etnis"
for r, conf in race_conf.items():
bar = "β–ˆ" * int(conf / 10)
result += f"\n- **{r.capitalize()}:** {conf:.1f}% {bar}"
result += "\n\n---\nβœ… **Analisis Selesai!**"
return result
except ValueError as e:
if "Face could not be detected" in str(e):
return "❌ **Error:** Wajah tidak terdeteksi!\n\nπŸ’‘ **Tips:**\n- Pastikan foto menampilkan wajah dengan jelas\n- Pencahayaan cukup\n- Wajah tidak tertutup\n- Coba foto lain"
return f"❌ **Error:** {str(e)}"
except Exception as e:
print(f"Error: {str(e)}")
traceback.print_exc()
return f"❌ **Error:** Terjadi kesalahan saat analisis.\n\nDetail: {str(e)}"
# Create Gradio Interface
with gr.Blocks(
theme=gr.themes.Soft(),
title="Face Analyzer Professional v2.0",
css="""
.gradio-container {
max-width: 900px !important;
}
h1 {
text-align: center;
color: #2563eb;
}
"""
) as demo:
gr.Markdown(
"""
# πŸ”¬ Face Analyzer Professional v2.0
### AI-Powered Face Recognition & Analysis
Upload foto wajah untuk mendapatkan analisis profesional tentang:
- πŸ‘€ Jenis kelamin
- πŸŽ‚ Estimasi usia
- 🌍 Ras/etnis
- 🎭 Analisis emosi
---
"""
)
with gr.Row():
with gr.Column():
input_image = gr.Image(
label="πŸ“· Upload Foto Wajah",
type="pil",
height=400
)
analyze_btn = gr.Button(
"πŸ” Analisis Wajah",
variant="primary",
size="lg"
)
gr.Markdown(
"""
### πŸ’‘ Tips untuk Hasil Terbaik:
- βœ… Foto wajah yang jelas
- βœ… Pencahayaan yang baik
- βœ… Wajah menghadap kamera
- βœ… Format: JPG, PNG
"""
)
with gr.Column():
output_text = gr.Markdown(
label="πŸ“Š Hasil Analisis",
value="Silakan upload foto dan klik tombol analisis."
)
# Examples
gr.Markdown("### πŸ“Έ Contoh Foto (Opsional)")
gr.Examples(
examples=[],
inputs=input_image,
label="Gunakan foto Anda sendiri"
)
# Event handler
analyze_btn.click(
fn=analyze_face_image,
inputs=input_image,
outputs=output_text
)
gr.Markdown(
"""
---
### πŸ”’ Privasi & Keamanan
- βœ… Foto tidak disimpan di server
- βœ… Analisis dilakukan secara real-time
- βœ… Data tidak dibagikan ke pihak ketiga
### πŸ“– Tentang
Aplikasi ini menggunakan DeepFace library dengan model AI terbaru untuk analisis wajah yang akurat.
Dikembangkan untuk tujuan edukasi dan research.
**Powered by:** DeepFace, TensorFlow, OpenCV
"""
)
# Launch
if __name__ == "__main__":
demo.launch()