Okay, here is a Python script that uses the Hugging Face microsoft/table-transformer-detection model to detect tables and cells, and then uses EasyOCR (which supports Farsi) to extract text from each detected cell. The results are structured into a JSON format.
Prerequisites:
-
Install necessary libraries:
pip install transformers torch Pillow easyocr numpy
transformers: For loading and using the Table Transformer model.
torch: PyTorch, the deep learning framework required by transformers and easyocr.
Pillow: For image manipulation (loading, cropping).
easyocr: For performing OCR, specifically supporting Farsi ('fa').
numpy: Used internally by Pillow and EasyOCR.
-
Have a Farsi table image: Replace "your_farsi_table_image.png" in the script with the actual path to your image file.
The Script:
import torch
from transformers import AutoModelForObjectDetection, AutoFeatureExtractor
from PIL import Image, ImageDraw
import easyocr
import json
import numpy as np
import os
# --- Configuration ---
TABLE_TRANSFORMER_MODEL = "microsoft/table-transformer-detection"
OCR_LANGUAGES = ['fa', 'en'] # 'fa' for Farsi, 'en' is optional but often helpful
DETECTION_THRESHOLD = 0.9 # Confidence threshold for object detection (tables and cells)
# --- Load Models ---
# Load Table Transformer model and feature extractor
try:
print(f"Loading Table Transformer model: {TABLE_TRANSFORMER_MODEL}...")
feature_extractor = AutoFeatureExtractor.from_pretrained(TABLE_TRANSFORMER_MODEL)
model = AutoModelForObjectDetection.from_pretrained(TABLE_TRANSFORMER_MODEL)
print("Table Transformer model loaded successfully.")
except Exception as e:
print(f"Error loading Table Transformer model: {e}")
print("Please ensure you have an active internet connection or the model is cached.")
exit()
# Initialize EasyOCR reader
try:
print(f"Initializing EasyOCR reader for languages: {', '.join(OCR_LANGUAGES)}...")
# EasyOCR might download language models on first run
reader = easyocr.Reader(OCR_LANGUAGES, gpu=torch.cuda.is_available()) # Use GPU if available
print("EasyOCR reader initialized successfully.")
except Exception as e:
print(f"Error initializing EasyOCR: {e}")
print("Please ensure EasyOCR can download language models (requires internet on first run).")
exit()
# --- Helper Function: Get Table and Cell Boxes ---
def get_table_and_cell_boxes(image_path):
"""
Detects tables and cells in an image using Table Transformer.
Returns the main table bbox and a list of detected cell bboxes.
"""
try:
image = Image.open(image_path).convert("RGB")
except FileNotFoundError:
print(f"Error: Image file not found at {image_path}")
return None, [], None
except Exception as e:
print(f"Error opening image {image_path}: {e}")
return None, [], None
# Prepare image for model
# Table Transformer expects inputs prepared by its feature extractor
inputs = feature_extractor(images=image, return_tensors="pt")
# Perform inference
with torch.no_grad():
outputs = model(**inputs)
# Post-process outputs to get actual bounding boxes
# The `post_process_object_detection` method handles scaling boxes to original image size
target_sizes = torch.tensor([image.size[::-1]]) # (height, width)
results = feature_extractor.post_process_object_detection(
outputs, threshold=DETECTION_THRESHOLD, target_sizes=target_sizes
)[0] # Get results for the first image
table_boxes = []
cell_boxes = []
# Map predicted class IDs to labels (should be 'table' and 'cell')
# model.config.id2label typically maps 0 to 'table', 1 to 'cell'
id_to_label = model.config.id2label
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
box = [round(i, 2) for i in box.tolist()] # Convert tensor box to list of floats
predicted_label = id_to_label[label.item()]
if predicted_label == 'table':
table_boxes.append({"box": box, "score": round(score.item(), 4)})
elif predicted_label == 'cell':
cell_boxes.append({"box": box, "score": round(score.item(), 4)})
# Optional: Find the main table box (e.g., the largest or the one with highest score)
# and potentially filter cells that fall within it.
# For simplicity, let's just find the table box with the highest score if multiple are detected.
main_table_box = None
if table_boxes:
# Sort by score descending and pick the top one
main_table_box = sorted(table_boxes, key=lambda x: x['score'], reverse=True)[0]['box']
print(f"Detected main table bbox: {main_table_box}")
# Filter cell boxes to only include those likely within the main table box
# This is a heuristic and might need tuning based on images
x1_t, y1_t, x2_t, y2_t = main_table_box
filtered_cell_boxes = []
for cell_info in cell_boxes:
x1_c, y1_c, x2_c, y2_c = cell_info['box']
# Check if cell's center is within the table box
cell_center_x = (x1_c + x2_c) / 2
cell_center_y = (y1_c + y1_c) / 2 # Should be (y1_c + y2_c) / 2
cell_center_y = (y1_c + y2_c) / 2 # Corrected line
if x1_t <= cell_center_x <= x2_t and y1_t <= cell_center_y <= y2_t:
filtered_cell_boxes.append(cell_info['box']) # Keep just the box list
cell_boxes = filtered_cell_boxes # Use the filtered list of just boxes
print(f"Filtered {len(cell_boxes)} cell boxes within the main table.")
else:
# If no table box is detected, return all detected cell boxes (just the box list)
cell_boxes = [cell_info['box'] for cell_info in cell_boxes]
print(f"No table box detected. Returning all {len(cell_boxes)} detected cell boxes.")
return main_table_box, cell_boxes, image
# --- Helper Function: Extract Text from Cells ---
def extract_text_from_cells(image, cell_boxes, reader):
"""
Crops image regions based on cell bboxes and performs OCR using EasyOCR.
Returns a list of dictionaries, each containing cell bbox and extracted text.
"""
extracted_data = []
print(f"Performing OCR on {len(cell_boxes)} detected cells...")
for i, bbox in enumerate(cell_boxes):
# Ensure bbox coordinates are integers for image cropping
# Add a small padding (e.g., 2 pixels) to avoid cutting off text at edges, optional
padding = 2
bbox_int = [
max(0, int(round(bbox[0]) - padding)), # x_min
max(0, int(round(bbox[1]) - padding)), # y_min
min(image.width, int(round(bbox[2]) + padding)), # x_max
min(image.height, int(round(bbox[3]) + padding)) # y_max
]
try:
# Crop image to cell bounding box
cropped_img = image.crop(bbox_int)
# Convert to numpy array for EasyOCR
cropped_img_np = np.array(cropped_img)
# Perform OCR on the cropped image
# EasyOCR returns a list of (bbox_in_cropped_img, text, prob)
results = reader.readtext(cropped_img_np, detail=0) # detail=0 returns only text
# Concatenate text from potentially multiple lines/segments detected by OCR within the cell
# For RTL languages like Farsi, simply joining with space works for reading order
cell_text = " ".join(results).strip()
# Optional: Add original bbox, extracted text, and perhaps OCR confidence
extracted_data.append({
"bbox": bbox, # Use the original float bbox from Table Transformer
"text": cell_text,
# "ocr_results": results # If you want detailed OCR output
})
# print(f" Cell {i+1}: Bbox={bbox}, Text='{cell_text}'") # Uncomment for verbose output
except Exception as e:
print(f"Error processing cell {i+1} with bbox {bbox}: {e}")
extracted_data.append({
"bbox": bbox,
"text": "[OCR Error]"
})
return extracted_data
# --- Main Processing Function ---
def process_image_for_tables(image_path, output_json_path=None):
"""
Processes an image to detect tables/cells and extract cell text, then saves to JSON.
"""
print(f"\n--- Starting processing for {image_path} ---")
# Step 1: Detect table and cell bounding boxes
main_table_box, cell_boxes, image = get_table_and_cell_boxes(image_path)
if image is None:
print("Image could not be processed. Exiting.")
return None
print(f"Total cells detected by Table Transformer: {len(cell_boxes)}")
# Step 2: Extract text from detected cells using OCR
if not cell_boxes:
print("No cells found to extract text from.")
extracted_data = []
else:
extracted_data = extract_text_from_cells(image, cell_boxes, reader)
print(f"Successfully extracted text from {len(extracted_data)} cells.")
# Step 3: Structure the output data into JSON format
output_data = {
"image_path": image_path,
"detected_table_bbox": main_table_box, # This is the main table box if detected
"cells": extracted_data
}
# Step 4: Save or print the JSON output
if output_json_path:
try:
with open(output_json_path, 'w', encoding='utf-8') as f:
# Use ensure_ascii=False to correctly handle Farsi characters
json.dump(output_data, f, ensure_ascii=False, indent=4)
print(f"\nResults saved to: {output_json_path}")
except Exception as e:
print(f"Error saving JSON to {output_json_path}: {e}")
# Fallback to printing if saving fails
print("\n--- Failed to save, printing JSON output ---")
print(json.dumps(output_data, ensure_ascii=False, indent=4))
print("--------------------------------------------")
else:
print("\n--- Extracted Data (JSON Output) ---")
print(json.dumps(output_data, ensure_ascii=False, indent=4))
print("------------------------------------")
print(f"--- Finished processing for {image_path} ---")
return output_data
# --- Example Usage ---
if __name__ == "__main__":
# --- IMPORTANT: Replace with the path to your Farsi table image ---
sample_image_path = "your_farsi_table_image.png"
# --- IMPORTANT: Replace with desired output JSON path (or set to None to print) ---
output_json_file = "farsi_table_data.json"
# output_json_file = None # Uncomment this line to print JSON to console instead of saving
# --- Run the process ---
if not os.path.exists(sample_image_path):
print(f"\nERROR: Image file not found at '{sample_image_path}'")
print("Please replace 'your_farsi_table_image.png' with the actual path to your image.")
else:
process_image_for_tables(sample_image_path, output_json_file)
# --- Optional: Add visualization (requires matplotlib) ---
# import matplotlib.pyplot as plt
#
# def visualize_results(image_path, data):
# """Visualizes detected table and cell bounding boxes on the image."""
# try:
# img = Image.open(image_path).convert("RGB")
# draw = ImageDraw.Draw(img)
#
# # Draw table box (if detected)
# table_bbox = data.get("detected_table_bbox")
# if table_bbox:
# draw.rectangle(table_bbox, outline="red", width=3)
# # Optional: Add label
# # draw.text((table_bbox[0], table_bbox[1]-10), "Table", fill="red")
#
# # Draw cell boxes
# cells = data.get("cells", [])
# for cell in cells:
# bbox = cell.get("bbox")
# if bbox:
# draw.rectangle(bbox, outline="blue", width=1)
# # Optional: Add text label near the box (might be tricky with RTL)
# # try:
# # # Requires Arabic/Farsi font support and potentially python-bidi
# # from bidi.algorithm import get_display
# # import arabic_reshaper
# # reshaped_text = arabic_reshaper.reshape(cell['text'])
# # bidi_text = get_display(reshaped_text)
# # # Need to load a font that supports Farsi
# # # from PIL import ImageFont
# # # font = ImageFont.truetype("arial.ttf", 15) # Replace with a suitable font path
# # # draw.text((bbox[0], bbox[1]), bidi_text, fill="blue", font=font)
# # except ImportError:
# # print("Install python-bidi and arabic-reshaper for text visualization (optional).")
# # pass # Skip text drawing
# # except Exception as e:
# # print(f"Error drawing text: {e}") # Handle potential font/drawing issues
#
# plt.figure(figsize=(15, 15))
# plt.imshow(img)
# plt.title("Detected Tables (Red) and Cells (Blue)")
# plt.axis('off')
# plt.show()
# except FileNotFoundError:
# print(f"Error: Image file not found for visualization at {image_path}")
# except Exception as e:
# print(f"Error during visualization: {e}")
#
# # Example of how to use visualization after processing
# # Make sure you processed the image and have the results dictionary
# # If you saved to a file, you might need to load it back:
# # if os.path.exists(sample_image_path) and os.path.exists(output_json_file):
# # with open(output_json_file, 'r', encoding='utf-8') as f:
# # results_data = json.load(f)
# # visualize_results(sample_image_path, results_data)
Explanation:
- Import Libraries: Imports
torch, transformers components, Pillow for image handling, easyocr for OCR, json for output, and numpy.
- Configuration: Sets the Table Transformer model name, the languages for EasyOCR (
'fa' for Farsi), and a confidence threshold for detection.
- Load Models: Loads the
AutoModelForObjectDetection and its corresponding AutoFeatureExtractor for the Table Transformer model. It also initializes the EasyOCR.Reader with the specified languages. It tries to use the GPU if available.
get_table_and_cell_boxes Function:
- Opens the image and converts it to RGB.
- Uses the
feature_extractor to prepare the image tensor for the model.
- Passes the input through the
model to get the raw outputs.
- Uses
feature_extractor.post_process_object_detection to convert raw outputs into human-readable bounding boxes ([x_min, y_min, x_max, y_max]), scores, and labels, scaled to the original image size.
- Filters these results based on the
DETECTION_THRESHOLD and label ('table' or 'cell').
- Optionally identifies the main table box (here, the one with the highest score) and filters cell boxes to include only those geometrically likely inside the main table.
- Returns the main table bbox, a list of cell bboxes, and the loaded
PIL.Image object.
extract_text_from_cells Function:
- Takes the
PIL.Image and the list of cell bboxes.
- Iterates through each
bbox.
- Crops the image to the region defined by the
bbox using image.crop(). A small padding is added to potentially improve OCR results.
- Converts the cropped image to a NumPy array, which
EasyOCR requires.
- Calls
reader.readtext() on the cropped image. detail=0 makes it return only the text strings.
- Joins multiple text segments found within a single cell (if any) into a single string.
- Appends a dictionary containing the original
bbox and the text to a results list.
- Returns the list of extracted cell data.
-
How to Run:
- Save the code as a Python file (e.g.,
table_extractor.py).
- Place your Farsi table image in a location accessible by the script.
- Edit the script:
- Change
sample_image_path = "your_farsi_table_image.png" to the correct path.
- Optionally, change
output_json_file.
- Open your terminal or command prompt.
- Navigate to the directory where you saved the script.
- Run the script:
python table_extractor.py
The script will print progress messages and either save the extracted data to the specified JSON file or print it directly to your console.