ads-bib 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. ads_bib/__init__.py +80 -0
  2. ads_bib/_dataset_bundle.py +266 -0
  3. ads_bib/_presets/hf_api.yaml +138 -0
  4. ads_bib/_presets/local_cpu.yaml +138 -0
  5. ads_bib/_presets/local_gpu.yaml +138 -0
  6. ads_bib/_presets/openrouter.yaml +138 -0
  7. ads_bib/_stage_state.py +376 -0
  8. ads_bib/_utils/__init__.py +0 -0
  9. ads_bib/_utils/ads_api.py +158 -0
  10. ads_bib/_utils/authors.py +31 -0
  11. ads_bib/_utils/checkpoints.py +176 -0
  12. ads_bib/_utils/cleaning.py +81 -0
  13. ads_bib/_utils/costs.py +117 -0
  14. ads_bib/_utils/hf_compat.py +151 -0
  15. ads_bib/_utils/huggingface_api.py +60 -0
  16. ads_bib/_utils/io.py +61 -0
  17. ads_bib/_utils/llama_server.py +903 -0
  18. ads_bib/_utils/logging.py +271 -0
  19. ads_bib/_utils/model_specs.py +91 -0
  20. ads_bib/_utils/openrouter_client.py +135 -0
  21. ads_bib/_utils/openrouter_costs.py +433 -0
  22. ads_bib/author_disambiguation.py +477 -0
  23. ads_bib/bootstrap.py +116 -0
  24. ads_bib/citations.py +1384 -0
  25. ads_bib/cli.py +252 -0
  26. ads_bib/config.py +109 -0
  27. ads_bib/curate.py +249 -0
  28. ads_bib/doctor.py +640 -0
  29. ads_bib/export.py +340 -0
  30. ads_bib/notebook.py +252 -0
  31. ads_bib/pipeline.py +1988 -0
  32. ads_bib/presets.py +75 -0
  33. ads_bib/prompts.py +105 -0
  34. ads_bib/run_manager.py +375 -0
  35. ads_bib/runner.py +268 -0
  36. ads_bib/search.py +173 -0
  37. ads_bib/tokenize.py +204 -0
  38. ads_bib/topic_model/__init__.py +28 -0
  39. ads_bib/topic_model/_runtime.py +34 -0
  40. ads_bib/topic_model/backends.py +2414 -0
  41. ads_bib/topic_model/embeddings.py +823 -0
  42. ads_bib/topic_model/input.py +40 -0
  43. ads_bib/topic_model/output.py +124 -0
  44. ads_bib/topic_model/reduction.py +246 -0
  45. ads_bib/translate.py +1457 -0
  46. ads_bib/visualize.py +1448 -0
  47. ads_bib-0.1.0.dist-info/METADATA +143 -0
  48. ads_bib-0.1.0.dist-info/RECORD +51 -0
  49. ads_bib-0.1.0.dist-info/WHEEL +4 -0
  50. ads_bib-0.1.0.dist-info/entry_points.txt +2 -0
  51. ads_bib-0.1.0.dist-info/licenses/LICENSE +21 -0
ads_bib/__init__.py ADDED
@@ -0,0 +1,80 @@
1
+ """NASA ADS bibliometric analysis pipeline."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+ from ads_bib._utils.logging import suppress_noisy_third_party_logs
8
+
9
+ suppress_noisy_third_party_logs()
10
+
11
+ from ads_bib.author_disambiguation import apply_author_disambiguation
12
+ from ads_bib.citations import build_all_nodes, process_all_citations
13
+ from ads_bib.config import init_paths, load_env
14
+ from ads_bib.notebook import NotebookSession, get_notebook_session
15
+ from ads_bib.pipeline import (
16
+ PipelineConfig,
17
+ PipelineContext,
18
+ StagePrerequisiteError,
19
+ run_pipeline,
20
+ )
21
+ from ads_bib.curate import (
22
+ get_cluster_summary,
23
+ get_hierarchy_cluster_summary,
24
+ normalize_cluster_targets,
25
+ remove_cluster_targets,
26
+ remove_clusters,
27
+ )
28
+ from ads_bib.export import resolve_dataset
29
+ from ads_bib.run_manager import RunManager
30
+ from ads_bib.runner import RunBlockedError, run
31
+ from ads_bib.search import search_ads
32
+ from ads_bib.tokenize import tokenize_texts
33
+ from ads_bib.topic_model import (
34
+ build_topic_dataframe,
35
+ compute_embeddings,
36
+ fit_bertopic,
37
+ fit_toponymy,
38
+ reduce_dimensions,
39
+ reduce_outliers,
40
+ )
41
+ from ads_bib.translate import detect_languages, translate_dataframe
42
+
43
+ try:
44
+ __version__ = version("ads_bib")
45
+ except PackageNotFoundError:
46
+ __version__ = "0.0.0"
47
+
48
+ __all__ = [
49
+ "__version__",
50
+ "apply_author_disambiguation",
51
+ "PipelineConfig",
52
+ "PipelineContext",
53
+ "NotebookSession",
54
+ "RunManager",
55
+ "RunBlockedError",
56
+ "StagePrerequisiteError",
57
+ "build_all_nodes",
58
+ "build_topic_dataframe",
59
+ "compute_embeddings",
60
+ "detect_languages",
61
+ "fit_bertopic",
62
+ "fit_toponymy",
63
+ "get_cluster_summary",
64
+ "get_hierarchy_cluster_summary",
65
+ "init_paths",
66
+ "load_env",
67
+ "get_notebook_session",
68
+ "normalize_cluster_targets",
69
+ "process_all_citations",
70
+ "reduce_dimensions",
71
+ "reduce_outliers",
72
+ "remove_cluster_targets",
73
+ "remove_clusters",
74
+ "resolve_dataset",
75
+ "search_ads",
76
+ "run",
77
+ "run_pipeline",
78
+ "tokenize_texts",
79
+ "translate_dataframe",
80
+ ]
@@ -0,0 +1,266 @@
1
+ """Helpers for run-local dataset bundle artifacts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ from pathlib import Path
8
+
9
+ import pandas as pd
10
+
11
+ from ads_bib._utils.io import load_parquet, save_parquet, sha256_file
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ _FRONT_COLUMNS: tuple[str, ...] = (
16
+ "Bibcode",
17
+ "Year",
18
+ "Author",
19
+ "author_display_names",
20
+ "author_uids",
21
+ "Title",
22
+ "Title_lang",
23
+ "Title_en",
24
+ "Abstract",
25
+ "Abstract_lang",
26
+ "Abstract_en",
27
+ "Journal",
28
+ "Journal Abbreviation",
29
+ "Citation Count",
30
+ "DOI",
31
+ "Affiliation",
32
+ "Keywords",
33
+ "Category",
34
+ "Volume",
35
+ "Issue",
36
+ "First Page",
37
+ "Last Page",
38
+ "References",
39
+ "full_text",
40
+ "tokens",
41
+ "topic_id",
42
+ "Name",
43
+ "Main",
44
+ "MMR",
45
+ "POS",
46
+ "KeyBERT",
47
+ "topic_primary_layer_index",
48
+ "topic_layer_count",
49
+ )
50
+
51
+ _TAIL_COLUMNS: tuple[str, ...] = (
52
+ "full_embeddings",
53
+ )
54
+
55
+ _TOPIC_INFO_FRONT_COLUMNS: tuple[str, ...] = (
56
+ "Topic",
57
+ "Count",
58
+ "Name",
59
+ "Main",
60
+ "MMR",
61
+ "POS",
62
+ "KeyBERT",
63
+ "Representation",
64
+ "Representative_Docs",
65
+ )
66
+
67
+
68
+ def _is_embedding_column(column: str) -> bool:
69
+ return column.startswith("embedding_5d_") or column in {"embedding_2d_x", "embedding_2d_y"}
70
+
71
+
72
+ def _embedding_sort_key(column: str) -> tuple[int, int, str]:
73
+ if column.startswith("embedding_5d_"):
74
+ suffix = column.removeprefix("embedding_5d_")
75
+ if suffix.isdigit():
76
+ return (0, int(suffix), column)
77
+ if column == "embedding_2d_x":
78
+ return (1, 0, column)
79
+ if column == "embedding_2d_y":
80
+ return (1, 1, column)
81
+ return (10**6, 10**6, column)
82
+
83
+
84
+ def _topic_layer_sort_key(column: str) -> tuple[int, int, str]:
85
+ if column.startswith("topic_layer_"):
86
+ parts = column.split("_")
87
+ if len(parts) >= 4 and parts[2].isdigit():
88
+ kind = 0 if column.endswith("_id") else 1
89
+ return (int(parts[2]), kind, column)
90
+ if column.startswith("Topic_Layer_"):
91
+ suffix = column.removeprefix("Topic_Layer_")
92
+ if suffix.isdigit():
93
+ return (int(suffix), 2, column)
94
+ return (10**6, 10**6, column)
95
+
96
+
97
+ def _ordered_dataset_frame(df: pd.DataFrame) -> pd.DataFrame:
98
+ columns = list(df.columns)
99
+ front = [column for column in _FRONT_COLUMNS if column in columns]
100
+ topic_layers = sorted(
101
+ [
102
+ column
103
+ for column in columns
104
+ if (column.startswith("topic_layer_") or column.startswith("Topic_Layer_"))
105
+ and column not in front
106
+ ],
107
+ key=_topic_layer_sort_key,
108
+ )
109
+ embeddings = sorted(
110
+ [column for column in columns if _is_embedding_column(column)],
111
+ key=_embedding_sort_key,
112
+ )
113
+ tail = [column for column in _TAIL_COLUMNS if column in columns]
114
+ used = set(front) | set(topic_layers) | set(embeddings) | set(tail)
115
+ middle = [column for column in columns if column not in used]
116
+ return df.loc[:, [*front, *topic_layers, *middle, *embeddings, *tail]]
117
+
118
+
119
+ def _ordered_topic_info_frame(df: pd.DataFrame) -> pd.DataFrame:
120
+ columns = list(df.columns)
121
+ front = [column for column in _TOPIC_INFO_FRONT_COLUMNS if column in columns]
122
+ used = set(front)
123
+ rest = [column for column in columns if column not in used]
124
+ return df.loc[:, [*front, *rest]].copy()
125
+
126
+
127
+ def ensure_run_references_artifact(
128
+ *,
129
+ refs: pd.DataFrame,
130
+ run_data_dir: Path | str,
131
+ force: bool = False,
132
+ ) -> Path:
133
+ run_data_dir = Path(run_data_dir)
134
+ references_path = run_data_dir / "references.parquet"
135
+ if force or not references_path.exists():
136
+ save_parquet(_ordered_dataset_frame(refs), references_path)
137
+ return references_path
138
+
139
+
140
+ def ensure_run_topic_info_artifact(
141
+ *,
142
+ topic_info: pd.DataFrame | None,
143
+ run_data_dir: Path | str,
144
+ force: bool = True,
145
+ ) -> Path | None:
146
+ if topic_info is None:
147
+ return None
148
+ run_data_dir = Path(run_data_dir)
149
+ topic_info_path = run_data_dir / "topic_info.parquet"
150
+ if force or not topic_info_path.exists():
151
+ save_parquet(_ordered_topic_info_frame(topic_info), topic_info_path)
152
+ return topic_info_path
153
+
154
+
155
+ def _artifact_manifest(path: Path | None) -> dict[str, int | str] | None:
156
+ if path is None or not path.exists() or not path.is_file():
157
+ return None
158
+ return {
159
+ "path": path.name,
160
+ "bytes": int(path.stat().st_size),
161
+ "sha256": sha256_file(path),
162
+ }
163
+
164
+
165
+ def write_dataset_bundle(
166
+ *,
167
+ publications: pd.DataFrame,
168
+ refs: pd.DataFrame | None,
169
+ topic_info: pd.DataFrame | None = None,
170
+ run_data_dir: Path | str,
171
+ run_id: str,
172
+ source_stage: str,
173
+ and_enabled: bool,
174
+ ) -> Path:
175
+ run_data_dir = Path(run_data_dir)
176
+ publications_path = run_data_dir / "publications.parquet"
177
+ manifest_path = run_data_dir / "dataset_manifest.json"
178
+
179
+ if refs is None:
180
+ logger.info("Skipping dataset bundle export at %s: refs are not available.", source_stage)
181
+ return publications_path
182
+
183
+ references_path = ensure_run_references_artifact(
184
+ refs=refs,
185
+ run_data_dir=run_data_dir,
186
+ )
187
+ topic_info_path = ensure_run_topic_info_artifact(
188
+ topic_info=topic_info,
189
+ run_data_dir=run_data_dir,
190
+ )
191
+ if topic_info_path is None:
192
+ existing_topic_info_path = run_data_dir / "topic_info.parquet"
193
+ topic_info_path = existing_topic_info_path if existing_topic_info_path.exists() else None
194
+ publications = _ordered_dataset_frame(publications)
195
+ save_parquet(publications, publications_path)
196
+
197
+ try:
198
+ from ads_bib import __version__ as ads_bib_version
199
+ except Exception:
200
+ ads_bib_version = "0.0.0"
201
+
202
+ coordinate_columns = sorted(
203
+ [column for column in publications.columns if _is_embedding_column(column)],
204
+ key=_embedding_sort_key,
205
+ )
206
+ artifact_paths = {
207
+ "publications": publications_path,
208
+ "references": references_path,
209
+ "topic_info": topic_info_path,
210
+ }
211
+ artifacts = {
212
+ name: payload
213
+ for name, path in artifact_paths.items()
214
+ if (payload := _artifact_manifest(path)) is not None
215
+ }
216
+
217
+ manifest = {
218
+ "schema_version": 1,
219
+ "producer": "ads_bib",
220
+ "producer_version": ads_bib_version,
221
+ "run_id": run_id,
222
+ "source_stage": source_stage,
223
+ "and_enabled": bool(and_enabled),
224
+ "publications_path": publications_path.name,
225
+ "references_path": references_path.name,
226
+ "topic_info_path": topic_info_path.name if topic_info_path is not None else None,
227
+ "coordinate_columns": coordinate_columns,
228
+ "counts": {
229
+ "publications": int(len(publications)),
230
+ "references": int(len(refs)),
231
+ },
232
+ "artifacts": artifacts,
233
+ "has_author_uids": bool(
234
+ "author_uids" in publications.columns and "author_uids" in refs.columns
235
+ ),
236
+ "has_author_display_names": bool(
237
+ "author_display_names" in publications.columns
238
+ and "author_display_names" in refs.columns
239
+ ),
240
+ }
241
+ manifest_path.write_text(
242
+ json.dumps(manifest, indent=2, sort_keys=True),
243
+ encoding="utf-8",
244
+ )
245
+
246
+ logger.info(
247
+ "Dataset bundle exported at %s | publications=%s | references=%s",
248
+ source_stage,
249
+ f"{len(publications):,}",
250
+ f"{len(refs):,}",
251
+ )
252
+ return publications_path
253
+
254
+
255
+ def load_curated_dataset(*, run_data_dir: Path | str) -> pd.DataFrame:
256
+ curated_path = Path(run_data_dir) / "publications.parquet"
257
+ if curated_path.exists():
258
+ return load_parquet(curated_path)
259
+ raise FileNotFoundError(f"Curated dataset not found at {curated_path}")
260
+
261
+
262
+ __all__ = [
263
+ "ensure_run_references_artifact",
264
+ "load_curated_dataset",
265
+ "write_dataset_bundle",
266
+ ]
@@ -0,0 +1,138 @@
1
+ # Starter preset for the Hugging Face API runtime road.
2
+ # Required before running: set search.query to your ADS query,
3
+ # either by editing this file or by passing --set search.query='...'.
4
+
5
+ run:
6
+ run_name: ads_bib_hf_api
7
+ start_stage: search
8
+ stop_stage: null
9
+ random_seed: 42
10
+ openrouter_cost_mode: hybrid
11
+ project_root: null
12
+
13
+ search:
14
+ query: ""
15
+ ads_token: null
16
+ refresh_search: true
17
+ refresh_export: true
18
+
19
+ translate:
20
+ enabled: true
21
+ provider: huggingface_api
22
+ model: unsloth/Qwen2.5-72B-Instruct:featherless-ai
23
+ model_repo: null
24
+ model_file: null
25
+ model_path: null
26
+ api_key: null
27
+ max_workers: 8
28
+ max_tokens: 2048
29
+ fasttext_model: data/models/lid.176.bin
30
+
31
+ llama_server:
32
+ command: llama-server
33
+ host: 127.0.0.1
34
+ port: null
35
+ threads: null
36
+ ctx_size: 4096
37
+ gpu_layers: -1
38
+ startup_timeout_s: 120.0
39
+ reasoning: "off"
40
+
41
+ tokenize:
42
+ enabled: true
43
+ spacy_model: en_core_web_md
44
+ batch_size: 512
45
+ n_process: 1
46
+ disable:
47
+ - ner
48
+ - parser
49
+ - textcat
50
+ fallback_model: en_core_web_md
51
+ auto_download: true
52
+
53
+ author_disambiguation:
54
+ enabled: false
55
+ backend: local
56
+ runtime: auto
57
+ modal_gpu: l4
58
+ model_bundle: null
59
+ dataset_id: null
60
+ force_refresh: false
61
+ infer_stage: full
62
+
63
+ topic_model:
64
+ sample_size: null
65
+ embedding_provider: huggingface_api
66
+ embedding_model: Qwen/Qwen3-Embedding-8B
67
+ embedding_api_key: null
68
+ embedding_batch_size: 32
69
+ embedding_max_workers: 8
70
+ reduction_method: pacmap
71
+ params_5d:
72
+ n_neighbors: 30
73
+ metric: angular
74
+ random_state: 42
75
+ params_2d:
76
+ n_neighbors: 30
77
+ metric: angular
78
+ random_state: 42
79
+ backend: bertopic
80
+ clustering_method: fast_hdbscan
81
+ cluster_params:
82
+ min_cluster_size: 15
83
+ min_samples: 3
84
+ cluster_selection_method: eom
85
+ cluster_selection_epsilon: 0.05
86
+ toponymy_cluster_params: {}
87
+ toponymy_layer_index: auto
88
+ llm_prompt_name: physics
89
+ llm_prompt: null
90
+ llm_provider: huggingface_api
91
+ llm_model: unsloth/Qwen2.5-72B-Instruct:featherless-ai
92
+ llm_model_repo: null
93
+ llm_model_file: null
94
+ llm_model_path: null
95
+ llm_api_key: null
96
+ bertopic_label_max_tokens: 64
97
+ toponymy_local_label_max_tokens: 128
98
+ pipeline_models:
99
+ - POS
100
+ - KeyBERT
101
+ - MMR
102
+ parallel_models:
103
+ - MMR
104
+ - POS
105
+ - KeyBERT
106
+ toponymy_embedding_model: null
107
+ toponymy_max_workers: 10
108
+ min_df: 3
109
+ outlier_threshold: 0.5
110
+
111
+ visualization:
112
+ enabled: true
113
+ title: "ADS Topic Map"
114
+ subtitle_template: "{topic_count} topics from {document_count:,} ADS records"
115
+ dark_mode: true
116
+ font_family: Cinzel
117
+ topic_tree: false
118
+
119
+ curation:
120
+ cluster_targets: []
121
+ clusters_to_remove: []
122
+
123
+ citations:
124
+ metrics:
125
+ - direct
126
+ - co_citation
127
+ - bibliographic_coupling
128
+ - author_co_citation
129
+ min_counts:
130
+ direct: 2
131
+ co_citation: 3
132
+ bibliographic_coupling: 2
133
+ author_co_citation: 3
134
+ authors_filter: null
135
+ authors_filter_uids: null
136
+ cited_authors_exclude: null
137
+ cited_author_uids_exclude: null
138
+ output_format: gexf
@@ -0,0 +1,138 @@
1
+ # Starter preset for the local CPU runtime road.
2
+ # Required before running: set search.query to your ADS query,
3
+ # either by editing this file or by passing --set search.query='...'.
4
+
5
+ run:
6
+ run_name: ads_bib_local_cpu
7
+ start_stage: search
8
+ stop_stage: null
9
+ random_seed: 42
10
+ openrouter_cost_mode: hybrid
11
+ project_root: null
12
+
13
+ search:
14
+ query: ""
15
+ ads_token: null
16
+ refresh_search: true
17
+ refresh_export: true
18
+
19
+ translate:
20
+ enabled: true
21
+ provider: nllb
22
+ model: JustFrederik/nllb-200-distilled-600M-ct2-int8
23
+ model_repo: null
24
+ model_file: null
25
+ model_path: null
26
+ api_key: null
27
+ max_workers: 8
28
+ max_tokens: 2048
29
+ fasttext_model: data/models/lid.176.bin
30
+
31
+ llama_server:
32
+ command: llama-server
33
+ host: 127.0.0.1
34
+ port: null
35
+ threads: null
36
+ ctx_size: 4096
37
+ gpu_layers: 0
38
+ startup_timeout_s: 120.0
39
+ reasoning: "off"
40
+
41
+ tokenize:
42
+ enabled: true
43
+ spacy_model: en_core_web_md
44
+ batch_size: 512
45
+ n_process: 1
46
+ disable:
47
+ - ner
48
+ - parser
49
+ - textcat
50
+ fallback_model: en_core_web_md
51
+ auto_download: true
52
+
53
+ author_disambiguation:
54
+ enabled: false
55
+ backend: local
56
+ runtime: auto
57
+ modal_gpu: l4
58
+ model_bundle: null
59
+ dataset_id: null
60
+ force_refresh: false
61
+ infer_stage: full
62
+
63
+ topic_model:
64
+ sample_size: null
65
+ embedding_provider: local
66
+ embedding_model: google/embeddinggemma-300m
67
+ embedding_api_key: null
68
+ embedding_batch_size: 32
69
+ embedding_max_workers: 8
70
+ reduction_method: pacmap
71
+ params_5d:
72
+ n_neighbors: 30
73
+ metric: angular
74
+ random_state: 42
75
+ params_2d:
76
+ n_neighbors: 30
77
+ metric: angular
78
+ random_state: 42
79
+ backend: bertopic
80
+ clustering_method: fast_hdbscan
81
+ cluster_params:
82
+ min_cluster_size: 15
83
+ min_samples: 3
84
+ cluster_selection_method: eom
85
+ cluster_selection_epsilon: 0.05
86
+ toponymy_cluster_params: {}
87
+ toponymy_layer_index: auto
88
+ llm_prompt_name: physics
89
+ llm_prompt: null
90
+ llm_provider: llama_server
91
+ llm_model: null
92
+ llm_model_repo: mradermacher/Qwen3.5-0.8B-GGUF
93
+ llm_model_file: Qwen3.5-0.8B.Q4_K_M.gguf
94
+ llm_model_path: null
95
+ llm_api_key: null
96
+ bertopic_label_max_tokens: 64
97
+ toponymy_local_label_max_tokens: 128
98
+ pipeline_models:
99
+ - POS
100
+ - KeyBERT
101
+ - MMR
102
+ parallel_models:
103
+ - MMR
104
+ - POS
105
+ - KeyBERT
106
+ toponymy_embedding_model: null
107
+ toponymy_max_workers: 10
108
+ min_df: 3
109
+ outlier_threshold: 0.5
110
+
111
+ visualization:
112
+ enabled: true
113
+ title: "ADS Topic Map"
114
+ subtitle_template: "{topic_count} topics from {document_count:,} ADS records"
115
+ dark_mode: true
116
+ font_family: Cinzel
117
+ topic_tree: false
118
+
119
+ curation:
120
+ cluster_targets: []
121
+ clusters_to_remove: []
122
+
123
+ citations:
124
+ metrics:
125
+ - direct
126
+ - co_citation
127
+ - bibliographic_coupling
128
+ - author_co_citation
129
+ min_counts:
130
+ direct: 2
131
+ co_citation: 3
132
+ bibliographic_coupling: 2
133
+ author_co_citation: 3
134
+ authors_filter: null
135
+ authors_filter_uids: null
136
+ cited_authors_exclude: null
137
+ cited_author_uids_exclude: null
138
+ output_format: gexf