TruthLens- AI Powered Fake News Detection Extension
Leverage the power of AI to combat misinformation with TruthLens, a browser extension designed to detect and flag fake news articles in real-time.
Demo Video
Source: https://youtu.be/E33CvPGcaOw
The Problem
Fake news and misinformation have become one of the most pressing challenges of our digital age. Social media platforms and news websites are flooded with content that ranges from slightly biased to completely fabricated. Users often lack the tools and time to verify the credibility of every article they encounter.
"The best way to combat misinformation is to make fact-checking as seamless and automatic as possible."
The Solution: TruthLens
TruthLens is a Chrome extension that analyzes news articles in real-time using advanced natural language processing and machine learning models. It provides users with instant credibility assessments and detailed analysis to help them make informed decisions about the content they consume.
Key Features
- Real-time Analysis - Instant credibility assessment as you browse
- Visual Trust Indicators - Clear High ✅, Medium ⚠️, Low ❌ credibility ratings
- Detailed Analysis Popup - Comprehensive breakdown of sentiment, bias, and source verification
- Cross-verification - Integration with trusted fact-checking sources
- Persistent Storage - Stores verified articles for transparency and reference
- User Reporting - Community feedback system for continuous improvement
Technical Architecture
TruthLens is built with a modern tech stack that ensures both performance and accuracy:
Frontend (Chrome Extension)
- React.js - Component-based UI development
- TypeScript - Type safety and better development experience
- Tailwind CSS - Utility-first styling for rapid UI development
- Manifest V3 - Latest Chrome extension protocol for enhanced security
Backend (AI Analysis)
- Python & FastAPI - High-performance API development
- Hugging Face Transformers - State-of-the-art NLP models
- Newspaper3k - Article extraction and parsing
- Google Fact-Check API - Cross-verification with trusted sources
Data & Caching
- Redis - High-speed caching for improved performance
- PostgreSQL - Robust data storage for production environments
AI Models and Analysis
The heart of TruthLens lies in its sophisticated AI analysis pipeline:
Natural Language Processing
TruthLens employs multiple pre-trained models from Hugging Face to analyze different aspects of news content:
# Credibility Analysis Pipeline
from transformers import pipeline
# Sentiment Analysis
sentiment_analyzer = pipeline(
"sentiment-analysis",
model="cardiffnlp/twitter-roberta-base-sentiment-latest"
)
# Bias Detection
bias_detector = pipeline(
"text-classification",
model="unitary/toxic-bert"
)
# Fact-checking Classification
fact_checker = pipeline(
"text-classification",
model="microsoft/DialoGPT-medium"
)
def analyze_article(article_text):
results = {
"sentiment": sentiment_analyzer(article_text),
"bias_score": bias_detector(article_text),
"credibility": fact_checker(article_text)
}
return calculate_trust_score(results)
Trust Score Calculation
TruthLens combines multiple factors to calculate a comprehensive trust score:
- Source Reliability - Domain authority and historical accuracy
- Content Analysis - Language patterns, sentiment, and bias detection
- Fact Verification - Cross-reference with verified fact-checking databases
- Social Signals - Community feedback and reporting patterns
Chrome Extension Development
Building a Chrome extension with Manifest V3 presented unique challenges and opportunities:
Content Script Integration
// content.ts - Real-time article analysis
class TruthLensContentScript {
private observer: MutationObserver;
constructor() {
this.initializeExtension();
this.setupArticleDetection();
}
private async analyzeArticle(element: HTMLElement) {
const articleText = this.extractArticleContent(element);
if (articleText.length > 100) {
const analysis = await this.sendToBackend(articleText);
this.displayTrustBadge(element, analysis);
}
}
private displayTrustBadge(element: HTMLElement, analysis: Analysis) {
const badge = this.createTrustBadge(analysis.trustScore);
element.appendChild(badge);
}
}
Popup Interface
The extension popup provides detailed analysis results in an intuitive interface:
// popup.tsx - Extension popup interface
const TruthLensPopup: React.FC = () => {
const [analysis, setAnalysis] = useState<ArticleAnalysis | null>(null);
const handleVerifyArticle = async () => {
const activeTab = await chrome.tabs.query({ active: true });
const result = await chrome.tabs.sendMessage(
activeTab[0].id!,
{ action: 'analyzeCurrentPage' }
);
setAnalysis(result);
};
return (
<div className="w-80 p-4 bg-white">
<TrustScoreDisplay score={analysis?.trustScore} />
<BiasIndicator bias={analysis?.bias} />
<SourceVerification sources={analysis?.sources} />
<UserActions onReport={handleReport} />
</div>
);
};
Backend API Design
The FastAPI backend provides robust endpoints for analysis and fact-checking:
# main.py - FastAPI backend
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import asyncio
app = FastAPI(title="TruthLens API")
class ArticleRequest(BaseModel):
url: str
content: str
title: str
class AnalysisResponse(BaseModel):
trust_score: float
sentiment: str
bias_level: str
fact_check_results: list
confidence: float
@app.post("/analyze", response_model=AnalysisResponse)
async def analyze_article(request: ArticleRequest):
try:
# Run analysis pipeline
analysis_tasks = [
analyze_sentiment(request.content),
detect_bias(request.content),
verify_facts(request.content),
check_source_credibility(request.url)
]
results = await asyncio.gather(*analysis_tasks)
return AnalysisResponse(
trust_score=calculate_trust_score(results),
sentiment=results[0]["label"],
bias_level=results[1]["classification"],
fact_check_results=results[2],
confidence=calculate_confidence(results)
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Project Structure
Challenges and Solutions
Performance Optimization
Real-time analysis requires careful optimization:
- Caching Strategy - Redis caching for previously analyzed articles
- Async Processing - Non-blocking analysis using Python asyncio
- Model Optimization - Using lightweight, fine-tuned models for speed
- Content Filtering - Smart article detection to avoid analyzing irrelevant content
Accuracy Improvements
Ensuring high accuracy in fake news detection:
- Ensemble Methods - Combining multiple models for better predictions
- Source Verification - Cross-referencing with established fact-checking organizations
- Continuous Learning - User feedback integration for model improvement
- Context Awareness - Considering article source, date, and related content
Setup and Installation
Extension Installation
- Clone the repository and navigate to the extension directory
- Install dependencies with
npm install
- Build the extension using
npm run build
- Load the extension in Chrome developer mode
Backend Setup
- Set up a Python virtual environment
- Install dependencies from
requirements.txt
- Configure environment variables for API keys
- Start the FastAPI server with
uvicorn app.main:app --reload
Environment Configuration
HUGGINGFACE_API_KEY=your_huggingface_key
GOOGLE_FACT_CHECK_API_KEY=your_google_api_key
REDIS_URL=redis://localhost:6379/0
DB_CONNECTION_STRING=postgresql://username:password@localhost/truthlens
USE_GPU=false
LOG_LEVEL=INFO
PORT=8000
Testing and Validation
TruthLens includes comprehensive testing strategies:
Automated Testing
- Unit Tests - Individual component and function testing
- Integration Tests - API endpoint and extension communication testing
- Model Validation - Accuracy testing against known datasets
- Performance Testing - Load testing for scalability
Real-world Validation
- Beta Testing - User testing with diverse news sources
- Accuracy Benchmarking - Comparison with established fact-checking services
- Performance Monitoring - Real-time performance metrics and optimization
Future Enhancements
TruthLens is continuously evolving with planned improvements:
- Multi-language Support - Extending analysis to non-English content
- Social Media Integration - Analysis of social media posts and comments
- Mobile Extension - Browser extensions for mobile platforms
- API Marketplace - Offering TruthLens analysis as a service
- Educational Features - Teaching users about media literacy
Impact and Results
TruthLens represents more than just a technical achievement—it's a step toward a more informed digital society. By making fact-checking accessible and automatic, we can help users develop better media literacy and make more informed decisions about the content they consume and share.
"Technology should empower users to think critically, not replace their critical thinking. TruthLens provides the tools; users make the decisions."
Conclusion
TruthLens demonstrates the potential of AI to address real-world problems. By combining advanced natural language processing, user-friendly design, and robust engineering, we can create tools that help users navigate the complex information landscape of the modern web.
This project has been an incredible journey in AI development, Chrome extension architecture, and user experience design. It showcases the power of modern web technologies to create meaningful, impactful applications that serve the public good.
As misinformation continues to evolve, so too must our tools for detecting and combating it. TruthLens is just the beginning of what's possible when we apply cutting-edge technology to one of the most pressing challenges of our time.