docuforge-local 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docuforge/__init__.py +0 -0
- docuforge/analytics/__init__.py +0 -0
- docuforge/analytics/tokenizer.py +39 -0
- docuforge/cli.py +282 -0
- docuforge/converters/__init__.py +0 -0
- docuforge/converters/pdf_to_md.py +54 -0
- docuforge/core/__init__.py +0 -0
- docuforge/core/document_processor.py +21 -0
- docuforge/core/exceptions.py +0 -0
- docuforge/core/file_handler.py +14 -0
- docuforge/core/validation.py +0 -0
- docuforge/mcp/__init__.py +0 -0
- docuforge/mcp/server.py +128 -0
- docuforge/optimizer/__init__.py +0 -0
- docuforge/optimizer/headers_footers.py +58 -0
- docuforge/optimizer/pipeline.py +44 -0
- docuforge/optimizer/whitespace.py +25 -0
- docuforge_local-0.1.0.dist-info/METADATA +187 -0
- docuforge_local-0.1.0.dist-info/RECORD +23 -0
- docuforge_local-0.1.0.dist-info/WHEEL +5 -0
- docuforge_local-0.1.0.dist-info/entry_points.txt +2 -0
- docuforge_local-0.1.0.dist-info/licenses/LICENSE +661 -0
- docuforge_local-0.1.0.dist-info/top_level.txt +1 -0
docuforge/__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
|
|
2
|
+
import tiktoken
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def estimate_tokens(text: str, encoding_name: str = "cl100k_base") -> int:
|
|
6
|
+
"""
|
|
7
|
+
Estimate the number of tokens in a text string.
|
|
8
|
+
|
|
9
|
+
Uses a local tokenizer. This is an estimate for models
|
|
10
|
+
that use the selected encoding, not an exact Claude or
|
|
11
|
+
Gemini token count.
|
|
12
|
+
"""
|
|
13
|
+
if not text:
|
|
14
|
+
return 0
|
|
15
|
+
|
|
16
|
+
encoding = tiktoken.get_encoding(encoding_name)
|
|
17
|
+
return len(encoding.encode(text))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def compare_token_counts(original: str, optimized: str) -> dict:
|
|
21
|
+
"""Compare token counts before and after optimization."""
|
|
22
|
+
|
|
23
|
+
original_tokens = estimate_tokens(original)
|
|
24
|
+
optimized_tokens = estimate_tokens(optimized)
|
|
25
|
+
|
|
26
|
+
reduction = original_tokens - optimized_tokens
|
|
27
|
+
|
|
28
|
+
percentage = (
|
|
29
|
+
(reduction / original_tokens) * 100
|
|
30
|
+
if original_tokens > 0
|
|
31
|
+
else 0
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
"original_tokens": original_tokens,
|
|
36
|
+
"optimized_tokens": optimized_tokens,
|
|
37
|
+
"tokens_reduced": reduction,
|
|
38
|
+
"reduction_percentage": round(percentage, 2),
|
|
39
|
+
}
|
docuforge/cli.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
CONFIG_DIR = Path.home() / ".docuforge"
|
|
10
|
+
CONFIG_FILE = CONFIG_DIR / "config.toml"
|
|
11
|
+
|
|
12
|
+
def get_document_directory():
|
|
13
|
+
import tomllib
|
|
14
|
+
|
|
15
|
+
if not CONFIG_FILE.exists():
|
|
16
|
+
return None
|
|
17
|
+
|
|
18
|
+
with CONFIG_FILE.open("rb") as file:
|
|
19
|
+
config = tomllib.load(file)
|
|
20
|
+
|
|
21
|
+
directory = config.get("documents", {}).get("allowed_directory")
|
|
22
|
+
|
|
23
|
+
if not directory:
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
return Path(directory).expanduser().resolve()
|
|
27
|
+
|
|
28
|
+
def setup():
|
|
29
|
+
"""Initialize DocuForge safely for the current user."""
|
|
30
|
+
|
|
31
|
+
default_dir = Path.home() / "Documents" / "DocuForge"
|
|
32
|
+
|
|
33
|
+
print("\nWelcome to DocuForge setup!")
|
|
34
|
+
print("Choose where DocuForge should access your documents.")
|
|
35
|
+
print("Press Enter to use the default directory.\n")
|
|
36
|
+
|
|
37
|
+
while True:
|
|
38
|
+
directory_input = input(
|
|
39
|
+
f"Document directory [{default_dir}]: "
|
|
40
|
+
).strip()
|
|
41
|
+
|
|
42
|
+
if not directory_input:
|
|
43
|
+
document_dir = default_dir
|
|
44
|
+
else:
|
|
45
|
+
document_dir = Path(directory_input).expanduser()
|
|
46
|
+
|
|
47
|
+
# Reject relative paths to prevent accidental input.
|
|
48
|
+
if not document_dir.is_absolute():
|
|
49
|
+
print(
|
|
50
|
+
"\nInvalid directory. Please enter an absolute path, "
|
|
51
|
+
"such as ~/Documents/DocuForge."
|
|
52
|
+
)
|
|
53
|
+
continue
|
|
54
|
+
|
|
55
|
+
document_dir = document_dir.resolve()
|
|
56
|
+
|
|
57
|
+
# Ask before creating a new directory.
|
|
58
|
+
if document_dir.exists() and not document_dir.is_dir():
|
|
59
|
+
print("\nError: The selected path is a file, not a directory.")
|
|
60
|
+
continue
|
|
61
|
+
|
|
62
|
+
if not document_dir.exists():
|
|
63
|
+
print(f"\nDirectory does not exist: {document_dir}")
|
|
64
|
+
create = input("Create this directory? [y/N]: ").strip().lower()
|
|
65
|
+
|
|
66
|
+
if create not in ("y", "yes"):
|
|
67
|
+
print("Setup cancelled. No changes were made.")
|
|
68
|
+
return
|
|
69
|
+
|
|
70
|
+
# Confirm the final configuration.
|
|
71
|
+
print(f"\nDocuForge will access:\n{document_dir}")
|
|
72
|
+
|
|
73
|
+
confirm = input("Continue with this directory? [y/N]: ").strip().lower()
|
|
74
|
+
|
|
75
|
+
if confirm not in ("y", "yes"):
|
|
76
|
+
print("Setup cancelled. No changes were made.")
|
|
77
|
+
return
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
document_dir.mkdir(parents=True, exist_ok=True)
|
|
81
|
+
|
|
82
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
83
|
+
|
|
84
|
+
import json
|
|
85
|
+
|
|
86
|
+
config_content = (
|
|
87
|
+
"[documents]\n"
|
|
88
|
+
f"allowed_directory = {json.dumps(str(document_dir))}\n"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
CONFIG_FILE.write_text(config_content, encoding="utf-8")
|
|
92
|
+
|
|
93
|
+
print("\nDocuForge setup completed successfully!")
|
|
94
|
+
print(f"Document directory: {document_dir}")
|
|
95
|
+
print(f"Configuration: {CONFIG_FILE}")
|
|
96
|
+
return
|
|
97
|
+
|
|
98
|
+
except OSError as error:
|
|
99
|
+
print(f"\nCould not configure directory: {error}")
|
|
100
|
+
return
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def install_cursor_mcp(document_dir: Path):
|
|
104
|
+
"""Register DocuForge with Cursor without overwriting other MCP servers."""
|
|
105
|
+
|
|
106
|
+
cursor_config_dir = Path.home() / ".cursor"
|
|
107
|
+
cursor_config_file = cursor_config_dir / "mcp.json"
|
|
108
|
+
|
|
109
|
+
cursor_config_dir.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
|
|
111
|
+
# Load existing configuration, if present.
|
|
112
|
+
if cursor_config_file.exists():
|
|
113
|
+
try:
|
|
114
|
+
config = json.loads(
|
|
115
|
+
cursor_config_file.read_text(encoding="utf-8")
|
|
116
|
+
)
|
|
117
|
+
except json.JSONDecodeError as error:
|
|
118
|
+
print(f"Invalid Cursor MCP configuration: {error}")
|
|
119
|
+
print("Please fix mcp.json before continuing.")
|
|
120
|
+
return
|
|
121
|
+
else:
|
|
122
|
+
config = {}
|
|
123
|
+
|
|
124
|
+
if not isinstance(config, dict):
|
|
125
|
+
print("Invalid Cursor configuration: expected a JSON object.")
|
|
126
|
+
return
|
|
127
|
+
|
|
128
|
+
# Preserve existing MCP server configurations.
|
|
129
|
+
servers = config.setdefault("mcpServers", {})
|
|
130
|
+
|
|
131
|
+
if not isinstance(servers, dict):
|
|
132
|
+
print("Invalid Cursor configuration: mcpServers must be an object.")
|
|
133
|
+
return
|
|
134
|
+
|
|
135
|
+
# Build the DocuForge MCP configuration.
|
|
136
|
+
servers["docuforge"] = {
|
|
137
|
+
"command": sys.executable,
|
|
138
|
+
"args": [
|
|
139
|
+
"-m",
|
|
140
|
+
"docuforge.mcp.server",
|
|
141
|
+
],
|
|
142
|
+
"env": {
|
|
143
|
+
"DOCUFORGE_ALLOWED_DIR": str(document_dir),
|
|
144
|
+
},
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
# Write atomically to avoid leaving a partially written config.
|
|
148
|
+
temporary_file = cursor_config_file.with_suffix(".json.tmp")
|
|
149
|
+
|
|
150
|
+
try:
|
|
151
|
+
temporary_file.write_text(
|
|
152
|
+
json.dumps(config, indent=2) + "\n",
|
|
153
|
+
encoding="utf-8",
|
|
154
|
+
)
|
|
155
|
+
temporary_file.replace(cursor_config_file)
|
|
156
|
+
|
|
157
|
+
print("\nDocuForge MCP integration configured for Cursor!")
|
|
158
|
+
print(f"Configuration: {cursor_config_file}")
|
|
159
|
+
print(f"Python interpreter: {sys.executable}")
|
|
160
|
+
print(f"Allowed documents: {document_dir}")
|
|
161
|
+
print("\nRestart Cursor to load the MCP server.")
|
|
162
|
+
|
|
163
|
+
except OSError as error:
|
|
164
|
+
if temporary_file.exists():
|
|
165
|
+
temporary_file.unlink()
|
|
166
|
+
|
|
167
|
+
print(f"Could not update Cursor configuration: {error}")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def install_mcp(client: str):
|
|
171
|
+
if client == "cursor":
|
|
172
|
+
document_dir = get_document_directory()
|
|
173
|
+
|
|
174
|
+
if document_dir is None or not document_dir.is_dir():
|
|
175
|
+
print("DocuForge is not configured correctly.")
|
|
176
|
+
print("Run 'docuforge setup' first.")
|
|
177
|
+
return
|
|
178
|
+
|
|
179
|
+
install_cursor_mcp(document_dir)
|
|
180
|
+
return
|
|
181
|
+
|
|
182
|
+
if client != "claude":
|
|
183
|
+
print(f"Unsupported MCP client: {client}")
|
|
184
|
+
return
|
|
185
|
+
|
|
186
|
+
document_dir = get_document_directory()
|
|
187
|
+
|
|
188
|
+
if document_dir is None or not document_dir.is_dir():
|
|
189
|
+
print("DocuForge is not configured correctly.")
|
|
190
|
+
print("Run 'docuforge setup' first.")
|
|
191
|
+
return
|
|
192
|
+
|
|
193
|
+
claude = shutil.which("claude")
|
|
194
|
+
|
|
195
|
+
if not claude:
|
|
196
|
+
print("Claude Code CLI was not found.")
|
|
197
|
+
return
|
|
198
|
+
|
|
199
|
+
base_command = [
|
|
200
|
+
claude,
|
|
201
|
+
"mcp",
|
|
202
|
+
"add",
|
|
203
|
+
"--transport", "stdio",
|
|
204
|
+
"--scope", "user",
|
|
205
|
+
"docuforge",
|
|
206
|
+
"-e", f"DOCUFORGE_ALLOWED_DIR={document_dir}",
|
|
207
|
+
"--",
|
|
208
|
+
sys.executable,
|
|
209
|
+
"-m", "docuforge.mcp.server",
|
|
210
|
+
]
|
|
211
|
+
|
|
212
|
+
try:
|
|
213
|
+
existing = subprocess.run(
|
|
214
|
+
[claude, "mcp", "get", "docuforge"],
|
|
215
|
+
capture_output=True,
|
|
216
|
+
text=True,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
if existing.returncode == 0:
|
|
220
|
+
print("Existing DocuForge MCP registration found.")
|
|
221
|
+
print("Removing old registration...")
|
|
222
|
+
|
|
223
|
+
subprocess.run(
|
|
224
|
+
[claude, "mcp", "remove", "docuforge"],
|
|
225
|
+
check=True,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
print("Installing DocuForge MCP integration...")
|
|
229
|
+
subprocess.run(base_command, check=True)
|
|
230
|
+
|
|
231
|
+
print("\nDocuForge MCP integration installed successfully!")
|
|
232
|
+
|
|
233
|
+
except subprocess.CalledProcessError as error:
|
|
234
|
+
print(f"\nMCP installation failed: {error}")
|
|
235
|
+
|
|
236
|
+
def main():
|
|
237
|
+
parser = argparse.ArgumentParser(
|
|
238
|
+
prog="docuforge",
|
|
239
|
+
description="Local-first document intelligence for AI assistants",
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
243
|
+
|
|
244
|
+
subparsers.add_parser(
|
|
245
|
+
"setup",
|
|
246
|
+
help="Configure DocuForge for your machine",
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
mcp_parser = subparsers.add_parser(
|
|
250
|
+
"mcp",
|
|
251
|
+
help="Manage MCP integration",
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
mcp_subparsers = mcp_parser.add_subparsers(
|
|
255
|
+
dest="mcp_command"
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
install_parser = mcp_subparsers.add_parser(
|
|
259
|
+
"install",
|
|
260
|
+
help="Install DocuForge MCP integration",
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
install_parser.add_argument(
|
|
264
|
+
"--client",
|
|
265
|
+
choices=["claude", "cursor"],
|
|
266
|
+
required=True,
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
args = parser.parse_args()
|
|
270
|
+
|
|
271
|
+
if args.command == "setup":
|
|
272
|
+
setup()
|
|
273
|
+
|
|
274
|
+
elif args.command == "mcp" and args.mcp_command == "install":
|
|
275
|
+
install_mcp(args.client)
|
|
276
|
+
|
|
277
|
+
else:
|
|
278
|
+
parser.print_help()
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
if __name__ == "__main__":
|
|
282
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import pymupdf4llm
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def convert_pdf_to_markdown(pdf_path: Path) -> str:
|
|
7
|
+
"""
|
|
8
|
+
Convert a PDF document into Markdown.
|
|
9
|
+
"""
|
|
10
|
+
if not pdf_path.exists():
|
|
11
|
+
raise FileNotFoundError("PDF file does not exist")
|
|
12
|
+
|
|
13
|
+
if not pdf_path.is_file():
|
|
14
|
+
raise ValueError("Provided path is not a file")
|
|
15
|
+
|
|
16
|
+
if pdf_path.suffix.lower() != ".pdf":
|
|
17
|
+
raise ValueError("Only PDF files are supported")
|
|
18
|
+
|
|
19
|
+
markdown = pymupdf4llm.to_markdown(str(pdf_path))
|
|
20
|
+
|
|
21
|
+
if not markdown.strip():
|
|
22
|
+
raise ValueError("No extractable content found")
|
|
23
|
+
|
|
24
|
+
return markdown
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def extract_pdf_pages(pdf_path: Path) -> list[str]:
|
|
28
|
+
"""
|
|
29
|
+
Extract individual PDF pages as Markdown.
|
|
30
|
+
|
|
31
|
+
Keeping pages separate allows the optimizer to detect
|
|
32
|
+
recurring headers and footers.
|
|
33
|
+
"""
|
|
34
|
+
if not pdf_path.exists() or not pdf_path.is_file():
|
|
35
|
+
raise FileNotFoundError("PDF file does not exist")
|
|
36
|
+
|
|
37
|
+
if pdf_path.suffix.lower() != ".pdf":
|
|
38
|
+
raise ValueError("Only PDF files are supported")
|
|
39
|
+
|
|
40
|
+
pages = pymupdf4llm.to_markdown(
|
|
41
|
+
str(pdf_path),
|
|
42
|
+
page_chunks=True,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
extracted_pages = [
|
|
46
|
+
page["text"]
|
|
47
|
+
for page in pages
|
|
48
|
+
if page.get("text", "").strip()
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
if not extracted_pages:
|
|
52
|
+
raise ValueError("No extractable content found")
|
|
53
|
+
|
|
54
|
+
return extracted_pages
|
|
File without changes
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from docuforge.converters.pdf_to_md import extract_pdf_pages
|
|
5
|
+
from docuforge.optimizer.pipeline import optimize_document
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def process_pdf(pdf_path: Path) -> dict:
|
|
9
|
+
"""
|
|
10
|
+
Extract, optimize, and analyze a PDF document.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
pages = extract_pdf_pages(pdf_path)
|
|
14
|
+
|
|
15
|
+
result = optimize_document(pages)
|
|
16
|
+
|
|
17
|
+
return {
|
|
18
|
+
"filename": pdf_path.name,
|
|
19
|
+
"total_pages": len(pages),
|
|
20
|
+
**result,
|
|
21
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def validate_pdf(filename: str, content: bytes) -> None:
|
|
6
|
+
if not filename.lower().endswith(".pdf"):
|
|
7
|
+
raise ValueError("Only PDF files are supported")
|
|
8
|
+
|
|
9
|
+
if not content.startswith(b"%PDF-"):
|
|
10
|
+
raise ValueError("Invalid PDF file")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_output_filename(filename: str) -> str:
|
|
14
|
+
return f"{Path(filename).stem}.md"
|
|
File without changes
|
|
File without changes
|
docuforge/mcp/server.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
|
|
2
|
+
import sys
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
|
8
|
+
|
|
9
|
+
if str(PROJECT_ROOT) not in sys.path:
|
|
10
|
+
sys.path.insert(0, str(PROJECT_ROOT))
|
|
11
|
+
|
|
12
|
+
import pymupdf
|
|
13
|
+
from mcp.server import MCPServer
|
|
14
|
+
|
|
15
|
+
from docuforge.converters.pdf_to_md import convert_pdf_to_markdown
|
|
16
|
+
from docuforge.core.document_processor import process_pdf
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
mcp = MCPServer("DocuForge")
|
|
20
|
+
|
|
21
|
+
# Restrict access to an explicitly configured directory.
|
|
22
|
+
ALLOWED_DIRECTORY = Path(
|
|
23
|
+
os.getenv(
|
|
24
|
+
"DOCUFORGE_ALLOWED_DIR",
|
|
25
|
+
str(Path.home() / "Documents" / "DocuForge"),
|
|
26
|
+
)
|
|
27
|
+
).expanduser().resolve()
|
|
28
|
+
|
|
29
|
+
MAX_PDF_SIZE = 100 * 1024 * 1024
|
|
30
|
+
MAX_OUTPUT_CHARS = 50000
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def validate_access(pdf_path: str) -> Path:
|
|
34
|
+
"""Validate PDF path and enforce the allowed directory."""
|
|
35
|
+
|
|
36
|
+
path = Path(pdf_path).expanduser().resolve()
|
|
37
|
+
|
|
38
|
+
if not path.is_relative_to(ALLOWED_DIRECTORY):
|
|
39
|
+
raise ValueError(
|
|
40
|
+
f"Access denied. Files must be inside: {ALLOWED_DIRECTORY}"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
if not path.exists() or not path.is_file():
|
|
44
|
+
raise FileNotFoundError("PDF file not found")
|
|
45
|
+
|
|
46
|
+
if path.suffix.lower() != ".pdf":
|
|
47
|
+
raise ValueError("Only PDF files are supported")
|
|
48
|
+
|
|
49
|
+
if path.stat().st_size > MAX_PDF_SIZE:
|
|
50
|
+
raise ValueError("PDF exceeds the 100 MB size limit")
|
|
51
|
+
|
|
52
|
+
return path
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@mcp.tool()
|
|
56
|
+
def inspect_pdf(pdf_path: str) -> str:
|
|
57
|
+
"""
|
|
58
|
+
Inspect a PDF and return its metadata, page count and file size.
|
|
59
|
+
The PDF must be inside the configured DocuForge directory.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
path = validate_access(pdf_path)
|
|
63
|
+
|
|
64
|
+
with pymupdf.open(path) as document:
|
|
65
|
+
result = {
|
|
66
|
+
"filename": path.name,
|
|
67
|
+
"pages": len(document),
|
|
68
|
+
"file_size_bytes": path.stat().st_size,
|
|
69
|
+
"title": document.metadata.get("title"),
|
|
70
|
+
"author": document.metadata.get("author"),
|
|
71
|
+
"encrypted": document.is_encrypted,
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return json.dumps(result, indent=2)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@mcp.tool()
|
|
78
|
+
def convert_pdf(pdf_path: str) -> str:
|
|
79
|
+
"""
|
|
80
|
+
Convert a local PDF into Markdown.
|
|
81
|
+
Returns extracted Markdown content.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
path = validate_access(pdf_path)
|
|
85
|
+
|
|
86
|
+
markdown = convert_pdf_to_markdown(path)
|
|
87
|
+
|
|
88
|
+
if len(markdown) > MAX_OUTPUT_CHARS:
|
|
89
|
+
return (
|
|
90
|
+
f"Document converted successfully, but output is too large "
|
|
91
|
+
f"to return in one response ({len(markdown)} characters). "
|
|
92
|
+
"Use the Streamlit application to download the Markdown."
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
return markdown
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@mcp.tool()
|
|
99
|
+
def optimize_pdf(pdf_path: str) -> str:
|
|
100
|
+
"""
|
|
101
|
+
Extract and optimize a PDF, returning Markdown and token statistics.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
path = validate_access(pdf_path)
|
|
105
|
+
|
|
106
|
+
result = process_pdf(path)
|
|
107
|
+
|
|
108
|
+
response = {
|
|
109
|
+
"filename": result["filename"],
|
|
110
|
+
"total_pages": result["total_pages"],
|
|
111
|
+
"original_tokens": result["original_tokens"],
|
|
112
|
+
"optimized_tokens": result["optimized_tokens"],
|
|
113
|
+
"tokens_reduced": result["tokens_reduced"],
|
|
114
|
+
"reduction_percentage": result["reduction_percentage"],
|
|
115
|
+
"optimized_markdown": result["optimized_text"],
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if len(response["optimized_markdown"]) > MAX_OUTPUT_CHARS:
|
|
119
|
+
response["optimized_markdown"] = (
|
|
120
|
+
"Markdown is too large to return in one response. "
|
|
121
|
+
"Use the Streamlit application to download it."
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
return json.dumps(response, indent=2)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
if __name__ == "__main__":
|
|
128
|
+
mcp.run()
|
|
File without changes
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
|
|
2
|
+
import re
|
|
3
|
+
from collections import Counter
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def remove_repeated_headers_footers(
|
|
7
|
+
pages: list[str],
|
|
8
|
+
threshold: float = 0.6,
|
|
9
|
+
) -> list[str]:
|
|
10
|
+
"""
|
|
11
|
+
Remove lines repeated across multiple pages.
|
|
12
|
+
|
|
13
|
+
A line is considered a repeated header/footer candidate
|
|
14
|
+
if it appears on at least `threshold` proportion of pages.
|
|
15
|
+
|
|
16
|
+
Only the first two and last two non-empty lines of each
|
|
17
|
+
page are considered.
|
|
18
|
+
"""
|
|
19
|
+
if not pages:
|
|
20
|
+
return []
|
|
21
|
+
|
|
22
|
+
if not 0 < threshold <= 1:
|
|
23
|
+
raise ValueError("threshold must be greater than 0 and at most 1")
|
|
24
|
+
|
|
25
|
+
candidates = Counter()
|
|
26
|
+
|
|
27
|
+
for page in pages:
|
|
28
|
+
lines = [line.strip() for line in page.splitlines() if line.strip()]
|
|
29
|
+
|
|
30
|
+
boundary_lines = set(lines[:2] + lines[-2:])
|
|
31
|
+
|
|
32
|
+
for line in boundary_lines:
|
|
33
|
+
candidates[line] += 1
|
|
34
|
+
|
|
35
|
+
minimum_occurrences = len(pages) * threshold
|
|
36
|
+
|
|
37
|
+
repeated_lines = {
|
|
38
|
+
line
|
|
39
|
+
for line, count in candidates.items()
|
|
40
|
+
if count >= minimum_occurrences
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
cleaned_pages = []
|
|
44
|
+
|
|
45
|
+
for page in pages:
|
|
46
|
+
cleaned_lines = []
|
|
47
|
+
|
|
48
|
+
for line in page.splitlines():
|
|
49
|
+
normalized = line.strip()
|
|
50
|
+
|
|
51
|
+
if normalized in repeated_lines:
|
|
52
|
+
continue
|
|
53
|
+
|
|
54
|
+
cleaned_lines.append(line)
|
|
55
|
+
|
|
56
|
+
cleaned_pages.append("\n".join(cleaned_lines).strip())
|
|
57
|
+
|
|
58
|
+
return cleaned_pages
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
|
|
2
|
+
from docuforge.optimizer.whitespace import normalize_whitespace
|
|
3
|
+
from docuforge.optimizer.headers_footers import (
|
|
4
|
+
remove_repeated_headers_footers,
|
|
5
|
+
)
|
|
6
|
+
from docuforge.analytics.tokenizer import (
|
|
7
|
+
estimate_tokens,
|
|
8
|
+
compare_token_counts,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def optimize_document(pages: list[str]) -> dict:
|
|
13
|
+
"""
|
|
14
|
+
Optimize extracted document pages and calculate
|
|
15
|
+
character and token statistics.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
original_text = "\n\n".join(pages)
|
|
19
|
+
|
|
20
|
+
cleaned_pages = remove_repeated_headers_footers(pages)
|
|
21
|
+
|
|
22
|
+
optimized_pages = [
|
|
23
|
+
normalize_whitespace(page)
|
|
24
|
+
for page in cleaned_pages
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
optimized_text = "\n\n".join(optimized_pages)
|
|
28
|
+
|
|
29
|
+
token_stats = compare_token_counts(
|
|
30
|
+
original_text,
|
|
31
|
+
optimized_text,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
"pages": optimized_pages,
|
|
36
|
+
"original_text": original_text,
|
|
37
|
+
"optimized_text": optimized_text,
|
|
38
|
+
"original_characters": len(original_text),
|
|
39
|
+
"optimized_characters": len(optimized_text),
|
|
40
|
+
"characters_reduced": (
|
|
41
|
+
len(original_text) - len(optimized_text)
|
|
42
|
+
),
|
|
43
|
+
**token_stats,
|
|
44
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def normalize_whitespace(text: str) -> str:
|
|
6
|
+
"""
|
|
7
|
+
Normalize unnecessary whitespace while preserving
|
|
8
|
+
Markdown structure.
|
|
9
|
+
"""
|
|
10
|
+
if not text:
|
|
11
|
+
return ""
|
|
12
|
+
|
|
13
|
+
# Normalize Windows and old Mac line endings
|
|
14
|
+
text = text.replace("\r\n", "\n").replace("\r", "\n")
|
|
15
|
+
|
|
16
|
+
# Remove trailing spaces from each line
|
|
17
|
+
lines = [line.rstrip() for line in text.split("\n")]
|
|
18
|
+
|
|
19
|
+
text = "\n".join(lines)
|
|
20
|
+
|
|
21
|
+
# Replace 3 or more consecutive blank lines with 2
|
|
22
|
+
text = re.sub(r"\n{4,}", "\n\n\n", text)
|
|
23
|
+
|
|
24
|
+
# Remove leading and trailing whitespace
|
|
25
|
+
return text.strip()
|