paperminertoolkit 1.0.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.
Files changed (45) hide show
  1. paperminertoolkit/__init__.py +10 -0
  2. paperminertoolkit/_version.py +11 -0
  3. paperminertoolkit/cli.py +1053 -0
  4. paperminertoolkit/corpus/__init__.py +1 -0
  5. paperminertoolkit/corpus/database.py +1542 -0
  6. paperminertoolkit/corpus/documents.py +313 -0
  7. paperminertoolkit/corpus/filtering.py +1390 -0
  8. paperminertoolkit/corpus/metadata.py +532 -0
  9. paperminertoolkit/extraction/__init__.py +1 -0
  10. paperminertoolkit/extraction/compression.py +486 -0
  11. paperminertoolkit/extraction/extract.py +573 -0
  12. paperminertoolkit/extraction/models.py +784 -0
  13. paperminertoolkit/extraction/recipes.py +241 -0
  14. paperminertoolkit/extraction/scrape.py +737 -0
  15. paperminertoolkit/extraction/store.py +244 -0
  16. paperminertoolkit/extraction/tokenizer.py +313 -0
  17. paperminertoolkit/providers/__init__.py +1 -0
  18. paperminertoolkit/providers/arxiv.py +760 -0
  19. paperminertoolkit/providers/base.py +514 -0
  20. paperminertoolkit/providers/biorxiv.py +561 -0
  21. paperminertoolkit/providers/chemrxiv.py +1115 -0
  22. paperminertoolkit/providers/core.py +423 -0
  23. paperminertoolkit/providers/crossref.py +649 -0
  24. paperminertoolkit/providers/elsevier.py +455 -0
  25. paperminertoolkit/providers/medrxiv.py +548 -0
  26. paperminertoolkit/providers/openalex.py +471 -0
  27. paperminertoolkit/providers/pubmed.py +1272 -0
  28. paperminertoolkit/providers/registry.py +521 -0
  29. paperminertoolkit/providers/rxiv.py +936 -0
  30. paperminertoolkit/providers/unpaywall.py +162 -0
  31. paperminertoolkit/resources/recipes.json +1670 -0
  32. paperminertoolkit/settings.py +661 -0
  33. paperminertoolkit/workflows/__init__.py +1 -0
  34. paperminertoolkit/workflows/download.py +1748 -0
  35. paperminertoolkit/workflows/enrichment.py +1906 -0
  36. paperminertoolkit/workflows/imports.py +121 -0
  37. paperminertoolkit/workflows/search.py +877 -0
  38. paperminertoolkit/workflows/topics.py +2837 -0
  39. paperminertoolkit/workflows/utilities.py +73 -0
  40. paperminertoolkit-1.0.0.dist-info/METADATA +126 -0
  41. paperminertoolkit-1.0.0.dist-info/RECORD +45 -0
  42. paperminertoolkit-1.0.0.dist-info/WHEEL +5 -0
  43. paperminertoolkit-1.0.0.dist-info/entry_points.txt +2 -0
  44. paperminertoolkit-1.0.0.dist-info/licenses/LICENSE +21 -0
  45. paperminertoolkit-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,313 @@
1
+ """Read text from PDFs and extract images/pages for vision analysis.
2
+
3
+ This module centralizes document IO helpers used by scraping: text extraction
4
+ from PDFs, text/PDF path lookup for paper rows, and image extraction/rendering
5
+ for figure or page-level model analysis.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import io
11
+ import os
12
+ import re
13
+ from os import PathLike
14
+ from pypdf import PdfReader
15
+ from pathlib import Path
16
+ from types import TracebackType
17
+ from typing import Any, BinaryIO, Protocol, Self
18
+
19
+
20
+ class _FitzPixmapLike(Protocol):
21
+ """Pixmap behavior used when rendering PDF pages."""
22
+
23
+ def save(self, filename: str) -> None:
24
+ """Write the pixmap to an image file."""
25
+ ...
26
+
27
+
28
+ class _FitzPageLike(Protocol):
29
+ """PyMuPDF page behavior used by image extraction."""
30
+
31
+ def get_images(self, *, full: bool) -> list[tuple[int, ...]]:
32
+ """Return image descriptors embedded in the page."""
33
+ ...
34
+
35
+ def get_pixmap(self, *, matrix: object, alpha: bool) -> _FitzPixmapLike:
36
+ """Render the page to a pixmap."""
37
+ ...
38
+
39
+
40
+ class _FitzDocumentLike(Protocol):
41
+ """PyMuPDF document behavior used by this module."""
42
+
43
+ def __len__(self) -> int:
44
+ """Return the page count."""
45
+ ...
46
+
47
+ def __getitem__(self, index: int) -> _FitzPageLike:
48
+ """Return one page by zero-based index."""
49
+ ...
50
+
51
+ def __enter__(self) -> Self:
52
+ """Enter the document context manager."""
53
+ ...
54
+
55
+ def __exit__(
56
+ self,
57
+ exc_type: type[BaseException] | None,
58
+ exc_value: BaseException | None,
59
+ traceback: TracebackType | None,
60
+ ) -> bool | None:
61
+ """Close the document when leaving its context."""
62
+ ...
63
+
64
+ def extract_image(self, xref: int) -> dict[str, Any]:
65
+ """Extract an embedded image by cross-reference number."""
66
+ ...
67
+
68
+
69
+ class _FitzModuleLike(Protocol):
70
+ """PyMuPDF module behavior used by this module."""
71
+
72
+ def Matrix(self, x_zoom: float, y_zoom: float) -> object:
73
+ """Build a page-rendering transformation matrix."""
74
+ ...
75
+
76
+ def open(self, filename: str) -> _FitzDocumentLike:
77
+ """Open a PDF document."""
78
+ ...
79
+
80
+
81
+ def read_pdf_text(pdf_path: str | PathLike[str] | BinaryIO) -> str:
82
+ """Extract concatenated text from every page in a PDF.
83
+
84
+ Parameters
85
+ ----------
86
+ pdf_path : str, os.PathLike[str], or BinaryIO
87
+ PDF path or binary stream accepted by :class:`pypdf.PdfReader`.
88
+
89
+ Returns
90
+ -------
91
+ str
92
+ Page text in document order. Pages without extractable text contribute
93
+ an empty string.
94
+ """
95
+ reader = PdfReader(pdf_path)
96
+ text = ''
97
+ for page in reader.pages:
98
+ page_text = page.extract_text() or ''
99
+ text += page_text
100
+ return text
101
+
102
+
103
+ def read_pdf_bytes(content: bytes) -> str:
104
+ """Extract text directly from in-memory PDF bytes.
105
+
106
+ Parameters
107
+ ----------
108
+ content : bytes
109
+ Complete PDF file contents.
110
+
111
+ Returns
112
+ -------
113
+ str
114
+ Concatenated text from the PDF pages.
115
+ """
116
+ return read_pdf_text(io.BytesIO(content))
117
+
118
+
119
+ def trim_reference_section(text: str) -> str:
120
+ """Remove a trailing reference section identified by a standalone heading.
121
+
122
+ Parameters
123
+ ----------
124
+ text : str
125
+ Document text to trim.
126
+
127
+ Returns
128
+ -------
129
+ str
130
+ Text before the final references heading, or the original text when no
131
+ heading is present.
132
+ """
133
+ headings = list(re.finditer(
134
+ r'(?im)^\s*(?:\d+(?:\.\d+)*[.)]?\s+)?(?:references|bibliography|literature cited)\s*$',
135
+ text,
136
+ ))
137
+ if headings:
138
+ return text[:headings[-1].start()]
139
+ return text
140
+
141
+
142
+ def read_document_text(path: str, trim_references: bool = True) -> str:
143
+ """Read text from a TXT or PDF document.
144
+
145
+ Parameters
146
+ ----------
147
+ path : str
148
+ Path to a ``.txt`` or ``.pdf`` document.
149
+ trim_references : bool, default=True
150
+ Whether to remove the trailing reference section from PDFs.
151
+
152
+ Returns
153
+ -------
154
+ str
155
+ Extracted document text.
156
+
157
+ Raises
158
+ ------
159
+ ValueError
160
+ If ``path`` does not have a supported extension.
161
+ """
162
+ if path.lower().endswith('.txt'):
163
+ with open(path, 'r', encoding='utf-8') as f:
164
+ return f.read()
165
+ if path.lower().endswith('.pdf'):
166
+ text = read_pdf_text(path)
167
+ if trim_references:
168
+ text = trim_reference_section(text)
169
+ return text
170
+ raise ValueError(f'Unsupported document type: {path}')
171
+
172
+
173
+ def _load_fitz() -> _FitzModuleLike:
174
+ """Import PyMuPDF lazily.
175
+
176
+ Returns
177
+ -------
178
+ _FitzModuleLike
179
+ Imported :mod:`fitz` module.
180
+
181
+ Raises
182
+ ------
183
+ RuntimeError
184
+ If PyMuPDF is not installed.
185
+ """
186
+ try:
187
+ import fitz
188
+ except ImportError as e:
189
+ raise RuntimeError('Image analysis requires PyMuPDF. Install the package with: pip install pymupdf') from e
190
+ return fitz
191
+
192
+
193
+ def _extract_embedded_pdf_images(doc: _FitzDocumentLike, output_dir: str, prefix: str) -> list[str]:
194
+ """Save unique embedded images from an opened PyMuPDF document.
195
+
196
+ Parameters
197
+ ----------
198
+ doc : _FitzDocumentLike
199
+ Open PyMuPDF document.
200
+ output_dir : str
201
+ Directory where extracted images are written.
202
+ prefix : str
203
+ Filename prefix for saved images.
204
+
205
+ Returns
206
+ -------
207
+ list[str]
208
+ Paths to saved images in page and image order.
209
+ """
210
+ saved = []
211
+ seen_xrefs = set()
212
+ for page_index in range(len(doc)):
213
+ page = doc[page_index]
214
+ for image_index, image in enumerate(page.get_images(full=True), start=1):
215
+ xref = image[0]
216
+ if xref in seen_xrefs:
217
+ continue
218
+ seen_xrefs.add(xref)
219
+ extracted = doc.extract_image(xref)
220
+ ext = extracted.get('ext', 'png')
221
+ image_bytes = extracted['image']
222
+ filename = f'{prefix}_page-{page_index + 1}_image-{image_index}.{ext}'
223
+ filepath = os.path.join(output_dir, filename)
224
+ with open(filepath, 'wb') as out_file:
225
+ out_file.write(image_bytes)
226
+ saved.append(filepath)
227
+ return saved
228
+
229
+
230
+ def _render_pdf_pages(
231
+ fitz: _FitzModuleLike,
232
+ doc: _FitzDocumentLike,
233
+ output_dir: str,
234
+ prefix: str,
235
+ dpi: int = 200,
236
+ ) -> list[str]:
237
+ """Render each PDF page to a PNG image file.
238
+
239
+ Parameters
240
+ ----------
241
+ fitz : _FitzModuleLike
242
+ Imported PyMuPDF module.
243
+ doc : _FitzDocumentLike
244
+ Open PyMuPDF document.
245
+ output_dir : str
246
+ Directory where rendered pages are written.
247
+ prefix : str
248
+ Filename prefix for rendered pages.
249
+ dpi : int, default=200
250
+ Render resolution in dots per inch.
251
+
252
+ Returns
253
+ -------
254
+ list[str]
255
+ Paths to rendered page images in document order.
256
+ """
257
+ saved = []
258
+ zoom = dpi / 72
259
+ render_matrix = fitz.Matrix(zoom, zoom)
260
+ for page_index in range(len(doc)):
261
+ page = doc[page_index]
262
+ pixmap = page.get_pixmap(matrix=render_matrix, alpha=False)
263
+ filepath = os.path.join(output_dir, f'{prefix}_page-{page_index + 1}.png')
264
+ pixmap.save(filepath)
265
+ saved.append(filepath)
266
+ return saved
267
+
268
+
269
+ def extract_pdf_images(pdf_path: str,
270
+ output_dir: str,
271
+ prefix: str | None = None,
272
+ strategy: str = 'auto',
273
+ dpi: int = 200) -> list[str]:
274
+ """Extract images from a PDF for vision scraping.
275
+
276
+ Parameters
277
+ ----------
278
+ pdf_path : str
279
+ Path to the source PDF.
280
+ output_dir : str
281
+ Directory where image files are written.
282
+ prefix : str, optional
283
+ Filename prefix. The PDF stem is used when omitted.
284
+ strategy : {'auto', 'embedded', 'pages'}, default='auto'
285
+ Extraction strategy. ``auto`` uses embedded images when present and
286
+ otherwise renders complete pages.
287
+ dpi : int, default=200
288
+ Resolution used when rendering complete pages.
289
+
290
+ Returns
291
+ -------
292
+ list[str]
293
+ Paths to extracted or rendered image files.
294
+
295
+ Raises
296
+ ------
297
+ ValueError
298
+ If ``strategy`` is not supported.
299
+ RuntimeError
300
+ If PyMuPDF is unavailable.
301
+ """
302
+ if strategy not in {'auto', 'embedded', 'pages'}:
303
+ raise ValueError('Image extraction strategy must be one of: auto, embedded, pages')
304
+
305
+ fitz = _load_fitz()
306
+ os.makedirs(output_dir, exist_ok=True)
307
+ prefix = prefix or Path(pdf_path).stem
308
+ with fitz.open(pdf_path) as doc:
309
+ if strategy in {'auto', 'embedded'}:
310
+ saved = _extract_embedded_pdf_images(doc, output_dir, prefix)
311
+ if saved or strategy == 'embedded':
312
+ return saved
313
+ return _render_pdf_pages(fitz, doc, output_dir, prefix, dpi=dpi)