Handling multi-token entities that span across different OCR lines or blocks is indeed more challenging. This requires a more robust approach for matching sequences. We need to consider cases where an entity might be split across lines or blocks and use a search algorithm that can consolidate these fragments.
For this purpose, let's implement an improved draw_boxes function that uses a sequence search approach to match tokens and accounts for potential mismatches and OCR errors. Also, we'll use the fuzzywuzzy library for fuzzy string matching which can help match entities even if there are slight OCR errors.
First, install the required package:
pip install fuzzywuzzy python-Levenshtein
Now, we update our script to search for multi-token entities more robustly:
import json
import cv2
import pandas as pd
from fuzzywuzzy import fuzz
# Load your JSON, CSV, and image here...
def flexible_match(query, source, threshold=80):
"""
Attempts to find the best match for a query string within a source string,
allowing for partial and fuzzy matches.
Args:
query (str): The query string we are trying to find.
source (str): The source string within which we are looking for the query.
threshold (int, optional): The minimum matching score to consider a match.
Returns:
tuple: (is_matched, match_start_index, match_end_index)
"""
tokens = query.split()
if len(tokens) == 0: return (False, None, None)
for start_idx in range(len(tokens)):
for end_idx in range(len(tokens), start_idx, -1):
sub_query = ' '.join(tokens[start_idx:end_idx])
if fuzz.partial_ratio(sub_query.lower(), source.lower()) > threshold:
if start_idx == 0:
return (True, start_idx, end_idx)
else:
# Since we might not start with the first token, let's
# confirm that the previous token is not in the string.
prev_token = tokens[start_idx - 1]
if prev_token.lower() not in source.lower():
return (True, start_idx, end_idx)
return (False, None, None)
def draw_boxes(image, df, data):
for key, value in data.items():
if value: # Ensure the value is not empty
words = value.split()
first_word = words[0]
# We'll create large blocks of text by combining OCR lines within the same block
unique_blocks = df['block_num'].unique()
for block_num in unique_blocks:
block_lines = df[df['block_num'] == block_num]
full_block_text = ' '.join(block_lines['text'].tolist())
# Check flexible match
is_matched, start_idx, end_idx = flexible_match(value, full_block_text)
if is_matched:
relevant_lines = block_lines.iloc[start_idx:end_idx]
top_left = (relevant_lines['left'].min(), relevant_lines['top'].min())
bottom_right = (relevant_lines['right'].max(), relevant_lines['bottom'].max())
cv2.rectangle(image, top_left, bottom_right, (0, 255, 0), 2)
print(f"Box drawn for: {value}")
break # Stop looking within other blocks since we found a match
# Run the updated function
draw_boxes(image, df, flat_data)
# Save and display the image as before...
Here, we implement a function flexible_match which tries to find the best match for the query string within a source string by checking for partial and fuzzy matches, allowing the sequence of tokens to be in a different order or spread across different lines. We leverage the partial_ratio function from fuzzywuzzy to find matches with some tolerance for errors.
Keep in mind, even with this improved approach, there are still edge-cases that may not be perfectly handled. OCR errors, significant variations in token order, or heavily fragmented text might require custom handling or manual corrections. Moreover, tuning the threshold parameter is crucial to balance between false positives and false negatives in entity matching.