Johnniewhite commited on
Commit
ec163c5
·
verified ·
1 Parent(s): d6d2ef0

Update index.py

Browse files
Files changed (1) hide show
  1. index.py +65 -14
index.py CHANGED
@@ -1,24 +1,75 @@
1
  import transformers
2
  from flask import Flask, request, jsonify
3
  from transformers import RobertaTokenizerFast, TFRobertaForSequenceClassification, pipeline
 
 
 
 
 
 
4
 
5
- app = Flask(__name__)
6
-
7
- # Load model and tokenizer once at app startup
8
  tokenizer = RobertaTokenizerFast.from_pretrained("arpanghoshal/EmoRoBERTa")
9
  model = TFRobertaForSequenceClassification.from_pretrained("arpanghoshal/EmoROBERTa")
10
  emotion = pipeline("sentiment-analysis", model="arpanghoshal/EmoROBERTa")
11
 
12
- @app.route("/analyze_sentiment", methods=["POST"])
13
- def analyze_sentiment():
14
- data = request.get_json()
15
- phrase = data.get("phrase")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- if phrase:
18
- emotion_labels = emotion(phrase)
19
- return jsonify({"emotion_labels": emotion_labels})
20
- else:
21
- return jsonify({"error": "Missing phrase"}), 400
 
 
22
 
23
- if __name__ == "__main__":
24
- app.run(debug=True) # Set debug=False in production
 
1
  import transformers
2
  from flask import Flask, request, jsonify
3
  from transformers import RobertaTokenizerFast, TFRobertaForSequenceClassification, pipeline
4
+ import gradio as gr
5
+ import pandas as pd
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ import io
9
+ from io import BytesIO # Import BytesIO for image generation
10
 
11
+ # Load model and tokenizer
 
 
12
  tokenizer = RobertaTokenizerFast.from_pretrained("arpanghoshal/EmoRoBERTa")
13
  model = TFRobertaForSequenceClassification.from_pretrained("arpanghoshal/EmoROBERTa")
14
  emotion = pipeline("sentiment-analysis", model="arpanghoshal/EmoROBERTa")
15
 
16
+ def analyze_csv(file):
17
+ try:
18
+ # Print file content for debugging
19
+ file_content = file.read()
20
+ print("File content:", file_content)
21
+
22
+ # Reset file position to the beginning
23
+ file.seek(0)
24
+
25
+ # Read the CSV file into a DataFrame
26
+ df = pd.read_csv(io.BytesIO(file_content))``
27
+ print("DataFrame shape:", df.shape) # Print DataFrame shape for debugging
28
+ print("DataFrame columns:", df.columns) # Print DataFrame columns for debugging
29
+
30
+ # Check if the DataFrame is empty
31
+ if df.empty:
32
+ return "Empty file. Please upload a CSV file with data.", None
33
+
34
+ # Check if the expected column "phrase" is present in the DataFrame
35
+ if "phrase" not in df.columns:
36
+ return "Column 'phrase' not found in the CSV file. Please check the file format.", None
37
+
38
+ phrases = df["phrase"]
39
+
40
+ # Analyze sentiment for each phrase
41
+ emotion_labels = emotion(phrases)
42
+
43
+ # Create summary statistics
44
+ summary_df = pd.DataFrame(emotion_labels).describe()
45
+
46
+ # Create a bar chart of emotion distribution
47
+ plt.figure()
48
+ emotion_counts = emotion_labels.get("labels").value_counts()
49
+ emotion_counts.plot(kind="bar")
50
+ plt.title("Emotion Distribution")
51
+ plt.xlabel("Emotion")
52
+ plt.ylabel("Count")
53
+
54
+ # Generate PNG image of the chart
55
+ chart_img = BytesIO()
56
+ plt.savefig(chart_img, format="png")
57
+ chart_img.seek(0)
58
+
59
+ return summary_df.to_json(), chart_img.read()
60
+
61
+ except Exception as e:
62
+ error_message = f"Error processing the CSV file: {str(e)}"
63
+ print(error_message) # Print the error message for debugging
64
+ return error_message, None
65
+
66
 
67
+ iface = gr.Interface(
68
+ fn=analyze_csv,
69
+ inputs=[gr.File(label="Upload CSV File")],
70
+ outputs=["dataframe", "image"],
71
+ title="Emotion Analyzer with CSV",
72
+ description="Analyzes sentiment and creates charts/tables from a CSV file.",
73
+ )
74
 
75
+ iface.launch()