douglasgoodwin commited on
Commit
a9c47e0
·
verified ·
1 Parent(s): 7d213ed

try this change

Browse files
Files changed (1) hide show
  1. app.py +51 -56
app.py CHANGED
@@ -6,29 +6,29 @@ import sys
6
  import pandas as pd
7
 
8
  # Set up logging
9
- logging.basicConfig(level=logging.INFO, stream=sys.stdout,
10
- format='%(asctime)s - %(levelname)s - %(message)s')
 
 
 
11
  logger = logging.getLogger(__name__)
12
 
13
- try:
14
- logger.info("Initializing emotion classification pipeline...")
15
- classifier = pipeline(
16
- "text-classification",
17
- model="bhadresh-savani/distilbert-base-uncased-emotion",
18
- return_all_scores=True
19
- )
20
- logger.info("Pipeline initialized successfully")
21
- except Exception as e:
22
- logger.error(f"Failed to initialize pipeline: {str(e)}")
23
- raise
24
 
25
  def predict_emotion(text):
 
26
  try:
27
  logger.info(f"Received input text: {text}")
28
 
29
  if not text:
30
  logger.warning("Empty text received")
31
- # Return empty DataFrame with correct structure
32
  return pd.DataFrame({
33
  'emotion': ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise'],
34
  'score': [0, 0, 0, 0, 0, 0]
@@ -41,51 +41,46 @@ def predict_emotion(text):
41
 
42
  # Convert to DataFrame and format for visualization
43
  df = pd.DataFrame(predictions)
44
- df.columns = ['emotion', 'score'] # Rename columns
45
- df = df.sort_values('score', ascending=True) # Sort for better visualization
46
  logger.info(f"Processed scores as DataFrame: {df.to_dict()}")
47
 
48
  return df
 
 
 
 
 
 
 
49
 
50
- # Create the Gradio interface with error handling
51
- try:
52
- logger.info("Setting up Gradio interface...")
53
- demo = gr.Interface(
54
- fn=predict_emotion,
55
- inputs=gr.Textbox(
56
- placeholder="Enter text to analyze...",
57
- label="Input Text",
58
- lines=4
59
- ),
60
- outputs=gr.BarPlot(
61
- title="Emotion Probabilities",
62
- x="emotion",
63
- y="score",
64
- xlabel="Emotion",
65
- ylabel="Probability",
66
- height=400
67
- ),
68
- title="Emotion Detection with DistilBERT",
69
- description="This app uses the DistilBERT model fine-tuned for emotion detection. Enter any text to analyze its emotional content.",
70
- examples=[
71
- ["I am so happy to see you!"],
72
- ["I'm really angry about what happened."],
73
- ["The sunset was absolutely beautiful today."],
74
- ["I'm worried about the upcoming exam."],
75
- ["Fear is the mind-killer. I will face my fear."]
76
- ],
77
- allow_flagging="never"
78
- )
79
- logger.info("Gradio interface setup complete")
80
- except Exception as e:
81
- logger.error(f"Failed to create Gradio interface: {str(e)}")
82
- raise
83
 
84
  if __name__ == "__main__":
85
- try:
86
- logger.info("Launching Gradio app...")
87
- demo.launch(debug=True)
88
- logger.info("Gradio app launched successfully")
89
- except Exception as e:
90
- logger.error(f"Failed to launch Gradio app: {str(e)}")
91
- raise
 
6
  import pandas as pd
7
 
8
  # Set up logging
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ stream=sys.stdout,
12
+ format='%(asctime)s - %(levelname)s - %(message)s'
13
+ )
14
  logger = logging.getLogger(__name__)
15
 
16
+ # Initialize the pipeline
17
+ logger.info("Initializing emotion classification pipeline...")
18
+ classifier = pipeline(
19
+ "text-classification",
20
+ model="bhadresh-savani/distilbert-base-uncased-emotion",
21
+ return_all_scores=True
22
+ )
23
+ logger.info("Pipeline initialized successfully")
 
 
 
24
 
25
  def predict_emotion(text):
26
+ """Predict emotions from text and return formatted results."""
27
  try:
28
  logger.info(f"Received input text: {text}")
29
 
30
  if not text:
31
  logger.warning("Empty text received")
 
32
  return pd.DataFrame({
33
  'emotion': ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise'],
34
  'score': [0, 0, 0, 0, 0, 0]
 
41
 
42
  # Convert to DataFrame and format for visualization
43
  df = pd.DataFrame(predictions)
44
+ df.columns = ['emotion', 'score']
45
+ df = df.sort_values('score', ascending=True)
46
  logger.info(f"Processed scores as DataFrame: {df.to_dict()}")
47
 
48
  return df
49
+
50
+ except Exception as e:
51
+ logger.error(f"Error in prediction: {str(e)}")
52
+ return pd.DataFrame({
53
+ 'emotion': ['error'],
54
+ 'score': [1.0]
55
+ })
56
 
57
+ # Create the Gradio interface
58
+ demo = gr.Interface(
59
+ fn=predict_emotion,
60
+ inputs=gr.Textbox(
61
+ placeholder="Enter text to analyze...",
62
+ label="Input Text",
63
+ lines=4
64
+ ),
65
+ outputs=gr.BarPlot(
66
+ title="Emotion Probabilities",
67
+ x="emotion",
68
+ y="score",
69
+ xlabel="Emotion",
70
+ ylabel="Probability",
71
+ height=400
72
+ ),
73
+ title="Emotion Detection with DistilBERT",
74
+ description="This app uses the DistilBERT model fine-tuned for emotion detection. Enter any text to analyze its emotional content.",
75
+ examples=[
76
+ ["I am so happy to see you!"],
77
+ ["I'm really angry about what happened."],
78
+ ["The sunset was absolutely beautiful today."],
79
+ ["I'm worried about the upcoming exam."],
80
+ ["Fear is the mind-killer. I will face my fear."]
81
+ ],
82
+ allow_flagging="never"
83
+ )
 
 
 
 
 
 
84
 
85
  if __name__ == "__main__":
86
+ demo.launch(debug=True)