balaji4991512 commited on
Commit
5cd8a80
·
verified ·
1 Parent(s): bb777c9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -0
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline # For loading Hugging Face pre-trained models
2
+ import gradio as gr # For creating the user interface
3
+ import pandas as pd # For handling CSV and Excel files
4
+ import matplotlib.pyplot as plt # For plotting the pie chart
5
+
6
+ # Load the pre-trained sentiment-analysis model from Hugging Face
7
+ # This is a binary sentiment model (Positive/Negative)
8
+ sentiment_analyzer = pipeline(
9
+ "sentiment-analysis",
10
+ model="distilbert-base-uncased-finetuned-sst-2-english" # Model fine-tuned on SST-2 for sentiment analysis
11
+ )
12
+
13
+ # Function to analyze sentiment of a single text input
14
+ def analyze_sentiment(text):
15
+ # Run the text through the sentiment analyzer
16
+ result = sentiment_analyzer(text)
17
+
18
+ # Return the sentiment label (Positive/Negative)
19
+ return result[0]['label']
20
+
21
+ # Function to analyze a file (CSV or Excel) and return sentiment results + pie chart
22
+ def analyze_file(file):
23
+ # Read the uploaded file based on its extension (CSV or Excel)
24
+ if file.name.endswith(".csv"):
25
+ df = pd.read_csv(file.name) # Read as CSV
26
+ elif file.name.endswith(".xlsx"):
27
+ df = pd.read_excel(file.name) # Read as Excel
28
+ else:
29
+ return "Unsupported file format", None # Return error message if the file format is unsupported
30
+
31
+ # Check if 'Text' column is present in the file
32
+ if "Text" not in df.columns:
33
+ return "Missing 'Text' column", None # Return error if 'Text' column is missing
34
+
35
+ # Predict sentiment for each row in the 'Text' column
36
+ sentiments = [sentiment_analyzer(t)[0]['label'] for t in df["Text"].fillna("")] # Handle empty cells with fillna("")
37
+
38
+ # Create a DataFrame with 'Text' and corresponding 'Sentiment'
39
+ df_result = pd.DataFrame({
40
+ "Text": df["Text"], # Original text column
41
+ "Sentiment": sentiments # Sentiment predictions
42
+ })
43
+
44
+ # Generate a pie chart to show the distribution of sentiments
45
+ sentiment_counts = df_result["Sentiment"].value_counts() # Count the occurrences of each sentiment
46
+ fig, ax = plt.subplots() # Create a figure and axis for plotting
47
+ ax.pie(
48
+ sentiment_counts.values, # Data for the pie chart
49
+ labels=sentiment_counts.index, # Sentiment labels (e.g., 'POSITIVE', 'NEGATIVE')
50
+ autopct="%1.1f%%", # Show percentage on the pie chart
51
+ colors=["#66bb6a", "#ef5350", "#ffee58"][:len(sentiment_counts)] # Color palette for the pie chart
52
+ )
53
+ ax.set_title("Sentiment Distribution") # Title of the pie chart
54
+
55
+ return df_result, fig # Return the DataFrame and the pie chart figure
56
+
57
+ # Creating the Gradio interface with two tabs: one for text input and one for file upload
58
+ with gr.Blocks() as demo:
59
+ gr.Markdown("## 🧠 Text Sentiment Analyzer with Pie Chart") # Title
60
+ gr.Markdown("Enter text manually or upload a file with a **Text** column.") # Description
61
+
62
+ # Tab for analyzing a single text input
63
+ with gr.Tab("🔤 Single Text"):
64
+ txt = gr.Textbox(label="Text", lines=4) # Textbox for text input
65
+ out = gr.Textbox(label="Sentiment") # Textbox to show sentiment output
66
+ btn = gr.Button("Analyze") # Button to trigger analysis
67
+ btn.click(analyze_sentiment, inputs=txt, outputs=out) # Trigger analysis when button is clicked
68
+
69
+ # Tab for uploading a file (CSV or Excel)
70
+ with gr.Tab("📁 Upload File"):
71
+ file_input = gr.File(label="Upload CSV or Excel File") # File uploader
72
+ file_output = gr.Dataframe(label="Sentiment Results") # Table to display the sentiment results
73
+ chart_output = gr.Plot(label="Sentiment Distribution Pie Chart") # Pie chart to display sentiment distribution
74
+ btn2 = gr.Button("Analyze File") # Button to trigger file analysis
75
+ btn2.click(analyze_file, inputs=file_input, outputs=[file_output, chart_output]) # Trigger file analysis when button is clicked
76
+
77
+ # Launch the app
78
+ demo.launch()