File size: 5,436 Bytes
efa0e35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import glob
import json
import argparse
import warnings
warnings.filterwarnings("ignore")

import torch
import torch.distributed as dist

from tqdm import tqdm
from datetime import timedelta

from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info


def clean_and_remove_hallucinations(text):
    # keywords_list can be added to process ocr results to a cleaner version
    keywords_list = ["addCriterion", "No text recognized."] 
    for keyword in keywords_list:
        s = text.replace(keyword, "").replace(f"\n{keyword}", "").replace(f"{keyword}\n", "")

    return s


class ImageEvaluator:
    def __init__(self, device):
        self.device = device

        model_id = os.environ.get("LONGTEXT_QWEN_MODEL_PATH", "Qwen/Qwen2.5-VL-7B-Instruct")
        self.qwen_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
            model_id,
            torch_dtype=torch.bfloat16,
            device_map=device,
        )
        self.qwen_processor = AutoProcessor.from_pretrained(model_id)
        self.qwen_prompt = (
            "Recognize the text in the image, only reply with the text content, "
            "but avoid repeating previously mentioned content. "
            "If no text is recognized, please reply with 'No text recognized'."
        )

    def qwen_ocr(self, image):
        message = [{"role": "user",
                    "content": [{"type": "image", "image": image},
                                {"type": "text", "text": self.qwen_prompt}],}]
        texts = self.qwen_processor.apply_chat_template(message, tokenize=False, add_generation_prompt=True)
        image_inputs, _ = process_vision_info(message)
        inputs = self.qwen_processor(
            text=texts,
            images=image_inputs,
            padding=True,
            return_tensors="pt",
        ).to(self.device)
        max_new_tokens = int(os.environ.get("LONGTEXT_MAX_NEW_TOKENS", "1024"))
        generated_ids = self.qwen_model.generate(**inputs, max_new_tokens=max_new_tokens)
        generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
        outputs = self.qwen_processor.batch_decode(
            generated_ids_trimmed,
            skip_special_tokens=True,
            clean_up_tokenization_spaces=False,
        )
        qwen_results = clean_and_remove_hallucinations(outputs[0])
        return qwen_results

    def evaluate(self, data_chunk):
        assert len(data_chunk) >= 1, f'At least one document is required.'
        eval_results = []
        with torch.no_grad():
            for data in tqdm(data_chunk):
                ocr_results = self.qwen_ocr(data['image'])
                final_result = {'image': data['image'],
                                'prompt': data['prompt'],
                                'ocr_gt': data['text'],
                                'ocr_results': ocr_results}
                eval_results.append(final_result)

        return eval_results


def split_list(x, n):
    k, m = divmod(len(x), n)
    return [x[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)]


def main(args):
    # Setup PyTorch:
    torch.set_grad_enabled(False)
    dist.init_process_group("nccl", timeout=timedelta(hours=1))
    rank = dist.get_rank()
    device = rank % torch.cuda.device_count()
    world_size = dist.get_world_size()
    seed = args.global_seed * world_size + rank
    torch.manual_seed(seed)

    os.makedirs(args.output_dir, exist_ok=True)

    prompt_file = args.prompt_file or ('text_prompts.jsonl' if args.mode == 'en' else 'text_prompts_zh.jsonl')
    prompts = [json.loads(line) for line in open(prompt_file)]
    prompt_map = {}
    for prompt in prompts:
        # LLTB metadata uses target_text instead of the upstream
        # LongText-Bench text list.
        if "text" not in prompt and "target_text" in prompt:
            prompt = dict(prompt)
            prompt["text"] = str(prompt["target_text"]).splitlines()
        prompt_map[prompt["prompt_id"]] = prompt

    data = []
    for image_file in sorted(glob.glob(f'{args.sample_dir}/*.png')):
        fname = image_file.split('/')[-1]
        if '_' in fname:
            prompt_id = int(fname.split('_')[0])
        else:
            prompt_id = int(fname.split('.')[0])
        info = prompt_map[prompt_id]
        data.append({'image': image_file, 
                     'prompt': info['prompt'], 
                     'text': info['text']})
    data_chunks = split_list(data, world_size)

    evaluator = ImageEvaluator(device)
    print(f'=============Evaluate {len(data_chunks[rank])} images in rank {rank}=============')
    results = evaluator.evaluate(data_chunks[rank])
    output_path = os.path.join(args.output_dir, f'results_chunk{rank}.jsonl')
    with open(output_path, 'w', encoding='utf-8') as f:
        for r in results:
            f.write(json.dumps(r, ensure_ascii=False) + '\n')


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--sample_dir", type=str, required=True)
    parser.add_argument("--output_dir", type=str, required=True)
    parser.add_argument("--mode", type=str, choices=['en', 'zh'], default='en')
    parser.add_argument("--prompt_file", type=str, default=None)
    parser.add_argument("--global_seed", type=str, default=42)
    
    args = parser.parse_args()
    main(args)