Project Overview
Objective:
Develop a PostgreSQL database named "Questionbank" using pgAdmin to store data extracted from State Engineering Services exam PDFs, specifically from the Preliminary Answer Key (PAK) and Final Answer Key (FAK) documents.
Database Schema
exams Table
Columns:
exam_id (SERIAL, PRIMARY KEY)
exam_name (VARCHAR(255), NOT NULL)
advertisement_number (VARCHAR(20), UNIQUE, NOT NULL)
exam_code (VARCHAR(20), UNIQUE, NULLABLE)
year (INT, NOT NULL)
questions Table
Columns:
question_id (SERIAL, PRIMARY KEY)
exam_id (INT, FOREIGN KEY referencing exams.exam_id ON DELETE CASCADE)
question_number (INT, NOT NULL)
question_text (TEXT, NOT NULL)
options Table
Columns:
option_id (SERIAL, PRIMARY KEY)
question_id (INT, FOREIGN KEY referencing questions.question_id ON DELETE CASCADE)
option_label (CHAR(1), CHECK IN ('A', 'B', 'C', 'D'))
option_text (TEXT, NOT NULL)
answers Table
Columns:
answer_id (SERIAL, PRIMARY KEY)
question_id (INT, UNIQUE, FOREIGN KEY referencing questions.question_id ON DELETE CASCADE)
correct_option (CHAR(1), CHECK IN ('A', 'B', 'C', 'D'))
Data Sources
Preliminary Answer Key (PAK) PDF
First Page: Contains unstructured exam details (Exam/Post Name, Exam Date, Advertisement Number) requiring OCR extraction.
Subsequent Pages: Contain structured questions and options directly extractable without OCR.
Final Answer Key (FAK) PDF
Contains structured tables mapping question numbers to correct options, extractable directly without OCR.
Tools & Libraries
Python Libraries:
pdfminer.six: For extracting text from PDFs.
pytesseract: For performing OCR on unstructured text.
langdetect: For detecting the language of extracted text.
psycopg2-binary: PostgreSQL adapter for Python.
logging: For logging script activities and errors.
External Tools:
Poppler: Required by pdf2image for PDF processing.
Tesseract OCR: Required by pytesseract for OCR tasks.
Ollama Backend & LLM: Considered for handling and translating Gujarati text (optional at this stage).
Issues & Resolutions
Schema Mismatch:
Issue:
Encountered an error while inserting exam details:
column "advertisement_number" of relation "exams" does not exist
Resolution:
Updated the exams table schema to include the advertisement_number column and ensured it matches the insertion script.
Parsing Failure:
Issue:
Script extracts 0 questions and 0 answers despite having structured text in the PDFs.
Sample Extracted Text from PAK:
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
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
Potential Causes:
Regex Misalignment: The current regex patterns do not accurately match the structure of the extracted text.
Formatting Variations: Inconsistent use of punctuation, spacing, or line breaks in the PDFs leading to parsing failures.
Database Connection Issues:
Error Message:
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "postgres"
Resolution:
Set a secure password for the postgres user.
Updated the pg_hba.conf file to use md5 authentication.
Restarted the PostgreSQL service to apply changes.
Modified the Python script to include the correct password in the connection parameters.
UnboundLocalError in Script:
Error Message:
UnboundLocalError: cannot access local variable 'conn' where it is not associated with a value
UnboundLocalError: cannot access local variable 'cursor' where it is not associated with a value
Resolution:
Enhanced error handling using try-except-finally blocks.
Utilized context managers (with statements) to manage database connections and cursors, ensuring they are properly closed even when exceptions occur.
Current Status
Exam Details Extraction:
Successfully extracted and inserted into the exams table with exam_id: 5.
Questions and Options Extraction:
Issue: Script is currently extracting 0 questions and 0 options from the PAK PDF.
Answers Extraction:
Issue: Script is currently extracting 0 answers from the FAK PDF.
Sample Data for Clarification
Extracted Questions and Options Format:
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
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
Key Steps Taken So Far
Setup:
Created the PostgreSQL database "Questionbank" using pgAdmin.
Defined and adjusted the database schema to include necessary columns like advertisement_number.
Extracting Exam Details:
Used OCR (pytesseract) to extract unstructured exam details from the first page of the PAK PDF.
Inserted the extracted exam details into the exams table.
Processing PAK and FAK PDFs:
Attempted to extract questions and options from the structured pages of the PAK PDF directly without OCR.
Attempted to extract answers from the FAK PDF directly without OCR.
Encountered issues with the parsing logic, resulting in zero questions and answers being extracted.
Database Connection:
Resolved password authentication issues by setting a password for the postgres user and updating the script's connection parameters.
Error Handling Improvements:
Enhanced the Python script's error handling to prevent crashes and provide meaningful log messages.
Next Steps for Assistance
Refinement of Parsing Logic:
Objective: Ensure the regex patterns accurately match the structure of extracted text to successfully parse questions, options, and answers.
Action Needed: Review and adjust the regex patterns based on the actual format of the extracted text samples.
Verification of Text Extraction:
Objective: Confirm that the text extraction from PAK and FAK PDFs is working as expected.
Action Needed: Add logging and print statements to inspect the complete extracted text before parsing.
Handling Variations in PDF Formatting:
Objective: Account for any inconsistencies or variations in how questions and answers are formatted across different PDFs.
Action Needed: Implement more flexible and robust parsing strategies, possibly incorporating natural language processing (NLP) techniques.
Multilingual Content Management:
Objective: Efficiently handle pages in Gujarati by either skipping them or processing them using translation models.
Action Needed: Utilize language detection to identify Gujarati pages and decide on an appropriate strategy (e.g., translation via a local LLM like Ollama).
Testing with Diverse Samples:
Objective: Ensure the script works across various PAK and FAK PDFs with different structures and content formats.
Action Needed: Test the parser with multiple sample PDFs and adjust the logic based on findings.
Additional Considerations
Security:
Ensure that database credentials are managed securely, avoiding hardcoding them in scripts. Utilize environment variables or secure configuration files.
Performance:
For large PDFs or bulk processing, consider optimizing the extraction and insertion processes to handle data efficiently.
Logging and Monitoring:
Maintain comprehensive logs to track the script's operations, aiding in troubleshooting and ensuring data integrity.
Backup:
Regularly backup the PostgreSQL database to prevent data loss.
Summary:
The project involves creating and populating a PostgreSQL database with exam questions and answers extracted from PAK and FAK PDFs. While OCR has been successfully implemented for the first, unstructured page of the PAK PDF, challenges remain in parsing and extracting structured questions, options, and answers from subsequent pages. The current parsing logic fails to extract data, resulting in zero entries. Assistance is needed to refine the parsing strategies, verify text extraction accuracy, handle multilingual content, and ensure seamless database integration.
Project Assistance: Refining Parsing Logic for "Questionbank" Database
You've made significant progress in setting up your PostgreSQL database and handling initial OCR tasks. The primary challenge now lies in refining the parsing logic to accurately extract questions, options, and answers from the PAK and FAK PDFs. Below are detailed steps and recommendations to address the issues you're encountering.
1. Verification of Text Extraction
Before diving into refining the parsing logic, it's crucial to ensure that the text extraction from the PDFs is functioning correctly.
Action Steps:
Add Comprehensive Logging:
Implement logging at various stages of text extraction to capture the raw extracted text.
Example:
python
import logging
logging.basicConfig(level=logging.DEBUG, filename='extraction.log',
format='%(asctime)s - %(levelname)s - %(message)s')
# After text extraction
extracted_text = extract_text_from_pdf(pdf_path)
logging.debug(f"Extracted Text: {extracted_text}")
Print Statements for Debugging:
Temporarily add print statements to display a portion of the extracted text.
python
print("Extracted Text Sample:", extracted_text[:1000]) # Print first 1000 characters
Save Extracted Text to Files:
Write the raw extracted text to separate .txt files for manual inspection.
python
with open('extracted_pak.txt', 'w', encoding='utf-8') as f:
f.write(extracted_text)
Benefits:
Identify Extraction Issues:
Confirm whether the structured content is being correctly extracted.
Detect if OCR is erroneously affecting structured pages.
Understand Text Structure:
Gain insights into how questions and options are formatted post-extraction, which aids in crafting accurate regex patterns.
2. Refinement of Regex Patterns
Once you've confirmed that the text extraction is accurate, the next step is to ensure that your regex patterns align with the structure of the extracted text.
Understanding the Extracted Text Structure:
Based on your sample:
code
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
Proposed Regex Patterns:
Question Extraction:
Pattern Explanation:
Start: Matches the question number followed by a dot and a space.
Body: Captures the entire question text until it encounters an option label.
Regex:
python
import re
question_pattern = re.compile(
r'(\d{1,3})\.\s+(.*?)\s+\(([A-D])\)', re.DOTALL
)
Usage:
python
questions = question_pattern.findall(extracted_text)
for q in questions:
question_id, question_text, first_option_label = q
# Further processing to extract options
Options Extraction:
Pattern Explanation:
Captures each option label (A, B, C, D) followed by the option text.
for question in questions:
options = options_pattern.findall(question_text)
for option in options:
label, option_text = option
# Insert into options table
Handling Line Breaks and Whitespace:
Whitespace Normalization:
Replace multiple spaces and line breaks with a single space to simplify regex matching.
If regex proves too brittle due to inconsistent formatting, consider leveraging Natural Language Processing (NLP) techniques for more robust parsing.
Approach:
Sentence Tokenization:
Use NLP libraries like NLTK or spaCy to tokenize the extracted text into sentences, aiding in identifying question and option boundaries.
Pattern Recognition:
Train a simple classifier to identify whether a sentence is a question, option, or other content.
Example with spaCy:
python
import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(extracted_text)
for sent in doc.sents:
text = sent.text.strip()
if re.match(r'^\d{1,3}\.', text):
# Identify as question
elif re.match(r'^\([A-D]\)', text):
# Identify as option
else:
# Handle accordingly
Benefits:
Flexibility:
Better handles variations in formatting and unexpected structures.
Scalability:
Easier to adapt to different PDF structures without constantly modifying regex patterns.
4. Handling PDF Formatting Variations
PDFs can have inconsistent formatting, especially when generated from different sources or versions. To make your parser more resilient:
Strategies:
Flexible Delimiters:
Instead of relying solely on specific characters like parentheses for options, allow for variations (e.g., dot, dash).
Multiple Patterns:
Implement multiple regex patterns and iterate over them to find a match.
State-Based Parsing:
Maintain a state machine (e.g., expecting a question, expecting options) to navigate through the text sequentially.
Example State-Based Parser:
python
def state_based_parser(text):
state = 'expect_question'
questions = []
current_question = {}
current_options = []
lines = text.split('\n')
for line in lines:
line = line.strip()
if state == 'expect_question':
q_match = re.match(r'^(\d{1,3})\.\s+(.*)', line)
if q_match:
current_question['number'] = int(q_match.group(1))
current_question['text'] = q_match.group(2)
current_options = []
state = 'expect_option'
elif state == 'expect_option':
o_match = re.match(r'^\(([A-D])\)\s+(.*)', line)
if o_match:
current_options.append({
'label': o_match.group(1),
'text': o_match.group(2)
})
if o_match.group(1) == 'D': # Assuming 4 options
current_question['options'] = current_options
questions.append(current_question)
current_question = {}
state = 'expect_question'
else:
# Handle cases where options are not on separate lines
pass
return questions
5. Extraction and Mapping of Answers from FAK PDF
Your FAK PDF contains mappings of question numbers to correct options, which should be parsed separately.
Proposed Approach:
Extract Answer Sections:
Identify sections in the FAK PDF that list answers, typically in a table format.
answers = answer_pattern.findall(fak_extracted_text)
for answer in answers:
question_number, correct_option = answer
# Fetch question_id using question_number and exam_id
# Insert into answers table
Handling Tables:
If the FAK PDF presents answers in a tabular format, consider parsing it as a table using libraries like tabula-py or camelot for more structured extraction.
python
import camelot
tables = camelot.read_pdf(fak_pdf_path, pages='all')
for table in tables:
df = table.df
# Iterate over DataFrame rows to extract question numbers and answers
6. Implementing Robust Error Handling and Logging
Enhancing error handling will make your script more resilient and easier to debug.
Recommendations:
Use Try-Except Blocks:
Encapsulate code sections with potential errors within try-except blocks.
python
try:
# Code that might raise an exception
except SpecificException as e:
logging.error(f"Specific error occurred: {e}")
except Exception as e:
logging.error(f"Unexpected error: {e}")
Context Managers:
Utilize with statements to manage resources like file handles and database connections.
python
with psycopg2.connect(...) as conn:
with conn.cursor() as cursor:
# Database operations
Detailed Logging:
Log the nature of the error, the location in the code, and relevant variables to facilitate debugging.
Graceful Degradation:
Ensure that one failure (e.g., a single malformed question) does not halt the entire script. Instead, log the issue and continue processing.
7. Managing Multilingual Content
Handling Gujarati text in your PDFs requires strategies to either process or skip such content.
Strategies:
Language Detection:
Use langdetect to identify the language of each page or text block.
If considering using the Ollama Backend & LLM, evaluate its efficacy in translating Gujarati.
Skipping Gujarati Content:
If Gujarati content is irrelevant (e.g., non-exam questions), simply skip processing those sections.
Implementation Example:
python
for page in pdf_pages:
text = extract_text(page)
if is_english(text):
process_english_text(text)
else:
logging.info("Skipped non-English content.")
continue
8. Database Integration and Data Insertion
Ensure that the extracted and parsed data seamlessly integrates into your PostgreSQL database.
For large datasets, inserting records in batches can significantly improve performance.
python
insert_questions_query = """
INSERT INTO questions (exam_id, question_number, question_text)
VALUES (%s, %s, %s) RETURNING question_id;
"""
question_records = [(exam_id, q['number'], q['text']) for q in questions]
cursor.executemany(insert_questions_query, question_records)
Transactional Integrity:
Use transactions to ensure that related inserts either all succeed or fail together.
python
try:
with conn:
with conn.cursor() as cursor:
# Insert operations
except Exception as e:
logging.error(f"Transaction failed: {e}")
9. Testing with Diverse Samples
To ensure robustness, test your parsing logic with various PAK and FAK PDFs that may have different formats.
Action Steps:
Collect Diverse Samples:
Gather PDFs from different years or sources to cover a range of formatting styles.
Automate Testing:
Create a testing script that processes each sample and validates the extracted data against expected results.
Document Findings:
Note any anomalies or patterns in the samples that require adjustments in your parsing logic.
10. Additional Considerations
Security:
Environment Variables:
Store database credentials and other sensitive information in environment variables or secure configuration files.
python
import os
DB_PASSWORD = os.getenv('DB_PASSWORD')
Use .env Files:
Utilize packages like python-dotenv to manage environment variables.
python
from dotenv import load_dotenv
load_dotenv()
DB_PASSWORD = os.getenv('DB_PASSWORD')
Performance Optimization:
Efficient Text Processing:
Avoid unnecessary computations by processing texts in a streamlined manner.
Parallel Processing:
For large PDFs, consider parallelizing the extraction and parsing tasks using multiprocessing.
Logging and Monitoring:
Log Levels:
Use appropriate log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) to differentiate the importance of log messages.
Log Rotation:
Implement log rotation to manage log file sizes, using tools like logging.handlers.RotatingFileHandler.
Database Backup:
Automated Backups:
Schedule regular backups using PostgreSQL tools like pg_dump.
bash
pg_dump -U postgres -F c -b -v -f "backup_questionbank.dump" Questionbank
Off-site Storage:
Store backups in a secure, off-site location to prevent data loss from local failures.
Sample Code Snippets
Here's a consolidated example integrating some of the recommendations mentioned above:
python
Note: This is a simplified example. You'll need to expand it to include answer parsing from the FAK PDF and handle edge cases as discussed.
Conclusion
By systematically verifying the text extraction, refining regex patterns, incorporating NLP techniques, and ensuring robust error handling, you can enhance your parsing logic to successfully extract and store questions, options, and answers in your "Questionbank" PostgreSQL database. Additionally, addressing multilingual content and testing with diverse samples will further strengthen the reliability and scalability of your solution.
Feel free to reach out with specific code snippets or error messages if you need more targeted assistance!