Added multi perspective feature
What I Added
I added a Multi-Perspective Analysis feature that lets users view any article through six different lenses - Educational, Technical, Political, Economic, Social, and Global.
Instead of giving just one summary, the system now generates separate analytical perspectives for each lens. The idea is to help users understand the same article from different viewpoints - like how it affects society, markets, policy, technology.
How It Works
Backend
I created a modular system inside app/modules/perspectives/ that handles the lens-based analysis.
The backend first processes the article once and extracts important metadata like:
- Main claim
- Key entities
- Tone
- Important points
Then this metadata is reused for each perspective. This keeps the outputs consistent and avoids repeating heavy processing.
For generation, I used llama-3.3-70b-versatile via Groq to produce the perspective analyses.
Performance
To avoid unnecessary API calls, I extended the SQLite caching layer so that:
- processed article metadata is cached
- generated perspectives are also cached
So if the same article is requested again, it loads much faster and doesn't hit the API again.
Frontend
I built a React component called:
MultiPerspectivePanel.tsx
This component:
- shows the six lenses
- lets users switch between them
- displays the generated analysis
- shows generation status if something is still loading
The UI uses a glassmorphism style with color-coded lenses so it feels interactive and easier to navigate.
Issue
Fixes #144
Notes
I tuned the prompts for each lens so they don't generate generic summaries.
Each lens focuses on its own angle. For example:
- Economic → market impact, financial implications
- Political → governance challenges, policy effects
- Technical → technology and implementation aspects
This helps the outputs stay focused and more useful.
AI Usage Disclosure
- [ ] This PR does not contain AI-generated code
- [x] This PR contains AI-generated code and follows the AI Usage Policy
Tools used
- Gemini 2.0 Pro - for architectural planning and some UI work
- Llama-3.3-70b-versatile (via Groq) - for generating the perspective analyses
Checklist
- [x] My PR focuses on a single improvement
- [x] Code follows the project's style and conventions
- [x] Documentation updated where needed
- [ ] Tests added where applicable
- [x] No new warnings or errors introduced
- [ ] I will share this PR on the Discord server
- [ ] I have read the Contribution Guidelines
- [x] I will address CodeRabbit review comments if any
- [x] This PR template has been filled properly
##short demo https://drive.google.com/file/u/1/d/1-nsQT61Yfc9YYFNorqbwGwBhrbK4_vkI/view?usp=sharing
Summary by CodeRabbit
Release Notes
-
New Features
- Multi-perspective article analysis with 6 distinct analytical lenses (educational, technical, political, economic, social, global)
- Trending articles feed with credibility-ranked sources
- Enhanced bias detection with dimensional breakdown and summary insights
- Improved article caching for faster re-analysis
- Modern UI with enhanced visual effects and custom cursor interactions
-
Improvements
- Better article extraction with multiple fallback strategies
- Streamlined fact-checking with batch verification
- Enhanced error handling with user-friendly messaging
This pull request introduces a comprehensive multi-perspective article analysis system with distributed caching, restructured LLM workflows, and a redesigned UI. Changes span new caching infrastructure (SQLite with TTL), refactored bias detection (multi-dimensional scoring), batch fact verification, and modular lens-based perspective generation, alongside significant frontend redesigns for article analysis, trending content, and multi-perspective comparison. 🎯 4 (Complex) | ⏱️ ~50 minutes 🐰 Hopping through perspectives with glee,
Six lenses now let us all see—
Cache speeds the way, facts verified true,
Multi-dimensional bias in view,
A journey of insights, clear as can be! ✨ ✏️ Tip: You can configure your own custom pre-merge checks in the settings.📝 Walkthrough
Walkthrough
Changes
Cohort / File(s)
Summary
Configuration & Infrastructure
.vscode/settings.json, backend/.pyre_configuration, pyrightconfig.json, frontend/.eslintrc.json, frontend/tsconfig.jsonNew IDE and static analysis configurations for Python type checking, ESLint, and TypeScript compiler flags (unused variable detection).
Caching & Database
backend/app/db/sqlite_cache.pyNew SQLite cache module with per-thread WAL connections, article/perspective TTL-based expiry (7/30 days), eviction policies, and hash-based lookups for both articles and multi-lens perspectives.
Article Extraction & Cleaning
backend/app/modules/scraper/extractor.py, backend/app/modules/scraper/cleaner.pyExtractor rewritten with five-strategy orchestration (Trafilatura, Newspaper3k, BS4, Playwright, AMP fallback), SSRF protection, and header/UA management; cleaner upgraded to single-pass quality pipeline with entity decoding, boilerplate removal, and line-level QA gates.
Metadata & Keywords
backend/app/modules/article_extractor/extract_metadata.py, backend/app/modules/scraper/keywords.pyNew metadata extraction module using Groq LLM with retry logic for summary/claim/entities/tone/key_points; keywords module refactored for per-call RAKE instances and phrase deduplication.
Bias Detection
backend/app/modules/bias_detection/check_bias.pyRedesigned from single numeric score to multi-dimensional JSON output (language_bias, source_balance, framing_bias, omission_bias, confirmation_bias) with composite score and one-sentence summary.
Fact Checking Pipeline
backend/app/modules/facts_check/llm_processing.py, backend/app/modules/facts_check/web_search.py, backend/app/utils/fact_check_utils.pyClaim extraction uses structured prompts with retry; fact verifier batches all claims into single LLM call via JSON array; web search replaced DuckDuckGo (multi-result, credibility scoring) for Google Custom Search; pipeline adds source credibility propagation and partial-failure handling.
Chat & RAG
backend/app/modules/chat/llm_processing.py, backend/app/modules/chat/embed_query.py, backend/app/modules/chat/get_rag_data.py, backend/app/modules/vector_store/chunk_rag_data.py, backend/app/modules/vector_store/embed.pyLLM processing reworked with build_context helper, structured system prompts, and factual constraints; chunk_rag_data refactored for dict/Pydantic tolerance with per-claim chunking; minor formatting cleanup elsewhere.
Perspectives & Lenses
backend/app/modules/perspectives/generate_lens.py, backend/app/modules/perspectives/lens_prompts.py, backend/app/modules/langgraph_nodes/generate_perspective.pyNew generate_lens module orchestrates multi-lens analysis with caching; lens_prompts defines six lenses (educational, technical, political, economic, social, global) with metadata; generate_perspective switched to JSON-centric parsing and structured result mapping.
LangGraph Pipeline
backend/app/modules/langgraph_builder.py, backend/app/modules/langgraph_nodes/sentiment.py, backend/app/modules/langgraph_nodes/judge.py, backend/app/modules/langgraph_nodes/fact_check.py, backend/app/modules/langgraph_nodes/store_and_send.py, backend/app/modules/langgraph_nodes/error_handler.pyPipeline streamlined from descriptive multi-step to fixed graph with retry routing; sentiment expanded to include tone/intensity JSON; judge simplified to read pre-assigned scores; fact_check and store_and_send made non-fatal; removed setup_logger import from error_handler (undefined symbol issue).
Core Pipeline & Utilities
backend/app/modules/pipeline.py, backend/app/utils/prompt_templates.py, backend/app/utils/generate_chunk_id.py, backend/app/utils/store_vectors.py, backend/app/logging/logging_config.pyPipeline adds _smart_sample for 3-segment text windowing; prompt_templates reworked for richer counter-perspective JSON schema; minor docstring and formatting updates; logging adds blank line after imports.
API Routes & Main
backend/app/routes/routes.py, backend/app/routes/perspective_routes.py, backend/main.pyRoutes renamed URlRequest → URLRequest and added caching/metadata extraction calls; new perspective_routes expose /perspective/generate, /perspective/metadata, /perspective/lenses, /trending endpoints; main.py upgraded to v2 API with URL validation middleware, startup lifecycle hooks, and perspective router inclusion.
Trending & Scheduler
backend/app/modules/trending/rss_fetcher.py, backend/app/modules/trending/cron_job.pyNew RSS fetcher aggregates trending articles from 8 feeds with credibility scoring and HTML cleaning; new cron_job module uses APScheduler for 6-hour pre-generation of eager lenses with in-memory cache and thread-safe access.
Health Check & Dependencies
backend/health_check.py, backend/pyproject.tomlNew comprehensive health-check orchestrator validating SQLite, RSS feeds, URL middleware, lens prompts, and chunk generation; added dependencies (apscheduler, cloudscraper, feedparser, playwright, playwright-stealth, curl-cffi).
Frontend Pages - Analyze
frontend/app/analyze/page.tsx, frontend/app/analyze/loading/page.tsx, frontend/app/analyze/stitch-analyze.htmlNew analyze page adds trending articles fetch, custom cursor, and URL validation; loading page adds error handling, incremental step progression, and sessionStorage persistence; static HTML stitch provides design reference.
Frontend Pages - Results
frontend/app/analyze/results/page.tsx, frontend/app/analyze/results/MultiPerspectivePanel.tsx, frontend/app/analyze/results/stitch-results.htmlResults page redesigned with typed AnalysisData, semi-circular bias gauge, bias dimensions display, multi-tab article/perspective/factcheck sections, and AI discussion chat; new MultiPerspectivePanel component fetches and renders per-lens perspectives with caching; static HTML reference provided.
Frontend Landing & Home
frontend/app/page.tsx, perspective-landing.htmlHomepage reworked with data-driven NodeData/NodeTypeWithName types, interactive TiltCard component, modal-based node details, custom cursor, and pipeline visualization; static landing page adds similar modal system with chain-of-thought rendering.
Frontend Styling & Config
frontend/app/globals.css, frontend/app/layout.tsx, frontend/tailwind.config.ts, frontend/components/ui/calendar.tsxGlobals adds custom cursor classes, glass-card, particle-mesh, tilt-effect, and chart color tokens; layout adds Space Grotesk/Playfair Display/Space Mono Google fonts and Material Symbols; tailwind expanded with darkMode, extended theme colors, and animations; calendar icon components simplified prop handling.
Frontend Dependencies & Setup
frontend/package.json, frontend/.gitignore, frontend/app/error.tsxAdded framer-motion, eslint, and eslint-config-next; updated .gitignore for err.html; new error boundary component with digest logging and user-friendly error UI.
Sequence Diagram(s)
sequenceDiagram
actor User
participant Frontend
participant Main as FastAPI Main
participant Pipeline as Scraper + Pipeline
participant Cache as SQLite Cache
participant LLM as Groq LLM
participant VectorStore as Vector Store
User->>Frontend: Enter article URL
Frontend->>Main: POST /api/process (URL)
Main->>Cache: Check article cache
alt Cache Hit
Cache-->>Main: Return cached data
else Cache Miss
Main->>Pipeline: run_scraper_pipeline(url)
Pipeline->>Pipeline: Extract + Clean text
Pipeline->>Cache: save_article_cache()
Cache-->>Pipeline: Stored
Pipeline-->>Main: Return extracted data
end
Main->>LJM: run_langgraph_workflow()
rect rgba(100, 150, 200, 0.5)
LJM->>LJM: sentiment_analysis
LJM->>LJM: fact_checking (batch)
LJM->>LJM: generate_perspective
LJM->>LJM: judge_perspective
end
LJM->>VectorStore: store_and_send(chunks)
VectorStore-->>LJM: Stored
LJM-->>Main: Analysis results
Main-->>Frontend: Return state + bias
Frontend->>Frontend: Display results
sequenceDiagram
actor User
participant Frontend
participant Main as FastAPI Main
participant Perspective as Perspective Module
participant Cache as SQLite Cache
participant LLM as Groq LLM
User->>Frontend: Click lens button
Frontend->>Main: POST /api/perspective/generate (url, lens)
Main->>Perspective: generate_lens_perspective(url, lens)
Perspective->>Cache: get_cached_article(url)
alt Article Cached
Cache-->>Perspective: article_data
else Article Not Cached
Perspective->>Perspective: get_or_create_article_data(url)
Perspective->>Cache: save_article_cache()
end
Perspective->>Cache: get_cached_perspective(url, lens)
alt Perspective Cached
Cache-->>Perspective: content
Perspective-->>Main: Return cached result
else Perspective Not Cached
Perspective->>LLM: generate via lens prompt
LJM-->>Perspective: Generated perspective
Perspective->>Cache: save_perspective_cache()
Perspective-->>Main: Return new result
end
Main-->>Frontend: Perspective data
Frontend->>Frontend: Display result
Estimated code review effort
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name
Status
Explanation
Resolution
Docstring Coverage
⚠️ Warning
Docstring coverage is 55.06% which is insufficient. The required threshold is 80.00%.
Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name
Status
Explanation
Linked Issues check
✅ Passed
The PR implements all core requirements from issue
#144: generates multiple lens-specific perspectives (6 lenses), backs each with article metadata and LLM analysis, surfaces framing differences via structured prompts, provides article caching for performance, and enables direct lens comparison in the frontend.
Out of Scope Changes check
✅ Passed
Changes are scoped to implementing multi-perspective feature (
#144): new perspective modules, caching/metadata extraction, frontend lens component, and supporting infrastructure like RSS feeders, health checks, and middleware. Some additions (health_check.py, middleware) support the core feature but are reasonable supporting work.
Title check
✅ Passed
The title 'Added multi perspective feature' directly describes the main feature introduced in this PR, which adds a multi-perspective analysis capability with six lens-specific analyses for articles.
Description Check
✅ Passed
Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
please take a look on this!!