File size: 11,951 Bytes
be9dd82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54b020c
be9dd82
 
 
 
 
 
 
 
 
 
 
 
54b020c
be9dd82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e460fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be9dd82
 
 
21d1711
 
 
d14b931
0601688
e460fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0601688
 
 
 
 
be9dd82
0601688
 
 
 
 
 
be9dd82
 
0601688
 
 
 
 
 
 
be9dd82
0601688
 
e460fc7
be9dd82
0601688
 
 
e460fc7
 
 
 
 
 
0601688
5b807f0
be9dd82
 
 
e460fc7
 
be9dd82
e460fc7
be9dd82
5b807f0
 
be9dd82
e460fc7
 
 
 
 
 
 
 
 
 
be9dd82
 
 
 
 
 
 
 
 
e460fc7
 
 
 
 
 
 
 
 
 
 
be9dd82
 
e460fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be9dd82
e460fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a93aae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e460fc7
5a93aae
 
 
 
 
 
 
 
e460fc7
 
 
 
 
5a93aae
e460fc7
 
5a93aae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be9dd82
 
 
 
 
 
 
 
 
d14b931
 
be9dd82
d14b931
 
be9dd82
 
 
 
 
 
 
 
 
 
d14b931
 
be9dd82
d14b931
 
be9dd82
 
 
e460fc7
 
7d84a3f
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
# import torch
# from model_loader import model, processor, device
# from processor_utils import load_input
# from prompt import get_prompt
# import json
# def process_document(image):
#     # images = load_input(file_path)
#     # image = images[0]
#     # print("Checking input type and no of pages in pdf")
#     # print(type(image))
#     # print(type(images))
#     # print(len(images))
    
    

#     messages = [
#         {
#             "role": "user",
#             "content": [
#                 {"type": "image", "image": image},
#                 {"type": "text", "text": get_prompt()}
#             ]
#         }
#     ]

#     text = processor.apply_chat_template(
#         messages,
#         tokenize=False,  # so that this can return string output
#         add_generation_prompt=True   # if true it will add extra on start and end
#     )
#     # print(f"The text of inference is {text}")

#     inputs = processor(
#         text=[text],
#         images=[image],
#         return_tensors="pt"
#     ).to(device)
#     # print(f"The inputs of inference is {inputs}")
    
#     output = model.generate(
#         **inputs,
#         max_new_tokens=1500,
#         do_sample=False,   #  if it is true there will be extra text with output
#         # temperature=0.1   # temp is not required
#     )
#     # print(f"The output of inference is {output}")
    

#     generated_ids = output[0][inputs.input_ids.shape[-1]:]
#     # print(f"The generated_ids of inference is {generated_ids}")

#     # response = processor.decode(   # past code
#     #     generated_ids,
#     #     skip_special_tokens=True
#     # )

#     # return response.strip()


    
#     response = processor.decode(
#     generated_ids,
#     skip_special_tokens=True
#     ).strip()
#     # print(f"The response of inference is {response}")

#     # 🔥 FORCE JSON CLEANING
#     start = response.find("{")
#     end = response.rfind("}") + 1

#     if start != -1 and end != -1:
#         response = response[start:end]
    
#     print(f"The type of response is before{response}")
#     try:
#         parsed = json.loads(response)
#     except:
#         parsed = {
#         "error":[
#             response
#         ] 
#         #     "Invalid JSON",
#         # "raw": response
#         }
#     print(f"The type of response is after{response}")
        
#     return response


# import json
# from model_loader import get_model
# from processor_utils import load_input
# from prompt import get_part_classifier_prompt, get_part_prompt


# def _run_model(image, prompt_text, model, processor, device):
#     messages = [
#         {
#             "role": "user",
#             "content": [
#                 {"type": "image", "image": image},
#                 {"type": "text", "text": prompt_text}
#             ]
#         }
#     ]

#     text = processor.apply_chat_template(
#         messages,
#         tokenize=False,
#         add_generation_prompt=True
#     )

#     inputs = processor(
#         text=[text],
#         images=[image],
#         return_tensors="pt"
#     ).to(device)

#     output = model.generate(
#         **inputs,
#         max_new_tokens=400,
#         do_sample=False
#     )

#     generated_ids = output[0][inputs.input_ids.shape[-1]:]
#     response = processor.decode(generated_ids, skip_special_tokens=True).strip()
#     return response


# def _extract_json_block(text):
#     start = text.find("{")
#     end = text.rfind("}") + 1
#     if start == -1 or end == 0:
#         return None
#     return text[start:end]


# def classify_page(image, model, processor, device):
#     raw = _run_model(image, get_part_classifier_prompt(), model, processor, device)
#     raw = raw.strip().upper()

#     valid_parts = {"PART-1", "PART-2", "PART-3", "PART-4", "PART-5", "PART-6"}
#     for part in valid_parts:
#         if part in raw:
#             return part

#     return "UNKNOWN"


# def extract_part_json(image, part_name, model, processor, device):
#     raw = _run_model(image, get_part_prompt(part_name), model, processor, device)
#     json_block = _extract_json_block(raw)

#     if not json_block:
#         return {
#             "status": "error",
#             "part": part_name,
#             "raw_output": raw,
#             "parsed": None
#         }

#     try:
#         parsed = json.loads(json_block)
#         return {
#             "status": "success",
#             "part": part_name,
#             "raw_output": raw,
#             "parsed": parsed
#         }
#     except json.JSONDecodeError:
#         return {
#             "status": "error",
#             "part": part_name,
#             "raw_output": raw,
#             "parsed": None
#         }


# def process_document(file_path):
#     model, processor, device = get_model()
#     pages = load_input(file_path)

#     page_results = []

#     for idx, image in enumerate(pages, start=1):
#         part_name = classify_page(image, model, processor, device)

#         if part_name == "UNKNOWN":
#             page_results.append({
#                 "page_number": idx,
#                 "status": "error",
#                 "part": "UNKNOWN",
#                 "raw_output": "",
#                 "parsed": None
#             })
#             continue

#         result = extract_part_json(image, part_name, model, processor, device)
#         result["page_number"] = idx
#         page_results.append(result)

#     return {
#         "total_pages": len(page_results),
#         "pages": page_results
#     }

import json
from model_loader import get_model
from processor_utils import load_input
# from prompt import get_part_classifier_prompt, get_part_prompt
from prompt1 import get_part_classifier_prompt, get_part_prompt

import time

def _get_max_tokens(part_name):
    limits = {
        "CLASSIFIER": 20,
        "PART-1": 1200,
        "PART-2": 700,
        "PART-3": 1800,
        "PART-4": 500,
        "PART-5": 300,
        "PART-6": 100
    }
    return limits.get(part_name, 600)


def _clean_raw_text(text):
    text = text.strip()

    if text.startswith("```json"):
        text = text[len("```json"):].strip()
    elif text.startswith("```"):
        text = text[len("```"):].strip()

    if text.endswith("```"):
        text = text[:-3].strip()

    return text


def _run_model(image, prompt_text, model, processor, device, max_new_tokens):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "image", "image": image},
                {"type": "text", "text": prompt_text}
            ]
        }
    ]

    text = processor.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )

    inputs = processor(
        text=[text],
        images=[image],
        return_tensors="pt"
    ).to(device)

    output = model.generate(
        **inputs,
        max_new_tokens=max_new_tokens,
        do_sample=False
    )

    generated_ids = output[0][inputs.input_ids.shape[-1]:]
    response = processor.decode(
        generated_ids,
        skip_special_tokens=True
    ).strip()

    return _clean_raw_text(response)


def _extract_json_block(text):
    start = text.find("{")
    end = text.rfind("}") + 1

    if start == -1 or end == 0 or end <= start:
        return None

    return text[start:end]


def classify_page(image, model, processor, device):
    raw = _run_model(
        image,
        get_part_classifier_prompt(),
        model,
        processor,
        device,
        max_new_tokens=_get_max_tokens("CLASSIFIER")
    ).upper()

    valid_parts = ["PART-1", "PART-2", "PART-3", "PART-4", "PART-5", "PART-6"]

    for part in valid_parts:
        if part in raw:
            return part

    return "UNKNOWN"


def extract_part_json(image, part_name, model, processor, device):
    max_tokens = _get_max_tokens(part_name)

    raw = _run_model(
        image,
        get_part_prompt(part_name),
        model,
        processor,
        device,
        max_new_tokens=max_tokens
    )

    json_block = _extract_json_block(raw)

    if json_block:
        try:
            parsed = json.loads(json_block)
            return {
                "status": "success",
                "part": part_name,
                "raw_output": raw,
                "parsed": parsed
            }
        except json.JSONDecodeError:
            pass

    # retry once with larger token budget
    retry_raw = _run_model(
        image,
        get_part_prompt(part_name),
        model,
        processor,
        device,
        max_new_tokens=max_tokens + 600
    )

    retry_json_block = _extract_json_block(retry_raw)

    if retry_json_block:
        try:
            parsed = json.loads(retry_json_block)
            return {
                "status": "success",
                "part": part_name,
                "raw_output": retry_raw,
                "parsed": parsed
            }
        except json.JSONDecodeError:
            pass

    return {
        "status": "error",
        "part": part_name,
        "raw_output": retry_raw if 'retry_raw' in locals() else raw,
        "parsed": None
    }


# def merge_page_results(page_results):
#     final_json = {}

#     for item in page_results:
#         if item["status"] != "success" or not item["parsed"]:
#             continue

#         parsed = item["parsed"]
#         for key, value in parsed.items():
#             final_json[key] = value

#     return final_json


# Adding these to handle json in structured format add from line 381 to 425

def merge_page_results(page_results):
    final_json = {
        "PART-1": {},
        "PART-2": {},
        "PART-3": {},
        "PART-4": {},
        "PART-5": {},
        "PART-6": {}
    }

    for item in page_results:
        if item["status"] != "success" or not item["parsed"]:
            continue

        part = item["part"]
        parsed = item["parsed"]

        final_json[part] = _merge_values(final_json[part], parsed)

    return {key: value for key, value in final_json.items() if value}



def _merge_values(old_value, new_value):
    if old_value is None:
        return new_value

    if isinstance(old_value, list) and isinstance(new_value, list):
        return old_value + new_value

    if isinstance(old_value, dict) and isinstance(new_value, dict):
        merged = dict(old_value)

        for key, value in new_value.items():
            if key in merged:
                merged[key] = _merge_values(merged[key], value)
            else:
                merged[key] = value

        return merged

    if old_value in ("", None, [], {}):
        return new_value

    return old_value


def process_document(file_path):
    model, processor, device = get_model()
    pages = load_input(file_path)

    page_results = []

    for idx, image in enumerate(pages, start=1):
        print("first model has been called for",idx,"image")
        start = time.time()
        part_name = classify_page(image, model, processor, device)
        end = time.time()
        print("total time taken by the first model",end-start,"sec")

        if part_name == "UNKNOWN":
            page_results.append({
                "page_number": idx,
                "status": "error",
                "part": "UNKNOWN",
                "raw_output": "",
                "parsed": None
            })
            continue
        print("second model has been called for",idx,"image")
        start = time.time()
        result = extract_part_json(image, part_name, model, processor, device)
        end = time.time()
        print("total time taken by the second model",end-start,"sec")
        result["page_number"] = idx
        page_results.append(result)

    final_json = merge_page_results(page_results)

    # return {
    #     "final_json": final_json
    #     # "total_pages": len(page_results),
    #     # "pages": page_results
    # }
    return final_json