File size: 6,585 Bytes
c8b6d1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84ee26b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8b6d1e
 
 
84ee26b
 
 
 
c8b6d1e
 
 
 
 
84ee26b
 
 
 
c8b6d1e
 
84ee26b
 
 
 
 
c8b6d1e
 
 
 
 
84ee26b
c8b6d1e
84ee26b
 
 
 
 
c8b6d1e
84ee26b
 
 
 
 
 
c8b6d1e
84ee26b
c8b6d1e
84ee26b
c8b6d1e
 
84ee26b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8b6d1e
84ee26b
c8b6d1e
 
84ee26b
c8b6d1e
84ee26b
 
 
 
 
c8b6d1e
 
84ee26b
c8b6d1e
 
84ee26b
c8b6d1e
 
 
84ee26b
c8b6d1e
84ee26b
c8b6d1e
 
 
84ee26b
 
 
c8b6d1e
84ee26b
c8b6d1e
84ee26b
 
 
 
c8b6d1e
84ee26b
 
 
c8b6d1e
 
84ee26b
c8b6d1e
 
 
 
 
 
 
 
 
84ee26b
 
c8b6d1e
 
 
84ee26b
c8b6d1e
 
 
84ee26b
 
c8b6d1e
 
 
 
84ee26b
 
c8b6d1e
84ee26b
 
 
 
 
 
 
 
c8b6d1e
 
84ee26b
 
 
 
 
c8b6d1e
cc54a84
c8b6d1e
84ee26b
c8b6d1e
 
84ee26b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8b6d1e
84ee26b
 
 
 
 
 
 
 
 
 
c8b6d1e
 
 
84ee26b
 
c8b6d1e
84ee26b
c8b6d1e
84ee26b
 
 
 
 
 
 
 
c8b6d1e
84ee26b
 
 
c8b6d1e
 
84ee26b
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
import gradio as gr
from transformers import AutoModel, AutoTokenizer
import torch
import spaces
import os
import sys
import tempfile
import shutil
from PIL import Image, ImageDraw, ImageFont, ImageOps
import fitz
import re
import numpy as np
import base64
from io import StringIO, BytesIO

# =====================
# MODEL SETUP
# =====================

MODEL_NAME = "deepseek-ai/DeepSeek-OCR"

tokenizer = AutoTokenizer.from_pretrained(
    MODEL_NAME,
    trust_remote_code=True
)

model = AutoModel.from_pretrained(
    MODEL_NAME,
    _attn_implementation="flash_attention_2",
    torch_dtype=torch.bfloat16,
    trust_remote_code=True,
    use_safetensors=True
)

model = model.eval().cuda()

# =====================
# CONFIGS
# =====================

MODEL_CONFIGS = {
    "Gundam": {"base_size": 1024, "image_size": 640, "crop_mode": True},
}

TASK_PROMPTS = {
    "πŸ“ Free OCR": {
        "prompt": "<image>\nFree OCR.",
        "has_grounding": False
    }
}

# =====================
# OCR CORE
# =====================

def clean_output(text):
    if not text:
        return ""
    return text.strip()

@spaces.GPU(duration=60)
def process_image(image):
    if image is None:
        return "Error: No image provided", "", "", None, []

    if image.mode in ("RGBA", "LA", "P"):
        image = image.convert("RGB")

    image = ImageOps.exif_transpose(image)

    config = MODEL_CONFIGS["Gundam"]
    prompt = TASK_PROMPTS["πŸ“ Free OCR"]["prompt"]

    tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg")
    image.save(tmp.name, "JPEG", quality=95)
    tmp.close()

    out_dir = tempfile.mkdtemp()

    stdout = sys.stdout
    sys.stdout = StringIO()

    model.infer(
        tokenizer=tokenizer,
        prompt=prompt,
        image_file=tmp.name,
        output_path=out_dir,
        base_size=config["base_size"],
        image_size=config["image_size"],
        crop_mode=config["crop_mode"]
    )

    result = "\n".join(
        line for line in sys.stdout.getvalue().split("\n")
        if not any(
            s in line
            for s in ["image:", "other:", "PATCHES", "====", "BASE:", "%|", "torch.Size"]
        )
    ).strip()

    sys.stdout = stdout

    os.unlink(tmp.name)
    shutil.rmtree(out_dir, ignore_errors=True)

    if not result:
        return "No text detected", "", "", None, []

    cleaned = clean_output(result)

    return cleaned, "", result, None, []

@spaces.GPU(duration=60)
def process_pdf(path, page_num):
    doc = fitz.open(path)
    total_pages = len(doc)

    if page_num < 1 or page_num > total_pages:
        doc.close()
        return f"Invalid page number. PDF has {total_pages} pages.", "", "", None, []

    page = doc.load_page(page_num - 1)
    pix = page.get_pixmap(matrix=fitz.Matrix(300 / 72, 300 / 72), alpha=False)
    img = Image.open(BytesIO(pix.tobytes("png")))
    doc.close()

    return process_image(img)

def process_file(path, page_num):
    if not path:
        return "Error: No file uploaded", "", "", None, []

    if path.lower().endswith(".pdf"):
        return process_pdf(path, page_num)
    else:
        return process_image(Image.open(path))

# =====================
# PDF HELPERS
# =====================

def get_pdf_page_count(file_path):
    if not file_path or not file_path.lower().endswith(".pdf"):
        return 1
    doc = fitz.open(file_path)
    count = len(doc)
    doc.close()
    return count

def load_image(file_path, page_num=1):
    if not file_path:
        return None

    if file_path.lower().endswith(".pdf"):
        doc = fitz.open(file_path)
        page_idx = max(0, min(int(page_num) - 1, len(doc) - 1))
        page = doc.load_page(page_idx)
        pix = page.get_pixmap(matrix=fitz.Matrix(300 / 72, 300 / 72), alpha=False)
        img = Image.open(BytesIO(pix.tobytes("png")))
        doc.close()
        return img

    return Image.open(file_path)

def update_page_selector(file_path):
    if not file_path:
        return gr.update(visible=False)

    if file_path.lower().endswith(".pdf"):
        page_count = get_pdf_page_count(file_path)
        return gr.update(
            visible=True,
            maximum=page_count,
            minimum=1,
            value=1,
            label=f"Select Page (1–{page_count})"
        )

    return gr.update(visible=False)

# =====================
# UI
# =====================

with gr.Blocks(theme=gr.themes.Soft(), title="DeepSeek OCR – Free OCR") as demo:
    gr.Markdown("""
    # OCR
    """)

    with gr.Row():
        with gr.Column(scale=1):
            file_in = gr.File(
                label="Upload Image or PDF",
                file_types=["image", ".pdf"],
                type="filepath"
            )

            input_img = gr.Image(
                label="Preview",
                type="pil",
                height=300
            )

            page_selector = gr.Number(
                label="Select Page",
                value=1,
                minimum=1,
                step=1,
                visible=False
            )

            # Hardcoded + locked
            mode = gr.Dropdown(
                ["Gundam"],
                value="Gundam",
                label="Mode",
                interactive=False
            )

            task = gr.Dropdown(
                ["πŸ“ Free OCR"],
                value="πŸ“ Free OCR",
                label="Task",
                interactive=False
            )

            prompt = gr.Textbox(visible=False)

            btn = gr.Button("Extract OCR", variant="primary", size="lg")

        with gr.Column(scale=2):
            with gr.Tabs():
                with gr.Tab("Text"):
                    text_out = gr.Textbox(lines=20)
                with gr.Tab("Raw Output"):
                    raw_out = gr.Textbox(lines=20)

    # =====================
    # EVENTS
    # =====================

    file_in.change(load_image, [file_in, page_selector], [input_img])
    file_in.change(update_page_selector, [file_in], [page_selector])
    page_selector.change(load_image, [file_in, page_selector], [input_img])

    def run(image, file_path, page_num):
        if file_path:
            return process_file(file_path, int(page_num))
        if image is not None:
            return process_image(image)
        return "Error", "", "", None, []

    btn.click(
        run,
        [input_img, file_in, page_selector],
        [text_out, gr.State(), raw_out, gr.State(), gr.State()]
    )

# =====================
# LAUNCH
# =====================

if __name__ == "__main__":
    demo.queue(max_size=20).launch()