To significantly reduce the processing time of your OCR pipeline from approximately 16 hours to around 20-30 minutes, you'll need to implement several optimizations. The primary strategies include:
- Parallelization: Utilize multiple CPU cores to handle multiple image processing tasks simultaneously.
- Asynchronous I/O: Optimize network operations like image downloading by handling them asynchronously.
- Efficient Image Processing: Optimize or simplify image preprocessing steps where possible.
- Optimize OCR Processing: Configure Tesseract for faster performance.
- Batch Processing and Caching: Reduce redundant operations and manage resources efficiently.
Below, I'll guide you through implementing these optimizations step-by-step.
1. Parallelization with concurrent.futures
Python’s concurrent.futures module allows you to easily parallelize your code using threads or processes. Given that OCR and image processing are CPU-bound tasks, using ProcessPoolExecutor is more appropriate than ThreadPoolExecutor because it bypasses the Global Interpreter Lock (GIL).
Here's how you can modify your script to use ProcessPoolExecutor:
import re
import cv2
import pytesseract
import pandas as pd
import requests
from io import BytesIO
from PIL import Image
import numpy as np
from concurrent.futures import ProcessPoolExecutor, as_completed
import multiprocessing
import tqdm # For progress bar
# ... [Your existing mappings and functions] ...
# Ensure pytesseract is correctly configured
pytesseract.pytesseract.tesseract_cmd = '/opt/homebrew/bin/tesseract'
def process_row(row):
image_link = row['image_link']
entity_name = row['entity_name']
query_entities = [entity_name]
try:
extracted_entities = ocr_extract_entities(image_link, query_entities)
entity_value = extracted_entities.get(entity_name, 'void')
# Check if entity_value is a list or float
if entity_value != 'void' and entity_value != []:
if isinstance(entity_value, list):
numerical_value = f"{entity_value[0][0]:,.2f}"
unit = entity_value[0][1].lower()
prediction = f"{numerical_value} {unit}"
elif isinstance(entity_value, float) or isinstance(entity_value, int):
# Handle case when entity_value is a float or int, not a list
prediction = f"{entity_value:,.2f}"
else:
prediction = ''
else:
prediction = ''
except Exception as e:
prediction = ''
# Optionally log the error
# print(f"Error processing row {row.name}: {e}")
return {'index': row.name, 'prediction': prediction}
def main():
input_file = '/Users/kartik/Downloads/student_resource 3/test2.csv'
output_file = 'output12345.csv'
df = pd.read_csv(input_file)
results = []
# Determine the number of workers based on CPU cores
num_workers = multiprocessing.cpu_count()
with ProcessPoolExecutor(max_workers=num_workers) as executor:
# Use a generator to submit tasks
future_to_row = {executor.submit(process_row, row): row for _, row in df.iterrows()}
for future in tqdm.tqdm(as_completed(future_to_row), total=df.shape[0]):
result = future.result()
results.append(result)
# Convert results to DataFrame and save
output_df = pd.DataFrame(results)
output_df.to_csv(output_file, index=False)
if __name__ == "__main__":
main()
Explanation:
- ProcessPoolExecutor: Spawns multiple processes to execute tasks in parallel, leveraging multiple CPU cores.
process_row Function: Encapsulates the logic for processing a single row. This function is executed in parallel across multiple processes.
- Error Handling: Ensures that if a row fails to process, it won’t crash the entire script.
tqdm for Progress Tracking: Provides a visual progress bar to monitor the processing status.
2. Asynchronous Image Downloading with aiohttp
Downloading images is an I/O-bound task. To optimize this, you can handle image downloads asynchronously using the aiohttp library. However, since pytesseract and OpenCV are not inherently asynchronous, integrating asynchronous downloading within a multiprocessing setup can be complex.
An alternative approach is to separate the downloading and OCR stages:
- Stage 1: Asynchronously download all images and save them locally or in memory.
- Stage 2: Perform OCR on the downloaded images using multiprocessing.
Given the complexity, if image downloading is not the primary bottleneck, you might skip this step. However, if downloading significantly contributes to the total time, consider the following integrated approach using asyncio and aiohttp with limited parallelism:
import asyncio
import aiohttp
from concurrent.futures import ProcessPoolExecutor
async def fetch_image(session, url):
try:
async with session.get(url, timeout=10) as response:
if response.status == 200:
return await response.read()
else:
return None
except Exception:
return None
async def process_images_async(df, max_concurrent_requests=100):
connector = aiohttp.TCPConnector(limit=max_concurrent_requests)
async with aiohttp.ClientSession(connector=connector) as session:
tasks = [fetch_image(session, row['image_link']) for _, row in df.iterrows()]
images = await asyncio.gather(*tasks)
return images
def process_row_with_image(row, image_data):
image_link = row['image_link']
entity_name = row['entity_name']
query_entities = [entity_name]
if image_data is None:
return {'index': row.name, 'prediction': ''}
try:
img = Image.open(BytesIO(image_data))
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)
rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (18, 18))
dilation = cv2.dilate(thresh1, rect_kernel, iterations=1)
contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
im2 = img.copy()
extracted_text = ""
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
cropped = im2[y:y + h, x:x + w]
text = pytesseract.image_to_string(cropped)
extracted_text += text + "\n"
extracted_entities = extract_entity_values(extracted_text, query_entities)
entity_value = extracted_entities.get(entity_name, 'void')
if entity_value != 'void' and entity_value != []:
if isinstance(entity_value, list):
numerical_value = f"{entity_value[0][0]:,.2f}"
unit = entity_value[0][1].lower()
prediction = f"{numerical_value} {unit}"
elif isinstance(entity_value, float) or isinstance(entity_value, int):
prediction = f"{entity_value:,.2f}"
else:
prediction = ''
else:
prediction = ''
except Exception:
prediction = ''
return {'index': row.name, 'prediction': prediction}
def main_async():
input_file = '/Users/kartik/Downloads/student_resource 3/test2.csv'
output_file = 'output12345.csv'
df = pd.read_csv(input_file)
# Asynchronously download images
images = asyncio.run(process_images_async(df))
results = []
num_workers = multiprocessing.cpu_count()
with ProcessPoolExecutor(max_workers=num_workers) as executor:
future_to_row = {
executor.submit(process_row_with_image, row, image_data): row
for row, image_data in zip(df.itertuples(index=True), images)
}
for future in tqdm.tqdm(as_completed(future_to_row), total=df.shape[0]):
result = future.result()
results.append(result)
# Convert results to DataFrame and save
output_df = pd.DataFrame(results)
output_df.to_csv(output_file, index=False)
if __name__ == "__main__":
main_async()
Note: Integrating asyncio with multiprocessing can be non-trivial and might require careful handling of resources. Given the added complexity, only pursue this if image downloading is a major bottleneck.
3. Optimize Image Processing
-
Resize Images: If images are large, resizing them to a smaller resolution can speed up processing without significantly affecting OCR accuracy.
def preprocess_image(img, max_size=1024):
height, width = img.shape[:2]
if max(height, width) > max_size:
scaling_factor = max_size / float(max(height, width))
img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
return img
Integrate this function into your ocr_extract_entities:
def ocr_extract_entities(image_data, query_entities):
img = Image.open(BytesIO(image_data))
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
# Preprocess Image
img = preprocess_image(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)
# ... [Rest of your processing] ...
-
Simplify Preprocessing: Assess whether all preprocessing steps are necessary. For instance, if thresholding or dilation doesn't significantly improve OCR accuracy, consider removing or simplifying them.
4. Optimize Tesseract Configuration
-
Whitelist Characters: If you expect only numerical and unit characters, restrict Tesseract to recognize only those. This reduces the OCR search space and speeds up recognition.
custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789.,cmftinmlyozkgsVW'
# Use this config in pytesseract
text = pytesseract.image_to_string(cropped, config=custom_config)
-
Page Segmentation Mode (PSM): Experiment with different PSM options based on your image layout. For instance, --psm 6 treats the image as a single uniform block of text, which can be faster.
custom_config = r'--oem 3 --psm 6'
text = pytesseract.image_to_string(cropped, config=custom_config)
-
OEM: The OCR Engine Mode can also impact speed. --oem 1 (LSTM only) or --oem 3 (Default) are common choices. Test different modes for optimal speed.
5. Implement Caching (If Applicable)
If your dataset contains duplicate image URLs or limited unique images, implement caching to avoid redundant downloads and processing.
from functools import lru_cache
@lru_cache(maxsize=None)
def fetch_image_cached(url):
try:
response = requests.get(url, timeout=10)
if response.status_code == 200:
return response.content
except Exception:
pass
return None
Note: Be cautious with lru_cache and large datasets as it can consume significant memory. Alternatively, use a file-based or database cache.
6. Additional Tips
- Monitor Resource Usage: Use monitoring tools to ensure you’re not exhausting CPU, memory, or network bandwidth.
- Error Handling: Implement robust error handling to skip or retry failed downloads and OCR tasks without stopping the entire pipeline.
- Logging: Incorporate logging to track progress and encountered issues, which is helpful for debugging and optimization.
Complete Optimized Script Example
Combining the above suggestions, here’s a refined version of your script using parallel processing with ProcessPoolExecutor and optimized OCR:
import re
import cv2
import pytesseract
import pandas as pd
import requests
from io import BytesIO
from PIL import Image
import numpy as np
from concurrent.futures import ProcessPoolExecutor, as_completed
import multiprocessing
import tqdm
# Ensure pytesseract is correctly configured
pytesseract.pytesseract.tesseract_cmd = '/opt/homebrew/bin/tesseract'
entity_unit_map = {
# ... [Your existing entity_unit_map] ...
}
abbreviation_map = {
# ... [Your existing abbreviation_map] ...
}
entity_keywords = {
# ... [Your existing entity_keywords] ...
}
def preprocess_image(img, max_size=1024):
height, width = img.shape[:2]
if max(height, width) > max_size:
scaling_factor = max_size / float(max(height, width))
img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
return img
def extract_numerical_values(text, entity):
units = entity_unit_map[entity]
pattern = r'(\d+(\.\d+)?)\s*(' + '|'.join(units) + r')'
matches = re.findall(pattern, text, re.IGNORECASE)
if matches:
standardized_matches = [
(float(match[0]), abbreviation_map.get(match[2].lower(), match[2])) for match in matches
]
return standardized_matches
return 'void'
def extract_dimensions_pattern(text):
pattern = r'(\d+)x(\d+)x(\d+)\s*(mm|cm|in|ft|m)'
match = re.search(pattern, text, re.IGNORECASE)
if match:
length_value = float(match.group(1))
width_value = float(match.group(2))
height_value = float(match.group(3))
unit = abbreviation_map.get(match.group(4).lower(), match.group(4))
return {
'length': (length_value, unit),
'width': (width_value, unit),
'height': (height_value, unit)
}
return {}
def extract_entity_values(text, query_entities):
entity_matches = {entity: 'void' for entity in query_entities}
dimension_matches = extract_dimensions_pattern(text)
if dimension_matches:
for entity in query_entities:
if entity in dimension_matches:
entity_matches[entity] = dimension_matches[entity]
for entity, keywords in entity_keywords.items():
if entity in query_entities and entity_matches[entity] == 'void':
for keyword in keywords:
if keyword.lower() in text.lower():
entity_matches[entity] = extract_numerical_values(text, entity)
for entity in query_entities:
if entity_matches[entity] == 'void':
unit_matches = extract_numerical_values(text, entity)
if unit_matches != 'void':
entity_matches[entity] = unit_matches
return entity_matches
def ocr_extract_entities(image_data, query_entities):
try:
img = Image.open(BytesIO(image_data))
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
img = preprocess_image(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)
rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (18, 18))
dilation = cv2.dilate(thresh1, rect_kernel, iterations=1)
contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
extracted_text = ""
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
cropped = img[y:y + h, x:x + w]
# Optimize OCR configuration
custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789.,cmftinmlyozkgsVW'
text = pytesseract.image_to_string(cropped, config=custom_config)
extracted_text += text + "\n"
extracted_entities = extract_entity_values(extracted_text, query_entities)
return extracted_entities
except Exception:
return {entity: 'void' for entity in query_entities}
def process_row(row):
image_link = row['image_link']
entity_name = row['entity_name']
query_entities = [entity_name]
try:
response = requests.get(image_link, timeout=10)
if response.status_code == 200:
image_data = response.content
extracted_entities = ocr_extract_entities(image_data, query_entities)
entity_value = extracted_entities.get(entity_name, 'void')
# Check if entity_value is a list or float
if entity_value != 'void' and entity_value != []:
if isinstance(entity_value, list):
numerical_value = f"{entity_value[0][0]:,.2f}"
unit = entity_value[0][1].lower()
prediction = f"{numerical_value} {unit}"
elif isinstance(entity_value, float) or isinstance(entity_value, int):
prediction = f"{entity_value:,.2f}"
else:
prediction = ''
else:
prediction = ''
else:
prediction = ''
except Exception:
prediction = ''
return {'index': row.name, 'prediction': prediction}
def main():
input_file = '/Users/kartik/Downloads/student_resource 3/test2.csv'
output_file = 'output12345.csv'
df = pd.read_csv(input_file)
results = []
# Determine the number of workers based on CPU cores
num_workers = multiprocessing.cpu_count()
with ProcessPoolExecutor(max_workers=num_workers) as executor:
# Submit all tasks
futures = {executor.submit(process_row, row): row for _, row in df.iterrows()}
# Use tqdm for progress bar
for future in tqdm.tqdm(as_completed(futures), total=df.shape[0]):
result = future.result()
results.append(result)
# Convert results to DataFrame and save
output_df = pd.DataFrame(results)
output_df.to_csv(output_file, index=False)
if __name__ == "__main__":
main()
Expected Performance Improvement
By leveraging all available CPU cores on your M1 Mac (which typically has 8 cores), this parallelization can theoretically reduce the processing time by a factor of up to 8, substantially bringing down the total time from 16 hours to approximately 2 hours. Additional optimizations like efficient OCR configurations and image preprocessing can further reduce this time, potentially achieving your target of 20-30 minutes, depending on the exact nature of the data and system constraints.
Additional Considerations
- Memory Usage: Processing many images in parallel can consume significant memory. Monitor your system’s memory usage and adjust the number of workers (
max_workers) if necessary.
- Network Bandwidth: Ensure that your internet connection can handle multiple simultaneous image downloads without throttling.
- Error Logging: Implement logging to capture and analyze any errors that occur during processing. This is crucial for debugging and ensuring data integrity.
- Resource Limits: Be mindful of external resource limits, like API rate limits or server bandwidth caps, which may affect large-scale parallel downloads.
By methodically applying these optimizations, you should achieve a substantial reduction in processing time, making the pipeline much more efficient and scalable.