Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import pipeline
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import gradio as gr
|
| 4 |
+
|
| 5 |
+
# Initialize the sentiment analysis pipeline
|
| 6 |
+
sentiment_pipeline = pipeline("sentiment-analysis")
|
| 7 |
+
|
| 8 |
+
def analyze_csv(file_path):
|
| 9 |
+
# Read the CSV file
|
| 10 |
+
df = pd.read_csv(file_path)
|
| 11 |
+
|
| 12 |
+
# Ensure the CSV has a 'text' column
|
| 13 |
+
if 'text' not in df.columns:
|
| 14 |
+
return "Error: CSV must contain a 'text' column."
|
| 15 |
+
|
| 16 |
+
# Apply sentiment analysis on each text entry
|
| 17 |
+
results = df['text'].apply(lambda x: sentiment_pipeline(x)[0])
|
| 18 |
+
df['sentiment'] = results.apply(lambda r: r['label'])
|
| 19 |
+
df['score'] = results.apply(lambda r: r['score'])
|
| 20 |
+
|
| 21 |
+
# Return the DataFrame as a CSV string
|
| 22 |
+
return df.to_csv(index=False)
|
| 23 |
+
|
| 24 |
+
def gradio_analyze(file_obj):
|
| 25 |
+
# Get the path of the uploaded file and analyze it
|
| 26 |
+
file_path = file_obj.name
|
| 27 |
+
return analyze_csv(file_path)
|
| 28 |
+
|
| 29 |
+
# Define the Gradio interface
|
| 30 |
+
iface = gr.Interface(
|
| 31 |
+
fn=gradio_analyze,
|
| 32 |
+
inputs=gr.File(label="Upload CSV File", file_count="single", type="file"),
|
| 33 |
+
outputs=gr.Textbox(label="CSV with Sentiment Analysis"),
|
| 34 |
+
title="CSV Sentiment Analysis App",
|
| 35 |
+
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."
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
if __name__ == "__main__":
|
| 39 |
+
iface.launch()
|