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.
- paperminertoolkit/__init__.py +10 -0
- paperminertoolkit/_version.py +11 -0
- paperminertoolkit/cli.py +1053 -0
- paperminertoolkit/corpus/__init__.py +1 -0
- paperminertoolkit/corpus/database.py +1542 -0
- paperminertoolkit/corpus/documents.py +313 -0
- paperminertoolkit/corpus/filtering.py +1390 -0
- paperminertoolkit/corpus/metadata.py +532 -0
- paperminertoolkit/extraction/__init__.py +1 -0
- paperminertoolkit/extraction/compression.py +486 -0
- paperminertoolkit/extraction/extract.py +573 -0
- paperminertoolkit/extraction/models.py +784 -0
- paperminertoolkit/extraction/recipes.py +241 -0
- paperminertoolkit/extraction/scrape.py +737 -0
- paperminertoolkit/extraction/store.py +244 -0
- paperminertoolkit/extraction/tokenizer.py +313 -0
- paperminertoolkit/providers/__init__.py +1 -0
- paperminertoolkit/providers/arxiv.py +760 -0
- paperminertoolkit/providers/base.py +514 -0
- paperminertoolkit/providers/biorxiv.py +561 -0
- paperminertoolkit/providers/chemrxiv.py +1115 -0
- paperminertoolkit/providers/core.py +423 -0
- paperminertoolkit/providers/crossref.py +649 -0
- paperminertoolkit/providers/elsevier.py +455 -0
- paperminertoolkit/providers/medrxiv.py +548 -0
- paperminertoolkit/providers/openalex.py +471 -0
- paperminertoolkit/providers/pubmed.py +1272 -0
- paperminertoolkit/providers/registry.py +521 -0
- paperminertoolkit/providers/rxiv.py +936 -0
- paperminertoolkit/providers/unpaywall.py +162 -0
- paperminertoolkit/resources/recipes.json +1670 -0
- paperminertoolkit/settings.py +661 -0
- paperminertoolkit/workflows/__init__.py +1 -0
- paperminertoolkit/workflows/download.py +1748 -0
- paperminertoolkit/workflows/enrichment.py +1906 -0
- paperminertoolkit/workflows/imports.py +121 -0
- paperminertoolkit/workflows/search.py +877 -0
- paperminertoolkit/workflows/topics.py +2837 -0
- paperminertoolkit/workflows/utilities.py +73 -0
- paperminertoolkit-1.0.0.dist-info/METADATA +126 -0
- paperminertoolkit-1.0.0.dist-info/RECORD +45 -0
- paperminertoolkit-1.0.0.dist-info/WHEEL +5 -0
- paperminertoolkit-1.0.0.dist-info/entry_points.txt +2 -0
- paperminertoolkit-1.0.0.dist-info/licenses/LICENSE +21 -0
- paperminertoolkit-1.0.0.dist-info/top_level.txt +1 -0
paperminertoolkit/cli.py
ADDED
|
@@ -0,0 +1,1053 @@
|
|
|
1
|
+
"""The nested ``pmt`` command-line interface for PaperMinerToolkit workflows.
|
|
2
|
+
|
|
3
|
+
This module maps installed commands to the underlying search, import,
|
|
4
|
+
download, scrape, store, configuration, and maintenance functions.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any, Mapping
|
|
10
|
+
|
|
11
|
+
import click
|
|
12
|
+
from paperminertoolkit.providers import registry as sources
|
|
13
|
+
from paperminertoolkit.corpus.database import connect, corpus_stats, enrichment_stats
|
|
14
|
+
from paperminertoolkit.providers.crossref import import_author_works
|
|
15
|
+
from paperminertoolkit.workflows.search import search_for_papers
|
|
16
|
+
from paperminertoolkit.extraction.compression import COMPRESSION_MODES, COMPRESSION_SCOPES
|
|
17
|
+
from paperminertoolkit.workflows.download import download_papers
|
|
18
|
+
from paperminertoolkit.workflows.enrichment import enrich_corpus
|
|
19
|
+
from paperminertoolkit.corpus.filtering import (apply_regex_filter,
|
|
20
|
+
apply_topic_filter,
|
|
21
|
+
filter_overview,
|
|
22
|
+
reset_filters)
|
|
23
|
+
from paperminertoolkit.workflows.imports import import_pdfs
|
|
24
|
+
from paperminertoolkit.extraction.scrape import SCRAPE_ORDERS, scrape_papers
|
|
25
|
+
from paperminertoolkit.extraction.store import store_results
|
|
26
|
+
from paperminertoolkit.workflows.topics import (aggregate_topic_trends,
|
|
27
|
+
compare_topic_models,
|
|
28
|
+
predict_topic_model,
|
|
29
|
+
set_topic_name,
|
|
30
|
+
store_topic_model_scores,
|
|
31
|
+
stored_topic_models,
|
|
32
|
+
topic_descriptions,
|
|
33
|
+
train_topic_model)
|
|
34
|
+
from paperminertoolkit.settings import (get_model_profile,
|
|
35
|
+
DEFAULT_INPUT_TOKEN_LIMIT,
|
|
36
|
+
infer_model_capabilities,
|
|
37
|
+
set_model_profile,
|
|
38
|
+
update_anthropic_key,
|
|
39
|
+
update_core_key,
|
|
40
|
+
update_crossref_email,
|
|
41
|
+
update_elsevier_key,
|
|
42
|
+
update_ncbi_email,
|
|
43
|
+
update_ncbi_key,
|
|
44
|
+
update_openai_key,
|
|
45
|
+
update_openalex_key,
|
|
46
|
+
update_unpaywall_email)
|
|
47
|
+
from paperminertoolkit.workflows.utilities import reset, status
|
|
48
|
+
|
|
49
|
+
# A download may fetch a PDF, full text, or an abstract, so its choices are
|
|
50
|
+
# the union of the three, kept in PDF order because that is the one a caller
|
|
51
|
+
# most often means.
|
|
52
|
+
DOWNLOAD_CHOICES = [
|
|
53
|
+
'all',
|
|
54
|
+
*dict.fromkeys((*sources.names(sources.PDF),
|
|
55
|
+
*sources.names(sources.TEXT),
|
|
56
|
+
*sources.names(sources.ABSTRACT))),
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _format_bytes(size: int) -> str:
|
|
61
|
+
"""Format a byte count using compact binary units."""
|
|
62
|
+
value = float(size)
|
|
63
|
+
for unit in ['B', 'KiB', 'MiB', 'GiB']:
|
|
64
|
+
if value < 1024 or unit == 'GiB':
|
|
65
|
+
return f'{value:.1f} {unit}' if unit != 'B' else f'{int(value)} B'
|
|
66
|
+
value /= 1024
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@click.command('search')
|
|
70
|
+
@click.argument('query', default='Lithium solid electrolyte', type=str)
|
|
71
|
+
@click.argument('db_path', default='papers.db', type=click.Path())
|
|
72
|
+
@click.option('--source',
|
|
73
|
+
type=click.Choice(sources.choices(sources.SEARCH)),
|
|
74
|
+
default='all',
|
|
75
|
+
show_default=True,
|
|
76
|
+
help='Search source to use.')
|
|
77
|
+
@click.option('--count',
|
|
78
|
+
default=200,
|
|
79
|
+
type=int,
|
|
80
|
+
show_default=True,
|
|
81
|
+
help='Maximum results to request from each selected source.')
|
|
82
|
+
@click.option('--store-abstract',
|
|
83
|
+
is_flag=True,
|
|
84
|
+
default=False,
|
|
85
|
+
help='Store abstracts returned by search providers as corpus assets.')
|
|
86
|
+
@click.option('--enrich', 'enrich_metadata',
|
|
87
|
+
is_flag=True,
|
|
88
|
+
default=False,
|
|
89
|
+
help='Supplement newly stored papers with all enrichment providers.')
|
|
90
|
+
def paper_search(query: str, db_path: str, source: str, count: int,
|
|
91
|
+
store_abstract: bool, enrich_metadata: bool) -> None:
|
|
92
|
+
"""Search configured paper sources and merge results into the paper corpus."""
|
|
93
|
+
search_for_papers(query, db_path, source=source, count=count,
|
|
94
|
+
store_abstract=store_abstract, enrich=enrich_metadata)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@click.command('pdfs')
|
|
98
|
+
@click.argument('dir', default='papers', type=click.Path(exists=True, file_okay=False))
|
|
99
|
+
@click.argument('db_path', default='papers.db', type=click.Path())
|
|
100
|
+
@click.option('--no-crossref',
|
|
101
|
+
is_flag=True,
|
|
102
|
+
default=False,
|
|
103
|
+
help='Only scrape DOI from PDFs; skip Crossref metadata lookup.')
|
|
104
|
+
def import_pdf_folder(dir: str, db_path: str, no_crossref: bool) -> None:
|
|
105
|
+
"""Import local PDFs into the paper corpus, optionally skipping Crossref lookup."""
|
|
106
|
+
import_pdfs(dir, db_path, use_crossref=not no_crossref)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@click.command('author')
|
|
110
|
+
@click.argument('db_path', default='papers.db', type=click.Path())
|
|
111
|
+
@click.option('--email', default=None,
|
|
112
|
+
help='Contact email sent with Crossref requests. '
|
|
113
|
+
'Defaults to the stored crossref_email setting.')
|
|
114
|
+
@click.option('--orcid', default=None, help='Exact ORCID identifier for the author.')
|
|
115
|
+
@click.option('--author', 'author_name', default=None, help='Author name fallback when no ORCID is available.')
|
|
116
|
+
@click.option('--affiliation', default=None, help='Require this affiliation on the matching author record.')
|
|
117
|
+
@click.option('--max-results', default=500, type=click.IntRange(min=1), show_default=True)
|
|
118
|
+
@click.option('--review-csv', default='author_works.csv', type=click.Path(), show_default=True,
|
|
119
|
+
help='CSV summary written for manual review.')
|
|
120
|
+
@click.option('--enrich', 'enrich_metadata',
|
|
121
|
+
is_flag=True,
|
|
122
|
+
default=False,
|
|
123
|
+
help='Supplement imported works with all enrichment providers.')
|
|
124
|
+
def import_author(db_path: str,
|
|
125
|
+
email: str | None,
|
|
126
|
+
orcid: str | None,
|
|
127
|
+
author_name: str | None,
|
|
128
|
+
affiliation: str | None,
|
|
129
|
+
max_results: int,
|
|
130
|
+
review_csv: str,
|
|
131
|
+
enrich_metadata: bool) -> None:
|
|
132
|
+
"""Import one author's DOI-bearing Crossref works into a corpus."""
|
|
133
|
+
if bool(orcid) == bool(author_name):
|
|
134
|
+
raise click.UsageError('Provide exactly one of --orcid or --author.')
|
|
135
|
+
try:
|
|
136
|
+
summary = import_author_works(
|
|
137
|
+
db_path,
|
|
138
|
+
email=email,
|
|
139
|
+
orcid=orcid,
|
|
140
|
+
author_name=author_name,
|
|
141
|
+
affiliation=affiliation,
|
|
142
|
+
max_results=max_results,
|
|
143
|
+
review_csv=review_csv,
|
|
144
|
+
enrich=enrich_metadata,
|
|
145
|
+
)
|
|
146
|
+
except (RuntimeError, ValueError) as error:
|
|
147
|
+
raise click.ClickException(str(error)) from error
|
|
148
|
+
click.echo(
|
|
149
|
+
f'Crossref found {summary["found"]} matching works: '
|
|
150
|
+
f'{summary["added"]} added and {summary["updated"]} updated in {db_path}.'
|
|
151
|
+
)
|
|
152
|
+
if enrich_metadata:
|
|
153
|
+
click.echo(f'Enriched {summary["enriched"]} imported works.')
|
|
154
|
+
click.echo(f'Review the imported metadata in {review_csv} before downloading papers.')
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@click.command('download')
|
|
158
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
159
|
+
@click.option('--format', 'download_format',
|
|
160
|
+
type=click.Choice(['abstract', 'text', 'pdf', 'both']),
|
|
161
|
+
default='both',
|
|
162
|
+
show_default=True)
|
|
163
|
+
@click.option('--source', 'sources',
|
|
164
|
+
multiple=True,
|
|
165
|
+
type=click.Choice(DOWNLOAD_CHOICES),
|
|
166
|
+
default=('all',),
|
|
167
|
+
show_default=True,
|
|
168
|
+
help='Content source to use for PDFs and PubMed Central full text. '
|
|
169
|
+
'Repeat to choose more than one.')
|
|
170
|
+
@click.option('--abstract/--no-abstract',
|
|
171
|
+
'download_abstract',
|
|
172
|
+
default=True,
|
|
173
|
+
show_default=True,
|
|
174
|
+
help='Download and store abstracts alongside requested paper assets.')
|
|
175
|
+
@click.option('--force', is_flag=True, default=False,
|
|
176
|
+
help='Redownload requested assets even when that content type is already stored.')
|
|
177
|
+
def download(
|
|
178
|
+
db_path: str,
|
|
179
|
+
download_format: str,
|
|
180
|
+
sources: tuple[str, ...],
|
|
181
|
+
download_abstract: bool,
|
|
182
|
+
force: bool,
|
|
183
|
+
) -> None:
|
|
184
|
+
"""Download abstracts, text, and/or PDFs for rows in the paper corpus."""
|
|
185
|
+
download_papers(
|
|
186
|
+
db_path,
|
|
187
|
+
download_format=download_format,
|
|
188
|
+
sources=list(sources),
|
|
189
|
+
download_abstract=download_abstract,
|
|
190
|
+
force=force,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@click.command('enrich')
|
|
195
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
196
|
+
@click.option('--source', 'sources',
|
|
197
|
+
multiple=True,
|
|
198
|
+
type=click.Choice(sources.choices(sources.ENRICH)),
|
|
199
|
+
default=('all',),
|
|
200
|
+
show_default=True,
|
|
201
|
+
help='Metadata source to use. Repeat to choose more than one.')
|
|
202
|
+
@click.option('--batch-size',
|
|
203
|
+
default=100,
|
|
204
|
+
type=click.IntRange(1, 100),
|
|
205
|
+
show_default=True,
|
|
206
|
+
help='Papers looked up per provider request.')
|
|
207
|
+
@click.option('--limit',
|
|
208
|
+
default=None,
|
|
209
|
+
type=click.IntRange(min=1),
|
|
210
|
+
help='Stop after enriching this many papers.')
|
|
211
|
+
@click.option('--force', is_flag=True, default=False,
|
|
212
|
+
help='Re-enrich papers whose enrichment already succeeded.')
|
|
213
|
+
@click.option('--retry-failed', is_flag=True, default=False,
|
|
214
|
+
help='Retry papers whose previous enrichment failed.')
|
|
215
|
+
@click.option('--refresh-after',
|
|
216
|
+
default=0,
|
|
217
|
+
type=click.IntRange(min=0),
|
|
218
|
+
show_default=True,
|
|
219
|
+
help='Re-enrich papers enriched more than this many days ago. 0 disables refreshing.')
|
|
220
|
+
@click.option('--references/--no-references',
|
|
221
|
+
default=True,
|
|
222
|
+
show_default=True,
|
|
223
|
+
help='Store reference lists returned by the selected sources.')
|
|
224
|
+
@click.option('--resolve-references', is_flag=True, default=False,
|
|
225
|
+
help='Link stored reference DOIs to papers already in the corpus.')
|
|
226
|
+
@click.option('--email',
|
|
227
|
+
default=None,
|
|
228
|
+
help='Contact email for Crossref. Defaults to the stored crossref_email setting.')
|
|
229
|
+
def enrich(db_path: str,
|
|
230
|
+
sources: tuple[str, ...],
|
|
231
|
+
batch_size: int,
|
|
232
|
+
limit: int | None,
|
|
233
|
+
force: bool,
|
|
234
|
+
retry_failed: bool,
|
|
235
|
+
refresh_after: int,
|
|
236
|
+
references: bool,
|
|
237
|
+
resolve_references: bool,
|
|
238
|
+
email: str | None) -> None:
|
|
239
|
+
"""Supplement corpus metadata with the selected provider records."""
|
|
240
|
+
try:
|
|
241
|
+
summary = enrich_corpus(
|
|
242
|
+
db_path,
|
|
243
|
+
sources=list(sources),
|
|
244
|
+
batch_size=batch_size,
|
|
245
|
+
limit=limit,
|
|
246
|
+
force=force,
|
|
247
|
+
retry_failed=retry_failed,
|
|
248
|
+
refresh_after=refresh_after,
|
|
249
|
+
references=references,
|
|
250
|
+
resolve_references=resolve_references,
|
|
251
|
+
email=email,
|
|
252
|
+
)
|
|
253
|
+
except (RuntimeError, ValueError) as error:
|
|
254
|
+
raise click.ClickException(str(error)) from error
|
|
255
|
+
click.echo(
|
|
256
|
+
f'Enrichment complete: {summary["succeeded"]} enriched, '
|
|
257
|
+
f'{summary["partial"]} partial, {summary["not_found"]} not found.'
|
|
258
|
+
)
|
|
259
|
+
click.echo(
|
|
260
|
+
f'Stored {summary["authors"]} author records, {summary["subjects"]} subject records, '
|
|
261
|
+
f'and {summary["references"]} references.'
|
|
262
|
+
)
|
|
263
|
+
if summary['unresolved']:
|
|
264
|
+
click.echo(
|
|
265
|
+
f'{summary["unresolved"]} papers have no DOI, OpenAlex identifier, PMID, '
|
|
266
|
+
f'arXiv identifier, medRxiv DOI, bioRxiv DOI, or chemRxiv DOI and were '
|
|
267
|
+
f'skipped.',
|
|
268
|
+
err=True,
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@click.command('stats')
|
|
273
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
274
|
+
def corpus_status(db_path: str) -> None:
|
|
275
|
+
"""Print storage statistics for the paper corpus."""
|
|
276
|
+
with connect(db_path) as conn:
|
|
277
|
+
stats = corpus_stats(conn)
|
|
278
|
+
enrichment = enrichment_stats(conn)
|
|
279
|
+
click.echo(f'Corpus: {db_path}')
|
|
280
|
+
click.echo(f'Papers: {stats["papers"]}')
|
|
281
|
+
click.echo(f'Papers with abstracts: {stats["papers_with_abstract"]}')
|
|
282
|
+
click.echo(f'Papers with text: {stats["papers_with_text"]}')
|
|
283
|
+
click.echo(f'Papers with PDFs: {stats["papers_with_pdf"]}')
|
|
284
|
+
click.echo(f'Text scrapes split into chunks: {stats["papers_with_chunked_text"]}')
|
|
285
|
+
click.echo(f'Abstract scrapes split into chunks: {stats["papers_with_chunked_abstracts"]}')
|
|
286
|
+
click.echo(f'Blobs: {stats["blobs"]}')
|
|
287
|
+
click.echo(f'Original size: {_format_bytes(stats["original_size"])}')
|
|
288
|
+
click.echo(f'Stored size: {_format_bytes(stats["stored_size"])}')
|
|
289
|
+
click.echo(f'Storage saved: {stats["savings_fraction"]:.1%}')
|
|
290
|
+
click.echo(f'Papers enriched: {enrichment["papers_succeeded"]}')
|
|
291
|
+
click.echo(f'Papers open access: {enrichment["papers_open_access"]}')
|
|
292
|
+
click.echo(f'Papers retracted: {enrichment["papers_retracted"]}')
|
|
293
|
+
click.echo(f'Author records: {enrichment["author_records"]} '
|
|
294
|
+
f'({enrichment["authors_with_orcid"]} with ORCID)')
|
|
295
|
+
click.echo(f'Subject records: {enrichment["subject_records"]}')
|
|
296
|
+
click.echo(f'Reference records: {enrichment["reference_records"]}')
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _echo_filter_overview(db_path: str, overview: Mapping[str, Any]) -> None:
|
|
300
|
+
"""Print a compact, explicit summary of the active filter stack."""
|
|
301
|
+
click.echo(f'Corpus filters: {db_path}')
|
|
302
|
+
if not overview['filters']:
|
|
303
|
+
click.echo('Active expression: none')
|
|
304
|
+
else:
|
|
305
|
+
click.echo(f'Active expression: {overview["expression"]}')
|
|
306
|
+
for index, item in enumerate(overview['filters']):
|
|
307
|
+
prefix = 'ROOT' if index == 0 else item['join_operator'].upper()
|
|
308
|
+
definition = item['definition']
|
|
309
|
+
counts = item['counts']
|
|
310
|
+
if item['method'] == 'regex':
|
|
311
|
+
details = (
|
|
312
|
+
f'regex; {definition["include_mode"]}; '
|
|
313
|
+
f'fields={",".join(definition["fields"])}; '
|
|
314
|
+
f'timeout={definition["timeout_ms"]}ms'
|
|
315
|
+
)
|
|
316
|
+
else:
|
|
317
|
+
details = (
|
|
318
|
+
f'topic; model={definition["model"]}; '
|
|
319
|
+
f'{definition["include_mode"]}'
|
|
320
|
+
)
|
|
321
|
+
stale = '; STALE' if item.get('stale') else ''
|
|
322
|
+
click.echo(
|
|
323
|
+
f' {prefix} {item["name"]} [{details}{stale}] '
|
|
324
|
+
f'included={counts["included"]}, excluded={counts["excluded"]}, '
|
|
325
|
+
f'unavailable={counts["unavailable"]}'
|
|
326
|
+
)
|
|
327
|
+
counts = overview['counts']
|
|
328
|
+
click.echo(
|
|
329
|
+
f'Final result: included={counts["included"]}, excluded={counts["excluded"]}, '
|
|
330
|
+
f'unavailable={counts["unavailable"]}'
|
|
331
|
+
)
|
|
332
|
+
if overview['unavailable_reasons']:
|
|
333
|
+
click.echo('Unavailable reasons:')
|
|
334
|
+
ordered = sorted(
|
|
335
|
+
overview['unavailable_reasons'].items(), key=lambda item: (-item[1], item[0])
|
|
336
|
+
)
|
|
337
|
+
for reason, count in ordered[:10]:
|
|
338
|
+
click.echo(f' {count}: {reason}')
|
|
339
|
+
if len(ordered) > 10:
|
|
340
|
+
click.echo(f' ... {len(ordered) - 10} more reason combinations stored in the corpus')
|
|
341
|
+
if overview.get('stale_topic_filters'):
|
|
342
|
+
click.echo(
|
|
343
|
+
'Stale topic filters: ' + ', '.join(overview['stale_topic_filters'])
|
|
344
|
+
+ '. Run pmt topics store again before scraping.'
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
@click.command('regex')
|
|
349
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
350
|
+
@click.argument('rules_path', type=click.Path(exists=True, dir_okay=False))
|
|
351
|
+
@click.option('--field', 'fields', multiple=True,
|
|
352
|
+
type=click.Choice(['title', 'abstract', 'full_text']),
|
|
353
|
+
help='Override JSON fields. Repeat to combine fields.')
|
|
354
|
+
@click.option('--join', 'join_operator', type=click.Choice(['and', 'or']), default=None,
|
|
355
|
+
help='Join this filter to the preceding active expression.')
|
|
356
|
+
@click.option('--replace', is_flag=True, default=False,
|
|
357
|
+
help='Replace and reevaluate an active filter with the same name.')
|
|
358
|
+
@click.option('--timeout-ms', type=click.IntRange(min=1), default=None,
|
|
359
|
+
help='Override the per-pattern match timeout from the JSON definition.')
|
|
360
|
+
def filter_regex(db_path: str, rules_path: str, fields: tuple[str, ...],
|
|
361
|
+
join_operator: str | None, replace: bool, timeout_ms: int | None) -> None:
|
|
362
|
+
"""Apply a named post-download regex filter to a paper corpus."""
|
|
363
|
+
try:
|
|
364
|
+
overview = apply_regex_filter(
|
|
365
|
+
db_path,
|
|
366
|
+
rules_path,
|
|
367
|
+
fields=fields or None,
|
|
368
|
+
join_operator=join_operator,
|
|
369
|
+
replace=replace,
|
|
370
|
+
timeout_ms=timeout_ms,
|
|
371
|
+
)
|
|
372
|
+
except (OSError, ValueError) as error:
|
|
373
|
+
raise click.ClickException(str(error)) from error
|
|
374
|
+
_echo_filter_overview(db_path, overview)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
@click.command('topic')
|
|
378
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
379
|
+
@click.argument('rules_path', type=click.Path(exists=True, dir_okay=False))
|
|
380
|
+
@click.option('--join', 'join_operator', type=click.Choice(['and', 'or']), default=None,
|
|
381
|
+
help='Join this filter to the preceding active expression.')
|
|
382
|
+
@click.option('--replace', is_flag=True, default=False,
|
|
383
|
+
help='Replace and reevaluate an active filter with the same name.')
|
|
384
|
+
def filter_topic(db_path: str, rules_path: str,
|
|
385
|
+
join_operator: str | None, replace: bool) -> None:
|
|
386
|
+
"""Apply a named stored-model topic filter to a paper corpus."""
|
|
387
|
+
try:
|
|
388
|
+
overview = apply_topic_filter(
|
|
389
|
+
db_path, rules_path, join_operator=join_operator, replace=replace
|
|
390
|
+
)
|
|
391
|
+
except (OSError, ValueError) as error:
|
|
392
|
+
raise click.ClickException(str(error)) from error
|
|
393
|
+
_echo_filter_overview(db_path, overview)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
@click.command('status')
|
|
397
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
398
|
+
def filter_status(db_path: str) -> None:
|
|
399
|
+
"""Show active corpus filters and their final paper decisions."""
|
|
400
|
+
with connect(db_path) as conn:
|
|
401
|
+
overview = filter_overview(conn)
|
|
402
|
+
_echo_filter_overview(db_path, overview)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
@click.command('reset')
|
|
406
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
407
|
+
@click.option('--name', default=None, help='Remove one active filter by name.')
|
|
408
|
+
@click.option('--all', 'all_filters', is_flag=True, default=False,
|
|
409
|
+
help='Remove every active filter.')
|
|
410
|
+
def filter_reset(db_path: str, name: str | None, all_filters: bool) -> None:
|
|
411
|
+
"""Remove one or all active corpus filters."""
|
|
412
|
+
try:
|
|
413
|
+
overview = reset_filters(db_path, name=name, all_filters=all_filters)
|
|
414
|
+
except ValueError as error:
|
|
415
|
+
raise click.ClickException(str(error)) from error
|
|
416
|
+
_echo_filter_overview(db_path, overview)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
@click.command('train')
|
|
420
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
421
|
+
@click.argument('model_dir', default='topic_model', type=click.Path())
|
|
422
|
+
@click.option('--topics', 'num_topics', default=10, type=click.IntRange(min=2), show_default=True)
|
|
423
|
+
@click.option('--field', 'text_fields', multiple=True,
|
|
424
|
+
type=click.Choice(['title', 'abstract', 'text']),
|
|
425
|
+
default=('title', 'abstract'), show_default=True,
|
|
426
|
+
help='Corpus text field to model. Repeat to combine fields.')
|
|
427
|
+
@click.option('--min-df', default=2, type=click.IntRange(min=1), show_default=True,
|
|
428
|
+
help='Minimum number of documents containing a retained term.')
|
|
429
|
+
@click.option('--max-df', default=0.95, type=click.FloatRange(min=0.0, max=1.0, min_open=True),
|
|
430
|
+
show_default=True, help='Maximum fraction of documents containing a retained term.')
|
|
431
|
+
@click.option('--max-features', default=20000, type=click.IntRange(min=2), show_default=True)
|
|
432
|
+
@click.option('--learning-method', type=click.Choice(['online', 'batch']), default='online', show_default=True)
|
|
433
|
+
@click.option('--iterations', 'max_iter', default=20, type=click.IntRange(min=1), show_default=True)
|
|
434
|
+
@click.option('--random-seed', 'random_state', default=0, type=int, show_default=True)
|
|
435
|
+
@click.option('--top-terms', default=15, type=click.IntRange(min=1), show_default=True)
|
|
436
|
+
@click.option('--representative-papers', default=5, type=click.IntRange(min=1), show_default=True)
|
|
437
|
+
@click.option('--stopwords-file', default=None, type=click.Path(exists=True, dir_okay=False),
|
|
438
|
+
help='UTF-8 file containing one corpus-specific stopword per line.')
|
|
439
|
+
@click.option('--ngram-max', default=2, type=click.IntRange(min=1, max=2), show_default=True,
|
|
440
|
+
help='Largest generated n-gram; use 2 to include bigrams.')
|
|
441
|
+
@click.option('--overwrite', is_flag=True, default=False,
|
|
442
|
+
help='Replace known model artifact files in a non-empty model directory.')
|
|
443
|
+
@click.option('--streaming/--in-memory', default=True, show_default=True,
|
|
444
|
+
help='Use disk-backed bounded batches or materialize the corpus in memory.')
|
|
445
|
+
@click.option('--batch-size', default=128, type=click.IntRange(min=1), show_default=True)
|
|
446
|
+
@click.option('--cache-dir', default=None, type=click.Path(file_okay=False),
|
|
447
|
+
help='Parent directory for temporary streaming caches.')
|
|
448
|
+
@click.option('--evaluation-sample-size', default=10000,
|
|
449
|
+
type=click.IntRange(min=1), show_default=True)
|
|
450
|
+
def topics_train(db_path: str,
|
|
451
|
+
model_dir: str,
|
|
452
|
+
num_topics: int,
|
|
453
|
+
text_fields: tuple[str, ...],
|
|
454
|
+
min_df: int,
|
|
455
|
+
max_df: float,
|
|
456
|
+
max_features: int,
|
|
457
|
+
learning_method: str,
|
|
458
|
+
max_iter: int,
|
|
459
|
+
random_state: int,
|
|
460
|
+
top_terms: int,
|
|
461
|
+
representative_papers: int,
|
|
462
|
+
stopwords_file: str | None,
|
|
463
|
+
ngram_max: int,
|
|
464
|
+
overwrite: bool,
|
|
465
|
+
streaming: bool,
|
|
466
|
+
batch_size: int,
|
|
467
|
+
cache_dir: str | None,
|
|
468
|
+
evaluation_sample_size: int) -> None:
|
|
469
|
+
"""Train an LDA model and write inspectable, manually nameable artifacts."""
|
|
470
|
+
try:
|
|
471
|
+
summary = train_topic_model(
|
|
472
|
+
db_path,
|
|
473
|
+
model_dir,
|
|
474
|
+
num_topics=num_topics,
|
|
475
|
+
text_fields=text_fields,
|
|
476
|
+
min_df=min_df,
|
|
477
|
+
max_df=max_df,
|
|
478
|
+
max_features=max_features,
|
|
479
|
+
learning_method=learning_method,
|
|
480
|
+
max_iter=max_iter,
|
|
481
|
+
random_state=random_state,
|
|
482
|
+
top_terms=top_terms,
|
|
483
|
+
representative_papers=representative_papers,
|
|
484
|
+
stopwords_file=stopwords_file,
|
|
485
|
+
ngram_max=ngram_max,
|
|
486
|
+
overwrite=overwrite,
|
|
487
|
+
emit_warnings=False,
|
|
488
|
+
streaming=streaming,
|
|
489
|
+
batch_size=batch_size,
|
|
490
|
+
cache_dir=cache_dir,
|
|
491
|
+
evaluation_sample_size=evaluation_sample_size,
|
|
492
|
+
)
|
|
493
|
+
except (OSError, ValueError) as error:
|
|
494
|
+
raise click.ClickException(str(error)) from error
|
|
495
|
+
for message in summary['report']['warnings']:
|
|
496
|
+
click.echo(f'Warning: {message}', err=True)
|
|
497
|
+
click.echo(
|
|
498
|
+
f'Trained {num_topics} topics from {summary["report"]["documents_used"]} papers '
|
|
499
|
+
f'using {summary["report"]["vocabulary_size"]} terms.'
|
|
500
|
+
)
|
|
501
|
+
click.echo(f'Model artifacts: {summary["model_dir"]}')
|
|
502
|
+
click.echo(f'Manual topic review: {summary["model_dir"]}/topics.csv')
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
@click.command('compare')
|
|
506
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
507
|
+
@click.argument('output_dir', default='topic_comparison', type=click.Path())
|
|
508
|
+
@click.option('--topics', 'topic_counts', multiple=True, type=click.IntRange(min=2),
|
|
509
|
+
default=(5, 10), show_default=True,
|
|
510
|
+
help='Topic count to train. Repeat to compare several values.')
|
|
511
|
+
@click.option('--seed', 'random_states', multiple=True, type=int, default=(0, 1), show_default=True,
|
|
512
|
+
help='Random seed to train. Repeat to assess stability.')
|
|
513
|
+
@click.option('--field', 'text_fields', multiple=True,
|
|
514
|
+
type=click.Choice(['title', 'abstract', 'text']),
|
|
515
|
+
default=('title', 'abstract'), show_default=True,
|
|
516
|
+
help='Corpus text field to model. Repeat to combine fields.')
|
|
517
|
+
@click.option('--min-df', default=2, type=click.IntRange(min=1), show_default=True)
|
|
518
|
+
@click.option('--max-df', default=0.95, type=click.FloatRange(min=0.0, max=1.0, min_open=True),
|
|
519
|
+
show_default=True)
|
|
520
|
+
@click.option('--max-features', default=20000, type=click.IntRange(min=2), show_default=True)
|
|
521
|
+
@click.option('--learning-method', type=click.Choice(['online', 'batch']), default='online', show_default=True)
|
|
522
|
+
@click.option('--iterations', 'max_iter', default=20, type=click.IntRange(min=1), show_default=True)
|
|
523
|
+
@click.option('--top-terms', default=15, type=click.IntRange(min=1), show_default=True)
|
|
524
|
+
@click.option('--representative-papers', default=5, type=click.IntRange(min=1), show_default=True)
|
|
525
|
+
@click.option('--stopwords-file', default=None, type=click.Path(exists=True, dir_okay=False),
|
|
526
|
+
help='UTF-8 file containing one corpus-specific stopword per line.')
|
|
527
|
+
@click.option('--ngram-max', default=2, type=click.IntRange(min=1, max=2), show_default=True)
|
|
528
|
+
@click.option('--overwrite', is_flag=True, default=False,
|
|
529
|
+
help='Replace known comparison and model artifact files.')
|
|
530
|
+
@click.option('--streaming/--in-memory', default=True, show_default=True,
|
|
531
|
+
help='Use one reusable disk-backed corpus cache or in-memory matrices.')
|
|
532
|
+
@click.option('--batch-size', default=128, type=click.IntRange(min=1), show_default=True)
|
|
533
|
+
@click.option('--cache-dir', default=None, type=click.Path(file_okay=False),
|
|
534
|
+
help='Parent directory for temporary streaming caches.')
|
|
535
|
+
@click.option('--evaluation-sample-size', default=10000,
|
|
536
|
+
type=click.IntRange(min=1), show_default=True)
|
|
537
|
+
def topics_compare(db_path: str,
|
|
538
|
+
output_dir: str,
|
|
539
|
+
topic_counts: tuple[int, ...],
|
|
540
|
+
random_states: tuple[int, ...],
|
|
541
|
+
text_fields: tuple[str, ...],
|
|
542
|
+
min_df: int,
|
|
543
|
+
max_df: float,
|
|
544
|
+
max_features: int,
|
|
545
|
+
learning_method: str,
|
|
546
|
+
max_iter: int,
|
|
547
|
+
top_terms: int,
|
|
548
|
+
representative_papers: int,
|
|
549
|
+
stopwords_file: str | None,
|
|
550
|
+
ngram_max: int,
|
|
551
|
+
overwrite: bool,
|
|
552
|
+
streaming: bool,
|
|
553
|
+
batch_size: int,
|
|
554
|
+
cache_dir: str | None,
|
|
555
|
+
evaluation_sample_size: int) -> None:
|
|
556
|
+
"""Train several LDA configurations and export comparable diagnostics."""
|
|
557
|
+
try:
|
|
558
|
+
summary = compare_topic_models(
|
|
559
|
+
db_path,
|
|
560
|
+
output_dir,
|
|
561
|
+
topic_counts=topic_counts,
|
|
562
|
+
random_states=random_states,
|
|
563
|
+
text_fields=text_fields,
|
|
564
|
+
min_df=min_df,
|
|
565
|
+
max_df=max_df,
|
|
566
|
+
max_features=max_features,
|
|
567
|
+
learning_method=learning_method,
|
|
568
|
+
max_iter=max_iter,
|
|
569
|
+
top_terms=top_terms,
|
|
570
|
+
representative_papers=representative_papers,
|
|
571
|
+
stopwords_file=stopwords_file,
|
|
572
|
+
ngram_max=ngram_max,
|
|
573
|
+
overwrite=overwrite,
|
|
574
|
+
streaming=streaming,
|
|
575
|
+
batch_size=batch_size,
|
|
576
|
+
cache_dir=cache_dir,
|
|
577
|
+
evaluation_sample_size=evaluation_sample_size,
|
|
578
|
+
)
|
|
579
|
+
except (OSError, ValueError) as error:
|
|
580
|
+
raise click.ClickException(str(error)) from error
|
|
581
|
+
warning_messages = dict.fromkeys(
|
|
582
|
+
message
|
|
583
|
+
for model in summary['models']
|
|
584
|
+
for message in model['warnings']
|
|
585
|
+
)
|
|
586
|
+
for message in warning_messages:
|
|
587
|
+
click.echo(f'Warning: {message}', err=True)
|
|
588
|
+
click.echo(f'Trained {summary["models_trained"]} comparison models in {summary["output_dir"]}.')
|
|
589
|
+
click.echo(f'Comparison metrics: {summary["comparison_csv"]}')
|
|
590
|
+
click.echo('Inspect each model with pmt topics show before choosing one.')
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
@click.command('show')
|
|
594
|
+
@click.argument('model_dir', default='topic_model', type=click.Path(exists=True, file_okay=False))
|
|
595
|
+
@click.option('--representatives', default=3, type=click.IntRange(min=0), show_default=True,
|
|
596
|
+
help='Representative paper titles to print for each topic.')
|
|
597
|
+
def topics_show(model_dir: str, representatives: int) -> None:
|
|
598
|
+
"""Print top terms and representative papers for manual topic naming."""
|
|
599
|
+
try:
|
|
600
|
+
topics = topic_descriptions(model_dir)
|
|
601
|
+
except (FileNotFoundError, OSError, ValueError) as error:
|
|
602
|
+
raise click.ClickException(str(error)) from error
|
|
603
|
+
for topic in topics:
|
|
604
|
+
name = topic['topic_name'] or '(unnamed)'
|
|
605
|
+
click.echo(f'Topic {topic["topic_id"]}: {name}')
|
|
606
|
+
click.echo(f' Terms: {", ".join(topic["top_terms"])}')
|
|
607
|
+
for paper in topic['representative_papers'][:representatives]:
|
|
608
|
+
click.echo(f' - {paper["title"]} ({float(paper["probability"]):.3f})')
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
@click.command('name')
|
|
612
|
+
@click.argument('model_dir', type=click.Path(exists=True, file_okay=False))
|
|
613
|
+
@click.argument('topic_id', type=click.IntRange(min=0))
|
|
614
|
+
@click.argument('topic_name', type=str)
|
|
615
|
+
def topics_name(model_dir: str, topic_id: int, topic_name: str) -> None:
|
|
616
|
+
"""Assign a manual human-readable name to one fitted topic."""
|
|
617
|
+
try:
|
|
618
|
+
set_topic_name(model_dir, topic_id, topic_name)
|
|
619
|
+
except (FileNotFoundError, OSError, ValueError) as error:
|
|
620
|
+
raise click.ClickException(str(error)) from error
|
|
621
|
+
click.echo(f'Named topic {topic_id}: {topic_name.strip()}')
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
@click.command('predict')
|
|
625
|
+
@click.argument('model_dir', type=click.Path(exists=True, file_okay=False))
|
|
626
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
627
|
+
@click.argument('output_path', default='paper_topics.csv', type=click.Path())
|
|
628
|
+
@click.option('--batch-size', default=128, type=click.IntRange(min=1), show_default=True)
|
|
629
|
+
def topics_predict(model_dir: str, db_path: str, output_path: str, batch_size: int) -> None:
|
|
630
|
+
"""Apply a saved LDA model to a corpus and export topic probabilities."""
|
|
631
|
+
try:
|
|
632
|
+
summary = predict_topic_model(
|
|
633
|
+
model_dir, db_path, output_path, batch_size=batch_size
|
|
634
|
+
)
|
|
635
|
+
except (FileNotFoundError, OSError, ValueError) as error:
|
|
636
|
+
raise click.ClickException(str(error)) from error
|
|
637
|
+
click.echo(
|
|
638
|
+
f'Predicted topics for {summary["papers_predicted"]} of {summary["papers_total"]} papers; '
|
|
639
|
+
f'{summary["papers_without_vocabulary_terms"]} had no model vocabulary terms.'
|
|
640
|
+
)
|
|
641
|
+
click.echo(f'Topic scores: {summary["output_path"]}')
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
@click.command('trends')
|
|
645
|
+
@click.argument('model_dir', type=click.Path(exists=True, file_okay=False))
|
|
646
|
+
@click.argument('output_dir', default='topic_trends', type=click.Path())
|
|
647
|
+
@click.option('--predictions', 'predictions_path', default=None,
|
|
648
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
649
|
+
help='Long-form prediction CSV; defaults to the model training predictions.')
|
|
650
|
+
@click.option('--bin-size', default=1, type=click.IntRange(min=1), show_default=True)
|
|
651
|
+
@click.option('--step-size', default=1, type=click.IntRange(min=1), show_default=True)
|
|
652
|
+
@click.option('--start-year', default=None, type=int)
|
|
653
|
+
@click.option('--end-year', default=None, type=int)
|
|
654
|
+
@click.option('--include-partial/--complete-only', default=True, show_default=True)
|
|
655
|
+
@click.option('--plot', is_flag=True, default=False,
|
|
656
|
+
help='Write topic_trends_plot.png in the trend output directory.')
|
|
657
|
+
@click.option('--plot-file', default=None, type=click.Path(dir_okay=False),
|
|
658
|
+
help='Write a plot to this filename instead; its extension selects the format.')
|
|
659
|
+
@click.option('--overwrite', is_flag=True, default=False,
|
|
660
|
+
help='Replace known trend artifacts in a non-empty output directory.')
|
|
661
|
+
def topics_trends(model_dir: str, output_dir: str, predictions_path: str | None,
|
|
662
|
+
bin_size: int, step_size: int, start_year: int | None,
|
|
663
|
+
end_year: int | None, include_partial: bool, plot: bool,
|
|
664
|
+
plot_file: str | None,
|
|
665
|
+
overwrite: bool) -> None:
|
|
666
|
+
"""Aggregate fixed-model topic probabilities over publication-year windows."""
|
|
667
|
+
try:
|
|
668
|
+
summary = aggregate_topic_trends(
|
|
669
|
+
model_dir,
|
|
670
|
+
output_dir,
|
|
671
|
+
predictions_path=predictions_path,
|
|
672
|
+
bin_size=bin_size,
|
|
673
|
+
step_size=step_size,
|
|
674
|
+
start_year=start_year,
|
|
675
|
+
end_year=end_year,
|
|
676
|
+
include_partial=include_partial,
|
|
677
|
+
overwrite=overwrite,
|
|
678
|
+
plot=plot_file or plot,
|
|
679
|
+
)
|
|
680
|
+
except (FileNotFoundError, OSError, RuntimeError, ValueError) as error:
|
|
681
|
+
raise click.ClickException(str(error)) from error
|
|
682
|
+
click.echo(f'Wrote {summary["windows"]} topic trend windows to {summary["trends_csv"]}.')
|
|
683
|
+
if summary['plot_path']:
|
|
684
|
+
click.echo(f'Topic trend plot: {summary["plot_path"]}')
|
|
685
|
+
if summary['papers_missing_or_invalid_date']:
|
|
686
|
+
click.echo(
|
|
687
|
+
f'{summary["papers_missing_or_invalid_date"]} papers had missing or invalid dates.',
|
|
688
|
+
err=True,
|
|
689
|
+
)
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
@click.command('store')
|
|
693
|
+
@click.argument('model_dir', type=click.Path(exists=True, file_okay=False))
|
|
694
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
695
|
+
@click.option('--name', default=None,
|
|
696
|
+
help='Immutable corpus display name; defaults to the model directory name.')
|
|
697
|
+
@click.option('--batch-size', default=128, type=click.IntRange(min=1), show_default=True)
|
|
698
|
+
def topics_store(model_dir: str, db_path: str, name: str | None, batch_size: int) -> None:
|
|
699
|
+
"""Predict afresh and transactionally store a topic model in the corpus."""
|
|
700
|
+
try:
|
|
701
|
+
summary = store_topic_model_scores(
|
|
702
|
+
model_dir, db_path, name=name, batch_size=batch_size
|
|
703
|
+
)
|
|
704
|
+
except (FileNotFoundError, OSError, ValueError) as error:
|
|
705
|
+
raise click.ClickException(str(error)) from error
|
|
706
|
+
click.echo(
|
|
707
|
+
f'Stored {summary["name"]} ({summary["model_id"]}): '
|
|
708
|
+
f'{summary["papers_predicted"]} predicted, '
|
|
709
|
+
f'{summary["papers_without_vocabulary_terms"]} without vocabulary terms.'
|
|
710
|
+
)
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
@click.command('models')
|
|
714
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
715
|
+
@click.option('--batch-size', default=128, type=click.IntRange(min=1), show_default=True)
|
|
716
|
+
def topics_models(db_path: str, batch_size: int) -> None:
|
|
717
|
+
"""List topic models and prediction freshness recorded in a corpus."""
|
|
718
|
+
models = stored_topic_models(db_path, batch_size=batch_size)
|
|
719
|
+
if not models:
|
|
720
|
+
click.echo('No topic models are stored in this corpus.')
|
|
721
|
+
return
|
|
722
|
+
for item in models:
|
|
723
|
+
state = 'current' if item['is_current'] else 'STALE'
|
|
724
|
+
click.echo(
|
|
725
|
+
f'{item["name"]} ({item["model_id"]}) [{state}]: '
|
|
726
|
+
f'{item["num_topics"]} topics, '
|
|
727
|
+
f'{item["papers_predicted"]} predicted, '
|
|
728
|
+
f'{item["papers_without_vocabulary_terms"]} without vocabulary terms; '
|
|
729
|
+
f'fields={",".join(item["text_fields"])}'
|
|
730
|
+
)
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
@click.command('scrape')
|
|
734
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
735
|
+
@click.argument('recipe', default='sse', type=str)
|
|
736
|
+
@click.option('--mode', type=click.Choice(['abstract', 'text', 'images', 'text-images']), default='text', show_default=True)
|
|
737
|
+
@click.option('--image-context', type=click.Choice(['none', 'paper-text']), default='none', show_default=True)
|
|
738
|
+
@click.option('--image-dir', default='paper_images', type=click.Path(), show_default=True)
|
|
739
|
+
@click.option('--image-extraction',
|
|
740
|
+
type=click.Choice(['auto', 'embedded', 'pages']),
|
|
741
|
+
default='auto',
|
|
742
|
+
show_default=True,
|
|
743
|
+
help='How to turn PDFs into images for vision analysis.')
|
|
744
|
+
@click.option('--image-dpi', default=200, type=int, show_default=True,
|
|
745
|
+
help='DPI for rendered page images when page rendering is used.')
|
|
746
|
+
@click.option('--image-batch-size', default='1', show_default=True,
|
|
747
|
+
help='Number of images per vision request, or "all".')
|
|
748
|
+
@click.option('--model', default=None, help='Text model name override for this scrape run.')
|
|
749
|
+
@click.option('--provider', default=None,
|
|
750
|
+
help='Text provider override: openai, anthropic, or local. Pair with --model when changing provider.')
|
|
751
|
+
@click.option('--base-url', default=None, help='Text model base URL override.')
|
|
752
|
+
@click.option('--vision-model', default=None, help='Vision model name override for this scrape run.')
|
|
753
|
+
@click.option('--vision-provider', default=None,
|
|
754
|
+
help='Vision provider override. Pair with --vision-model when changing provider.')
|
|
755
|
+
@click.option('--vision-base-url', default=None, help='Vision model base URL override.')
|
|
756
|
+
@click.option('--delete-images-after',
|
|
757
|
+
is_flag=True,
|
|
758
|
+
default=False,
|
|
759
|
+
help='Delete extracted images after successful image analysis.')
|
|
760
|
+
@click.option('--output', 'output_path',
|
|
761
|
+
default='temp_scraped_materials.csv',
|
|
762
|
+
type=click.Path(),
|
|
763
|
+
show_default=True,
|
|
764
|
+
help='CSV file for newly scraped material rows.')
|
|
765
|
+
@click.option('--force',
|
|
766
|
+
is_flag=True,
|
|
767
|
+
default=False,
|
|
768
|
+
help='Rescrape stages even if their status is already succeeded.')
|
|
769
|
+
@click.option('--ignore-filters',
|
|
770
|
+
is_flag=True,
|
|
771
|
+
default=False,
|
|
772
|
+
help='Explicitly bypass active corpus filters for this scrape run.')
|
|
773
|
+
@click.option('--count',
|
|
774
|
+
'scrape_count',
|
|
775
|
+
default=None,
|
|
776
|
+
type=int,
|
|
777
|
+
help='Maximum number of corpus papers to process in this scrape run.')
|
|
778
|
+
@click.option('--order',
|
|
779
|
+
'scrape_order',
|
|
780
|
+
type=click.Choice(sorted(SCRAPE_ORDERS)),
|
|
781
|
+
default='corpus',
|
|
782
|
+
show_default=True,
|
|
783
|
+
help='Order used to select papers for this scrape run.')
|
|
784
|
+
@click.option('--compression-scope',
|
|
785
|
+
type=click.Choice(sorted(COMPRESSION_SCOPES)),
|
|
786
|
+
default='none',
|
|
787
|
+
show_default=True,
|
|
788
|
+
help='Inputs to compress with Headroom.')
|
|
789
|
+
@click.option('--compression-mode',
|
|
790
|
+
type=click.Choice(sorted(COMPRESSION_MODES)),
|
|
791
|
+
default='auto',
|
|
792
|
+
show_default=True,
|
|
793
|
+
help='When to compress selected inputs.')
|
|
794
|
+
@click.option('--compression-ratio',
|
|
795
|
+
default='auto',
|
|
796
|
+
show_default=True,
|
|
797
|
+
help='Target compression ratio, or "auto" to fit the configured input token budget.')
|
|
798
|
+
@click.option('--compression-content-detection/--no-compression-content-detection',
|
|
799
|
+
default=True,
|
|
800
|
+
show_default=True,
|
|
801
|
+
help='Use Headroom content detection when compressing inputs.')
|
|
802
|
+
def scrape(
|
|
803
|
+
db_path: str,
|
|
804
|
+
recipe: str,
|
|
805
|
+
mode: str,
|
|
806
|
+
image_context: str,
|
|
807
|
+
image_dir: str,
|
|
808
|
+
image_extraction: str,
|
|
809
|
+
image_dpi: int,
|
|
810
|
+
image_batch_size: str,
|
|
811
|
+
model: str | None,
|
|
812
|
+
provider: str | None,
|
|
813
|
+
base_url: str | None,
|
|
814
|
+
vision_model: str | None,
|
|
815
|
+
vision_provider: str | None,
|
|
816
|
+
vision_base_url: str | None,
|
|
817
|
+
delete_images_after: bool,
|
|
818
|
+
output_path: str,
|
|
819
|
+
force: bool,
|
|
820
|
+
ignore_filters: bool,
|
|
821
|
+
scrape_count: int | None,
|
|
822
|
+
scrape_order: str,
|
|
823
|
+
compression_scope: str,
|
|
824
|
+
compression_mode: str,
|
|
825
|
+
compression_ratio: str,
|
|
826
|
+
compression_content_detection: bool,
|
|
827
|
+
) -> None:
|
|
828
|
+
"""Run text and/or image scraping over downloaded papers."""
|
|
829
|
+
scrape_papers(
|
|
830
|
+
db_path,
|
|
831
|
+
recipe,
|
|
832
|
+
mode=mode,
|
|
833
|
+
image_dir=image_dir,
|
|
834
|
+
image_context=image_context,
|
|
835
|
+
image_extraction=image_extraction,
|
|
836
|
+
image_dpi=image_dpi,
|
|
837
|
+
image_batch_size=image_batch_size,
|
|
838
|
+
model=model,
|
|
839
|
+
provider=provider,
|
|
840
|
+
base_url=base_url,
|
|
841
|
+
vision_model=vision_model,
|
|
842
|
+
vision_provider=vision_provider,
|
|
843
|
+
vision_base_url=vision_base_url,
|
|
844
|
+
delete_images_after=delete_images_after,
|
|
845
|
+
output_path=output_path,
|
|
846
|
+
force=force,
|
|
847
|
+
ignore_filters=ignore_filters,
|
|
848
|
+
scrape_count=scrape_count,
|
|
849
|
+
scrape_order=scrape_order,
|
|
850
|
+
compression_scope=compression_scope,
|
|
851
|
+
compression_mode=compression_mode,
|
|
852
|
+
compression_ratio=compression_ratio,
|
|
853
|
+
compression_content_detection=compression_content_detection,
|
|
854
|
+
)
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
@click.command('store')
|
|
858
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
859
|
+
@click.argument('in_file', default='temp_scraped_materials.csv', type=click.Path())
|
|
860
|
+
@click.argument('out_file', default='materials.csv', type=click.Path())
|
|
861
|
+
@click.argument('recipe', default='sse', type=str)
|
|
862
|
+
@click.option('--assume-yes', is_flag=True, default=False,
|
|
863
|
+
help='Store converted results without an interactive confirmation prompt.')
|
|
864
|
+
def store(db_path: str, in_file: str, out_file: str, recipe: str, assume_yes: bool) -> None:
|
|
865
|
+
"""Store temporary scrape results in the final materials CSV."""
|
|
866
|
+
store_results(db_path, in_file, out_file, True, recipe, assume_yes=assume_yes)
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
def update_elsevier_api_key() -> None:
|
|
870
|
+
"""Prompt for and save an Elsevier API key."""
|
|
871
|
+
update_elsevier_key()
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
def update_core_api_key() -> None:
|
|
875
|
+
"""Prompt for and save a CORE API key."""
|
|
876
|
+
update_core_key()
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def update_unpaywall_api_email() -> None:
|
|
880
|
+
"""Prompt for and save an Unpaywall email address."""
|
|
881
|
+
update_unpaywall_email()
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
def update_crossref_api_email() -> None:
|
|
885
|
+
"""Prompt for and save a Crossref contact email address."""
|
|
886
|
+
update_crossref_email()
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def update_openalex_api_key() -> None:
|
|
890
|
+
"""Prompt for and save an OpenAlex API key."""
|
|
891
|
+
update_openalex_key()
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
def update_ncbi_api_key() -> None:
|
|
895
|
+
"""Prompt for and save an NCBI E-utilities API key."""
|
|
896
|
+
update_ncbi_key()
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
def update_ncbi_api_email() -> None:
|
|
900
|
+
"""Prompt for and save an NCBI E-utilities contact email address."""
|
|
901
|
+
update_ncbi_email()
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
def update_openai_api_key() -> None:
|
|
905
|
+
"""Prompt for and save an OpenAI API key."""
|
|
906
|
+
update_openai_key()
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def update_anthropic_api_key() -> None:
|
|
910
|
+
"""Prompt for and save an Anthropic API key."""
|
|
911
|
+
update_anthropic_key()
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
@click.command('model')
|
|
915
|
+
@click.argument('profile', default='text', type=click.Choice(['text', 'vision']))
|
|
916
|
+
@click.option('--provider', prompt=True, help='Provider: openai, anthropic, or local.')
|
|
917
|
+
@click.option('--model', prompt=True, help='Model name.')
|
|
918
|
+
@click.option('--base-url', default=None, help='Base URL for local providers.')
|
|
919
|
+
@click.option('--api-key', default=None, help='Provider API key. Leave unset for env/provider defaults.')
|
|
920
|
+
@click.option('--capability', 'capabilities',
|
|
921
|
+
multiple=True,
|
|
922
|
+
help='Optional override. By default capabilities are inferred from profile/model name.')
|
|
923
|
+
@click.option('--temperature',
|
|
924
|
+
default=0.0,
|
|
925
|
+
type=float,
|
|
926
|
+
show_default=True,
|
|
927
|
+
help='Sampling temperature for model requests.')
|
|
928
|
+
@click.option('--top-p',
|
|
929
|
+
default=1.0,
|
|
930
|
+
type=float,
|
|
931
|
+
show_default=True,
|
|
932
|
+
help='Nucleus sampling probability mass for model requests.')
|
|
933
|
+
@click.option('--input-token-limit',
|
|
934
|
+
default=DEFAULT_INPUT_TOKEN_LIMIT,
|
|
935
|
+
type=int,
|
|
936
|
+
show_default=True,
|
|
937
|
+
help='Maximum input tokens to send to the model before chunking.')
|
|
938
|
+
def model_config(profile: str, provider: str, model: str, base_url: str | None, api_key: str | None,
|
|
939
|
+
capabilities: tuple[str, ...], temperature: float, top_p: float, input_token_limit: int) -> None:
|
|
940
|
+
"""Configure a text or vision model profile from CLI options."""
|
|
941
|
+
caps = list(capabilities) or infer_model_capabilities(profile, model)
|
|
942
|
+
set_model_profile(
|
|
943
|
+
profile,
|
|
944
|
+
provider,
|
|
945
|
+
model,
|
|
946
|
+
base_url,
|
|
947
|
+
api_key,
|
|
948
|
+
caps,
|
|
949
|
+
temperature=temperature,
|
|
950
|
+
top_p=top_p,
|
|
951
|
+
input_token_limit=input_token_limit,
|
|
952
|
+
)
|
|
953
|
+
click.echo(
|
|
954
|
+
f'Updated {profile} model profile: {provider}/{model} [{", ".join(caps)}] temperature={temperature} top_p={top_p} input_token_limit={input_token_limit}')
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
@click.command('status')
|
|
958
|
+
def model_status() -> None:
|
|
959
|
+
"""Print configured text and vision model profiles."""
|
|
960
|
+
for profile in ['text', 'vision']:
|
|
961
|
+
config = get_model_profile(profile)
|
|
962
|
+
capabilities = ', '.join(config.get('capabilities', []))
|
|
963
|
+
click.echo(
|
|
964
|
+
f'{profile}: {config.get("provider")}/{config.get("model")} capabilities=[{capabilities}] temperature={config.get("temperature")} top_p={config.get("top_p")} input_token_limit={config.get("input_token_limit")} base_url={config.get("base_url")}')
|
|
965
|
+
|
|
966
|
+
|
|
967
|
+
@click.command('reset')
|
|
968
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
969
|
+
def reset_miner(db_path: str) -> None:
|
|
970
|
+
"""Reset pipeline statuses in the paper corpus."""
|
|
971
|
+
reset(db_path)
|
|
972
|
+
|
|
973
|
+
|
|
974
|
+
@click.command('status')
|
|
975
|
+
@click.argument('db_path', default='papers.db', type=click.Path(exists=True))
|
|
976
|
+
def miner_status(db_path: str) -> None:
|
|
977
|
+
"""Print pipeline progress for the paper corpus."""
|
|
978
|
+
status(db_path)
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
@click.group()
|
|
982
|
+
def main() -> None:
|
|
983
|
+
"""Build, analyse, and extract structured data from paper corpora."""
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
@click.group('corpus')
|
|
987
|
+
def corpus_group() -> None:
|
|
988
|
+
"""Inspect and maintain a paper corpus."""
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
@click.group('filter')
|
|
992
|
+
def filter_group() -> None:
|
|
993
|
+
"""Apply, inspect, and reset corpus filters."""
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
@click.group('topics')
|
|
997
|
+
def topics_group() -> None:
|
|
998
|
+
"""Train, inspect, and apply LDA topic models."""
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
@click.group('import')
|
|
1002
|
+
def import_group() -> None:
|
|
1003
|
+
"""Import existing papers or an author's publication list."""
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
@click.group('config')
|
|
1007
|
+
def config_group() -> None:
|
|
1008
|
+
"""Configure model profiles and provider credentials."""
|
|
1009
|
+
|
|
1010
|
+
|
|
1011
|
+
main.add_command(paper_search, 'search')
|
|
1012
|
+
main.add_command(download, 'download')
|
|
1013
|
+
main.add_command(enrich, 'enrich')
|
|
1014
|
+
main.add_command(scrape, 'scrape')
|
|
1015
|
+
main.add_command(store, 'store')
|
|
1016
|
+
main.add_command(miner_status, 'status')
|
|
1017
|
+
main.add_command(reset_miner, 'reset')
|
|
1018
|
+
|
|
1019
|
+
corpus_group.add_command(corpus_status, 'stats')
|
|
1020
|
+
main.add_command(corpus_group)
|
|
1021
|
+
|
|
1022
|
+
filter_group.add_command(filter_regex, 'regex')
|
|
1023
|
+
filter_group.add_command(filter_topic, 'topic')
|
|
1024
|
+
filter_group.add_command(filter_status, 'status')
|
|
1025
|
+
filter_group.add_command(filter_reset, 'reset')
|
|
1026
|
+
main.add_command(filter_group)
|
|
1027
|
+
|
|
1028
|
+
topics_group.add_command(topics_train, 'train')
|
|
1029
|
+
topics_group.add_command(topics_compare, 'compare')
|
|
1030
|
+
topics_group.add_command(topics_show, 'show')
|
|
1031
|
+
topics_group.add_command(topics_name, 'name')
|
|
1032
|
+
topics_group.add_command(topics_predict, 'predict')
|
|
1033
|
+
topics_group.add_command(topics_trends, 'trends')
|
|
1034
|
+
topics_group.add_command(topics_store, 'store')
|
|
1035
|
+
topics_group.add_command(topics_models, 'models')
|
|
1036
|
+
main.add_command(topics_group)
|
|
1037
|
+
|
|
1038
|
+
import_group.add_command(import_pdf_folder, 'pdfs')
|
|
1039
|
+
import_group.add_command(import_author, 'author')
|
|
1040
|
+
main.add_command(import_group)
|
|
1041
|
+
|
|
1042
|
+
config_group.add_command(model_config, 'model')
|
|
1043
|
+
config_group.add_command(model_status, 'status')
|
|
1044
|
+
config_group.add_command(click.command('elsevier-key')(update_elsevier_api_key))
|
|
1045
|
+
config_group.add_command(click.command('core-key')(update_core_api_key))
|
|
1046
|
+
config_group.add_command(click.command('unpaywall-email')(update_unpaywall_api_email))
|
|
1047
|
+
config_group.add_command(click.command('crossref-email')(update_crossref_api_email))
|
|
1048
|
+
config_group.add_command(click.command('openalex-key')(update_openalex_api_key))
|
|
1049
|
+
config_group.add_command(click.command('ncbi-key')(update_ncbi_api_key))
|
|
1050
|
+
config_group.add_command(click.command('ncbi-email')(update_ncbi_api_email))
|
|
1051
|
+
config_group.add_command(click.command('openai-key')(update_openai_api_key))
|
|
1052
|
+
config_group.add_command(click.command('anthropic-key')(update_anthropic_api_key))
|
|
1053
|
+
main.add_command(config_group)
|