Spaces:
Sleeping
Sleeping
Commit ·
454f118
0
Parent(s):
Initial commit
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .env.example +31 -0
- .gitattributes +3 -0
- .gitignore +52 -0
- .streamlit/config.toml +17 -0
- Dockerfile +22 -0
- README.md +132 -0
- app/__init__.py +0 -0
- app/api/__init__.py +1 -0
- app/api/server.py +369 -0
- app/db/__init__.py +3 -0
- app/db/chat_store.py +167 -0
- app/main.py +862 -0
- app/pages/1_Chat.py +204 -0
- app/pages/2_Compare.py +259 -0
- app/pages/3_Dashboard.py +242 -0
- app/pages/__init__.py +0 -0
- app/rag_engine.py +57 -0
- app/static/index.html +1306 -0
- config/__init__.py +4 -0
- config/settings.py +168 -0
- data/bm25_index/bm25.pkl +3 -0
- data/bm25_index/docs.json +0 -0
- data/chat_history.db +0 -0
- docs/chat_screenshot.png +3 -0
- docs/chat_screenshot2.png +3 -0
- docs/compare_screenshot.png +3 -0
- docs/dashboard_screenshot.png +3 -0
- docs/main_ui.png +3 -0
- raw_pdfs/AIRTEL.pdf +3 -0
- raw_pdfs/AXIS.pdf +3 -0
- raw_pdfs/BAJAJ.pdf +3 -0
- raw_pdfs/HCL.pdf +3 -0
- raw_pdfs/HDFC.pdf +3 -0
- raw_pdfs/HU.pdf +3 -0
- raw_pdfs/ICICI-1.pdf +3 -0
- raw_pdfs/ICICI-2.pdf +3 -0
- raw_pdfs/INFOSYS-1.pdf +3 -0
- raw_pdfs/INFOSYS-2.pdf +3 -0
- raw_pdfs/ITC.pdf +3 -0
- raw_pdfs/KOTAK-1.pdf +3 -0
- raw_pdfs/KOTAK-2.pdf +3 -0
- raw_pdfs/KVB.pdf +3 -0
- raw_pdfs/L&T.pdf +3 -0
- raw_pdfs/MARUTI.pdf +3 -0
- raw_pdfs/MRF.pdf +3 -0
- raw_pdfs/ONGC.pdf +3 -0
- raw_pdfs/REL.pdf +3 -0
- raw_pdfs/SBI-1.pdf +3 -0
- raw_pdfs/SBI-2.pdf +3 -0
- raw_pdfs/TCS-1.pdf +3 -0
.env.example
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
# Groq API Key (get free key at: https://console.groq.com)
|
| 4 |
+
GROQ_API_KEY=your_groq_api_key_here
|
| 5 |
+
|
| 6 |
+
# LLM Model (default: llama-3.3-70b-versatile)
|
| 7 |
+
# Other options: mixtral-8x7b-32768, llama-3.1-8b-instant
|
| 8 |
+
GROQ_MODEL=llama-3.3-70b-versatile
|
| 9 |
+
|
| 10 |
+
EMBEDDING_MODEL=BAAI/bge-large-en-v1.5
|
| 11 |
+
|
| 12 |
+
RERANKER_MODEL=BAAI/bge-reranker-base
|
| 13 |
+
|
| 14 |
+
QDRANT_PATH=./data/qdrant_store
|
| 15 |
+
QDRANT_COLLECTION=financial_rag
|
| 16 |
+
|
| 17 |
+
BM25_INDEX_PATH=./data/bm25_index
|
| 18 |
+
|
| 19 |
+
# Processed Documents Cache
|
| 20 |
+
PROCESSED_DOCS_PATH=./data/processed
|
| 21 |
+
|
| 22 |
+
# Raw PDFs Directory
|
| 23 |
+
RAW_PDFS_PATH=./raw_pdfs
|
| 24 |
+
|
| 25 |
+
# Device (auto / cuda / cpu)
|
| 26 |
+
DEVICE=auto
|
| 27 |
+
|
| 28 |
+
USE_TF=0
|
| 29 |
+
USE_TORCH=1
|
| 30 |
+
|
| 31 |
+
LOG_LEVEL=INFO
|
.gitattributes
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.pdf filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ============================================================
|
| 2 |
+
# .gitignore for Production Financial RAG Project
|
| 3 |
+
# ============================================================
|
| 4 |
+
|
| 5 |
+
# Environment / secrets — NEVER commit this
|
| 6 |
+
.env
|
| 7 |
+
|
| 8 |
+
# Python
|
| 9 |
+
__pycache__/
|
| 10 |
+
*.py[cod]
|
| 11 |
+
*$py.class
|
| 12 |
+
*.so
|
| 13 |
+
.Python
|
| 14 |
+
*.egg-info/
|
| 15 |
+
dist/
|
| 16 |
+
build/
|
| 17 |
+
*.egg
|
| 18 |
+
.eggs/
|
| 19 |
+
|
| 20 |
+
# Virtual environments
|
| 21 |
+
venv/
|
| 22 |
+
env/
|
| 23 |
+
.venv/
|
| 24 |
+
ENV/
|
| 25 |
+
|
| 26 |
+
# Data directories (large files, auto-generated)
|
| 27 |
+
data/qdrant_store/
|
| 28 |
+
data/processed/
|
| 29 |
+
|
| 30 |
+
# Model cache (downloaded locally, ~1-3GB)
|
| 31 |
+
.cache/
|
| 32 |
+
models/
|
| 33 |
+
|
| 34 |
+
# Jupyter / IDE
|
| 35 |
+
.ipynb_checkpoints/
|
| 36 |
+
*.ipynb
|
| 37 |
+
.idea/
|
| 38 |
+
.vscode/
|
| 39 |
+
*.swp
|
| 40 |
+
*.swo
|
| 41 |
+
|
| 42 |
+
# OS
|
| 43 |
+
.DS_Store
|
| 44 |
+
Thumbs.db
|
| 45 |
+
desktop.ini
|
| 46 |
+
|
| 47 |
+
# Logs
|
| 48 |
+
logs/
|
| 49 |
+
*.log
|
| 50 |
+
|
| 51 |
+
# Streamlit
|
| 52 |
+
.streamlit/secrets.toml
|
.streamlit/config.toml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[theme]
|
| 2 |
+
base = "dark"
|
| 3 |
+
backgroundColor = "#0a0e1a"
|
| 4 |
+
secondaryBackgroundColor = "#0f1628"
|
| 5 |
+
primaryColor = "#3b82f6"
|
| 6 |
+
textColor = "#f1f5f9"
|
| 7 |
+
font = "sans serif"
|
| 8 |
+
|
| 9 |
+
[server]
|
| 10 |
+
headless = true
|
| 11 |
+
port = 8501
|
| 12 |
+
enableCORS = false
|
| 13 |
+
enableXsrfProtection = false
|
| 14 |
+
|
| 15 |
+
[browser]
|
| 16 |
+
gatherUsageStats = false
|
| 17 |
+
serverAddress = "localhost"
|
Dockerfile
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use official Python image
|
| 2 |
+
FROM python:3.12-slim
|
| 3 |
+
|
| 4 |
+
# Install system dependencies required for PyTorch and PDFs
|
| 5 |
+
RUN apt-get update && apt-get install -y build-essential
|
| 6 |
+
|
| 7 |
+
# Set working directory
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
|
| 10 |
+
# Copy requirements and install
|
| 11 |
+
COPY requirements.txt .
|
| 12 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 13 |
+
|
| 14 |
+
# Copy your application code
|
| 15 |
+
COPY . .
|
| 16 |
+
|
| 17 |
+
# Expose the port Hugging Face expects (7860)
|
| 18 |
+
EXPOSE 7860
|
| 19 |
+
|
| 20 |
+
# Run FastAPI on port 7860
|
| 21 |
+
CMD ["uvicorn", "app.api.server:app", "--host", "0.0.0.0", "--port", "7860"]
|
| 22 |
+
|
README.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<div align="center">
|
| 2 |
+
|
| 3 |
+
# FinRAG — Production Financial AI Assistant
|
| 4 |
+
|
| 5 |
+

|
| 6 |
+

|
| 7 |
+

|
| 8 |
+

|
| 9 |
+

|
| 10 |
+
|
| 11 |
+
> **An enterprise-grade Retrieval-Augmented Generation (RAG) system built over the official BSE Annual Reports of 17 major Indian companies.**
|
| 12 |
+
> FinRAG leverages advanced hybrid retrieval, cross-encoder reranking, and semantic caching to deliver lightning-fast, 100% grounded financial insights.
|
| 13 |
+
|
| 14 |
+
---
|
| 15 |
+
</div>
|
| 16 |
+
|
| 17 |
+
## 📑 Table of Contents
|
| 18 |
+
- [Project Overview](#-project-overview)
|
| 19 |
+
- [Core Features & UI](#-core-features--ui)
|
| 20 |
+
- [Production RAG Architecture](#-production-rag-architecture)
|
| 21 |
+
- [Tech Stack](#-tech-stack)
|
| 22 |
+
- [Companies Covered](#-companies-covered)
|
| 23 |
+
- [Local Setup & Running](#-local-setup--running)
|
| 24 |
+
|
| 25 |
+
---
|
| 26 |
+
|
| 27 |
+
## 🎯 Project Overview
|
| 28 |
+
|
| 29 |
+
FinRAG solves the hallucination problem in financial AI. It processes massive, complex PDF annual reports and transforms them into an interactive, highly-accurate AI assistant. Whether you need deep-dive qualitative analysis or exact quantitative metrics, every single claim the AI makes is backed by a direct, clickable citation linking directly to the source page of the official financial report.
|
| 30 |
+
|
| 31 |
+
---
|
| 32 |
+
|
| 33 |
+
## 🚀 Core Features & UI
|
| 34 |
+
|
| 35 |
+
### Main Interface
|
| 36 |
+

|
| 37 |
+
|
| 38 |
+
### Interactive Chat (Grounded Q&A)
|
| 39 |
+
Ask natural language questions about any company's financial performance. Features a **Semantic Cache** for blazing-fast 50ms responses on repeated/similar queries, and clickable source badges that instantly open the exact PDF page where the AI found the data.
|
| 40 |
+

|
| 41 |
+
|
| 42 |
+
#### 💡 Natural Language Explanations
|
| 43 |
+

|
| 44 |
+
|
| 45 |
+
### Automated KPI Dashboard
|
| 46 |
+
Automatically extracts and displays key financial metrics (Revenue, Net Profit, EPS, ROE, NPA) into a beautiful, color-coded dashboard. Includes dynamically split Plotly charts (P&L vs Balance Sheet) that accurately represent data magnitude.
|
| 47 |
+

|
| 48 |
+
|
| 49 |
+
### Cross-Document Compare Mode
|
| 50 |
+
A powerhouse analytical workspace capable of running parallel retrievals across different documents. You can instantly compare multiple companies (e.g., "HDFC vs ICICI Gross NPA") or track Year-over-Year trends for a single company (e.g., "TCS FY24 vs FY25 Revenue").
|
| 51 |
+

|
| 52 |
+
|
| 53 |
+
---
|
| 54 |
+
|
| 55 |
+
## 🧠 Production RAG Architecture
|
| 56 |
+
|
| 57 |
+
FinRAG implements state-of-the-art information retrieval techniques to ensure enterprise-grade accuracy.
|
| 58 |
+
|
| 59 |
+
```mermaid
|
| 60 |
+
flowchart TD
|
| 61 |
+
A[BSE PDFs] -->|PyMuPDF + pdfplumber| B(Smart Ingestion & OCR)
|
| 62 |
+
B --> C(Hierarchical Chunking)
|
| 63 |
+
C -->|Parent/Child Nodes| D{Embedding & Indexing}
|
| 64 |
+
D -->|Dense Vectors| E[(Qdrant HNSW)]
|
| 65 |
+
D -->|Sparse Terms| F[(BM25 Index)]
|
| 66 |
+
|
| 67 |
+
G[User Query] --> H(Query Expansion)
|
| 68 |
+
H --> I[Hybrid Retrieval]
|
| 69 |
+
E --> I
|
| 70 |
+
F --> I
|
| 71 |
+
I -->|Rank Fusion RRF| J(BGE Cross-Encoder Reranker)
|
| 72 |
+
J -->|Top-K Chunks| K(Llama 3.3 70B via Groq)
|
| 73 |
+
K --> L[Streaming Response with Citations]
|
| 74 |
+
|
| 75 |
+
G -.->|If >95% Match| M(In-Memory Semantic Cache)
|
| 76 |
+
M -.->|Instant 50ms Hit| L
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
### Advanced Concepts Used:
|
| 80 |
+
- **Hierarchical Chunking:** Splits documents into small chunks for precise searching, but passes the larger surrounding "parent" context to the LLM to prevent data fragmentation.
|
| 81 |
+
- **Hybrid Search (Dense + Sparse):** Combines Semantic vector search (Qdrant) with exact keyword matching (BM25) and fuses the scores using **Reciprocal Rank Fusion (RRF)**.
|
| 82 |
+
- **Cross-Encoder Reranking:** The initial search pulls 30-50 candidates. A powerful `BAAI/bge-reranker-base` model then heavily scores and re-orders them to find the absolute top 3-5 most relevant chunks.
|
| 83 |
+
- **Semantic Caching:** A NumPy-powered in-memory vector cache that short-circuits the entire pipeline if a user asks a semantically similar question, saving expensive API tokens.
|
| 84 |
+
|
| 85 |
+
---
|
| 86 |
+
|
| 87 |
+
## 🛠️ Tech Stack
|
| 88 |
+
|
| 89 |
+
- **Backend / API:** Python 3.12, FastAPI, Uvicorn
|
| 90 |
+
- **Frontend UI:** Vanilla JS, HTML, CSS (Custom Glassmorphism UI)
|
| 91 |
+
- **Vector Database:** Qdrant (Local via Docker)
|
| 92 |
+
- **Embeddings:** `BAAI/bge-large-en-v1.5`
|
| 93 |
+
- **Reranker:** `BAAI/bge-reranker-base`
|
| 94 |
+
- **LLM Inference:** Llama 3.3 70B (Powered by Groq LPUs for ultra-low latency)
|
| 95 |
+
|
| 96 |
+
---
|
| 97 |
+
|
| 98 |
+
## 🏢 Companies Covered
|
| 99 |
+
|
| 100 |
+
Data includes **FY2024–FY2025** BSE Annual Reports for 17 major entities across IT, Banking, FMCG, and Infrastructure:
|
| 101 |
+
|
| 102 |
+
*Airtel, Axis Bank, Bajaj Finance, HCL, HDFC Bank, HUL, ICICI Bank, Infosys, ITC, Kotak Mahindra Bank, Karur Vysya Bank, L&T, Maruti Suzuki, MRF, ONGC, Reliance Industries, SBI, TCS.*
|
| 103 |
+
|
| 104 |
+
---
|
| 105 |
+
|
| 106 |
+
## ⚙️ Local Setup & Running
|
| 107 |
+
|
| 108 |
+
1. **Clone & Install Dependencies**
|
| 109 |
+
```bash
|
| 110 |
+
git clone https://github.com/yourusername/finrag.git
|
| 111 |
+
cd finrag
|
| 112 |
+
pip install -r requirements.txt
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
2. **Set Environment Variables**
|
| 116 |
+
Create a `.env` file in the root directory:
|
| 117 |
+
```env
|
| 118 |
+
GROQ_API_KEY=gsk_your_groq_api_key_here
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
3. **Start the Qdrant Database (Docker required)**
|
| 122 |
+
```bash
|
| 123 |
+
docker run -p 6333:6333 -p 6334:6334 -v $(pwd)/qdrant_storage:/qdrant/storage:z qdrant/qdrant
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
4. **Run the FastAPI Server**
|
| 127 |
+
```bash
|
| 128 |
+
python -X utf8 -m uvicorn app.api.server:app --port 8000 --reload
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
5. **Open the UI**
|
| 132 |
+
Navigate to `http://localhost:8000/` in your browser.
|
app/__init__.py
ADDED
|
File without changes
|
app/api/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""app/api/__init__.py"""
|
app/api/server.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app/api/server.py
|
| 3 |
+
==================
|
| 4 |
+
FastAPI backend — serves the RAG pipeline via REST + SSE streaming.
|
| 5 |
+
Run with: uvicorn app.api.server:app --port 8000 --reload
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import sys, os, json, asyncio
|
| 9 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 10 |
+
os.environ["PYTHONUTF8"] = "1"
|
| 11 |
+
|
| 12 |
+
from fastapi import FastAPI, HTTPException
|
| 13 |
+
from fastapi.staticfiles import StaticFiles
|
| 14 |
+
from fastapi.responses import FileResponse, StreamingResponse, JSONResponse
|
| 15 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 16 |
+
from pydantic import BaseModel
|
| 17 |
+
from typing import Optional
|
| 18 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 19 |
+
|
| 20 |
+
from config.settings import settings
|
| 21 |
+
|
| 22 |
+
# ── lazy-loaded singletons ──────────────────────────────────────────
|
| 23 |
+
_retriever = None
|
| 24 |
+
_reranker = None
|
| 25 |
+
_groq = None
|
| 26 |
+
_extractor = None
|
| 27 |
+
_comparator = None
|
| 28 |
+
_embedder = None
|
| 29 |
+
_semantic_cache = None
|
| 30 |
+
_executor = ThreadPoolExecutor(max_workers=4)
|
| 31 |
+
|
| 32 |
+
def get_embedder():
|
| 33 |
+
global _embedder
|
| 34 |
+
if _embedder is None:
|
| 35 |
+
from src.embeddings.embedder import Embedder
|
| 36 |
+
_embedder = Embedder()
|
| 37 |
+
return _embedder
|
| 38 |
+
|
| 39 |
+
def get_retriever():
|
| 40 |
+
global _retriever
|
| 41 |
+
if _retriever is None:
|
| 42 |
+
from src.vectorstore.qdrant_store import QdrantStore
|
| 43 |
+
from src.vectorstore.bm25_index import BM25Index
|
| 44 |
+
from src.retrieval.hybrid_retriever import HybridRetriever
|
| 45 |
+
_retriever = HybridRetriever(QdrantStore(), BM25Index(), get_embedder())
|
| 46 |
+
return _retriever
|
| 47 |
+
|
| 48 |
+
def get_reranker():
|
| 49 |
+
global _reranker
|
| 50 |
+
if _reranker is None:
|
| 51 |
+
from src.retrieval.reranker import Reranker
|
| 52 |
+
_reranker = Reranker()
|
| 53 |
+
return _reranker
|
| 54 |
+
|
| 55 |
+
def get_groq():
|
| 56 |
+
global _groq
|
| 57 |
+
if _groq is None:
|
| 58 |
+
from src.generation.groq_client import GroqClient
|
| 59 |
+
_groq = GroqClient()
|
| 60 |
+
return _groq
|
| 61 |
+
|
| 62 |
+
def get_extractor():
|
| 63 |
+
global _extractor
|
| 64 |
+
if _extractor is None:
|
| 65 |
+
from src.metrics.metric_extractor import MetricExtractor
|
| 66 |
+
_extractor = MetricExtractor(groq_client=get_groq())
|
| 67 |
+
return _extractor
|
| 68 |
+
|
| 69 |
+
def get_semantic_cache():
|
| 70 |
+
global _semantic_cache
|
| 71 |
+
if _semantic_cache is None:
|
| 72 |
+
from src.generation.semantic_cache import SemanticCache
|
| 73 |
+
_semantic_cache = SemanticCache(max_size=500, threshold=0.95)
|
| 74 |
+
return _semantic_cache
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# ── app ─────────────────────────────────────────────────────────────
|
| 78 |
+
app = FastAPI(title="FinRAG API", version="1.0.0")
|
| 79 |
+
|
| 80 |
+
app.add_middleware(
|
| 81 |
+
CORSMiddleware,
|
| 82 |
+
allow_origins=["*"],
|
| 83 |
+
allow_methods=["*"],
|
| 84 |
+
allow_headers=["*"],
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# Static files (HTML/CSS/JS)
|
| 88 |
+
STATIC_DIR = os.path.join(os.path.dirname(__file__), "..", "static")
|
| 89 |
+
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
| 90 |
+
|
| 91 |
+
# Mount raw_pdfs directory for serving PDFs
|
| 92 |
+
PDF_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "raw_pdfs"))
|
| 93 |
+
if os.path.exists(PDF_DIR):
|
| 94 |
+
app.mount("/raw_pdfs", StaticFiles(directory=PDF_DIR), name="raw_pdfs")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# ── request models ──────────────────────────────────────────────────
|
| 98 |
+
class ChatRequest(BaseModel):
|
| 99 |
+
query: str
|
| 100 |
+
company: str
|
| 101 |
+
fiscal_year: Optional[str] = "FY2025"
|
| 102 |
+
conversation_id: Optional[str] = None
|
| 103 |
+
|
| 104 |
+
class CompareRequest(BaseModel):
|
| 105 |
+
query: str
|
| 106 |
+
companies: list[str]
|
| 107 |
+
fiscal_year: Optional[str] = "FY2025"
|
| 108 |
+
conversation_id: Optional[str] = None
|
| 109 |
+
|
| 110 |
+
class DashboardRequest(BaseModel):
|
| 111 |
+
company: str
|
| 112 |
+
fiscal_year: Optional[str] = "FY2025"
|
| 113 |
+
|
| 114 |
+
class ConversationCreate(BaseModel):
|
| 115 |
+
mode: str = "chat"
|
| 116 |
+
|
| 117 |
+
# ── routes ──────────────────────────────────────────────────────────
|
| 118 |
+
|
| 119 |
+
@app.get("/")
|
| 120 |
+
async def root():
|
| 121 |
+
return FileResponse(os.path.join(STATIC_DIR, "index.html"))
|
| 122 |
+
|
| 123 |
+
@app.get("/api/companies")
|
| 124 |
+
async def companies():
|
| 125 |
+
return {"companies": list(settings.company_ticker_map.keys()),
|
| 126 |
+
"tickers": settings.company_ticker_map}
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# ── Small-talk / greeting detection ─────────────────────────────────
|
| 130 |
+
_SMALL_TALK = {
|
| 131 |
+
'hi','hello','hey','hii','heya','howdy','sup','yo',
|
| 132 |
+
'bye','goodbye','see you','take care','cya',
|
| 133 |
+
'thanks','thank you','thank you so much','thx','ty',
|
| 134 |
+
'ok','okay','got it','understood','sure','alright',
|
| 135 |
+
'how are you','how r u','whats up',"what's up",
|
| 136 |
+
'who are you','what are you','what can you do','help me','help',
|
| 137 |
+
'good morning','good afternoon','good evening','good night',
|
| 138 |
+
'nice','cool','great','awesome','wow','amazing',
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
SMALL_TALK_SYSTEM = (
|
| 142 |
+
"You are FinRAG, an AI assistant specialised in Indian company financials. "
|
| 143 |
+
"Respond briefly and warmly to greetings or small talk. "
|
| 144 |
+
"Let the user know you can answer questions about major BSE-listed companies "
|
| 145 |
+
"(TCS, HDFC Bank, Infosys, Reliance, SBI etc.) using their official annual reports. "
|
| 146 |
+
"Keep it to 1-3 sentences."
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
def is_small_talk(query: str) -> bool:
|
| 150 |
+
q = query.lower().strip().rstrip('?!.,')
|
| 151 |
+
if q in _SMALL_TALK:
|
| 152 |
+
return True
|
| 153 |
+
words = q.split()
|
| 154 |
+
return len(words) <= 4 and any(w in _SMALL_TALK for w in words)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# ── Chat (SSE streaming) ─────────────────────────────────────────────
|
| 158 |
+
@app.post("/api/chat")
|
| 159 |
+
async def chat(req: ChatRequest):
|
| 160 |
+
from src.generation.prompts import build_qa_prompt
|
| 161 |
+
|
| 162 |
+
# 1. Check Semantic Cache first
|
| 163 |
+
semantic_cache = get_semantic_cache()
|
| 164 |
+
embedder = get_embedder()
|
| 165 |
+
|
| 166 |
+
# Run embedding in thread pool to not block async loop
|
| 167 |
+
loop = asyncio.get_event_loop()
|
| 168 |
+
query_emb = await loop.run_in_executor(_executor, embedder.embed_query, req.query)
|
| 169 |
+
|
| 170 |
+
fy = None if req.fiscal_year == "All" else req.fiscal_year
|
| 171 |
+
cached_result = semantic_cache.find_match(query_emb, req.company, fy)
|
| 172 |
+
|
| 173 |
+
if cached_result:
|
| 174 |
+
cached_text, cached_sources = cached_result
|
| 175 |
+
async def cached_stream():
|
| 176 |
+
yield f"data: {json.dumps({'type': 'chunk', 'text': cached_text})}\n\n"
|
| 177 |
+
yield f"data: {json.dumps({'type': 'sources', 'sources': cached_sources})}\n\n"
|
| 178 |
+
yield f"data: {json.dumps({'type': 'done'})}\n\n"
|
| 179 |
+
return StreamingResponse(cached_stream(), media_type="text/event-stream",
|
| 180 |
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
| 181 |
+
|
| 182 |
+
def _run():
|
| 183 |
+
if is_small_talk(req.query):
|
| 184 |
+
groq = get_groq()
|
| 185 |
+
return groq.generate_stream(SMALL_TALK_SYSTEM, req.query), []
|
| 186 |
+
|
| 187 |
+
retriever = get_retriever()
|
| 188 |
+
reranker = get_reranker()
|
| 189 |
+
groq = get_groq()
|
| 190 |
+
fy = None if req.fiscal_year == "All" else req.fiscal_year
|
| 191 |
+
|
| 192 |
+
candidates = retriever.retrieve(
|
| 193 |
+
query=req.query, top_k=50,
|
| 194 |
+
company_filter=req.company,
|
| 195 |
+
fiscal_year_filter=fy,
|
| 196 |
+
expand_query=True, promote_to_parent=True,
|
| 197 |
+
)
|
| 198 |
+
if not candidates:
|
| 199 |
+
return None, []
|
| 200 |
+
|
| 201 |
+
reranked = reranker.rerank(query=req.query, candidates=candidates, top_n=5)
|
| 202 |
+
system_p, user_p = build_qa_prompt(
|
| 203 |
+
query=req.query, results=reranked,
|
| 204 |
+
company_context=f"{req.company} ({settings.company_ticker_map.get(req.company, '')})",
|
| 205 |
+
)
|
| 206 |
+
sources = [
|
| 207 |
+
{"company": c.company, "fiscal_year": c.fiscal_year,
|
| 208 |
+
"page": c.page_number, "is_table": c.content_type == "table",
|
| 209 |
+
"section": c.section or "Financial Data", "file": c.source_file}
|
| 210 |
+
for c in reranked
|
| 211 |
+
]
|
| 212 |
+
return groq.generate_stream(system_p, user_p), sources
|
| 213 |
+
|
| 214 |
+
loop = asyncio.get_event_loop()
|
| 215 |
+
stream_gen, sources = await loop.run_in_executor(_executor, _run)
|
| 216 |
+
|
| 217 |
+
async def event_stream():
|
| 218 |
+
if stream_gen is None:
|
| 219 |
+
yield f"data: {json.dumps({'type': 'error', 'text': 'No relevant documents found.'})}\n\n"
|
| 220 |
+
return
|
| 221 |
+
|
| 222 |
+
# Stream text chunks
|
| 223 |
+
full_text = ""
|
| 224 |
+
def _collect():
|
| 225 |
+
return list(stream_gen)
|
| 226 |
+
|
| 227 |
+
chunks = await loop.run_in_executor(_executor, _collect)
|
| 228 |
+
for chunk in chunks:
|
| 229 |
+
full_text += chunk
|
| 230 |
+
yield f"data: {json.dumps({'type': 'chunk', 'text': chunk})}\n\n"
|
| 231 |
+
|
| 232 |
+
# Cache the result for future semantically similar queries
|
| 233 |
+
semantic_cache.add(query_emb, req.company, fy, full_text, sources)
|
| 234 |
+
|
| 235 |
+
# Send sources after text
|
| 236 |
+
yield f"data: {json.dumps({'type': 'sources', 'sources': sources})}\n\n"
|
| 237 |
+
yield f"data: {json.dumps({'type': 'done'})}\n\n"
|
| 238 |
+
|
| 239 |
+
return StreamingResponse(event_stream(), media_type="text/event-stream",
|
| 240 |
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
# ── Dashboard (JSON) ────────────────────────────────────────────────
|
| 244 |
+
@app.post("/api/dashboard")
|
| 245 |
+
async def dashboard(req: DashboardRequest):
|
| 246 |
+
def _run():
|
| 247 |
+
retriever = get_retriever()
|
| 248 |
+
reranker = get_reranker()
|
| 249 |
+
extractor = get_extractor()
|
| 250 |
+
fy = None if req.fiscal_year == "All" else req.fiscal_year
|
| 251 |
+
|
| 252 |
+
all_c = []
|
| 253 |
+
for q in ["revenue net profit financial performance", "balance sheet assets equity"]:
|
| 254 |
+
all_c.extend(retriever.retrieve(query=q, top_k=20,
|
| 255 |
+
company_filter=req.company, fiscal_year_filter=fy))
|
| 256 |
+
seen = set(); unique = []
|
| 257 |
+
for c in all_c:
|
| 258 |
+
if c.chunk_id not in seen:
|
| 259 |
+
seen.add(c.chunk_id); unique.append(c)
|
| 260 |
+
|
| 261 |
+
reranked = reranker.rerank(
|
| 262 |
+
query="financial metrics revenue profit assets equity EPS",
|
| 263 |
+
candidates=unique, top_n=4,
|
| 264 |
+
)
|
| 265 |
+
return extractor.extract(req.company, reranked)
|
| 266 |
+
|
| 267 |
+
loop = asyncio.get_event_loop()
|
| 268 |
+
data = await loop.run_in_executor(_executor, _run)
|
| 269 |
+
return JSONResponse(data)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# ── Compare (SSE streaming) ─────────────────────────────────────────
|
| 273 |
+
@app.post("/api/compare")
|
| 274 |
+
async def compare(req: CompareRequest):
|
| 275 |
+
def _run():
|
| 276 |
+
retriever = get_retriever()
|
| 277 |
+
reranker = get_reranker()
|
| 278 |
+
groq = get_groq()
|
| 279 |
+
from src.generation.prompts import build_comparison_prompt
|
| 280 |
+
import re
|
| 281 |
+
|
| 282 |
+
# Detect cross-year comparisons. If multiple years are mentioned, search across all years
|
| 283 |
+
years_mentioned = set(re.findall(r'202\d', req.query))
|
| 284 |
+
if len(years_mentioned) > 1:
|
| 285 |
+
fy = None
|
| 286 |
+
else:
|
| 287 |
+
fy = None if req.fiscal_year == "All" else req.fiscal_year
|
| 288 |
+
|
| 289 |
+
company_results = {}
|
| 290 |
+
top_n = max(1, 6 // len(req.companies)) if req.companies else 3
|
| 291 |
+
for company in req.companies:
|
| 292 |
+
cands = retriever.retrieve(
|
| 293 |
+
query=req.query, top_k=30,
|
| 294 |
+
company_filter=company, fiscal_year_filter=fy,
|
| 295 |
+
)
|
| 296 |
+
if cands:
|
| 297 |
+
company_results[company] = reranker.rerank(
|
| 298 |
+
query=req.query, candidates=cands, top_n=top_n,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
if not company_results:
|
| 302 |
+
return None, {}
|
| 303 |
+
|
| 304 |
+
system_p, user_p = build_comparison_prompt(
|
| 305 |
+
query=req.query,
|
| 306 |
+
company_results=company_results,
|
| 307 |
+
)
|
| 308 |
+
return groq.generate_stream(system_p, user_p), company_results
|
| 309 |
+
|
| 310 |
+
loop = asyncio.get_event_loop()
|
| 311 |
+
stream_gen, company_results = await loop.run_in_executor(_executor, _run)
|
| 312 |
+
|
| 313 |
+
async def event_stream():
|
| 314 |
+
if stream_gen is None:
|
| 315 |
+
yield f"data: {json.dumps({'type': 'error', 'text': 'No data found.'})}\n\n"
|
| 316 |
+
return
|
| 317 |
+
|
| 318 |
+
def _collect():
|
| 319 |
+
return list(stream_gen)
|
| 320 |
+
|
| 321 |
+
chunks = await loop.run_in_executor(_executor, _collect)
|
| 322 |
+
for chunk in chunks:
|
| 323 |
+
yield f"data: {json.dumps({'type': 'chunk', 'text': chunk})}\n\n"
|
| 324 |
+
|
| 325 |
+
sources = []
|
| 326 |
+
for company, results in company_results.items():
|
| 327 |
+
for r in results:
|
| 328 |
+
sources.append({"company": company, "page": r.page_number,
|
| 329 |
+
"is_table": False, "section": r.section or ""})
|
| 330 |
+
yield f"data: {json.dumps({'type': 'sources', 'sources': sources})}\n\n"
|
| 331 |
+
yield f"data: {json.dumps({'type': 'done'})}\n\n"
|
| 332 |
+
|
| 333 |
+
return StreamingResponse(event_stream(), media_type="text/event-stream",
|
| 334 |
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
# ── Conversation history ─────────────────────────────────────────────
|
| 338 |
+
@app.get("/api/conversations")
|
| 339 |
+
async def list_convs():
|
| 340 |
+
from app.db.chat_store import list_conversations, group_conversations_by_date
|
| 341 |
+
convs = list_conversations(40)
|
| 342 |
+
grouped = group_conversations_by_date(convs)
|
| 343 |
+
return {"grouped": grouped}
|
| 344 |
+
|
| 345 |
+
@app.post("/api/conversations")
|
| 346 |
+
async def create_conv(body: ConversationCreate):
|
| 347 |
+
from app.db.chat_store import new_conversation
|
| 348 |
+
cid = new_conversation(body.mode)
|
| 349 |
+
return {"id": cid}
|
| 350 |
+
|
| 351 |
+
@app.get("/api/conversations/{cid}/messages")
|
| 352 |
+
async def get_conv_messages(cid: str):
|
| 353 |
+
from app.db.chat_store import get_messages
|
| 354 |
+
msgs = get_messages(cid)
|
| 355 |
+
return {"messages": msgs}
|
| 356 |
+
|
| 357 |
+
@app.delete("/api/conversations/{cid}")
|
| 358 |
+
async def delete_conv(cid: str):
|
| 359 |
+
from app.db.chat_store import delete_conversation
|
| 360 |
+
delete_conversation(cid)
|
| 361 |
+
return {"ok": True}
|
| 362 |
+
|
| 363 |
+
@app.post("/api/conversations/{cid}/messages")
|
| 364 |
+
async def save_msg(cid: str, body: dict):
|
| 365 |
+
from app.db.chat_store import add_message, update_conversation_title
|
| 366 |
+
add_message(cid, body["role"], body["content"], body.get("metadata"))
|
| 367 |
+
if body["role"] == "user":
|
| 368 |
+
update_conversation_title(cid, body["content"])
|
| 369 |
+
return {"ok": True}
|
app/db/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app/db/__init__.py
|
| 3 |
+
"""
|
app/db/chat_store.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app/db/chat_store.py
|
| 3 |
+
=====================
|
| 4 |
+
SQLite-backed chat history store.
|
| 5 |
+
Zero dependencies beyond Python stdlib — single .db file on disk.
|
| 6 |
+
|
| 7 |
+
Schema:
|
| 8 |
+
conversations — one row per chat session (id, title, created_at, mode)
|
| 9 |
+
messages — one row per message (id, conversation_id, role, content, metadata_json)
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import sqlite3
|
| 16 |
+
import uuid
|
| 17 |
+
from datetime import datetime
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
DB_PATH = Path("data/chat_history.db")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _conn() -> sqlite3.Connection:
|
| 25 |
+
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 26 |
+
conn = sqlite3.connect(str(DB_PATH), check_same_thread=False)
|
| 27 |
+
conn.row_factory = sqlite3.Row
|
| 28 |
+
return conn
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def init_db() -> None:
|
| 32 |
+
"""Create tables if they don't exist."""
|
| 33 |
+
with _conn() as conn:
|
| 34 |
+
conn.executescript("""
|
| 35 |
+
CREATE TABLE IF NOT EXISTS conversations (
|
| 36 |
+
id TEXT PRIMARY KEY,
|
| 37 |
+
title TEXT NOT NULL DEFAULT 'New Chat',
|
| 38 |
+
mode TEXT NOT NULL DEFAULT 'chat',
|
| 39 |
+
created_at TEXT NOT NULL,
|
| 40 |
+
updated_at TEXT NOT NULL
|
| 41 |
+
);
|
| 42 |
+
|
| 43 |
+
CREATE TABLE IF NOT EXISTS messages (
|
| 44 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 45 |
+
conversation_id TEXT NOT NULL,
|
| 46 |
+
role TEXT NOT NULL,
|
| 47 |
+
content TEXT NOT NULL,
|
| 48 |
+
metadata TEXT,
|
| 49 |
+
created_at TEXT NOT NULL,
|
| 50 |
+
FOREIGN KEY (conversation_id) REFERENCES conversations(id)
|
| 51 |
+
);
|
| 52 |
+
""")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ------------------------------------------------------------------ #
|
| 56 |
+
# Conversations
|
| 57 |
+
# ------------------------------------------------------------------ #
|
| 58 |
+
|
| 59 |
+
def new_conversation(mode: str = "chat") -> str:
|
| 60 |
+
"""Create a new conversation, return its ID."""
|
| 61 |
+
cid = str(uuid.uuid4())
|
| 62 |
+
now = datetime.utcnow().isoformat()
|
| 63 |
+
with _conn() as conn:
|
| 64 |
+
conn.execute(
|
| 65 |
+
"INSERT INTO conversations (id, title, mode, created_at, updated_at) VALUES (?,?,?,?,?)",
|
| 66 |
+
(cid, "New Chat", mode, now, now),
|
| 67 |
+
)
|
| 68 |
+
return cid
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def update_conversation_title(cid: str, title: str) -> None:
|
| 72 |
+
"""Set conversation title from first user message (truncated)."""
|
| 73 |
+
short = title[:60] + "…" if len(title) > 60 else title
|
| 74 |
+
now = datetime.utcnow().isoformat()
|
| 75 |
+
with _conn() as conn:
|
| 76 |
+
conn.execute(
|
| 77 |
+
"UPDATE conversations SET title=?, updated_at=? WHERE id=?",
|
| 78 |
+
(short, now, cid),
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def touch_conversation(cid: str) -> None:
|
| 83 |
+
now = datetime.utcnow().isoformat()
|
| 84 |
+
with _conn() as conn:
|
| 85 |
+
conn.execute("UPDATE conversations SET updated_at=? WHERE id=?", (now, cid))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def delete_conversation(cid: str) -> None:
|
| 89 |
+
with _conn() as conn:
|
| 90 |
+
conn.execute("DELETE FROM messages WHERE conversation_id=?", (cid,))
|
| 91 |
+
conn.execute("DELETE FROM conversations WHERE id=?", (cid,))
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def list_conversations(limit: int = 40) -> list[dict]:
|
| 95 |
+
"""Return conversations newest-first."""
|
| 96 |
+
with _conn() as conn:
|
| 97 |
+
rows = conn.execute(
|
| 98 |
+
"SELECT id, title, mode, created_at, updated_at FROM conversations ORDER BY updated_at DESC LIMIT ?",
|
| 99 |
+
(limit,),
|
| 100 |
+
).fetchall()
|
| 101 |
+
return [dict(r) for r in rows]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# ------------------------------------------------------------------ #
|
| 105 |
+
# Messages
|
| 106 |
+
# ------------------------------------------------------------------ #
|
| 107 |
+
|
| 108 |
+
def add_message(
|
| 109 |
+
cid: str,
|
| 110 |
+
role: str,
|
| 111 |
+
content: str,
|
| 112 |
+
metadata: Optional[dict] = None,
|
| 113 |
+
) -> None:
|
| 114 |
+
"""Append a message to a conversation."""
|
| 115 |
+
now = datetime.utcnow().isoformat()
|
| 116 |
+
meta_str = json.dumps(metadata) if metadata else None
|
| 117 |
+
with _conn() as conn:
|
| 118 |
+
conn.execute(
|
| 119 |
+
"INSERT INTO messages (conversation_id, role, content, metadata, created_at) VALUES (?,?,?,?,?)",
|
| 120 |
+
(cid, role, content, meta_str, now),
|
| 121 |
+
)
|
| 122 |
+
touch_conversation(cid)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def get_messages(cid: str) -> list[dict]:
|
| 126 |
+
"""Return all messages for a conversation, oldest-first."""
|
| 127 |
+
with _conn() as conn:
|
| 128 |
+
rows = conn.execute(
|
| 129 |
+
"SELECT role, content, metadata, created_at FROM messages WHERE conversation_id=? ORDER BY id ASC",
|
| 130 |
+
(cid,),
|
| 131 |
+
).fetchall()
|
| 132 |
+
result = []
|
| 133 |
+
for r in rows:
|
| 134 |
+
msg = dict(r)
|
| 135 |
+
msg["metadata"] = json.loads(msg["metadata"]) if msg["metadata"] else {}
|
| 136 |
+
result.append(msg)
|
| 137 |
+
return result
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def group_conversations_by_date(conversations: list[dict]) -> dict[str, list[dict]]:
|
| 141 |
+
"""Group conversation list into Today / Yesterday / Earlier."""
|
| 142 |
+
from datetime import date, timedelta
|
| 143 |
+
today = date.today()
|
| 144 |
+
yesterday = today - timedelta(days=1)
|
| 145 |
+
week_ago = today - timedelta(days=7)
|
| 146 |
+
|
| 147 |
+
groups: dict[str, list] = {"Today": [], "Yesterday": [], "This Week": [], "Earlier": []}
|
| 148 |
+
for c in conversations:
|
| 149 |
+
try:
|
| 150 |
+
d = datetime.fromisoformat(c["updated_at"]).date()
|
| 151 |
+
except Exception:
|
| 152 |
+
d = today
|
| 153 |
+
|
| 154 |
+
if d == today:
|
| 155 |
+
groups["Today"].append(c)
|
| 156 |
+
elif d == yesterday:
|
| 157 |
+
groups["Yesterday"].append(c)
|
| 158 |
+
elif d >= week_ago:
|
| 159 |
+
groups["This Week"].append(c)
|
| 160 |
+
else:
|
| 161 |
+
groups["Earlier"].append(c)
|
| 162 |
+
|
| 163 |
+
return {k: v for k, v in groups.items() if v} # drop empty groups
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# Initialise on import
|
| 167 |
+
init_db()
|
app/main.py
ADDED
|
@@ -0,0 +1,862 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app/main.py — FinRAG | Production Financial Intelligence UI
|
| 3 |
+
================================================================
|
| 4 |
+
Single-page Streamlit app. No sub-pages.
|
| 5 |
+
|
| 6 |
+
Layout:
|
| 7 |
+
Sidebar : logo · new chat · conversation history · quick actions
|
| 8 |
+
Main : mode pills · chat thread · company context bar · chat input
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import sys, os, re, json
|
| 12 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 13 |
+
os.environ["PYTHONUTF8"] = "1"
|
| 14 |
+
|
| 15 |
+
from config.settings import settings
|
| 16 |
+
|
| 17 |
+
import streamlit as st
|
| 18 |
+
import plotly.graph_objects as go
|
| 19 |
+
|
| 20 |
+
# ── page config (MUST be first Streamlit call) ──────────────────────
|
| 21 |
+
st.set_page_config(
|
| 22 |
+
page_title="FinRAG",
|
| 23 |
+
page_icon="📈",
|
| 24 |
+
layout="wide",
|
| 25 |
+
initial_sidebar_state="expanded",
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# ── imports ──────────────────────────────────────────────────────────
|
| 29 |
+
from app.rag_engine import (
|
| 30 |
+
load_embedder, load_retriever, load_reranker,
|
| 31 |
+
load_groq, load_comparator, load_metric_extractor,
|
| 32 |
+
)
|
| 33 |
+
from app.db.chat_store import (
|
| 34 |
+
new_conversation, list_conversations, get_messages,
|
| 35 |
+
add_message, update_conversation_title,
|
| 36 |
+
delete_conversation, group_conversations_by_date,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# ════════════════════════════════════════════════════════════════════
|
| 40 |
+
# CSS
|
| 41 |
+
# ════════════════════════════════════════════════════════════════════
|
| 42 |
+
st.markdown("""
|
| 43 |
+
<style>
|
| 44 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
|
| 45 |
+
|
| 46 |
+
/* ── Reset & base ─────────────────────────────────────────────── */
|
| 47 |
+
*, *::before, *::after { box-sizing: border-box; }
|
| 48 |
+
html, body, .stApp {
|
| 49 |
+
font-family: 'Inter', -apple-system, sans-serif;
|
| 50 |
+
background: #0d0f17;
|
| 51 |
+
color: #e2e8f0;
|
| 52 |
+
}
|
| 53 |
+
#MainMenu, footer, header { visibility: hidden; }
|
| 54 |
+
.block-container { padding: 0 !important; max-width: 100% !important; }
|
| 55 |
+
|
| 56 |
+
/* ── Sidebar ──────────────────────────────────────────────────── */
|
| 57 |
+
[data-testid="stSidebar"] {
|
| 58 |
+
background: #0a0c13 !important;
|
| 59 |
+
border-right: 1px solid rgba(255,255,255,0.06) !important;
|
| 60 |
+
padding: 0 !important;
|
| 61 |
+
}
|
| 62 |
+
[data-testid="stSidebar"] > div:first-child { padding: 0 !important; }
|
| 63 |
+
|
| 64 |
+
/* ── Sidebar collapse button ─────────────────────────────────── */
|
| 65 |
+
[data-testid="collapsedControl"] {
|
| 66 |
+
color: #64748b !important;
|
| 67 |
+
background: #0a0c13 !important;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
/* ── Remove default padding from main content ────────────────── */
|
| 71 |
+
[data-testid="stMainBlockContainer"] {
|
| 72 |
+
padding: 0 !important;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
/* ── Chat messages ───────────────────────────────────────────── */
|
| 76 |
+
[data-testid="stChatMessage"] {
|
| 77 |
+
background: transparent !important;
|
| 78 |
+
border: none !important;
|
| 79 |
+
padding: 0.6rem 0 !important;
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
/* ── User bubble ─────────────────────────────────────────────── */
|
| 83 |
+
[data-testid="stChatMessage"][data-testid*="user"] {
|
| 84 |
+
flex-direction: row-reverse !important;
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
/* ── Chat input ──────────────────────────────────────────────── */
|
| 88 |
+
[data-testid="stChatInput"] {
|
| 89 |
+
background: #161929 !important;
|
| 90 |
+
border: 1px solid rgba(255,255,255,0.1) !important;
|
| 91 |
+
border-radius: 14px !important;
|
| 92 |
+
}
|
| 93 |
+
[data-testid="stChatInput"] textarea {
|
| 94 |
+
color: #e2e8f0 !important;
|
| 95 |
+
font-family: 'Inter', sans-serif !important;
|
| 96 |
+
font-size: 0.95rem !important;
|
| 97 |
+
}
|
| 98 |
+
[data-testid="stChatInput"] button {
|
| 99 |
+
background: linear-gradient(135deg, #3b82f6, #06b6d4) !important;
|
| 100 |
+
border-radius: 8px !important;
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
/* ── Scrollbar ───────────────────────────────────────────────── */
|
| 104 |
+
::-webkit-scrollbar { width: 5px; }
|
| 105 |
+
::-webkit-scrollbar-track { background: transparent; }
|
| 106 |
+
::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 3px; }
|
| 107 |
+
|
| 108 |
+
/* ── Selectbox / radio ───────────────────────────────────────── */
|
| 109 |
+
.stSelectbox > div > div,
|
| 110 |
+
.stMultiSelect > div > div {
|
| 111 |
+
background: #161929 !important;
|
| 112 |
+
border: 1px solid rgba(255,255,255,0.08) !important;
|
| 113 |
+
border-radius: 8px !important;
|
| 114 |
+
color: #e2e8f0 !important;
|
| 115 |
+
}
|
| 116 |
+
.stRadio > div { gap: 0.4rem; }
|
| 117 |
+
.stRadio label { color: #94a3b8 !important; }
|
| 118 |
+
|
| 119 |
+
/* ── Buttons ─────────────────────────────────────────────────── */
|
| 120 |
+
.stButton > button {
|
| 121 |
+
border-radius: 8px !important;
|
| 122 |
+
font-weight: 500 !important;
|
| 123 |
+
font-size: 0.85rem !important;
|
| 124 |
+
transition: all 0.15s !important;
|
| 125 |
+
border: none !important;
|
| 126 |
+
}
|
| 127 |
+
.stButton > button:hover { transform: translateY(-1px) !important; }
|
| 128 |
+
|
| 129 |
+
/* ── Expander ────────────────────────────────────────────────── */
|
| 130 |
+
.streamlit-expanderHeader {
|
| 131 |
+
background: rgba(255,255,255,0.03) !important;
|
| 132 |
+
border: 1px solid rgba(255,255,255,0.07) !important;
|
| 133 |
+
border-radius: 8px !important;
|
| 134 |
+
color: #64748b !important;
|
| 135 |
+
font-size: 0.8rem !important;
|
| 136 |
+
}
|
| 137 |
+
.streamlit-expanderContent {
|
| 138 |
+
background: rgba(255,255,255,0.02) !important;
|
| 139 |
+
border: 1px solid rgba(255,255,255,0.05) !important;
|
| 140 |
+
border-top: none !important;
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
/* ── Divider ─────────────────────────────────────────────────── */
|
| 144 |
+
hr { border-color: rgba(255,255,255,0.07) !important; }
|
| 145 |
+
|
| 146 |
+
/* ── Plotly charts ───────────────────────────────────────────── */
|
| 147 |
+
.js-plotly-plot { border-radius: 12px; overflow: hidden; }
|
| 148 |
+
|
| 149 |
+
/* ── Custom components ───────────────────────────────────────── */
|
| 150 |
+
.fin-brand {
|
| 151 |
+
padding: 1.2rem 1rem 0.8rem 1rem;
|
| 152 |
+
display: flex; align-items: center; gap: 0.6rem;
|
| 153 |
+
}
|
| 154 |
+
.fin-brand-icon { font-size: 1.4rem; }
|
| 155 |
+
.fin-brand-name {
|
| 156 |
+
font-size: 1.1rem; font-weight: 700; letter-spacing: -0.02em;
|
| 157 |
+
background: linear-gradient(135deg, #3b82f6, #06b6d4);
|
| 158 |
+
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
|
| 159 |
+
}
|
| 160 |
+
.fin-brand-sub {
|
| 161 |
+
font-size: 0.65rem; color: #475569;
|
| 162 |
+
text-transform: uppercase; letter-spacing: 0.08em;
|
| 163 |
+
margin-top: -0.15rem;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
.history-group-label {
|
| 167 |
+
font-size: 0.68rem; font-weight: 600; color: #475569;
|
| 168 |
+
text-transform: uppercase; letter-spacing: 0.08em;
|
| 169 |
+
padding: 0.6rem 0.8rem 0.3rem 0.8rem;
|
| 170 |
+
}
|
| 171 |
+
.history-item {
|
| 172 |
+
padding: 0.45rem 0.8rem; border-radius: 7px; cursor: pointer;
|
| 173 |
+
font-size: 0.82rem; color: #94a3b8; white-space: nowrap;
|
| 174 |
+
overflow: hidden; text-overflow: ellipsis;
|
| 175 |
+
transition: background 0.1s, color 0.1s;
|
| 176 |
+
}
|
| 177 |
+
.history-item:hover { background: rgba(255,255,255,0.05); color: #e2e8f0; }
|
| 178 |
+
.history-item.active { background: rgba(59,130,246,0.12); color: #93c5fd; }
|
| 179 |
+
|
| 180 |
+
.mode-bar {
|
| 181 |
+
display: flex; gap: 0.3rem; padding: 0.8rem 1.2rem 0;
|
| 182 |
+
}
|
| 183 |
+
.mode-pill {
|
| 184 |
+
padding: 0.35rem 1rem; border-radius: 20px; font-size: 0.8rem;
|
| 185 |
+
font-weight: 500; cursor: pointer; border: 1px solid rgba(255,255,255,0.08);
|
| 186 |
+
color: #64748b; background: transparent; transition: all 0.15s;
|
| 187 |
+
}
|
| 188 |
+
.mode-pill.active {
|
| 189 |
+
background: linear-gradient(135deg, rgba(59,130,246,0.2), rgba(6,182,212,0.1));
|
| 190 |
+
border-color: rgba(59,130,246,0.4); color: #93c5fd;
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
.context-bar {
|
| 194 |
+
display: flex; align-items: center; gap: 0.5rem;
|
| 195 |
+
padding: 0.4rem 1.2rem; flex-wrap: wrap;
|
| 196 |
+
}
|
| 197 |
+
.ctx-tag {
|
| 198 |
+
display: inline-flex; align-items: center; gap: 0.3rem;
|
| 199 |
+
background: rgba(59,130,246,0.12); border: 1px solid rgba(59,130,246,0.25);
|
| 200 |
+
border-radius: 20px; padding: 0.2rem 0.65rem; font-size: 0.75rem;
|
| 201 |
+
color: #93c5fd; font-family: 'JetBrains Mono', monospace;
|
| 202 |
+
}
|
| 203 |
+
.ctx-hint { font-size: 0.72rem; color: #475569; }
|
| 204 |
+
|
| 205 |
+
.kpi-grid {
|
| 206 |
+
display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.7rem;
|
| 207 |
+
margin: 0.8rem 0;
|
| 208 |
+
}
|
| 209 |
+
.kpi-card {
|
| 210 |
+
background: rgba(255,255,255,0.04);
|
| 211 |
+
border: 1px solid rgba(255,255,255,0.08);
|
| 212 |
+
border-radius: 10px; padding: 0.85rem 1rem; text-align: center;
|
| 213 |
+
}
|
| 214 |
+
.kpi-card.has-value { border-color: rgba(59,130,246,0.2); }
|
| 215 |
+
.kpi-val {
|
| 216 |
+
font-size: 1.25rem; font-weight: 700; font-family: 'JetBrains Mono', monospace;
|
| 217 |
+
color: #06b6d4; line-height: 1.2;
|
| 218 |
+
}
|
| 219 |
+
.kpi-val.na { color: #334155; font-size: 0.9rem; }
|
| 220 |
+
.kpi-lbl { font-size: 0.68rem; color: #64748b; margin-top: 0.25rem;
|
| 221 |
+
text-transform: uppercase; letter-spacing: 0.05em; }
|
| 222 |
+
|
| 223 |
+
.source-chips { display: flex; flex-wrap: wrap; gap: 0.3rem; margin-top: 0.6rem; }
|
| 224 |
+
.chip {
|
| 225 |
+
background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08);
|
| 226 |
+
border-radius: 5px; padding: 0.15rem 0.5rem; font-size: 0.68rem;
|
| 227 |
+
color: #64748b; font-family: 'JetBrains Mono', monospace;
|
| 228 |
+
}
|
| 229 |
+
.chip.table-chip { border-color: rgba(16,185,129,0.3); color: #6ee7b7; }
|
| 230 |
+
|
| 231 |
+
.welcome-wrap {
|
| 232 |
+
display: flex; flex-direction: column; align-items: center;
|
| 233 |
+
justify-content: center; min-height: 60vh; gap: 1.2rem; text-align: center;
|
| 234 |
+
padding: 2rem;
|
| 235 |
+
}
|
| 236 |
+
.welcome-logo { font-size: 3rem; }
|
| 237 |
+
.welcome-title {
|
| 238 |
+
font-size: 2rem; font-weight: 800; letter-spacing: -0.04em;
|
| 239 |
+
background: linear-gradient(135deg, #3b82f6 0%, #06b6d4 50%, #8b5cf6 100%);
|
| 240 |
+
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
|
| 241 |
+
}
|
| 242 |
+
.welcome-sub { font-size: 1rem; color: #64748b; max-width: 460px; line-height: 1.6; }
|
| 243 |
+
.suggestion-grid {
|
| 244 |
+
display: grid; grid-template-columns: repeat(2, 1fr);
|
| 245 |
+
gap: 0.6rem; max-width: 560px; width: 100%;
|
| 246 |
+
}
|
| 247 |
+
.suggestion-card {
|
| 248 |
+
background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08);
|
| 249 |
+
border-radius: 10px; padding: 0.8rem 1rem; font-size: 0.82rem;
|
| 250 |
+
color: #94a3b8; cursor: pointer; text-align: left;
|
| 251 |
+
transition: all 0.15s;
|
| 252 |
+
}
|
| 253 |
+
.suggestion-card:hover {
|
| 254 |
+
background: rgba(59,130,246,0.08); border-color: rgba(59,130,246,0.3);
|
| 255 |
+
color: #e2e8f0;
|
| 256 |
+
}
|
| 257 |
+
.suggestion-icon { font-size: 1rem; margin-bottom: 0.3rem; display: block; }
|
| 258 |
+
</style>
|
| 259 |
+
""", unsafe_allow_html=True)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
# ════════════════════════════════════════════════════════════════════
|
| 263 |
+
# Session State Init
|
| 264 |
+
# ════════════════════════════════════════════════════════════════════
|
| 265 |
+
COMPANIES = list(settings.company_ticker_map.keys())
|
| 266 |
+
|
| 267 |
+
def _init_state():
|
| 268 |
+
defaults = {
|
| 269 |
+
"conversation_id": None,
|
| 270 |
+
"messages": [], # list of dicts: role, content, metadata
|
| 271 |
+
"mode": "chat", # "chat" | "compare" | "dashboard"
|
| 272 |
+
"company": COMPANIES[0], # primary company
|
| 273 |
+
"companies_compare": [], # for compare mode
|
| 274 |
+
"fy": "FY2025",
|
| 275 |
+
"pending_suggestion": None,
|
| 276 |
+
}
|
| 277 |
+
for k, v in defaults.items():
|
| 278 |
+
if k not in st.session_state:
|
| 279 |
+
st.session_state[k] = v
|
| 280 |
+
|
| 281 |
+
_init_state()
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
# ════════════════════════════════════════════════════════════════════
|
| 285 |
+
# Helpers
|
| 286 |
+
# ════════════════════════════════════════════════════════════════════
|
| 287 |
+
|
| 288 |
+
def start_new_conversation():
|
| 289 |
+
cid = new_conversation(mode=st.session_state.mode)
|
| 290 |
+
st.session_state.conversation_id = cid
|
| 291 |
+
st.session_state.messages = []
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def load_conversation(cid: str):
|
| 295 |
+
st.session_state.conversation_id = cid
|
| 296 |
+
st.session_state.messages = get_messages(cid)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def save_message(role: str, content: str, metadata: dict = None):
|
| 300 |
+
cid = st.session_state.conversation_id
|
| 301 |
+
if not cid:
|
| 302 |
+
cid = new_conversation()
|
| 303 |
+
st.session_state.conversation_id = cid
|
| 304 |
+
add_message(cid, role, content, metadata)
|
| 305 |
+
# Set title from first user message
|
| 306 |
+
if role == "user" and len(st.session_state.messages) == 0:
|
| 307 |
+
update_conversation_title(cid, content)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def parse_at_mentions(text: str) -> tuple[str, list[str]]:
|
| 311 |
+
"""Extract @COMPANY mentions; return (cleaned_text, [companies])."""
|
| 312 |
+
found = []
|
| 313 |
+
cleaned = text
|
| 314 |
+
for c in COMPANIES:
|
| 315 |
+
if f"@{c}" in text or f"@{c.lower()}" in text.lower():
|
| 316 |
+
found.append(c)
|
| 317 |
+
cleaned = re.sub(f"@{re.escape(c)}", c, cleaned, flags=re.IGNORECASE)
|
| 318 |
+
return cleaned.strip(), found
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def detect_intent(query: str, mentioned: list[str]) -> str:
|
| 322 |
+
"""Auto-detect mode from query text."""
|
| 323 |
+
ql = query.lower()
|
| 324 |
+
if any(k in ql for k in ["dashboard", "kpi", "extract metrics", "show metrics", "key metrics"]):
|
| 325 |
+
return "dashboard"
|
| 326 |
+
if len(mentioned) > 1 or any(k in ql for k in ["compare", " vs ", "versus", "better than", "difference between"]):
|
| 327 |
+
return "compare"
|
| 328 |
+
return "chat"
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def fmt_crore(v):
|
| 332 |
+
if v is None: return "N/A"
|
| 333 |
+
if v >= 100000: return f"₹{v/100000:.1f}L Cr"
|
| 334 |
+
return f"₹{v:,.0f} Cr"
|
| 335 |
+
|
| 336 |
+
def fmt_pct(v):
|
| 337 |
+
return f"{v:.2f}%" if v is not None else "N/A"
|
| 338 |
+
|
| 339 |
+
def fmt_inr(v):
|
| 340 |
+
return f"₹{v:.2f}" if v is not None else "N/A"
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
# ════════════════════════════════════════════════════════════════════
|
| 344 |
+
# Render helpers
|
| 345 |
+
# ════════════════════════════════════════════════════════════════════
|
| 346 |
+
|
| 347 |
+
def render_source_chips(sources: list[dict]):
|
| 348 |
+
if not sources:
|
| 349 |
+
return
|
| 350 |
+
chips_html = '<div class="source-chips">'
|
| 351 |
+
for s in sources:
|
| 352 |
+
cls = "chip table-chip" if s.get("is_table") else "chip"
|
| 353 |
+
chips_html += f'<span class="{cls}">{s["label"]}</span>'
|
| 354 |
+
chips_html += "</div>"
|
| 355 |
+
st.markdown(chips_html, unsafe_allow_html=True)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def render_kpi_cards(metrics: dict):
|
| 359 |
+
"""Render 2 rows of KPI cards from extracted metrics dict."""
|
| 360 |
+
rows = [
|
| 361 |
+
[
|
| 362 |
+
("Revenue", fmt_crore(metrics.get("revenue_crore")), metrics.get("revenue_crore") is not None),
|
| 363 |
+
("Net Profit", fmt_crore(metrics.get("net_profit_crore")), metrics.get("net_profit_crore") is not None),
|
| 364 |
+
("Net Margin", fmt_pct(metrics.get("net_profit_margin_pct")), metrics.get("net_profit_margin_pct") is not None),
|
| 365 |
+
("EBITDA Margin", fmt_pct(metrics.get("ebitda_margin_pct")), metrics.get("ebitda_margin_pct") is not None),
|
| 366 |
+
],
|
| 367 |
+
[
|
| 368 |
+
("Total Assets", fmt_crore(metrics.get("total_assets_crore")), metrics.get("total_assets_crore") is not None),
|
| 369 |
+
("Equity", fmt_crore(metrics.get("equity_crore")), metrics.get("equity_crore") is not None),
|
| 370 |
+
("EPS", fmt_inr(metrics.get("eps_inr")), metrics.get("eps_inr") is not None),
|
| 371 |
+
("ROE", fmt_pct(metrics.get("roe_pct")), metrics.get("roe_pct") is not None),
|
| 372 |
+
],
|
| 373 |
+
]
|
| 374 |
+
banking_row = None
|
| 375 |
+
if any(metrics.get(k) is not None for k in ["npa_gross_pct", "npa_net_pct", "nim_pct"]):
|
| 376 |
+
banking_row = [
|
| 377 |
+
("Gross NPA", fmt_pct(metrics.get("npa_gross_pct")), metrics.get("npa_gross_pct") is not None),
|
| 378 |
+
("Net NPA", fmt_pct(metrics.get("npa_net_pct")), metrics.get("npa_net_pct") is not None),
|
| 379 |
+
("NIM", fmt_pct(metrics.get("nim_pct")), metrics.get("nim_pct") is not None),
|
| 380 |
+
("EBITDA", fmt_crore(metrics.get("ebitda_crore")), metrics.get("ebitda_crore") is not None),
|
| 381 |
+
]
|
| 382 |
+
|
| 383 |
+
for row in ([*rows] + ([banking_row] if banking_row else [])):
|
| 384 |
+
cols = st.columns(4)
|
| 385 |
+
for col, (label, value, has_val) in zip(cols, row):
|
| 386 |
+
card_cls = "kpi-card has-value" if has_val else "kpi-card"
|
| 387 |
+
val_cls = "kpi-val" if has_val else "kpi-val na"
|
| 388 |
+
col.markdown(
|
| 389 |
+
f'<div class="{card_cls}"><div class="{val_cls}">{value}</div>'
|
| 390 |
+
f'<div class="kpi-lbl">{label}</div></div>',
|
| 391 |
+
unsafe_allow_html=True,
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def render_kpi_chart(metrics: dict, company: str):
|
| 396 |
+
chart_map = {
|
| 397 |
+
"Revenue": metrics.get("revenue_crore"),
|
| 398 |
+
"Net Profit": metrics.get("net_profit_crore"),
|
| 399 |
+
"EBITDA": metrics.get("ebitda_crore"),
|
| 400 |
+
"Total Assets": metrics.get("total_assets_crore"),
|
| 401 |
+
"Equity": metrics.get("equity_crore"),
|
| 402 |
+
}
|
| 403 |
+
data = {k: v for k, v in chart_map.items() if v is not None}
|
| 404 |
+
if not data:
|
| 405 |
+
return
|
| 406 |
+
|
| 407 |
+
colors = ["#3b82f6", "#06b6d4", "#8b5cf6", "#10b981", "#f59e0b"]
|
| 408 |
+
fig = go.Figure(go.Bar(
|
| 409 |
+
y=list(data.keys()), x=list(data.values()), orientation="h",
|
| 410 |
+
marker=dict(color=colors[:len(data)], opacity=0.85),
|
| 411 |
+
text=[f"₹{v:,.0f} Cr" for v in data.values()],
|
| 412 |
+
textposition="outside", textfont=dict(color="#e2e8f0", size=11),
|
| 413 |
+
))
|
| 414 |
+
fig.update_layout(
|
| 415 |
+
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(255,255,255,0.02)",
|
| 416 |
+
font=dict(color="#94a3b8", family="Inter"),
|
| 417 |
+
xaxis=dict(gridcolor="rgba(255,255,255,0.05)", tickfont=dict(color="#64748b")),
|
| 418 |
+
yaxis=dict(tickfont=dict(color="#e2e8f0", size=12)),
|
| 419 |
+
margin=dict(t=10, b=10, l=10, r=70), height=220,
|
| 420 |
+
title=dict(text=f"{company} — Financial Overview", font=dict(color="#94a3b8", size=12)),
|
| 421 |
+
)
|
| 422 |
+
st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def render_compare_chart(company_data: dict, metric_label: str):
|
| 426 |
+
"""Bar chart for one metric across multiple companies."""
|
| 427 |
+
companies = list(company_data.keys())
|
| 428 |
+
values = list(company_data.values())
|
| 429 |
+
colors = ["#3b82f6", "#06b6d4", "#8b5cf6", "#10b981"]
|
| 430 |
+
|
| 431 |
+
fig = go.Figure(go.Bar(
|
| 432 |
+
x=companies, y=values,
|
| 433 |
+
marker_color=colors[:len(companies)],
|
| 434 |
+
text=[f"{v:,.1f}" if v else "N/A" for v in values],
|
| 435 |
+
textposition="outside", textfont=dict(color="#e2e8f0", size=12),
|
| 436 |
+
))
|
| 437 |
+
fig.update_layout(
|
| 438 |
+
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(255,255,255,0.02)",
|
| 439 |
+
font=dict(color="#94a3b8", family="Inter"),
|
| 440 |
+
title=dict(text=metric_label, font=dict(color="#94a3b8", size=12)),
|
| 441 |
+
xaxis=dict(showgrid=False, tickfont=dict(color="#e2e8f0")),
|
| 442 |
+
yaxis=dict(gridcolor="rgba(255,255,255,0.05)", tickfont=dict(color="#64748b")),
|
| 443 |
+
margin=dict(t=40, b=10, l=10, r=10), height=260,
|
| 444 |
+
)
|
| 445 |
+
st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def render_chat_history():
|
| 449 |
+
"""Render all messages in the current conversation."""
|
| 450 |
+
for msg in st.session_state.messages:
|
| 451 |
+
role = msg["role"]
|
| 452 |
+
content = msg["content"]
|
| 453 |
+
meta = msg.get("metadata") or {}
|
| 454 |
+
|
| 455 |
+
with st.chat_message(role, avatar="🧑" if role == "user" else "📈"):
|
| 456 |
+
st.markdown(content)
|
| 457 |
+
|
| 458 |
+
# KPI cards (dashboard mode results)
|
| 459 |
+
if meta.get("kpi_metrics"):
|
| 460 |
+
render_kpi_cards(meta["kpi_metrics"])
|
| 461 |
+
render_kpi_chart(meta["kpi_metrics"], meta.get("company", ""))
|
| 462 |
+
|
| 463 |
+
# Comparison chart
|
| 464 |
+
if meta.get("compare_chart"):
|
| 465 |
+
cc = meta["compare_chart"]
|
| 466 |
+
render_compare_chart(cc["data"], cc["label"])
|
| 467 |
+
|
| 468 |
+
# Sources
|
| 469 |
+
if meta.get("sources"):
|
| 470 |
+
with st.expander(f"Sources ({len(meta['sources'])})", expanded=False):
|
| 471 |
+
render_source_chips(meta["sources"])
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
# ════════════════════════════════════════════════════════════════════
|
| 475 |
+
# Pipeline runners
|
| 476 |
+
# ════════════════════════════════════════════════════════════════════
|
| 477 |
+
|
| 478 |
+
def run_chat(query: str, company: str, fy: str | None) -> tuple[str, dict]:
|
| 479 |
+
from src.generation.prompts import build_qa_prompt
|
| 480 |
+
|
| 481 |
+
retriever = load_retriever()
|
| 482 |
+
reranker = load_reranker()
|
| 483 |
+
llm = load_groq()
|
| 484 |
+
|
| 485 |
+
with st.spinner("Retrieving relevant passages…"):
|
| 486 |
+
candidates = retriever.retrieve(
|
| 487 |
+
query=query, top_k=50,
|
| 488 |
+
company_filter=company,
|
| 489 |
+
fiscal_year_filter=fy,
|
| 490 |
+
expand_query=True, promote_to_parent=True,
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
if not candidates:
|
| 494 |
+
return "No relevant documents found for this query.", {}
|
| 495 |
+
|
| 496 |
+
with st.spinner("Reranking results…"):
|
| 497 |
+
reranked = reranker.rerank(query=query, candidates=candidates, top_n=5)
|
| 498 |
+
|
| 499 |
+
system_prompt, user_msg = build_qa_prompt(
|
| 500 |
+
query=query, results=reranked,
|
| 501 |
+
company_context=f"{company} ({settings.company_ticker_map.get(company, '')})",
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
with st.chat_message("assistant", avatar="📈"):
|
| 505 |
+
answer = st.write_stream(llm.generate_stream(system_prompt, user_msg))
|
| 506 |
+
|
| 507 |
+
sources = [
|
| 508 |
+
{"label": f"{c.company} | {c.fiscal_year} | Pg.{c.page_number}",
|
| 509 |
+
"is_table": c.content_type == "table"}
|
| 510 |
+
for c in reranked
|
| 511 |
+
]
|
| 512 |
+
meta = {"sources": sources, "company": company}
|
| 513 |
+
with st.chat_message("assistant", avatar="📈"):
|
| 514 |
+
with st.expander(f"Sources ({len(sources)})", expanded=False):
|
| 515 |
+
render_source_chips(sources)
|
| 516 |
+
|
| 517 |
+
return answer, meta
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def run_dashboard(company: str, fy: str | None) -> tuple[str, dict]:
|
| 521 |
+
retriever = load_retriever()
|
| 522 |
+
reranker = load_reranker()
|
| 523 |
+
extractor = load_metric_extractor()
|
| 524 |
+
|
| 525 |
+
with st.spinner(f"Retrieving financial data for {company}…"):
|
| 526 |
+
all_cands = []
|
| 527 |
+
for q in ["revenue net profit financial performance", "balance sheet assets equity"]:
|
| 528 |
+
all_cands.extend(retriever.retrieve(
|
| 529 |
+
query=q, top_k=20, company_filter=company,
|
| 530 |
+
fiscal_year_filter=fy, expand_query=False,
|
| 531 |
+
))
|
| 532 |
+
seen = set(); unique = []
|
| 533 |
+
for c in all_cands:
|
| 534 |
+
if c.chunk_id not in seen:
|
| 535 |
+
seen.add(c.chunk_id); unique.append(c)
|
| 536 |
+
|
| 537 |
+
reranked = reranker.rerank(
|
| 538 |
+
query="financial metrics revenue profit assets equity EPS",
|
| 539 |
+
candidates=unique, top_n=4,
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
with st.spinner("Extracting KPIs with AI…"):
|
| 543 |
+
data = extractor.extract(company, reranked)
|
| 544 |
+
|
| 545 |
+
metrics = data.get("metrics", {})
|
| 546 |
+
fy_label = data.get("fiscal_year", fy or "FY2025")
|
| 547 |
+
ticker = settings.company_ticker_map.get(company, company)
|
| 548 |
+
|
| 549 |
+
answer = f"**{company}** ({ticker}) — KPI Summary for **{fy_label}**"
|
| 550 |
+
|
| 551 |
+
with st.chat_message("assistant", avatar="📈"):
|
| 552 |
+
st.markdown(answer)
|
| 553 |
+
render_kpi_cards(metrics)
|
| 554 |
+
render_kpi_chart(metrics, company)
|
| 555 |
+
|
| 556 |
+
meta = {"kpi_metrics": metrics, "company": company, "fy": fy_label}
|
| 557 |
+
return answer, meta
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def run_compare(query: str, companies: list[str], fy: str | None) -> tuple[str, dict]:
|
| 561 |
+
comparator = load_comparator()
|
| 562 |
+
extractor = load_metric_extractor()
|
| 563 |
+
|
| 564 |
+
with st.spinner(f"Comparing {' vs '.join(companies)}…"):
|
| 565 |
+
company_results, answer_gen = comparator.compare(
|
| 566 |
+
query=query, companies=companies, fiscal_year=fy, stream=True,
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
meta = {}
|
| 570 |
+
with st.chat_message("assistant", avatar="📈"):
|
| 571 |
+
answer = st.write_stream(answer_gen)
|
| 572 |
+
|
| 573 |
+
# Try to extract one plottable metric
|
| 574 |
+
try:
|
| 575 |
+
with st.spinner("Generating comparison chart…"):
|
| 576 |
+
mlist = extractor.extract_multi(company_results)
|
| 577 |
+
comp_table = extractor.to_comparison_table(mlist)
|
| 578 |
+
comp_table.pop("companies", None)
|
| 579 |
+
|
| 580 |
+
for metric_label, vals in comp_table.items():
|
| 581 |
+
numeric = {c: v for c, v in vals.items() if v is not None and isinstance(v, (int, float))}
|
| 582 |
+
if len(numeric) >= 2:
|
| 583 |
+
render_compare_chart(numeric, metric_label)
|
| 584 |
+
meta["compare_chart"] = {"data": numeric, "label": metric_label}
|
| 585 |
+
break
|
| 586 |
+
except Exception:
|
| 587 |
+
pass
|
| 588 |
+
|
| 589 |
+
sources = []
|
| 590 |
+
for company, results in company_results.items():
|
| 591 |
+
for r in results:
|
| 592 |
+
sources.append({"label": f"{company} Pg.{r.page_number}", "is_table": False})
|
| 593 |
+
meta["sources"] = sources
|
| 594 |
+
|
| 595 |
+
return answer, meta
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
# ════════════════════════════════════════════════════════════════════
|
| 599 |
+
# SIDEBAR
|
| 600 |
+
# ════════════════════════════════════════════════════════════════════
|
| 601 |
+
with st.sidebar:
|
| 602 |
+
# Brand
|
| 603 |
+
st.markdown("""
|
| 604 |
+
<div class="fin-brand">
|
| 605 |
+
<span class="fin-brand-icon">📈</span>
|
| 606 |
+
<div>
|
| 607 |
+
<div class="fin-brand-name">FinRAG</div>
|
| 608 |
+
<div class="fin-brand-sub">Indian Markets Intelligence</div>
|
| 609 |
+
</div>
|
| 610 |
+
</div>
|
| 611 |
+
""", unsafe_allow_html=True)
|
| 612 |
+
|
| 613 |
+
# New chat button
|
| 614 |
+
if st.button("+ New Chat", use_container_width=True,
|
| 615 |
+
type="secondary", key="new_chat_btn"):
|
| 616 |
+
start_new_conversation()
|
| 617 |
+
st.rerun()
|
| 618 |
+
|
| 619 |
+
st.markdown("<hr style='margin:0.6rem 0'>", unsafe_allow_html=True)
|
| 620 |
+
|
| 621 |
+
# Quick actions
|
| 622 |
+
st.markdown('<div class="history-group-label">Quick Actions</div>', unsafe_allow_html=True)
|
| 623 |
+
col_a, col_b = st.columns(2)
|
| 624 |
+
with col_a:
|
| 625 |
+
if st.button("⚖️ Compare", use_container_width=True, key="sb_compare"):
|
| 626 |
+
st.session_state.mode = "compare"
|
| 627 |
+
if not st.session_state.conversation_id:
|
| 628 |
+
start_new_conversation()
|
| 629 |
+
st.rerun()
|
| 630 |
+
with col_b:
|
| 631 |
+
if st.button("📊 Dashboard", use_container_width=True, key="sb_dashboard"):
|
| 632 |
+
st.session_state.mode = "dashboard"
|
| 633 |
+
if not st.session_state.conversation_id:
|
| 634 |
+
start_new_conversation()
|
| 635 |
+
st.rerun()
|
| 636 |
+
|
| 637 |
+
st.markdown("<hr style='margin:0.6rem 0'>", unsafe_allow_html=True)
|
| 638 |
+
|
| 639 |
+
# Conversation history
|
| 640 |
+
all_convs = list_conversations(40)
|
| 641 |
+
if all_convs:
|
| 642 |
+
grouped = group_conversations_by_date(all_convs)
|
| 643 |
+
current_cid = st.session_state.conversation_id
|
| 644 |
+
|
| 645 |
+
for group_label, convs in grouped.items():
|
| 646 |
+
st.markdown(f'<div class="history-group-label">{group_label}</div>', unsafe_allow_html=True)
|
| 647 |
+
for conv in convs:
|
| 648 |
+
is_active = conv["id"] == current_cid
|
| 649 |
+
active_cls = "history-item active" if is_active else "history-item"
|
| 650 |
+
mode_icon = {"chat": "💬", "compare": "⚖️", "dashboard": "📊"}.get(conv["mode"], "💬")
|
| 651 |
+
label = f"{mode_icon} {conv['title']}"
|
| 652 |
+
|
| 653 |
+
# Use a button styled as a list item
|
| 654 |
+
if st.button(label, key=f"hist_{conv['id']}", use_container_width=True,
|
| 655 |
+
help=conv["title"]):
|
| 656 |
+
load_conversation(conv["id"])
|
| 657 |
+
st.rerun()
|
| 658 |
+
else:
|
| 659 |
+
st.markdown('<div style="padding:0.5rem 0.8rem;font-size:0.78rem;color:#334155;">No history yet</div>',
|
| 660 |
+
unsafe_allow_html=True)
|
| 661 |
+
|
| 662 |
+
# Sidebar footer
|
| 663 |
+
st.markdown("<hr style='margin:0.6rem 0'>", unsafe_allow_html=True)
|
| 664 |
+
st.markdown(
|
| 665 |
+
'<div style="padding:0.3rem 0.8rem;font-size:0.68rem;color:#334155;line-height:1.6;">'
|
| 666 |
+
f'17 companies · FY2024–25<br>'
|
| 667 |
+
'Hybrid RAG · BGE-large · Groq LPU'
|
| 668 |
+
'</div>', unsafe_allow_html=True,
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
# ════════════════════════════════════════════════════════════════════
|
| 673 |
+
# MAIN AREA
|
| 674 |
+
# ════════════════════════════════════════════════════════════════════
|
| 675 |
+
main = st.container()
|
| 676 |
+
|
| 677 |
+
with main:
|
| 678 |
+
# ── Mode pills (top bar) ────────────────────────────────────────
|
| 679 |
+
st.markdown('<div style="height:0.8rem"></div>', unsafe_allow_html=True)
|
| 680 |
+
mode_col, spacer = st.columns([3, 7])
|
| 681 |
+
with mode_col:
|
| 682 |
+
mode_labels = {"chat": "💬 Chat", "compare": "⚖️ Compare", "dashboard": "📊 Dashboard"}
|
| 683 |
+
new_mode = st.radio(
|
| 684 |
+
"Mode", list(mode_labels.values()),
|
| 685 |
+
index=list(mode_labels.keys()).index(st.session_state.mode),
|
| 686 |
+
horizontal=True, label_visibility="collapsed", key="mode_radio",
|
| 687 |
+
)
|
| 688 |
+
selected_mode_key = list(mode_labels.keys())[list(mode_labels.values()).index(new_mode)]
|
| 689 |
+
if selected_mode_key != st.session_state.mode:
|
| 690 |
+
st.session_state.mode = selected_mode_key
|
| 691 |
+
st.rerun()
|
| 692 |
+
|
| 693 |
+
st.markdown("<hr style='margin:0.3rem 0 0.6rem 0'>", unsafe_allow_html=True)
|
| 694 |
+
|
| 695 |
+
# ── Context selectors ──────────────────��────────────────────────
|
| 696 |
+
if st.session_state.mode == "compare":
|
| 697 |
+
ctx1, ctx2, ctx3 = st.columns([3, 1.5, 5])
|
| 698 |
+
with ctx1:
|
| 699 |
+
sel_companies = st.multiselect(
|
| 700 |
+
"Companies", COMPANIES,
|
| 701 |
+
default=st.session_state.companies_compare or ["TCS", "INFOSYS"],
|
| 702 |
+
max_selections=4, label_visibility="collapsed", key="cmp_sel",
|
| 703 |
+
)
|
| 704 |
+
st.session_state.companies_compare = sel_companies
|
| 705 |
+
with ctx2:
|
| 706 |
+
fy_sel = st.selectbox("FY", ["FY2025", "FY2024", "All"], index=0,
|
| 707 |
+
label_visibility="collapsed", key="cmp_fy")
|
| 708 |
+
elif st.session_state.mode == "dashboard":
|
| 709 |
+
ctx1, ctx2, ctx3 = st.columns([2.5, 1.5, 6])
|
| 710 |
+
with ctx1:
|
| 711 |
+
sel_company = st.selectbox("Company", COMPANIES, label_visibility="collapsed",
|
| 712 |
+
key="dash_company_sel")
|
| 713 |
+
st.session_state.company = sel_company
|
| 714 |
+
with ctx2:
|
| 715 |
+
fy_sel = st.selectbox("FY", ["FY2025", "FY2024"], index=0,
|
| 716 |
+
label_visibility="collapsed", key="dash_fy")
|
| 717 |
+
with ctx3:
|
| 718 |
+
if st.button("Extract KPIs →", type="primary", key="dash_extract_btn"):
|
| 719 |
+
fy_filter = None if fy_sel == "All" else fy_sel
|
| 720 |
+
|
| 721 |
+
if not st.session_state.conversation_id:
|
| 722 |
+
start_new_conversation()
|
| 723 |
+
|
| 724 |
+
user_text = f"Show KPI dashboard for {st.session_state.company} {fy_sel}"
|
| 725 |
+
st.session_state.messages.append({"role": "user", "content": user_text, "metadata": {}})
|
| 726 |
+
save_message("user", user_text)
|
| 727 |
+
|
| 728 |
+
answer, meta = run_dashboard(st.session_state.company, fy_filter)
|
| 729 |
+
|
| 730 |
+
st.session_state.messages.append({"role": "assistant", "content": answer, "metadata": meta})
|
| 731 |
+
save_message("assistant", answer, meta)
|
| 732 |
+
st.rerun()
|
| 733 |
+
else:
|
| 734 |
+
# Chat mode context bar
|
| 735 |
+
ctx1, ctx2, ctx3 = st.columns([2.5, 1.5, 6])
|
| 736 |
+
with ctx1:
|
| 737 |
+
sel_company = st.selectbox(
|
| 738 |
+
"Company", COMPANIES,
|
| 739 |
+
index=COMPANIES.index(st.session_state.company) if st.session_state.company in COMPANIES else 0,
|
| 740 |
+
label_visibility="collapsed", key="chat_company_sel",
|
| 741 |
+
)
|
| 742 |
+
st.session_state.company = sel_company
|
| 743 |
+
with ctx2:
|
| 744 |
+
fy_sel = st.selectbox("FY", ["FY2025", "FY2024", "All"],
|
| 745 |
+
index=0, label_visibility="collapsed", key="chat_fy_sel")
|
| 746 |
+
|
| 747 |
+
st.markdown("<div style='height:0.4rem'></div>", unsafe_allow_html=True)
|
| 748 |
+
|
| 749 |
+
# ── Chat thread ─────────────────────────────────────────────────
|
| 750 |
+
if not st.session_state.messages:
|
| 751 |
+
# Welcome screen
|
| 752 |
+
st.markdown("""
|
| 753 |
+
<div class="welcome-wrap">
|
| 754 |
+
<div class="welcome-logo">📈</div>
|
| 755 |
+
<div class="welcome-title">FinRAG</div>
|
| 756 |
+
<div class="welcome-sub">
|
| 757 |
+
Ask anything about 17 major Indian companies.<br>
|
| 758 |
+
Grounded in official BSE annual reports.
|
| 759 |
+
</div>
|
| 760 |
+
</div>
|
| 761 |
+
""", unsafe_allow_html=True)
|
| 762 |
+
|
| 763 |
+
# Suggestion cards
|
| 764 |
+
suggestions = [
|
| 765 |
+
("💰", "What was TCS's revenue and net profit for FY2025?"),
|
| 766 |
+
("🏦", "What is HDFC Bank's gross NPA ratio?"),
|
| 767 |
+
("⚖️", "Compare Infosys vs HCL Technologies on revenue growth"),
|
| 768 |
+
("📊", "Show KPI dashboard for Reliance Industries"),
|
| 769 |
+
]
|
| 770 |
+
cols = st.columns(2)
|
| 771 |
+
for i, (icon, text) in enumerate(suggestions):
|
| 772 |
+
with cols[i % 2]:
|
| 773 |
+
st.markdown(
|
| 774 |
+
f'<div class="suggestion-card"><span class="suggestion-icon">{icon}</span>{text}</div>',
|
| 775 |
+
unsafe_allow_html=True,
|
| 776 |
+
)
|
| 777 |
+
if st.button(text, key=f"sug_{i}", help=text,
|
| 778 |
+
use_container_width=True):
|
| 779 |
+
st.session_state.pending_suggestion = text
|
| 780 |
+
st.rerun()
|
| 781 |
+
else:
|
| 782 |
+
render_chat_history()
|
| 783 |
+
|
| 784 |
+
# ── Chat input ──────────────────────────────────────────────────
|
| 785 |
+
mode = st.session_state.mode
|
| 786 |
+
placeholders = {
|
| 787 |
+
"chat": "Ask anything… use @CompanyName to specify (e.g. @TCS what was the revenue?)",
|
| 788 |
+
"compare": "Compare selected companies… (e.g. Compare revenue and margins)",
|
| 789 |
+
"dashboard": "Dashboard mode — use Extract KPIs button above, or type a question",
|
| 790 |
+
}
|
| 791 |
+
|
| 792 |
+
# Handle pending suggestion (clicked welcome card)
|
| 793 |
+
prefill = st.session_state.pop("pending_suggestion", None) or ""
|
| 794 |
+
|
| 795 |
+
user_input = st.chat_input(
|
| 796 |
+
placeholder=placeholders.get(mode, "Ask anything…"),
|
| 797 |
+
key="main_chat_input",
|
| 798 |
+
)
|
| 799 |
+
|
| 800 |
+
# Use suggestion if no direct input
|
| 801 |
+
if not user_input and prefill:
|
| 802 |
+
user_input = prefill
|
| 803 |
+
|
| 804 |
+
if user_input:
|
| 805 |
+
raw_query = user_input.strip()
|
| 806 |
+
if not raw_query:
|
| 807 |
+
st.stop()
|
| 808 |
+
|
| 809 |
+
# Parse @ mentions
|
| 810 |
+
query, mentioned_companies = parse_at_mentions(raw_query)
|
| 811 |
+
|
| 812 |
+
# Override company from @ mention
|
| 813 |
+
if mentioned_companies:
|
| 814 |
+
st.session_state.company = mentioned_companies[0]
|
| 815 |
+
if len(mentioned_companies) > 1:
|
| 816 |
+
st.session_state.companies_compare = mentioned_companies
|
| 817 |
+
|
| 818 |
+
# Auto-detect mode
|
| 819 |
+
intent = detect_intent(query, mentioned_companies)
|
| 820 |
+
if intent != "chat":
|
| 821 |
+
st.session_state.mode = intent
|
| 822 |
+
|
| 823 |
+
# Ensure conversation exists
|
| 824 |
+
if not st.session_state.conversation_id:
|
| 825 |
+
start_new_conversation()
|
| 826 |
+
|
| 827 |
+
# Show user message
|
| 828 |
+
with st.chat_message("user", avatar="🧑"):
|
| 829 |
+
st.markdown(raw_query)
|
| 830 |
+
|
| 831 |
+
# Save user message
|
| 832 |
+
st.session_state.messages.append({"role": "user", "content": raw_query, "metadata": {}})
|
| 833 |
+
save_message("user", raw_query)
|
| 834 |
+
|
| 835 |
+
fy_filter = None if fy_sel == "All" else fy_sel
|
| 836 |
+
|
| 837 |
+
# Route to correct pipeline
|
| 838 |
+
try:
|
| 839 |
+
if st.session_state.mode == "dashboard":
|
| 840 |
+
answer, meta = run_dashboard(st.session_state.company, fy_filter)
|
| 841 |
+
|
| 842 |
+
elif st.session_state.mode == "compare":
|
| 843 |
+
compare_cos = st.session_state.companies_compare or [st.session_state.company]
|
| 844 |
+
if len(compare_cos) < 2:
|
| 845 |
+
with st.chat_message("assistant", avatar="📈"):
|
| 846 |
+
st.warning("Please select at least 2 companies from the Compare selector above.")
|
| 847 |
+
answer, meta = "Please select at least 2 companies.", {}
|
| 848 |
+
else:
|
| 849 |
+
answer, meta = run_compare(query, compare_cos, fy_filter)
|
| 850 |
+
|
| 851 |
+
else: # chat
|
| 852 |
+
answer, meta = run_chat(query, st.session_state.company, fy_filter)
|
| 853 |
+
|
| 854 |
+
except Exception as e:
|
| 855 |
+
with st.chat_message("assistant", avatar="📈"):
|
| 856 |
+
st.error(f"Something went wrong: {e}")
|
| 857 |
+
answer, meta = str(e), {}
|
| 858 |
+
|
| 859 |
+
# Save assistant message
|
| 860 |
+
st.session_state.messages.append({"role": "assistant", "content": answer, "metadata": meta})
|
| 861 |
+
save_message("assistant", answer, meta)
|
| 862 |
+
st.rerun()
|
app/pages/1_Chat.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app/pages/1_Chat.py
|
| 3 |
+
====================
|
| 4 |
+
Single company Q&A page with streaming answers and citation display.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
import os
|
| 9 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 10 |
+
from config.settings import settings
|
| 11 |
+
|
| 12 |
+
import streamlit as st
|
| 13 |
+
|
| 14 |
+
st.set_page_config(page_title="Q&A | FinRAG", page_icon="💬", layout="wide")
|
| 15 |
+
|
| 16 |
+
# Shared resource loaders (cached across all pages)
|
| 17 |
+
from app.rag_engine import load_retriever, load_reranker, load_groq
|
| 18 |
+
|
| 19 |
+
# Apply same CSS
|
| 20 |
+
st.markdown("""
|
| 21 |
+
<style>
|
| 22 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
|
| 23 |
+
:root {
|
| 24 |
+
--bg-card: rgba(255,255,255,0.04);
|
| 25 |
+
--accent-cyan: #06b6d4;
|
| 26 |
+
--accent-blue: #3b82f6;
|
| 27 |
+
--text-primary: #f1f5f9;
|
| 28 |
+
--text-secondary: #94a3b8;
|
| 29 |
+
--border: rgba(255,255,255,0.08);
|
| 30 |
+
}
|
| 31 |
+
.stApp { background: linear-gradient(135deg, #0a0e1a, #0f1628); font-family: 'Inter', sans-serif; }
|
| 32 |
+
#MainMenu, footer, header { visibility: hidden; }
|
| 33 |
+
.stButton > button {
|
| 34 |
+
background: linear-gradient(135deg, #3b82f6, #06b6d4) !important;
|
| 35 |
+
color: white !important; border: none !important;
|
| 36 |
+
border-radius: 8px !important; font-weight: 600 !important;
|
| 37 |
+
}
|
| 38 |
+
.stButton > button:hover { transform: translateY(-1px) !important; }
|
| 39 |
+
.citation-chip {
|
| 40 |
+
display: inline-block; background: rgba(59,130,246,0.15);
|
| 41 |
+
border: 1px solid rgba(59,130,246,0.3); border-radius: 20px;
|
| 42 |
+
padding: 0.2rem 0.7rem; font-size: 0.72rem; color: #93c5fd; margin: 0.15rem;
|
| 43 |
+
font-family: 'JetBrains Mono', monospace;
|
| 44 |
+
}
|
| 45 |
+
.fin-card {
|
| 46 |
+
background: var(--bg-card); border: 1px solid var(--border);
|
| 47 |
+
border-radius: 12px; padding: 1rem 1.2rem; margin-bottom: 0.8rem;
|
| 48 |
+
}
|
| 49 |
+
</style>
|
| 50 |
+
""", unsafe_allow_html=True)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# ---- Header ----
|
| 54 |
+
st.markdown("""
|
| 55 |
+
<div style="padding:1.5rem 0 1rem 0;">
|
| 56 |
+
<h1 style="font-size:1.8rem;font-weight:700;margin:0;
|
| 57 |
+
background:linear-gradient(135deg,#3b82f6,#06b6d4);
|
| 58 |
+
-webkit-background-clip:text;-webkit-text-fill-color:transparent;">
|
| 59 |
+
💬 Company Q&A
|
| 60 |
+
</h1>
|
| 61 |
+
<p style="color:#64748b;font-size:0.9rem;margin-top:0.3rem;">
|
| 62 |
+
Ask anything about a company's financials. Answers are grounded in BSE annual reports.
|
| 63 |
+
</p>
|
| 64 |
+
</div>
|
| 65 |
+
""", unsafe_allow_html=True)
|
| 66 |
+
|
| 67 |
+
# ---- Controls ----
|
| 68 |
+
col_company, col_fy = st.columns([2, 1])
|
| 69 |
+
|
| 70 |
+
with col_company:
|
| 71 |
+
companies = list(settings.company_ticker_map.keys())
|
| 72 |
+
selected_company = st.selectbox(
|
| 73 |
+
"Select Company",
|
| 74 |
+
options=companies,
|
| 75 |
+
index=companies.index("TCS") if "TCS" in companies else 0,
|
| 76 |
+
key="qa_company",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
with col_fy:
|
| 80 |
+
fy_options = ["All Years", "FY2025", "FY2024"]
|
| 81 |
+
selected_fy = st.selectbox("Fiscal Year", fy_options, key="qa_fy")
|
| 82 |
+
fy_filter = None if selected_fy == "All Years" else selected_fy
|
| 83 |
+
|
| 84 |
+
# ---- Sample questions ----
|
| 85 |
+
sample_questions = {
|
| 86 |
+
"TCS": [
|
| 87 |
+
"What was TCS's total revenue and net profit for FY2025?",
|
| 88 |
+
"What are TCS's key business segments and their revenue contributions?",
|
| 89 |
+
"What is TCS's headcount and employee attrition rate?",
|
| 90 |
+
],
|
| 91 |
+
"HDFC": [
|
| 92 |
+
"What is HDFC Bank's gross NPA and net NPA ratio?",
|
| 93 |
+
"What was HDFC Bank's net interest income for FY2025?",
|
| 94 |
+
"What is HDFC Bank's CASA ratio?",
|
| 95 |
+
],
|
| 96 |
+
"INFOSYS": [
|
| 97 |
+
"What was Infosys's operating margin for FY2025?",
|
| 98 |
+
"What are Infosys's key geographies and their revenue split?",
|
| 99 |
+
"What is Infosys's guidance for the next fiscal year?",
|
| 100 |
+
],
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
if selected_company in sample_questions:
|
| 104 |
+
with st.expander("Sample questions for " + selected_company, expanded=False):
|
| 105 |
+
for q in sample_questions[selected_company]:
|
| 106 |
+
if st.button(q, key=f"sample_{q[:20]}"):
|
| 107 |
+
st.session_state["qa_prefill"] = q
|
| 108 |
+
|
| 109 |
+
# ---- Chat Input ----
|
| 110 |
+
default_q = st.session_state.pop("qa_prefill", "")
|
| 111 |
+
user_query = st.text_area(
|
| 112 |
+
"Your question",
|
| 113 |
+
value=default_q,
|
| 114 |
+
placeholder="e.g. What was the company's net profit margin for FY2025?",
|
| 115 |
+
height=80,
|
| 116 |
+
key="qa_input",
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
col_btn, col_opts = st.columns([1, 3])
|
| 120 |
+
with col_btn:
|
| 121 |
+
ask_btn = st.button("Ask Question", type="primary", key="qa_ask")
|
| 122 |
+
with col_opts:
|
| 123 |
+
show_chunks = st.checkbox("Show retrieved chunks", value=False, key="qa_show_chunks")
|
| 124 |
+
|
| 125 |
+
# ---- Answer ----
|
| 126 |
+
if ask_btn and user_query.strip():
|
| 127 |
+
retriever = load_retriever()
|
| 128 |
+
llm = load_groq()
|
| 129 |
+
|
| 130 |
+
from src.generation.prompts import build_qa_prompt
|
| 131 |
+
|
| 132 |
+
# Stage 1: Hybrid retrieval (fast ~1-2s)
|
| 133 |
+
with st.spinner(f"Step 1/3 — Searching {selected_company} documents (hybrid dense+sparse)..."):
|
| 134 |
+
candidates = retriever.retrieve(
|
| 135 |
+
query=user_query,
|
| 136 |
+
top_k=50,
|
| 137 |
+
company_filter=selected_company,
|
| 138 |
+
fiscal_year_filter=fy_filter,
|
| 139 |
+
expand_query=True,
|
| 140 |
+
promote_to_parent=True,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
if not candidates:
|
| 144 |
+
st.warning("No relevant documents found. Try a different question or company.")
|
| 145 |
+
st.stop()
|
| 146 |
+
|
| 147 |
+
# Stage 2: Reranking (first time: downloads ~550MB model, ~2-5 min; subsequent: ~3s)
|
| 148 |
+
reranker = load_reranker()
|
| 149 |
+
with st.spinner("Step 2/3 — Reranking with cross-encoder (first run downloads BGE model ~550MB)..."):
|
| 150 |
+
reranked = reranker.rerank(
|
| 151 |
+
query=user_query,
|
| 152 |
+
candidates=candidates,
|
| 153 |
+
top_n=5,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
if not reranked:
|
| 157 |
+
st.warning("No relevant documents found. Try a different question or company.")
|
| 158 |
+
st.stop()
|
| 159 |
+
|
| 160 |
+
# Build prompt and stream answer
|
| 161 |
+
system_prompt, user_message = build_qa_prompt(
|
| 162 |
+
query=user_query,
|
| 163 |
+
results=reranked,
|
| 164 |
+
company_context=f"{selected_company} ({settings.company_ticker_map.get(selected_company, '')})",
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# Stage 3: LLM generation via Groq (streaming)
|
| 168 |
+
st.markdown("---")
|
| 169 |
+
st.markdown(f"""
|
| 170 |
+
<div style="font-size:0.8rem;color:#64748b;margin-bottom:0.5rem;">
|
| 171 |
+
Step 3/3 — Generating answer from {len(reranked)} chunks | {selected_company} {fy_filter or 'all years'}
|
| 172 |
+
</div>
|
| 173 |
+
""", unsafe_allow_html=True)
|
| 174 |
+
|
| 175 |
+
# Stream the answer
|
| 176 |
+
with st.chat_message("assistant", avatar="📈"):
|
| 177 |
+
answer = st.write_stream(llm.generate_stream(system_prompt, user_message))
|
| 178 |
+
|
| 179 |
+
# Citations
|
| 180 |
+
st.markdown("**Sources:**")
|
| 181 |
+
citation_html = ""
|
| 182 |
+
for chunk in reranked:
|
| 183 |
+
label = f"{chunk.company} | {chunk.fiscal_year} | Pg.{chunk.page_number}"
|
| 184 |
+
if chunk.content_type == "table":
|
| 185 |
+
label += " [TABLE]"
|
| 186 |
+
citation_html += f'<span class="citation-chip">{label}</span>'
|
| 187 |
+
st.markdown(citation_html, unsafe_allow_html=True)
|
| 188 |
+
|
| 189 |
+
# Retrieved chunks expander
|
| 190 |
+
if show_chunks:
|
| 191 |
+
with st.expander(f"Retrieved chunks ({len(reranked)})", expanded=False):
|
| 192 |
+
for i, chunk in enumerate(reranked, 1):
|
| 193 |
+
st.markdown(f"""
|
| 194 |
+
<div class="fin-card">
|
| 195 |
+
<div style="font-size:0.72rem;color:#64748b;margin-bottom:0.4rem;">
|
| 196 |
+
Chunk {i} | {chunk.company} | {chunk.section} | Page {chunk.page_number} |
|
| 197 |
+
Score: {chunk.rrf_score:.3f} | Type: {chunk.content_type}
|
| 198 |
+
</div>
|
| 199 |
+
<div style="font-size:0.82rem;color:#cbd5e1;white-space:pre-wrap;">{chunk.content[:600]}{"..." if len(chunk.content) > 600 else ""}</div>
|
| 200 |
+
</div>
|
| 201 |
+
""", unsafe_allow_html=True)
|
| 202 |
+
|
| 203 |
+
elif ask_btn:
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app/pages/2_Compare.py
|
| 3 |
+
========================
|
| 4 |
+
Cross-company comparison page with streaming answers and auto-generated Plotly charts.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
import os
|
| 9 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 10 |
+
from config.settings import settings
|
| 11 |
+
|
| 12 |
+
import streamlit as st
|
| 13 |
+
import plotly.graph_objects as go
|
| 14 |
+
import plotly.express as px
|
| 15 |
+
|
| 16 |
+
st.set_page_config(page_title="Compare | FinRAG", page_icon="⚖️", layout="wide")
|
| 17 |
+
|
| 18 |
+
from app.rag_engine import load_comparator, load_metric_extractor
|
| 19 |
+
|
| 20 |
+
# Shared CSS (same dark theme)
|
| 21 |
+
st.markdown("""
|
| 22 |
+
<style>
|
| 23 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
|
| 24 |
+
.stApp { background: linear-gradient(135deg, #0a0e1a, #0f1628); font-family: 'Inter', sans-serif; color: #f1f5f9; }
|
| 25 |
+
#MainMenu, footer, header { visibility: hidden; }
|
| 26 |
+
.stButton > button {
|
| 27 |
+
background: linear-gradient(135deg, #3b82f6, #06b6d4) !important;
|
| 28 |
+
color: white !important; border: none !important; border-radius: 8px !important; font-weight: 600 !important;
|
| 29 |
+
}
|
| 30 |
+
.citation-chip {
|
| 31 |
+
display: inline-block; background: rgba(59,130,246,0.15);
|
| 32 |
+
border: 1px solid rgba(59,130,246,0.3); border-radius: 20px;
|
| 33 |
+
padding: 0.2rem 0.7rem; font-size: 0.72rem; color: #93c5fd; margin: 0.15rem;
|
| 34 |
+
font-family: 'JetBrains Mono', monospace;
|
| 35 |
+
}
|
| 36 |
+
</style>
|
| 37 |
+
""", unsafe_allow_html=True)
|
| 38 |
+
|
| 39 |
+
# ---- Header ----
|
| 40 |
+
st.markdown("""
|
| 41 |
+
<div style="padding:1.5rem 0 1rem 0;">
|
| 42 |
+
<h1 style="font-size:1.8rem;font-weight:700;margin:0;
|
| 43 |
+
background:linear-gradient(135deg,#8b5cf6,#06b6d4);
|
| 44 |
+
-webkit-background-clip:text;-webkit-text-fill-color:transparent;">
|
| 45 |
+
⚖️ Compare Companies
|
| 46 |
+
</h1>
|
| 47 |
+
<p style="color:#64748b;font-size:0.9rem;margin-top:0.3rem;">
|
| 48 |
+
Side-by-side comparison of 2–4 companies from their BSE annual reports.
|
| 49 |
+
</p>
|
| 50 |
+
</div>
|
| 51 |
+
""", unsafe_allow_html=True)
|
| 52 |
+
|
| 53 |
+
# ---- Company Selection ----
|
| 54 |
+
companies_all = list(settings.company_ticker_map.keys())
|
| 55 |
+
|
| 56 |
+
col1, col2 = st.columns([2, 1])
|
| 57 |
+
with col1:
|
| 58 |
+
selected_companies = st.multiselect(
|
| 59 |
+
"Select 2–4 Companies to Compare",
|
| 60 |
+
options=companies_all,
|
| 61 |
+
default=["TCS", "INFOSYS"],
|
| 62 |
+
max_selections=4,
|
| 63 |
+
key="cmp_companies",
|
| 64 |
+
)
|
| 65 |
+
with col2:
|
| 66 |
+
fy_options = ["All Years", "FY2025", "FY2024"]
|
| 67 |
+
selected_fy = st.selectbox("Fiscal Year", fy_options, key="cmp_fy")
|
| 68 |
+
fy_filter = None if selected_fy == "All Years" else selected_fy
|
| 69 |
+
|
| 70 |
+
# Sample comparison queries
|
| 71 |
+
sample_comparisons = [
|
| 72 |
+
"Compare revenue and net profit margins",
|
| 73 |
+
"Which company has better return on equity (ROE)?",
|
| 74 |
+
"Compare employee count and revenue per employee",
|
| 75 |
+
"Compare NPA ratios (for banks)",
|
| 76 |
+
"Compare dividend payout and EPS",
|
| 77 |
+
"Which company has stronger balance sheet?",
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
st.markdown("**Quick comparison templates:**")
|
| 81 |
+
cols = st.columns(3)
|
| 82 |
+
for i, q in enumerate(sample_comparisons):
|
| 83 |
+
with cols[i % 3]:
|
| 84 |
+
if st.button(q, key=f"cmp_template_{i}"):
|
| 85 |
+
st.session_state["cmp_prefill"] = q
|
| 86 |
+
|
| 87 |
+
# ---- Query Input ----
|
| 88 |
+
default_q = st.session_state.pop("cmp_prefill", "")
|
| 89 |
+
compare_query = st.text_area(
|
| 90 |
+
"Comparison question",
|
| 91 |
+
value=default_q,
|
| 92 |
+
placeholder="e.g. Compare revenue growth and net profit margin for the latest fiscal year",
|
| 93 |
+
height=80,
|
| 94 |
+
key="cmp_query",
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
compare_btn = st.button("Run Comparison", type="primary", key="cmp_run")
|
| 98 |
+
|
| 99 |
+
# ---- Comparison Results ----
|
| 100 |
+
if compare_btn:
|
| 101 |
+
if len(selected_companies) < 2:
|
| 102 |
+
st.warning("Please select at least 2 companies to compare.")
|
| 103 |
+
st.stop()
|
| 104 |
+
if not compare_query.strip():
|
| 105 |
+
st.warning("Please enter a comparison question.")
|
| 106 |
+
st.stop()
|
| 107 |
+
|
| 108 |
+
comparator = load_comparator()
|
| 109 |
+
metric_extractor = load_metric_extractor()
|
| 110 |
+
|
| 111 |
+
with st.spinner(f"Retrieving data for {', '.join(selected_companies)}..."):
|
| 112 |
+
company_results, answer_gen = comparator.compare(
|
| 113 |
+
query=compare_query,
|
| 114 |
+
companies=selected_companies,
|
| 115 |
+
fiscal_year=fy_filter,
|
| 116 |
+
stream=True,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
st.markdown("---")
|
| 120 |
+
|
| 121 |
+
# Tabs: Answer | Chart | Raw Data
|
| 122 |
+
tab_answer, tab_chart, tab_data = st.tabs(["📝 Analysis", "📊 Chart", "🔍 Retrieved Data"])
|
| 123 |
+
|
| 124 |
+
with tab_answer:
|
| 125 |
+
st.markdown(f"""
|
| 126 |
+
<div style="font-size:0.8rem;color:#64748b;margin-bottom:0.5rem;">
|
| 127 |
+
Comparing: {' vs '.join(selected_companies)} | {fy_filter or 'All Years'}
|
| 128 |
+
</div>
|
| 129 |
+
""", unsafe_allow_html=True)
|
| 130 |
+
|
| 131 |
+
with st.chat_message("assistant", avatar="📈"):
|
| 132 |
+
answer_text = st.write_stream(answer_gen)
|
| 133 |
+
|
| 134 |
+
# Citations per company
|
| 135 |
+
st.markdown("**Sources:**")
|
| 136 |
+
for company, results in company_results.items():
|
| 137 |
+
chips = "".join(
|
| 138 |
+
f'<span class="citation-chip">{company} Pg.{r.page_number}</span>'
|
| 139 |
+
for r in results
|
| 140 |
+
)
|
| 141 |
+
st.markdown(f"**{company}:** {chips}", unsafe_allow_html=True)
|
| 142 |
+
|
| 143 |
+
with tab_chart:
|
| 144 |
+
st.markdown("*Extracting financial metrics for visualization...*")
|
| 145 |
+
|
| 146 |
+
with st.spinner("Extracting KPIs with LLM..."):
|
| 147 |
+
metrics_list = metric_extractor.extract_multi(company_results)
|
| 148 |
+
comparison_data = metric_extractor.to_comparison_table(metrics_list)
|
| 149 |
+
|
| 150 |
+
companies_in_data = comparison_data.pop("companies", selected_companies)
|
| 151 |
+
|
| 152 |
+
# Find numeric metrics to plot
|
| 153 |
+
plottable = {}
|
| 154 |
+
for metric, values in comparison_data.items():
|
| 155 |
+
numeric_vals = {c: v for c, v in values.items() if v is not None and isinstance(v, (int, float))}
|
| 156 |
+
if len(numeric_vals) >= 2:
|
| 157 |
+
plottable[metric] = numeric_vals
|
| 158 |
+
|
| 159 |
+
if plottable:
|
| 160 |
+
metric_to_plot = st.selectbox(
|
| 161 |
+
"Select metric to chart",
|
| 162 |
+
options=list(plottable.keys()),
|
| 163 |
+
key="cmp_metric_chart",
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
chart_data = plottable[metric_to_plot]
|
| 167 |
+
|
| 168 |
+
# Color palette
|
| 169 |
+
colors = ["#3b82f6", "#06b6d4", "#8b5cf6", "#10b981"]
|
| 170 |
+
|
| 171 |
+
fig = go.Figure()
|
| 172 |
+
fig.add_trace(go.Bar(
|
| 173 |
+
x=list(chart_data.keys()),
|
| 174 |
+
y=list(chart_data.values()),
|
| 175 |
+
marker_color=colors[:len(chart_data)],
|
| 176 |
+
text=[f"{v:,.1f}" for v in chart_data.values()],
|
| 177 |
+
textposition="outside",
|
| 178 |
+
textfont=dict(color="#f1f5f9", size=12),
|
| 179 |
+
))
|
| 180 |
+
|
| 181 |
+
fig.update_layout(
|
| 182 |
+
title=dict(
|
| 183 |
+
text=metric_to_plot,
|
| 184 |
+
font=dict(color="#f1f5f9", size=16),
|
| 185 |
+
),
|
| 186 |
+
paper_bgcolor="rgba(0,0,0,0)",
|
| 187 |
+
plot_bgcolor="rgba(255,255,255,0.03)",
|
| 188 |
+
font=dict(color="#94a3b8"),
|
| 189 |
+
xaxis=dict(
|
| 190 |
+
showgrid=False,
|
| 191 |
+
tickfont=dict(color="#f1f5f9", size=12),
|
| 192 |
+
),
|
| 193 |
+
yaxis=dict(
|
| 194 |
+
gridcolor="rgba(255,255,255,0.06)",
|
| 195 |
+
tickfont=dict(color="#94a3b8"),
|
| 196 |
+
),
|
| 197 |
+
hoverlabel=dict(
|
| 198 |
+
bgcolor="#1e293b",
|
| 199 |
+
font_color="#f1f5f9",
|
| 200 |
+
),
|
| 201 |
+
margin=dict(t=50, b=20, l=20, r=20),
|
| 202 |
+
height=380,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 206 |
+
|
| 207 |
+
# Radar chart if multiple metrics available
|
| 208 |
+
if len(plottable) >= 3:
|
| 209 |
+
st.markdown("**Multi-metric Radar Chart**")
|
| 210 |
+
radar_metrics = list(plottable.keys())[:6]
|
| 211 |
+
|
| 212 |
+
fig_radar = go.Figure()
|
| 213 |
+
for i, company in enumerate(companies_in_data):
|
| 214 |
+
values = []
|
| 215 |
+
for m in radar_metrics:
|
| 216 |
+
v = plottable.get(m, {}).get(company)
|
| 217 |
+
values.append(v if v is not None else 0)
|
| 218 |
+
|
| 219 |
+
# Normalize to 0-100 scale per metric
|
| 220 |
+
maxv = max(max(plottable[m].values(), default=1) for m in radar_metrics)
|
| 221 |
+
norm_values = [v / maxv * 100 if maxv > 0 else 0 for v in values]
|
| 222 |
+
|
| 223 |
+
fig_radar.add_trace(go.Scatterpolar(
|
| 224 |
+
r=norm_values + [norm_values[0]],
|
| 225 |
+
theta=radar_metrics + [radar_metrics[0]],
|
| 226 |
+
fill='toself',
|
| 227 |
+
name=company,
|
| 228 |
+
opacity=0.7,
|
| 229 |
+
line_color=colors[i % len(colors)],
|
| 230 |
+
))
|
| 231 |
+
|
| 232 |
+
fig_radar.update_layout(
|
| 233 |
+
polar=dict(
|
| 234 |
+
bgcolor="rgba(255,255,255,0.02)",
|
| 235 |
+
radialaxis=dict(visible=True, range=[0, 100], tickfont=dict(color="#64748b")),
|
| 236 |
+
angularaxis=dict(tickfont=dict(color="#f1f5f9")),
|
| 237 |
+
),
|
| 238 |
+
paper_bgcolor="rgba(0,0,0,0)",
|
| 239 |
+
font=dict(color="#94a3b8"),
|
| 240 |
+
height=380,
|
| 241 |
+
legend=dict(font=dict(color="#f1f5f9")),
|
| 242 |
+
)
|
| 243 |
+
st.plotly_chart(fig_radar, use_container_width=True)
|
| 244 |
+
else:
|
| 245 |
+
st.info("Could not extract numeric metrics for charting from the available context. The text analysis above still provides the comparison.")
|
| 246 |
+
|
| 247 |
+
with tab_data:
|
| 248 |
+
for company, results in company_results.items():
|
| 249 |
+
with st.expander(f"{company} — {len(results)} chunks retrieved"):
|
| 250 |
+
for chunk in results:
|
| 251 |
+
st.markdown(f"""
|
| 252 |
+
<div style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.07);
|
| 253 |
+
border-radius:8px;padding:0.8rem;margin-bottom:0.5rem;">
|
| 254 |
+
<div style="font-size:0.72rem;color:#64748b;margin-bottom:0.3rem;">
|
| 255 |
+
{chunk.section} | Page {chunk.page_number} | {chunk.content_type} | Score: {chunk.rrf_score:.3f}
|
| 256 |
+
</div>
|
| 257 |
+
<div style="font-size:0.8rem;color:#cbd5e1;white-space:pre-wrap;">{chunk.content[:500]}{"..." if len(chunk.content) > 500 else ""}</div>
|
| 258 |
+
</div>
|
| 259 |
+
""", unsafe_allow_html=True)
|
app/pages/3_Dashboard.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app/pages/3_Dashboard.py
|
| 3 |
+
=========================
|
| 4 |
+
KPI financial dashboard with automatic metric extraction and Plotly visualizations.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
import os
|
| 9 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 10 |
+
from config.settings import settings
|
| 11 |
+
|
| 12 |
+
import streamlit as st
|
| 13 |
+
import plotly.graph_objects as go
|
| 14 |
+
|
| 15 |
+
st.set_page_config(page_title="Dashboard | FinRAG", page_icon="📊", layout="wide")
|
| 16 |
+
|
| 17 |
+
from app.rag_engine import load_retriever, load_reranker, load_metric_extractor
|
| 18 |
+
|
| 19 |
+
# Shared CSS
|
| 20 |
+
st.markdown("""
|
| 21 |
+
<style>
|
| 22 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
|
| 23 |
+
.stApp { background: linear-gradient(135deg, #0a0e1a, #0f1628); font-family: 'Inter', sans-serif; color: #f1f5f9; }
|
| 24 |
+
#MainMenu, footer, header { visibility: hidden; }
|
| 25 |
+
.stButton > button {
|
| 26 |
+
background: linear-gradient(135deg, #10b981, #06b6d4) !important;
|
| 27 |
+
color: white !important; border: none !important; border-radius: 8px !important; font-weight: 600 !important;
|
| 28 |
+
}
|
| 29 |
+
.metric-card {
|
| 30 |
+
background: linear-gradient(135deg, rgba(59,130,246,0.1), rgba(6,182,212,0.05));
|
| 31 |
+
border: 1px solid rgba(59,130,246,0.2); border-radius: 10px; padding: 1rem; text-align: center;
|
| 32 |
+
}
|
| 33 |
+
.metric-value { font-size:1.5rem; font-weight:700; color:#06b6d4; font-family:'JetBrains Mono',monospace; }
|
| 34 |
+
.metric-label { font-size:0.72rem; color:#64748b; margin-top:0.25rem; text-transform:uppercase; letter-spacing:0.05em; }
|
| 35 |
+
.na-metric { color: #475569 !important; }
|
| 36 |
+
</style>
|
| 37 |
+
""", unsafe_allow_html=True)
|
| 38 |
+
|
| 39 |
+
# ---- Header ----
|
| 40 |
+
st.markdown("""
|
| 41 |
+
<div style="padding:1.5rem 0 1rem 0;">
|
| 42 |
+
<h1 style="font-size:1.8rem;font-weight:700;margin:0;
|
| 43 |
+
background:linear-gradient(135deg,#10b981,#06b6d4);
|
| 44 |
+
-webkit-background-clip:text;-webkit-text-fill-color:transparent;">
|
| 45 |
+
📊 KPI Dashboard
|
| 46 |
+
</h1>
|
| 47 |
+
<p style="color:#64748b;font-size:0.9rem;margin-top:0.3rem;">
|
| 48 |
+
Auto-extract financial KPIs from annual reports and visualize with interactive charts.
|
| 49 |
+
</p>
|
| 50 |
+
</div>
|
| 51 |
+
""", unsafe_allow_html=True)
|
| 52 |
+
|
| 53 |
+
# ---- Controls ----
|
| 54 |
+
col1, col2, col3 = st.columns([2, 1, 1])
|
| 55 |
+
with col1:
|
| 56 |
+
companies = list(settings.company_ticker_map.keys())
|
| 57 |
+
selected_company = st.selectbox("Select Company", companies, key="dash_company")
|
| 58 |
+
with col2:
|
| 59 |
+
fy_options = ["FY2025", "FY2024", "All Years"]
|
| 60 |
+
selected_fy = st.selectbox("Fiscal Year", fy_options, key="dash_fy")
|
| 61 |
+
fy_filter = None if selected_fy == "All Years" else selected_fy
|
| 62 |
+
with col3:
|
| 63 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 64 |
+
extract_btn = st.button("Extract KPIs", type="primary", key="dash_extract")
|
| 65 |
+
|
| 66 |
+
# ---- Extraction & Display ----
|
| 67 |
+
if extract_btn:
|
| 68 |
+
retriever = load_retriever()
|
| 69 |
+
reranker = load_reranker()
|
| 70 |
+
extractor = load_metric_extractor()
|
| 71 |
+
|
| 72 |
+
# Retrieve financial statement chunks
|
| 73 |
+
with st.spinner(f"Retrieving financial data for {selected_company}..."):
|
| 74 |
+
# Search specifically for financial metrics
|
| 75 |
+
metric_queries = [
|
| 76 |
+
"revenue net profit income financial performance",
|
| 77 |
+
"balance sheet total assets equity",
|
| 78 |
+
"earnings per share EPS return on equity",
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
all_candidates = []
|
| 82 |
+
for q in metric_queries:
|
| 83 |
+
candidates = retriever.retrieve(
|
| 84 |
+
query=q,
|
| 85 |
+
top_k=20,
|
| 86 |
+
company_filter=selected_company,
|
| 87 |
+
fiscal_year_filter=fy_filter,
|
| 88 |
+
expand_query=False,
|
| 89 |
+
)
|
| 90 |
+
all_candidates.extend(candidates)
|
| 91 |
+
|
| 92 |
+
# Deduplicate
|
| 93 |
+
seen = set()
|
| 94 |
+
unique_candidates = []
|
| 95 |
+
for c in all_candidates:
|
| 96 |
+
if c.chunk_id not in seen:
|
| 97 |
+
seen.add(c.chunk_id)
|
| 98 |
+
unique_candidates.append(c)
|
| 99 |
+
|
| 100 |
+
reranked = reranker.rerank(
|
| 101 |
+
query="financial metrics revenue profit assets equity EPS NPA",
|
| 102 |
+
candidates=unique_candidates,
|
| 103 |
+
top_n=8,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
with st.spinner("Extracting KPIs using AI..."):
|
| 107 |
+
metrics_data = extractor.extract(selected_company, reranked[:4]) # max 4 chunks to stay under token limit
|
| 108 |
+
|
| 109 |
+
metrics = metrics_data.get("metrics", {})
|
| 110 |
+
fiscal_year = metrics_data.get("fiscal_year", selected_fy or "FY2025")
|
| 111 |
+
ticker = settings.company_ticker_map.get(selected_company, selected_company)
|
| 112 |
+
|
| 113 |
+
# ---- Company header ----
|
| 114 |
+
st.markdown("---")
|
| 115 |
+
st.markdown(f"""
|
| 116 |
+
<div style="display:flex;align-items:center;gap:1rem;margin-bottom:1.5rem;">
|
| 117 |
+
<div style="background:linear-gradient(135deg,#1e293b,#0f172a);border:1px solid rgba(255,255,255,0.1);
|
| 118 |
+
border-radius:10px;padding:0.8rem 1.2rem;">
|
| 119 |
+
<div style="font-size:1.4rem;font-weight:700;color:#f1f5f9;">{selected_company}</div>
|
| 120 |
+
<div style="font-size:0.8rem;color:#3b82f6;font-family:monospace;">{ticker}</div>
|
| 121 |
+
</div>
|
| 122 |
+
<div>
|
| 123 |
+
<div style="font-size:0.75rem;color:#64748b;text-transform:uppercase;letter-spacing:0.1em;">Fiscal Year</div>
|
| 124 |
+
<div style="font-size:1.1rem;font-weight:600;color:#06b6d4;">{fiscal_year}</div>
|
| 125 |
+
</div>
|
| 126 |
+
</div>
|
| 127 |
+
""", unsafe_allow_html=True)
|
| 128 |
+
|
| 129 |
+
# ---- KPI Metric Cards ----
|
| 130 |
+
def fmt_crore(v):
|
| 131 |
+
if v is None: return "N/A"
|
| 132 |
+
if v >= 100000: return f"₹{v/100000:.2f}L Cr"
|
| 133 |
+
if v >= 1000: return f"₹{v:,.0f} Cr"
|
| 134 |
+
return f"₹{v:.1f} Cr"
|
| 135 |
+
|
| 136 |
+
def fmt_pct(v):
|
| 137 |
+
return f"{v:.2f}%" if v is not None else "N/A"
|
| 138 |
+
|
| 139 |
+
def fmt_plain(v):
|
| 140 |
+
return f"{v:.2f}" if v is not None else "N/A"
|
| 141 |
+
|
| 142 |
+
# Row 1: Revenue metrics
|
| 143 |
+
st.markdown("**Revenue & Profitability**")
|
| 144 |
+
r1c1, r1c2, r1c3, r1c4 = st.columns(4)
|
| 145 |
+
with r1c1:
|
| 146 |
+
v = metrics.get("revenue_crore")
|
| 147 |
+
st.markdown(f'<div class="metric-card"><div class="metric-value {"na-metric" if v is None else ""}">{fmt_crore(v)}</div><div class="metric-label">Revenue</div></div>', unsafe_allow_html=True)
|
| 148 |
+
with r1c2:
|
| 149 |
+
v = metrics.get("net_profit_crore")
|
| 150 |
+
st.markdown(f'<div class="metric-card"><div class="metric-value {"na-metric" if v is None else ""}">{fmt_crore(v)}</div><div class="metric-label">Net Profit</div></div>', unsafe_allow_html=True)
|
| 151 |
+
with r1c3:
|
| 152 |
+
v = metrics.get("net_profit_margin_pct")
|
| 153 |
+
st.markdown(f'<div class="metric-card"><div class="metric-value {"na-metric" if v is None else ""}">{fmt_pct(v)}</div><div class="metric-label">Net Margin</div></div>', unsafe_allow_html=True)
|
| 154 |
+
with r1c4:
|
| 155 |
+
v = metrics.get("ebitda_margin_pct")
|
| 156 |
+
st.markdown(f'<div class="metric-card"><div class="metric-value {"na-metric" if v is None else ""}">{fmt_pct(v)}</div><div class="metric-label">EBITDA Margin</div></div>', unsafe_allow_html=True)
|
| 157 |
+
|
| 158 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 159 |
+
|
| 160 |
+
# Row 2: Balance sheet
|
| 161 |
+
st.markdown("**Balance Sheet**")
|
| 162 |
+
r2c1, r2c2, r2c3, r2c4 = st.columns(4)
|
| 163 |
+
with r2c1:
|
| 164 |
+
v = metrics.get("total_assets_crore")
|
| 165 |
+
st.markdown(f'<div class="metric-card"><div class="metric-value {"na-metric" if v is None else ""}">{fmt_crore(v)}</div><div class="metric-label">Total Assets</div></div>', unsafe_allow_html=True)
|
| 166 |
+
with r2c2:
|
| 167 |
+
v = metrics.get("equity_crore")
|
| 168 |
+
st.markdown(f'<div class="metric-card"><div class="metric-value {"na-metric" if v is None else ""}">{fmt_crore(v)}</div><div class="metric-label">Equity</div></div>', unsafe_allow_html=True)
|
| 169 |
+
with r2c3:
|
| 170 |
+
v = metrics.get("eps_inr")
|
| 171 |
+
st.markdown(f'<div class="metric-card"><div class="metric-value {"na-metric" if v is None else ""}">{"₹"+fmt_plain(v) if v is not None else "N/A"}</div><div class="metric-label">EPS</div></div>', unsafe_allow_html=True)
|
| 172 |
+
with r2c4:
|
| 173 |
+
v = metrics.get("roe_pct")
|
| 174 |
+
st.markdown(f'<div class="metric-card"><div class="metric-value {"na-metric" if v is None else ""}">{fmt_pct(v)}</div><div class="metric-label">ROE</div></div>', unsafe_allow_html=True)
|
| 175 |
+
|
| 176 |
+
# Banking metrics (if applicable)
|
| 177 |
+
if selected_company in {"HDFC", "ICICI", "AXIS", "SBI", "KOTAK", "KVB"}:
|
| 178 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 179 |
+
st.markdown("**Banking Metrics**")
|
| 180 |
+
rb1, rb2, rb3 = st.columns(3)
|
| 181 |
+
with rb1:
|
| 182 |
+
v = metrics.get("npa_gross_pct")
|
| 183 |
+
st.markdown(f'<div class="metric-card" style="border-color:rgba(239,68,68,0.3)"><div class="metric-value {"na-metric" if v is None else ""}" style="{"color:#f87171" if v and v > 3 else ""}">{fmt_pct(v)}</div><div class="metric-label">Gross NPA</div></div>', unsafe_allow_html=True)
|
| 184 |
+
with rb2:
|
| 185 |
+
v = metrics.get("npa_net_pct")
|
| 186 |
+
st.markdown(f'<div class="metric-card" style="border-color:rgba(239,68,68,0.3)"><div class="metric-value {"na-metric" if v is None else ""}">{fmt_pct(v)}</div><div class="metric-label">Net NPA</div></div>', unsafe_allow_html=True)
|
| 187 |
+
with rb3:
|
| 188 |
+
v = metrics.get("nim_pct")
|
| 189 |
+
st.markdown(f'<div class="metric-card"><div class="metric-value {"na-metric" if v is None else ""}">{fmt_pct(v)}</div><div class="metric-label">Net Interest Margin</div></div>', unsafe_allow_html=True)
|
| 190 |
+
|
| 191 |
+
# ---- Plotly Chart ----
|
| 192 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 193 |
+
st.markdown("**Financial Overview Chart**")
|
| 194 |
+
|
| 195 |
+
chart_data = {}
|
| 196 |
+
label_map = {
|
| 197 |
+
"revenue_crore": "Revenue",
|
| 198 |
+
"net_profit_crore": "Net Profit",
|
| 199 |
+
"ebitda_crore": "EBITDA",
|
| 200 |
+
"total_assets_crore": "Total Assets",
|
| 201 |
+
"equity_crore": "Equity",
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
for key, label in label_map.items():
|
| 205 |
+
v = metrics.get(key)
|
| 206 |
+
if v is not None:
|
| 207 |
+
chart_data[label] = v
|
| 208 |
+
|
| 209 |
+
if chart_data:
|
| 210 |
+
colors_list = ["#3b82f6", "#06b6d4", "#8b5cf6", "#10b981", "#f59e0b"]
|
| 211 |
+
fig = go.Figure(go.Bar(
|
| 212 |
+
y=list(chart_data.keys()),
|
| 213 |
+
x=list(chart_data.values()),
|
| 214 |
+
orientation="h",
|
| 215 |
+
marker=dict(
|
| 216 |
+
color=colors_list[:len(chart_data)],
|
| 217 |
+
opacity=0.85,
|
| 218 |
+
),
|
| 219 |
+
text=[f"₹{v:,.0f} Cr" for v in chart_data.values()],
|
| 220 |
+
textposition="outside",
|
| 221 |
+
textfont=dict(color="#f1f5f9", size=11),
|
| 222 |
+
))
|
| 223 |
+
fig.update_layout(
|
| 224 |
+
paper_bgcolor="rgba(0,0,0,0)",
|
| 225 |
+
plot_bgcolor="rgba(255,255,255,0.02)",
|
| 226 |
+
font=dict(color="#94a3b8"),
|
| 227 |
+
xaxis=dict(gridcolor="rgba(255,255,255,0.05)", tickfont=dict(color="#94a3b8")),
|
| 228 |
+
yaxis=dict(tickfont=dict(color="#f1f5f9", size=12)),
|
| 229 |
+
margin=dict(t=10, b=20, l=20, r=80),
|
| 230 |
+
height=300,
|
| 231 |
+
)
|
| 232 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 233 |
+
else:
|
| 234 |
+
st.info("Monetary metrics not available for charting. Check the KPI cards above.")
|
| 235 |
+
|
| 236 |
+
# ---- Source citation ----
|
| 237 |
+
st.markdown("---")
|
| 238 |
+
st.caption(f"Source: {metrics_data.get('source_citation', f'{selected_company} BSE Annual Report {fiscal_year}')}")
|
| 239 |
+
with st.expander("Retrieved document chunks used for extraction"):
|
| 240 |
+
for chunk in reranked:
|
| 241 |
+
st.markdown(f"**Page {chunk.page_number}** | {chunk.section} | {chunk.content_type}")
|
| 242 |
+
st.code(chunk.content[:400], language=None)
|
app/pages/__init__.py
ADDED
|
File without changes
|
app/rag_engine.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app/rag_engine.py
|
| 3 |
+
==================
|
| 4 |
+
Shared cached resource loaders for all Streamlit pages.
|
| 5 |
+
Import from here instead of app.main to avoid page_config conflicts.
|
| 6 |
+
"""
|
| 7 |
+
import sys
|
| 8 |
+
import os
|
| 9 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 10 |
+
from config.settings import settings
|
| 11 |
+
|
| 12 |
+
import streamlit as st
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@st.cache_resource(show_spinner="Loading embedding model (first time ~30s)...")
|
| 16 |
+
def load_embedder():
|
| 17 |
+
from src.embeddings.embedder import Embedder
|
| 18 |
+
return Embedder()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@st.cache_resource(show_spinner="Connecting to vector store...")
|
| 22 |
+
def load_retriever():
|
| 23 |
+
from src.retrieval.hybrid_retriever import HybridRetriever
|
| 24 |
+
from src.vectorstore.qdrant_store import QdrantStore
|
| 25 |
+
from src.vectorstore.bm25_index import BM25Index
|
| 26 |
+
qdrant = QdrantStore()
|
| 27 |
+
bm25 = BM25Index()
|
| 28 |
+
embedder = load_embedder()
|
| 29 |
+
return HybridRetriever(qdrant_store=qdrant, bm25_index=bm25, embedder=embedder)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@st.cache_resource(show_spinner="Loading reranker model...")
|
| 33 |
+
def load_reranker():
|
| 34 |
+
from src.retrieval.reranker import Reranker
|
| 35 |
+
return Reranker()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@st.cache_resource
|
| 39 |
+
def load_groq():
|
| 40 |
+
from src.generation.groq_client import GroqClient
|
| 41 |
+
return GroqClient()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@st.cache_resource
|
| 45 |
+
def load_comparator():
|
| 46 |
+
from src.comparison.company_comparator import CompanyComparator
|
| 47 |
+
return CompanyComparator(
|
| 48 |
+
retriever=load_retriever(),
|
| 49 |
+
reranker=load_reranker(),
|
| 50 |
+
groq_client=load_groq(),
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@st.cache_resource
|
| 55 |
+
def load_metric_extractor():
|
| 56 |
+
from src.metrics.metric_extractor import MetricExtractor
|
| 57 |
+
return MetricExtractor(groq_client=load_groq())
|
app/static/index.html
ADDED
|
@@ -0,0 +1,1306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>FinRAG — Indian Markets Intelligence</title>
|
| 7 |
+
<meta name="description" content="AI-powered financial Q&A over BSE annual reports of major Indian companies">
|
| 8 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 9 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
|
| 10 |
+
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
| 11 |
+
<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
|
| 12 |
+
<style>
|
| 13 |
+
/* ═══════════════════════════════════════════
|
| 14 |
+
RESET & TOKENS
|
| 15 |
+
═══════════════════════════════════════════ */
|
| 16 |
+
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
| 17 |
+
|
| 18 |
+
:root {
|
| 19 |
+
--bg: #0d0f17;
|
| 20 |
+
--bg-sidebar: #0a0c13;
|
| 21 |
+
--bg-input: #131620;
|
| 22 |
+
--bg-msg: #111420;
|
| 23 |
+
--bg-hover: rgba(255,255,255,0.04);
|
| 24 |
+
--bg-active: rgba(59,130,246,0.1);
|
| 25 |
+
--border: rgba(255,255,255,0.07);
|
| 26 |
+
--border-blue: rgba(59,130,246,0.3);
|
| 27 |
+
--text: #e2e8f0;
|
| 28 |
+
--text-muted: #64748b;
|
| 29 |
+
--text-dim: #334155;
|
| 30 |
+
--accent: #3b82f6;
|
| 31 |
+
--accent2: #06b6d4;
|
| 32 |
+
--accent3: #8b5cf6;
|
| 33 |
+
--green: #10b981;
|
| 34 |
+
--red: #ef4444;
|
| 35 |
+
--amber: #f59e0b;
|
| 36 |
+
--radius: 10px;
|
| 37 |
+
--sidebar-w: 260px;
|
| 38 |
+
--font: 'Inter', -apple-system, sans-serif;
|
| 39 |
+
--mono: 'JetBrains Mono', monospace;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
html, body {
|
| 43 |
+
height: 100%; width: 100%;
|
| 44 |
+
font-family: var(--font);
|
| 45 |
+
background: var(--bg);
|
| 46 |
+
color: var(--text);
|
| 47 |
+
overflow: hidden;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
/* ═══════════════════════════════════════════
|
| 51 |
+
LAYOUT
|
| 52 |
+
═══════════════════════════════════════════ */
|
| 53 |
+
#app { display: flex; height: 100vh; width: 100vw; overflow: hidden; }
|
| 54 |
+
|
| 55 |
+
/* ── Sidebar ── */
|
| 56 |
+
#sidebar {
|
| 57 |
+
width: var(--sidebar-w);
|
| 58 |
+
min-width: var(--sidebar-w);
|
| 59 |
+
background: var(--bg-sidebar);
|
| 60 |
+
border-right: 1px solid var(--border);
|
| 61 |
+
display: flex;
|
| 62 |
+
flex-direction: column;
|
| 63 |
+
overflow: hidden;
|
| 64 |
+
transition: width 0.22s cubic-bezier(0.4,0,0.2,1),
|
| 65 |
+
min-width 0.22s cubic-bezier(0.4,0,0.2,1);
|
| 66 |
+
position: relative;
|
| 67 |
+
z-index: 10;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
#sidebar.collapsed { width: 0; min-width: 0; }
|
| 71 |
+
|
| 72 |
+
/* ── Main ── */
|
| 73 |
+
#main {
|
| 74 |
+
flex: 1;
|
| 75 |
+
display: flex;
|
| 76 |
+
flex-direction: column;
|
| 77 |
+
overflow: hidden;
|
| 78 |
+
position: relative;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
/* ═══════════════════════════════════════════
|
| 82 |
+
SIDEBAR INTERNALS
|
| 83 |
+
═══════════════════════════════════════════ */
|
| 84 |
+
.sb-top {
|
| 85 |
+
padding: 1rem 0.85rem 0.6rem;
|
| 86 |
+
flex-shrink: 0;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
.brand {
|
| 90 |
+
display: flex; align-items: center; gap: 0.6rem;
|
| 91 |
+
padding: 0.2rem 0 0.8rem;
|
| 92 |
+
}
|
| 93 |
+
.brand-icon { font-size: 1.3rem; }
|
| 94 |
+
.brand-name {
|
| 95 |
+
font-size: 1rem; font-weight: 700; letter-spacing: -0.02em;
|
| 96 |
+
background: linear-gradient(135deg, var(--accent), var(--accent2));
|
| 97 |
+
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
|
| 98 |
+
}
|
| 99 |
+
.brand-sub { font-size: 0.6rem; color: var(--text-dim); text-transform: uppercase; letter-spacing: 0.08em; }
|
| 100 |
+
|
| 101 |
+
.new-chat-btn {
|
| 102 |
+
width: 100%; padding: 0.55rem 0.8rem;
|
| 103 |
+
background: rgba(255,255,255,0.05);
|
| 104 |
+
border: 1px solid var(--border);
|
| 105 |
+
border-radius: var(--radius);
|
| 106 |
+
color: var(--text); font-family: var(--font); font-size: 0.83rem; font-weight: 500;
|
| 107 |
+
cursor: pointer; display: flex; align-items: center; gap: 0.5rem;
|
| 108 |
+
transition: background 0.15s, border-color 0.15s;
|
| 109 |
+
}
|
| 110 |
+
.new-chat-btn:hover {
|
| 111 |
+
background: rgba(255,255,255,0.08); border-color: rgba(255,255,255,0.15);
|
| 112 |
+
}
|
| 113 |
+
.new-chat-btn .plus { font-size: 1.1rem; font-weight: 300; color: var(--accent2); }
|
| 114 |
+
|
| 115 |
+
.sb-divider { height: 1px; background: var(--border); margin: 0.5rem 0; }
|
| 116 |
+
|
| 117 |
+
.sb-scroll {
|
| 118 |
+
flex: 1; overflow-y: auto; overflow-x: hidden;
|
| 119 |
+
padding: 0 0.5rem;
|
| 120 |
+
}
|
| 121 |
+
.sb-scroll::-webkit-scrollbar { width: 3px; }
|
| 122 |
+
.sb-scroll::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.08); border-radius: 2px; }
|
| 123 |
+
|
| 124 |
+
.group-label {
|
| 125 |
+
font-size: 0.65rem; font-weight: 600; color: var(--text-dim);
|
| 126 |
+
text-transform: uppercase; letter-spacing: 0.08em;
|
| 127 |
+
padding: 0.7rem 0.4rem 0.25rem;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
.hist-item {
|
| 131 |
+
display: flex; align-items: center; gap: 0.4rem;
|
| 132 |
+
padding: 0.42rem 0.6rem; border-radius: 7px;
|
| 133 |
+
font-size: 0.8rem; color: var(--text-muted);
|
| 134 |
+
cursor: pointer; overflow: hidden; white-space: nowrap;
|
| 135 |
+
text-overflow: ellipsis;
|
| 136 |
+
transition: background 0.12s, color 0.12s;
|
| 137 |
+
user-select: none;
|
| 138 |
+
}
|
| 139 |
+
.hist-item:hover { background: var(--bg-hover); color: var(--text); }
|
| 140 |
+
.hist-item.active { background: var(--bg-active); color: #93c5fd; }
|
| 141 |
+
.hist-item .icon { font-size: 0.75rem; flex-shrink: 0; }
|
| 142 |
+
.hist-item .title { overflow: hidden; text-overflow: ellipsis; flex: 1; }
|
| 143 |
+
.hist-item .del {
|
| 144 |
+
flex-shrink: 0; font-size: 0.85rem;
|
| 145 |
+
color: var(--text-dim); opacity: 0.35;
|
| 146 |
+
padding: 0.1rem 0.3rem; border-radius: 4px;
|
| 147 |
+
transition: opacity 0.15s, color 0.15s, background 0.15s;
|
| 148 |
+
cursor: pointer;
|
| 149 |
+
}
|
| 150 |
+
.hist-item:hover .del { opacity: 1; color: var(--red); }
|
| 151 |
+
.hist-item .del:hover { background: rgba(239,68,68,0.12); }
|
| 152 |
+
|
| 153 |
+
.sb-footer {
|
| 154 |
+
padding: 0.6rem 0.85rem;
|
| 155 |
+
border-top: 1px solid var(--border);
|
| 156 |
+
flex-shrink: 0;
|
| 157 |
+
font-size: 0.65rem; color: var(--text-dim); line-height: 1.7;
|
| 158 |
+
letter-spacing: 0.02em;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
/* ═══════════════════════════════════════════
|
| 162 |
+
TOPBAR
|
| 163 |
+
═══════════════════════════════════════════ */
|
| 164 |
+
#topbar {
|
| 165 |
+
display: flex; align-items: center; gap: 0.75rem;
|
| 166 |
+
padding: 0.7rem 1.2rem;
|
| 167 |
+
border-bottom: 1px solid var(--border);
|
| 168 |
+
flex-shrink: 0;
|
| 169 |
+
background: rgba(13,15,23,0.85);
|
| 170 |
+
backdrop-filter: blur(10px);
|
| 171 |
+
-webkit-backdrop-filter: blur(10px);
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
.toggle-btn {
|
| 175 |
+
background: none; border: none; cursor: pointer;
|
| 176 |
+
color: var(--text-muted); padding: 0.3rem; border-radius: 6px;
|
| 177 |
+
font-size: 1rem; transition: background 0.12s, color 0.12s;
|
| 178 |
+
flex-shrink: 0;
|
| 179 |
+
}
|
| 180 |
+
.toggle-btn:hover { background: var(--bg-hover); color: var(--text); }
|
| 181 |
+
|
| 182 |
+
/* Mode tabs */
|
| 183 |
+
.mode-tabs { display: flex; gap: 0.2rem; background: rgba(255,255,255,0.04); border-radius: 8px; padding: 0.2rem; }
|
| 184 |
+
.mode-tab {
|
| 185 |
+
padding: 0.3rem 0.9rem; border-radius: 6px;
|
| 186 |
+
font-size: 0.78rem; font-weight: 500; color: var(--text-muted);
|
| 187 |
+
cursor: pointer; border: none; background: none; font-family: var(--font);
|
| 188 |
+
transition: all 0.15s; white-space: nowrap; letter-spacing: 0.01em;
|
| 189 |
+
}
|
| 190 |
+
.mode-tab.active { background: rgba(59,130,246,0.18); color: #93c5fd; }
|
| 191 |
+
.mode-tab:hover:not(.active) { color: var(--text); }
|
| 192 |
+
|
| 193 |
+
/* Context selects */
|
| 194 |
+
.ctx-row { display: flex; align-items: center; gap: 0.5rem; margin-left: auto; }
|
| 195 |
+
.ctx-select {
|
| 196 |
+
background: rgba(255,255,255,0.05); border: 1px solid var(--border);
|
| 197 |
+
border-radius: 7px; color: var(--text); font-family: var(--font);
|
| 198 |
+
font-size: 0.78rem; padding: 0.3rem 0.6rem; cursor: pointer;
|
| 199 |
+
outline: none; transition: border-color 0.15s;
|
| 200 |
+
}
|
| 201 |
+
.ctx-select:focus { border-color: var(--border-blue); }
|
| 202 |
+
.ctx-select option { background: #1e2538; }
|
| 203 |
+
|
| 204 |
+
/* Multi-company select for compare */
|
| 205 |
+
.multi-company-bar {
|
| 206 |
+
display: flex; gap: 0.3rem; align-items: center; flex-wrap: wrap;
|
| 207 |
+
}
|
| 208 |
+
.co-pill {
|
| 209 |
+
display: flex; align-items: center; gap: 0.25rem;
|
| 210 |
+
background: rgba(59,130,246,0.12); border: 1px solid var(--border-blue);
|
| 211 |
+
border-radius: 20px; padding: 0.18rem 0.55rem;
|
| 212 |
+
font-size: 0.72rem; color: #93c5fd; font-family: var(--mono);
|
| 213 |
+
}
|
| 214 |
+
.co-pill .rm { cursor: pointer; opacity: 0.6; transition: opacity 0.1s; }
|
| 215 |
+
.co-pill .rm:hover { opacity: 1; }
|
| 216 |
+
.add-company-btn {
|
| 217 |
+
background: rgba(255,255,255,0.04); border: 1px dashed var(--border);
|
| 218 |
+
border-radius: 20px; padding: 0.18rem 0.7rem;
|
| 219 |
+
font-size: 0.72rem; color: var(--text-muted); cursor: pointer;
|
| 220 |
+
font-family: var(--font); transition: all 0.15s;
|
| 221 |
+
}
|
| 222 |
+
.add-company-btn:hover { border-color: var(--border-blue); color: var(--accent2); }
|
| 223 |
+
|
| 224 |
+
.extract-btn {
|
| 225 |
+
padding: 0.35rem 1rem; border-radius: 7px;
|
| 226 |
+
background: linear-gradient(135deg, var(--accent), var(--accent2));
|
| 227 |
+
border: none; color: #fff; font-family: var(--font);
|
| 228 |
+
font-size: 0.78rem; font-weight: 600; cursor: pointer;
|
| 229 |
+
transition: opacity 0.15s; white-space: nowrap;
|
| 230 |
+
}
|
| 231 |
+
.extract-btn:hover { opacity: 0.85; }
|
| 232 |
+
.extract-btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
| 233 |
+
|
| 234 |
+
/* ═══════════════════════════════════════════
|
| 235 |
+
CHAT THREAD
|
| 236 |
+
═══════════════════════════════════════════ */
|
| 237 |
+
#thread {
|
| 238 |
+
flex: 1; overflow-y: auto; overflow-x: hidden;
|
| 239 |
+
padding: 1.5rem 0 2rem;
|
| 240 |
+
scroll-behavior: smooth;
|
| 241 |
+
}
|
| 242 |
+
#thread::-webkit-scrollbar { width: 4px; }
|
| 243 |
+
#thread::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.07); border-radius: 2px; }
|
| 244 |
+
|
| 245 |
+
/* welcome */
|
| 246 |
+
#welcome {
|
| 247 |
+
display: flex; flex-direction: column; align-items: center;
|
| 248 |
+
justify-content: center; min-height: 70vh;
|
| 249 |
+
padding: 2rem; text-align: center; gap: 1rem;
|
| 250 |
+
animation: fadeUp 0.4s ease;
|
| 251 |
+
}
|
| 252 |
+
.wlc-logo { font-size: 3.2rem; margin-bottom: 0.3rem; }
|
| 253 |
+
.wlc-title {
|
| 254 |
+
font-size: 2.2rem; font-weight: 800; letter-spacing: -0.04em;
|
| 255 |
+
background: linear-gradient(135deg, var(--accent) 0%, var(--accent2) 50%, var(--accent3) 100%);
|
| 256 |
+
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
|
| 257 |
+
line-height: 1.1;
|
| 258 |
+
}
|
| 259 |
+
.wlc-sub { font-size: 0.95rem; color: var(--text-muted); max-width: 420px; line-height: 1.65; }
|
| 260 |
+
.sug-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0.55rem; max-width: 580px; width: 100%; margin-top: 0.5rem; }
|
| 261 |
+
.sug-card {
|
| 262 |
+
background: rgba(255,255,255,0.03); border: 1px solid var(--border);
|
| 263 |
+
border-radius: var(--radius); padding: 0.85rem 1rem;
|
| 264 |
+
text-align: left; cursor: pointer;
|
| 265 |
+
transition: background 0.15s, border-color 0.15s, transform 0.12s;
|
| 266 |
+
user-select: none;
|
| 267 |
+
}
|
| 268 |
+
.sug-card:hover {
|
| 269 |
+
background: rgba(59,130,246,0.07); border-color: var(--border-blue);
|
| 270 |
+
transform: translateY(-1px);
|
| 271 |
+
}
|
| 272 |
+
.sug-icon { font-size: 1rem; margin-bottom: 0.3rem; display: block; }
|
| 273 |
+
.sug-text { font-size: 0.8rem; color: var(--text-muted); line-height: 1.4; }
|
| 274 |
+
|
| 275 |
+
/* Message wrapper */
|
| 276 |
+
.msg-wrap {
|
| 277 |
+
max-width: 780px; margin: 0 auto; padding: 0 1.5rem;
|
| 278 |
+
animation: fadeUp 0.25s ease;
|
| 279 |
+
}
|
| 280 |
+
.msg-wrap + .msg-wrap { margin-top: 0.15rem; }
|
| 281 |
+
|
| 282 |
+
/* User message */
|
| 283 |
+
.msg-user {
|
| 284 |
+
display: flex; justify-content: flex-end; margin: 0.8rem 0 0.3rem;
|
| 285 |
+
}
|
| 286 |
+
.msg-user .bubble {
|
| 287 |
+
background: linear-gradient(135deg, rgba(59,130,246,0.2), rgba(6,182,212,0.12));
|
| 288 |
+
border: 1px solid rgba(59,130,246,0.2);
|
| 289 |
+
border-radius: 14px 14px 3px 14px;
|
| 290 |
+
padding: 0.7rem 1rem; max-width: 75%;
|
| 291 |
+
font-size: 0.9rem; line-height: 1.6; color: #dbeafe;
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
/* Assistant message */
|
| 295 |
+
.msg-asst { display: flex; gap: 0.75rem; margin: 0.5rem 0; }
|
| 296 |
+
.asst-avatar {
|
| 297 |
+
width: 30px; height: 30px; border-radius: 8px; flex-shrink: 0;
|
| 298 |
+
background: linear-gradient(135deg, var(--accent), var(--accent2));
|
| 299 |
+
display: flex; align-items: center; justify-content: center;
|
| 300 |
+
font-size: 0.85rem; margin-top: 0.15rem;
|
| 301 |
+
}
|
| 302 |
+
.asst-body { flex: 1; min-width: 0; }
|
| 303 |
+
.asst-name { font-size: 0.72rem; color: var(--text-dim); margin-bottom: 0.3rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; }
|
| 304 |
+
.asst-content { font-size: 0.9rem; line-height: 1.75; color: #cbd5e1; }
|
| 305 |
+
.asst-content p { margin-bottom: 0.6rem; }
|
| 306 |
+
.asst-content p:last-child { margin-bottom: 0; }
|
| 307 |
+
.asst-content strong { color: #e2e8f0; font-weight: 600; }
|
| 308 |
+
.asst-content em { color: var(--accent2); }
|
| 309 |
+
.asst-content ul, .asst-content ol { padding-left: 1.4rem; margin: 0.4rem 0; }
|
| 310 |
+
.asst-content li { margin: 0.2rem 0; }
|
| 311 |
+
.asst-content table { width: 100%; border-collapse: collapse; margin: 0.6rem 0; font-size: 0.83rem; }
|
| 312 |
+
.asst-content th { background: rgba(59,130,246,0.1); border: 1px solid var(--border-blue); padding: 0.4rem 0.7rem; text-align: left; color: #93c5fd; }
|
| 313 |
+
.asst-content td { border: 1px solid var(--border); padding: 0.35rem 0.7rem; color: var(--text-muted); }
|
| 314 |
+
.asst-content tr:nth-child(even) td { background: rgba(255,255,255,0.02); }
|
| 315 |
+
.asst-content code { background: rgba(255,255,255,0.08); border-radius: 4px; padding: 0.1em 0.35em; font-family: var(--mono); font-size: 0.85em; color: var(--accent2); }
|
| 316 |
+
.asst-content pre { background: rgba(0,0,0,0.3); border: 1px solid var(--border); border-radius: 8px; padding: 0.8rem 1rem; overflow-x: auto; margin: 0.5rem 0; }
|
| 317 |
+
.asst-content h3, .asst-content h4 { color: #e2e8f0; margin: 0.8rem 0 0.3rem; font-weight: 600; }
|
| 318 |
+
|
| 319 |
+
/* Typing cursor */
|
| 320 |
+
.cursor {
|
| 321 |
+
display: inline-block; width: 2px; height: 1em;
|
| 322 |
+
background: var(--accent2); margin-left: 2px;
|
| 323 |
+
vertical-align: middle; border-radius: 1px;
|
| 324 |
+
animation: blink 0.9s infinite;
|
| 325 |
+
}
|
| 326 |
+
@keyframes blink { 0%,50% { opacity: 1; } 51%,100% { opacity: 0; } }
|
| 327 |
+
|
| 328 |
+
/* Sources */
|
| 329 |
+
.sources-bar {
|
| 330 |
+
display: flex; flex-wrap: wrap; gap: 0.3rem;
|
| 331 |
+
margin-top: 0.7rem; padding-top: 0.6rem;
|
| 332 |
+
border-top: 1px solid var(--border);
|
| 333 |
+
}
|
| 334 |
+
.src-chip {
|
| 335 |
+
background: rgba(59,130,246,0.08); border: 1px solid rgba(59,130,246,0.3);
|
| 336 |
+
border-radius: 5px; padding: 0.15rem 0.5rem;
|
| 337 |
+
font-size: 0.67rem; color: #93c5fd; font-family: var(--mono);
|
| 338 |
+
transition: all 0.12s; text-decoration: none; cursor: pointer;
|
| 339 |
+
}
|
| 340 |
+
.src-chip:hover { background: rgba(59,130,246,0.15); border-color: rgba(59,130,246,0.5); }
|
| 341 |
+
|
| 342 |
+
/* KPI Grid */
|
| 343 |
+
.kpi-section { margin: 0.8rem 0; }
|
| 344 |
+
.kpi-section-title { font-size: 0.7rem; color: var(--text-dim); text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 0.5rem; }
|
| 345 |
+
.kpi-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.55rem; margin-bottom: 0.55rem; }
|
| 346 |
+
.kpi-card {
|
| 347 |
+
background: rgba(255,255,255,0.03); border: 1px solid var(--border);
|
| 348 |
+
border-radius: 9px; padding: 0.8rem 0.9rem; text-align: center;
|
| 349 |
+
transition: border-color 0.15s;
|
| 350 |
+
}
|
| 351 |
+
.kpi-card.has-val { border-color: rgba(59,130,246,0.2); }
|
| 352 |
+
.kpi-card .val {
|
| 353 |
+
font-size: 1.15rem; font-weight: 700; font-family: var(--mono);
|
| 354 |
+
color: var(--accent2); line-height: 1.2; margin-bottom: 0.25rem;
|
| 355 |
+
}
|
| 356 |
+
.kpi-card .val.na { color: var(--text-dim); font-size: 0.85rem; font-family: var(--font); }
|
| 357 |
+
.kpi-card .val.text-green { color: #10b981; }
|
| 358 |
+
.kpi-card .val.text-red { color: #ef4444; }
|
| 359 |
+
.kpi-card .lbl { font-size: 0.63rem; color: var(--text-dim); text-transform: uppercase; letter-spacing: 0.05em; }
|
| 360 |
+
|
| 361 |
+
/* chart wrapper */
|
| 362 |
+
.chart-wrap { margin: 0.5rem 0; border-radius: var(--radius); overflow: hidden; }
|
| 363 |
+
|
| 364 |
+
/* Spinner */
|
| 365 |
+
.spin-row { display: flex; align-items: center; gap: 0.5rem; padding: 0.4rem 0; font-size: 0.8rem; color: var(--text-dim); }
|
| 366 |
+
.spinner {
|
| 367 |
+
width: 14px; height: 14px; border: 2px solid rgba(59,130,246,0.15);
|
| 368 |
+
border-top-color: var(--accent); border-radius: 50%;
|
| 369 |
+
animation: spin 0.7s linear infinite; flex-shrink: 0;
|
| 370 |
+
}
|
| 371 |
+
@keyframes spin { to { transform: rotate(360deg); } }
|
| 372 |
+
|
| 373 |
+
/* ═══════════════════════════════════════════
|
| 374 |
+
INPUT AREA
|
| 375 |
+
═══════════════════════════════════════════ */
|
| 376 |
+
#input-area {
|
| 377 |
+
flex-shrink: 0;
|
| 378 |
+
padding: 0.8rem 1.5rem 1.2rem;
|
| 379 |
+
background: linear-gradient(to top, var(--bg) 80%, transparent);
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
.input-wrap {
|
| 383 |
+
max-width: 780px; margin: 0 auto;
|
| 384 |
+
background: var(--bg-input);
|
| 385 |
+
border: 1px solid var(--border);
|
| 386 |
+
border-radius: 14px;
|
| 387 |
+
transition: border-color 0.2s, box-shadow 0.2s;
|
| 388 |
+
display: flex; flex-direction: column;
|
| 389 |
+
}
|
| 390 |
+
.input-wrap:focus-within {
|
| 391 |
+
border-color: var(--border-blue);
|
| 392 |
+
box-shadow: 0 0 0 3px rgba(59,130,246,0.08);
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
.input-row {
|
| 396 |
+
display: flex; align-items: flex-end; gap: 0.5rem;
|
| 397 |
+
padding: 0.55rem 0.65rem 0.55rem 0.65rem;
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
#query-input {
|
| 401 |
+
flex: 1; resize: none; border: none; outline: none;
|
| 402 |
+
background: transparent; color: var(--text);
|
| 403 |
+
font-family: var(--font); font-size: 0.92rem; line-height: 1.55;
|
| 404 |
+
min-height: 24px; max-height: 180px;
|
| 405 |
+
overflow-y: auto; padding: 0;
|
| 406 |
+
}
|
| 407 |
+
#query-input::placeholder { color: var(--text-dim); }
|
| 408 |
+
#query-input::-webkit-scrollbar { width: 3px; }
|
| 409 |
+
|
| 410 |
+
.input-left { display: flex; align-items: flex-end; gap: 0.3rem; }
|
| 411 |
+
.input-right { display: flex; align-items: flex-end; }
|
| 412 |
+
|
| 413 |
+
.at-btn {
|
| 414 |
+
width: 30px; height: 30px; border-radius: 7px; border: none;
|
| 415 |
+
background: rgba(255,255,255,0.05); color: var(--text-muted);
|
| 416 |
+
font-size: 0.85rem; cursor: pointer; display: flex; align-items: center; justify-content: center;
|
| 417 |
+
transition: background 0.12s, color 0.12s; position: relative; flex-shrink: 0;
|
| 418 |
+
}
|
| 419 |
+
.at-btn:hover { background: rgba(255,255,255,0.1); color: var(--text); }
|
| 420 |
+
|
| 421 |
+
.send-btn {
|
| 422 |
+
width: 32px; height: 32px; border-radius: 8px; border: none;
|
| 423 |
+
background: linear-gradient(135deg, var(--accent), var(--accent2));
|
| 424 |
+
color: #fff; font-size: 1rem; cursor: pointer;
|
| 425 |
+
display: flex; align-items: center; justify-content: center;
|
| 426 |
+
transition: opacity 0.15s, transform 0.12s;
|
| 427 |
+
flex-shrink: 0;
|
| 428 |
+
}
|
| 429 |
+
.send-btn:hover { opacity: 0.85; transform: scale(1.04); }
|
| 430 |
+
.send-btn:disabled { opacity: 0.3; cursor: not-allowed; transform: none; }
|
| 431 |
+
|
| 432 |
+
/* Company picker popup */
|
| 433 |
+
#company-picker {
|
| 434 |
+
position: absolute; bottom: calc(100% + 8px); left: 0;
|
| 435 |
+
background: #1a1f33; border: 1px solid var(--border-blue);
|
| 436 |
+
border-radius: 10px; width: 280px; max-height: 260px;
|
| 437 |
+
overflow-y: auto; z-index: 100; display: none;
|
| 438 |
+
box-shadow: 0 16px 40px rgba(0,0,0,0.5);
|
| 439 |
+
}
|
| 440 |
+
#company-picker.open { display: block; animation: popUp 0.15s ease; }
|
| 441 |
+
.picker-search {
|
| 442 |
+
padding: 0.5rem 0.7rem; border-bottom: 1px solid var(--border);
|
| 443 |
+
position: sticky; top: 0; background: #1a1f33;
|
| 444 |
+
}
|
| 445 |
+
.picker-search input {
|
| 446 |
+
width: 100%; background: none; border: none; outline: none;
|
| 447 |
+
color: var(--text); font-family: var(--font); font-size: 0.82rem;
|
| 448 |
+
}
|
| 449 |
+
.picker-search input::placeholder { color: var(--text-dim); }
|
| 450 |
+
.picker-item {
|
| 451 |
+
padding: 0.45rem 0.8rem; font-size: 0.8rem; color: var(--text-muted);
|
| 452 |
+
cursor: pointer; display: flex; justify-content: space-between; align-items: center;
|
| 453 |
+
transition: background 0.1s;
|
| 454 |
+
}
|
| 455 |
+
.picker-item:hover { background: var(--bg-hover); color: var(--text); }
|
| 456 |
+
.picker-item .ticker { font-size: 0.67rem; font-family: var(--mono); color: var(--text-dim); }
|
| 457 |
+
|
| 458 |
+
/* no hint row — removed */
|
| 459 |
+
|
| 460 |
+
/* ═══════════════════════════════════════════
|
| 461 |
+
ANIMATIONS
|
| 462 |
+
═══════════════════════════════════════════ */
|
| 463 |
+
@keyframes fadeUp {
|
| 464 |
+
from { opacity: 0; transform: translateY(10px); }
|
| 465 |
+
to { opacity: 1; transform: translateY(0); }
|
| 466 |
+
}
|
| 467 |
+
@keyframes popUp {
|
| 468 |
+
from { opacity: 0; transform: translateY(6px) scale(0.97); }
|
| 469 |
+
to { opacity: 1; transform: translateY(0) scale(1); }
|
| 470 |
+
}
|
| 471 |
+
</style>
|
| 472 |
+
</head>
|
| 473 |
+
<body>
|
| 474 |
+
<div id="app">
|
| 475 |
+
|
| 476 |
+
<!-- ═══ SIDEBAR ═══ -->
|
| 477 |
+
<aside id="sidebar">
|
| 478 |
+
<div class="sb-top">
|
| 479 |
+
<div class="brand">
|
| 480 |
+
<span class="brand-icon">📈</span>
|
| 481 |
+
<div>
|
| 482 |
+
<div class="brand-name">FinRAG</div>
|
| 483 |
+
<div class="brand-sub">Indian Markets Intelligence</div>
|
| 484 |
+
</div>
|
| 485 |
+
</div>
|
| 486 |
+
<button class="new-chat-btn" onclick="newChat()">
|
| 487 |
+
<span class="plus">+</span> New Chat
|
| 488 |
+
</button>
|
| 489 |
+
</div>
|
| 490 |
+
|
| 491 |
+
<div class="sb-divider"></div>
|
| 492 |
+
|
| 493 |
+
<div class="sb-scroll" id="history-list">
|
| 494 |
+
<!-- populated by JS -->
|
| 495 |
+
</div>
|
| 496 |
+
|
| 497 |
+
<div class="sb-footer">
|
| 498 |
+
Hybrid RAG · Financial Intelligence
|
| 499 |
+
</div>
|
| 500 |
+
</aside>
|
| 501 |
+
|
| 502 |
+
<!-- ═══ MAIN ═══ -->
|
| 503 |
+
<div id="main">
|
| 504 |
+
|
| 505 |
+
<!-- Topbar -->
|
| 506 |
+
<div id="topbar">
|
| 507 |
+
<button class="toggle-btn" onclick="toggleSidebar()" title="Toggle sidebar">☰</button>
|
| 508 |
+
|
| 509 |
+
<div class="mode-tabs">
|
| 510 |
+
<button class="mode-tab active" data-mode="chat" onclick="setMode('chat')">Chat</button>
|
| 511 |
+
<button class="mode-tab" data-mode="compare" onclick="setMode('compare')">Compare</button>
|
| 512 |
+
<button class="mode-tab" data-mode="dashboard" onclick="setMode('dashboard')">Dashboard</button>
|
| 513 |
+
</div>
|
| 514 |
+
|
| 515 |
+
<!-- Context (changes per mode) -->
|
| 516 |
+
<div class="ctx-row" id="ctx-row">
|
| 517 |
+
<!-- rendered by renderCtx() -->
|
| 518 |
+
</div>
|
| 519 |
+
</div>
|
| 520 |
+
|
| 521 |
+
<!-- Chat Thread -->
|
| 522 |
+
<div id="thread">
|
| 523 |
+
<div id="welcome">
|
| 524 |
+
<div class="wlc-logo"></div>
|
| 525 |
+
<div class="wlc-title">FinRAG</div>
|
| 526 |
+
<div class="wlc-sub">Ask anything about major Indian companies.<br>Answers grounded in official BSE annual reports.</div>
|
| 527 |
+
<div class="sug-grid" id="suggestions"></div>
|
| 528 |
+
</div>
|
| 529 |
+
</div>
|
| 530 |
+
|
| 531 |
+
<!-- Input Area -->
|
| 532 |
+
<div id="input-area">
|
| 533 |
+
<div style="max-width:780px;margin:0 auto;position:relative;">
|
| 534 |
+
<div id="company-picker" class="closed">
|
| 535 |
+
<div class="picker-search">
|
| 536 |
+
<input type="text" id="picker-search" placeholder="Search company…" oninput="filterPicker(this.value)">
|
| 537 |
+
</div>
|
| 538 |
+
<div id="picker-list"></div>
|
| 539 |
+
</div>
|
| 540 |
+
|
| 541 |
+
<div class="input-wrap">
|
| 542 |
+
<div class="input-row">
|
| 543 |
+
<div class="input-left">
|
| 544 |
+
<button class="at-btn" onclick="togglePicker()" title="Select company">@</button>
|
| 545 |
+
</div>
|
| 546 |
+
<textarea id="query-input" placeholder="Ask anything… or type @Company to filter" rows="1"
|
| 547 |
+
onkeydown="handleKey(event)" oninput="autoResize(this)"></textarea>
|
| 548 |
+
<div class="input-right">
|
| 549 |
+
<button class="send-btn" id="send-btn" onclick="submitQuery()">↑</button>
|
| 550 |
+
</div>
|
| 551 |
+
</div>
|
| 552 |
+
</div>
|
| 553 |
+
</div>
|
| 554 |
+
</div>
|
| 555 |
+
|
| 556 |
+
</div><!-- end main -->
|
| 557 |
+
</div><!-- end app -->
|
| 558 |
+
|
| 559 |
+
<script>
|
| 560 |
+
/* ═══════════════════════════════════════════════════════
|
| 561 |
+
STATE
|
| 562 |
+
═══════════════════════════════════════════════════════ */
|
| 563 |
+
const state = {
|
| 564 |
+
mode: 'chat',
|
| 565 |
+
company: 'TCS',
|
| 566 |
+
fy: 'FY2025',
|
| 567 |
+
compareCompanies: ['TCS', 'INFOSYS'],
|
| 568 |
+
conversationId: null,
|
| 569 |
+
isStreaming: false,
|
| 570 |
+
companies: [],
|
| 571 |
+
tickers: {},
|
| 572 |
+
};
|
| 573 |
+
|
| 574 |
+
/* ═══════════════════════════════════════════════════════
|
| 575 |
+
INIT
|
| 576 |
+
═══════════════════════════════════════════════════════ */
|
| 577 |
+
async function init() {
|
| 578 |
+
// Load companies
|
| 579 |
+
const res = await fetch('/api/companies');
|
| 580 |
+
const data = await res.json();
|
| 581 |
+
state.companies = data.companies;
|
| 582 |
+
state.tickers = data.tickers;
|
| 583 |
+
state.company = state.companies[0];
|
| 584 |
+
|
| 585 |
+
renderCtx();
|
| 586 |
+
renderSuggestions();
|
| 587 |
+
buildPicker();
|
| 588 |
+
loadHistory();
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
/* ═══════════════════════════════════════════════════════
|
| 592 |
+
SIDEBAR TOGGLE
|
| 593 |
+
═══════════════════════════════════════════════════════ */
|
| 594 |
+
function toggleSidebar() {
|
| 595 |
+
document.getElementById('sidebar').classList.toggle('collapsed');
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
/* ═══════════════════════════════════════════════════════
|
| 599 |
+
MODE
|
| 600 |
+
═══════════════════════════════════════════════════════ */
|
| 601 |
+
function setMode(mode) {
|
| 602 |
+
state.mode = mode;
|
| 603 |
+
document.querySelectorAll('.mode-tab').forEach(t => t.classList.toggle('active', t.dataset.mode === mode));
|
| 604 |
+
renderCtx();
|
| 605 |
+
}
|
| 606 |
+
|
| 607 |
+
function renderCtx() {
|
| 608 |
+
const row = document.getElementById('ctx-row');
|
| 609 |
+
const cos = state.companies;
|
| 610 |
+
const fyOptions = ['FY2025', 'FY2024', 'All'];
|
| 611 |
+
|
| 612 |
+
if (state.mode === 'compare') {
|
| 613 |
+
let html = `<div class="multi-company-bar" id="compare-bar">`;
|
| 614 |
+
state.compareCompanies.forEach(c => {
|
| 615 |
+
html += `<span class="co-pill">${c} <span class="rm" onclick="removeCompare('${c}')">×</span></span>`;
|
| 616 |
+
});
|
| 617 |
+
html += `<button class="add-company-btn" onclick="openComparePicker()">+ Add</button></div>`;
|
| 618 |
+
html += fySelect();
|
| 619 |
+
row.innerHTML = html;
|
| 620 |
+
} else if (state.mode === 'dashboard') {
|
| 621 |
+
row.innerHTML = companySelect() + fySelect() +
|
| 622 |
+
`<button class="extract-btn" id="extract-btn" onclick="extractDashboard()">Extract KPIs →</button>`;
|
| 623 |
+
} else {
|
| 624 |
+
row.innerHTML = companySelect() + fySelect();
|
| 625 |
+
}
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
function companySelect() {
|
| 629 |
+
let s = `<select class="ctx-select" id="company-sel" onchange="state.company=this.value">`;
|
| 630 |
+
state.companies.forEach(c => {
|
| 631 |
+
s += `<option value="${c}" ${c === state.company ? 'selected' : ''}>${c}</option>`;
|
| 632 |
+
});
|
| 633 |
+
return s + '</select>';
|
| 634 |
+
}
|
| 635 |
+
|
| 636 |
+
function fySelect() {
|
| 637 |
+
return `<select class="ctx-select" id="fy-sel" onchange="state.fy=this.value">
|
| 638 |
+
<option value="FY2025">FY2025</option>
|
| 639 |
+
<option value="FY2024">FY2024</option>
|
| 640 |
+
<option value="All">All Years</option>
|
| 641 |
+
</select>`;
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
/* ═══════════════════════════════════════════════════════
|
| 645 |
+
COMPARE COMPANY MANAGEMENT
|
| 646 |
+
═══════════════════════════════════════════════════════ */
|
| 647 |
+
function removeCompare(c) {
|
| 648 |
+
state.compareCompanies = state.compareCompanies.filter(x => x !== c);
|
| 649 |
+
renderCtx();
|
| 650 |
+
}
|
| 651 |
+
|
| 652 |
+
function openComparePicker() {
|
| 653 |
+
const picker = document.getElementById('company-picker');
|
| 654 |
+
picker.classList.add('open');
|
| 655 |
+
document.getElementById('picker-search').focus();
|
| 656 |
+
picker._mode = 'compare';
|
| 657 |
+
}
|
| 658 |
+
|
| 659 |
+
/* ═══════════════════════════════════════════════════════
|
| 660 |
+
COMPANY PICKER
|
| 661 |
+
═══════════════════════════════════════════════════════ */
|
| 662 |
+
function buildPicker() {
|
| 663 |
+
renderPickerItems(state.companies);
|
| 664 |
+
}
|
| 665 |
+
|
| 666 |
+
function renderPickerItems(items) {
|
| 667 |
+
const list = document.getElementById('picker-list');
|
| 668 |
+
list.innerHTML = items.map(c =>
|
| 669 |
+
`<div class="picker-item" onclick="selectFromPicker('${c}')">
|
| 670 |
+
<span>${c}</span>
|
| 671 |
+
<span class="ticker">${state.tickers[c] || ''}</span>
|
| 672 |
+
</div>`
|
| 673 |
+
).join('');
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
function filterPicker(q) {
|
| 677 |
+
const filtered = state.companies.filter(c => c.toLowerCase().includes(q.toLowerCase()));
|
| 678 |
+
renderPickerItems(filtered);
|
| 679 |
+
}
|
| 680 |
+
|
| 681 |
+
function togglePicker() {
|
| 682 |
+
const picker = document.getElementById('company-picker');
|
| 683 |
+
picker.classList.toggle('open');
|
| 684 |
+
picker._mode = 'chat';
|
| 685 |
+
if (picker.classList.contains('open')) {
|
| 686 |
+
document.getElementById('picker-search').value = '';
|
| 687 |
+
document.getElementById('picker-search').focus();
|
| 688 |
+
renderPickerItems(state.companies);
|
| 689 |
+
}
|
| 690 |
+
}
|
| 691 |
+
|
| 692 |
+
function selectFromPicker(company) {
|
| 693 |
+
const picker = document.getElementById('company-picker');
|
| 694 |
+
if (picker._mode === 'compare') {
|
| 695 |
+
if (!state.compareCompanies.includes(company)) {
|
| 696 |
+
state.compareCompanies.push(company);
|
| 697 |
+
}
|
| 698 |
+
renderCtx();
|
| 699 |
+
} else {
|
| 700 |
+
state.company = company;
|
| 701 |
+
const sel = document.getElementById('company-sel');
|
| 702 |
+
if (sel) sel.value = company;
|
| 703 |
+
// Also insert @company into input
|
| 704 |
+
const inp = document.getElementById('query-input');
|
| 705 |
+
if (!inp.value.includes(company)) {
|
| 706 |
+
inp.value = `@${company} ` + inp.value;
|
| 707 |
+
}
|
| 708 |
+
inp.focus();
|
| 709 |
+
}
|
| 710 |
+
picker.classList.remove('open');
|
| 711 |
+
}
|
| 712 |
+
|
| 713 |
+
// Close picker on outside click
|
| 714 |
+
document.addEventListener('click', e => {
|
| 715 |
+
const picker = document.getElementById('company-picker');
|
| 716 |
+
const atBtn = document.querySelector('.at-btn');
|
| 717 |
+
if (!picker.contains(e.target) && !atBtn.contains(e.target)) {
|
| 718 |
+
picker.classList.remove('open');
|
| 719 |
+
}
|
| 720 |
+
});
|
| 721 |
+
|
| 722 |
+
/* ═══════════════════════════════════════════════════════
|
| 723 |
+
SUGGESTIONS
|
| 724 |
+
═══════════════════════════════════════════════════════ */
|
| 725 |
+
const SUGGESTIONS = [
|
| 726 |
+
{ icon: '💰', text: "What was TCS's revenue and net profit for FY2025?" },
|
| 727 |
+
{ icon: '🏦', text: "What is HDFC Bank's gross NPA ratio?" },
|
| 728 |
+
{ icon: '⚖️', text: "Compare Infosys vs HCL Technologies on revenue growth" },
|
| 729 |
+
{ icon: '📊', text: "Show KPI dashboard for Reliance Industries" },
|
| 730 |
+
];
|
| 731 |
+
|
| 732 |
+
function renderSuggestions() {
|
| 733 |
+
const grid = document.getElementById('suggestions');
|
| 734 |
+
grid.innerHTML = SUGGESTIONS.map(s =>
|
| 735 |
+
`<div class="sug-card" onclick="submitSuggestion('${s.text.replace(/'/g,"\\'")}')">
|
| 736 |
+
<span class="sug-icon">${s.icon}</span>
|
| 737 |
+
<div class="sug-text">${s.text}</div>
|
| 738 |
+
</div>`
|
| 739 |
+
).join('');
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
function submitSuggestion(text) {
|
| 743 |
+
const inp = document.getElementById('query-input');
|
| 744 |
+
inp.value = text;
|
| 745 |
+
submitQuery();
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
/* ═══════════════════════════════════════════════════════
|
| 749 |
+
TEXTAREA AUTO-RESIZE
|
| 750 |
+
═══════════════════════════════════════════════════════ */
|
| 751 |
+
function autoResize(el) {
|
| 752 |
+
el.style.height = 'auto';
|
| 753 |
+
el.style.height = Math.min(el.scrollHeight, 180) + 'px';
|
| 754 |
+
}
|
| 755 |
+
|
| 756 |
+
function handleKey(e) {
|
| 757 |
+
if (e.key === 'Enter' && !e.shiftKey) {
|
| 758 |
+
e.preventDefault();
|
| 759 |
+
submitQuery();
|
| 760 |
+
}
|
| 761 |
+
}
|
| 762 |
+
|
| 763 |
+
/* ═══════════════════════════════════════════════════════
|
| 764 |
+
CONVERSATION MANAGEMENT
|
| 765 |
+
═══════════════════════════════════════════════════════ */
|
| 766 |
+
async function newChat() {
|
| 767 |
+
const res = await fetch('/api/conversations', {
|
| 768 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 769 |
+
body: JSON.stringify({ mode: state.mode }),
|
| 770 |
+
});
|
| 771 |
+
const data = await res.json();
|
| 772 |
+
state.conversationId = data.id;
|
| 773 |
+
|
| 774 |
+
// Clear thread, show welcome
|
| 775 |
+
document.getElementById('thread').innerHTML = `
|
| 776 |
+
<div id="welcome">
|
| 777 |
+
<div class="wlc-logo">📈</div>
|
| 778 |
+
<div class="wlc-title">FinRAG</div>
|
| 779 |
+
<div class="wlc-sub">Ask anything about 17 major Indian companies.<br>Answers grounded in official BSE annual reports.</div>
|
| 780 |
+
<div class="sug-grid" id="suggestions"></div>
|
| 781 |
+
</div>`;
|
| 782 |
+
renderSuggestions();
|
| 783 |
+
loadHistory();
|
| 784 |
+
}
|
| 785 |
+
|
| 786 |
+
async function loadHistory() {
|
| 787 |
+
const res = await fetch('/api/conversations');
|
| 788 |
+
const data = await res.json();
|
| 789 |
+
renderHistory(data.grouped || {});
|
| 790 |
+
}
|
| 791 |
+
|
| 792 |
+
function renderHistory(grouped) {
|
| 793 |
+
const list = document.getElementById('history-list');
|
| 794 |
+
let html = '';
|
| 795 |
+
const icons = { chat: '💬', compare: '⚖️', dashboard: '📊' };
|
| 796 |
+
|
| 797 |
+
for (const [group, convs] of Object.entries(grouped)) {
|
| 798 |
+
html += `<div class="group-label">${group}</div>`;
|
| 799 |
+
convs.forEach(c => {
|
| 800 |
+
const active = c.id === state.conversationId ? 'active' : '';
|
| 801 |
+
const icon = icons[c.mode] || '💬';
|
| 802 |
+
html += `<div class="hist-item ${active}" onclick="loadConversation('${c.id}', '${c.mode}')">
|
| 803 |
+
<span class="icon">${icon}</span>
|
| 804 |
+
<span class="title">${escHtml(c.title)}</span>
|
| 805 |
+
<span class="del" onclick="event.stopPropagation();deleteConv('${c.id}')">🗑</span>
|
| 806 |
+
</div>`;
|
| 807 |
+
});
|
| 808 |
+
}
|
| 809 |
+
|
| 810 |
+
list.innerHTML = html || '<div style="padding:0.5rem 0.8rem;font-size:0.75rem;color:var(--text-dim);">No history yet</div>';
|
| 811 |
+
}
|
| 812 |
+
|
| 813 |
+
async function loadConversation(cid, mode) {
|
| 814 |
+
state.conversationId = cid;
|
| 815 |
+
if (mode) setMode(mode);
|
| 816 |
+
|
| 817 |
+
const res = await fetch(`/api/conversations/${cid}/messages`);
|
| 818 |
+
const data = await res.json();
|
| 819 |
+
|
| 820 |
+
const thread = document.getElementById('thread');
|
| 821 |
+
thread.innerHTML = '';
|
| 822 |
+
|
| 823 |
+
for (const msg of data.messages) {
|
| 824 |
+
if (msg.role === 'user') {
|
| 825 |
+
appendUserMsg(msg.content);
|
| 826 |
+
} else {
|
| 827 |
+
const meta = msg.metadata || {};
|
| 828 |
+
const el = appendAssistantMsg(msg.content, false);
|
| 829 |
+
if (meta.sources?.length) appendSources(el, meta.sources);
|
| 830 |
+
if (meta.kpi_metrics) appendKPI(el, meta.kpi_metrics, meta.company || '');
|
| 831 |
+
}
|
| 832 |
+
}
|
| 833 |
+
|
| 834 |
+
thread.scrollTop = thread.scrollHeight;
|
| 835 |
+
loadHistory();
|
| 836 |
+
}
|
| 837 |
+
|
| 838 |
+
async function deleteConv(cid) {
|
| 839 |
+
await fetch(`/api/conversations/${cid}`, { method: 'DELETE' });
|
| 840 |
+
if (state.conversationId === cid) {
|
| 841 |
+
state.conversationId = null;
|
| 842 |
+
newChat();
|
| 843 |
+
} else {
|
| 844 |
+
loadHistory();
|
| 845 |
+
}
|
| 846 |
+
}
|
| 847 |
+
|
| 848 |
+
/* ═══════════════════════════════════════════════════════
|
| 849 |
+
SAVE MESSAGE
|
| 850 |
+
═══════════════════════════════════════════════════════ */
|
| 851 |
+
async function saveMessage(role, content, metadata = null) {
|
| 852 |
+
if (!state.conversationId) {
|
| 853 |
+
const res = await fetch('/api/conversations', {
|
| 854 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 855 |
+
body: JSON.stringify({ mode: state.mode }),
|
| 856 |
+
});
|
| 857 |
+
const data = await res.json();
|
| 858 |
+
state.conversationId = data.id;
|
| 859 |
+
}
|
| 860 |
+
|
| 861 |
+
await fetch(`/api/conversations/${state.conversationId}/messages`, {
|
| 862 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 863 |
+
body: JSON.stringify({ role, content, metadata }),
|
| 864 |
+
});
|
| 865 |
+
}
|
| 866 |
+
|
| 867 |
+
/* ═══════════════════════════════════════════════════════
|
| 868 |
+
SUBMIT QUERY
|
| 869 |
+
═══════════════════════════════════════════════════════ */
|
| 870 |
+
async function submitQuery() {
|
| 871 |
+
const inp = document.getElementById('query-input');
|
| 872 |
+
const query = inp.value.trim();
|
| 873 |
+
if (!query || state.isStreaming) return;
|
| 874 |
+
|
| 875 |
+
inp.value = '';
|
| 876 |
+
inp.style.height = 'auto';
|
| 877 |
+
|
| 878 |
+
// Hide welcome
|
| 879 |
+
const welcome = document.getElementById('welcome');
|
| 880 |
+
if (welcome) welcome.remove();
|
| 881 |
+
|
| 882 |
+
// Get current selectors FIRST
|
| 883 |
+
const companySel = document.getElementById('company-sel');
|
| 884 |
+
if (companySel) state.company = companySel.value;
|
| 885 |
+
const fySel = document.getElementById('fy-sel');
|
| 886 |
+
if (fySel) state.fy = fySel.value;
|
| 887 |
+
|
| 888 |
+
const ql = query.toLowerCase();
|
| 889 |
+
|
| 890 |
+
// Auto-detect compare/dashboard intent FIRST
|
| 891 |
+
if (/compare|vs |versus|vs\./i.test(ql) && state.mode !== 'compare') setMode('compare');
|
| 892 |
+
else if (/dashboard|kpi|extract metric/i.test(ql) && state.mode !== 'dashboard') setMode('dashboard');
|
| 893 |
+
|
| 894 |
+
if (state.mode === 'compare') {
|
| 895 |
+
const mentioned = state.companies.filter(c => ql.includes(c.toLowerCase()) || (state.tickers[c] && ql.includes(state.tickers[c].toLowerCase())));
|
| 896 |
+
if (mentioned.length > 0) {
|
| 897 |
+
state.compareCompanies = [];
|
| 898 |
+
mentioned.forEach(c => {
|
| 899 |
+
if (!state.compareCompanies.includes(c)) state.compareCompanies.push(c);
|
| 900 |
+
});
|
| 901 |
+
renderCtx();
|
| 902 |
+
}
|
| 903 |
+
} else {
|
| 904 |
+
// Single company detection for chat/dashboard
|
| 905 |
+
const atMatch = query.match(/@(\w+)/);
|
| 906 |
+
if (atMatch) {
|
| 907 |
+
const mentioned = state.companies.find(c => c.toLowerCase() === atMatch[1].toLowerCase());
|
| 908 |
+
if (mentioned) state.company = mentioned;
|
| 909 |
+
} else {
|
| 910 |
+
for (const c of state.companies) {
|
| 911 |
+
if (ql.includes(c.toLowerCase()) || (state.tickers[c] && ql.includes(state.tickers[c].toLowerCase()))) {
|
| 912 |
+
state.company = c;
|
| 913 |
+
break;
|
| 914 |
+
}
|
| 915 |
+
}
|
| 916 |
+
}
|
| 917 |
+
// Sync dropdown UI
|
| 918 |
+
if (companySel && companySel.value !== state.company) {
|
| 919 |
+
companySel.value = state.company;
|
| 920 |
+
}
|
| 921 |
+
}
|
| 922 |
+
|
| 923 |
+
appendUserMsg(query);
|
| 924 |
+
await saveMessage('user', query);
|
| 925 |
+
loadHistory();
|
| 926 |
+
|
| 927 |
+
if (state.mode === 'dashboard') {
|
| 928 |
+
await runDashboard();
|
| 929 |
+
} else if (state.mode === 'compare') {
|
| 930 |
+
await runCompare(query);
|
| 931 |
+
} else {
|
| 932 |
+
await runChat(query);
|
| 933 |
+
}
|
| 934 |
+
|
| 935 |
+
loadHistory();
|
| 936 |
+
}
|
| 937 |
+
|
| 938 |
+
/* ═══════════════════════════════════════════════════════
|
| 939 |
+
CHAT
|
| 940 |
+
═══════════════════════════════════════════════════════ */
|
| 941 |
+
async function runChat(query) {
|
| 942 |
+
setBusy(true);
|
| 943 |
+
const spinEl = appendSpinner('Searching documents…');
|
| 944 |
+
|
| 945 |
+
let fullText = '';
|
| 946 |
+
let sources = [];
|
| 947 |
+
const asst = createAssistantEl();
|
| 948 |
+
|
| 949 |
+
try {
|
| 950 |
+
const res = await fetch('/api/chat', {
|
| 951 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 952 |
+
body: JSON.stringify({ query, company: state.company, fiscal_year: state.fy }),
|
| 953 |
+
});
|
| 954 |
+
|
| 955 |
+
spinEl.remove();
|
| 956 |
+
const thread = document.getElementById('thread');
|
| 957 |
+
thread.appendChild(asst.wrap);
|
| 958 |
+
|
| 959 |
+
const reader = res.body.getReader();
|
| 960 |
+
const decoder = new TextDecoder();
|
| 961 |
+
let buf = '';
|
| 962 |
+
|
| 963 |
+
while (true) {
|
| 964 |
+
const { done, value } = await reader.read();
|
| 965 |
+
if (done) break;
|
| 966 |
+
buf += decoder.decode(value, { stream: true });
|
| 967 |
+
const lines = buf.split('\n');
|
| 968 |
+
buf = lines.pop();
|
| 969 |
+
|
| 970 |
+
for (const line of lines) {
|
| 971 |
+
if (!line.startsWith('data: ')) continue;
|
| 972 |
+
const evt = JSON.parse(line.slice(6));
|
| 973 |
+
if (evt.type === 'chunk') {
|
| 974 |
+
fullText += evt.text;
|
| 975 |
+
asst.content.innerHTML = marked.parse(fullText) + '<span class="cursor"></span>';
|
| 976 |
+
scrollThread();
|
| 977 |
+
} else if (evt.type === 'sources') {
|
| 978 |
+
sources = evt.sources;
|
| 979 |
+
} else if (evt.type === 'done') {
|
| 980 |
+
asst.content.innerHTML = marked.parse(fullText);
|
| 981 |
+
if (sources.length) appendSources(asst.content, sources);
|
| 982 |
+
}
|
| 983 |
+
}
|
| 984 |
+
}
|
| 985 |
+
} catch (e) {
|
| 986 |
+
spinEl.remove();
|
| 987 |
+
appendAssistantMsg(`Error: ${e.message}`, false);
|
| 988 |
+
}
|
| 989 |
+
|
| 990 |
+
await saveMessage('assistant', fullText, { sources });
|
| 991 |
+
setBusy(false);
|
| 992 |
+
}
|
| 993 |
+
|
| 994 |
+
/* ═══════════════════════════════════════════════════════
|
| 995 |
+
COMPARE
|
| 996 |
+
═══════════════════════════════════════════════════════ */
|
| 997 |
+
async function runCompare(query) {
|
| 998 |
+
setBusy(true);
|
| 999 |
+
const companies = state.compareCompanies.length >= 1 ? state.compareCompanies : [state.company];
|
| 1000 |
+
|
| 1001 |
+
const spinEl = appendSpinner(`Comparing ${companies.join(' vs ')}…`);
|
| 1002 |
+
let fullText = '';
|
| 1003 |
+
let sources = [];
|
| 1004 |
+
const asst = createAssistantEl();
|
| 1005 |
+
|
| 1006 |
+
try {
|
| 1007 |
+
const res = await fetch('/api/compare', {
|
| 1008 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 1009 |
+
body: JSON.stringify({ query, companies, fiscal_year: state.fy }),
|
| 1010 |
+
});
|
| 1011 |
+
|
| 1012 |
+
spinEl.remove();
|
| 1013 |
+
document.getElementById('thread').appendChild(asst.wrap);
|
| 1014 |
+
|
| 1015 |
+
const reader = res.body.getReader();
|
| 1016 |
+
const decoder = new TextDecoder();
|
| 1017 |
+
let buf = '';
|
| 1018 |
+
|
| 1019 |
+
while (true) {
|
| 1020 |
+
const { done, value } = await reader.read();
|
| 1021 |
+
if (done) break;
|
| 1022 |
+
buf += decoder.decode(value, { stream: true });
|
| 1023 |
+
const lines = buf.split('\n');
|
| 1024 |
+
buf = lines.pop();
|
| 1025 |
+
|
| 1026 |
+
for (const line of lines) {
|
| 1027 |
+
if (!line.startsWith('data: ')) continue;
|
| 1028 |
+
const evt = JSON.parse(line.slice(6));
|
| 1029 |
+
if (evt.type === 'chunk') {
|
| 1030 |
+
fullText += evt.text;
|
| 1031 |
+
asst.content.innerHTML = marked.parse(fullText) + '<span class="cursor"></span>';
|
| 1032 |
+
scrollThread();
|
| 1033 |
+
} else if (evt.type === 'sources') {
|
| 1034 |
+
sources = evt.sources;
|
| 1035 |
+
} else if (evt.type === 'done') {
|
| 1036 |
+
asst.content.innerHTML = marked.parse(fullText);
|
| 1037 |
+
if (sources.length) appendSources(asst.content, sources);
|
| 1038 |
+
}
|
| 1039 |
+
}
|
| 1040 |
+
}
|
| 1041 |
+
} catch (e) {
|
| 1042 |
+
spinEl.remove();
|
| 1043 |
+
appendAssistantMsg(`Error: ${e.message}`, false);
|
| 1044 |
+
}
|
| 1045 |
+
|
| 1046 |
+
await saveMessage('assistant', fullText, { sources });
|
| 1047 |
+
setBusy(false);
|
| 1048 |
+
}
|
| 1049 |
+
|
| 1050 |
+
/* ═══════════════════════════════════════════════════════
|
| 1051 |
+
DASHBOARD
|
| 1052 |
+
═══════════════════════════════════════════════════════ */
|
| 1053 |
+
async function extractDashboard() {
|
| 1054 |
+
const companySel = document.getElementById('company-sel');
|
| 1055 |
+
if (companySel) state.company = companySel.value;
|
| 1056 |
+
const fySel = document.getElementById('fy-sel');
|
| 1057 |
+
if (fySel) state.fy = fySel.value;
|
| 1058 |
+
|
| 1059 |
+
const welcome = document.getElementById('welcome');
|
| 1060 |
+
if (welcome) welcome.remove();
|
| 1061 |
+
|
| 1062 |
+
const query = `Show KPI dashboard for ${state.company} ${state.fy}`;
|
| 1063 |
+
appendUserMsg(query);
|
| 1064 |
+
await saveMessage('user', query);
|
| 1065 |
+
|
| 1066 |
+
await runDashboard();
|
| 1067 |
+
loadHistory();
|
| 1068 |
+
}
|
| 1069 |
+
|
| 1070 |
+
async function runDashboard() {
|
| 1071 |
+
setBusy(true);
|
| 1072 |
+
const companySel = document.getElementById('company-sel');
|
| 1073 |
+
if (companySel) state.company = companySel.value;
|
| 1074 |
+
|
| 1075 |
+
const spinEl = appendSpinner(`Extracting KPIs for ${state.company}…`);
|
| 1076 |
+
const asst = createAssistantEl();
|
| 1077 |
+
|
| 1078 |
+
try {
|
| 1079 |
+
const res = await fetch('/api/dashboard', {
|
| 1080 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 1081 |
+
body: JSON.stringify({ company: state.company, fiscal_year: state.fy }),
|
| 1082 |
+
});
|
| 1083 |
+
const data = await res.json();
|
| 1084 |
+
const metrics = data.metrics || {};
|
| 1085 |
+
const fyLabel = data.fiscal_year || state.fy;
|
| 1086 |
+
const ticker = state.tickers[state.company] || '';
|
| 1087 |
+
|
| 1088 |
+
spinEl.remove();
|
| 1089 |
+
const thread = document.getElementById('thread');
|
| 1090 |
+
thread.appendChild(asst.wrap);
|
| 1091 |
+
|
| 1092 |
+
asst.content.innerHTML = `<strong>${state.company}</strong> (${ticker}) — KPI Summary <span style="color:var(--accent2)">${fyLabel}</span>`;
|
| 1093 |
+
appendKPI(asst.content, metrics, state.company);
|
| 1094 |
+
|
| 1095 |
+
await saveMessage('assistant',
|
| 1096 |
+
`${state.company} KPI Dashboard — ${fyLabel}`,
|
| 1097 |
+
{ kpi_metrics: metrics, company: state.company, fy: fyLabel }
|
| 1098 |
+
);
|
| 1099 |
+
} catch (e) {
|
| 1100 |
+
spinEl.remove();
|
| 1101 |
+
appendAssistantMsg(`Error: ${e.message}`, false);
|
| 1102 |
+
}
|
| 1103 |
+
|
| 1104 |
+
setBusy(false);
|
| 1105 |
+
scrollThread();
|
| 1106 |
+
}
|
| 1107 |
+
|
| 1108 |
+
/* ═══════════════════════════════════════════════════════
|
| 1109 |
+
DOM HELPERS
|
| 1110 |
+
═══════════════════════════════════════════════════════ */
|
| 1111 |
+
function appendUserMsg(text) {
|
| 1112 |
+
const thread = document.getElementById('thread');
|
| 1113 |
+
const wrap = document.createElement('div');
|
| 1114 |
+
wrap.className = 'msg-wrap';
|
| 1115 |
+
wrap.innerHTML = `<div class="msg-user"><div class="bubble">${escHtml(text)}</div></div>`;
|
| 1116 |
+
thread.appendChild(wrap);
|
| 1117 |
+
scrollThread();
|
| 1118 |
+
}
|
| 1119 |
+
|
| 1120 |
+
function createAssistantEl() {
|
| 1121 |
+
const wrap = document.createElement('div');
|
| 1122 |
+
wrap.className = 'msg-wrap';
|
| 1123 |
+
const content = document.createElement('div');
|
| 1124 |
+
content.className = 'asst-content';
|
| 1125 |
+
wrap.innerHTML = `
|
| 1126 |
+
<div class="msg-asst">
|
| 1127 |
+
<div class="asst-avatar">📈</div>
|
| 1128 |
+
<div class="asst-body">
|
| 1129 |
+
<div class="asst-name">FinRAG</div>
|
| 1130 |
+
</div>
|
| 1131 |
+
</div>`;
|
| 1132 |
+
wrap.querySelector('.asst-body').appendChild(content);
|
| 1133 |
+
return { wrap, content };
|
| 1134 |
+
}
|
| 1135 |
+
|
| 1136 |
+
function appendAssistantMsg(markdown, streaming = false) {
|
| 1137 |
+
const thread = document.getElementById('thread');
|
| 1138 |
+
const { wrap, content } = createAssistantEl();
|
| 1139 |
+
content.innerHTML = marked.parse(markdown);
|
| 1140 |
+
thread.appendChild(wrap);
|
| 1141 |
+
scrollThread();
|
| 1142 |
+
return content;
|
| 1143 |
+
}
|
| 1144 |
+
|
| 1145 |
+
function appendSpinner(text) {
|
| 1146 |
+
const thread = document.getElementById('thread');
|
| 1147 |
+
const el = document.createElement('div');
|
| 1148 |
+
el.style.cssText = 'max-width:780px;margin:0.5rem auto;padding:0 1.5rem;';
|
| 1149 |
+
el.innerHTML = `<div class="spin-row"><div class="spinner"></div><span>${escHtml(text)}</span></div>`;
|
| 1150 |
+
thread.appendChild(el);
|
| 1151 |
+
scrollThread();
|
| 1152 |
+
return el;
|
| 1153 |
+
}
|
| 1154 |
+
|
| 1155 |
+
function appendSources(container, sources) {
|
| 1156 |
+
if (!sources?.length) return;
|
| 1157 |
+
const div = document.createElement('div');
|
| 1158 |
+
div.className = 'sources-bar';
|
| 1159 |
+
sources.forEach(s => {
|
| 1160 |
+
const chip = document.createElement('a');
|
| 1161 |
+
chip.className = 'src-chip' + (s.is_table ? ' tbl' : '');
|
| 1162 |
+
chip.textContent = `${s.company || ''} ${s.fiscal_year || ''} Pg.${s.page}${s.is_table ? ' [TABLE]' : ''}`.trim();
|
| 1163 |
+
chip.title = s.file || '';
|
| 1164 |
+
if (s.file) {
|
| 1165 |
+
chip.href = `/raw_pdfs/${encodeURIComponent(s.file)}#page=${s.page}`;
|
| 1166 |
+
chip.target = '_blank';
|
| 1167 |
+
}
|
| 1168 |
+
div.appendChild(chip);
|
| 1169 |
+
});
|
| 1170 |
+
container.appendChild(div);
|
| 1171 |
+
}
|
| 1172 |
+
|
| 1173 |
+
function appendKPI(container, metrics, company) {
|
| 1174 |
+
const fmt = (v, type) => {
|
| 1175 |
+
if (v === null || v === undefined) return null;
|
| 1176 |
+
if (type === 'crore') return v >= 100000 ? `₹${(v/100000).toFixed(1)}L Cr` : `₹${Math.round(v).toLocaleString('en-IN')} Cr`;
|
| 1177 |
+
if (type === 'pct') return `${v.toFixed(2)}%`;
|
| 1178 |
+
if (type === 'inr') return `₹${v.toFixed(2)}`;
|
| 1179 |
+
return String(v);
|
| 1180 |
+
};
|
| 1181 |
+
|
| 1182 |
+
const rows = [
|
| 1183 |
+
{ title: 'Revenue & Profitability', items: [
|
| 1184 |
+
['Revenue', metrics.revenue_crore, fmt(metrics.revenue_crore, 'crore')],
|
| 1185 |
+
['Net Profit', metrics.net_profit_crore, fmt(metrics.net_profit_crore, 'crore')],
|
| 1186 |
+
['Net Margin', metrics.net_profit_margin_pct, fmt(metrics.net_profit_margin_pct, 'pct')],
|
| 1187 |
+
['EBITDA Margin',metrics.ebitda_margin_pct, fmt(metrics.ebitda_margin_pct, 'pct')],
|
| 1188 |
+
]},
|
| 1189 |
+
{ title: 'Balance Sheet', items: [
|
| 1190 |
+
['Total Assets', metrics.total_assets_crore, fmt(metrics.total_assets_crore, 'crore')],
|
| 1191 |
+
['Equity', metrics.equity_crore, fmt(metrics.equity_crore, 'crore')],
|
| 1192 |
+
['EPS', metrics.eps_inr, fmt(metrics.eps_inr, 'inr')],
|
| 1193 |
+
['ROE', metrics.roe_pct, fmt(metrics.roe_pct, 'pct')],
|
| 1194 |
+
]},
|
| 1195 |
+
];
|
| 1196 |
+
|
| 1197 |
+
const hasBanking = metrics.npa_gross_pct || metrics.npa_net_pct || metrics.nim_pct;
|
| 1198 |
+
if (hasBanking) rows.push({ title: 'Banking Metrics', items: [
|
| 1199 |
+
['Gross NPA', metrics.npa_gross_pct, fmt(metrics.npa_gross_pct, 'pct')],
|
| 1200 |
+
['Net NPA', metrics.npa_net_pct, fmt(metrics.npa_net_pct, 'pct')],
|
| 1201 |
+
['NIM', metrics.nim_pct, fmt(metrics.nim_pct, 'pct')],
|
| 1202 |
+
['EBITDA', metrics.ebitda_crore, fmt(metrics.ebitda_crore, 'crore')],
|
| 1203 |
+
]});
|
| 1204 |
+
|
| 1205 |
+
const section = document.createElement('div');
|
| 1206 |
+
section.className = 'kpi-section';
|
| 1207 |
+
|
| 1208 |
+
const colorMetrics = ['Net Margin', 'EBITDA Margin', 'EPS', 'ROE', 'NIM'];
|
| 1209 |
+
const inverseColorMetrics = ['Gross NPA', 'Net NPA'];
|
| 1210 |
+
|
| 1211 |
+
rows.forEach(row => {
|
| 1212 |
+
const validItems = row.items.filter(([lbl, raw, val]) => val !== null);
|
| 1213 |
+
if (validItems.length === 0) return; // Skip section if all metrics are N/A
|
| 1214 |
+
|
| 1215 |
+
section.innerHTML += `<div class="kpi-section-title">${row.title}</div>`;
|
| 1216 |
+
const grid = document.createElement('div');
|
| 1217 |
+
grid.className = 'kpi-grid';
|
| 1218 |
+
|
| 1219 |
+
validItems.forEach(([lbl, raw, val]) => {
|
| 1220 |
+
let colorClass = '';
|
| 1221 |
+
if (colorMetrics.includes(lbl) && raw !== null) {
|
| 1222 |
+
colorClass = raw > 0 ? ' text-green' : (raw < 0 ? ' text-red' : '');
|
| 1223 |
+
} else if (inverseColorMetrics.includes(lbl) && raw !== null) {
|
| 1224 |
+
colorClass = ' text-red'; // NPA is bad
|
| 1225 |
+
}
|
| 1226 |
+
|
| 1227 |
+
const card = document.createElement('div');
|
| 1228 |
+
card.className = 'kpi-card has-val';
|
| 1229 |
+
card.innerHTML = `<div class="val${colorClass}">${val}</div><div class="lbl">${lbl}</div>`;
|
| 1230 |
+
grid.appendChild(card);
|
| 1231 |
+
});
|
| 1232 |
+
section.appendChild(grid);
|
| 1233 |
+
});
|
| 1234 |
+
|
| 1235 |
+
container.appendChild(section);
|
| 1236 |
+
|
| 1237 |
+
// Charts
|
| 1238 |
+
const renderChart = (id, title, dataMap) => {
|
| 1239 |
+
const filtered = Object.entries(dataMap).filter(([,v]) => v != null);
|
| 1240 |
+
if (filtered.length < 1) return;
|
| 1241 |
+
|
| 1242 |
+
const chartWrap = document.createElement('div');
|
| 1243 |
+
chartWrap.className = 'chart-wrap';
|
| 1244 |
+
chartWrap.innerHTML = `<div id="${id}"></div>`;
|
| 1245 |
+
container.appendChild(chartWrap);
|
| 1246 |
+
|
| 1247 |
+
setTimeout(() => {
|
| 1248 |
+
Plotly.newPlot(id,
|
| 1249 |
+
[{ type: 'bar', orientation: 'h',
|
| 1250 |
+
y: filtered.map(([k]) => k),
|
| 1251 |
+
x: filtered.map(([,v]) => v),
|
| 1252 |
+
marker: { color: ['#3b82f6','#06b6d4','#8b5cf6'] },
|
| 1253 |
+
text: filtered.map(([,v]) => `₹${(v).toLocaleString('en-IN')} Cr`),
|
| 1254 |
+
textposition: 'outside', textfont: { color: '#e2e8f0', size: 11 },
|
| 1255 |
+
}],
|
| 1256 |
+
{ paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(255,255,255,0.02)',
|
| 1257 |
+
font: { color: '#94a3b8', family: 'Inter' },
|
| 1258 |
+
xaxis: { gridcolor: 'rgba(255,255,255,0.05)', tickfont: { color: '#64748b' } },
|
| 1259 |
+
yaxis: { tickfont: { color: '#e2e8f0', size: 12 }, automargin: true },
|
| 1260 |
+
margin: { t: 35, b: 10, l: 10, r: 80 }, height: filtered.length === 1 ? 90 : 160,
|
| 1261 |
+
title: { text: title, font: { color: '#64748b', size: 11 } },
|
| 1262 |
+
},
|
| 1263 |
+
{ displayModeBar: false, responsive: true }
|
| 1264 |
+
);
|
| 1265 |
+
}, 100);
|
| 1266 |
+
};
|
| 1267 |
+
|
| 1268 |
+
const stamp = Date.now();
|
| 1269 |
+
renderChart('chart-pl-' + stamp, `${company} — P&L Overview`, {
|
| 1270 |
+
'Revenue': metrics.revenue_crore,
|
| 1271 |
+
'EBITDA': metrics.ebitda_crore,
|
| 1272 |
+
'Net Profit': metrics.net_profit_crore,
|
| 1273 |
+
});
|
| 1274 |
+
|
| 1275 |
+
renderChart('chart-bs-' + stamp, `${company} — Balance Sheet`, {
|
| 1276 |
+
'Total Assets': metrics.total_assets_crore,
|
| 1277 |
+
'Equity': metrics.equity_crore,
|
| 1278 |
+
});
|
| 1279 |
+
}
|
| 1280 |
+
|
| 1281 |
+
/* ═══════════════════════════════════════════════════════
|
| 1282 |
+
UTILS
|
| 1283 |
+
═══════════════════════════════════════════════════════ */
|
| 1284 |
+
function scrollThread() {
|
| 1285 |
+
const t = document.getElementById('thread');
|
| 1286 |
+
t.scrollTop = t.scrollHeight;
|
| 1287 |
+
}
|
| 1288 |
+
|
| 1289 |
+
function setBusy(busy) {
|
| 1290 |
+
state.isStreaming = busy;
|
| 1291 |
+
document.getElementById('send-btn').disabled = busy;
|
| 1292 |
+
const eb = document.getElementById('extract-btn');
|
| 1293 |
+
if (eb) eb.disabled = busy;
|
| 1294 |
+
}
|
| 1295 |
+
|
| 1296 |
+
function escHtml(s) {
|
| 1297 |
+
return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
| 1298 |
+
}
|
| 1299 |
+
|
| 1300 |
+
/* Configure marked */
|
| 1301 |
+
marked.setOptions({ breaks: true, gfm: true });
|
| 1302 |
+
|
| 1303 |
+
init();
|
| 1304 |
+
</script>
|
| 1305 |
+
</body>
|
| 1306 |
+
</html>
|
config/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""config/__init__.py"""
|
| 2 |
+
from .settings import settings
|
| 3 |
+
|
| 4 |
+
__all__ = ["settings"]
|
config/settings.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
config/settings.py
|
| 3 |
+
==================
|
| 4 |
+
Central configuration for the entire RAG pipeline.
|
| 5 |
+
All tunable hyperparameters live here — no magic numbers scattered in code.
|
| 6 |
+
Uses pydantic-settings to load from .env file automatically.
|
| 7 |
+
|
| 8 |
+
IMPORTANT: This file sets USE_TF=0 / USE_TORCH=1 at import time to prevent
|
| 9 |
+
the broken TensorFlow installation on this machine from crashing sentence_transformers.
|
| 10 |
+
Always import config.settings BEFORE importing sentence_transformers or transformers.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
# Must be set BEFORE importing transformers / sentence_transformers
|
| 15 |
+
os.environ.setdefault("USE_TF", "0")
|
| 16 |
+
os.environ.setdefault("USE_TORCH", "1")
|
| 17 |
+
|
| 18 |
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 19 |
+
from pydantic import Field
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Settings(BaseSettings):
|
| 24 |
+
"""
|
| 25 |
+
Production RAG Configuration.
|
| 26 |
+
Values are loaded from .env file (override defaults by editing .env).
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
model_config = SettingsConfigDict(
|
| 30 |
+
env_file=".env",
|
| 31 |
+
env_file_encoding="utf-8",
|
| 32 |
+
case_sensitive=False,
|
| 33 |
+
extra="ignore",
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# ------------------------------------------------------------------ #
|
| 37 |
+
# Paths
|
| 38 |
+
# ------------------------------------------------------------------ #
|
| 39 |
+
raw_pdfs_path: Path = Field(default=Path("./raw_pdfs"))
|
| 40 |
+
qdrant_path: Path = Field(default=Path("./data/qdrant_store"))
|
| 41 |
+
bm25_index_path: Path = Field(default=Path("./data/bm25_index"))
|
| 42 |
+
processed_docs_path: Path = Field(default=Path("./data/processed"))
|
| 43 |
+
|
| 44 |
+
# ------------------------------------------------------------------ #
|
| 45 |
+
# Models
|
| 46 |
+
# ------------------------------------------------------------------ #
|
| 47 |
+
groq_api_key: str = Field(default="")
|
| 48 |
+
groq_model: str = Field(default="llama-3.3-70b-versatile")
|
| 49 |
+
|
| 50 |
+
embedding_model: str = Field(default="BAAI/bge-large-en-v1.5")
|
| 51 |
+
embedding_dim: int = Field(default=1024) # bge-large output dimension (NOT 768 — that's bge-base)
|
| 52 |
+
|
| 53 |
+
reranker_model: str = Field(default="BAAI/bge-reranker-base")
|
| 54 |
+
|
| 55 |
+
device: str = Field(default="auto") # auto | cuda | cpu
|
| 56 |
+
|
| 57 |
+
# ------------------------------------------------------------------ #
|
| 58 |
+
# Qdrant / Vector Store
|
| 59 |
+
# ------------------------------------------------------------------ #
|
| 60 |
+
qdrant_url: str = Field(default="")
|
| 61 |
+
qdrant_api_key: str = Field(default="")
|
| 62 |
+
qdrant_collection: str = Field(default="financial_rag")
|
| 63 |
+
|
| 64 |
+
# HNSW index params
|
| 65 |
+
hnsw_m: int = Field(default=16) # connections per node
|
| 66 |
+
hnsw_ef_construct: int = Field(default=200) # build accuracy
|
| 67 |
+
|
| 68 |
+
# ------------------------------------------------------------------ #
|
| 69 |
+
# Chunking Hyperparameters
|
| 70 |
+
# ------------------------------------------------------------------ #
|
| 71 |
+
# Child chunks (used for retrieval / indexing)
|
| 72 |
+
child_chunk_size: int = Field(default=350) # tokens
|
| 73 |
+
child_chunk_overlap: int = Field(default=50) # tokens (~14% overlap)
|
| 74 |
+
|
| 75 |
+
# Parent chunks (returned to LLM as context)
|
| 76 |
+
parent_chunk_size: int = Field(default=1800) # tokens
|
| 77 |
+
parent_chunk_overlap: int = Field(default=100) # tokens
|
| 78 |
+
|
| 79 |
+
# Minimum chunk size — discard orphan fragments
|
| 80 |
+
min_chunk_tokens: int = Field(default=80)
|
| 81 |
+
|
| 82 |
+
# Font size threshold to detect headings in PyMuPDF
|
| 83 |
+
heading_font_size_threshold: float = Field(default=12.0)
|
| 84 |
+
|
| 85 |
+
# ------------------------------------------------------------------ #
|
| 86 |
+
# Retrieval Hyperparameters
|
| 87 |
+
# ------------------------------------------------------------------ #
|
| 88 |
+
# How many candidates to retrieve at each stage
|
| 89 |
+
dense_top_k: int = Field(default=30) # dense retrieval candidates
|
| 90 |
+
sparse_top_k: int = Field(default=30) # BM25 candidates
|
| 91 |
+
rrf_k: int = Field(default=60) # RRF constant (standard = 60)
|
| 92 |
+
rerank_top_n: int = Field(default=5) # final chunks after reranking
|
| 93 |
+
|
| 94 |
+
# Query expansion: number of paraphrased queries to generate
|
| 95 |
+
num_expanded_queries: int = Field(default=3)
|
| 96 |
+
|
| 97 |
+
# Score threshold — discard chunks below this similarity
|
| 98 |
+
score_threshold: float = Field(default=0.35)
|
| 99 |
+
|
| 100 |
+
# ------------------------------------------------------------------ #
|
| 101 |
+
# LLM Generation
|
| 102 |
+
# ------------------------------------------------------------------ #
|
| 103 |
+
llm_temperature: float = Field(default=0.1) # low = more factual
|
| 104 |
+
llm_max_tokens: int = Field(default=2048)
|
| 105 |
+
llm_context_window: int = Field(default=8192)
|
| 106 |
+
|
| 107 |
+
# ------------------------------------------------------------------ #
|
| 108 |
+
# Embedding Batch Processing
|
| 109 |
+
# ------------------------------------------------------------------ #
|
| 110 |
+
embed_batch_size: int = Field(default=32)
|
| 111 |
+
|
| 112 |
+
# ------------------------------------------------------------------ #
|
| 113 |
+
# Metadata / Fiscal Year
|
| 114 |
+
# ------------------------------------------------------------------ #
|
| 115 |
+
# BSE India: Financial year = April to March
|
| 116 |
+
# Reports filed Apr–Jun 2025 → FY2024-25
|
| 117 |
+
default_fiscal_year: str = Field(default="FY2025")
|
| 118 |
+
|
| 119 |
+
# Known company name → ticker mapping (for metadata tagging)
|
| 120 |
+
company_ticker_map: dict = Field(default={
|
| 121 |
+
"AIRTEL": "BHARTIARTL",
|
| 122 |
+
"AXIS": "AXISBANK",
|
| 123 |
+
"BAJAJ": "BAJFINANCE",
|
| 124 |
+
"HCL": "HCLTECH",
|
| 125 |
+
"HDFC": "HDFCBANK",
|
| 126 |
+
"HU": "HINDUNILVR",
|
| 127 |
+
"ICICI": "ICICIBANK",
|
| 128 |
+
"INFOSYS": "INFY",
|
| 129 |
+
"ITC": "ITC",
|
| 130 |
+
"KOTAK": "KOTAKBANK",
|
| 131 |
+
"KVB": "KARURVYSYA",
|
| 132 |
+
"L&T": "LT",
|
| 133 |
+
"MARUTI": "MARUTI",
|
| 134 |
+
"MRF": "MRF",
|
| 135 |
+
"ONGC": "ONGC",
|
| 136 |
+
"REL": "RELIANCE",
|
| 137 |
+
"SBI": "SBIN",
|
| 138 |
+
"TCS": "TCS",
|
| 139 |
+
})
|
| 140 |
+
|
| 141 |
+
# ------------------------------------------------------------------ #
|
| 142 |
+
# Logging
|
| 143 |
+
# ------------------------------------------------------------------ #
|
| 144 |
+
log_level: str = Field(default="INFO")
|
| 145 |
+
|
| 146 |
+
def get_device(self) -> str:
|
| 147 |
+
"""Resolve 'auto' to actual device string."""
|
| 148 |
+
if self.device == "auto":
|
| 149 |
+
try:
|
| 150 |
+
import torch
|
| 151 |
+
return "cuda" if torch.cuda.is_available() else "cpu"
|
| 152 |
+
except ImportError:
|
| 153 |
+
return "cpu"
|
| 154 |
+
return self.device
|
| 155 |
+
|
| 156 |
+
def ensure_dirs(self) -> None:
|
| 157 |
+
"""Create all required data directories if they don't exist."""
|
| 158 |
+
dirs = [
|
| 159 |
+
self.qdrant_path,
|
| 160 |
+
self.bm25_index_path,
|
| 161 |
+
self.processed_docs_path,
|
| 162 |
+
]
|
| 163 |
+
for d in dirs:
|
| 164 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# Singleton settings instance — import this everywhere
|
| 168 |
+
settings = Settings()
|
data/bm25_index/bm25.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a66665e27415615d4edcf594d3fcabbf2a16f0590891f938346d6dd0bdfe1670
|
| 3 |
+
size 7513418
|
data/bm25_index/docs.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/chat_history.db
ADDED
|
Binary file (94.2 kB). View file
|
|
|
docs/chat_screenshot.png
ADDED
|
Git LFS Details
|
docs/chat_screenshot2.png
ADDED
|
Git LFS Details
|
docs/compare_screenshot.png
ADDED
|
Git LFS Details
|
docs/dashboard_screenshot.png
ADDED
|
Git LFS Details
|
docs/main_ui.png
ADDED
|
Git LFS Details
|
raw_pdfs/AIRTEL.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ffa09ffb84a9a7227aebec50349bc8eda1703367423297263b34978c965ec63e
|
| 3 |
+
size 11537945
|
raw_pdfs/AXIS.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eaa1ed42ce4dcab5171ed8397c82de934672520cb5c564b16371580e76ce17e1
|
| 3 |
+
size 11565500
|
raw_pdfs/BAJAJ.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4d351d4b9e9f7967024a45f742b06af4f5a1eea19bb4edae65e011a96facd835
|
| 3 |
+
size 24748183
|
raw_pdfs/HCL.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:961964d275ffa47dcf64de645a17ddb8ad528ee485225ed4d61d043abbe22584
|
| 3 |
+
size 3562300
|
raw_pdfs/HDFC.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:771ea082ef816ef545a461386c754b28a179c54122c2bff719969a7d2826f116
|
| 3 |
+
size 3385161
|
raw_pdfs/HU.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e74b121cc2e81faf5d88cbab13ffde50d94a7e7e6393449cfb8ba2e3b7aca9c7
|
| 3 |
+
size 10323093
|
raw_pdfs/ICICI-1.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:185da6e4ef6d4b4f4d46651fca44fa5d03aaa9896f23dacb8c4632cf231cf62c
|
| 3 |
+
size 7405296
|
raw_pdfs/ICICI-2.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:683090513f3aaa94a4b1d80881e97791a602c5a30335c9f7d2c5a2d8113edd3d
|
| 3 |
+
size 14432316
|
raw_pdfs/INFOSYS-1.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f572c75144e5e94d236a07338241d1df8a1a0fd4bb2586bd4648ccaa16cf0874
|
| 3 |
+
size 13479064
|
raw_pdfs/INFOSYS-2.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:52a4806c71b9ea9aa638afa98892872de04f00198dd4ba5568ba2a9db01fc696
|
| 3 |
+
size 24602967
|
raw_pdfs/ITC.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:caebfa5858812fa4f6d45ad869f93c7ba98d7df271ff8d184cfd95c7e4fffc9a
|
| 3 |
+
size 8835583
|
raw_pdfs/KOTAK-1.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4711799115d5f9136a2d34ae9036d46f721a38099066605c26d99b062c065a64
|
| 3 |
+
size 7610804
|
raw_pdfs/KOTAK-2.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ccfc0c8342ba0477f645e4b2d7cd28a1ad7148268cb048d9f793f89c7617d2bf
|
| 3 |
+
size 8311729
|
raw_pdfs/KVB.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:947c5ed406b3500ce2162627647ee964307794a0d8d9218e774ae5ee537c5daa
|
| 3 |
+
size 6682873
|
raw_pdfs/L&T.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e3ae9197774db11fc5152da67d77715569a3861ee56ae4c67c835624ca779b2a
|
| 3 |
+
size 2224630
|
raw_pdfs/MARUTI.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5e1707ba47fca6d987c3ea8a3966422c8399cc238027fe300d80bf1cd3286930
|
| 3 |
+
size 6470898
|
raw_pdfs/MRF.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:85d3baa366f1d6c9fea309596df3bc9d6af5d5d4db06df42f5265713b04e177a
|
| 3 |
+
size 12350351
|
raw_pdfs/ONGC.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2000b2ac6d4003431a12cd6d88779769dd4211dd4aced450c956be3375d474ac
|
| 3 |
+
size 18473570
|
raw_pdfs/REL.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fb1d955d020af91eca05f6b5099adc1e4bf5fac876878b966ea90f6a989f5c0c
|
| 3 |
+
size 11382737
|
raw_pdfs/SBI-1.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:08c572aafab2c27e0a0a7474493458983968b5bcdce33ba0fda2de6fd4c5bc6b
|
| 3 |
+
size 3953780
|
raw_pdfs/SBI-2.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:20683bf74cd8f81e17047802c6e33afd0cd1107050248b7b6a2d7ffd2bbe5d5b
|
| 3 |
+
size 4870767
|
raw_pdfs/TCS-1.pdf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ad6961834e1ddd9ad06c7dd734214f3daf8ca1062b6086fa0b611f1e6a7c0a61
|
| 3 |
+
size 3350055
|