Something went wrong. Try again.
Scripts to use scopus API to download economics journals and articles metadata + use of Elsevier API for full-text
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286#: Extracting and cleaning Elsevier full-text XMLs -----------------------# Script goals:# * Extract paragraph-level text from the Elsevier full-text XML files not yet# processed by the current extraction version, and write it to the `text`# table of `scopus.duckdb`, with the section hierarchy (`section_level`,# `section_number`, `section_path`) and the bibliography entries (type_text# "references").# * Write the JEL codes printed in the articles to `article_jel` (scopus_id,# jel_code, raw).# * Keep `article.elsevier_full_text` in line with `text` (TRUE when the article# has paragraphs in `text`).## Setup Instructions:# * `scripts/paths_and_packages.R` must set `db_path` and `xml_data_path`.# * Run `downloading_xml.R` first: it fills `xml_download`, which tells which# files hold the full text.## How it works (high level):# 1. Select the files logged `full_text` in `xml_download` that were never# extracted (`n_paragraphs` is NULL) or extracted by an earlier version of# the extraction (`extraction_version` below `text_extraction_version`, set# in functions.R). Bumping the version re-extracts every file, from the# gzipped XML (no API request): about 2-3 hours for 260,000 files.# 2. By chunks of `chunk_size` files: extract the paragraphs and JEL codes# (`extract_elsevier_fulltext()`), clean and classify the paragraphs# (`clean_fulltext_paragraphs()`), normalise the JEL codes# (`clean_jel_codes()`), then, in one transaction, replace the rows of these# articles in `text` and `article_jel`, and record `n_paragraphs` (0 when a# file gives no paragraph, e.g. a scanned article, so that it is not# processed again) and `extraction_version`.# 3. Read the journal section label (`ce:dochead`: "Research paper",# "Commentary", "Discussion"...) of every extracted file not read yet# (`xml_download.dochead_read` is NULL) into `xml_download.dochead`, used# by `classifying_doc_type.R`. It is a separate pass, not part of the# extraction, so that adding it (November 2026) did not re-extract the# text: the label is read from the raw file and never changes, so it is# read once per file. Files are read in parallel (mirai daemons,# `n_workers`; reading is I/O and decompression bound, ~25 ms per file:# about 10 minutes for 228,000 files with 8 workers), and written by# chunks of `dochead_chunk_size` files, each in one transaction.# 4. Recompute `article.elsevier_full_text` from `text`.# While the script writes, a read-only snapshot of the database is kept up to# date (see `refresh_snapshot()` in functions.R) and removed at the end.
#: Setup & safety checks ---------source("scripts/paths_and_packages.R") # defines `db_path`, `xml_data_path`, etc.source("scripts/functions.R") # extract_elsevier_fulltext(), clean_fulltext_paragraphs(), clean_jel_codes()
#: Parameters ---------chunk_size <- 1000L # files extracted between two writes to the databasefile_limit <- Inf # e.g. 4000 to test the script on two chunkssnapshot_every_hours <- 1 # refresh of the read-only snapshot during the rundochead_chunk_size <- 10000L # files whose section label is read between two writes
if (!dir.exists(path.expand(xml_data_path))) { stop( "Directory with fulltext XMLs not found: ", xml_data_path, "\nPlease download XMLs or check `xml_data_path` in paths_and_packages.R." )}
con <- dbConnect(duckdb::duckdb(), dbdir = db_path)# DuckDB takes up to 80% of the RAM by default: cap it, the machine is shared# with other jobs (a run was killed when memory and swap were full)invisible(dbExecute(con, "SET memory_limit = '4GB'"))
if (!dbExistsTable(con, "xml_download")) { dbDisconnect(con, shutdown = TRUE) cli_abort("Table `xml_download` not found: run `downloading_xml.R` first.")}
#: Tables and columns (created or added if missing) ---------invisible(dbExecute( con, 'CREATE TABLE IF NOT EXISTS "text" ( scopus_id VARCHAR, paragraph_id INTEGER, text VARCHAR, section VARCHAR, type_text VARCHAR )'))# Column `type` renamed `type_text` (labels shared with the JSTOR and ISTEX# databases); the old values are replaced when the file is extracted againif ("type" %in% dbListFields(con, "text")) { invisible(dbExecute(con, 'ALTER TABLE "text" RENAME COLUMN type TO type_text'))}# Columns of extraction version 2: added to the existing table (NULL for the# rows of version 1 until their file is extracted again)text_columns <- dbListFields(con, "text")for (column in c("section_level INTEGER", "section_number VARCHAR", "section_path VARCHAR")) { if (!word(column, 1) %in% text_columns) { invisible(dbExecute(con, glue('ALTER TABLE "text" ADD COLUMN {column}'))) }}if (!"extraction_version" %in% dbListFields(con, "xml_download")) { # Files extracted before versions existed are version 1 invisible(dbExecute(con, "ALTER TABLE xml_download ADD COLUMN extraction_version INTEGER")) invisible(dbExecute( con, "UPDATE xml_download SET extraction_version = 1 WHERE n_paragraphs IS NOT NULL" ))}invisible(dbExecute( con, "CREATE TABLE IF NOT EXISTS article_jel ( scopus_id VARCHAR, jel_code VARCHAR, raw VARCHAR )"))
refresh_snapshot(con)
#: 1. Files to process ---------to_process <- dbGetQuery( con, glue( "SELECT x.scopus_id, x.file_name FROM xml_download x WHERE x.outcome = 'full_text' AND (x.n_paragraphs IS NULL OR coalesce(x.extraction_version, 1) < {text_extraction_version}) AND x.scopus_id IN (SELECT scopus_id FROM article) ORDER BY x.scopus_id" )) |> as.data.table()if (is.finite(file_limit)) { to_process <- head(to_process, file_limit)}cli_alert_info( "{nrow(to_process)} full-text XML file{?s} to extract (extraction version {text_extraction_version}).")
#: 2. Extract, clean and save by chunks ---------chunks <- split(to_process, ceiling(seq_len(nrow(to_process)) / chunk_size))n_paragraphs_total <- 0L
for (k in seq_along(chunks)) { chunk <- chunks[[k]] cli_alert_info("Chunk {k}/{length(chunks)}: extracting {nrow(chunk)} files")
extracted <- map( chunk$file_name, \(f) extract_elsevier_fulltext(xml_file = f, xml_dir = xml_data_path) ) extracted_paragraphs <- rbindlist(map(extracted, "paragraphs")) paragraphs <- if (nrow(extracted_paragraphs) > 0L) { clean_fulltext_paragraphs(extracted_paragraphs) } else { data.table( scopus_id = character(), paragraph_id = integer(), text = character(), section = character(), section_level = integer(), section_number = character(), section_path = character(), type_text = character() ) } jel <- clean_jel_codes(rbindlist(map(extracted, "jel")))
# Number of paragraphs per file, 0 for files without any counts <- paragraphs[, .(n_paragraphs = .N), by = scopus_id][ chunk[, .(scopus_id)], on = "scopus_id" ] counts[is.na(n_paragraphs), n_paragraphs := 0L] counts[, extraction_version := text_extraction_version]
# * One transaction per chunk: `text`, `article_jel` and the log stay consistent duckdb::duckdb_register(con, "tmp_paragraphs", paragraphs) duckdb::duckdb_register(con, "tmp_jel", jel) duckdb::duckdb_register(con, "tmp_counts", counts) dbBegin(con) dbExecute( con, 'DELETE FROM "text" WHERE scopus_id IN (SELECT scopus_id FROM tmp_counts)' ) dbExecute(con, 'INSERT INTO "text" BY NAME SELECT * FROM tmp_paragraphs') dbExecute( con, "DELETE FROM article_jel WHERE scopus_id IN (SELECT scopus_id FROM tmp_counts)" ) dbExecute(con, "INSERT INTO article_jel BY NAME SELECT * FROM tmp_jel") dbExecute( con, "UPDATE xml_download SET n_paragraphs = c.n_paragraphs, extraction_version = c.extraction_version FROM tmp_counts c WHERE xml_download.scopus_id = c.scopus_id" ) dbCommit(con) duckdb::duckdb_unregister(con, "tmp_paragraphs") duckdb::duckdb_unregister(con, "tmp_jel") duckdb::duckdb_unregister(con, "tmp_counts")
n_paragraphs_total <- n_paragraphs_total + nrow(paragraphs) cli_alert_success( "Chunk {k}/{length(chunks)}: {nrow(paragraphs)} paragraphs from {sum(counts$n_paragraphs > 0)} files, {uniqueN(jel[!is.na(jel_code)]$scopus_id)} articles with JEL codes." ) rm(extracted, extracted_paragraphs, paragraphs, jel, counts) gc() refresh_snapshot(con, min_interval_hours = snapshot_every_hours)}
if (length(chunks) > 0L) { cli_alert_success( "{n_paragraphs_total} paragraphs written to `text` from {nrow(to_process)} files." )}
#: 3. Journal section labels (ce:dochead) ---------for (column in c("dochead VARCHAR", "dochead_read BOOLEAN")) { if (!word(column, 1) %in% dbListFields(con, "xml_download")) { invisible(dbExecute(con, glue("ALTER TABLE xml_download ADD COLUMN {column}"))) }}to_label <- dbGetQuery( con, "SELECT scopus_id, file_name FROM xml_download WHERE n_paragraphs > 0 AND dochead_read IS NULL ORDER BY scopus_id") |> as.data.table()if (is.finite(file_limit)) { to_label <- head(to_label, file_limit)}cli_alert_info("{nrow(to_label)} file{?s} whose section label (ce:dochead) is to read.")if (nrow(to_label) > 0L) { # read_xml_dochead() is defined at top level of functions.R and calls no # project helper, so the daemons need nothing else daemons(n_workers) label_chunks <- split(to_label, ceiling(seq_len(nrow(to_label)) / dochead_chunk_size)) for (k in seq_along(label_chunks)) { chunk <- label_chunks[[k]] chunk[, dochead := mirai_map(file.path(xml_data_path, file_name), read_xml_dochead)[.flat]] duckdb::duckdb_register(con, "tmp_dochead", chunk[, .(scopus_id, dochead)]) dbBegin(con) dbExecute( con, "UPDATE xml_download SET dochead = d.dochead, dochead_read = TRUE FROM tmp_dochead d WHERE xml_download.scopus_id = d.scopus_id" ) dbCommit(con) duckdb::duckdb_unregister(con, "tmp_dochead") cli_alert_success( "Section labels {k}/{length(label_chunks)}: {sum(!is.na(chunk$dochead))} of {nrow(chunk)} files have one." ) refresh_snapshot(con, min_interval_hours = snapshot_every_hours) } daemons(0)}
#: 4. Update `article.elsevier_full_text` ---------if (!"elsevier_full_text" %in% dbListFields(con, "article")) { invisible(dbExecute( con, "ALTER TABLE article ADD COLUMN elsevier_full_text BOOLEAN DEFAULT FALSE" ))}invisible(dbExecute( con, 'UPDATE article SET elsevier_full_text = scopus_id IN (SELECT DISTINCT scopus_id FROM "text")'))
cli_alert_info("Full-text extraction status:")print(dbGetQuery( con, "SELECT (SELECT count(*) FROM article WHERE elsevier_full_text) AS articles_with_text, (SELECT count(*) FROM xml_download WHERE outcome = 'full_text') AS full_text_files, (SELECT count(*) FROM xml_download WHERE n_paragraphs = 0) AS files_without_paragraphs, (SELECT count(DISTINCT scopus_id) FROM article_jel WHERE jel_code IS NOT NULL) AS articles_with_jel"))print(dbGetQuery( con, "SELECT extraction_version, count(*) AS files FROM xml_download WHERE outcome = 'full_text' GROUP BY ALL ORDER BY 1"))
dbDisconnect(con, shutdown = TRUE)remove_snapshot()