ToL-EDA / scripts /make_licenses.py
egrace479's picture
Update to accept snakecase license_name for futher compatibility.
7f010b4
raw
history blame
3.22 kB
import pandas as pd
from pathlib import Path
import argparse
import sys
# Output of match_owners.py (catalog-media.csv) should be fed in.
# Will also work with the media manifest.
CC_URL = "https://creativecommons.org/"
def get_license_url(license_version):
"""
Function to generate the appropriate Creative Commons URL for a given license.
All licenses in the media manifest are "cc-XX", a variation on "publicdomain", or "No known copyright restrictions".
Parameters:
-----------
license_version - String. License (eg., "cc-by-nc 3.0").
Returns:
--------
license_url - String. Creative Commons URL associated with the license_version.
"""
# First check for version number and isolate it
if "." in license_version:
version = license_version.split(sep="-")[-1]
license_name = license_version.split(sep="-" + version)[0]
else:
# No version specified, so default to latest version (4.0)
license_name = license_version
version = "4.0"
# Check which type of license
if license_name[:5] == "cc-by":
by_x = license_name.split(sep="cc-")[1]
license_url = CC_URL + "licenses/" + by_x + "/" + version
elif (license_name[:4] == "cc-0") or ("public" in license_name):
license_url = CC_URL + "publicdomain/zero/1.0"
else:
# "No known copyright restrictions"
license_url = None
return license_url
def main(src_csv, dest_dir):
# Check CSV compatibility
try:
print("Reading CSV")
df = pd.read_csv(src_csv, low_memory=False)
except Exception as e:
sys.exit(e)
# Check for "License Name" or "license_name" column
print("Processing data")
df_cols = list(df.columns)
if "License Name" not in df_cols:
if "license_name" not in df_cols:
sys.exit("Source CSV does not have a column labeled License Name or license_name.")
license_col = "license_name"
license_col = "License Name"
# Check filepath given by user
dest_dir_path = Path(dest_dir)
if not dest_dir_path.is_absolute():
# Use ToL-EDA as reference folder
base_path = Path(__file__).parent.parent.resolve()
filepath = base_path / dest_dir_path
else:
filepath = dest_dir_path
filepath.mkdir(parents=True, exist_ok=True)
# Add links for licenses to catalog manifest
print("Getting URLs for licenses")
df["license_link"] = df[license_col].apply(get_license_url)
# Save license file
df.to_csv(str(filepath / "licenses.csv"), index=False)
# Print counts of licenses for which URL was not resolved
print(
"Licenses with no URL: \n",
df.loc[df["license_link"].isna(), license_col].value_counts(),
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Add license URLs to catalog-media file"
)
parser.add_argument("input_file", help="Path to the input CSV file")
parser.add_argument(
"--output_path",
default="data",
required=False,
help="Path to the folder for output license file",
)
args = parser.parse_args()
main(args.input_file, args.output_path)