Zum Inhalt

common.functions

Overview

common.functions provides shared helpers for harvesting modules. Its responsibilities include:

  • resolving date suffixes in article folders,
  • checking processing-folder state,
  • appending log entries,
  • cleaning duplicate CSV rows,
  • deleting and copying directory content,
  • formatting durations and logging iteration progress,
  • exporting publisher-specific CSV reports,
  • standardizing terms using external vocabulary files.

The module combines filesystem utilities, CSV/DataFrame processing, logging helpers, and vocabulary-based normalization.


Dependencies

Standard library:

  • ast.literal_eval
  • datetime.datetime
  • pathlib.Path
  • shutil

External dependencies:

  • numpy
  • pandas
  • requests

API Reference

common.functions.get_latest_folder_date(logger, issn, article, content_of_article_folder)

Extracts date suffixes from supplied folder or file names, sorts them in descending chronological order, and returns the latest one.

The function assumes that the final ten characters of each name represent a date in YYYY-MM-DD format.

Parameters

logger
Logger used for critical and debug messages.

issn
Journal ISSN used for log context.

article
Article object expected to expose a .name attribute.

content_of_article_folder
Iterable containing folder or file names.

Returns

Latest suffix from the resulting list, typically in the form:

YYYY-MM-DD

Raises

IndexError
May be raised when the supplied iterable is empty because the function accesses suffix_list[0].

AttributeError
May be raised when article does not provide .name.

Processing

  1. Take the final ten characters of every entry.
  2. Remove duplicate suffixes.
  3. Sort the suffixes in descending date order.
  4. Log a critical message if a suffix cannot be parsed as %Y-%m-%d.
  5. Return the first suffix.

Notes

A ValueError during sorting is logged but not re-raised. The function then continues.


common.functions.processfolder_check(logger, issn, article, article_folder, foldername)

Checks an article directory for temporary, stop-processing, or already completed module folders.

Temporary folders for the specified module are deleted.

Parameters

logger
Logger used for debug and informational messages.

issn
Journal ISSN used for log context.

article
Article object expected to expose .name.

article_folder
Path to the article directory.

foldername
Module/folder prefix to inspect.

Returns

bool

Returns True when either a stop folder or a completed <foldername>_... folder exists. Otherwise returns False.

Raises

Filesystem exceptions from iteration or deletion are not caught.

Processing

  • temp_<foldername>... directories are deleted recursively.
  • names beginning with stop set the stop flag.
  • names beginning with <foldername>_ set the completed-folder flag.

Side Effects

May delete matching temporary directories using shutil.rmtree().


common.functions.log_in_csv(logger, log_file, log_entry, log_specification)

Appends a preformatted log entry to a file.

Parameters

logger
Logger used for the completion message.

log_file
Path to the target file.

log_entry
Text to append.

log_specification
Human-readable description included in the debug log.

Returns

None

Raises

Filesystem exceptions are not caught.

Side Effects

Opens the target file in append mode with UTF-8 encoding and writes log_entry.


common.functions.delete_duplicates_in_csv(logger, csv, csv_header, separator=";")

Removes duplicate CSV rows while keeping the last occurrence.

Parameters

logger
Logger used for the completion message.

csv
Path to the CSV file.

csv_header
Column names assigned to the loaded DataFrame.

separator: str = ";"
CSV delimiter.

Returns

None

Raises

Exceptions from pandas, column assignment, or filesystem access are not caught.

Processing

  1. Read the CSV into a DataFrame.
  2. Replace its column names with csv_header.
  3. Call drop_duplicates(keep="last").
  4. Write the cleaned DataFrame back to the original file.

Side Effects

Overwrites the original CSV file.


common.functions.delete_duplicate_articles_in_csv(logger, csv, csv_header, separator=";")

Removes duplicate article rows based on the DOI column while keeping the last occurrence.

Parameters

logger
Logger used for the completion message.

csv
Path to the CSV file.

csv_header
Column names assigned to the DataFrame.

separator: str = ";"
CSV delimiter.

Returns

None

Raises

KeyError
May be raised when the DataFrame does not contain a DOI column.

Other pandas and filesystem exceptions propagate.

Side Effects

Overwrites the original CSV file.


common.functions.delete_folder_content(logger, folder_path)

Deletes all direct contents of a directory while keeping the directory itself.

Parameters

logger
Logger used for the completion message.

folder_path
Directory whose contents should be removed.

Returns

None

Raises

Filesystem exceptions are not caught.

Processing

  • real directories are removed recursively with shutil.rmtree(),
  • files and symbolic links are removed with Path.unlink().

Side Effects

Permanently deletes all direct contents of the target directory.


common.functions.copy_folder_into_another(logger, src, dst)

Copies the direct contents of one directory into an existing destination directory.

Parameters

logger
Logger used for the completion message.

src
Source directory.

dst
Destination directory.

Returns

None

Raises

Filesystem exceptions are not caught.

Processing

  • directories are copied with shutil.copytree(),
  • files are copied with shutil.copy2().

Notes

The destination directory is expected to exist already.

If a target subdirectory already exists, shutil.copytree() may raise FileExistsError.


common.functions.time_display(seconds, short=True)

Formats a duration given in seconds.

Parameters

seconds
Duration in seconds.

short: bool = True
Controls output style.

  • True: compact d:h:min:s format.
  • False: descriptive text.

Returns

For short output:

DD:HH:MM:SS (d:h:min:s)

For long output, returns a descriptive string based on the largest non-zero unit.

Returns None for exactly zero seconds when short=False.

Notes

Days, hours, and minutes use round(), while seconds use int().


common.functions.article_iterator_log(logger, article, issn, start_time, actual_time, i_step, i_sum)

Logs article-processing progress and estimates the remaining duration.

Parameters

logger
Logger used for the progress message.

article
Article identifier displayed in the log.

issn
Journal ISSN displayed in the log.

start_time
Start timestamp.

actual_time
Current timestamp.

i_step
Current iteration number.

i_sum
Total number of iterations.

Returns

None

Raises

ZeroDivisionError
May be raised if i_step or i_sum is zero during percentage or duration calculations.

Processing

The function calculates:

  • completion percentage,
  • elapsed time,
  • estimated remaining duration.

The remaining duration is formatted using time_display().


common.functions.improper_article_exporter(logger, root_path, log_list, separator=";")

Creates publisher-specific CSV reports from a source CSV.

Parameters

logger
Logger used for report-generation messages.

root_path
Root directory under which reports are created.

log_list
Sequence where:

  • log_list[0] is the source CSV path,
  • log_list[1] controls optional publisher-blacklist handling.

separator: str = ";"
CSV delimiter.

Returns

None

Raises

KeyError
May be raised when expected columns such as Local File Path, Publisher, Error Message, or ISSN are missing.

IndexError
May be raised if log_list contains fewer than two elements.

Other pandas and filesystem exceptions propagate.

Processing

  1. Read the source CSV.
  2. Drop Local File Path.
  3. Determine unique publishers.
  4. Optionally apply the internal publisher blacklist.
  5. Filter rows per publisher.
  6. Sort by Error Message and ISSN.
  7. Create a publisher-specific output directory.
  8. Write one CSV per publisher.

Output Structure

<root_path>/
└── report-to-publisher/
    └── <publisher>/
        └── <source-name>_<publisher>.csv

Notes

The current publisher_blacklist is an empty list, so blacklist handling has no effect.


common.functions.term_standardizer(logger, dataframe, path, vocabularies, abbreviation=False)

Standardizes terms in a DataFrame using vocabulary CSV files downloaded from the WDM public vocabularies repository.

Parameters

logger
Logger used for directory and file messages.

dataframe
Source pandas DataFrame.

A copy is created before replacements are applied.

path
Base path under which the vocabularies directory is created.

vocabularies
Iterable of vocabulary names.

abbreviation: bool = False
Controls which vocabulary column is used as the replacement value.

  • False: column index 0
  • True: column index 1

Returns

pandas.DataFrame

A standardized copy of the input DataFrame.

Raises

Network, CSV parsing, literal_eval, DataFrame indexing, and filesystem exceptions are not caught.

Processing

For each vocabulary:

  1. Create <path>/vocabularies if needed.
  2. Download <vocabulary>.csv.
  3. Save it locally.
  4. Load it with semicolon separation.
  5. Parse the Variants column using literal_eval.
  6. Select the canonical replacement column.
  7. Replace each configured variant in the copied DataFrame.

Expected Vocabulary Structure

The implementation assumes:

  • variants are in column index 2,
  • that column is named Variants,
  • canonical values are in column index 0,
  • abbreviations are in column index 1.

Side Effects

  • creates the vocabularies directory,
  • downloads and writes vocabulary CSV files.

Operational Notes

No explicit request timeout, retry handling, or HTTP-status validation is performed before the response body is written.


Functional Groups

Filesystem Helpers

  • processfolder_check()
  • delete_folder_content()
  • copy_folder_into_another()

CSV and DataFrame Helpers

  • log_in_csv()
  • delete_duplicates_in_csv()
  • delete_duplicate_articles_in_csv()
  • improper_article_exporter()
  • term_standardizer()

Date and Progress Helpers

  • get_latest_folder_date()
  • time_display()
  • article_iterator_log()

Operational Considerations

Error Handling

Most functions do not catch filesystem, pandas, or network exceptions. Callers should handle failures where recovery is required.

Destructive Operations

Several helpers modify or delete data:

  • processfolder_check() deletes temporary directories.
  • delete_folder_content() deletes directory contents.
  • delete_duplicates_in_csv() overwrites a CSV.
  • delete_duplicate_articles_in_csv() overwrites a CSV.
  • improper_article_exporter() writes report CSVs.
  • term_standardizer() downloads and overwrites vocabulary files.

Logging

The module expects the caller to provide a logger.

Network Access

Only term_standardizer() performs external HTTP requests.

Type Expectations

Most functions are not type-annotated. Expected parameter types are therefore inferred from their usage in the implementation.