File size: 11,316 Bytes
6f8b70f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# srd_engine_final.py
# ============================================================
# CedroPass SRD – Final RAG Engine (Stable, Section-Aware)
# ============================================================

import os
import re
import io
import base64
import time
import shutil
import warnings
from typing import List, Dict, Any, Optional

from dotenv import load_dotenv
load_dotenv()

# -------------------- Data Processing --------------------
import pdfplumber
import camelot
from pdf2image import convert_from_path
import pytesseract
from PIL import Image

# -------------------- NLP & Retrieval --------------------
import spacy
from sentence_transformers import CrossEncoder
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.retrievers import BM25Retriever
from langchain_core.documents import Document
from rapidfuzz import process as fuzz_process

# -------------------- Claude --------------------
try:
    from anthropic import Anthropic
except ImportError:
    Anthropic = None

# -------------------- CONFIG --------------------
warnings.filterwarnings("ignore")
Image.MAX_IMAGE_PIXELS = None

POPPLER_PATH = os.getenv("POPPLER_PATH")
TESSERACT_PATH = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
if os.path.exists(TESSERACT_PATH):
    pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH

# -------------------- NLP MODEL --------------------
print("[SYSTEM] Loading NLP pipelines...")
try:
    NLP_EN = spacy.load("en_core_web_sm")
except OSError:
    from spacy.cli import download
    download("en_core_web_sm")
    NLP_EN = spacy.load("en_core_web_sm")


# ============================================================
# TEXT UTILS
# ============================================================
def normalize_text(text: str) -> str:
    return re.sub(r"\s+", " ", text).strip()


def lemmatize_text(text: str) -> str:
    doc = NLP_EN(text[:50000])
    return " ".join(
        t.lemma_.lower()
        for t in doc
        if not t.is_space and not t.is_punct
    )


# ============================================================
# SECTION-AWARE SRD SPLITTER (CRITICAL FIX)
# ============================================================
class SmartSRDSplitter:
    """
    Guarantees that ALL child paragraphs inherit the correct
    section_type until a new header appears.
    """

    HEADER_REGEX = re.compile(
        r"^(\d+(\.\d+)*|FR-\d+|NFR-\d+|[A-Z][A-Za-z\s]{3,}:)",
        re.IGNORECASE,
    )

    def split_text(self, text: str) -> List[Document]:
        docs: List[Document] = []
        lines = text.splitlines()

        buffer: List[str] = []
        current_section_title = "General"
        current_section_type = "general"

        for raw in lines:
            line = raw.strip()
            if not line:
                continue

            if self.HEADER_REGEX.match(line):
                # Flush previous chunk
                if buffer:
                    docs.append(
                        Document(
                            page_content="\n".join(buffer),
                            metadata={
                                "type": "text",
                                "section": current_section_title,
                                "section_type": current_section_type,
                                "source": "SRD_Main",
                            },
                        )
                    )

                buffer = [line]
                current_section_title = line[:80]

                lowered = line.lower()
                if "functional requirement" in lowered or "fr-" in lowered:
                    current_section_type = "functional"
                elif "non-functional" in lowered or "nfr-" in lowered:
                    current_section_type = "nonfunctional"
                else:
                    current_section_type = "general"
            else:
                buffer.append(line)

        # Final flush
        if buffer:
            docs.append(
                Document(
                    page_content="\n".join(buffer),
                    metadata={
                        "type": "text",
                        "section": current_section_title,
                        "section_type": current_section_type,
                        "source": "SRD_Main",
                    },
                )
            )

        return docs


# ============================================================
# PDF EXTRACTORS
# ============================================================
def extract_pdf_text(path: str) -> str:
    text = ""
    with pdfplumber.open(path) as pdf:
        for p in pdf.pages:
            t = p.extract_text()
            if t:
                text += t + "\n"
    return text


def extract_tables(path: str) -> List[Document]:
    docs: List[Document] = []
    try:
        tables = camelot.read_pdf(path, pages="all", flavor="stream")
        for i, t in enumerate(tables):
            md = t.df.to_markdown(index=False)
            if len(md) > 30:
                docs.append(
                    Document(
                        page_content=md,
                        metadata={
                            "type": "table",
                            "section_type": "general",
                            "source": "SRD_Table",
                        },
                    )
                )
    except Exception:
        pass
    return docs


# ============================================================
# DIAGRAM INTERPRETER (TEXT-ONLY SAFE)
# ============================================================
class DiagramInterpreter:
    def __init__(self):
        self.client = (
            Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
            if Anthropic and os.getenv("ANTHROPIC_API_KEY")
            else None
        )

    def describe(self, image: Image.Image, label: str) -> str:
        if not self.client:
            return pytesseract.image_to_string(image)

        buf = io.BytesIO()
        image.convert("RGB").save(buf, format="JPEG", quality=85)
        b64 = base64.b64encode(buf.getvalue()).decode()

        resp = self.client.messages.create(
            model="claude-sonnet-4-5-20250929",
            max_tokens=600,
            temperature=0.2,
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": f"Explain this {label} diagram for an SRD."},
                        {
                            "type": "image",
                            "source": {
                                "type": "base64",
                                "media_type": "image/jpeg",
                                "data": b64,
                            },
                        },
                    ],
                }
            ],
        )
        return resp.content[0].text


# ============================================================
# CORE RAG ENGINE
# ============================================================
class SRDChatbotEngine:
    def __init__(self, chroma_dir: str = "chroma_db_final"):
        print("[ENGINE] Initializing retrievers...")

        self.embedding_model = HuggingFaceEmbeddings(
            model_name="sentence-transformers/all-MiniLM-L6-v2"
        )
        self.reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

        self.chroma_dir = chroma_dir
        self.vectorstore: Optional[Chroma] = None
        self.chroma_retriever = None
        self.bm25_retriever: Optional[BM25Retriever] = None
        self.vocab = set()

    # -------------------- BUILD INDEX --------------------
    def build_index(
        self,
        pdf_path: str,
        diagrams: Optional[List[str]] = None,
    ):
        if os.path.exists(self.chroma_dir):
            shutil.rmtree(self.chroma_dir)

        splitter = SmartSRDSplitter()
        docs = splitter.split_text(extract_pdf_text(pdf_path))
        docs.extend(extract_tables(pdf_path))

        for d in docs:
            d.metadata["lemma"] = lemmatize_text(d.page_content)
            for w in d.page_content.split():
                if w.isalnum():
                    self.vocab.add(w.lower())

        self.vectorstore = Chroma.from_documents(
            docs,
            embedding=self.embedding_model,
            persist_directory=self.chroma_dir,
            collection_name="srd_final",
        )

        self.chroma_retriever = self.vectorstore.as_retriever(search_kwargs={"k": 20})
        self.bm25_retriever = BM25Retriever.from_documents(docs)
        self.bm25_retriever.k = 20

        print(f"✅ Indexed {len(docs)} SRD chunks")

    # -------------------- INTENT --------------------
    def detect_intent(self, q: str) -> str:
        q = q.lower()
        if any(w in q for w in ["list", "enumerate", "all functional", "requirements of"]):
            return "enumeration"
        return "qa"

    # -------------------- ENUMERATION (NO SIM SEARCH) --------------------
    def list_functional_requirements(self) -> List[str]:
        data = self.vectorstore.get(
            where={"section_type": "functional"}
        )
        return data.get("documents", [])

    # -------------------- QUERY --------------------
    def answer(self, query: str, claude) -> str:
        intent = self.detect_intent(query)

        if intent == "enumeration":
            items = self.list_functional_requirements()
            if not items:
                return "I could not find sufficient information in the provided SRD."

            prompt = f"""
You are a Senior Project Architect.

List ALL functional requirements below.
Do not merge, summarize, or invent anything.

REQUIREMENTS:
{chr(10).join(items)}
"""
            return claude.generate_raw(prompt)

        # ---------- Normal QA ----------
        dense = self.chroma_retriever.invoke(query)
        sparse = self.bm25_retriever.invoke(query)

        pool = dense + sparse
        pairs = [[query, d.page_content] for d in pool]
        scores = self.reranker.predict(pairs)

        top = [
            d.page_content
            for d, s in sorted(zip(pool, scores), key=lambda x: x[1], reverse=True)
            if s > -6
        ][:8]

        if not top:
            return "I could not find sufficient information in the provided SRD."

        ctx = "\n---\n".join(top[:4000])

        prompt = f"""
Answer using ONLY the SRD context below.
If unsupported, say so explicitly.

CONTEXT:
{ctx}

QUESTION:
{query}
"""
        return claude.generate_raw(prompt)


# ============================================================
# CLAUDE ANSWERER
# ============================================================
class ClaudeAnswerer:
    def __init__(self):
        if Anthropic is None:
            raise RuntimeError("anthropic not installed")

        self.client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
        self.model = "claude-sonnet-4-5-20250929"

    def generate_raw(self, prompt: str) -> str:
        resp = self.client.messages.create(
            model=self.model,
            max_tokens=1200,
            temperature=0.2,
            messages=[{"role": "user", "content": prompt}],
        )
        return resp.content[0].text