-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #22 from markusjt/dev-cdi
WIP version of DDI-C to DDI-CDI and Python module for running XSLT transformations with SaxonC
- Loading branch information
Showing
19 changed files
with
4,883 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
*.pyc | ||
*.yaml | ||
*.egg-info |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
[FORMAT] | ||
max-line-length=120 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
DDI-C to DDI-CDI Transformer changelog | ||
====================================== | ||
|
||
0.1.0 (2023-03-26) | ||
------------------ | ||
|
||
* Initial release | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
Installing SaxonC | ||
----------------- | ||
|
||
Rocky Linux 8 | ||
````````````` | ||
|
||
1. cd /your/path | ||
2. wget https://www.saxonica.com/download/libsaxon-HEC-setup64-v11.4.zip | ||
3. unzip libsaxon-HEC-setup64-v11.4.zip | ||
4. rm libsaxon-HEC-setup64-v11.4.zip | ||
5. cd libsaxon-HEC-11.4/ | ||
6. sudo cp libsaxonhec.so /usr/lib/. | ||
7. sudo cp -r rt /usr/lib/. | ||
8. sudo cp -r saxon-data /usr/lib/. | ||
9. export SAXONC_HOME=/usr/lib | ||
10. cd Saxon.C.API/python-saxon/ | ||
11. sudo yum install gcc | ||
12. sudo yum install gcc-c++ | ||
13. sudo yum install python3-devel | ||
14. pip3 install --user cython | ||
15. python3 saxon-setup.py build_ext -if | ||
16. export PYTHONPATH=$PYTHONPATH:/your/path/to/libsaxon-HEC-11.4/Saxon.C.API/python-saxon | ||
|
||
Ubuntu 20.04 | ||
```````````` | ||
|
||
1. cd /your/path | ||
2. wget https://www.saxonica.com/download/libsaxon-HEC-setup64-v11.4.zip | ||
3. sudo apt-get install unzip | ||
4. unzip libsaxon-HEC-setup64-v11.4.zip | ||
5. rm libsaxon-HEC-setup64-v11.4.zip | ||
6. cd libsaxon-HEC-11.4/ | ||
7. sudo cp libsaxonhec.so /usr/lib/. | ||
8. sudo cp -r rt /usr/lib/. | ||
9. sudo cp -r saxon-data /usr/lib/. | ||
10. export SAXONC_HOME=/usr/lib | ||
11. cd Saxon.C.API/python-saxon/ | ||
12. sudo apt-get install gcc | ||
13. sudo apt-get install python3-dev | ||
14. sudo apt-get install python3-pip | ||
15. sudo apt install python3.8-venv | ||
16. pip3 install --user cython | ||
17. python3 saxon-setup.py build_ext -if | ||
18. export PYTHONPATH=$PYTHONPATH:/your/path/to/libsaxon-HEC-11.4/Saxon.C.API/python-saxon | ||
|
||
Adding environment variable to automatically be exported by login shells | ||
```````````````````````````````````````````````````````````````````````` | ||
|
||
sudo nano /etc/profile.d/saxonc_pythonpath.sh | ||
export PYTHONPATH=$PYTHONPATH:/your/path/to/libsaxon-HEC-11.4/Saxon.C.API/python-saxon | ||
|
||
Installing DDI-C to DDI-CDI Transformer | ||
--------------------------------------- | ||
|
||
1. Change to repository directory | ||
|
||
cd ddi-xslt/transformations/cdi/codebook_cdi_transformer | ||
|
||
2. Create virtualenv | ||
|
||
python3 -m venv ../codebook_cdi_transformer-env | ||
|
||
3. Activate virtualenv | ||
|
||
source ../codebook_cdi_transformer-env/bin/activate | ||
|
||
4. Install requirements | ||
|
||
pip install -r requirements.txt | ||
|
||
5. Install codebook-cdi-transformer | ||
|
||
pip install . |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
GNU LESSER GENERAL PUBLIC LICENSE | ||
Version 3, 29 June 2007 | ||
|
||
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/> | ||
|
||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. | ||
|
||
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. | ||
|
||
0. Additional Definitions. | ||
As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License. | ||
|
||
“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. | ||
|
||
An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. | ||
|
||
A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”. | ||
|
||
The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. | ||
|
||
The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. | ||
|
||
1. Exception to Section 3 of the GNU GPL. | ||
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. | ||
|
||
2. Conveying Modified Versions. | ||
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: | ||
|
||
a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or | ||
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. | ||
3. Object Code Incorporating Material from Library Header Files. | ||
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: | ||
|
||
a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. | ||
b) Accompany the object code with a copy of the GNU GPL and this license document. | ||
4. Combined Works. | ||
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: | ||
|
||
a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. | ||
b) Accompany the Combined Work with a copy of the GNU GPL and this license document. | ||
c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. | ||
d) Do one of the following: | ||
0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. | ||
1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. | ||
e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) | ||
5. Combined Libraries. | ||
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: | ||
|
||
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. | ||
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. | ||
6. Revised Versions of the GNU Lesser General Public License. | ||
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. | ||
|
||
Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. | ||
|
||
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
# DDI-C to DDI-CDI Transformer | ||
|
||
Created for transforming DDI-Codebook 2.5 to DDI-CDI 1.0 but can also be used for transformations with other XSLT files. | ||
Development work was part of DDI Hackathon 2023 by Markus Tuominen, Thomas Gilders and Alizera Davoudian. | ||
|
||
## XML Validation | ||
|
||
With xmllint: | ||
|
||
- curl -o DDI-CDI_1-0.xsd https://ddi-alliance.bitbucket.io/DDI-CDI/DDI-CDI_2022-10-06/encoding/xsd/DDI-CDI_1-0.xsd | ||
- xmllint --noout --schema DDI-CDI_1-0.xsd /path/to/cdi.xml |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
0.1.0 |
Empty file.
71 changes: 71 additions & 0 deletions
71
transformations/cdi/codebook_cdi_transformer/codebook_cdi_transformer/__main__.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
#!/usr/bin/env python3 | ||
"""Read/write/transform metadata""" | ||
import sys | ||
import logging | ||
from pathlib import Path | ||
import configargparse | ||
import yaml | ||
from py12flogging import log_formatter | ||
|
||
from .read_write_metadata import ReadWriteMetadata | ||
from .transform_metadata import TransformMetadata | ||
|
||
log_formatter.setup_app_logging('codebook_cdi_transformer', loglevel=logging.INFO) | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
def parse_all_args(): | ||
''' | ||
Parse arguments from environment variables, configuration files and/or command line parameters | ||
Returns: | ||
options (argparse.Namespace): Parsed arguments | ||
''' | ||
parser = configargparse.ArgParser(config_file_parser_class=configargparse.ConfigparserConfigFileParser, | ||
default_config_files=['configuration.yaml']) | ||
parser.add('-p', '--print_current_config', help='Show keys and values added to namespace and where they come from', | ||
action='store_true') | ||
parser.add('-c', '--config', is_config_file=True, help='Config file path') | ||
parser.add('-v', help='verbose', action='store_true') | ||
directory_path_group = parser.add_argument_group("Directory paths", "Set paths for writing/reading files") | ||
directory_path_group.add('-cb', '--codebook_directory_path', | ||
help='Path to directory where to write/read harvested metadata files', | ||
env_var='XML_TRANSFORMER_CODEBOOK_DIRECTORY_PATH') | ||
directory_path_group.add('-cdi', '--cdi_directory_path', | ||
help='Path to directory where to write/read transformed metadata files', | ||
env_var='XML_TRANSFORMER_CDI_DIRECTORY_PATH') | ||
transform_metadata_group = parser.add_argument_group("CDI", "Settings related to CDI") | ||
transform_metadata_group.add('-x', '--xslt_path', | ||
help='Path to XSLT file for transforming Codebook to CDI', | ||
env_var='XML_TRANSFORMER_XSLT_PATH', type=yaml.safe_load) | ||
options = parser.parse_args() | ||
|
||
if options.print_current_config: | ||
print(options) | ||
print("----------") | ||
print(parser.format_values()) | ||
sys.exit(0) | ||
|
||
return options | ||
|
||
|
||
def main(): | ||
''' | ||
Transform and write metadata to filesystem in DDI-CDI format | ||
Returns: | ||
0 (int): Returns 0 on success | ||
''' | ||
args = parse_all_args() | ||
codebook_directory = ReadWriteMetadata(args.codebook_directory_path) | ||
|
||
# Could get things like registrationAuthorityIdentifier or versionIdentifier from config instead of DDI-C xml | ||
# and pass them to TransformMetadata here for adding them to DDI-CDI xml | ||
transform = TransformMetadata(args.cdi_directory_path, args.xslt_path) | ||
transform.start_transformation(codebook_directory) | ||
|
||
return 0 | ||
|
||
|
||
if __name__ == '__main__': | ||
sys.exit(main()) |
144 changes: 144 additions & 0 deletions
144
transformations/cdi/codebook_cdi_transformer/codebook_cdi_transformer/read_write_metadata.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
#!/usr/bin/env python3 | ||
"""Read/write metadata files""" | ||
import html | ||
import re | ||
import logging | ||
from pathlib import Path | ||
from lxml import etree | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
NAMESPACES_DDI = {"c": "ddi:codebook:2_5", | ||
"xml": "http://www.w3.org/XML/1998/namespace"} | ||
MALFORMED_HTML_REPLACE = {"<br>": "<br />", | ||
" ": " "} | ||
TAGS_HTML_STRIP_DDI = ["abstract", | ||
"restrctn"] | ||
|
||
|
||
# Borrowed from kuha_common.document_store.mappings.xmlbase | ||
def element_remove_whitespaces(element): | ||
"""Conversion function to remove extra whitespace from end of element text. | ||
Iterates element's inner text using | ||
:meth:`xml.etree.ElementTree.Element.itertext` | ||
which iterates over this element and all subelements. | ||
Removes extra whitespaces so paragraphs of text will | ||
only have one separating whitespace character. | ||
:param element: Element from which to get text. | ||
:type element: :obj:`xml.etree.ElementTree.Element` | ||
:returns: Element's inner text without extra whitespace. | ||
:rtype: str | ||
""" | ||
value = "" | ||
ends_with_space = False | ||
for text in element.itertext(): | ||
text = " ".join([_p.strip() for _p in text.split("\n")]) | ||
if not ends_with_space and value != "": | ||
value = value + " " + text.lstrip() | ||
else: | ||
value += text.lstrip() | ||
ends_with_space = text.endswith(" ") | ||
if ends_with_space: | ||
value = value.rstrip() | ||
return value | ||
|
||
|
||
class ReadWriteMetadata(): | ||
"""Read and write metadata in file system using xml format. | ||
Attributes: | ||
directory_path (str): Directory for reading and writing metadata files. | ||
""" | ||
def __init__(self, directory_path): | ||
self.directory_path = Path(directory_path) | ||
|
||
if not self.directory_path.exists() or not self.directory_path.is_dir(): | ||
self.directory_path.mkdir(parents=True, exist_ok=True) | ||
logger.info('Directory for xml files created in %s.', self.directory_path) | ||
|
||
def write_record(self, filename, content, directory=None): | ||
''' | ||
Writes record on filesystem | ||
Args: | ||
filename (str): Name for the file | ||
content (str): Content to write | ||
directory (str): Optional directory path if not using the one initialized with the class | ||
''' | ||
write_path = Path(directory) if directory is not None else self.directory_path | ||
if not write_path.exists() or not write_path.is_dir(): | ||
write_path.mkdir(parents=True, exist_ok=True) | ||
logger.info('Subdirectory for xml files created in %s.', write_path) | ||
full_write_path = write_path / filename | ||
|
||
with open(full_write_path, 'wb') as write_file: | ||
write_file.write(content) | ||
|
||
def read_and_yield_records(self, directory=None, subdirectory=None, to_string=False): | ||
''' | ||
Reads metadata records in directory and yields them for transforming | ||
Args: | ||
directory (str): Optional directory path if not using the one initialized with the class | ||
subdirectory (str): Optional subdirectory path to limit reading to one subdirectory | ||
to_string (bool): Returns content as str if True and as lxml.etree._Element if False | ||
Returns: | ||
record (dict): All information about the record: name, path on filesystem and content | ||
''' | ||
read_path = Path(directory) if directory is not None else self.directory_path | ||
parser = etree.XMLParser(remove_blank_text=True) | ||
subdir = subdirectory if subdirectory else '**' | ||
for file_path in read_path.glob('**/' + subdir + '/*.xml'): | ||
tree = etree.parse(file_path, parser) | ||
file_content = etree.tostring(tree, encoding='unicode', pretty_print=True) if to_string else tree | ||
yield {'name': str(file_path).rsplit('/', maxsplit=1)[-1], 'path': str(file_path), 'content': file_content} | ||
|
||
def strip_html_from_xml_string(self, xml_string, record_id): | ||
''' | ||
Unescapes XML string, parses it and removes html from certain elements | ||
Args: | ||
xml_string (str): Original XML string before unescaping | ||
record_id (str): ID of the record for logging errors | ||
Returns: | ||
metadata_tree (lxml.etree._Element): XML content after fixing and removing html | ||
''' | ||
# Using parser with recover=True means some errors, i.e. broken html, may result in some metadata being left out | ||
# but it allows parsing to complete despite those errors that we are hopefully fixing anyway | ||
parser_recover = etree.XMLParser(encoding='utf-8', recover=True) | ||
xml_string_html_unescape = html.unescape(xml_string) | ||
# Replace html tags that are known to be malformed in some study xml files | ||
for tag, value in MALFORMED_HTML_REPLACE.items(): | ||
xml_string_html_unescape = re.sub(tag, value, xml_string_html_unescape, flags=re.I) | ||
metadata_tree = etree.fromstring(xml_string_html_unescape, parser_recover) | ||
|
||
# Remove html tags | ||
for tag in TAGS_HTML_STRIP_DDI: | ||
for possible_html_element in metadata_tree.findall(".//*/c:" + tag + "[@xml:lang='en']", | ||
namespaces=NAMESPACES_DDI): | ||
# Recreate clean element and delete previous mess | ||
text_html_removed_element = etree.SubElement(possible_html_element.getparent(), | ||
'{' + NAMESPACES_DDI['c'] + '}' + tag) | ||
text_html_removed_element.attrib['{' + NAMESPACES_DDI['xml'] + '}lang'] = 'en' | ||
text_html_removed_element.text = element_remove_whitespaces(possible_html_element) | ||
possible_html_element.getparent().remove(possible_html_element) | ||
|
||
# See if we can now parse file without recover=True | ||
# Return None if there's still issues | ||
try: | ||
xml_string_cleaned = etree.tostring(metadata_tree, encoding='unicode') | ||
parser_no_recover = etree.XMLParser(encoding='utf-8') | ||
metadata_tree_cleaned = etree.fromstring(xml_string_cleaned, parser_no_recover) | ||
except etree.XMLSyntaxError as err: | ||
logger.error("XML syntax error %s in %s", err, record_id) | ||
return None | ||
except BaseException as err: | ||
logger.error("Unexpected error %s in %s", err, record_id) | ||
return None | ||
return metadata_tree_cleaned |
Oops, something went wrong.