benchmarking-cultures-25 / code /arxiv-metadata.R
matybohacek's picture
init
d17d083 verified
raw
history blame
2.45 kB
#!/usr/bin/env Rscript
library(tidyverse)
library(xml2)
library(lubridate)
library(optparse)
library(glue)
# Define command line options
option_list <- list(
make_option(c("-i", "--input"), type = "character", default = NULL,
help = "Directory containing ArXiv XML files", metavar = "character"),
make_option(c("-o", "--output"), type = "character", default = NULL,
help = "Output CSV file path", metavar = "character")
)
# Parse command line arguments
opt_parser <- OptionParser(option_list = option_list)
opt <- parse_args(opt_parser)
# Check if required arguments are provided
if (is.null(opt$input)) {
stop("Error: Input directory (-i, --input) is required")
}
if (is.null(opt$output)) {
stop("Error: Output file (-o, --output) is required")
}
# List all XML files
xml_files <- list.files(path = opt$input, pattern = "\\.xml$", full.names = TRUE)
# Function to parse one XML file and extract all metadata
extract_metadata <- function(file_path) {
# Read the XML
doc <- read_xml(file_path)
# Get file ID from filename (without .xml extension)
file_id <- tools::file_path_sans_ext(basename(file_path))
# Define namespaces properly
ns <- c(atom = "http://www.w3.org/2005/Atom")
# Find all entries
entries <- xml_find_all(doc, "//atom:entry", ns)
# For each entry, extract all metadata
map_dfr(entries, function(entry) {
# Extract authors
authors <- xml_find_all(entry, ".//atom:author/atom:name", ns) %>%
map_chr(~ xml_text(.)) %>%
list()
# Extract entry ID and version
entry_id <- xml_text(xml_find_first(entry, ".//atom:id", ns))
version_number <- as.numeric(str_extract(entry_id, "v(\\d+)$", group = 1))
# Extract dates
updated_date <- xml_text(xml_find_first(entry, ".//atom:updated", ns))
published_date <- xml_text(xml_find_first(entry, ".//atom:published", ns))
# Convert to Date format (yyyy-mm-dd)
updated_date <- as.Date(ymd_hms(updated_date))
published_date <- as.Date(ymd_hms(published_date))
# Create tibble with all data
tibble(
id = file_id,
href = glue("https://arxiv.org/abs/{file_id}"),
updated_at = updated_date,
published_at = published_date,
count_versions = version_number
)
})
}
# Apply to all XML files and combine results
results <- map_dfr(xml_files, extract_metadata)
# Print the result
print(results)
# Save to CSV file
write_csv(results, opt$output)