File size: 6,769 Bytes
f7695e9
526e5ae
 
f7695e9
 
526e5ae
f7695e9
526e5ae
 
 
f7695e9
526e5ae
 
 
 
 
f7695e9
 
 
 
526e5ae
 
 
 
 
 
 
 
 
 
 
e4b0b88
f7695e9
 
526e5ae
 
 
f7695e9
 
526e5ae
f7695e9
526e5ae
f7695e9
 
526e5ae
f7695e9
526e5ae
f7695e9
 
526e5ae
 
 
f7695e9
526e5ae
 
f7695e9
 
526e5ae
 
 
 
f7695e9
 
526e5ae
f7695e9
 
 
 
526e5ae
f7695e9
 
526e5ae
f7695e9
 
 
526e5ae
f7695e9
 
 
526e5ae
 
 
 
 
 
542e67d
526e5ae
542e67d
 
 
 
526e5ae
542e67d
526e5ae
542e67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526e5ae
 
 
 
 
 
 
 
 
 
 
542e67d
 
526e5ae
 
 
 
 
 
 
f7695e9
542e67d
 
 
f7695e9
526e5ae
f7695e9
e4b0b88
526e5ae
e4b0b88
542e67d
526e5ae
e4b0b88
f7695e9
526e5ae
 
 
 
f7695e9
 
526e5ae
f7695e9
 
 
 
 
 
 
 
 
e4b0b88
 
 
542e67d
f7695e9
526e5ae
 
e4b0b88
526e5ae
 
f7695e9
e4b0b88
 
 
 
 
 
f7695e9
e4b0b88
f7695e9
e4b0b88
f7695e9
 
526e5ae
 
 
f7695e9
526e5ae
 
 
e4b0b88
526e5ae
542e67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526e5ae
f7695e9
d2146b6
 
 
 
 
 
 
 
526e5ae
d2146b6
 
 
526e5ae
d2146b6
 
f7695e9
 
526e5ae
 
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
import os
import gc
import copy
import torch
import gradio as gr
import spaces

from argparse import ArgumentParser
from transformers import AutoProcessor, HunYuanVLForConditionalGeneration
from qwen_vl_utils import process_vision_info

# -------------------------------------------------------------------
# Global config
# -------------------------------------------------------------------
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "1"


def _get_args():
    parser = ArgumentParser()
    parser.add_argument(
        "-c",
        "--checkpoint-path",
        type=str,
        default="tencent/HunyuanOCR",
        help="Checkpoint name or path",
    )
    parser.add_argument("--cpu-only", action="store_true")
    parser.add_argument("--share", action="store_true")
    parser.add_argument("--inbrowser", action="store_true")
    return parser.parse_args()


def _load_model_processor(args):
    print("[INFO] Loading model")
    print("[INFO] CUDA available:", torch.cuda.is_available())

    model = HunYuanVLForConditionalGeneration.from_pretrained(
        args.checkpoint_path,
        attn_implementation="eager",
        torch_dtype=torch.bfloat16,
        device_map="auto",
    )

    if hasattr(model, "gradient_checkpointing_disable"):
        model.gradient_checkpointing_disable()
        print("[INFO] Gradient checkpointing disabled")

    model.eval()
    processor = AutoProcessor.from_pretrained(
        args.checkpoint_path, use_fast=False, trust_remote_code=True
    )

    print("[INFO] Model device:", next(model.parameters()).device)
    return model, processor


def _parse_text(text: str) -> str:
    if not isinstance(text, str):
        text = str(text)
    return text.replace("<trans>", "").replace("</trans>", "")


def clean_repeated_substrings(text: str) -> str:
    n = len(text)
    if n < 2000:
        return text
    for length in range(2, n // 10 + 1):
        candidate = text[-length:]
        count = 0
        i = n - length
        while i >= 0 and text[i : i + length] == candidate:
            count += 1
            i -= length
        if count >= 10:
            return text[: n - length * (count - 1)]
    return text


def _gc():
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()


def build_hunyuan_messages_from_history(history, image_path, latest_user_text):
    """
    history: list of [user_text, assistant_text] pairs from ChatInterface
    image_path: current uploaded image file path (or None)
    latest_user_text: current user message (str)
    Returns: list[{"role": ..., "content": [...]}] for HunYuan
    """
    messages = []

    # 1) Past turns (only text – image reused only for current turn)
    for user, assistant in history:
        # user
        messages.append(
            {
                "role": "user",
                "content": [{"type": "text", "text": user}],
            }
        )
        # assistant
        messages.append(
            {
                "role": "assistant",
                "content": [{"type": "text", "text": assistant}],
            }
        )

    # 2) Current user turn (image + text)
    content = []
    if image_path:
        content.append(
            {
                "type": "image",
                "image": os.path.abspath(image_path),
            }
        )
    if latest_user_text:
        content.append({"type": "text", "text": latest_user_text})

    if content:
        messages.append({"role": "user", "content": content})

    return messages


def main():
    args = _get_args()
    model, processor = _load_model_processor(args)

    # -------------------------
    # Core model call
    # -------------------------
    @spaces.GPU(duration=120)
    def call_local_model(hy_messages):
        import time

        start_time = time.time()

        # HunYuan expects list[list[message]]
        convs = [hy_messages]

        texts = [
            processor.apply_chat_template(
                c, tokenize=False, add_generation_prompt=True
            )
            for c in convs
        ]

        image_inputs, video_inputs = process_vision_info(convs)

        inputs = processor(
            text=texts,
            images=image_inputs,
            videos=video_inputs,
            padding=True,
            return_tensors="pt",
        )

        device = "cuda" if torch.cuda.is_available() else "cpu"
        inputs = inputs.to(device)

        max_new_tokens = 512  # keep this smaller on CPU
        with torch.no_grad():
            if device == "cuda":
                with torch.cuda.amp.autocast(dtype=torch.bfloat16):
                    _ = model(**inputs, use_cache=False)
            else:
                _ = model(**inputs, use_cache=False)

            generated_ids = model.generate(
                **inputs,
                max_new_tokens=max_new_tokens,
                do_sample=False,
                temperature=0,
            )

        input_ids = inputs.input_ids
        generated_ids_trimmed = [
            out_ids[len(in_ids) :] for in_ids, out_ids in zip(input_ids, generated_ids)
        ]
        output_texts = processor.batch_decode(
            generated_ids_trimmed,
            skip_special_tokens=True,
            clean_up_tokenization_spaces=False,
        )
        text = clean_repeated_substrings(_parse_text(output_texts[0]))
        print(f"[DEBUG] Total generation time: {time.time() - start_time:.2f}s")
        return text

    # -------------------------
    # Chat handler for ChatInterface
    # -------------------------
    def ocr_chat(message, history, image_path):
        """
        message: current user text (str)
        history: list[[user, assistant], ...]
        image_path: filepath from Image component
        """
        message = (message or "").strip()

        if not message and not image_path:
            return "Please upload an image and/or type a question."

        hy_messages = build_hunyuan_messages_from_history(
            history or [], image_path, message
        )
        answer = call_local_model(hy_messages)
        return answer

    # -------------------------
    # UI: ChatInterface + image
    # -------------------------
    with gr.Blocks() as demo:
        gr.Markdown("# HunyuanOCR\nUpload an image and ask OCR questions.")
    
        chat = gr.ChatInterface(
            fn=ocr_chat,
            additional_inputs=[
                gr.Image(
                    label="Upload Image",
                    type="filepath"
                )
            ],
            title="Hunyuan OCR",
            description="Ask questions about the uploaded document",
        )
    
    demo.launch()


if __name__ == "__main__":
    main()