#!/bin/bash # get_equivalent.sh - Search equivalent element on Wikidata. # Copyright (C) 2022 Pierre Choffet # # This program is free software: you can redistribute it and/or modify # it under the terms of version 3 of the GNU General Public License as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . source "$(dirname "$0")/query.sh" set -euo pipefail function buildQuery() { local -r pid="${1}" shift local -r values=( "${@}" ) echo 'SELECT DISTINCT ?element WHERE {' for index in ${!values[@]} do if [ "${index}" -ne 0 ] then echo 'UNION' fi echo "{ ?element p:${pid} ?id${index}. ?id${index} (ps:${pid}) ${values[$index]@Q}. }" done echo '} LIMIT 2' } function usage() { cat << EOF USAGE: get_qid_from_property.sh This script will get Wikidata's equivalent element to an entry in a wdef. If uniqueness can be ensured from a literal value (typically an external identifier), it's an easy way to merge your wdef with Wikidata. EOF } if [ "$#" -ne 3 ] then usage >&2 exit 1 fi readonly WDEF_PATH="${1}" readonly ELEMENT_ID="${2}" readonly ELEMENT_PID="${3}" # Get wdef readarray -t VALUES<<<$(xmlstarlet sel -t -m "/wdef:knowledge/wdef:element[@wdef:id = \"${ELEMENT_ID}\"]/wdef:property[@wdef:pid = \"${ELEMENT_PID}\"]/wdef:value/wdef:literal" -v '.' -n "${WDEF_PATH}") # Build query readonly QUERY_PATH=$(mktemp) buildQuery "${ELEMENT_PID}" ${VALUES[@]} > "${QUERY_PATH}" readonly RESULT_PATH=$(query "${QUERY_PATH}") # Cleanup rm "${QUERY_PATH}" # Print potential result in stdout, cleanup, exit readonly QID=$(xmlstarlet sel -t -m '/_:sparql/_:results[count(_:result) = 1]' -v '_:result/_:binding[@name = "element"]/_:uri' "${RESULT_PATH}") if [ "${QID}" != '' ] then echo "${QID##*/}" else exit 1 fi