Spaces:
Sleeping
Sleeping
Rename final_test3.py to app.py
Browse files- final_test3.py → app.py +316 -246
final_test3.py → app.py
RENAMED
@@ -1,246 +1,316 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
from langchain_groq import ChatGroq
|
3 |
-
from langchain_core.output_parsers import StrOutputParser
|
4 |
-
from langchain_core.prompts import ChatPromptTemplate
|
5 |
-
from dotenv import load_dotenv
|
6 |
-
import pytesseract
|
7 |
-
from PIL import Image
|
8 |
-
import pdfplumber
|
9 |
-
import docx
|
10 |
-
from io import BytesIO
|
11 |
-
import logging
|
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 |
-
for
|
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 |
-
elif file_type == "
|
82 |
-
text =
|
83 |
-
elif file_type
|
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 |
-
Difficulty Levels:
|
114 |
-
- Remember: {difficulty_level.get('Remember', 0)}
|
115 |
-
- Understand: {difficulty_level.get('Understand', 0)}
|
116 |
-
- Apply: {difficulty_level.get('Apply', 0)}
|
117 |
-
- Analyze: {difficulty_level.get('Analyze', 0)}
|
118 |
-
- Evaluate: {difficulty_level.get('Evaluate', 0)}
|
119 |
-
- Create: {difficulty_level.get('Create', 0)}
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
return
|
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 |
-
if
|
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 |
-
st.
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
st.
|
244 |
-
|
245 |
-
|
246 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from langchain_groq import ChatGroq
|
3 |
+
from langchain_core.output_parsers import StrOutputParser
|
4 |
+
from langchain_core.prompts import ChatPromptTemplate
|
5 |
+
from dotenv import load_dotenv
|
6 |
+
import pytesseract
|
7 |
+
from PIL import Image
|
8 |
+
import pdfplumber
|
9 |
+
import docx
|
10 |
+
from io import BytesIO
|
11 |
+
import logging
|
12 |
+
from docx import Document
|
13 |
+
from fpdf import FPDF
|
14 |
+
|
15 |
+
# Load environment variables
|
16 |
+
load_dotenv()
|
17 |
+
|
18 |
+
# Initialize logging
|
19 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
20 |
+
|
21 |
+
# Initialize LLM
|
22 |
+
llm = ChatGroq(temperature=0.5, groq_api_key="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", model_name="llama3-8b-8192")
|
23 |
+
|
24 |
+
# OCR Configuration for Pytesseract
|
25 |
+
pytesseract.pytesseract.tesseract_cmd = r"/usr/bin/tesseract" # Adjust to your system's path
|
26 |
+
|
27 |
+
# Enhanced OCR with configurable language option and multi-image support
|
28 |
+
def extract_text_from_images(images, lang="eng"):
|
29 |
+
ocr_text = ""
|
30 |
+
for image in images:
|
31 |
+
try:
|
32 |
+
ocr_text += pytesseract.image_to_string(image, lang=lang).strip() + "\n"
|
33 |
+
except Exception as e:
|
34 |
+
logging.error(f"Error in OCR: {e}")
|
35 |
+
return ocr_text.strip()
|
36 |
+
|
37 |
+
# Function to extract text, images, tables, and formulas from PDF
|
38 |
+
def extract_pdf_data(pdf_path):
|
39 |
+
data = {"text": "", "tables": [], "images": []}
|
40 |
+
try:
|
41 |
+
with pdfplumber.open(pdf_path) as pdf:
|
42 |
+
for page in pdf.pages:
|
43 |
+
data["text"] += page.extract_text() or ""
|
44 |
+
tables = page.extract_tables()
|
45 |
+
for table in tables:
|
46 |
+
data["tables"].append(table)
|
47 |
+
for image in page.images:
|
48 |
+
base_image = pdf.extract_image(image["object_number"])
|
49 |
+
image_obj = Image.open(BytesIO(base_image["image"]))
|
50 |
+
data["images"].append(image_obj)
|
51 |
+
except Exception as e:
|
52 |
+
logging.error(f"Error processing PDF: {e}")
|
53 |
+
return data
|
54 |
+
|
55 |
+
# Function to extract text from DOCX files
|
56 |
+
def extract_docx_data(docx_file):
|
57 |
+
try:
|
58 |
+
doc = docx.Document(docx_file)
|
59 |
+
text = "\n".join([para.text.strip() for para in doc.paragraphs if para.text.strip()])
|
60 |
+
return text
|
61 |
+
except Exception as e:
|
62 |
+
logging.error(f"Error extracting DOCX content: {e}")
|
63 |
+
return ""
|
64 |
+
|
65 |
+
# Function to extract text from plain text files
|
66 |
+
def extract_text_file_data(text_file):
|
67 |
+
try:
|
68 |
+
return text_file.read().decode("utf-8").strip()
|
69 |
+
except Exception as e:
|
70 |
+
logging.error(f"Error extracting TXT content: {e}")
|
71 |
+
return ""
|
72 |
+
|
73 |
+
# Function to process extracted content (PDF, DOCX, etc.)
|
74 |
+
def process_content(file_data, file_type, lang="eng"):
|
75 |
+
text = ""
|
76 |
+
images = []
|
77 |
+
if file_type == "pdf":
|
78 |
+
pdf_data = extract_pdf_data(file_data)
|
79 |
+
text = process_pdf_content(pdf_data)
|
80 |
+
images = pdf_data["images"]
|
81 |
+
elif file_type == "docx":
|
82 |
+
text = extract_docx_data(file_data)
|
83 |
+
elif file_type == "txt":
|
84 |
+
text = extract_text_file_data(file_data)
|
85 |
+
elif file_type in ["png", "jpg", "jpeg"]:
|
86 |
+
image = Image.open(file_data)
|
87 |
+
images.append(image)
|
88 |
+
|
89 |
+
ocr_text = extract_text_from_images(images, lang)
|
90 |
+
return text + "\n" + ocr_text
|
91 |
+
|
92 |
+
# Function to process PDF content
|
93 |
+
def process_pdf_content(pdf_data):
|
94 |
+
ocr_text = extract_text_from_images(pdf_data["images"])
|
95 |
+
combined_text = pdf_data["text"] + ocr_text
|
96 |
+
|
97 |
+
table_text = ""
|
98 |
+
for table in pdf_data["tables"]:
|
99 |
+
table_rows = [" | ".join(str(cell) if cell else "" for cell in row) for row in table]
|
100 |
+
table_text += "\n".join(table_rows) + "\n"
|
101 |
+
|
102 |
+
return (combined_text + "\n" + table_text).strip()
|
103 |
+
|
104 |
+
# Function to generate questions
|
105 |
+
def generate_questions(question_type, subject_name, instructor, class_name, institution, syllabus_context, num_questions, difficulty_level):
|
106 |
+
prompt_template = f"""
|
107 |
+
Based on the following syllabus content, generate {num_questions} {question_type} questions. Ensure the questions are directly derived from the provided syllabus content.
|
108 |
+
Subject: {subject_name}
|
109 |
+
Instructor: {instructor}
|
110 |
+
Class: {class_name}
|
111 |
+
Institution: {institution}
|
112 |
+
Syllabus Content: {syllabus_context}
|
113 |
+
Difficulty Levels:
|
114 |
+
- Remember: {difficulty_level.get('Remember', 0)}
|
115 |
+
- Understand: {difficulty_level.get('Understand', 0)}
|
116 |
+
- Apply: {difficulty_level.get('Apply', 0)}
|
117 |
+
- Analyze: {difficulty_level.get('Analyze', 0)}
|
118 |
+
- Evaluate: {difficulty_level.get('Evaluate', 0)}
|
119 |
+
- Create: {difficulty_level.get('Create', 0)}
|
120 |
+
Format questions as follows:
|
121 |
+
Q1. ________________
|
122 |
+
Q2. ________________
|
123 |
+
...
|
124 |
+
"""
|
125 |
+
chain = (ChatPromptTemplate.from_template(prompt_template) | llm | StrOutputParser())
|
126 |
+
try:
|
127 |
+
return chain.invoke({})
|
128 |
+
except Exception as e:
|
129 |
+
logging.error(f"Error generating {question_type} questions: {e}")
|
130 |
+
return ""
|
131 |
+
|
132 |
+
# Function to generate answers
|
133 |
+
def generate_answers(questions, syllabus_context):
|
134 |
+
prompt = f"""
|
135 |
+
Based on the provided syllabus content, generate detailed answers for the following questions. The answers must only be based on the syllabus content.
|
136 |
+
Syllabus Content: {syllabus_context}
|
137 |
+
Questions:
|
138 |
+
{questions}
|
139 |
+
Format answers as follows:
|
140 |
+
Answer 1: ________________
|
141 |
+
Answer 2: ________________
|
142 |
+
...
|
143 |
+
"""
|
144 |
+
chain = (ChatPromptTemplate.from_template(prompt) | llm | StrOutputParser())
|
145 |
+
try:
|
146 |
+
return chain.invoke({})
|
147 |
+
except Exception as e:
|
148 |
+
logging.error(f"Error generating answers: {e}")
|
149 |
+
return ""
|
150 |
+
|
151 |
+
# Function to download as DOCX
|
152 |
+
def download_as_docx(content, file_name="output.docx"):
|
153 |
+
doc = Document()
|
154 |
+
for line in content.split("\n"):
|
155 |
+
doc.add_paragraph(line)
|
156 |
+
buffer = BytesIO()
|
157 |
+
doc.save(buffer)
|
158 |
+
buffer.seek(0)
|
159 |
+
return buffer
|
160 |
+
|
161 |
+
# Function to download as PDF
|
162 |
+
def download_as_pdf(content, file_name="output.pdf"):
|
163 |
+
pdf = FPDF()
|
164 |
+
pdf.add_page()
|
165 |
+
pdf.set_font("Arial", size=12)
|
166 |
+
for line in content.split("\n"):
|
167 |
+
pdf.cell(200, 10, txt=line, ln=True)
|
168 |
+
buffer = BytesIO()
|
169 |
+
pdf.output(buffer)
|
170 |
+
buffer.seek(0)
|
171 |
+
return buffer
|
172 |
+
|
173 |
+
# Streamlit app with enhanced UI and multi-image upload support
|
174 |
+
st.title("Bloom's Taxonomy Based Exam Paper Developer")
|
175 |
+
st.markdown("""
|
176 |
+
### A powerful tool to generate exam questions and answers using AI, based on syllabus content and Bloom's Taxonomy principles.
|
177 |
+
""")
|
178 |
+
|
179 |
+
# Sidebar Clear Data Button
|
180 |
+
if st.sidebar.button("Clear All Data"):
|
181 |
+
st.session_state.clear()
|
182 |
+
st.success("All data has been cleared. You can now upload a new syllabus.")
|
183 |
+
|
184 |
+
# Upload Syllabus and Multiple Images
|
185 |
+
uploaded_file = st.sidebar.file_uploader(
|
186 |
+
"Upload Syllabus (PDF, DOCX, TXT)",
|
187 |
+
type=["pdf", "docx", "txt"]
|
188 |
+
)
|
189 |
+
|
190 |
+
uploaded_images = st.sidebar.file_uploader(
|
191 |
+
"Upload Supplementary Images (PNG, JPG, JPEG)",
|
192 |
+
type=["png", "jpg", "jpeg"],
|
193 |
+
accept_multiple_files=True
|
194 |
+
)
|
195 |
+
|
196 |
+
# Sidebar Inputs for Subject Name, Instructor, Class, and Institution
|
197 |
+
subject_name = st.sidebar.text_input("Enter Subject Name", "Subject Name")
|
198 |
+
instructor_name = st.sidebar.text_input("Enter Instructor Name", "Instructor Name")
|
199 |
+
class_name = st.sidebar.text_input("Enter Class Name", "Class Name")
|
200 |
+
institution_name = st.sidebar.text_input("Enter Institution Name", "Institution Name")
|
201 |
+
|
202 |
+
# Language Option for OCR
|
203 |
+
ocr_lang = st.sidebar.selectbox("Select OCR Language", ["eng", "spa", "fra", "deu", "ita"])
|
204 |
+
|
205 |
+
# Process uploaded file and images
|
206 |
+
if uploaded_file or uploaded_images:
|
207 |
+
# Clear session state when new files are uploaded
|
208 |
+
if "uploaded_filename" in st.session_state and st.session_state.uploaded_filename != uploaded_file.name:
|
209 |
+
st.session_state.clear()
|
210 |
+
st.success("Previous data cleared. Processing new file...")
|
211 |
+
|
212 |
+
st.session_state.uploaded_filename = uploaded_file.name if uploaded_file else None
|
213 |
+
|
214 |
+
# Process syllabus file
|
215 |
+
if uploaded_file:
|
216 |
+
file_type = uploaded_file.type.split("/")[-1]
|
217 |
+
if file_type in ["pdf", "docx", "txt"]:
|
218 |
+
syllabus_text = process_content(uploaded_file, file_type, lang=ocr_lang)
|
219 |
+
st.session_state.syllabus_text = syllabus_text
|
220 |
+
else:
|
221 |
+
st.error("Unsupported file type. Please upload PDF, DOCX, or TXT files.")
|
222 |
+
|
223 |
+
# Process images
|
224 |
+
if uploaded_images:
|
225 |
+
image_text = extract_text_from_images([Image.open(img) for img in uploaded_images], lang=ocr_lang)
|
226 |
+
st.session_state.syllabus_text = st.session_state.get("syllabus_text", "") + "\n" + image_text
|
227 |
+
|
228 |
+
# Preview of Syllabus
|
229 |
+
if "syllabus_text" in st.session_state:
|
230 |
+
st.markdown("### Preview of Extracted Syllabus Content")
|
231 |
+
st.text_area("Extracted Syllabus Content", st.session_state.syllabus_text, height=300)
|
232 |
+
|
233 |
+
# Inputs for Question Generation
|
234 |
+
if "syllabus_text" in st.session_state:
|
235 |
+
st.markdown("### Generate Questions")
|
236 |
+
question_type = st.selectbox("Select Question Type", ["Multiple Choice", "Short Answer", "Essay"])
|
237 |
+
num_questions = st.number_input("Number of Questions", min_value=1, max_value=50, value=10)
|
238 |
+
difficulty_levels = {
|
239 |
+
"Remember": st.slider("Remember (%)", 0, 100, 20),
|
240 |
+
"Understand": st.slider("Understand (%)", 0, 100, 20),
|
241 |
+
"Apply": st.slider("Apply (%)", 0, 100, 20),
|
242 |
+
"Analyze": st.slider("Analyze (%)", 0, 100, 20),
|
243 |
+
"Evaluate": st.slider("Evaluate (%)", 0, 100, 10),
|
244 |
+
"Create": st.slider("Create (%)", 0, 100, 10),
|
245 |
+
}
|
246 |
+
|
247 |
+
if st.button("Generate Questions"):
|
248 |
+
with st.spinner("Generating questions..."):
|
249 |
+
questions = generate_questions(
|
250 |
+
question_type,
|
251 |
+
subject_name,
|
252 |
+
instructor_name,
|
253 |
+
class_name,
|
254 |
+
institution_name,
|
255 |
+
st.session_state.syllabus_text,
|
256 |
+
num_questions,
|
257 |
+
difficulty_levels,
|
258 |
+
)
|
259 |
+
st.session_state.generated_questions = questions
|
260 |
+
st.success("Questions generated successfully!")
|
261 |
+
|
262 |
+
# Display Generated Questions
|
263 |
+
if "generated_questions" in st.session_state:
|
264 |
+
st.markdown("### Generated Questions")
|
265 |
+
st.text_area("Questions", st.session_state.generated_questions, height=300)
|
266 |
+
|
267 |
+
if st.button("Generate Answers"):
|
268 |
+
with st.spinner("Generating answers..."):
|
269 |
+
answers = generate_answers(
|
270 |
+
st.session_state.generated_questions,
|
271 |
+
st.session_state.syllabus_text,
|
272 |
+
)
|
273 |
+
st.session_state.generated_answers = answers
|
274 |
+
st.success("Answers generated successfully!")
|
275 |
+
|
276 |
+
# Display Generated Answers
|
277 |
+
if "generated_answers" in st.session_state:
|
278 |
+
st.markdown("### Generated Answers")
|
279 |
+
st.text_area("Answers", st.session_state.generated_answers, height=300)
|
280 |
+
|
281 |
+
# Download Options
|
282 |
+
if "generated_questions" in st.session_state or "generated_answers" in st.session_state:
|
283 |
+
st.markdown("### Download Options")
|
284 |
+
download_choice = st.radio("Select Download Format", ["DOCX", "PDF", "TXT"])
|
285 |
+
|
286 |
+
content_to_download = ""
|
287 |
+
if "generated_questions" in st.session_state:
|
288 |
+
content_to_download += "Generated Questions:\n" + st.session_state.generated_questions + "\n\n"
|
289 |
+
if "generated_answers" in st.session_state:
|
290 |
+
content_to_download += "Generated Answers:\n" + st.session_state.generated_answers
|
291 |
+
|
292 |
+
if st.button("Download"):
|
293 |
+
if download_choice == "DOCX":
|
294 |
+
buffer = download_as_docx(content_to_download)
|
295 |
+
st.download_button(
|
296 |
+
label="Download as DOCX",
|
297 |
+
data=buffer,
|
298 |
+
file_name="exam_content.docx",
|
299 |
+
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
300 |
+
)
|
301 |
+
elif download_choice == "PDF":
|
302 |
+
buffer = download_as_pdf(content_to_download)
|
303 |
+
st.download_button(
|
304 |
+
label="Download as PDF",
|
305 |
+
data=buffer,
|
306 |
+
file_name="exam_content.pdf",
|
307 |
+
mime="application/pdf",
|
308 |
+
)
|
309 |
+
elif download_choice == "TXT":
|
310 |
+
buffer = BytesIO(content_to_download.encode("utf-8"))
|
311 |
+
st.download_button(
|
312 |
+
label="Download as TXT",
|
313 |
+
data=buffer,
|
314 |
+
file_name="exam_content.txt",
|
315 |
+
mime="text/plain",
|
316 |
+
)
|