""" 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()