| import pandas as pd |
| import matplotlib.pyplot as plt |
| from transformers import pipeline |
| import gradio as gr |
| import os |
|
|
| |
| DEFAULT_FILE_PATH = "reviews.txt" |
|
|
| |
| sentiment_Analyzer = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english") |
|
|
| |
| 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 |
|
|
| |
| def analyzer(text): |
| output = sentiment_Analyzer(text)[0] |
| return output['label'], output['score'] |
|
|
| |
| 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 |
|
|
| |
| 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') |
| plt.title('Sentiment Analysis of Reviews') |
| chart_path = 'sentiment_pie_chart.png' |
| plt.savefig(chart_path) |
| plt.close(fig) |
| return chart_path |
|
|
| |
| 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 |
|
|
| |
| def gradio_interface(file): |
| return process_reviews(file) |
|
|
| |
| 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" |
| ) |
|
|
| |
| interface.launch() |
|
|
|
|