tippex 0.0.1__tar.gz

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.
@@ -0,0 +1,5 @@
1
+ .venv/
2
+ __pycache__/
3
+ .DS_Store
4
+ *.pdf
5
+ dist/
tippex-0.0.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dannyfriar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
tippex-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.5
2
+ Name: tippex
3
+ Version: 0.0.1
4
+ Summary: The simplest possible PDF text editor, for macOS
5
+ Project-URL: Homepage, https://github.com/dannyfriar/tippex
6
+ Author-email: dannyfriar <dfriar93@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Environment :: MacOS X
10
+ Classifier: Operating System :: MacOS
11
+ Classifier: Topic :: Office/Business
12
+ Requires-Python: >=3.9
13
+ Requires-Dist: pymupdf>=1.24
14
+ Description-Content-Type: text/markdown
15
+
16
+ # Tippex
17
+
18
+ The simplest possible PDF text editor, for macOS.
19
+
20
+ ## Install
21
+
22
+ ```
23
+ uv tool install tippex
24
+ ```
25
+
26
+ or `pipx install tippex`, or `uv pip install tippex` into an environment of your choice.
27
+
28
+ Without uv or pipx:
29
+
30
+ ```
31
+ curl -fsSL https://raw.githubusercontent.com/dannyfriar/tippex/main/install.sh | sh
32
+ ```
33
+
34
+ ## Use
35
+
36
+ ```
37
+ tippex path/to/file.pdf
38
+ ```
39
+
40
+ A browser tab opens showing the PDF. Click any line of text and type over it.
41
+
42
+ The first time you press **Save…** (or ⌘S), the macOS Save dialog asks where to put the file, suggesting `file-tippexed.pdf` next to the original. After that, **Save** (⌘S) writes to the same file, and **Save As…** (⇧⌘S) picks a new one. The banner under the toolbar always shows where the file is saved, with a link to show it in Finder. Press Ctrl+C in Terminal to quit.
43
+
44
+ The first run creates a local `.venv` and installs [PyMuPDF](https://pymupdf.readthedocs.io/).
45
+
46
+ ## Limitations
47
+
48
+ - Edited lines are redrawn in Helvetica (bold if the original was bold) at the original size and color.
49
+ - Editing is one line at a time; long replacements don't wrap.
50
+ - Scanned PDFs have no text layer, so there is nothing to edit.
tippex-0.0.1/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # Tippex
2
+
3
+ The simplest possible PDF text editor, for macOS.
4
+
5
+ ## Install
6
+
7
+ ```
8
+ uv tool install tippex
9
+ ```
10
+
11
+ or `pipx install tippex`, or `uv pip install tippex` into an environment of your choice.
12
+
13
+ Without uv or pipx:
14
+
15
+ ```
16
+ curl -fsSL https://raw.githubusercontent.com/dannyfriar/tippex/main/install.sh | sh
17
+ ```
18
+
19
+ ## Use
20
+
21
+ ```
22
+ tippex path/to/file.pdf
23
+ ```
24
+
25
+ A browser tab opens showing the PDF. Click any line of text and type over it.
26
+
27
+ The first time you press **Save…** (or ⌘S), the macOS Save dialog asks where to put the file, suggesting `file-tippexed.pdf` next to the original. After that, **Save** (⌘S) writes to the same file, and **Save As…** (⇧⌘S) picks a new one. The banner under the toolbar always shows where the file is saved, with a link to show it in Finder. Press Ctrl+C in Terminal to quit.
28
+
29
+ The first run creates a local `.venv` and installs [PyMuPDF](https://pymupdf.readthedocs.io/).
30
+
31
+ ## Limitations
32
+
33
+ - Edited lines are redrawn in Helvetica (bold if the original was bold) at the original size and color.
34
+ - Editing is one line at a time; long replacements don't wrap.
35
+ - Scanned PDFs have no text layer, so there is nothing to edit.
@@ -0,0 +1,33 @@
1
+ [project]
2
+ name = "tippex"
3
+ dynamic = ["version"]
4
+ description = "The simplest possible PDF text editor, for macOS"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ requires-python = ">=3.9"
8
+ authors = [{ name = "dannyfriar", email = "dfriar93@gmail.com" }]
9
+ dependencies = ["pymupdf>=1.24"]
10
+ classifiers = [
11
+ "Operating System :: MacOS",
12
+ "Environment :: MacOS X",
13
+ "Topic :: Office/Business",
14
+ ]
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/dannyfriar/tippex"
18
+
19
+ [project.scripts]
20
+ tippex = "tippex:main"
21
+
22
+ [build-system]
23
+ requires = ["hatchling"]
24
+ build-backend = "hatchling.build"
25
+
26
+ [tool.hatch.version]
27
+ path = "tippex.py"
28
+
29
+ [tool.hatch.build.targets.wheel]
30
+ only-include = ["tippex.py"]
31
+
32
+ [tool.hatch.build.targets.sdist]
33
+ include = ["tippex.py", "README.md", "LICENSE"]
tippex-0.0.1/tippex.py ADDED
@@ -0,0 +1,201 @@
1
+ """Tippex: minimal PDF text editor for macOS. Usage: tippex file.pdf"""
2
+ import base64, json, subprocess, sys, threading, urllib.parse, webbrowser
3
+ from http.server import BaseHTTPRequestHandler, HTTPServer
4
+ from pathlib import Path
5
+
6
+ import pymupdf
7
+
8
+ __version__ = "0.0.1"
9
+
10
+ SRC = None # the PDF being edited; set in main()
11
+ ORIGINAL = None # its bytes; edits always apply to this, so saving over SRC is safe
12
+ OUT = None # chosen via the Save dialog on first save
13
+ ZOOM = 1.5
14
+
15
+ # Correction-fluid brush painting a white stroke.
16
+ LOGO = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
17
+ <path d="M3 27.5c5-3.5 9-1 15-5" fill="none" stroke="#9aa4b2" stroke-width="5.5" stroke-linecap="round"/>
18
+ <path d="M3 27.5c5-3.5 9-1 15-5" fill="none" stroke="#fff" stroke-width="3.5" stroke-linecap="round"/>
19
+ <g transform="translate(18.5 21.5) rotate(45)">
20
+ <rect x="-3.2" y="-21" width="6.4" height="12" rx="2" fill="#e8413a"/>
21
+ <rect x="-3.2" y="-21" width="2" height="12" rx="1" fill="#ff7a70"/>
22
+ <rect x="-2.9" y="-9.5" width="5.8" height="3" fill="#c9ced6"/>
23
+ <path d="M-2.6 -6.5h5.2c0 3.2-1.2 5.6-2.6 6.8c-1.4-1.2-2.6-3.6-2.6-6.8z" fill="#fff" stroke="#9aa4b2" stroke-width=".8"/>
24
+ </g></svg>"""
25
+ FAVICON = "data:image/svg+xml," + urllib.parse.quote(LOGO)
26
+
27
+
28
+ def lines(page):
29
+ for block in page.get_text("dict")["blocks"]:
30
+ for line in block.get("lines", []):
31
+ spans = [s for s in line["spans"] if s["text"].strip()]
32
+ if spans:
33
+ yield line["bbox"], "".join(s["text"] for s in line["spans"]), spans[0]
34
+
35
+
36
+ def build_page():
37
+ doc = pymupdf.open(stream=ORIGINAL)
38
+ html = []
39
+ for pno, page in enumerate(doc):
40
+ png = base64.b64encode(page.get_pixmap(matrix=pymupdf.Matrix(ZOOM, ZOOM)).tobytes("png")).decode()
41
+ boxes = []
42
+ for i, (bbox, text, span) in enumerate(lines(page)):
43
+ x0, y0, x1, y1 = (v * ZOOM for v in bbox)
44
+ boxes.append(
45
+ f'<input data-p="{pno}" data-i="{i}" value="{escape(text)}" data-orig="{escape(text)}" '
46
+ f'style="left:{x0}px;top:{y0}px;width:{x1 - x0 + 40}px;height:{y1 - y0}px;font-size:{span["size"] * ZOOM * 0.9}px">'
47
+ )
48
+ html.append(f'<div class="page"><img src="data:image/png;base64,{png}">{"".join(boxes)}</div>')
49
+ return TEMPLATE.replace("{{LOGO}}", LOGO).replace("{{FAVICON}}", FAVICON).replace("{{NAME}}", escape(SRC.name)).replace("{{PAGES}}", "".join(html))
50
+
51
+
52
+ def escape(s):
53
+ return s.replace("&", "&amp;").replace('"', "&quot;").replace("<", "&lt;")
54
+
55
+
56
+ def ask_save_path():
57
+ """Show the native macOS Save dialog. Returns a Path, or None if cancelled."""
58
+ default = OUT or SRC.with_name(SRC.stem + "-tippexed.pdf")
59
+ q = lambda v: json.dumps(str(v), ensure_ascii=False)
60
+ script = [
61
+ "activate",
62
+ f'set f to choose file name with prompt "Save edited PDF as:" default name {q(default.name)} '
63
+ f"default location (POSIX file {q(default.parent)})",
64
+ "POSIX path of f",
65
+ ]
66
+ r = subprocess.run(["osascript", *(a for line in script for a in ("-e", line))], capture_output=True, text=True)
67
+ if r.returncode:
68
+ if "-128" in r.stderr: # user pressed Cancel
69
+ return None
70
+ raise RuntimeError(r.stderr.strip())
71
+ path = Path(r.stdout.strip())
72
+ return path if path.suffix.lower() == ".pdf" else path.with_name(path.name + ".pdf")
73
+
74
+
75
+ def save(edits, path):
76
+ doc = pymupdf.open(stream=ORIGINAL)
77
+ for pno in {e["p"] for e in edits}:
78
+ page = doc[pno]
79
+ page_lines = list(lines(page))
80
+ todo = [(page_lines[e["i"]], e["text"]) for e in edits if e["p"] == pno]
81
+ for (bbox, _, _), _ in todo:
82
+ page.add_redact_annot(bbox, fill=False)
83
+ page.apply_redactions(images=pymupdf.PDF_REDACT_IMAGE_NONE, graphics=pymupdf.PDF_REDACT_LINE_ART_NONE)
84
+ for (bbox, _, span), text in todo:
85
+ c = span["color"]
86
+ color = ((c >> 16) / 255, ((c >> 8) & 255) / 255, (c & 255) / 255)
87
+ bold = "bold" in span["font"].lower()
88
+ page.insert_text(span["origin"], text, fontsize=span["size"], fontname="hebo" if bold else "helv", color=color)
89
+ doc.save(path, garbage=3, deflate=True)
90
+
91
+
92
+ class Handler(BaseHTTPRequestHandler):
93
+ def do_GET(self):
94
+ self.reply(build_page().encode(), "text/html")
95
+
96
+ def do_POST(self):
97
+ global OUT
98
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
99
+ if self.path == "/reveal":
100
+ subprocess.run(["open", "-R", str(OUT)])
101
+ return self.reply(b"{}", "application/json")
102
+ try:
103
+ path = OUT
104
+ if path is None or body["saveAs"]:
105
+ path = ask_save_path()
106
+ if path is None:
107
+ return self.reply(json.dumps({"cancelled": True}).encode(), "application/json")
108
+ save(body["edits"], path)
109
+ OUT = path
110
+ result = {"path": str(path)}
111
+ except Exception as e:
112
+ result = {"error": str(e)}
113
+ self.reply(json.dumps(result).encode(), "application/json")
114
+
115
+ def reply(self, body, ctype):
116
+ self.send_response(200)
117
+ self.send_header("Content-Type", ctype + "; charset=utf-8")
118
+ self.end_headers()
119
+ self.wfile.write(body)
120
+
121
+ def log_message(self, *args):
122
+ pass
123
+
124
+
125
+ TEMPLATE = """<!doctype html><meta charset="utf-8"><title>Tippex – {{NAME}}</title><link rel="icon" href="{{FAVICON}}">
126
+ <style>
127
+ body{margin:0;background:#888;font-family:-apple-system,sans-serif}
128
+ header{position:sticky;top:0;z-index:9;background:#222;color:#fff;padding:10px 16px;display:flex;gap:12px;align-items:center;flex-wrap:wrap}
129
+ header .grow{flex:1}
130
+ .brand{display:flex;align-items:center;gap:8px;font-weight:700;font-size:17px;letter-spacing:.3px}
131
+ .brand svg{width:30px;height:30px}
132
+ .dim{color:#aaa}
133
+ button{font-size:15px;padding:6px 16px}
134
+ #dest{position:sticky;top:52px;z-index:8;background:#fffbe6;color:#333;padding:8px 16px;font-size:13px;border-bottom:1px solid #e5d98a;word-break:break-all}
135
+ #dest a{margin-left:8px;color:#06c}
136
+ .page{position:relative;width:max-content;margin:20px auto;box-shadow:0 2px 10px #0006}
137
+ .page img{display:block}
138
+ .page input{position:absolute;box-sizing:border-box;border:1px solid transparent;background:transparent;color:transparent;padding:0;font-family:Helvetica,Arial,sans-serif;outline:none}
139
+ .page input:hover{border-color:#39f8}
140
+ .page input:focus,.page input.changed{background:#fff;color:#000;border-color:#39f}
141
+ </style>
142
+ <header>
143
+ <span class="brand">{{LOGO}}Tippex</span><span class="dim">{{NAME}}</span>
144
+ <span class="grow"></span>
145
+ <span id="status" class="dim"></span>
146
+ <button id="save">Save…</button><button id="saveas" hidden>Save As…</button>
147
+ </header>
148
+ <div id="dest">Not saved yet. You'll choose where to save the first time you press Save.</div>
149
+ {{PAGES}}
150
+ <script>
151
+ let savedPath = null, dirty = false;
152
+ const $ = id => document.getElementById(id);
153
+ const setDirty = d => { dirty = d; $('status').textContent = d ? 'Unsaved changes' : (savedPath ? 'All changes saved' : ''); };
154
+
155
+ document.querySelectorAll('.page input').forEach(el => el.addEventListener('input', () => {
156
+ el.classList.toggle('changed', el.value !== el.dataset.orig);
157
+ setDirty(true);
158
+ }));
159
+
160
+ async function save(saveAs) {
161
+ const edits = [...document.querySelectorAll('input.changed')].map(el => ({p: +el.dataset.p, i: +el.dataset.i, text: el.value}));
162
+ $('status').textContent = savedPath && !saveAs ? 'Saving…' : 'Choose where to save…';
163
+ const r = await (await fetch('/save', {method: 'POST', body: JSON.stringify({edits, saveAs})})).json();
164
+ if (r.cancelled) return setDirty(dirty);
165
+ if (r.error) return $('status').textContent = 'Error: ' + r.error;
166
+ savedPath = r.path;
167
+ $('dest').innerHTML = 'Saving to <b></b> <a href="#">Show in Finder</a>';
168
+ $('dest').querySelector('b').textContent = savedPath;
169
+ $('dest').querySelector('a').onclick = e => { e.preventDefault(); fetch('/reveal', {method: 'POST', body: '{}'}); };
170
+ $('save').textContent = 'Save';
171
+ $('saveas').hidden = false;
172
+ setDirty(false);
173
+ }
174
+ $('save').onclick = () => save(false);
175
+ $('saveas').onclick = () => save(true);
176
+ document.addEventListener('keydown', e => {
177
+ if (e.metaKey && e.key.toLowerCase() === 's') { e.preventDefault(); save(e.shiftKey); }
178
+ });
179
+ addEventListener('beforeunload', e => { if (dirty) e.preventDefault(); });
180
+ </script>"""
181
+
182
+ def main():
183
+ global SRC, ORIGINAL
184
+ if len(sys.argv) != 2 or sys.argv[1] in ("-h", "--help"):
185
+ sys.exit("Usage: tippex file.pdf")
186
+ SRC = Path(sys.argv[1]).expanduser().resolve()
187
+ if not SRC.is_file():
188
+ sys.exit(f"No such file: {SRC}")
189
+ ORIGINAL = SRC.read_bytes()
190
+ server = HTTPServer(("127.0.0.1", 0), Handler)
191
+ url = f"http://127.0.0.1:{server.server_port}/"
192
+ print(f"Editing {SRC.name} at {url}\nPress Ctrl+C to quit.")
193
+ threading.Timer(0.3, webbrowser.open, [url]).start()
194
+ try:
195
+ server.serve_forever()
196
+ except KeyboardInterrupt:
197
+ pass
198
+
199
+
200
+ if __name__ == "__main__":
201
+ main()