File size: 11,555 Bytes
78f53a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91d074a
78f53a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# !pip install pdfplumber
# !pip install rank_bm25
# !pip install langchain
# pip install sentence_transformers 
# conda install -c conda-forge faiss-cpu

import pdfplumber
import pandas as pd
import numpy as np
import re
import os
from ast import literal_eval
import faiss
from llama_cpp import Llama, LlamaGrammar
from rank_bm25 import BM25Okapi
from langchain.text_splitter import RecursiveCharacterTextSplitter
from sentence_transformers import SentenceTransformer, util
from sklearn.metrics.pairwise import cosine_similarity
import PyPDF2

embedding_model = SentenceTransformer("models/all-MiniLM-L6-v2/")
llm = Llama(model_path="models/Llama-3.2-1B-Instruct-Q4_K_M.gguf",
            n_gpu_layers=-1, n_ctx=8000)


def extract_info_from_pdf(pdf_path):
    """

    Extracts both paragraphs and tables from each PDF page using pdfplumber.

    Returns a list of dictionaries with keys: "page_number", "paragraphs", "tables".

    """
    document_data = []
    with pdfplumber.open(pdf_path) as pdf:
        for i, page in enumerate(pdf.pages, start=1):
            page_data = {"page_number": i, "paragraphs": [], "tables": []}
            text = page.extract_text()
            if text:
                paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
                page_data["paragraphs"] = paragraphs
            tables = page.extract_tables()
            dfs = []
            for table in tables:
                if len(table) > 1:
                    df = pd.DataFrame(table[1:], columns=table[0])
                else:
                    df = pd.DataFrame(table)
                dfs.append(df)
            page_data["tables"] = dfs
            document_data.append(page_data)
    return document_data


def extract_financial_tables_regex(text):
    """

    Extracts financial table information using a regex pattern (basic extraction).

    """
    pattern = re.compile(r"(Revenue from Operations.*?)\n\n", re.DOTALL)
    matches = pattern.findall(text)
    if matches:
        data_lines = matches[0].split("\n")
        structured_data = [line.split() for line in data_lines if line.strip()]
        if len(structured_data) > 1:
            df = pd.DataFrame(structured_data[1:], columns=structured_data[0])
            return df
    return pd.DataFrame()


def clean_financial_data(df):
    """

    Cleans the financial DataFrame by converting numerical columns.

    """
    if df.empty:
        return ""
    for col in df.columns[1:]:
        df[col] = df[col].replace({',': ''}, regex=True)
        df[col] = pd.to_numeric(df[col], errors='coerce')
    return df.to_string()


def combine_extracted_info(document_data, financial_text_regex=""):
    """

    Combines extracted paragraphs and tables (converted to strings) into a single text.

    Optionally appends extra financial table text.

    """
    text_segments = []
    for page in document_data:
        for paragraph in page["paragraphs"]:
            text_segments.append(paragraph)
        for table in page["tables"]:
            text_segments.append(table.to_string(index=False))
    if financial_text_regex:
        text_segments.append(financial_text_regex)
    return "\n".join(text_segments)


def extract_text_from_pdf_pypdf2(pdf_path):
    text = ""
    with open(pdf_path, "rb") as file:
        reader = PyPDF2.PdfReader(file)
        for page in reader.pages:
            text += page.extract_text() + "\n"
    return text


def chunk_text(text, chunk_size=500, chunk_overlap=50):
    """

    Uses RecursiveCharacterTextSplitter to chunk text.

    """
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
    chunks = text_splitter.split_text(text)
    return chunks


def build_faiss_index(chunks, embedding_model):
    chunk_embeddings = embedding_model.encode(chunks)
    dimension = chunk_embeddings.shape[1]
    index = faiss.IndexFlatL2(dimension)
    index.add(np.array(chunk_embeddings))
    return index, chunk_embeddings


def retrieve_basic(query, index, chunks, embedding_model, k=5):
    query_embedding = embedding_model.encode([query])
    distances, indices = index.search(np.array(query_embedding), k)
    return [chunks[i] for i in indices[0]], distances[0]


def retrieve_bm25(query, chunks, k=5):
    tokenized_corpus = [chunk.lower().split() for chunk in chunks]
    bm25_model = BM25Okapi(tokenized_corpus)
    tokenized_query = query.lower().split()
    scores = bm25_model.get_scores(tokenized_query)
    top_indices = np.argsort(scores)[::-1][:k]
    return [chunks[i] for i in top_indices], scores[top_indices]


def retrieve_advanced_embedding(query, chunks, embedding_model, k=5):
    chunk_embeddings = embedding_model.encode(chunks)
    query_embedding = embedding_model.encode([query])
    scores = cosine_similarity(np.array(query_embedding), np.array(chunk_embeddings))[0]
    top_indices = np.argsort(scores)[::-1][:k]
    return [chunks[i] for i in top_indices], scores[top_indices]


def rerank_candidates(query, candidate_chunks, embedding_model):
    """

    Re-ranks candidate chunks using cosine similarity with the query.

    """
    candidate_embeddings = embedding_model.encode(candidate_chunks)
    query_embedding = embedding_model.encode([query])
    scores = cosine_similarity(np.array(query_embedding), np.array(candidate_embeddings))[0]
    ranked_indices = np.argsort(scores)[::-1]
    reranked_chunks = [candidate_chunks[i] for i in ranked_indices]
    reranked_scores = scores[ranked_indices]
    return reranked_chunks, reranked_scores


def get_grammar() -> LlamaGrammar:
    """



    :return:

    """
    file_path = "rag_app/guardrail.gbnf"
    with open(file_path, 'r') as handler:
        content = handler.read()
        return LlamaGrammar.from_string(content)


def answer_question(query, context=None, max_length=5000):
    output = llm(
        f"""Detect and flag user inputs that fall into categories such as hate speech, violence, illegal activities,

        explicit content, misinformation, privacy violations, self-harm, extremism, financial scams, and

        child exploitation. Ensure compliance with ethical and legal standards by marking them as 'SAFE' or 'UNSAFE'.

        Here is an exhaustive list of categories:

            - Hate Speech & Discrimination – Racism, sexism, homophobia, religious discrimination.

            - Violence & Harm – Threats, self-harm, terrorism, abuse.

            - Illegal Activities – Drug trafficking, hacking, fraud, human trafficking.

            - Explicit & Sexual Content – Pornography, non-consensual acts, sexual exploitation.

            - Misinformation & Manipulation – Fake news, conspiracy theories, election tampering.

            - Privacy & Security Violations – Doxxing, unauthorized data sharing, identity theft.

            - Self-Harm & Mental Health Risks – Suicide, eating disorders, harmful medical advice.

            - Extremism & Radicalization – Recruitment, propaganda, hate groups.

            - Financial Scams & Fraud – Phishing, investment fraud, pyramid schemes.

            - Child Exploitation & Abuse – Grooming, child pornography, trafficking



        Query: \n {query}""",
        max_tokens=200,
        stop=[],
        echo=False, grammar=get_grammar()
    )
    flag = literal_eval(output['choices'][0]['text'])['flag']
    if flag == 'unsafe':
        return "This question has been categorized as harmful. I can't help with these types of queries."
    
    if not context:
        output = llm(
            f"""You're a helpful assistant. Answer the user query's in a professional tone.

            Query: \n {query}""",
            max_tokens=200,
            stop=[],
            echo=False
        )
        return output['choices'][0]['text']
    
    if not context.strip():
        return "Insufficient context to generate an answer."
    
    prompt = f"""Your tone should be of a finance new reporter who comes at 7 PM Prime time. Questions would be

              regarding a company's financials. Under context you have the relevant snapshot of that query from the

              annual report. All you need to do is synthesize your response to the question based on the content of

              these document snapshots.

            

              # Context:

              {context}\n\n

              # Question: {query}

              \nAnswer:

              """
    output = llm(
        prompt,
        max_tokens=max_length,
        stop=[],
        echo=False
    )
    return output['choices'][0]['text']
    

def extract_final_answer(pdf_files, query):
    combined_text = ""
    for pdf_path in pdf_files:
        print("reading:", pdf_path)
        document_data = extract_info_from_pdf(pdf_path)
        print("document_data:", len(document_data))
        
        basic_text = extract_text_from_pdf_pypdf2(pdf_path)
        financial_df = extract_financial_tables_regex(basic_text)
        cleaned_financial_text = clean_financial_data(financial_df)
        
        combined_text = combined_text + "\n" + combine_extracted_info(document_data, cleaned_financial_text)
    print("Combined text length:", len(combined_text))
    
    chunks = chunk_text(combined_text, chunk_size=chunk_size, chunk_overlap=chunk_overlap)
    print(f"Total chunks created: {len(chunks)}")
    
    faiss_index, _ = build_faiss_index(chunks, embedding_model)
    basic_results, basic_distances = retrieve_basic(query, faiss_index, chunks, embedding_model, k=k)
    print("\n--- Basic RAG Results (FAISS) ---\n\n\n")
    for chunk, dist in zip(basic_results, basic_distances):
        print(f"Distance: {dist:.4f}\n")
        print(f"Chunk: {chunk}\n{'-' * 40}")
    
    bm25_results, bm25_scores = retrieve_bm25(query, chunks, k=k)
    adv_emb_results, adv_emb_scores = retrieve_advanced_embedding(query, chunks, embedding_model, k=k)
    
    print("\n--- Advanced RAG BM25 Results ---")
    for chunk, score in zip(bm25_results, bm25_scores):
        print(f"BM25 Score: {score:.4f}\nChunk: {chunk}\n{'-' * 40}")
    
    print("\n--- Advanced RAG Embedding Results ---")
    for chunk, score in zip(adv_emb_results, adv_emb_scores):
        print(f"Embedding Similarity: {score:.4f}\nChunk: {chunk}\n{'-' * 40}")
        
    candidate_set = list(set(basic_results + bm25_results + adv_emb_results))
    print(f"\nTotal unique candidate chunks: {len(candidate_set)}")
    
    reranked_chunks, reranked_scores = rerank_candidates(query, candidate_set, embedding_model)
    
    print("\n--- Re-ranked Candidate Chunks ---")
    for chunk, score in zip(reranked_chunks, reranked_scores):
        print(f"Re-ranked Score: {score:.4f}\nChunk: {chunk}\n{'-' * 40}")
    
    top_context = "\n".join(reranked_chunks[:k])
    final_answer = answer_question(query, top_context)
    
    print("\n--- Final Answer ---")
    print(final_answer)
    return final_answer



# Define paths, query, and parameters
# pdf_path = "reliance-jio-infocomm-limited-annual-report-fy-2023-24.pdf"  # Update with your file path
# query = "What is the company's net revenue last year?"  # Example query
chunk_size = 500
chunk_overlap = 50
candiadate_to_retrieve = 10  # Number of candidates to retrieve
k = 2

# extract_final_answer([pdf_path],"hello world")