forked from Bogdanovich77/DeekSeek-OCR---Dockerized-API
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdf_to_custom_prompt.py
More file actions
281 lines (227 loc) · 10.7 KB
/
pdf_to_custom_prompt.py
File metadata and controls
281 lines (227 loc) · 10.7 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#!/usr/bin/env python3
"""
PDF to Custom Prompt Processor
This application scans the /data folder for PDF files and converts them to Markdown format
using the DeepSeek OCR API at localhost:8000 with a custom prompt loaded from
custom_prompt.yaml in the project root.
This version returns the raw model response without any post-processing.
"""
import os
import sys
import glob
import logging
import base64
import json
import requests
import yaml
from pathlib import Path
from typing import List, Optional, Dict, Any
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('pdf_processor.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class Colors:
"""ANSI color codes for terminal output"""
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
RESET = '\033[0m'
class PDFToCustomPromptProcessor:
"""Processor for converting PDF files to Markdown using DeepSeek OCR API with custom prompt"""
def __init__(self, data_folder: str = "data", api_base_url: str = "http://localhost:8000",
custom_prompt_file: str = "custom_prompt.yaml"):
"""
Initialize the PDF processor
Args:
data_folder: Path to the folder containing PDF files
api_base_url: Base URL of the DeepSeek OCR API
custom_prompt_file: Path to the YAML file containing the custom prompt
"""
self.data_folder = Path(data_folder)
self.data_folder.mkdir(exist_ok=True)
self.api_base_url = api_base_url
self.custom_prompt_file = custom_prompt_file
# Load custom prompt from YAML file
self.custom_prompt = self._load_custom_prompt()
# Test API connection
if not self._test_api_connection():
raise ConnectionError(f"Cannot connect to API at {api_base_url}")
def _load_custom_prompt(self) -> str:
"""
Load custom prompt from YAML file
Returns:
The custom prompt string
Raises:
FileNotFoundError: If the custom prompt file doesn't exist
yaml.YAMLError: If the YAML file is malformed
KeyError: If the prompt key is not found in the YAML file
"""
try:
with open(self.custom_prompt_file, 'r', encoding='utf-8') as file:
config = yaml.safe_load(file)
if 'prompt' not in config:
raise KeyError(f"'prompt' key not found in {self.custom_prompt_file}")
prompt = config['prompt']
logger.info(f"Loaded custom prompt from {self.custom_prompt_file}: {prompt}")
return prompt
except FileNotFoundError:
logger.error(f"Custom prompt file not found: {self.custom_prompt_file}")
raise
except yaml.YAMLError as e:
logger.error(f"Error parsing {self.custom_prompt_file}: {str(e)}")
raise
except KeyError as e:
logger.error(f"Missing required key in {self.custom_prompt_file}: {str(e)}")
raise
def _test_api_connection(self) -> bool:
"""Test if the API is accessible"""
try:
response = requests.get(f"{self.api_base_url}/docs", timeout=5)
if response.status_code == 200:
logger.info("API connection successful")
return True
else:
logger.error(f"API returned status code: {response.status_code}")
return False
except requests.exceptions.RequestException as e:
logger.error(f"API connection failed: {str(e)}")
return False
def _get_api_endpoints(self) -> Dict[str, str]:
"""Get available API endpoints"""
try:
response = requests.get(f"{self.api_base_url}/openapi.json", timeout=5)
if response.status_code == 200:
openapi_spec = response.json()
endpoints = {}
for path, methods in openapi_spec.get("paths", {}).items():
for method, details in methods.items():
if method.upper() in ["POST", "GET"]:
operation_id = details.get("operationId", "")
if "pdf" in operation_id.lower() or "ocr" in operation_id.lower():
endpoints[operation_id] = f"{method.upper()} {path}"
return endpoints
else:
logger.error(f"Failed to get API spec: {response.status_code}")
return {}
except requests.exceptions.RequestException as e:
logger.error(f"Error getting API spec: {str(e)}")
return {}
def _call_ocr_api(self, pdf_path: str) -> Optional[str]:
"""
Call the OCR API to process a PDF file using the custom prompt
Args:
pdf_path: Path to the PDF file
Returns:
Raw markdown content or None if processing failed
"""
try:
# Use the correct endpoint based on the API documentation
endpoint = "/ocr/pdf"
url = f"{self.api_base_url}{endpoint}"
logger.info(f"Processing PDF with API endpoint: {url}")
# Prepare the file for multipart/form-data upload
with open(pdf_path, 'rb') as pdf_file:
files = {'file': (os.path.basename(pdf_path), pdf_file, 'application/pdf')}
# Use custom prompt from YAML file
data = {'prompt': self.custom_prompt}
response = requests.post(url, files=files, data=data, timeout=300)
if response.status_code == 200:
result = response.json()
logger.info(f"Successfully processed PDF using endpoint: {endpoint}")
# Extract markdown content from BatchOCRResponse
if isinstance(result, dict):
# Check if this is a batch response with results
if "results" in result and isinstance(result["results"], list):
# Combine all page results into a single markdown
markdown_content = ""
for page_result in result["results"]:
if isinstance(page_result, dict) and "result" in page_result:
page_content = page_result["result"]
if page_content:
markdown_content += page_content + "\n\n<--- Page Split --->\n\n"
return markdown_content.strip()
# Try common response field names
for field in ["markdown", "content", "text", "result", "output"]:
if field in result:
return result[field]
# If no standard field, return the whole response as string
return json.dumps(result, indent=2)
else:
return str(result)
else:
logger.error(f"API request failed with status {response.status_code}: {response.text}")
return None
except Exception as e:
logger.error(f"Error processing {pdf_path}: {str(e)}")
return None
def convert_pdf_to_markdown(self, pdf_path: str) -> Optional[str]:
"""
Convert a single PDF file to Markdown
Args:
pdf_path: Path to the PDF file
Returns:
Path to the generated Markdown file, or None if conversion failed
"""
try:
logger.info(f"Processing PDF: {pdf_path}")
# Call OCR API
markdown_content = self._call_ocr_api(pdf_path)
if not markdown_content:
logger.error(f"Failed to get markdown content for {pdf_path}")
return None
# Save markdown file with -CUSTOM suffix
pdf_path_obj = Path(pdf_path)
markdown_path = pdf_path_obj.with_name(f"{pdf_path_obj.stem}-CUSTOM.md")
with open(markdown_path, 'w', encoding='utf-8') as f:
f.write(markdown_content)
logger.info(f"Successfully converted {pdf_path} to {markdown_path}")
return str(markdown_path)
except Exception as e:
logger.error(f"Error converting {pdf_path}: {str(e)}")
return None
def scan_and_process_all_pdfs(self) -> List[str]:
"""
Scan the data folder for PDF files and convert all of them to Markdown
Returns:
List of paths to generated Markdown files
"""
# Find all PDF files in the data folder
pdf_files = list(self.data_folder.glob("*.pdf"))
if not pdf_files:
logger.info(f"No PDF files found in {self.data_folder}")
return []
logger.info(f"Found {len(pdf_files)} PDF files to process")
markdown_files = []
for pdf_file in pdf_files:
markdown_file = self.convert_pdf_to_markdown(str(pdf_file))
if markdown_file:
markdown_files.append(markdown_file)
return markdown_files
def main():
"""Main function to run the PDF processor"""
print(f"{Colors.BLUE}PDF to Custom Prompt Processor{Colors.RESET}")
print(f"{Colors.YELLOW}Scanning /data folder for PDF files...{Colors.RESET}")
try:
processor = PDFToCustomPromptProcessor()
markdown_files = processor.scan_and_process_all_pdfs()
if markdown_files:
print(f"\n{Colors.GREEN}Successfully converted {len(markdown_files)} PDF files to Markdown:{Colors.RESET}")
for md_file in markdown_files:
print(f" - {md_file}")
print(f"\n{Colors.BLUE}Used custom prompt: {processor.custom_prompt}{Colors.RESET}")
print(f"{Colors.YELLOW}Note: This is the raw model response without post-processing.{Colors.RESET}")
else:
print(f"{Colors.YELLOW}No PDF files were processed.{Colors.RESET}")
except Exception as e:
logger.error(f"Application error: {str(e)}")
print(f"{Colors.RED}Error: {str(e)}{Colors.RESET}")
sys.exit(1)
if __name__ == "__main__":
main()