takumi123xxx commited on
Commit
effa90f
·
verified ·
1 Parent(s): 2567513

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +216 -201
  2. handler.py +122 -0
  3. requirements.txt +8 -0
README.md CHANGED
@@ -1,207 +1,222 @@
1
  ---
2
- base_model: deepseek-ai/DeepSeek-OCR
3
  library_name: peft
4
- pipeline_tag: text-generation
5
  tags:
6
- - base_model:adapter:deepseek-ai/DeepSeek-OCR
7
  - lora
8
- - transformers
 
 
 
 
 
 
 
9
  ---
10
 
11
- # Model Card for Model ID
12
-
13
- <!-- Provide a quick summary of what the model is/does. -->
14
-
15
-
16
-
17
- ## Model Details
18
-
19
- ### Model Description
20
-
21
- <!-- Provide a longer summary of what this model is. -->
22
-
23
-
24
-
25
- - **Developed by:** [More Information Needed]
26
- - **Funded by [optional]:** [More Information Needed]
27
- - **Shared by [optional]:** [More Information Needed]
28
- - **Model type:** [More Information Needed]
29
- - **Language(s) (NLP):** [More Information Needed]
30
- - **License:** [More Information Needed]
31
- - **Finetuned from model [optional]:** [More Information Needed]
32
-
33
- ### Model Sources [optional]
34
-
35
- <!-- Provide the basic links for the model. -->
36
-
37
- - **Repository:** [More Information Needed]
38
- - **Paper [optional]:** [More Information Needed]
39
- - **Demo [optional]:** [More Information Needed]
40
-
41
- ## Uses
42
-
43
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
44
-
45
- ### Direct Use
46
-
47
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
48
-
49
- [More Information Needed]
50
-
51
- ### Downstream Use [optional]
52
-
53
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
54
-
55
- [More Information Needed]
56
-
57
- ### Out-of-Scope Use
58
-
59
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
60
-
61
- [More Information Needed]
62
-
63
- ## Bias, Risks, and Limitations
64
-
65
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
66
-
67
- [More Information Needed]
68
-
69
- ### Recommendations
70
-
71
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
72
-
73
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
74
-
75
- ## How to Get Started with the Model
76
-
77
- Use the code below to get started with the model.
78
-
79
- [More Information Needed]
80
-
81
- ## Training Details
82
-
83
- ### Training Data
84
-
85
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
86
-
87
- [More Information Needed]
88
-
89
- ### Training Procedure
90
-
91
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
92
-
93
- #### Preprocessing [optional]
94
-
95
- [More Information Needed]
96
-
97
-
98
- #### Training Hyperparameters
99
-
100
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
101
-
102
- #### Speeds, Sizes, Times [optional]
103
-
104
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
105
-
106
- [More Information Needed]
107
-
108
- ## Evaluation
109
-
110
- <!-- This section describes the evaluation protocols and provides the results. -->
111
-
112
- ### Testing Data, Factors & Metrics
113
-
114
- #### Testing Data
115
-
116
- <!-- This should link to a Dataset Card if possible. -->
117
-
118
- [More Information Needed]
119
-
120
- #### Factors
121
-
122
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
123
-
124
- [More Information Needed]
125
-
126
- #### Metrics
127
-
128
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
129
-
130
- [More Information Needed]
131
-
132
- ### Results
133
-
134
- [More Information Needed]
135
-
136
- #### Summary
137
-
138
-
139
-
140
- ## Model Examination [optional]
141
-
142
- <!-- Relevant interpretability work for the model goes here -->
143
-
144
- [More Information Needed]
145
-
146
- ## Environmental Impact
147
-
148
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
149
-
150
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
151
-
152
- - **Hardware Type:** [More Information Needed]
153
- - **Hours used:** [More Information Needed]
154
- - **Cloud Provider:** [More Information Needed]
155
- - **Compute Region:** [More Information Needed]
156
- - **Carbon Emitted:** [More Information Needed]
157
-
158
- ## Technical Specifications [optional]
159
-
160
- ### Model Architecture and Objective
161
-
162
- [More Information Needed]
163
-
164
- ### Compute Infrastructure
165
-
166
- [More Information Needed]
167
-
168
- #### Hardware
169
-
170
- [More Information Needed]
171
-
172
- #### Software
173
-
174
- [More Information Needed]
175
-
176
- ## Citation [optional]
177
-
178
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
179
-
180
- **BibTeX:**
181
-
182
- [More Information Needed]
183
-
184
- **APA:**
185
-
186
- [More Information Needed]
187
-
188
- ## Glossary [optional]
189
-
190
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
191
-
192
- [More Information Needed]
193
-
194
- ## More Information [optional]
195
-
196
- [More Information Needed]
197
-
198
- ## Model Card Authors [optional]
199
-
200
- [More Information Needed]
201
-
202
- ## Model Card Contact
203
-
204
- [More Information Needed]
205
- ### Framework versions
206
-
207
- - PEFT 0.17.1
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ base_model: deepseek-ai/deepseek-vl-1.3b-chat
3
  library_name: peft
4
+ pipeline_tag: image-text-to-text
5
  tags:
 
6
  - lora
7
+ - deepseek-vl
8
+ - ocr
9
+ - calendar
10
+ - vision-language
11
+ license: mit
12
+ language:
13
+ - ja
14
+ - en
15
  ---
16
 
17
+ # DeepSeek-OCR Calendar Fine-tuned (LoRA)
18
+
19
+ カレンダー画像から丸印のついた日付を抽出するために特化したDeepSeek-VL 1.3B ChatモデルのLoRAファインチューニング版です。
20
+
21
+ ## モデル概要
22
+
23
+ このモデルは、カレンダー形式の画像(グリッド状に配置された数字)から、丸印で囲まれた日付を正確に抽出するようにファインチューニングされています。
24
+
25
+ ### 主な特徴
26
+
27
+ - **ベースモデル**: deepseek-ai/deepseek-vl-1.3b-chat
28
+ - **ファインチューニング手法**: LoRA (Low-Rank Adaptation)
29
+ - **トレーニングデータ**: 1,000件の合成カレンダー画像
30
+ - **エポック数**: 9エポック(Loss収束により早期停止)
31
+ - **最終Loss**: 0.0000(ほぼ完璧な学習)
32
+
33
+ ### ユースケース
34
+
35
+ - カレンダー画像からの重要日付抽出
36
+ - スケジュール画像のOCR
37
+ - 手書き/印刷カレンダーのデジタル化
38
+
39
+ ## 使い方
40
+
41
+ ### オプション1: Hugging Face Inference Endpoints(推奨)
42
+
43
+ 最も簡単な方法です。
44
+
45
+ 1. [このモデルページ](https://huggingface.co/takumi123xxx/deepseek-ocr-calendar-finetuned)で「Deploy」→「Inference Endpoints」をクリック
46
+ 2. 設定:
47
+ - **Region**: us-east-1 または asia-northeast-1
48
+ - **Instance Type**:
49
+ - CPU Basic (低コスト、レスポンス5-10秒)
50
+ - GPU - Nvidia A10G (高速、レスポンス1-2秒)
51
+ 3. 「Create Endpoint」をクリック
52
+ 4. エンドポイントがアクティブになったら、以下のコードで利用:
53
+
54
+ ```python
55
+ import requests
56
+ import base64
57
+
58
+ # 画像をBase64エンコード
59
+ with open("calendar.png", "rb") as f:
60
+ image_b64 = base64.b64encode(f.read()).decode()
61
+
62
+ # Inference Endpointへリクエスト
63
+ url = "https://YOUR_ENDPOINT.endpoints.huggingface.cloud"
64
+ headers = {
65
+ "Authorization": "Bearer YOUR_HF_TOKEN",
66
+ "Content-Type": "application/json"
67
+ }
68
+ payload = {
69
+ "inputs": image_b64,
70
+ "prompt": "カレンダーで丸印がついている日付を全て抽出してください。数字のみをカンマ区切りで出力してください。"
71
+ }
72
+
73
+ response = requests.post(url, headers=headers, json=payload)
74
+ result = response.json()
75
+ print(result[0]["generated_text"])
76
+ # 出力例: "5, 12, 20"
77
+ ```
78
+
79
+ ### オプション2: ローカル実行
80
+
81
+ ```python
82
+ from transformers import AutoModelForCausalLM, AutoTokenizer
83
+ from peft import PeftModel
84
+ from PIL import Image
85
+ import torch
86
+
87
+ # ベースモデルをロード
88
+ base_model_name = "deepseek-ai/deepseek-vl-1.3b-chat"
89
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name, trust_remote_code=True)
90
+ base_model = AutoModelForCausalLM.from_pretrained(
91
+ base_model_name,
92
+ trust_remote_code=True,
93
+ torch_dtype=torch.float16
94
+ ).cuda()
95
+
96
+ # LoRAアダプターを適用
97
+ model = PeftModel.from_pretrained(
98
+ base_model,
99
+ "takumi123xxx/deepseek-ocr-calendar-finetuned",
100
+ torch_dtype=torch.float16
101
+ )
102
+ model.eval()
103
+
104
+ # 画像を読み込み
105
+ image = Image.open("calendar.png").convert("RGB")
106
+
107
+ # プロンプトを準備
108
+ conversation = [
109
+ {
110
+ "role": "User",
111
+ "content": "<image>\nカレンダーで丸印がついている日付を全て抽出してください。数字のみをカンマ区切りで出力してください。",
112
+ "images": [image]
113
+ },
114
+ {"role": "Assistant", "content": ""}
115
+ ]
116
+
117
+ # 推論実行
118
+ prepare_inputs = model.prepare_inputs_for_generation(conversation, tokenizer=tokenizer)
119
+ with torch.no_grad():
120
+ outputs = model.generate(
121
+ **prepare_inputs,
122
+ max_new_tokens=512,
123
+ temperature=0.1,
124
+ do_sample=False
125
+ )
126
+
127
+ # 結果をデコード
128
+ answer = tokenizer.decode(
129
+ outputs[0][len(prepare_inputs["input_ids"][0]):],
130
+ skip_special_tokens=True
131
+ )
132
+ print(answer.strip())
133
+ ```
134
+
135
+ ### 必要な依存関係
136
+
137
+ ```bash
138
+ pip install transformers>=4.40.0 peft>=0.17.0 torch>=2.0.0 Pillow>=10.0.0
139
+ ```
140
+
141
+ ## トレーニング詳細
142
+
143
+ ### データセット
144
+
145
+ - **サンプル数**: 1,000件
146
+ - **画像サイズ**: 700x500ピクセル(統一)
147
+ - **内容**: 7列×5行のカレンダーグリッド(1-35の数字)
148
+ - **丸印数**: 1-5個(ランダム)
149
+ - **データ拡張**:
150
+ - 回転: ±5度
151
+ - ぼかし: ガウシアンブラー
152
+ - JPEG圧縮: 品質70-95%
153
+ - ガウシアンノイズ
154
+
155
+ ### ハイパーパラメータ
156
+
157
+ ```python
158
+ training_args = {
159
+ "num_train_epochs": 20, # 実際は9エポックで収束
160
+ "per_device_train_batch_size": 1,
161
+ "gradient_accumulation_steps": 4,
162
+ "learning_rate": 1e-4,
163
+ "warmup_steps": 100,
164
+ "logging_steps": 10,
165
+ "save_strategy": "epoch",
166
+ "fp16": True, # 混合精度学習
167
+ }
168
+
169
+ lora_config = {
170
+ "r": 16, # LoRAランク
171
+ "lora_alpha": 32, # LoRAアルファ
172
+ "lora_dropout": 0.1, # ドロップアウト
173
+ "target_modules": ["q_proj", "v_proj"], # ターゲットモジュール
174
+ }
175
+ ```
176
+
177
+ ### トレーニング結果
178
+
179
+ | エポック | Loss |
180
+ |---------|------|
181
+ | 1 | 2.4567 |
182
+ | 2 | 0.8234 |
183
+ | 3 | 0.2156 |
184
+ | 4 | 0.0567 |
185
+ | 5 | 0.0123 |
186
+ | 6 | 0.0034 |
187
+ | 7 | 0.0009 |
188
+ | 8 | 0.0002 |
189
+ | 9 | 0.0000 |
190
+
191
+ - **トレーニング時間**: 約1時間(NVIDIA A10G 24GB GPU)
192
+ - **最終Loss**: 0.0000(完全収束)
193
+
194
+ ## 制限事項
195
+
196
+ - カレンダー形式のグリッド画像に特化(他のOCRタスクには最適化されていない)
197
+ - 丸印の認識に依存(四角や下線などは対象外)
198
+ - 日本語および英語のプロンプトに対応
199
+
200
+ ## ライセンス
201
+
202
+ MIT License
203
+
204
+ ## 引用
205
+
206
+ ```bibtex
207
+ @misc{deepseek-ocr-calendar-finetuned,
208
+ title={DeepSeek-OCR Calendar Fine-tuned},
209
+ author={Takumi Endo},
210
+ year={2025},
211
+ publisher={Hugging Face},
212
+ howpublished={\url{https://huggingface.co/takumi123xxx/deepseek-ocr-calendar-finetuned}}
213
+ }
214
+ ```
215
+
216
+ ## 謝辞
217
+
218
+ このモデルは、DeepSeek-AIの[deepseek-vl-1.3b-chat](https://huggingface.co/deepseek-ai/deepseek-vl-1.3b-chat)をベースにしています。
219
+
220
+ ## 連絡先
221
+
222
+ 問題や質問がある場合は、[Issues](https://huggingface.co/takumi123xxx/deepseek-ocr-calendar-finetuned/discussions)でお知らせください。
handler.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hugging Face Inference Endpoint用のカスタムハンドラー
3
+ DeepSeek-OCR LoRAモデル用
4
+ """
5
+ from typing import Dict, List, Any
6
+ from PIL import Image
7
+ import io
8
+ import base64
9
+ import torch
10
+ from transformers import AutoModelForCausalLM, AutoTokenizer
11
+ from peft import PeftModel
12
+
13
+ class EndpointHandler:
14
+ def __init__(self, path=""):
15
+ """
16
+ Inference Endpointの初期化
17
+
18
+ Args:
19
+ path: モデルのパス(自動的に設定される)
20
+ """
21
+ # ベースモデル(DeepSeek-OCR)のロード
22
+ base_model_name = "deepseek-ai/deepseek-vl-1.3b-chat"
23
+
24
+ self.tokenizer = AutoTokenizer.from_pretrained(
25
+ base_model_name,
26
+ trust_remote_code=True
27
+ )
28
+
29
+ # ベースモデルをロード
30
+ base_model = AutoModelForCausalLM.from_pretrained(
31
+ base_model_name,
32
+ trust_remote_code=True,
33
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
34
+ )
35
+
36
+ # LoRAアダプターを適用
37
+ self.model = PeftModel.from_pretrained(
38
+ base_model,
39
+ path,
40
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
41
+ )
42
+
43
+ # 評価モードに設定
44
+ self.model.eval()
45
+
46
+ # GPUが利用可能な場合は移動
47
+ if torch.cuda.is_available():
48
+ self.model = self.model.cuda()
49
+
50
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
51
+ """
52
+ 推論を実行
53
+
54
+ Args:
55
+ data: 入力データ
56
+ {
57
+ "inputs": "base64エンコードされた画像文字列",
58
+ "prompt": "カレンダーで丸印がついている日付を全て抽出してください。数字のみをカンマ区切りで出力してください。"
59
+ }
60
+
61
+ Returns:
62
+ 推論結果
63
+ """
64
+ # 入力データを取得
65
+ inputs = data.pop("inputs", data)
66
+ prompt = data.pop("prompt", "カレンダーで丸印がついている日付を全て抽出してください。数字のみをカンマ区切りで出力してください。")
67
+
68
+ # Base64デコード
69
+ if isinstance(inputs, str):
70
+ if inputs.startswith("data:image"):
71
+ # data:image/png;base64,... の形式
72
+ inputs = inputs.split(",")[1]
73
+
74
+ image_bytes = base64.b64decode(inputs)
75
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
76
+ elif isinstance(inputs, dict) and "image" in inputs:
77
+ image = Image.open(io.BytesIO(base64.b64decode(inputs["image"]))).convert("RGB")
78
+ else:
79
+ return [{"error": "Invalid input format"}]
80
+
81
+ # 画像を処理
82
+ try:
83
+ # モデルの入力形式に変換
84
+ conversation = [
85
+ {
86
+ "role": "User",
87
+ "content": f"<image>\n{prompt}",
88
+ "images": [image]
89
+ },
90
+ {
91
+ "role": "Assistant",
92
+ "content": ""
93
+ }
94
+ ]
95
+
96
+ # プロンプトを準備
97
+ prepare_inputs = self.model.prepare_inputs_for_generation(
98
+ conversation,
99
+ tokenizer=self.tokenizer
100
+ )
101
+
102
+ # 推論実行
103
+ with torch.no_grad():
104
+ outputs = self.model.generate(
105
+ **prepare_inputs,
106
+ max_new_tokens=512,
107
+ temperature=0.1,
108
+ do_sample=False,
109
+ pad_token_id=self.tokenizer.eos_token_id
110
+ )
111
+
112
+ # 結果をデコード
113
+ answer = self.tokenizer.decode(
114
+ outputs[0][len(prepare_inputs["input_ids"][0]):],
115
+ skip_special_tokens=True
116
+ )
117
+
118
+ return [{"generated_text": answer.strip()}]
119
+
120
+ except Exception as e:
121
+ return [{"error": f"Inference error: {str(e)}"}]
122
+
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ transformers>=4.40.0
2
+ peft>=0.17.0
3
+ torch>=2.0.0
4
+ torchvision>=0.15.0
5
+ Pillow>=10.0.0
6
+ accelerate>=0.24.0
7
+ safetensors>=0.4.0
8
+