Spaces:
Sleeping
Sleeping
Download app.py from rohitme890712/Sentiment-analysis: direct link, hf CLI and curl.
- Browser
- Download file 3.04 kB
-
https://huggingface.co/spaces/rohitme890712/Sentiment-analysis/resolve/main/app.py
- Command line
-
hf download hf://spaces/rohitme890712/Sentiment-analysis/app.py
-
curl -L -o app.py https://huggingface.co/spaces/rohitme890712/Sentiment-analysis/resolve/main/app.py
3.04 kB
| import streamlit as st | |
| import pandas as pd | |
| from transformers import pipeline | |
| # Load the sentiment analysis pipeline | |
| # Cache the pipeline for faster loading | |
| def load_pipeline(): | |
| return pipeline("sentiment-analysis", model="distilbert-base-uncased", framework="pt") | |
| sentiment_pipeline = load_pipeline() | |
| # Streamlit app | |
| st.title("Sentiment Analysis Tool") | |
| # Input option: Text area or CSV file | |
| input_option = st.radio("Choose input method:", ("Text Area", "CSV File")) | |
| if input_option == "Text Area": | |
| # User input (Text Area) | |
| text = st.text_area("Enter text to analyze:", "This is a great movie!") | |
| # Analyze button | |
| if st.button("Analyze Text"): | |
| if text: | |
| with st.spinner("Analyzing..."): | |
| result = sentiment_pipeline(text)[0] # Get the first (and only) result | |
| st.write("Sentiment:", result['label']) | |
| st.write("Confidence:", result['score']) | |
| else: | |
| st.warning("Please enter some text to analyze.") | |
| elif input_option == "CSV File": | |
| # CSV File Upload | |
| uploaded_file = st.file_uploader("Upload a CSV file", type="csv") | |
| if uploaded_file is not None: | |
| try: | |
| df = pd.read_csv(uploaded_file) | |
| st.write("Preview of the CSV file:") | |
| st.dataframe(df.head()) # Display the first few rows | |
| # Column selection | |
| text_column = st.selectbox("Select the column containing the text:", df.columns) | |
| # Analyze button | |
| if st.button("Analyze CSV"): | |
| if text_column: | |
| with st.spinner("Analyzing..."): | |
| # Perform sentiment analysis on each row | |
| results = [] | |
| for index, row in df.iterrows(): | |
| text = row[text_column] | |
| try: | |
| result = sentiment_pipeline(text)[0] | |
| results.append({"text": text, "sentiment": result['label'], "confidence": result['score']}) | |
| except Exception as e: | |
| results.append({"text": text, "sentiment": "Error", "confidence": 0.0, "error": str(e)}) #append error to text column | |
| results_df = pd.DataFrame(results) | |
| st.write("Sentiment Analysis Results:") | |
| st.dataframe(results_df) | |
| # Download the results as CSV | |
| csv = results_df.to_csv(index=False).encode('utf-8') | |
| st.download_button( | |
| label="Download results as CSV", | |
| data=csv, | |
| file_name="sentiment_analysis_results.csv", | |
| mime='text/csv', | |
| ) | |
| else: | |
| st.warning("Please select the text column.") | |
| except Exception as e: | |
| st.error(f"Error reading the CSV file: {e}") |