fetchpdf 0.1.8__tar.gz → 0.1.10__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. {fetchpdf-0.1.8/fetchpdf.egg-info → fetchpdf-0.1.10}/PKG-INFO +66 -21
  2. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/README.md +65 -20
  3. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/__init__.py +1 -1
  4. fetchpdf-0.1.10/fetchpdf/_cli.py +122 -0
  5. fetchpdf-0.1.10/fetchpdf/_prompt.py +41 -0
  6. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/fetchpdf.py +915 -291
  7. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/get_cookies.py +188 -40
  8. fetchpdf-0.1.10/fetchpdf/openalex_content.py +325 -0
  9. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/_util.py +13 -0
  10. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/classify.py +37 -7
  11. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/engine.py +32 -0
  12. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/extract_images.py +3 -1
  13. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/figures.py +5 -1
  14. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/institutional.py +259 -19
  15. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/ladder.json +18 -0
  16. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/pdf_identity.py +161 -10
  17. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/pdf_text.py +25 -13
  18. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/pubpeer.py +3 -1
  19. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/crossref_tdm.py +14 -0
  20. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/supplements.py +2 -1
  21. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/supplement_atypon.py +10 -2
  22. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/supplement_graph.py +368 -55
  23. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/supplement_index.py +47 -9
  24. fetchpdf-0.1.10/fetchpdf/retrieval/supplement_repos.py +459 -0
  25. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/supplementary.py +28 -2
  26. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/to_html.py +3 -1
  27. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/to_markdown.py +70 -14
  28. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/validate.py +14 -3
  29. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/verify.py +3 -1
  30. {fetchpdf-0.1.8 → fetchpdf-0.1.10/fetchpdf.egg-info}/PKG-INFO +66 -21
  31. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf.egg-info/SOURCES.txt +11 -0
  32. fetchpdf-0.1.10/tests/test_cli_suggest.py +74 -0
  33. fetchpdf-0.1.10/tests/test_datacite_reverse_paging.py +300 -0
  34. fetchpdf-0.1.10/tests/test_datacite_supplement_identity.py +232 -0
  35. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_get_cookies.py +69 -2
  36. fetchpdf-0.1.10/tests/test_high_severity_fixes.py +246 -0
  37. fetchpdf-0.1.10/tests/test_ia_scholar.py +416 -0
  38. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_institutional.py +219 -0
  39. fetchpdf-0.1.10/tests/test_openalex_content.py +447 -0
  40. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_pdf_identity.py +113 -0
  41. fetchpdf-0.1.10/tests/test_prompt.py +34 -0
  42. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_pure.py +38 -0
  43. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_retrieval.py +51 -0
  44. fetchpdf-0.1.10/tests/test_supplement_repos.py +419 -0
  45. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_supplementary.py +7 -3
  46. fetchpdf-0.1.8/tests/test_datacite_supplement_identity.py +0 -30
  47. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/LICENSE +0 -0
  48. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/MANIFEST.in +0 -0
  49. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/__main__.py +0 -0
  50. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/_env.py +0 -0
  51. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/_http.py +0 -0
  52. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/fetch_abstract_from_doi.py +0 -0
  53. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/fetch_metadata_from_doi.py +0 -0
  54. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/__init__.py +0 -0
  55. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/artifact.py +0 -0
  56. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/backends/__init__.py +0 -0
  57. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/backends/claude_cli.py +0 -0
  58. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/backends/openrouter.py +0 -0
  59. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/blocked.py +0 -0
  60. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/byline.py +0 -0
  61. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/cache.py +0 -0
  62. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/chunk.py +0 -0
  63. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/context.py +0 -0
  64. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/corresponding.py +0 -0
  65. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/fulltext_scan.py +0 -0
  66. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/goals.py +0 -0
  67. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/http.py +0 -0
  68. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/identifiers.py +0 -0
  69. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/linked_artifacts.py +0 -0
  70. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/llm_adjudicate.py +0 -0
  71. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/llm_agent_retrieval.py +0 -0
  72. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/normalize.py +0 -0
  73. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/provenance.py +0 -0
  74. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/ratelimit.py +0 -0
  75. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/references.py +0 -0
  76. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/repository_waf.py +0 -0
  77. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/request_drafts.py +0 -0
  78. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/resolve.py +0 -0
  79. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/__init__.py +0 -0
  80. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/arxiv.py +0 -0
  81. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/core_text.py +0 -0
  82. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/epmc.py +0 -0
  83. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/epmc_repo.py +0 -0
  84. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/landing.py +0 -0
  85. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/legacy_pdf.py +0 -0
  86. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/pmc.py +0 -0
  87. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/pmc_html.py +0 -0
  88. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/preprint.py +0 -0
  89. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/sources/publisher_html.py +0 -0
  90. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/supplement_dspace.py +0 -0
  91. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/supplement_jci.py +0 -0
  92. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/supplement_pmc.py +0 -0
  93. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/supplement_publishers.py +0 -0
  94. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/supplement_wayback.py +0 -0
  95. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf/retrieval/tiers.py +0 -0
  96. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf.egg-info/dependency_links.txt +0 -0
  97. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf.egg-info/entry_points.txt +0 -0
  98. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf.egg-info/requires.txt +0 -0
  99. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/fetchpdf.egg-info/top_level.txt +0 -0
  100. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/pyproject.toml +0 -0
  101. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/requirements.txt +0 -0
  102. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/setup.cfg +0 -0
  103. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_agent_backends.py +0 -0
  104. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_blocked.py +0 -0
  105. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_cookie_offer.py +0 -0
  106. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_corresponding.py +0 -0
  107. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_dspace.py +0 -0
  108. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_elsevier_routing.py +0 -0
  109. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_entrypoints.py +0 -0
  110. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_epmc_repo.py +0 -0
  111. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_extract_images.py +0 -0
  112. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_figures.py +0 -0
  113. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_folder_encoding.py +0 -0
  114. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_fulltext_scan.py +0 -0
  115. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_jci_supplements.py +0 -0
  116. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_json_output.py +0 -0
  117. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_landing_candidates.py +0 -0
  118. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_landing_page_detection.py +0 -0
  119. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_last_resort_reachability.py +0 -0
  120. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_linked_artifacts.py +0 -0
  121. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_llm_adjudicate.py +0 -0
  122. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_llm_agent_retrieval.py +0 -0
  123. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_normalize_cells.py +0 -0
  124. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_pdf_trailer.py +0 -0
  125. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_pmc_page.py +0 -0
  126. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_polite_ua.py +0 -0
  127. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_pubmed_identity.py +0 -0
  128. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_pubpeer.py +0 -0
  129. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_pull_for_record_call_sites.py +0 -0
  130. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_request_drafts.py +0 -0
  131. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_review_fixes.py +0 -0
  132. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_scan_record.py +0 -0
  133. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_screening_conversion.py +0 -0
  134. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_serpapi_scholar.py +0 -0
  135. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_short_conference_xml.py +0 -0
  136. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_supplement_asset_identity.py +0 -0
  137. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_to_html.py +0 -0
  138. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_xml_fallback_extras.py +0 -0
  139. {fetchpdf-0.1.8 → fetchpdf-0.1.10}/tests/test_xml_last.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fetchpdf
3
- Version: 0.1.8
3
+ Version: 0.1.10
4
4
  Summary: A comprehensive tool to download PDFs from DOIs using multiple sources
5
5
  Author-email: Dan Elton <delton17@gmail.com>
6
6
  License-Expression: MIT
@@ -74,6 +74,7 @@ A comprehensive Python package to download academic papers (PDFs) from DOIs (or
74
74
  - Crossref
75
75
  - Semantic Scholar
76
76
  - OpenAlex
77
+ - Internet Archive Scholar
77
78
  - CORE
78
79
  - Figshare
79
80
  - SSRN (Social Science Research Network)
@@ -133,7 +134,7 @@ too. API keys are **optional** but improve rate limits and reliability:
133
134
  EMAIL=your@email.com
134
135
 
135
136
  # Optional — improves rate limits / avoids throttling
136
- OPENALEXAPIKEY=your_openalex_key # OpenAlex: fewer 429 rate-limit errors
137
+ OPENALEXAPIKEY=your_openalex_key # OpenAlex: fewer 429s; paid full-text PDFs at end of run
137
138
  SEMANTIC_SCHOLAR_API_KEY=your_s2_key # Semantic Scholar: 1 → 10 req/s
138
139
  ENTREZ_EUTILS_API_KEY=your_ncbi_key # NCBI E-utilities: 3 → 10 req/s
139
140
  COREAPIKEY=your_core_key # CORE: 40M+ OA papers from core.ac.uk
@@ -151,6 +152,38 @@ OPENROUTER_API_KEY=your_openrouter_key # the retrieval agent's second backe
151
152
  PUBPEER_DEVKEY=your_pubpeer_key
152
153
  ```
153
154
 
155
+ **OpenAlex full-text PDFs (paid, asked first).** When a run ends with papers it
156
+ could not fetch, fetchpdf asks OpenAlex which of them it holds a PDF of (one
157
+ list call per 50 DOIs, $0.0001 each) and, in a terminal, asks before buying:
158
+
159
+ ```
160
+ 📚 12 papers are available through OpenAlex's full-text API, and it will cost $0.12 ($0.01 each).
161
+ Your API key has $0.98 credit available ($0.98 of today's daily allowance; the daily allowance resets in 4h 06m).
162
+ Would you like to download those papers? [y/N]:
163
+ ```
164
+
165
+ Answer `y` to buy them all, or a number to buy only that many. After a number,
166
+ the papers on offer are listed by journal with their counts (the 30 largest
167
+ first; `more` lists the rest), and you pick which journals to take them from,
168
+ e.g. `1,3,5-7`, or press Enter for any. `q` or Ctrl+C there buys nothing.
169
+
170
+ The credit is the key's free daily allowance ($1/day, reset at midnight UTC)
171
+ plus any prepaid balance, read from OpenAlex's free `/rate-limit` endpoint. When
172
+ it covers only some of the papers, only those are offered. Each PDF goes through
173
+ the same identity check as every other source, and recovered papers leave
174
+ `failed_dois.csv`. Pipes, cron and `--json` runs print the counts and buy
175
+ nothing; `--cookies-only`, `--abstract-only` and the XML-only modes skip it.
176
+ Without `OPENALEXAPIKEY` the run only says how many are available.
177
+
178
+ To go straight to that question without running retrieval at all, pass
179
+ `--skip-to-openalex`. It leaves out records that already have a PDF in the
180
+ output directory, so nothing is bought twice. Without a terminal it only
181
+ reports the count, which makes it a cheap way to check:
182
+
183
+ ```bash
184
+ fetchpdf failed_dois.csv --doi-column doi -o ./pdfs --skip-to-openalex
185
+ ```
186
+
154
187
  **What the keys change** (the rates are fetchpdf's own per-host throttles, set in
155
188
  [`ladder.json`](fetchpdf/retrieval/ladder.json)):
156
189
 
@@ -677,7 +710,7 @@ Twenty routes, tried in a fixed order so the numbering is reproducible:
677
710
  | bioRxiv / medRxiv | `10.1101` |
678
711
  | APA supplemental | `10.1037` |
679
712
  | Figshare / Zenodo / OSF | repository DOIs, and datasets reached through link services |
680
- | DataCite reverse relations | any DOI — finds deposits whose own DataCite record points at the article through a non-citation relation (e.g. `IsSupplementTo`); deposits that merely cite it are dropped |
713
+ | DataCite reverse relations | any DOI — finds deposits whose own DataCite record claims the article through a supplement relation (`IsSupplementTo`, `IsPartOf`, `IsDescribedBy`, `IsDocumentedBy`, or the inverse `IsSupplementedBy` / `HasPart`); deposits that cite it, derive from it (`IsDerivedFrom`) or relate to it any other way are dropped unless their title is a "Data from: <article title>"-style match or, for Dryad, Dryad's own API names the article as the dataset's primary article. Reads up to 500 records and routes up to 100 deposits, one per deposit however many versions are registered. Figshare "journal contribution" items (publisher SI documents, typed `JournalArticle` in DataCite) are kept when they say `IsSupplementTo` the article |
681
714
  | Crossref component DOIs | publishers that register components |
682
715
  | JATS-declared URLs | absolute URLs the JATS itself declares (e.g. LWW permalinks, publisher Source Data links) — recovery of last resort. Read from the PMC copy or, with no PMCID, from a publisher `{stem}.xml` saved beside the record (e.g. by `--get-xml-and-pdf`); TEI and non-JATS XML are ignored |
683
716
  | OpenAIRE ScholeXplorer | any DOI — Scholix publication→dataset/software links |
@@ -762,7 +795,7 @@ citation-grade link is promoted to `owned` only when the deposit's DataCite
762
795
  record names the article. Under `--download-data-artifacts`, `related` links are
763
796
  downloaded too, unless the deposit's own metadata says it belongs to a
764
797
  *different* article (`--download-related-unverified` drops even that check).
765
- Routed deposits in Figshare, Zenodo, OSF, Dryad or Harvard Dataverse go to those
798
+ Routed deposits in any repository in the download table below go to those
766
799
  enumerators and land under `{stem}_data_artifacts/<deposit>/` with their
767
800
  original filenames (`routed_to_download: true` in the sidecar); they still get
768
801
  an entry in the supplementary manifest. The same deposit named by several link
@@ -810,19 +843,28 @@ Download — repositories with file enumerators (links that pass the routing rul
810
843
 
811
844
  | Repository | Routed on | Notes |
812
845
  |---|---|---|
813
- | figshare | `10.6084` / "figshare" | declared size + md5 before transfer |
846
+ | figshare | `10.6084` / "figshare" | declared size + md5 before transfer; collections (`figshare.c.N`) are listed item by item |
847
+ | figshare portals | GSA `10.25386`/`10.25387`, ASHA `10.23641`, Sheffield `10.15131`, Loughborough `10.17028`, UCL `10.5522/04`, and any deposit whose DataCite landing page is on `*.figshare.com` | the item must name the deposit DOI back before its files are taken |
814
848
  | Zenodo | `10.5281` / "zenodo" | restricted records skipped |
815
849
  | OSF | `10.17605` / "osf.io" | walks folder trees (depth/node caps) |
816
850
  | Dryad | `10.5061` / "dryad" | declared size + sha-256, paginated |
817
851
  | Harvard Dataverse | `10.7910/DVN` | declared md5; restricted files skipped |
852
+ | Mendeley Data | `10.17632` | declared size + sha-256; older versions listed folder by folder |
853
+ | PANGAEA | `10.1594/PANGAEA.N` | one file per DOI (table, binary, or a zip for a series); no declared size or checksum; datasets under moratorium skipped |
854
+ | 4TU.ResearchData | `10.4121` | declared size + md5; embargoed and metadata-only records skipped; collections supported |
855
+ | Science Data Bank | `10.57760` / `10.11922` `sciencedb.` | declared size + md5; walks folders |
818
856
  | BioStudies | — | content arrives via the Europe PMC supplementary bundle instead, never fetched twice |
819
857
 
820
- Not yet downloadable (recorded in the sidecar, left to the operator):
821
- Mendeley Data (`10.17632`), non-Harvard Dataverse installations, subject
822
- databases (GEO, SRA, PDB, UniProt — accession records, not file bundles),
823
- GitLab repositories, and the institutional-repository long tail.
824
- Adding an enumerator is the same small pattern as `enumerate_dryad` /
825
- `enumerate_dataverse` in `fetchpdf/retrieval/supplement_index.py`.
858
+ Not downloadable (recorded, left to the operator):
859
+ SAGE's figshare (`10.25384` — the public figshare API does not serve it; SAGE
860
+ supplements come through the Atypon and Internet Archive routes instead),
861
+ ICPSR / openICPSR (`10.3886` — login and terms of use), non-Harvard Dataverse
862
+ installations, subject databases (GEO, SRA, PDB, UniProt — accession records,
863
+ not file bundles), GitLab repositories, and the institutional-repository long
864
+ tail. Dryad lists files freely but its download API currently answers HTTP 401
865
+ without a bearer token, so Dryad files are reported as `blocked`.
866
+ Adding an enumerator is the same small pattern as the ones in
867
+ `fetchpdf/retrieval/supplement_repos.py`.
826
868
 
827
869
  ## `--fetch-everything`: the second layer
828
870
 
@@ -1431,22 +1473,25 @@ These run first when the DOI matches (by prefix, or by the name appearing anywhe
1431
1473
  - `openAccessPdf` field, with a landing page fallback for OJS sites
1432
1474
  - PsyArXiv → OSF URL conversion
1433
1475
  8. **OpenAlex** — open-access locations; placed after Semantic Scholar to conserve OpenAlex's download quota
1434
- 9. **CORE** (core.ac.uk) — 40M+ repository papers; needs `COREAPIKEY`
1435
- 10. **DOAJ** — open-access full-text links
1436
- 11. **DataCite content URLs** — direct content and related resource links
1437
- 12. **Wiley rendered PDF** — only when Playwright is installed
1438
- 13. **APA supplemental** — APA supplemental files, converting `.doc`/`.docx` to PDF when available
1439
- 14. **Direct DOI resolver**
1476
+ 9. **Internet Archive Scholar** — the Archive's own capture of the PDF, served from the Wayback Machine
1477
+ - One keyless lookup by DOI ([scholar.archive.org](https://scholar.archive.org)); retried by PMID when the Archive does not know the DOI, and used for a PMID that has no DOI at all
1478
+ - Ahead of CORE because it has no daily quota; reported as `ia_scholar` in source tracking
1479
+ 10. **CORE** (core.ac.uk) — 40M+ repository papers; needs `COREAPIKEY`
1480
+ 11. **DOAJ** — open-access full-text links
1481
+ 12. **DataCite content URLs** — direct content and related resource links
1482
+ 13. **Wiley rendered PDF** — only when Playwright is installed
1483
+ 14. **APA supplemental** — APA supplemental files, converting `.doc`/`.docx` to PDF when available
1484
+ 15. **Direct DOI resolver**
1440
1485
  - Follows `https://doi.org/{doi}` to the landing page
1441
1486
  - Handles Crossref chooser pages (multiple resolution)
1442
1487
  - Scrapes PDF links from HTML (`citation_pdf_url`, href patterns)
1443
1488
  - Publisher-specific deterministic URL patterns (Wiley, T&F, SAGE, MIT Press, …)
1444
- 15. **DataCite related identifiers**
1489
+ 16. **DataCite related identifiers**
1445
1490
  - Supplementary material → main paper
1446
1491
  - Versioned DOI resolution (`IsIdenticalTo`, `IsVersionOf`)
1447
- 16. **DOI → PMID fallback**
1492
+ 17. **DOI → PMID fallback**
1448
1493
  - Converts the DOI to a PMID and tries PMID-native sources (the PubMed page's `citation_pdf_url`)
1449
- 17. **Google Scholar via SerpApi** (optional)
1494
+ 18. **Google Scholar via SerpApi** (optional)
1450
1495
  - Enabled by `SERPAPI_API_KEY` in `.env.local` or the environment
1451
1496
  - Searches the quoted DOI, then the quoted article title if the DOI search returned results but no accepted PDF
1452
1497
  - At most two searches per unresolved DOI, with up to five results per search;
@@ -1460,7 +1505,7 @@ These run first when the DOI matches (by prefix, or by the name appearing anywhe
1460
1505
 
1461
1506
  ### Final Fallbacks
1462
1507
 
1463
- 18. **Elsevier full-text API**
1508
+ 19. **Elsevier full-text API**
1464
1509
  - Elsevier records only (`10.1016/*`, or a Crossref landing page on sciencedirect.com / elsevier.com)
1465
1510
  - Requires `ELSEVIER_TDM_API_KEY`
1466
1511
  - **`10.1016/*` DOIs are asked for their PDF first** — before PMC, Unpaywall,
@@ -34,6 +34,7 @@ A comprehensive Python package to download academic papers (PDFs) from DOIs (or
34
34
  - Crossref
35
35
  - Semantic Scholar
36
36
  - OpenAlex
37
+ - Internet Archive Scholar
37
38
  - CORE
38
39
  - Figshare
39
40
  - SSRN (Social Science Research Network)
@@ -93,7 +94,7 @@ too. API keys are **optional** but improve rate limits and reliability:
93
94
  EMAIL=your@email.com
94
95
 
95
96
  # Optional — improves rate limits / avoids throttling
96
- OPENALEXAPIKEY=your_openalex_key # OpenAlex: fewer 429 rate-limit errors
97
+ OPENALEXAPIKEY=your_openalex_key # OpenAlex: fewer 429s; paid full-text PDFs at end of run
97
98
  SEMANTIC_SCHOLAR_API_KEY=your_s2_key # Semantic Scholar: 1 → 10 req/s
98
99
  ENTREZ_EUTILS_API_KEY=your_ncbi_key # NCBI E-utilities: 3 → 10 req/s
99
100
  COREAPIKEY=your_core_key # CORE: 40M+ OA papers from core.ac.uk
@@ -111,6 +112,38 @@ OPENROUTER_API_KEY=your_openrouter_key # the retrieval agent's second backe
111
112
  PUBPEER_DEVKEY=your_pubpeer_key
112
113
  ```
113
114
 
115
+ **OpenAlex full-text PDFs (paid, asked first).** When a run ends with papers it
116
+ could not fetch, fetchpdf asks OpenAlex which of them it holds a PDF of (one
117
+ list call per 50 DOIs, $0.0001 each) and, in a terminal, asks before buying:
118
+
119
+ ```
120
+ 📚 12 papers are available through OpenAlex's full-text API, and it will cost $0.12 ($0.01 each).
121
+ Your API key has $0.98 credit available ($0.98 of today's daily allowance; the daily allowance resets in 4h 06m).
122
+ Would you like to download those papers? [y/N]:
123
+ ```
124
+
125
+ Answer `y` to buy them all, or a number to buy only that many. After a number,
126
+ the papers on offer are listed by journal with their counts (the 30 largest
127
+ first; `more` lists the rest), and you pick which journals to take them from,
128
+ e.g. `1,3,5-7`, or press Enter for any. `q` or Ctrl+C there buys nothing.
129
+
130
+ The credit is the key's free daily allowance ($1/day, reset at midnight UTC)
131
+ plus any prepaid balance, read from OpenAlex's free `/rate-limit` endpoint. When
132
+ it covers only some of the papers, only those are offered. Each PDF goes through
133
+ the same identity check as every other source, and recovered papers leave
134
+ `failed_dois.csv`. Pipes, cron and `--json` runs print the counts and buy
135
+ nothing; `--cookies-only`, `--abstract-only` and the XML-only modes skip it.
136
+ Without `OPENALEXAPIKEY` the run only says how many are available.
137
+
138
+ To go straight to that question without running retrieval at all, pass
139
+ `--skip-to-openalex`. It leaves out records that already have a PDF in the
140
+ output directory, so nothing is bought twice. Without a terminal it only
141
+ reports the count, which makes it a cheap way to check:
142
+
143
+ ```bash
144
+ fetchpdf failed_dois.csv --doi-column doi -o ./pdfs --skip-to-openalex
145
+ ```
146
+
114
147
  **What the keys change** (the rates are fetchpdf's own per-host throttles, set in
115
148
  [`ladder.json`](fetchpdf/retrieval/ladder.json)):
116
149
 
@@ -637,7 +670,7 @@ Twenty routes, tried in a fixed order so the numbering is reproducible:
637
670
  | bioRxiv / medRxiv | `10.1101` |
638
671
  | APA supplemental | `10.1037` |
639
672
  | Figshare / Zenodo / OSF | repository DOIs, and datasets reached through link services |
640
- | DataCite reverse relations | any DOI — finds deposits whose own DataCite record points at the article through a non-citation relation (e.g. `IsSupplementTo`); deposits that merely cite it are dropped |
673
+ | DataCite reverse relations | any DOI — finds deposits whose own DataCite record claims the article through a supplement relation (`IsSupplementTo`, `IsPartOf`, `IsDescribedBy`, `IsDocumentedBy`, or the inverse `IsSupplementedBy` / `HasPart`); deposits that cite it, derive from it (`IsDerivedFrom`) or relate to it any other way are dropped unless their title is a "Data from: <article title>"-style match or, for Dryad, Dryad's own API names the article as the dataset's primary article. Reads up to 500 records and routes up to 100 deposits, one per deposit however many versions are registered. Figshare "journal contribution" items (publisher SI documents, typed `JournalArticle` in DataCite) are kept when they say `IsSupplementTo` the article |
641
674
  | Crossref component DOIs | publishers that register components |
642
675
  | JATS-declared URLs | absolute URLs the JATS itself declares (e.g. LWW permalinks, publisher Source Data links) — recovery of last resort. Read from the PMC copy or, with no PMCID, from a publisher `{stem}.xml` saved beside the record (e.g. by `--get-xml-and-pdf`); TEI and non-JATS XML are ignored |
643
676
  | OpenAIRE ScholeXplorer | any DOI — Scholix publication→dataset/software links |
@@ -722,7 +755,7 @@ citation-grade link is promoted to `owned` only when the deposit's DataCite
722
755
  record names the article. Under `--download-data-artifacts`, `related` links are
723
756
  downloaded too, unless the deposit's own metadata says it belongs to a
724
757
  *different* article (`--download-related-unverified` drops even that check).
725
- Routed deposits in Figshare, Zenodo, OSF, Dryad or Harvard Dataverse go to those
758
+ Routed deposits in any repository in the download table below go to those
726
759
  enumerators and land under `{stem}_data_artifacts/<deposit>/` with their
727
760
  original filenames (`routed_to_download: true` in the sidecar); they still get
728
761
  an entry in the supplementary manifest. The same deposit named by several link
@@ -770,19 +803,28 @@ Download — repositories with file enumerators (links that pass the routing rul
770
803
 
771
804
  | Repository | Routed on | Notes |
772
805
  |---|---|---|
773
- | figshare | `10.6084` / "figshare" | declared size + md5 before transfer |
806
+ | figshare | `10.6084` / "figshare" | declared size + md5 before transfer; collections (`figshare.c.N`) are listed item by item |
807
+ | figshare portals | GSA `10.25386`/`10.25387`, ASHA `10.23641`, Sheffield `10.15131`, Loughborough `10.17028`, UCL `10.5522/04`, and any deposit whose DataCite landing page is on `*.figshare.com` | the item must name the deposit DOI back before its files are taken |
774
808
  | Zenodo | `10.5281` / "zenodo" | restricted records skipped |
775
809
  | OSF | `10.17605` / "osf.io" | walks folder trees (depth/node caps) |
776
810
  | Dryad | `10.5061` / "dryad" | declared size + sha-256, paginated |
777
811
  | Harvard Dataverse | `10.7910/DVN` | declared md5; restricted files skipped |
812
+ | Mendeley Data | `10.17632` | declared size + sha-256; older versions listed folder by folder |
813
+ | PANGAEA | `10.1594/PANGAEA.N` | one file per DOI (table, binary, or a zip for a series); no declared size or checksum; datasets under moratorium skipped |
814
+ | 4TU.ResearchData | `10.4121` | declared size + md5; embargoed and metadata-only records skipped; collections supported |
815
+ | Science Data Bank | `10.57760` / `10.11922` `sciencedb.` | declared size + md5; walks folders |
778
816
  | BioStudies | — | content arrives via the Europe PMC supplementary bundle instead, never fetched twice |
779
817
 
780
- Not yet downloadable (recorded in the sidecar, left to the operator):
781
- Mendeley Data (`10.17632`), non-Harvard Dataverse installations, subject
782
- databases (GEO, SRA, PDB, UniProt — accession records, not file bundles),
783
- GitLab repositories, and the institutional-repository long tail.
784
- Adding an enumerator is the same small pattern as `enumerate_dryad` /
785
- `enumerate_dataverse` in `fetchpdf/retrieval/supplement_index.py`.
818
+ Not downloadable (recorded, left to the operator):
819
+ SAGE's figshare (`10.25384` — the public figshare API does not serve it; SAGE
820
+ supplements come through the Atypon and Internet Archive routes instead),
821
+ ICPSR / openICPSR (`10.3886` — login and terms of use), non-Harvard Dataverse
822
+ installations, subject databases (GEO, SRA, PDB, UniProt — accession records,
823
+ not file bundles), GitLab repositories, and the institutional-repository long
824
+ tail. Dryad lists files freely but its download API currently answers HTTP 401
825
+ without a bearer token, so Dryad files are reported as `blocked`.
826
+ Adding an enumerator is the same small pattern as the ones in
827
+ `fetchpdf/retrieval/supplement_repos.py`.
786
828
 
787
829
  ## `--fetch-everything`: the second layer
788
830
 
@@ -1391,22 +1433,25 @@ These run first when the DOI matches (by prefix, or by the name appearing anywhe
1391
1433
  - `openAccessPdf` field, with a landing page fallback for OJS sites
1392
1434
  - PsyArXiv → OSF URL conversion
1393
1435
  8. **OpenAlex** — open-access locations; placed after Semantic Scholar to conserve OpenAlex's download quota
1394
- 9. **CORE** (core.ac.uk) — 40M+ repository papers; needs `COREAPIKEY`
1395
- 10. **DOAJ** — open-access full-text links
1396
- 11. **DataCite content URLs** — direct content and related resource links
1397
- 12. **Wiley rendered PDF** — only when Playwright is installed
1398
- 13. **APA supplemental** — APA supplemental files, converting `.doc`/`.docx` to PDF when available
1399
- 14. **Direct DOI resolver**
1436
+ 9. **Internet Archive Scholar** — the Archive's own capture of the PDF, served from the Wayback Machine
1437
+ - One keyless lookup by DOI ([scholar.archive.org](https://scholar.archive.org)); retried by PMID when the Archive does not know the DOI, and used for a PMID that has no DOI at all
1438
+ - Ahead of CORE because it has no daily quota; reported as `ia_scholar` in source tracking
1439
+ 10. **CORE** (core.ac.uk) — 40M+ repository papers; needs `COREAPIKEY`
1440
+ 11. **DOAJ** — open-access full-text links
1441
+ 12. **DataCite content URLs** — direct content and related resource links
1442
+ 13. **Wiley rendered PDF** — only when Playwright is installed
1443
+ 14. **APA supplemental** — APA supplemental files, converting `.doc`/`.docx` to PDF when available
1444
+ 15. **Direct DOI resolver**
1400
1445
  - Follows `https://doi.org/{doi}` to the landing page
1401
1446
  - Handles Crossref chooser pages (multiple resolution)
1402
1447
  - Scrapes PDF links from HTML (`citation_pdf_url`, href patterns)
1403
1448
  - Publisher-specific deterministic URL patterns (Wiley, T&F, SAGE, MIT Press, …)
1404
- 15. **DataCite related identifiers**
1449
+ 16. **DataCite related identifiers**
1405
1450
  - Supplementary material → main paper
1406
1451
  - Versioned DOI resolution (`IsIdenticalTo`, `IsVersionOf`)
1407
- 16. **DOI → PMID fallback**
1452
+ 17. **DOI → PMID fallback**
1408
1453
  - Converts the DOI to a PMID and tries PMID-native sources (the PubMed page's `citation_pdf_url`)
1409
- 17. **Google Scholar via SerpApi** (optional)
1454
+ 18. **Google Scholar via SerpApi** (optional)
1410
1455
  - Enabled by `SERPAPI_API_KEY` in `.env.local` or the environment
1411
1456
  - Searches the quoted DOI, then the quoted article title if the DOI search returned results but no accepted PDF
1412
1457
  - At most two searches per unresolved DOI, with up to five results per search;
@@ -1420,7 +1465,7 @@ These run first when the DOI matches (by prefix, or by the name appearing anywhe
1420
1465
 
1421
1466
  ### Final Fallbacks
1422
1467
 
1423
- 18. **Elsevier full-text API**
1468
+ 19. **Elsevier full-text API**
1424
1469
  - Elsevier records only (`10.1016/*`, or a Crossref landing page on sciencedirect.com / elsevier.com)
1425
1470
  - Requires `ELSEVIER_TDM_API_KEY`
1426
1471
  - **`10.1016/*` DOIs are asked for their PDF first** — before PMC, Unpaywall,
@@ -15,7 +15,7 @@ from .fetch_metadata_from_doi import fetch_metadata_from_doi
15
15
  # behavioural difference, it is the same object.
16
16
  fetch_pdf_from_doi = fetch_pdf
17
17
 
18
- __version__ = "0.1.8"
18
+ __version__ = "0.1.10"
19
19
  __all__ = [
20
20
  "fetch_pdf",
21
21
  "fetch_pdf_from_doi", # deprecated alias for fetch_pdf
@@ -0,0 +1,122 @@
1
+ """An argparse parser that answers a mistyped flag with what was probably meant.
2
+
3
+ $ fetchpdf 10.1038/nature12373 --fetch-everyting
4
+ fetchpdf: error: unrecognized arguments: --fetch-everyting
5
+ --fetch-everyting: did you mean --fetch-everything?
6
+
7
+ Stock argparse only says the argument is unrecognized. The suggestion is
8
+ drawn from the long options of the parsers that actually took part in the
9
+ parse -- the top-level one and, for `fetchpdf cookies setup ...`, the chosen
10
+ subcommand's -- so it never names a flag from a sibling subcommand that
11
+ would be rejected in turn. A mistyped subcommand or choice value gets the
12
+ same treatment ("invalid choice: 'setpu'" -> setup).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import difflib
19
+ import re
20
+ from typing import Iterable, List, Sequence
21
+
22
+ __all__ = ["ArgumentParser", "suggest"]
23
+
24
+ # Parsers whose parse_known_args ran during the current parse_args call, in
25
+ # order: the top-level parser, then each subcommand parser it dispatched to.
26
+ # Module-level because a subparser has no link back to its parent; the CLI
27
+ # parses once per process, on one thread.
28
+ _active: List["ArgumentParser"] = []
29
+
30
+
31
+ def _normalize(token: str) -> str:
32
+ """`--Fetch_Everything=yes` and `-fetch-everything` both -> `--fetch-everything`."""
33
+ flag = token.split("=", 1)[0].lower().replace("_", "-")
34
+ if not flag.startswith("--") and len(flag) > 2:
35
+ flag = "-" + flag # a long name typed with one dash
36
+ return flag
37
+
38
+
39
+ def suggest(token: str, options: Iterable[str], n: int = 3) -> List[str]:
40
+ """Up to `n` long options close to `token`, best first.
41
+
42
+ String similarity first (typos, transpositions, a swapped verb such as
43
+ --pull-/--fetch-); failing that, options sharing a whole word with it,
44
+ so `--everything` still finds --fetch-everything.
45
+ """
46
+ flag = _normalize(token)
47
+ longs = [o for o in dict.fromkeys(options) if o.startswith("--")]
48
+ ratios = sorted(((difflib.SequenceMatcher(None, flag, o).ratio(), o) for o in longs),
49
+ reverse=True)
50
+ if ratios and ratios[0][0] >= 0.6:
51
+ # Only the near-best: a clear typo of one flag shouldn't drag in
52
+ # whatever else happens to share its prefix.
53
+ best = ratios[0][0]
54
+ return [o for r, o in ratios[:n] if r >= max(0.6, best - 0.1)]
55
+ words = {w for w in flag.strip("-").split("-") if len(w) >= 4}
56
+ if not words:
57
+ return []
58
+ scored = []
59
+ for opt in longs:
60
+ shared = len(words & set(opt[2:].split("-")))
61
+ if shared:
62
+ scored.append((-shared, difflib.SequenceMatcher(None, flag, opt).ratio() * -1, opt))
63
+ return [opt for *_, opt in sorted(scored)[:n]]
64
+
65
+
66
+ def _or_list(items: Sequence[str]) -> str:
67
+ return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " or " + items[-1]
68
+
69
+
70
+ class ArgumentParser(argparse.ArgumentParser):
71
+ """argparse.ArgumentParser plus did-you-mean hints for unknown flags."""
72
+
73
+ def parse_known_args(self, args=None, namespace=None):
74
+ _active.append(self)
75
+ return super().parse_known_args(args, namespace)
76
+
77
+ def parse_args(self, args=None, namespace=None):
78
+ _active.clear()
79
+ parsed, extras = self.parse_known_args(args, namespace)
80
+ if extras:
81
+ self.error(self._unrecognized_message(extras))
82
+ return parsed
83
+
84
+ def _scope(self) -> List["ArgumentParser"]:
85
+ return list(_active) or [self]
86
+
87
+ def _unrecognized_message(self, extras: Sequence[str]) -> str:
88
+ lines = ["unrecognized arguments: " + " ".join(extras)]
89
+ actions = {} # option string -> action, to show one name per action
90
+ for parser in self._scope():
91
+ for opt, action in parser._option_string_actions.items():
92
+ actions.setdefault(opt, action)
93
+ for token in extras:
94
+ if not token.startswith("-") or len(token) <= 2 or _looks_numeric(token):
95
+ continue
96
+ seen, picks = set(), []
97
+ for opt in suggest(token, actions):
98
+ if id(actions[opt]) not in seen: # --pull-everything = --fetch-everything
99
+ seen.add(id(actions[opt]))
100
+ picks.append(opt)
101
+ if picks:
102
+ lines.append(f" {token}: did you mean {_or_list(picks)}?")
103
+ return "\n".join(lines)
104
+
105
+ def error(self, message):
106
+ # Python 3.14+ can already suggest choices itself (suggest_on_error).
107
+ match = re.search(r"invalid choice: '([^']*)'", message)
108
+ if match and "maybe you meant" not in message:
109
+ choices = [str(c) for p in self._scope() for a in p._actions
110
+ if a.choices for c in a.choices]
111
+ picks = difflib.get_close_matches(match.group(1), choices, n=3, cutoff=0.6)
112
+ if picks:
113
+ message += f"\n did you mean {_or_list(picks)}?"
114
+ super().error(message)
115
+
116
+
117
+ def _looks_numeric(token: str) -> bool:
118
+ try:
119
+ float(token)
120
+ return True
121
+ except ValueError:
122
+ return False
@@ -0,0 +1,41 @@
1
+ """Read one answer from the user without input()'s terminal trap.
2
+
3
+ On a terminal, input() reads through CPython's C line reader, which measures
4
+ the line with strlen(). A NUL byte -- what Ctrl+Space types, easy to hit by
5
+ accident -- ends the string early, so the reader never sees the newline and
6
+ keeps waiting: the prompt shows "^@y", Enter does nothing, and only Ctrl+C
7
+ gets out. A run that took twenty minutes then looks hung at its last question.
8
+
9
+ sys.stdin.readline() reads the same terminal line without that limit, so on a
10
+ terminal it is used instead, and control characters are dropped from the
11
+ answer either way. Off a terminal input() is kept: it behaves there, and it is
12
+ what the test suite stubs.
13
+ """
14
+ import re
15
+ import sys
16
+
17
+ _CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")
18
+
19
+
20
+ def _stdin_is_tty() -> bool:
21
+ try:
22
+ return bool(sys.stdin and sys.stdin.isatty())
23
+ except (AttributeError, ValueError, OSError):
24
+ return False
25
+
26
+
27
+ def ask(prompt: str) -> str:
28
+ """The user's answer, stripped of control characters and outer whitespace.
29
+
30
+ Raises EOFError when stdin is closed and KeyboardInterrupt on Ctrl+C,
31
+ the same as input(), so callers keep their existing handlers.
32
+ """
33
+ if _stdin_is_tty():
34
+ sys.stdout.write(prompt)
35
+ sys.stdout.flush()
36
+ line = sys.stdin.readline()
37
+ if not line:
38
+ raise EOFError
39
+ else:
40
+ line = input(prompt)
41
+ return _CONTROL.sub("", line).strip()