universal_dependencies / tools /01_fetch_ud_snapshot.sh
iiegn's picture
tools: standardize UD version flag on --ud-ver
783e782 verified
#!/usr/bin/env bash
#
# Fetch UD release snapshots from the LINDAT/CLARIN repository.
#
# NOTE:
# This script intentionally uses snapshot-oriented naming and does not
# fetch GitHub repositories/submodules.
#
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="${SCRIPT_DIR}/.env"
HANDLE_MAP_FILE="${SCRIPT_DIR}/etc/ud_release_handles.tsv"
[ -e "${ENV_FILE}" ] && . "${ENV_FILE}"
ONLINE_MODE=false
KEEP_ARCHIVE=false
KEEP_BACKUP=false
UD_VER=${UD_VER:-"2.17"}
UDS_SUBDIR="${SCRIPT_DIR}/UD_repos"
###################
#############
#
# USAGE
#
usage() { OUTPUT=${1:-"verbose"}
echo "Usage: $0 [-o] [--ud-ver VER] [--keep-archive] [--keep-backup]" >&2
[ "$OUTPUT" = "short" ] && exit 0
>&2 cat << EOF
Download and extract one official Universal Dependencies snapshot from:
* https://lindat.mff.cuni.cz/repository/
The snapshot archive is resolved from CLARIN API for the given handle
and UD version (e.g., ud-treebanks-v<VER>.tgz).
and extracted to:
* ud-treebanks-v<VER>/
Then a symlink is created/updated:
* UD_repos -> ud-treebanks-v<VER>
Options:
-h Print this help message
-o|--online Force re-download and re-extract
--ud-ver VER UD version to fetch (default: \${UD_VER} from .env)
--keep-archive Keep downloaded archive after extraction
--keep-backup Keep existing snapshot directory as timestamped backup
EOF
}
#
######
############
##################
VALID_ARGS=$(getopt -o hou:r: --long help,online,ud-ver:,rev:,keep-archive,keep-backup -- "$@")
if [[ $? -ne 0 ]]; then
usage "short"
exit 1
fi
eval set -- "$VALID_ARGS"
while [ : ]
do
case "$1" in
-o | --online) ONLINE_MODE=true; shift ;;
-u | --ud-ver | -r | --rev) UD_VER="$2"; shift 2 ;;
--keep-archive) KEEP_ARCHIVE=true; shift ;;
--keep-backup) KEEP_BACKUP=true; shift ;;
-h | --help) usage; shift ; exit 0 ;;
--) shift ; break ;;
*) >&2 echo "Unsupported option: $1"; usage; exit 1 ;;
esac
done
if [[ ! -r "${HANDLE_MAP_FILE}" ]]; then
>&2 echo "Missing handle mapping file: ${HANDLE_MAP_FILE}"
exit 1
fi
HANDLE="$(
awk -v ver="${UD_VER}" '
BEGIN { FS="[[:space:]]+" }
/^[[:space:]]*#/ { next }
NF < 2 { next }
$1 == ver { print $2; exit }
' "${HANDLE_MAP_FILE}"
)"
if [[ -z "${HANDLE}" ]]; then
>&2 echo "Unsupported UD version: ${UD_VER}"
>&2 echo "Update ${HANDLE_MAP_FILE} first."
exit 1
fi
SNAPSHOT_DIR_NAME="ud-treebanks-v${UD_VER}"
SNAPSHOT_DIR="${SCRIPT_DIR}/${SNAPSHOT_DIR_NAME}"
SNAPSHOT_ARCHIVE_NAME=""
SNAPSHOT_ARCHIVE=""
SNAPSHOT_URL=""
resolve_snapshot_download() {
local resolved
resolved="$(
python3 - "${HANDLE}" "${UD_VER}" <<'PY'
import json
import sys
from urllib.parse import urlencode
from urllib.request import urlopen
handle = sys.argv[1]
ud_ver = sys.argv[2]
api_base = "https://lindat.mff.cuni.cz/repository/server/api/core/metadatabitstreams/search/byHandle"
api_url = f"{api_base}?{urlencode({'handle': handle, 'fileGrpType': 'ORIGINAL', 'size': 200})}"
host_prefix = "https://lindat.mff.cuni.cz"
target_prefix = f"ud-treebanks-v{ud_ver}."
with urlopen(api_url, timeout=30) as response:
payload = json.loads(response.read().decode("utf-8"))
items = payload.get("_embedded", {}).get("metadatabitstreams", [])
candidates = [
item for item in items
if item.get("name", "").startswith(target_prefix) and item.get("href")
]
if not candidates:
raise SystemExit(f"No treebanks archive found for UD {ud_ver} at handle {handle}")
def sort_key(item):
name = item.get("name", "").lower()
if name.endswith(".tgz") or name.endswith(".tar.gz"):
return 0
if name.endswith(".zip"):
return 1
return 2
selected = sorted(candidates, key=sort_key)[0]
bitstream_id = selected.get("id")
if not bitstream_id:
raise SystemExit(f"Missing bitstream id for UD {ud_ver} at handle {handle}")
url = f"{host_prefix}/repository/server/api/core/bitstreams/{bitstream_id}/content"
print(selected["name"])
print(url)
PY
)"
if [[ -z "${resolved}" ]]; then
>&2 echo "Failed to resolve snapshot archive URL for UD ${UD_VER}."
exit 1
fi
SNAPSHOT_ARCHIVE_NAME="$(printf '%s\n' "${resolved}" | sed -n '1p')"
SNAPSHOT_URL="$(printf '%s\n' "${resolved}" | sed -n '2p')"
SNAPSHOT_ARCHIVE="${SCRIPT_DIR}/${SNAPSHOT_ARCHIVE_NAME}"
if [[ -z "${SNAPSHOT_ARCHIVE_NAME}" || -z "${SNAPSHOT_URL}" ]]; then
>&2 echo "Failed to parse resolved archive metadata for UD ${UD_VER}."
exit 1
fi
}
download_snapshot() {
echo "Downloading UD ${UD_VER} snapshot archive (${SNAPSHOT_ARCHIVE_NAME})"
echo "URL: ${SNAPSHOT_URL}"
if command -v curl >/dev/null 2>&1; then
curl -fL --retry 3 --retry-delay 1 "${SNAPSHOT_URL}" -o "${SNAPSHOT_ARCHIVE}"
elif command -v wget >/dev/null 2>&1; then
wget "${SNAPSHOT_URL}" -O "${SNAPSHOT_ARCHIVE}"
else
python3 - "${SNAPSHOT_URL}" "${SNAPSHOT_ARCHIVE}" <<'PY'
import sys
from urllib.request import urlretrieve
urlretrieve(sys.argv[1], sys.argv[2])
PY
fi
}
extract_snapshot() {
local tmp_dir backup_dir
tmp_dir=$(mktemp -d)
echo "Extracting ${SNAPSHOT_ARCHIVE} into ${SNAPSHOT_DIR_NAME}"
if [[ "${SNAPSHOT_ARCHIVE_NAME}" == *.zip ]]; then
if command -v unzip >/dev/null 2>&1; then
unzip -q "${SNAPSHOT_ARCHIVE}" -d "${tmp_dir}"
else
python3 - "${SNAPSHOT_ARCHIVE}" "${tmp_dir}" <<'PY'
import sys
import zipfile
with zipfile.ZipFile(sys.argv[1]) as zf:
zf.extractall(sys.argv[2])
PY
fi
else
if command -v tar >/dev/null 2>&1; then
tar -xzf "${SNAPSHOT_ARCHIVE}" -C "${tmp_dir}"
else
python3 - "${SNAPSHOT_ARCHIVE}" "${tmp_dir}" <<'PY'
import sys
import tarfile
with tarfile.open(sys.argv[1], mode="r:*") as tf:
tf.extractall(sys.argv[2])
PY
fi
fi
mapfile -t snapshot_candidates < <(find "${tmp_dir}" -mindepth 1 -maxdepth 1 -type d -name 'ud-treebanks-v*' | sort)
if [[ ${#snapshot_candidates[@]} -ne 1 ]]; then
>&2 echo "Expected one ud-treebanks-v* directory in archive, found ${#snapshot_candidates[@]}."
>&2 echo "Archive: ${SNAPSHOT_ARCHIVE}"
exit 1
fi
if [[ -d "${SNAPSHOT_DIR}" ]]; then
if [[ "${KEEP_BACKUP}" == true ]]; then
backup_dir="${SNAPSHOT_DIR}.bak.$(date +%s)"
echo "Existing ${SNAPSHOT_DIR_NAME} found; moving it to ${backup_dir}"
mv "${SNAPSHOT_DIR}" "${backup_dir}"
else
echo "Existing ${SNAPSHOT_DIR_NAME} found; removing it"
rm -rf "${SNAPSHOT_DIR}"
fi
fi
mv "${snapshot_candidates[0]}" "${SNAPSHOT_DIR}"
rm -rf "${tmp_dir}"
}
if [[ "${ONLINE_MODE}" == true ]] || [[ ! -d "${SNAPSHOT_DIR}" ]]; then
resolve_snapshot_download
if [[ "${ONLINE_MODE}" == true ]] || [[ ! -s "${SNAPSHOT_ARCHIVE}" ]]; then
download_snapshot
else
echo "Using existing archive ${SNAPSHOT_ARCHIVE}"
fi
extract_snapshot
else
echo "Snapshot directory already exists: ${SNAPSHOT_DIR_NAME}"
fi
if [[ "${KEEP_ARCHIVE}" != true ]] && [[ -n "${SNAPSHOT_ARCHIVE}" ]] && [[ -f "${SNAPSHOT_ARCHIVE}" ]]; then
echo "Removing archive ${SNAPSHOT_ARCHIVE_NAME}"
rm -f "${SNAPSHOT_ARCHIVE}"
fi
if [[ -L "${UDS_SUBDIR}" ]]; then
ln -sfn "${SNAPSHOT_DIR_NAME}" "${UDS_SUBDIR}"
elif [[ ! -e "${UDS_SUBDIR}" ]]; then
ln -s "${SNAPSHOT_DIR_NAME}" "${UDS_SUBDIR}"
else
>&2 echo "${UDS_SUBDIR} exists and is not a symlink. Please move/remove it, then rerun."
exit 1
fi
echo "UD snapshot ready:"
echo " UD_repos -> ${SNAPSHOT_DIR_NAME}"