balaji4991512's picture
Create app.py
5cd8a80 verified
Raw History Blame Contribute Delete
3.93 kB
from transformers import pipeline # For loading Hugging Face pre-trained models
import gradio as gr # For creating the user interface
import pandas as pd # For handling CSV and Excel files
import matplotlib.pyplot as plt # For plotting the pie chart
# Load the pre-trained sentiment-analysis model from Hugging Face
# This is a binary sentiment model (Positive/Negative)
sentiment_analyzer = pipeline(
"sentiment-analysis",
model="distilbert-base-uncased-finetuned-sst-2-english" # Model fine-tuned on SST-2 for sentiment analysis
)
# Function to analyze sentiment of a single text input
def analyze_sentiment(text):
# Run the text through the sentiment analyzer
result = sentiment_analyzer(text)
# Return the sentiment label (Positive/Negative)
return result[0]['label']
# Function to analyze a file (CSV or Excel) and return sentiment results + pie chart
def analyze_file(file):
# Read the uploaded file based on its extension (CSV or Excel)
if file.name.endswith(".csv"):
df = pd.read_csv(file.name) # Read as CSV
elif file.name.endswith(".xlsx"):
df = pd.read_excel(file.name) # Read as Excel
else:
return "Unsupported file format", None # Return error message if the file format is unsupported
# Check if 'Text' column is present in the file
if "Text" not in df.columns:
return "Missing 'Text' column", None # Return error if 'Text' column is missing
# Predict sentiment for each row in the 'Text' column
sentiments = [sentiment_analyzer(t)[0]['label'] for t in df["Text"].fillna("")] # Handle empty cells with fillna("")
# Create a DataFrame with 'Text' and corresponding 'Sentiment'
df_result = pd.DataFrame({
"Text": df["Text"], # Original text column
"Sentiment": sentiments # Sentiment predictions
})
# Generate a pie chart to show the distribution of sentiments
sentiment_counts = df_result["Sentiment"].value_counts() # Count the occurrences of each sentiment
fig, ax = plt.subplots() # Create a figure and axis for plotting
ax.pie(
sentiment_counts.values, # Data for the pie chart
labels=sentiment_counts.index, # Sentiment labels (e.g., 'POSITIVE', 'NEGATIVE')
autopct="%1.1f%%", # Show percentage on the pie chart
colors=["#66bb6a", "#ef5350", "#ffee58"][:len(sentiment_counts)] # Color palette for the pie chart
)
ax.set_title("Sentiment Distribution") # Title of the pie chart
return df_result, fig # Return the DataFrame and the pie chart figure
# Creating the Gradio interface with two tabs: one for text input and one for file upload
with gr.Blocks() as demo:
gr.Markdown("## 🧠 Text Sentiment Analyzer with Pie Chart") # Title
gr.Markdown("Enter text manually or upload a file with a **Text** column.") # Description
# Tab for analyzing a single text input
with gr.Tab("🔤 Single Text"):
txt = gr.Textbox(label="Text", lines=4) # Textbox for text input
out = gr.Textbox(label="Sentiment") # Textbox to show sentiment output
btn = gr.Button("Analyze") # Button to trigger analysis
btn.click(analyze_sentiment, inputs=txt, outputs=out) # Trigger analysis when button is clicked
# Tab for uploading a file (CSV or Excel)
with gr.Tab("📁 Upload File"):
file_input = gr.File(label="Upload CSV or Excel File") # File uploader
file_output = gr.Dataframe(label="Sentiment Results") # Table to display the sentiment results
chart_output = gr.Plot(label="Sentiment Distribution Pie Chart") # Pie chart to display sentiment distribution
btn2 = gr.Button("Analyze File") # Button to trigger file analysis
btn2.click(analyze_file, inputs=file_input, outputs=[file_output, chart_output]) # Trigger file analysis when button is clicked
# Launch the app
demo.launch()