File size: 1,400 Bytes
d7b6823
 
 
 
 
a3f23ab
d7b6823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7d4c76
d7b6823
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from transformers import pipeline
import pandas as pd
import gradio as gr

# Initialize the sentiment analysis pipeline
sentiment_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english", framework="pt")

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="filepath"),
    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()