argumentext_ftp_file_transfer
Overview
The argumentext_ftp_file_transfer module uploads article full-text PDFs, their CrossRef metadata, and journal-level DDC (Dewey Decimal Classification) subject files to an external SFTP server operated for the ArgumenText project. It is a delivery/export module rather than a harvesting module (ie, it does not add content to the local article folder structure, it pushes already-harvested content out to a third party).
Module-specific information:
- It does not use
common.configuration.get_module_context()to determine which journals to process. Instead, the caller must pass an explicitissn_listdirectly as a function argument; if none is given, the flow logs a warning and exits immediately without processing anything (there is commented-out code for traversing the entire article root automatically, but it is currently disabled). - It does not follow the
previous_module→temp-module→modulefolder convention, since it isn't creating a new module folder for the article at all, it reads directly from whichever module folder is currently the article's "active" folder. - It does not write to
history.csv. Instead, it maintains its own per-article upload history file (constants.SFTP_HISTORY_FILE) recording which CrossRef deposit dates have already been uploaded, to avoid redundant re-uploads. - It uses Prefect's
ConcurrentTaskRunner, and runs a background heartbeat thread to keep the SFTP connection alive during idle periods (since long-lived SFTP sessions can otherwise time out server-side).
The module contains two primary Python files:
flow.pytasks.py
flow.py
This file defines the main flow for uploading content to the ArgumenText SFTP server, using the Prefect library and ConcurrentTaskRunner (since the heartbeat thread and upload tasks can run concurrently). It opens a single SFTP connection for the whole run, processes each journal's remote directory tree and DDC file, then traverses each article's local folder scanning for content to upload.
argumentext_ftp_file_transfer()
-
Required Parameters:
-
issn_list(list): List of ISSNs to process. Default is[]— if empty, the flow logs a warning and returns without doing anything. -
name_of_config_file(str): Name of the configuration file used to resolve each ISSN's publisher and journal name. Default is"config_argumentext.json" -
Context for Use:
-
This function is the main entry point. It opens one SFTP connection for the entire run (via
tasks.SftpConnection) and starts a background heartbeat thread. For each ISSN (processed in reverse order of the input list), it ensures the remote publisher/journal/CrossRef/PDF folder tree exists, uploads the journal's DDC subjects, then scans the journal's local article folders. For each article, it looks at the article's module subdirectories and, for the first one that isn't a temp/stop-processing folder, either skips it (if already recorded in the article's SFTP history file) or attempts to upload its PDF and metadata. Per-journal and cumulative upload statistics are logged after each journal. -
Example Usage:
-
python argumentext_ftp_file_transfer(['1867-8548'], 'ct3.json') -
Example Output:
-
INFO: Path to log file: /mnt/nas/.../argumentext_ftp_file_transfer/....log INFO: issn list: ['1867-8548'] INFO: name of config file: ct3.json INFO: DDC information written successfully to DDC.txt file INFO: Full text file amt-2-401-2009.pdf uploaded successfully to SFTP server INFO: Crossref metadata file for article amt-2-401-2009 uploaded successfully to SFTP server INFO: Statistics for 1867-8548: Skipped: 0; Newly uploaded: 1, Previously uploaded: 3; Total Uploaded: 4 INFO: Cumulative statistics including 1867-8548: Skipped: 0; Newly uploaded: 1, Previously uploaded: 3; Total Uploaded: 4WARNING: No ISSN list given.When no ISSN list is provided:
tasks.py
This file contains the task definitions and helper classes used in the ArgumenText SFTP transfer flow. It handles the SFTP connection lifecycle (including keep-alive heartbeats), remote directory tree creation, DDC subject retrieval and upload, and the actual PDF/metadata upload.
SftpConnection (class)
-
Context for Use:
-
A thin lazy-connection wrapper.
get_connection(config_file=None)creates the underlyingpysftp.Connectionon first call (viaconnect_sftp) and returns the cached connection on subsequent calls, so the same connection is reused across the whole flow run rather than reconnecting per task. -
Example Usage:
-
python sftp_connection_obj = tasks.SftpConnection() with sftp_connection_obj.get_connection() as sftp_connection: ...
connect_sftp()
-
Optional Parameters:
-
config_file(optional): Currently unused — reading SFTP credentials from a config file is not yet implemented -
Context for Use:
-
Establishes a
pysftp.Connectionto the ArgumenText SFTP server, with host key checking disabled. Credentials (argumentext-ftp-server,-username,-password) are always read from the shared harvesting config JSON viaget_config_json(), regardless of theconfig_fileargument.
start_heartbeat_thread()
-
Required Parameters:
-
sftp_connection(pysftp.Connection): The active SFTP connection heartbeat_interval(int): Seconds between heartbeat checks (the flow uses270)-
prefect_logger: The Prefect run logger to use inside the background thread -
Context for Use:
-
This is a Prefect
@taskthat starts a daemonthreading.Threadrunningsend_heartbeatin the background. Its purpose is to prevent the SFTP server from dropping the connection due to inactivity while other, longer-running tasks (like PDF uploads) are not actively using it. The heartbeat only pings the server (sftp_connection.listdir('.')) when no other tracked task is currently marked as running (seetask_activity/any_task_running()), to avoid interfering with in-progress SFTP operations.
create_tree_sftp()
-
Required Parameters:
-
issn(str): The journal's ISSN sftp_connection(pysftp.Connection): The active SFTP connection-
config_file(str): Name of the configuration file used to resolve publisher/journal names -
Context for Use:
-
A Prefect
@taskthat ensures the remote folder structure exists for the given journal:/<publisher>,/<publisher>/<journal>,/<publisher>/<journal>/CrossRef, and/<publisher>/<journal>/PDF. Each level is created only if it doesn't already exist.
write_ddc()
-
Required Parameters:
-
issn(str): The journal's ISSN sftp_path_creator(SFTPPathCreator): Provides the remote paths for this journal-
sftp_connection(pysftp.Connection): The active SFTP connection -
Context for Use:
-
A Prefect
@taskthat fetches DDC subject classifications for the journal from the DNB SRU API (viaget_ddc) and writes them, one per line, to a localDDC.txtfile, then uploads that file to the journal's remote folder. If no DDC subjects can be retrieved, the ISSN is recorded in a localmissing_ddc.txtfile for later review instead. If DDC subjects are found and an ISSN was previously in the missing-DDC list, it is removed from that list.
upload_article_pdf()
-
Required Parameters:
-
module_dir(pathlib.Path): The article's current module directory to upload from article_dir(pathlib.Path): The article's root directory (used for the SFTP history file)sftp_path_creator(SFTPPathCreator): Provides the remote paths for this journalsftp_connection(pysftp.Connection): The active SFTP connection-
logger: The Prefect run logger -
Context for Use:
-
A Prefect
@taskthat uploads the article's PDF and CrossRef metadata to the SFTP server, providedmodule_dircontains both apdf/subfolder andmetadata-article.json. The metadata file is uploaded under a renamed filename matching the PDF's base name (viaget_sftp_metadata_file_name), replacing any existing remote file of that name. After a successful upload, the article's SFTP history file is updated with the current module's CrossRef deposit-date suffix, so future runs recognize this version as already uploaded. ReturnsTrueif an upload occurred (or the PDF folder was found but empty — see Comments),Falseifmodule_dirdid not contain the expectedpdf/folder and metadata file.
The lower-level helper functions in tasks.py are listed below.
SFTPPathCreator (class)
-
Constructor Parameters:
-
issn(str): The journal's ISSN -
config_file(str): Name of the configuration file used to resolve the publisher and journal name -
Context for Use:
-
Resolves the journal's publisher and title from the flow config file (via
get_journal_issn_title) and builds the remote SFTP paths for that journal: publisher directory, journal directory, CrossRef metadata directory, PDF directory, and DDC file path. -
Accessors:
get_publisher_dir(),get_journal_dir(),get_metadata_dir(),get_pdf_dir(),get_ddc_path()
get_journal_issn_title()
-
Required Parameters:
-
issn(str): The journal's ISSN -
config_file(str): Name of the configuration file to read -
Context for Use:
-
Looks up the journal's
source-name(publisher) andjournal-namein the given flow config file by matchingissn-e. Returns a dict mapping the ISSN to a(publisher, journal_name)tuple.
get_sftp_metadata_file_name()
-
Required Parameters:
-
pdf_file_name(str): The PDF file's name (with extension) -
Context for Use:
-
Strips the
.pdfextension from the given filename and appends.json, producing the filename the CrossRef metadata should be renamed to when uploaded to the SFTP server (so the metadata file name matches its corresponding PDF's base name).
exist_in_history() / update_sftp_history()
-
Required Parameters:
-
module_dir(pathlib.Path): The article's current module directory (its name suffix encodes the CrossRef deposit date) -
sftp_history_path(pathlib.Path): Path to the article's local SFTP history file -
Context for Use:
-
exist_in_historychecks whether the current module's deposit-date suffix already appears as a line in the article's SFTP history file (if so, this version has already been uploaded and can be skipped).update_sftp_historyappends (or creates) that history file with the current deposit-date suffix after a successful upload.
get_ddc()
-
Required Parameters:
-
issn(str): The journal's ISSN -
Context for Use:
-
Queries the DNB (Deutsche Nationalbibliothek) SRU API for DDC subject classifications associated with the given ISSN, and returns the list of subject strings found in the response.
get_missing_ddc_file() / add_entry_to_missing_ddc() / remove_entry_from_missing_ddc()
-
Required Parameters:
-
issn(str): The journal's ISSN (for add/remove) -
is_temp(bool, forget_missing_ddc_fileonly): Whether to return the path to the temp version of the file used during a rewrite -
Context for Use:
-
Maintain a shared
missing_ddc.txtfile at the data root, listing ISSNs for which no DDC classification could be retrieved from DNB.add_entry_to_missing_ddcappends an ISSN if not already present;remove_entry_from_missing_ddcrewrites the file excluding that ISSN (via a temp file that then replaces the original), used once DDC information becomes available for a previously-missing journal.
any_task_running() / send_heartbeat()
-
Context for Use:
-
any_task_running()checks the sharedtask_activitydict ofthreading.Eventobjects to determine whethercreate_tree_sftp,write_ddc, orupload_article_pdfis currently executing.send_heartbeat()is the target function run by the background thread started instart_heartbeat_thread— it loops indefinitely, pinging the SFTP server with alistdir('.')call at the configured interval whenever no other tracked task is active, and attempts to reconnect if the ping fails.