import gradio as gr import pandas as pd from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline import matplotlib.pyplot as plt import spaces # Load model and tokenizer model_name = "ac0hik/Sentiment_Analysis_French" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSequenceClassification.from_pretrained(model_name) # Create sentiment analysis pipeline classifier = pipeline('sentiment-analysis', model=model, tokenizer=tokenizer) # Function to process a single text input @spaces.GPU def analyze_text(text): result = classifier(text)[0] return result # Function to process a CSV file and update results live @spaces.GPU def analyze_csv(file): df = pd.read_csv(file.name, nrows=100) texts = df['text'].tolist() results = [] pos_count = neg_count = neu_count = 0 for text in texts: result = classifier(text)[0] results.append({'text': text, 'sentiment': result['label']}) if result['label'] == 'positive': pos_count += 1 elif result['label'] == 'negative': neg_count += 1 else: neu_count += 1 # Create a pie chart labels = 'Positive', 'Negative', 'Neutral' sizes = [pos_count, neg_count, neu_count] colors = ['#ff9999','#66b3ff','#99ff99'] fig, ax = plt.subplots() wedges, texts, autotexts = ax.pie(sizes, labels=labels, colors=colors, autopct=lambda pct: "{:.1f}%\n({:d})".format(pct, int(pct/100.*sum(sizes))), startangle=90) ax.axis('equal') # Update results live yield pd.DataFrame(results), fig # Gradio interface with gr.Blocks() as demo: with gr.Row(): with gr.Column(): gr.Markdown("## Sentiment Analysis") text_input = gr.Textbox(label="Enter Text") text_output = gr.JSON(label="Sentiment Analysis Result") text_button = gr.Button("Analyze Text") csv_input = gr.File(label="Upload CSV", file_types=['csv']) csv_output = gr.Dataframe(label="Sentiment Analysis Results") csv_button = gr.Button("Analyze CSV") with gr.Column(): csv_chart = gr.Plot(label="Sentiment Distribution") text_button.click(analyze_text, inputs=text_input, outputs=text_output) csv_button.click(analyze_csv, inputs=csv_input, outputs=[csv_output, csv_chart]) # Launch the Gradio app demo.launch()