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,1390 @@
1
+ """Persistent post-download filtering for paper corpora.
2
+
3
+ Regex and stored-topic filters are evaluated independently for every paper and
4
+ then combined in application order. The generic SQLite tables deliberately
5
+ keep definitions and paper-level decisions separate from scrape statuses.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ import sqlite3
13
+ from collections.abc import Iterable, Mapping, Sequence
14
+ from os import PathLike
15
+ from pathlib import Path
16
+ from typing import Any, Literal, TypeAlias, TypeVar
17
+
18
+ import regex
19
+
20
+ from paperminertoolkit.corpus.database import connect, get_asset, paper_rows, utc_now
21
+ from paperminertoolkit.corpus.documents import read_pdf_bytes, trim_reference_section
22
+
23
+
24
+ FILTER_FIELDS = {'title', 'abstract', 'full_text'}
25
+ FILTER_STATUSES = {'included', 'excluded', 'unavailable'}
26
+ JOIN_OPERATORS = {'and', 'or'}
27
+ DEFAULT_TIMEOUT_MS = 500
28
+ MAX_MATCHES_PER_FIELD = 1000
29
+ MAX_SNIPPETS_PER_FIELD = 3
30
+ SNIPPET_CONTEXT = 80
31
+ T = TypeVar('T')
32
+ _FilterStatus: TypeAlias = Literal['included', 'excluded', 'unavailable']
33
+ _RegexRule: TypeAlias = dict[str, str]
34
+ _RegexDefinition: TypeAlias = dict[str, Any]
35
+ _CompiledDefinition: TypeAlias = dict[str, list[tuple[_RegexRule, regex.Pattern]]]
36
+ _FilterOverview: TypeAlias = dict[str, Any]
37
+
38
+
39
+ def _require_type(value: object, expected_type: type[T], label: str) -> T:
40
+ """Validate a value's type.
41
+
42
+ Parameters
43
+ ----------
44
+ value : object
45
+ Value to validate.
46
+ expected_type : type[T]
47
+ Required Python type.
48
+ label : str
49
+ Human-readable field label for errors.
50
+
51
+ Returns
52
+ -------
53
+ T
54
+ The original validated value.
55
+
56
+ Raises
57
+ ------
58
+ ValueError
59
+ If ``value`` is not an instance of ``expected_type``.
60
+ """
61
+ if not isinstance(value, expected_type):
62
+ raise ValueError(f'{label} must be {expected_type.__name__}.')
63
+ return value
64
+
65
+
66
+ def _normalize_rule(rule: object, label: str) -> _RegexRule:
67
+ """Normalize one regular-expression rule.
68
+
69
+ Parameters
70
+ ----------
71
+ rule : object
72
+ Rule containing a name and pattern.
73
+ label : str
74
+ Rule location used in validation errors.
75
+
76
+ Returns
77
+ -------
78
+ _RegexRule
79
+ Normalized rule name and pattern.
80
+
81
+ Raises
82
+ ------
83
+ ValueError
84
+ If the rule is malformed or empty.
85
+ """
86
+ _require_type(rule, dict, label)
87
+ name = str(rule.get('name') or '').strip()
88
+ pattern = rule.get('pattern')
89
+ if not name:
90
+ raise ValueError(f'{label} requires a non-empty name.')
91
+ if not isinstance(pattern, str) or not pattern:
92
+ raise ValueError(f'{label} requires a non-empty string pattern.')
93
+ return {'name': name, 'pattern': pattern}
94
+
95
+
96
+ def normalize_regex_definition(
97
+ definition: object,
98
+ fields: Iterable[str] | None = None,
99
+ timeout_ms: int | None = None,
100
+ ) -> _RegexDefinition:
101
+ """Normalize a regular-expression filter definition.
102
+
103
+ Parameters
104
+ ----------
105
+ definition : object
106
+ Raw filter definition.
107
+ fields : Iterable[str] or None, optional
108
+ Content fields overriding those in the definition.
109
+ timeout_ms : int, optional
110
+ Per-field matching timeout overriding the definition.
111
+
112
+ Returns
113
+ -------
114
+ _RegexDefinition
115
+ Validated deterministic filter definition.
116
+
117
+ Raises
118
+ ------
119
+ ValueError
120
+ If names, rules, fields, or options are invalid.
121
+ """
122
+ _require_type(definition, dict, 'Filter definition')
123
+ name = str(definition.get('name') or '').strip()
124
+ if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]*', name):
125
+ raise ValueError('Filter name must use only letters, numbers, dots, underscores, and hyphens.')
126
+
127
+ include_mode = str(definition.get('include_mode', 'any')).lower()
128
+ if include_mode not in {'any', 'all'}:
129
+ raise ValueError('include_mode must be "any" or "all".')
130
+ include_rules = definition.get('include', [])
131
+ exclude_rules = definition.get('exclude', [])
132
+ if not isinstance(include_rules, list) or not isinstance(exclude_rules, list):
133
+ raise ValueError('include and exclude must be JSON lists.')
134
+ include = [
135
+ _normalize_rule(rule, f'include[{index}]')
136
+ for index, rule in enumerate(include_rules)
137
+ ]
138
+ if not include:
139
+ raise ValueError('A regex filter requires at least one include rule.')
140
+ exclude = [
141
+ _normalize_rule(rule, f'exclude[{index}]')
142
+ for index, rule in enumerate(exclude_rules)
143
+ ]
144
+ rule_names = [rule['name'] for rule in include + exclude]
145
+ if len(rule_names) != len(set(rule_names)):
146
+ raise ValueError('Regex rule names must be unique within a filter.')
147
+
148
+ resolved_fields = list(fields) if fields else definition.get(
149
+ 'fields', ['title', 'abstract', 'full_text']
150
+ )
151
+ if not isinstance(resolved_fields, (list, tuple)) or not resolved_fields:
152
+ raise ValueError('fields must be a non-empty list.')
153
+ resolved_fields = list(dict.fromkeys(str(field).lower() for field in resolved_fields))
154
+ unknown_fields = set(resolved_fields) - FILTER_FIELDS
155
+ if unknown_fields:
156
+ raise ValueError(f'Unknown filter fields: {", ".join(sorted(unknown_fields))}.')
157
+
158
+ resolved_timeout = timeout_ms if timeout_ms is not None else definition.get(
159
+ 'timeout_ms', DEFAULT_TIMEOUT_MS
160
+ )
161
+ if isinstance(resolved_timeout, bool) or not isinstance(resolved_timeout, int) or resolved_timeout < 1:
162
+ raise ValueError('timeout_ms must be a positive integer.')
163
+ case_sensitive = definition.get('case_sensitive', False)
164
+ if not isinstance(case_sensitive, bool):
165
+ raise ValueError('case_sensitive must be true or false.')
166
+ description = definition.get('description', '')
167
+ if not isinstance(description, str):
168
+ raise ValueError('description must be a string.')
169
+
170
+ return {
171
+ 'name': name,
172
+ 'description': description.strip(),
173
+ 'fields': resolved_fields,
174
+ 'case_sensitive': case_sensitive,
175
+ 'include_mode': include_mode,
176
+ 'include': include,
177
+ 'exclude': exclude,
178
+ 'timeout_ms': resolved_timeout,
179
+ }
180
+
181
+
182
+ def load_regex_definition(
183
+ path: str | PathLike[str],
184
+ fields: Iterable[str] | None = None,
185
+ timeout_ms: int | None = None,
186
+ ) -> _RegexDefinition:
187
+ """Load and normalize a JSON filter definition.
188
+
189
+ Parameters
190
+ ----------
191
+ path : str or os.PathLike[str]
192
+ JSON definition file.
193
+ fields : Iterable[str] or None, optional
194
+ Content fields overriding the file.
195
+ timeout_ms : int, optional
196
+ Matching timeout overriding the file.
197
+
198
+ Returns
199
+ -------
200
+ _RegexDefinition
201
+ Validated filter definition.
202
+
203
+ Raises
204
+ ------
205
+ OSError
206
+ If the definition file cannot be read.
207
+ ValueError
208
+ If the JSON or filter definition is invalid.
209
+ """
210
+ try:
211
+ definition = json.loads(Path(path).read_text(encoding='utf-8'))
212
+ except json.JSONDecodeError as error:
213
+ raise ValueError(f'Invalid filter JSON: {error}') from error
214
+ return normalize_regex_definition(definition, fields=fields, timeout_ms=timeout_ms)
215
+
216
+
217
+ def _normalize_topic_rule(
218
+ rule: object,
219
+ label: str,
220
+ valid_topic_ids: set[int],
221
+ ) -> dict[str, Any]:
222
+ """Normalize one probability or dominance topic condition.
223
+
224
+ Parameters
225
+ ----------
226
+ rule : object
227
+ Candidate mapping containing a rule name, topic ID, and threshold or
228
+ dominance requirement.
229
+ label : str
230
+ Rule location used in validation errors.
231
+ valid_topic_ids : set[int]
232
+ Topic IDs defined by the referenced stored model.
233
+
234
+ Returns
235
+ -------
236
+ dict[str, Any]
237
+ Validated topic rule with explicit optional values.
238
+
239
+ Raises
240
+ ------
241
+ ValueError
242
+ If the rule is malformed, refers to an unknown topic, or contains no
243
+ effective condition.
244
+ """
245
+ _require_type(rule, dict, label)
246
+ name = str(rule.get('name') or '').strip()
247
+ if not name:
248
+ raise ValueError(f'{label} requires a non-empty name.')
249
+ topic_id = rule.get('topic_id')
250
+ if isinstance(topic_id, bool) or not isinstance(topic_id, int):
251
+ raise ValueError(f'{label}.topic_id must be an integer.')
252
+ if topic_id not in valid_topic_ids:
253
+ raise ValueError(f'{label} refers to unknown topic {topic_id}.')
254
+ minimum = rule.get('min_probability')
255
+ if minimum is not None:
256
+ if isinstance(minimum, bool) or not isinstance(minimum, (int, float)) or not 0 <= minimum <= 1:
257
+ raise ValueError(f'{label}.min_probability must be between 0 and 1.')
258
+ minimum = float(minimum)
259
+ require_dominant = rule.get('require_dominant', False)
260
+ if not isinstance(require_dominant, bool):
261
+ raise ValueError(f'{label}.require_dominant must be true or false.')
262
+ if minimum is None and not require_dominant:
263
+ raise ValueError(
264
+ f'{label} requires min_probability and/or require_dominant=true.'
265
+ )
266
+ return {
267
+ 'name': name,
268
+ 'topic_id': topic_id,
269
+ 'min_probability': minimum,
270
+ 'require_dominant': require_dominant,
271
+ }
272
+
273
+
274
+ def normalize_topic_definition(
275
+ conn: sqlite3.Connection,
276
+ definition: object,
277
+ ) -> dict[str, Any]:
278
+ """Resolve and normalize a persistent topic-filter definition.
279
+
280
+ Parameters
281
+ ----------
282
+ conn : sqlite3.Connection
283
+ Open corpus connection containing stored topic models.
284
+ definition : object
285
+ Candidate topic-filter definition loaded from JSON.
286
+
287
+ Returns
288
+ -------
289
+ dict[str, Any]
290
+ Validated definition with the model name and immutable model ID.
291
+
292
+ Raises
293
+ ------
294
+ ValueError
295
+ If the definition is malformed, its model is unavailable, or any rule
296
+ refers to an unknown topic.
297
+ """
298
+ _require_type(definition, dict, 'Filter definition')
299
+ name = str(definition.get('name') or '').strip()
300
+ if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]*', name):
301
+ raise ValueError('Filter name must use only letters, numbers, dots, underscores, and hyphens.')
302
+ model_reference = str(definition.get('model') or '').strip()
303
+ if not model_reference:
304
+ raise ValueError('A topic filter requires a stored model name or model ID.')
305
+ model = conn.execute(
306
+ 'SELECT * FROM topic_models WHERE name = ? OR model_id = ?',
307
+ (model_reference, model_reference),
308
+ ).fetchone()
309
+ if model is None:
310
+ raise ValueError(f'No stored topic model matches {model_reference!r}.')
311
+ valid_topic_ids = {
312
+ row['topic_id']
313
+ for row in conn.execute(
314
+ 'SELECT topic_id FROM topic_definitions WHERE model_id = ?',
315
+ (model['model_id'],),
316
+ ).fetchall()
317
+ }
318
+ include_mode = str(definition.get('include_mode', 'any')).lower()
319
+ if include_mode not in {'any', 'all'}:
320
+ raise ValueError('include_mode must be "any" or "all".')
321
+ include_values = definition.get('include', [])
322
+ exclude_values = definition.get('exclude', [])
323
+ if not isinstance(include_values, list) or not isinstance(exclude_values, list):
324
+ raise ValueError('include and exclude must be JSON lists.')
325
+ include = [
326
+ _normalize_topic_rule(rule, f'include[{index}]', valid_topic_ids)
327
+ for index, rule in enumerate(include_values)
328
+ ]
329
+ if not include:
330
+ raise ValueError('A topic filter requires at least one include rule.')
331
+ exclude = [
332
+ _normalize_topic_rule(rule, f'exclude[{index}]', valid_topic_ids)
333
+ for index, rule in enumerate(exclude_values)
334
+ ]
335
+ rule_names = [rule['name'] for rule in include + exclude]
336
+ if len(rule_names) != len(set(rule_names)):
337
+ raise ValueError('Topic rule names must be unique within a filter.')
338
+ description = definition.get('description', '')
339
+ if not isinstance(description, str):
340
+ raise ValueError('description must be a string.')
341
+ return {
342
+ 'name': name,
343
+ 'description': description.strip(),
344
+ 'model': model['name'],
345
+ 'model_id': model['model_id'],
346
+ 'include_mode': include_mode,
347
+ 'include': include,
348
+ 'exclude': exclude,
349
+ }
350
+
351
+
352
+ def load_topic_definition(
353
+ conn: sqlite3.Connection,
354
+ path: str | PathLike[str],
355
+ ) -> dict[str, Any]:
356
+ """Load and normalize a topic-filter JSON document.
357
+
358
+ Parameters
359
+ ----------
360
+ conn : sqlite3.Connection
361
+ Open corpus connection used to resolve the stored model.
362
+ path : str or os.PathLike[str]
363
+ Topic-filter JSON file.
364
+
365
+ Returns
366
+ -------
367
+ dict[str, Any]
368
+ Validated persistent topic-filter definition.
369
+
370
+ Raises
371
+ ------
372
+ OSError
373
+ If the definition file cannot be read.
374
+ ValueError
375
+ If the JSON or topic-filter definition is invalid.
376
+ """
377
+ try:
378
+ value = json.loads(Path(path).read_text(encoding='utf-8'))
379
+ except json.JSONDecodeError as error:
380
+ raise ValueError(f'Invalid filter JSON: {error}') from error
381
+ return normalize_topic_definition(conn, value)
382
+
383
+
384
+ def compile_regex_definition(definition: _RegexDefinition) -> _CompiledDefinition:
385
+ """Compile every pattern in a filter definition.
386
+
387
+ Parameters
388
+ ----------
389
+ definition : _RegexDefinition
390
+ Normalized regular-expression filter definition.
391
+
392
+ Returns
393
+ -------
394
+ _CompiledDefinition
395
+ Include and exclude rules paired with compiled expressions.
396
+
397
+ Raises
398
+ ------
399
+ ValueError
400
+ If any regular expression is invalid.
401
+ """
402
+ flags = regex.VERSION1
403
+ if not definition['case_sensitive']:
404
+ flags |= regex.IGNORECASE
405
+ compiled = {'include': [], 'exclude': []}
406
+ for rule_type in compiled:
407
+ for rule in definition[rule_type]:
408
+ try:
409
+ expression = regex.compile(rule['pattern'], flags)
410
+ except regex.error as error:
411
+ raise ValueError(f'Invalid regex in rule {rule["name"]!r}: {error}') from error
412
+ compiled[rule_type].append((rule, expression))
413
+ return compiled
414
+
415
+
416
+ def _decode_text_asset(asset: Mapping[str, Any] | None) -> str | None:
417
+ """Decode and trim a stored text asset.
418
+
419
+ Parameters
420
+ ----------
421
+ asset : Mapping[str, Any] or None
422
+ Corpus asset row containing binary content.
423
+
424
+ Returns
425
+ -------
426
+ str or None
427
+ Usable text without references, or ``None``.
428
+ """
429
+ if asset is None:
430
+ return None
431
+ text = asset['content'].decode('utf-8', errors='replace')
432
+ text = trim_reference_section(text)
433
+ return text if text.strip() else None
434
+
435
+
436
+ def _paper_content(
437
+ conn: sqlite3.Connection,
438
+ paper: Mapping[str, Any],
439
+ fields: Iterable[str],
440
+ ) -> tuple[dict[str, str], dict[str, str], list[str]]:
441
+ """Load the selected raw content fields for a paper.
442
+
443
+ Parameters
444
+ ----------
445
+ conn : sqlite3.Connection
446
+ Open corpus connection.
447
+ paper : Mapping[str, Any]
448
+ Corpus paper row.
449
+ fields : Iterable[str]
450
+ Content fields to load.
451
+
452
+ Returns
453
+ -------
454
+ tuple[dict[str, str], dict[str, str], list[str]]
455
+ Available content, the source of each field, and reasons that requested
456
+ fields were unavailable.
457
+ """
458
+ content = {}
459
+ sources = {}
460
+ unavailable = []
461
+ paper_id = paper['paper_id']
462
+
463
+ if 'title' in fields:
464
+ title = str(paper.get('title') or '').strip()
465
+ if title:
466
+ content['title'] = title
467
+ sources['title'] = 'metadata:title'
468
+ else:
469
+ unavailable.append('title: missing')
470
+
471
+ if 'abstract' in fields:
472
+ try:
473
+ abstract = _decode_text_asset(get_asset(conn, paper_id, 'abstract'))
474
+ except Exception as error:
475
+ abstract = None
476
+ unavailable.append(f'abstract: unreadable ({error})')
477
+ if abstract:
478
+ content['abstract'] = abstract
479
+ sources['abstract'] = 'corpus:abstract'
480
+ elif not any(reason.startswith('abstract:') for reason in unavailable):
481
+ unavailable.append('abstract: missing')
482
+
483
+ if 'full_text' in fields:
484
+ full_text = None
485
+ text_error = None
486
+ pdf_error = None
487
+ try:
488
+ full_text = _decode_text_asset(get_asset(conn, paper_id, 'text'))
489
+ except Exception as error:
490
+ text_error = error
491
+ if full_text:
492
+ sources['full_text'] = 'corpus:text'
493
+ else:
494
+ try:
495
+ pdf_asset = get_asset(conn, paper_id, 'pdf')
496
+ except Exception as error:
497
+ pdf_asset = None
498
+ pdf_error = error
499
+ if pdf_asset is not None:
500
+ try:
501
+ full_text = trim_reference_section(read_pdf_bytes(pdf_asset['content']))
502
+ if not full_text.strip():
503
+ full_text = None
504
+ else:
505
+ sources['full_text'] = 'corpus:pdf'
506
+ except Exception as error:
507
+ pdf_error = error
508
+ if full_text:
509
+ content['full_text'] = full_text
510
+ elif text_error or pdf_error:
511
+ errors = '; '.join(str(error) for error in [text_error, pdf_error] if error)
512
+ unavailable.append(f'full_text: unreadable ({errors})')
513
+ else:
514
+ unavailable.append('full_text: missing')
515
+ return content, sources, unavailable
516
+
517
+
518
+ def _snippet(text: str, start: int, end: int) -> str:
519
+ """Return normalized context surrounding a matched text span.
520
+
521
+ Parameters
522
+ ----------
523
+ text : str
524
+ Complete text containing the match.
525
+ start : int
526
+ Inclusive match start offset.
527
+ end : int
528
+ Exclusive match end offset.
529
+
530
+ Returns
531
+ -------
532
+ str
533
+ Whitespace-normalized context around the match.
534
+ """
535
+ snippet = text[max(0, start - SNIPPET_CONTEXT):min(len(text), end + SNIPPET_CONTEXT)]
536
+ return re.sub(r'\s+', ' ', snippet).strip()
537
+
538
+
539
+ def _match_rule(
540
+ expression: regex.Pattern,
541
+ content: Mapping[str, str],
542
+ timeout_seconds: float,
543
+ ) -> tuple[list[dict[str, Any]], list[str]]:
544
+ """Collect bounded matches for one expression across content fields.
545
+
546
+ Parameters
547
+ ----------
548
+ expression : regex.Pattern
549
+ Compiled regular expression to evaluate.
550
+ content : Mapping[str, str]
551
+ Content keyed by field name.
552
+ timeout_seconds : float
553
+ Maximum matching time for each field, in seconds.
554
+
555
+ Returns
556
+ -------
557
+ tuple[list[dict[str, Any]], list[str]]
558
+ Match evidence and fields whose evaluation timed out.
559
+ """
560
+ matches = []
561
+ timed_out = []
562
+ for field, text in content.items():
563
+ count = 0
564
+ snippets = []
565
+ truncated = False
566
+ try:
567
+ for match in expression.finditer(text, timeout=timeout_seconds):
568
+ count += 1
569
+ if len(snippets) < MAX_SNIPPETS_PER_FIELD:
570
+ snippets.append(_snippet(text, match.start(), match.end()))
571
+ if count >= MAX_MATCHES_PER_FIELD:
572
+ truncated = True
573
+ break
574
+ except TimeoutError:
575
+ timed_out.append(field)
576
+ if count:
577
+ matches.append({
578
+ 'field': field,
579
+ 'count': count,
580
+ 'count_truncated': truncated,
581
+ 'snippets': snippets,
582
+ })
583
+ return matches, timed_out
584
+
585
+
586
+ def evaluate_regex_paper(
587
+ conn: sqlite3.Connection,
588
+ paper: Mapping[str, Any],
589
+ definition: _RegexDefinition,
590
+ compiled: _CompiledDefinition,
591
+ ) -> tuple[_FilterStatus, dict[str, Any], str]:
592
+ """Evaluate one regex definition against one corpus paper.
593
+
594
+ Parameters
595
+ ----------
596
+ conn : sqlite3.Connection
597
+ Open corpus connection.
598
+ paper : Mapping[str, Any]
599
+ Corpus paper row to evaluate.
600
+ definition : _RegexDefinition
601
+ Normalized regex filter definition.
602
+ compiled : _CompiledDefinition
603
+ Compiled include and exclude rules.
604
+
605
+ Returns
606
+ -------
607
+ tuple[_FilterStatus, dict[str, Any], str]
608
+ Filter status, structured match evidence, and a joined unavailable
609
+ reason.
610
+ """
611
+ content, sources, unavailable = _paper_content(conn, paper, definition['fields'])
612
+ timeout_seconds = definition['timeout_ms'] / 1000
613
+ evidence_matches = []
614
+ timed_out = []
615
+ matched_rules = {'include': set(), 'exclude': set()}
616
+
617
+ for rule_type in ['include', 'exclude']:
618
+ for rule, expression in compiled[rule_type]:
619
+ matches, timeout_fields = _match_rule(expression, content, timeout_seconds)
620
+ if matches:
621
+ matched_rules[rule_type].add(rule['name'])
622
+ evidence_matches.append({
623
+ 'type': rule_type,
624
+ 'name': rule['name'],
625
+ 'pattern': rule['pattern'],
626
+ 'matches': matches,
627
+ })
628
+ timed_out.extend(
629
+ f'{rule_type}:{rule["name"]}:{field}' for field in timeout_fields
630
+ )
631
+
632
+ if matched_rules['exclude']:
633
+ status = 'excluded'
634
+ else:
635
+ include_names = {rule['name'] for rule in definition['include']}
636
+ if definition['include_mode'] == 'any':
637
+ include_satisfied = bool(matched_rules['include'])
638
+ else:
639
+ include_satisfied = matched_rules['include'] == include_names
640
+ if include_satisfied:
641
+ status = 'included'
642
+ elif unavailable or timed_out:
643
+ status = 'unavailable'
644
+ else:
645
+ status = 'excluded'
646
+
647
+ unavailable_reasons = unavailable + [f'regex timeout: {item}' for item in timed_out]
648
+ evidence = {
649
+ 'available_fields': list(content),
650
+ 'sources': sources,
651
+ 'matched_include_rules': sorted(matched_rules['include']),
652
+ 'matched_exclude_rules': sorted(matched_rules['exclude']),
653
+ 'matches': evidence_matches,
654
+ 'unavailable': unavailable_reasons,
655
+ }
656
+ return status, evidence, '; '.join(unavailable_reasons)
657
+
658
+
659
+ def _topic_rule_matches(
660
+ rule: Mapping[str, Any],
661
+ probability: float,
662
+ dominant_topic: int | None,
663
+ ) -> bool:
664
+ """Evaluate one normalized condition against a paper's topic result.
665
+
666
+ Parameters
667
+ ----------
668
+ rule : Mapping[str, Any]
669
+ Normalized probability or dominance condition.
670
+ probability : float
671
+ Paper probability for the rule's topic.
672
+ dominant_topic : int or None
673
+ Paper's dominant topic ID when prediction succeeded.
674
+
675
+ Returns
676
+ -------
677
+ bool
678
+ ``True`` when every configured condition is satisfied.
679
+ """
680
+ if rule['min_probability'] is not None and probability < rule['min_probability']:
681
+ return False
682
+ if rule['require_dominant'] and dominant_topic != rule['topic_id']:
683
+ return False
684
+ return True
685
+
686
+
687
+ def evaluate_topic_paper(
688
+ conn: sqlite3.Connection,
689
+ paper: Mapping[str, Any],
690
+ definition: Mapping[str, Any],
691
+ ) -> tuple[_FilterStatus, dict[str, Any], str]:
692
+ """Evaluate a stored topic-filter definition for one corpus paper.
693
+
694
+ Parameters
695
+ ----------
696
+ conn : sqlite3.Connection
697
+ Open corpus connection containing predictions and scores.
698
+ paper : Mapping[str, Any]
699
+ Corpus paper row to classify.
700
+ definition : Mapping[str, Any]
701
+ Normalized topic-filter definition.
702
+
703
+ Returns
704
+ -------
705
+ tuple[_FilterStatus, dict[str, Any], str]
706
+ Filter status, structured rule evidence, and an unavailable reason.
707
+ """
708
+ prediction = conn.execute(
709
+ 'SELECT status, dominant_topic_id FROM paper_topic_predictions '
710
+ 'WHERE model_id = ? AND paper_id = ?',
711
+ (definition['model_id'], paper['paper_id']),
712
+ ).fetchone()
713
+ if prediction is None:
714
+ reason = 'topic prediction missing'
715
+ return 'unavailable', {'model_id': definition['model_id'], 'unavailable': [reason]}, reason
716
+ if prediction['status'] != 'predicted':
717
+ reason = prediction['status']
718
+ return 'unavailable', {'model_id': definition['model_id'], 'unavailable': [reason]}, reason
719
+ scores = {
720
+ row['topic_id']: row['probability']
721
+ for row in conn.execute(
722
+ 'SELECT topic_id, probability FROM paper_topic_scores '
723
+ 'WHERE model_id = ? AND paper_id = ?',
724
+ (definition['model_id'], paper['paper_id']),
725
+ ).fetchall()
726
+ }
727
+ required_ids = {rule['topic_id'] for rule in definition['include'] + definition['exclude']}
728
+ if not required_ids <= scores.keys():
729
+ reason = 'topic scores incomplete'
730
+ return 'unavailable', {'model_id': definition['model_id'], 'unavailable': [reason]}, reason
731
+ topic_names = {
732
+ row['topic_id']: row['topic_name']
733
+ for row in conn.execute(
734
+ 'SELECT topic_id, topic_name FROM topic_definitions WHERE model_id = ?',
735
+ (definition['model_id'],),
736
+ ).fetchall()
737
+ }
738
+ matched = {'include': [], 'exclude': []}
739
+ evidence_rules = []
740
+ for rule_type in ['include', 'exclude']:
741
+ for rule in definition[rule_type]:
742
+ probability = scores[rule['topic_id']]
743
+ did_match = _topic_rule_matches(
744
+ rule, probability, prediction['dominant_topic_id']
745
+ )
746
+ if did_match:
747
+ matched[rule_type].append(rule['name'])
748
+ evidence_rules.append({
749
+ **rule,
750
+ 'type': rule_type,
751
+ 'topic_name': topic_names.get(rule['topic_id'], ''),
752
+ 'probability': probability,
753
+ 'is_dominant': prediction['dominant_topic_id'] == rule['topic_id'],
754
+ 'matched': did_match,
755
+ })
756
+ if matched['exclude']:
757
+ status = 'excluded'
758
+ elif definition['include_mode'] == 'any':
759
+ status = 'included' if matched['include'] else 'excluded'
760
+ else:
761
+ status = 'included' if len(matched['include']) == len(definition['include']) else 'excluded'
762
+ evidence = {
763
+ 'model': definition['model'],
764
+ 'model_id': definition['model_id'],
765
+ 'dominant_topic_id': prediction['dominant_topic_id'],
766
+ 'matched_include_rules': matched['include'],
767
+ 'matched_exclude_rules': matched['exclude'],
768
+ 'rules': evidence_rules,
769
+ 'unavailable': [],
770
+ }
771
+ return status, evidence, ''
772
+
773
+
774
+ def _database_path(conn: sqlite3.Connection) -> str:
775
+ """Return the on-disk path for a corpus connection.
776
+
777
+ Parameters
778
+ ----------
779
+ conn : sqlite3.Connection
780
+ Open SQLite connection.
781
+
782
+ Returns
783
+ -------
784
+ str
785
+ Main database path, or an empty string for an in-memory connection.
786
+ """
787
+ rows = conn.execute('PRAGMA database_list').fetchall()
788
+ return next((row['file'] for row in rows if row['name'] == 'main'), '')
789
+
790
+
791
+ def topic_filter_staleness(conn: sqlite3.Connection) -> dict[str, bool]:
792
+ """Check whether active topic filters use current corpus predictions.
793
+
794
+ Parameters
795
+ ----------
796
+ conn : sqlite3.Connection
797
+ Open corpus connection.
798
+
799
+ Returns
800
+ -------
801
+ dict[str, bool]
802
+ Stale state keyed by each model ID used by an active topic filter.
803
+ """
804
+ filters = [item for item in active_filter_stack(conn) if item['method'] == 'topic']
805
+ if not filters:
806
+ return {}
807
+ from paperminertoolkit.workflows.topics import topic_corpus_fingerprint
808
+
809
+ db_path = _database_path(conn)
810
+ results = {}
811
+ for item in filters:
812
+ model_id = item['definition']['model_id']
813
+ if model_id in results:
814
+ continue
815
+ model = conn.execute(
816
+ 'SELECT prediction_corpus_fingerprint, text_fields_json '
817
+ 'FROM topic_models WHERE model_id = ?', (model_id,)
818
+ ).fetchone()
819
+ if model is None or not db_path:
820
+ results[model_id] = True
821
+ continue
822
+ current = topic_corpus_fingerprint(
823
+ db_path, json.loads(model['text_fields_json'])
824
+ )['sha256']
825
+ results[model_id] = current != model['prediction_corpus_fingerprint']
826
+ return results
827
+
828
+
829
+ def active_filter_stack(conn: sqlite3.Connection) -> list[dict[str, Any]]:
830
+ """Return active filters in expression order.
831
+
832
+ Parameters
833
+ ----------
834
+ conn : sqlite3.Connection
835
+ Open corpus connection.
836
+
837
+ Returns
838
+ -------
839
+ list[dict[str, Any]]
840
+ Filter rows with decoded definitions.
841
+
842
+ Raises
843
+ ------
844
+ json.JSONDecodeError
845
+ If a stored filter definition is invalid JSON.
846
+ """
847
+ rows = conn.execute(
848
+ 'SELECT * FROM corpus_filters ORDER BY stack_position, filter_id'
849
+ ).fetchall()
850
+ filters = []
851
+ for row in rows:
852
+ item = dict(row)
853
+ item['definition'] = json.loads(item.pop('definition_json'))
854
+ filters.append(item)
855
+ return filters
856
+
857
+
858
+ def filter_expression(filters: Sequence[Mapping[str, Any]]) -> str:
859
+ """Build the explicit expression for an active filter stack.
860
+
861
+ Parameters
862
+ ----------
863
+ filters : Sequence[Mapping[str, Any]]
864
+ Active filters in evaluation order.
865
+
866
+ Returns
867
+ -------
868
+ str
869
+ Parenthesized left-to-right expression, or an empty string.
870
+ """
871
+ if not filters:
872
+ return ''
873
+ expression = filters[0]['name']
874
+ for item in filters[1:]:
875
+ expression = f'({expression} {item["join_operator"].upper()} {item["name"]})'
876
+ return expression
877
+
878
+
879
+ def combine_status(left: str, right: str, operator: str) -> _FilterStatus:
880
+ """Combine two filter decisions with three-valued Boolean logic.
881
+
882
+ Parameters
883
+ ----------
884
+ left : {'excluded', 'included', 'unavailable'}
885
+ Left-hand filter decision.
886
+ right : {'excluded', 'included', 'unavailable'}
887
+ Right-hand filter decision.
888
+ operator : {'and', 'or'}
889
+ Boolean operator joining the decisions.
890
+
891
+ Returns
892
+ -------
893
+ str
894
+ Combined filter status.
895
+
896
+ Raises
897
+ ------
898
+ ValueError
899
+ If either status or the operator is unsupported.
900
+ """
901
+ if left not in FILTER_STATUSES or right not in FILTER_STATUSES:
902
+ raise ValueError('Unknown filter status.')
903
+ if operator == 'and':
904
+ if 'excluded' in {left, right}:
905
+ return 'excluded'
906
+ if left == right == 'included':
907
+ return 'included'
908
+ return 'unavailable'
909
+ if operator == 'or':
910
+ if 'included' in {left, right}:
911
+ return 'included'
912
+ if left == right == 'excluded':
913
+ return 'excluded'
914
+ return 'unavailable'
915
+ raise ValueError(f'Unknown join operator: {operator}')
916
+
917
+
918
+ def _recompute_filter_state(conn: sqlite3.Connection) -> None:
919
+ """Rebuild final per-paper decisions from the active filter stack.
920
+
921
+ Parameters
922
+ ----------
923
+ conn : sqlite3.Connection
924
+ Open corpus connection whose filter state is updated.
925
+ """
926
+ filters = active_filter_stack(conn)
927
+ conn.execute('DELETE FROM paper_filter_state')
928
+ if not filters:
929
+ return
930
+ expression = filter_expression(filters)
931
+ result_rows = conn.execute(
932
+ 'SELECT filter_id, paper_id, status FROM paper_filter_results'
933
+ ).fetchall()
934
+ results = {(row['filter_id'], row['paper_id']): row['status'] for row in result_rows}
935
+ now = utc_now()
936
+ states = []
937
+ for paper in paper_rows(conn):
938
+ paper_id = paper['paper_id']
939
+ status = results.get((filters[0]['filter_id'], paper_id), 'unavailable')
940
+ for item in filters[1:]:
941
+ right = results.get((item['filter_id'], paper_id), 'unavailable')
942
+ status = combine_status(status, right, item['join_operator'])
943
+ states.append((paper_id, status, expression, now))
944
+ conn.executemany(
945
+ 'INSERT INTO paper_filter_state (paper_id, status, expression, updated_at) VALUES (?, ?, ?, ?)',
946
+ states,
947
+ )
948
+
949
+
950
+ def filter_overview(conn: sqlite3.Connection) -> _FilterOverview:
951
+ """Summarize the active filter stack and its decisions.
952
+
953
+ Parameters
954
+ ----------
955
+ conn : sqlite3.Connection
956
+ Open corpus connection.
957
+
958
+ Returns
959
+ -------
960
+ _FilterOverview
961
+ Active filters, their expression, final status counts, and unavailable
962
+ reason counts.
963
+ """
964
+ filters = active_filter_stack(conn)
965
+ stale_models = topic_filter_staleness(conn)
966
+ paper_count = conn.execute('SELECT COUNT(*) FROM papers').fetchone()[0]
967
+ for item in filters:
968
+ item['stale'] = (
969
+ stale_models.get(item['definition'].get('model_id'), False)
970
+ if item['method'] == 'topic' else False
971
+ )
972
+ counts = dict(conn.execute(
973
+ 'SELECT status, COUNT(*) AS count FROM paper_filter_results '
974
+ 'WHERE filter_id = ? GROUP BY status',
975
+ (item['filter_id'],),
976
+ ).fetchall())
977
+ recorded = sum(counts.values())
978
+ counts['unavailable'] = counts.get('unavailable', 0) + max(0, paper_count - recorded)
979
+ item['counts'] = {status: counts.get(status, 0) for status in sorted(FILTER_STATUSES)}
980
+ if filters:
981
+ counts = dict(conn.execute(
982
+ 'SELECT status, COUNT(*) AS count FROM paper_filter_state GROUP BY status'
983
+ ).fetchall())
984
+ recorded = sum(counts.values())
985
+ counts['unavailable'] = counts.get('unavailable', 0) + max(0, paper_count - recorded)
986
+ final_counts = {status: counts.get(status, 0) for status in sorted(FILTER_STATUSES)}
987
+ else:
988
+ final_counts = {'excluded': 0, 'included': paper_count, 'unavailable': 0}
989
+ reasons = dict(conn.execute(
990
+ "SELECT unavailable_reason, COUNT(*) FROM paper_filter_results "
991
+ "WHERE status = 'unavailable' AND unavailable_reason != '' GROUP BY unavailable_reason"
992
+ ).fetchall())
993
+ return {
994
+ 'filters': filters,
995
+ 'expression': filter_expression(filters),
996
+ 'counts': final_counts,
997
+ 'unavailable_reasons': reasons,
998
+ 'stale_topic_filters': [item['name'] for item in filters if item['stale']],
999
+ }
1000
+
1001
+
1002
+ def apply_regex_filter(db_path: str | PathLike[str],
1003
+ rules_path: str | PathLike[str],
1004
+ fields: Iterable[str] | None = None,
1005
+ join_operator: str | None = None,
1006
+ replace: bool = False,
1007
+ timeout_ms: int | None = None) -> _FilterOverview:
1008
+ """Apply or replace one named regex filter in a corpus.
1009
+
1010
+ Parameters
1011
+ ----------
1012
+ db_path : str or pathlib.Path
1013
+ Path to the SQLite paper corpus.
1014
+ rules_path : str or pathlib.Path
1015
+ Path to the JSON regex definition.
1016
+ fields : Iterable[str] or None, optional
1017
+ Content fields overriding the definition.
1018
+ join_operator : {'and', 'or'} or None, optional
1019
+ Operator joining this filter to the preceding active filter.
1020
+ replace : bool, default=False
1021
+ Whether to replace an active filter with the same name.
1022
+ timeout_ms : int or None, optional
1023
+ Per-field regex timeout overriding the definition.
1024
+
1025
+ Returns
1026
+ -------
1027
+ _FilterOverview
1028
+ Updated filter overview.
1029
+
1030
+ Raises
1031
+ ------
1032
+ OSError
1033
+ If the rules file cannot be read.
1034
+ ValueError
1035
+ If the definition, join operator, or replacement request is invalid.
1036
+ """
1037
+ definition = load_regex_definition(rules_path, fields=fields, timeout_ms=timeout_ms)
1038
+ compiled = compile_regex_definition(definition)
1039
+ if join_operator is not None:
1040
+ join_operator = join_operator.lower()
1041
+ if join_operator not in JOIN_OPERATORS:
1042
+ raise ValueError('join_operator must be "and" or "or".')
1043
+
1044
+ with connect(db_path) as conn:
1045
+ existing = conn.execute(
1046
+ 'SELECT * FROM corpus_filters WHERE name = ?', (definition['name'],)
1047
+ ).fetchone()
1048
+ if existing is not None and not replace:
1049
+ raise ValueError(
1050
+ f'Filter {definition["name"]!r} is already active; use --replace to reevaluate it.'
1051
+ )
1052
+ stack_size = conn.execute('SELECT COUNT(*) FROM corpus_filters').fetchone()[0]
1053
+ now = utc_now()
1054
+ try:
1055
+ conn.execute('BEGIN')
1056
+ if existing is None:
1057
+ position = stack_size
1058
+ if position == 0 and join_operator is not None:
1059
+ raise ValueError('The first filter cannot have a join operator.')
1060
+ resolved_join = None if position == 0 else (join_operator or 'and')
1061
+ cursor = conn.execute(
1062
+ """
1063
+ INSERT INTO corpus_filters (
1064
+ name, method, description, definition_json, stack_position,
1065
+ join_operator, created_at, updated_at
1066
+ ) VALUES (?, 'regex', ?, ?, ?, ?, ?, ?)
1067
+ """,
1068
+ (
1069
+ definition['name'], definition['description'],
1070
+ json.dumps(definition, sort_keys=True), position,
1071
+ resolved_join, now, now,
1072
+ ),
1073
+ )
1074
+ filter_id = cursor.lastrowid
1075
+ else:
1076
+ if existing['method'] != 'regex':
1077
+ raise ValueError(
1078
+ f'Filter {definition["name"]!r} already exists with method '
1079
+ f'{existing["method"]!r}.'
1080
+ )
1081
+ position = existing['stack_position']
1082
+ if position == 0 and join_operator is not None:
1083
+ raise ValueError('The first filter cannot have a join operator.')
1084
+ resolved_join = existing['join_operator'] if join_operator is None else join_operator
1085
+ conn.execute(
1086
+ """
1087
+ UPDATE corpus_filters
1088
+ SET description = ?, definition_json = ?, join_operator = ?, updated_at = ?
1089
+ WHERE filter_id = ?
1090
+ """,
1091
+ (
1092
+ definition['description'], json.dumps(definition, sort_keys=True),
1093
+ resolved_join, now, existing['filter_id'],
1094
+ ),
1095
+ )
1096
+ filter_id = existing['filter_id']
1097
+ conn.execute('DELETE FROM paper_filter_results WHERE filter_id = ?', (filter_id,))
1098
+
1099
+ for paper in paper_rows(conn):
1100
+ status, evidence, unavailable_reason = evaluate_regex_paper(
1101
+ conn, paper, definition, compiled
1102
+ )
1103
+ conn.execute(
1104
+ """
1105
+ INSERT INTO paper_filter_results (
1106
+ filter_id, paper_id, status, evidence_json,
1107
+ unavailable_reason, evaluated_at
1108
+ ) VALUES (?, ?, ?, ?, ?, ?)
1109
+ """,
1110
+ (
1111
+ filter_id, paper['paper_id'], status,
1112
+ json.dumps(evidence, sort_keys=True), unavailable_reason, now,
1113
+ ),
1114
+ )
1115
+ _recompute_filter_state(conn)
1116
+ conn.commit()
1117
+ except Exception:
1118
+ conn.rollback()
1119
+ raise
1120
+ return filter_overview(conn)
1121
+
1122
+
1123
+ def apply_topic_filter(
1124
+ db_path: str | PathLike[str],
1125
+ rules_path: str | PathLike[str],
1126
+ join_operator: str | None = None,
1127
+ replace: bool = False,
1128
+ ) -> _FilterOverview:
1129
+ """Apply or replace one named stored-model topic filter.
1130
+
1131
+ Parameters
1132
+ ----------
1133
+ db_path : str or os.PathLike[str]
1134
+ Path to the SQLite paper corpus.
1135
+ rules_path : str or os.PathLike[str]
1136
+ Topic-filter JSON definition.
1137
+ join_operator : {'and', 'or'} or None, optional
1138
+ Operator joining a new filter to the preceding active expression.
1139
+ replace : bool, default=False
1140
+ Whether to replace and reevaluate an active filter with the same name.
1141
+
1142
+ Returns
1143
+ -------
1144
+ _FilterOverview
1145
+ Updated filter stack and paper-status summary.
1146
+
1147
+ Raises
1148
+ ------
1149
+ OSError
1150
+ If the rules file or corpus cannot be accessed.
1151
+ ValueError
1152
+ If the definition, join operation, stored model, or stored scores are
1153
+ invalid or stale.
1154
+ """
1155
+ if join_operator is not None:
1156
+ join_operator = join_operator.lower()
1157
+ if join_operator not in JOIN_OPERATORS:
1158
+ raise ValueError('join_operator must be "and" or "or".')
1159
+ with connect(db_path) as conn:
1160
+ definition = load_topic_definition(conn, rules_path)
1161
+ model = conn.execute(
1162
+ 'SELECT prediction_corpus_fingerprint, text_fields_json FROM topic_models '
1163
+ 'WHERE model_id = ?', (definition['model_id'],)
1164
+ ).fetchone()
1165
+ from paperminertoolkit.workflows.topics import topic_corpus_fingerprint
1166
+
1167
+ current_fingerprint = topic_corpus_fingerprint(
1168
+ db_path, json.loads(model['text_fields_json'])
1169
+ )['sha256']
1170
+ if current_fingerprint != model['prediction_corpus_fingerprint']:
1171
+ raise ValueError(
1172
+ f'Topic scores for {definition["model"]!r} are stale; '
1173
+ 'run pmt topics store again before applying this filter.'
1174
+ )
1175
+ existing = conn.execute(
1176
+ 'SELECT * FROM corpus_filters WHERE name = ?', (definition['name'],)
1177
+ ).fetchone()
1178
+ if existing is not None and not replace:
1179
+ raise ValueError(
1180
+ f'Filter {definition["name"]!r} is already active; use --replace to reevaluate it.'
1181
+ )
1182
+ stack_size = conn.execute('SELECT COUNT(*) FROM corpus_filters').fetchone()[0]
1183
+ now = utc_now()
1184
+ try:
1185
+ conn.execute('BEGIN')
1186
+ if existing is None:
1187
+ position = stack_size
1188
+ if position == 0 and join_operator is not None:
1189
+ raise ValueError('The first filter cannot have a join operator.')
1190
+ resolved_join = None if position == 0 else (join_operator or 'and')
1191
+ cursor = conn.execute(
1192
+ """
1193
+ INSERT INTO corpus_filters (
1194
+ name, method, description, definition_json, stack_position,
1195
+ join_operator, created_at, updated_at
1196
+ ) VALUES (?, 'topic', ?, ?, ?, ?, ?, ?)
1197
+ """,
1198
+ (
1199
+ definition['name'], definition['description'],
1200
+ json.dumps(definition, sort_keys=True), position,
1201
+ resolved_join, now, now,
1202
+ ),
1203
+ )
1204
+ filter_id = cursor.lastrowid
1205
+ else:
1206
+ if existing['method'] != 'topic':
1207
+ raise ValueError(
1208
+ f'Filter {definition["name"]!r} already exists with method '
1209
+ f'{existing["method"]!r}.'
1210
+ )
1211
+ position = existing['stack_position']
1212
+ if position == 0 and join_operator is not None:
1213
+ raise ValueError('The first filter cannot have a join operator.')
1214
+ resolved_join = existing['join_operator'] if join_operator is None else join_operator
1215
+ conn.execute(
1216
+ """
1217
+ UPDATE corpus_filters
1218
+ SET description = ?, definition_json = ?, join_operator = ?, updated_at = ?
1219
+ WHERE filter_id = ?
1220
+ """,
1221
+ (
1222
+ definition['description'], json.dumps(definition, sort_keys=True),
1223
+ resolved_join, now, existing['filter_id'],
1224
+ ),
1225
+ )
1226
+ filter_id = existing['filter_id']
1227
+ conn.execute('DELETE FROM paper_filter_results WHERE filter_id = ?', (filter_id,))
1228
+ for paper in paper_rows(conn):
1229
+ status, evidence, unavailable_reason = evaluate_topic_paper(
1230
+ conn, paper, definition
1231
+ )
1232
+ conn.execute(
1233
+ """
1234
+ INSERT INTO paper_filter_results (
1235
+ filter_id, paper_id, status, evidence_json,
1236
+ unavailable_reason, evaluated_at
1237
+ ) VALUES (?, ?, ?, ?, ?, ?)
1238
+ """,
1239
+ (
1240
+ filter_id, paper['paper_id'], status,
1241
+ json.dumps(evidence, sort_keys=True), unavailable_reason, now,
1242
+ ),
1243
+ )
1244
+ _recompute_filter_state(conn)
1245
+ conn.commit()
1246
+ except Exception:
1247
+ conn.rollback()
1248
+ raise
1249
+ return filter_overview(conn)
1250
+
1251
+
1252
+ def refresh_topic_filters(
1253
+ db_path: str | PathLike[str],
1254
+ model_id: str,
1255
+ ) -> None:
1256
+ """Reevaluate filters after a stored model's scores are refreshed.
1257
+
1258
+ Parameters
1259
+ ----------
1260
+ db_path : str or os.PathLike[str]
1261
+ Path to the SQLite paper corpus.
1262
+ model_id : str
1263
+ Immutable identifier of the refreshed topic model.
1264
+
1265
+ Returns
1266
+ -------
1267
+ None
1268
+ Matching active filters and the combined filter state are updated in
1269
+ the corpus transactionally.
1270
+ """
1271
+ with connect(db_path) as conn:
1272
+ filters = [
1273
+ item for item in active_filter_stack(conn)
1274
+ if item['method'] == 'topic' and item['definition'].get('model_id') == model_id
1275
+ ]
1276
+ if not filters:
1277
+ return
1278
+ now = utc_now()
1279
+ try:
1280
+ conn.execute('BEGIN')
1281
+ for item in filters:
1282
+ conn.execute(
1283
+ 'DELETE FROM paper_filter_results WHERE filter_id = ?',
1284
+ (item['filter_id'],),
1285
+ )
1286
+ for paper in paper_rows(conn):
1287
+ status, evidence, reason = evaluate_topic_paper(
1288
+ conn, paper, item['definition']
1289
+ )
1290
+ conn.execute(
1291
+ """
1292
+ INSERT INTO paper_filter_results (
1293
+ filter_id, paper_id, status, evidence_json,
1294
+ unavailable_reason, evaluated_at
1295
+ ) VALUES (?, ?, ?, ?, ?, ?)
1296
+ """,
1297
+ (
1298
+ item['filter_id'], paper['paper_id'], status,
1299
+ json.dumps(evidence, sort_keys=True), reason, now,
1300
+ ),
1301
+ )
1302
+ _recompute_filter_state(conn)
1303
+ conn.commit()
1304
+ except Exception:
1305
+ conn.rollback()
1306
+ raise
1307
+
1308
+
1309
+ def reset_filters(
1310
+ db_path: str | PathLike[str],
1311
+ name: str | None = None,
1312
+ all_filters: bool = False,
1313
+ ) -> _FilterOverview:
1314
+ """Remove filters and recompute final paper decisions.
1315
+
1316
+ Parameters
1317
+ ----------
1318
+ db_path : str or os.PathLike[str]
1319
+ Path to the SQLite paper corpus.
1320
+ name : str or None, optional
1321
+ Name of the single filter to remove.
1322
+ all_filters : bool, default=False
1323
+ Whether to remove the complete active stack.
1324
+
1325
+ Returns
1326
+ -------
1327
+ _FilterOverview
1328
+ Updated filter overview.
1329
+
1330
+ Raises
1331
+ ------
1332
+ ValueError
1333
+ If exactly one removal mode is not selected or ``name`` is not active.
1334
+ """
1335
+ if bool(name) == bool(all_filters):
1336
+ raise ValueError('Choose exactly one of a filter name or all filters.')
1337
+ with connect(db_path) as conn:
1338
+ try:
1339
+ conn.execute('BEGIN')
1340
+ if all_filters:
1341
+ conn.execute('DELETE FROM corpus_filters')
1342
+ else:
1343
+ cursor = conn.execute('DELETE FROM corpus_filters WHERE name = ?', (name,))
1344
+ if cursor.rowcount == 0:
1345
+ raise ValueError(f'No active filter named {name!r}.')
1346
+ remaining = conn.execute(
1347
+ 'SELECT filter_id, join_operator FROM corpus_filters '
1348
+ 'ORDER BY stack_position, filter_id'
1349
+ ).fetchall()
1350
+ for position, row in enumerate(remaining):
1351
+ conn.execute(
1352
+ 'UPDATE corpus_filters SET stack_position = ?, join_operator = ? WHERE filter_id = ?',
1353
+ (
1354
+ position,
1355
+ None if position == 0 else row['join_operator'] or 'and',
1356
+ row['filter_id'],
1357
+ ),
1358
+ )
1359
+ _recompute_filter_state(conn)
1360
+ conn.commit()
1361
+ except Exception:
1362
+ conn.rollback()
1363
+ raise
1364
+ return filter_overview(conn)
1365
+
1366
+
1367
+ def current_filter_statuses(conn: sqlite3.Connection) -> dict[str, _FilterStatus]:
1368
+ """Return current final statuses keyed by paper ID.
1369
+
1370
+ Parameters
1371
+ ----------
1372
+ conn : sqlite3.Connection
1373
+ Open corpus connection.
1374
+
1375
+ Returns
1376
+ -------
1377
+ dict[str, _FilterStatus]
1378
+ Final filter status for each evaluated paper ID.
1379
+ """
1380
+ stale_models = topic_filter_staleness(conn)
1381
+ stale = [model_id for model_id, is_stale in stale_models.items() if is_stale]
1382
+ if stale:
1383
+ raise ValueError(
1384
+ 'Active topic filters use stale scores; run pmt topics store again for: '
1385
+ + ', '.join(stale)
1386
+ )
1387
+ return {
1388
+ row['paper_id']: row['status']
1389
+ for row in conn.execute('SELECT paper_id, status FROM paper_filter_state')
1390
+ }