import torch import re import gradio as gr import pandas as pd import matplotlib.pyplot as plt from pydantic import BaseModel, PydanticUserError, ConfigDict from pydantic import BaseModel, ConfigDict class MyModel(BaseModel): request: 'starlette.requests.Request' model_config = ConfigDict(arbitrary_types_allowed=True) from pydantic_core import core_schema from starlette.requests import Request def get_pydantic_core_schema(request_type, handler): return core_schema.any_schema() Request.__get_pydantic_core_schema__ = get_pydantic_core_schema from transformers import pipeline pipe = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english") analyzer=pipeline(task="text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english") def sentiment_analyzer(review): sentiment = analyzer(review) return sentiment[0]['label'] def sentiment_bar_chart(df): sentiment_counts=df['Sentiment'].value_counts() fig, ax=plt.subplots() sentiment_counts.plot(kind='pie', ax=ax, autopct='%1.1f%%', color=['green', 'red']) ax.set_title('Review Sentiment Counts') ax.set_xlabel('Sentiment') ax.set_ylabel('Count') #ax.set_xticklabels(['Positive', 'Negative'], rotation=0) return fig def get_sentiment(review): from textblob import TextBlob analysis=TextBlob(review) return analysis.sentiment.polarity def read_reviews_and_analyze_sentiment(file_object): print("file_obj received:", file_object) # Handle file path or file object if hasattr(file_object, 'name'): file_name = file_object.name else: file_name = file_object # Read file based on extension if str(file_name).lower().endswith('.csv'): df = pd.read_csv(file_object) elif str(file_name).lower().endswith(('.xlsx', '.xls', '.xlsm', '.xlsb', '.ods', '.odt')): df = pd.read_excel(file_object) else: raise ValueError("Unsupported file type. Please upload a CSV or Excel file.") df['Sentiment']=df['Reviews'].apply(sentiment_analyzer) chart_object=sentiment_bar_chart(df) return df, chart_object gr.close_all() demo = gr.Interface( fn=read_reviews_and_analyze_sentiment, inputs=gr.File(file_types=['.xlsx','csv'], label='Upload your review comment file'), outputs=[gr.Dataframe(label='Sentiments'), gr.Plot(label='Sentiment Analysis')], title='KS Sentiment Analyzer', description='This application will classify the sentiment of reviews based on an uploaded Excel file. The file must contain a column named "Reviews".' ) demo.launch(share=True)