MuhammmadRizwanRizwan commited on
Commit
c14e2fe
·
verified ·
1 Parent(s): 6954573

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -49
app.py CHANGED
@@ -2,78 +2,56 @@
2
 
3
  # gr.load("models/dima806/facial_emotions_image_detection").launch()
4
 
5
-
6
  import gradio as gr
7
- from huggingface_hub import from_pretrained_keras
8
- import numpy as np
9
- from datetime import datetime
10
  import tensorflow as tf
 
11
 
12
  def process_image(image):
13
  try:
14
- model = from_pretrained_keras("dima806/facial_emotions_image_detection")
15
-
16
- # Preprocess image
17
- img = tf.image.resize(image, (48, 48))
18
- img = tf.image.rgb_to_grayscale(img)
19
- img = img / 255.0
20
- img = tf.expand_dims(img, 0)
21
 
22
  # Get predictions
23
- pred = model.predict(img)
24
 
25
- emotions = {
26
- 'happy': float(pred[0][0]),
27
- 'angry': float(pred[0][1]),
28
- 'surprise': float(pred[0][2]),
29
- 'fear': float(pred[0][3]),
30
- 'neutral': float(pred[0][4])
31
- }
32
 
33
- # Generate analysis
34
  analysis = generate_analysis(emotions)
35
- report = generate_report(image, analysis)
36
 
37
- return emotions, analysis['detailed_analysis'], report
38
  except Exception as e:
39
- return {"error": str(e)}, "Error in processing", "Error generating report"
40
 
41
- def generate_analysis(emotion_scores):
42
- emotions = {
43
- 'happy': 'indicates joy, satisfaction, or positive mood',
44
- 'angry': 'suggests frustration, irritation, or displeasure',
45
- 'surprise': 'shows astonishment or unexpected reaction',
46
- 'fear': 'reflects anxiety, worry, or concern',
47
- 'neutral': 'displays a balanced or unemotional state'
48
  }
49
 
50
- top_emotion = max(emotion_scores.items(), key=lambda x: x[1])
51
 
52
  return {
53
- "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
54
  "primary_emotion": top_emotion[0],
55
- "confidence_scores": emotion_scores,
56
- "detailed_analysis": f"Primary emotion: {top_emotion[0]} ({top_emotion[1]:.1f}% confidence)",
57
- "secondary_indicators": [f"{k} ({v:.1f}%)" for k, v in emotion_scores.items() if v > 20 and k != top_emotion[0]]
58
  }
59
 
60
- def generate_report(image, analysis):
61
- report = f"""Emotion Analysis Report
62
- Generated: {analysis['timestamp']}
63
 
64
  Primary Emotion: {analysis['primary_emotion'].upper()}
65
- Confidence: {analysis['confidence_scores'][analysis['primary_emotion']]:.1f}%
66
 
67
- Secondary Emotions:
68
- {', '.join(analysis['secondary_indicators']) if analysis['secondary_indicators'] else 'None significant'}
69
-
70
- All Scores:
71
  """ + '\n'.join(f"- {k}: {v:.1f}%" for k, v in sorted(
72
- analysis['confidence_scores'].items(),
73
  key=lambda x: x[1],
74
  reverse=True))
75
-
76
- return report
77
 
78
  # Create Gradio interface
79
  with gr.Blocks(theme=gr.themes.Soft()) as app:
@@ -81,12 +59,12 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
81
 
82
  with gr.Row():
83
  with gr.Column(scale=1):
84
- input_image = gr.Image(label="Upload Image")
85
  submit_btn = gr.Button("Analyze", variant="primary")
86
 
87
  with gr.Column(scale=1):
88
- emotion_scores = gr.Label(label="Emotion Confidence Scores")
89
- analysis_text = gr.Textbox(label="Detailed Analysis", lines=3)
90
  report_text = gr.Textbox(label="Full Report", lines=10)
91
  download_btn = gr.Button("Download Report")
92
 
 
2
 
3
  # gr.load("models/dima806/facial_emotions_image_detection").launch()
4
 
 
5
  import gradio as gr
 
 
 
6
  import tensorflow as tf
7
+ from transformers import pipeline
8
 
9
  def process_image(image):
10
  try:
11
+ # Initialize emotion classifier
12
+ classifier = pipeline("image-classification", model="dima806/facial_emotions_image_detection")
 
 
 
 
 
13
 
14
  # Get predictions
15
+ result = classifier(image)
16
 
17
+ # Convert results to required format
18
+ emotions = {item['label']: float(item['score']) * 100 for item in result}
 
 
 
 
 
19
 
20
+ # Generate analysis and report
21
  analysis = generate_analysis(emotions)
22
+ report = generate_report(emotions, analysis)
23
 
24
+ return [(k, v) for k, v in emotions.items()], analysis['detailed_analysis'], report
25
  except Exception as e:
26
+ return [("error", 0)], f"Error: {str(e)}", "Error generating report"
27
 
28
+ def generate_analysis(emotions):
29
+ descriptions = {
30
+ 'happy': 'indicates joy and positive mood',
31
+ 'angry': 'suggests frustration or displeasure',
32
+ 'surprise': 'shows astonishment',
33
+ 'fear': 'reflects anxiety or concern',
34
+ 'neutral': 'displays a balanced state'
35
  }
36
 
37
+ top_emotion = max(emotions.items(), key=lambda x: x[1])
38
 
39
  return {
 
40
  "primary_emotion": top_emotion[0],
41
+ "detailed_analysis": f"Primary emotion detected is {top_emotion[0]} ({top_emotion[1]:.1f}%), which {descriptions.get(top_emotion[0], '')}."
 
 
42
  }
43
 
44
+ def generate_report(emotions, analysis):
45
+ return f"""Emotion Analysis Report
 
46
 
47
  Primary Emotion: {analysis['primary_emotion'].upper()}
48
+ Confidence: {emotions[analysis['primary_emotion']]:.1f}%
49
 
50
+ All Detected Emotions:
 
 
 
51
  """ + '\n'.join(f"- {k}: {v:.1f}%" for k, v in sorted(
52
+ emotions.items(),
53
  key=lambda x: x[1],
54
  reverse=True))
 
 
55
 
56
  # Create Gradio interface
57
  with gr.Blocks(theme=gr.themes.Soft()) as app:
 
59
 
60
  with gr.Row():
61
  with gr.Column(scale=1):
62
+ input_image = gr.Image(type="numpy")
63
  submit_btn = gr.Button("Analyze", variant="primary")
64
 
65
  with gr.Column(scale=1):
66
+ emotion_scores = gr.Label(label="Emotion Scores")
67
+ analysis_text = gr.Textbox(label="Analysis", lines=3)
68
  report_text = gr.Textbox(label="Full Report", lines=10)
69
  download_btn = gr.Button("Download Report")
70