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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""SLM with RAG for financial statements"""
|
2 |
+
|
3 |
+
# Importing the dependencies
|
4 |
+
import logging
|
5 |
+
import os
|
6 |
+
import subprocess
|
7 |
+
import time
|
8 |
+
import re
|
9 |
+
import pickle
|
10 |
+
import numpy as np
|
11 |
+
import pandas as pd
|
12 |
+
import torch
|
13 |
+
import spacy
|
14 |
+
import pdfplumber
|
15 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
16 |
+
import gradio as gr
|
17 |
+
import faiss
|
18 |
+
from rank_bm25 import BM25Okapi
|
19 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
20 |
+
from data_filters import (
|
21 |
+
restricted_patterns,
|
22 |
+
restricted_topics,
|
23 |
+
FINANCIAL_DATA_PATTERNS,
|
24 |
+
sensitive_terms,
|
25 |
+
FINANCIAL_TERMS,
|
26 |
+
)
|
27 |
+
|
28 |
+
# Initialize logger
|
29 |
+
logging.basicConfig(
|
30 |
+
# filename="app.log",
|
31 |
+
level=logging.INFO,
|
32 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
33 |
+
)
|
34 |
+
logger = logging.getLogger()
|
35 |
+
os.makedirs("data", exist_ok=True)
|
36 |
+
|
37 |
+
# SLM: Microsoft PHI-2 model is loaded
|
38 |
+
# It does have higher memory and compute requirements compared to TinyLlama and Falcon
|
39 |
+
# But it gives the best results among the three
|
40 |
+
DEVICE = "cpu" # or cuda
|
41 |
+
# MODEL_NAME = "TinyLlama/TinyLlama_v1.1"
|
42 |
+
# MODEL_NAME = "tiiuae/falcon-rw-1b"
|
43 |
+
MODEL_NAME = "microsoft/phi-2"
|
44 |
+
# MODEL_NAME = "google/gemma-3-1b-pt"
|
45 |
+
# Load the Tokenizer for PHI-2
|
46 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
|
47 |
+
MAX_TOKENS = tokenizer.model_max_length
|
48 |
+
CONTEXT_MULTIPLIER = 0.7
|
49 |
+
# The max_context tokens is used to limit the retrieved chunks during querying
|
50 |
+
# to provide some headroom for the query
|
51 |
+
MAX_CONTEXT_TOKENS = int(MAX_TOKENS * CONTEXT_MULTIPLIER)
|
52 |
+
if tokenizer.pad_token is None:
|
53 |
+
tokenizer.pad_token = tokenizer.eos_token
|
54 |
+
# Since the model is to be hosted on a cpu instance, we use float32
|
55 |
+
# For GPU, we can use float16 or bfloat16
|
56 |
+
model = AutoModelForCausalLM.from_pretrained(
|
57 |
+
MODEL_NAME, torch_dtype=torch.float32, trust_remote_code=True
|
58 |
+
).to(DEVICE)
|
59 |
+
model.eval()
|
60 |
+
# model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
|
61 |
+
logger.info("Model loaded successfully.")
|
62 |
+
# Load Sentence Transformer for Embeddings and Cross Encoder for re-ranking
|
63 |
+
embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
64 |
+
cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
|
65 |
+
# Load spaCy English model for Named Entity Recognition (mainly for guardrail)
|
66 |
+
try:
|
67 |
+
nlp = spacy.load("en_core_web_sm")
|
68 |
+
except OSError:
|
69 |
+
subprocess.run(["python", "-m", "spacy", "download", "en_core_web_sm"])
|
70 |
+
nlp = spacy.load("en_core_web_sm")
|
71 |
+
|
72 |
+
|
73 |
+
# Extract the yaer from the upload file's name if any
|
74 |
+
def extract_year_from_filename(filename):
|
75 |
+
"""Extract Year from Filename"""
|
76 |
+
match = re.search(r"(\d{4})-(\d{4})", filename)
|
77 |
+
if match:
|
78 |
+
return match.group(1)
|
79 |
+
match = re.search(r"(\d{4})", filename)
|
80 |
+
return match.group(1) if match else "Unknown"
|
81 |
+
|
82 |
+
|
83 |
+
# Use PDFPlumber to extract the tables from the uploaded file
|
84 |
+
# Add the year column for context and create a dataframe
|
85 |
+
def extract_tables_from_pdf(pdf_path):
|
86 |
+
"""Extract tables from PDF into a DataFrame"""
|
87 |
+
all_tables = []
|
88 |
+
report_year = extract_year_from_filename(pdf_path)
|
89 |
+
with pdfplumber.open(pdf_path) as pdf:
|
90 |
+
for page_num, page in enumerate(pdf.pages, start=1):
|
91 |
+
tables = page.extract_tables()
|
92 |
+
for table in tables:
|
93 |
+
df = pd.DataFrame(table)
|
94 |
+
df["year"] = report_year
|
95 |
+
all_tables.append(df)
|
96 |
+
return pd.concat(all_tables, ignore_index=True) if all_tables else pd.DataFrame()
|
97 |
+
|
98 |
+
|
99 |
+
# Load the csv files directly using pandas into a dataframe
|
100 |
+
def load_csv(file_path):
|
101 |
+
"""Loads a CSV file into a DataFrame"""
|
102 |
+
try:
|
103 |
+
df = pd.read_csv(file_path)
|
104 |
+
df["year"] = extract_year_from_filename(file_path)
|
105 |
+
return df
|
106 |
+
except Exception as e:
|
107 |
+
print(f"Error loading CSV: {e}")
|
108 |
+
return None
|
109 |
+
|
110 |
+
|
111 |
+
# Preprocess the dataframe - Replace null values and create text rows suitable for chunking
|
112 |
+
def clean_dataframe_text(df):
|
113 |
+
"""Clean and format PDF/CSV data"""
|
114 |
+
df.fillna("", inplace=True)
|
115 |
+
text_data = []
|
116 |
+
for _, row in df.iterrows():
|
117 |
+
parts = []
|
118 |
+
if "year" in df.columns:
|
119 |
+
parts.append(f"Year: {row['year']}")
|
120 |
+
parts.extend([str(val).strip() for val in row if str(val).strip()])
|
121 |
+
text_data.append(", ".join(parts))
|
122 |
+
df["text"] = text_data
|
123 |
+
return df[["text"]].replace("", np.nan).dropna()
|
124 |
+
|
125 |
+
|
126 |
+
# Chunk the text for retrival
|
127 |
+
# Different chunk sizes - 256,512,1024,2048 were tried and 512 worked the best for financial RAG
|
128 |
+
def chunk_text(text, chunk_size=512):
|
129 |
+
"""Apply Chunking on the text"""
|
130 |
+
words = text.split()
|
131 |
+
chunks, temp_chunk = [], []
|
132 |
+
for word in words:
|
133 |
+
if sum(len(w) for w in temp_chunk) + len(temp_chunk) + len(word) <= chunk_size:
|
134 |
+
temp_chunk.append(word)
|
135 |
+
else:
|
136 |
+
chunks.append(" ".join(temp_chunk))
|
137 |
+
temp_chunk = [word]
|
138 |
+
if temp_chunk:
|
139 |
+
chunks.append(" ".join(temp_chunk))
|
140 |
+
return chunks
|
141 |
+
|
142 |
+
|
143 |
+
# Uses regex to identify financial terms and ensure relevant data is only merged
|
144 |
+
def is_financial_text(text):
|
145 |
+
"""Detects financial data"""
|
146 |
+
return bool(
|
147 |
+
re.search(
|
148 |
+
FINANCIAL_DATA_PATTERNS,
|
149 |
+
text,
|
150 |
+
re.IGNORECASE,
|
151 |
+
)
|
152 |
+
)
|
153 |
+
|
154 |
+
|
155 |
+
# Uses a sentence transformer "all-MiniLM-L6-v2" to embed text chunks
|
156 |
+
# Stores embeddings in a FAISS vector database for similarity search
|
157 |
+
# BM25 is implemented alongside FAISS to improve retrieval
|
158 |
+
# Use FAISS Cosine Similarity index and merge only highly similar text chunks (>85%)
|
159 |
+
def merge_similar_chunks(chunks, similarity_threshold=0.85):
|
160 |
+
"""Merge similar chunks while preserving financial data structure"""
|
161 |
+
if not chunks:
|
162 |
+
return []
|
163 |
+
# Encode chunks into embeddings
|
164 |
+
embeddings = np.array(
|
165 |
+
embed_model.encode(chunks, normalize_embeddings=True), dtype="float32"
|
166 |
+
)
|
167 |
+
# FAISS Cosine Similarity Index
|
168 |
+
index = faiss.IndexFlatIP(embeddings.shape[1])
|
169 |
+
index.add(embeddings)
|
170 |
+
# Get top-2 most similar chunks
|
171 |
+
_, indices = index.search(embeddings, 2)
|
172 |
+
merged_chunks = {}
|
173 |
+
for i, idx in enumerate(indices[:, 1]):
|
174 |
+
if i in merged_chunks or idx in merged_chunks:
|
175 |
+
continue
|
176 |
+
sim_score = np.dot(embeddings[i], embeddings[idx])
|
177 |
+
# Ensure financial data isn't incorrectly merged
|
178 |
+
if is_financial_text(chunks[i]) or is_financial_text(chunks[idx]):
|
179 |
+
merged_chunks[i] = chunks[i]
|
180 |
+
merged_chunks[idx] = chunks[idx]
|
181 |
+
continue
|
182 |
+
# Merge only if similarity is high and chunks are adjacent
|
183 |
+
if sim_score > similarity_threshold and abs(i - idx) == 1:
|
184 |
+
merged_chunks[i] = chunks[i] + " " + chunks[idx]
|
185 |
+
merged_chunks[idx] = merged_chunks[i]
|
186 |
+
else:
|
187 |
+
merged_chunks[i] = chunks[i]
|
188 |
+
return list(set(merged_chunks.values()))
|
189 |
+
|
190 |
+
|
191 |
+
# Handle for file upload button in UI
|
192 |
+
# Processes the uploaded files and generates the embeddings
|
193 |
+
# The FAISS embeddings and tokenized chunks are saved for retrieval
|
194 |
+
def process_files(files, chunk_size=512):
|
195 |
+
"""Process uploaded files and generate embeddings"""
|
196 |
+
if not files:
|
197 |
+
logger.warning("No files uploaded!")
|
198 |
+
return "Please upload at least one PDF or CSV file."
|
199 |
+
pdf_paths = [file.name for file in files if file.name.endswith(".pdf")]
|
200 |
+
csv_paths = [file.name for file in files if file.name.endswith(".csv")]
|
201 |
+
logger.info(f"Processing {len(pdf_paths)} PDFs and {len(csv_paths)} CSVs")
|
202 |
+
df_list = []
|
203 |
+
if pdf_paths:
|
204 |
+
df_list.extend([extract_tables_from_pdf(pdf) for pdf in pdf_paths])
|
205 |
+
for csv in csv_paths:
|
206 |
+
df = load_csv(csv)
|
207 |
+
df_list.append(df)
|
208 |
+
if not df_list:
|
209 |
+
logger.warning("No valid data found in the uploaded files")
|
210 |
+
return "No valid data found in the uploaded files"
|
211 |
+
df = pd.concat(df_list, ignore_index=True)
|
212 |
+
df.dropna(how="all", inplace=True)
|
213 |
+
logger.info("Data extracted from the files")
|
214 |
+
df_cleaned = clean_dataframe_text(df)
|
215 |
+
df_cleaned["chunks"] = df_cleaned["text"].apply(lambda x: chunk_text(x, chunk_size))
|
216 |
+
df_chunks = df_cleaned.explode("chunks").reset_index(drop=True)
|
217 |
+
merged_chunks = merge_similar_chunks(df_chunks["chunks"].tolist())
|
218 |
+
chunk_texts = merged_chunks
|
219 |
+
# chunk_texts = df_chunks["chunks"].tolist()
|
220 |
+
embeddings = np.array(
|
221 |
+
embed_model.encode(chunk_texts, normalize_embeddings=True), dtype="float32"
|
222 |
+
)
|
223 |
+
# Save FAISS index
|
224 |
+
index = faiss.IndexFlatL2(embeddings.shape[1])
|
225 |
+
index.add(embeddings)
|
226 |
+
faiss.write_index(index, "data/faiss_index.bin")
|
227 |
+
logger.info("FAISS index created and saved.")
|
228 |
+
# Save BM25 index
|
229 |
+
tokenized_chunks = [text.lower().split() for text in chunk_texts]
|
230 |
+
bm25_data = {"tokenized_chunks": tokenized_chunks, "chunk_texts": chunk_texts}
|
231 |
+
logger.info("BM25 index created and saved.")
|
232 |
+
with open("data/bm25_data.pkl", "wb") as f:
|
233 |
+
pickle.dump(bm25_data, f)
|
234 |
+
return "Files processed successfully! You can now query."
|
235 |
+
|
236 |
+
|
237 |
+
# Input guardrail implementation
|
238 |
+
# Regex is used to filter queries related to sensitive topics
|
239 |
+
# Uses spaCy model's Named Entity Recognition to filter queries for personal details
|
240 |
+
# Uses cosine similarity with the embedded query and sensitive topic vectors
|
241 |
+
# to filter out queries violating confidential/security rules (additional)
|
242 |
+
def is_query_allowed(query):
|
243 |
+
"""Checks if the query violates security or confidentiality rules"""
|
244 |
+
for pattern in restricted_patterns:
|
245 |
+
if re.search(pattern, query, re.IGNORECASE):
|
246 |
+
return False, "This query requests sensitive or confidential information."
|
247 |
+
doc = nlp(query)
|
248 |
+
for ent in doc.ents:
|
249 |
+
if ent.label_ == "PERSON":
|
250 |
+
for token in ent.subtree:
|
251 |
+
if token.text.lower() in sensitive_terms:
|
252 |
+
return (
|
253 |
+
False,
|
254 |
+
"Query contains personal salary information, which is restricted.",
|
255 |
+
)
|
256 |
+
query_embedding = embed_model.encode(query, normalize_embeddings=True)
|
257 |
+
topic_embeddings = embed_model.encode(
|
258 |
+
list(restricted_topics), normalize_embeddings=True
|
259 |
+
)
|
260 |
+
similarities = np.dot(topic_embeddings, query_embedding)
|
261 |
+
if np.max(similarities) > 0.85:
|
262 |
+
return False, "This query requests sensitive or confidential information."
|
263 |
+
return True, None
|
264 |
+
|
265 |
+
|
266 |
+
# Boosts the scores for texts containing financial terms
|
267 |
+
# This is useful during re-ranking
|
268 |
+
def boost_score(text, base_score, boost_factor=1.2):
|
269 |
+
"""Boost scores if the text contains financial terms"""
|
270 |
+
if any(term in text.lower() for term in FINANCIAL_TERMS):
|
271 |
+
return base_score * boost_factor
|
272 |
+
return base_score
|
273 |
+
|
274 |
+
|
275 |
+
# FAISS embeddings are used to retrieve semantically similar chunks
|
276 |
+
# BM25 is used to retrieve relevant chunks based on the keywords (TF-IDF)
|
277 |
+
# FAISS and BM25 complement each other- similar matches and important exact matches
|
278 |
+
# The retrieved chunks are merged and sorted based on a lambda FAISS value
|
279 |
+
# if lambda FAISS is 0.6, weightage for retrieved FAISS chunks are 0.6 and 0.4 for BM25 chunks
|
280 |
+
# Cross encoder model ms-marco-MiniLM-L6-v2 is used for scoring and re-ranking the chunks
|
281 |
+
def hybrid_retrieve(query, chunk_texts, index, bm25, top_k=5, lambda_faiss=0.7):
|
282 |
+
"""Hybrid Retrieval with FAISS, BM25, Cross-Encoder & Financial Term Boosting"""
|
283 |
+
# FAISS Retrieval
|
284 |
+
query_embedding = np.array(
|
285 |
+
[embed_model.encode(query, normalize_embeddings=True)], dtype="float32"
|
286 |
+
)
|
287 |
+
_, faiss_indices = index.search(query_embedding, top_k)
|
288 |
+
faiss_results = [chunk_texts[idx] for idx in faiss_indices[0]]
|
289 |
+
# BM25 Retrieval
|
290 |
+
tokenized_query = query.lower().split()
|
291 |
+
bm25_scores = bm25.get_scores(tokenized_query)
|
292 |
+
bm25_top_indices = np.argsort(bm25_scores)[::-1][:top_k]
|
293 |
+
bm25_results = [chunk_texts[idx] for idx in bm25_top_indices]
|
294 |
+
# Merge FAISS & BM25 Scores
|
295 |
+
results = {}
|
296 |
+
for entry in faiss_results:
|
297 |
+
results[entry] = boost_score(entry, lambda_faiss)
|
298 |
+
for entry in bm25_results:
|
299 |
+
results[entry] = results.get(entry, 0) + boost_score(entry, (1 - lambda_faiss))
|
300 |
+
# Rank initial results
|
301 |
+
retrieved_docs = sorted(results.items(), key=lambda x: x[1], reverse=True)
|
302 |
+
retrieved_texts = [r[0] for r in retrieved_docs]
|
303 |
+
# Cross-Encoder Re-Ranking
|
304 |
+
query_text_pairs = [[query, text] for text in retrieved_texts]
|
305 |
+
scores = cross_encoder.predict(query_text_pairs)
|
306 |
+
ranked_indices = np.argsort(scores)[::-1]
|
307 |
+
# Return top-ranked results
|
308 |
+
final_results = [retrieved_texts[i] for i in ranked_indices[:top_k]]
|
309 |
+
return final_results
|
310 |
+
|
311 |
+
|
312 |
+
# A confidence score is computed using FAISS and BM25 ranking
|
313 |
+
# FAISS: The similarity score between the query (with response) and the retrieved chunks are normalized
|
314 |
+
# BM25: The BM25 scores for the query is normalized
|
315 |
+
# Both the scores are aggregated using a weighted sum (lambda FAISS) and normalized
|
316 |
+
def compute_confidence_score(query, retrieved_chunks, bm25, lambda_faiss):
|
317 |
+
"""Calculates a confidence score using FAISS and BM25 rankings."""
|
318 |
+
if not retrieved_chunks:
|
319 |
+
return 0
|
320 |
+
query_embedding = embed_model.encode(query, normalize_embeddings=True)
|
321 |
+
response_embedding = embed_model.encode(
|
322 |
+
" ".join(retrieved_chunks), normalize_embeddings=True
|
323 |
+
)
|
324 |
+
# FAISS Similarity
|
325 |
+
faiss_score = np.dot(query_embedding, response_embedding)
|
326 |
+
normalized_faiss = (faiss_score + 1) / 2
|
327 |
+
# BM25 Ranking
|
328 |
+
tokenized_query = query.lower().split()
|
329 |
+
bm25_scores = bm25.get_scores(tokenized_query)
|
330 |
+
if bm25_scores.size > 0:
|
331 |
+
min_bm25 = (
|
332 |
+
np.min(bm25_scores) if np.min(bm25_scores) != np.max(bm25_scores) else 0
|
333 |
+
)
|
334 |
+
max_bm25 = (
|
335 |
+
np.max(bm25_scores) if np.min(bm25_scores) != np.max(bm25_scores) else 1
|
336 |
+
)
|
337 |
+
bm25_score = (
|
338 |
+
np.mean([bm25_scores[idx] for idx in range(len(retrieved_chunks))])
|
339 |
+
if len(retrieved_chunks) > 0
|
340 |
+
else 0
|
341 |
+
)
|
342 |
+
normalized_bm25 = (bm25_score - min_bm25) / (max_bm25 - min_bm25)
|
343 |
+
normalized_bm25 = max(0, min(1, normalized_bm25))
|
344 |
+
else:
|
345 |
+
normalized_bm25 = 0
|
346 |
+
# Final Confidence Score (use Lambda FAISS value for weighted sum)
|
347 |
+
confidence_score = round(
|
348 |
+
(normalized_faiss * lambda_faiss + normalized_bm25 * (1 - lambda_faiss)), 2
|
349 |
+
)
|
350 |
+
return confidence_score
|
351 |
+
|
352 |
+
|
353 |
+
# UI handle for query model button
|
354 |
+
# Loads the saved FAISS embeddings and tokenized chunks for BM25
|
355 |
+
# Check the query for any policy violation
|
356 |
+
# Retrieve similar texts using the RAG implementation
|
357 |
+
# Prompt the loaded SLM along with the retrieved texts and compute confidence score
|
358 |
+
def query_model(
|
359 |
+
query,
|
360 |
+
top_k=10,
|
361 |
+
lambda_faiss=0.5,
|
362 |
+
repetition_penalty=1.5,
|
363 |
+
max_new_tokens=100,
|
364 |
+
use_extraction=False,
|
365 |
+
):
|
366 |
+
"""Query function"""
|
367 |
+
start_time = time.perf_counter()
|
368 |
+
# Check if FAISS and BM25 indexes exist
|
369 |
+
if not os.path.exists("data/faiss_index.bin") or not os.path.exists(
|
370 |
+
"data/bm25_data.pkl"
|
371 |
+
):
|
372 |
+
logger.error("No index found! Prompting user to upload PDFs.")
|
373 |
+
return (
|
374 |
+
"Index files not found! Please upload PDFs first to generate embeddings.",
|
375 |
+
"Error",
|
376 |
+
)
|
377 |
+
allowed, reason = is_query_allowed(query)
|
378 |
+
if not allowed:
|
379 |
+
logger.error(f"Query Rejected: {reason}")
|
380 |
+
return f"Query Rejected: {reason}", "Warning"
|
381 |
+
logger.info(
|
382 |
+
f"Received query: {query} | Top-K: {top_k}, "
|
383 |
+
f"Lambda: {lambda_faiss}, Tokens: {max_new_tokens}"
|
384 |
+
)
|
385 |
+
# Load FAISS & BM25 Indexes
|
386 |
+
index = faiss.read_index("data/faiss_index.bin")
|
387 |
+
with open("data/bm25_data.pkl", "rb") as f:
|
388 |
+
bm25_data = pickle.load(f)
|
389 |
+
# Restore tokenized chunks and metadata
|
390 |
+
tokenized_chunks = bm25_data["tokenized_chunks"]
|
391 |
+
chunk_texts = bm25_data["chunk_texts"]
|
392 |
+
bm25 = BM25Okapi(tokenized_chunks)
|
393 |
+
retrieved_chunks = hybrid_retrieve(
|
394 |
+
query, chunk_texts, index, bm25, top_k=top_k, lambda_faiss=lambda_faiss
|
395 |
+
)
|
396 |
+
logger.info("Retrieved chunks")
|
397 |
+
context = ""
|
398 |
+
token_count = 0
|
399 |
+
# context = "\n".join(retrieved_chunks)
|
400 |
+
for chunk in retrieved_chunks:
|
401 |
+
chunk_tokens = tokenizer(chunk, return_tensors="pt")["input_ids"].shape[1]
|
402 |
+
if token_count + chunk_tokens < MAX_CONTEXT_TOKENS:
|
403 |
+
context += chunk + "\n"
|
404 |
+
token_count += chunk_tokens
|
405 |
+
else:
|
406 |
+
break
|
407 |
+
prompt = (
|
408 |
+
f"Based on the following information:\n\n{context}\n\n"
|
409 |
+
"Answer the query in one or two sentences. "
|
410 |
+
"Do not provide follow-ups. "
|
411 |
+
f"Answer the query: {query}"
|
412 |
+
)
|
413 |
+
inputs = tokenizer(prompt, return_tensors="pt", padding=True).to(DEVICE)
|
414 |
+
inputs.pop("token_type_ids", None)
|
415 |
+
logger.info("Generating output")
|
416 |
+
input_len = inputs["input_ids"].shape[-1]
|
417 |
+
with torch.inference_mode():
|
418 |
+
output = model.generate(
|
419 |
+
**inputs,
|
420 |
+
max_new_tokens=max_new_tokens,
|
421 |
+
num_return_sequences=1,
|
422 |
+
repetition_penalty=repetition_penalty,
|
423 |
+
pad_token_id=tokenizer.eos_token_id,
|
424 |
+
)
|
425 |
+
start_len = 0
|
426 |
+
if use_extraction:
|
427 |
+
start_len = input_len
|
428 |
+
output = output[0][start_len:]
|
429 |
+
execution_time = time.perf_counter() - start_time
|
430 |
+
logger.info(f"Query processed in {execution_time:.2f} seconds.")
|
431 |
+
response = tokenizer.decode(output, skip_special_tokens=True)
|
432 |
+
confidence_score = compute_confidence_score(
|
433 |
+
query + " " + response, retrieved_chunks, bm25, lambda_faiss
|
434 |
+
)
|
435 |
+
logger.info(f"Confidence: {confidence_score*100}%")
|
436 |
+
if confidence_score <= 0.3:
|
437 |
+
logger.error(f"The system is unsure about this response.")
|
438 |
+
response += "\nThe system is unsure about this response."
|
439 |
+
return (
|
440 |
+
response,
|
441 |
+
f"Confidence: {confidence_score*100}%\nTime taken: {execution_time:.2f} seconds",
|
442 |
+
)
|
443 |
+
|
444 |
+
|
445 |
+
# Gradio UI
|
446 |
+
with gr.Blocks(title="Financial Statement RAG with LLM") as ui:
|
447 |
+
gr.Markdown("## Financial Statement RAG with LLM")
|
448 |
+
# File upload section
|
449 |
+
with gr.Group():
|
450 |
+
gr.Markdown("### Upload & Process Annual Reports")
|
451 |
+
file_input = gr.File(
|
452 |
+
file_count="multiple",
|
453 |
+
file_types=[".pdf", ".csv"],
|
454 |
+
type="filepath",
|
455 |
+
label="Upload Annual Reports (PDFs/CSVs)",
|
456 |
+
)
|
457 |
+
process_button = gr.Button("Process Files")
|
458 |
+
process_output = gr.Textbox(label="Processing Status", interactive=False)
|
459 |
+
# Query model section
|
460 |
+
with gr.Group():
|
461 |
+
gr.Markdown("### Ask a Financial Query")
|
462 |
+
query_input = gr.Textbox(label="Enter Query")
|
463 |
+
with gr.Row():
|
464 |
+
top_k_input = gr.Number(value=15, label="Top K (Default: 15)")
|
465 |
+
lambda_faiss_input = gr.Slider(0, 1, value=0.5, label="Lambda FAISS (0-1)")
|
466 |
+
repetition_penalty = gr.Slider(
|
467 |
+
1, 2, value=1.0, label="Repetition Penality (1-2)"
|
468 |
+
)
|
469 |
+
max_tokens_input = gr.Number(value=100, label="Max New Tokens")
|
470 |
+
use_extraction = gr.Checkbox(label="Retrieve only the answer", value=False)
|
471 |
+
query_button = gr.Button("Submit Query")
|
472 |
+
query_output = gr.Textbox(label="Query Response", interactive=False)
|
473 |
+
time_output = gr.Textbox(label="Time Taken", interactive=False)
|
474 |
+
# Button Actions
|
475 |
+
process_button.click(process_files, inputs=[file_input], outputs=process_output)
|
476 |
+
query_button.click(
|
477 |
+
query_model,
|
478 |
+
inputs=[
|
479 |
+
query_input,
|
480 |
+
top_k_input,
|
481 |
+
lambda_faiss_input,
|
482 |
+
repetition_penalty,
|
483 |
+
max_tokens_input,
|
484 |
+
use_extraction,
|
485 |
+
],
|
486 |
+
outputs=[query_output, time_output],
|
487 |
+
)
|
488 |
+
# Application entry point
|
489 |
+
if __name__ == "__main__":
|
490 |
+
logger.info("Starting Gradio server...")
|
491 |
+
ui.launch(server_name="0.0.0.0", server_port=7860, pwa=True)
|
data_filters.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Sensitive data filters"""
|
2 |
+
|
3 |
+
restricted_patterns = [
|
4 |
+
r"\b(?:CFO|CEO|CTO|executive|director|manager|employee|staff|worker)\b.*\b(?:salary|compensation|bonus|pay|income)\b",
|
5 |
+
r"\b(?:salary|compensation|bonus|pay|income)\b.*\b(?:CFO|CEO|CTO|executive|director|manager|employee|staff|worker)\b",
|
6 |
+
r"\b(?:acquisition|merger|buyout)\b.*\b(?:before|pre-announcement|leak|inside information)\b",
|
7 |
+
r"\b(?:before|pre-announcement|leak|inside information)\b.*\b(?:acquisition|merger|buyout)\b",
|
8 |
+
r"\b(?:stock price|share price|insider trading|buying shares)\b",
|
9 |
+
r"\b(?:internal policy|data breach|security protocol|confidential|classified)\b",
|
10 |
+
r"\b(?:password|access credentials|encryption key|secure key)\b",
|
11 |
+
r"\b(?:social security number|SSN|passport number|credit card|bank account|tax ID|TIN|personal details)\b",
|
12 |
+
r"\b(?:employee records|payroll|medical records|HR data|salary data|PII|personally identifiable information)\b",
|
13 |
+
r"\b(?:CFO|CEO|CTO|executive|director|manager|employee|staff|worker)\b.*\b(?:address|work location|home location|residence|personal contact|phone number|email|office location)\b",
|
14 |
+
]
|
15 |
+
|
16 |
+
restricted_topics = {
|
17 |
+
"CEO salary",
|
18 |
+
"CFO salary",
|
19 |
+
"executive pay",
|
20 |
+
"stock options",
|
21 |
+
"compensation details",
|
22 |
+
"classified financial data",
|
23 |
+
"insider trading",
|
24 |
+
"password",
|
25 |
+
"login credentials",
|
26 |
+
"HR complaints",
|
27 |
+
"remuneration",
|
28 |
+
"director salary",
|
29 |
+
"financial package",
|
30 |
+
}
|
31 |
+
|
32 |
+
sensitive_terms = {
|
33 |
+
"salary",
|
34 |
+
"compensation",
|
35 |
+
"income",
|
36 |
+
"pay",
|
37 |
+
"bonus",
|
38 |
+
"earnings",
|
39 |
+
"wages",
|
40 |
+
}
|
41 |
+
|
42 |
+
|
43 |
+
FINANCIAL_DATA_PATTERNS = (
|
44 |
+
r"\b(\₹?\s?\d{1,3}(?:,\d{2,3})*(?:\.\d+)?\s*(million|billion|crore|lakh|%)"
|
45 |
+
r"?|Rs\.?\s?\d{1,3}(?:,\d{2,3})*(?:\.\d+)?)\b"
|
46 |
+
)
|
47 |
+
|
48 |
+
FINANCIAL_TERMS = {
|
49 |
+
"income",
|
50 |
+
"revenue",
|
51 |
+
"profit",
|
52 |
+
"dividend",
|
53 |
+
"investment",
|
54 |
+
"earnings",
|
55 |
+
"turnover",
|
56 |
+
"expenses",
|
57 |
+
"assets",
|
58 |
+
"liabilities",
|
59 |
+
"capital",
|
60 |
+
"cash",
|
61 |
+
"EBITDA",
|
62 |
+
"margin",
|
63 |
+
"tax",
|
64 |
+
"costs",
|
65 |
+
"reserves",
|
66 |
+
"equity",
|
67 |
+
"debt",
|
68 |
+
"interest",
|
69 |
+
"valuation",
|
70 |
+
"amortization",
|
71 |
+
"depreciation",
|
72 |
+
"returns",
|
73 |
+
"funds",
|
74 |
+
"shares",
|
75 |
+
"stock",
|
76 |
+
"pricing",
|
77 |
+
"liquidity",
|
78 |
+
"credit",
|
79 |
+
"bond",
|
80 |
+
"expense",
|
81 |
+
"budget",
|
82 |
+
"yield",
|
83 |
+
"growth",
|
84 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
numpy
|
2 |
+
pandas
|
3 |
+
matplotlib
|
4 |
+
torch
|
5 |
+
transformers
|
6 |
+
sentence_transformers
|
7 |
+
spacy
|
8 |
+
faiss-cpu
|
9 |
+
pdfplumber
|
10 |
+
rank_bm25
|
11 |
+
fastapi
|
12 |
+
gradio
|