Views
No views yet
| Training Loss | Epoch | Step | Validation Loss | Precision | Recall | F1 | Accuracy |
|---|---|---|---|---|---|---|---|
| 0.7142 | 1.0 | 522 | 0.7296 | 0.6225 | 0.7066 | 0.6619 | 0.7212 |
| 0.5881 | 2.0 | 1044 | 0.6032 | 0.6841 | 0.8100 | 0.7417 | 0.7688 |
| 0.4179 | 3.0 | 1566 | 0.5904 | 0.7204 | 0.8222 | 0.7679 | 0.7858 |
| 0.3507 | 4.0 | 2088 | 0.6088 | 0.7600 | 0.8458 | 0.8006 | 0.7979 |
| 0.2618 | 5.0 | 2610 | 0.6625 | 0.7711 | 0.8476 | 0.8075 | 0.8030 |
1# Install the Python wrapper
2!pip install pytesseract pillow
3
4# Install the Tesseract engine on a Debian/Ubuntu-based system (like Colab)
5!sudo apt install tesseract-ocr1import torch
2from transformers import AutoProcessor, AutoModelForTokenClassification
3from PIL import Image, ImageDraw, ImageFont
4import pytesseract
5import numpy as np
6import os # For setting environment variable
7
8# --- CRITICAL FOR DEBUGGING: Set this at the very top ---
9os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
10
11# --- ADD THE NORMALIZATION FUNCTION ---
12def normalize_bbox(bbox, width, height):
13 return [
14 int(1000 * min(max(bbox[0] / width, 0), 1)),
15 int(1000 * min(max(bbox[1] / height, 0), 1)),
16 int(1000 * min(max(bbox[2] / width, 0), 1)),
17 int(1000 * min(max(bbox[3] / height, 0), 1))
18 ]1# --- 1. Load your Fine-Tuned Model and Processor ---
2MODEL_ID = "nnul/layoutlmv3-xfund"
3
4print("Loading processor...")
5processor = AutoProcessor.from_pretrained(MODEL_ID)
6print("Loading model...")
7model = AutoModelForTokenClassification.from_pretrained(MODEL_ID)
8
9print("Moving model to device...")
10device = "cuda" if torch.cuda.is_available() else "cpu"
11model.to(device)
12print("Model moved successfully.")1# --- 2. Load the Image ---
2image_path = "your_image.png"
3image = Image.open(image_path).convert("RGB")
4width, height = image.size1# --- 3. Perform OCR and NORMALIZE Bounding Boxes ---
2print("Performing OCR...")
3data = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)
4words = []
5unnormalized_boxes = []
6normalized_boxes = []
7
8for i in range(len(data['text'])):
9 if int(data['conf'][i]) > 30 and data['text'][i].strip() != '':
10 word = data['text'][i]
11 x, y, w, h = data['left'][i], data['top'][i], data['width'][i], data['height'][i]
12
13 actual_box = [x, y, x + w, y + h]
14 unnormalized_boxes.append(actual_box)
15
16 normalized_box = normalize_bbox(actual_box, width, height)
17 normalized_boxes.append(normalized_box)
18
19 words.append(word)
20
21print(f"OCR found {len(words)} words.")1# --- 4. Manually Preprocess and Predict ---
2print("Preprocessing inputs...")
3encoding = processor(
4 image,
5 words,
6 boxes=normalized_boxes,
7 return_tensors="pt",
8 truncation=True
9)
10
11print("Moving inputs to device...")
12for k, v in encoding.items():
13 encoding[k] = v.to(device)
14
15print("Running inference...")
16with torch.no_grad():
17 outputs = model(**encoding)
18
19logits = outputs.logits
20predictions_indices = logits.argmax(-1).squeeze().tolist()
21
22word_ids = encoding.word_ids()
23previous_word_id = None
24word_predictions = []
25for idx, word_id in enumerate(word_ids):
26 if word_id is not None and word_id != previous_word_id:
27 label_id = predictions_indices[idx]
28 word_predictions.append(model.config.id2label[label_id])
29 previous_word_id = word_id1def visualize_predictions(image, words, boxes, predictions):
2 label2color = {
3 "B-QUESTION": "blue", "I-QUESTION": "blue",
4 "B-ANSWER": "green", "I-ANSWER": "green",
5 "B-HEADER": "orange", "I-HEADER": "orange",
6 "O": "gray"
7 }
8 draw_image = image.copy()
9 draw = ImageDraw.Draw(draw_image)
10 try:
11 font = ImageFont.truetype("arial.ttf", 12)
12 except IOError:
13 font = ImageFont.load_default()
14 for word, box, label in zip(words, boxes, predictions):
15 color = label2color.get(label, 'red')
16 draw.rectangle(box, outline=color, width=2)
17 entity_type = label.split('-')[1] if '-' in label else 'OTHER'
18 if entity_type != 'OTHER':
19 draw.text((box[0], box[1] - 10), entity_type, fill=color, font=font)
20 return draw_image1print("Visualizing results...")
2visualized_image = visualize_predictions(image, words, unnormalized_boxes, word_predictions)
3display(visualized_image)
4visualized_image.save("result_visualization_manual.png")
5print("Saved visualization to result_visualization_manual.png")