-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
239 lines (190 loc) · 9.06 KB
/
app.py
File metadata and controls
239 lines (190 loc) · 9.06 KB
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
import streamlit as st
import os
from utils import generate_mcq, load_docs, load_llama, downlode_hugging_face_embeddings, split_docs, create_vectorstore
import tempfile
from langchain_chroma import Chroma
st.set_page_config(page_title="GenAI MCQ Generator", layout="wide")
st.title("GenAI based MCQ Quiz App")
# session states initialization
if "questions" not in st.session_state:
st.session_state.questions = []
<<<<<<< HEAD
def load_llama():
repo_id='meta-llama/Llama-3.2-3B-Instruct'
llm=HuggingFaceEndpoint(
repo_id=repo_id,
task="text-generation",
max_new_tokens=256,
temperature=0.3,
repetition_penalty=1.1,
huggingfacehub_api_token=HF_TOKEN
)
chat_model = ChatHuggingFace(llm=llm)
return chat_model
llm=load_llama()
mcq_prompt_template = """<|begin_of_text|><|start_header_id|>system<|end_header_id|>
You are a strict medical educator.
1. Generate ONE MCQ based ONLY on the provided context.
2. If the context does not contain enough specific information to create a high-quality question, respond with "INSUFFICIENT_CONTEXT".
3. Ensure distractors are medically plausible but factually incorrect based on the text.
4. DO NOT provide any introductory text or conversational filler. Start immediately with 'Question:'.<|eot_id|>
<|start_header_id|>user<|end_header_id|>
Context: {context}
Follow this EXACT format:
Question: [Text]
A) [Option]
B) [Option]
C) [Option]
D) [Option]
Correct Answer: [Letter]
Explanation: [Concise reason]<|eot_id|>
<|start_header_id|>assistant<|end_header_id|>
Question:"""
mcq_prompt = ChatPromptTemplate.from_template(mcq_prompt_template)
# def generate_mcq(topic: str, retriever, num_questions: int=5):
# docs = retriever.invoke(topic)
# mcq_chain = mcq_prompt | llm | StrOutputParser()
# generated_mcqs = []
# for i in range(min(num_questions, len(docs))):
# context_chunk = docs[i].page_content
# response = mcq_chain.invoke({"context": context_chunk})
# generated_mcqs.append(response)
# #testing for streamlit app
# generated_mcqs.append({
# "question": response, # The whole LLM response for now
# "option": ["Option A", "Option B", "Option C", "Option D"],
# "correct_answer": "Option B"
# })
# return generated_mcqs
def generate_mcq(topic: str, retriever, num_questions: int=5):
docs = retriever.invoke(topic)
mcq_chain = mcq_prompt | llm | StrOutputParser()
generated_mcqs = []
for i in range(min(num_questions, len(docs))):
context_chunk = docs[i].page_content
response = mcq_chain.invoke({"context": context_chunk})
try:
# Splitting by A) or 1) to ensure we get only the question text
question_part = re.split(r'[A-D]\)|1\)', response)[0]
question = question_part.replace("Question:", "").strip()
# This regex looks for A) Text, B) Text, etc., OR 1) Text, 2) Text, etc.
options = re.findall(r'(?:[A-D]\)|[1-4]\)) (.*)', response)
# Searches for 'Correct Answer:' followed by a Letter or Number, ignoring case
correct_match = re.search(r'Correct Answer:\s*(?:Option\s*)?([A-D]|1|2|3|4)', response, re.IGNORECASE)
if correct_match:
ans_raw = correct_match.group(1).upper()
# Map both letters and numbers to the correct list index
letter_to_index = {"A": 0, "B": 1, "C": 2, "D": 3, "1": 0, "2": 1, "3": 2, "4": 3}
idx = letter_to_index.get(ans_raw, 0)
# Ensure the index exists in the found options
if len(options) > idx:
correct_text = options[idx].strip()
else:
correct_text = "Refer to Explanation"
else:
correct_text = "Refer to Explanation"
# Create the dictionary your UI expects
generated_mcqs.append({
"question": question,
# Fallback to letters if parsing fails to find 4 distinct options
"option": [opt.strip() for opt in options] if len(options) >= 4 else ["Option A", "Option B", "Option C", "Option D"],
"correct_answer": correct_text
})
except Exception as e:
print(f"Error parsing MCQ: {e}")
# Add a fallback dictionary to prevent the UI loop from crashing
generated_mcqs.append({
"question": "Error parsing this specific question.",
"option": ["N/A", "N/A", "N/A", "N/A"],
"correct_answer": "N/A"
})
return generated_mcqs
if __name__ == "__main__":
# raw_documents = load_docs(file_path)
# print(f"Length of the raw documents: {len(raw_documents)}")
# text_chunks = split_docs(raw_documents)
# print(f"Length of the text chunks: {len(text_chunks)}")
# embeddings=downlode_hugging_face_embeddings()
# #test_embedding = embeddings.embed_query("Suprito")
# #print(len(test_embedding))
# vectorstore=create_vectorstore(text_chunks, embeddings)
persist_directory = 'chroma_db_MCQGen'
embeddings=downlode_hugging_face_embeddings()
if os.path.exists(persist_directory):
print("Existing Vectorstore found. Loading...")
=======
# load the default retriever on app start up
if "retriever" not in st.session_state:
# check if persistance folder exists
if os.path.exists('chroma_db_MCQGen'):
embeddings = downlode_hugging_face_embeddings()
>>>>>>> 28f25b2 (Updaed code, webUI functionality added, updated app structure.)
vectorstore = Chroma(
persist_directory='chroma_db_MCQGen',
embedding_function=embeddings
)
st.session_state.retriever = vectorstore.as_retriever(search_kwargs={"k": 10})
else:
st.session_state.retriever = None
#side bar for document upload and processing
with st.sidebar:
st.header("Upload Medical Document")
uploaded_file = st.file_uploader("Upload a medical book or document to generate the questions", type=["pdf"])
if uploaded_file:
if st.button("Process Document"):
with st.spinner("Analysing your document. This may take a few minutes..."):
# tempory file path to store the uploded pdf
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
tmp_file.write(uploaded_file.getvalue())
tmp_path = tmp_file.name
<<<<<<< HEAD
retriver=vectorstore.as_retriever(search_kwargs={"k": 10})
# run in cmd
while True:
topic = input("Enter the topic for MCQ generation (or 'q' to quit): ").strip()
if topic.lower() == 'q':
break
mcqs = generate_mcq(topic, retriver, num_questions=5)
for i, mcq in enumerate(mcqs, 1):
print(f"\nMCQ {i}:\n{mcq}\n")
=======
# load and split the document from app.py functions
loader = load_docs(tmp_path)
chunks=split_docs(loader)
embeddings=downlode_hugging_face_embeddings()
vectorstore = create_vectorstore(chunks, embeddings, persist_dir='chroma_db_MCQGen')
st.session_state.retriever = vectorstore.as_retriever(search_kwargs={"k": 10})
os.remove(tmp_path) #Clean up
st.success("Analysis Complete")
>>>>>>> 28f25b2 (Updaed code, webUI functionality added, updated app structure.)
# document upload block(Stage-1)
topic = st.text_input("Enter Topic:")
if st.button("Generate MCQs"):
# Check if a document has been processed first
if st.session_state.retriever is not None:
with st.spinner("Generating..."):
# CHANGE 'retriever' TO 'st.session_state.retriever'
st.session_state.questions = generate_mcq(topic, st.session_state.retriever)
st.rerun()
else:
st.error("Please upload and process a document in the sidebar first!")
# quiz block(Stage-2)
if st.session_state.questions:
with st.form("quiz_form", border=False):
for i, mcq in enumerate(st.session_state.questions):
st.write(f"## Question {i+1}")
st.write(f"Question: {mcq['question']}")
user_choice = st.radio(label="Select an option", options=mcq['option'], index=None, key=f"radio_{i}")
if st.session_state.get(f"radio_{i}") and st.session_state.get("FormSubmitter:quiz_form-Submit"):
if user_choice.strip().lower() == mcq['correct_answer'].strip().lower():
st.success("Correct Answer!", icon="✅")
else:
st.error("Incorrect!", icon="❌")
with st.expander(label="Check Answer"):
st.write(f"Correct Answer: {mcq['correct_answer']}")
st.write("---")
submit_btn = st.form_submit_button("Submit", type="primary")
if submit_btn:
st.success("Quiz Submitted!")
else:
st.info("The quiz will appear here once you enter a topic and click 'Generate MCQs'.")