File size: 11,098 Bytes
71c632c
323e21c
71c632c
 
93ae679
 
 
 
146b51b
d19085e
146b51b
323e21c
 
d19085e
 
71c632c
323e21c
 
 
 
d19085e
 
 
71c632c
d19085e
 
323e21c
 
d19085e
 
646deb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93ae679
146b51b
 
 
 
 
 
 
d19085e
 
 
 
93ae679
146b51b
93ae679
 
 
 
 
146b51b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323e21c
7ecbb59
146b51b
 
7ecbb59
 
146b51b
 
 
7ecbb59
323e21c
146b51b
 
 
1756424
146b51b
 
 
 
71c632c
 
323e21c
146b51b
 
323e21c
 
 
146b51b
323e21c
 
146b51b
 
 
323e21c
 
146b51b
323e21c
146b51b
71c632c
93ae679
146b51b
 
 
 
 
 
 
d19085e
 
08c1eb5
 
 
 
 
 
 
 
 
 
 
d19085e
 
08c1eb5
146b51b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d19085e
 
 
93ae679
146b51b
 
 
 
 
 
 
 
 
d19085e
 
146b51b
 
 
323e21c
d19085e
146b51b
323e21c
d19085e
 
 
 
 
 
 
 
 
323e21c
 
 
d19085e
323e21c
 
93ae679
d19085e
 
323e21c
146b51b
d19085e
323e21c
d19085e
93ae679
 
 
d19085e
 
 
 
 
 
93ae679
 
d19085e
93ae679
d19085e
 
323e21c
93ae679
d19085e
 
 
 
93ae679
 
d19085e
93ae679
 
146b51b
 
 
 
 
 
 
 
 
323e21c
146b51b
 
d19085e
 
146b51b
d19085e
146b51b
71c632c
146b51b
 
323e21c
 
 
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
"""
Mylangv2: Process raw text or uploaded document into vectorstore and generate questions via Azure OpenAI using LangChain.
Includes a simple CLI test at the bottom to verify both `process_text` and `process_uploaded_document`.
"""
import os
import logging
import re
import json
import numpy as np
from dotenv import load_dotenv
from typing import Dict, List, Any, Tuple, Optional

# LangChain and Azure OpenAI imports
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_openai import AzureOpenAIEmbeddings, AzureChatOpenAI
from langchain.document_loaders import PyPDFLoader
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
from langchain.evaluation import load_evaluator

# Vectorstore: FAISS
try:
    from langchain_community.vectorstores import FAISS
except ImportError as e:
    FAISS = None
    logging.warning(
        "FAISS import failed (%s). Falling back to in-memory store. "
        "Install faiss-cpu/faiss-gpu or downgrade NumPy to <2.0 to enable FAISS." % e
    )

# Load env vars
dotenv_path = os.getenv('DOTENV_PATH')
if dotenv_path:
    load_dotenv(dotenv_path)
else:
    load_dotenv()

# Validate env vars
def check_env():
    required = [
    "AZURE_OPENAI_API_KEY",
    "AZURE_OPENAI_ENDPOINT",
    "AZURE_OPENAI_EMBEDDING_DEPLOYMENT",
    "AZURE_OPENAI_CHAT_DEPLOYMENT",
    "AZURE_OPENAI_API_VERSION"
]
    missing = [v for v in required if not os.getenv(v)]
    if missing:
        raise EnvironmentError(f"Missing required environment variables: {', '.join(missing)}")

class DocumentProcessor:
    def __init__(
        self,
        embeddings: Optional[AzureOpenAIEmbeddings] = None,
        text_splitter: Optional[RecursiveCharacterTextSplitter] = None
    ):
        """Initialize DocumentProcessor with injectable embeddings and splitter."""
        self.embeddings = embeddings or AzureOpenAIEmbeddings(
            azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
            api_key=os.getenv("AZURE_OPENAI_API_KEY"),
            api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
            model=os.getenv("AZURE_OPENAI_EMBEDDING_DEPLOYMENT")
        )
        self.text_splitter = text_splitter or RecursiveCharacterTextSplitter(
            chunk_size=1000,
            chunk_overlap=200,
            separators=["\n\n", "\n", " ", ""]
        )

    def _create_fallback_vectorstore(self, texts: List[str]) -> Any:
        """Creates a basic in-memory vectorstore with cosine similarity search and embedding shape checks."""
        embs = self.embeddings.embed_documents(texts)
        dim = len(embs[0]) if embs else 0

        class Doc:
            def __init__(self, content: str):
                self.page_content = content

        class BasicVectorStore:
            def __init__(self, texts: List[str], embs: List[List[float]]):
                self.texts = texts
                self.embs = embs

            def similarity_search(self, query: str, k: int = 3) -> List[Doc]:
                q_emb = self.embeddings.embed_query(query)
                if len(q_emb) != dim:
                    raise ValueError(f"Query embedding dimension {len(q_emb)} != stored dimension {dim}")
                sims = []
                for emb in self.embs:
                    if len(emb) != dim:
                        raise ValueError("Stored embedding has unexpected dimension")
                    sims.append(np.dot(q_emb, emb) / (np.linalg.norm(q_emb) * np.linalg.norm(emb)))
                idxs = sorted(range(len(sims)), key=lambda i: sims[i], reverse=True)[:k]
                return [Doc(self.texts[i]) for i in idxs]

        # Bind embeddings for inner class
        BasicVectorStore.embeddings = self.embeddings
        return BasicVectorStore(texts, embs)

    def process_text(self, text: str, persist_directory: str = None) -> Tuple[Any, List[str], Dict[str, str]]:
        """Split raw text, build vectorstore (FAISS or fallback), return store, chunks, and metadata."""
        chunks = self.text_splitter.split_text(text)
        backend = 'fallback'
        if FAISS:
            try:
                vs = FAISS.from_texts(texts=chunks, embedding=self.embeddings)
                backend = 'faiss'
                if persist_directory:
                    vs.save_local(persist_directory)
                    _log_vectorstore_size(persist_directory)
                logging.info(f"Processed {len(chunks)} chunks into FAISS vectorstore.")
                return vs, chunks, {'backend': backend}
            except Exception as e:
                logging.warning(f"FAISS.from_texts failed ({e}), using fallback vectorstore.")
        vs_fb = self._create_fallback_vectorstore(chunks)
        logging.info(f"Processed {len(chunks)} chunks into fallback vectorstore.")
        return vs_fb, chunks, {'backend': backend}

    def process_uploaded_document(
        self, pdf_path: str, persist_directory: str = None
    ) -> Tuple[Any, List[str], Dict[str, str]]:
        """Load PDF, split, build vectorstore, and return store, raw texts, and metadata."""
        loader = PyPDFLoader(pdf_path)
        pages = loader.load()
        docs = self.text_splitter.split_documents(pages)
        texts = [doc.page_content for doc in docs]
        backend = 'fallback'
        if FAISS:
            try:
                vs = FAISS.from_documents(documents=docs, embedding=self.embeddings)
                backend = 'faiss'
                if persist_directory:
                    vs.save_local(persist_directory)
                    _log_vectorstore_size(persist_directory)
                logging.info(f"Processed PDF with {len(texts)} chunks into FAISS vectorstore.")
                return vs, texts, {'backend': backend}
            except Exception as e:
                logging.warning(f"FAISS.from_documents failed ({e}), falling back.")
        vs_fb = self._create_fallback_vectorstore(texts)
        logging.info(f"Processed PDF with {len(texts)} chunks into fallback vectorstore.")
        return vs_fb, texts, {'backend': backend}

class QuestionGenerator:
    def __init__(self, prompt_template_path: str = None):
        # Load prompt template from file or default
        if prompt_template_path and os.path.exists(prompt_template_path):
            with open(prompt_template_path) as f:
                template_str = f.read()
        else:
            template_str = (
"""
Based on the following context:
{context}

Generate {num_questions} {question_type} questions for:
Subject: {subject}
Class: {class_grade}
Topic: {topic}
Difficulty: {difficulty}
Bloom's Level: {bloom_level}

Additional Instructions: {instructions}

Format as JSON:
{"questions": [{"question":"","options":[],"correctAnswer":"","explanation":""}]}
"""
            )
        self.llm = AzureChatOpenAI(
            azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
            api_key=os.getenv("AZURE_OPENAI_API_KEY"),
            api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
            model=os.getenv("AZURE_OPENAI_CHAT_DEPLOYMENT"),
            temperature=0.3
        )
        self.chain = LLMChain(
            llm=self.llm,
            prompt=PromptTemplate(
                input_variables=[
                    "context","num_questions","question_type","subject",
                    "class_grade","topic","difficulty","bloom_level","instructions"
                ],
                template=template_str
            )
        )

    def generate_questions(self, topic_data: Dict[str, Any], vectorstore: Any) -> Dict[str, Any]:
        # Validate topic_data keys
        required_keys = [
            'subjectName','sectionName','numQuestions','questionType',
            'classGrade','difficulty','bloomLevel'
        ]
        missing = [k for k in required_keys if k not in topic_data]
        if missing:
            raise ValueError(f"Missing required topic_data keys: {', '.join(missing)}")

        context = ""
        if vectorstore:
            docs = vectorstore.similarity_search(
                f"{topic_data['subjectName']} {topic_data['sectionName']}", k=3
            )
            context = "\n".join(getattr(doc, 'page_content', '') for doc in docs)
            logging.info(f"Context length: {len(context)}")

        payload = {
            "context": context,
            "num_questions": topic_data['numQuestions'],
            "question_type": topic_data['questionType'],
            "subject": topic_data['subjectName'],
            "class_grade": topic_data['classGrade'],
            "topic": topic_data['sectionName'],
            "difficulty": topic_data['difficulty'],
            "bloom_level": topic_data['bloomLevel'],
            "instructions": topic_data.get('additionalInstructions','')
        }
        response = self.chain.invoke(payload)
        text = response.get('text', response) if isinstance(response, dict) else response
        output = text.strip()
        if output.startswith('```') and output.endswith('```'):
            output = re.sub(r'^```[a-zA-Z]*|```$', '', output).strip()
        try:
            result = json.loads(output)
        except json.JSONDecodeError:
            logging.error(f"JSON parsing failed. Raw output: {output}")
            raise
        if 'questions' not in result:
            raise ValueError(f"Missing 'questions' key in output JSON: {result}")
        return result

class QuestionEvaluator:
    def __init__(self):
        common = dict(
            azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
            api_key=os.getenv("AZURE_OPENAI_API_KEY"),
            api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
            model=os.getenv("AZURE_OPENAI_CHAT_DEPLOYMENT")
        )
        self.evaluator = load_evaluator(
            "qa",
            llm=AzureChatOpenAI(**common, temperature=0)
        )

    def evaluate(self, question: str, answer: str, reference: str) -> Dict[str, Any]:
        """Evaluate question-answer pair against reference."""
        try:
            return self.evaluator.evaluate_strings(
                input=question,
                prediction=answer,
                reference=reference
            )
        except Exception as e:
            logging.error(f"Evaluation error: {e}")
            raise

# Helper for logging vectorstore size
def _log_vectorstore_size(directory: str):
    total = 0
    for root, _, files in os.walk(directory):
        for f in files:
            total += os.path.getsize(os.path.join(root, f))
    logging.info(f"Vectorstore on disk: {total/1024:.2f} KB")

# CLI test and env validation
def main():
    # Validate env only on script run
    check_env()
    dp = DocumentProcessor()
    sample = "This is a simple test. It splits into chunks and embeds."
    vs, chunks, meta = dp.process_text(sample)
    print("Chunks:", chunks)
    print("Backend used:", meta['backend'])
    if os.path.exists('sample.pdf'):
        vs2, raw, meta2 = dp.process_uploaded_document('sample.pdf')
        print("PDF raw chunks count:", len(raw), "Backend:", meta2['backend'])

if __name__ == "__main__":
    main()