hal-dl 0.1.0

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: be0a1072d4996d735a8e0b98a17f31f3e18e05dfe60051f2c1a68e6f660f4509
4
+ data.tar.gz: 4d6a0469fb2557edf0ae806b2eea646a09bc2fe4e0c367a6bf478567d012cc8c
5
+ SHA512:
6
+ metadata.gz: 61e11c505aea561cc60465c842ceb0fec6c690e78def32a12239dfe45d8e55114222f3e6f25b5b2040d01384d428f1a9717bb9fa6635bc678b92113a3ccbe817
7
+ data.tar.gz: d1dd31c24addd5852d00c4a35413bbb0adf8a9ce6c54069661acddbe64d91dc5d74721e608e716a90ceec8106bd1d7ce01770851d1c445490901500c5d617c5d
data/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ ## [0.1.0]
2
+
3
+ First version. Per-paper offline archive of HAL (hal.science) papers, any version, built on [dl-core](https://github.com/xoengineering/dl-core).
4
+
5
+ - Accepts HAL IDs with any portal prefix (`hal-`, `tel-`, `halshs-`, `hal-pasteur-`, …), with or without a version, and hal.science, portal, and archives-ouvertes.fr URLs.
6
+ - Saves the deposited PDF, HAL's TEI metadata verbatim, and four sidecar metadata files; `metadata.bib` is HAL's own BibTeX. Authors carry their primary affiliations.
7
+ - Layout: `YYYY/MM/DD/<domain>/<hal-id>-<slug>/`, flat for a paper with only v1 archived, `v<N>/` folders otherwise.
8
+ - Metadata-only records raise `HAL::Downloader::NoFile`; unknown IDs raise `HAL::Downloader::PaperNotFound`.
9
+ - Rate-limited HTTP client (3s default) with timeouts and retries on 429/503, staged downloads that skip already-archived versions, and a CLI with `--input FILE|-`, per-target error reporting, and exit status 1 on any failure, all from dl-core.
@@ -0,0 +1,83 @@
1
+ # Contributor Covenant 3.0 Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We pledge to make our community welcoming, safe, and equitable for all.
6
+
7
+ We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant.
8
+
9
+ ## Encouraged Behaviors
10
+
11
+ While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language.
12
+
13
+ With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including:
14
+
15
+ 1. Respecting the **purpose of our community**, our activities, and our ways of gathering.
16
+ 2. Engaging **kindly and honestly** with others.
17
+ 3. Respecting **different viewpoints** and experiences.
18
+ 4. **Taking responsibility** for our actions and contributions.
19
+ 5. Gracefully giving and accepting **constructive feedback**.
20
+ 6. Committing to **repairing harm** when it occurs.
21
+ 7. Behaving in other ways that promote and sustain the **well-being of our community**.
22
+
23
+ ## Restricted Behaviors
24
+
25
+ We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct.
26
+
27
+ 1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop.
28
+ 2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people.
29
+ 3. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits.
30
+ 4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community.
31
+ 5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission.
32
+ 6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group.
33
+ 7. Behaving in other ways that **threaten the well-being** of our community.
34
+
35
+ ### Other Restrictions
36
+
37
+ 1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions.
38
+ 2. **Failing to credit sources.** Not properly crediting the sources of content you contribute.
39
+ 3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community.
40
+ 4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors.
41
+
42
+ ## Reporting an Issue
43
+
44
+ Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm.
45
+
46
+ When an incident does occur, it is important to report it promptly. To report a possible violation, **email the maintainer at [veganstraightedge@gmail.com](mailto:veganstraightedge@gmail.com).**
47
+
48
+ Community Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution.
49
+
50
+ ## Addressing and Repairing Harm
51
+
52
+ If an investigation by the Community Moderators finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped.
53
+
54
+ 1. Warning
55
+ 1. Event: A violation involving a single incident or series of incidents.
56
+ 2. Consequence: A private, written warning from the Community Moderators.
57
+ 3. Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations.
58
+ 2. Temporarily Limited Activities
59
+ 1. Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation.
60
+ 2. Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members.
61
+ 3. Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over.
62
+ 3. Temporary Suspension
63
+ 1. Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation.
64
+ 2. Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behavior and possible corrective actions.
65
+ 3. Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted.
66
+ 4. Permanent Ban
67
+ 1. Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member.
68
+ 2. Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behavior.
69
+ 3. Repair: There is no possible repair in cases of this severity.
70
+
71
+ This enforcement ladder is intended as a guideline. It does not limit the ability of Community Managers to use their discretion and judgment, in keeping with the best interests of our community.
72
+
73
+ ## Scope
74
+
75
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
76
+
77
+ ## Attribution
78
+
79
+ This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/).
80
+
81
+ Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/)
82
+
83
+ For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion).
data/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Shane Becker
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,117 @@
1
+ # hal-dl
2
+
3
+ Download papers and metadata from [HAL](https://hal.science), France's national open archive, for offline archives.
4
+
5
+ For each paper version, `hal-dl` saves:
6
+
7
+ - The deposited PDF
8
+ - HAL's own TEI metadata (XML), verbatim
9
+ - Four sidecar metadata files: `metadata.md`, `metadata.yaml`, `metadata.json`, and `metadata.bib` (HAL's own BibTeX)
10
+
11
+ Any version can be archived, not just the latest.
12
+
13
+ ## HAL's terms
14
+
15
+ From HAL's [legal aspects](http://doc.hal.science/en/legal-aspects/): HAL does not permit commercial use of extracted data; cite the source (the HAL URL, which `hal-dl` writes into every sidecar); authors retain their intellectual property rights, and each record's licence (recorded as `licence`) governs reuse of its files.
16
+
17
+ ## Installation
18
+
19
+ ```sh
20
+ gem install hal-dl
21
+ ```
22
+
23
+ ## CLI usage
24
+
25
+ ```sh
26
+ hal-dl <HAL_ID_OR_URL> [<HAL_ID_OR_URL>...]
27
+ ```
28
+
29
+ Accepted input forms:
30
+
31
+ | Form | Example |
32
+ | ----------------- | ------------------------------------------------------------------------------ |
33
+ | HAL ID | `hal-01207234`, `tel-00012345`, `halshs-00012345`, `hal-pasteur-00012345` |
34
+ | Versioned HAL ID | `hal-01207234v1` |
35
+ | hal.science URL | `https://hal.science/hal-01207234v3`, `https://hal.science/hal-01207234/document` |
36
+ | Portal URL | `https://theses.hal.science/tel-00012345` |
37
+ | Older HAL URL | `https://hal.archives-ouvertes.fr/hal-01207234v2` |
38
+
39
+ An unversioned ID archives the latest version; a versioned ID archives that version.
40
+
41
+ ### Flags
42
+
43
+ | Flag | Description |
44
+ | ------------------------- | ----------------------------------------------------------------------------- |
45
+ | `-i FILE`, `--input FILE` | Read IDs/URLs from FILE, one per line (`-` for stdin; blanks and `#` skipped) |
46
+ | `-p PATH`, `--path PATH` | Root download directory |
47
+ | `--rate-limit SECONDS` | Seconds between HTTP requests; `0` disables throttling |
48
+ | `-v`, `--verbose` | Print step lines and per-request URL/byte logs to stdout |
49
+ | `-q`, `--quiet` | Print nothing to stdout; errors still go to stderr |
50
+ | `--version` | Print the gem version and exit |
51
+ | `-h`, `--help` | Print help and exit |
52
+
53
+ `-v` and `-q` are mutually exclusive.
54
+
55
+ ### Environment variables
56
+
57
+ | Variable | Effect |
58
+ | ------------------- | --------------------------------------------------------------- |
59
+ | `HAL_DOWNLOAD_PATH` | Root download directory (default: `$HOME/Downloads/HAL_Papers`) |
60
+ | `HAL_RATE_LIMIT` | Seconds between HTTP requests (default: `3`; `0` disables) |
61
+
62
+ Precedence: CLI flag > ENV var > default.
63
+
64
+ ### Errors and exit status
65
+
66
+ A target that fails (unrecognized ID, no such document, metadata-only record with no file, HTTP error, network failure) is reported on stderr as `<target>: <message>`, and the remaining targets still download. Exit status is `0` when every target succeeds and `1` when any fails.
67
+
68
+ ## Output layout
69
+
70
+ ```txt
71
+ $HAL_DOWNLOAD_PATH/ # default: $HOME/Downloads/HAL_Papers
72
+ YYYY/MM/DD/<domain>/<hal-id>-<slug>/
73
+ <hal-id>v<N>.pdf
74
+ hal.xml # HAL's TEI metadata, verbatim
75
+ metadata.md # YAML frontmatter + Markdown body
76
+ metadata.yaml
77
+ metadata.json
78
+ metadata.bib # HAL's own BibTeX
79
+ ```
80
+
81
+ `YYYY/MM/DD` is the publication date (shorter when only the year or month is known; the submission date when there is none). `<domain>` is HAL's primary domain code (`spi.auto`, `sdv.gen`, …). `<slug>` is derived from the title.
82
+
83
+ A paper with only v1 archived is kept flat, as above. When a paper has more than one version, each version gets its own `v<N>/` folder with the same contents; archiving a second version of a flat paper first moves the existing files into `v<N>/`. A paper whose latest version is v2 or later starts out in `v<N>/` folders.
84
+
85
+ Each version downloads into a sibling `.partial` folder and is renamed into place only when every file succeeded. Re-running skips versions already archived.
86
+
87
+ ## Library usage
88
+
89
+ ```ruby
90
+ require 'hal/downloader'
91
+
92
+ identifier = HAL::Downloader::Identifier.new 'https://hal.science/hal-01207234v1'
93
+ client = HAL::Downloader::Client.new # 3-second rate limit by default
94
+ path = HAL::Downloader::Archive.new(identifier, root: '/tmp/papers', client: client).run
95
+ ```
96
+
97
+ ## Development
98
+
99
+ ```sh
100
+ script/setup # install dependencies
101
+ script/test # run specs and rubocop
102
+ script/console # interactive prompt
103
+ ```
104
+
105
+ Specs run offline against recorded fixtures in `spec/fixtures/http/` (the PDF fixture is the first 4 KB of the real file). To check the JSON fixtures against the live HAL site, run:
106
+
107
+ ```sh
108
+ HAL_LIVE=1 script/test
109
+ ```
110
+
111
+ ## License
112
+
113
+ MIT — see [LICENSE.md](LICENSE.md).
114
+
115
+ ## Code of Conduct
116
+
117
+ This project follows the [Contributor Covenant](https://www.contributor-covenant.org/version/3/0/) 3.0 — see [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
data/exe/hal-dl ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'hal/downloader'
4
+
5
+ exit HAL::Downloader::CLI.new(ARGV).run
@@ -0,0 +1,93 @@
1
+ require 'fileutils'
2
+
3
+ module HAL
4
+ module Downloader
5
+ class Archive
6
+ def initialize identifier, root:, client: Client.new
7
+ @identifier = identifier
8
+ @root = root
9
+ @client = client
10
+ end
11
+
12
+ # Downloads into <destination>.partial/ and
13
+ # renames it into place only once everything succeeded.
14
+ # An archived version is always complete and is skipped.
15
+ # PaperFolder decides flat (single version) vs v<N>/ (several versions).
16
+ def run
17
+ raise NoFile unless metadata.submit_type == 'file'
18
+ return paper_folder.location_of(metadata.version) if paper_folder.archived? metadata.version
19
+
20
+ paper_folder.unflatten!
21
+ FileUtils.rm_rf staging_dir
22
+ FileUtils.mkdir_p staging_dir
23
+
24
+ download_pdf
25
+ download_tei
26
+ write_sidecars
27
+
28
+ File.rename staging_dir, destination
29
+ destination
30
+ end
31
+
32
+ private
33
+
34
+ def parser
35
+ @parser ||= MetadataParser.new fetch_metadata
36
+ end
37
+
38
+ # the requested version, or the latest when none was requested
39
+ def fetch_metadata
40
+ @client.get("https://hal.science/#{@identifier}/json").to_s
41
+ rescue HTTPError => e
42
+ raise PaperNotFound if e.status == 404
43
+
44
+ raise
45
+ end
46
+
47
+ def metadata
48
+ @metadata ||= parser.metadata
49
+ end
50
+
51
+ # the version HAL actually returned, so every download matches the metadata
52
+ def archived
53
+ @archived ||= Identifier.new "#{metadata.hal_id}v#{metadata.version}"
54
+ end
55
+
56
+ def paper_folder
57
+ @paper_folder ||= PaperFolder.new File.join(@root, Path.new(metadata).to_s)
58
+ end
59
+
60
+ # evaluated after unflatten!, which can turn a flat folder into v<N>/ folders
61
+ def destination
62
+ @destination ||= paper_folder.destination_for metadata.version
63
+ end
64
+
65
+ # a sibling of destination, so the rename is a single atomic step
66
+ def staging_dir
67
+ "#{destination}.partial"
68
+ end
69
+
70
+ def download_pdf
71
+ body = @client.get("https://hal.science/#{archived}/document").to_s
72
+ File.binwrite File.join(staging_dir, "#{archived.file_stem}.pdf"), body
73
+ end
74
+
75
+ # HAL's own TEI metadata, verbatim, when it has it
76
+ def download_tei
77
+ body = @client.get("https://hal.science/#{archived}/tei").to_s
78
+ File.write File.join(staging_dir, 'hal.xml'), body
79
+ rescue HTTPError => e
80
+ raise unless e.status == 404
81
+ end
82
+
83
+ def write_sidecars
84
+ body = MarkdownBody.new(metadata).to_s
85
+
86
+ DL::Core::Sidecar::Markdown.new(metadata, body:).write to: staging_dir
87
+ DL::Core::Sidecar::YAML.new(metadata).write to: staging_dir
88
+ DL::Core::Sidecar::JSON.new(metadata).write to: staging_dir
89
+ File.write File.join(staging_dir, 'metadata.bib'), parser.bibtex
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,5 @@
1
+ module HAL
2
+ module Downloader
3
+ Author = DL::Core::Author
4
+ end
5
+ end
@@ -0,0 +1,24 @@
1
+ module HAL
2
+ module Downloader
3
+ class CLI < DL::Core::CLI
4
+ def program = 'hal-dl'
5
+
6
+ def target_name = 'HAL_ID_OR_URL'
7
+
8
+ # HAL_DOWNLOAD_PATH, HAL_RATE_LIMIT
9
+ def env_prefix = 'HAL'
10
+
11
+ def default_path = File.join(Dir.home, 'Downloads', 'HAL_Papers')
12
+
13
+ def version = VERSION
14
+
15
+ def user_agent = Client::USER_AGENT
16
+
17
+ def client_for(rate_limit:, log:) = Client.new(rate_limit:, log:)
18
+
19
+ def identifier_for(target) = Identifier.new(target)
20
+
21
+ def archive_for(identifier, root:, client:) = Archive.new(identifier, root:, client:)
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,13 @@
1
+ module HAL
2
+ module Downloader
3
+ # DL::Core::Client with hal-dl's User-Agent filled in
4
+ class Client < DL::Core::Client
5
+ SOURCE_URL = 'https://github.com/xoengineering/hal-dl'.freeze
6
+ USER_AGENT = "hal-dl/#{VERSION} (+#{SOURCE_URL})".freeze
7
+
8
+ def initialize log: nil, rate_limit: DEFAULT_RATE_LIMIT
9
+ super(user_agent: USER_AGENT, log:, rate_limit:)
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,5 @@
1
+ module HAL
2
+ module Downloader
3
+ class Error < DL::Core::Error; end
4
+ end
5
+ end
@@ -0,0 +1,5 @@
1
+ module HAL
2
+ module Downloader
3
+ HTTPError = DL::Core::HTTPError
4
+ end
5
+ end
@@ -0,0 +1,48 @@
1
+ require 'uri'
2
+
3
+ module HAL
4
+ module Downloader
5
+ # A HAL document ID, with its version when one was given. IDs are a portal
6
+ # prefix (hal, tel, halshs, inria, hal-pasteur, …), a dash, and eight digits.
7
+ class Identifier
8
+ class Invalid < Error; end
9
+
10
+ ID = /\A(?<id>[a-z][a-z0-9]*(?:-[a-z0-9]+)*-\d{8})(?:v(?<version>\d+))?\z/
11
+
12
+ attr_reader :id, :version, :input
13
+
14
+ def initialize input
15
+ @input = input
16
+ match = parse input.to_s.strip
17
+ raise Invalid, "not a HAL identifier: #{input}" if match.nil?
18
+
19
+ @id = match[:id]
20
+ @version = match[:version] && Integer(match[:version])
21
+ end
22
+
23
+ # the URL form: hal-01207234, or hal-01207234v3 when a version is known
24
+ def to_s = version.nil? ? id : "#{id}v#{version}"
25
+
26
+ # HAL IDs have no slashes, so to_s is already a single path segment
27
+ def file_stem = to_s
28
+
29
+ private
30
+
31
+ def parse text
32
+ ID.match(text) || parse_url(text)
33
+ end
34
+
35
+ # hal.science, its portals (theses.hal.science, …), and the older archives-ouvertes.fr hosts
36
+ def parse_url text
37
+ uri = URI.parse(text.include?('://') ? text : "https://#{text}")
38
+ host = uri.host.to_s
39
+ return unless host == 'hal.science' || host.end_with?('.hal.science', 'archives-ouvertes.fr')
40
+
41
+ first_segment = uri.path.to_s.split('/').reject(&:empty?).first
42
+ ID.match first_segment.to_s
43
+ rescue URI::InvalidURIError
44
+ nil
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,50 @@
1
+ module HAL
2
+ module Downloader
3
+ # The body of metadata.md. HAL's terms ask users to cite the HAL URL.
4
+ class MarkdownBody
5
+ def initialize metadata
6
+ @metadata = metadata
7
+ end
8
+
9
+ def to_s
10
+ <<~MARKDOWN
11
+
12
+ # #{@metadata.title}
13
+
14
+ #{authors_list}
15
+
16
+ #{details_list}
17
+
18
+ ## Abstract
19
+
20
+ #{@metadata.abstract}
21
+ MARKDOWN
22
+ end
23
+
24
+ private
25
+
26
+ def authors_list
27
+ @metadata.authors.map { |author| "- #{author_line author}" }.join "\n"
28
+ end
29
+
30
+ def author_line author
31
+ return author.name if author.affiliations.empty?
32
+
33
+ "#{author.name} (#{author.affiliations.join '; '})"
34
+ end
35
+
36
+ def details_list
37
+ details = [
38
+ "Published: #{@metadata.published}",
39
+ "Domain: #{@metadata.domain[:id]} — #{@metadata.domain[:name]}",
40
+ "HAL: [#{@metadata.hal_id}v#{@metadata.version}](#{@metadata.hal_url})"
41
+ ]
42
+ details << "DOI: [#{@metadata.doi}](https://doi.org/#{@metadata.doi})" if @metadata.doi
43
+ details << "arXiv: [#{@metadata.arxiv_id}](https://arxiv.org/abs/#{@metadata.arxiv_id})" if @metadata.arxiv_id
44
+ details << "Licence: #{@metadata.licence}" if @metadata.licence
45
+
46
+ details.map { "- #{it}" }.join "\n"
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,28 @@
1
+ module HAL
2
+ module Downloader
3
+ # Field order is the reading order of the metadata sidecars.
4
+ Metadata = Data.define(
5
+ :hal_id,
6
+ :version,
7
+ :hal_url,
8
+ :title,
9
+ :authors,
10
+ :abstract,
11
+ :published,
12
+ :submitted,
13
+ :domain,
14
+ :doc_type,
15
+ :journal,
16
+ :volume,
17
+ :issue,
18
+ :pages,
19
+ :doi,
20
+ :arxiv_id,
21
+ :pubmed_id,
22
+ :language,
23
+ :keywords,
24
+ :licence,
25
+ :submit_type
26
+ )
27
+ end
28
+ end
@@ -0,0 +1,83 @@
1
+ require 'json'
2
+
3
+ module HAL
4
+ module Downloader
5
+ # Parses HAL's JSON export of one document version (https://hal.science/<id>v<N>/json)
6
+ class MetadataParser
7
+ FACET_SEPARATOR = '_FacetSep_'.freeze
8
+ JOIN_SEPARATOR = '_JoinSep_'.freeze
9
+
10
+ def initialize json
11
+ @json = JSON.parse json
12
+ end
13
+
14
+ # HAL's own BibTeX entry, kept verbatim for metadata.bib
15
+ def bibtex
16
+ fields.fetch 'label_bibtex'
17
+ end
18
+
19
+ def metadata
20
+ Metadata.new(
21
+ hal_id: fields['halId_s'],
22
+ version: fields['version_i'],
23
+ hal_url: fields['uri_s'],
24
+ title: Array(fields['title_s']).first,
25
+ authors: authors_from(fields),
26
+ abstract: Array(fields['abstract_s']).first,
27
+ published: fields['publicationDate_s'],
28
+ submitted: fields['submittedDate_s'].to_s[0, 10],
29
+ domain: domain_from(fields),
30
+ doc_type: fields['docType_s'],
31
+ journal: fields['journalTitle_s'],
32
+ volume: fields['volume_s'],
33
+ issue: Array(fields['issue_s']).first,
34
+ pages: fields['page_s'],
35
+ doi: fields['doiId_s'],
36
+ arxiv_id: fields['arxivId_s'],
37
+ pubmed_id: fields['pubmedId_s'],
38
+ language: Array(fields['language_s']).first,
39
+ keywords: Array(fields['keyword_s']),
40
+ licence: fields['licence_s'],
41
+ submit_type: fields['submitType_s']
42
+ )
43
+ end
44
+
45
+ private
46
+
47
+ def fields
48
+ @json.dig('response', 'docs', 0) || raise(PaperNotFound)
49
+ end
50
+
51
+ # authFullName_s and authIdFormPerson_s are parallel lists; affiliations
52
+ # are "<form id>_FacetSep_<name>_JoinSep_<struct id>_FacetSep_<struct name>"
53
+ def authors_from fields
54
+ names = Array(fields['authFullName_s'])
55
+ form_ids = Array(fields['authIdFormPerson_s'])
56
+ by_form = affiliations_by_form_id fields['authIdHasPrimaryStructure_fs']
57
+
58
+ names.each_with_index.map do |name, index|
59
+ Author.new name:, affiliations: by_form.fetch(form_ids[index], [])
60
+ end
61
+ end
62
+
63
+ def affiliations_by_form_id entries
64
+ Array(entries).each_with_object({}) do |entry, by_form|
65
+ author, structure = entry.split JOIN_SEPARATOR
66
+ form_id = author.split(FACET_SEPARATOR).first
67
+ structure_name = structure.to_s.split(FACET_SEPARATOR).last
68
+ next if structure_name.nil?
69
+
70
+ (by_form[form_id] ||= []) << structure_name
71
+ end
72
+ end
73
+
74
+ # the English label for the primary domain: "spi.auto_FacetSep_Engineering Sciences [physics]/Automatic"
75
+ def domain_from fields
76
+ id = fields['primaryDomain_s']
77
+ label = Array(fields['en_domainAllCodeLabel_fs']).find { it.start_with? "#{id}#{FACET_SEPARATOR}" }
78
+
79
+ { id:, name: label&.split(FACET_SEPARATOR)&.last }
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,9 @@
1
+ module HAL
2
+ module Downloader
3
+ class NoFile < Error
4
+ def initialize message = 'metadata-only record: HAL has no file for it'
5
+ super
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,5 @@
1
+ module HAL
2
+ module Downloader
3
+ PaperFolder = DL::Core::PaperFolder
4
+ end
5
+ end
@@ -0,0 +1,9 @@
1
+ module HAL
2
+ module Downloader
3
+ class PaperNotFound < Error
4
+ def initialize message = 'no such document on HAL'
5
+ super
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,30 @@
1
+ module HAL
2
+ module Downloader
3
+ # The paper's folder, shared by all its versions
4
+ class Path
5
+ def initialize metadata
6
+ @metadata = metadata
7
+ end
8
+
9
+ def to_s
10
+ [date_dir, domain, "#{@metadata.hal_id}-#{slug}"].join '/'
11
+ end
12
+
13
+ private
14
+
15
+ # 2015-09-30 becomes 2015/09/30; a year-only or year-month date gives a shorter path
16
+ def date_dir
17
+ date = @metadata.published || @metadata.submitted
18
+ date.to_s.split('-').join '/'
19
+ end
20
+
21
+ def domain
22
+ @metadata.domain[:id]
23
+ end
24
+
25
+ def slug
26
+ DL::Core::Slug.new(@metadata.title).to_s
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,5 @@
1
+ module HAL
2
+ module Downloader
3
+ VERSION = '0.1.0'.freeze
4
+ end
5
+ end
@@ -0,0 +1,23 @@
1
+ require 'dl/core'
2
+
3
+ require_relative 'downloader/version' # before client: Client::USER_AGENT uses VERSION
4
+
5
+ require_relative 'downloader/archive'
6
+ require_relative 'downloader/author'
7
+ require_relative 'downloader/cli'
8
+ require_relative 'downloader/client' # after version
9
+ require_relative 'downloader/error' # before errors below that subclass Error
10
+ require_relative 'downloader/http_error'
11
+ require_relative 'downloader/identifier' # after error
12
+ require_relative 'downloader/markdown_body'
13
+ require_relative 'downloader/metadata'
14
+ require_relative 'downloader/metadata_parser'
15
+ require_relative 'downloader/no_file' # after error
16
+ require_relative 'downloader/paper_folder'
17
+ require_relative 'downloader/paper_not_found' # after error
18
+ require_relative 'downloader/path'
19
+
20
+ module HAL
21
+ module Downloader
22
+ end
23
+ end
@@ -0,0 +1,5 @@
1
+ module HAL
2
+ module Downloader
3
+ VERSION: String
4
+ end
5
+ end
metadata ADDED
@@ -0,0 +1,86 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hal-dl
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Shane Becker
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: dl-core
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '0.2'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '0.2'
26
+ description: |
27
+ Command line tool and Ruby library for archiving HAL (hal.science) papers as PDFs
28
+ with HAL's TEI metadata and sidecar metadata, any version.
29
+ email:
30
+ - veganstraightedge@gmail.com
31
+ executables:
32
+ - hal-dl
33
+ extensions: []
34
+ extra_rdoc_files: []
35
+ files:
36
+ - CHANGELOG.md
37
+ - CODE_OF_CONDUCT.md
38
+ - LICENSE.md
39
+ - README.md
40
+ - exe/hal-dl
41
+ - lib/hal/downloader.rb
42
+ - lib/hal/downloader/archive.rb
43
+ - lib/hal/downloader/author.rb
44
+ - lib/hal/downloader/cli.rb
45
+ - lib/hal/downloader/client.rb
46
+ - lib/hal/downloader/error.rb
47
+ - lib/hal/downloader/http_error.rb
48
+ - lib/hal/downloader/identifier.rb
49
+ - lib/hal/downloader/markdown_body.rb
50
+ - lib/hal/downloader/metadata.rb
51
+ - lib/hal/downloader/metadata_parser.rb
52
+ - lib/hal/downloader/no_file.rb
53
+ - lib/hal/downloader/paper_folder.rb
54
+ - lib/hal/downloader/paper_not_found.rb
55
+ - lib/hal/downloader/path.rb
56
+ - lib/hal/downloader/version.rb
57
+ - sig/hal/downloader.rbs
58
+ homepage: https://github.com/xoengineering/hal-dl
59
+ licenses:
60
+ - MIT
61
+ metadata:
62
+ allowed_push_host: https://rubygems.org
63
+ homepage_uri: https://github.com/xoengineering/hal-dl
64
+ source_code_uri: https://github.com/xoengineering/hal-dl
65
+ bug_tracker_uri: https://github.com/xoengineering/hal-dl/issues
66
+ changelog_uri: https://github.com/xoengineering/hal-dl/blob/main/CHANGELOG.md
67
+ rubygems_mfa_required: 'true'
68
+ rdoc_options: []
69
+ require_paths:
70
+ - lib
71
+ required_ruby_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: 4.0.10
76
+ required_rubygems_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ requirements: []
82
+ rubygems_version: 4.0.20
83
+ specification_version: 4
84
+ summary: Download papers and metadata from HAL, France's national open archive, for
85
+ offline archives.
86
+ test_files: []