A very specific and interesting request!
Here's a Python script that uses the Hugging Face Transformers library to load the microsoft/table-transformer-detection model and extract table data from Farsi (Persian) images. The script will also save the extracted data in JSON format.
Prerequisites:
- Install the required libraries:
pip install transformers torch torchvision Pillow
- Make sure you have a Persian image containing a table (e.g.,
table_image.jpg). You can replace table_image.jpg with your own image file.
Script:
import os
import json
from PIL import Image
import torch
from transformers import TableTransformerForObjectDetection, TableTransformerProcessor
from torchvision import transforms
# Set the device (GPU or CPU)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Load the pre-trained model and processor
model_name = "microsoft/table-transformer-detection"
model = TableTransformerForObjectDetection.from_pretrained(model_name)
processor = TableTransformerProcessor.from_pretrained(model_name)
# Move the model to the device (GPU or CPU)
model.to(device)
# Load the Persian image
image_path = "table_image.jpg" # replace with your image file
image = Image.open(image_path)
# Preprocess the image
inputs = processor(images=image, return_tensors="pt").to(device)
# Forward pass
outputs = model(**inputs)
# Use the `torchvision` library to post-process the outputs
target_sizes = torch.tensor([[image.height, image.width]])
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes)[0]
# Extract the detected tables and cells
tables = []
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
if score > 0.9: # adjust the confidence threshold as needed
box = [round(i, 2) for i in box.tolist()]
if label == "table":
tables.append({"box": box, "cells": []})
elif label == "table cell":
# Associate the cell with the corresponding table
for table in tables:
if (box[0] > table["box"][0] and box[1] > table["box"][1] and
box[2] < table["box"][2] and box[3] < table["box"][3]):
table["cells"].append(box)
# Extract text from cells using OCR (optional, requires `pytesseract` library)
# import pytesseract
# for table in tables:
# for i, cell in enumerate(table["cells"]):
# cell_image = image.crop(cell)
# text = pytesseract.image_to_string(cell_image, lang="fas") # Farsi language code
# table["cells"][i] = {"box": cell, "text": text.strip()}
# Create a JSON-friendly data structure
data = []
for table in tables:
table_data = []
cells = table["cells"]
num_rows = max(int((cell[3] - table["box"][1]) / (table["box"][3] - table["box"][1]) * 10) for cell in cells) + 1
num_cols = max(int((cell[2] - table["box"][0]) / (table["box"][2] - table["box"][0]) * 10) for cell in cells) + 1
grid = [[None for _ in range(num_cols)] for _ in range(num_rows)]
for cell in cells:
row_idx = int((cell[3] - table["box"][1]) / (table["box"][3] - table["box"][1]) * num_rows)
col_idx = int((cell[2] - table["box"][0]) / (table["box"][2] - table["box"][0]) * num_cols)
grid[row_idx][col_idx] = {"box": cell} # , "text": cell.get("text", "")}
# Simplify the grid structure
for row in grid:
table_data.append([cell["box"] if cell else None for cell in row])
data.append({"table": table_data})
# Save the extracted data in JSON format
output_path = "extracted_table_data.json"
with open(output_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=4)
print(f"Extracted table data saved to: {output_path}")
Here's what the script does:
- Loads the
microsoft/table-transformer-detection model and processor.
- Preprocesses the input image using the processor.
- Performs object detection (tables and cells) using the model.
- Post-processes the outputs to get the detected tables and cells with their bounding boxes.
- Associates cells with their corresponding tables.
- Optionally, you can uncomment the OCR section to extract text from cells using
pytesseract. You'll need to install pytesseract and have Tesseract OCR installed on your system.
- Creates a JSON-friendly data structure representing the extracted table data.
- Saves the extracted data in JSON format.
The resulting JSON file (extracted_table_data.json) will contain a list of tables, where each table is represented as a 2D grid of cells. Each cell contains its bounding box coordinates (box key). If you enabled OCR, each cell will also have a text key with the extracted text.
Example output (simplified):
[
{
"table": [
[
{"box": [10, 10, 50, 30]},
{"box": [60, 10, 100, 30]},
null
],
[
{"box": [10, 40, 50, 60]},
{"box": [60, 40, 100, 60]},
{"box": [110, 40, 150, 60]}
]
]
}
]
This indicates a single table with 2 rows and 3 columns. The first row has two cells, and the second row has three cells. Each cell has its bounding box coordinates.
Notes:
- Adjust the
score threshold (currently 0.9) to filter out low-confidence detections.
- If you encounter issues with the model not detecting tables or cells correctly, try resizing the input image or experimenting with different pre-processing techniques.
- For better OCR accuracy, consider pre-processing the cell images (e.g., binarization, deskewing) before passing them to
pytesseract.
I hope this script helps you extract Farsi table data successfully!