Analyse this code and Improve it with best of your knowlegde
I want only nearest words in multi token entities. Calculate the distance before creating bounding boxes.
import json
import pandas as pd
import cv2
from thefuzz import fuzz
from thefuzz import process
import numpy as np
def read_textract_output(csv_path):
return pd.read_csv(csv_path)
def read_json_entities(json_path):
with open(json_path, "r") as file:
return json.load(file)
def calculate_bounding_boxes(cluster, scale_x, scale_y):
min_left = np.min([bbox[0] for bbox in cluster])
min_top = np.min([bbox[1] for bbox in cluster])
max_right = np.max([bbox[0] + bbox[2] for bbox in cluster])
max_bottom = np.max([bbox[1] + bbox[3] for bbox in cluster])
bbox = (min_left * scale_x, min_top * scale_y, (max_right - min_left) * scale_x, (max_bottom - min_top) * scale_y)
return bbox
def find_entity_bounding_boxes(entity_text, textract_df, image_size, proximity_threshold=90):
entity_tokens = entity_text.split()
bounding_boxes = []
for token in entity_tokens:
choices = textract_df["text"].dropna().tolist()
best_match = process.extractOne(token, choices, scorer=fuzz.token_sort_ratio)
if best_match and best_match[1] > 95:
best_matches_df = textract_df[textract_df["text"] == best_match[0]]
bounding_boxes.extend([(row["left"], row["top"], row["width"], row["height"]) for _, row in best_matches_df.iterrows()])
clustered_boxes = []
for bbox in bounding_boxes:
if not clustered_boxes:
clustered_boxes.append([bbox])
else:
clustered = False
for cluster in clustered_boxes:
cluster_x, cluster_y, _, _ = calculate_bounding_boxes(cluster, 1, 1)
if abs(bbox[0] - cluster_x) <= proximity_threshold and abs(bbox[1] - cluster_y) <= proximity_threshold:
cluster.append(bbox)
clustered = True
break
if not clustered:
clustered_boxes.append([bbox])
final_boxes = []
for cluster in clustered_boxes:
scale_x = image_size[0] / cluster[0][2] if cluster[0][2] != 0 else 1
scale_y = image_size[1] / cluster[0][3] if cluster[0][3] != 0 else 1
final_boxes.append(calculate_bounding_boxes(cluster, scale_x, scale_y))
return final_boxes
def draw_bounding_boxes(image_path, entities, textract_df):
image = cv2.imread(image_path)
image_size = image.shape[1], image.shape[0]
for category, details in entities.items():
if category in {"invoice_details", "Payment Details", "amounts_and_tax"}:
for entity, value in details.items():
if value:
bounding_boxes = find_entity_bounding_boxes(value, textract_df, image_size)
for bbox in bounding_boxes:
x, y, w, h = map(int, bbox)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imwrite("/home/ritik1s/Desktop/bbox_issues/temp_GPT/annotated_invoice.jpg", image)
IMAGE_PATH = "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg"
CSV_PATH = "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv"
JSON_PATH = "/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json"
textract_df = read_textract_output(CSV_PATH)
entities = read_json_entities(JSON_PATH)
draw_bounding_boxes(IMAGE_PATH, entities, textract_df)