It sounds like your PDF text parsing module is struggling to correctly extract and detect Gujarati text, resulting in it being misclassified or skipped by the language filter. Here's a comprehensive approach to address and resolve this issue:
- Ensure Proper OCR Language Configuration
- Verify Tesseract Gujarati Language Data Installation
- Enhance Language Detection Mechanism
- Handle Embedded Gujarati Text in PDFs
Let's go through each step in detail:
1. Ensure Proper OCR Language Configuration
Currently, your OCR function is set to recognize only English text:
ocr_text = pytesseract.image_to_string(img, lang='eng')
To correctly recognize Gujarati text, you need to include Gujarati in the OCR language configuration. Tesseract supports multiple languages, and you can specify multiple languages by separating them with a plus sign (+).
Action Steps:
-
Update the OCR Language Parameter:
Modify the lang parameter to include both English and Gujarati. Replace 'eng' with 'eng+guj' (assuming 'guj' is the correct Tesseract language code for Gujarati).
ocr_text = pytesseract.image_to_string(img, lang='eng+guj')
-
Verify Language Codes:
Ensure that 'guj' is the correct language code for Gujarati in your Tesseract installation. You can list available languages using:
tesseract --list-langs
If Gujarati is not listed, you may need to download the Gujarati language training data.
2. Verify Tesseract Gujarati Language Data Installation
For Tesseract to recognize Gujarati, the appropriate language data must be installed.
Action Steps:
-
Check Installed Languages:
Run the following command to list all installed languages:
tesseract --list-langs
Look for 'guj' in the output.
-
Download Gujarati Language Data (If Not Installed):
If Gujarati is not listed, download the language data:
sudo apt-get install tesseract-ocr-guj
Note: The installation command may vary based on your operating system. For Windows, you can download the .traineddata file from Tesseract's GitHub repository and place it in the tessdata directory.
-
Confirm Installation:
After installation, verify again using:
tesseract --list-langs
3. Enhance Language Detection Mechanism
The current language detection uses the langdetect library, which might not always accurately detect Gujarati, especially with short or fragmented text. To improve accuracy:
Action Steps:
-
Use More Robust Language Detection:
Consider using alternative libraries like fasttext for more accurate language detection, especially for Gujarati.
import fasttext
# Download the pre-trained language identification model
# https://fasttext.cc/docs/en/language-identification.html
model = fasttext.load_model('lid.176.bin')
def is_gujarati(text):
predictions = model.predict(text.replace('\n', ' '), k=1) # top-1 prediction
return predictions[0][0].replace('__label__', '') == 'gu'
-
Increase Text Sample Size for Detection:
Ensure that the text passed to the language detector is sufficiently long to improve detection accuracy.
def is_gujarati(text):
if len(text) < 20: # Adjust threshold as needed
return False
try:
lang = detect(text)
return lang == 'gu'
except Exception as e:
logging.warning(f"Language detection failed: {e}")
return False
-
Combine Multiple Language Detectors:
Using a combination of detectors can enhance reliability.
4. Handle Embedded Gujarati Text in PDFs
If the PDF contains embedded (selectable) Gujarati text rather than scanned images, PyMuPDF (fitz) should be able to extract it directly without needing OCR. However, if it's returning gibberish, there might be encoding or font issues.
Action Steps:
-
Verify Text Extraction with PyMuPDF:
Extract text using PyMuPDF and inspect it manually.
extracted_text = extract_text_with_pymupdf(pdf_path)
print(extracted_text[:1000]) # Print the first 1000 characters for inspection
-
Check for Encoding Issues:
Ensure that the extracted text is correctly decoded. PyMuPDF should handle Unicode properly, but sometimes fonts with custom encodings can cause issues.
-
Fallback to OCR for Embedded Text:
If embedded text is not extractable or is garbled, consider falling back to OCR even for such PDFs.
def extract_text_hybrid(pdf_path, start_page=None, end_page=None):
# Attempt to extract using PyMuPDF
text = extract_text_with_pymupdf(pdf_path, start_page, end_page)
if not text.strip() or is_garbage(text):
logging.warning(f"No usable text extracted with PyMuPDF for {pdf_path}. Using OCR.")
text = extract_text_with_ocr(pdf_path, start_page, end_page)
return text
Implement an is_garbage function to determine if the extracted text is valid.
5. Update Your Parsing Logic to Handle Gujarati
Once the text extraction and language detection are robust, ensure that your parsing logic (parse_questions_and_options) correctly handles Gujarati text.
Action Steps:
-
Modify Parsing Logic to Support Gujarati:
If questions and options are in Gujarati, make sure your regex patterns accommodate Gujarati characters. For example, ensure that regex patterns are Unicode-aware.
# Example: Using Unicode word characters
question_blocks = re.split(r'\b(\d+)\.\s+', text, flags=re.UNICODE)
-
Process Mixed Language Content Appropriately:
If some questions are in English and others in Gujarati, handle each case accordingly based on the detected language.
6. Comprehensive Code Update Example
Here's an updated version of your OCR extraction function and related parts to incorporate the above recommendations:
import os
import re
import logging
from datetime import datetime
from dotenv import load_dotenv
from langdetect import detect, DetectorFactory
import psycopg2
from psycopg2 import sql
import fitz # PyMuPDF
from pdf2image import convert_from_path
import pytesseract
from PIL import Image
import fasttext # Optional for improved language detection
# Load environment variables from .env file
load_dotenv()
# Ensure consistent language detection
DetectorFactory.seed = 0
# Configure logging
logging.basicConfig(
filename='exam_data_import.log',
filemode='a',
level=logging.DEBUG, # Set to DEBUG for detailed logs
format='%(asctime)s:%(levelname)s:%(message)s'
)
# Database connection parameters from environment variables
DB_PARAMS = {
'dbname': os.getenv('DB_NAME'),
'user': os.getenv('DB_USER'),
'password': os.getenv('DB_PASSWORD'),
'host': os.getenv('DB_HOST'),
'port': os.getenv('DB_PORT')
}
# Paths from environment variables
PAK_PDF_PATH = os.getenv('PAK_PDF_PATH')
FAK_PDF_PATH = os.getenv('FAK_PDF_PATH')
POPPLER_PATH = os.getenv('POPPLER_PATH')
TESSERACT_CMD = os.getenv('TESSERACT_CMD')
OUTPUT_DIR = os.getenv('OUTPUT_DIR')
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Configure Tesseract OCR
pytesseract.pytesseract.tesseract_cmd = TESSERACT_CMD
# Optional: Initialize FastText model for language detection
# model = fasttext.load_model('lid.176.bin') # Ensure the model file is available
def extract_text_with_pymupdf(pdf_path, start_page=None, end_page=None):
"""
Extract text from PDF using PyMuPDF (fitz).
"""
try:
doc = fitz.open(pdf_path)
text = ""
total_pages = doc.page_count
# Determine pages to extract
if start_page and end_page:
pages = range(start_page - 1, min(end_page, total_pages))
elif start_page:
pages = range(start_page - 1, total_pages)
else:
pages = range(total_pages)
for page_num in pages:
page = doc.load_page(page_num)
page_text = page.get_text("text") # Explicitly get plain text
text += page_text + "\n"
logging.info(f"Extracted text from PDF {pdf_path} using PyMuPDF.")
return text
except Exception as e:
logging.error(f"Error extracting text from PDF {pdf_path} with PyMuPDF: {e}")
return ""
def extract_text_with_ocr(pdf_path, start_page=None, end_page=None):
"""
Extract text from PDF using OCR with Tesseract.
"""
try:
images = convert_from_path(
pdf_path,
first_page=start_page,
last_page=end_page,
poppler_path=POPPLER_PATH
)
text = ""
for img in images:
# Use both English and Gujarati OCR
ocr_text = pytesseract.image_to_string(img, lang='eng+guj')
text += ocr_text + "\n"
logging.info(f"Extracted text from PDF {pdf_path} using OCR.")
return text
except Exception as e:
logging.error(f"Error extracting text from PDF {pdf_path} with OCR: {e}")
return ""
def is_gujarati(text):
"""
Detect if the given text is in Gujarati.
"""
try:
if len(text.strip()) < 20:
return False # Adjust threshold as needed
lang = detect(text)
return lang == 'gu'
# Optional: Using FastText for improved detection
# predictions = model.predict(text.replace('\n', ' '), k=1)
# return predictions[0][0].replace('__label__', '') == 'gu'
except Exception as e:
logging.warning(f"Language detection failed: {e}")
return False
def normalize_text(text):
"""
Normalize text by replacing multiple spaces and newlines with single space.
"""
text = re.sub(r'\s+', ' ', text, flags=re.UNICODE)
return text.strip()
def extract_text_hybrid(pdf_path, start_page=None, end_page=None):
"""
Hybrid extraction: Try PyMuPDF first, fallback to OCR if no or invalid text is found.
"""
text = extract_text_with_pymupdf(pdf_path, start_page, end_page)
if not text.strip() or is_garbage(text):
logging.warning(f"No usable text extracted with PyMuPDF for {pdf_path}. Using OCR.")
text = extract_text_with_ocr(pdf_path, start_page, end_page)
return text
def is_garbage(text):
"""
Define a heuristic to determine if the text is garbage.
For simplicity, check if a significant portion is non-printable or has low language detection confidence.
"""
# Example heuristic: Check for a high percentage of non-ASCII characters
non_ascii = sum(1 for c in text if ord(c) > 127)
ratio = non_ascii / len(text) if text else 0
return ratio > 0.9 # Adjust threshold as needed
# ... [Rest of your existing functions remain unchanged] ...
# Example updates in parse_questions_and_options
def parse_questions_and_options(text):
"""
Parse questions and options from the extracted PAK text.
Returns two lists:
- questions: List of dictionaries with 'number' and 'text'.
- options: List of dictionaries mapping option labels to option texts.
"""
questions = []
options = []
# Improved split: Use word boundary and flexible spacing, capture question numbers
question_blocks = re.split(r'\b(\d+)\.\s+', text, flags=re.UNICODE)
total_questions = (len(question_blocks) - 1) // 2
logging.debug(f"Total question blocks found: {total_questions}")
for i in range(1, len(question_blocks), 2):
q_num_str = question_blocks[i]
try:
q_num = int(q_num_str)
except ValueError:
logging.warning(f"Invalid question number encountered: {q_num_str}. Skipping block.")
continue
block = question_blocks[i + 1]
# Extract question text ending before option (A)
q_text_match = re.match(r'\s*(.*?)\s*\(\s*A\s*\)', block, re.IGNORECASE | re.DOTALL)
if q_text_match:
q_text = q_text_match.group(1).strip()
# Per-question language detection to skip Gujarati
if is_gujarati(q_text):
logging.info(f"Question {q_num} is in Gujarati. Skipping.")
continue # Skip Gujarati questions
# Extract options using regex
opts = re.findall(r'\(\s*([A-Da-d])\s*\)\s*(.*?)(?=\(\s*[A-Da-d]\s*\)|$)', block, re.IGNORECASE | re.DOTALL)
option_dict = {}
for opt in opts:
label = opt[0].upper()
opt_text = ' '.join(opt[1].strip().split()) # Normalize whitespace
option_dict[label] = opt_text
if len(option_dict) != 4:
logging.warning(f"Question {q_num} has {len(option_dict)} options instead of 4.")
questions.append({'number': q_num, 'text': q_text})
options.append(option_dict)
logging.debug(f"Parsed Question {q_num}: {q_text}")
for label, opt_text in option_dict.items():
logging.debug(f" Option {label}: {opt_text}")
else:
logging.warning(f"Failed to match question text in block for Question No. {q_num}")
return questions, options
# ... [Continue with the rest of your existing functions] ...
def main():
"""
Main function to orchestrate the extraction and insertion process.
"""
# Step 1: Extract and Insert Exam Details from PAK (First Page)
print("Extracting Exam Details from PAK (First Page)...")
# Assume this step is already completed, and you have exam_details
# In practice, use the OCR extraction you have done previously
exam_details = {
'exam_name': 'Assistant Engineer (Civil), Class-2, Roads and Building Department',
'exam_date': datetime.strptime('23/06/2019', '%d/%m/%Y').date(),
'advertisement_number': '79/2018-19',
'exam_code': None # If not extracted, keep as None
}
print("Inserting Exam Details into Database...")
exam_id = extract_and_insert_exam_details(exam_details, DB_PARAMS)
if not exam_id:
print("Failed to insert exam details. Exiting...")
return
# Step 2: Extract Questions and Options from PAK (Subsequent Pages)
print("Extracting Questions and Options from PAK...")
extract_and_insert_questions(PAK_PDF_PATH, exam_id, DB_PARAMS)
# Step 3: Extract Answers from FAK
print("Extracting Answers from FAK...")
extract_and_insert_answers(FAK_PDF_PATH, exam_id, DB_PARAMS)
print("Data extraction and insertion completed successfully.")
if __name__ == '__main__':
main()
7. Additional Recommendations
-
Logging and Monitoring:
Ensure that your logging captures enough detail to diagnose issues. Consider logging the detected language for each question to verify the accuracy of your language detection mechanism.
-
Error Handling:
Enhance error handling to gracefully manage unexpected scenarios, such as missing language data or corrupted PDFs.
-
Performance Optimization:
If processing large PDFs, consider optimizing OCR performance by processing pages in parallel or caching results where applicable.
-
Testing:
Thoroughly test the updated module with a variety of PDFs containing Gujarati and English text to ensure robustness and accuracy.
By implementing these changes, your module should more accurately extract and detect Gujarati text from PDFs, ensuring that relevant content is correctly processed and stored in your database.