aagamjtdev commited on
Commit
525a040
Β·
1 Parent(s): 07abef7
Files changed (1) hide show
  1. HF_LayoutLM_with_Passage.py +514 -33
HF_LayoutLM_with_Passage.py CHANGED
@@ -1,3 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import json
2
  import argparse
3
  import os
@@ -8,8 +494,9 @@ import torch.nn as nn
8
  from torch.utils.data import Dataset, DataLoader, random_split
9
  from transformers import LayoutLMv3TokenizerFast, LayoutLMv3Model
10
  from TorchCRF import CRF
 
11
  from torch.optim import AdamW
12
- from tqdm import tqdm # Keep for evaluate
13
  from sklearn.metrics import precision_recall_fscore_support
14
  import fitz # PyMuPDF
15
  import pytesseract
@@ -33,10 +520,10 @@ def preprocess_labelstudio(input_path, output_path):
33
  data = json.load(f)
34
 
35
  processed = []
36
- total_items = len(data)
37
  print(f"πŸ”„ Starting preprocessing of {total_items} documents...")
38
 
39
- for i, item in enumerate(data):
40
  words = item["data"]["original_words"]
41
  bboxes = item["data"]["original_bboxes"]
42
  labels = ["O"] * len(words)
@@ -51,19 +538,17 @@ def preprocess_labelstudio(input_path, output_path):
51
  # Some tokenizers may split words, so we must find a consecutive word match.
52
  text_tokens = text.split()
53
 
54
- for j in range(len(words) - len(text_tokens) + 1):
55
- if words[j:j + len(text_tokens)] == text_tokens:
56
- labels[j] = f"B-{tag}"
57
- for k in range(1, len(text_tokens)):
58
- labels[j + k] = f"I-{tag}"
59
  break # Move to next annotation if a match is found
60
 
61
  processed.append({"tokens": words, "labels": labels, "bboxes": bboxes})
62
 
63
- # --- HEARTBEAT LOGGING ---
64
- if (i + 1) % 50 == 0:
65
- print(f"--- HEARTBEAT: Preprocessed {i + 1}/{total_items} documents ---")
66
- # -------------------------
67
 
68
  print(f"βœ… Preprocessed data saved to {output_path}")
69
  return output_path
@@ -142,11 +627,6 @@ def augment_and_save_dataset(input_json_path, output_json_path):
142
  else:
143
  print(f"Warning: Skipping augmentation for sample {i} due to missing keys.")
144
 
145
- # --- HEARTBEAT LOGGING ---
146
- if (i + 1) % 50 == 0:
147
- print(f"--- HEARTBEAT: Augmented {i + 1}/{original_count} original documents ---")
148
- # -------------------------
149
-
150
  augmented_count = len(augmented_data)
151
  print(f"Dataset Augmentation: Original samples: {original_count}, Total samples: {augmented_count}")
152
 
@@ -229,14 +709,12 @@ class LayoutLMv3CRF(nn.Module):
229
 
230
 
231
  # -------------------------
232
- # Step 4: Training + Evaluation (Modified for Verbose Logging)
233
  # -------------------------
234
  def train_one_epoch(model, dataloader, optimizer, device):
235
  model.train()
236
  total_loss = 0
237
-
238
- # Removed tqdm here to ensure cleaner log streaming to Gradio.
239
- for batch_idx, batch in enumerate(dataloader):
240
  batch = {k: v.to(device) for k, v in batch.items()}
241
  labels = batch.pop("labels")
242
  optimizer.zero_grad()
@@ -244,11 +722,6 @@ def train_one_epoch(model, dataloader, optimizer, device):
244
  loss.backward()
245
  optimizer.step()
246
  total_loss += loss.item()
247
-
248
- # VERBOSE LOGGING: Print batch progress every 5 batches to keep the Gradio connection alive
249
- if (batch_idx + 1) % 5 == 0:
250
- print(f"| Epoch Progress | Batch {batch_idx + 1}/{len(dataloader)} | Current Batch Loss: {loss.item():.4f}")
251
-
252
  return total_loss / len(dataloader)
253
 
254
 
@@ -273,7 +746,7 @@ def evaluate(model, dataloader, device, id2label):
273
 
274
 
275
  # -------------------------
276
- # Step 5: Main Pipeline (Training) - MODIFIED LABELS
277
  # -------------------------
278
  def main(args):
279
  # LABELS UPDATED: Added SECTION_HEADING and PASSAGE
@@ -288,18 +761,28 @@ def main(args):
288
  label2id = {l: i for i, l in enumerate(labels)}
289
  id2label = {i: l for l, i in label2id.items()}
290
 
 
 
 
 
 
291
  # 1. Preprocess and save the initial training data
292
  print("\n--- START PHASE: PREPROCESSING ---")
293
- initial_bio_json = "training_data_bio_bboxes.json"
 
 
294
  preprocess_labelstudio(args.input, initial_bio_json)
295
 
296
  # 2. Augment the dataset with translated bboxes
297
  print("\n--- START PHASE: AUGMENTATION ---")
298
- augmented_bio_json = "augmented_training_data_bio_bboxes.json"
 
 
299
  final_data_path = augment_and_save_dataset(initial_bio_json, augmented_bio_json)
300
 
301
  # Clean up the intermediary file (optional)
302
- # os.remove(initial_bio_json)
 
303
 
304
  # 3. Load and split augmented dataset
305
  print("\n--- START PHASE: MODEL/DATASET SETUP ---")
@@ -313,7 +796,6 @@ def main(args):
313
  train_dataset, val_dataset = random_split(dataset, [train_size, val_size])
314
  train_loader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True)
315
  val_loader = DataLoader(val_dataset, batch_size=args.batch_size)
316
- print(f"Dataset split: Train samples: {train_size}, Validation samples: {val_size}")
317
 
318
  # 4. Initialize and load model
319
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@@ -341,7 +823,7 @@ def main(args):
341
  precision, recall, f1 = evaluate(model, val_loader, device, id2label)
342
 
343
  print(
344
- f"Epoch {epoch + 1}/{args.epochs} | Avg Loss: {avg_loss:.4f} | P: {precision:.3f} R: {recall:.3f} F1: {f1:.3f}")
345
  torch.save(model.state_dict(), ckpt_path)
346
  print(f"πŸ’Ύ Model saved at {ckpt_path}")
347
 
@@ -480,5 +962,4 @@ if __name__ == "__main__":
480
  elif args.mode == "infer":
481
  if not args.input:
482
  parser.error("--input is required for 'infer' mode.")
483
- # NOTE: The model path here should ideally match the ckpt_path in main: checkpoints/layoutlmv3_crf_passage.pth
484
  run_inference(args.input, "checkpoints/layoutlmv3_crf_new_passage.pth", "inference_predictions.json")
 
1
+ # import json
2
+ # import argparse
3
+ # import os
4
+ # import random
5
+ # import numpy as np
6
+ # import torch
7
+ # import torch.nn as nn
8
+ # from torch.utils.data import Dataset, DataLoader, random_split
9
+ # from transformers import LayoutLMv3TokenizerFast, LayoutLMv3Model
10
+ # from TorchCRF import CRF
11
+ # from torch.optim import AdamW
12
+ # from tqdm import tqdm # Keep for evaluate
13
+ # from sklearn.metrics import precision_recall_fscore_support
14
+ # import fitz # PyMuPDF
15
+ # import pytesseract
16
+ # from PIL import Image
17
+ # from pdf2image import convert_from_path
18
+ #
19
+ # # --- Configuration for Augmentation ---
20
+ # MAX_BBOX_DIMENSION = 999
21
+ # MAX_SHIFT = 30
22
+ # AUGMENTATION_FACTOR = 1
23
+ #
24
+ #
25
+ # # -------------------------------------
26
+ #
27
+ #
28
+ # # -------------------------
29
+ # # Step 1: Preprocessing (Label Studio β†’ BIO + bboxes)
30
+ # # -------------------------
31
+ # def preprocess_labelstudio(input_path, output_path):
32
+ # with open(input_path, "r", encoding="utf-8") as f:
33
+ # data = json.load(f)
34
+ #
35
+ # processed = []
36
+ # total_items = len(data)
37
+ # print(f"πŸ”„ Starting preprocessing of {total_items} documents...")
38
+ #
39
+ # for i, item in enumerate(data):
40
+ # words = item["data"]["original_words"]
41
+ # bboxes = item["data"]["original_bboxes"]
42
+ # labels = ["O"] * len(words)
43
+ #
44
+ # if "annotations" in item:
45
+ # for ann in item["annotations"]:
46
+ # for res in ann["result"]:
47
+ # # Check if the result item is a span annotation
48
+ # if "value" in res and "labels" in res["value"]:
49
+ # text = res["value"]["text"]
50
+ # tag = res["value"]["labels"][0]
51
+ # # Some tokenizers may split words, so we must find a consecutive word match.
52
+ # text_tokens = text.split()
53
+ #
54
+ # for j in range(len(words) - len(text_tokens) + 1):
55
+ # if words[j:j + len(text_tokens)] == text_tokens:
56
+ # labels[j] = f"B-{tag}"
57
+ # for k in range(1, len(text_tokens)):
58
+ # labels[j + k] = f"I-{tag}"
59
+ # break # Move to next annotation if a match is found
60
+ #
61
+ # processed.append({"tokens": words, "labels": labels, "bboxes": bboxes})
62
+ #
63
+ # # --- HEARTBEAT LOGGING ---
64
+ # if (i + 1) % 50 == 0:
65
+ # print(f"--- HEARTBEAT: Preprocessed {i + 1}/{total_items} documents ---")
66
+ # # -------------------------
67
+ #
68
+ # print(f"βœ… Preprocessed data saved to {output_path}")
69
+ # return output_path
70
+ #
71
+ #
72
+ # # -------------------------
73
+ # # Step 1.5: Bounding Box Augmentation
74
+ # # -------------------------
75
+ #
76
+ # def translate_bbox(bbox, shift_x, shift_y):
77
+ # """
78
+ # Translates a single bounding box [x_min, y_min, x_max, y_max] by (shift_x, shift_y)
79
+ # and clamps the coordinates to the valid range [0, MAX_BBOX_DIMENSION].
80
+ # """
81
+ # x_min, y_min, x_max, y_max = bbox
82
+ #
83
+ # new_x_min = x_min + shift_x
84
+ # new_y_min = y_min + shift_y
85
+ # new_x_max = x_max + shift_x
86
+ # new_y_max = y_max + shift_y
87
+ #
88
+ # # Clamp the new coordinates
89
+ # new_x_min = max(0, min(new_x_min, MAX_BBOX_DIMENSION))
90
+ # new_y_min = max(0, min(new_y_min, MAX_BBOX_DIMENSION))
91
+ # new_x_max = max(0, min(new_x_max, MAX_BBOX_DIMENSION))
92
+ # new_y_max = max(0, min(new_y_max, MAX_BBOX_DIMENSION))
93
+ #
94
+ # # Safety check
95
+ # if new_x_min > new_x_max: new_x_min = new_x_max
96
+ # if new_y_min > new_y_max: new_y_min = new_y_max
97
+ #
98
+ # return [new_x_min, new_y_min, new_x_max, new_y_max]
99
+ #
100
+ #
101
+ # def augment_sample(sample):
102
+ # """
103
+ # Generates a new sample by translating all bounding boxes.
104
+ # """
105
+ # shift_x = random.randint(-MAX_SHIFT, MAX_SHIFT)
106
+ # shift_y = random.randint(-MAX_SHIFT, MAX_SHIFT)
107
+ #
108
+ # new_sample = sample.copy()
109
+ #
110
+ # # Ensure tokens and labels are copied (they remain unchanged)
111
+ # new_sample["tokens"] = sample["tokens"]
112
+ # new_sample["labels"] = sample["labels"]
113
+ #
114
+ # # Translate all bounding boxes
115
+ # new_bboxes = [translate_bbox(bbox, shift_x, shift_y) for bbox in sample["bboxes"]]
116
+ # new_sample["bboxes"] = new_bboxes
117
+ #
118
+ # return new_sample
119
+ #
120
+ #
121
+ # def augment_and_save_dataset(input_json_path, output_json_path):
122
+ # """
123
+ # Loads preprocessed data, performs augmentation, and saves the result.
124
+ # """
125
+ # print(f"πŸ”„ Loading preprocessed data from {input_json_path} for augmentation...")
126
+ # with open(input_json_path, 'r', encoding="utf-8") as f:
127
+ # training_data = json.load(f)
128
+ #
129
+ # augmented_data = []
130
+ # original_count = len(training_data)
131
+ #
132
+ # print(f"πŸ”„ Starting augmentation (Factor: {AUGMENTATION_FACTOR}, {original_count} documents)...")
133
+ #
134
+ # for i, original_sample in enumerate(training_data):
135
+ # # 1. Add the original sample
136
+ # augmented_data.append(original_sample)
137
+ #
138
+ # # 2. Generate augmented samples
139
+ # for _ in range(AUGMENTATION_FACTOR):
140
+ # if "tokens" in original_sample and "labels" in original_sample and "bboxes" in original_sample:
141
+ # augmented_data.append(augment_sample(original_sample))
142
+ # else:
143
+ # print(f"Warning: Skipping augmentation for sample {i} due to missing keys.")
144
+ #
145
+ # # --- HEARTBEAT LOGGING ---
146
+ # if (i + 1) % 50 == 0:
147
+ # print(f"--- HEARTBEAT: Augmented {i + 1}/{original_count} original documents ---")
148
+ # # -------------------------
149
+ #
150
+ # augmented_count = len(augmented_data)
151
+ # print(f"Dataset Augmentation: Original samples: {original_count}, Total samples: {augmented_count}")
152
+ #
153
+ # # Save the augmented dataset
154
+ # with open(output_json_path, 'w', encoding="utf-8") as f:
155
+ # json.dump(augmented_data, f, indent=2, ensure_ascii=False)
156
+ #
157
+ # print(f"βœ… Augmented data saved to {output_json_path}")
158
+ # return output_json_path
159
+ #
160
+ #
161
+ # # -------------------------
162
+ # # Step 2: Dataset Class (Unchanged)
163
+ # # -------------------------
164
+ # class LayoutDataset(Dataset):
165
+ # def __init__(self, json_path, tokenizer, label2id, max_len=512):
166
+ # with open(json_path, "r", encoding="utf-8") as f:
167
+ # self.data = json.load(f)
168
+ # self.tokenizer = tokenizer
169
+ # self.label2id = label2id
170
+ # self.max_len = max_len
171
+ #
172
+ # def __len__(self):
173
+ # return len(self.data)
174
+ #
175
+ # def __getitem__(self, idx):
176
+ # item = self.data[idx]
177
+ # words, bboxes, labels = item["tokens"], item["bboxes"], item["labels"]
178
+ #
179
+ # # Tokenize
180
+ # encodings = self.tokenizer(
181
+ # words,
182
+ # boxes=bboxes,
183
+ # padding="max_length",
184
+ # truncation=True,
185
+ # max_length=self.max_len,
186
+ # return_offsets_mapping=True,
187
+ # return_tensors="pt"
188
+ # )
189
+ #
190
+ # # Align labels to word pieces
191
+ # word_ids = encodings.word_ids(batch_index=0)
192
+ # label_ids = []
193
+ # for word_id in word_ids:
194
+ # if word_id is None:
195
+ # label_ids.append(self.label2id["O"]) # [CLS], [SEP], padding
196
+ # else:
197
+ # label_ids.append(self.label2id.get(labels[word_id], self.label2id["O"]))
198
+ #
199
+ # encodings.pop("offset_mapping")
200
+ # encodings["labels"] = torch.tensor(label_ids)
201
+ #
202
+ # return {key: val.squeeze(0) for key, val in encodings.items()}
203
+ #
204
+ #
205
+ # # -------------------------
206
+ # # Step 3: Model Architecture (Unchanged)
207
+ # # -------------------------
208
+ # class LayoutLMv3CRF(nn.Module):
209
+ # def __init__(self, model_name, num_labels):
210
+ # super().__init__()
211
+ # self.layoutlm = LayoutLMv3Model.from_pretrained(model_name)
212
+ # self.dropout = nn.Dropout(0.1)
213
+ # self.classifier = nn.Linear(self.layoutlm.config.hidden_size, num_labels)
214
+ # self.crf = CRF(num_labels)
215
+ #
216
+ # def forward(self, input_ids, bbox, attention_mask, labels=None):
217
+ # outputs = self.layoutlm(input_ids=input_ids, bbox=bbox, attention_mask=attention_mask)
218
+ # sequence_output = self.dropout(outputs.last_hidden_state)
219
+ # emissions = self.classifier(sequence_output)
220
+ #
221
+ # if labels is not None:
222
+ # # Training mode: calculate loss
223
+ # log_likelihood = self.crf(emissions, labels, mask=attention_mask.bool())
224
+ # return -log_likelihood.mean()
225
+ # else:
226
+ # # Inference mode: decode best path
227
+ # best_paths = self.crf.viterbi_decode(emissions, mask=attention_mask.bool())
228
+ # return best_paths
229
+ #
230
+ #
231
+ # # -------------------------
232
+ # # Step 4: Training + Evaluation (Modified for Verbose Logging)
233
+ # # -------------------------
234
+ # def train_one_epoch(model, dataloader, optimizer, device):
235
+ # model.train()
236
+ # total_loss = 0
237
+ #
238
+ # # Removed tqdm here to ensure cleaner log streaming to Gradio.
239
+ # for batch_idx, batch in enumerate(dataloader):
240
+ # batch = {k: v.to(device) for k, v in batch.items()}
241
+ # labels = batch.pop("labels")
242
+ # optimizer.zero_grad()
243
+ # loss = model(**batch, labels=labels)
244
+ # loss.backward()
245
+ # optimizer.step()
246
+ # total_loss += loss.item()
247
+ #
248
+ # # VERBOSE LOGGING: Print batch progress every 5 batches to keep the Gradio connection alive
249
+ # if (batch_idx + 1) % 5 == 0:
250
+ # print(f"| Epoch Progress | Batch {batch_idx + 1}/{len(dataloader)} | Current Batch Loss: {loss.item():.4f}")
251
+ #
252
+ # return total_loss / len(dataloader)
253
+ #
254
+ #
255
+ # def evaluate(model, dataloader, device, id2label):
256
+ # model.eval()
257
+ # all_preds, all_labels = [], []
258
+ # with torch.no_grad():
259
+ # for batch in tqdm(dataloader, desc="Evaluating"):
260
+ # batch = {k: v.to(device) for k, v in batch.items()}
261
+ # labels = batch.pop("labels").cpu().numpy()
262
+ # preds = model(**batch)
263
+ # for p, l, mask in zip(preds, labels, batch["attention_mask"].cpu().numpy()):
264
+ # valid = mask == 1
265
+ # l = l[valid].tolist()
266
+ # all_labels.extend(l)
267
+ # all_preds.extend(p[:len(l)])
268
+ #
269
+ # # Exclude the "O" label and other special tokens if necessary, but using 'micro' average
270
+ # # on all valid tokens is typically fine for the initial evaluation.
271
+ # precision, recall, f1, _ = precision_recall_fscore_support(all_labels, all_preds, average="micro", zero_division=0)
272
+ # return precision, recall, f1
273
+ #
274
+ #
275
+ # # -------------------------
276
+ # # Step 5: Main Pipeline (Training) - MODIFIED LABELS
277
+ # # -------------------------
278
+ # def main(args):
279
+ # # LABELS UPDATED: Added SECTION_HEADING and PASSAGE
280
+ # labels = [
281
+ # "O",
282
+ # "B-QUESTION", "I-QUESTION",
283
+ # "B-OPTION", "I-OPTION",
284
+ # "B-ANSWER", "I-ANSWER",
285
+ # "B-SECTION_HEADING", "I-SECTION_HEADING",
286
+ # "B-PASSAGE", "I-PASSAGE"
287
+ # ]
288
+ # label2id = {l: i for i, l in enumerate(labels)}
289
+ # id2label = {i: l for l, i in label2id.items()}
290
+ #
291
+ # # 1. Preprocess and save the initial training data
292
+ # print("\n--- START PHASE: PREPROCESSING ---")
293
+ # initial_bio_json = "training_data_bio_bboxes.json"
294
+ # preprocess_labelstudio(args.input, initial_bio_json)
295
+ #
296
+ # # 2. Augment the dataset with translated bboxes
297
+ # print("\n--- START PHASE: AUGMENTATION ---")
298
+ # augmented_bio_json = "augmented_training_data_bio_bboxes.json"
299
+ # final_data_path = augment_and_save_dataset(initial_bio_json, augmented_bio_json)
300
+ #
301
+ # # Clean up the intermediary file (optional)
302
+ # # os.remove(initial_bio_json)
303
+ #
304
+ # # 3. Load and split augmented dataset
305
+ # print("\n--- START PHASE: MODEL/DATASET SETUP ---")
306
+ # tokenizer = LayoutLMv3TokenizerFast.from_pretrained("microsoft/layoutlmv3-base")
307
+ # dataset = LayoutDataset(final_data_path, tokenizer, label2id, max_len=args.max_len)
308
+ # val_size = int(0.2 * len(dataset))
309
+ # train_size = len(dataset) - val_size
310
+ #
311
+ # # Use a fixed seed for reproducibility in split
312
+ # torch.manual_seed(42)
313
+ # train_dataset, val_dataset = random_split(dataset, [train_size, val_size])
314
+ # train_loader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True)
315
+ # val_loader = DataLoader(val_dataset, batch_size=args.batch_size)
316
+ # print(f"Dataset split: Train samples: {train_size}, Validation samples: {val_size}")
317
+ #
318
+ # # 4. Initialize and load model
319
+ # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
320
+ # print(f"Using device: {device}")
321
+ # # Num_labels is based on the updated 'labels' list
322
+ # model = LayoutLMv3CRF("microsoft/layoutlmv3-base", num_labels=len(labels)).to(device)
323
+ # ckpt_path = "checkpoints/layoutlmv3_crf_passage.pth"
324
+ # os.makedirs("checkpoints", exist_ok=True)
325
+ # if os.path.exists(ckpt_path):
326
+ # # NOTE: Loading an old checkpoint will likely fail now because num_labels has changed,
327
+ # # unless the old checkpoint had the *exact* same number of labels.
328
+ # # It is recommended to start training from scratch.
329
+ # # print(f"πŸ”„ Loading checkpoint from {ckpt_path}")
330
+ # # model.load_state_dict(torch.load(ckpt_path, map_location=device))
331
+ # print(f"⚠️ Starting fresh training. Old checkpoint {ckpt_path} may be incompatible with new label count.")
332
+ #
333
+ # optimizer = AdamW(model.parameters(), lr=args.lr)
334
+ #
335
+ # # 5. Training loop
336
+ # for epoch in range(args.epochs):
337
+ # print(f"\n--- START PHASE: EPOCH {epoch + 1}/{args.epochs} TRAINING ---")
338
+ # avg_loss = train_one_epoch(model, train_loader, optimizer, device)
339
+ #
340
+ # print(f"\n--- START PHASE: EPOCH {epoch + 1}/{args.epochs} EVALUATION ---")
341
+ # precision, recall, f1 = evaluate(model, val_loader, device, id2label)
342
+ #
343
+ # print(
344
+ # f"Epoch {epoch + 1}/{args.epochs} | Avg Loss: {avg_loss:.4f} | P: {precision:.3f} R: {recall:.3f} F1: {f1:.3f}")
345
+ # torch.save(model.state_dict(), ckpt_path)
346
+ # print(f"πŸ’Ύ Model saved at {ckpt_path}")
347
+ #
348
+ #
349
+ # def run_inference(pdf_path, model_path, output_path):
350
+ # # LABELS UPDATED: Added SECTION_HEADING and PASSAGE (Must match main)
351
+ # labels = [
352
+ # "O",
353
+ # "B-QUESTION", "I-QUESTION",
354
+ # "B-OPTION", "I-OPTION",
355
+ # "B-ANSWER", "I-ANSWER",
356
+ # "B-SECTION_HEADING", "I-SECTION_HEADING",
357
+ # "B-PASSAGE", "I-PASSAGE"
358
+ # ]
359
+ # label2id = {l: i for i, l in enumerate(labels)}
360
+ # id2label = {i: l for l, i in label2id.items()}
361
+ # tokenizer = LayoutLMv3TokenizerFast.from_pretrained("microsoft/layoutlmv3-base")
362
+ #
363
+ # # Load the trained model
364
+ # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
365
+ # model = LayoutLMv3CRF("microsoft/layoutlmv3-base", num_labels=len(labels)).to(device)
366
+ # try:
367
+ # model.load_state_dict(torch.load(model_path, map_location=device))
368
+ # except Exception as e:
369
+ # print(
370
+ # f"❌ Error loading model state: {e}. Ensure the model at {model_path} has been successfully trained with the new labels.")
371
+ # return
372
+ #
373
+ # model.eval()
374
+ #
375
+ # # Process PDF with OCR
376
+ # try:
377
+ # doc = fitz.open(pdf_path)
378
+ # except Exception as e:
379
+ # print(f"❌ Error opening PDF: {e}")
380
+ # return
381
+ #
382
+ # all_predictions = []
383
+ # tesseract_config = '--psm 6'
384
+ #
385
+ # for page_num in range(len(doc)):
386
+ # page = doc.load_page(page_num)
387
+ #
388
+ # # Get a high-resolution image of the page for Tesseract
389
+ # pix = page.get_pixmap(dpi=300)
390
+ # img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
391
+ #
392
+ # # Get page dimensions from PyMuPDF
393
+ # page_width, page_height = page.bound().width, page.bound().height
394
+ #
395
+ # # Get OCR data (words and bboxes)
396
+ # ocr_data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT, config=tesseract_config)
397
+ # words = [word for word in ocr_data['text'] if word.strip()]
398
+ #
399
+ # # Skip empty pages
400
+ # if not words:
401
+ # continue
402
+ #
403
+ # # Get the scaling factors from the image resolution to the PDF's native resolution
404
+ # x_scale = page_width / pix.width
405
+ # y_scale = page_height / pix.height
406
+ #
407
+ # # Create original pixel bboxes
408
+ # bboxes_raw = [[
409
+ # ocr_data['left'][i],
410
+ # ocr_data['top'][i],
411
+ # ocr_data['left'][i] + ocr_data['width'][i],
412
+ # ocr_data['top'][i] + ocr_data['height'][i]
413
+ # ] for i in range(len(ocr_data['text'])) if ocr_data['text'][i].strip()]
414
+ #
415
+ # # Normalize bboxes to 0-1000 scale using the correct scaling factors
416
+ # normalized_bboxes = [[
417
+ # int(1000 * (b[0] * x_scale) / page_width),
418
+ # int(1000 * (b[1] * y_scale) / page_height),
419
+ # int(1000 * (b[2] * x_scale) / page_width),
420
+ # int(1000 * (b[3] * y_scale) / page_height)
421
+ # ] for b in bboxes_raw]
422
+ #
423
+ # # Tokenize and run inference
424
+ # inputs = tokenizer(words, boxes=normalized_bboxes, return_tensors="pt", truncation=True).to(device)
425
+ #
426
+ # with torch.no_grad():
427
+ # # The model is run on the normalized bboxes
428
+ # preds = model(**inputs)
429
+ #
430
+ # # Align predictions back to words
431
+ # word_ids = inputs.word_ids(batch_index=0)
432
+ # final_preds = []
433
+ # previous_word_idx = None
434
+ # for idx, word_id in enumerate(word_ids):
435
+ # if word_id is not None and word_id != previous_word_idx:
436
+ # # The model returns a list of predicted classes for each token
437
+ # final_preds.append(id2label[preds[0][idx]])
438
+ # previous_word_idx = word_id
439
+ #
440
+ # # Prepare structured output
441
+ # page_results = []
442
+ # # Tesseract returns word list that is shorter than ocr_data if it contains empty strings.
443
+ # # We need to use the cleaned 'words' list and its corresponding filtered bboxes.
444
+ # # Note: We must ensure that the word and bbox lists passed to tokenizer and the filtered
445
+ # # final_preds list are all correctly aligned with the original ocr_data indices.
446
+ # # Since 'words' and 'bboxes_raw' are filtered exactly the same way (by word.strip()),
447
+ # # and 'final_preds' is aligned back to 'words', we can zip them.
448
+ # for word, bbox, label in zip(words, bboxes_raw, final_preds):
449
+ # page_results.append({
450
+ # "word": word,
451
+ # "bbox": bbox,
452
+ # "predicted_label": label
453
+ # })
454
+ # all_predictions.extend(page_results)
455
+ #
456
+ # doc.close()
457
+ # with open(output_path, "w") as f:
458
+ # json.dump(all_predictions, f, indent=2, ensure_ascii=False)
459
+ # print(f"βœ… Inference complete. Predictions saved to {output_path}")
460
+ #
461
+ #
462
+ # # -------------------------
463
+ # # Step 7: Main Execution (Unchanged)
464
+ # # -------------------------
465
+ # if __name__ == "__main__":
466
+ # parser = argparse.ArgumentParser(description="LayoutLMv3 Fine-tuning and Inference Script.")
467
+ # parser.add_argument("--mode", type=str, required=True, choices=["train", "infer"],
468
+ # help="Select mode: 'train' or 'infer'")
469
+ # parser.add_argument("--input", type=str, help="Path to input file (Label Studio JSON for train, PDF for infer).")
470
+ # parser.add_argument("--batch_size", type=int, default=4)
471
+ # parser.add_argument("--epochs", type=int, default=5)
472
+ # parser.add_argument("--lr", type=float, default=5e-5)
473
+ # parser.add_argument("--max_len", type=int, default=512)
474
+ # args = parser.parse_args()
475
+ #
476
+ # if args.mode == "train":
477
+ # if not args.input:
478
+ # parser.error("--input is required for 'train' mode.")
479
+ # main(args)
480
+ # elif args.mode == "infer":
481
+ # if not args.input:
482
+ # parser.error("--input is required for 'infer' mode.")
483
+ # # NOTE: The model path here should ideally match the ckpt_path in main: checkpoints/layoutlmv3_crf_passage.pth
484
+ # run_inference(args.input, "checkpoints/layoutlmv3_crf_new_passage.pth", "inference_predictions.json")
485
+
486
+
487
  import json
488
  import argparse
489
  import os
 
494
  from torch.utils.data import Dataset, DataLoader, random_split
495
  from transformers import LayoutLMv3TokenizerFast, LayoutLMv3Model
496
  from TorchCRF import CRF
497
+
498
  from torch.optim import AdamW
499
+ from tqdm import tqdm
500
  from sklearn.metrics import precision_recall_fscore_support
501
  import fitz # PyMuPDF
502
  import pytesseract
 
520
  data = json.load(f)
521
 
522
  processed = []
523
+ total_items = len(data) # Added for potential verbose logging
524
  print(f"πŸ”„ Starting preprocessing of {total_items} documents...")
525
 
526
+ for item in data:
527
  words = item["data"]["original_words"]
528
  bboxes = item["data"]["original_bboxes"]
529
  labels = ["O"] * len(words)
 
538
  # Some tokenizers may split words, so we must find a consecutive word match.
539
  text_tokens = text.split()
540
 
541
+ for i in range(len(words) - len(text_tokens) + 1):
542
+ if words[i:i + len(text_tokens)] == text_tokens:
543
+ labels[i] = f"B-{tag}"
544
+ for j in range(1, len(text_tokens)):
545
+ labels[i + j] = f"I-{tag}"
546
  break # Move to next annotation if a match is found
547
 
548
  processed.append({"tokens": words, "labels": labels, "bboxes": bboxes})
549
 
550
+ with open(output_path, "w", encoding="utf-8") as f:
551
+ json.dump(processed, f, indent=2, ensure_ascii=False)
 
 
552
 
553
  print(f"βœ… Preprocessed data saved to {output_path}")
554
  return output_path
 
627
  else:
628
  print(f"Warning: Skipping augmentation for sample {i} due to missing keys.")
629
 
 
 
 
 
 
630
  augmented_count = len(augmented_data)
631
  print(f"Dataset Augmentation: Original samples: {original_count}, Total samples: {augmented_count}")
632
 
 
709
 
710
 
711
  # -------------------------
712
+ # Step 4: Training + Evaluation (Unchanged)
713
  # -------------------------
714
  def train_one_epoch(model, dataloader, optimizer, device):
715
  model.train()
716
  total_loss = 0
717
+ for batch in tqdm(dataloader, desc="Training"):
 
 
718
  batch = {k: v.to(device) for k, v in batch.items()}
719
  labels = batch.pop("labels")
720
  optimizer.zero_grad()
 
722
  loss.backward()
723
  optimizer.step()
724
  total_loss += loss.item()
 
 
 
 
 
725
  return total_loss / len(dataloader)
726
 
727
 
 
746
 
747
 
748
  # -------------------------
749
+ # Step 5: Main Pipeline (Training) - MODIFIED LABELS + FILE PATH FIX
750
  # -------------------------
751
  def main(args):
752
  # LABELS UPDATED: Added SECTION_HEADING and PASSAGE
 
761
  label2id = {l: i for i, l in enumerate(labels)}
762
  id2label = {i: l for l, i in label2id.items()}
763
 
764
+ # --- FIX for FileNotFoundError: Use a temporary directory for intermediate files ---
765
+ TEMP_DIR = "temp_intermediate_files"
766
+ os.makedirs(TEMP_DIR, exist_ok=True)
767
+ print(f"\n--- SETUP PHASE: Created temp directory: {TEMP_DIR} ---")
768
+
769
  # 1. Preprocess and save the initial training data
770
  print("\n--- START PHASE: PREPROCESSING ---")
771
+
772
+ # FIX: Prepend the directory path to the file name
773
+ initial_bio_json = os.path.join(TEMP_DIR, "training_data_bio_bboxes.json")
774
  preprocess_labelstudio(args.input, initial_bio_json)
775
 
776
  # 2. Augment the dataset with translated bboxes
777
  print("\n--- START PHASE: AUGMENTATION ---")
778
+
779
+ # FIX: Prepend the directory path to the file name
780
+ augmented_bio_json = os.path.join(TEMP_DIR, "augmented_training_data_bio_bboxes.json")
781
  final_data_path = augment_and_save_dataset(initial_bio_json, augmented_bio_json)
782
 
783
  # Clean up the intermediary file (optional)
784
+ # import shutil
785
+ # shutil.rmtree(TEMP_DIR)
786
 
787
  # 3. Load and split augmented dataset
788
  print("\n--- START PHASE: MODEL/DATASET SETUP ---")
 
796
  train_dataset, val_dataset = random_split(dataset, [train_size, val_size])
797
  train_loader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True)
798
  val_loader = DataLoader(val_dataset, batch_size=args.batch_size)
 
799
 
800
  # 4. Initialize and load model
801
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
823
  precision, recall, f1 = evaluate(model, val_loader, device, id2label)
824
 
825
  print(
826
+ f"Epoch {epoch + 1}/{args.epochs} | Loss: {avg_loss:.4f} | P: {precision:.3f} R: {recall:.3f} F1: {f1:.3f}")
827
  torch.save(model.state_dict(), ckpt_path)
828
  print(f"πŸ’Ύ Model saved at {ckpt_path}")
829
 
 
962
  elif args.mode == "infer":
963
  if not args.input:
964
  parser.error("--input is required for 'infer' mode.")
 
965
  run_inference(args.input, "checkpoints/layoutlmv3_crf_new_passage.pth", "inference_predictions.json")