from transformers import pipeline import pandas as pd import gradio as gr # Initialize the sentiment analysis pipeline sentiment_pipeline = pipeline("sentiment-analysis") def analyze_csv(file_path): # Read the CSV file df = pd.read_csv(file_path) # Ensure the CSV has a 'text' column if 'text' not in df.columns: return "Error: CSV must contain a 'text' column." # Apply sentiment analysis on each text entry results = df['text'].apply(lambda x: sentiment_pipeline(x)[0]) df['sentiment'] = results.apply(lambda r: r['label']) df['score'] = results.apply(lambda r: r['score']) # Return the DataFrame as a CSV string return df.to_csv(index=False) def gradio_analyze(file_obj): # Get the path of the uploaded file and analyze it file_path = file_obj.name return analyze_csv(file_path) # Define the Gradio interface iface = gr.Interface( fn=gradio_analyze, inputs=gr.File(label="Upload CSV File", file_count="single", type="file"), outputs=gr.Textbox(label="CSV with Sentiment Analysis"), title="CSV Sentiment Analysis App", description="Upload a CSV file with a 'text' column. The app will run sentiment analysis on each row and return the CSV with sentiment labels and scores." ) if __name__ == "__main__": iface.launch()