|
|
|
|
|
|
|
|
|
import gradio as gr |
|
import tensorflow as tf |
|
from transformers import pipeline |
|
|
|
def process_image(image): |
|
try: |
|
|
|
classifier = pipeline("image-classification", model="dima806/facial_emotions_image_detection") |
|
|
|
|
|
result = classifier(image) |
|
|
|
|
|
emotions = {item['label']: float(item['score']) * 100 for item in result} |
|
|
|
|
|
analysis = generate_analysis(emotions) |
|
report = generate_report(emotions, analysis) |
|
|
|
return [(k, v) for k, v in emotions.items()], analysis['detailed_analysis'], report |
|
except Exception as e: |
|
return [("error", 0)], f"Error: {str(e)}", "Error generating report" |
|
|
|
def generate_analysis(emotions): |
|
descriptions = { |
|
'happy': 'indicates joy and positive mood', |
|
'angry': 'suggests frustration or displeasure', |
|
'surprise': 'shows astonishment', |
|
'fear': 'reflects anxiety or concern', |
|
'neutral': 'displays a balanced state' |
|
} |
|
|
|
top_emotion = max(emotions.items(), key=lambda x: x[1]) |
|
|
|
return { |
|
"primary_emotion": top_emotion[0], |
|
"detailed_analysis": f"Primary emotion detected is {top_emotion[0]} ({top_emotion[1]:.1f}%), which {descriptions.get(top_emotion[0], '')}." |
|
} |
|
|
|
def generate_report(emotions, analysis): |
|
return f"""Emotion Analysis Report |
|
|
|
Primary Emotion: {analysis['primary_emotion'].upper()} |
|
Confidence: {emotions[analysis['primary_emotion']]:.1f}% |
|
|
|
All Detected Emotions: |
|
""" + '\n'.join(f"- {k}: {v:.1f}%" for k, v in sorted( |
|
emotions.items(), |
|
key=lambda x: x[1], |
|
reverse=True)) |
|
|
|
|
|
with gr.Blocks(theme=gr.themes.Soft()) as app: |
|
gr.Markdown("# Facial Emotion Analysis System") |
|
|
|
with gr.Row(): |
|
with gr.Column(scale=1): |
|
input_image = gr.Image(type="numpy") |
|
submit_btn = gr.Button("Analyze", variant="primary") |
|
|
|
with gr.Column(scale=1): |
|
emotion_scores = gr.Label(label="Emotion Scores") |
|
analysis_text = gr.Textbox(label="Analysis", lines=3) |
|
report_text = gr.Textbox(label="Full Report", lines=10) |
|
download_btn = gr.Button("Download Report") |
|
|
|
submit_btn.click( |
|
fn=process_image, |
|
inputs=[input_image], |
|
outputs=[emotion_scores, analysis_text, report_text] |
|
) |
|
|
|
download_btn.click( |
|
fn=lambda x: x, |
|
inputs=[report_text], |
|
outputs=[gr.File(label="Download Report")] |
|
) |
|
|
|
app.launch() |