j4xfu2mm commited on
Commit
a808206
·
verified ·
1 Parent(s): 98f7ad6

Upload deepseek-ocr2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. deepseek-ocr2.py +115 -0
deepseek-ocr2.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=4.0.0",
5
+ # "huggingface-hub",
6
+ # "pillow",
7
+ # "torch",
8
+ # "transformers>=5.0.0",
9
+ # "tqdm",
10
+ # "accelerate",
11
+ # ]
12
+ # ///
13
+
14
+ """Convert document images to markdown using DeepSeek-OCR-2 via transformers."""
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import sys
20
+ import tempfile
21
+ from datetime import datetime
22
+
23
+ import torch
24
+ from datasets import load_dataset, Dataset
25
+ from huggingface_hub import login
26
+ from PIL import Image
27
+ from tqdm.auto import tqdm
28
+ from transformers import AutoModel, AutoTokenizer
29
+
30
+ PROMPT = "<image>\n<|grounding|>Convert the document to markdown. "
31
+
32
+
33
+ def main(input_dataset: str, output_dataset: str, split: str = "train",
34
+ max_samples: int | None = None, image_column: str = "image"):
35
+
36
+ if not torch.cuda.is_available():
37
+ print("ERROR: CUDA not available. GPU required.")
38
+ sys.exit(1)
39
+ print(f"GPU: {torch.cuda.get_device_name(0)}")
40
+
41
+ token = os.environ.get("HF_TOKEN")
42
+ if token:
43
+ login(token=token)
44
+
45
+ print("Loading model deepseek-ai/DeepSeek-OCR-2...")
46
+ tokenizer = AutoTokenizer.from_pretrained(
47
+ "deepseek-ai/DeepSeek-OCR-2", trust_remote_code=True
48
+ )
49
+ model = AutoModel.from_pretrained(
50
+ "deepseek-ai/DeepSeek-OCR-2",
51
+ trust_remote_code=True,
52
+ use_safetensors=True,
53
+ torch_dtype=torch.bfloat16,
54
+ ).cuda()
55
+
56
+ print(f"Loading dataset {input_dataset}...")
57
+ ds = load_dataset(input_dataset, split=split)
58
+ if max_samples:
59
+ ds = ds.select(range(min(max_samples, len(ds))))
60
+ print(f"Processing {len(ds)} samples...")
61
+
62
+ results = []
63
+ with tempfile.TemporaryDirectory() as tmpdir:
64
+ for i, row in enumerate(tqdm(ds)):
65
+ img_path = os.path.join(tmpdir, f"img_{i}.jpg")
66
+ img = row[image_column]
67
+ if isinstance(img, dict):
68
+ img = Image.open(__import__("io").BytesIO(img["bytes"]))
69
+ img.save(img_path, format="JPEG", quality=95)
70
+
71
+ try:
72
+ out = model.infer(
73
+ tokenizer,
74
+ prompt=PROMPT,
75
+ image_file=img_path,
76
+ output_path=tmpdir,
77
+ base_size=1024,
78
+ image_size=768,
79
+ crop_mode=True,
80
+ save_results=False,
81
+ )
82
+ if i == 0:
83
+ print(f"[DEBUG] out type={type(out)}, value={repr(out)[:200]}")
84
+ markdown = out if isinstance(out, str) else str(out)
85
+ except Exception as e:
86
+ print(f"Error on sample {i}: {e}")
87
+ markdown = ""
88
+
89
+ results.append({
90
+ "image": row[image_column],
91
+ "gt_json": row.get("gt_json", ""),
92
+ "markdown": markdown,
93
+ "inference_info": json.dumps([{
94
+ "column_name": "markdown",
95
+ "model_id": "deepseek-ai/DeepSeek-OCR-2",
96
+ "processing_date": datetime.now().strftime("%Y-%m-%d"),
97
+ "backend": "transformers",
98
+ }]),
99
+ })
100
+
101
+ print(f"Pushing to {output_dataset}...")
102
+ Dataset.from_list(results).push_to_hub(output_dataset, private=False)
103
+ print(f"Done → https://huggingface.co/datasets/{output_dataset}")
104
+
105
+
106
+ if __name__ == "__main__":
107
+ parser = argparse.ArgumentParser()
108
+ parser.add_argument("input_dataset")
109
+ parser.add_argument("output_dataset")
110
+ parser.add_argument("--split", default="train")
111
+ parser.add_argument("--max-samples", type=int, default=None)
112
+ parser.add_argument("--image-column", default="image")
113
+ args = parser.parse_args()
114
+ main(args.input_dataset, args.output_dataset, args.split,
115
+ args.max_samples, args.image_column)