Project Assistance: Refining Parsing Logic for "Questionbank" PostgreSQL Database
Overview
You've made significant progress in setting up the PostgreSQL database and extracting exam details using OCR. However, challenges remain in parsing and extracting questions, options, and answers from the PAK and FAK PDFs. This guide will help you refine your parsing logic, verify text extraction, handle multilingual content, and ensure seamless database integration.
Table of Contents
- Understanding the Extracted Text Structure
- Refining Regex Patterns
- Implementing Robust Parsing in Python
- Verifying Text Extraction
- Handling Variations in PDF Formatting
- Managing Multilingual Content
- Enhancing the Python Script
- Best Practices and Additional Considerations
1. Understanding the Extracted Text Structure
Based on your sample extracted text, each question follows this general format:
102. The plan of a map was photocopied to a reduced size such that a line originally 120 mm, measures
90 mm. The original scale of plan was 1:1000. What will be the revised scale?
(A) 1: 1200 (B) 1: 1232
(C) 1: 1333 (D) 1: 1121
Key Observations:
- Question Number: Starts with digits followed by a period (e.g.,
102.).
- Question Text: Can span multiple lines.
- Options: Each option starts with
(A), (B), (C), or (D), followed by the option text. Options may be on the same line or separate lines.
2. Refining Regex Patterns
To accurately parse the questions and options, we'll design regex patterns that:
Proposed Regex Patterns:
-
Question Extraction:
question_pattern = re.compile(
r'(?P<question_number>\d+)\.\s+(?P<question_text>.*?)(?=\(\w\))',
re.DOTALL
)
- Explanation:
(?P<question_number>\d+): Captures one or more digits as the question number.
\.\s+: Matches a period followed by one or more whitespace characters.
(?P<question_text>.*?): Lazily captures all characters up to the next pattern.
(?=\(\w\)): Positive lookahead to ensure that the question text ends where an option begins (e.g., (A)).
re.DOTALL: Allows . to match newline characters, enabling multi-line question texts.
-
Options Extraction:
options_pattern = re.compile(
r'\((?P<option_label>[A-D])\)\s*(?P<option_text>[^()]+)',
re.MULTILINE
)
- Explanation:
\((?P<option_label>[A-D])\): Captures the option label (A, B, C, D) enclosed in parentheses.
\s*: Matches zero or more whitespace characters.
(?P<option_text>[^()]+): Captures the option text, ensuring it doesn't include parentheses.
re.MULTILINE: Allows the pattern to match across multiple lines.
-
Answer Extraction from FAK:
Assuming the FAK PDF maps question numbers to correct options in a format like:
102:A
103:C
answer_pattern = re.compile(
r'(?P<question_number>\d+)\s*[:\-]\s*(?P<correct_option>[A-D])',
re.MULTILINE
)
- Explanation:
(?P<question_number>\d+): Captures the question number.
\s*[:\-]\s*: Matches a colon or hyphen with optional surrounding whitespace.
(?P<correct_option>[A-D]): Captures the correct option label.
3. Implementing Robust Parsing in Python
Below is a Python script that integrates the refined regex patterns to extract questions, options, and answers, then inserts them into the PostgreSQL database.
import re
import logging
import psycopg2
from psycopg2 import sql
# Configure logging
logging.basicConfig(level=logging.INFO, filename='questionbank.log',
format='%(asctime)s - %(levelname)s - %(message)s')
# Database connection parameters (use environment variables in production)
DB_PARAMS = {
'dbname': 'Questionbank',
'user': 'postgres',
'password': 'your_secure_password',
'host': 'localhost',
'port': 5432
}
def connect_db():
try:
conn = psycopg2.connect(**DB_PARAMS)
return conn
except psycopg2.OperationalError as e:
logging.error(f"Database connection failed: {e}")
raise
def parse_pak_text(pak_text):
questions = []
# Define regex patterns
question_pattern = re.compile(
r'(?P<question_number>\d+)\.\s+(?P<question_text>.*?)(?=\(\w\))',
re.DOTALL
)
options_pattern = re.compile(
r'\((?P<option_label>[A-D])\)\s*(?P<option_text>[^()]+)',
re.MULTILINE
)
# Find all questions
for q_match in question_pattern.finditer(pak_text):
q_num = int(q_match.group('question_number'))
q_text = q_match.group('question_text').strip().replace('\n', ' ')
start, end = q_match.span()
# Extract the options text starting from the end of the question
options_text = pak_text[end:]
options = options_pattern.findall(options_text)
# Take only the first 4 options (A-D)
options = options[:4]
if len(options) < 4:
logging.warning(f"Question {q_num} has less than 4 options.")
questions.append({
'question_number': q_num,
'question_text': q_text,
'options': options
})
return questions
def parse_fak_text(fak_text):
answers = {}
answer_pattern = re.compile(
r'(?P<question_number>\d+)\s*[:\-]\s*(?P<correct_option>[A-D])',
re.MULTILINE
)
for a_match in answer_pattern.finditer(fak_text):
q_num = int(a_match.group('question_number'))
correct_opt = a_match.group('correct_option')
answers[q_num] = correct_opt
return answers
def insert_data(conn, exam_id, questions, answers):
try:
with conn.cursor() as cur:
for q in questions:
# Insert question
cur.execute(
"""
INSERT INTO questions (exam_id, question_number, question_text)
VALUES (%s, %s, %s)
RETURNING question_id
""",
(exam_id, q['question_number'], q['question_text'])
)
q_id = cur.fetchone()[0]
# Insert options
for opt_label, opt_text in q['options']:
cur.execute(
"""
INSERT INTO options (question_id, option_label, option_text)
VALUES (%s, %s, %s)
""",
(q_id, opt_label, opt_text.strip())
)
# Insert answer if available
if q['question_number'] in answers:
correct_opt = answers[q['question_number']]
cur.execute(
"""
INSERT INTO answers (question_id, correct_option)
VALUES (%s, %s)
""",
(q_id, correct_opt)
)
else:
logging.warning(f"No answer found for Question {q['question_number']}.")
conn.commit()
logging.info("Data insertion completed successfully.")
except Exception as e:
conn.rollback()
logging.error(f"Data insertion failed: {e}")
raise
def main():
# Example extracted text from PAK and FAK PDFs
pak_text = """
102. The plan of a map was photocopied to a reduced size such that a line originally 120 mm, measures
90 mm. The original scale of plan was 1:1000. What will be the revised scale?
(A) 1: 1200 (B) 1: 1232
(C) 1: 1333 (D) 1: 1121
103. A lighthouse is visible above the horizon at a certain station at the sea level. If the distance between
the station and the lighthouse is 40 km, then the height of lighthouse is approximately
(A) 108 m (B) 126 m
(C) 132 m (D) 148 m
"""
fak_text = """
102:A
103:C
"""
# Parse the texts
questions = parse_pak_text(pak_text)
answers = parse_fak_text(fak_text)
# Connect to the database
conn = connect_db()
try:
# Insert data
exam_id = 5 # Replace with the actual exam_id
insert_data(conn, exam_id, questions, answers)
finally:
conn.close()
if __name__ == "__main__":
main()
Key Components:
-
Logging:
- Logs are written to
questionbank.log with timestamps and severity levels.
- Helps in tracking the script's operations and troubleshooting.
-
Database Connection:
- Encapsulated in the
connect_db function with error handling.
- Security Note: Avoid hardcoding credentials. Use environment variables or configuration files.
-
Parsing Functions:
parse_pak_text: Extracts questions and options from the PAK text.
parse_fak_text: Extracts answers from the FAK text.
-
Data Insertion:
- Inserts questions, options, and answers into their respective tables.
- Uses transactions to ensure data integrity. Rolls back in case of errors.
-
Main Execution:
- Demonstrates parsing with sample texts.
- Replace
pak_text and fak_text with actual extracted texts from PDFs.
4. Verifying Text Extraction
Before parsing, it's crucial to ensure that the text extraction from PDFs is accurate. Here's how you can verify:
-
Add Logging and Print Statements:
Modify your extraction functions to log the raw extracted text.
def extract_pak_text(pdf_path):
# Your existing extraction logic using pdfminer or pytesseract
extracted_text = "..." # Replace with actual extraction
logging.info("PAK Text Extracted Successfully.")
logging.debug(f"PAK Text: {extracted_text}")
return extracted_text
def extract_fak_text(pdf_path):
# Your existing extraction logic
extracted_text = "..." # Replace with actual extraction
logging.info("FAK Text Extracted Successfully.")
logging.debug(f"FAK Text: {extracted_text}")
return extracted_text
-
Inspect Logs:
- Set the logging level to
DEBUG to capture detailed information.
- Review
questionbank.log to ensure the extracted text is as expected.
-
Handle OCR Output:
If OCR is used for the first page (PAK), ensure that the OCR quality is sufficient. Poor OCR results can lead to inaccurate parsing.
- Tips for Better OCR:
- Use high-resolution PDFs.
- Preprocess images to enhance text clarity (e.g., binarization, noise reduction).
- Specify the correct language for
pytesseract to improve accuracy.
5. Handling Variations in PDF Formatting
PDFs might have inconsistencies such as varying line breaks, spacing, or punctuation. To handle these:
-
Normalize Text:
Preprocess the extracted text to standardize formatting.
def normalize_text(text):
# Replace multiple spaces and newlines with single space
text = re.sub(r'\s+', ' ', text)
return text
- Apply
normalize_text to pak_text and fak_text before parsing.
-
Flexible Regex Patterns:
Ensure that regex patterns account for optional spaces and varying formats.
-
Iterative Testing:
Test the parser with multiple sample PDFs to identify and handle edge cases.
6. Managing Multilingual Content
If some pages or sections are in Gujarati, handle them appropriately to prevent parsing errors.
-
Language Detection:
Use langdetect to identify the language of each text block.
from langdetect import detect, DetectorFactory
DetectorFactory.seed = 0 # For consistent results
def is_english(text):
try:
return detect(text) == 'en'
except:
return False
-
Processing Strategy:
-
Integrate Language Check in Parsing:
def parse_pak_text(pak_text):
if not is_english(pak_text):
logging.warning("PAK text is not in English. Skipping parsing.")
return []
# Proceed with parsing as before
...
7. Enhancing the Python Script
Implementing the above improvements, here's an enhanced version of the parsing and insertion logic with additional features:
import re
import logging
import psycopg2
from psycopg2 import sql
from langdetect import detect, DetectorFactory
# Configure logging
logging.basicConfig(level=logging.DEBUG, filename='questionbank.log',
format='%(asctime)s - %(levelname)s - %(message)s')
# Ensure consistent language detection
DetectorFactory.seed = 0
# Database connection parameters
DB_PARAMS = {
'dbname': 'Questionbank',
'user': 'postgres',
'password': 'your_secure_password',
'host': 'localhost',
'port': 5432
}
def connect_db():
try:
conn = psycopg2.connect(**DB_PARAMS)
logging.info("Database connection established.")
return conn
except psycopg2.OperationalError as e:
logging.error(f"Database connection failed: {e}")
raise
def normalize_text(text):
return re.sub(r'\s+', ' ', text).strip()
def is_english(text):
try:
return detect(text) == 'en'
except:
return False
def parse_pak_text(pak_text):
if not is_english(pak_text):
logging.warning("PAK text is not in English. Skipping parsing.")
return []
normalized_text = normalize_text(pak_text)
questions = []
question_pattern = re.compile(
r'(?P<question_number>\d+)\.\s+(?P<question_text>.*?)(?=\(\w\))',
re.DOTALL
)
options_pattern = re.compile(
r'\((?P<option_label>[A-D])\)\s*(?P<option_text>[^()]+)',
re.MULTILINE
)
for q_match in question_pattern.finditer(normalized_text):
q_num = int(q_match.group('question_number'))
q_text = q_match.group('question_text').strip()
start, end = q_match.span()
options_text = normalized_text[end:]
options = options_pattern.findall(options_text)
options = options[:4]
if len(options) < 4:
logging.warning(f"Question {q_num} has less than 4 options.")
questions.append({
'question_number': q_num,
'question_text': q_text,
'options': options
})
logging.info(f"Parsed {len(questions)} questions from PAK.")
return questions
def parse_fak_text(fak_text):
if not is_english(fak_text):
logging.warning("FAK text is not in English. Skipping parsing.")
return {}
normalized_text = normalize_text(fak_text)
answers = {}
answer_pattern = re.compile(
r'(?P<question_number>\d+)\s*[:\-]\s*(?P<correct_option>[A-D])',
re.MULTILINE
)
for a_match in answer_pattern.finditer(normalized_text):
q_num = int(a_match.group('question_number'))
correct_opt = a_match.group('correct_option')
answers[q_num] = correct_opt
logging.info(f"Parsed {len(answers)} answers from FAK.")
return answers
def insert_data(conn, exam_id, questions, answers):
try:
with conn.cursor() as cur:
for q in questions:
# Check if question already exists to prevent duplicates
cur.execute(
"SELECT question_id FROM questions WHERE exam_id = %s AND question_number = %s",
(exam_id, q['question_number'])
)
result = cur.fetchone()
if result:
q_id = result[0]
logging.info(f"Question {q['question_number']} already exists. Skipping insertion.")
else:
# Insert question
cur.execute(
"""
INSERT INTO questions (exam_id, question_number, question_text)
VALUES (%s, %s, %s)
RETURNING question_id
""",
(exam_id, q['question_number'], q['question_text'])
)
q_id = cur.fetchone()[0]
logging.info(f"Inserted Question {q['question_number']} with ID {q_id}.")
# Insert options
for opt_label, opt_text in q['options']:
# Check if option already exists
cur.execute(
"""
SELECT option_id FROM options
WHERE question_id = %s AND option_label = %s
""",
(q_id, opt_label)
)
opt_result = cur.fetchone()
if opt_result:
logging.info(f"Option {opt_label} for Question {q['question_number']} already exists.")
continue
cur.execute(
"""
INSERT INTO options (question_id, option_label, option_text)
VALUES (%s, %s, %s)
""",
(q_id, opt_label, opt_text.strip())
)
logging.info(f"Inserted Option {opt_label} for Question {q['question_number']}.")
# Insert answer if available
if q['question_number'] in answers:
correct_opt = answers[q['question_number']]
cur.execute(
"SELECT answer_id FROM answers WHERE question_id = %s",
(q_id,)
)
ans_result = cur.fetchone()
if ans_result:
logging.info(f"Answer for Question {q['question_number']} already exists.")
continue
cur.execute(
"""
INSERT INTO answers (question_id, correct_option)
VALUES (%s, %s)
""",
(q_id, correct_opt)
)
logging.info(f"Inserted Answer for Question {q['question_number']}: {correct_opt}.")
else:
logging.warning(f"No answer found for Question {q['question_number']}.")
conn.commit()
logging.info("All data inserted successfully.")
except Exception as e:
conn.rollback()
logging.error(f"Data insertion failed: {e}")
raise
def main():
# Paths to your PAK and FAK PDFs
pak_pdf_path = 'path_to_pak_pdf.pdf'
fak_pdf_path = 'path_to_fak_pdf.pdf'
# Extract text from PDFs (implement actual extraction logic)
pak_text = extract_pak_text(pak_pdf_path) # Replace with actual function
fak_text = extract_fak_text(fak_pdf_path) # Replace with actual function
# Parse the texts
questions = parse_pak_text(pak_text)
answers = parse_fak_text(fak_text)
# Connect to the database
conn = connect_db()
try:
# Insert data
exam_id = 5 # Replace with dynamic exam_id as needed
insert_data(conn, exam_id, questions, answers)
finally:
conn.close()
logging.info("Database connection closed.")
def extract_pak_text(pdf_path):
# Implement your PDF extraction logic here
# Example using pdfminer.six or pytesseract
extracted_text = "" # Replace with actual extraction
logging.info(f"Extracted PAK text from {pdf_path}.")
return extracted_text
def extract_fak_text(pdf_path):
# Implement your PDF extraction logic here
extracted_text = "" # Replace with actual extraction
logging.info(f"Extracted FAK text from {pdf_path}.")
return extracted_text
if __name__ == "__main__":
main()
Enhancements:
-
Normalization:
- Reduces inconsistencies caused by varying spacing and line breaks.
-
Language Detection:
- Skips non-English content to prevent parsing errors.
-
Duplicate Checks:
- Prevents inserting duplicate questions, options, or answers.
-
Comprehensive Logging:
- Logs all significant actions, aiding in monitoring and debugging.
-
Placeholder Extraction Functions:
extract_pak_text and extract_fak_text should be implemented with actual PDF extraction logic using pdfminer.six or pytesseract.
8. Best Practices and Additional Considerations
-
Secure Handling of Credentials:
-
Use Environment Variables:
import os
DB_PARAMS = {
'dbname': os.getenv('DB_NAME'),
'user': os.getenv('DB_USER'),
'password': os.getenv('DB_PASSWORD'),
'host': os.getenv('DB_HOST', 'localhost'),
'port': os.getenv('DB_PORT', 5432)
}
-
Set Environment Variables: Use .env files with libraries like python-dotenv or set them directly in the deployment environment.
-
Error Handling:
- Ensure all exceptions are caught and logged appropriately.
- Provide meaningful error messages to facilitate troubleshooting.
-
Performance Optimization:
-
Bulk Insertions:
- Use
executemany or PostgreSQL's COPY for larger datasets to improve insertion speed.
-
Connection Pooling:
- For large-scale operations, use connection pooling libraries like
psycopg2.pool.
-
Testing:
-
Unit Tests:
- Write tests for parsing functions to ensure reliability across different input formats.
-
Integration Tests:
- Test the entire workflow from PDF extraction to database insertion with diverse samples.
-
Backup and Recovery:
- Implement regular backups of the PostgreSQL database.
- Test restore procedures to ensure data can be recovered in case of failures.
-
Logging Enhancement:
- Rotate logs to prevent them from growing indefinitely using tools like
logrotate or logging handlers in Python.
-
Documentation:
- Document the codebase, especially the parsing logic and database schema, for future maintenance and onboarding.
-
Scalability:
- Design the system to handle increasing volumes of PDFs and data without significant performance degradation.
Conclusion
By refining your regex patterns, implementing robust parsing logic, verifying text extraction, and adhering to best practices, you can overcome the existing challenges in populating the "Questionbank" PostgreSQL database. Ensure thorough testing with diverse PDF samples to handle various formatting nuances and maintain data integrity. Addressing multilingual content thoughtfully will further enhance the system's reliability and usability.
Feel free to reach out with specific code snippets or further questions as you progress!