create a webapp for fake news detection and sentiment analysis
To upload files, please first save the app
import streamlit as st
from textblob import TextBlob
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
import numpy as np
import pandas as pd
# Set page config
st.set_page_config(page_title="News Analyzer", layout="wide")
# Initialize the fake news classifier
@st.cache_resource
def initialize_classifier():
# Create some example data for demonstration
fake_news = [
"BREAKING: Aliens found living among us in secret!",
"Scientists discover chocolate cures all diseases!",
"Government admits to controlling weather patterns!",
"New study shows phones actually make you smarter!",
"Celebrity reveals they're actually a robot!"
]
real_news = [
"Local community opens new public library",
"Research shows benefits of regular exercise",
"New environmental protection law passed",
"Stock market shows steady growth this quarter",
"Scientists develop new renewable energy technology"
]
# Create labels
X = fake_news + real_news
y = [0] * len(fake_news) + [1] * len(real_news) # 0 for fake, 1 for real
# Create and train the classifier
vectorizer = TfidfVectorizer()
X_vectorized = vectorizer.fit_transform(X)
classifier = MultinomialNB()
classifier.fit(X_vectorized, y)
return vectorizer, classifier
# Load the classifier
vectorizer, classifier = initialize_classifier()
# Title and description
st.title("📰 News Analyzer")
st.markdown("""
This app helps you analyze news content in two ways:
1. Detect potential fake news
2. Analyze the sentiment of the text
""")
# Text input
news_text = st.text_area("Enter the news text to analyze:", height=200)
if news_text:
# Create columns for results
col1, col2 = st.columns(2)
with col1:
st.subheader("Fake News Detection")
# Vectorize the input text
text_vectorized = vectorizer.transform([news_text])
# Get prediction and probability
prediction = classifier.predict(text_vectorized)[0]
prob = classifier.predict_proba(text_vectorized)[0]
# Display results with color coding
if prediction == 1:
probability_real = prob[1] * 100
st.success(f"This news appears to be REAL with {probability_real:.2f}% confidence")
else:
probability_fake = prob[0] * 100
st.error(f"This news might be FAKE with {probability_fake:.2f}% confidence")
st.info("Note: This is a simple demonstration model. Always verify news from reliable sources.")
with col2:
st.subheader("Sentiment Analysis")
# Perform sentiment analysis
blob = TextBlob(news_text)
sentiment = blob.sentiment
# Calculate sentiment scores
polarity = sentiment.polarity
subjectivity = sentiment.subjectivity
# Display sentiment results
st.write("Sentiment Polarity:", round(polarity, 2))
st.write("Subjectivity Score:", round(subjectivity, 2))
# Interpret sentiment
if polarity > 0:
st.success("This text has a POSITIVE tone")
elif polarity < 0:
st.error("This text has a NEGATIVE tone")
else:
st.info("This text has a NEUTRAL tone")
# Create a gauge chart for sentiment
sentiment_data = pd.DataFrame({
'Metric': ['Polarity', 'Subjectivity'],
'Score': [polarity, subjectivity]
})
st.bar_chart(sentiment_data.set_index('Metric'))
# Add explanation section
st.markdown("""
---
### How it works
**Fake News Detection:**
- Uses a simple Naive Bayes classifier trained on example data
- Analyzes patterns in text that might indicate misleading content
- Provides a confidence score for the prediction
**Sentiment Analysis:**
- Measures the emotional tone of the text (positive, negative, or neutral)
- Polarity ranges from -1 (negative) to 1 (positive)
- Subjectivity ranges from 0 (objective) to 1 (subjective)
⚠️ **Disclaimer:** This is a demonstration tool and should not be used as the sole method for verifying news authenticity.
""")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?