nnul commited on
Commit
df6e6de
·
verified ·
1 Parent(s): 8beea53

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +144 -0
README.md CHANGED
@@ -64,6 +64,150 @@ The following hyperparameters were used during training:
64
  | 0.2618 | 5.0 | 2610 | 0.6625 | 0.7711 | 0.8476 | 0.8075 | 0.8030 |
65
 
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  ### Framework versions
68
 
69
  - Transformers 4.52.4
 
64
  | 0.2618 | 5.0 | 2610 | 0.6625 | 0.7711 | 0.8476 | 0.8075 | 0.8030 |
65
 
66
 
67
+
68
+ ### Inference
69
+
70
+ ```bash
71
+ # Install the Python wrapper
72
+ !pip install pytesseract pillow
73
+
74
+ # Install the Tesseract engine on a Debian/Ubuntu-based system (like Colab)
75
+ !sudo apt install tesseract-ocr
76
+ ```
77
+
78
+ ```python
79
+ import torch
80
+ from transformers import AutoProcessor, AutoModelForTokenClassification
81
+ from PIL import Image, ImageDraw, ImageFont
82
+ import pytesseract
83
+ import numpy as np
84
+ import os # For setting environment variable
85
+
86
+ # --- CRITICAL FOR DEBUGGING: Set this at the very top ---
87
+ os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
88
+
89
+ # --- ADD THE NORMALIZATION FUNCTION ---
90
+ def normalize_bbox(bbox, width, height):
91
+ return [
92
+ int(1000 * min(max(bbox[0] / width, 0), 1)),
93
+ int(1000 * min(max(bbox[1] / height, 0), 1)),
94
+ int(1000 * min(max(bbox[2] / width, 0), 1)),
95
+ int(1000 * min(max(bbox[3] / height, 0), 1))
96
+ ]
97
+ ```
98
+
99
+ ```python
100
+ # --- 1. Load your Fine-Tuned Model and Processor ---
101
+ MODEL_ID = "nnul/layoutlmv3-xfund"
102
+
103
+ print("Loading processor...")
104
+ processor = AutoProcessor.from_pretrained(MODEL_ID)
105
+ print("Loading model...")
106
+ model = AutoModelForTokenClassification.from_pretrained(MODEL_ID)
107
+
108
+ print("Moving model to device...")
109
+ device = "cuda" if torch.cuda.is_available() else "cpu"
110
+ model.to(device)
111
+ print("Model moved successfully.")
112
+ ```
113
+
114
+ ```python
115
+ # --- 2. Load the Image ---
116
+ image_path = "your_image.png"
117
+ image = Image.open(image_path).convert("RGB")
118
+ width, height = image.size
119
+ ```
120
+
121
+ ```python
122
+ # --- 3. Perform OCR and NORMALIZE Bounding Boxes ---
123
+ print("Performing OCR...")
124
+ data = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)
125
+ words = []
126
+ unnormalized_boxes = []
127
+ normalized_boxes = []
128
+
129
+ for i in range(len(data['text'])):
130
+ if int(data['conf'][i]) > 30 and data['text'][i].strip() != '':
131
+ word = data['text'][i]
132
+ x, y, w, h = data['left'][i], data['top'][i], data['width'][i], data['height'][i]
133
+
134
+ actual_box = [x, y, x + w, y + h]
135
+ unnormalized_boxes.append(actual_box)
136
+
137
+ normalized_box = normalize_bbox(actual_box, width, height)
138
+ normalized_boxes.append(normalized_box)
139
+
140
+ words.append(word)
141
+
142
+ print(f"OCR found {len(words)} words.")
143
+ ```
144
+
145
+ ```python
146
+ # --- 4. Manually Preprocess and Predict ---
147
+ print("Preprocessing inputs...")
148
+ encoding = processor(
149
+ image,
150
+ words,
151
+ boxes=normalized_boxes,
152
+ return_tensors="pt",
153
+ truncation=True
154
+ )
155
+
156
+ print("Moving inputs to device...")
157
+ for k, v in encoding.items():
158
+ encoding[k] = v.to(device)
159
+
160
+ print("Running inference...")
161
+ with torch.no_grad():
162
+ outputs = model(**encoding)
163
+
164
+ logits = outputs.logits
165
+ predictions_indices = logits.argmax(-1).squeeze().tolist()
166
+
167
+ word_ids = encoding.word_ids()
168
+ previous_word_id = None
169
+ word_predictions = []
170
+ for idx, word_id in enumerate(word_ids):
171
+ if word_id is not None and word_id != previous_word_id:
172
+ label_id = predictions_indices[idx]
173
+ word_predictions.append(model.config.id2label[label_id])
174
+ previous_word_id = word_id
175
+ ```
176
+
177
+ ```python
178
+ def visualize_predictions(image, words, boxes, predictions):
179
+ label2color = {
180
+ "B-QUESTION": "blue", "I-QUESTION": "blue",
181
+ "B-ANSWER": "green", "I-ANSWER": "green",
182
+ "B-HEADER": "orange", "I-HEADER": "orange",
183
+ "O": "gray"
184
+ }
185
+ draw_image = image.copy()
186
+ draw = ImageDraw.Draw(draw_image)
187
+ try:
188
+ font = ImageFont.truetype("arial.ttf", 12)
189
+ except IOError:
190
+ font = ImageFont.load_default()
191
+ for word, box, label in zip(words, boxes, predictions):
192
+ color = label2color.get(label, 'red')
193
+ draw.rectangle(box, outline=color, width=2)
194
+ entity_type = label.split('-')[1] if '-' in label else 'OTHER'
195
+ if entity_type != 'OTHER':
196
+ draw.text((box[0], box[1] - 10), entity_type, fill=color, font=font)
197
+ return draw_image
198
+ ```
199
+
200
+ ```python
201
+ print("Visualizing results...")
202
+ visualized_image = visualize_predictions(image, words, unnormalized_boxes, word_predictions)
203
+ display(visualized_image)
204
+ visualized_image.save("result_visualization_manual.png")
205
+ print("Saved visualization to result_visualization_manual.png")
206
+ ```
207
+
208
+
209
+
210
+
211
  ### Framework versions
212
 
213
  - Transformers 4.52.4