I have a code understand the code and
Write the a new function in code to draw to bounding box for those entities who are spreading across multiple lines these entities are basically address_details entities
import cv2
import pandas as pd
import json
from thefuzz import fuzz
from itertools import product
used_bounding_boxes = {}
def merge_boxes(boxes):
min_left = min(box["left"] for box in boxes)
max_right = max(box["right"] for box in boxes)
min_top = min(box["top"] for box in boxes)
max_bottom = max(box["bottom"] for box in boxes)
return {"left": min_left, "right": max_right, "top": min_top, "bottom": max_bottom}
This condition won't be true in case of address_details because it can have upto 50 tokens and each token can't satisfy this condition so modify this approach if not all(matches for matches in all_potential_matches):
return None
Assistant
User
modify main function as well according to the updated code
Assistant
code
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
for _, row in dataframe.iterrows():
ocr_text = preprocess_entity(row['text'])
score = fuzz.ratio(entity, ocr_text)
current_box = {'left': row['left'], 'right': row['right'], 'top': row['top'], 'bottom': row['bottom']}
if score > best_score and current_box not in used_bounding_boxes[entity]:
best_score = score
best_match = current_box
if best_match:
used_bounding_boxes[entity].append(best_match)
return best_match
boxes_to_merge = [match['box'] for match in best_sequence]
merged_box = merge_boxes(boxes_to_merge)
used_bounding_boxes[entity].append(merged_box)
return merged_box
return None
def box_overlap(box1, box2):
"""Check if there’s any overlap in any coordinate between two boxes."""
return box1["left"] == box2["left"] or box1["right"] == box2["right"]
def all_boxes_unique(sequence_boxes, used_boxes):
"""Ensure no part of the boxes in sequence_boxes overlaps with any box in used_boxes."""
for seq_box in sequence_boxes:
for used_box in used_boxes:
if box_overlap(seq_box, used_box):
return False
return True
def get_next_best_sequence(all_potential_matches, previous_matches, entity):
"""
Try to find the next best sequence of matches that hasn’t used any part of the bounding boxes.
"""
# Flatten the list of used boxes for easier comparison.
used_boxes = [box for sequence in previous_matches.get(entity, []) for box in sequence]
code
for sequence in product(*all_potential_matches):
sequence_boxes = [match["box"] for match in sequence]
if all_boxes_unique(sequence_boxes, used_boxes):
return sequence # Found a sequence where no box part has been used before
return None # No unique sequence found
def process_multi_token_entity(dataframe, entity, threshold=85):
global used_bounding_boxes
code
# if entity not in used_bounding_boxes:
# used_bounding_boxes[entity] = []
tokens = entity.split()
all_potential_matches = [find_potential_matches(dataframe, token, threshold) for token in tokens]
# Ensuring all tokens have at least one match
if not all(matches for matches in all_potential_matches):
return None
# This assumes used_bounding_boxes[entity] holds lists of used sequences of boxes (not merged boxes)
previous_matches = used_bounding_boxes.get(entity, [])
next_best_sequence = get_next_best_sequence(all_potential_matches, used_bounding_boxes, entity)
if next_best_sequence:
new_boxes_sequence = [match["box"] for match in next_best_sequence]
merged_box = merge_boxes(new_boxes_sequence)
# If we found a new sequence, add it to the used sequences for this entity
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
used_bounding_boxes[entity].append(new_boxes_sequence)
return merged_box
return None
def draw_bounding_boxes(image_path, bounding_boxes, entity_names):
image = cv2.imread(image_path)
font = cv2.FONT_HERSHEY_SIMPLEX
for box, name in zip(bounding_boxes, entity_names):
if box:
cv2.rectangle(image, (box["left"], box["top"]), (box["right"], box["bottom"]), (0, 255, 0), 2)
cv2.putText(image, name, (box["left"], max(box["top"] - 10, 0)), font, 0.5, (0, 0, 255), 2)
cv2.imwrite("annotated_image_using_dp1119.jpg", image)
def main(json_path, csv_path, image_path):
with open(json_path, "r") as f:
data = json.load(f)
dataframe = pd.read_csv(csv_path)
bounding_boxes = []
entity_names = []
code
# Existing processing for non-special sections
special_sections = ["amounts_and_tax","Payment Details"] # Define special handling cases here
for section in ["invoice_details", "Payment Details", "amounts_and_tax"]:
entities = data.get(section, {})
# Check if the current section needs special handling
if section not in special_sections:
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
box = process_multi_token_entity(dataframe, entity_value_no_comma)
else:
box = process_single_token_entity(dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
else:
# Special handling for "amounts_and_tax" section
reversed_dataframe = dataframe.iloc[::-1].reset_index(drop=True) # Reverse the dataframe
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
# Use the reversed_dataframe for multi-token entities
box = process_multi_token_entity(reversed_dataframe, entity_value_no_comma)
else:
# Use the reversed_dataframe for single-token entities
box = process_single_token_entity(reversed_dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
draw_bounding_boxes(image_path, bounding_boxes, entity_names)
To draw bounding boxes specifically for entities that spread across multiple lines, we can add a new function that focuses on address_details entities. Since you already have functions in place for processing single and multi-token entities, I'll demonstrate the addition of a bespoke function to target multi-line address_details.
First, ensure to mark the address_details in your input JSON file (or however you are feeding the entity details) to signify that specific handling is needed for them.
Next, we will create a function tailored for identifying and processing address_details. This function could operate similarly to process_multi_token_entity but with more relaxed criteria for merging bounding boxes to accommodate the likelihood of addresses spreading over multiple lines.
Below is a new function called process_address_details that leans on existing infrastructure with some tweaks. This function assumes address_details might span multiple lines and might have more lenient distance criteria:
python
def process_address_details(dataframe, entity, threshold=75):
global used_bounding_boxes
tokens = entity.split()
all_potential_matches = []
for token in tokens:
potential_matches = find_potential_matches(dataframe, token, threshold)
all_potential_matches.append(potential_matches)
if not all(matches for matches in all_potential_matches):
return None
next_best_sequence = get_next_best_sequence(all_potential_matches, used_bounding_boxes, entity, max_line_difference=2, max_distance=50)
if next_best_sequence:
new_boxes_sequence = [match["box"] for match in next_best_sequence]
merged_box = merge_boxes(new_boxes_sequence)
# Save the used boxes for this entity to avoid reprocessing
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
used_bounding_boxes[entity].append(new_boxes_sequence)
return merged_box
return None
In this process_address_details version, you might want to adjust the max_line_difference and max_distance parameters in the get_next_best_sequence call (which doesn't exist yet in your provided code, so you'll need to modify that function to accept and handle these parameters). The idea is to make these parameters more forgiving for address details, where entities can be spread across multiple lines but still part of the same address.
You would then hook this new function into your data processing flow, likely identifying address_details entities separately from the standard single-token or multi-token entities. The separation logic entirely depends on how your entities are structured. Assuming address_details is a known key, you could perform a check when iterating through entities:
python
if entity_name == "address_details":
box = process_address_details(dataframe, entity_value_no_comma)
else: # Existing conditions for single or multi-token entities
# Your existing handling logic...
Don't forget to adjust the parameters and logic inside process_address_details to better fit your data and requirements, especially regarding how you determine whether bounding boxes should be merged based on proximity and alignment. Also, ensure you've hooked up the modified or additional get_next_best_sequence with your custom logic to accommodate address-specific handling.
Remember, successful implementation will hinge on finely tuning the combination of distance, score thresholds, and handling overlapping or adjacent bounding boxes especially for the nuances of address details that can significantly vary in format and layout.
Understanding your requirements clearer now, it seems we need an approach that accommodates the possibility of not all tokens in address_details being successfully matched, which is quite common given the nature of OCR data and addresses.
To handle cases where not all tokens find a match due to OCR errors, illegibility, or the inherent variability in addresses, you can modify the approach to collate potential matches for each token and proceed with grouping and merging what matches you do find. This requires a more forgiving strategy that attempts to stitch together the most promising sequence of bounding boxes without insisting on a match for every single token.
Here's how you might adjust the process_address_details function:
python
def process_address_details(dataframe, entity, threshold=75):
global used_bounding_boxes
tokens = entity.split()
# Collect only the non-empty lists of matches
all_potential_matches = [find_potential_matches(dataframe, token, threshold) for token in tokens]
non_empty_matches = [matches for matches in all_potential_matches if matches]
if not non_empty_matches:
return None
# Attempt to form a coherent sequence of matches considering only non-empty match sets
# and focusing more on proximity and less on complete coverage of all tokens
merged_boxes = []
for matches in non_empty_matches:
for match in matches:
# If there's already a merged box, check if this box is nearby to it
if merged_boxes and is_nearby(merged_boxes[-1], match["box"], max_line_difference=3, max_distance=50):
merged_boxes.append(match["box"])
elif not merged_boxes: # If merged_boxes is still empty, start it with this match
merged_boxes.append(match["box"])
if merged_boxes:
merged_box = merge_boxes(merged_boxes)
# Update used_bounding_boxes if necessary
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
used_bounding_boxes[entity].append(merged_box)
return merged_box
return None
Adjustments made in this version:
Relaxed Requirement for All Matches: Instead of requiring a match for every token, it collates potential matches and works with what is found, which is critical for handling lengthy entities like addresses.
Proximity-Based Merging: Instead of forcing a sequence, it looks to merge boxes that are nearby. This might result in merging fewer boxes than there are tokens, but it should handle multiline addresses more gracefully by focusing on spatial proximity.
Parameters Tuning: Adjust is_nearby parameters (max_line_difference, max_distance) accordingly to be more forgiving for address details that can span wide areas and multiple lines.
Lastly, integrate this function similar to before, identifying when you're dealing with address_details and utilizing this function to process those particulars.
This is a complex and heuristic-driven approach, so I recommend extensive testing with your actual OCR data to fine-tune the parameters and logic for best results. Also, consider edge cases such as very fragmented addresses or incorrect OCR reads that could influence the effectiveness of the bounding box merging.
Given the updated approach and changes in handling for address_details, let's update the main function to process address_details entities using our new process_address_details strategy. We'll assume address_details are marked distinctly in the input data so that they can be processed with the consideration they require.
Here's how the modified main function could look, with adjustments to handle address_details separately from other entities:
python
def main(json_path, csv_path, image_path):
with open(json_path, "r") as f:
data = json.load(f)
dataframe = pd.read_csv(csv_path)
bounding_boxes = []
entity_names = []
# Assume "address_details" require special handling; add or modify as per your use case
special_sections = ["amounts_and_tax", "Payment Details"]
address_section = "address_details" # Defining the specific section for address details
for section in data.keys(): # Improved to iterate over keys from loaded JSON data
entities = data.get(section, {})
if section == address_section:
# Special handling for "address_details"
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
# Using updated process_address_details function
box = process_address_details(dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
elif section in special_sections:
# Existing special section handling logic
reversed_dataframe = dataframe.iloc[::-1].reset_index(drop=True)
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
box = process_multi_token_entity(reversed_dataframe, entity_value_no_comma)
else:
box = process_single_token_entity(reversed_dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
else:
# Handling non-special sections
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
box = process_multi_token_entity(dataframe, entity_value_no_comma)
else:
box = process_single_token_entity(dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
draw_bounding_boxes(image_path, bounding_boxes, entity_names)
# Example usage
#main("/path/to/row_skip.json", "/path/to/check.csv", "/path/to/check.jpeg")
This version of the main function adds checks to distinguish address_details from other entity types or sections, applying process_address_details specifically for addresses. This allows us to use our custom logic designed to accommodate the peculiarities of address data, such as potential multi-line formatting and partial OCR matches.
Couple of notes:
Ensure your address_details entities are appropriately flagged or arranged in your input data (json_path). The specific handling logic is contingent on recognizing these entities correctly.
Validate and adjust the proximity and threshold parameters for process_address_details based on real OCR data and the observed distribution of addresses in your documents. This might require iterative testing to get right.
If there are other entities or sections requiring special handling beyond address_details, consider extending or further customizing the logic within the main function or adding new processing functions as needed.