import pandas as pd import matplotlib.pyplot as plt from transformers import pipeline import gradio as gr import os # Define the default file path for the example reviews.txt DEFAULT_FILE_PATH = "reviews.txt" # Initialize the sentiment analyzer pipeline sentiment_Analyzer = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english") # Function to read reviews from a text file and convert to a pandas DataFrame def read_reviews_to_dataframe(file_path): reviews = [] with open(file_path, 'r', encoding='utf-8') as file: for line in file: reviews.append(line.strip()) df = pd.DataFrame(reviews, columns=['Review']) return df # Analyzer function to apply sentiment analysis on each review def analyzer(text): output = sentiment_Analyzer(text)[0] return output['label'], output['score'] # Function to add an 'Evaluation' column to the DataFrame based on sentiment analysis def evaluate_reviews(df): df['Evaluation'] = df['Review'].apply(lambda x: analyzer(x)) df[['Sentiment', 'Score']] = pd.DataFrame(df['Evaluation'].tolist(), index=df.index) df.drop(columns=['Evaluation'], inplace=True) return df # Function to create a pie chart showing the percentage of positive and negative reviews def create_pie_chart(df): sentiment_counts = df['Sentiment'].value_counts() labels = sentiment_counts.index sizes = sentiment_counts.values colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99'] fig, ax = plt.subplots() ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90) ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.title('Sentiment Analysis of Reviews') chart_path = 'sentiment_pie_chart.png' plt.savefig(chart_path) plt.close(fig) return chart_path # Function to process the file def process_reviews(file): file_path = file.name df = read_reviews_to_dataframe(file_path) df = evaluate_reviews(df) chart_path = create_pie_chart(df) return df, chart_path # Gradio interface function def gradio_interface(file): return process_reviews(file) # Create the Gradio interface interface = gr.Interface( fn=gradio_interface, inputs=gr.File(label="Upload a text file with reviews"), outputs=[ gr.Dataframe(label="Reviews with Evaluation"), gr.Image(label="Sentiment Pie Chart") ], title="Sentiment Analyzer", description="Upload a text file with reviews to analyze the sentiment and visualize the results.", examples=[[DEFAULT_FILE_PATH]], allow_flagging="never" ) # Launch the Gradio interface interface.launch()